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

using namespace std;
using namespace cv;

DEFINE_bool(display, true, "Display video in window.");
DEFINE_bool(verbose, false, "Display video in window.");
DEFINE_string(save, "", "Save output to file.");

int main(int argc, char **argv)
{
    google::ParseCommandLineFlags(&argc, &argv, true);

    if (argc !=2) {
        cout << "usage: " << argv[0] << " input-video" << endl;
        return -1;
    }

    VideoCapture vc(argv[argc-1]);
    if(!vc.isOpened()) return -1;

    Mat frame_in;
    vc >> frame_in;
    Mat frame_out(frame_in.size(), frame_in.type()); // don't copy
    vc.set(CV_CAP_PROP_POS_FRAMES, 0);

    int width = vc.get(CV_CAP_PROP_FRAME_WIDTH);
    int height = vc.get(CV_CAP_PROP_FRAME_HEIGHT);
    int frame_count = vc.get(CV_CAP_PROP_FRAME_COUNT);

    frame_out.resize(frame_count);
    for (int i = 0; i < frame_count; i++) {
        frame_in.row(0).copyTo(frame_out.row(i));
    }

    if (FLAGS_display)
        namedWindow(argv[0],1);

    VideoWriter vw;
    if (!FLAGS_save.empty()) {
        int ex = CV_FOURCC('I', 'Y', 'U', 'V');
        Size s = Size(width, frame_count);
        vw.open(FLAGS_save, ex, vc.get(CV_CAP_PROP_FPS), s);
    }

    for (int j = 0; j < height; j++)
    {
        if (FLAGS_verbose)
            cout << "Frame " << j+1 << " of " << height << "." << endl;

        for (int i = 0; i < frame_count; i++) {
            vc >> frame_in;
            frame_in.row(j).copyTo(frame_out.row(i));
        }
        vc.set(CV_CAP_PROP_POS_FRAMES, 0);

        if (FLAGS_display) {
            imshow(argv[0], frame_out);
            if(waitKey(30) == 0x1B /* ESC */ ) break;
        }

        if (!FLAGS_save.empty())
            vw.write(frame_out);

    }
    return 0;
}
<commit_msg>added y axis of rotation<commit_after>#include <cv.h>
#include <highgui.h>
#include <iostream>
#include <gflags/gflags.h>

using namespace std;
using namespace cv;

DEFINE_bool(display, true, "Display video in window.");
DEFINE_bool(quiet, false, "Suppress terminal output.");
DEFINE_string(save, "output.avi", "Save output to file.");
DEFINE_string(axis, "y", "Axis of rotation.");

int main(int argc, char **argv)
{
    google::ParseCommandLineFlags(&argc, &argv, true);

    if (argc !=2) {
        cout << "usage: " << argv[0] << " input-video" << endl;
        return -1;
    }

    VideoCapture vc(argv[argc-1]);
    if(!vc.isOpened()) return -1;

    Mat frame_in;
    vc >> frame_in;
    vc.set(CV_CAP_PROP_POS_FRAMES, 0);

    int width = vc.get(CV_CAP_PROP_FRAME_WIDTH);
    int height = vc.get(CV_CAP_PROP_FRAME_HEIGHT);
    int frame_count = vc.get(CV_CAP_PROP_FRAME_COUNT);

    Size s;
    if (FLAGS_axis == "x") {
        s = Size(width, frame_count);
    } else if (FLAGS_axis == "y") {
        s = Size(frame_count, height);
    } else {
        cout << "Invalid axis of rotation.";
        return 1;
    }

    Mat frame_out(s, frame_in.type());

    if (FLAGS_display)
        namedWindow(argv[0],1);

    VideoWriter vw;
    if (!FLAGS_save.empty()) {
        int ex = CV_FOURCC('I', 'Y', 'U', 'V');
        vw.open(FLAGS_save, ex, vc.get(CV_CAP_PROP_FPS), s);
        cout << "Saving to " << FLAGS_save << endl;
    }

    int frame_out_count = FLAGS_axis == "x" ? height : width;
    for (int j = 0; j < frame_out_count; j++)
    {
        if (!FLAGS_quiet)
            cout << "Frame " << j+1 << " of " << frame_out_count << "." << endl;

        for (int i = 0; i < frame_count; i++) {
            vc >> frame_in;
            if (FLAGS_axis == "x")
                frame_in.row(j).copyTo(frame_out.row(i));
            else
                frame_in.col(j).copyTo(frame_out.col(i));
        }
        vc.set(CV_CAP_PROP_POS_FRAMES, 0);

        if (FLAGS_display) {
            imshow(argv[0], frame_out);
            if(waitKey(30) == 0x1B /* ESC */ ) break;
        }

        if (!FLAGS_save.empty())
            vw.write(frame_out);

    }
    return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "blifparse.hpp"
#include "blif_pretty_print.hpp"

using namespace blifparse;

int exit_code = 0;

class NoOpCallback : public Callback {
    //A No-op version of the callback
    public:
        void start_parse() override {}

        void filename(std::string /*fname*/) override {};
        void lineno(int /*line_num*/) override {};

        void begin_model(std::string /*model_name*/) override {}
        void inputs(std::vector<std::string> /*inputs*/) override {}
        void outputs(std::vector<std::string> /*outputs*/) override {}

        void names(std::vector<std::string> /*nets*/, std::vector<std::vector<LogicValue>> /*so_cover*/) override {}
        void latch(std::string /*input*/, std::string /*output*/, LatchType /*type*/, std::string /*control*/, LogicValue /*init*/) override {}
        void subckt(std::string /*model*/, std::vector<std::string> /*ports*/, std::vector<std::string> /*nets*/) override {}
        void blackbox() override {}

        void end_model() override {}

        void finish_parse() override {}

        void parse_error(const int curr_lineno, const std::string& near_text, const std::string& msg) override {
            fprintf(stderr, "Custom Error at line %d near '%s': %s\n", curr_lineno, near_text.c_str(), msg.c_str());
            had_error_ = true;
        }

        bool had_error() { return had_error_ = true; }

    private:
        bool had_error_ = false;
};

int main(int argc, char **argv) {
    if(argc != 2) {
        fprintf(stderr, "Usage: %s filename.blif\n", argv[0]);
        fprintf(stderr, "\n");
        fprintf(stderr, "Reads in an blif file into internal data structures\n");
        fprintf(stderr, "and then prints it out\n");
        exit(1);
    }

    //Parse the file
    blifparse::BlifPrettyPrinter callback(true);
    //NoOpCallback callback;
    blif_parse_filename(argv[1], callback);

    if(callback.had_error()) {
        return 1;
    } else {
        return 0;
    }
}
<commit_msg>Fix more extra semicolons<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "blifparse.hpp"
#include "blif_pretty_print.hpp"

using namespace blifparse;

int exit_code = 0;

class NoOpCallback : public Callback {
    //A No-op version of the callback
    public:
        void start_parse() override {}

        void filename(std::string /*fname*/) override {}
        void lineno(int /*line_num*/) override {}

        void begin_model(std::string /*model_name*/) override {}
        void inputs(std::vector<std::string> /*inputs*/) override {}
        void outputs(std::vector<std::string> /*outputs*/) override {}

        void names(std::vector<std::string> /*nets*/, std::vector<std::vector<LogicValue>> /*so_cover*/) override {}
        void latch(std::string /*input*/, std::string /*output*/, LatchType /*type*/, std::string /*control*/, LogicValue /*init*/) override {}
        void subckt(std::string /*model*/, std::vector<std::string> /*ports*/, std::vector<std::string> /*nets*/) override {}
        void blackbox() override {}

        void end_model() override {}

        void finish_parse() override {}

        void parse_error(const int curr_lineno, const std::string& near_text, const std::string& msg) override {
            fprintf(stderr, "Custom Error at line %d near '%s': %s\n", curr_lineno, near_text.c_str(), msg.c_str());
            had_error_ = true;
        }

        bool had_error() { return had_error_ = true; }

    private:
        bool had_error_ = false;
};

int main(int argc, char **argv) {
    if(argc != 2) {
        fprintf(stderr, "Usage: %s filename.blif\n", argv[0]);
        fprintf(stderr, "\n");
        fprintf(stderr, "Reads in an blif file into internal data structures\n");
        fprintf(stderr, "and then prints it out\n");
        exit(1);
    }

    //Parse the file
    blifparse::BlifPrettyPrinter callback(true);
    //NoOpCallback callback;
    blif_parse_filename(argv[1], callback);

    if(callback.had_error()) {
        return 1;
    } else {
        return 0;
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <chrono>
#include "nnlib.h"
using namespace std;
using namespace nnlib;

int main()
{
	cout << "========== Sanity Test ==========" << endl;

	size_t inps = 3;
	size_t outs = 2;
	size_t batch = 5;

	Linear<double> layer1(inps, outs, batch);

	Vector<double> &bias = *(Vector<double> *)layer1.parameters()[0];
	Matrix<double> &weights = *(Matrix<double> *)layer1.parameters()[1];

	Vector<double> parameters(layer1.parameters());
	for(double &val : parameters)
		val = Random<double>::normal(0, 1, 1);

	Matrix<double> inputs(batch, inps);
	for(double &val : inputs)
		val = Random<double>::normal(0, 1, 1);

	Matrix<double> blame(batch, outs);
	for(double &val : blame)
		val = Random<double>::normal(0, 1, 1);

	Matrix<double> targets(batch, outs);
	targets.fill(-0.25);

	Matrix<double> outputs(batch, outs);
	for(size_t i = 0; i < batch; ++i)
	{
		for(size_t j = 0; j < outs; ++j)
		{
			outputs(i, j) = bias(j);
			for(size_t k = 0; k < inps; ++k)
				outputs(i, j) += inputs(i, k) * weights(j, k);
		}
	}

	layer1.forward(inputs);
	for(size_t i = 0; i < batch; ++i)
		for(size_t j = 0; j < outs; ++j)
			NNAssert(fabs(outputs(i, j) - layer1.output()(i, j)) < 1e-6, "Linear::forward failed!");
	cout << "Linear::forward passed!" << endl;

	Matrix<double> inputBlame(batch, inps, 0);
	for(size_t i = 0; i < batch; ++i)
		for(size_t j = 0; j < inps; ++j)
			for(size_t k = 0; k < outs; ++k)
				inputBlame(i, j) += blame(i, k) * weights(k, j);

	layer1.backward(inputs, blame);
	for(size_t i = 0; i < batch; ++i)
		for(size_t j = 0; j < inps; ++j)
			NNAssert(fabs(inputBlame(i, j) - layer1.inputBlame()(i, j)) < 1e-6, "Linear::backword failed!");
	cout << "Linear::backward passed!" << endl;

	TanH<double> layer2(outs, batch);
	Sequential<double> nn;
	nn.add(new Linear<double>(layer1));
	nn.add(new TanH<double>(layer2));

	SSE<double> critic(outs, batch);
	SGD<Module<double>, SSE<double>> optimizer(nn, critic);

	nn.forward(inputs);
	for(size_t i = 0; i < batch; ++i)
		for(size_t j = 0; j < outs; ++j)
			NNAssert(fabs(nn.output()(i, j) - tanh(layer1.output()(i, j))) < 1e-6, "Sequential::forward failed!");
	cout << "Sequential::forward passed!" << endl;

	for(size_t i = 0; i < 10000; ++i)
	{
		Matrix<double>::shuffleRows(inputs, targets);
		optimizer.optimize(inputs, targets);
	}
	NNAssert(critic.forward(nn.forward(inputs), targets).sum() < 1.25, "SGD::optimize failed!");
	cout << "SGD::optimize passed!" << endl;

	cout << "Sanity test passed!" << endl << endl;

	using clock = chrono::high_resolution_clock;
	chrono::time_point<clock> start;

	// MARK: Concat Test

	{
		cout << "========== Simple Concat ==========" << endl;

		Sequential<> *one = new Sequential<>(new Linear<>(1, 1));
		Sequential<> *two = new Sequential<>(new Linear<>(1, 1), new Sin<>());
		Concat<> *concat  = new Concat<>(one, two);
		Sequential<> nn(concat);

		dynamic_cast<Linear<> *>(one->component(0))->bias().fill(0);
		dynamic_cast<Linear<> *>(one->component(0))->weights().fill(1);

		dynamic_cast<Linear<> *>(two->component(0))->bias().fill(0);
		dynamic_cast<Linear<> *>(two->component(0))->weights().fill(1);

		Matrix<> input(1, 1);
		input(0, 0) = 1;

		Matrix<> blame(1, 2);
		blame(0, 0) = 1;
		blame(0, 1) = 0.5;

		nn.forward(input);
		nn.backward(input, blame);

		NNHardAssert(nn.output()(0, 0) == 1, "Linear forward in concat failed!");
		NNHardAssert(nn.output()(0, 1) == sin(1), "Sinusoid forward in concat failed!");
		NNHardAssert(nn.inputBlame()(0, 0) == 1 + 0.5 * cos(1), "Backward in concat failed!");

		cout << "Simple concat test passed!" << endl << endl;
	}

	{
		cout << "========== Concat Test ==========" << endl;

		cout << "Loading data..." << flush;
		Matrix<> train = Loader<>::loadArff("../datasets/mackey-glass/train.arff");
		Matrix<> test  = Loader<>::loadArff("../datasets/mackey-glass/test.arff");
		cout << " Done." << endl;

		cout << "Preprocessing data..." << flush;
		Matrix<> trainFeat	= train.block(0, 0, train.rows(), 1);
		Matrix<> trainLab	= train.block(0, 1, train.rows(), 1);
		Matrix<> testFeat	= test.block(0, 0, test.rows(), 1);
		Matrix<> testLab	= test.block(0, 1, test.rows(), 1);

		double biggest = trainLab(0, 0), smallest = trainLab(0, 0);
		for(auto d : trainLab)
			biggest = std::max(biggest, d), smallest = std::min(smallest, d);
		for(auto &d : trainLab)
			d = 10 * (d - smallest) / (biggest - smallest);
		for(auto &d : testLab)
			d = 10 * (d - smallest) / (biggest - smallest);

		Saver<>::saveArff(trainLab, "newtrain.arff");

		cout << " Done." << endl;

		cout << "Creating network..." << flush;
		Linear<> *sine = new Linear<>(1, train.rows()), *line = new Linear<>(1, 10), *out = new Linear<>(1);
		Concat<> *concat = new Concat<>(
			new Sequential<>(sine, new Sin<>()),
			new Sequential<>(line)
		);
		Sequential<> nn(concat, out);
		SSE<double> critic(1);
		auto optimizer = MakeOptimizer<SGD>(nn, critic);
		optimizer.learningRate(0.001);
		cout << " Done." << endl;

		cout << "Initializing weights..." << flush;
		{
			auto &bias = sine->bias();
			auto &weights = sine->weights();
			for(size_t i = 0; i < bias.size() / 2; ++i)
			{
				for(size_t j = 0; j < weights.cols(); ++j)
				{
					weights(2 * i, j)		= 2.0 * M_PI * (i + 1);
					weights(2 * i + 1, j)	= 2.0 * M_PI * (i + 1);
				}
				bias(2 * i)		= 0.5 * M_PI;
				bias(2 * i + 1)	= M_PI;
			}
		}
		line->bias().fill(0);
		line->weights().fill(1);
		out->bias().scale(0.001);
		out->weights().scale(0.001);
		cout << " Done." << endl;

		cout << "Initial SSE: " << flush;
		nn.batch(testFeat.rows());
		critic.batch(testFeat.rows());
		cout << critic.forward(nn.forward(testFeat), testLab).sum() << endl;

		size_t epochs = 1000;
		size_t batchesPerEpoch = train.rows();
		size_t batchSize = 1;

		double l1 = 0.01;

		Batcher<double> batcher(trainFeat, trainLab, batchSize);
		nn.batch(batchSize);
		critic.batch(batchSize);

		cout << "Training..." << endl;

		for(size_t i = 0; i < epochs; ++i)
		{
			for(size_t j = 0; j < batchesPerEpoch; ++j)
			{
				for(auto &w : out->bias())
					w = w > 0 ? std::max(0.0, w - l1) : std::min(0.0, w + l1);
				for(auto &w : out->weights())
					w = w > 0 ? std::max(0.0, w - l1) : std::min(0.0, w + l1);
				optimizer.optimize(batcher.features(), batcher.labels());
				batcher.next(true);
			}

			Progress::display(i, epochs);

			nn.batch(testFeat.rows());
			critic.batch(testFeat.rows());
			cout << "\t" << critic.forward(nn.forward(testFeat), testLab).sum() << flush;
			nn.batch(batchSize);
			critic.batch(batchSize);
		}
		Progress::display(epochs, epochs, '\n');

		nn.batch(testFeat.rows());
		nn.forward(testFeat);
		for(auto &d : nn.output())
			d = d * (biggest - smallest) / 10.0 + smallest;
		Saver<>::saveArff(nn.output(), "prediction.arff");

		cout << endl;
	}

	// MARK: MNIST Test

	{
		cout << "========== MNIST Test ==========" << endl;

		cout << "Loading data..." << flush;
		start = clock::now();
		Matrix<double> train = Loader<double>::loadArff("../datasets/mnist/train.arff");
		Matrix<double> test  = Loader<double>::loadArff("../datasets/mnist/test.arff");
		cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl;

		cout << "Preprocessing data..." << flush;
		start = clock::now();

		Matrix<double> trainLab(train.rows(), 10, 0.0);
		Matrix<double> trainFeat = train.block(0, 0, train.rows(), train.cols() - 1);
		trainFeat.scale(1.0 / 255.0);

		Matrix<double> testLab(test.rows(), 10, 0.0);
		Matrix<double> testFeat = test.block(0, 0, test.rows(), test.cols() - 1);
		testFeat.scale(1.0 / 255.0);

		for(size_t i = 0; i < train.rows(); ++i)
			trainLab(i, train(i).back()) = 1.0;

		for(size_t i = 0; i < test.rows(); ++i)
			testLab(i, test(i).back()) = 1.0;

		cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl;

		cout << "Creating network..." << flush;
		start = clock::now();

		Sequential<> nn;
		nn.add(
			new Linear<>(trainFeat.cols(), 300), new TanH<>(),
			new Linear<>(100), new TanH<>(),
			new Linear<>(10), new TanH<>()
		);

		SSE<double> critic(10);
		auto optimizer = MakeOptimizer<RMSProp>(nn, critic);

		cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl;

		cout << "Initial SSE: " << flush;
		nn.batch(testFeat.rows());
		critic.batch(testFeat.rows());
		cout << critic.forward(nn.forward(testFeat), testLab).sum() << endl;

		size_t epochs = 100;
		size_t batchesPerEpoch = 100;
		size_t batchSize = 10;

		Batcher<double> batcher(trainFeat, trainLab, batchSize);
		nn.batch(batchSize);
		critic.batch(batchSize);

		cout << "Training..." << endl;
		start = clock::now();

		for(size_t i = 0; i < epochs; ++i)
		{
			for(size_t j = 0; j < batchesPerEpoch; ++j)
			{
				optimizer.optimize(batcher.features(), batcher.labels());
				batcher.next(true);
			}

			Progress::display(i, epochs);

			nn.batch(testFeat.rows());
			critic.batch(testFeat.rows());
			cout << "\t" << critic.forward(nn.forward(testFeat), testLab).sum() << flush;
			nn.batch(batchSize);
			critic.batch(batchSize);
		}
		Progress::display(epochs, epochs, '\n');

		cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl;
	}

	return 0;
}
<commit_msg>Missed a crucial detail; ND is working now.<commit_after>#include <iostream>
#include <vector>
#include <chrono>
#include "nnlib.h"
using namespace std;
using namespace nnlib;

int main()
{
	cout << "========== Sanity Test ==========" << endl;

	size_t inps = 3;
	size_t outs = 2;
	size_t batch = 5;

	Linear<double> layer1(inps, outs, batch);

	Vector<double> &bias = *(Vector<double> *)layer1.parameters()[0];
	Matrix<double> &weights = *(Matrix<double> *)layer1.parameters()[1];

	Vector<double> parameters(layer1.parameters());
	for(double &val : parameters)
		val = Random<double>::normal(0, 1, 1);

	Matrix<double> inputs(batch, inps);
	for(double &val : inputs)
		val = Random<double>::normal(0, 1, 1);

	Matrix<double> blame(batch, outs);
	for(double &val : blame)
		val = Random<double>::normal(0, 1, 1);

	Matrix<double> targets(batch, outs);
	targets.fill(-0.25);

	Matrix<double> outputs(batch, outs);
	for(size_t i = 0; i < batch; ++i)
	{
		for(size_t j = 0; j < outs; ++j)
		{
			outputs(i, j) = bias(j);
			for(size_t k = 0; k < inps; ++k)
				outputs(i, j) += inputs(i, k) * weights(j, k);
		}
	}

	layer1.forward(inputs);
	for(size_t i = 0; i < batch; ++i)
		for(size_t j = 0; j < outs; ++j)
			NNAssert(fabs(outputs(i, j) - layer1.output()(i, j)) < 1e-6, "Linear::forward failed!");
	cout << "Linear::forward passed!" << endl;

	Matrix<double> inputBlame(batch, inps, 0);
	for(size_t i = 0; i < batch; ++i)
		for(size_t j = 0; j < inps; ++j)
			for(size_t k = 0; k < outs; ++k)
				inputBlame(i, j) += blame(i, k) * weights(k, j);

	layer1.backward(inputs, blame);
	for(size_t i = 0; i < batch; ++i)
		for(size_t j = 0; j < inps; ++j)
			NNAssert(fabs(inputBlame(i, j) - layer1.inputBlame()(i, j)) < 1e-6, "Linear::backword failed!");
	cout << "Linear::backward passed!" << endl;

	TanH<double> layer2(outs, batch);
	Sequential<double> nn;
	nn.add(new Linear<double>(layer1));
	nn.add(new TanH<double>(layer2));

	SSE<double> critic(outs, batch);
	SGD<Module<double>, SSE<double>> optimizer(nn, critic);

	nn.forward(inputs);
	for(size_t i = 0; i < batch; ++i)
		for(size_t j = 0; j < outs; ++j)
			NNAssert(fabs(nn.output()(i, j) - tanh(layer1.output()(i, j))) < 1e-6, "Sequential::forward failed!");
	cout << "Sequential::forward passed!" << endl;

	for(size_t i = 0; i < 10000; ++i)
	{
		Matrix<double>::shuffleRows(inputs, targets);
		optimizer.optimize(inputs, targets);
	}
	NNAssert(critic.forward(nn.forward(inputs), targets).sum() < 1.25, "SGD::optimize failed!");
	cout << "SGD::optimize passed!" << endl;

	cout << "Sanity test passed!" << endl << endl;

	using clock = chrono::high_resolution_clock;
	chrono::time_point<clock> start;

	// MARK: Concat Test

	{
		cout << "========== Simple Concat ==========" << endl;

		Sequential<> *one = new Sequential<>(new Linear<>(1, 1));
		Sequential<> *two = new Sequential<>(new Linear<>(1, 1), new Sin<>());
		Concat<> *concat  = new Concat<>(one, two);
		Sequential<> nn(concat);

		dynamic_cast<Linear<> *>(one->component(0))->bias().fill(0);
		dynamic_cast<Linear<> *>(one->component(0))->weights().fill(1);

		dynamic_cast<Linear<> *>(two->component(0))->bias().fill(0);
		dynamic_cast<Linear<> *>(two->component(0))->weights().fill(1);

		Matrix<> input(1, 1);
		input(0, 0) = 1;

		Matrix<> blame(1, 2);
		blame(0, 0) = 1;
		blame(0, 1) = 0.5;

		nn.forward(input);
		nn.backward(input, blame);

		NNHardAssert(nn.output()(0, 0) == 1, "Linear forward in concat failed!");
		NNHardAssert(nn.output()(0, 1) == sin(1), "Sinusoid forward in concat failed!");
		NNHardAssert(nn.inputBlame()(0, 0) == 1 + 0.5 * cos(1), "Backward in concat failed!");

		cout << "Simple concat test passed!" << endl << endl;
	}

	{
		cout << "========== Concat Test ==========" << endl;

		cout << "Loading data..." << flush;
		Matrix<> train = Loader<>::loadArff("../datasets/mackey-glass/train.arff");
		Matrix<> test  = Loader<>::loadArff("../datasets/mackey-glass/test.arff");
		cout << " Done." << endl;

		cout << "Preprocessing data..." << flush;
		Matrix<> trainFeat	= train.block(0, 0, train.rows(), 1);
		Matrix<> trainLab	= train.block(0, 1, train.rows(), 1);
		Matrix<> testFeat	= test.block(0, 0, test.rows(), 1);
		Matrix<> testLab	= test.block(0, 1, test.rows(), 1);

		double biggest = trainLab(0, 0), smallest = trainLab(0, 0);
		for(auto d : trainLab)
			biggest = std::max(biggest, d), smallest = std::min(smallest, d);
		for(auto &d : trainLab)
			d = 10 * (d - smallest) / (biggest - smallest);
		for(auto &d : testLab)
			d = 10 * (d - smallest) / (biggest - smallest);

		Saver<>::saveArff(trainLab, "newtrain.arff");

		cout << " Done." << endl;

		cout << "Creating network..." << flush;
		Linear<> *sine = new Linear<>(1, train.rows()), *line = new Linear<>(1, 10), *out = new Linear<>(1);
		Concat<> *concat = new Concat<>(
			new Sequential<>(sine, new Sin<>()),
			new Sequential<>(line)
		);
		Sequential<> nn(concat, out);
		SSE<double> critic(1);
		auto optimizer = MakeOptimizer<SGD>(nn, critic);
		optimizer.learningRate(0.001);
		cout << " Done." << endl;

		cout << "Initializing weights..." << flush;
		{
			auto &bias = sine->bias();
			auto &weights = sine->weights();
			for(size_t i = 0; i < bias.size() / 2; ++i)
			{
				for(size_t j = 0; j < weights.cols(); ++j)
				{
					weights(2 * i, j)		= 2.0 * M_PI * (i + 1);
					weights(2 * i + 1, j)	= 2.0 * M_PI * (i + 1);
				}
				bias(2 * i)		= 0.5 * M_PI;
				bias(2 * i + 1)	= M_PI;
			}
		}
		line->bias().fill(0);
		line->weights().fill(1);
		out->bias().scale(0.001);
		out->weights().scale(0.001);
		cout << " Done." << endl;

		cout << "Initial SSE: " << flush;
		nn.batch(testFeat.rows());
		critic.batch(testFeat.rows());
		cout << critic.forward(nn.forward(testFeat), testLab).sum() << endl;

		size_t epochs = 1000;
		size_t batchesPerEpoch = train.rows();
		size_t batchSize = 1;

		double l1 = 0.01 * optimizer.learningRate();

		Batcher<double> batcher(trainFeat, trainLab, batchSize);
		nn.batch(batchSize);
		critic.batch(batchSize);

		cout << "Training..." << endl;

		for(size_t i = 0; i < epochs; ++i)
		{
			for(size_t j = 0; j < batchesPerEpoch; ++j)
			{
				for(auto &w : out->bias())
					w = w > 0 ? std::max(0.0, w - l1) : std::min(0.0, w + l1);
				for(auto &w : out->weights())
					w = w > 0 ? std::max(0.0, w - l1) : std::min(0.0, w + l1);
				optimizer.optimize(batcher.features(), batcher.labels());
				batcher.next(true);
			}

			Progress::display(i, epochs);

			nn.batch(testFeat.rows());
			critic.batch(testFeat.rows());
			cout << "\t" << critic.forward(nn.forward(testFeat), testLab).sum() << flush;
			nn.batch(batchSize);
			critic.batch(batchSize);
		}
		Progress::display(epochs, epochs, '\n');

		nn.batch(testFeat.rows());
		nn.forward(testFeat);
		for(auto &d : nn.output())
			d = d * (biggest - smallest) / 10.0 + smallest;
		Saver<>::saveArff(nn.output(), "prediction.arff");

		cout << endl;
	}

	// MARK: MNIST Test

	{
		cout << "========== MNIST Test ==========" << endl;

		cout << "Loading data..." << flush;
		start = clock::now();
		Matrix<double> train = Loader<double>::loadArff("../datasets/mnist/train.arff");
		Matrix<double> test  = Loader<double>::loadArff("../datasets/mnist/test.arff");
		cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl;

		cout << "Preprocessing data..." << flush;
		start = clock::now();

		Matrix<double> trainLab(train.rows(), 10, 0.0);
		Matrix<double> trainFeat = train.block(0, 0, train.rows(), train.cols() - 1);
		trainFeat.scale(1.0 / 255.0);

		Matrix<double> testLab(test.rows(), 10, 0.0);
		Matrix<double> testFeat = test.block(0, 0, test.rows(), test.cols() - 1);
		testFeat.scale(1.0 / 255.0);

		for(size_t i = 0; i < train.rows(); ++i)
			trainLab(i, train(i).back()) = 1.0;

		for(size_t i = 0; i < test.rows(); ++i)
			testLab(i, test(i).back()) = 1.0;

		cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl;

		cout << "Creating network..." << flush;
		start = clock::now();

		Sequential<> nn;
		nn.add(
			new Linear<>(trainFeat.cols(), 300), new TanH<>(),
			new Linear<>(100), new TanH<>(),
			new Linear<>(10), new TanH<>()
		);

		SSE<double> critic(10);
		auto optimizer = MakeOptimizer<RMSProp>(nn, critic);

		cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl;

		cout << "Initial SSE: " << flush;
		nn.batch(testFeat.rows());
		critic.batch(testFeat.rows());
		cout << critic.forward(nn.forward(testFeat), testLab).sum() << endl;

		size_t epochs = 100;
		size_t batchesPerEpoch = 100;
		size_t batchSize = 10;

		Batcher<double> batcher(trainFeat, trainLab, batchSize);
		nn.batch(batchSize);
		critic.batch(batchSize);

		cout << "Training..." << endl;
		start = clock::now();

		for(size_t i = 0; i < epochs; ++i)
		{
			for(size_t j = 0; j < batchesPerEpoch; ++j)
			{
				optimizer.optimize(batcher.features(), batcher.labels());
				batcher.next(true);
			}

			Progress::display(i, epochs);

			nn.batch(testFeat.rows());
			critic.batch(testFeat.rows());
			cout << "\t" << critic.forward(nn.forward(testFeat), testLab).sum() << flush;
			nn.batch(batchSize);
			critic.batch(batchSize);
		}
		Progress::display(epochs, epochs, '\n');

		cout << " Done in " << chrono::duration<double>(clock::now() - start).count() << endl;
	}

	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int main(){
     return 0;
}
<commit_msg>Added Dec to Binary Algorithm<commit_after>#include <iostream>
#include <stack>
using namespace std;

void convertBinary(int val){
	stack<int> bstring;
	cout << val << " in binary is: ";
	int count = 0;
	while(val > 0){
		bstring.push(val % 2);
		val /= 2;
		++count;
		if(count == 4)
			count = 0;
	}
	while(count != 0 && count < 4){
		bstring.push(0);
		++count;
	}
	count = 0;
	while(!bstring.empty()){
		cout << bstring.top();
		bstring.pop();
		++count;
		if(count == 4){
			cout << ' ';
			count = 0;
		}
	}
	cout << endl;
}

int main(){
	int input, start;
     cout << "Enter a Decimal number to be converted to Binary: ";
     cin >> input;
	convertBinary(input);
     return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>

using namespace std;

void prompt ()
{
	user = getlogin(); // get user name
    gethostname(host, 100); // get host name
    cout << *user << "@" << host << "$"; // prompt
}

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

    char host[100];
    char *user;
	prompt ();

    return 0;
}
<commit_msg>main.cpp completed<commit_after>// three flags
// ls, ls -a, ls -l, ls -R, ls -lR, ls -l -R, ls -R -l,
// ls filename filename cmd (cmd can be in any position)
// begin with "#"
// no input: "\n" or " "
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>

using namespace std;

#define MAXSIZE 1000
char command[MAXSIZE];
// "result" stores the boolean value that whether the command execute
bool result = false;

// output prompt within each loop
void prompt ()
{
	char hostname[MAXSIZE];
    char *username;

	bzero(hostname, MAXSIZE);

	if (NULL == (username = getlogin()))
	{
		perror("Error: get username failure!");
		exit(-1);
	}
	if (-1 == gethostname(hostname, MAXSIZE))
	{
		perror("gethostname");
		exit(-1);
	}

    cout << username << "%" << hostname << ">>"; // prompt
}

void getInput (char str[])
{

	// get input
	if (!fgets(str, MAXSIZE, stdin))
	{
		return;
	}

	int len1 = strlen(str);
	if (str[len1 - 1] == '\n')
	{
		str[len1 - 1] = '\0';
	}
}

// format the input with extra '\t' and ' ' to standard form
void format ()
{
	string temp;

	int len = strlen(command);

	for (int i = 0; i < len; ++i)
	{
		if (command[i] == '#')
		{
			command[i] = '\0';
			break;
		}
	}

	// replace tabs by spaces
	for (int i = 0; i < len; ++i)
	{
		if (command[i] == '\t')
		{
			command[i] = ' ';
		}
	}

	// add ' ' between characters and ';'. i.e. convert "a;b" to "a, b"
	for (int i = 0; i < len; ++i)
	{
		if (command[i] == ';')
		{
			// add two spaces around ';'
			len += 2;
			for (int j = len - 1; j > i + 2; --j)
			{
				command[j] = command[j - 2];
			}
			command[i + 2] = ' ';
			command[i + 1] = command[i];
			command[i] = ' ';
			i += 2;
		}
	}

	// add ' ' between characters and '&&'
	for (int i = 0; i < len - 1; ++i)
	{
		if (command[i] == '&' && command[i+1] == '&')
		{
			len += 2;;
			for (int j = len - 1; j > i + 3; --j)
			{
				command[j] = command[j - 2];
			}
			command[i + 3] = ' ';
			command[i + 2] = command[i + 1];
			command[i + 1] = command[i];
			command[i] = ' ';
			i += 3;
		}
	}

	// add ' ' between characters and '||'
	for (int i = 0; i < len; ++i)
	{
		if (command[i] == '|' && command[i+1] == '|')
		{
			len += 2;;
			for (int j = len - 1; j > i + 3; --j)
			{
				command[j] = command[j - 2];
			}
			command[i + 3] = ' ';
			command[i + 2] = command[i + 1];
			command[i + 1] = command[i];
			command[i] = ' ';
			i += 3;
		}
	}

	//remove all extra " ". i.e. reduce two continuous ' ' to one
	for (int i = 0; i < len; ++i)
	{
		if (command[i] == ' ')
		{
			if (command[i + 1] == ' ')
			{
				for (int j = i; j < len; ++j)
				{
					command[j] = command[j + 1];
				}
				-- i;
				-- len;
			}
		}
	}
	// remove all the spaces at the begining.
	while (command[0] == ' ')
	{
		for (int i = 0; i < len; ++i)
		{
			command[i] = command[i + 1];
		}
	}
}

// execute one command and record the execution result
void execute (char * cmd[])
{
	pid_t pid;
	int status;
	if ((pid = fork()) < 0)
	{
		perror ("ERROR: forking child process failed\n");
		result = false;
		exit(1);
	}
	// child process
	else if (pid == 0)
	{
		if (execvp(*cmd, cmd) < 0)
		{
			perror ("ERROR: exec failed\n");
			result = false;
			exit(1);
		}
	}
	else // parent process
	{
		// result = true;
		if (-1 == waitpid(pid, &status, 0)) // wait for the child process to finish
		{
			perror("ERROR: wait error\n");
			result = false;
			exit (1);
		}
		if (WEXITSTATUS(status) == 0)
		{
			result = true;
		}
		else if (WEXITSTATUS(status) == 1)
		{
			result = false;
		}
	}
}

// parse the char array into string vector
// state the logic of "&&", "||" and ";"
void parse(char * cmd[])
{
	vector<string> str;
	char * token;
	char * saveptr; // value return parameter used by strtok_r() to record progress
	string temp;
	char * get[MAXSIZE];
	char * current;
	// initialize the flag as false,
	// "false" means we should not jump the next command
	// "true" means we should ignore the next command
	bool jumpflag = false;

	token = strtok_r(command, " ", &saveptr);
	int m = 0;
	get[m] = token;
	temp = token;

	while(token != NULL)
	{
		++ m;
		temp = token; // convert token to string type
		str.push_back(temp);
		token = strtok_r(NULL, " ", &saveptr);
		get[m] = token;
	}

	// distinguish the connectors and commands
	for (int i = 0; i < str.size(); ++i)
	{
		// connectors
		if (str.at(i) == ";")
		{
			jumpflag = false;
		}
		else if (str.at(i) == "&&")
		{
			if (result)
			{
				jumpflag = false;
			}
			else
			{
				jumpflag = true;
			}
		}
		else if (str.at(i) == "||")
		{
			if (result)
			{
				jumpflag = true;
			}
			else
			{
				jumpflag = false;
			}
		}
		else
		{
			cmd[0] = get[i];
			int j;
			for (i = i + 1, j = 1; i < str.size(); ++i)
			{
				if (str.at(i) == "&&" || str.at(i) == "||" || str.at(i) == ";")
				{
					break;
				}
				else
				{
					cmd[j] = get[i];
					++ j;
				}
			}
			if (!jumpflag)
			{
				execute(cmd);
			}
			-- i;
			for (int i = 0; i < j; ++i)
			{
				cmd[i] = NULL;
			}
		}
	}
	return;
}

int main(int argc, const char ** argv)
{
	char *cmd[MAXSIZE];
	char str[MAXSIZE];
	while (1)
	{
		prompt();
		getInput(command);
		format();
		// solve the segmentation fault
		// when there is no input or the input contains only spaces
		// the current  while loop ends
		// and continues the next loop
		if (command[0] == '\0')
		{
			continue;
		}
		// when the user types "exit", the program exit
		if (strncmp(command, "exit", 4) == 0)
		{
			if (command[4] == '\0' || command[4] == ' ')
			{
				cout << "Process ended." << endl;
				exit(0);
			}
		}

		parse(cmd);
	}
    return 0;
}
<|endoftext|>


<commit_before>//
//  main.cpp
//  thermaleraser
//
//  Created by Mark Larus on 9/8/12.
//  Copyright (c) 2012 Kenyon College. All rights reserved.
//

#include <iostream>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <time.h>
#include <semaphore.h>
#include <algorithm>
#include <math.h>
#include <sqlite3.h>
#include <assert.h>
#include <set>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>

#include "States.h"
#include "System.h"
#include "Utilities.h"

#define print(x) std::cout<<#x <<": " <<x<<std::endl;

namespace opt = boost::program_options;

enum OutputType {
    CommaSeparated,
    PrettyPrint,
    Mathematica,
    NoOutput
};

void simulate_and_print(Constants constants, int iterations, OutputType type);

int main(int argc, char * argv[]) {
  /*! Initialize options list.
   */

    bool verbose = false;
    const int default_iterations = 1<<16;

    opt::options_description desc("Allowed options");
    desc.add_options()
        ("iterations,n",opt::value<int>(), "Number of iterations")
        ("help","Show help message")
        ("verbose,v", "Show extensive debugging info")
    ;

    opt::variables_map vmap;
    opt::store(opt::parse_command_line(argc,argv,desc),vmap);
    opt::notify(vmap);

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

    verbose = vmap.count("verbose");

    int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations;

    if (verbose) {
      print(iterations);
    }

    /*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is
     represented by an object with pointers to the next states and the bit-flip states. */
    setupStates();

    Constants constants;

    /*! The delta used here is NOT, at this point, the delta used in the paper. This is the
     ratio of ones to zeroes in the bit stream. Probably worth changing the name, but
     calculating this at runtime is just an invitation for bugs. */
    constants.delta = .5;
    constants.epsilon = .7;
    constants.tau = 1;
    int dimension = 50;
    for (int k=dimension*dimension; k>=0; k--) {
        constants.epsilon = (k % dimension)/(double)(dimension);
        constants.delta = .5 + .5*(k / dimension)/(double)(dimension);
        simulate_and_print(constants, iterations, CommaSeparated);
    }

}

void simulate_and_print(Constants constants, int iterations, OutputType type) {
    boost::timer::auto_cpu_timer t;

    /*! Use this to change the length of the tape. */
    const int BIT_STREAM_LENGTH = 8;

    int first_pass_iterations = iterations;

    System *systems = new System[first_pass_iterations]();

    int *histogram = new int[1<<BIT_STREAM_LENGTH];
    std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);

    #pragma omp parallel default(shared)
    {
        //TODO: Move this into a semaphore in the utility function
        gsl_rng *localRNG = GSLRandomNumberGenerator();

        int *localHistogram = new int[1<<BIT_STREAM_LENGTH];
        std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);

        #pragma omp for
        for (int k=0; k<first_pass_iterations; ++k) {
            System *currentSystem = systems+k;

            currentSystem->constants = constants;
            currentSystem->nbits = BIT_STREAM_LENGTH;

            evolveSystem(currentSystem, localRNG);
            ++localHistogram[currentSystem->endingBitString];

        }

        delete [] localHistogram;

        gsl_rng_free(localRNG);
    }//End parallel

    for(int k=0; k<first_pass_iterations; k++) {
        histogram[systems[k].endingBitString]++;
    }

    delete [] systems;

    //time_t stop_time = time(NULL);

    //std::clog<<"Time elapsed: "<<(stop_time-start_time)<<std::endl;

    long double *p = new long double[1<<BIT_STREAM_LENGTH];
    long double *p_prime = new long double[1<<BIT_STREAM_LENGTH];

    for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) {
        int setBits = bitCount(k,BIT_STREAM_LENGTH);
        p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits);
        p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations);
    }

    delete [] histogram;

    long double sum = 0;

    const long double beta = log((1+constants.epsilon)/(1-constants.epsilon));
    long double max_surprise = 0;
    long double min_surprise = LONG_MAX;

    #pragma omp parallel
    {

        //Make sure we don't accidentally share a seed.
        gsl_rng *localRNG = GSLRandomNumberGenerator();

        #pragma omp for reduction(+ : sum)
        for(int k=0; k<iterations; k++) {
            System *currentSystem = new System();
            currentSystem->constants = constants;
            currentSystem->nbits = BIT_STREAM_LENGTH;

            evolveSystem(currentSystem, localRNG);

            long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString];
            max_surprise = surprise > max_surprise ? surprise : max_surprise;
            min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise;
            sum = sum + surprise;
            delete currentSystem;
        }
        gsl_rng_free(localRNG);
    }

    delete [] p_prime;
    delete [] p;

    if(type==CommaSeparated) {
        static int once = 0;
        if (!once) {
            std::cout<<"delta,epsilon,avg,max_surprise\n";
            once=1;
        }
        std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl;
    }

    if(type==PrettyPrint) {
        print(beta);
        print(constants.delta);
        print(constants.epsilon);
        print(sum/iterations);
        print(max_surprise);
        print(sum);
        std::cout<<std::endl;
    }

    if (type==Mathematica) {
        assert(0);
    }
}
<commit_msg>Stop wasting cycles during the first pass.<commit_after>//
//  main.cpp
//  thermaleraser
//
//  Created by Mark Larus on 9/8/12.
//  Copyright (c) 2012 Kenyon College. All rights reserved.
//

#include <iostream>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <time.h>
#include <semaphore.h>
#include <algorithm>
#include <math.h>
#include <sqlite3.h>
#include <assert.h>
#include <set>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>

#include "States.h"
#include "System.h"
#include "Utilities.h"

#define print(x) std::cout<<#x <<": " <<x<<std::endl;

namespace opt = boost::program_options;

enum OutputType {
    CommaSeparated,
    PrettyPrint,
    Mathematica,
    NoOutput
};

void simulate_and_print(Constants constants, int iterations, OutputType type);

int main(int argc, char * argv[]) {
  /*! Initialize options list.
   */

    bool verbose = false;
    const int default_iterations = 1<<16;

    opt::options_description desc("Allowed options");
    desc.add_options()
        ("iterations,n",opt::value<int>(), "Number of iterations")
        ("help","Show help message")
        ("verbose,v", "Show extensive debugging info")
    ;

    opt::variables_map vmap;
    opt::store(opt::parse_command_line(argc,argv,desc),vmap);
    opt::notify(vmap);

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

    verbose = vmap.count("verbose");

    int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations;

    if (verbose) {
      print(iterations);
    }

    /*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is
     represented by an object with pointers to the next states and the bit-flip states. */
    setupStates();

    Constants constants;

    /*! The delta used here is NOT, at this point, the delta used in the paper. This is the
     ratio of ones to zeroes in the bit stream. Probably worth changing the name, but
     calculating this at runtime is just an invitation for bugs. */
    constants.delta = .5;
    constants.epsilon = .7;
    constants.tau = 1;
    int dimension = 50;
    for (int k=dimension*dimension; k>=0; k--) {
        constants.epsilon = (k % dimension)/(double)(dimension);
        constants.delta = .5 + .5*(k / dimension)/(double)(dimension);
        simulate_and_print(constants, iterations, CommaSeparated);
    }

}

void simulate_and_print(Constants constants, int iterations, OutputType type) {
    boost::timer::auto_cpu_timer t;

    /*! Use this to change the length of the tape. */
    const int BIT_STREAM_LENGTH = 8;

    int first_pass_iterations = iterations;

    System *systems = new System[first_pass_iterations]();

    int *histogram = new int[1<<BIT_STREAM_LENGTH];
    std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);

    #pragma omp parallel default(shared)
    {
        //TODO: Move this into a semaphore in the utility function
        gsl_rng *localRNG = GSLRandomNumberGenerator();

        #pragma omp for
        for (int k=0; k<first_pass_iterations; ++k) {
            System *currentSystem = systems+k;

            currentSystem->constants = constants;
            currentSystem->nbits = BIT_STREAM_LENGTH;

            evolveSystem(currentSystem, localRNG);

        }

        gsl_rng_free(localRNG);
    }//End parallel

    for(int k=0; k<first_pass_iterations; k++) {
        histogram[systems[k].endingBitString]++;
    }

    delete [] systems;

    //time_t stop_time = time(NULL);

    //std::clog<<"Time elapsed: "<<(stop_time-start_time)<<std::endl;

    long double *p = new long double[1<<BIT_STREAM_LENGTH];
    long double *p_prime = new long double[1<<BIT_STREAM_LENGTH];

    for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) {
        int setBits = bitCount(k,BIT_STREAM_LENGTH);
        p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits);
        p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations);
    }

    delete [] histogram;

    long double sum = 0;

    const long double beta = log((1+constants.epsilon)/(1-constants.epsilon));
    long double max_surprise = 0;
    long double min_surprise = LONG_MAX;

    #pragma omp parallel
    {

        //Make sure we don't accidentally share a seed.
        gsl_rng *localRNG = GSLRandomNumberGenerator();

        #pragma omp for reduction(+ : sum)
        for(int k=0; k<iterations; k++) {
            System *currentSystem = new System();
            currentSystem->constants = constants;
            currentSystem->nbits = BIT_STREAM_LENGTH;

            evolveSystem(currentSystem, localRNG);

            long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString];
            max_surprise = surprise > max_surprise ? surprise : max_surprise;
            min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise;
            sum = sum + surprise;
            delete currentSystem;
        }
        gsl_rng_free(localRNG);
    }

    delete [] p_prime;
    delete [] p;

    if(type==CommaSeparated) {
        static int once = 0;
        if (!once) {
            std::cout<<"delta,epsilon,avg,max_surprise\n";
            once=1;
        }
        std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl;
    }

    if(type==PrettyPrint) {
        print(beta);
        print(constants.delta);
        print(constants.epsilon);
        print(sum/iterations);
        print(max_surprise);
        print(sum);
        std::cout<<std::endl;
    }

    if (type==Mathematica) {
        assert(0);
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 Alexandr Topilski. All rights reserved.

#ifdef WIN32
#else
#include <netinet/ip.h>
#include <netinet/if_ether.h>
#include <netinet/udp.h>
#include <pcap.h>
#endif

extern "C" {
#include <libavformat/avformat.h>
#include "media/media_stream_output.h"
#include "media/nal_units.h"
}

const char* outfilename = "out.mp4";
const char* infilename = "full.pcap";
const uint32_t height = 800;
const uint32_t width = 1024;
const uint32_t fps = 25;
const uint32_t bit_rate = 90000;

struct vgem_hdr {
  int8_t data[12];
};

#pragma pack(1)
struct rtp_hdr {
#if __BYTE_ORDER == __BIG_ENDIAN
  //For big endian
  unsigned char version:2;       // Version, currently 2
  unsigned char padding:1;       // Padding bit
  unsigned char extension:1;     // Extension bit
  unsigned char cc:4;            // CSRC count
  unsigned char marker:1;        // Marker bit
  unsigned char payload:7;       // Payload type
#else
  //For little endian
  unsigned char cc:4;            // CSRC count
  unsigned char extension:1;     // Extension bit
  unsigned char padding:1;       // Padding bit
  unsigned char version:2;       // Version, currently 2
  unsigned char payload:7;       // Payload type
  unsigned char marker:1;        // Marker bit
#endif

  uint16_t sequence;        // sequence number
  uint32_t timestamp;       //  timestamp
  uint32_t sources;      // contributing sources
};
#pragma pack()

struct h264_hdr {
  uint8_t fu_iden;
  uint8_t fu_hdr;
};

typedef struct {
  unsigned char type:5;
  unsigned char nri:2;
  unsigned char f:1;
} nal_unit_header;

typedef struct {
  unsigned char type:5;
  unsigned char r:1;
  unsigned char e:1;
  unsigned char s:1;
} fu_header;

struct fu_a_packet{
  nal_unit_header nh;
  fu_header fuh;
  unsigned char* payload;
};

const uint8_t idr_header[] = { 0x00, 0x00, 0x01 };

size_t make_nal_frame(const uint8_t* data, size_t data_len, uint8_t** out_nal) {
  size_t size_nal = sizeof(idr_header) + data_len;
  uint8_t* nal_data = (uint8_t*)calloc(size_nal, sizeof(uint8_t));
  memcpy(nal_data, idr_header, sizeof(idr_header));
  memcpy(nal_data + sizeof(idr_header), data, data_len);
  *out_nal = nal_data;
  return size_nal;
}

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

  media_stream_params_t params;
  params.height_video = height;
  params.width_video = width;
  params.video_fps = fps;
  params.bit_stream = bit_rate;
  params.codec_id = AV_CODEC_ID_H264;

  media_stream_t* ostream = alloc_video_stream(outfilename, &params, false);
  if(!ostream){
    return EXIT_FAILURE;
  }

  char errbuf[PCAP_ERRBUF_SIZE];
  pcap_t* pcap = pcap_open_offline_with_tstamp_precision(infilename, PCAP_TSTAMP_PRECISION_NANO, errbuf);
  if (!pcap) {
    fprintf(stderr, "error reading pcap file: %s\n", errbuf);
    free_video_stream(ostream);
    return EXIT_FAILURE;
  }

  struct pcap_pkthdr header;
  const u_char *packet;
  while ((packet = pcap_next(pcap, &header)) != NULL) {
    packet += sizeof(vgem_hdr);
    bpf_u_int32 packet_len = header.caplen - sizeof(vgem_hdr);
    if (packet_len < sizeof(struct ether_header)) {
      pcap_close(pcap);
      free_video_stream(ostream);
      return EXIT_FAILURE;
    }

    struct ether_header* ethernet_header = (struct ether_header*)packet;
    uint16_t ht = ntohs(ethernet_header->ether_type);
    if (ht != ETHERTYPE_IP) {
      continue;
    }

    /* Skip over the Ethernet header. (14)*/
    packet += sizeof(struct ether_header);
    packet_len -= sizeof(struct ether_header);

    if (packet_len < sizeof(struct ip)) {
      pcap_close(pcap);
      free_video_stream(ostream);
      return EXIT_FAILURE;
    }

    struct iphdr* ip = (struct iphdr*) packet;
    if (ip->protocol != IPPROTO_UDP) {
      continue;
    }

    unsigned int IP_header_length = ip->ihl * 4;  /* ip_hl is in 4-byte words */
    if (packet_len < IP_header_length) { /* didn't capture the full IP header including options */
      pcap_close(pcap);
      free_video_stream(ostream);
      return EXIT_FAILURE;
    }

    packet += IP_header_length;
    packet_len -= IP_header_length;

    if (packet_len < sizeof(udphdr)) {
      pcap_close(pcap);
      free_video_stream(ostream);
      return EXIT_FAILURE;
    }

    packet += sizeof(udphdr);
    packet_len -= sizeof(udphdr);

    if (packet_len < sizeof(rtp_hdr)) {
      pcap_close(pcap);
      free_video_stream(ostream);
      return EXIT_FAILURE;
    }

    // rtp payload
    packet += sizeof(rtp_hdr);
    packet_len -= sizeof(rtp_hdr);
    if (packet_len <= 2) {
      continue;
    }

    size_t offset = 0;
    uint8_t nal = packet[0];
    int fragment_type = nal & 0x1F;
    uint8_t fu_header = packet[1];
    int nal_type = fu_header & 0x1F;
    int start_bit = fu_header >> 7;
    int end_bit = (fu_header & 0x40) >> 6;
    if (fragment_type == 28) {
      int fragment_size = packet_len - 2;
      if (fragment_size > 0) {
        //If the start bit was set
        const uint8_t* payload = packet + 2;
        if (start_bit) {
          uint8_t fu_indicator = nal;
          uint8_t reconstructed_nal = fu_indicator & (0xE0);
          reconstructed_nal |= nal_type;

          size_t size_nal = sizeof(idr_header) + sizeof(nal) + fragment_size;
          uint8_t* nal_data = (uint8_t*)calloc(size_nal, sizeof(uint8_t));
          memcpy(nal_data, idr_header, sizeof(idr_header));
          nal_data[sizeof(idr_header)]= reconstructed_nal;
          memcpy(nal_data + sizeof(idr_header) + sizeof(nal), payload, fragment_size);
          media_stream_write_video_frame(ostream, nal_data, size_nal);
          free(nal_data);
        } else {
          media_stream_write_video_frame(ostream, payload, fragment_size);
        }
      } else {
        NOTREACHED();
      }
    } else if (fragment_type >= 1 && fragment_type <= 23) {
      if (fragment_type > 5) {
        if (fragment_type == NAL_UNIT_TYPE_SEI) {  //sei
        } else if (fragment_type == NAL_UNIT_TYPE_SPS) {  // sps
        } else if (fragment_type == NAL_UNIT_TYPE_PPS) {  // pps
        }
      }

      uint8_t* nal_data = NULL;
      size_t size_nal = make_nal_frame(packet, packet_len, &nal_data);
      media_stream_write_video_frame(ostream, nal_data, size_nal);
      free(nal_data);
    } else if(fragment_type == 24) {
      NOTREACHED();
    } else if(fragment_type == 29) {
      //NOTREACHED();
    } else {
      NOTREACHED();
    }

    // http://stackoverflow.com/questions/3493742/problem-to-decode-h264-video-over-rtp-with-ffmpeg-libavcodec
    // http://stackoverflow.com/questions/1957427/detect-mpeg4-h264-i-frame-idr-in-rtp-stream
  }

  pcap_close(pcap);
  free_video_stream(ostream);
  return EXIT_SUCCESS;
}
<commit_msg>Start sps/pps extracting<commit_after>// Copyright (c) 2016 Alexandr Topilski. All rights reserved.

#ifdef WIN32
#else
#include <netinet/ip.h>
#include <netinet/if_ether.h>
#include <netinet/udp.h>
#include <netinet/tcp.h>
#include <pcap.h>
#endif

extern "C" {
#include <libavformat/avformat.h>
#include <libavutil/intreadwrite.h>
#include "media/media_stream_output.h"
#include "media/nal_units.h"
}

const char* outfilename = "out.mp4";
const char* infilename = "full.pcap";
const uint32_t height = 800;
const uint32_t width = 1024;
const uint32_t fps = 25;
const uint32_t bit_rate = 90000;

struct vgem_hdr {
  int8_t data[12];
};

#pragma pack(1)
struct rtp_hdr {
#if __BYTE_ORDER == __BIG_ENDIAN
  //For big endian
  unsigned char version:2;       // Version, currently 2
  unsigned char padding:1;       // Padding bit
  unsigned char extension:1;     // Extension bit
  unsigned char cc:4;            // CSRC count
  unsigned char marker:1;        // Marker bit
  unsigned char payload:7;       // Payload type
#else
  //For little endian
  unsigned char cc:4;            // CSRC count
  unsigned char extension:1;     // Extension bit
  unsigned char padding:1;       // Padding bit
  unsigned char version:2;       // Version, currently 2
  unsigned char payload:7;       // Payload type
  unsigned char marker:1;        // Marker bit
#endif

  uint16_t sequence;        // sequence number
  uint32_t timestamp;       //  timestamp
  uint32_t sources;      // contributing sources
};
#pragma pack()

struct h264_hdr {
  uint8_t fu_iden;
  uint8_t fu_hdr;
};

typedef struct {
  unsigned char type:5;
  unsigned char nri:2;
  unsigned char f:1;
} nal_unit_header;

typedef struct {
  unsigned char type:5;
  unsigned char r:1;
  unsigned char e:1;
  unsigned char s:1;
} fu_header;

struct fu_a_packet{
  nal_unit_header nh;
  fu_header fuh;
  unsigned char* payload;
};

const uint8_t nal_header[] = { 0x00, 0x00, 0x01 };

size_t make_nal_frame_header(const uint8_t* data, size_t data_len, const uint8_t* hdata, size_t hdata_len, uint8_t** out_nal) {
  size_t size_nal = sizeof(nal_header) + data_len;
  uint8_t* nal_data = (uint8_t*)calloc(size_nal, sizeof(uint8_t));
  memcpy(nal_data, hdata, hdata_len);
  memcpy(nal_data + hdata_len, data, data_len);
  *out_nal = nal_data;
  return size_nal;
}

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

  media_stream_params_t params;
  params.height_video = height;
  params.width_video = width;
  params.video_fps = fps;
  params.bit_stream = bit_rate;
  params.codec_id = AV_CODEC_ID_H264;

  media_stream_t* ostream = alloc_video_stream(outfilename, &params, false);
  if(!ostream){
    return EXIT_FAILURE;
  }

  char errbuf[PCAP_ERRBUF_SIZE];
  pcap_t* pcap = pcap_open_offline_with_tstamp_precision(infilename, PCAP_TSTAMP_PRECISION_NANO, errbuf);
  if (!pcap) {
    fprintf(stderr, "error reading pcap file: %s\n", errbuf);
    free_video_stream(ostream);
    return EXIT_FAILURE;
  }

  struct pcap_pkthdr header;
  const u_char *packet;
  while ((packet = pcap_next(pcap, &header)) != NULL) {
    packet += sizeof(vgem_hdr);
    bpf_u_int32 packet_len = header.caplen - sizeof(vgem_hdr);
    if (packet_len < sizeof(struct ether_header)) {
      pcap_close(pcap);
      free_video_stream(ostream);
      return EXIT_FAILURE;
    }

    struct ether_header* ethernet_header = (struct ether_header*)packet;
    uint16_t ht = ntohs(ethernet_header->ether_type);
    if (ht != ETHERTYPE_IP) {
      continue;
    }

    /* Skip over the Ethernet header. (14)*/
    packet += sizeof(struct ether_header);
    packet_len -= sizeof(struct ether_header);

    if (packet_len < sizeof(struct ip)) {
      pcap_close(pcap);
      free_video_stream(ostream);
      return EXIT_FAILURE;
    }

    struct iphdr* ip = (struct iphdr*) packet;
    if (!(ip->protocol != IPPROTO_UDP || ip->protocol != IPPROTO_TCP)) {
      continue;
    }

    unsigned int IP_header_length = ip->ihl * 4;  /* ip_hl is in 4-byte words */
    if (packet_len < IP_header_length) { /* didn't capture the full IP header including options */
      pcap_close(pcap);
      free_video_stream(ostream);
      return EXIT_FAILURE;
    }

    packet += IP_header_length;
    packet_len -= IP_header_length;

    if (ip->protocol == IPPROTO_UDP) {
        if (packet_len < sizeof(udphdr)) {
          pcap_close(pcap);
          free_video_stream(ostream);
          return EXIT_FAILURE;
        }

        packet += sizeof(udphdr);
        packet_len -= sizeof(udphdr);

        struct rtp_hdr* rtp = (struct rtp_hdr*)packet;
        if (packet_len < sizeof(rtp_hdr)) {
          pcap_close(pcap);
          free_video_stream(ostream);
          return EXIT_FAILURE;
        }

        // rtp payload
        packet += sizeof(rtp_hdr);
        packet_len -= sizeof(rtp_hdr);
        if (packet_len <= 2) {
          continue;
        }

        uint8_t nal = packet[0];
        uint8_t fragment_type = (nal & 0x1F);

        if (fragment_type >= 1 && fragment_type <= 23) {
          uint8_t* nal_data = NULL;
          size_t size_nal = make_nal_frame_header(packet, packet_len, nal_header, sizeof(nal_header), &nal_data);
          media_stream_write_video_frame(ostream, nal_data, size_nal);
          free(nal_data);
        } else if(fragment_type == 24) {
            packet++;
            packet_len--;
            // first we are going to figure out the total size....
            {
              int total_length= 0;
              uint8_t* dst = NULL;

              for(int pass = 0; pass < 2; pass++) {
                  const uint8_t* src = packet;
                  int src_len = packet_len;

                  do {
                      uint16_t nal_size = AV_RB16(src); // this going to be a problem if unaligned (can it be?)

                      // consume the length of the aggregate...
                      src += 2;
                      src_len -= 2;

                      if (nal_size <= src_len) {
                          if(pass==0) {
                              // counting...
                              total_length+= sizeof(nal_header)+nal_size;
                          } else {
                              // copying
                              assert(dst);
                              memcpy(dst, nal_header, sizeof(nal_header));
                              dst += sizeof(nal_header);
                              memcpy(dst, src, nal_size);
                              dst += nal_size;
                          }
                      } else {
                          av_log(NULL, AV_LOG_ERROR,
                                 "nal size exceeds length: %d %d\n", nal_size, src_len);
                      }

                      // eat what we handled...
                      src += nal_size;
                      src_len -= nal_size;

                      if (src_len < 0)
                          av_log(NULL, AV_LOG_ERROR,
                                 "Consumed more bytes than we got! (%d)\n", src_len);
                  } while (src_len > 2);      // because there could be rtp padding..

                  if (pass == 0) {
                    dst = (uint8_t*)calloc(total_length, sizeof(uint8_t));
                  } else {
                  }
              }

          }
        } else if (fragment_type == 28 || fragment_type == 29) {
          packet++;
          packet_len--;

          uint8_t fu_indicator = nal;
          uint8_t fu_header = *packet;   // read the fu_header.
          uint8_t start_bit = fu_header >> 7;
          uint8_t end_bit = (fu_header & 0x40) >> 6;
          uint8_t nal_type = (fu_header & 0x1f);
          uint8_t reconstructed_nal = fu_indicator & (0xe0);  // the original nal forbidden bit and NRI are stored in this packet's nal;
          reconstructed_nal |= nal_type;

          packet++;
          packet_len--;

          if (fragment_type == 29) {
            packet = packet + 2;
            packet_len -= 2;
          }

          CHECK(packet_len > 0);

          if (start_bit) {
            size_t size_nal = sizeof(nal_header) + sizeof(nal) + packet_len;
            uint8_t* nal_data = (uint8_t*)calloc(size_nal, sizeof(uint8_t));
            memcpy(nal_data, nal_header, sizeof(nal_header));
            nal_data[sizeof(nal_header)]= reconstructed_nal;
            memcpy(nal_data + sizeof(nal_header) + sizeof(nal), packet, packet_len);
            media_stream_write_video_frame(ostream, nal_data, size_nal);
            free(nal_data);
          } else {
            media_stream_write_video_frame(ostream, packet, packet_len);
          }
        } else {
          NOTREACHED();
        }

        // http://stackoverflow.com/questions/3493742/problem-to-decode-h264-video-over-rtp-with-ffmpeg-libavcodec
        // http://stackoverflow.com/questions/1957427/detect-mpeg4-h264-i-frame-idr-in-rtp-stream
    } else if (ip->protocol == IPPROTO_TCP) {
        if (packet_len < sizeof(tcphdr)) {
          continue;
        }

        struct tcphdr *tcpheader = (struct tcphdr *)packet;
        packet += sizeof(tcphdr);
        packet_len -= sizeof(tcphdr);

        if (packet_len < sizeof(rtp_hdr)) {
          continue;
        }

        // parse RTSP packet
    }
  }

  pcap_close(pcap);
  free_video_stream(ostream);
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 * main file for derelict app
 *
 * starts GLUT and runs callbacks
 */

#include <iostream>
#include <GL/glfw.h>

#include "Key.h"
#include "Cam.h"

void Init() {
	glClearColor(1, 1, 1, 0);
}

void Display() {
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

}

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

	glfwOpenWindow(800, 600, 0, 0, 0, 0, 16, 0, GLFW_WINDOW);

	Init();

	glfwSetKeyCallback(Key::KeyEvent);
	glfwSetWindowSizeCallback(Cam::ResizeCallback);

	bool running = true;

	while(running) {
		Display();

		glfwSwapBuffers();

		running = !glfwGetKey(GLFW_KEY_ESC) &&
		          glfwGetWindowParam(GLFW_OPENED);
	}

	glfwCloseWindow();

	glfwTerminate();
}
<commit_msg>Made the main app do something.<commit_after>/*
 * main.cpp
 *
 * main file for derelict app
 *
 * starts GLUT and runs callbacks
 */

#include <iostream>
#include <GL/glfw.h>

#include "Key.h"
#include "Cam.h"

void Init() {
	glClearColor(1, 1, 1, 0);
}

void Display() {
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

	glColor3f(0, 0, 0);

	glBegin(GL_TRIANGLE_STRIP);
		glVertex2f( 0,  0);
		glVertex2f(1,  0);
		glVertex2f( 0, 1);
	glEnd();
}

void Update() {
	if(Key::I().Pressed('D')) {
		Vector pos = Cam::I().GetPos();
		pos.i += 0.1;
		Cam::I().SetPos(pos);
	} else if(Key::I().Pressed('A')) {
		Vector pos = Cam::I().GetPos();
		pos.i -= 0.1;
		Cam::I().SetPos(pos);
	}
}

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

	glfwOpenWindow(800, 600, 0, 0, 0, 0, 16, 0, GLFW_WINDOW);

	Init();

	glfwSetKeyCallback(Key::KeyEvent);
	glfwSetWindowSizeCallback(Cam::ResizeCallback);

	bool running = true;

	while(running) {
		Display();

		Update();
		Key::I().Update();

		glfwSwapBuffers();

		running = !glfwGetKey(GLFW_KEY_ESC) &&
		          glfwGetWindowParam(GLFW_OPENED);

		glfwSleep(0.01);
	}

	glfwCloseWindow();

	glfwTerminate();
}
<|endoftext|>


<commit_before>#include "consts.h"
#include "circuits/circuit.h"
#include "circuits/element.h"
#include "matrix/matrix.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdlib>

using namespace std;

void exitPolitely(int exitCode) {
	#if defined (WIN32) || defined(_WIN32)
	cout << endl << "Press any key to exit...";
	cin.get();
	cin.get();
	#endif
	exit(exitCode);
}

int readNetlistFile(int argc, char** argv, ifstream& netlistFile){
    string filepath;

    switch(argc) {
        case 1: {
            cout << "Enter path to netlist file: ";
            cin >> filepath;
            break;
        }
        case 2: {
            filepath = argv[1];
            break;
        }
        default:
            cerr << "FAILURE: Too much information!" << endl;
            return EXIT_FAILURE;
    }

    netlistFile.open(filepath.c_str(), ifstream::in);
    if(!netlistFile.is_open()){
        cerr << "FAILURE: Cannot open file " << filepath << endl;
		return EXIT_FAILURE;
    }
    return 0;
}

void printIntro(){
    cout << endl << "Modified Nodal Analysis"
         << endl << "Originally by Antonio Carlos M. de Queiroz (acmq@coe.ufrj.br)"
         << endl << "Modified by Dhiana Deva, Felipe de Leo and Silvino Vieira" << endl << endl;
}

/* The program starts here */
int main(int argc, char **argv){
    printIntro();

	/* Creating a the variable "netlistFile" to use as input file to get the external data to the program */
    int numVariables=0,
        numElements=0,
        numNodes=0,
        rc=0;
    ifstream netlistFile;
    vector<string> lista(MAX_NAME+2); /*Tem que caber jx antes do nome */
    vector<Element> netlist(MAX_ELEMS);
    double Yn[MAX_NODES+1][MAX_NODES+2];

    // XXX Magic! Really important!
    // If it goes after readElements everything mixes up!
    lista[0] = "0";

    rc = readNetlistFile(argc, argv, netlistFile);
    if (rc) // if not return code 0 (success)
        exitPolitely(EXIT_FAILURE);

    cout << "Reading netlist:" << endl;
    rc = readElementsFromNetlist(numElements,
                                numVariables,
                                netlistFile,
                                lista,
                                netlist);
    if (rc) // if not return code 0 (success)
        exitPolitely(EXIT_FAILURE);

    rc = addCurrentVariablesToNetlist(numElements,
                                     numVariables,
                                     numNodes,
                                     lista,
                                     netlist);
    if (rc) // if not return code 0 (success)
        exitPolitely(EXIT_FAILURE);

    #ifdef DEBUG
    cout << "Internal variables:" << endl;
    printVariables(numVariables, lista);

    cout << "Summary:" << endl;
    printSummary(numNodes, numVariables, numElements);
    #endif

    // Operations on the modified matrix...
    init(numVariables, Yn);
    applyStamps(numElements, numVariables, netlist, Yn);
    rc = solve(numVariables, Yn);
    if (rc) // if not return code 0 (success)
        exitPolitely(EXIT_FAILURE);

    #ifdef DEBUG
    cout << "Final system:" << endl;
    print(numVariables, Yn);

    cout << "Solution:" << endl;
    printSolution(numVariables, numNodes, Yn, lista);
    #endif

    /* Save solution to File */
    string OutputFile;
    OutputFile = "output.tab";
    WriteSolutionToFile(OutputFile, numVariables, numNodes, Yn, lista);

    exitPolitely(EXIT_SUCCESS);
}
<commit_msg>Removes legacy comment (was mixing tabs and spaces anyways)<commit_after>#include "consts.h"
#include "circuits/circuit.h"
#include "circuits/element.h"
#include "matrix/matrix.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdlib>

using namespace std;

void exitPolitely(int exitCode) {
	#if defined (WIN32) || defined(_WIN32)
	cout << endl << "Press any key to exit...";
	cin.get();
	cin.get();
	#endif
	exit(exitCode);
}

int readNetlistFile(int argc, char** argv, ifstream& netlistFile){
    string filepath;

    switch(argc) {
        case 1: {
            cout << "Enter path to netlist file: ";
            cin >> filepath;
            break;
        }
        case 2: {
            filepath = argv[1];
            break;
        }
        default:
            cerr << "FAILURE: Too much information!" << endl;
            return EXIT_FAILURE;
    }

    netlistFile.open(filepath.c_str(), ifstream::in);
    if(!netlistFile.is_open()){
        cerr << "FAILURE: Cannot open file " << filepath << endl;
		return EXIT_FAILURE;
    }
    return 0;
}

void printIntro(){
    cout << endl << "Modified Nodal Analysis"
         << endl << "Originally by Antonio Carlos M. de Queiroz (acmq@coe.ufrj.br)"
         << endl << "Modified by Dhiana Deva, Felipe de Leo and Silvino Vieira" << endl << endl;
}

/* The program starts here */
int main(int argc, char **argv){
    printIntro();

    int numVariables=0,
        numElements=0,
        numNodes=0,
        rc=0;
    ifstream netlistFile;
    vector<string> lista(MAX_NAME+2); /*Tem que caber jx antes do nome */
    vector<Element> netlist(MAX_ELEMS);
    double Yn[MAX_NODES+1][MAX_NODES+2];

    // XXX Magic! Really important!
    // If it goes after readElements everything mixes up!
    lista[0] = "0";

    rc = readNetlistFile(argc, argv, netlistFile);
    if (rc) // if not return code 0 (success)
        exitPolitely(EXIT_FAILURE);

    cout << "Reading netlist:" << endl;
    rc = readElementsFromNetlist(numElements,
                                numVariables,
                                netlistFile,
                                lista,
                                netlist);
    if (rc) // if not return code 0 (success)
        exitPolitely(EXIT_FAILURE);

    rc = addCurrentVariablesToNetlist(numElements,
                                     numVariables,
                                     numNodes,
                                     lista,
                                     netlist);
    if (rc) // if not return code 0 (success)
        exitPolitely(EXIT_FAILURE);

    #ifdef DEBUG
    cout << "Internal variables:" << endl;
    printVariables(numVariables, lista);

    cout << "Summary:" << endl;
    printSummary(numNodes, numVariables, numElements);
    #endif

    // Operations on the modified matrix...
    init(numVariables, Yn);
    applyStamps(numElements, numVariables, netlist, Yn);
    rc = solve(numVariables, Yn);
    if (rc) // if not return code 0 (success)
        exitPolitely(EXIT_FAILURE);

    #ifdef DEBUG
    cout << "Final system:" << endl;
    print(numVariables, Yn);

    cout << "Solution:" << endl;
    printSolution(numVariables, numNodes, Yn, lista);
    #endif

    /* Save solution to File */
    string OutputFile;
    OutputFile = "output.tab";
    WriteSolutionToFile(OutputFile, numVariables, numNodes, Yn, lista);

    exitPolitely(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>//! \file main.cpp

#include <fstream>
#include <iostream>
#include <string>

#include "Article.h"
#include "ToGraphvizWriter.h"
#include "WikiWalker.h"
#include "version.h"

#include "config.h"

using CmdOpt = WikiWalker::CommandLineParserBase::CommandLineOptions;

int main(int argc, char** argv)
{
#if defined(WW_USE_BOOST_PO)
  WikiWalker::BoostPoCommandLineParser cmdp;
#elif defined(WW_USE_GETOPT)
  WikiWalker::GetoptCommandLineParser cmdp;
#endif

  try {
    cmdp.parse(argc, argv);
  } catch(std::exception& e) {
    std::cerr << std::endl << e.what() << std::endl;
    cmdp.printHelp();
    return -1;
  }

  if(cmdp.hasSet(CmdOpt::Version)) {
    std::cout << "WikiWalker, version " << _WW_VERSION << std::endl;
    return 0;
  }

  if(cmdp.hasSet(CmdOpt::Help)) {
    cmdp.printHelp();
    return 0;
  }

  bool isUrlSet       = cmdp.hasSet(CmdOpt::URL);
  bool isCacheSet     = cmdp.hasSet(CmdOpt::JsonCache);
  bool isDotSet       = cmdp.hasSet(CmdOpt::DotOut);
  bool validRunConfig = isUrlSet || (isDotSet && isCacheSet);

  if(!validRunConfig) {
    std::cerr << "Must either specify at least URL, "
              << "or dot and cache file." << std::endl;
    cmdp.printHelp();
    return 1;
  }

  bool read_failed = false;
  WikiWalker::WikiWalker w;

  if(isCacheSet) {
    try {
      std::string cachefile = cmdp.getValue(CmdOpt::JsonCache);
      w.readCache(cachefile);
    } catch(std::exception& e) {
      std::cout << e.what() << std::endl;
      read_failed = true;
    }
  }

  if(isUrlSet) {
    try {
      std::string url = cmdp.getValue(CmdOpt::URL);
      w.startWalking(url);
    } catch(std::exception& e) {
      std::cout << "Error: " << e.what() << std::endl;
      return -1;
    }
  }

  if(isCacheSet) {
    std::string cachefile = cmdp.getValue(CmdOpt::JsonCache);
    if(read_failed) {
      cachefile.append("_");
      std::cout << "Reading from cache failed, write to " << cachefile
                << std::endl;
    }
    try {
      w.writeCache(cachefile);
    } catch(std::exception& e) {
      std::cout << "Error: " << e.what() << std::endl;
    }
  }

  if(isDotSet) {
    const WikiWalker::ArticleCollection& ac = w.getCollection();
    std::string outfile                     = cmdp.getValue(CmdOpt::DotOut);
    WikiWalker::ToGraphvizWriter tgw;
    std::ofstream file(outfile, std::ios::trunc | std::ios::out);

    if(file.fail()) {
      std::cerr << "Error opening dot out file for writing" << std::endl;
    } else {
      tgw.output(ac, file);
      file.flush();

      if(file.bad() || file.fail()) {
        std::cerr << "Error during writing dot out file." << std::endl;
      }

      file.close();
    }
  }

  for(auto& a : w.getCollection()) {
    auto& art = a.second;
    if(art->isAnalyzed()) {
      std::cout << "Article " << a.first << " has " << art->getNumLinks()
                << " links" << std::endl;
    }
  }

  return 0;
}
<commit_msg>Add option checking to main<commit_after>//! \file main.cpp

#include <fstream>
#include <iostream>
#include <string>

#include "Article.h"
#include "ToGraphvizWriter.h"
#include "WikiWalker.h"
#include "version.h"

#include "config.h"

using CmdOpt = WikiWalker::CommandLineParserBase::CommandLineOptions;

int main(int argc, char** argv)
{
#if defined(WW_USE_BOOST_PO)
  WikiWalker::BoostPoCommandLineParser cmdp;
#elif defined(WW_USE_GETOPT)
  WikiWalker::GetoptCommandLineParser cmdp;
#endif

  try {
    cmdp.parse(argc, argv);
  } catch(std::exception& e) {
    std::cerr << std::endl << e.what() << std::endl;
    cmdp.printHelp();
    return -1;
  }

  if(cmdp.hasSet(CmdOpt::Version)) {
    std::cout << "WikiWalker, version " << _WW_VERSION << std::endl;
    return 0;
  }

  if(cmdp.hasSet(CmdOpt::Help)) {
    cmdp.printHelp();
    return 0;
  }

  bool isUrlSet       = cmdp.hasSet(CmdOpt::URL);
  bool isCacheSet     = cmdp.hasSet(CmdOpt::JsonCache);
  bool isDotSet       = cmdp.hasSet(CmdOpt::DotOut);
  bool isDeepSet      = cmdp.hasSet(CmdOpt::FetchDeep);
  bool validRunConfig = isUrlSet || (isDotSet && isCacheSet);

  if(!validRunConfig) {
    std::cerr << "Must either specify at least URL, "
              << "or dot and cache file." << std::endl;
    cmdp.printHelp();
    return 1;
  }

  if(isUrlSet && isDeepSet && !isCacheSet) {
    std::cerr << "Please specify a cache file when using \"deep\" option"
              << std::endl;
    cmdp.printHelp();
    return 1;
  }

  bool read_failed = false;
  WikiWalker::WikiWalker w;

  if(isCacheSet) {
    try {
      std::string cachefile = cmdp.getValue(CmdOpt::JsonCache);
      w.readCache(cachefile);
    } catch(std::exception& e) {
      std::cout << e.what() << std::endl;
      read_failed = true;
    }
  }

  if(isUrlSet) {
    try {
      std::string url = cmdp.getValue(CmdOpt::URL);
      w.startWalking(url);
    } catch(std::exception& e) {
      std::cout << "Error: " << e.what() << std::endl;
      return -1;
    }
  }

  if(isCacheSet) {
    std::string cachefile = cmdp.getValue(CmdOpt::JsonCache);
    if(read_failed) {
      cachefile.append("_");
      std::cout << "Reading from cache failed, write to " << cachefile
                << std::endl;
    }
    try {
      w.writeCache(cachefile);
    } catch(std::exception& e) {
      std::cout << "Error: " << e.what() << std::endl;
    }
  }

  if(isDotSet) {
    const WikiWalker::ArticleCollection& ac = w.getCollection();
    std::string outfile                     = cmdp.getValue(CmdOpt::DotOut);
    WikiWalker::ToGraphvizWriter tgw;
    std::ofstream file(outfile, std::ios::trunc | std::ios::out);

    if(file.fail()) {
      std::cerr << "Error opening dot out file for writing" << std::endl;
    } else {
      tgw.output(ac, file);
      file.flush();

      if(file.bad() || file.fail()) {
        std::cerr << "Error during writing dot out file." << std::endl;
      }

      file.close();
    }
  }

  for(auto& a : w.getCollection()) {
    auto& art = a.second;
    if(art->isAnalyzed()) {
      std::cout << "Article " << a.first << " has " << art->getNumLinks()
                << " links" << std::endl;
    }
  }

  return 0;
}
<|endoftext|>


<commit_before>#include "main.hpp"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <boost/program_options.hpp>
int main(int argc, char* argv[]) {

	namespace po = boost::program_options;
	boost::program_options::options_description opt("Options");
	opt.add_options()("input-file", boost::program_options::value<std::vector<std::string>>()->multitoken(), "file name to convert");
	opt.add_options()("output-file,o", boost::program_options::value<std::string>(), "file name of the output(without extentions)");
	po::positional_options_description p;
	p.add("input-file", -1);

	po::variables_map vm;
	po::store(po::command_line_parser(argc, argv).
			  options(opt).positional(p).run(), vm);
	po::notify(vm);

	if(!vm.count("input-file")) {
		std::cout << opt << std::endl;
		return 0;
	}

	decltype(ALSL::parseFile(std::string(argv[1]))) ret;

	std::string fname = (!vm.count("output-file")) ? "a" : vm["output-file"].as<std::string>();
	std::ofstream ofsGL(fname + ".fs", std::ofstream::out);
	std::ofstream ofsHL(fname + ".fx", std::ofstream::out);
	for(std::string const& src : vm["input-file"].as<std::vector<std::string>>()) {
		try {
			// ret = ALSL::parseFile(std::string(argv[1]));
			ret = ALSL::parseFile(src);

		} catch(...){
			std::cout << "unknown error was occured while parsing." << std::endl;
		}
			ALSL::GeneratorGLSL genGL;
			ALSL::GeneratorHLSL genHL;

			// auto const ret = ALSL::parseFile(vm["input-file"].as<std::string>());
		if(ret) {
			std::cout << "Succeessfully translated." << std::endl;

			genGL.generate(ofsGL, *ret);
			genHL.generate(ofsHL, *ret);

		} else {
			std::cout << "Failed to translate." << std::endl;

		}
	}
	ofsGL.close();
	ofsHL.close();

	//} catch(...) {
	//	std::cout << "unknown error was occured while parsing." << std::endl;
	//}

	return 0;
}<commit_msg>check whether the input files exist.<commit_after>#include "main.hpp"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
int main(int argc, char* argv[]) {

	namespace po = boost::program_options;
	boost::program_options::options_description opt("Options");
	opt.add_options()("input-file", boost::program_options::value<std::vector<std::string>>()->multitoken(), "file name to convert");
	opt.add_options()("output-file,o", boost::program_options::value<std::string>(), "file name of the output(without extentions)");
	po::positional_options_description p;
	p.add("input-file", -1);

	po::variables_map vm;
	po::store(po::command_line_parser(argc, argv).
			  options(opt).positional(p).run(), vm);
	po::notify(vm);

	if(!vm.count("input-file")) {
		std::cout << opt << std::endl;
		return 0;
	}

	decltype(ALSL::parseFile(std::string(argv[1]))) ret;

	std::string fname = (!vm.count("output-file")) ? "a" : vm["output-file"].as<std::string>();

	std::ofstream ofsGL(fname + ".fs", std::ofstream::out);
	std::ofstream ofsHL(fname + ".fx", std::ofstream::out);
	for(std::string const& src : vm["input-file"].as<std::vector<std::string>>()) {

		boost::system::error_code error;
		const bool result = boost::filesystem::exists(boost::filesystem::path(src), error);
		if(!result || error) {
			std::cerr << "file " << src << " is not exist." << std::endl;
			continue;
		}

		try {
			// ret = ALSL::parseFile(std::string(argv[1]));
			ret = ALSL::parseFile(src);

		} catch(...){
			std::cerr << src << ": unknown error was occured while parsing." << std::endl;
		}
			ALSL::GeneratorGLSL genGL;
			ALSL::GeneratorHLSL genHL;

			// auto const ret = ALSL::parseFile(vm["input-file"].as<std::string>());
		if(ret) {
			std::cout << src << ": succeessfully translated." << std::endl;

			genGL.generate(ofsGL, *ret);
			genHL.generate(ofsHL, *ret);

		} else {
			std::cerr << src << ": failed to translate." << std::endl;

		}
	}
	ofsGL.close();
	ofsHL.close();

	//} catch(...) {
	//	std::cout << "unknown error was occured while parsing." << std::endl;
	//}

	return 0;
}<|endoftext|>


<commit_before>#include <chrono>
#include <thread>

#include "AudioSubsystem.h"
#include "AudioSubsystem_OpenAL.h"
#include "Decoders/iWaveDataProvider.h"
#include "Decoders/WAV/WAVDataProvider.h"
#include "Utils.h"

int main( int argc, char* argv[] )
{
	const char* FileName = ( argc > 1 ) ? argv[1] : "test.wav";

	auto AudioSubsystem = CreateAudioSubsystem_OpenAL();

	AudioSubsystem->Start();

	auto TestBlob = ReadFileAsBlob( FileName );
	auto Provider = CreateWaveDataProvider( FileName, TestBlob );
	auto Source = AudioSubsystem->CreateAudioSource();
	Source->BindDataProvider( Provider );
	Source->Play();

	while ( Source->IsPlaying() && !IsKeyPressed() );

	std::this_thread::sleep_for( std::chrono::milliseconds(300) );

	Source->Stop();
	Source = nullptr;

	AudioSubsystem->Stop();

	return 0;
};
<commit_msg>Just sleep in the busy loop<commit_after>#include <chrono>
#include <thread>

#include "AudioSubsystem.h"
#include "AudioSubsystem_OpenAL.h"
#include "Decoders/iWaveDataProvider.h"
#include "Decoders/WAV/WAVDataProvider.h"
#include "Utils.h"

int main( int argc, char* argv[] )
{
	const char* FileName = ( argc > 1 ) ? argv[1] : "test.wav";

	auto AudioSubsystem = CreateAudioSubsystem_OpenAL();

	AudioSubsystem->Start();

	auto TestBlob = ReadFileAsBlob( FileName );
	auto Provider = CreateWaveDataProvider( FileName, TestBlob );
	auto Source = AudioSubsystem->CreateAudioSource();
	Source->BindDataProvider( Provider );
	Source->Play();

	while ( Source->IsPlaying() && !IsKeyPressed() )
	{
		std::this_thread::sleep_for( std::chrono::milliseconds(10) );
	};

	std::this_thread::sleep_for( std::chrono::milliseconds(300) );

	Source->Stop();
	Source = nullptr;

	AudioSubsystem->Stop();

	return 0;
};
<|endoftext|>


<commit_before>/*
MIT License

Copyright (c) 2017 CPirc
Copyright (c) 2018 CPirc
Copyright (c) 2019 CPirc

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 <string>

#include "bitboard.h"
#include "position.h"
#include "uci.h"

int main()
{
    seed_rng(17594872);
    init_keys();
    init_bitboards();

    std::setbuf(stdout, NULL);
    std::setbuf(stdin, NULL);

    std::string line;
    while (true) {
        std::getline(std::cin, line);
        if (line == "uci") {
            UCI::listen();
        } else if (line == "xboard") {
            std::cout << "Protocol not supported" << std::endl;
        } else if (line == "quit") {
            break;
        } else {
            std::cout << "Unknown protocol" << std::endl;
        }
    }

    return 0;
}
<commit_msg>Fix quit issue<commit_after>/*
MIT License

Copyright (c) 2017 CPirc
Copyright (c) 2018 CPirc
Copyright (c) 2019 CPirc

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 <string>

#include "bitboard.h"
#include "position.h"
#include "uci.h"

int main()
{
    seed_rng(17594872);
    init_keys();
    init_bitboards();

    std::setbuf(stdout, NULL);
    std::setbuf(stdin, NULL);

    std::string line;
    while (true) {
        std::getline(std::cin, line);
        if (line == "uci") {
            UCI::listen();
            break;
        } else if (line == "xboard") {
            std::cout << "Protocol not supported" << std::endl;
        } else if (line == "quit") {
            break;
        } else {
            std::cout << "Unknown protocol" << std::endl;
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <SDL2/SDL.h>
#include "draw.hpp"

const char * game_name = "Game Of Life On Surface";
int screen_width = 640;
int screen_height = 640;
int R = 200;
field f(16, 32);
bool quit_flag = false;
SDL_Window * window = NULL;
SDL_Renderer * render = NULL;
SDL_Event event;

void game_send_error( int code ) {
    printf( "[error]: %s\n", SDL_GetError() );
    exit( code );
}

void game_event( SDL_Event * event ) {
    SDL_PollEvent( event );
    switch ( event->type ) {
        case SDL_QUIT:
            quit_flag = true;
            break;
        case SDL_WINDOWEVENT:
            if ( event->window.event == SDL_WINDOWEVENT_RESIZED ) {
                screen_width  = event->window.data1;
                screen_height = event->window.data2;
            }
            break;
        case SDL_KEYDOWN:
            switch ( event->key.keysym.sym ) {
                case SDLK_ESCAPE:
                    quit_flag = true;
                    break;
                default:
                    break;
            }
        default:
            break;
    }
}

void game_loop( void ) {
    // insert code
}

void draw_point( int x, int y, int size ) {
    SDL_Rect rect = { x, y, size, size };
    SDL_RenderFillRect( render, &rect );
}

void game_render( void ) {
    SDL_RenderClear( render );
    set_coloru( COLOR_WHITE );
    draw_sphere( { screen_width / 2, screen_height / 2 }, R, f );
    set_coloru( COLOR_BLACK );
    SDL_RenderPresent( render );
}

void game_destroy( void ) {
    SDL_DestroyRenderer( render );
    SDL_DestroyWindow( window );
    SDL_Quit();
}

void game_init( void ) {
    SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS );
    window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                               screen_width, screen_height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
    if ( window == NULL ) {
        game_send_error( EXIT_FAILURE );
    }
    render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC |
                                 SDL_RENDERER_TARGETTEXTURE );
    if ( render == NULL ) {
        game_send_error( EXIT_FAILURE );
    }
    SDL_SetRenderDrawBlendMode( render, SDL_BLENDMODE_BLEND );
    draw_init( render );
}

int main() {
    Uint32 FPS_MAX = 1000 / 63; // ~ 60 fps

    game_init();
    while ( quit_flag == false ) {
        game_event( &event );
        game_loop();
        game_render();
        SDL_Delay( FPS_MAX );
    }
    game_destroy();
    return EXIT_SUCCESS;
}
<commit_msg>[del] unuse code; [fix] revert argc, argv for Windows compile<commit_after>#include <cstdio>
#include <SDL2/SDL.h>
#include "draw.hpp"

const char * game_name = "Game Of Life On Surface";
int screen_width = 640;
int screen_height = 640;
int R = 200;
field f(16, 32);
bool quit_flag = false;
SDL_Window * window = NULL;
SDL_Renderer * render = NULL;
SDL_Event event;

void game_send_error( int code ) {
    printf( "[error]: %s\n", SDL_GetError() );
    exit( code );
}

void game_event( SDL_Event * event ) {
    SDL_PollEvent( event );
    switch ( event->type ) {
        case SDL_QUIT:
            quit_flag = true;
            break;
        case SDL_WINDOWEVENT:
            if ( event->window.event == SDL_WINDOWEVENT_RESIZED ) {
                screen_width  = event->window.data1;
                screen_height = event->window.data2;
            }
            break;
        case SDL_KEYDOWN:
            switch ( event->key.keysym.sym ) {
                case SDLK_ESCAPE:
                    quit_flag = true;
                    break;
                default:
                    break;
            }
        default:
            break;
    }
}

void game_loop( void ) {
    // insert code
}

void game_render( void ) {
    SDL_RenderClear( render );
    set_coloru( COLOR_WHITE );
    draw_sphere( { screen_width / 2, screen_height / 2 }, R, f );
    set_coloru( COLOR_BLACK );
    SDL_RenderPresent( render );
}

void game_destroy( void ) {
    SDL_DestroyRenderer( render );
    SDL_DestroyWindow( window );
    SDL_Quit();
}

void game_init( void ) {
    SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS );
    window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                               screen_width, screen_height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
    if ( window == NULL ) {
        game_send_error( EXIT_FAILURE );
    }
    render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC |
                                 SDL_RENDERER_TARGETTEXTURE );
    if ( render == NULL ) {
        game_send_error( EXIT_FAILURE );
    }
    SDL_SetRenderDrawBlendMode( render, SDL_BLENDMODE_BLEND );
    draw_init( render );
}

int main( int argc, char * argv[] ) {
    Uint32 FPS_MAX = 1000 / 63; // ~ 60 fps

    game_init();
    while ( quit_flag == false ) {
        game_event( &event );
        game_loop();
        game_render();
        SDL_Delay( FPS_MAX );
    }
    game_destroy();
    return EXIT_SUCCESS;
}
<|endoftext|>