<commit_before>// Copyright (c) 2013 Park Jeongmin (pjm0616@gmail.com)
// See LICENSE for details.

#include <string>
#include <list>
#include <vector>
#include <map>
#include <sstream>

#include <string.h>
#include <inttypes.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <dirent.h>

#include "mabipack.h"
#include "wildcard.h"

// utilities
time_t filetime_to_unix_ts(uint64_t filetime, int utc_offset=MABIPACK_DEFAULT_TIMEZONE)
{
	return filetime / 10000000 - 11644473600 - utc_offset;
}

const char *format_filetime(uint64_t filetime)
{
	int utcoff = MABIPACK_DEFAULT_TIMEZONE;
	time_t ts = filetime_to_unix_ts(filetime, utcoff);
	static char buf[512];
	strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S %Z (Assuming KST)", localtime(&ts));
	return buf;
}

static bool check_patterns(const std::vector<const char *> &patterns, const std::string &name)
{
	if (patterns.empty()) {
		return true;
	}
	for (const char *pattern : patterns) {
		if (wc_match_nocase(pattern, name.c_str())) {
			return true;
		}
	}
	return false;
}

static void str_split(std::vector<std::string> &out, const std::string &str, char delim)
{
	std::stringstream ss(str);
	std::string buf;
	while (std::getline(ss, buf, delim)) {
		out.push_back(buf);
	}
}

static int mkdir_recursive(const std::string &path, bool ignore_last_elem=false)
{
	std::vector<std::string> elems;
	str_split(elems, path, '/');
	std::string buf("./");
	for (auto it = elems.begin(); it != elems.end(); ++it) {
		std::string &elem = *it;
		if (elem == "..") {
			return -1;
		}
		if (ignore_last_elem && (it + 1 == elems.end())) {
			break;
		}
		buf += elem + "/";
		int ret = mkdir(buf.c_str(), 0755);
		if (ret != 0 && errno != EEXIST) {
			perror("mkdir");
			return -1;
		}
	}
	return 0;
}

static int extract_file(MabiPack &pack, const std::string &name, const file_info &entry)
{
	int ret = mkdir_recursive(name, true);
	if (ret < 0) {
		// failed to make directory or there were invalid characters in filename.
		return -1;
	}

	int fd = open(name.c_str(), O_CREAT | O_WRONLY, 0644);
	if (fd < 0) {
		perror("open");
		return -1;
	}

	char *data = pack.readfile(entry);
	if (data == nullptr) {
		close(fd);
		unlink(name.c_str());
		fprintf(stderr, "Cannot extract file: %s\n", name.c_str());
		return -1;
	}
	int nwrite = write(fd, data, entry.size_orig);
	if (nwrite != (int)entry.size_orig) {
		if (nwrite < 0) {
			perror("write");
		} else {
			fprintf(stderr, "short write: %d, %d\n", nwrite, entry.size_orig);
		}
		close(fd);
		unlink(name.c_str());
		delete[] data;
		return -1;
	}

	close(fd);
	delete[] data;
	return 0;
}

// Program options
static const char *g_program_name;
static const char *g_packfile;
static std::vector<const char *> g_arglist;
// extract only
static const char *g_extract_dir = "./";
// create only
static int g_pack_version = 0;
static const char *g_pack_mountpoint = "data\\";

// verbs
typedef int (*mabipack_verb_t)();

static int do_extract()
{
	MabiPack pack;
	int ret = pack.openpack(g_packfile);
	if (ret != 0) {
		fprintf(stderr, "ERROR: Cannot open packfile: %d\n", ret);
		return EXIT_FAILURE;
	}

	ret = chdir(g_extract_dir);
	if (ret != 0) {
		ret = mkdir(g_extract_dir, 0755);
		if (ret != 0) {
			perror("mkdir");
			return EXIT_FAILURE;
		}

		ret = chdir(g_extract_dir);
		if (ret != 0) {
			perror("chdir");
			return EXIT_FAILURE;
		}
	}

	for (auto &entry : pack) {
		if (check_patterns(g_arglist, entry.first)) {
			printf("%s\n", entry.first.c_str());
			int ret = extract_file(pack, entry.first, entry.second);
			if (ret < 0) {
				fprintf(stderr, "Error extracting the package. aborting...\n");
				return EXIT_FAILURE;
			}
		}
	}

	return EXIT_SUCCESS;
}

static int do_list()
{
	MabiPack pack;
	int ret = pack.openpack(g_packfile);
	if (ret != 0) {
		fprintf(stderr, "ERROR: Cannot open packfile: %d\n", ret);
		return EXIT_FAILURE;
	}

	const package_header &hdr = pack.header();
	printf("Version number: %d\n", hdr.version);
	printf("Creation date: %s\n", format_filetime(hdr.time1));
	printf("Mountpoint: %s\n", hdr.mountpoint);
	printf("====================\n");
	uint32_t cnt = 0;
	uint64_t total_size = 0;
	for (auto &entry : pack) {
		if (check_patterns(g_arglist, entry.first)) {
			printf("%.2f KiB\t%s\n", entry.second.size_orig / 1024.0f, entry.first.c_str());
			cnt += 1;
			total_size += entry.second.size_orig;
		}
	}
	printf("Total %d file(s), %.2f MiB\n", cnt, total_size / 1048576.0f);

	return EXIT_SUCCESS;
}

// Note: trailing slashes must not be present in path argument.
static int collect_files(std::vector<std::string> &result, const std::string &path)
{
	struct stat sb;
	int ret = ::stat(path.c_str(), &sb);
	if (ret < 0) {
		fprintf(stderr, "ERROR: Cannot stat %s: %s\n", path.c_str(), strerror(errno));
		return -1;
	}

	if (S_ISREG(sb.st_mode)) {
		result.push_back(path);
	} else if (S_ISDIR(sb.st_mode)) {
		DIR *dp = opendir(path.c_str());
		if (!dp) {
			return -2;
		}

		struct dirent *entry;
		errno = 0;
		while ((entry = readdir(dp)) != NULL) {
			if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
				continue;
			}

			ret = collect_files(result, path + "/" + entry->d_name);
			if (ret < 0) {
				{
					PreserveErrno ep;
					closedir(dp);
				}
				return -3;
			}

			errno = 0;
		}
		{
			PreserveErrno ep;
			closedir(dp);
		}
		if (errno != 0) {
			return -4;
		}
	} else {
		errno = ESOCKTNOSUPPORT;
		return -5;
	}

	return 0;
}
static int do_create()
{
	std::vector<std::string> files;
	for (const char *name : g_arglist) {
		// Get the length of `name' without trailing slashes.
		int i = strlen(name) - 1;
		while (i >= 0 && name[i] == '/') {
			i--;
		}
		i++;
		if (i == 0) {
			fprintf(stderr, "ERROR: Empty filename in argument list\n");
			return EXIT_FAILURE;
		}
		std::string sname(name, i);
		int ret = collect_files(files, sname);
		if (ret < 0) {
			fprintf(stderr, "ERROR: Failed to collect filelist(%d): %s: %s\n", ret, sname.c_str(), strerror(errno));
			return EXIT_FAILURE;
		}
	}

	fprintf(stdout, "Creating package %s\n", g_packfile);
	fprintf(stdout, "Pack version: %d\n", g_pack_version);
	fprintf(stdout, "Mountpoint: %s\n", g_pack_mountpoint);
	fprintf(stdout, "Number of files: %lu\n", files.size());

	MabiPackWriter pack_writer;
	int ret = pack_writer.open(g_packfile, g_pack_version, files.size(), g_pack_mountpoint);
	if (ret != 0) {
		fprintf(stderr, "ERROR: Cannot open packfile: %d\n", ret);
		return EXIT_FAILURE;
	}

	for (const std::string &path : files) {
		fprintf(stdout, "Adding file %s\n", path.c_str());
		ret = pack_writer.addfile(path);
		if (ret < 0) {
			fprintf(stderr, "ERROR: Cannot add file(%d): %s: %s\n", ret, path.c_str(), strerror(errno));
			pack_writer.discard();
			return EXIT_FAILURE;
		}
	}

	ret = pack_writer.commit();
	if (ret < 0) {
		fprintf(stderr, "ERROR: Cannot write package header(%d): %s\n", ret, strerror(errno));
		pack_writer.discard();
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}

static int do_usage()
{
	fprintf(stderr, "Usage: %s <options> <packfile> [patterns...]\n", g_program_name);
	fprintf(stderr, "Options:\n");
	fprintf(stderr, "\t-h - help message\n");
	fprintf(stderr, "\t-l - list files in the package\n");
	fprintf(stderr, "\t-e - extract files in the package (default)\n");
	fprintf(stderr, "\t-c - create a new package\n");
	fprintf(stderr, "\t-d - set output directory (extract only)\n");
	fprintf(stderr, "\t-v - set package version (create only)\n");
	fprintf(stderr, "\t-m - set package mountpoint (create only)\n");

	return EXIT_SUCCESS;
}

// main
int main(int argc, char *argv[])
{
	// parse args
	g_program_name = argv[0];
	mabipack_verb_t func = do_extract;
	int opt;
	while ((opt = getopt(argc, argv, "hlecd:v:m:")) != -1) {
		switch (opt) {
		case 'h':
			do_usage();
			exit(EXIT_SUCCESS);

		case 'l':
			func = do_list;
			break;

		case 'e':
			func = do_extract;
			break;

		case 'c':
			func = do_create;
			break;

		case 'd':
			g_extract_dir = optarg;
			break;

		case 'v':
			g_pack_version = atoi(optarg);
			break;

		case 'm':
			g_pack_mountpoint = optarg;
			break;
		}
	}
	if (optind >= argc) {
		fprintf(stderr, "Error: Expected packfile argument after options.\n");
		do_usage();
		exit(EXIT_FAILURE);
	}

	g_packfile = argv[optind++];
	for (int i = optind; i < argc; i++) {
		g_arglist.push_back(argv[i]);
	}

	return func();
}

<commit_msg>Ignore duplicate files<commit_after>// Copyright (c) 2013 Park Jeongmin (pjm0616@gmail.com)
// See LICENSE for details.

#include <string>
#include <list>
#include <vector>
#include <map>
#include <set>
#include <sstream>

#include <string.h>
#include <inttypes.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <dirent.h>

#include "mabipack.h"
#include "wildcard.h"

// utilities
time_t filetime_to_unix_ts(uint64_t filetime, int utc_offset=MABIPACK_DEFAULT_TIMEZONE)
{
	return filetime / 10000000 - 11644473600 - utc_offset;
}

const char *format_filetime(uint64_t filetime)
{
	int utcoff = MABIPACK_DEFAULT_TIMEZONE;
	time_t ts = filetime_to_unix_ts(filetime, utcoff);
	static char buf[512];
	strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S %Z (Assuming KST)", localtime(&ts));
	return buf;
}

static bool check_patterns(const std::vector<const char *> &patterns, const std::string &name)
{
	if (patterns.empty()) {
		return true;
	}
	for (const char *pattern : patterns) {
		if (wc_match_nocase(pattern, name.c_str())) {
			return true;
		}
	}
	return false;
}

static void str_split(std::vector<std::string> &out, const std::string &str, char delim)
{
	std::stringstream ss(str);
	std::string buf;
	while (std::getline(ss, buf, delim)) {
		out.push_back(buf);
	}
}

static int mkdir_recursive(const std::string &path, bool ignore_last_elem=false)
{
	std::vector<std::string> elems;
	str_split(elems, path, '/');
	std::string buf("./");
	for (auto it = elems.begin(); it != elems.end(); ++it) {
		std::string &elem = *it;
		if (elem == "..") {
			return -1;
		}
		if (ignore_last_elem && (it + 1 == elems.end())) {
			break;
		}
		buf += elem + "/";
		int ret = mkdir(buf.c_str(), 0755);
		if (ret != 0 && errno != EEXIST) {
			perror("mkdir");
			return -1;
		}
	}
	return 0;
}

static int extract_file(MabiPack &pack, const std::string &name, const file_info &entry)
{
	int ret = mkdir_recursive(name, true);
	if (ret < 0) {
		// failed to make directory or there were invalid characters in filename.
		return -1;
	}

	int fd = open(name.c_str(), O_CREAT | O_WRONLY, 0644);
	if (fd < 0) {
		perror("open");
		return -1;
	}

	char *data = pack.readfile(entry);
	if (data == nullptr) {
		close(fd);
		unlink(name.c_str());
		fprintf(stderr, "Cannot extract file: %s\n", name.c_str());
		return -1;
	}
	int nwrite = write(fd, data, entry.size_orig);
	if (nwrite != (int)entry.size_orig) {
		if (nwrite < 0) {
			perror("write");
		} else {
			fprintf(stderr, "short write: %d, %d\n", nwrite, entry.size_orig);
		}
		close(fd);
		unlink(name.c_str());
		delete[] data;
		return -1;
	}

	close(fd);
	delete[] data;
	return 0;
}

// Program options
static const char *g_program_name;
static const char *g_packfile;
static std::vector<const char *> g_arglist;
// extract only
static const char *g_extract_dir = "./";
// create only
static int g_pack_version = 0;
static const char *g_pack_mountpoint = "data\\";

// verbs
typedef int (*mabipack_verb_t)();

static int do_extract()
{
	MabiPack pack;
	int ret = pack.openpack(g_packfile);
	if (ret != 0) {
		fprintf(stderr, "ERROR: Cannot open packfile: %d\n", ret);
		return EXIT_FAILURE;
	}

	ret = chdir(g_extract_dir);
	if (ret != 0) {
		ret = mkdir(g_extract_dir, 0755);
		if (ret != 0) {
			perror("mkdir");
			return EXIT_FAILURE;
		}

		ret = chdir(g_extract_dir);
		if (ret != 0) {
			perror("chdir");
			return EXIT_FAILURE;
		}
	}

	for (auto &entry : pack) {
		if (check_patterns(g_arglist, entry.first)) {
			printf("%s\n", entry.first.c_str());
			int ret = extract_file(pack, entry.first, entry.second);
			if (ret < 0) {
				fprintf(stderr, "Error extracting the package. aborting...\n");
				return EXIT_FAILURE;
			}
		}
	}

	return EXIT_SUCCESS;
}

static int do_list()
{
	MabiPack pack;
	int ret = pack.openpack(g_packfile);
	if (ret != 0) {
		fprintf(stderr, "ERROR: Cannot open packfile: %d\n", ret);
		return EXIT_FAILURE;
	}

	const package_header &hdr = pack.header();
	printf("Version number: %d\n", hdr.version);
	printf("Creation date: %s\n", format_filetime(hdr.time1));
	printf("Mountpoint: %s\n", hdr.mountpoint);
	printf("====================\n");
	uint32_t cnt = 0;
	uint64_t total_size = 0;
	for (auto &entry : pack) {
		if (check_patterns(g_arglist, entry.first)) {
			printf("%.2f KiB\t%s\n", entry.second.size_orig / 1024.0f, entry.first.c_str());
			cnt += 1;
			total_size += entry.second.size_orig;
		}
	}
	printf("Total %d file(s), %.2f MiB\n", cnt, total_size / 1048576.0f);

	return EXIT_SUCCESS;
}

// Note: trailing slashes must not be present in path argument.
static int collect_files(std::list<std::string> &result, std::set<std::string> &result_set, const std::string &path)
{
	struct stat sb;
	int ret = ::stat(path.c_str(), &sb);
	if (ret < 0) {
		fprintf(stderr, "ERROR: Cannot stat %s: %s\n", path.c_str(), strerror(errno));
		return -1;
	}

	if (S_ISREG(sb.st_mode)) {
		if (result_set.count(path)) {
			return 0;
		}
		result.push_back(path);
		result_set.insert(path);
	} else if (S_ISDIR(sb.st_mode)) {
		DIR *dp = opendir(path.c_str());
		if (!dp) {
			return -2;
		}

		struct dirent *entry;
		errno = 0;
		while ((entry = readdir(dp)) != NULL) {
			if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
				continue;
			}

			ret = collect_files(result, result_set, path + "/" + entry->d_name);
			if (ret < 0) {
				{
					PreserveErrno ep;
					closedir(dp);
				}
				return -3;
			}

			errno = 0;
		}
		{
			PreserveErrno ep;
			closedir(dp);
		}
		if (errno != 0) {
			return -4;
		}
	} else {
		errno = ESOCKTNOSUPPORT;
		return -5;
	}

	return 0;
}
static int do_create()
{
	std::list<std::string> files;
	std::set<std::string> files_set;
	for (const char *name : g_arglist) {
		// Get the length of `name' without trailing slashes.
		int i = strlen(name) - 1;
		while (i >= 0 && name[i] == '/') {
			i--;
		}
		i++;
		if (i == 0) {
			fprintf(stderr, "ERROR: Empty filename in argument list\n");
			return EXIT_FAILURE;
		}
		std::string sname(name, i);
		int ret = collect_files(files, files_set, sname);
		if (ret < 0) {
			fprintf(stderr, "ERROR: Failed to collect filelist(%d): %s: %s\n", ret, sname.c_str(), strerror(errno));
			return EXIT_FAILURE;
		}
	}

	fprintf(stdout, "Creating package %s\n", g_packfile);
	fprintf(stdout, "Pack version: %d\n", g_pack_version);
	fprintf(stdout, "Mountpoint: %s\n", g_pack_mountpoint);
	fprintf(stdout, "Number of files: %lu\n", files.size());

	MabiPackWriter pack_writer;
	int ret = pack_writer.open(g_packfile, g_pack_version, files.size(), g_pack_mountpoint);
	if (ret != 0) {
		fprintf(stderr, "ERROR: Cannot open packfile: %d\n", ret);
		return EXIT_FAILURE;
	}

	for (const std::string &path : files) {
		fprintf(stdout, "Adding file %s\n", path.c_str());
		ret = pack_writer.addfile(path);
		if (ret < 0) {
			fprintf(stderr, "ERROR: Cannot add file(%d): %s: %s\n", ret, path.c_str(), strerror(errno));
			pack_writer.discard();
			return EXIT_FAILURE;
		}
	}

	ret = pack_writer.commit();
	if (ret < 0) {
		fprintf(stderr, "ERROR: Cannot write package header(%d): %s\n", ret, strerror(errno));
		pack_writer.discard();
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}

static int do_usage()
{
	fprintf(stderr, "Usage: %s <options> <packfile> [patterns...]\n", g_program_name);
	fprintf(stderr, "Options:\n");
	fprintf(stderr, "\t-h - help message\n");
	fprintf(stderr, "\t-l - list files in the package\n");
	fprintf(stderr, "\t-e - extract files in the package (default)\n");
	fprintf(stderr, "\t-c - create a new package\n");
	fprintf(stderr, "\t-d - set output directory (extract only)\n");
	fprintf(stderr, "\t-v - set package version (create only)\n");
	fprintf(stderr, "\t-m - set package mountpoint (create only)\n");

	return EXIT_SUCCESS;
}

// main
int main(int argc, char *argv[])
{
	// parse args
	g_program_name = argv[0];
	mabipack_verb_t func = do_extract;
	int opt;
	while ((opt = getopt(argc, argv, "hlecd:v:m:")) != -1) {
		switch (opt) {
		case 'h':
			do_usage();
			exit(EXIT_SUCCESS);

		case 'l':
			func = do_list;
			break;

		case 'e':
			func = do_extract;
			break;

		case 'c':
			func = do_create;
			break;

		case 'd':
			g_extract_dir = optarg;
			break;

		case 'v':
			g_pack_version = atoi(optarg);
			break;

		case 'm':
			g_pack_mountpoint = optarg;
			break;
		}
	}
	if (optind >= argc) {
		fprintf(stderr, "Error: Expected packfile argument after options.\n");
		do_usage();
		exit(EXIT_FAILURE);
	}

	g_packfile = argv[optind++];
	for (int i = optind; i < argc; i++) {
		g_arglist.push_back(argv[i]);
	}

	return func();
}

<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

#include <SFML/Graphics.hpp>

using namespace std;
using namespace sf;

void load_csv(string & filename, vector<float> & data)
{
    ifstream infile(filename.c_str());
    string s_number, line;
    getline(infile, line);
    stringstream linestream(line);
    while(getline(linestream, s_number, ','))
    {
        data.push_back(atof(s_number.c_str()));
    }
    infile.close();
}

class TimeCourse : public Drawable
{
public:
    vector<float> data;
    TimeCourse(vector<float> & data)
    : data(data) {}
private:
    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
    {
        VertexArray polyline(sf::LinesStrip, data.size());
        for (int i = 0; i < data.size(); i++)
        {
            polyline[i] = Vector2f(i, (data.at(i) + 1) * 100);
        }
        target.draw(polyline, states);
    }
};

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

    if (argc < 2)
    {
        cout << "Usage: viewer [SIGNAL_FILENAME]" << endl;
        cout << "Exiting." << endl;
        exit(-1);
    }

    string filename(argv[1]);
    vector<float> data;
    load_csv(filename, data);
    TimeCourse tc(data);

    RenderWindow window(sf::VideoMode(1000, 200), "Mega Chaos");
    View view;
    view.reset(sf::FloatRect(0, 0, 1000, 200));
    view.setViewport(sf::FloatRect(0.f, 0.f, 1.f, 1.f));

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
            if (event.type == sf::Event::MouseWheelMoved)
            {
                if (event.mouseWheel.delta == 1)
                {
                    view.zoom(0.9);
                }
                else
                    view.zoom(1.1);
            }
        }

        sf::Vertex line[] =
        {
            sf::Vertex(sf::Vector2f(100, 0)),
            sf::Vertex(sf::Vector2f(100, 200))
        };
        window.clear(sf::Color::Black);
        //window.draw(line, 2, sf::Lines);

        window.setView(view);
        window.draw(tc);
        window.display();
    }
}<commit_msg>Zooming @ mouse position (of X axis)<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

#include <SFML/Graphics.hpp>

using namespace std;
using namespace sf;

void load_csv(string & filename, vector<float> & data)
{
    ifstream infile(filename.c_str());
    string s_number, line;
    getline(infile, line);
    stringstream linestream(line);
    while(getline(linestream, s_number, ','))
    {
        data.push_back(atof(s_number.c_str()));
    }
    infile.close();
}

class TimeCourse : public Drawable
{
public:
    vector<float> data;
    TimeCourse(vector<float> & data, Transform& transform)
    : data(data), transform(transform) {}
private:
    Transform& transform;
    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
    {
        VertexArray polyline(sf::LinesStrip, data.size());
        for (int i = 0; i < data.size(); i++)
        {
            Vector2f p = Vector2f(i, data.at(i));
            polyline[i] = transform.transformPoint(p);
        }
        target.draw(polyline, states);
    }
};

Transform getTransform(Vector2f center, Vector2f zoom) {
    Transform transform = Transform::Identity;
    transform = transform.translate(center.x, center.y);
    transform = transform.scale(zoom.x, zoom.y);
    return transform.translate(-center.x, -center.y);
}

int main(int argc, char ** argv)
{
    Vector2f center = Vector2f(500, -1);
    Vector2f zoom = Vector2f(1, 100);
    Transform transform = getTransform(center, zoom);

    if (argc < 2)
    {
        cout << "Usage: viewer [SIGNAL_FILENAME]" << endl;
        cout << "Exiting." << endl;
        exit(-1);
    }

    string filename(argv[1]);
    vector<float> data;
    load_csv(filename, data);
    TimeCourse tc(data, transform);

    RenderWindow window(sf::VideoMode(1000, 200), "Mega Chaos");
    View view;
    view.reset(sf::FloatRect(0, 0, 1000, 200));
    view.setViewport(sf::FloatRect(0.f, 0.f, 1.f, 1.f));

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
            if (event.type == sf::Event::MouseWheelMoved)
            {
                center = Vector2f(event.mouseWheel.x, -1);
                switch (event.mouseWheel.delta)
                {
                case 1:
                    //view.zoom(0.9);
                    zoom.x = zoom.x * 0.9f;
                    transform = getTransform(center, zoom);
                    break;
                case -1:
                    //view.zoom(1.1);
                    zoom.x = zoom.x * 1.1f;
                    transform = getTransform(center, zoom);
                    break;
                }
            }
        }

        sf::Vertex line[] =
        {
            sf::Vertex(sf::Vector2f(100, 0)),
            sf::Vertex(sf::Vector2f(100, 200))
        };
        window.clear(sf::Color::Black);
        //window.draw(line, 2, sf::Lines);

        window.setView(view);
        window.draw(tc);
        window.display();
    }
}<|endoftext|>


<commit_before>/*
 * This file intentionally left empty.
 *
 * The libmaple build system stupidly insists that you really didn't
 * want to build main.cpp from anywhere other than the root directory
 * of libmaple. If you put anything in here, it'll get compiled
 * without your local CXXFLAGS, etc., and you'll get angry. Best just
 * to leave it empty for now.
 */
<commit_msg>main.cpp: Add reference to real-main.cpp.<commit_after>/*
 * This file intentionally left empty. See real-main.cpp.
 *
 * The libmaple build system stupidly insists that you really didn't
 * want to build main.cpp from anywhere other than the root directory
 * of libmaple. If you put anything in here, it'll get compiled
 * without your local CXXFLAGS, etc., and you'll get angry. Best just
 * to leave it empty for now.
 */
<|endoftext|>


<commit_before><commit_msg>compiles now<commit_after><|endoftext|>


<commit_before>#include "Arena.hpp"
#include "Button.hpp"
using namespace HIC;

// Global Engine
I3DEngine* gEngine = nullptr;

// Global Camera
ICamera* gCamera = nullptr;
ICamera* gGameCamera = nullptr;
#ifdef _DEBUG
ICamera* gDebugCamera = nullptr;
#endif

// The game arena
Arena* gArena = nullptr;

///////////////////////////
// Front End Data

IFont* gMainMenuFont = nullptr;

ISprite* gNewGameButtonSprite			= nullptr;
ISprite* gViewHiScoreButtonSprite		= nullptr;
ISprite* gQuitGameButtonSprite			= nullptr;

Button* gContinueButton = nullptr;

const float MENU_BUTTON_WIDTH = 192U;
const float MENU_BUTTON_HEIGHT = 64U;

// One off setup for the entire program.
// Returns true on success, false on failure
bool ProgramSetup()
{
	// Initialise the TL-Engine
	gEngine = New3DEngine(kTLX);
	gEngine->StartWindowed();
	gEngine->SetWindowCaption("Hyper Infinity Carnage");

	// Add default folder for meshes and other media
	gEngine->AddMediaFolder(".\\Media");

	// Initialise the camera
	gGameCamera = gEngine->CreateCamera(kManual, 0.0f, 500.0f, -700.0f);
#ifdef _DEBUG
	gDebugCamera = gEngine->CreateCamera(kFPS, 0.0f, 500.0f, -700.0f);
	gDebugCamera->SetMovementSpeed(200.0f);
	gDebugCamera->SetRotationSpeed(20.0f);
#endif
	gCamera = gGameCamera;

	return true;
}

// One off shutdown of the entire program
// Returns true on success, false on failure
bool ProgramShutdown()
{
	// Shutdown the TL-Engine
	gEngine->Delete();
	gEngine = nullptr;

	// Cleanup pointers
	gCamera = nullptr;
	gGameCamera = nullptr;
#ifdef _DEBUG
	gDebugCamera = nullptr;
#endif

	return true;
}

// Setups the front end menu
// Returns true on success, false on failure
bool FrontEndSetup()
{
	// Load the main menu font
	gMainMenuFont = gEngine->LoadFont("Ubuntu Mono", 72);

	// Load the menu button sprites
	uint32_t halfScreenWidth = gEngine->GetWidth() / 2;

	// TODO: Check if save file exists

	Button::gEngine = gEngine;
	gContinueButton = new Button("Continue_Button.png", XMFLOAT2((float)halfScreenWidth, 250.0f), MENU_BUTTON_WIDTH, MENU_BUTTON_HEIGHT);
	return true;
}

// Updates the front end menu
// Returns true on success, false on failure
bool FrontEndUpdate(float frameTime)
{
	// Calculate the position to draw the title text
	uint32_t screenWidth = gEngine->GetWidth();
	uint32_t textWidth = gMainMenuFont->MeasureTextWidth("Hyper Infinity Carnage");

	// Draw the title
	gMainMenuFont->Draw("Hyper Infinity Carnage", (screenWidth / 2) - (textWidth / 2), 100, kRed);

	return true;
}

// Shutdowns the front end menu
// Returns true on success, false on failure
bool FrontEndShutdown()
{
	// Cleanup the main menu font
	gEngine->RemoveFont(gMainMenuFont);
	gMainMenuFont = nullptr;

	// Cleanup the menu button sprites
	delete gContinueButton;

	return true;
}

// Setups the main game
// Returns true on success, false on failure
bool GameSetup()
{
	// Load the player mesh
	Player::MESH = gEngine->LoadMesh("Player.x");
	Arena::ARENA_MESH = gEngine->LoadMesh("Arena.x");
#ifdef _DEBUG
	CollisionObject::MARKER_MESH = gEngine->LoadMesh("dummy.x");
#endif
	// Load the arena
	gArena = new Arena(gEngine);

	return true;
}

// Updates the main game
// Returns true on success, false on failure
void GameUpdate(float frameTime)
{
	gArena->Update(frameTime);
	gArena->TargetCamera(gGameCamera);
#ifdef _DEBUG
	if (gEngine->KeyHit(Key_Tab))
	{
		//Swap which camera is the gCamera
		if (gGameCamera == gCamera)
		{
			gCamera = gDebugCamera;
		}
		else
		{
			gCamera = gGameCamera;
		}
	}

#endif
}

// Updates the main game
// Returns true on success, false on failure
bool GameShutdown()
{
	// Delete the arena
	delete(gArena);
	gArena = nullptr;

	// Delete the player mesh
	gEngine->RemoveMesh(Player::MESH);
	Player::MESH = nullptr;
	//Delete the arena mesh
	gEngine->RemoveMesh(Arena::ARENA_MESH);
	Arena::ARENA_MESH = nullptr;

#ifdef _DEBUG
	//Delete the collision object mesh
	gEngine->RemoveMesh(CollisionObject::MARKER_MESH);
	CollisionObject::MARKER_MESH = nullptr;
#endif

	return true;
}

// Main entry to the program
int main(int argc, char* argv[])
{
	// Initialise program (TL-Engine, OpenAL etc...). Quit Program on Failure
	if (!ProgramSetup())
	{
		return EXIT_FAILURE;
	}

	// Loop to return to the front-end
	while (true)
	{
		///////////////////////////////////
		// Front End Enter

		// Setup the front end
		if (!FrontEndSetup())
		{
			ProgramShutdown();
			return EXIT_FAILURE;
		}

		bool quitFrontend = false;
		// Update the front-end until the exit key is pressed
		while (!quitFrontend)
		{
			gContinueButton->MouseIsOver();
			if (gEngine->KeyHit(Mouse_LButton))
			{
				if (gContinueButton->MouseIsOver())
				{
					quitFrontend = true;
				}
			}
			if (gEngine->KeyHit(Key_P))
			{
				quitFrontend = true;
			}

			// Update the front end
			float frameTime = gEngine->Timer();
			FrontEndUpdate(frameTime);

			// Exit the program if the exit key is pressed
			if (gEngine->KeyHit(Key_Q) || !gEngine->IsRunning())
			{
				FrontEndShutdown();
				ProgramShutdown();
				return EXIT_SUCCESS;
			}

			// Draw the scene
			gEngine->DrawScene(gCamera);
		}

		if (!FrontEndShutdown())
		{
			ProgramShutdown();
			return EXIT_FAILURE;
		}

		// Front End Exit
		///////////////////////////////////

		// TODO: Loading Screen

		///////////////////////////////////
		// Game Enter

		// Setup the game
		if (!GameSetup())
		{
			ProgramShutdown();
			return EXIT_FAILURE;
		}

		// Continue in game loop until exited
		while (!gEngine->KeyHit(Key_Escape))
		{

			// Update the game
			float frameTime = gEngine->Timer();
			GameUpdate(frameTime);

			// Immediate program exit required (User closed window or pressed Alt-F4)
			if (!gEngine->IsRunning())
			{
				ProgramShutdown();
				return EXIT_SUCCESS;
			}

			// Draw the scene
			gEngine->DrawScene(gCamera);
		}

		if (!GameShutdown())
		{
			ProgramShutdown();
			return EXIT_FAILURE;
		}

		// Game Exit
		///////////////////////////////////
	}

	// Shutdown the program
	ProgramShutdown();

	return EXIT_SUCCESS;
}
<commit_msg>Added some structure to the main file<commit_after>#include "Arena.hpp"
#include "Button.hpp"
using namespace HIC;

// Global Engine
I3DEngine* gEngine = nullptr;

// Global Camera
ICamera* gCamera = nullptr;
ICamera* gGameCamera = nullptr;
#ifdef _DEBUG
ICamera* gDebugCamera = nullptr;
#endif

// The game arena
Arena* gArena = nullptr;

//------------------------
// Front End Data
//------------------------

IFont* gMainMenuFont = nullptr;

ISprite* gNewGameButtonSprite			= nullptr;
ISprite* gViewHiScoreButtonSprite		= nullptr;
ISprite* gQuitGameButtonSprite			= nullptr;

Button* gContinueButton = nullptr;

const float MENU_BUTTON_WIDTH = 192U;
const float MENU_BUTTON_HEIGHT = 64U;

//-------------------------------------------
// Program
//-------------------------------------------

// One off setup for the entire program.
// Returns true on success, false on failure
bool ProgramSetup()
{
	// Initialise the TL-Engine
	gEngine = New3DEngine(kTLX);
	gEngine->StartWindowed();
	gEngine->SetWindowCaption("Hyper Infinity Carnage");

	// Add default folder for meshes and other media
	gEngine->AddMediaFolder(".\\Media");

	// Initialise the camera
	gGameCamera = gEngine->CreateCamera(kManual, 0.0f, 500.0f, -700.0f);
#ifdef _DEBUG
	gDebugCamera = gEngine->CreateCamera(kFPS, 0.0f, 500.0f, -700.0f);
	gDebugCamera->SetMovementSpeed(200.0f);
	gDebugCamera->SetRotationSpeed(20.0f);
#endif
	gCamera = gGameCamera;

	return true;
}

// One off shutdown of the entire program
// Returns true on success, false on failure
bool ProgramShutdown()
{
	// Shutdown the TL-Engine
	gEngine->Delete();
	gEngine = nullptr;

	// Cleanup pointers
	gCamera = nullptr;
	gGameCamera = nullptr;
#ifdef _DEBUG
	gDebugCamera = nullptr;
#endif

	return true;
}

//-------------------------------------------
// Front End
//-------------------------------------------

// Setups the front end menu
// Returns true on success, false on failure
bool FrontEndSetup()
{
	// Load the main menu font
	gMainMenuFont = gEngine->LoadFont("Ubuntu Mono", 72);

	// Load the menu button sprites
	uint32_t halfScreenWidth = gEngine->GetWidth() / 2;

	// TODO: Check if save file exists

	Button::gEngine = gEngine;
	gContinueButton = new Button("Continue_Button.png", XMFLOAT2((float)halfScreenWidth, 250.0f), MENU_BUTTON_WIDTH, MENU_BUTTON_HEIGHT);
	return true;
}

// Updates the front end menu
// Returns true on success, false on failure
bool FrontEndUpdate(float frameTime)
{
	// Calculate the position to draw the title text
	uint32_t screenWidth = gEngine->GetWidth();
	uint32_t textWidth = gMainMenuFont->MeasureTextWidth("Hyper Infinity Carnage");

	// Draw the title
	gMainMenuFont->Draw("Hyper Infinity Carnage", (screenWidth / 2) - (textWidth / 2), 100, kRed);

	return true;
}

// Shutdowns the front end menu
// Returns true on success, false on failure
bool FrontEndShutdown()
{
	// Cleanup the main menu font
	gEngine->RemoveFont(gMainMenuFont);
	gMainMenuFont = nullptr;

	// Cleanup the menu button sprites
	delete gContinueButton;

	return true;
}

//-------------------------------------------
// Main Game
//-------------------------------------------

// Setups the main game
// Returns true on success, false on failure
bool GameSetup()
{
	// Load the player mesh
	Player::MESH = gEngine->LoadMesh("Player.x");
	Arena::ARENA_MESH = gEngine->LoadMesh("Arena.x");
#ifdef _DEBUG
	CollisionObject::MARKER_MESH = gEngine->LoadMesh("dummy.x");
#endif
	// Load the arena
	gArena = new Arena(gEngine);

	return true;
}

// Updates the main game
// Returns true on success, false on failure
void GameUpdate(float frameTime)
{
	gArena->Update(frameTime);
	gArena->TargetCamera(gGameCamera);
#ifdef _DEBUG
	if (gEngine->KeyHit(Key_Tab))
	{
		//Swap which camera is the gCamera
		if (gGameCamera == gCamera)
		{
			gCamera = gDebugCamera;
		}
		else
		{
			gCamera = gGameCamera;
		}
	}

#endif
}

// Updates the main game
// Returns true on success, false on failure
bool GameShutdown()
{
	// Delete the arena
	delete(gArena);
	gArena = nullptr;

	// Delete the player mesh
	gEngine->RemoveMesh(Player::MESH);
	Player::MESH = nullptr;
	//Delete the arena mesh
	gEngine->RemoveMesh(Arena::ARENA_MESH);
	Arena::ARENA_MESH = nullptr;

#ifdef _DEBUG
	//Delete the collision object mesh
	gEngine->RemoveMesh(CollisionObject::MARKER_MESH);
	CollisionObject::MARKER_MESH = nullptr;
#endif

	return true;
}

//-------------------------------------------
// Main
//-------------------------------------------

// Main entry to the program
int main(int argc, char* argv[])
{
	// Initialise program (TL-Engine, OpenAL etc...). Quit Program on Failure
	if (!ProgramSetup())
	{
		return EXIT_FAILURE;
	}

	// Loop to return to the front-end
	while (true)
	{
		///////////////////////////////////
		// Front End Enter

		// Setup the front end
		if (!FrontEndSetup())
		{
			ProgramShutdown();
			return EXIT_FAILURE;
		}

		bool quitFrontend = false;
		// Update the front-end until the exit key is pressed
		while (!quitFrontend)
		{
			gContinueButton->MouseIsOver();
			if (gEngine->KeyHit(Mouse_LButton))
			{
				if (gContinueButton->MouseIsOver())
				{
					quitFrontend = true;
				}
			}
			if (gEngine->KeyHit(Key_P))
			{
				quitFrontend = true;
			}

			// Update the front end
			float frameTime = gEngine->Timer();
			FrontEndUpdate(frameTime);

			// Exit the program if the exit key is pressed
			if (gEngine->KeyHit(Key_Q) || !gEngine->IsRunning())
			{
				FrontEndShutdown();
				ProgramShutdown();
				return EXIT_SUCCESS;
			}

			// Draw the scene
			gEngine->DrawScene(gCamera);
		}

		if (!FrontEndShutdown())
		{
			ProgramShutdown();
			return EXIT_FAILURE;
		}

		// Front End Exit
		///////////////////////////////////

		// TODO: Loading Screen

		///////////////////////////////////
		// Game Enter

		// Setup the game
		if (!GameSetup())
		{
			ProgramShutdown();
			return EXIT_FAILURE;
		}

		// Continue in game loop until exited
		while (!gEngine->KeyHit(Key_Escape))
		{

			// Update the game
			float frameTime = gEngine->Timer();
			GameUpdate(frameTime);

			// Immediate program exit required (User closed window or pressed Alt-F4)
			if (!gEngine->IsRunning())
			{
				ProgramShutdown();
				return EXIT_SUCCESS;
			}

			// Draw the scene
			gEngine->DrawScene(gCamera);
		}

		if (!GameShutdown())
		{
			ProgramShutdown();
			return EXIT_FAILURE;
		}

		// Game Exit
		///////////////////////////////////
	}

	// Shutdown the program
	ProgramShutdown();

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>f7a6a421-2747-11e6-94ee-e0f84713e7b8<commit_msg>Fix that bug where things didn't work but now they should<commit_after>f7b022ca-2747-11e6-bc9d-e0f84713e7b8<|endoftext|>


<commit_before>#include <chrono>
#include <functional>

#include <boost/filesystem.hpp>
#include <boost/optional.hpp>
#include <boost/program_options.hpp>

#include <cereal/types/polymorphic.hpp>
#include <cereal/archives/json.hpp>
#include <cereal/types/vector.hpp>

#include <opencv2/opencv.hpp>

#include "source/tracking/algorithm/BeesBook/BeesBookImgAnalysisTracker/GroundTruthEvaluator.h"

#include "source/tracking/algorithm/BeesBook/BeesBookImgAnalysisTracker/pipeline/Preprocessor.h"
#include "source/tracking/algorithm/BeesBook/BeesBookImgAnalysisTracker/pipeline/Localizer.h"
#include "source/tracking/algorithm/BeesBook/BeesBookImgAnalysisTracker/pipeline/EllipseFitter.h"
#include "source/tracking/algorithm/BeesBook/BeesBookImgAnalysisTracker/pipeline/GridFitter.h"
#include "source/tracking/algorithm/BeesBook/BeesBookImgAnalysisTracker/pipeline/Decoder.h"
#include "source/tracking/algorithm/BeesBook/BeesBookImgAnalysisTracker/pipeline/datastructure/settings.h"
#include "source/tracking/algorithm/BeesBook/BeesBookImgAnalysisTracker/pipeline/datastructure/PipelineGrid.h"
#include "source/tracking/algorithm/BeesBook/BeesBookImgAnalysisTracker/pipeline/datastructure/PipelineGrid.impl.h"

#include "source/tracking/serialization/SerializationData.h"

#include "source/utility/util.h"

namespace {
typedef std::pair<boost::filesystem::path, boost::filesystem::path> path_pair_t;
typedef std::vector<path_pair_t> task_vector_t;
}

class MeasureTimeRAII {
public:
	MeasureTimeRAII()
		: _start(std::chrono::steady_clock::now())
	{}

	~MeasureTimeRAII() {
		const auto end = std::chrono::steady_clock::now();
		const auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(end - _start).count();
		std::stringstream message;
		message << "finished in " << dur << "ms.";
		std::cout << message.str() << std::endl;
	}
private:
	const std::chrono::steady_clock::time_point _start;
};

template <typename Settings>
struct OptimizationResult
{
	const double fscore;
	const double recall;
	const double precision;

	Settings settings;
};

template <typename Settings>
bool operator<(const OptimizationResult<Settings>& a, const OptimizationResult<Settings>& b)
{
	return a.fscore > b.fscore;
}

typedef OptimizationResult<pipeline::settings::localizer_settings_t> LocalizerResult;

boost::optional<std::string> getCommandLineOptions(int argc, char** argv) {
	namespace po = boost::program_options;

	po::options_description desc("Allowed options");
	desc.add_options()
		("help", "produce help message")
		("data", po::value<std::string>(), "data folder")
	;

	po::positional_options_description p;
	p.add("data", 1);

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

	if (!vm.count("data")) {
		std::cout << "Input data folder not specified." << std::endl << std::endl;
		std::cout << desc << std::endl;

		return boost::optional<std::string>();
	}

	return vm["data"].as<std::string>();
}

task_vector_t getTasks(boost::filesystem::path dataFolder) {
	namespace fs = boost::filesystem;

	task_vector_t groundTruthByImagePaths;

	std::set<fs::path> files;
	std::copy(fs::directory_iterator(dataFolder), fs::directory_iterator(), std::inserter(files, files.begin()));

	for (const fs::path entry : files) {
		if (fs::is_regular_file(entry)) {
			if (entry.extension() == ".jpeg") {
				fs::path groundTruthPath(entry);
				groundTruthPath.replace_extension(".tdat");
				if (fs::is_regular_file(groundTruthPath)) {
					groundTruthByImagePaths.emplace_back(entry, groundTruthPath);
				}
			}
		}
	}

	return groundTruthByImagePaths;
}

double getFScore(const double recall, const double precision, const double beta) {
	return ((1 + std::pow(beta, 2)) * ((precision * recall) / (std::pow(beta, 2) * precision + recall)));
}

boost::optional<LocalizerResult> getLocalizerResult(const GroundTruth::LocalizerEvaluationResults& results,
													const pipeline::settings::localizer_settings_t& settings)
{
	static const double beta = 2.;

	const size_t numGroundTruth    = results.taggedGridsOnFrame.size();
	const size_t numTruePositives  = results.truePositives.size();
	const size_t numFalsePositives = results.falsePositives.size();

	const double recall    = numGroundTruth ?
				(static_cast<double>(numTruePositives) / static_cast<double>(numGroundTruth)) : 0.;
	const double precision = (numTruePositives + numFalsePositives) ?
				(static_cast<double>(numTruePositives) / static_cast<double>(numTruePositives + numFalsePositives)) : 0.;

	const double fscore = getFScore(recall, precision, beta);

	if (std::isnan(fscore)) {
		return boost::optional<LocalizerResult>();
	} else {
		LocalizerResult result { fscore, recall, precision, settings };
		return result;
	}
}

class apply_t
{
public:
	apply_t(pipeline::Preprocessor& preprocessor, pipeline::Localizer& localizer, cv::Mat& imgOrig,
			GroundTruthEvaluation& evaluation, std::set<LocalizerResult>& localizerResults)
		: _preprocessor(preprocessor)
		, _localizer(localizer)
		, _imgOrig(imgOrig)
		, _evaluation(evaluation)
		, _localizerResults(localizerResults)
	{}

	inline void operator()() {
		MeasureTimeRAII measure;

		cv::Mat img(_imgOrig.get());

		cv::Mat imgPreprocessed = _preprocessor.get().process(img);
		taglist_t taglist       = _localizer.get().process(std::move(img), std::move(imgPreprocessed));

		_evaluation.get().evaluateLocalizer(0, taglist);

		_localizer.get().getSettings().print(_localizer.get().getSettings().getPTree());

		boost::optional<LocalizerResult> result =
				getLocalizerResult(_evaluation.get().getLocalizerResults(), _localizer.get().getSettings());

		if (result) {
			std::cout << "F-Score: " << result.get().fscore << std::endl << std::endl;
			_localizerResults.get().insert(result.get());
		} else {
			std::cout << "Invalid results" << std::endl << std::endl;
		}

		_evaluation.get().reset();
	}

private:
	std::reference_wrapper<pipeline::Preprocessor> _preprocessor;
	std::reference_wrapper<pipeline::Localizer> _localizer;
	std::reference_wrapper<cv::Mat> _imgOrig;
	std::reference_wrapper<GroundTruthEvaluation> _evaluation;
	std::reference_wrapper<std::set<LocalizerResult>> _localizerResults;
};

template <typename Setter, typename Range, typename RecurseFunctor>
class recurse_t
{
public:
	recurse_t(pipeline::settings::localizer_settings_t& settings,
			pipeline::Localizer& localizer,
			Setter&& setter,
			Range&& range,
			RecurseFunctor&& recurseFunctor)
		: _settings(settings)
		, _localizer(localizer)
		, _setter(std::move(setter))
		, _range(std::move(range))
		, _recurseFunctor(std::move(recurseFunctor))
	{}

	inline void operator()() {
		for (const auto elem : _range) {
			_setter(elem);
			_localizer.get().loadSettings(_settings.get());

			_recurseFunctor();
		}
	}

private:
	std::reference_wrapper<pipeline::settings::localizer_settings_t> _settings;
	std::reference_wrapper<pipeline::Localizer> _localizer;
	Setter _setter;
	Range _range;
	RecurseFunctor _recurseFunctor;
};

template <typename T, typename RecurseFunctor>
recurse_t<std::function<void(T)>, std::vector<T>, RecurseFunctor>
		getRecurseFunctor(std::vector<T>&& range, std::string const& param, RecurseFunctor&& recurseFunctor,
							pipeline::settings::localizer_settings_t& settings,
							pipeline::Localizer::Localizer& localizer)
{
	std::function<void(T)> paramSetter = std::bind(&pipeline::settings::localizer_settings_t::_setValue<T>, &settings,
								  param, std::placeholders::_1);
	recurse_t<std::function<void(T)>, std::vector<T>, RecurseFunctor>
			functor(settings, localizer, std::move(paramSetter), std::move(range), std::move(recurseFunctor));

	return functor;
}

void optimizeParameters(const path_pair_t& task) {
	cv::Mat imgOrig = cv::imread(task.first.string());

	Serialization::Data data;
	{
		std::ifstream is(task.second.string());
		cereal::JSONInputArchive ar(is);

		// load serialized data into member .data
		ar(data);
	}

	GroundTruthEvaluation evaluation(std::move(data));
	pipeline::Preprocessor preprocessor;
	pipeline::Localizer localizer;

	pipeline::settings::preprocessor_settings_t preprocessorSettings;
	pipeline::settings::localizer_settings_t localizerSettings;

	std::set<LocalizerResult> localizerResults;

	namespace settingspreprocessor = pipeline::settings::Preprocessor::Params;
	preprocessorSettings._setValue(settingspreprocessor::COMB_ENABLED, true);
	preprocessorSettings._setValue(settingspreprocessor::HONEY_ENABLED, true);

	apply_t applicator(preprocessor, localizer, imgOrig, evaluation, localizerResults);

	auto binaryThresholdFunctor = getRecurseFunctor(util::linspace<int>(25, 30, 2), pipeline::settings::Localizer::Params::BINARY_THRESHOLD,
													std::move(applicator), localizerSettings, localizer);

	auto numIterationsFunctor = getRecurseFunctor(util::linspace<unsigned int>(3, 5, 2), pipeline::settings::Localizer::Params::FIRST_DILATION_NUM_ITERATIONS,
													std::move(binaryThresholdFunctor), localizerSettings, localizer);

	auto firstDilationSizeFunctor = getRecurseFunctor(util::linspace<unsigned int>(2, 3, 2), pipeline::settings::Localizer::Params::FIRST_DILATION_SIZE,
													std::move(numIterationsFunctor), localizerSettings, localizer);

	auto erosionSizeFunctor = getRecurseFunctor(util::linspace<unsigned int>(23, 26, 2), pipeline::settings::Localizer::Params::EROSION_SIZE,
													std::move(firstDilationSizeFunctor), localizerSettings, localizer);

	auto secondDilationSizeFunctor = getRecurseFunctor(util::linspace<unsigned int>(2, 3, 2), pipeline::settings::Localizer::Params::SECOND_DILATION_SIZE,
													std::move(erosionSizeFunctor), localizerSettings, localizer);

	auto maxTagSizeFunctor = getRecurseFunctor(util::linspace<unsigned int>(200, 300, 2), pipeline::settings::Localizer::Params::MAX_TAG_SIZE,
													std::move(secondDilationSizeFunctor), localizerSettings, localizer);

	auto minBoundingBoxSizeFunctor = getRecurseFunctor(util::linspace<int>(300, 400, 2), pipeline::settings::Localizer::Params::MIN_BOUNDING_BOX_SIZE,
													std::move(maxTagSizeFunctor), localizerSettings, localizer);

	minBoundingBoxSizeFunctor();

	if (!localizerResults.empty()) {
		LocalizerResult bestResult = *localizerResults.begin();

		std::cout << "Best Result: " << std::endl;
		bestResult.settings.print(bestResult.settings.getPTree());
		std::cout << "Recall: " << bestResult.recall << std::endl;
		std::cout << "Precision: " << bestResult.precision << std::endl;
		std::cout << "F-Score: " << bestResult.fscore << std::endl;
	}

////		static const int BINARY_THRESHOLD = 29;
////static const unsigned int FIRST_DILATION_NUM_ITERATIONS = 4;
////static const unsigned int FIRST_DILATION_SIZE = 2;
////static const unsigned int EROSION_SIZE = 25;
////static const unsigned int SECOND_DILATION_SIZE = 2;
////static const unsigned int MAX_TAG_SIZE = 250;
////static const int MIN_BOUNDING_BOX_SIZE = 100;

//		for (int binary_threshold = 0; binary_threshold < 100; ++binary_threshold) {

//			MeasureTimeRAII measure;

//			cv::Mat img(imgOrig);

//			pipeline::settings::preprocessor_settings_t preprocessorSettings;
//			pipeline::settings::localizer_settings_t localizerSettings;

//			preprocessorSettings._setValue(settingspreprocessor::COMB_ENABLED, true);
//			preprocessorSettings._setValue(settingspreprocessor::HONEY_ENABLED, true);

////			localizerSettings._setValue(pipeline::settings::Localizer::Params::BINARY_THRESHOLD, binary_threshold);

//			auto binThrSetter = std::bind(&pipeline::settings::localizer_settings_t::_setValue<int>, &localizerSettings,
//										  pipeline::settings::Localizer::Params::BINARY_THRESHOLD, std::placeholders::_1);
//			const auto range = util::linspace(1, 100, 100);
//			binThrSetter(binary_threshold);

//			pipeline::Preprocessor preprocessor;
//			pipeline::Localizer localizer;

//			preprocessor.setOptions(preprocessorSettings);
//			localizer.loadSettings(localizerSettings);

//			cv::Mat imgOut = preprocessor.process(img);
//			taglist = localizer.process(std::move(img), std::move(imgOut));

//			evaluation.evaluateLocalizer(0, taglist);

//			std::cout << getLocalizerScore(evaluation.getLocalizerResults());

//			evaluation.reset();
//		}
//	}
}

int main(int argc, char** argv) {
	const boost::optional<std::string> dataFolder = getCommandLineOptions(argc, argv);

	if (!dataFolder) return EXIT_FAILURE;

	if (!boost::filesystem::is_directory(dataFolder.get())) {
		std::cout << "Invalid input data path." << std::endl << std::endl;

		return EXIT_FAILURE;
	}

	task_vector_t tasks = getTasks(dataFolder.get());

	for (const path_pair_t& task : tasks) {
		optimizeParameters(task);
	}

	return EXIT_SUCCESS;
}
<commit_msg>fix includes/namespaces<commit_after>#include <chrono>
#include <functional>

#include <boost/filesystem.hpp>
#include <boost/optional.hpp>
#include <boost/program_options.hpp>

#include <cereal/types/polymorphic.hpp>
#include <cereal/archives/json.hpp>
#include <cereal/types/vector.hpp>

#include <opencv2/opencv.hpp>

#include "source/tracking/algorithm/BeesBook/ImgAnalysisTracker/GroundTruthEvaluator.h"

#include "source/tracking/algorithm/BeesBook/ImgAnalysisTracker/pipeline/Preprocessor.h"
#include "source/tracking/algorithm/BeesBook/ImgAnalysisTracker/pipeline/Localizer.h"
#include "source/tracking/algorithm/BeesBook/ImgAnalysisTracker/pipeline/EllipseFitter.h"
#include "source/tracking/algorithm/BeesBook/ImgAnalysisTracker/pipeline/GridFitter.h"
#include "source/tracking/algorithm/BeesBook/ImgAnalysisTracker/pipeline/Decoder.h"
#include "source/tracking/algorithm/BeesBook/ImgAnalysisTracker/pipeline/util/Util.h"
#include "source/tracking/algorithm/BeesBook/ImgAnalysisTracker/pipeline/datastructure/settings.h"
#include "source/tracking/algorithm/BeesBook/ImgAnalysisTracker/pipeline/datastructure/PipelineGrid.h"
#include "source/tracking/algorithm/BeesBook/ImgAnalysisTracker/pipeline/datastructure/PipelineGrid.impl.h"

#include "source/tracking/serialization/SerializationData.h"

namespace {
typedef std::pair<boost::filesystem::path, boost::filesystem::path> path_pair_t;
typedef std::vector<path_pair_t> task_vector_t;
}

class MeasureTimeRAII {
public:
	MeasureTimeRAII()
		: _start(std::chrono::steady_clock::now())
	{}

	~MeasureTimeRAII() {
		const auto end = std::chrono::steady_clock::now();
		const auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(end - _start).count();
		std::stringstream message;
		message << "finished in " << dur << "ms.";
		std::cout << message.str() << std::endl;
	}
private:
	const std::chrono::steady_clock::time_point _start;
};

template <typename Settings>
struct OptimizationResult
{
	const double fscore;
	const double recall;
	const double precision;

	Settings settings;
};

template <typename Settings>
bool operator<(const OptimizationResult<Settings>& a, const OptimizationResult<Settings>& b)
{
	return a.fscore > b.fscore;
}

typedef OptimizationResult<pipeline::settings::localizer_settings_t> LocalizerResult;

boost::optional<std::string> getCommandLineOptions(int argc, char** argv) {
	namespace po = boost::program_options;

	po::options_description desc("Allowed options");
	desc.add_options()
		("help", "produce help message")
		("data", po::value<std::string>(), "data folder")
	;

	po::positional_options_description p;
	p.add("data", 1);

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

	if (!vm.count("data")) {
		std::cout << "Input data folder not specified." << std::endl << std::endl;
		std::cout << desc << std::endl;

		return boost::optional<std::string>();
	}

	return vm["data"].as<std::string>();
}

task_vector_t getTasks(boost::filesystem::path dataFolder) {
	namespace fs = boost::filesystem;

	task_vector_t groundTruthByImagePaths;

	std::set<fs::path> files;
	std::copy(fs::directory_iterator(dataFolder), fs::directory_iterator(), std::inserter(files, files.begin()));

	for (const fs::path entry : files) {
		if (fs::is_regular_file(entry)) {
			if (entry.extension() == ".jpeg") {
				fs::path groundTruthPath(entry);
				groundTruthPath.replace_extension(".tdat");
				if (fs::is_regular_file(groundTruthPath)) {
					groundTruthByImagePaths.emplace_back(entry, groundTruthPath);
				}
			}
		}
	}

	return groundTruthByImagePaths;
}

double getFScore(const double recall, const double precision, const double beta) {
	return ((1 + std::pow(beta, 2)) * ((precision * recall) / (std::pow(beta, 2) * precision + recall)));
}

boost::optional<LocalizerResult> getLocalizerResult(const GroundTruth::LocalizerEvaluationResults& results,
													const pipeline::settings::localizer_settings_t& settings)
{
	static const double beta = 2.;

	const size_t numGroundTruth    = results.taggedGridsOnFrame.size();
	const size_t numTruePositives  = results.truePositives.size();
	const size_t numFalsePositives = results.falsePositives.size();

	const double recall    = numGroundTruth ?
				(static_cast<double>(numTruePositives) / static_cast<double>(numGroundTruth)) : 0.;
	const double precision = (numTruePositives + numFalsePositives) ?
				(static_cast<double>(numTruePositives) / static_cast<double>(numTruePositives + numFalsePositives)) : 0.;

	const double fscore = getFScore(recall, precision, beta);

	if (std::isnan(fscore)) {
		return boost::optional<LocalizerResult>();
	} else {
		LocalizerResult result { fscore, recall, precision, settings };
		return result;
	}
}

class apply_t
{
public:
	apply_t(pipeline::Preprocessor& preprocessor, pipeline::Localizer& localizer, cv::Mat& imgOrig,
			GroundTruthEvaluation& evaluation, std::set<LocalizerResult>& localizerResults)
		: _preprocessor(preprocessor)
		, _localizer(localizer)
		, _imgOrig(imgOrig)
		, _evaluation(evaluation)
		, _localizerResults(localizerResults)
	{}

	inline void operator()() {
		MeasureTimeRAII measure;

		cv::Mat img(_imgOrig.get());

		cv::Mat imgPreprocessed = _preprocessor.get().process(img);
		taglist_t taglist       = _localizer.get().process(std::move(img), std::move(imgPreprocessed));

		_evaluation.get().evaluateLocalizer(0, taglist);

		// TODO
		//_localizer.get().getSettings().print(_localizer.get().getSettings().getPTree());

		boost::optional<LocalizerResult> result =
				getLocalizerResult(_evaluation.get().getLocalizerResults(), _localizer.get().getSettings());

		if (result) {
			std::cout << "F-Score: " << result.get().fscore << std::endl << std::endl;
			_localizerResults.get().insert(result.get());
		} else {
			std::cout << "Invalid results" << std::endl << std::endl;
		}

		_evaluation.get().reset();
	}

private:
	std::reference_wrapper<pipeline::Preprocessor> _preprocessor;
	std::reference_wrapper<pipeline::Localizer> _localizer;
	std::reference_wrapper<cv::Mat> _imgOrig;
	std::reference_wrapper<GroundTruthEvaluation> _evaluation;
	std::reference_wrapper<std::set<LocalizerResult>> _localizerResults;
};

template <typename Setter, typename Range, typename RecurseFunctor>
class recurse_t
{
public:
	recurse_t(pipeline::settings::localizer_settings_t& settings,
			pipeline::Localizer& localizer,
			Setter&& setter,
			Range&& range,
			RecurseFunctor&& recurseFunctor)
		: _settings(settings)
		, _localizer(localizer)
		, _setter(std::move(setter))
		, _range(std::move(range))
		, _recurseFunctor(std::move(recurseFunctor))
	{}

	inline void operator()() {
		for (const auto elem : _range) {
			_setter(elem);
			_localizer.get().loadSettings(_settings.get());

			_recurseFunctor();
		}
	}

private:
	std::reference_wrapper<pipeline::settings::localizer_settings_t> _settings;
	std::reference_wrapper<pipeline::Localizer> _localizer;
	Setter _setter;
	Range _range;
	RecurseFunctor _recurseFunctor;
};

template <typename T, typename RecurseFunctor>
recurse_t<std::function<void(T)>, std::vector<T>, RecurseFunctor>
		getRecurseFunctor(std::vector<T>&& range, std::string const& param, RecurseFunctor&& recurseFunctor,
							pipeline::settings::localizer_settings_t& settings,
							pipeline::Localizer& localizer)
{
	std::function<void(T)> paramSetter = std::bind(&pipeline::settings::localizer_settings_t::_setValue<T>, &settings,
								  param, std::placeholders::_1);
	recurse_t<std::function<void(T)>, std::vector<T>, RecurseFunctor>
			functor(settings, localizer, std::move(paramSetter), std::move(range), std::move(recurseFunctor));

	return functor;
}

void optimizeParameters(const path_pair_t& task) {
	cv::Mat imgOrig = cv::imread(task.first.string());

	Serialization::Data data;
	{
		std::ifstream is(task.second.string());
		cereal::JSONInputArchive ar(is);

		// load serialized data into member .data
		ar(data);
	}

	GroundTruthEvaluation evaluation(std::move(data));
	pipeline::Preprocessor preprocessor;
	pipeline::Localizer localizer;

	pipeline::settings::preprocessor_settings_t preprocessorSettings;
	pipeline::settings::localizer_settings_t localizerSettings;

	std::set<LocalizerResult> localizerResults;

	namespace settingspreprocessor = pipeline::settings::Preprocessor::Params;
	preprocessorSettings._setValue(settingspreprocessor::COMB_ENABLED, true);
	preprocessorSettings._setValue(settingspreprocessor::HONEY_ENABLED, true);

	apply_t applicator(preprocessor, localizer, imgOrig, evaluation, localizerResults);

	auto binaryThresholdFunctor = getRecurseFunctor(Util::linspace<int>(25, 30, 2), pipeline::settings::Localizer::Params::BINARY_THRESHOLD,
													std::move(applicator), localizerSettings, localizer);

	auto numIterationsFunctor = getRecurseFunctor(Util::linspace<unsigned int>(3, 5, 2), pipeline::settings::Localizer::Params::FIRST_DILATION_NUM_ITERATIONS,
													std::move(binaryThresholdFunctor), localizerSettings, localizer);

	auto firstDilationSizeFunctor = getRecurseFunctor(Util::linspace<unsigned int>(2, 3, 2), pipeline::settings::Localizer::Params::FIRST_DILATION_SIZE,
													std::move(numIterationsFunctor), localizerSettings, localizer);

	auto erosionSizeFunctor = getRecurseFunctor(Util::linspace<unsigned int>(23, 26, 2), pipeline::settings::Localizer::Params::EROSION_SIZE,
													std::move(firstDilationSizeFunctor), localizerSettings, localizer);

	auto secondDilationSizeFunctor = getRecurseFunctor(Util::linspace<unsigned int>(2, 3, 2), pipeline::settings::Localizer::Params::SECOND_DILATION_SIZE,
													std::move(erosionSizeFunctor), localizerSettings, localizer);

	auto maxTagSizeFunctor = getRecurseFunctor(Util::linspace<unsigned int>(200, 300, 2), pipeline::settings::Localizer::Params::MAX_TAG_SIZE,
													std::move(secondDilationSizeFunctor), localizerSettings, localizer);

	auto minBoundingBoxSizeFunctor = getRecurseFunctor(Util::linspace<int>(300, 400, 2), pipeline::settings::Localizer::Params::MIN_BOUNDING_BOX_SIZE,
													std::move(maxTagSizeFunctor), localizerSettings, localizer);

	minBoundingBoxSizeFunctor();

	if (!localizerResults.empty()) {
		LocalizerResult bestResult = *localizerResults.begin();

		std::cout << "Best Result: " << std::endl;
		//bestResult.settings.print(bestResult.settings.getPTree());
		std::cout << "Recall: " << bestResult.recall << std::endl;
		std::cout << "Precision: " << bestResult.precision << std::endl;
		std::cout << "F-Score: " << bestResult.fscore << std::endl;
	}
}

int main(int argc, char** argv) {
	const boost::optional<std::string> dataFolder = getCommandLineOptions(argc, argv);

	if (!dataFolder) return EXIT_FAILURE;

	if (!boost::filesystem::is_directory(dataFolder.get())) {
		std::cout << "Invalid input data path." << std::endl << std::endl;

		return EXIT_FAILURE;
	}

	task_vector_t tasks = getTasks(dataFolder.get());

	for (const path_pair_t& task : tasks) {
		optimizeParameters(task);
	}

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>d30666e6-ad5b-11e7-8741-ac87a332f658<commit_msg>add file<commit_after>d3822ae1-ad5b-11e7-9dfc-ac87a332f658<|endoftext|>


<commit_before>//Simple Arduino game

#include <LiquidCrystal.h>
#include <stdlib.h> //RNG purposes
#include <time.h>   //RNG purposes

//Alien definition
byte Alien[8] = {
    B01110,
    B10001,
    B11111,
    B10101,
    B01010,
    B10001,
    B01010,
    B00000
};

struct Joystick
{
	const int Switch_PIN = 8;
	const int X_PIN = 0;
	const int Y_PIN = 1;
};

struct LCD
{
	const int RS = 12;
	const int Enable = 11;
	const int D4 = 5;
	const int D5 = 4;
	const int D6 = 3;
	const int D7 = 2;

	const int columns = 16;
	const int rows = 2;
};

struct Game
{
	bool gameStarted = false;
	bool gameFinished = false;
	int startScreenCount = 0;
	int score = 0;
	int distance = 0;
};

struct Player
{
	int lifes = 3;
	int X = 7;
	int Y = 1;
};

struct Enemy
{
	int character = 183;
	int X = 0;
	int Y = 0;
};

//Objects
Joystick stick;
LCD lcdPins;
LiquidCrystal LCD(lcdPins.RS, lcdPins.Enable, lcdPins.D4, lcdPins.D5, lcdPins.D6, lcdPins.D7);

Game game1;
Player player1;
Enemy enemy1;

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

	pinMode(stick.Switch_PIN, INPUT);
	digitalWrite(stick.Switch_PIN, HIGH);

	LCD.begin(lcdPins.columns, lcdPins.rows);

	printStartScreen();

}

void loop()
{
	if (!game1.gameStarted)
	{
		if (!digitalRead(stick.Switch_PIN))
		{//Start game
			delay(500);
			game1.gameStarted = true;
			printPlayer();
			createAlien();
			printAlien();

		}
		else
		{//Game Menu
			printStartScreen();
		}
	}
	else
	{//Game running
		if (!digitalRead(stick.Switch_PIN))
		{//End game
			printScoreScreen();
			delay(5000);
			game1.gameFinished = true;
			game1.gameStarted = false;
			Serial.println("Partida finalizada.");
		}
		else
		{//Game core
			movePlayer();
			checkCollision();
		}
	}

	//Debug
	Serial.print("Joystick lectures: X->");
    Serial.print(X_Axys());
	Serial.print(" Y->");
	Serial.print(analogRead(stick.Y_PIN));
	Serial.print(" Switch->");
	Serial.print(digitalRead(stick.Switch_PIN));
	Serial.print(" Player_X->");
	Serial.print(player1.X);
	Serial.print(" Player_Y->");
	Serial.println(player1.Y);

	if (game1.gameStarted)
	{
		delay(16);
	}
	else
	{
		delay(100);
	}
}

int X_Axys()
{
	return analogRead(stick.X_PIN);
}

int Y_Axys()
{
	return analogRead(stick.Y_PIN);
}

void printPlayer()
{
	LCD.clear();
	LCD.setCursor(player1.X, player1.Y);
	LCD.write(255);
}

void movePlayer()
{
	if (X_Axys() > 600)
	{
		//Move right
		if (player1.X + 1 <= lcdPins.columns - 1)
		{
			player1.X += 1;
			printPlayer();
			printAlien();
			game1.distance += 1;
		}
	}
	else if (X_Axys() < 400)
	{
		//Move left
		if (player1.X - 1 >= 0)
		{
			player1.X -= 1;
			printPlayer();
			printAlien();
			game1.distance += 1;
		}
	}

	if (Y_Axys() > 600)
	{
		//Move Down
		if (player1.Y == 1)
		{
			player1.Y -= 1;
			printPlayer();
			printAlien();
			game1.distance += 1;
		}

	}
	else if (Y_Axys() < 400)
	{
		//Move UP
		if (player1.Y == 0)
		{
			player1.Y += 1;
			printPlayer();
			printAlien();
			game1.distance += 1;
		}
	}
}

void createAlien()
{
	srand (time(NULL));

	int X = random(0, 16);
	int Y = random(0, 2);

	enemy1.X = X;
	enemy1.Y = Y;

	Serial.println(X);
	Serial.println(Y);
}

void printAlien()
{
	LCD.setCursor(enemy1.X, enemy1.Y);
	LCD.write(enemy1.character);
}

void checkCollision()
{
	if ((player1.X == enemy1.X) && (player1.Y == enemy1.Y))
	{
		printPlayer();
		createAlien();
		printAlien();
		Serial.print("Kill!");

		game1.score += 1;
	}
}

void printStartScreen()
{
	LCD.setCursor(0,0);
	LCD.print(" A simple Game");

	Serial.println(game1.startScreenCount);
	game1.startScreenCount += 50;
	if (game1.startScreenCount > 1000)
	{
		game1.startScreenCount = 0;
	}
	LCD.setCursor(0,1);

	if (game1.startScreenCount < 750)
	{

		LCD.print("Click to start..");
	}
	else
	{
		LCD.print("                ");
	}
}

void printScoreScreen()
{
	LCD.clear();

	LCD.setCursor(0,0);
	LCD.print("Kills: ");
	LCD.setCursor(7, 0);
	LCD.print(game1.score);

	LCD.setCursor(0,1);
	LCD.print("Km: ");
	LCD.setCursor(4, 1);
	LCD.print(game1.distance);
}<commit_msg>Update main.cpp<commit_after>//Simple Arduino game

#include <LiquidCrystal.h>
#include <stdlib.h> //RNG purposes
#include <time.h>   //RNG purposes

struct Joystick
{
	const int Switch_PIN = 8;
	const int X_PIN = 0;
	const int Y_PIN = 1;
};

struct LCD
{
	const int RS = 12;
	const int Enable = 11;
	const int D4 = 5;
	const int D5 = 4;
	const int D6 = 3;
	const int D7 = 2;

	const int columns = 16;
	const int rows = 2;
};

struct Game
{
	bool gameStarted = false;
	bool gameFinished = false;
	int startScreenCount = 0;
	int score = 0;
	int distance = 0;
};

struct Player
{
	int lifes = 3;
	int X = 7;
	int Y = 1;
};

struct Enemy
{
	int character = 183;
	int X = 0;
	int Y = 0;
};

//Objects
Joystick stick;
LCD lcdPins;
LiquidCrystal LCD(lcdPins.RS, lcdPins.Enable, lcdPins.D4, lcdPins.D5, lcdPins.D6, lcdPins.D7);

Game game1;
Player player1;
Enemy enemy1;

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

	pinMode(stick.Switch_PIN, INPUT);
	digitalWrite(stick.Switch_PIN, HIGH);

	LCD.begin(lcdPins.columns, lcdPins.rows);

	printStartScreen();

}

void loop()
{
	if (!game1.gameStarted)
	{
		if (!digitalRead(stick.Switch_PIN))
		{//Start game
			delay(500);
			game1.gameStarted = true;
			printPlayer();
			createAlien();
			printAlien();

		}
		else
		{//Game Menu
			printStartScreen();
		}
	}
	else
	{//Game running
		if (!digitalRead(stick.Switch_PIN))
		{//End game
			printScoreScreen();
			delay(5000);
			game1.gameFinished = true;
			game1.gameStarted = false;
			Serial.println("Partida finalizada.");
		}
		else
		{//Game core
			movePlayer();
			checkCollision();
		}
	}

	//Debug
	Serial.print("Joystick lectures: X->");
    Serial.print(X_Axys());
	Serial.print(" Y->");
	Serial.print(analogRead(stick.Y_PIN));
	Serial.print(" Switch->");
	Serial.print(digitalRead(stick.Switch_PIN));
	Serial.print(" Player_X->");
	Serial.print(player1.X);
	Serial.print(" Player_Y->");
	Serial.println(player1.Y);

	if (game1.gameStarted)
	{
		delay(16);
	}
	else
	{
		delay(100);
	}
}

int X_Axys()
{
	return analogRead(stick.X_PIN);
}

int Y_Axys()
{
	return analogRead(stick.Y_PIN);
}

void printPlayer()
{
	LCD.clear();
	LCD.setCursor(player1.X, player1.Y);
	LCD.write(255);
}

void movePlayer()
{
	if (X_Axys() > 600)
	{
		//Move right
		if (player1.X + 1 <= lcdPins.columns - 1)
		{
			player1.X += 1;
			printPlayer();
			printAlien();
			game1.distance += 1;
		}
	}
	else if (X_Axys() < 400)
	{
		//Move left
		if (player1.X - 1 >= 0)
		{
			player1.X -= 1;
			printPlayer();
			printAlien();
			game1.distance += 1;
		}
	}

	if (Y_Axys() > 600)
	{
		//Move Down
		if (player1.Y == 1)
		{
			player1.Y -= 1;
			printPlayer();
			printAlien();
			game1.distance += 1;
		}

	}
	else if (Y_Axys() < 400)
	{
		//Move UP
		if (player1.Y == 0)
		{
			player1.Y += 1;
			printPlayer();
			printAlien();
			game1.distance += 1;
		}
	}
}

void createAlien()
{
	srand (time(NULL));

	int X = random(0, 16);
	int Y = random(0, 2);

	enemy1.X = X;
	enemy1.Y = Y;

	Serial.println(X);
	Serial.println(Y);
}

void printAlien()
{
	LCD.setCursor(enemy1.X, enemy1.Y);
	LCD.write(enemy1.character);
}

void checkCollision()
{
	if ((player1.X == enemy1.X) && (player1.Y == enemy1.Y))
	{
		printPlayer();
		createAlien();
		printAlien();
		Serial.print("Kill!");

		game1.score += 1;
	}
}

void printStartScreen()
{
	LCD.setCursor(0,0);
	LCD.print(" A simple Game");

	Serial.println(game1.startScreenCount);
	game1.startScreenCount += 50;
	if (game1.startScreenCount > 1000)
	{
		game1.startScreenCount = 0;
	}
	LCD.setCursor(0,1);

	if (game1.startScreenCount < 750)
	{

		LCD.print("Click to start..");
	}
	else
	{
		LCD.print("                ");
	}
}

void printScoreScreen()
{
	LCD.clear();

	LCD.setCursor(0,0);
	LCD.print("Kills: ");
	LCD.setCursor(7, 0);
	LCD.print(game1.score);

	LCD.setCursor(0,1);
	LCD.print("Km: ");
	LCD.setCursor(4, 1);
	LCD.print(game1.distance);
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////
// main.cpp -- Test Main
// Date: Wed Nov 27 23:07:19 2013
///////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <assert.h>

#include <sys/stat.h>

#include "glue.hpp"
#include "utils.hpp"
#include "ansi-c-yacc.hpp"
#include "comp.hpp"

#include <iostream>
#include <istream>

int
main(int argc,char **argv) {
	std::string platform, version, machine;
	int ltoken;

	platform = uts_platform();
	version = uts_version();
	machine = uts_machine();

	printf("OS: %s, machine %s\n",
		platform.c_str(),
		machine.c_str());
	printf("Version: %s\n",version.c_str());

	loadconfig();

	system("rm -fr ./staging");
	mkdir("./staging",0777);
	system("cp 0005.ads ./staging/.");
	system("cp 0005.adb ./staging/.");
	system("cp 0060.ads ./staging/.");
	system("cp 9999.ads ./staging/.");
	system("cp 9999.adb ./staging/.");

	comp_macros();
	comp_types();
	comp_systypes();
//	comp_funcs();

	emit_basic_types();
	emit_sys_types();
	emit_macros();
	emit_section2();

	system("cat ./staging/????.ads >posix.ads");
	system("cat ./staging/????.adb >posix.adb");

exit(0);
	set_input(stdin);

	while ( (ltoken = yylex()) != 0 ) {
		unsigned lno = lex_lineno();
		int id = lex_token();
		std::string& token = revsym[id];

		printf("%06u : %3d '%s' (%d)\n",
			lno,
			ltoken,
			token.c_str(),
			id);
	}
}

// End main.cpp
<commit_msg>Cleaned up display of Platform etc.<commit_after>//////////////////////////////////////////////////////////////////////
// main.cpp -- Test Main
// Date: Wed Nov 27 23:07:19 2013
///////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <assert.h>

#include <sys/stat.h>

#include "glue.hpp"
#include "utils.hpp"
#include "ansi-c-yacc.hpp"
#include "comp.hpp"

#include <iostream>
#include <istream>

int
main(int argc,char **argv) {
	std::string platform, version, machine;
	int ltoken;

	platform = uts_platform();
	version = uts_version();
	machine = uts_machine();

	std::cout << "Platform: " << platform << "\n"
		<< "Machine:  " << machine << "\n"
		<< "Version:  " << version << "\n";

	loadconfig();

	system("rm -fr ./staging");
	mkdir("./staging",0777);
	system("cp 0005.ads ./staging/.");
	system("cp 0005.adb ./staging/.");
	system("cp 0060.ads ./staging/.");
	system("cp 9999.ads ./staging/.");
	system("cp 9999.adb ./staging/.");

	comp_macros();
	comp_types();
	comp_systypes();
//	comp_funcs();

	emit_basic_types();
	emit_sys_types();
	emit_macros();
	emit_section2();

	system("cat ./staging/????.ads >posix.ads");
	system("cat ./staging/????.adb >posix.adb");

exit(0);
	set_input(stdin);

	while ( (ltoken = yylex()) != 0 ) {
		unsigned lno = lex_lineno();
		int id = lex_token();
		std::string& token = revsym[id];

		printf("%06u : %3d '%s' (%d)\n",
			lno,
			ltoken,
			token.c_str(),
			id);
	}
}

// End main.cpp
<|endoftext|>


<commit_before>72f4b1d1-4b02-11e5-b685-28cfe9171a43<commit_msg>Initial commit.13<commit_after>73017833-4b02-11e5-b16f-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/un.h>

#include "CReader.h"

#define SOCK_PATH "octomap"

using namespace std;

int main (int argv, char ** argc)
{
	//cout << "Hier";
	CReader *reader = new CReader();
	int s, s2, t, len;
	int ret = 0;
	int run = 1;
	char str[100];
	stringstream buff(ios::in|ios::out);
	struct sockaddr_un local, remote;

	try {
		if (!reader->init()) {
			exit(1);
		}
	}
	catch (...) {
		cout << "Error!" << endl;
	}

	// UDS -------------------------------------------------------------
	//start server

	if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1 ) {
		perror("socket");
		exit(1);
	}

	local.sun_family = AF_UNIX;
	strcpy(local.sun_path, SOCK_PATH);
	unlink(local.sun_path);
	len = strlen(local.sun_path) + sizeof(local.sun_family);

	if (bind(s, (struct sockaddr *)&local, len) == -1) {
		perror("bind");
		exit(1);
	}

	if (listen(s, 5) == -1) {
		perror("listen");
		exit(1);
	}

	while (run) {
		int done, n;
		printf("Waiting for a connection...\n");
		t = sizeof(remote);
		if ((s2 = accept(s, (struct sockaddr *)&remote, (socklen_t*)&t)) == -1) {
			perror("accept");
			exit(1);
		}

		printf("Connected.\n");

		done = 0;

		do {
			// receive data from client
			n = recv(s2, str, 100, 0);
			str[n] = '\0';
			cout << str << endl;
			if (n <= 0) {
				if (n < 0)
					perror("recv");

				done = 1;
			} else {

				if (strncmp(str,"GET_OCTOMAP",n) == 0) {
					done = 0;
				} else if (strncmp(str,"QUIT",n) == 0) {
					//reader->writeDataBT(); // write octree to bt-file
					run = 0; // stop main loop
					done = 1;
				}
			}

			// send data to client
			if (!done) {
				//strcpy(str,"RESPONSE");
				//str[8] = '\0';

				ret = reader->getOctomap(buff);
				if (ret == 0)
					buff << "NO_DATA";

				//cout << "RESPONSE:" << buff.str().c_str() << endl;
				//cout << buff.str() << endl;
				if (send(s2, buff.str().c_str(), strlen(buff.str().c_str()), 0) < 0) {
					perror("send");
					done = 1;
				}
				done = 1;
			}
		} while (!done);

		close(s2);
	}

	if (reader != NULL)
		delete reader;
	return 0;
}
<commit_msg>use binary buffer for UDS data transfer<commit_after>#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/un.h>

#include "CReader.h"

#define SOCK_PATH "octomap"

using namespace std;

int main (int argv, char ** argc)
{
	//cout << "Hier";
	CReader *reader = new CReader();
	int s, s2, t, len;
	int ret = 0;
	int run = 1;
	char str[100];
	char buff[2048];
	struct sockaddr_un local, remote;

	try {
		if (!reader->init()) {
			exit(1);
		}
	}
	catch (...) {
		cout << "Error!" << endl;
	}

	// UDS -------------------------------------------------------------
	//start server

	if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1 ) {
		perror("socket");
		exit(1);
	}

	local.sun_family = AF_UNIX;
	strcpy(local.sun_path, SOCK_PATH);
	unlink(local.sun_path);
	len = strlen(local.sun_path) + sizeof(local.sun_family);

	if (bind(s, (struct sockaddr *)&local, len) == -1) {
		perror("bind");
		exit(1);
	}

	if (listen(s, 5) == -1) {
		perror("listen");
		exit(1);
	}

	while (run) {
		int done, n;
		printf("Waiting for a connection...\n");
		t = sizeof(remote);
		if ((s2 = accept(s, (struct sockaddr *)&remote, (socklen_t*)&t)) == -1) {
			perror("accept");
			exit(1);
		}

		printf("Connected.\n");

		done = 0;

		do {
			// receive data from client
			n = recv(s2, str, 100, 0);
			str[n] = '\0';
			cout << str << endl;
			if (n <= 0) {
				if (n < 0)
					perror("recv");

				done = 1;
			} else {

				if (strncmp(str,"GET_OCTOMAP",n) == 0) {
					done = 0;
				} else if (strncmp(str,"QUIT",n) == 0) {
					//reader->writeDataBT(); // write octree to bt-file
					run = 0; // stop main loop
					done = 1;
				}
			}

			// send data to client
			if (!done) {
				//strcpy(str,"RESPONSE");
				//str[8] = '\0';

				ret = reader->getOctomap(buff);
				if (ret == 0) {
					strncpy(buff,"NO_DATA",8);
					buff[8] = '\n';
					//buff << "NO_DATA";
				}

				if (send(s2, buff, ret, 0) < 0) {
					perror("send");
					done = 1;
				}
				done = 1;
			}
		} while (!done);

		close(s2);
	}

	if (reader != NULL)
		delete reader;
	return 0;
}
<|endoftext|>


<commit_before>2c254ecc-2748-11e6-bc6d-e0f84713e7b8<commit_msg>I'm done<commit_after>2c365991-2748-11e6-921b-e0f84713e7b8<|endoftext|>


<commit_before>c0e2bb45-4b02-11e5-a30a-28cfe9171a43<commit_msg>bug fix<commit_after>c10c004c-4b02-11e5-944d-28cfe9171a43<|endoftext|>


<commit_before>30df9d14-2748-11e6-ac6b-e0f84713e7b8<commit_msg>almost working<commit_after>30ee41fd-2748-11e6-888e-e0f84713e7b8<|endoftext|>


<commit_before>#include "code_printer/cpp.h"

#include <cxxutils/hashing.h>

// STL
#include <iostream>
#include <memory>
#include <string>
#include <functional>

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

  std::unique_ptr<CodePrinterBase> printer;

  std::string filename = "/tmp/demo-file.h";

  printer = std::make_unique<CppCodePrinter>();

  if(printer != nullptr)
  {
    printer->local_functions.push_back({"local_example", {{"posix::fd_t", "fd"}, {"long", "demo"}, {"std::string", "lol"}}});
    printer->remote_functions.push_back({"remote_example", {{"std::string", "lulz"}, {"std::vector<int>", "arr"}}});
    printer->local_functions.push_back({"local_example2", {{"std::string", "lulz"}, {"std::vector<int>", "arr"}}});
    printer->remote_functions.push_back({"remote_example2", {{"long", "demo"}, {"posix::fd_t", "fd"}, {"std::string", "lol"}}});

    try
    {
      printer->file_open(filename);
      printer->print_local();
      printer->print_remote();
      printer->file_close();
      std::cout << "success!" << std::endl;
    }
    catch(std::system_error e) { std::cout << "error: " << e.what() << std::endl; }
    catch(...) { std::cout << "unexpected error!" << std::endl; }
  }

  return 0;
}
<commit_msg>reorg/comments<commit_after>// STL
#include <iostream>
#include <memory>
#include <string>
#include <functional>

// PDTK
#include <cxxutils/hashing.h>

// incanto
#include "code_printer/cpp.h"

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

  std::unique_ptr<CodePrinterBase> printer;

  std::string filename = "/tmp/demo-file.h";

  printer = std::make_unique<CppCodePrinter>();

  if(printer != nullptr)
  {
    printer->local_functions.push_back({"local_example", {{"posix::fd_t", "fd"}, {"long", "demo"}, {"std::string", "lol"}}});
    printer->remote_functions.push_back({"remote_example", {{"std::string", "lulz"}, {"std::vector<int>", "arr"}}});
    printer->local_functions.push_back({"local_example2", {{"std::string", "lulz"}, {"std::vector<int>", "arr"}}});
    printer->remote_functions.push_back({"remote_example2", {{"long", "demo"}, {"posix::fd_t", "fd"}, {"std::string", "lol"}}});

    try
    {
      printer->file_open(filename);
      printer->print_local();
      printer->print_remote();
      printer->file_close();
      std::cout << "success!" << std::endl;
    }
    catch(std::system_error e) { std::cout << "error: " << e.what() << std::endl; }
    catch(...) { std::cout << "unexpected error!" << std::endl; }
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <array>
#include <cfloat>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <tgmath.h>
#include <unordered_map>
#include <utility>
#include <vector>
#include <functional>

using std::abs;
using std::array;
using std::bernoulli_distribution;
using std::cin;
using std::copy;
using std::cout;
using std::endl;
using std::get;
using std::getline;
using std::ifstream;
using std::istream;
using std::knuth_b;
using std::list;
using std::lower_bound;
using std::map;
using std::max;
using std::min;
using std::mt19937;
using std::multimap;
using std::normal_distribution;
using std::numeric_limits;
using std::ofstream;
using std::pair;
using std::random_device;
using std::reverse_iterator;
using std::round;
using std::setw;
using std::shuffle;
using std::sort;
using std::sqrt;
using std::string;
using std::stringstream;
using std::swap;
using std::tuple;
using std::uniform_real_distribution;
using std::unique;
using std::unordered_map;
using std::vector;

const double pi = M_PI;

template<class T>
inline constexpr T pow(const T &base, unsigned const &exponent)
{
    // (parentheses not required in next line)
    return (exponent == 0)     ? 1 :
           (exponent % 2 == 0) ? pow(base, exponent/2)*pow(base, exponent/2) :
           base * pow(base, (exponent-1)/2) * pow(base, (exponent-1)/2);
}

static const double gaussian(const double& x, const double& m, const double s){
  return exp(-(x-m)*(x-m)/(2*s*s))/(s*sqrt(2*pi));
}
                        //weight,μ     ,σ
static const vector<tuple<double,double,double>> ex_max_gauss(
  const vector<tuple<double,double>> &data, n){
  vector<tuple<double,double,double>> distr0;
  distr0.reserve(min(n,data.size()));
  for(auto it=data.begin();it!=data.end()&&distr0.size()<n;++it){
    distr0.push_back(1.0,get<0>(*it),get<1>(*it));
  }
  for (auto it=distr0.begin();it!=distr0.end();++it){
    get<0>(*it)=1.0/distr0.size();
  }
  vector<tuple<double,double,double>> distr1=distr0;
  for (double change=numeric_limits<double>::infinity();change>1e-10;){
    //distr0 old, distr1 new
    distr0=distr1;
    for (auto it0=distr0.begin(),it1=distr1.begin();
           it0!=distr0.end()&&it1!=distr1.end(); (++it0,++it1)){
      douleb t_n=0;
      for (auto it0=distr0.begin(); it0!=distr0.begin(); ++it0){
        for (auto it=data.begin(); it!=data.end(); ++it){
          const double m1=get<0>(*it);
          const double s1=get<1>(*it);
          const double t =get<0>(*it0);
          const double m2=get<1>(*it0);
          const double s2=get<2>(*it0);
//           const double m = (m1/(s1*s1)+m2/(s2*s2))
//           /(1.0/(s1*s1)+1.0/(s2*s2));
//           const double s = s1*s1*s2*s2/(s1*s1+s2*s2);
//           integrate(gaussian(m1,m2,sqrt(s1**2+s2**2))*gaussian(x,m,s))
          t_n+=t*gaussian(m1,m2,sqrt(s1*s1+s2*s2));
        }
      }
      for (auto it0=distr0.begin(),it1=distr1.begin();
           it0!=distr0.end()&&it1!=distr1.end(); (++it0,++it1)){
        get<0>(*it1)=0;
        for (auto it=data.begin(); it!=data.end(); ++it){
          const double m1=get<0>(*it);
          const double s1=get<1>(*it);
          const double t =get<0>(*it0);
          const double m2=get<1>(*it0);
          const double s2=get<2>(*it0);
          get<0>(*it1)+=t*gaussian(m1,m2,sqrt(s1*s1+s2*s2));
        }
      }
      for (auto it0=distr0.begin(); it0!=distr0.begin(); ++it0){

        for (auto it=data.begin(); it!=data.end(); ++it){
          const double m1=get<0>(*it);
          const double s1=get<1>(*it);
          const double m2=get<1>(*it0);
          const double s2=get<2>(*it0);
//           const double m = (m1/(s1*s1)+m2/(s2*s2))
//           /(1.0/(s1*s1)+1.0/(s2*s2));
//           const double s = s1*s1*s2*s2/(s1*s1+s2*s2);
//           integrate(gaussian(m1,m2,sqrt(s1**2+s2**2))*gaussian(x,m,s))
          get<0>(*it0)=get<0>gaussian(m1,m2,sqrt(s1*s1+s2*s2));
        }
      }

    }
    for (auto it=data.begin(); it!=data.end(); ++it){
      for (auto it0=distr0.begin(),it1=distr1.begin();
           it0!=distr0.end()&&it1!=distr1.end(); (++it0,++it1)){
      }
      get<0>(*it1)=new wheight;
      get<1>(*it1)=new mean;
      for (auto it0=distr0.begin(),it1=distr1.begin();
           it0!=distr0.end()&&it1!=distr1.end(); (++it0,++it1)){
        get<2>(it1)=

      }
    }
  }
}

void generate_distributions(
  const unordered_map<size_t,vector<tuple<size_t,double,double>>> &uniques,
  unordered_map<size_t,PPD> &distr,
  const column_vector &starting_point
){
  cout << "generating partiality distributions" << endl;
  for (auto it0=uniques.begin(); it0!=uniques.end(); ++it0){
    double mean=0.0;
    for (auto it1=it0->second.begin();it1!=it0->second.end();++it1){
      mean += get<1>(*it1);
    }
    //initialization
    mean/=it0->second.size();
    distr[it0->first]={0.0,mean,4*mean,4*mean,0.75};
    //maximization
    for (size_t i=0; i<8; ++i){
      const double n = it0->second.size();
      double s_t1 =0;
      double s_t2 =0;
      double m1_n =0;
      double m2_n =0;
      for (auto it1=it0->second.begin();it1!=it0->second.end();++it1){
        const double t1=distr[it0->first].t1;
        const double t2=1-t1;
        const double s =starting_point(get<0>(*it1));
        const double x =get<1>(*it1)*s;
        //         cout << x << endl;
        const double m1=distr[it0->first].m1;
        const double m2=distr[it0->first].m2;
        const double s1=distr[it0->first].s1;
        const double s2=distr[it0->first].s2;
        const double e1=(s1*s1*128<(x-m1)*(x-m1))?t1*0.00311664:t1*exp(-(x-m1)*(x-m1)/(2*s1*s1))/(s1*sqrt(2*pi));
        const double e2=(s2*s2*128<(x-m2)*(x-m2))?t2*0.00311664:t2*exp(-(x-m2)*(x-m2)/(2*s2*s2))/(s2*sqrt(2*pi));
        //         const double t1i =(abs(e1)+abs(e2)<1e-10)?(e1>e2?1:0):e1/(e1+e2);
        //         const double t2i =(abs(e1)+abs(e2)<1e-10)?(e2>e1?1:0):e2/(e1+e2);
        const double t1i =e1/(e1+e2);
        const double t2i =e2/(e1+e2);
        //         cout << x << " " << m1 << " " << m2 << " " << s1 << " " << s2 << " " << e1 << " " << e2 << " " << t1i << " " << t2i << endl;
        s_t1 += t1i;
        s_t2 += t2i;
        m1_n += t1i*x;
        m2_n += t2i*x;
        //         cout << s_t1 << " " << s_t2 << " " << m1_n << " " << m2_n << endl;
      }
      //       cout << m1_n/s_t1 << " " << m2_n/s_t2 << endl;
      double s1_n =0;
      double s2_n =0;
      for (auto it1=it0->second.begin();it1!=it0->second.end();++it1){
        const double t1=distr[it0->first].t1;
        const double t2=1-t1;
        const double m1=distr[it0->first].m1;
        const double m2=distr[it0->first].m2;
        const double s =starting_point(get<0>(*it1));
        const double x =get<1>(*it1)*s;
        const double s1=distr[it0->first].s1;
        const double s2=distr[it0->first].s2;
        const double e1=(s1*s1*128<(x-m1)*(x-m1))?0.00311664:t1*exp(-(x-m1)*(x-m1)/(2*s1*s1))/(s1*sqrt(2*pi));
        const double e2=(s2*s2*128<(x-m2)*(x-m2))?0.00311664:t2*exp(-(x-m2)*(x-m2)/(2*s2*s2))/(s2*sqrt(2*pi));
        //         const double t1i =(abs(e1)+abs(e2)<1e-10)?(e1>e2?1:0):e1/(e1+e2);
        //         const double t2i =(abs(e1)+abs(e2)<1e-10)?(e2>e1?1:0):e2/(e1+e2);
        const double t1i =e1/(e1+e2);
        const double t2i =e2/(e1+e2);
        //         cout << t1 << " " << x << " " << m1 << " " << m2 << " " << s1 << " " << s2 << " " << e1 << " " << e2 << " " << t1i << " " << t2i << endl;
        s1_n += t1i*(x-m1_n/s_t1)*(x-m1_n/s_t1); // dot product
        s2_n += t2i*(x-m2_n/s_t2)*(x-m2_n/s_t2); // dot product
        //         cout << s1_n << " " << s2_n << endl;
      }
      //       cout << sqrt(abs(s1_n/s_t1)) << " " << sqrt(abs(s2_n/s_t2)) << endl;
      distr[it0->first].t1 = s_t1/n;
      distr[it0->first].m1 = m1_n/s_t1;
      distr[it0->first].m2 = m2_n/s_t2;
      distr[it0->first].s1 = sqrt(abs(s1_n/s_t1));
      distr[it0->first].s2 = sqrt(abs(s2_n/s_t2));
      if (distr[it0->first].m2<distr[it0->first].m1){
        swap(distr[it0->first].m2,distr[it0->first].m1);
        swap(distr[it0->first].s2,distr[it0->first].s1);
        distr[it0->first].t1=1-distr[it0->first].t1;
      }
      if (distr[it0->first].s1<max(distr[it0->first].m2,distr[it0->first].m1)/10){
        distr[it0->first].s1=max(distr[it0->first].m2,distr[it0->first].m1)/10;
      }
      if (distr[it0->first].s1<max(abs(distr[it0->first].m2),abs(distr[it0->first].m1))/10){
        distr[it0->first].s1=max(abs(distr[it0->first].m2),abs(distr[it0->first].m1))/10;
      }
      if (distr[it0->first].t1<0.015625) distr[it0->first].t1=0.015625;
      if (distr[it0->first].t1>0.984375) distr[it0->first].t1=0.984375;
      if (isnan(distr[it0->first].m1)||isnan(distr[it0->first].m2)||isnan(distr[it0->first].s1)||isnan(distr[it0->first].s2)){
        cout <<  "maan schon wieder ein nan :( " << endl;
        exit(-1);
      }
    }
    //     cout << mean << " " << distr[it0->first].m1 << " " << distr[it0->first].m2 << endl;
  }
}

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

  return 0;
}
<commit_msg>add comment<commit_after>#include <algorithm>
#include <array>
#include <cfloat>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <tgmath.h>
#include <unordered_map>
#include <utility>
#include <vector>
#include <functional>

using std::abs;
using std::array;
using std::bernoulli_distribution;
using std::cin;
using std::copy;
using std::cout;
using std::endl;
using std::get;
using std::getline;
using std::ifstream;
using std::istream;
using std::knuth_b;
using std::list;
using std::lower_bound;
using std::map;
using std::max;
using std::min;
using std::mt19937;
using std::multimap;
using std::normal_distribution;
using std::numeric_limits;
using std::ofstream;
using std::pair;
using std::random_device;
using std::reverse_iterator;
using std::round;
using std::setw;
using std::shuffle;
using std::sort;
using std::sqrt;
using std::string;
using std::stringstream;
using std::swap;
using std::tuple;
using std::uniform_real_distribution;
using std::unique;
using std::unordered_map;
using std::vector;

const double pi = M_PI;

// faster pow implementation for integer powers - is there something more elegant?
template<class T>
inline constexpr T pow(const T &base, unsigned const &exponent)
{
    // (parentheses not required in next line)
    return (exponent == 0)     ? 1 :
           (exponent % 2 == 0) ? pow(base, exponent/2)*pow(base, exponent/2) :
           base * pow(base, (exponent-1)/2) * pow(base, (exponent-1)/2);
}

static const double gaussian(const double& x, const double& m, const double s){
  return exp(-(x-m)*(x-m)/(2*s*s))/(s*sqrt(2*pi));
}
                        //weight,μ     ,σ
static const vector<tuple<double,double,double>> ex_max_gauss(
  const vector<tuple<double,double>> &data, n){
  vector<tuple<double,double,double>> distr0;
  distr0.reserve(min(n,data.size()));
  for(auto it=data.begin();it!=data.end()&&distr0.size()<n;++it){
    distr0.push_back(1.0,get<0>(*it),get<1>(*it));
  }
  for (auto it=distr0.begin();it!=distr0.end();++it){
    get<0>(*it)=1.0/distr0.size();
  }
  vector<tuple<double,double,double>> distr1=distr0;
  for (double change=numeric_limits<double>::infinity();change>1e-10;){
    //distr0 old, distr1 new
    distr0=distr1;
    for (auto it0=distr0.begin(),it1=distr1.begin();
           it0!=distr0.end()&&it1!=distr1.end(); (++it0,++it1)){
      douleb t_n=0;
      for (auto it0=distr0.begin(); it0!=distr0.begin(); ++it0){
        for (auto it=data.begin(); it!=data.end(); ++it){
          const double m1=get<0>(*it);
          const double s1=get<1>(*it);
          const double t =get<0>(*it0);
          const double m2=get<1>(*it0);
          const double s2=get<2>(*it0);
//           const double m = (m1/(s1*s1)+m2/(s2*s2))
//           /(1.0/(s1*s1)+1.0/(s2*s2));
//           const double s = s1*s1*s2*s2/(s1*s1+s2*s2);
//           integrate(gaussian(m1,m2,sqrt(s1**2+s2**2))*gaussian(x,m,s))
          t_n+=t*gaussian(m1,m2,sqrt(s1*s1+s2*s2));
        }
      }
      for (auto it0=distr0.begin(),it1=distr1.begin();
           it0!=distr0.end()&&it1!=distr1.end(); (++it0,++it1)){
        get<0>(*it1)=0;
        for (auto it=data.begin(); it!=data.end(); ++it){
          const double m1=get<0>(*it);
          const double s1=get<1>(*it);
          const double t =get<0>(*it0);
          const double m2=get<1>(*it0);
          const double s2=get<2>(*it0);
          get<0>(*it1)+=t*gaussian(m1,m2,sqrt(s1*s1+s2*s2));
        }
      }
      for (auto it0=distr0.begin(); it0!=distr0.begin(); ++it0){

        for (auto it=data.begin(); it!=data.end(); ++it){
          const double m1=get<0>(*it);
          const double s1=get<1>(*it);
          const double m2=get<1>(*it0);
          const double s2=get<2>(*it0);
//           const double m = (m1/(s1*s1)+m2/(s2*s2))
//           /(1.0/(s1*s1)+1.0/(s2*s2));
//           const double s = s1*s1*s2*s2/(s1*s1+s2*s2);
//           integrate(gaussian(m1,m2,sqrt(s1**2+s2**2))*gaussian(x,m,s))
          get<0>(*it0)=get<0>gaussian(m1,m2,sqrt(s1*s1+s2*s2));
        }
      }

    }
    for (auto it=data.begin(); it!=data.end(); ++it){
      for (auto it0=distr0.begin(),it1=distr1.begin();
           it0!=distr0.end()&&it1!=distr1.end(); (++it0,++it1)){
      }
      get<0>(*it1)=new wheight;
      get<1>(*it1)=new mean;
      for (auto it0=distr0.begin(),it1=distr1.begin();
           it0!=distr0.end()&&it1!=distr1.end(); (++it0,++it1)){
        get<2>(it1)=

      }
    }
  }
}

void generate_distributions(
  const unordered_map<size_t,vector<tuple<size_t,double,double>>> &uniques,
  unordered_map<size_t,PPD> &distr,
  const column_vector &starting_point
){
  cout << "generating partiality distributions" << endl;
  for (auto it0=uniques.begin(); it0!=uniques.end(); ++it0){
    double mean=0.0;
    for (auto it1=it0->second.begin();it1!=it0->second.end();++it1){
      mean += get<1>(*it1);
    }
    //initialization
    mean/=it0->second.size();
    distr[it0->first]={0.0,mean,4*mean,4*mean,0.75};
    //maximization
    for (size_t i=0; i<8; ++i){
      const double n = it0->second.size();
      double s_t1 =0;
      double s_t2 =0;
      double m1_n =0;
      double m2_n =0;
      for (auto it1=it0->second.begin();it1!=it0->second.end();++it1){
        const double t1=distr[it0->first].t1;
        const double t2=1-t1;
        const double s =starting_point(get<0>(*it1));
        const double x =get<1>(*it1)*s;
        //         cout << x << endl;
        const double m1=distr[it0->first].m1;
        const double m2=distr[it0->first].m2;
        const double s1=distr[it0->first].s1;
        const double s2=distr[it0->first].s2;
        const double e1=(s1*s1*128<(x-m1)*(x-m1))?t1*0.00311664:t1*exp(-(x-m1)*(x-m1)/(2*s1*s1))/(s1*sqrt(2*pi));
        const double e2=(s2*s2*128<(x-m2)*(x-m2))?t2*0.00311664:t2*exp(-(x-m2)*(x-m2)/(2*s2*s2))/(s2*sqrt(2*pi));
        //         const double t1i =(abs(e1)+abs(e2)<1e-10)?(e1>e2?1:0):e1/(e1+e2);
        //         const double t2i =(abs(e1)+abs(e2)<1e-10)?(e2>e1?1:0):e2/(e1+e2);
        const double t1i =e1/(e1+e2);
        const double t2i =e2/(e1+e2);
        //         cout << x << " " << m1 << " " << m2 << " " << s1 << " " << s2 << " " << e1 << " " << e2 << " " << t1i << " " << t2i << endl;
        s_t1 += t1i;
        s_t2 += t2i;
        m1_n += t1i*x;
        m2_n += t2i*x;
        //         cout << s_t1 << " " << s_t2 << " " << m1_n << " " << m2_n << endl;
      }
      //       cout << m1_n/s_t1 << " " << m2_n/s_t2 << endl;
      double s1_n =0;
      double s2_n =0;
      for (auto it1=it0->second.begin();it1!=it0->second.end();++it1){
        const double t1=distr[it0->first].t1;
        const double t2=1-t1;
        const double m1=distr[it0->first].m1;
        const double m2=distr[it0->first].m2;
        const double s =starting_point(get<0>(*it1));
        const double x =get<1>(*it1)*s;
        const double s1=distr[it0->first].s1;
        const double s2=distr[it0->first].s2;
        const double e1=(s1*s1*128<(x-m1)*(x-m1))?0.00311664:t1*exp(-(x-m1)*(x-m1)/(2*s1*s1))/(s1*sqrt(2*pi));
        const double e2=(s2*s2*128<(x-m2)*(x-m2))?0.00311664:t2*exp(-(x-m2)*(x-m2)/(2*s2*s2))/(s2*sqrt(2*pi));
        //         const double t1i =(abs(e1)+abs(e2)<1e-10)?(e1>e2?1:0):e1/(e1+e2);
        //         const double t2i =(abs(e1)+abs(e2)<1e-10)?(e2>e1?1:0):e2/(e1+e2);
        const double t1i =e1/(e1+e2);
        const double t2i =e2/(e1+e2);
        //         cout << t1 << " " << x << " " << m1 << " " << m2 << " " << s1 << " " << s2 << " " << e1 << " " << e2 << " " << t1i << " " << t2i << endl;
        s1_n += t1i*(x-m1_n/s_t1)*(x-m1_n/s_t1); // dot product
        s2_n += t2i*(x-m2_n/s_t2)*(x-m2_n/s_t2); // dot product
        //         cout << s1_n << " " << s2_n << endl;
      }
      //       cout << sqrt(abs(s1_n/s_t1)) << " " << sqrt(abs(s2_n/s_t2)) << endl;
      distr[it0->first].t1 = s_t1/n;
      distr[it0->first].m1 = m1_n/s_t1;
      distr[it0->first].m2 = m2_n/s_t2;
      distr[it0->first].s1 = sqrt(abs(s1_n/s_t1));
      distr[it0->first].s2 = sqrt(abs(s2_n/s_t2));
      if (distr[it0->first].m2<distr[it0->first].m1){
        swap(distr[it0->first].m2,distr[it0->first].m1);
        swap(distr[it0->first].s2,distr[it0->first].s1);
        distr[it0->first].t1=1-distr[it0->first].t1;
      }
      if (distr[it0->first].s1<max(distr[it0->first].m2,distr[it0->first].m1)/10){
        distr[it0->first].s1=max(distr[it0->first].m2,distr[it0->first].m1)/10;
      }
      if (distr[it0->first].s1<max(abs(distr[it0->first].m2),abs(distr[it0->first].m1))/10){
        distr[it0->first].s1=max(abs(distr[it0->first].m2),abs(distr[it0->first].m1))/10;
      }
      if (distr[it0->first].t1<0.015625) distr[it0->first].t1=0.015625;
      if (distr[it0->first].t1>0.984375) distr[it0->first].t1=0.984375;
      if (isnan(distr[it0->first].m1)||isnan(distr[it0->first].m2)||isnan(distr[it0->first].s1)||isnan(distr[it0->first].s2)){
        cout <<  "maan schon wieder ein nan :( " << endl;
        exit(-1);
      }
    }
    //     cout << mean << " " << distr[it0->first].m1 << " " << distr[it0->first].m2 << endl;
  }
}

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

  return 0;
}
<|endoftext|>


<commit_before>#include "OpenCLManager.hpp"
#include "ImageImporter2D.hpp"
#include "DeviceManager.hpp"
using namespace fast;

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

    DeviceManager& deviceManager = DeviceManager::getInstance();
    deviceManager.setDefaultDevice(deviceManager.getOneGPUDevice());

    ImageImporter2D::Ptr importer = ImageImporter2D::New();
    importer->setFilename("lena.jpg");
    Image2D::Ptr image = importer->getOutput();
    std::cout << "Pipeline setup finished" << std::endl;
    image->update();
    std::cout << "Pipeline finished execution" << std::endl;
}
<commit_msg>clean up<commit_after>#include "ImageImporter2D.hpp"
#include "DeviceManager.hpp"
using namespace fast;

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

    // Get a GPU device and set it as the default device
    DeviceManager& deviceManager = DeviceManager::getInstance();
    deviceManager.setDefaultDevice(deviceManager.getOneGPUDevice());

    ImageImporter2D::Ptr importer = ImageImporter2D::New();
    importer->setFilename("lena.jpg");
    Image2D::Ptr image = importer->getOutput();
    std::cout << "Pipeline setup finished" << std::endl;
    image->update();
    std::cout << "Pipeline finished execution" << std::endl;
}
<|endoftext|>


<commit_before>36e4bb5e-ad5c-11e7-926a-ac87a332f658<commit_msg>Now it no longer crashes if X<commit_after>3745651c-ad5c-11e7-98aa-ac87a332f658<|endoftext|>


<commit_before>f34427ab-ad58-11e7-9300-ac87a332f658<commit_msg>more fixes<commit_after>f3e78991-ad58-11e7-8d19-ac87a332f658<|endoftext|>