<commit_before>#include <iostream>
#include <boost/tokenizer.hpp>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <vector>
#include <stack>

using namespace std;
using namespace boost;

//function used to seperate commands
void parseconnect(vector< vector<string> > &cmd, vector<string> &connect, string command)
{
	//different connectors
	string semicolon = ";";
	string needfirst = "&&";
	string needfirstfail = "||";
	int i = 0;
	string comment = "#";

	//deleting all comments
	if (command.find(comment) != string::npos)
	{
		int com = command.find(comment);
		command = command.substr(0, com);
	}

	//finding connectors
	while (command.size() != 0)
	{
		int semi = 0;//command.find(semicolon);
		int needf = 0;//command.find(needfirst);
		int needff = 0;//command.find(needfirstfail);

		//test for cases where connectors are gone
		if (command.find(semicolon) != string::npos)
		{
			semi = command.find(semicolon);
		}
		else
		{
			semi = 10000;
		}
		if (command.find(needfirst) != string::npos)
		{
			needf = command.find(needfirst);
		}
		else
		{
			needf = 10000;
		}
		if (command.find(needfirstfail) != string::npos)
		{
			needff = command.find(needfirstfail);
		}
		else
		{
			needff = 10000;
		}

		//checks to see which index of the different connectors are first
		vector<string> temp;
		if (semi > needf)
		{
			if (needf > needff)
			{
				connect.push_back(needfirstfail);
				temp.push_back(command.substr(0, needff));
				command = command.substr(needff + 2, command.size() - needff - 2);
				++i;
			}
			else
			{
				connect.push_back(needfirst);
				temp.push_back(command.substr(0, needf));
				command = command.substr(needf + 2, command.size() - needf - 2);
				++i;
			}
		}
		else if (needf > semi)
		{
			if (semi > needff)
			{
				connect.push_back(needfirstfail);
				temp.push_back(command.substr(0, needff));
				command = command.substr(needff + 2, command.size() - needff - 2);
				++i;
			}
			else
			{
				connect.push_back(semicolon);
				temp.push_back(command.substr(0, semi));
				command = command.substr(semi + 1, command.size() - semi - 1);
				++i;
			}
		}
		else if ( (needf == semi) && (needff != 10000) )
		{
			if (needf > needff)
			{
				connect.push_back(needfirstfail);
				temp.push_back(command.substr(0, needff));
				command = command.substr(needff + 2, command.size() - needff - 2);
				++i;
			}
		}
		else
		{
			//used when out of connectors
			temp.push_back(command);
			cmd.push_back(temp);
			return;
		}
		cmd.push_back(temp);
	}
}

//tokenizer function
void token(vector< vector<string> > cmdl, vector< vector<string> > &cmdl2)
{
	string f;
	int size = cmdl.size();
	for (int i = 0; i < size; ++i)
	{
		int j = 0;
		char_separator<char> sep(" ");
		tokenizer< char_separator<char> > tok(cmdl.at(i).at(0), sep);

		//cout << cmdl.at(i).at(0) << endl;
		cmdl2.push_back(vector<string>());

		//must seperate vectors or the tokenizer will BREAK
		for (tokenizer< char_separator<char> >::iterator iter = tok.begin(); iter != tok.end(); ++iter)
		{
			//cout << "deref iters: " << *iter << endl;
			f = *iter;
			cmdl2.at(i).push_back(f);
			++j;
		}

	}
}

void startline()
{
    char hostname[128];
	//passes in an array named hostname & it basically makes a copy of the hostname stored
    int hostnameStatus = gethostname(hostname, sizeof(hostname));
    //somewhere else and passes it back by reference (default b/c its an array).
    if (hostnameStatus == -1)
    {
        perror(hostname);
    }
    else
    {
         char* login = getlogin();
         cout << login << "@" << hostname << " $ ";
    }
}

//main run function, will prepare the command line
void run()
{
	//sentinel for while loop
	while (true)
	{
		//take in a command into a variable
		string command;
		startline();
		getline(cin, command);

		//exit command
		if (command == "exit")
		{
			exit(0);
		}
		else
		{
		    //call to parse
			vector< vector<string> > cmdline;
			vector<string> connectors;
			parseconnect(cmdline, connectors, command);

			//for (int i = 0; i < cmdline.size(); ++i)
			//{
			//	cout << "cmd before tokenizing: " << cmdline.at(i).at(0) << endl;
			//}
			vector< vector<string> > cmdline2;
            token(cmdline, cmdline2);
            vector< vector<char*> > commands;

			//changes all strings to char pointers
			int size = cmdline2.size();
			for (int i = 0; i < size; ++i)
			{
				//cout << cmdline.size() << endl;
				commands.push_back( vector<char*>() );
				for (unsigned int j = 0; j < cmdline2.at(i).size(); ++j)
				{
					//cout << endl;
					//cout << "before conversion to char*: " << cmdline2.at(i).at(j) << endl;
					//cout << "during conversion to char*: " << cmdline2.at(i).at(j).c_str() << endl;
					commands.at(i).push_back(const_cast<char*>(cmdline2.at(i).at(j).c_str()));
				}
				char* temp = NULL;
				commands.at(i).push_back(temp);
			}

			//calls process
			unsigned int i = 0;
			unsigned int j = 0;
         	bool sentinel = true;
          	while (sentinel == true)
           	{
				if (commands.size() == 1)
				{
					pid_t pid = fork();
					if (pid == 0)
					{
						if (execvp(commands.at(i).at(0), &(commands.at(i).at(0))) == -1)
						{
							perror("exec");
						}
					}
					if (pid > 0)
					{
						if (wait(0) == -1)
						{
							perror("wait");
						}
					}
					sentinel = false;
				}
				else
				{
					if (j == connectors.size())
					{
						--j;
					}
					//checks for connector logic
					string temp = commands.at(i).at(0);
					string tempconnectors = connectors.at(j);
					if (temp.compare("exit") == 0)
					{
						exit(0);
					}
					//forking process to child
					pid_t pid = fork();
					if (pid == 0)
					{
						if (execvp(commands.at(i).at(0), &(commands.at(i).at(0))) == -1)
						{
							if (tempconnectors.compare("&&") == 0)
							{
								++i;
								++j;
								if (i < commands.size())
								{
									continue;
								}
								//else
								//{
								//	sentinel = false;
								//}
							}
							perror("exec");
						}
					}
					if (pid > 0)
					{
						int stats;
						if (wait(&stats) == -1)
						{
							perror("wait");
						}
						else if (WEXITSTATUS(stats) == 0)
						{
							if ( (tempconnectors.compare("||") == 0) )
							{
								++i;
								++i;
								++j;
								++j;
								if (j < connectors.size())
								{
									tempconnectors = connectors.at(j);
									if (tempconnectors.compare("||") == 0)
									{
										++i;
										++j;
									}
								}
								if (i >= commands.size())
								{
									sentinel = false;
								}
								else
								{
									continue;
								}
							}
						}
					}
					if (i >= connectors.size())
					{
						sentinel = false;
					}
					++i;
					++j;
				}
           	}
		}
	}
}

void parser(string command, vector<string> &cmd)
{
    stack<int> parenthesis;
    string firstParent = "(";
    string closeParent = ")";
    int topIndex = -1;
    string subCommand = command;    //initialized subCommand to command.

    if(command.find(firstParent) != string::npos)
    {
        //ck if there r things before first parenthesis
        if(command.find(firstParent) != 0)
        {
            subCommand = command.substr(0, index);
            cmd.push_back(subCommand);
        }
        for(int i = 0; i < command.size(); i++)
        {
            if(command.at(i) == firstParent)
            {
                parenthesis.push(i);
                if(
            }
            if(command.at(i) == closeParent)
            {
                topIndex = parenthesis.top();
                parenthesis.pop();
                subCommand = command.substr(topIndex + 1, i - topIndex - 1);
                cmd.push_back(subCommand);
            }
        }
        if(!parenthesis.empty())
        {
            cout << "Error" << endl;
        }

    }//end if no firstParent

}//end of parser function

//main function, will contain test cases
int main()
{
/*
	string command = "ls -a ; echo asdfkasdfjasdf ; echo asdfjjenenc || aasdfaf";
	vector<string> connectors;
	vector< vector<string> > cmdline;
	vector< vector<string> > cmdline2;
	parseconnect(cmdline, connectors, command);

	for (int i = 0; i < cmdline.size() - 1; ++i)
	{
		cout << cmdline.at(i).at(0);
		for (int j = i; j < i + 1; ++j)
		{
			cout << connectors.at(j);
		}
	}
	cout << cmdline.at(cmdline.size() - 1).at(0) << endl;
	token(cmdline, cmdline2);
	for (int i = 0; i < cmdline2.size(); ++i)
	{
		for (int j = 0; j < cmdline2.at(i).size(); ++j)
		{
			cout << "<" << cmdline2.at(i).at(j) << ">" << endl;
		}
	}
*/
	run();
	return 0;
}
<commit_msg>Changed main file to accept the test function<commit_after>#include <iostream>
#include <boost/tokenizer.hpp>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <vector>
#include <stack>
#include <cstring>

using namespace std;
using namespace boost;

//function used to seperate commands
void parseconnect(vector< vector<string> > &cmd, vector<string> &connect, string command)
{
	//different connectors
	string semicolon = ";";
	string needfirst = "&&";
	string needfirstfail = "||";
	int i = 0;
	string comment = "#";

	//deleting all comments
	if (command.find(comment) != string::npos)
	{
		int com = command.find(comment);
		command = command.substr(0, com);
	}

	//finding connectors
	while (command.size() != 0)
	{
		int semi = 0;//command.find(semicolon);
		int needf = 0;//command.find(needfirst);
		int needff = 0;//command.find(needfirstfail);

		//test for cases where connectors are gone
		if (command.find(semicolon) != string::npos)
		{
			semi = command.find(semicolon);
		}
		else
		{
			semi = 10000;
		}
		if (command.find(needfirst) != string::npos)
		{
			needf = command.find(needfirst);
		}
		else
		{
			needf = 10000;
		}
		if (command.find(needfirstfail) != string::npos)
		{
			needff = command.find(needfirstfail);
		}
		else
		{
			needff = 10000;
		}

		//checks to see which index of the different connectors are first
		vector<string> temp;
		if (semi > needf)
		{
			if (needf > needff)
			{
				connect.push_back(needfirstfail);
				temp.push_back(command.substr(0, needff));
				command = command.substr(needff + 2, command.size() - needff - 2);
				++i;
			}
			else
			{
				connect.push_back(needfirst);
				temp.push_back(command.substr(0, needf));
				command = command.substr(needf + 2, command.size() - needf - 2);
				++i;
			}
		}
		else if (needf > semi)
		{
			if (semi > needff)
			{
				connect.push_back(needfirstfail);
				temp.push_back(command.substr(0, needff));
				command = command.substr(needff + 2, command.size() - needff - 2);
				++i;
			}
			else
			{
				connect.push_back(semicolon);
				temp.push_back(command.substr(0, semi));
				command = command.substr(semi + 1, command.size() - semi - 1);
				++i;
			}
		}
		else if ( (needf == semi) && (needff != 10000) )
		{
			if (needf > needff)
			{
				connect.push_back(needfirstfail);
				temp.push_back(command.substr(0, needff));
				command = command.substr(needff + 2, command.size() - needff - 2);
				++i;
			}
		}
		else
		{
			//used when out of connectors
			temp.push_back(command);
			cmd.push_back(temp);
			return;
		}
		cmd.push_back(temp);
	}
}

//tokenizer function
void token(vector< vector<string> > cmdl, vector< vector<string> > &cmdl2)
{
	string f;
	int size = cmdl.size();
	for (int i = 0; i < size; ++i)
	{
		int j = 0;
		char_separator<char> sep(" ");
		tokenizer< char_separator<char> > tok(cmdl.at(i).at(0), sep);

		//cout << cmdl.at(i).at(0) << endl;
		cmdl2.push_back(vector<string>());

		//must seperate vectors or the tokenizer will BREAK
		for (tokenizer< char_separator<char> >::iterator iter = tok.begin(); iter != tok.end(); ++iter)
		{
			//cout << "deref iters: " << *iter << endl;
			f = *iter;
			cmdl2.at(i).push_back(f);
			++j;
		}

	}
}

void startline()
{
    char hostname[128];
	//passes in an array named hostname & it basically makes a copy of the hostname stored
    int hostnameStatus = gethostname(hostname, sizeof(hostname));
    //somewhere else and passes it back by reference (default b/c its an array).
    if (hostnameStatus == -1)
    {
        perror(hostname);
    }
    else
    {
         char* login = getlogin();
         cout << login << "@" << hostname << " $ ";
    }
}

//-----------------------------------------------------------------------------
void test_func(vector <char*> to_test)
{
	//cout << "detects [] or test" << endl;
	string e_delim = "-e";
	char* ed = const_cast<char*>(e_delim.c_str());
	string f_delim = "-f";
	char* fd = const_cast<char*>(f_delim.c_str());
	string d_delim = "-d";
	char* dd = const_cast<char*>(d_delim.c_str());
	if (strcmp(to_test.at(1), ed) == 0)
	{
		struct stat buffer;
		//cout << "there we go E" << endl;
		int statusstat = stat(to_test.at(2), &buffer);
		//cout << "Status of stat: " << statusstat << endl;
		if (statusstat == 0)
		{
			cout << "(true)" << endl;
			cout << "Path: Exists." << endl;
		}
		else
		{
			cout << "(false)" << endl;
			cout << "Path: Does not exist." << endl;
		}
	}
	else if (strcmp(to_test.at(1), fd) == 0)
	{
		//cout << "there we go F" << endl;
		struct stat buffer;
		stat(to_test.at(2), &buffer);
		//cout << "Status of stat: " << statusstat << endl;
		bool tempbool = S_ISREG(buffer.st_mode);
		if (tempbool)
		{
			cout << "(true)" << endl;
			cout << "Filename: Is regular file." << endl;
		}
		else
		{
			cout << "(false)" << endl;
			cout << "Filename: Is not regular file." << endl;
		}
	}
	else if (strcmp(to_test.at(1), dd) == 0)
	{
		//cout << "there we go D" << endl;
		struct stat buffer;
		stat(to_test.at(2), &buffer);
		//cout << "Status of stat: " << statusstat << endl;
		bool tempbool = S_ISDIR(buffer.st_mode);
		if (tempbool)
		{
			cout << "(true)" << endl;
			cout << "Filename: Is a directory." << endl;
		}
		else
		{
			cout << "(false)" << endl;
			cout << "Filename: Is not a directory." << endl;
		}
	}
	else if (to_test.size() == 2)
	{
		//cout << "auto set: E" << endl;
		struct stat buffer;
		int statusstat = stat(to_test.at(1), &buffer);
		//cout << "Status of stat: " << statusstat << endl;
		if (statusstat == 0)
		{
			cout << "(true)" << endl;
			cout << "Path: Exists." << endl;
		}
		else
		{
			cout << "(false)" << endl;
			cout << "Path: Does not exist." << endl;
		}
	}
	else if (to_test.size() == 1)
	{
		cout << "Error: invalid use of test" << endl;
	}
	else
	{
		//cout << "auto set: E" << endl;
		struct stat buffer;
		int statusstat = stat(to_test.at(2), &buffer);
		//cout << "Status of stat: " << statusstat << endl;
		if (statusstat == 0)
		{
			cout << "(true)" << endl;
			cout << "Path: Exists." << endl;
		}
		else
		{
			cout << "(false)" << endl;
			cout << "Path: Does not exist." << endl;
		}
	}

}
//-------------------------------------------------------------------------------

//main run function, will prepare the command line
void run()
{
	//sentinel for while loop
	while (true)
	{
		//take in a command into a variable
		string command;
		startline();
		getline(cin, command);

		//exit command
		if (command == "exit")
		{
			exit(0);
		}
		else
		{
		    //call to parse
			vector< vector<string> > cmdline;
			vector<string> connectors;
			parseconnect(cmdline, connectors, command);

			//for (int i = 0; i < cmdline.size(); ++i)
			//{
			//	cout << "cmd before tokenizing: " << cmdline.at(i).at(0) << endl;
			//}
			vector< vector<string> > cmdline2;
            token(cmdline, cmdline2);
            vector< vector<char*> > commands;
			//-------------------------------------------------------------------------
			//changes
			string test1 = "test";
			char* test2 = const_cast<char*>(test1.c_str());
			string test_openb = "[";
			string test_closedb = "]";
			char* test3 = const_cast<char*>(test_openb.c_str());
			char* test4 = const_cast<char*>(test_closedb.c_str());
			//-------------------------------------------------------------------------

			//changes all strings to char pointers
			int size = cmdline2.size();
			for (int i = 0; i < size; ++i)
			{
				//cout << cmdline.size() << endl;
				commands.push_back( vector<char*>() );
				for (unsigned int j = 0; j < cmdline2.at(i).size(); ++j)
				{
					//cout << endl;
					//cout << "before conversion to char*: " << cmdline2.at(i).at(j) << endl;
					//cout << "during conversion to char*: " << cmdline2.at(i).at(j).c_str() << endl;
					commands.at(i).push_back(const_cast<char*>(cmdline2.at(i).at(j).c_str()));
					/*--------------------------------------------------------------------------
					if (strcmp(commands.at(i).at(0), test2) == 0)
					{
						cout << "Hello there!" << " " << commands.at(i).at(0) << endl;
					}
					else if (strcmp(commands.at(i).at(0), test3) == 0)
					{
						cout << "Hello there!" << " " << commands.at(i).at(0) << endl;
					}
					*///-------------------------------------------------------------------------
				}
				char* temp = NULL;
				commands.at(i).push_back(temp);
			}

			//calls process
			unsigned int i = 0;
			unsigned int j = 0;
         	bool sentinel = true;
          	while (sentinel == true)
           	{
				if (strcmp(commands.at(i).at(0), test3) == 0)
				{
					char* tempcharp = commands.at(i).at(commands.at(i).size() - 1);
					if (strcmp(tempcharp, test4) == 0)
					{
						test_func(commands.at(i));
					}
					++i;
					++j;
					if (i == commands.size())
					{
						break;
					}
				}
				else if (strcmp(commands.at(i).at(0), test2) == 0)
				{
					test_func(commands.at(i));
					++i;
					++j;
					if (i == commands.size())
					{
						break;
					}
				}
				else
				{
					if (commands.size() == 1)
					{
						pid_t pid = fork();
						if (pid == 0)
						{
							//--------------------------------------------------------------------------
							int tempexec = execvp(commands.at(i).at(0), &(commands.at(i).at(0)));
							if (tempexec == -1)
							{
								perror("exec");
							}
							//-----------------------
						}
						if (pid > 0)
						{
							if (wait(0) == -1)
							{
								perror("wait");
							}
						}
						sentinel = false;
					}
					else
					{
						if (j == connectors.size())
						{
							--j;
						}
						//checks for connector logic
						string temp = commands.at(i).at(0);
						string tempconnectors = connectors.at(j);
						if (temp.compare("exit") == 0)
						{
							exit(0);
						}
						//forking process to child
						pid_t pid = fork();
						if (pid == 0)
						{
							if (execvp(commands.at(i).at(0), &(commands.at(i).at(0))) == -1)
							{
								if (tempconnectors.compare("&&") == 0)
								{
									++i;
									++j;
									if (i < commands.size())
									{
										continue;
									}
									//else
									//{
									//	sentinel = false;
									//}
								}
								perror("exec");
							}
						}
						if (pid > 0)
						{
							int stats;
							if (wait(&stats) == -1)
							{
								perror("wait");
							}
							else if (WEXITSTATUS(stats) == 0)
							{
								if ( (tempconnectors.compare("||") == 0) )
								{
									++i;
									++i;
									++j;
									++j;
									if (j < connectors.size())
									{
										tempconnectors = connectors.at(j);
										if (tempconnectors.compare("||") == 0)
										{
											++i;
											++j;
										}
									}
									if (i >= commands.size())
									{
										sentinel = false;
									}
									else
									{
										continue;
									}
								}
							}
						}
						if (i >= connectors.size())
						{
							sentinel = false;
						}
						++i;
						++j;
					}
				}
           	}
		}
	}
}
/*
void parser(string command, vector<string> &cmd)
{
    stack<int> parenthesis;
    string firstParent = "(";
    string closeParent = ")";
    int topIndex = -1;
    string subCommand = command;    //initialized subCommand to command.

    if(command.find(firstParent) != string::npos)
    {
        //ck if there r things before first parenthesis
        if(command.find(firstParent) != 0)
        {
            subCommand = command.substr(0, index);
            cmd.push_back(subCommand);
        }
        for(int i = 0; i < command.size(); i++)
        {
            if(command.at(i) == firstParent)
            {
                parenthesis.push(i);
                if(
            }
            if(command.at(i) == closeParent)
            {
                topIndex = parenthesis.top();
                parenthesis.pop();
                subCommand = command.substr(topIndex + 1, i - topIndex - 1);
                cmd.push_back(subCommand);
            }
        }
        if(!parenthesis.empty())
        {
            cout << "Error" << endl;
        }

    }//end if no firstParent

}//end of parser function
*/
//main function, will contain test cases
int main()
{
/*
	string command = "ls -a ; echo asdfkasdfjasdf ; echo asdfjjenenc || aasdfaf";
	vector<string> connectors;
	vector< vector<string> > cmdline;
	vector< vector<string> > cmdline2;
	parseconnect(cmdline, connectors, command);

	for (int i = 0; i < cmdline.size() - 1; ++i)
	{
		cout << cmdline.at(i).at(0);
		for (int j = i; j < i + 1; ++j)
		{
			cout << connectors.at(j);
		}
	}
	cout << cmdline.at(cmdline.size() - 1).at(0) << endl;
	token(cmdline, cmdline2);
	for (int i = 0; i < cmdline2.size(); ++i)
	{
		for (int j = 0; j < cmdline2.at(i).size(); ++j)
		{
			cout << "<" << cmdline2.at(i).at(j) << ">" << endl;
		}
	}
*/
	run();
	return 0;
}
<|endoftext|>


<commit_before>/*
  main.c
  The Knights from Porto

  Created by Daniel Monteiro on 11/26/14.
  Copyright (c) 2014 Daniel Monteiro. All rights reserved.
*/

#include <utility>
#include <string>
#include <iostream>
#include <memory>
#include <fstream>
#include <vector>

#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CMap.h"
#include "IRenderer.h"
#include "CConsoleRenderer.h"
#include "CFalconKnight.h"
#include "CBullKnight.h"
#include "CTurtleKnight.h"
#include "CGame.h"

std::string readMap(const char *mapName) {

    std::string entry;
    std::ifstream mapFile("res/map1.txt");

    char line[80];

    while (!mapFile.eof()) {
        mapFile >> line;
        entry += line;
    }

    auto position = entry.find('\n');

    while (position != std::string::npos) {
        entry.replace(position, 1, "");
        position = entry.find('\n', position + 1);
    }

    return entry;
}

int main ( int argc, char **argv ) {
    std::string mapData = readMap("res/map1.txt");
    Knights::CGame game( mapData, std::make_shared<Knights::CConsoleRenderer>() );

  return 0;
}
<commit_msg>Makes the map actually load the file I choose<commit_after>/*
  main.c
  The Knights from Porto

  Created by Daniel Monteiro on 11/26/14.
  Copyright (c) 2014 Daniel Monteiro. All rights reserved.
*/

#include <utility>
#include <string>
#include <iostream>
#include <memory>
#include <fstream>
#include <vector>

#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CMap.h"
#include "IRenderer.h"
#include "CConsoleRenderer.h"
#include "CFalconKnight.h"
#include "CBullKnight.h"
#include "CTurtleKnight.h"
#include "CGame.h"

std::string readMap(const char *mapName) {

    std::string entry;
    std::ifstream mapFile(mapName);

    char line[80];

    while (!mapFile.eof()) {
        mapFile >> line;
        entry += line;
    }

    auto position = entry.find('\n');

    while (position != std::string::npos) {
        entry.replace(position, 1, "");
        position = entry.find('\n', position + 1);
    }

    return entry;
}

int main ( int argc, char **argv ) {
    std::string mapData = readMap("res/map1.txt");
    Knights::CGame game( mapData, std::make_shared<Knights::CConsoleRenderer>() );

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
//linux system libraries
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
//system libraries end
#include <csignal>
#include <queue>

#define MEMORY 66666
using namespace std;
void parsing(string& cmd)
{
    char* parsed = (char*) malloc (MEMORY);
    for (int i = 0, j = 0; cmd[i] != '\0'; ++i, ++j)
    {
        if(cmd[i] == '#')
        {
            //cout << "made it#" << endl;
            cmd[i] = '\0';
            parsed[j] = '\0';
        }
        else if (cmd[i] == ';')
        {
            //cout << "made it;" << endl;
            parsed[j] = ' ';
            parsed[++j] = ';';
            parsed[++j] = ' ';
            //display(parsed);
        }
        else if (cmd[i] == '|' && cmd[i + 1] == '|')
        {
            //cout << "made it||" << endl;
            parsed[j] = ' ';
            parsed[++j] = '|';
            parsed[++j] = '|';
            parsed[++j] = ' ';
            ++i;
        }
        else if (cmd[i] == '&' && cmd[i + 1] == '&')//&& connector
        {
            //cout << "made it&&" << endl;
            parsed[j] = ' ';
            parsed[++j] = '&';
            parsed[++j] = '&';
            parsed[++j] = ' ';
            ++i;
        }
        else
        {
            //cout <<"This is parsed at " << parsed[j] << endl;
            parsed[j] = cmd[i];
        }
        if (cmd[i + 1] == '\0')
        {
            parsed[j + 1] = '\0';
            //cout << "Index of j: " << j << end
        }
        //display(parsed);
    }
    cout << "Original: " << cmd << endl;
    cout << "parsed commands: " << parsed <<endl;
    //display(parsed);
    cmd = parsed;
    free(parsed);
    //cout << "new cmd: " << cmd << endl;
    //const char *c = cmd.c_str();
    //strcpy(, parsed);
    //free(parsed)
}
// queue of strings
//pop strings to an array of char
//point array to c
void commandsort(char* cmd, char* b[] )
{
    int i = 0;
    char* token = strtok(cmd, " ");
    while (token != NULL)
    {
        b[i] = token;
        token = strtok(NULL , " " );
        i++;
    }

    b[i] = '\0';
    //cout << "Work\n";
    // queue<string> test;
    // for(unsigned k = 0; b[k] != '\0'; k++)
    // {
    //     cout << "Pointer " << k << ": ";
    //     for(unsigned l = 0; b[k][l] != '\0'; l++)
    //     {
    //         cout << b[k][l];
    //     }
    //     test.push(b[k]);
    //     cout << endl;
    // }
}

//when i hit a connector in char array set it to null and keep track of array
void executecmd(char* array[])
{
    pid_t processID, pid; //processID = commands
	int status;
    int i = 0;
    queue<string> connectors;
    queue<string> comms;

	while(array[i] != '\0')
	{
	    comms.push(array[i]); //pushes commands into queue
	    i++;
	}
	i = 0;

	//char* temp = new char [100];    //mem = 66666
    while (true)
    {
	    //char* temp[100];
        if(comms.empty())
        {
            break;
        }
        if ((comms.front() != ";") || (comms.front() != "&&")|| //populate array
    	    (comms.front() != "||"))
        {
            char* temp = new char [100];
            strcpy(temp, comms.front().c_str());
            array[i] = temp;
            comms.pop();
            i++;
        }
        else //comms.front == connector //stop parsing and execvp
        {
            connectors.push(comms.front());
            comms.pop();
            break;
    	}
    }

    array[i] = '\0';
    for(unsigned k = 0; array[k] != '\0'; k++)
    {
        cout << "Pointer " << k << ": ";
        cout << array[k];
        // for(unsigned l = 0; array[k][l] != '\0'; l++)
        // {
        //     cout << array[k][l];
        // }
        cout << endl;
    }
    cout << "Value of i: " << i <<endl;
    processID = fork(); //fork
    if(processID < 0) //fork fails
    {
    	cout << "Fork Failed" << endl;
        exit(1);
    }
    else if(processID == 0) // child process
    {
        cout << "Executing \n";
        cout << "Child: executing: \n";
        //cout << comms.front() << endl; // switches off the parent
        cout << "Work dammit \n";
        execvp(array[0], array);
        cout << "Execute failed \n";
        perror("There was an error with the executable or argument list");
    }
    else if (processID > 0)
    {
    	if((pid = wait(&status)) < 0)
    	{
    	    cout << "Process failed\n";
    		perror("Process failed");
    		exit(-1);
    	}
    	if (WIFEXITED(status))
    	{
    		if(WIFEXITED(status) != 0)
    		{
    		    //bool success = false;
    		}
    	}

    	cout << "Parent: finished" << endl;
    }

}
int main (int argc, char **argv)
{
    string cmd;
    cout << "$ ";
    getline(cin, cmd);
    parsing(cmd);

    //put null after every connector
    //tokenize strtok with \0 as a delimiter.
    //vector<string> commands;
    char* b[MEMORY];
    char command[MEMORY];
    cout << "Copying \n";
    for(unsigned i =0; cmd[i] != '\0'; i++)
    {
        command[i] = cmd[i];
    }
    command[cmd.length()] = '\0';

    for (unsigned i = 0; command[i] != '\0'; i++)
    {
        cout << command[i];
    }
    cout << endl;
    commandsort(command, b);
    executecmd(b);
    //character pointer array
    //char *b[MEMORY];
    //if i find a space ' ' then everything before that space goes into the first pointer
    //of the character array get the address of everything before the space into the chararray

}
// if it fails then child returns -1 //
//perror outputs failure when fork fails
//waitpid(current_pid, &status, 0)

//strtok(string, " ");
//while (string != NULL)<commit_msg>Able to execute  multiple commands<commit_after>#include <iostream>
//linux system libraries
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
//system libraries end
#include <csignal>
#include <queue>

#define MEMORY 66666
using namespace std;
void parsing(string& cmd)
{
    char* parsed = (char*) malloc (MEMORY);
    for (int i = 0, j = 0; cmd[i] != '\0'; ++i, ++j)
    {
        if(cmd[i] == '#')
        {
            //cout << "made it#" << endl;
            cmd[i] = '\0';
            parsed[j] = '\0';
        }
        else if (cmd[i] == ';')
        {
            //cout << "made it;" << endl;
            parsed[j] = ' ';
            parsed[++j] = ';';
            parsed[++j] = ' ';
            //display(parsed);
        }
        else if (cmd[i] == '|' && cmd[i + 1] == '|')
        {
            //cout << "made it||" << endl;
            parsed[j] = ' ';
            parsed[++j] = '|';
            parsed[++j] = '|';
            parsed[++j] = ' ';
            ++i;
        }
        else if (cmd[i] == '&' && cmd[i + 1] == '&')//&& connector
        {
            //cout << "made it&&" << endl;
            parsed[j] = ' ';
            parsed[++j] = '&';
            parsed[++j] = '&';
            parsed[++j] = ' ';
            ++i;
        }
        else
        {
            //cout <<"This is parsed at " << parsed[j] << endl;
            parsed[j] = cmd[i];
        }
        if (cmd[i + 1] == '\0')
        {
            parsed[j + 1] = '\0';
            //cout << "Index of j: " << j << end
        }
        //display(parsed);
    }
    cout << "Original: " << cmd << endl;
    cout << "parsed commands: " << parsed <<endl;
    //display(parsed);
    cmd = parsed;
    free(parsed);
    //cout << "new cmd: " << cmd << endl;
    //const char *c = cmd.c_str();
    //strcpy(, parsed);
    //free(parsed)
}
// queue of strings
//pop strings to an array of char
//point array to c
void commandsort(char* cmd, char* b[] )
{
    int i = 0;
    char* token = strtok(cmd, " ");
    while (token != NULL)
    {
        b[i] = token;
        token = strtok(NULL , " " );
        i++;
    }

    b[i] = '\0';
    //cout << "Work\n";
    // queue<string> test;
    // for(unsigned k = 0; b[k] != '\0'; k++)
    // {
    //     cout << "Pointer " << k << ": ";
    //     for(unsigned l = 0; b[k][l] != '\0'; l++)
    //     {
    //         cout << b[k][l];
    //     }
    //     test.push(b[k]);
    //     cout << endl;
    // }
}

//when i hit a connector in char array set it to null and keep track of array
void executecmd(char* array[])
{
    pid_t processID, pid; //processID = commands
	int status;
    int i = 0;
    queue<string> connectors;
    queue<string> comms;

	while(array[i] != '\0')
	{
	    comms.push(array[i]); //pushes commands into queue
	    i++;
	}

	//char* temp = new char [100];    //mem = 66666
	while (true)
	{
	    i = 0;
	    if(comms.empty())
	    {
	        break;
	    }

        while (true)
        {
    	    //char* temp[100];
            if(comms.empty())
            {
                break;
            }
            if ((comms.front() != ";") || (comms.front() != "&&")|| //populate array
        	    (comms.front() != "||"))
            {
                char* temp = new char [100];
                strcpy(temp, comms.front().c_str());
                array[i] = temp;
                comms.pop();
                i++;
            }
            else //comms.front == connector //stop parsing and execvp
            {
                connectors.push(comms.front());
                comms.pop();
                break;
        	}
        }

    array[i] = '\0';
    for(unsigned k = 0; array[k] != '\0'; k++)
    {
        cout << "Pointer " << k << ": ";
        cout << array[k];
        // for(unsigned l = 0; array[k][l] != '\0'; l++)
        // {
        //     cout << array[k][l];
        // }
        cout << endl;
    }
    cout << "Value of i: " << i <<endl;
    processID = fork(); //fork
    if(processID < 0) //fork fails
    {
    	cout << "Fork Failed" << endl;
        exit(1);
    }
    else if(processID == 0) // child process
    {
        cout << "Executing \n";
        cout << "Child: executing: \n";
        //cout << comms.front() << endl; // switches off the parent
        cout << "Work dammit \n";
        execvp(array[0], array);
        cout << "Execute failed \n";

        perror("There was an error with the executable or argument list");
    }
    else if (processID > 0)
    {
    	if((pid = wait(&status)) < 0)
    	{
    	    cout << "Process failed\n";
    		perror("Process failed");
    		exit(-1);
    	}
    	if (WIFEXITED(status))
    	{
    		if(WIFEXITED(status) != 0)//command sucess
    		{

    		}
    	}

    	cout << "Parent: finished" << endl;
    }
    break;
	}

}
int main (int argc, char **argv)
{
    string cmd;
    cout << "$ ";
    getline(cin, cmd);
    parsing(cmd);

    //put null after every connector
    //tokenize strtok with \0 as a delimiter.
    //vector<string> commands;
    char* b[MEMORY];
    char command[MEMORY];
    cout << "Copying \n";
    for(unsigned i =0; cmd[i] != '\0'; i++)
    {
        command[i] = cmd[i];
    }
    command[cmd.length()] = '\0';

    for (unsigned i = 0; command[i] != '\0'; i++)
    {
        cout << command[i];
    }
    cout << endl;
    commandsort(command, b);
    executecmd(b);
    //character pointer array
    //char *b[MEMORY];
    //if i find a space ' ' then everything before that space goes into the first pointer
    //of the character array get the address of everything before the space into the chararray

}
// if it fails then child returns -1 //
//perror outputs failure when fork fails
//waitpid(current_pid, &status, 0)

//strtok(string, " ");
//while (string != NULL)<|endoftext|>


<commit_before>#include <vraptor.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
#include "vrtimer.hpp"
#include<codegen.hpp>
#include<iostream>
#include<sstream>
#include<string>
#include<fstream>
#include<cstdlib>
#include<prettyPrinter.hpp>
#include<vector>
#include<string.h>
#include <node-collector.hpp>
#include<getopt.h>
using namespace std;
using namespace VRaptor;

extern bool memOptimise;
extern bool prelim_bounds;
extern bool phase2Optimise;
extern bool enableOpenMp;

string readFile(const string& fname) {
        ifstream f(fname.c_str());
        stringstream buf;
        while (f.good()) {
                string line;
                getline(f, line);
                buf << line << endl;
        }
        f.close();
        return buf.str();
}

string readDataIntoString(const string& fname){
    ifstream ifile(fname.c_str());
    stringstream ss;
    string line;
    while(!ifile.eof()){
        getline(ifile,line);
        ss<<line<<endl;
    }
    return ss.str();
}
void writeFile(const string& fname , vector<string>& data){
    ofstream f(fname.c_str());
    for(int i=0;i<data.size();i++){
        f<<data[i];
    }
}
string getFileNameNoExt(string fname){
    std::string fCopy =fname;
    char* tok = strtok(const_cast<char*>(fCopy.c_str()),"/");
    char* tok1=NULL;
    while(tok!=NULL) {
        tok1=tok;
        tok = strtok(NULL,"/");
    }
    if(tok1==NULL){
        tok1=const_cast<char*>(fname.c_str());
    }
    return string(const_cast<const char*>(strtok(const_cast<char*>(tok1),".")));
}
void setOptFlags(string optArg) {
    if(optArg.compare("mem") == 0) {
        memOptimise = true;
    }
    if(optArg.compare("bounds") == 0) {
        prelim_bounds=true;
        phase2Optimise = true;
    }
    if(optArg.compare("par") == 0) {
        enableOpenMp = true;
    }
}

int main(int argc,char * argv[]){
    if(argc<2){
        std::cout<<"Usage: <filename>"<<std::endl;
        exit(0);
    }
    static struct option long_options[] =
    {
        /* These options don’t set a flag.
           We distinguish them by their indices. */
        {"opt", required_argument,0, 'O'},
        {"outFile",required_argument,0, 'f'},
        {0, 0, 0, 0}
    };
    std::string fname;
    std::string outFilePath = "";
    bool genFile =false;
    while(1) {
        int option_index = 0;
        int c = getopt_long (argc, argv, "O:f:",
                 long_options, &option_index);
        if(c==-1)  {
            break;
        }
        switch(c) {
            case 0:
                printf("probably should not be here\n");
                break;
            case 'O':
                setOptFlags(optarg);
                break;
            case 'f' :
                outFilePath = strdup(optarg);
                genFile = true;
                break;
            default:
                break;
        }

    }
    if(optind < argc) {
        fname  = argv[optind];
    }
    std::string optionStr="";
    initRaptor();
    fname = argv[1];
    std::string fCopy = fname;
    string s =readDataIntoString(fname);
    VModule *m=NULL;
    m= VModule::readFromString(s);
    NodeCollector nc;
    nc.analyze(m);
    std::string str = getFileNameNoExt(fCopy);
    VCompiler vc(str);
    vc.setCollector(nc);
    Context cntxt=vc.moduleCodeGen(m);
    PrettyPrinter pp;

    vector<string> vec_cpp = pp.prettyPrint(cntxt.getAllStmt());
    vector<string> vec_hpp = pp.prettyPrint(vc.getHeaderContext().getAllStmt());
    if(genFile) {
        for(int i=0;i<vec_cpp.size();i++){
            std::cout<<vec_cpp[i];
        }
        for(int i=0;i<vec_hpp.size();i++){
            std::cout<<vec_hpp[i];
        }
    } else  {
        writeFile(str+"Impl.cpp",vec_cpp);
        writeFile(str+"Impl.hpp",vec_hpp);
    }
}
<commit_msg>Removed bug in main file<commit_after>#include <vraptor.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
#include "vrtimer.hpp"
#include<codegen.hpp>
#include<iostream>
#include<sstream>
#include<string>
#include<fstream>
#include<cstdlib>
#include<prettyPrinter.hpp>
#include<vector>
#include<string.h>
#include <node-collector.hpp>
#include<getopt.h>
using namespace std;
using namespace VRaptor;

extern bool memOptimise;
extern bool prelim_bounds;
extern bool phase2Optimise;
extern bool enableOpenMp;

string readFile(const string& fname) {
        ifstream f(fname.c_str());
        stringstream buf;
        while (f.good()) {
                string line;
                getline(f, line);
                buf << line << endl;
        }
        f.close();
        return buf.str();
}

string readDataIntoString(const string& fname){
    ifstream ifile(fname.c_str());
    stringstream ss;
    string line;
    while(!ifile.eof()){
        getline(ifile,line);
        ss<<line<<endl;
    }
    return ss.str();
}
void writeFile(const string& fname , vector<string>& data){
    ofstream f(fname.c_str());
    for(int i=0;i<data.size();i++){
        f<<data[i];
    }
}
string getFileNameNoExt(string fname){
    std::string fCopy =fname;
    char* tok = strtok(const_cast<char*>(fCopy.c_str()),"/");
    char* tok1=NULL;
    while(tok!=NULL) {
        tok1=tok;
        tok = strtok(NULL,"/");
    }
    if(tok1==NULL){
        tok1=const_cast<char*>(fname.c_str());
    }
    return string(const_cast<const char*>(strtok(const_cast<char*>(tok1),".")));
}
void setOptFlags(string optArg) {
    if(optArg.compare("mem") == 0) {
        memOptimise = true;
    }
    if(optArg.compare("bounds") == 0) {
        prelim_bounds=true;
        phase2Optimise = true;
    }
    if(optArg.compare("par") == 0) {
        enableOpenMp = true;
    }
    if(optArg.compare("all") == 0) {
        enableOpenMp = true;
    }
}

int main(int argc,char * argv[]){
    if(argc<2){
        std::cout<<"Usage: <filename>"<<std::endl;
        exit(0);
    }
    static struct option long_options[] =
    {
        /* These options don’t set a flag.
           We distinguish them by their indices. */
        {"opt", required_argument,0, 'O'},
        {"outFile",required_argument,0, 'f'},
        {0, 0, 0, 0}
    };
    std::string fname;
    std::string outFilePath = "";
    bool genFile =false;
    while(1) {
        int option_index = 0;
        int c = getopt_long (argc, argv, "O:f:",
                 long_options, &option_index);
        if(c==-1)  {
            break;
        }
        switch(c) {
            case 0:
                printf("probably should not be here\n");
                break;
            case 'O':
                setOptFlags(optarg);
                break;
            case 'f' :
                outFilePath = strdup(optarg);
                genFile = true;
                break;
            default:
                break;
        }

    }
    if(optind < argc) {
        fname  = argv[optind];
    } else  {
        printf("atleast one input file required\n");
    }
    std::string optionStr="";
    initRaptor();
    std::string fCopy = fname;
    string s =readDataIntoString(fname);
    VModule *m=NULL;
    m= VModule::readFromString(s);
    NodeCollector nc;
    nc.analyze(m);
    std::string str = getFileNameNoExt(fCopy);
    VCompiler vc(str);
    vc.setCollector(nc);
    Context cntxt=vc.moduleCodeGen(m);
    PrettyPrinter pp;

    vector<string> vec_cpp = pp.prettyPrint(cntxt.getAllStmt());
    vector<string> vec_hpp = pp.prettyPrint(vc.getHeaderContext().getAllStmt());
    if(!genFile) {
        for(int i=0;i<vec_cpp.size();i++){
            std::cout<<vec_cpp[i];
        }
        for(int i=0;i<vec_hpp.size();i++){
            std::cout<<vec_hpp[i];
        }
    } else  {
        writeFile(str+"Impl.cpp",vec_cpp);
        writeFile(str+"Impl.hpp",vec_hpp);
    }
}
<|endoftext|>


<commit_before>#include <irrlicht.h>
#include "events.h"
#include "gui_game.h"

using namespace irr;

namespace ic = irr::core;
namespace is = irr::scene;
namespace iv = irr::video;
namespace ig = irr::gui;

is::ITriangleSelector* createTree(is::IAnimatedMesh *mesh, is::ISceneManager *smgr, EventReceiver receiver, iv::IVideoDriver  *driver);
is::ITriangleSelector*  createColumn(int position_x, int position_z, int height, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver);
is::ITriangleSelector* createMountain(int nbMountains, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver);

const int ID = 40;
const int cpt = 0;

int main()
{
    // Le gestionnaire d'événements
    EventReceiver receiver;
    std::vector<iv::ITexture*> textures;

    // Création de la fenêtre et du système de rendu.
    IrrlichtDevice *device = createDevice(iv::EDT_OPENGL,
                                          ic::dimension2d<u32>(640, 480),
                                          16, false, false, false, &receiver);

    is::ISceneManager *smgr = device->getSceneManager();
    iv::IVideoDriver  *driver = device->getVideoDriver();
    ig::IGUIEnvironment *gui_game = device->getGUIEnvironment();

    // Stockage des textures
    textures.push_back(driver->getTexture("data/TXsQk.png"));

    // Chargement du cube
   is::IAnimatedMesh *mesh = smgr->getMesh("data/cube.obj");

    //chargement du santaclaus
    is::IAnimatedMesh *mesh_santaclaus = smgr->getMesh("data/Steve.obj");

    //chargement du tree
    is::IAnimatedMesh *mesh_tree = smgr->getMesh("data/lowpolytree.obj");

    // Ajout de la scène
    is::IAnimatedMeshSceneNode *node;
    int Ni = 100;
    int Nj = 100;

    is::IMetaTriangleSelector *metaselector = smgr-> createMetaTriangleSelector();

    for (int i = 0 ; i < Ni ; i ++)
    {
        for (int j = 0 ; j < Nj ; j ++)
        {
            node = smgr->addAnimatedMeshSceneNode(mesh,nullptr,i+j);
            node->setMaterialFlag(irr::video::EMF_LIGHTING, false);
            node->setPosition (core::vector3df(i,0,j));

            textures.push_back(driver->getTexture("data/TXsQk.png"));
            node->setMaterialTexture(0, textures[0]);
            receiver.set_node(node);
            receiver.set_textures(textures);

            // Création du triangle selector pour gérer la collision
            is::ITriangleSelector *selector = smgr->createTriangleSelector(node->getMesh(),node);
            node ->setTriangleSelector (selector);

            //meta selector permettant de stocker les selecteurs de tous mes cubes
            metaselector->addTriangleSelector(selector);

        }
    }

    //is::ITriangleSelector* selector1 = createTree(mesh, smgr,receiver,driver);
    //metaselector->addTriangleSelector(selector1);

    //Ajout de reliefs sur la scene
    int nbMountains = 2;
    is::ITriangleSelector* selector2 = createMountain(nbMountains, node, mesh, smgr, textures, receiver);
    metaselector->addTriangleSelector(selector2);

    // Ajout du cube à la scène
    /*is::IAnimatedMeshSceneNode *node_personnage;
    node_personnage = smgr->addAnimatedMeshSceneNode(mesh);
    node_personnage->setPosition(core::vector3df(20, 10, 20));
    textures.push_back(driver->getTexture("data/rouge.jpg"));
    node_personnage->setMaterialTexture(0, textures.back());
    node_personnage->setMaterialFlag(irr::video::EMF_LIGHTING, false);
    receiver.set_node(node_personnage);
    receiver.set_textures(textures);*/

    //ajout tree (ou une forêt)  à la scene
    is::IAnimatedMeshSceneNode *node_tree;
    int Nl = 7;
    int Nk = 7;

    for (int l=0; l<Nl; l++)
    {
	for (int k=0; k<Nk; k++)
	{
	    node_tree = smgr->addAnimatedMeshSceneNode(mesh_tree,nullptr, l+k);
	    node_tree->setMaterialFlag(irr::video::EMF_LIGHTING, false);
	    node_tree->setPosition(core::vector3df(10+4*l, 4.3, 60+4*k));//30+4*l, 4.3, 5+4*l));
	    node_tree->setScale(core::vector3df(1.5,1.5,1.5));
	    receiver.set_node(node_tree);

	    //node_tree->setDebugDataVisible(is::EDS_NORMALS);

	    //selector sur l'arbre
	    is::ITriangleSelector *selector = smgr->createTriangleSelector(mesh_tree,node_tree);
	    node_tree->setTriangleSelector(selector);
	    selector->drop();
	    node_tree->setID(ID);

	    metaselector->addTriangleSelector(selector);
	}
    }

    //ajout santaclaus à la scene
    is::IAnimatedMeshSceneNode *node_santaclaus;
    node_santaclaus = smgr->addAnimatedMeshSceneNode(mesh_santaclaus);
    node_santaclaus->setMaterialFlag(irr::video::EMF_LIGHTING, false);
    node_santaclaus->setPosition(core::vector3df(20, 2, 30));
    textures.push_back(driver->getTexture("data/Santa.png"));
    node_santaclaus->setMaterialTexture(0, textures.back());
    node_santaclaus->setScale(core::vector3df(0.5,0.5,0.5));
    receiver.set_node(node_santaclaus);
    receiver.set_textures(textures);

    receiver.set_gui(gui_game);

    //Gestion collision
    is::ISceneNodeAnimator *anim;
    anim = smgr ->createCollisionResponseAnimator(metaselector, node_santaclaus,
                                                  ic::vector3df(1, 1, 1), //Rayon de la cam
                                                  ic::vector3df(0, -10, 0),  //gravité
						  ic::vector3df(0, 0, 0));  // décalage du centre

    node_santaclaus->addAnimator(anim);

    //gestionnaire de collision "Selection"

     is::ISceneCollisionManager *collision_manager = smgr->getSceneCollisionManager();

    //caméra qui va suivre notre personnage

    //son parent est donc le noeud qui definit le personnage
    //deuxieme paramètre:position de la camera (look From)
    //troisieme paramètre: look at (ici c'est la position du personnage) mise a jour dans event.cpp
    is::ICameraSceneNode *camera = smgr->addCameraSceneNode(node_santaclaus, ic::vector3df(20,10,0), node_santaclaus->getPosition());
    receiver.set_camera(camera);

    // La barre de menu
    gui_game::create_menu(gui_game);

    while(device->run())
    {

        driver->beginScene(true, true, iv::SColor(0,50,100,255));

	//Séléction de l'arbre à couper avec la souris
	int mouse_x, mouse_y;
	if (receiver.is_mouse_pressed(mouse_x, mouse_y))
	{
	  ic::line3d<f32> ray;
	  ray = collision_manager->getRayFromScreenCoordinates(ic::position2d<s32>(mouse_x, mouse_y));

	  ic::vector3df intersection;
	  ic::triangle3df hit_triangle;

	  is::ISceneNode *selected_scene_node = collision_manager->getSceneNodeAndCollisionPointFromRay(ray,
													intersection, // On récupère ici les coordonnées 3D de l'intersection
													hit_triangle, // et le triangle intersecté
													ID); // On ne veut que des noeuds avec cet identifiant

	  //on supprime les arbres
	  if (selected_scene_node)
	  {
	    selected_scene_node->setVisible(false);
	    cpt ++;
	  }

	}

        // Dessin de la scène :
        smgr->drawAll();
        // Dessin de l'interface utilisateur :
        gui_game->drawAll();

        driver->endScene();

    }
    device->drop();

    return 0;
}

/*is::ITriangleSelector* createTree(is::IAnimatedMesh *mesh, is::ISceneManager *smgr, EventReceiver receiver, iv::IVideoDriver  *driver)
{
    std::vector<iv::ITexture*> textures;
    is::IAnimatedMeshSceneNode *node_arbre;
    int i = 10;
    int j = 10;

    is::ITriangleSelector *selector;
    is::IMetaTriangleSelector *

            metaselector = smgr-> createMetaTriangleSelector();;

    for (int k = 0 ; k < 15 ; k ++)
    {
        node_arbre = smgr->addAnimatedMeshSceneNode(mesh,nullptr,i+j+k);
        node_arbre->setMaterialFlag(irr::video::EMF_LIGHTING, false);
        node_arbre->setPosition (core::vector3df(i,k,j));
        textures.push_back(driver->getTexture("data/tree.jpg"));
        node_arbre->setMaterialTexture(0, textures[0]);
        //node_arbre->setDebugDataVisible(is::EDS_BBOX | is::EDS_HALF_TRANSPARENCY);
        receiver.set_node(node_arbre);
        receiver.set_textures(textures);

        // Création du triangle selector pour gérer la collision
        selector = smgr->createTriangleSelector(node_arbre->getMesh(),node_arbre);
        node_arbre ->setTriangleSelector (selector);

        metaselector->addTriangleSelector(selector);
    }

    return metaselector;
}*/

//Create a moutain
is::ITriangleSelector* createMountain(int nbMountains, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver)
{
    int Ni=100;
    int Nj=100;

    is::ITriangleSelector *selector;
    is::IMetaTriangleSelector *metaselector = smgr-> createMetaTriangleSelector();

    for(int i = 0; i<nbMountains; ++i)
    {
        int delta_max = 20;
        int delta = delta_max;
        int height = 1;
        // Get a random position for the lowest left point of the mountain
        int position_x = rand()%Ni;
        int position_z = rand()%Nj;
        while(delta>2)
        {
            for (int x=position_x; x<position_x+delta; ++x)
            {
                for(int z=position_z; z<position_z+delta; ++z)
                {
                    selector = createColumn(x, z, height, node, mesh, smgr, textures, receiver);

                    metaselector->addTriangleSelector(selector);
                }
            }
            position_x++;
            position_z++;
            height++;
            delta-=2;
        }
    }
    return metaselector;
}

// Given a position on the scene, add cubes to go to the given height
is::ITriangleSelector* createColumn(int position_x, int position_z, int height, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver)
{
    is::ITriangleSelector *selector;
    is::IMetaTriangleSelector *metaselector = smgr-> createMetaTriangleSelector();

    for(int i=1; i<height; ++i)
    {
        node = smgr->addAnimatedMeshSceneNode(mesh, nullptr, position_x+i+position_z);
        node->setMaterialFlag(irr::video::EMF_LIGHTING, false);
        node->setPosition (core::vector3df(position_x, i, position_z));

        node->setMaterialTexture(0, textures[0]);
        receiver.set_node(node);
        receiver.set_textures(textures);

        selector = smgr->createTriangleSelector(node->getMesh(),node);
        node ->setTriangleSelector (selector);

        metaselector->addTriangleSelector(selector);
    }
    return metaselector;
}

<commit_msg>foret_rand<commit_after>#include <irrlicht.h>
#include "events.h"
#include "gui_game.h"

using namespace irr;

namespace ic = irr::core;
namespace is = irr::scene;
namespace iv = irr::video;
namespace ig = irr::gui;

is::ITriangleSelector* createTree(is::IAnimatedMesh *mesh, is::ISceneManager *smgr, EventReceiver receiver, iv::IVideoDriver  *driver);
is::ITriangleSelector*  createColumn(int position_x, int position_z, int height, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver);
is::ITriangleSelector* createMountain(int nbMountains, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver);

const int ID = 40;

int main()
{
    // Le gestionnaire d'événements
    EventReceiver receiver;
    std::vector<iv::ITexture*> textures;

    // Création de la fenêtre et du système de rendu.
    IrrlichtDevice *device = createDevice(iv::EDT_OPENGL,
                                          ic::dimension2d<u32>(640, 480),
                                          16, false, false, false, &receiver);

    is::ISceneManager *smgr = device->getSceneManager();
    iv::IVideoDriver  *driver = device->getVideoDriver();
    ig::IGUIEnvironment *gui_game = device->getGUIEnvironment();

    // Stockage des textures
    textures.push_back(driver->getTexture("data/TXsQk.png"));

    // Chargement du cube
   is::IAnimatedMesh *mesh = smgr->getMesh("data/cube.obj");

    //chargement du santaclaus
    is::IAnimatedMesh *mesh_santaclaus = smgr->getMesh("data/Steve.obj");

    //chargement du tree
    is::IAnimatedMesh *mesh_tree = smgr->getMesh("data/lowpolytree.obj");

    // Ajout de la scène
    is::IAnimatedMeshSceneNode *node;
    int Ni = 100;
    int Nj = 100;

    is::IMetaTriangleSelector *metaselector = smgr-> createMetaTriangleSelector();

    for (int i = 0 ; i < Ni ; i ++)
    {
        for (int j = 0 ; j < Nj ; j ++)
        {
            node = smgr->addAnimatedMeshSceneNode(mesh,nullptr,i+j);
            node->setMaterialFlag(irr::video::EMF_LIGHTING, false);
            node->setPosition (core::vector3df(i,0,j));

            textures.push_back(driver->getTexture("data/TXsQk.png"));
            node->setMaterialTexture(0, textures[0]);
            receiver.set_node(node);
            receiver.set_textures(textures);

            // Création du triangle selector pour gérer la collision
            is::ITriangleSelector *selector = smgr->createTriangleSelector(node->getMesh(),node);
            node ->setTriangleSelector (selector);

            //meta selector permettant de stocker les selecteurs de tous mes cubes
            metaselector->addTriangleSelector(selector);

        }
    }

    //is::ITriangleSelector* selector1 = createTree(mesh, smgr,receiver,driver);
    //metaselector->addTriangleSelector(selector1);

    //Ajout de reliefs sur la scene
    int nbMountains = 2;
    is::ITriangleSelector* selector2 = createMountain(nbMountains, node, mesh, smgr, textures, receiver);
    metaselector->addTriangleSelector(selector2);

    // Ajout du cube à la scène
    /*is::IAnimatedMeshSceneNode *node_personnage;
    node_personnage = smgr->addAnimatedMeshSceneNode(mesh);
    node_personnage->setPosition(core::vector3df(20, 10, 20));
    textures.push_back(driver->getTexture("data/rouge.jpg"));
    node_personnage->setMaterialTexture(0, textures.back());
    node_personnage->setMaterialFlag(irr::video::EMF_LIGHTING, false);
    receiver.set_node(node_personnage);
    receiver.set_textures(textures);*/

    //ajout tree (ou une forêt)  à la scene
    is::IAnimatedMeshSceneNode *node_tree;
    int Nl = 7;
    int Nk = 7;
    int pos_x;
    int pos_y;

    for (int l=0; l<Nl; l++)
    {
	for (int k=0; k<Nk; k++)
	{
	    pos_x = rand()%Nl + 8*l;
	    pos_y = rand()%Nk + 5*k;

	    node_tree = smgr->addAnimatedMeshSceneNode(mesh_tree,nullptr, l+k);
	    node_tree->setMaterialFlag(irr::video::EMF_LIGHTING, false);
	    node_tree->setPosition(core::vector3df(pos_x, 4.3,pos_y));//30+4*l, 4.3, 5+4*l));
	    node_tree->setScale(core::vector3df(1.5,1.5,1.5));
	    receiver.set_node(node_tree);

	    //selector sur l'arbre
	    is::ITriangleSelector *selector = smgr->createTriangleSelector(mesh_tree,node_tree);
	    node_tree->setTriangleSelector(selector);
	    selector->drop();
	    node_tree->setID(ID);

	    metaselector->addTriangleSelector(selector);
	}
    }

    //ajout santaclaus à la scene
    is::IAnimatedMeshSceneNode *node_santaclaus;
    node_santaclaus = smgr->addAnimatedMeshSceneNode(mesh_santaclaus);
    node_santaclaus->setMaterialFlag(irr::video::EMF_LIGHTING, false);
    node_santaclaus->setPosition(core::vector3df(20,2,60)); //20, 2, 30));
    textures.push_back(driver->getTexture("data/Santa.png"));
    node_santaclaus->setMaterialTexture(0, textures.back());
    node_santaclaus->setScale(core::vector3df(0.5,0.5,0.5));
    receiver.set_node(node_santaclaus);
    receiver.set_textures(textures);

    receiver.set_gui(gui_game);

    //Gestion collision
    is::ISceneNodeAnimator *anim;
    anim = smgr ->createCollisionResponseAnimator(metaselector, node_santaclaus,
                                                  ic::vector3df(1, 1, 1), //Rayon de la cam
                                                  ic::vector3df(0, -10, 0),  //gravité
						  ic::vector3df(0, 0, 0));  // décalage du centre

    node_santaclaus->addAnimator(anim);

    //gestionnaire de collision "Selection"

     is::ISceneCollisionManager *collision_manager = smgr->getSceneCollisionManager();

    //caméra qui va suivre notre personnage

    //son parent est donc le noeud qui definit le personnage
    //deuxieme paramètre:position de la camera (look From)
    //troisieme paramètre: look at (ici c'est la position du personnage) mise a jour dans event.cpp
    is::ICameraSceneNode *camera = smgr->addCameraSceneNode(node_santaclaus, ic::vector3df(20,10,0), node_santaclaus->getPosition());
    receiver.set_camera(camera);

    // La barre de menu
    gui_game::create_menu(gui_game);

    while(device->run())
    {

        driver->beginScene(true, true, iv::SColor(0,50,100,255));

	//Séléction de l'arbre à couper avec la souris
	int mouse_x, mouse_y;
	if (receiver.is_mouse_pressed(mouse_x, mouse_y))
	{
	  ic::line3d<f32> ray;
	  ray = collision_manager->getRayFromScreenCoordinates(ic::position2d<s32>(mouse_x, mouse_y));

	  ic::vector3df intersection;
	  ic::triangle3df hit_triangle;

	  is::ISceneNode *selected_scene_node = collision_manager->getSceneNodeAndCollisionPointFromRay(ray,
													intersection, // On récupère ici les coordonnées 3D de l'intersection
													hit_triangle, // et le triangle intersecté
													ID); // On ne veut que des noeuds avec cet identifiant

	  //on supprime les arbres
	  if (selected_scene_node)
	  {
	    selected_scene_node->setVisible(false);
	  }

	}

        // Dessin de la scène :
        smgr->drawAll();
        // Dessin de l'interface utilisateur :
        gui_game->drawAll();

        driver->endScene();

    }
    device->drop();

    return 0;
}

/*is::ITriangleSelector* createTree(is::IAnimatedMesh *mesh, is::ISceneManager *smgr, EventReceiver receiver, iv::IVideoDriver  *driver)
{
    std::vector<iv::ITexture*> textures;
    is::IAnimatedMeshSceneNode *node_arbre;
    int i = 10;
    int j = 10;

    is::ITriangleSelector *selector;
    is::IMetaTriangleSelector *

            metaselector = smgr-> createMetaTriangleSelector();;

    for (int k = 0 ; k < 15 ; k ++)
    {
        node_arbre = smgr->addAnimatedMeshSceneNode(mesh,nullptr,i+j+k);
        node_arbre->setMaterialFlag(irr::video::EMF_LIGHTING, false);
        node_arbre->setPosition (core::vector3df(i,k,j));
        textures.push_back(driver->getTexture("data/tree.jpg"));
        node_arbre->setMaterialTexture(0, textures[0]);
        //node_arbre->setDebugDataVisible(is::EDS_BBOX | is::EDS_HALF_TRANSPARENCY);
        receiver.set_node(node_arbre);
        receiver.set_textures(textures);

        // Création du triangle selector pour gérer la collision
        selector = smgr->createTriangleSelector(node_arbre->getMesh(),node_arbre);
        node_arbre ->setTriangleSelector (selector);

        metaselector->addTriangleSelector(selector);
    }

    return metaselector;
}*/

//Create a moutain
is::ITriangleSelector* createMountain(int nbMountains, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver)
{
    int Ni=100;
    int Nj=100;

    is::ITriangleSelector *selector;
    is::IMetaTriangleSelector *metaselector = smgr-> createMetaTriangleSelector();

    for(int i = 0; i<nbMountains; ++i)
    {
        int delta_max = 20;
        int delta = delta_max;
        int height = 1;
        // Get a random position for the lowest left point of the mountain
        int position_x = rand()%Ni;
        int position_z = rand()%Nj;
        while(delta>2)
        {
            for (int x=position_x; x<position_x+delta; ++x)
            {
                for(int z=position_z; z<position_z+delta; ++z)
                {
                    selector = createColumn(x, z, height, node, mesh, smgr, textures, receiver);

                    metaselector->addTriangleSelector(selector);
                }
            }
            position_x++;
            position_z++;
            height++;
            delta-=2;
        }
    }
    return metaselector;
}

// Given a position on the scene, add cubes to go to the given height
is::ITriangleSelector* createColumn(int position_x, int position_z, int height, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver)
{
    is::ITriangleSelector *selector;
    is::IMetaTriangleSelector *metaselector = smgr-> createMetaTriangleSelector();

    for(int i=1; i<height; ++i)
    {
        node = smgr->addAnimatedMeshSceneNode(mesh, nullptr, position_x+i+position_z);
        node->setMaterialFlag(irr::video::EMF_LIGHTING, false);
        node->setPosition (core::vector3df(position_x, i, position_z));

        node->setMaterialTexture(0, textures[0]);
        receiver.set_node(node);
        receiver.set_textures(textures);

        selector = smgr->createTriangleSelector(node->getMesh(),node);
        node ->setTriangleSelector (selector);

        metaselector->addTriangleSelector(selector);
    }
    return metaselector;
}

<|endoftext|>


<commit_before>//Author: Julian Yi
//Date Started: 14 July 2017, Friday.
//Purpose: This is a project to create a working chess engine and gui using C++.
//File: This is the main file.
#include <iostream>
#include <memory>
#include "board.h"
#include "pawn.h"
#include "knight.h"
#include "bishop.h"
#include "coord.h"
#include "BearLibTerminal.h"

#define sizeY 8
#define sizeX 8

int main()
{
	board Chessboard;
	board::Square **tile = new board::Square*[sizeY];

	for (int index = 0; index < sizeY; ++index)
	{
		tile[index] = new board::Square[sizeX];
	}

	Chessboard.initializeBoard(tile);

	auto testPawn = new Pawn();
	testPawn->setPosition(coord{0, 3}, tile);
	std::cout << testPawn->getPieceName() << " " << testPawn->getPosition().x << " " << testPawn->getPosition().y << std::endl;

	coordList validMoves;

	validMoves = testPawn->calculateMoves(coord{10, 10});
	for (auto& move : validMoves) {
		std::cout << "Can move to: " << move.x << " " << move.y << std::endl;
	}

	auto testKnight = new Knight();
	testKnight->setPosition(coord{0, 3}, tile);
	std::cout << "Knight at: " << testKnight->getPosition().x << " " << testKnight->getPosition().y << std::endl;

	validMoves = testKnight->calculateMoves(coord{10, 10});
	for (auto& move : validMoves) {
		std::cout << "Can move to: " << move.x << " " << move.y << std::endl;
	}

	auto testBishop = new Bishop();
	testBishop->setPosition(coord{2, 2}, tile);
	std::cout << "Bishop at: " << testBishop->getPosition().x << " " << testBishop->getPosition().y << std::endl;

	validMoves = testBishop->calculateMoves(coord{10, 10});
	for (auto& move : validMoves) {
		std::cout << "Can move to: " << move.x << " " << move.y << std::endl;
	}
	//Chessboard.placePiece("Pawn1", testPawn->getPosition().x, testPawn->getPosition().y, tile);
	//Chessboard.placePiece("Knight1", testPawn->getPosition().x, testPawn->getPosition().y, tile);

	std::cout << "pause here" << std::endl;

	for (int index = 0; index < sizeY; ++index)
	{
		delete[] tile[index];
	}

	delete[] tile;

	terminal_open();

	// Printing text
    terminal_print(1, 1, "Hello, world!");
    terminal_refresh();

    // Wait until user close the window
    while (terminal_read() != TK_CLOSE);

    terminal_close();

	return 0;
}
<commit_msg>Added intro to the terminal gui and key press recognition.<commit_after>//Author: Julian Yi
//Date Started: 14 July 2017, Friday.
//Purpose: This is a project to create a working chess engine and gui using C++.
//File: This is the main file.
#include <iostream>
#include "board.h"
#include "pawn.h"
#include "knight.h"
#include "bishop.h"
#include "coord.h"
#include "BearLibTerminal.h"

int main()
{
	board Chessboard;
	// Do these need to be on the heap?
	board::Square **tile = new board::Square*[board::sizeY];

	for (int index = 0; index < board::sizeY; ++index)
	{
		tile[index] = new board::Square[board::sizeX];
	}

	Chessboard.initializeBoard(tile);

	auto testPawn = new Pawn();
	testPawn->setPosition(coord{0, 3}, tile);
	std::cout << testPawn->getPieceName() << " " << testPawn->getPosition().x << " " << testPawn->getPosition().y << std::endl;

	coordList validMoves;

	validMoves = testPawn->calculateMoves(coord{10, 10});
	for (auto& move : validMoves) {
		std::cout << "Can move to: " << move.x << " " << move.y << std::endl;
	}

	auto testKnight = new Knight();
	testKnight->setPosition(coord{0, 3}, tile);
	std::cout << "Knight at: " << testKnight->getPosition().x << " " << testKnight->getPosition().y << std::endl;

	validMoves = testKnight->calculateMoves(coord{10, 10});
	for (auto& move : validMoves) {
		std::cout << "Can move to: " << move.x << " " << move.y << std::endl;
	}

	auto testBishop = new Bishop();
	testBishop->setPosition(coord{2, 2}, tile);
	std::cout << "Bishop at: " << testBishop->getPosition().x << " " << testBishop->getPosition().y << std::endl;

	validMoves = testBishop->calculateMoves(coord{10, 10});
	for (auto& move : validMoves) {
		std::cout << "Can move to: " << move.x << " " << move.y << std::endl;
	}
	//Chessboard.placePiece("Pawn1", testPawn->getPosition().x, testPawn->getPosition().y, tile);
	//Chessboard.placePiece("Knight1", testPawn->getPosition().x, testPawn->getPosition().y, tile);

	// Open the terminal. Since no terminal_set() method is called,
	// the terminal will use default settings.
	terminal_open();

	// Print intro text.
	terminal_print(1, 1, "Chess Engine");
	terminal_print(4, 2, "by Julian Yi, Sean Brock, and Simon Kim");
	terminal_print(1, 4, "Press Enter to start...");
	terminal_refresh();

	bool running = true;
	while (running) {
		// Check for input. termnial_read() is blocking, meaning the
		// program will wait until it reads a key press.
		auto key = terminal_read();

		// Reset the terminal to blank state.
		terminal_clear();

		// Print instructions.
		terminal_print(1, 1, "Press Enter to start...");

		// Handle key presses.
		switch (key) {
			case TK_CLOSE:
				running = false;
				break;
			case TK_ESCAPE:
				running = false;
				break;
			case TK_ENTER:
				terminal_print(1, 2, "Simon is king; Kylee is queen.");
				break;
			default:
				terminal_print(1, 2, "The key pressed has no function.");
				break;
		}

		// Commit the buffer and draw it.
		terminal_refresh();

	}

	// We're done here.
	terminal_close();

	// Do we need to delete pointers if we are exiting?
	/*
	std::cout << "pause here" << std::endl;

	for (int index = 0; index < board::sizeY; ++index)
	{
		delete[] tile[index];
	}

	delete[] tile;
	*/
	return 0;
}
<|endoftext|>


<commit_before>#include <ROOT/RDataFrame.hxx>
#include <ROOT/RArrowDS.hxx>
#include <ROOT/TSeq.hxx>
#include <TROOT.h>

#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#endif
#include <arrow/builder.h>
#include <arrow/memory_pool.h>
#include <arrow/record_batch.h>
#include <arrow/table.h>
#include <arrow/test-util.h>
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif

#include <gtest/gtest.h>

#include <iostream>

using namespace ROOT;
using namespace ROOT::RDF;
using namespace arrow;

std::shared_ptr<Schema> exampleSchema()
{
   return schema({field("Name", arrow::utf8()), field("Age", arrow::int64()), field("Height", arrow::float64()),
                  field("Married", arrow::boolean()), field("Babies", arrow::uint32())});
}

std::shared_ptr<Table> createTestTable()
{
   auto schema_ = exampleSchema();

   std::vector<bool> is_valid(6, true);
   std::vector<std::string> names = {"Harry", "Bob,Bob", "\"Joe\"", "Tom", " John  ", " Mary Ann "};
   std::vector<int64_t> ages = {64, 50, 40, 30, 2, 0};
   std::vector<double> heights = {180.0, 200.5, 1.7, 1.9, 1.0, 0.8};
   std::vector<bool> marriageStatus = {true, true, false, true, false, false};
   std::vector<unsigned int> babies = {1, 0, 2, 3, 4, 21};

   std::shared_ptr<Array> arrays_[5];

   arrow::ArrayFromVector<StringType, std::string>(names, &arrays_[0]);
   arrow::ArrayFromVector<Int64Type, int64_t>(ages, &arrays_[1]);
   arrow::ArrayFromVector<DoubleType, double>(heights, &arrays_[2]);
   arrow::ArrayFromVector<BooleanType, bool>(marriageStatus, &arrays_[3]);
   arrow::ArrayFromVector<UInt32Type, unsigned int>(babies, &arrays_[4]);

   std::vector<std::shared_ptr<Column>> columns_ = {
      std::make_shared<Column>(schema_->field(0), arrays_[0]), std::make_shared<Column>(schema_->field(1), arrays_[1]),
      std::make_shared<Column>(schema_->field(2), arrays_[2]), std::make_shared<Column>(schema_->field(3), arrays_[3]),
      std::make_shared<Column>(schema_->field(4), arrays_[4])};

   auto table_ = Table::Make(schema_, columns_);
   return table_;
}

TEST(RArrowDS, ColTypeNames)
{
   RArrowDS tds(createTestTable(), {"Name", "Age", "Height", "Married", "Babies"});
   tds.SetNSlots(1);

   auto colNames = tds.GetColumnNames();

   EXPECT_TRUE(tds.HasColumn("Name"));
   EXPECT_TRUE(tds.HasColumn("Age"));
   EXPECT_FALSE(tds.HasColumn("Address"));

   ASSERT_EQ(colNames.size(), 5U);
   EXPECT_STREQ("Height", colNames[2].c_str());
   EXPECT_STREQ("Married", colNames[3].c_str());

   EXPECT_STREQ("string", tds.GetTypeName("Name").c_str());
   EXPECT_STREQ("Long64_t", tds.GetTypeName("Age").c_str());
   EXPECT_STREQ("double", tds.GetTypeName("Height").c_str());
   EXPECT_STREQ("bool", tds.GetTypeName("Married").c_str());
   EXPECT_STREQ("UInt_t", tds.GetTypeName("Babies").c_str());
}

TEST(RArrowDS, EntryRanges)
{
   RArrowDS tds(createTestTable(), {});
   tds.SetNSlots(3U);
   tds.Initialise();

   // Still dividing in equal parts...
   auto ranges = tds.GetEntryRanges();

   ASSERT_EQ(3U, ranges.size());
   EXPECT_EQ(0U, ranges[0].first);
   EXPECT_EQ(2U, ranges[0].second);
   EXPECT_EQ(2U, ranges[1].first);
   EXPECT_EQ(4U, ranges[1].second);
   EXPECT_EQ(4U, ranges[2].first);
   EXPECT_EQ(6U, ranges[2].second);
}

TEST(RArrowDS, ColumnReaders)
{
   RArrowDS tds(createTestTable(), {});

   const auto nSlots = 3U;
   tds.SetNSlots(nSlots);
   auto valsAge = tds.GetColumnReaders<Long64_t>("Age");
   auto valsBabies = tds.GetColumnReaders<unsigned int>("Babies");

   tds.Initialise();
   auto ranges = tds.GetEntryRanges();
   auto slot = 0U;
   std::vector<Long64_t> RefsAge = {64, 50, 40, 30, 2, 0};
   std::vector<unsigned int> RefsBabies = {1, 0, 2, 3, 4, 21};
   for (auto &&range : ranges) {
      tds.InitSlot(slot, range.first);
      ASSERT_LT(slot, valsAge.size());
      for (auto i : ROOT::TSeq<int>(range.first, range.second)) {
         tds.SetEntry(slot, i);
         auto valAge = **valsAge[slot];
         EXPECT_EQ(RefsAge[i], valAge);
         auto valBabies = **valsBabies[slot];
         EXPECT_EQ(RefsBabies[i], valBabies);
      }
      slot++;
   }
}

TEST(RArrowDS, ColumnReadersString)
{
   RArrowDS tds(createTestTable(), {});

   const auto nSlots = 3U;
   tds.SetNSlots(nSlots);
   auto vals = tds.GetColumnReaders<std::string>("Name");
   tds.Initialise();
   auto ranges = tds.GetEntryRanges();
   auto slot = 0U;
   std::vector<std::string> names = {"Harry", "Bob,Bob", "\"Joe\"", "Tom", " John  ", " Mary Ann "};
   for (auto &&range : ranges) {
      tds.InitSlot(slot, range.first);
      ASSERT_LT(slot, vals.size());
      for (auto i : ROOT::TSeqU(range.first, range.second)) {
         tds.SetEntry(slot, i);
         auto val = *((std::string *)*vals[slot]);
         ASSERT_LT(i, names.size());
         EXPECT_EQ(names[i], val);
      }
      slot++;
   }
}

#ifndef NDEBUG

TEST(RArrowDS, SetNSlotsTwice)
{
   auto theTest = []() {
      RArrowDS tds(createTestTable(), {});
      tds.SetNSlots(1);
      tds.SetNSlots(1);
   };
   ASSERT_DEATH(theTest(), "Setting the number of slots even if the number of slots is different from zero.");
}
#endif

#ifdef R__B64

TEST(RArrowDS, FromARDF)
{
   std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
   ROOT::RDataFrame rdf(std::move(tds));
   auto max = rdf.Max<double>("Height");
   auto min = rdf.Min<double>("Height");
   auto c = rdf.Count();

   EXPECT_EQ(6U, *c);
   EXPECT_DOUBLE_EQ(200.5, *max);
   EXPECT_DOUBLE_EQ(0.8, *min);
}

TEST(RArrowDS, FromARDFWithJitting)
{
   std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
   ROOT::RDataFrame rdf(std::move(tds));
   auto max = rdf.Filter("Age<40").Max("Age");
   auto min = rdf.Define("Age2", "Age").Filter("Age2>30").Min("Age2");

   EXPECT_EQ(30, *max);
   EXPECT_EQ(40, *min);
}

// NOW MT!-------------
#ifdef R__USE_IMT

TEST(RArrowDS, DefineSlotCheckMT)
{
   const auto nSlots = 4U;
   ROOT::EnableImplicitMT(nSlots);

   std::vector<unsigned int> ids(nSlots, 0u);
   std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
   ROOT::RDataFrame d(std::move(tds));
   auto m = d.DefineSlot("x", [&](unsigned int slot) {
                ids[slot] = 1u;
                return 1;
             }).Max("x");
   EXPECT_EQ(1, *m); // just in case

   const auto nUsedSlots = std::accumulate(ids.begin(), ids.end(), 0u);
   EXPECT_GT(nUsedSlots, 0u);
   EXPECT_LE(nUsedSlots, nSlots);
}

TEST(RArrowDS, FromARDFMT)
{
   std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
   ROOT::RDataFrame tdf(std::move(tds));
   auto max = tdf.Max<double>("Height");
   auto min = tdf.Min<double>("Height");
   auto c = tdf.Count();

   EXPECT_EQ(6U, *c);
   EXPECT_DOUBLE_EQ(200.5, *max);
   EXPECT_DOUBLE_EQ(.8, *min);
}

TEST(RArrowDS, FromARDFWithJittingMT)
{
   std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
   ROOT::RDataFrame tdf(std::move(tds));
   auto max = tdf.Filter("Age<40").Max("Age");
   auto min = tdf.Define("Age2", "Age").Filter("Age2>30").Min("Age2");

   EXPECT_EQ(30, *max);
   EXPECT_EQ(40, *min);
}

#endif // R__USE_IMT

#endif // R__B64
<commit_msg>Latest binary of Apache Arrow actually has test-utils.h in arrow/compute/<commit_after>#include <ROOT/RDataFrame.hxx>
#include <ROOT/RArrowDS.hxx>
#include <ROOT/TSeq.hxx>
#include <TROOT.h>

#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#endif
#include <arrow/builder.h>
#include <arrow/memory_pool.h>
#include <arrow/record_batch.h>
#include <arrow/table.h>
#include <arrow/compute/test-util.h>
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif

#include <gtest/gtest.h>

#include <iostream>

using namespace ROOT;
using namespace ROOT::RDF;
using namespace arrow;

std::shared_ptr<Schema> exampleSchema()
{
   return schema({field("Name", arrow::utf8()), field("Age", arrow::int64()), field("Height", arrow::float64()),
                  field("Married", arrow::boolean()), field("Babies", arrow::uint32())});
}

std::shared_ptr<Table> createTestTable()
{
   auto schema_ = exampleSchema();

   std::vector<bool> is_valid(6, true);
   std::vector<std::string> names = {"Harry", "Bob,Bob", "\"Joe\"", "Tom", " John  ", " Mary Ann "};
   std::vector<int64_t> ages = {64, 50, 40, 30, 2, 0};
   std::vector<double> heights = {180.0, 200.5, 1.7, 1.9, 1.0, 0.8};
   std::vector<bool> marriageStatus = {true, true, false, true, false, false};
   std::vector<unsigned int> babies = {1, 0, 2, 3, 4, 21};

   std::shared_ptr<Array> arrays_[5];

   arrow::ArrayFromVector<StringType, std::string>(names, &arrays_[0]);
   arrow::ArrayFromVector<Int64Type, int64_t>(ages, &arrays_[1]);
   arrow::ArrayFromVector<DoubleType, double>(heights, &arrays_[2]);
   arrow::ArrayFromVector<BooleanType, bool>(marriageStatus, &arrays_[3]);
   arrow::ArrayFromVector<UInt32Type, unsigned int>(babies, &arrays_[4]);

   std::vector<std::shared_ptr<Column>> columns_ = {
      std::make_shared<Column>(schema_->field(0), arrays_[0]), std::make_shared<Column>(schema_->field(1), arrays_[1]),
      std::make_shared<Column>(schema_->field(2), arrays_[2]), std::make_shared<Column>(schema_->field(3), arrays_[3]),
      std::make_shared<Column>(schema_->field(4), arrays_[4])};

   auto table_ = Table::Make(schema_, columns_);
   return table_;
}

TEST(RArrowDS, ColTypeNames)
{
   RArrowDS tds(createTestTable(), {"Name", "Age", "Height", "Married", "Babies"});
   tds.SetNSlots(1);

   auto colNames = tds.GetColumnNames();

   EXPECT_TRUE(tds.HasColumn("Name"));
   EXPECT_TRUE(tds.HasColumn("Age"));
   EXPECT_FALSE(tds.HasColumn("Address"));

   ASSERT_EQ(colNames.size(), 5U);
   EXPECT_STREQ("Height", colNames[2].c_str());
   EXPECT_STREQ("Married", colNames[3].c_str());

   EXPECT_STREQ("string", tds.GetTypeName("Name").c_str());
   EXPECT_STREQ("Long64_t", tds.GetTypeName("Age").c_str());
   EXPECT_STREQ("double", tds.GetTypeName("Height").c_str());
   EXPECT_STREQ("bool", tds.GetTypeName("Married").c_str());
   EXPECT_STREQ("UInt_t", tds.GetTypeName("Babies").c_str());
}

TEST(RArrowDS, EntryRanges)
{
   RArrowDS tds(createTestTable(), {});
   tds.SetNSlots(3U);
   tds.Initialise();

   // Still dividing in equal parts...
   auto ranges = tds.GetEntryRanges();

   ASSERT_EQ(3U, ranges.size());
   EXPECT_EQ(0U, ranges[0].first);
   EXPECT_EQ(2U, ranges[0].second);
   EXPECT_EQ(2U, ranges[1].first);
   EXPECT_EQ(4U, ranges[1].second);
   EXPECT_EQ(4U, ranges[2].first);
   EXPECT_EQ(6U, ranges[2].second);
}

TEST(RArrowDS, ColumnReaders)
{
   RArrowDS tds(createTestTable(), {});

   const auto nSlots = 3U;
   tds.SetNSlots(nSlots);
   auto valsAge = tds.GetColumnReaders<Long64_t>("Age");
   auto valsBabies = tds.GetColumnReaders<unsigned int>("Babies");

   tds.Initialise();
   auto ranges = tds.GetEntryRanges();
   auto slot = 0U;
   std::vector<Long64_t> RefsAge = {64, 50, 40, 30, 2, 0};
   std::vector<unsigned int> RefsBabies = {1, 0, 2, 3, 4, 21};
   for (auto &&range : ranges) {
      tds.InitSlot(slot, range.first);
      ASSERT_LT(slot, valsAge.size());
      for (auto i : ROOT::TSeq<int>(range.first, range.second)) {
         tds.SetEntry(slot, i);
         auto valAge = **valsAge[slot];
         EXPECT_EQ(RefsAge[i], valAge);
         auto valBabies = **valsBabies[slot];
         EXPECT_EQ(RefsBabies[i], valBabies);
      }
      slot++;
   }
}

TEST(RArrowDS, ColumnReadersString)
{
   RArrowDS tds(createTestTable(), {});

   const auto nSlots = 3U;
   tds.SetNSlots(nSlots);
   auto vals = tds.GetColumnReaders<std::string>("Name");
   tds.Initialise();
   auto ranges = tds.GetEntryRanges();
   auto slot = 0U;
   std::vector<std::string> names = {"Harry", "Bob,Bob", "\"Joe\"", "Tom", " John  ", " Mary Ann "};
   for (auto &&range : ranges) {
      tds.InitSlot(slot, range.first);
      ASSERT_LT(slot, vals.size());
      for (auto i : ROOT::TSeqU(range.first, range.second)) {
         tds.SetEntry(slot, i);
         auto val = *((std::string *)*vals[slot]);
         ASSERT_LT(i, names.size());
         EXPECT_EQ(names[i], val);
      }
      slot++;
   }
}

#ifndef NDEBUG

TEST(RArrowDS, SetNSlotsTwice)
{
   auto theTest = []() {
      RArrowDS tds(createTestTable(), {});
      tds.SetNSlots(1);
      tds.SetNSlots(1);
   };
   ASSERT_DEATH(theTest(), "Setting the number of slots even if the number of slots is different from zero.");
}
#endif

#ifdef R__B64

TEST(RArrowDS, FromARDF)
{
   std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
   ROOT::RDataFrame rdf(std::move(tds));
   auto max = rdf.Max<double>("Height");
   auto min = rdf.Min<double>("Height");
   auto c = rdf.Count();

   EXPECT_EQ(6U, *c);
   EXPECT_DOUBLE_EQ(200.5, *max);
   EXPECT_DOUBLE_EQ(0.8, *min);
}

TEST(RArrowDS, FromARDFWithJitting)
{
   std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
   ROOT::RDataFrame rdf(std::move(tds));
   auto max = rdf.Filter("Age<40").Max("Age");
   auto min = rdf.Define("Age2", "Age").Filter("Age2>30").Min("Age2");

   EXPECT_EQ(30, *max);
   EXPECT_EQ(40, *min);
}

// NOW MT!-------------
#ifdef R__USE_IMT

TEST(RArrowDS, DefineSlotCheckMT)
{
   const auto nSlots = 4U;
   ROOT::EnableImplicitMT(nSlots);

   std::vector<unsigned int> ids(nSlots, 0u);
   std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
   ROOT::RDataFrame d(std::move(tds));
   auto m = d.DefineSlot("x", [&](unsigned int slot) {
                ids[slot] = 1u;
                return 1;
             }).Max("x");
   EXPECT_EQ(1, *m); // just in case

   const auto nUsedSlots = std::accumulate(ids.begin(), ids.end(), 0u);
   EXPECT_GT(nUsedSlots, 0u);
   EXPECT_LE(nUsedSlots, nSlots);
}

TEST(RArrowDS, FromARDFMT)
{
   std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
   ROOT::RDataFrame tdf(std::move(tds));
   auto max = tdf.Max<double>("Height");
   auto min = tdf.Min<double>("Height");
   auto c = tdf.Count();

   EXPECT_EQ(6U, *c);
   EXPECT_DOUBLE_EQ(200.5, *max);
   EXPECT_DOUBLE_EQ(.8, *min);
}

TEST(RArrowDS, FromARDFWithJittingMT)
{
   std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
   ROOT::RDataFrame tdf(std::move(tds));
   auto max = tdf.Filter("Age<40").Max("Age");
   auto min = tdf.Define("Age2", "Age").Filter("Age2>30").Min("Age2");

   EXPECT_EQ(30, *max);
   EXPECT_EQ(40, *min);
}

#endif // R__USE_IMT

#endif // R__B64
<|endoftext|>