<commit_before>#include "mainwindow.h"
#include <QWebView>
#include <QtWidgets>
#include <QWebFrame>
#include <QDir>
#include <QApplication>
#include <QDebug>
#include <QWebPage>
#include <QObject>

/*
 *  Utility:
 *  ./exectuable pageAddress width height decoration
 *
 *   - pageAddress: the html file path or url
 *   - width:       integer that represent the width of the window
 *   - height:      integer that represent the height of the window
 *   - decoration:  if it is "UNDECORATED" the window will be undecorated (it will not have
 *                  borders and the window buttons
 *
 * */

QWebView *webView;

/*
 *  Javascript functions (Public API)
 * */
class MyJavaScriptOperations : public QObject {
    Q_OBJECT
public:
    /*
     *  Close window
     *  $API.closeWindow();
     *
     **/
    Q_INVOKABLE void closeWindow () {
        webView->close();
    }

    /*
     *  Resize
     *  $API.resize(width, height);
     *
     **/
    Q_INVOKABLE void resize (int width, int height) {
        webView->resize(width, height);
    }

    /*
     *  Set window flags
     *  $API.setWindowFlags (type)
     *      - UNDECORATED
     *
     * */
    Q_INVOKABLE void setWindowFlags (QString type) {

        QStringList options;
        options << "UNDECORATED";

        switch (options.indexOf(type)) {
            case 0:
                webView->setWindowFlags(Qt::FramelessWindowHint);
                webView->show();
                break;
            // TODO Other cases
        }
    }

    /*
     *  Set window state
     *  $API.setWindowState (value)
     *      - MAXIMIZED
     *      - MINIMIZED
     *      - FULLSCREEN
     *      - ACTIVE
     * */
    Q_INVOKABLE void setWindowState (QString type) {

        QStringList options;
        options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE";

        switch (options.indexOf(type)) {
            case 0:
                webView->setWindowState(Qt::WindowMaximized);
                break;
            case 1:
                webView->setWindowState(Qt::WindowMinimized);
                break;
            case 2:
                webView->setWindowState(Qt::WindowFullScreen);
                break;
            case 3:
                webView->setWindowState(Qt::WindowActive);
                break;
        }
    }

    /*
     *  Get window size
     *  $API.getWindowSize ()
     * */
    Q_INVOKABLE QObject *getWindowSize () {

        QObject *size = new QObject();
        QSize winSize = webView->size();

        size->setProperty("width", winSize.width());
        size->setProperty("height", winSize.height());

        return size;
    }
};

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

    QApplication app(argc, argv);

    // build the web view
    QWebView *view = new QWebView();

    webView = view;

    // get the html path
    QString HTML_PATH       = QString(argv[1]);

    // the path is NOT a web site url
    if (!HTML_PATH.startsWith("htt"))
    {
        // get it from the local machine
        HTML_PATH = "file://" + QDir::current().absolutePath() + QDir::separator() + HTML_PATH;
    }

    // set window width and height
    int     WINDOW_WIDTH    = QString(argv[2]).toInt();
    int     WINDOW_HEIGHT   = QString(argv[3]).toInt();

    // handle "UNDECORATED" flag
    if (QString(argv[4]) == "UNDECORATED") {
        view->setWindowFlags(Qt::FramelessWindowHint);
    }

    // add the public api functions
    view->page()->mainFrame()->addToJavaScriptWindowObject("$API", new MyJavaScriptOperations);

    // resize the window
    view->resize(WINDOW_WIDTH, WINDOW_HEIGHT);

    // load that HTML file or website
    view->load(QUrl(HTML_PATH));

    // show the web view
    view->show();

    return app.exec();
}

#include "main.moc"
<commit_msg>Added new functions<commit_after>#include "mainwindow.h"
#include <QWebView>
#include <QtWidgets>
#include <QWebFrame>
#include <QDir>
#include <QApplication>
#include <QDebug>
#include <QWebPage>
#include <QObject>

/*
 *  Utility:
 *  ./exectuable pageAddress width height decoration
 *
 *   - pageAddress: the html file path or url
 *   - width:       integer that represent the width of the window
 *   - height:      integer that represent the height of the window
 *   - decoration:  if it is "UNDECORATED" the window will be undecorated (it will not have
 *                  borders and the window buttons
 *
 * */

QWebView *webView;

/*
 *  Javascript functions (Public API)
 * */
class MyJavaScriptOperations : public QObject {
    Q_OBJECT
public:
    /*
     *  Close window
     *  $API.closeWindow();
     *
     **/
    Q_INVOKABLE void closeWindow () {
        webView->close();
    }

    /*
     *  Resize
     *  $API.resize(width, height);
     *
     **/
    Q_INVOKABLE void resize (int width, int height) {
        webView->resize(width, height);
    }

    /*
     *  Set window flags
     *  $API.setWindowFlags (type)
     *      - UNDECORATED
     *
     * */
    Q_INVOKABLE void setWindowFlags (QString type) {

        QStringList options;
        options << "UNDECORATED";

        switch (options.indexOf(type)) {
            case 0:
                webView->setWindowFlags(Qt::FramelessWindowHint);
                webView->show();
                break;
            // TODO Other cases
        }
    }

    /*
     *  Set window state
     *  $API.setWindowState (value)
     *      - MAXIMIZED
     *      - MINIMIZED
     *      - FULLSCREEN
     *      - ACTIVE
     * */
    Q_INVOKABLE void setWindowState (QString type) {

        QStringList options;
        options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE";

        switch (options.indexOf(type)) {
            case 0:
                webView->setWindowState(Qt::WindowMaximized);
                break;
            case 1:
                webView->setWindowState(Qt::WindowMinimized);
                break;
            case 2:
                webView->setWindowState(Qt::WindowFullScreen);
                break;
            case 3:
                webView->setWindowState(Qt::WindowActive);
                break;
        }
    }

    /*
     *  Get window size
     *  $API.getWindowSize ()
     * */
    Q_INVOKABLE QObject *getWindowSize () {

        QObject *size = new QObject();
        QSize winSize = webView->size();

        size->setProperty("width", winSize.width());
        size->setProperty("height", winSize.height());

        return size;
    }

    /*
     *  Set window position
     *  $API.setWindowPosition (left, top)
     * */
    Q_INVOKABLE void setWindowPosition (int left, int top) {
        webView->move(left, top);
    }

    /*
     *  Get window position
     *  $API.getWindowPosition (left, top)
     * */
    Q_INVOKABLE QObject *getWindowPosition () {
        QObject *position = new QObject();
        QPoint point = webView->pos();

        position->setProperty("left", point.x());
        position->setProperty("top", point.y());

        return position;
    }

    /*
     *  Debug
     *  $API.debug(message)
     *
     * */
    Q_INVOKABLE void debug (QString message) {
        qDebug() << message;
    }
};

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

    QApplication app(argc, argv);

    // build the web view
    QWebView *view = new QWebView();

    webView = view;

    // get the html path
    QString HTML_PATH       = QString(argv[1]);

    // the path is NOT a web site url
    if (!HTML_PATH.startsWith("htt"))
    {
        // get it from the local machine
        HTML_PATH = "file://" + QDir::current().absolutePath() + QDir::separator() + HTML_PATH;
    }

    // set window width and height
    int     WINDOW_WIDTH    = QString(argv[2]).toInt();
    int     WINDOW_HEIGHT   = QString(argv[3]).toInt();

    // handle "UNDECORATED" flag
    if (QString(argv[4]) == "UNDECORATED") {
        view->setWindowFlags(Qt::FramelessWindowHint);
    }

    // add the public api functions
    view->page()->mainFrame()->addToJavaScriptWindowObject("$API", new MyJavaScriptOperations);

    // resize the window
    view->resize(WINDOW_WIDTH, WINDOW_HEIGHT);

    // load that HTML file or website
    view->load(QUrl(HTML_PATH));

    // show the web view
    view->show();

    return app.exec();
}

#include "main.moc"
<|endoftext|>


<commit_before>52989f82-2748-11e6-b1b9-e0f84713e7b8<commit_msg>Did a thing<commit_after>52a9f745-2748-11e6-901f-e0f84713e7b8<|endoftext|>


<commit_before>76332e3a-4b02-11e5-aba4-28cfe9171a43<commit_msg>lets try again<commit_after>763e0f3a-4b02-11e5-a4f0-28cfe9171a43<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004-2007  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <signal.h>
#include "znc.h"
#include "Modules.h"
#include "MD5.h"

static struct option g_LongOpts[] = {
	{ "help",			no_argument,	0,	'h' },
	{ "version",			no_argument,	0,	'v' },
	{ "makeconf",			no_argument,	0,	'c' },
	{ "makepass",			no_argument,	0,	's' },
#ifdef HAVE_LIBSSL
	{ "makepem",			no_argument,	0,	'p' },
	{ "encrypt-pem",		no_argument,	0, 	'e' },
#endif /* HAVE_LIBSSL */
	{ "datadir",                    required_argument,	0,   'd' },
	{ 0, 0, 0, 0 }
};

void GenerateHelp(const char *appname) {
	CUtils::PrintMessage("USAGE: " + CString(appname) + " [options] [config]");
	CUtils::PrintMessage("Options are:");
	CUtils::PrintMessage("\t-h, --help         List available command line options (this page)");
	CUtils::PrintMessage("\t-v, --version      Output version information and exit");
	CUtils::PrintMessage("\t-c, --makeconf     Interactively create a new config");
	CUtils::PrintMessage("\t-s, --makepass     Generates a password for use in config");
#ifdef HAVE_LIBSSL
	CUtils::PrintMessage("\t-p, --makepem      Generates a pemfile for use with SSL");
	CUtils::PrintMessage("\t-e, --encrypt-pem  when used along with --makepem, encrypts the private key in the pemfile");
#endif /* HAVE_LIBSSL */
	CUtils::PrintMessage("\t-d, --datadir      Set a different znc repository (default is ~/.znc)");
}

void die(int sig) {
	signal(SIGSEGV, SIG_DFL);
	signal(SIGABRT, SIG_DFL);
	signal(SIGPIPE, SIG_DFL);

#ifdef _DEBUG
	CUtils::PrintMessage("Exiting on SIG [" + CString(sig) + "]");
	if ((sig == SIGABRT) || (sig == SIGSEGV)) {
		abort();
	}
#endif /* _DEBUG */

	delete &CZNC::Get();
	exit(sig);
}

int main(int argc, char** argv, char** envp) {
	CString sConfig;
	CString sDataDir = "";

	srand(time(NULL));

#ifdef HAVE_LIBSSL
	InitSSL();
#endif /* HAVE_LIBSSL */

	int iArg, iOptIndex = -1;
	bool bMakeConf = false;
	bool bMakePass = false;
#ifdef HAVE_LIBSSL
	bool bMakePem = false;
	bool bEncPem = false;

	while ((iArg = getopt_long(argc, argv, "hvcsped:", g_LongOpts, &iOptIndex)) != -1) {
#else

	while ((iArg = getopt_long(argc, argv, "hvcsd:", g_LongOpts, &iOptIndex)) != -1) {
#endif /* HAVE_LIBSSL */
	    switch (iArg) {
		case 'h':
			    GenerateHelp(argv[0]);
			    return 0;
		case 'v':
			    cout << CZNC::GetTag() << endl;
			    return 0;
		case 'c':
			    bMakeConf = true;
			    break;
		case 's':
			    bMakePass = true;
			    break;
#ifdef HAVE_LIBSSL
		case 'p':
			    bMakePem = true;
			    break;
		case 'e':
			    bEncPem = true;
			    break;
#endif /* HAVE_LIBSSL */
		case 'd':
			    sDataDir = CString(optarg);
			    break;
		case '?':
		default:
			    GenerateHelp(argv[0]);
			    return 1;
	    }
	}

	if (optind < argc) {
		sConfig = argv[optind];
	} else {
		sConfig = "znc.conf";
	}

	if (bMakeConf) {
		CZNC& ZNC = CZNC::Get();
		ZNC.InitDirs("", sDataDir);
		if (ZNC.WriteNewConfig(sConfig)) {
			char const* args[5];

			if (argc > 2) {
				args[0] = argv[0];
				if (!sDataDir.empty()) {
					args[1] = "--datadir";
					args[2] = strdup(sDataDir.c_str());
					args[3] = argv[optind];
					args[4] = NULL;
				} else {
					args[1] = argv[optind];
					args[2] = NULL;
				}
			} else if (argc > 1) {
				args[0] = argv[0];
				if (!sDataDir.empty()) {
					args[1] = "--datadir";
					args[2] = strdup(sDataDir.c_str());
					args[3] = NULL;
				} else {
					args[1] = NULL;
				}
			} else {
				CUtils::PrintError("Unable to launch znc [Try manually restarting]");
				return 1;
			}

			if ((chdir(ZNC.GetCurPath().c_str()) == -1)
					|| (execve(*argv, (char *const*)args, envp) == -1)) {
				CUtils::PrintError("Unable to launch znc [" + CString(strerror(errno)) + "]");
				return 1;
			}
		}

		return 0;
	}

#ifdef HAVE_LIBSSL
	if (bMakePem) {
		CZNC* pZNC = &CZNC::Get();
		pZNC->InitDirs("", sDataDir);
		pZNC->WritePemFile( bEncPem );

		delete pZNC;
		return 0;
	}
	if( bEncPem && !bMakePem ) {
		CUtils::PrintError("--encrypt-pem should be used along with --makepem.");
		return 1;
	}

#endif /* HAVE_LIBSSL */
	if (bMakePass) {
		CString sHash = CUtils::GetHashPass();
		CUtils::PrintMessage("Use this in the <User> section of your config:");
		CUtils::PrintMessage("Pass = " + sHash + " -");

		return 0;
	}

	CZNC* pZNC = &CZNC::Get();
	pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir);

	if (!pZNC->ParseConfig(sConfig)) {
		CUtils::PrintError("Unrecoverable config error.");
		delete pZNC;
		return 1;
	}

	if (!pZNC->GetListeners().size()) {
		CUtils::PrintError("You must supply at least one Listen port in your config.");
		delete pZNC;
		return 1;
	}

	if (!pZNC->OnBoot()) {
		CUtils::PrintError("Exiting due to module boot errors.");
		delete pZNC;
		return 1;
	}

#ifdef _DEBUG
	CUtils::PrintMessage("Staying open for debugging");
#else
	CUtils::PrintAction("Forking into the background");

	int iPid = fork();

	if (iPid == -1) {
		CUtils::PrintStatus(false, strerror(errno));
		delete pZNC;
		exit(1);
	}

	if (iPid > 0) {
		CUtils::PrintStatus(true, "[pid: " + CString(iPid) + "]");

		pZNC->WritePidFile(iPid);
		CUtils::PrintMessage(CZNC::GetTag(false));
		exit(0);
	}

	// Redirect std in/out/err to /dev/null
	close(0); open("/dev/null", O_RDONLY);
	close(1); open("/dev/null", O_WRONLY);
	close(2); open("/dev/null", O_WRONLY);
#endif

	struct sigaction sa;
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);

	sa.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &sa, (struct sigaction*) NULL);

	sa.sa_handler = die;
	sigaction(SIGINT,  &sa, (struct sigaction*) NULL);
	sigaction(SIGILL,  &sa, (struct sigaction*) NULL);
	sigaction(SIGQUIT, &sa, (struct sigaction*) NULL);
	sigaction(SIGBUS,  &sa, (struct sigaction*) NULL);
	sigaction(SIGSEGV, &sa, (struct sigaction*) NULL);
	sigaction(SIGTERM, &sa, (struct sigaction*) NULL);

	int iRet = 0;

	try {
		iRet = pZNC->Loop();
	} catch (CException e) {
		// EX_Shutdown is thrown to exit
		switch (e.GetType()) {
			case CException::EX_Shutdown:
				iRet = 0;
			default:
				iRet = 1;
		}
	}

	delete pZNC;

	return iRet;
}
<commit_msg>Remove third argument of main()<commit_after>/*
 * Copyright (C) 2004-2007  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <signal.h>
#include "znc.h"
#include "Modules.h"
#include "MD5.h"

static struct option g_LongOpts[] = {
	{ "help",			no_argument,	0,	'h' },
	{ "version",			no_argument,	0,	'v' },
	{ "makeconf",			no_argument,	0,	'c' },
	{ "makepass",			no_argument,	0,	's' },
#ifdef HAVE_LIBSSL
	{ "makepem",			no_argument,	0,	'p' },
	{ "encrypt-pem",		no_argument,	0, 	'e' },
#endif /* HAVE_LIBSSL */
	{ "datadir",                    required_argument,	0,   'd' },
	{ 0, 0, 0, 0 }
};

void GenerateHelp(const char *appname) {
	CUtils::PrintMessage("USAGE: " + CString(appname) + " [options] [config]");
	CUtils::PrintMessage("Options are:");
	CUtils::PrintMessage("\t-h, --help         List available command line options (this page)");
	CUtils::PrintMessage("\t-v, --version      Output version information and exit");
	CUtils::PrintMessage("\t-c, --makeconf     Interactively create a new config");
	CUtils::PrintMessage("\t-s, --makepass     Generates a password for use in config");
#ifdef HAVE_LIBSSL
	CUtils::PrintMessage("\t-p, --makepem      Generates a pemfile for use with SSL");
	CUtils::PrintMessage("\t-e, --encrypt-pem  when used along with --makepem, encrypts the private key in the pemfile");
#endif /* HAVE_LIBSSL */
	CUtils::PrintMessage("\t-d, --datadir      Set a different znc repository (default is ~/.znc)");
}

void die(int sig) {
	signal(SIGSEGV, SIG_DFL);
	signal(SIGABRT, SIG_DFL);
	signal(SIGPIPE, SIG_DFL);

#ifdef _DEBUG
	CUtils::PrintMessage("Exiting on SIG [" + CString(sig) + "]");
	if ((sig == SIGABRT) || (sig == SIGSEGV)) {
		abort();
	}
#endif /* _DEBUG */

	delete &CZNC::Get();
	exit(sig);
}

int main(int argc, char** argv) {
	CString sConfig;
	CString sDataDir = "";

	srand(time(NULL));

#ifdef HAVE_LIBSSL
	InitSSL();
#endif /* HAVE_LIBSSL */

	int iArg, iOptIndex = -1;
	bool bMakeConf = false;
	bool bMakePass = false;
#ifdef HAVE_LIBSSL
	bool bMakePem = false;
	bool bEncPem = false;

	while ((iArg = getopt_long(argc, argv, "hvcsped:", g_LongOpts, &iOptIndex)) != -1) {
#else

	while ((iArg = getopt_long(argc, argv, "hvcsd:", g_LongOpts, &iOptIndex)) != -1) {
#endif /* HAVE_LIBSSL */
	    switch (iArg) {
		case 'h':
			    GenerateHelp(argv[0]);
			    return 0;
		case 'v':
			    cout << CZNC::GetTag() << endl;
			    return 0;
		case 'c':
			    bMakeConf = true;
			    break;
		case 's':
			    bMakePass = true;
			    break;
#ifdef HAVE_LIBSSL
		case 'p':
			    bMakePem = true;
			    break;
		case 'e':
			    bEncPem = true;
			    break;
#endif /* HAVE_LIBSSL */
		case 'd':
			    sDataDir = CString(optarg);
			    break;
		case '?':
		default:
			    GenerateHelp(argv[0]);
			    return 1;
	    }
	}

	if (optind < argc) {
		sConfig = argv[optind];
	} else {
		sConfig = "znc.conf";
	}

	if (bMakeConf) {
		CZNC& ZNC = CZNC::Get();
		ZNC.InitDirs("", sDataDir);
		if (ZNC.WriteNewConfig(sConfig)) {
			char const* args[5];

			if (argc > 2) {
				args[0] = argv[0];
				if (!sDataDir.empty()) {
					args[1] = "--datadir";
					args[2] = strdup(sDataDir.c_str());
					args[3] = argv[optind];
					args[4] = NULL;
				} else {
					args[1] = argv[optind];
					args[2] = NULL;
				}
			} else if (argc > 1) {
				args[0] = argv[0];
				if (!sDataDir.empty()) {
					args[1] = "--datadir";
					args[2] = strdup(sDataDir.c_str());
					args[3] = NULL;
				} else {
					args[1] = NULL;
				}
			} else {
				CUtils::PrintError("Unable to launch znc [Try manually restarting]");
				return 1;
			}

			if ((chdir(ZNC.GetCurPath().c_str()) == -1)
					|| (execv(*argv, (char *const*)args) == -1)) {
				CUtils::PrintError("Unable to launch znc [" + CString(strerror(errno)) + "]");
				return 1;
			}
		}

		return 0;
	}

#ifdef HAVE_LIBSSL
	if (bMakePem) {
		CZNC* pZNC = &CZNC::Get();
		pZNC->InitDirs("", sDataDir);
		pZNC->WritePemFile( bEncPem );

		delete pZNC;
		return 0;
	}
	if( bEncPem && !bMakePem ) {
		CUtils::PrintError("--encrypt-pem should be used along with --makepem.");
		return 1;
	}

#endif /* HAVE_LIBSSL */
	if (bMakePass) {
		CString sHash = CUtils::GetHashPass();
		CUtils::PrintMessage("Use this in the <User> section of your config:");
		CUtils::PrintMessage("Pass = " + sHash + " -");

		return 0;
	}

	CZNC* pZNC = &CZNC::Get();
	pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir);

	if (!pZNC->ParseConfig(sConfig)) {
		CUtils::PrintError("Unrecoverable config error.");
		delete pZNC;
		return 1;
	}

	if (!pZNC->GetListeners().size()) {
		CUtils::PrintError("You must supply at least one Listen port in your config.");
		delete pZNC;
		return 1;
	}

	if (!pZNC->OnBoot()) {
		CUtils::PrintError("Exiting due to module boot errors.");
		delete pZNC;
		return 1;
	}

#ifdef _DEBUG
	CUtils::PrintMessage("Staying open for debugging");
#else
	CUtils::PrintAction("Forking into the background");

	int iPid = fork();

	if (iPid == -1) {
		CUtils::PrintStatus(false, strerror(errno));
		delete pZNC;
		exit(1);
	}

	if (iPid > 0) {
		CUtils::PrintStatus(true, "[pid: " + CString(iPid) + "]");

		pZNC->WritePidFile(iPid);
		CUtils::PrintMessage(CZNC::GetTag(false));
		exit(0);
	}

	// Redirect std in/out/err to /dev/null
	close(0); open("/dev/null", O_RDONLY);
	close(1); open("/dev/null", O_WRONLY);
	close(2); open("/dev/null", O_WRONLY);
#endif

	struct sigaction sa;
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);

	sa.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &sa, (struct sigaction*) NULL);

	sa.sa_handler = die;
	sigaction(SIGINT,  &sa, (struct sigaction*) NULL);
	sigaction(SIGILL,  &sa, (struct sigaction*) NULL);
	sigaction(SIGQUIT, &sa, (struct sigaction*) NULL);
	sigaction(SIGBUS,  &sa, (struct sigaction*) NULL);
	sigaction(SIGSEGV, &sa, (struct sigaction*) NULL);
	sigaction(SIGTERM, &sa, (struct sigaction*) NULL);

	int iRet = 0;

	try {
		iRet = pZNC->Loop();
	} catch (CException e) {
		// EX_Shutdown is thrown to exit
		switch (e.GetType()) {
			case CException::EX_Shutdown:
				iRet = 0;
			default:
				iRet = 1;
		}
	}

	delete pZNC;

	return iRet;
}
<|endoftext|>


<commit_before>c326efee-ad58-11e7-88c2-ac87a332f658<commit_msg>this is my first commit?<commit_after>c38e58a1-ad58-11e7-bc79-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int main(int argc,char * argv){
	return 0;
}

<commit_msg>I1 & I2 inputs added<commit_after>/* vim: set tabstop=4 autoindent: */

#include <iostream>

using namespace std;

int main(int argc,char * argv){
	uint32_t i1 = 0; //Number of works
	float i2 = 0.0f; //Concurrency of works range from 0.0 to 1.0
	cout<<"Enter I1(number of works): ";
	cin>>i1;
	cout<<endl;
	cout<<"Enter 2(Concurreny constant)(0-1): ";
	cin>>i2;
	cout<<endl;
	return 0;
}

<|endoftext|>


<commit_before>e0eac64f-2747-11e6-bed9-e0f84713e7b8<commit_msg>I'm done<commit_after>e0fcee47-2747-11e6-8697-e0f84713e7b8<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_COLLISION_BARYCENTRICPENALITYCONTACT_INL
#define SOFA_COMPONENT_COLLISION_BARYCENTRICPENALITYCONTACT_INL

#include <SofaMeshCollision/BarycentricPenalityContact.h>
#include <sofa/core/visual/VisualParams.h>
#include <SofaMeshCollision/RigidContactMapper.inl>

namespace sofa
{

namespace component
{

namespace collision
{

using namespace sofa::defaulttype;
using namespace core::collision;

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::BarycentricPenalityContact(CollisionModel1* _model1, CollisionModel2* _model2, Intersection* _intersectionMethod)
    : model1(_model1), model2(_model2), intersectionMethod(_intersectionMethod), ff(NULL), parent(NULL)
{
    mapper1.setCollisionModel(model1);
    mapper2.setCollisionModel(model2);
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::~BarycentricPenalityContact()
{
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::cleanup()
{
    if (ff!=NULL)
    {
        ff->cleanup();
        if (parent!=NULL) parent->removeObject(ff);
        //delete ff;
        parent = NULL;
        ff = NULL;
        mapper1.cleanup();
        mapper2.cleanup();
    }
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::setDetectionOutputs(OutputVector* o)
{
    TOutputVector& outputs = *static_cast<TOutputVector*>(o);
    const bool printLog = this->f_printLog.getValue();
    if (ff==NULL)
    {
        MechanicalState1* mstate1 = mapper1.createMapping();
        MechanicalState2* mstate2 = mapper2.createMapping();
        ff = sofa::core::objectmodel::New<ResponseForceField>(mstate1,mstate2);
        ff->setName( getName() );
        setInteractionTags(mstate1, mstate2);
        ff->init();
#ifdef SOFA_SMP
        ff->setPartition(mstate1->getPartition());
#endif

    }

    int insize = outputs.size();

    // old index for each contact
    // >0 indicate preexisting contact
    // 0  indicate new contact
    // -1 indicate ignored duplicate contact
    std::vector<int> oldIndex(insize);

    int nbnew = 0;

    for (int i=0; i<insize; i++)
    {
        DetectionOutput* o = &outputs[i];
        // find this contact in contactIndex, possibly creating a new entry initialized by 0
        int& index = contactIndex[o->id];
        if (index < 0) // duplicate contact
        {
            int i2 = -1-index;
            DetectionOutput* o2 = &outputs[i2];
            if (o2->value <= o->value)
            {
                // current contact is ignored
                oldIndex[i] = -1;
                continue;
            }
            else
            {
                // previous contact is replaced
                oldIndex[i] = oldIndex[i2];
                oldIndex[i2] = -1;
            }
        }
        else
        {
            oldIndex[i] = index;
            if (!index)
            {
                ++nbnew;
                if (printLog) sout << "BarycentricPenalityContact: New contact "<<o->id<<sendl;
            }
        }
        index = -1-i; // save this index as a negative value in contactIndex map.
    }

    // compute new index of each contact
    std::vector<int> newIndex(insize);
    // number of final contacts used in the response
    int size = 0;
    for (int i=0; i<insize; i++)
    {
        if (oldIndex[i] >= 0)
        {
            ++size;
            newIndex[i] = size;
        }
    }

    // update contactMap
    for (ContactIndexMap::iterator it = contactIndex.begin(), itend = contactIndex.end(); it != itend; )
    {
        int& index = it->second;
        if (index >= 0)
        {
            if (printLog) sout << "BarycentricPenalityContact: Removed contact "<<it->first<<sendl;
            ContactIndexMap::iterator oldit = it;
            ++it;
            contactIndex.erase(oldit);
        }
        else
        {
            index = newIndex[-1-index]; // write the final contact index
            ++it;
        }
    }
    if (printLog) sout << "BarycentricPenalityContact: "<<insize<<" input contacts, "<<size<<" contacts used for response ("<<nbnew<<" new)."<<sendl;

    //int size = contacts.size();
    ff->clear(size);
    mapper1.resize(size);
    mapper2.resize(size);
    //int i = 0;
    const double d0 = intersectionMethod->getContactDistance() + model1->getProximity() + model2->getProximity(); // - 0.001;
    //for (std::vector<DetectionOutput>::iterator it = outputs.begin(); it!=outputs.end(); it++)
    //{
    //    DetectionOutput* o = &*it;
    for (int i=0; i<insize; i++)
    {
        int index = oldIndex[i];
        if (index < 0) continue; // this contact is ignored
        DetectionOutput* o = &outputs[i];
        CollisionElement1 elem1(o->elem.first);
        CollisionElement2 elem2(o->elem.second);
        int index1 = elem1.getIndex();
        int index2 = elem2.getIndex();
        typename DataTypes1::Real r1 = 0.0;
        typename DataTypes2::Real r2 = 0.0;

        // Just make it work, some changes have been done in rev 10382 so that BarycentricPenaltyContact doesn't
        // map well the contact points because o->baryCoords is used ant not initialized. It means that
        // the mapped contact point is random ! So I replaced addPointB by addPoint to make it work.
        // Create mapping for first point
//        index1 = mapper1.addPointB(o->point[0], index1, r1
//#ifdef DETECTIONOUTPUT_BARYCENTRICINFO
//                , o->baryCoords[0]
//#endif
//                                  );

        index1 = mapper1.addPoint(o->point[0], index1, r1);

        // Create mapping for second point
//        index2 = mapper2.addPointB(o->point[1], index2, r2
//#ifdef DETECTIONOUTPUT_BARYCENTRICINFO
//                , o->baryCoords[1]
//#endif
//                                  );

        index2 = mapper2.addPoint(o->point[1], index2, r2);

        double distance = d0 + r1 + r2;
        double stiffness = (elem1.getContactStiffness() * elem2.getContactStiffness());
        if (distance != 0.0) stiffness /= distance;

        double mu_v = (elem1.getContactFriction() + elem2.getContactFriction());
        ff->addContact(index1, index2, elem1.getIndex(), elem2.getIndex(), o->normal, distance, stiffness, mu_v/* *distance */, mu_v, index);
    }
    // Update mappings
    mapper1.update();
    mapper2.update();
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::createResponse(core::objectmodel::BaseContext* group)
{
    if (ff!=NULL)
    {
        if (parent!=NULL)
        {
            parent->removeObject(this);
            parent->removeObject(ff);
        }
        parent = group;
        if (parent!=NULL)
        {
            //sout << "Attaching contact response to "<<parent->getName()<<sendl;
            parent->addObject(this);
            parent->addObject(ff);
        }
    }
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::removeResponse()
{
    if (ff!=NULL)
    {
        if (parent!=NULL)
        {
            //sout << "Removing contact response from "<<parent->getName()<<sendl;
            parent->removeObject(this);
            parent->removeObject(ff);
        }
        parent = NULL;
    }
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::draw(const core::visual::VisualParams* )
{
    //	if (ff!=NULL)
    //		ff->draw(vparams);
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::setInteractionTags(MechanicalState1* mstate1, MechanicalState2* mstate2)
{
    TagSet tagsm1 = mstate1->getTags();
    TagSet tagsm2 = mstate2->getTags();
    TagSet::iterator it;
    for(it=tagsm1.begin(); it != tagsm1.end(); it++)
        ff->addTag(*it);
    for(it=tagsm2.begin(); it!=tagsm2.end(); it++)
        ff->addTag(*it);
}

} // namespace collision

} // namespace component

} // namespace sofa

#endif

<commit_msg>FIX: SofaMeshCollision compilation<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_COLLISION_BARYCENTRICPENALITYCONTACT_INL
#define SOFA_COMPONENT_COLLISION_BARYCENTRICPENALITYCONTACT_INL

#include <SofaMeshCollision/BarycentricPenalityContact.h>
#include <sofa/core/visual/VisualParams.h>
#include <SofaMeshCollision/RigidContactMapper.inl>

namespace sofa
{

namespace component
{

namespace collision
{

using namespace sofa::defaulttype;
using namespace core::collision;

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::BarycentricPenalityContact(CollisionModel1* _model1, CollisionModel2* _model2, Intersection* _intersectionMethod)
    : model1(_model1), model2(_model2), intersectionMethod(_intersectionMethod), ff(NULL), parent(NULL)
{
    mapper1.setCollisionModel(model1);
    mapper2.setCollisionModel(model2);
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::~BarycentricPenalityContact()
{
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::cleanup()
{
    if (ff!=NULL)
    {
        ff->cleanup();
        if (parent!=NULL) parent->removeObject(ff);
        //delete ff;
        parent = NULL;
        ff = NULL;
        mapper1.cleanup();
        mapper2.cleanup();
    }
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::setDetectionOutputs(OutputVector* o)
{
    TOutputVector& outputs = *static_cast<TOutputVector*>(o);
    const bool printLog = this->f_printLog.getValue();
    if (ff==NULL)
    {
        MechanicalState1* mstate1 = mapper1.createMapping();
        MechanicalState2* mstate2 = mapper2.createMapping();
        ff = sofa::core::objectmodel::New<ResponseForceField>(mstate1,mstate2);
        ff->setName( getName() );
        setInteractionTags(mstate1, mstate2);
        ff->init();
#ifdef SOFA_SMP
        ff->setPartition(mstate1->getPartition());
#endif

    }

    int insize = outputs.size();

    // old index for each contact
    // >0 indicate preexisting contact
    // 0  indicate new contact
    // -1 indicate ignored duplicate contact
    std::vector<int> oldIndex(insize);

    int nbnew = 0;

    for (int i=0; i<insize; i++)
    {
        DetectionOutput* o = &outputs[i];
        // find this contact in contactIndex, possibly creating a new entry initialized by 0
        int& index = contactIndex[o->id];
        if (index < 0) // duplicate contact
        {
            int i2 = -1-index;
            DetectionOutput* o2 = &outputs[i2];
            if (o2->value <= o->value)
            {
                // current contact is ignored
                oldIndex[i] = -1;
                continue;
            }
            else
            {
                // previous contact is replaced
                oldIndex[i] = oldIndex[i2];
                oldIndex[i2] = -1;
            }
        }
        else
        {
            oldIndex[i] = index;
            if (!index)
            {
                ++nbnew;
                if (printLog) sout << "BarycentricPenalityContact: New contact "<<o->id<<sendl;
            }
        }
        index = -1-i; // save this index as a negative value in contactIndex map.
    }

    // compute new index of each contact
    std::vector<int> newIndex(insize);
    // number of final contacts used in the response
    int size = 0;
    for (int i=0; i<insize; i++)
    {
        if (oldIndex[i] >= 0)
        {
            ++size;
            newIndex[i] = size;
        }
    }

    // update contactMap
    for (ContactIndexMap::iterator it = contactIndex.begin(), itend = contactIndex.end(); it != itend; )
    {
        int& index = it->second;
        if (index >= 0)
        {
            if (printLog) sout << "BarycentricPenalityContact: Removed contact "<<it->first<<sendl;
            ContactIndexMap::iterator oldit = it;
            ++it;
            contactIndex.erase(oldit);
        }
        else
        {
            index = newIndex[-1-index]; // write the final contact index
            ++it;
        }
    }
    if (printLog) sout << "BarycentricPenalityContact: "<<insize<<" input contacts, "<<size<<" contacts used for response ("<<nbnew<<" new)."<<sendl;

    //int size = contacts.size();
    ff->clear(size);
    mapper1.resize(size);
    mapper2.resize(size);
    //int i = 0;
    const double d0 = intersectionMethod->getContactDistance() + model1->getProximity() + model2->getProximity(); // - 0.001;
    //for (std::vector<DetectionOutput>::iterator it = outputs.begin(); it!=outputs.end(); it++)
    //{
    //    DetectionOutput* o = &*it;
    for (int i=0; i<insize; i++)
    {
        int index = oldIndex[i];
        if (index < 0) continue; // this contact is ignored
        DetectionOutput* o = &outputs[i];
        CollisionElement1 elem1(o->elem.first);
        CollisionElement2 elem2(o->elem.second);
        int index1 = elem1.getIndex();
        int index2 = elem2.getIndex();
        typename DataTypes1::Real r1 = 0.0;
        typename DataTypes2::Real r2 = 0.0;

        // Just make it work, some changes have been done in rev 10382 so that BarycentricPenaltyContact doesn't
        // map well the contact points because o->baryCoords is used ant not initialized. It means that
        // the mapped contact point is random ! So I replaced addPointB by addPoint to make it work.
        // Create mapping for first point
//        index1 = mapper1.addPointB(o->point[0], index1, r1
//#ifdef DETECTIONOUTPUT_BARYCENTRICINFO
//                , o->baryCoords[0]
//#endif
//                                  );

        index1 = mapper1.addPoint(o->point[0], index1, r1);

        // Create mapping for second point
//        index2 = mapper2.addPointB(o->point[1], index2, r2
//#ifdef DETECTIONOUTPUT_BARYCENTRICINFO
//                , o->baryCoords[1]
//#endif
//                                  );

        index2 = mapper2.addPoint(o->point[1], index2, r2);

        double distance = d0 + r1 + r2;
        double stiffness = (elem1.getContactStiffness() * elem2.getContactStiffness());
        if (distance != 0.0) stiffness /= distance;

        double mu_v = (elem1.getContactFriction() + elem2.getContactFriction());
        ff->addContact(index1, index2, elem1.getIndex(), elem2.getIndex(), o->normal, distance, stiffness, mu_v/* *distance */, mu_v, index);
    }
    // Update mappings
    mapper1.update();
    mapper2.update();
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::createResponse(core::objectmodel::BaseContext* group)
{
    if (ff!=NULL)
    {
        if (parent!=NULL)
        {
            parent->removeObject(this);
            parent->removeObject(ff);
        }
        parent = group;
        if (parent!=NULL)
        {
            //sout << "Attaching contact response to "<<parent->getName()<<sendl;
            parent->addObject(this);
            parent->addObject(ff);
        }
    }
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::removeResponse()
{
    if (ff!=NULL)
    {
        if (parent!=NULL)
        {
            //sout << "Removing contact response from "<<parent->getName()<<sendl;
            parent->removeObject(this);
            parent->removeObject(ff);
        }
        parent = NULL;
    }
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::draw(const core::visual::VisualParams* )
{
    //	if (ff!=NULL)
    //		ff->draw(vparams);
}

template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::setInteractionTags(MechanicalState1* mstate1, MechanicalState2* mstate2)
{
    sofa::core::objectmodel::TagSet tagsm1 = mstate1->getTags();
    sofa::core::objectmodel::TagSet tagsm2 = mstate2->getTags();
    sofa::core::objectmodel::TagSet::iterator it;
    for(it=tagsm1.begin(); it != tagsm1.end(); it++)
        ff->addTag(*it);
    for(it=tagsm2.begin(); it!=tagsm2.end(); it++)
        ff->addTag(*it);
}

} // namespace collision

} // namespace component

} // namespace sofa

#endif

<|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h> // getopt

#include "Maze.h"
#include "MazeDefinitions.h"
#include "PathFinder.h"

/**
 * Demo of a PathFinder implementation.
 *
 * Do not use a left/right wall following algorithm, as most
 * Micromouse mazes are designed for such algorithms to fail.
 */
class LeftWallFollower : public PathFinder {
public:
    LeftWallFollower(bool shouldPause = false) : pause(shouldPause) {}

    MouseMovement nextMovement(unsigned x, unsigned y, const Maze &maze) {
        const bool frontWall = maze.wallInFront();
        const bool leftWall  = maze.wallOnLeft();

        // Pause at each cell if the user requests it.
        // It allows for better viewing on command line.
        if(pause) {
            std::cout << "Hit enter to continue..." << std::endl;
            std::cin.ignore(10000, '\n');
            std::cin.clear();
        }

        std::cout << maze.draw() << std::endl << std::endl;

        // If we somehow miraculously hit the center
        // of the maze, just terminate and celebrate!
        if(isAtCenter(x, y)) {
            return Finish;
        }

        // If we hit the start of the maze a second time, then
        // we couldn't find the center and never will...
        if(x == 0 && y == 0) {
            if(visitedStart) {
                return Finish;
            } else {
                visitedStart = true;
            }
        }

        // If we have just turned left, we should take that path!
        if(!frontWall && shouldGoForward) {
            shouldGoForward = false;
            return MoveForward;
        }

        // As long as nothing is in front and we have
        // a wall to our left, keep going forward!
        if(!frontWall && leftWall) {
            shouldGoForward = false;
            return MoveForward;
        }

        // If our forward and left paths are blocked
        // we should try going to the right!
        if(frontWall && leftWall) {
            shouldGoForward = false;
            return TurnClockwise;
        }

        // Lastly, if there is no left wall we should take that path!
        if(!leftWall) {
            shouldGoForward = true;
            return TurnCounterClockwise;
        }

        // If we get stuck somehow, just terminate.
        return Finish;
    }

protected:
    // Helps us determine that we should go forward if we have just turned left.
    bool shouldGoForward = false;

    // Helps us determine if we've made a loop around the maze without finding the center.
    bool visitedStart = false;

    // Indicates we should pause before moving to next cell.
    // Useful for command line usage.
    bool pause = false;

    bool isAtCenter(unsigned x, unsigned y) const {
        unsigned midpoint = MazeDefinitions::MAZE_LEN / 2;

        if(MazeDefinitions::MAZE_LEN % 2 != 0) {
            return x == midpoint && y == midpoint;
        }

        return  (x == midpoint     && y == midpoint    ) ||
        (x == midpoint - 1 && y == midpoint    ) ||
        (x == midpoint     && y == midpoint - 1) ||
        (x == midpoint - 1 && y == midpoint - 1);
    }
};

int main(int argc, char * argv[]) {
    MazeDefinitions::MazeEncodingName mazeName = MazeDefinitions::MAZE_CAMM_2012;
    bool pause = false;

    int opt;
    opterr = 0;

    while((opt = getopt(argc, argv, "m:ph")) != -1) {
        switch(opt) {
            case 'm': {
                int mazeOption = atoi(optarg);
                if(mazeOption < MazeDefinitions::MAZE_NAME_MAX && mazeOption > 0) {
                    mazeName = (MazeDefinitions::MazeEncodingName)mazeOption;
                }
                break;
            }

            case 'p':
                pause = true;
                break;

            case 'h':
            default:
                std::cout << "Usage: " << argv[0] << " [-m N] [-p]" << std::endl;
                std::cout << "\t-m N will load the maze corresponding to N, or 0 if invalid N or missing option" << std::endl;
                std::cout << "\t-p will wait for a newline in between cell traversals" << std::endl;
                return -1;
        }
    }

    LeftWallFollower leftWallFollower(pause);
    Maze maze(mazeName, &leftWallFollower);
    std::cout << maze.draw() << std::endl << std::endl;

    maze.start();
    std::cout << maze.draw() << std::endl << std::endl;
}
<commit_msg>Add a few diagnostic message to the demo<commit_after>#include <iostream>
#include <unistd.h> // getopt

#include "Maze.h"
#include "MazeDefinitions.h"
#include "PathFinder.h"

/**
 * Demo of a PathFinder implementation.
 *
 * Do not use a left/right wall following algorithm, as most
 * Micromouse mazes are designed for such algorithms to fail.
 */
class LeftWallFollower : public PathFinder {
public:
    LeftWallFollower(bool shouldPause = false) : pause(shouldPause) {}

    MouseMovement nextMovement(unsigned x, unsigned y, const Maze &maze) {
        const bool frontWall = maze.wallInFront();
        const bool leftWall  = maze.wallOnLeft();

        // Pause at each cell if the user requests it.
        // It allows for better viewing on command line.
        if(pause) {
            std::cout << "Hit enter to continue..." << std::endl;
            std::cin.ignore(10000, '\n');
            std::cin.clear();
        }

        std::cout << maze.draw() << std::endl << std::endl;

        // If we somehow miraculously hit the center
        // of the maze, just terminate and celebrate!
        if(isAtCenter(x, y)) {
            std::cout << "Found center! Good enough for the demo, won't try to get back." << std::endl;
            return Finish;
        }

        // If we hit the start of the maze a second time, then
        // we couldn't find the center and never will...
        if(x == 0 && y == 0) {
            if(visitedStart) {
                std::cout << "Unable to find center, giving up." << std::endl;
                return Finish;
            } else {
                visitedStart = true;
            }
        }

        // If we have just turned left, we should take that path!
        if(!frontWall && shouldGoForward) {
            shouldGoForward = false;
            return MoveForward;
        }

        // As long as nothing is in front and we have
        // a wall to our left, keep going forward!
        if(!frontWall && leftWall) {
            shouldGoForward = false;
            return MoveForward;
        }

        // If our forward and left paths are blocked
        // we should try going to the right!
        if(frontWall && leftWall) {
            shouldGoForward = false;
            return TurnClockwise;
        }

        // Lastly, if there is no left wall we should take that path!
        if(!leftWall) {
            shouldGoForward = true;
            return TurnCounterClockwise;
        }

        // If we get stuck somehow, just terminate.
        std::cout << "Got stuck..." << std::endl;
        return Finish;
    }

protected:
    // Helps us determine that we should go forward if we have just turned left.
    bool shouldGoForward = false;

    // Helps us determine if we've made a loop around the maze without finding the center.
    bool visitedStart = false;

    // Indicates we should pause before moving to next cell.
    // Useful for command line usage.
    bool pause = false;

    bool isAtCenter(unsigned x, unsigned y) const {
        unsigned midpoint = MazeDefinitions::MAZE_LEN / 2;

        if(MazeDefinitions::MAZE_LEN % 2 != 0) {
            return x == midpoint && y == midpoint;
        }

        return  (x == midpoint     && y == midpoint    ) ||
        (x == midpoint - 1 && y == midpoint    ) ||
        (x == midpoint     && y == midpoint - 1) ||
        (x == midpoint - 1 && y == midpoint - 1);
    }
};

int main(int argc, char * argv[]) {
    MazeDefinitions::MazeEncodingName mazeName = MazeDefinitions::MAZE_CAMM_2012;
    bool pause = false;

    int opt;
    opterr = 0;

    while((opt = getopt(argc, argv, "m:ph")) != -1) {
        switch(opt) {
            case 'm': {
                int mazeOption = atoi(optarg);
                if(mazeOption < MazeDefinitions::MAZE_NAME_MAX && mazeOption > 0) {
                    mazeName = (MazeDefinitions::MazeEncodingName)mazeOption;
                }
                break;
            }

            case 'p':
                pause = true;
                break;

            case 'h':
            default:
                std::cout << "Usage: " << argv[0] << " [-m N] [-p]" << std::endl;
                std::cout << "\t-m N will load the maze corresponding to N, or 0 if invalid N or missing option" << std::endl;
                std::cout << "\t-p will wait for a newline in between cell traversals" << std::endl;
                return -1;
        }
    }

    LeftWallFollower leftWallFollower(pause);
    Maze maze(mazeName, &leftWallFollower);
    std::cout << maze.draw() << std::endl << std::endl;

    maze.start();
}
<|endoftext|>


<commit_before>#include <iostream>
#include "include/matrix.h" //

using namespace std;

int main(){

	// New matrix, size: 10x10
	matrix<int> m(10, 10);

	// Inserts a value on the specified position and shows its content
	m[0][2] = 95;
	cout << m[0][2] << endl;

	// Makes the matrix bigger
	m.resize(20, 20);

	// Inserts a new value and shows its value
	m[11][8] = 100;
	cout << m[0][2] << ' ' << m[11][8] <<  endl;

	// Copy constructor
	matrix<int> m2(m);
	cout << m[11][8] << endl;

	// pauses the program (optional)
	cin.ignore();

	return 0;
}<commit_msg>Added files via upload<commit_after>#include <iostream>
#include "include/matrix.h"

using namespace std;

int main(){

	// New matrix, size: 10x10
	matrix<int> m(10, 10);

	// Inserts a value on the specified position and shows its content
	m[0][2] = 95;
	cout << m[0][2] << endl;

	// Makes the matrix bigger
	m.resize(20, 20);

	// Inserts a new value and shows its value
	m[11][8] = 100;
	cout << m[0][2] << ' ' << m[11][8] <<  endl;

	// Copy constructor
	matrix<int> m2(m);
	cout << m[11][8] << endl;

	// New Empty matrix
	matrix<bool> test;

	// Resize the empty matrix
	test.resize(10, 10);

	// Inserts new value and show its content
	test[5][5] = 1;
	cout << test[5][5] << endl;

	// pauses the program (optional)
	cin.ignore();

	return 0;
}<|endoftext|>


<commit_before>75c33570-2749-11e6-a768-e0f84713e7b8<commit_msg>new flies<commit_after>75d5e940-2749-11e6-bdbd-e0f84713e7b8<|endoftext|>


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

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

		sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
		sf::CircleShape shape(100.f);
		shape.setFillColor(sf::Color::Green);

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

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

		return 0;
	}
<commit_msg>prout<commit_after>#include <iostream>
#include <SFML/Graphics.hpp>

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

		sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
		sf::CircleShape shape(100.f);
		shape.setFillColor(sf::Color::Green);

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

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

		prout;

		return 0;
	}
<|endoftext|>


<commit_before>de1127f3-ad58-11e7-b156-ac87a332f658<commit_msg>fix for the previous fix<commit_after>de70df4f-ad58-11e7-a80e-ac87a332f658<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   main.cpp
 * Author: aybar
 *
 * Created on September 14, 2017, 4:59 PM
 */

#include <iostream>
#include <map>
#include <fstream> // Para archivo
#include <string>
#include <cstring>
#include "Punto.h"
//-------------------------
using std::cout;
using std::cin;
using std::endl;
using std::toupper;
//-------------------------

enum class Menu {
    AGREGAR = 1, ELIMINAR, BUSCAR
};
// ------------------------
void agregarPunto(Punto&);
void eliminarPunto(Punto&);
void buscarPunto(Punto&);
void guardarPunto();
//------------------------

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

    // Declaraciones para el switch case;
    std::map<unsigned short, Menu> opciones;
    opciones[1] = Menu::AGREGAR;
    opciones[2] = Menu::ELIMINAR;
    opciones[3] = Menu::BUSCAR;
    unsigned short opcion;
    // ---------------------------------------

    char salir;
    bool haSalido = false;
    bool esValida = false; // Valida entradas por teclado.
    Punto punto;
    while (!haSalido) {

        while (!esValida) {
            cout << "\t\tElija la opcion que desea dentro del plano: \n";
            cout << "1. Agregar un punto.\n";
            cout << "2. Eliminar un punto.\n";
            cout << "3. Buscar un punto.\n\n";
            cin >> opcion;

            esValida = opcion >= 1 && opcion <= 3;
            cout << "\n\n";
        }

        try {
            switch (opciones[opcion]) {
                case Menu::AGREGAR:
                    agregarPunto(punto);
                    break;
                case Menu::ELIMINAR:
                    //eliminarPunto(punto);
                    break;
                case Menu::BUSCAR:
                    //buscarPunto(punto);
                    break;
            }
        } catch (std::string e){
            cout << e;
        }

        cout << "\n\n";

        esValida = false;
        while (!esValida) {
            cout << "Desea salir del programa?[S/N]: ";
            cin >> salir;

            salir = toupper(salir); // Convierte a mayuscula la opcion.
            esValida = salir == 'S' || salir == 'N'; // Valida entrada por teclado.
        }

        haSalido = (salir == 'S');

    }

    cout << "Presione ENTER para cerrar el programa...";
    cin.ignore();
    cin.get();

    return 0;
}

void agregarPunto(Punto& punto) {
    int x, y;
    cout << "Ingrese valor de eje x: ";
    cin >> x;

    cout << "Ingrese valor de eje y: ";
    cin >> y;

    if (punto.alta(x, y)) {
        cout << "El punto P(" << x << ", " << y << ") ha sido agregado correctamente." << endl;
    } else {
        throw "El punto P (" + std::to_string(x) + ", " + std::to_string(y) + ")"
                "no fue agregado correctamente. Intente de nuevo. ";
    }

}

void eliminarPunto(Punto& punto) {
    int pos;
    cout << "Ingrese la posicion del elemento que desea eliminar: ";
    cin >> pos;

    if (punto.baja(pos)) {
        cout << "El punto de la posicion " << pos << " del vector ha sido eliminado";
    } else {
        throw "El punto no ha sido eliminado correctamente. Intente otra vez";
    }

}

void buscarPunto(Punto& punto) {
    int i;
    cout << "Ingrese indice de elemento a buscar: ";
    cin >> i;

}

void guardarPunto() {

}<commit_msg>feat: Implementa modularizacion a las opciones del menu.<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   main.cpp
 * Author: aybar
 *
 * Created on September 14, 2017, 4:59 PM
 */

#include <iostream>
#include <map>  // Para coleccionar menu.
#include <fstream> // Para archivo punto.txt.
#include <string>
#include <cctype> // toupper();
#include "Punto.h"
//-------------------------
using std::cout;
using std::cin;
using std::endl;
using std::toupper;
using std::string;
//-------------------------

enum class Menu {
    AGREGAR = 1, ELIMINAR, BUSCAR, SALIR = 0
};
// ------------------------
unsigned short mostrarMenu();
bool haSalido();
void agregarPunto(Punto&);
void eliminarPunto(Punto&);
void buscarPunto(Punto&);
//------------------------

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

    // Opciones a comparar con switch case;
    std::map<unsigned short, Menu> opciones;
    opciones[1] = Menu::AGREGAR;
    opciones[2] = Menu::ELIMINAR;
    opciones[3] = Menu::BUSCAR;
    opciones[0] = Menu::SALIR;
    unsigned short opcion;
    // ---------------------------------------

    Punto punto;
    punto.leer();
    bool haTerminado = false;
    while (!haTerminado) {

        opcion = mostrarMenu();

        try {
            switch (opciones[opcion]) {
                case Menu::AGREGAR:
                    agregarPunto(punto);
                    break;
                case Menu::ELIMINAR:
                    eliminarPunto(punto);
                    break;
                case Menu::BUSCAR:
                    buscarPunto(punto);
                    break;
                default:
                    haTerminado = haSalido();
            }
        } catch (string e) {
            cout << e << endl;
        }

        cout << "\n\n";
        cout << "Presione ENTER para continuar...";
        cin.ignore();
        cin.get();
        cout << "\n\n";
    }

    return 0;
}

unsigned short mostrarMenu() {
    unsigned short opcion;
    const unsigned short SALIR = 0;
    const unsigned short ULTIMA = 4;
    bool esValida = false;
    while (!esValida) {
        cout << "\t\tElija la opcion que desea dentro del plano: \n";
        cout << "1. Agregar un punto.\n";
        cout << "2. Eliminar un punto.\n";
        cout << "3. Buscar un punto.\n";
        cout << "0. Salir.\n\n";
        cin >> opcion;

        esValida = opcion >= SALIR && opcion <= ULTIMA;
        cout << "\n\n";
    }

    return opcion;
}

bool haSalido() {
    char salir;
    bool esValida = false; // Valida entrada por teclado del siguiente mensaje.
    while (!esValida) {
        cout << "Desea salir del programa?[S/N]: ";
        cin >> salir;

        salir = toupper(salir); // Convierte a mayuscula la opcion.
        esValida = salir == 'S' || salir == 'N'; // Condicion de entrada por teclado.
    }

    return (salir == 'S');

}

void agregarPunto(Punto& punto) {
    int x, y;
    cout << "Ingrese valor de eje x: ";
    cin >> x;

    cout << "Ingrese valor de eje y: ";
    cin >> y;

    if (punto.alta(x, y)) {
        cout << "El punto P(" << x << ", " << y << ") ha sido agregado correctamente." << endl;
    } else {
        throw "El punto P (" + std::to_string(x) + ", " + std::to_string(y) + ")"
                "no fue agregado correctamente. Intente de nuevo. ";
    }

}

void eliminarPunto(Punto& punto) {
    int pos;
    cout << "Ingrese la posicion del elemento que desea eliminar: ";
    cin >> pos;

    int x = punto.buscar(pos).getAbscisa();
    int y = punto.buscar(pos).getOrdenada();

    punto.baja(pos);
    cout << "El punto P(" << x << ", " << y << ") del vector ha sido eliminado";

}

void buscarPunto(Punto& punto) {
    unsigned i;
    cout << "Ingrese indice de elemento a buscar : [0-n]";
    cin >> i;

    Punto p = punto.buscar(i);

    string x = std::to_string(p.getAbscisa());
    string y = std::to_string(p.getOrdenada());
    cout << "El punto #" << i << "  del vector corresponde al punto P(" + x + ", " + y + ")\n";

}
<|endoftext|>


<commit_before>d4bf0a6e-4b02-11e5-8594-28cfe9171a43<commit_msg>fix for the previous fix<commit_after>d4d1aa7a-4b02-11e5-8f2f-28cfe9171a43<|endoftext|>


<commit_before>80e233f8-4b02-11e5-97f3-28cfe9171a43<commit_msg>Hey we can now do a thing<commit_after>80ef941c-4b02-11e5-a603-28cfe9171a43<|endoftext|>


<commit_before>77913202-4b02-11e5-aa93-28cfe9171a43<commit_msg>Really doesn't crash if X, now<commit_after>77a04a6e-4b02-11e5-ae4a-28cfe9171a43<|endoftext|>


<commit_before>dbd8d95e-4b02-11e5-9f1c-28cfe9171a43<commit_msg>Really doesn't crash if X, now<commit_after>dbe588cc-4b02-11e5-8821-28cfe9171a43<|endoftext|>


<commit_before>df0a78d9-ad59-11e7-a951-ac87a332f658<commit_msg>For bobby to integrate at some point<commit_after>df82ddf3-ad59-11e7-8000-ac87a332f658<|endoftext|>


<commit_before>// Farneback dense optical flow calculate and show in Munsell system of colors
// Author : Zouxy
// Date   : 2013-3-15
// HomePage : http://blog.csdn.net/zouxy09
// Email  : zouxy09@qq.com

// API calcOpticalFlowFarneback() comes from OpenCV, and this
// 2D dense optical flow algorithm from the following paper:
// Gunnar Farneback. "Two-Frame Motion Estimation Based on Polynomial Expansion".
// And the OpenCV source code locate in ..\opencv2.4.3\modules\video\src\optflowgf.cpp

#include <iostream>
#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;

#define UNKNOWN_FLOW_THRESH 1e9

// Color encoding of flow vectors from:
// http://members.shaw.ca/quadibloc/other/colint.htm
// This code is modified from:
// http://vision.middlebury.edu/flow/data/

Mat computeSalMap(Mat& flow, Mat& gray)
{
	Mat result = gray;

	for ( int i = 0; i < flow.rows; i++)
	{
		for (int j = 0; j < flow.cols; j++)
		{
			float f1 = flow.ptr<float>(i)[2 * j]; // first channel
			float f2 = flow.ptr<float>(i)[2 * j + 1]; // second channel
			uchar f3 = uchar(sqrt(f1*f1 + f2*f2) / 255);
			result.at<uchar>(i, j) = f3;
		}
	}
	return result;
}

void makecolorwheel(vector<Scalar> &colorwheel)
{
	int RY = 15;
	int YG = 6;
	int GC = 4;
	int CB = 11;
	int BM = 13;
	int MR = 6;

	int i;

	for (i = 0; i < RY; i++) colorwheel.push_back(Scalar(255, 255 * i / RY, 0));
	for (i = 0; i < YG; i++) colorwheel.push_back(Scalar(255 - 255 * i / YG, 255, 0));
	for (i = 0; i < GC; i++) colorwheel.push_back(Scalar(0, 255, 255 * i / GC));
	for (i = 0; i < CB; i++) colorwheel.push_back(Scalar(0, 255 - 255 * i / CB, 255));
	for (i = 0; i < BM; i++) colorwheel.push_back(Scalar(255 * i / BM, 0, 255));
	for (i = 0; i < MR; i++) colorwheel.push_back(Scalar(255, 0, 255 - 255 * i / MR));
}

void motionToColor(Mat flow, Mat &color)
{
	if (color.empty())
		color.create(flow.rows, flow.cols, CV_8UC3);

	static vector<Scalar> colorwheel; //Scalar r,g,b
	if (colorwheel.empty())
		makecolorwheel(colorwheel);

	// determine motion range:
	float maxrad = -1;

	// Find max flow to normalize fx and fy
	for (int i = 0; i < flow.rows; ++i)
	{
		for (int j = 0; j < flow.cols; ++j)
		{
			Vec2f flow_at_point = flow.at<Vec2f>(i, j);
			float fx = flow_at_point[0];
			float fy = flow_at_point[1];
			if ((fabs(fx) >  UNKNOWN_FLOW_THRESH) || (fabs(fy) >  UNKNOWN_FLOW_THRESH))
				continue;
			float rad = sqrt(fx * fx + fy * fy);
			maxrad = maxrad > rad ? maxrad : rad;
		}
	}

	for (int i = 0; i < flow.rows; ++i)
	{
		for (int j = 0; j < flow.cols; ++j)
		{
			uchar *data = color.data + color.step[0] * i + color.step[1] * j;
			Vec2f flow_at_point = flow.at<Vec2f>(i, j);

			float fx = flow_at_point[0] / maxrad;
			float fy = flow_at_point[1] / maxrad;
			if ((fabs(fx) >  UNKNOWN_FLOW_THRESH) || (fabs(fy) >  UNKNOWN_FLOW_THRESH))
			{
				data[0] = data[1] = data[2] = 0;
				continue;
			}
			float rad = sqrt(fx * fx + fy * fy);

			float angle = atan2(-fy, -fx) / CV_PI;
			float fk = (angle + 1.0) / 2.0 * (colorwheel.size() - 1);
			int k0 = (int)fk;
			int k1 = (k0 + 1) % colorwheel.size();
			float f = fk - k0;
			//f = 0; // uncomment to see original color wheel

			for (int b = 0; b < 3; b++)
			{
				float col0 = colorwheel[k0][b] / 255.0;
				float col1 = colorwheel[k1][b] / 255.0;
				float col = (1 - f) * col0 + f * col1;
				if (rad <= 1)
					col = 1 - rad * (1 - col); // increase saturation with radius
				else
					col *= .75; // out of range
				data[2 - b] = (int)(255.0 * col);
			}
		}
	}
}

int main(int, char**)
{
	VideoCapture cap;
	//cap.open(0);
	cap.open("test.mp4");

	if (!cap.isOpened())
		return -1;

	Mat prevgray, gray, flow, cflow, frame;
	namedWindow("flow", 1);
	namedWindow("flow_raw", 1);

	Mat motion2color;

	for (;;)
	{
		double t = (double)cvGetTickCount();

		cap >> frame;
		cvtColor(frame, gray, CV_BGR2GRAY);
		imshow("original", frame);

		if (prevgray.data)
		{
			calcOpticalFlowFarneback(prevgray, gray, flow, 0.5, 3, 15, 3, 5, 1.2, 0);
			Mat flow_result = computeSalMap(flow, gray);
			imshow("flow_raw", flow_result);
			motionToColor(flow, motion2color);
			imshow("flow", motion2color);
		}
		if (waitKey(10) >= 0)
			break;
		std::swap(prevgray, gray);

		t = (double)cvGetTickCount() - t;
		cout << "cost time: " << t / ((double)cvGetTickFrequency()*1000.) << endl;
	}
	return 0;
}

<commit_msg>sal_map done<commit_after>// Farneback dense optical flow calculate and show in Munsell system of colors
// Author : Zouxy
// Date   : 2013-3-15
// HomePage : http://blog.csdn.net/zouxy09
// Email  : zouxy09@qq.com

// API calcOpticalFlowFarneback() comes from OpenCV, and this
// 2D dense optical flow algorithm from the following paper:
// Gunnar Farneback. "Two-Frame Motion Estimation Based on Polynomial Expansion".
// And the OpenCV source code locate in ..\opencv2.4.3\modules\video\src\optflowgf.cpp

#include <iostream>
#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;

#define UNKNOWN_FLOW_THRESH 1e9

// Color encoding of flow vectors from:
// http://members.shaw.ca/quadibloc/other/colint.htm
// This code is modified from:
// http://vision.middlebury.edu/flow/data/

Mat computeSalMap(Mat flow, Mat gray)
{
	Mat result(gray.size(), CV_32FC1);

	for ( int i = 0; i < flow.rows; i++)
	{
		for (int j = 0; j < flow.cols; j++)
		{
			float f1 = flow.ptr<float>(i, j)[0]; // first channel
			float f2 = flow.ptr<float>(i, j)[1]; // second channel
			float f3 = sqrt(f1*f1*100 + f2*f2*100) / 255;
			result.at<float>(i, j) = f3;
		}
	}
	return result;
}

void makecolorwheel(vector<Scalar> &colorwheel)
{
	int RY = 15;
	int YG = 6;
	int GC = 4;
	int CB = 11;
	int BM = 13;
	int MR = 6;

	int i;

	for (i = 0; i < RY; i++) colorwheel.push_back(Scalar(255, 255 * i / RY, 0));
	for (i = 0; i < YG; i++) colorwheel.push_back(Scalar(255 - 255 * i / YG, 255, 0));
	for (i = 0; i < GC; i++) colorwheel.push_back(Scalar(0, 255, 255 * i / GC));
	for (i = 0; i < CB; i++) colorwheel.push_back(Scalar(0, 255 - 255 * i / CB, 255));
	for (i = 0; i < BM; i++) colorwheel.push_back(Scalar(255 * i / BM, 0, 255));
	for (i = 0; i < MR; i++) colorwheel.push_back(Scalar(255, 0, 255 - 255 * i / MR));
}

void motionToColor(Mat flow, Mat &color)
{
	if (color.empty())
		color.create(flow.rows, flow.cols, CV_8UC3);

	static vector<Scalar> colorwheel; //Scalar r,g,b
	if (colorwheel.empty())
		makecolorwheel(colorwheel);

	// determine motion range:
	float maxrad = -1;

	// Find max flow to normalize fx and fy
	for (int i = 0; i < flow.rows; ++i)
	{
		for (int j = 0; j < flow.cols; ++j)
		{
			Vec2f flow_at_point = flow.at<Vec2f>(i, j);
			float fx = flow_at_point[0];
			float fy = flow_at_point[1];
			if ((fabs(fx) >  UNKNOWN_FLOW_THRESH) || (fabs(fy) >  UNKNOWN_FLOW_THRESH))
				continue;
			float rad = sqrt(fx * fx + fy * fy);
			maxrad = maxrad > rad ? maxrad : rad;
		}
	}

	for (int i = 0; i < flow.rows; ++i)
	{
		for (int j = 0; j < flow.cols; ++j)
		{
			uchar *data = color.data + color.step[0] * i + color.step[1] * j;
			Vec2f flow_at_point = flow.at<Vec2f>(i, j);

			float fx = flow_at_point[0] / maxrad;
			float fy = flow_at_point[1] / maxrad;
			if ((fabs(fx) >  UNKNOWN_FLOW_THRESH) || (fabs(fy) >  UNKNOWN_FLOW_THRESH))
			{
				data[0] = data[1] = data[2] = 0;
				continue;
			}
			float rad = sqrt(fx * fx + fy * fy);

			float angle = atan2(-fy, -fx) / CV_PI;
			float fk = (angle + 1.0) / 2.0 * (colorwheel.size() - 1);
			int k0 = (int)fk;
			int k1 = (k0 + 1) % colorwheel.size();
			float f = fk - k0;
			//f = 0; // uncomment to see original color wheel

			for (int b = 0; b < 3; b++)
			{
				float col0 = colorwheel[k0][b] / 255.0;
				float col1 = colorwheel[k1][b] / 255.0;
				float col = (1 - f) * col0 + f * col1;
				if (rad <= 1)
					col = 1 - rad * (1 - col); // increase saturation with radius
				else
					col *= .75; // out of range
				data[2 - b] = (int)(255.0 * col);
			}
		}
	}
}

int main(int, char**)
{
	VideoCapture cap;
	//cap.open(0);
	cap.open("test.mp4");

	if (!cap.isOpened())
		return -1;

	Mat prevgray, gray, flow, cflow, frame;
	namedWindow("flow", 1);

	Mat motion2color;

	for (;;)
	{
		double t = (double)cvGetTickCount();

		cap >> frame;
		cvtColor(frame, gray, CV_BGR2GRAY);
		imshow("original", frame);

		if (prevgray.data)
		{
			calcOpticalFlowFarneback(prevgray, gray, flow, 0.5, 3, 15, 3, 5, 1.2, 0);
			Mat flow_result = computeSalMap(flow, gray);
			imshow("Sal_Map", flow_result);
			motionToColor(flow, motion2color);
			imshow("flow", motion2color);
		}
		if (waitKey(10) >= 0)
			break;
		std::swap(prevgray, gray);

		t = (double)cvGetTickCount() - t;
		cout << "cost time: " << t / ((double)cvGetTickFrequency()*1000.) << endl;
	}
	return 0;
}

<|endoftext|>


<commit_before>/*
 * Main File for controlling the car vehicle
 * Modified version of vehicle tool with threaded execution and read from file instead of stdin
 */

#include "examples/simple-c-interface/anki-simplified.h"
#include "CV/get_camera.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "C/FlyCapture2_C.h"
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <string>

// Bash colors
#define KNRM  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"
#define KBOLD  "\x1B[1m"
#define RESET "\033[0m"

/**
 * Global variables
 */
static int camera_index; //index for camera update
static int run_index; //index for global simulation update
static int exit_signal = 0;
static pthread_t camera;
static AnkiHandle h;
camera_localization_t* camera_loc;
camera_obst_localization_t* camera_obst;
shared_struct* background;
unsigned char** input_median;

/**
 * Handle keyboard interrupts
 */
static int kbint = 1;
static void intHandler(int sig) {
    fprintf(stderr, "Keyboard interrupt - execute final block\n");
    kbint = 0;
}

/**
 *  Print car's current location
 */
void print_loc(AnkiHandle h){
    localization_t loc;
    loc = anki_s_get_localization(h);
    printf(KBLU "[Location]" RESET " segm: %03x subsegm: %03x clock-wise: %i last-update: %i\n",
	   loc.segm, loc.subsegm, loc.is_clockwise, loc.update_time);
}

/**
 *  Print car's current location (from camera)
 */
void print_camera_loc(){
    if (camera_loc->success) {
	printf(KBOLD KGRN "[Camera location]" RESET " x: %.2f y: %.2f size: %.2f last-update: %i\n",
	       camera_loc->x, camera_loc->y, camera_loc->size, camera_loc->update_time);
    } else {
	float result[2];
	get_camera_lock_dead_reckon(camera_index, result);
	printf(KBOLD KRED "[Camera location (DR)]" RESET " x: %.2f y: %.2f size: %.2f last-update: %i\n", result[0], result[1], camera_loc->size, camera_loc->update_time);
    }
}

/**
 * Get vehicle's location through camera (runs on independent thread)
 */
// Struct type to pass arguments to thread
struct arg_struct {
    const char* vehicle_color;   // Our vehicle's color
	int nobstacles;
    int update;            // Image update (time in millisecond)
    int background_update; // new background every X image updates
    int background_start;  // index of first background computation
    int history;           // nbr of images for bacground computation
    int verbose;           // 0-1: set verbosity level
};

// Main function run on the thread
void* update_camera_loc(void* aux) {
    // Read arguments
    struct arg_struct *args = (struct arg_struct *)aux;
    int img_update = args->update;
    int bg_history = args->history;
    int bg_start = args->background_start;
    int bg_update = args->background_update;
    int verbose = args->verbose;
    const char* car_name = args->vehicle_color;
	int nobstacles = args->nobstacles;

    // Init shared memory
    int shmid;
    key_t key;
    shared_struct *shm;
    key = 192012003; // 1920x1200x3
    const int width = 1696;
    const int height = 720;
    if ((shmid = shmget(key, sizeof(shared_struct), 0666)) < 0) { perror("shmget"); exit(1); }
    if ((shm = (shared_struct*)shmat(shmid, NULL, 0)) == (shared_struct *) -1) { perror("shmat"); exit(1); }

    // Additional Paramaters
    camera_index = 0;
    char filename[256];
    int next_bg_update = bg_start - bg_history;
    shared_struct* temp = (shared_struct*) malloc(sizeof(shared_struct));

    //Init arrays for saving past images for background computation
    int i;
    input_median = (unsigned char**) malloc(sizeof(unsigned char*) * bg_history);
    for (i = 0; i < bg_history; i++) {
	input_median[i] = (unsigned char*) malloc(sizeof(unsigned char) * IMAGE_SIZE);
    }

    /*
     * Update location until receiving exit signal
     */
    while (!exit_signal && kbint) {
	// DEBUG
	if (verbose) {
	    fprintf(stderr, "Index: %d - Next bg update: %d - Current saving index: %d\n", camera_index, next_bg_update  - next_bg_update%bg_update + bg_start, (next_bg_update + bg_history - bg_start) % bg_update);
	}

	// Update background if needed
	if ((next_bg_update - bg_start) % bg_update  == 0) {
	    next_bg_update += bg_update - bg_history;
	    //compute_median(bg_history, input_median, background);
	    compute_median_multithread(bg_history, 8);
	    if (verbose) {
		export_ppm(filename, width, height, background);
	    }
	}

	// Compute differential image in temp and update location
	temp->count = camera_index + 1;
	sub_thres_min(shm, background, temp, 80);
	get_camera_loc(temp, camera_index, verbose, car_name, nobstacles);

	// If needed, save current image for next background update
	if (camera_index == next_bg_update) {
	    memcpy(input_median[(next_bg_update + bg_history - bg_start) % bg_update], shm->data, IMAGE_SIZE);
	    next_bg_update += 1;
	}
	camera_index += 1;
	usleep(img_update * 1000);
    }

    // Free and close
    if ( shmdt(shm) == -1) { perror("shmdt"); exit(1); }
    for (i = 0; i < bg_history; i++) {
	free(input_median[i]);
    }
    free(input_median);
}

/**
 * Return car's MAC address given color or name
 */
std::string get_car_mac(char* color) {
    if (!strcmp(color, "grey") || !strcmp(color, "boson") || !strcmp(color, "gray")) {
        return "D9:81:41:5C:D4:31";
    }
    else if (!strcmp(color, "blue") || !strcmp(color, "katal")) {
        return "D8:64:85:29:01:C0";
    }
    else if (!strcmp(color, "koural") || !strcmp(color, "yellow")) {
        return "EB:0D:D8:05:CA:1A";
    }
    else if (!strcmp(color, "nuke") || !strcmp(color, "green")) {
        return "C5:34:5D:26:BE:53";
    }
    else if (!strcmp(color, "hadion") || !strcmp(color, "orange")) {
        return "D4:48:49:03:98:95";
    }
    else {
        return "E6:D8:52:F1:D9:43";
    }
}

/**
 * Return car's color given color or name
 */
std::string get_car_color(char* color) {
    if (!strcmp(color, "grey") || !strcmp(color, "boson") || !strcmp(color, "gray")) {
        return "grey";
    }
    else if (!strcmp(color, "blue") || !strcmp(color, "katal")) {
        return "blue";
    }
    else if (!strcmp(color, "koural") || !strcmp(color, "yellow")) {
        return "yellow";
    }
    else if (!strcmp(color, "nuke") || !strcmp(color, "green")) {
        return "green";
    }
    else if (!strcmp(color, "hadion") || !strcmp(color, "orange")) {
        return "orange";
    }
    else {
        return "red";
    }
}

/**
 * Main routine
 **/
int main(int argc, char *argv[]) {
    signal(SIGINT, intHandler);

    /*
     * Read parameters and Initialization
     */
    if(argc<2){
	fprintf(stderr, "usage: %s car-name [nbr of cars] [adaptater] [verbose]\n",argv[0]);
	exit(0);
    }
    const char* adapter = "hci0";
    const char* car_id  = get_car_mac(argv[1]).c_str();
    const char* car_color  = get_car_color(argv[1]).c_str();
    int opponents = 3;
    if (argc > 2) {
	opponents = atoi(argv[2]);
	if (argc > 3) {
		adapter = argv[3];
	   }
    }
    camera_obst = (camera_obst_localization_t*) malloc(sizeof(camera_obst_localization_t));
    camera_obst->total = opponents;
    init_blob_detector();
    camera_loc = (camera_localization_t*) malloc(sizeof(camera_localization_t));

    /*
     * Load thread to update picture every second and process it
     */
    // Set arguments
    struct arg_struct args;
    args.vehicle_color = car_color;
    args.update = 100; //time in milliseconds
    args.background_update = 1000;
    args.background_start = 20;
    args.history = 15;
    args.verbose = argc > 4;

    // Load default background
    background = (shared_struct*) malloc(sizeof(shared_struct));
    background->count = 0;
    FILE *f = fopen("/home/cvml1/Code/Images/default_background.txt", "rb");
    fread(background->data, IMAGE_SIZE, 1, f);
    fclose(f);

    // Launch camera thread
    int ret = pthread_create (&camera, 0, update_camera_loc,  &args);

    /*
     * Set vehicle's behaviour
     */
    // Init bluethooth and wait for connection successful
    fprintf(stderr, "Attempting connection to %s\n", car_id);
    h = anki_s_init(adapter, car_id, argc>4);
    fprintf(stderr, "Connection successful\n");

    // Additional parameters
    int res;
    run_index = 0;
    int lookup_update = 500;
    int is_still = 0;
    int previous_camera_loc[2] = {camera_loc->x, camera_loc->y};

    // Run until ctrl-C
    res = anki_s_set_speed(h,600,20000);
    usleep(500*1000);
    int race_clockwise=1;

    while (kbint && !res) {
	// Print
	print_loc(h);
	print_camera_loc();
	printf("\n");

	// Check if car stands still (no update of loc information) and set speed randomly  if so
	if(camera_loc->success && previous_camera_loc[0] == camera_loc->x && previous_camera_loc[1] == camera_loc->y){
		is_still = 1;
		fprintf(stderr, "standing still\n");
		anki_s_set_speed(h,500 + 1000 * ((double) rand() / (RAND_MAX)), 20000);
	}

	// Check direction and perform uturn if false
	localization_t loc = anki_s_get_localization(h);
	if(loc.update_time > 0 && loc.is_clockwise != race_clockwise && !is_still){
		anki_s_uturn(h);
		fprintf(stderr, "U-turn\n");
	}

	previous_camera_loc[0] = camera_loc->x;
	previous_camera_loc[1] = camera_loc->y;

	// Sleep
	run_index += 1;
	usleep(lookup_update*1000);
    }

    /*
     * Close and disconnect
     */
    anki_s_close(h);
    exit_signal = 1;
    pthread_join(camera, NULL);
    free(background);
    free(camera_loc);
    return 0;
}
<commit_msg>Switching main to cpp<commit_after>/*
 * Main File for controlling the car vehicle
 * Modified version of vehicle tool with threaded execution and read from file instead of stdin
 */

#include "examples/simple-c-interface/anki-simplified.h"
#include "CV/get_camera.hpp"
#include "ML/state.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "C/FlyCapture2_C.h"
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <string>

// Bash colors
#define KNRM  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"
#define KBOLD  "\x1B[1m"
#define RESET "\033[0m"

/**
 * Global variables
 */
static int camera_index = 0; //index for camera update
static int run_index = 0; //index for global simulation update
static int exit_signal = 0;
static pthread_t camera; // Thread running the camera detection
static AnkiHandle h;
static State* states_list; // List of all possible states
static int current_state; //  index of the current state the vehicle is in
camera_localization_t* camera_loc;
camera_obst_localization_t* camera_obst;
shared_struct* background;
unsigned char** input_median;

/**
 * Handle keyboard interrupts
 */
static int kbint = 1;
static void intHandler(int sig) {
    fprintf(stderr, "Keyboard interrupt - execute final block\n");
    kbint = 0;
}

/**
 *  Print car's current location
 */
void print_loc(AnkiHandle h){
    localization_t loc;
    loc = anki_s_get_localization(h);
    printf(KBLU "[Location]" RESET " segm: %03x subsegm: %03x clock-wise: %i last-update: %i\n",
	   loc.segm, loc.subsegm, loc.is_clockwise, loc.update_time);
}

/**
 *  Print car's current location (from camera)
 */
void print_camera_loc(){
    if (camera_loc->success) {
	printf(KBOLD KGRN "[Camera location]" RESET " x: %.2f y: %.2f size: %.2f last-update: %i\n",
	       camera_loc->x, camera_loc->y, camera_loc->size, camera_loc->update_time);
    } else {
	float result[2];
	get_camera_lock_dead_reckon(camera_index, result);
	printf(KBOLD KRED "[Camera location (DR)]" RESET " x: %.2f y: %.2f size: %.2f last-update: %i\n", result[0], result[1], camera_loc->size, camera_loc->update_time);
    }
}

/**
 * Get vehicle's location through camera (runs on independent thread)
 */
// Struct type to pass arguments to thread
struct arg_struct {
    const char* vehicle_color;   // Our vehicle's color
    int update;            // Image update (time in millisecond)
    int background_update; // new background every X image updates
    int background_start;  // index of first background computation
    int history;           // nbr of images for bacground computation
    int n_obst;            //nbr  of opponents on the track
    int verbose;           // 0-1: set verbosity level
};

// Main function run on the thread
void* update_camera_loc(void* aux) {
    // Read arguments
    struct arg_struct *args = (struct arg_struct *)aux;
    const char* car_color = args->vehicle_color;
    int img_update = args->update;
    int bg_history = args->history;
    int bg_start = args->background_start;
    int bg_update = args->background_update;
    int verbose = args->verbose;

    //Load background
    background = (shared_struct*) malloc(sizeof(shared_struct));
    background->count = 0;
    FILE *f = fopen("/home/cvml1/Code/Images/default_background.txt", "rb");
    fread(background->data, IMAGE_SIZE, 1, f);
    fclose(f);

    //Init structures
    init_blob_detector();
    camera_obst = (camera_obst_localization_t*) malloc(sizeof(camera_obst_localization_t));
    camera_obst->total = args.n_obst;
    camera_loc = (camera_localization_t*) malloc(sizeof(camera_localization_t));

    // Init shared memory
    int shmid;
    key_t key;
    shared_struct *shm;
    key = 192012003; // 1920x1200x3
    const int width = 1696;
    const int height = 720;
    if ((shmid = shmget(key, sizeof(shared_struct), 0666)) < 0) { perror("shmget"); exit(1); }
    if ((shm = (shared_struct*)shmat(shmid, NULL, 0)) == (shared_struct *) -1) { perror("shmat"); exit(1); }

    // Additional Paramaters
    camera_index = 0;
    char filename[256];
    int next_bg_update = bg_start - bg_history;
    shared_struct* temp = (shared_struct*) malloc(sizeof(shared_struct));

    //Init arrays for saving past images for background computation
    int i;
    input_median = (unsigned char**) malloc(sizeof(unsigned char*) * bg_history);
    for (i = 0; i < bg_history; i++) {
	input_median[i] = (unsigned char*) malloc(sizeof(unsigned char) * IMAGE_SIZE);
    }

    /*
     * Update location until receiving exit signal
     */
    while (!exit_signal && kbint) {
	// DEBUG
	if (verbose) {
	    fprintf(stderr, "Index: %d - Next bg update: %d - Current saving index: %d\n", camera_index, next_bg_update  - next_bg_update%bg_update + bg_start, (next_bg_update + bg_history - bg_start) % bg_update);
	}

	// Update background if needed
	if ((next_bg_update - bg_start) % bg_update  == 0) {
	    next_bg_update += bg_update - bg_history;
	    //compute_median(bg_history, input_median, background);
	    compute_median_multithread(bg_history, 8);
	    if (verbose) {
		export_ppm(filename, width, height, background);
	    }
	}

	// Compute differential image in temp and update location
	temp->count = camera_index + 1;
	sub_thres_min(shm, background, temp, 80);
	get_camera_loc(temp, camera_index, verbose, car_name, nobstacles);

	// If needed, save current image for next background update
	if (camera_index == next_bg_update) {
	    memcpy(input_median[(next_bg_update + bg_history - bg_start) % bg_update], shm->data, IMAGE_SIZE);
	    next_bg_update += 1;
	}
	camera_index += 1;
	usleep(img_update * 1000);
    }

    // Free and close
    if ( shmdt(shm) == -1) { perror("shmdt"); exit(1); }
    for (i = 0; i < bg_history; i++) {
	free(input_median[i]);
    }
    free(input_median);
}

/**
 * Return car's MAC address given color or name
 */
const std::string get_car_mac(char* color) {
    if (!strcmp(color, "grey") || !strcmp(color, "boson") || !strcmp(color, "gray")) {
        return "D9:81:41:5C:D4:31";
    }
    else if (!strcmp(color, "blue") || !strcmp(color, "katal")) {
        return "D8:64:85:29:01:C0";
    }
    else if (!strcmp(color, "koural") || !strcmp(color, "yellow")) {
        return "EB:0D:D8:05:CA:1A";
    }
    else if (!strcmp(color, "nuke") || !strcmp(color, "green")) {
        return "C5:34:5D:26:BE:53";
    }
    else if (!strcmp(color, "hadion") || !strcmp(color, "orange")) {
        return "D4:48:49:03:98:95";
    }
    else {
        return "E6:D8:52:F1:D9:43";
    }
}

/**
 * Return car's color given color or name
 */
const std::string get_car_color(char* color) {
    if (!strcmp(color, "grey") || !strcmp(color, "boson") || !strcmp(color, "gray")) {
        return "grey";
    }
    else if (!strcmp(color, "blue") || !strcmp(color, "katal")) {
        return "blue";
    }
    else if (!strcmp(color, "koural") || !strcmp(color, "yellow")) {
        return "yellow";
    }
    else if (!strcmp(color, "nuke") || !strcmp(color, "green")) {
        return "green";
    }
    else if (!strcmp(color, "hadion") || !strcmp(color, "orange")) {
        return "orange";
    }
    else {
        return "red";
    }
}

/**
 * Main routine
 **/
int main(int argc, char *argv[]) {
    signal(SIGINT, intHandler);

    /*
     * Hyper parameters
     */
    float camera_update = 0.1; // Update of the camera picture, in percent of seconds
    float control_update = 0.5; // Update of the vehicle action, `` `` ``
    float background_update = 5; // Update of the background, `` `` ``
    int background_start = 20;  // Index at which the background computation starts
    int background_history = 15; // Number of images to use for median computation

    /*
     * Read parameters
     */
    if(argc<2){
	fprintf(stderr, "usage: %s car-name [nbr of cars] [adaptater] [verbose]\n",argv[0]);
	exit(0);
    }
    const char* adapter = "hci0";
    const char* car_id  = get_car_mac(argv[1]).c_str();
    const char* car_color  = get_car_color(argv[1]).c_str();
    int opponents = 3;
    if (argc > 2) {
	opponents = atoi(argv[2]);
	if (argc > 3) {
	    adapter = argv[3];
	}
    }

    /*
     * Load thread to update picture every second and process it
     */
    struct arg_struct camera_args = {car_color, 1000 * camera_update, 1000 * background_update, background_start, background_history, opponents, argc > 4};
    int ret = pthread_create (&camera, 0, update_camera_loc,  &args);

    /*
     * Control vehicle's behaviour (run until ctrl-c)
     */

    // Init bluethooth and wait for connection successful
    fprintf(stderr, "Attempting connection to %s\n", car_id);
    h = anki_s_init(adapter, car_id, argc>4);
    fprintf(stderr, "Connection successful\n");

    // Additional parameters
    run_index = 0;
    int res;
    float previous_camera_loc[2] = {camera_loc->x, camera_loc->y};

    // Start Run until ctrl-C
    res = anki_s_set_speed(h,600,20000);

    while (kbint && !res) {
	// Display
	print_loc(h);
	print_camera_loc();
	printf("\n");

	// Check if car stands still (no update of loc information) and set speed randomly  if so
	if(camera_loc->success && previous_camera_loc[0] == camera_loc->x && previous_camera_loc[1] == camera_loc->y){
	    anki_s_set_speed(h,500 + 1000 * ((double) rand() / (RAND_MAX)), 20000);
	    fprintf(stderr, "Still\n");
	}

	// Check direction and perform uturn if false
	localization_t loc = anki_s_get_localization(h);
	if(loc.update_time > 0 && !is_still && !loc.is_clockwise){
	    anki_s_uturn(h);
	    fprintf(stderr, "U-turn\n");
	}

	// Next loop
	run_index += 1;
	previous_camera_loc[0] = camera_loc->x;
	previous_camera_loc[1] = camera_loc->y;
	usleep(control_update * 1000000);
    }

    /*
     * Close and disconnect
     */
    anki_s_close(h);
    exit_signal = 1;
    pthread_join(camera, NULL);
    free(background);
    free(camera_loc);
    return 0;
}
<|endoftext|>


<commit_before>6e06850a-ad58-11e7-b3c7-ac87a332f658<commit_msg>Introduced random NullPointerException bug<commit_after>6e6c42bd-ad58-11e7-91e1-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include "estimators.h"
#include "vcflib/Variant.h"
#include "vcflib/convert.h"

using namespace std;
using namespace vcf;

void extractProbsFromGLs(Variant& var, vector<vector<double> >& GLs) {
    for (vector<string>::iterator s = var.sampleNames.begin(); s != var.sampleNames.end(); ++s) {
        vector<double> g;
        map<string, map<string, vector<string> > >::iterator m = var.samples.find(*s);
        if (m != var.samples.end()) {
            map<string, vector<string> >& sample = m->second;
            map<string, vector<string> >::iterator l = sample.find("GL");
            if (l != sample.end()) {
                for (vector<string>::iterator i = l->second.begin(); i != l->second.end(); ++i) {
                    double x;
                    convert(*i, x);
                    x = pow(10, x);
                    g.push_back(x);
                }
            }
        }
        GLs.push_back(g);
    }
}

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

    VariantCallFile variantFile;

    if (argc > 1) {
        string filename = argv[1];
        variantFile.open(filename);
    } else {
        variantFile.open(std::cin);
    }

    if (!variantFile.is_open()) {
        return 1;
    }

    variantFile.addHeaderLine("##INFO=<ID=AFmle,Number=A,Type=Integer,Description=\"Allele frequency estimated from GLs.\">");
    variantFile.addHeaderLine("##INFO=<ID=AFmle_ref,Number=1,Type=Integer,Description=\"Reference allele frequency estimated from GLs.\">");

    cout << variantFile.header << endl;

    double eps = 1e-20;

    Variant var(variantFile);
    while (variantFile.getNextVariant(var)) {
        vector<vector<double> > GLs;
        vector<double> mleHWEAlleleFreq;
        uint32_t N;  // should be == # of samples with data
        extractProbsFromGLs(var, GLs);
        if (estimateHWEAlleleFrequencies(GLs, eps, mleHWEAlleleFreq, N, var.alleles.size())) {
            vector<string>::iterator a = var.alleles.begin();
            vector<double>::iterator f = mleHWEAlleleFreq.begin();
            var.info["AFmle_ref"].push_back(convert(*f));
            ++a; ++f;
            vector<string>& afmles = var.info["AFmle"];
            for ( ; f != mleHWEAlleleFreq.end(); ++f, ++a) {
                afmles.push_back(convert(*f));
            }
        }
        cout << var << endl;
    }

    return 0;

}
<commit_msg>added the rest of multiallelic estimators<commit_after>#include <iostream>
#include <algorithm>
#include "estimators.h"
#include "vcflib/Variant.h"
#include "vcflib/convert.h"

using namespace std;
using namespace vcf;

void extractProbsFromGLs(Variant& var, vector<vector<double> >& GLs) {
    for (vector<string>::iterator s = var.sampleNames.begin(); s != var.sampleNames.end(); ++s) {
        vector<double> g;
        map<string, map<string, vector<string> > >::iterator m = var.samples.find(*s);
        if (m != var.samples.end()) {
            map<string, vector<string> >& sample = m->second;
            map<string, vector<string> >::iterator l = sample.find("GL");
            if (l != sample.end()) {
                for (vector<string>::iterator i = l->second.begin(); i != l->second.end(); ++i) {
                    double x;
                    convert(*i, x);
                    x = pow(10, x);
                    g.push_back(x);
                }
            }
        }
        GLs.push_back(g);
    }
}

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

    VariantCallFile variantFile;

    if (argc > 1) {
        string filename = argv[1];
        variantFile.open(filename);
    } else {
        variantFile.open(std::cin);
    }

    if (!variantFile.is_open()) {
        return 1;
    }

    variantFile.addHeaderLine("##INFO=<ID=AFmle,Number=A,Type=Float,Description=\"Allele frequency estimated from GLs.\">");
    variantFile.addHeaderLine("##INFO=<ID=AFmle_ref,Number=1,Type=Float,Description=\"Reference allele frequency estimated from GLs.\">");
    variantFile.addHeaderLine("##INFO=<ID=GFmle,Number=G,Type=Float,Description=\"Genotype frequencies estimated from GLs.\">");
    variantFile.addHeaderLine("##INFO=<ID=HWEpval,Number=1,Type=Float,Description=\"HWE p-value estimated from GLs.\">");
    variantFile.addHeaderLine("##INFO=<ID=FIC,Number=1,Type=Float,Description=\"Inbreeding coefficient estimated from GLs.\">");

    cout << variantFile.header << endl;

    double eps = 1e-20;  // convergence limit

    Variant var(variantFile);
    while (variantFile.getNextVariant(var)) {
        vector<vector<double> > GLs;
        vector<double> mleHWEAlleleFreq;
        uint32_t N;  // should be == # of samples with data
        extractProbsFromGLs(var, GLs);
        if (estimateHWEAlleleFrequencies(GLs, eps, mleHWEAlleleFreq, N, var.alleles.size())) {
            vector<double>::iterator f = mleHWEAlleleFreq.begin();
            var.info["AFmle_ref"].clear();
            var.info["AFmle_ref"].push_back(convert(*f));
            ++f;
            vector<string>& afmles = var.info["AFmle"];
            afmles.clear();
            for ( ; f != mleHWEAlleleFreq.end(); ++f) {
                afmles.push_back(convert(*f));
            }
        } else {
            cerr << "could not estimate allele frequencies for " << var.sequenceName << ":" << var.position << endl;
            continue;
        }

        vector<double> mleGenotypeFreq;
        if (estimateGenotypeFrequencies(GLs, eps, mleGenotypeFreq, N, var.alleles.size())) {
            vector<string>& mlegfs = var.info["GFmle"];
            mlegfs.clear();
            for (vector<double>::iterator gf = mleGenotypeFreq.begin(); gf != mleGenotypeFreq.end(); ++gf) {
                mlegfs.push_back(convert(*gf));
            }
        } else {
            cerr << "could not estimate genotype frequencies for " << var.sequenceName << ":" << var.position << endl;
            continue;
        }

        double lrts; // likelihood ratio test statistic
        double pValue; // likelihood ratio p-value
        uint32_t dof;
        if (hweLRT(GLs, mleGenotypeFreq, mleHWEAlleleFreq, lrts, pValue, dof, var.alleles.size())) {
            var.info["HWEpval"].clear();
            var.info["HWEpval"].push_back(convert(pValue));
        } else {
            cerr << "could not estimate HWE likelihood ratio test for " << var.sequenceName << ":" << var.position << endl;
            continue;
        }

        double F; // inbreeding coefficient
        if (estimateFIC(GLs, mleGenotypeFreq, mleHWEAlleleFreq, F, var.alleles.size())) {
            var.info["FIC"].clear();
            var.info["FIC"].push_back(convert(F));
        } else {
            cerr << "could not estimate inbreeding coefficient for " << var.sequenceName << ":" << var.position << endl;
            continue;
        }

        cout << var << endl;
    }

    return 0;

}
<|endoftext|>


<commit_before>8572478f-2749-11e6-8db7-e0f84713e7b8<commit_msg>Initial commit.2<commit_after>857c91f0-2749-11e6-8876-e0f84713e7b8<|endoftext|>