<commit_before>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <deque>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
#include <algorithm>
#include <pwd.h>
#include <grp.h>
#include <time.h>
using namespace std;

void organize(deque <string> &files)
{
	sort(files.begin(), files.end(), locale("en_US.UTF-8"));
}

void printlFlag(struct stat name)
{
	if(name.st_mode & S_IFDIR)
		cout << 'd';
	else if(!(name.st_mode & S_IFLNK)) //! because prints otherwise
		cout << 'l';
	else
		cout << '-';

	cout << ((name.st_mode & S_IRUSR)? "r" : "-" );
	cout << ((name.st_mode & S_IWUSR)? "w" : "-" );
	cout << ((name.st_mode & S_IXUSR)? "x" : "-" );
	cout << ((name.st_mode & S_IRGRP)? "r" : "-" );
	cout << ((name.st_mode & S_IWGRP)? "w" : "-" );
	cout << ((name.st_mode & S_IXGRP)? "x" : "-" );
	cout << ((name.st_mode & S_IROTH)? "r" : "-" );
	cout << ((name.st_mode & S_IWOTH)? "w" : "-" );
	cout << ((name.st_mode & S_IXOTH)? "x" : "-" );
	cout << " " << name.st_nlink << " ";

	struct passwd* p;
	if((p = getpwuid(name.st_uid)) == NULL)
	{
		perror("getpwuid error");
		exit(1);
	}
	else
		cout << p->pw_name << " ";

	struct group* g;
	if((g = getgrgid(name.st_gid)) == NULL)
	{
		perror("getgrgid error");
		exit(1);
	}
	else
		cout << g->gr_name << " ";

	cout << name.st_size << " ";

	string time = ctime(&name.st_mtime);
	if(time.at(time.size() - 1) == '\n')
		time.at(time.size() - 1) = '\0';
	cout << time << " ";
}

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

	//cout << "argc = " << argc << endl;

	bool aFlag = false;
	bool lFlag = false;
	bool RFlag = false;
	bool filesonly = false;

	deque <string> arguments;
	//put all passed in arguments into a vector
	for(int i = 0; i < (argc - 1); i++)
	{
		arguments.push_back(argv[i + 1]);
	}
	//for(unsigned int i = 0; i < arguments.size(); i++)
	//{
	//	cout << arguments.at(i) << endl;
	//}

	//check for directory argument
	deque <string> directories;
	deque <string> flags;
	for(unsigned int i = 0; i < arguments.size(); i++)
	{
		if(arguments.at(i).at(0) == '-') //if argument starts with a -, then it is a flag
			flags.push_back(arguments.at(i));
		else
			directories.push_back(arguments.at(i));
	}
	//cout << "flags: " << endl;
	//for(unsigned int i = 0; i < flags.size(); i++)
	//{
	//	cout << flags.at(i) << endl;
	//}
	//cout << " directories: "<< endl;
	//for(unsigned int i = 0; i < directories.size(); i++)
	//{
	//	cout << directories.at(i);
	//}

	//flag checking
	for(unsigned int i = 0; i < flags.size(); i++)
	{
		for(unsigned int j = 0; j < flags.at(i).size(); j++) //loop through each letter of the flag
		{
			//cout << i << " " << j << " ";
			//cout << flags.at(i).at(j) << endl;
			if(flags.at(i).at(j) == '-') //do nothing
				{}
			else if(flags.at(i).at(j) == 'a')
				aFlag = true;
			else if(flags.at(i).at(j) == 'l')
				lFlag = true;
			else if(flags.at(i).at(j) == 'R')
				RFlag = true;
			else
			{
				perror("invalid flag");
				exit(1);
			}
		}
	}

	if(aFlag || lFlag || RFlag)
		cout << "yay" << endl;

	struct stat name;

	if(directories.size() == 0) //case where no arguments are passed in
		directories.push_back("."); //add current directory as default

	//handle case if file names are passed in
	deque <string> files;
	if(directories.size() > 0)
	{
		for(unsigned int i = 0; i < directories.size(); i++)
		{
			//DIR *directory;

			//Check if argument is a file
			if(stat(directories.at(i).c_str(), &name) == -1)
			{
				perror("stat error");
				directories.erase(directories.begin() + i);
				i--;
			}
			else
			{
				if(!(name.st_mode & S_IFDIR))
				{
					files.push_back(directories.at(i));
					directories.erase(directories.begin() + i);
					i--;
				}
			}
		}
	}
	if(directories.size() == 0)
	{
		filesonly = true;
	}

	//for(unsigned int i = 0; i < directories.size(); i++)
	//	cout << "Listed as dir: " << directories.at(i) << endl;

	//cout << filesonly << endl;
	//for(unsigned int i = 0; i < files.size(); i++)
	//{
	//	cout << "Tracked files: " << files.at(i) << endl;
	//}

	organize(files); //sort files alphabetically

	//for(unsigned int i = 0; i < files.size(); i++)
	//{
	//	cout << "Sorted files: " << files.at(i) << endl;
	//}

	if(filesonly)
	{
		if(!lFlag) //print without -l descriptors
		{
			for(unsigned int i = 0; i < files.size(); i++)
				cout << files.at(i) << "  ";
			cout << endl;
			return 0; //end program
		}
		else //only l flag has effect when only file names a inputted
		{
			for(unsigned int i = 0; i < files.size(); i++)
			{
				if(stat(files.at(i).c_str(), &name) == -1)
					perror("stat error");

				printlFlag(name);
				cout << files.at(i) << endl;
			}
			return 0; //end program
		}
	}

	else //case with directories as args
	{
		for(unsigned int i = 0; i < files.size(); i++)
			cout << files.at(i) << "  "; //print out file arguments first

		if(files.size() > 0)
			cout << endl;
		files.clear();

		organize(directories);
		for(unsigned int i = 0; i < directories.size(); i++)
		{

			DIR* dp;
			if((dp = opendir(directories.at(i).c_str()))==0)
			{
				perror("cannot open dir");
				exit(1);
			}
			dirent* direntp;
			while((direntp = readdir(dp)) != 0) //extract files from directory
			{
				files.push_back(direntp->d_name);
			}
			organize(files); //sort extracted files

			if(!aFlag) //remove hidden files
			{
				for(unsigned int k = 0; k < files.size(); k++)
				{
					if(files.at(k).at(0) == '.')
					{
						files.erase(files.begin() + k); //erase hidden files
						k--;
					}
				}
			}

			if(lFlag)
			{
				int total = 0;
				for(unsigned int h = 0; h < files.size(); h++) //get total block size
				{
					string path = directories.at(i) + "/" + files.at(h);
					if(-1 == (stat(path.c_str(), &name)))
					{
						perror("stat error 1");
						exit(1);
					}
					else
						total += name.st_blocks;

					//cout << total << endl;
				}
				cout << "total " << total/2 << endl; //output total block size
			}

			if(directories.size() > 1) //output directory currently working on
				cout << directories.at(i) << ":" << endl;

			for(unsigned int j = 0; j < files.size(); j++)
			{
				if(lFlag)
				{
					string path = directories.at(i) + "/" + files.at(j);
					if(stat(path.c_str(), &name) == -1)
						perror("stat error 2");

					printlFlag(name);
				}
				cout << files.at(j) << "  ";
				if(lFlag)
					cout << endl;
			}
			cout << endl << endl;
			files.clear();
		}
	}
	return 0;
}
<commit_msg>updated output formatting<commit_after>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <deque>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
#include <algorithm>
#include <pwd.h>
#include <grp.h>
#include <time.h>
using namespace std;

void organize(deque <string> &files)
{
	sort(files.begin(), files.end(), locale("en_US.UTF-8"));
}

void printlFlag(struct stat name)
{
	if(name.st_mode & S_IFDIR)
		cout << 'd';
	else if(!(name.st_mode & S_IFLNK)) //! because prints otherwise
		cout << 'l';
	else
		cout << '-';

	cout << ((name.st_mode & S_IRUSR)? "r" : "-" );
	cout << ((name.st_mode & S_IWUSR)? "w" : "-" );
	cout << ((name.st_mode & S_IXUSR)? "x" : "-" );
	cout << ((name.st_mode & S_IRGRP)? "r" : "-" );
	cout << ((name.st_mode & S_IWGRP)? "w" : "-" );
	cout << ((name.st_mode & S_IXGRP)? "x" : "-" );
	cout << ((name.st_mode & S_IROTH)? "r" : "-" );
	cout << ((name.st_mode & S_IWOTH)? "w" : "-" );
	cout << ((name.st_mode & S_IXOTH)? "x" : "-" );
	cout << " " << name.st_nlink << " ";

	struct passwd* p;
	if((p = getpwuid(name.st_uid)) == NULL)
	{
		perror("getpwuid error");
		exit(1);
	}
	else
		cout << p->pw_name << " ";

	struct group* g;
	if((g = getgrgid(name.st_gid)) == NULL)
	{
		perror("getgrgid error");
		exit(1);
	}
	else
		cout << g->gr_name << " ";

	cout << name.st_size << " ";

	string time = ctime(&name.st_mtime);
	if(time.at(time.size() - 1) == '\n')
		time.at(time.size() - 1) = '\0';
	cout << time << " ";
}

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

	//cout << "argc = " << argc << endl;

	bool aFlag = false;
	bool lFlag = false;
	bool RFlag = false;
	bool filesonly = false;

	deque <string> arguments;
	//put all passed in arguments into a vector
	for(int i = 0; i < (argc - 1); i++)
	{
		arguments.push_back(argv[i + 1]);
	}
	//for(unsigned int i = 0; i < arguments.size(); i++)
	//{
	//	cout << arguments.at(i) << endl;
	//}

	//check for directory argument
	deque <string> directories;
	deque <string> flags;
	for(unsigned int i = 0; i < arguments.size(); i++)
	{
		if(arguments.at(i).at(0) == '-') //if argument starts with a -, then it is a flag
			flags.push_back(arguments.at(i));
		else
			directories.push_back(arguments.at(i));
	}
	//cout << "flags: " << endl;
	//for(unsigned int i = 0; i < flags.size(); i++)
	//{
	//	cout << flags.at(i) << endl;
	//}
	//cout << " directories: "<< endl;
	//for(unsigned int i = 0; i < directories.size(); i++)
	//{
	//	cout << directories.at(i);
	//}

	//flag checking
	for(unsigned int i = 0; i < flags.size(); i++)
	{
		for(unsigned int j = 0; j < flags.at(i).size(); j++) //loop through each letter of the flag
		{
			//cout << i << " " << j << " ";
			//cout << flags.at(i).at(j) << endl;
			if(flags.at(i).at(j) == '-') //do nothing
				{}
			else if(flags.at(i).at(j) == 'a')
				aFlag = true;
			else if(flags.at(i).at(j) == 'l')
				lFlag = true;
			else if(flags.at(i).at(j) == 'R')
				RFlag = true;
			else
			{
				perror("invalid flag");
				exit(1);
			}
		}
	}

	if(aFlag || lFlag || RFlag)
		cout << "yay" << endl;

	struct stat name;

	if(directories.size() == 0) //case where no arguments are passed in
		directories.push_back("."); //add current directory as default

	//handle case if file names are passed in
	deque <string> files;
	if(directories.size() > 0)
	{
		for(unsigned int i = 0; i < directories.size(); i++)
		{
			//DIR *directory;

			//Check if argument is a file
			if(stat(directories.at(i).c_str(), &name) == -1)
			{
				perror("stat error");
				directories.erase(directories.begin() + i);
				i--;
			}
			else
			{
				if(!(name.st_mode & S_IFDIR))
				{
					files.push_back(directories.at(i));
					directories.erase(directories.begin() + i);
					i--;
				}
			}
		}
	}
	if(directories.size() == 0)
	{
		filesonly = true;
	}

	//for(unsigned int i = 0; i < directories.size(); i++)
	//	cout << "Listed as dir: " << directories.at(i) << endl;

	//cout << filesonly << endl;
	//for(unsigned int i = 0; i < files.size(); i++)
	//{
	//	cout << "Tracked files: " << files.at(i) << endl;
	//}

	organize(files); //sort files alphabetically

	//for(unsigned int i = 0; i < files.size(); i++)
	//{
	//	cout << "Sorted files: " << files.at(i) << endl;
	//}

	if(filesonly)
	{
		if(!lFlag) //print without -l descriptors
		{
			for(unsigned int i = 0; i < files.size(); i++)
				cout << files.at(i) << "  ";
			cout << endl;
			return 0; //end program
		}
		else //only l flag has effect when only file names a inputted
		{
			for(unsigned int i = 0; i < files.size(); i++)
			{
				if(stat(files.at(i).c_str(), &name) == -1)
					perror("stat error");

				printlFlag(name);
				cout << files.at(i) << endl;
			}
			return 0; //end program
		}
	}

	else //case with directories as args
	{
		bool otherOutput = false;
		for(unsigned int i = 0; i < files.size(); i++)
			cout << files.at(i) << "  "; //print out file arguments first

		if(files.size() > 0)
		{
			cout << endl << endl;
			otherOutput = true;
		}
		files.clear();

		organize(directories);
		for(unsigned int i = 0; i < directories.size(); i++)
		{

			DIR* dp;
			if((dp = opendir(directories.at(i).c_str()))==0)
			{
				perror("cannot open dir");
				exit(1);
			}
			dirent* direntp;
			while((direntp = readdir(dp)) != 0) //extract files from directory
			{
				files.push_back(direntp->d_name);
			}
			organize(files); //sort extracted files

			if(!aFlag) //remove hidden files
			{
				for(unsigned int k = 0; k < files.size(); k++)
				{
					if(files.at(k).at(0) == '.')
					{
						files.erase(files.begin() + k); //erase hidden files
						k--;
					}
				}
			}

			if(lFlag)
			{
				int total = 0;
				for(unsigned int h = 0; h < files.size(); h++) //get total block size
				{
					string path = directories.at(i) + "/" + files.at(h);
					if(-1 == (stat(path.c_str(), &name)))
					{
						perror("stat error 1");
						exit(1);
					}
					else
						total += name.st_blocks;

					//cout << total << endl;
				}
				cout << "total " << total/2 << endl; //output total block size
			}

			if((directories.size() > 1) || otherOutput) //output directory currently working on
				cout << directories.at(i) << ":" << endl;

			for(unsigned int j = 0; j < files.size(); j++)
			{
				if(lFlag)
				{
					string path = directories.at(i) + "/" + files.at(j);
					if(stat(path.c_str(), &name) == -1)
						perror("stat error 2");

					printlFlag(name);
				}
				cout << files.at(j) << "  ";
				if(lFlag)
					cout << endl;
			}
			cout << endl << endl;
			files.clear();
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>#include "assert.h"
#include "display.h"

void assertFail(const char* expr, const char* file, const char* line,
                const char* function) {
  display::println("\nAssertion failes at {}:{}:{}: expression: {}", file, line,
                   function, expr);
}
<commit_msg>Fix typo.<commit_after>#include "assert.h"
#include "display.h"

void assertFail(const char* expr, const char* file, const char* line,
                const char* function) {
  display::println("\nAssertion failed at {}:{}:{}: expression: {}", file, line,
                   function, expr);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <vector>
#include <boost/algorithm/string/trim.hpp>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdlib>
#include <errno.h>
#include <dirent.h>

using namespace std;
using namespace boost;

void make_strings(int size, char** parse, vector<string> &give)	//converts char** argv into vector of strings for easier use
{
	for(int i = 1; i < size; ++i)
	{
		give.push_back(string(parse[i]));
	}
}

void identify(const vector<string> &commands, vector<char> &flags, vector<int> &dirs , bool &cond)
{
	bool hasa = false;	//this function identifies where the directories are in the command line
	bool hasl = false;	//determines what the flags are, and checks if they are all valid
	bool hasR = false;
	for(unsigned int i = 0; i < commands.size(); ++i)
	{
		if(commands.at(i).at(0) == '-')
		{
			for(unsigned int j = 1; j < commands.at(i).size(); ++j)
			{
				if((commands.at(i).at(j) == 'a') && !hasa)
				{
					flags.push_back(commands.at(i).at(j));
					hasa = true;
				}
				else if((commands.at(i).at(j) == 'l') && !hasl)
				{
					flags.push_back(commands.at(i).at(j));
					hasl = true;
				}
				else if((commands.at(i).at(j) == 'R') && !hasR)
				{
					flags.push_back(commands.at(i).at(j));
					hasR = true;
				}
				else if((commands.at(i).at(j) != 'R') && (commands.at(i).at(j) != 'a') && (commands.at(i).at(j) != 'l'))
				{
					cond = false;
				}
			}
		}
		else
		{
			dirs.push_back(i+1);
		}
	}
}

void getfiles(vector<string> &currfiles, char** argv, const int &loc)	//this function gets all the files and directories
{				//from whatever directory it is pointed to, and stores them in a vector of strings
	DIR *currdir;
	struct dirent *files;
	errno = 0;
	if(NULL == (currdir = opendir(argv[loc])))
	{
		perror("There was an error with opendir(). ");
		exit(1);
	}
	while(NULL != (files = readdir(currdir)))
	{
		currfiles.push_back(string(files->d_name));
	}
	if(errno != 0)
	{
		perror("There was an error with readdir(). ");
		exit(1);
	}
	if(-1 == closedir(currdir))
	{
		perror("There was an error with closedir(). ");
		exit(1);
	}
	sort(currfiles.begin(), currfiles.end());
}

int main(int argc, char **argv)
{
	vector<string> commands;
	vector<int> directories;
	vector<string> dirfiles;
	vector<char> flags;
	bool okay = true;
	make_strings(argc, argv, commands);		//first change all inputs into strings
	identify(commands, flags, directories, okay);
	if(okay)
	{
		cout << "The flags are: ";
		for(unsigned int i = 0; i < flags.size(); ++i)
		{
			cout << flags.at(i) << " ";
		}
		cout << endl;
		cout << "The directories are located at: ";
		for(unsigned int i = 0; i < directories.size(); ++i)
		{
			cout << directories.at(i) << " ";
		}
		cout << endl;
		for(unsigned int i = 0; i < directories.size(); ++i)
		{
			getfiles(dirfiles, argv, directories.at(i));
			cout << commands.at(directories.at(i)-1) << ": " << endl;
			for(unsigned int j = 0; j < dirfiles.size(); ++j)
			{
				cout << dirfiles.at(j) << "    ";
			}
			cout << endl;
			dirfiles.clear();
		}
	}
	else
	{
		cout << "Error: flag not recognized or valid. " << endl;
	}
	return 0;
}
<commit_msg>working on seperating cases<commit_after>#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <vector>
#include <boost/algorithm/string/trim.hpp>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdlib>
#include <errno.h>
#include <dirent.h>

using namespace std;
using namespace boost;

void make_strings(int size, char** parse, vector<string> &give)	//converts char** argv into vector of strings for easier use
{
	for(int i = 1; i < size; ++i)
	{
		give.push_back(string(parse[i]));
	}
}

void identify(const vector<string> &commands, vector<char> &flags, vector<int> &dirs , bool &cond)
{
	bool hasa = false;	//this function identifies where the directories are in the command line
	bool hasl = false;	//determines what the flags are, and checks if they are all valid
	bool hasR = false;
	for(unsigned int i = 0; i < commands.size(); ++i)
	{
		if(commands.at(i).at(0) == '-')
		{
			for(unsigned int j = 1; j < commands.at(i).size(); ++j)
			{
				if((commands.at(i).at(j) == 'a') && !hasa)
				{
					flags.push_back(commands.at(i).at(j));
					hasa = true;
				}
				else if((commands.at(i).at(j) == 'l') && !hasl)
				{
					flags.push_back(commands.at(i).at(j));
					hasl = true;
				}
				else if((commands.at(i).at(j) == 'R') && !hasR)
				{
					flags.push_back(commands.at(i).at(j));
					hasR = true;
				}
				else if((commands.at(i).at(j) != 'R') && (commands.at(i).at(j) != 'a') && (commands.at(i).at(j) != 'l'))
				{
					cond = false;
				}
			}
		}
		else
		{
			dirs.push_back(i+1);
		}
	}
}

void getfiles(vector<string> &currfiles, char** argv, const int &loc)	//this function gets all the files and directories
{				//from whatever directory it is pointed to, and stores them in a vector of strings
	DIR *currdir;
	struct dirent *files;
	errno = 0;
	if(NULL == (currdir = opendir(argv[loc])))
	{
		perror("There was an error with opendir(). ");
		exit(1);
	}
	while(NULL != (files = readdir(currdir)))
	{
		currfiles.push_back(string(files->d_name));
	}
	if(errno != 0)
	{
		perror("There was an error with readdir(). ");
		exit(1);
	}
	if(-1 == closedir(currdir))
	{
		perror("There was an error with closedir(). ");
		exit(1);
	}
	sort(currfiles.begin(), currfiles.end());
}

void outputnorm(vector<string> &display)
{
	int row = 0;
	if(hasa)
	{
		for(unsigned int i = 0; i < display.size(); ++i)
		{
			if(row >= 5)
			{
				cout << endl;
				row = 5;
			}
			else
			{
				row++;
			}
			cout << display.at(i) << "    ";
		}
	}
	else
	{
		for(unsigned int i = 0; i < display.size(); ++i)
		{
			if(row >= 5)
			{
				cout << endl;
				row = 5;
			}
			else
			{
				row++;
			}
			if(display.at(i).at(0) != '.')
			{
				cout << display.at(i) << "    ";
			}
		}
	}
}

int main(int argc, char **argv)
{
	vector<string> commands;
	vector<int> directories;
	vector<string> dirfiles;
	vector<char> flags;
	bool okay = true;
	make_strings(argc, argv, commands);		//first change all inputs into strings
	identify(commands, flags, directories, okay);		//organize and get all the info

	if(okay)	//if no errors in flag, proceed to output
	{
		if(directories.size() > 0)
		{
			cout << "The flags are: ";
			for(unsigned int i = 0; i < flags.size(); ++i)
			{
				cout << flags.at(i) << " ";
			}
			cout << endl;
			cout << "The directories are located at: ";
			for(unsigned int i = 0; i < directories.size(); ++i)
			{
				cout << directories.at(i) << " ";
			}
			cout << endl;
			for(unsigned int i = 0; i < directories.size(); ++i)
			{
				getfiles(dirfiles, argv, directories.at(i));
				cout << commands.at(directories.at(i)-1) << ": " << endl;
				displaynorm(directories);
				dirfiles.clear();
			}
		}
		else
		{

	}
	else
	{
		cout << "Error: flag not recognized or valid. " << endl;
	}
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <vector>
#include <list>
#include <iterator>
#include <fcntl.h>
#include <dirent.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <unistd.h>
#include <cmath>
#include <string.h>
#include <sys/stat.h>

using namespace std;

void list_output(vector<char*> &v)
{
    char *arg[256];
    arg[0] = "stat";
    arg[1] = "-LF";
    for(auto x : v) {
        arg[2] = x;
        pid_t cpid;
        int   status = 0;

        cpid = fork();
        if (cpid == 0) {
            cout << execvp(arg[0], arg) << endl;
        }
        wait(&status);
        if(status < 0)
            perror("Abnormal exit of program ls");
    }
}

void standard_output(vector<char*> &v, int length)
{
    struct winsize w;
    ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
    int check_width = v.size()*length;
    int num_rows = ceil((double)check_width/(double)w.ws_col);

    for(int i = 0; i < num_rows; ++i)
    {
        for(int a = i; a < v.size(); a += num_rows) {
            cout << v.at(a);
            for(int i = strlen(v.at(a)); i < length; ++i)
                cout << " ";
        }
        cout << endl;
    }
}

int main (int argc, char const *argv[])
{
    DIR *dirp;
    string direc = "./";
    bool list = false;
    bool all = false;
    bool recursive = false;
    vector<char*> files;
    int max_length = 9;

    if(argc == 2) {
        string first = argv[1];
        if(first[0] == '-') {
            if(first.find('a') != string::npos)
                all = true;
            if(first.find('l') != string::npos)
                list = true;
            if(first.find('R') != string::npos)
                recursive = true;
        }
        else
            direc = argv[1];
    }

    if(argc > 2) {
        direc = argv[2];
    }

    if(NULL == (dirp = opendir(const_cast<char*>(direc.c_str())))) {
        perror("There was an error with opendir(). ");
        exit(1);
    }

    struct dirent *filespecs;
    errno = 0;
    while(NULL != (filespecs = readdir(dirp))) {
        if(filespecs->d_name[0] == '.' && !all)
            continue;
        files.push_back(filespecs->d_name);
        strlen(filespecs->d_name) > max_length ? max_length = strlen(filespecs->d_name) : max_length;
    }
    if(errno != 0) {
        perror("There was an error with readdir(). ");
        exit(1);
    }

    if(!list)
        standard_output(files, ++max_length);
    else
        list_output(files);

    if(-1 == closedir(dirp)) {
        perror("There was an error with closedir(). ");
        exit(1);
    }
    return 0;
}<commit_msg>Upading ls<commit_after>#include <iostream>
#include <fstream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <vector>
#include <list>
#include <iterator>
#include <fcntl.h>
#include <dirent.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <unistd.h>
#include <cmath>
#include <string.h>
#include <sys/stat.h>
#include <grp.h>
#include <pwd.h>

using namespace std;

void list_output(vector<char*> &v)
{
	struct passwd *pws;
	pws = getpwuid(geteuid());

	struct group *grp;
	grp = getgrgid(getgid());

	int width = 0;
	int total = 0;

	for(auto x : v) {
		int tempWidth = 0;
		struct stat fileStat;
		if(stat(x, &fileStat) < 0)
			perror("Failed");

		total += ceil(fileStat.st_size/512);

		for(; fileStat.st_size != 0; fileStat.st_size /= 10, tempWidth++);
		tempWidth > width ? width = tempWidth : width;
	}

	cout << "total " << total << endl;

    for(auto x : v) {
		struct stat fileStat;
	    if(stat(x, &fileStat) < 0)
			perror("Failed");

		printf( (S_ISDIR(fileStat.st_mode)) ? "d" : "-");
	    printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-");
	    printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-");
	    printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-");
	    printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-");
	    printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-");
	    printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-");
	    printf( (fileStat.st_mode & S_IROTH) ? "r" : "-");
	    printf( (fileStat.st_mode & S_IWOTH) ? "w" : "-");
	    printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-");
		printf("  ");
		printf("%d ",fileStat.st_nlink);
		printf("%s  ", pws->pw_name);
		printf("%s ", grp->gr_name);
		std::cout.width(width);
		cout << std::right << fileStat.st_size << " ";
		struct tm * timeinfo = localtime(&fileStat.st_ctime);
		printf("%s", asctime(timeinfo));

		cout << x << endl;
	}
}

void standard_output(vector<char*> &v, int length)
{
    struct winsize w;
    ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
    int check_width = v.size()*length;
    int num_rows = ceil((double)check_width/(double)w.ws_col);

    for(int i = 0; i < num_rows; ++i)
    {
        for(int a = i; a < v.size(); a += num_rows) {
            cout << v.at(a);
            for(int i = strlen(v.at(a)); i < length; ++i)
                cout << " ";
        }
        cout << endl;
    }
}

int main (int argc, char const *argv[])
{
    DIR *dirp;
    string direc = "./";
    bool list = false;
    bool all = false;
    bool recursive = false;
    vector<char*> files;
    int max_length = 9;

    if(argc == 2) {
        string first = argv[1];
        if(first[0] == '-') {
            if(first.find('a') != string::npos)
                all = true;
            if(first.find('l') != string::npos)
                list = true;
            if(first.find('R') != string::npos)
                recursive = true;
        }
        else
            direc = argv[1];
    }

    if(argc > 2) {
        direc = argv[2];
    }

    if(NULL == (dirp = opendir(const_cast<char*>(direc.c_str())))) {
        perror("There was an error with opendir(). ");
        exit(1);
    }

    struct dirent *filespecs;
    errno = 0;
    while(NULL != (filespecs = readdir(dirp))) {
        if(filespecs->d_name[0] == '.' && !all)
            continue;
        files.push_back(filespecs->d_name);
        strlen(filespecs->d_name) > max_length ? max_length = strlen(filespecs->d_name) : max_length;
    }
    if(errno != 0) {
        perror("There was an error with readdir(). ");
        exit(1);
    }

    if(!list)
        standard_output(files, ++max_length);
    else
        list_output(files);

    if(-1 == closedir(dirp)) {
        perror("There was an error with closedir(). ");
        exit(1);
    }
    return 0;
}<|endoftext|>


<commit_before>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <deque>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
using namespace std;

void printme(string argument, struct stat name)
{
	if(argument.at(0) == '.') //argument is a hidden file
	{
		if(name.st_mode & S_IFDIR) //argument is a directory
		{
		}
		else if(name.st_mode & S_IXUSR) //argument is a usr file
		{
		}
		else //argument is a regular file
		{
		}
	}
	else if(name.st_mode & S_IFDIR) //argument is a directory
	{
	}
	else if(name.st_mode & S_IXUSR) //argument is a usr file
	{
	}
	else //argument is a regular file
		cout << argument;
}

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

	//cout << "argc = " << argc << endl;

	deque <string> arguments;
	//put all passed in arguments into a vector
	for(int i = 0; i < (argc - 1); i++)
	{
		arguments.push_back(argv[i + 1]);
	}
	//for(unsigned int i = 0; i < arguments.size(); i++)
	//{
	//	cout << arguments.at(i) << endl;
	//}

	//check for directory argument
	deque <string> directories;
	deque <string> flags;
	for(unsigned int i = 0; i < arguments.size(); i++)
	{
		if(arguments.at(i).at(0) == '-') //if argument starts with a -, then it is a flag
			flags.push_back(arguments.at(i));
		else
			directories.push_back(arguments.at(i));
	}
	//cout << "flags: " << endl;
	//for(unsigned int i = 0; i < flags.size(); i++)
	//{
	//	cout << flags.at(i) << endl;
	//}
	//cout << " directories: "<< endl;
	//for(unsigned int i = 0; i < directories.size(); i++)
	//{
	//	cout << directories.at(i);
	//}

	//flag checking
	bool aFlag = false;
	bool lFlag = false;
	bool RFlag = false;
	for(unsigned int i = 0; i < flags.size(); i++)
	{
		for(unsigned int j = 0; j < flags.at(i).size(); j++) //loop through each letter of the flag
		{
			//cout << i << " " << j << " ";
			//cout << flags.at(i).at(j) << endl;
			if(flags.at(i).at(j) == '-') //do nothing
				{}
			else if(flags.at(i).at(j) == 'a')
				aFlag = true;
			else if(flags.at(i).at(j) == 'l')
				lFlag = true;
			else if(flags.at(i).at(j) == 'R')
				RFlag = true;
			else
			{
				perror("invalid flag");
				exit(1);
			}
		}
	}

	if(aFlag || lFlag || RFlag)
		cout << "yay" << endl;

	//address directories first
	if(directories.size() > 0)
	{
		//check if valid directory
		struct stat name;
		for(unsigned int i = 0; i < directories.size(); i++)
		{
			if(stat(directories.at(i).c_str(), &name) == -1)
			{
				perror("stat error");
				continue;
			}
			else
			{
				if(!(name.st_mode & S_IFDIR))
				{
					printme(directories.at(i), name);
					continue;
				}
				//cout << directories.at(i) << ": " << endl;
			}
		}
	}
	else
	{
		cout << "yolo" << endl;
	}
	return 0;
}
<commit_msg>commit to save<commit_after>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <deque>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
#include <algorithm>
using namespace std;

void organize(deque <string> files)
{
	sort(files.begin(), files.end());
}

void printme(string argument, struct stat name)
{
	if(argument.at(0) == '.') //argument is a hidden file
	{
		if(name.st_mode & S_IFDIR) //argument is a directory
		{
		}
		else if(name.st_mode & S_IXUSR) //argument is a usr file
		{
		}
		else //argument is a regular file
		{
		}
	}
	else if(name.st_mode & S_IFDIR) //argument is a directory
	{
	}
	else if(name.st_mode & S_IXUSR) //argument is a usr file
	{
	}
	else //argument is a regular file
		cout << argument;
}

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

	//cout << "argc = " << argc << endl;

	bool aFlag = false;
	bool lFlag = false;
	bool RFlag = false;

	deque <string> arguments;
	//put all passed in arguments into a vector
	for(int i = 0; i < (argc - 1); i++)
	{
		arguments.push_back(argv[i + 1]);
	}
	//for(unsigned int i = 0; i < arguments.size(); i++)
	//{
	//	cout << arguments.at(i) << endl;
	//}

	//check for directory argument
	deque <string> directories;
	deque <string> flags;
	for(unsigned int i = 0; i < arguments.size(); i++)
	{
		if(arguments.at(i).at(0) == '-') //if argument starts with a -, then it is a flag
			flags.push_back(arguments.at(i));
		else
			directories.push_back(arguments.at(i));
	}
	//cout << "flags: " << endl;
	//for(unsigned int i = 0; i < flags.size(); i++)
	//{
	//	cout << flags.at(i) << endl;
	//}
	//cout << " directories: "<< endl;
	//for(unsigned int i = 0; i < directories.size(); i++)
	//{
	//	cout << directories.at(i);
	//}

	//flag checking
	for(unsigned int i = 0; i < flags.size(); i++)
	{
		for(unsigned int j = 0; j < flags.at(i).size(); j++) //loop through each letter of the flag
		{
			//cout << i << " " << j << " ";
			//cout << flags.at(i).at(j) << endl;
			if(flags.at(i).at(j) == '-') //do nothing
				{}
			else if(flags.at(i).at(j) == 'a')
				aFlag = true;
			else if(flags.at(i).at(j) == 'l')
				lFlag = true;
			else if(flags.at(i).at(j) == 'R')
				RFlag = true;
			else
			{
				perror("invalid flag");
				exit(1);
			}
		}
	}

	if(aFlag || lFlag || RFlag)
		cout << "yay" << endl;

	//handle whatever is in directories deque
	if(directories.size() > 0)
	{

		struct stat name;
		for(unsigned int i = 0; i < directories.size(); i++)
		{
			deque <string> files;
			DIR *directory;

			//Check if argument is a file
			if(stat(directories.at(i).c_str(), &name) == -1)
			{
				perror("stat error");
				continue;
			}
			else
			{
				if(!(name.st_mode & S_IFDIR))
				{
					printme(directories.at(i), name);
					continue;
				}
				//cout << directories.at(i) << ": " << endl;
			}
			cout <<"hello" << endl;
			//transfer files in directory to files deque
			if(!(directory = opendir(directories.at(i).c_str())))
			{
				perror("cannot open dir");
				exit(1);
			}

			dirent *dirp = readdir(directory);
			while(dirp == readdir(directory))
			{
				if(!(errno == 0))
				{
					perror("error in readdir");
					exit(1);
				}
				files.push_back(dirp->d_name);
			}

			organize(files); //sort the files
			cout << "hello1" << endl;
			for(unsigned int k = 0; k < files.size(); k++)
			{
				cout << files.at(k) << endl;
			}

			//handle hidden files
			if(!aFlag)
			{
				for(unsigned int j = 0; j < files.size(); j++)
				{
					if(files.at(j).at(i) == '.')
					{
						files.erase(files.begin() + j);
						j = j -1;
					}
				}
			}

		}
	}
	else
	{
		cout << "yolo" << endl;
	}
	return 0;
}
<|endoftext|>


<commit_before>// Copyright 2014 Mike Tsao <mike@sowbug.com>

// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include "blockchain.h"

#include <memory>

#include "gtest/gtest.h"
#include "test_constants.h"

static bool TransactionsContain(const std::vector<const Transaction*>
                                transactions,
                                const Blockchain::address_t& expected_addr,
                                uint64_t expected_value) {
// #if defined(BE_LOUD)
//   std::cerr << "START HIST" << std::endl;
//   for (history_t::const_iterator i = history.begin();
//        i != history.end(); ++i) {
//     std::cerr << "Hist: "
//               << to_hex(i->tx_hash())
//               << ": " << Base58::hash160toAddress(i->hash160())
//               << ": " << i->value() << std::endl;
//   }
//   std::cerr << "END HIST" << std::endl;
// #endif

//   for (history_t::const_iterator i = history.begin();
//        i != history.end(); ++i) {
//     if (i->hash160() == expected_addr && i->value() == expected_value) {
//       return true;
//     }
//   }
//   return false;
}

TEST(BlockchainTest, HappyPath) {
  std::auto_ptr<Blockchain> blockchain(new Blockchain);
  Blockchain::address_set_t address_set;
  std::vector<const Transaction*> transactions;
  history_t history;

  EXPECT_EQ(0, blockchain->max_block_height());
  EXPECT_EQ(0, blockchain->GetBlockTimestamp(0));

  blockchain->ConfirmBlock(0, 1231006505);
  EXPECT_EQ(1231006505, blockchain->GetBlockTimestamp(0));

  blockchain->ConfirmBlock(1, 1231469665);
  EXPECT_EQ(1, blockchain->max_block_height());

  blockchain->AddTransaction(TX_0E3E);
  EXPECT_EQ(0, blockchain->GetTransactionHeight(TX_0E3E_HASH));
  blockchain->ConfirmTransaction(TX_0E3E_HASH, 1);
  EXPECT_EQ(1, blockchain->GetTransactionHeight(TX_0E3E_HASH));

  EXPECT_EQ(50 * SATOSHIS_IN_BTC, blockchain->GetAddressBalance(ADDR_12c6));
  EXPECT_EQ(1, blockchain->GetAddressTxCount(ADDR_12c6));

  // History
  address_set.clear();
  address_set.insert(ADDR_12c6);
  blockchain->GetTransactionsForAddresses(address_set, transactions);
  EXPECT_TRUE(TransactionsContain(transactions, ADDR_12c6, 50 * SATOSHIS_IN_BTC));

  // Get all unspent txos.
  Blockchain::address_set_t address_filter;
  tx_outs_t unspent_txos;
  blockchain->GetUnspentTxos(address_filter, unspent_txos);
  EXPECT_EQ(1, unspent_txos.size());

  // Get a filtered unspent txo list that should be the null set.
  address_filter.insert(ADDR_1A1z);
  blockchain->GetUnspentTxos(address_filter, unspent_txos);
  EXPECT_EQ(0, unspent_txos.size());

  // Get a filtered unspent txo list that should be just one item.
  address_filter.insert(ADDR_12c6);
  blockchain->GetUnspentTxos(address_filter, unspent_txos);
  EXPECT_EQ(1, unspent_txos.size());

  address_filter.clear();
  blockchain->AddTransaction(TX_1BCB);
  blockchain->GetUnspentTxos(address_filter, unspent_txos);
  EXPECT_EQ(2, unspent_txos.size());

  // History
  address_set.clear();
  address_set.insert(ADDR_199T);
  blockchain->GetTransactionsForAddresses(address_set, transactions);
  EXPECT_TRUE(TransactionsContain(transactions, ADDR_199T, 29000));

  blockchain->AddTransaction(TX_100D);
  blockchain->GetUnspentTxos(address_filter, unspent_txos);
  EXPECT_EQ(3, unspent_txos.size());
  EXPECT_EQ(14000, blockchain->GetAddressBalance(ADDR_1Guw));
  EXPECT_EQ(1, blockchain->GetAddressTxCount(ADDR_1Guw));

  // History
  address_set.clear();
  address_set.insert(ADDR_1Guw);
  blockchain->GetTransactionsForAddresses(address_set, transactions);
  EXPECT_TRUE(TransactionsContain(transactions, ADDR_1Guw, 13000));

  blockchain->AddTransaction(TX_BFB1);
  blockchain->GetUnspentTxos(address_filter, unspent_txos);
  EXPECT_EQ(3, unspent_txos.size());

  EXPECT_EQ(50 * SATOSHIS_IN_BTC, blockchain->GetAddressBalance(ADDR_12c6));
  EXPECT_EQ(1, blockchain->GetAddressTxCount(ADDR_12c6));
  EXPECT_EQ(27000, blockchain->GetAddressBalance(ADDR_1PB8));
  EXPECT_EQ(2, blockchain->GetAddressTxCount(ADDR_1PB8));
  EXPECT_EQ(0, blockchain->GetAddressBalance(ADDR_1Guw));
  EXPECT_EQ(2, blockchain->GetAddressTxCount(ADDR_1Guw));

  // History
  address_set.clear();
  address_set.insert(ADDR_1Guw);
  blockchain->GetTransactionsForAddresses(address_set, transactions);
  EXPECT_TRUE(TransactionsContain(transactions, ADDR_1Guw, 13000));
  EXPECT_TRUE(TransactionsContain(transactions, ADDR_1Guw, 13000));
}

TEST(BlockchainTest, OutOfOrder) {
  std::auto_ptr<Blockchain> blockchain(new Blockchain);

  blockchain->AddTransaction(TX_BFB1);
  blockchain->AddTransaction(TX_100D);
  blockchain->AddTransaction(TX_1BCB);

  EXPECT_EQ(27000, blockchain->GetAddressBalance(ADDR_1PB8));
  EXPECT_EQ(2, blockchain->GetAddressTxCount(ADDR_1PB8));
  EXPECT_EQ(0, blockchain->GetAddressBalance(ADDR_1Guw));
  EXPECT_EQ(2, blockchain->GetAddressTxCount(ADDR_1Guw));
}
<commit_msg>Separate transactions from history in testing<commit_after>// Copyright 2014 Mike Tsao <mike@sowbug.com>

// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include "blockchain.h"

#include <memory>

#include "gtest/gtest.h"
#include "test_constants.h"

static bool TransactionsContain(const std::vector<const Transaction*>&
                                transactions,
                                const bytes_t& tx_hash) {
#if defined(BE_LOUD)
  std::cerr << "---->" << std::endl;
  for (std::vector<const Transaction*>::const_iterator
         i = transactions.begin();
       i != transactions.end(); ++i) {
    std::cerr << to_hex((*i)->hash()) << std::endl;
  }
  std::cerr << "<----" << std::endl;
#endif

  for (std::vector<const Transaction*>::const_iterator
         i = transactions.begin();
       i != transactions.end(); ++i) {
    if ((*i)->hash() == tx_hash) {
      return true;
    }
  }
  return false;
}

TEST(BlockchainTest, HappyPath) {
  std::auto_ptr<Blockchain> blockchain(new Blockchain);
  Blockchain::address_set_t address_set;
  std::vector<const Transaction*> transactions;
  history_t history;

  EXPECT_EQ(0, blockchain->max_block_height());
  EXPECT_EQ(0, blockchain->GetBlockTimestamp(0));

  blockchain->ConfirmBlock(0, 1231006505);
  EXPECT_EQ(1231006505, blockchain->GetBlockTimestamp(0));

  blockchain->ConfirmBlock(1, 1231469665);
  EXPECT_EQ(1, blockchain->max_block_height());

  blockchain->AddTransaction(TX_0E3E);
  EXPECT_EQ(0, blockchain->GetTransactionHeight(TX_0E3E_HASH));
  blockchain->ConfirmTransaction(TX_0E3E_HASH, 1);
  EXPECT_EQ(1, blockchain->GetTransactionHeight(TX_0E3E_HASH));

  EXPECT_EQ(50 * SATOSHIS_IN_BTC, blockchain->GetAddressBalance(ADDR_12c6));
  EXPECT_EQ(1, blockchain->GetAddressTxCount(ADDR_12c6));

  // Get all unspent txos.
  Blockchain::address_set_t address_filter;
  tx_outs_t unspent_txos;
  blockchain->GetUnspentTxos(address_filter, unspent_txos);
  EXPECT_EQ(1, unspent_txos.size());

  // Get a filtered unspent txo list that should be the null set.
  address_filter.insert(ADDR_1A1z);
  blockchain->GetUnspentTxos(address_filter, unspent_txos);
  EXPECT_EQ(0, unspent_txos.size());

  // Get a filtered unspent txo list that should be just one item.
  address_filter.insert(ADDR_12c6);
  blockchain->GetUnspentTxos(address_filter, unspent_txos);
  EXPECT_EQ(1, unspent_txos.size());

  address_filter.clear();
  blockchain->AddTransaction(TX_1BCB);
  blockchain->GetUnspentTxos(address_filter, unspent_txos);
  EXPECT_EQ(2, unspent_txos.size());

  blockchain->AddTransaction(TX_100D);
  blockchain->GetUnspentTxos(address_filter, unspent_txos);
  EXPECT_EQ(3, unspent_txos.size());
  EXPECT_EQ(14000, blockchain->GetAddressBalance(ADDR_1Guw));
  EXPECT_EQ(1, blockchain->GetAddressTxCount(ADDR_1Guw));

  blockchain->AddTransaction(TX_BFB1);
  blockchain->GetUnspentTxos(address_filter, unspent_txos);
  EXPECT_EQ(3, unspent_txos.size());

  EXPECT_EQ(50 * SATOSHIS_IN_BTC, blockchain->GetAddressBalance(ADDR_12c6));
  EXPECT_EQ(1, blockchain->GetAddressTxCount(ADDR_12c6));
  EXPECT_EQ(27000, blockchain->GetAddressBalance(ADDR_1PB8));
  EXPECT_EQ(2, blockchain->GetAddressTxCount(ADDR_1PB8));
  EXPECT_EQ(0, blockchain->GetAddressBalance(ADDR_1Guw));
  EXPECT_EQ(2, blockchain->GetAddressTxCount(ADDR_1Guw));

  // History
  address_set.clear();
  address_set.insert(ADDR_1Guw);
  blockchain->GetTransactionsForAddresses(address_set, transactions);
  EXPECT_EQ(2, transactions.size());
  EXPECT_TRUE(TransactionsContain(transactions, TX_100D_HASH));
  EXPECT_TRUE(TransactionsContain(transactions, TX_BFB1_HASH));
}

TEST(BlockchainTest, OutOfOrder) {
  std::auto_ptr<Blockchain> blockchain(new Blockchain);

  blockchain->AddTransaction(TX_BFB1);
  blockchain->AddTransaction(TX_100D);
  blockchain->AddTransaction(TX_1BCB);

  EXPECT_EQ(27000, blockchain->GetAddressBalance(ADDR_1PB8));
  EXPECT_EQ(2, blockchain->GetAddressTxCount(ADDR_1PB8));
  EXPECT_EQ(0, blockchain->GetAddressBalance(ADDR_1Guw));
  EXPECT_EQ(2, blockchain->GetAddressTxCount(ADDR_1Guw));
}
<|endoftext|>


<commit_before>#include "vulkan/vulkan.h"
#include <Windows.h>

int CALLBACK
WinMain(
    HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR lpCmdLine,
    int nCmdShow)
{
    auto createInstanceFn = reinterpret_cast<PFN_vkCreateInstance>(vkGetInstanceProcAddr(nullptr, "vkCreateInstance"));
    ::VkInstanceCreateInfo createInfo;
    ::VkAllocationCallbacks allocCbs;
    ::VkInstance instance;
    memset(&createInfo, 0, sizeof(createInfo));
    memset(&allocCbs, 0, sizeof(allocCbs));
    auto result = createInstanceFn(&createInfo, &allocCbs, &instance);
    if (VK_SUCCESS == result)
    {
        auto destroyInstanceFn = reinterpret_cast<PFN_vkDestroyInstance>(vkGetInstanceProcAddr(instance, "vkDestroyInstance"));
        destroyInstanceFn(instance, &allocCbs);
    }
    return 0;
}
<commit_msg>[tests,VulkanCube] Some fixes to the test, but still no cigar on the Vulkan instance<commit_after>#include "vulkan/vulkan.h"
#include <Windows.h>

int CALLBACK
WinMain(
    HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR lpCmdLine,
    int nCmdShow)
{
    auto createInstanceFn = reinterpret_cast<PFN_vkCreateInstance>(vkGetInstanceProcAddr(nullptr, "vkCreateInstance"));
    ::VkInstanceCreateInfo createInfo;
    //::VkAllocationCallbacks allocCbs;
    ::VkInstance instance;
    memset(&createInfo, 0, sizeof(createInfo));
    createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; // required
    //memset(&allocCbs, 0, sizeof(allocCbs));
    auto result = createInstanceFn(&createInfo, nullptr, &instance);
    if (VK_SUCCESS == result)
    {
        auto destroyInstanceFn = reinterpret_cast<PFN_vkDestroyInstance>(vkGetInstanceProcAddr(instance, "vkDestroyInstance"));
        destroyInstanceFn(instance, nullptr);
    }
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <string.h>
#include <sstream>

#include <zorba/zorba.h>
#include <zorba/store_manager.h>
#include <zorba/uri_resolvers.h>
#include <zorba/iterator.h>
#include <zorba/zorba_exception.h>

using namespace zorba;

/** Schema Resolver */
class ValidationTestSchemaURIMapper: public URIMapper
{
public:

  virtual void mapURI(const zorba::String aUri,
    EntityData const* aEntityData,
    std::vector<zorba::String>& oUris) throw ()
  {
    if (aEntityData->getKind() != EntityData::SCHEMA) {
      return;
    }
    if(aUri == "http://www.zorba-xquery.com/helloworld") {
      oUris.push_back("http://zorba-xquery.com/tutorials/helloworld.xsd");
    }
  }
};

bool
item_validation(Zorba* aZorba)
{
  try {
    StaticContext_t lContext = aZorba->createStaticContext();

    ValidationTestSchemaURIMapper lMapper;

    lContext->registerURIMapper(&lMapper);

    std::ostringstream lQueryStream;

    lQueryStream << "import schema namespace h = 'http://www.zorba-xquery.com/helloworld';"
                 << std::endl
                 << "
Hello World!
";

    XQuery_t lQuery = aZorba->compileQuery(lQueryStream.str(), lContext);

    Iterator_t lIterator = lQuery->iterator();
    lIterator->open();

    Item lItem;
    while (lIterator->next(lItem)) {
      Item lValidatedItem;
      if (!lContext->validate(lItem, lValidatedItem)) {
        return false;
      }
    }
    lIterator->close();

  } catch (ZorbaException &e) {
    std::cerr << e << std::endl;
    return false;
  }
  return true;
}

bool
item_validation_with_error(Zorba* aZorba)
{
  try {
    StaticContext_t lContext = aZorba->createStaticContext();

    ValidationTestSchemaURIMapper lMapper;

    lContext->registerURIMapper(&lMapper);

    std::ostringstream lQueryStream;

    lQueryStream << "import schema namespace h = 'http://www.zorba-xquery.com/helloworld';"
                 << std::endl
                 << "3";

    XQuery_t lQuery = aZorba->compileQuery(lQueryStream.str(), lContext);

    Iterator_t lIterator = lQuery->iterator();
    lIterator->open();

    Item lItem;
    while (lIterator->next(lItem)) {
      Item lValidatedItem;
      if (!lContext->validate(lItem, lValidatedItem)) {
        return true; // atomic types can not be validated
      }
    }
    lIterator->close();

  } catch (ZorbaException &e) {
    std::cerr << e << std::endl;
    return false;
  }
  return false;
}

bool
item_validation_with_error2(Zorba* aZorba)
{
  try {
    StaticContext_t lContext = aZorba->createStaticContext();

    ValidationTestSchemaURIMapper lMapper;

    lContext->registerURIMapper(&lMapper);

    std::ostringstream lQueryStream;

    lQueryStream << "import schema namespace h = 'http://www.zorba-xquery.com/helloworld';"
                 << std::endl
                 << "<h:foo><bar/></h:foo>";

    XQuery_t lQuery = aZorba->compileQuery(lQueryStream.str(), lContext);

    Iterator_t lIterator = lQuery->iterator();
    lIterator->open();

    Item lItem;
    while (lIterator->next(lItem)) {
      Item lValidatedItem;
      if (!lContext->validate(lItem, lValidatedItem)) {
        return false;
      }
    }
    lIterator->close();

  } catch (ZorbaException &e) {
    std::cerr << e << std::endl;
    return true;
  }
  return false;
}

int
validate(int argc, char* argv[])
{
  Zorba* lZorba = Zorba::getInstance(zorba::StoreManager::getStore());

  int retval = 0;

  std::cout << "item_validation()" << std::endl;
  if (!item_validation(lZorba)) {
    retval = 1;
    std::cout << "  ...failed!" << std::endl;
  }

  std::cout << "item_validation_with_error()" << std::endl;
  if (!item_validation_with_error(lZorba)) {
    retval = 1;
    std::cout << "  ...failed!" << std::endl;
  }

  std::cout << "item_validatio_nwith_error2()" << std::endl;
  if (!item_validation_with_error2(lZorba)) {
    retval = 1;
    std::cout << "  ...failed!" << std::endl;
  }

  return retval;
}

<commit_msg>Another test using zorba-xquery.com.<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <string.h>
#include <sstream>

#include <zorba/zorba.h>
#include <zorba/store_manager.h>
#include <zorba/uri_resolvers.h>
#include <zorba/iterator.h>
#include <zorba/zorba_exception.h>

using namespace zorba;

/** Schema Resolver */
class ValidationTestSchemaURIMapper: public URIMapper
{
public:

  virtual void mapURI(const zorba::String aUri,
    EntityData const* aEntityData,
    std::vector<zorba::String>& oUris) throw ()
  {
    if (aEntityData->getKind() != EntityData::SCHEMA) {
      return;
    }
    if(aUri == "http://www.zorba-xquery.com/helloworld") {
      oUris.push_back("http://www.zorba-xquery.com/tutorials/helloworld.xsd");
    }
  }
};

bool
item_validation(Zorba* aZorba)
{
  try {
    StaticContext_t lContext = aZorba->createStaticContext();

    ValidationTestSchemaURIMapper lMapper;

    lContext->registerURIMapper(&lMapper);

    std::ostringstream lQueryStream;

    lQueryStream << "import schema namespace h = 'http://www.zorba-xquery.com/helloworld';"
                 << std::endl
                 << "
Hello World!
";

    XQuery_t lQuery = aZorba->compileQuery(lQueryStream.str(), lContext);

    Iterator_t lIterator = lQuery->iterator();
    lIterator->open();

    Item lItem;
    while (lIterator->next(lItem)) {
      Item lValidatedItem;
      if (!lContext->validate(lItem, lValidatedItem)) {
        return false;
      }
    }
    lIterator->close();

  } catch (ZorbaException &e) {
    std::cerr << e << std::endl;
    return false;
  }
  return true;
}

bool
item_validation_with_error(Zorba* aZorba)
{
  try {
    StaticContext_t lContext = aZorba->createStaticContext();

    ValidationTestSchemaURIMapper lMapper;

    lContext->registerURIMapper(&lMapper);

    std::ostringstream lQueryStream;

    lQueryStream << "import schema namespace h = 'http://www.zorba-xquery.com/helloworld';"
                 << std::endl
                 << "3";

    XQuery_t lQuery = aZorba->compileQuery(lQueryStream.str(), lContext);

    Iterator_t lIterator = lQuery->iterator();
    lIterator->open();

    Item lItem;
    while (lIterator->next(lItem)) {
      Item lValidatedItem;
      if (!lContext->validate(lItem, lValidatedItem)) {
        return true; // atomic types can not be validated
      }
    }
    lIterator->close();

  } catch (ZorbaException &e) {
    std::cerr << e << std::endl;
    return false;
  }
  return false;
}

bool
item_validation_with_error2(Zorba* aZorba)
{
  try {
    StaticContext_t lContext = aZorba->createStaticContext();

    ValidationTestSchemaURIMapper lMapper;

    lContext->registerURIMapper(&lMapper);

    std::ostringstream lQueryStream;

    lQueryStream << "import schema namespace h = 'http://www.zorba-xquery.com/helloworld';"
                 << std::endl
                 << "<h:foo><bar/></h:foo>";

    XQuery_t lQuery = aZorba->compileQuery(lQueryStream.str(), lContext);

    Iterator_t lIterator = lQuery->iterator();
    lIterator->open();

    Item lItem;
    while (lIterator->next(lItem)) {
      Item lValidatedItem;
      if (!lContext->validate(lItem, lValidatedItem)) {
        return false;
      }
    }
    lIterator->close();

  } catch (ZorbaException &e) {
    std::cerr << e << std::endl;
    return true;
  }
  return false;
}

int
validate(int argc, char* argv[])
{
  Zorba* lZorba = Zorba::getInstance(zorba::StoreManager::getStore());

  int retval = 0;

  std::cout << "item_validation()" << std::endl;
  if (!item_validation(lZorba)) {
    retval = 1;
    std::cout << "  ...failed!" << std::endl;
  }

  std::cout << "item_validation_with_error()" << std::endl;
  if (!item_validation_with_error(lZorba)) {
    retval = 1;
    std::cout << "  ...failed!" << std::endl;
  }

  std::cout << "item_validatio_nwith_error2()" << std::endl;
  if (!item_validation_with_error2(lZorba)) {
    retval = 1;
    std::cout << "  ...failed!" << std::endl;
  }

  return retval;
}

<|endoftext|>


<commit_before>/*****************************************************************************************
*                                                                                *
* OpenSpace                                                                             *
*                                                                                *
* Copyright (c) 2014-2019                                                               *
*                                                                                *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify,    *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
* permit persons to whom the Software is furnished to do so, subject to the following   *
* conditions:                                                                           *
*                                                                                *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software.                                              *
*                                                                                *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
****************************************************************************************/

#include <modules/autonavigation/pathcurves.h>

#include <modules/autonavigation/helperfunctions.h>
#include <openspace/query/query.h>
#include <openspace/scene/scenegraphnode.h>
#include <ghoul/logging/logmanager.h>
#include <glm/gtx/projection.hpp>

namespace {
constexpr const char* _loggerCat = "PathCurve";
} // namespace

namespace openspace::autonavigation {

PathCurve::~PathCurve() {}

// Approximate the curve length by dividing the curve into smaller linear
// segments and accumulate their length
double PathCurve::arcLength(double tLimit) {
    double dt = 0.01; // TODO: choose a good dt
    double sum = 0.0;
    for (double t = 0.0; t <= tLimit - dt; t += dt) {
        double ds = glm::length(valueAt(t + dt) - valueAt(t));
        sum += ds;
    }
    return sum;
}

// TODO: remove when not needed
// Created for debugging
std::vector<glm::dvec3> PathCurve::getPoints() {
    return _points;
}

Bezier3Curve::Bezier3Curve(CameraState& start, CameraState& end) {
    //TODO try to clean up using variable for nodes
    glm::dvec3 startNodePos = sceneGraphNode(start.referenceNode)->worldPosition();
    glm::dvec3 endNodePos = sceneGraphNode(end.referenceNode)->worldPosition();
    glm::dvec3 startNodeToStartPos = start.position - startNodePos;
    glm::dvec3 endNodeToEndPos = end.position - endNodePos;
    double startNodeRadius = sceneGraphNode(start.referenceNode)->boundingSphere();
    double endNodeRadius = sceneGraphNode(end.referenceNode)->boundingSphere();

    glm::dvec3 startNodeToEndNode = endNodePos - startNodePos;
    glm::dvec3 startToEnd = end.position - start.position;
    double distance = length(startToEnd);

    // Assuming we move straigh out to point to a distance proportional to radius, angle is enough to check collision risk
    double cosStartAngle = glm::dot(normalize(startNodeToStartPos), normalize(startToEnd));
    double cosEndAngle = glm::dot(normalize(endNodeToEndPos), normalize(startToEnd));
    double cosStartDir = glm::dot(normalize(startNodeToStartPos), normalize(endNodeToEndPos));

    //TODO: investigate suitable values, could be risky close to surface..
    bool TARGET_BEHIND_STARTNODE = cosStartAngle < -0.8;
    bool TARGET_BEHIND_ENDNODE = cosEndAngle > 0.8;
    bool TARGET_IN_OPPOSITE_DIRECTION = cosStartAngle > 0.7;

    // Variables that determine behaviour close to start and end
    double startTangentLength = 2.0 * startNodeRadius;
    double endTangentLength = 2.0 * endNodeRadius;

    // SET CONTROL POINTS
    // Start by going outwards
    _points.push_back(start.position);
    _points.push_back(start.position + startTangentLength * normalize(startNodeToStartPos));

    // Avoid collision with startnode by control points on the side of it
    if (TARGET_BEHIND_STARTNODE) {
        glm::dvec3 parallell = glm::proj(startNodeToStartPos, startNodeToEndNode);
        glm::dvec3 orthogonal = normalize(startNodeToStartPos - parallell);
        double dist = 5.0 * startNodeRadius;
        glm::dvec3 extraKnot = startNodePos + dist * orthogonal;

        _points.push_back(extraKnot + parallell);
        _points.push_back(extraKnot);
        _points.push_back(extraKnot - parallell);
    }

    // Zoom out, to get a better understanding in a 180 degree turn situation
    if (TARGET_IN_OPPOSITE_DIRECTION) {
        glm::dvec3 parallell = glm::proj(startNodeToStartPos, startNodeToEndNode);
        glm::dvec3 orthogonal = normalize(startNodeToStartPos - parallell);
        double dist = 0.5 * length(startNodeToEndNode);
        // Distant middle point
        glm::dvec3 extraKnot = startNodePos + dist * normalize(parallell) + 3.0 * dist * orthogonal;

        _points.push_back(extraKnot - 0.3 * dist *  normalize(parallell));
        _points.push_back(extraKnot);
        _points.push_back(extraKnot + 0.3 * dist *  normalize(parallell));
    }

    // Avoid collision with endnode by adding a control points on the side of it
    if (TARGET_BEHIND_ENDNODE) {
        glm::dvec3 parallell = normalize(startNodeToEndNode) * glm::dot(endNodeToEndPos, normalize(startNodeToEndNode));
        glm::dvec3 orthogonal = normalize(endNodeToEndPos - parallell);
        double dist = 5.0 * endNodeRadius;
        glm::dvec3 extraKnot = endNodePos + dist * orthogonal;

        _points.push_back(extraKnot - parallell);
        _points.push_back(extraKnot);
        _points.push_back(extraKnot + parallell);
    }

    _points.push_back(end.position + endTangentLength * normalize(endNodeToEndPos));
    _points.push_back(end.position);
}

glm::dvec3 Bezier3Curve::valueAt(double t) {
    return interpolation::piecewiseCubicBezier(t, _points);
}

LinearCurve::LinearCurve(CameraState& start, CameraState& end) {
    _points.push_back(start.position);
    _points.push_back(end.position);
}

glm::dvec3 LinearCurve::valueAt(double t) {
    return interpolation::linear(t, _points[0], _points[1]);
}

// TODO: Iprove handling of pauses
PauseCurve::PauseCurve(CameraState& state) {
    _points.push_back(state.position);
}

glm::dvec3 PauseCurve::valueAt(double t) {
    return _points[0];
}

} // namespace openspace::autonavigation
<commit_msg>Same anchor bug fix and readability in bezier3<commit_after>/*****************************************************************************************
*                                                                                *
* OpenSpace                                                                             *
*                                                                                *
* Copyright (c) 2014-2019                                                               *
*                                                                                *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify,    *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
* permit persons to whom the Software is furnished to do so, subject to the following   *
* conditions:                                                                           *
*                                                                                *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software.                                              *
*                                                                                *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
****************************************************************************************/

#include <modules/autonavigation/pathcurves.h>

#include <modules/autonavigation/helperfunctions.h>
#include <openspace/query/query.h>
#include <openspace/scene/scenegraphnode.h>
#include <ghoul/logging/logmanager.h>
#include <glm/gtx/projection.hpp>

namespace {
constexpr const char* _loggerCat = "PathCurve";
} // namespace

namespace openspace::autonavigation {

PathCurve::~PathCurve() {}

// Approximate the curve length by dividing the curve into smaller linear
// segments and accumulate their length
double PathCurve::arcLength(double tLimit) {
    double dt = 0.01; // TODO: choose a good dt
    double sum = 0.0;
    for (double t = 0.0; t <= tLimit - dt; t += dt) {
        double ds = glm::length(valueAt(t + dt) - valueAt(t));
        sum += ds;
    }
    return sum;
}

// TODO: remove when not needed
// Created for debugging
std::vector<glm::dvec3> PathCurve::getPoints() {
    return _points;
}

Bezier3Curve::Bezier3Curve(CameraState& start, CameraState& end) {
    glm::dvec3 startNodePos = sceneGraphNode(start.referenceNode)->worldPosition();
    glm::dvec3 endNodePos = sceneGraphNode(end.referenceNode)->worldPosition();
    double startNodeRadius = sceneGraphNode(start.referenceNode)->boundingSphere();
    double endNodeRadius = sceneGraphNode(end.referenceNode)->boundingSphere();

    glm::dvec3 startNodeToStartPos = start.position - startNodePos;
    glm::dvec3 endNodeToEndPos = end.position - endNodePos;

    double startTangentLength = 2.0 * startNodeRadius;
    double endTangentLength = 2.0 * endNodeRadius;
    glm::dvec3 startTangentDirection = normalize(startNodeToStartPos);
    glm::dvec3 endTangentDirection = normalize(endNodeToEndPos);

    // Start by going outwards
    _points.push_back(start.position);
    _points.push_back(start.position + startTangentLength * startTangentDirection);

    if (start.referenceNode != end.referenceNode) {

        glm::dvec3 startNodeToEndNode = endNodePos - startNodePos;
        glm::dvec3 startToEndDirection = normalize(end.position - start.position);

        // Assuming we move straigh out to point to a distance proportional to radius, angle is enough to check collision risk
        double cosStartAngle = glm::dot(startTangentDirection, startToEndDirection);
        double cosEndAngle = glm::dot(endTangentDirection, startToEndDirection);
        double cosStartDir = glm::dot(startTangentDirection, endTangentDirection);

        //TODO: investigate suitable values, could be risky close to surface..
        bool TARGET_BEHIND_STARTNODE = cosStartAngle < -0.8;
        bool TARGET_BEHIND_ENDNODE = cosEndAngle > 0.8;
        bool TARGET_IN_OPPOSITE_DIRECTION = cosStartAngle > 0.7;

        // Avoid collision with startnode by adding control points on the side of it
        if (TARGET_BEHIND_STARTNODE) {
            glm::dvec3 parallell = glm::proj(startNodeToStartPos, startNodeToEndNode);
            glm::dvec3 orthogonal = normalize(startNodeToStartPos - parallell);
            double dist = 5.0 * startNodeRadius;
            glm::dvec3 extraKnot = startNodePos + dist * orthogonal;

            _points.push_back(extraKnot + parallell);
            _points.push_back(extraKnot);
            _points.push_back(extraKnot - parallell);
        }

        // Zoom out, to get a better understanding in a 180 degree turn situation
        if (TARGET_IN_OPPOSITE_DIRECTION) {
            glm::dvec3 parallell = glm::proj(startNodeToStartPos, startNodeToEndNode);
            glm::dvec3 orthogonal = normalize(startNodeToStartPos - parallell);
            double dist = 0.5 * length(startNodeToEndNode);
            // Distant middle point
            glm::dvec3 extraKnot = startNodePos + dist * normalize(parallell) + 3.0 * dist * orthogonal;

            _points.push_back(extraKnot - 0.3 * dist *  normalize(parallell));
            _points.push_back(extraKnot);
            _points.push_back(extraKnot + 0.3 * dist *  normalize(parallell));
        }

        // Avoid collision with endnode by adding control points on the side of it
        if (TARGET_BEHIND_ENDNODE) {
            glm::dvec3 parallell = glm::proj(endNodeToEndPos, startNodeToEndNode);
            glm::dvec3 orthogonal = normalize(endNodeToEndPos - parallell);
            double dist = 5.0 * endNodeRadius;
            glm::dvec3 extraKnot = endNodePos + dist * orthogonal;

            _points.push_back(extraKnot - parallell);
            _points.push_back(extraKnot);
            _points.push_back(extraKnot + parallell);
        }
    }

    _points.push_back(end.position + endTangentLength * endTangentDirection);
    _points.push_back(end.position);
}

glm::dvec3 Bezier3Curve::valueAt(double t) {
    return interpolation::piecewiseCubicBezier(t, _points);
}

LinearCurve::LinearCurve(CameraState& start, CameraState& end) {
    _points.push_back(start.position);
    _points.push_back(end.position);
}

glm::dvec3 LinearCurve::valueAt(double t) {
    return interpolation::linear(t, _points[0], _points[1]);
}

// TODO: Iprove handling of pauses
PauseCurve::PauseCurve(CameraState& state) {
    _points.push_back(state.position);
}

glm::dvec3 PauseCurve::valueAt(double t) {
    return _points[0];
}

} // namespace openspace::autonavigation
<|endoftext|>


<commit_before>/*
 * MPDFactory.cpp
 *****************************************************************************
 * Copyright (C) 2010 - 2012 Klagenfurt University
 *
 * Created on: Jan 27, 2012
 * Authors: Christopher Mueller <christopher.mueller@itec.uni-klu.ac.at>
 *          Christian Timmerer  <christian.timmerer@itec.uni-klu.ac.at>
 *
 * This program 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 program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "MPDFactory.h"

using namespace dash::xml;
using namespace dash::mpd;

MPD* MPDFactory::create             (dash::xml::Node *root, stream_t *p_stream, Profile profile)
{
    IMPDParser *parser = NULL;

    switch( profile )
    {
        case Profile::ISOOnDemand:
        case Profile::ISOMain:
        case Profile::ISOLive:
        case Profile::MPEG2TSSimple:
            parser = new IsoffMainParser(root, p_stream);
        default:
            break;
    }

    if(!parser)
        return NULL;

    MPD* mpd = NULL;
    if(parser->parse(profile))
        mpd = parser->getMPD();

    delete parser;

    return mpd;
}
<commit_msg>demux: dash: enable all profiles<commit_after>/*
 * MPDFactory.cpp
 *****************************************************************************
 * Copyright (C) 2010 - 2012 Klagenfurt University
 *
 * Created on: Jan 27, 2012
 * Authors: Christopher Mueller <christopher.mueller@itec.uni-klu.ac.at>
 *          Christian Timmerer  <christian.timmerer@itec.uni-klu.ac.at>
 *
 * This program 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 program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "MPDFactory.h"

using namespace dash::xml;
using namespace dash::mpd;

MPD* MPDFactory::create             (dash::xml::Node *root, stream_t *p_stream, Profile profile)
{
    IMPDParser *parser = NULL;

    switch( profile )
    {
        case Profile::Unknown:
            break;
        default:
            parser = new IsoffMainParser(root, p_stream);
            break;
    }

    if(!parser)
        return NULL;

    MPD* mpd = NULL;
    if(parser->parse(profile))
        mpd = parser->getMPD();

    delete parser;

    return mpd;
}
<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Flacon - audio File Encoder
 * https://github.com/flacon/flacon
 *
 * Copyright: 2012-2013
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * 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
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "inputaudiofile.h"
#include <settings.h>
#include <QProcess>
#include <QStringList>
#include <QByteArray>
#include <QTextStream>
#include <QDebug>
#include <QFileInfo>
#include <QDir>

void initInputAudioFormat(QList<InputAudioFormat> *formats)
{
    *formats << InputAudioFormat("APE",     "ape",  "mac");
    *formats << InputAudioFormat("FLAC",    "flac", "flac");
    *formats << InputAudioFormat("WavPack", "wv",   "wvunpack");
    *formats << InputAudioFormat("TTA",     "tta",  "ttaenc");
    *formats << InputAudioFormat("WAV",     "wav",  "");
}

/************************************************

 ************************************************/
InputAudioFormat::InputAudioFormat(const QString &name, const QString &ext, const QString &program):
    mName(name),
    mExt(ext),
    mProgram(program)
{
}

/************************************************

 ************************************************/
QList<InputAudioFormat> InputAudioFormat::allFormats()
{
    QList<InputAudioFormat> formats;
    if (formats.count() == 0)
        initInputAudioFormat(&formats);

    return formats;
}

/************************************************

 ************************************************/
InputAudioFile::InputAudioFile(const QString &fileName):
    mFileName(fileName),
    mValid(false),
    mSampleRate(0),
    mCdQuality(false),
    mDuration(0)

{
    mValid = load();
}

/************************************************

 ************************************************/
InputAudioFile::InputAudioFile(const InputAudioFile &other)
{
    mFileName    = other.mFileName;
    mValid       = other.mValid;
    mErrorString = other.mErrorString;
    mSampleRate  = other.mSampleRate;
    mCdQuality   = other.mCdQuality;
    mDuration    = other.mDuration;
}

/************************************************

 ************************************************/
bool InputAudioFile::load()
{
    if (mFileName == "")
    {
        qWarning() << "The audio file name is not set";
        mErrorString = QObject::tr("The audio file name is not set");
        return false;
    }

    if (!QFileInfo(mFileName).exists())
    {
        qWarning() << QString("The audio file \"%1\" does not exist").arg(mFileName);
        mErrorString = QObject::tr("The audio file \"%1\" does not exist").arg(mFileName);
        return false;
    }

    QString shntool = QDir::toNativeSeparators(settings->value(Settings::Prog_Shntool).toString());
    if (shntool.isEmpty())
    {
        qWarning() << "Program shntool not found.";
        mErrorString = QObject::tr("I can't find program %1.").arg("shntool");
        return false;
    }

    QProcess proc;

    QStringList args;
    args << "info";
    args << QDir::toNativeSeparators(mFileName);

    proc.start(shntool, args);

    if (!proc.waitForFinished())
    {
        qWarning("------------------------------------");
        qWarning() << "Test audio command:" << (shntool + " " + args.join(" "));
        qWarning() << "shntool info waitForFinished faild";
        qWarning() << proc.readAllStandardError();
        qWarning("------------------------------------");
        return false;
    }

    if (proc.exitCode() != 0)
    {
        qWarning("------------------------------------");
        qWarning() << "Test audio command:" << (shntool + " " + args.join(" "));
        qWarning() << "shntool info nonzero exit code:" << proc.exitCode();
        qWarning() << proc.readAllStandardError();
        qWarning("------------------------------------");
        mErrorString = QObject::tr("File %1 is not a supported audio file.
"
                                   "
Verify that all required programs are installed and in your preferences.").arg(mFileName);
        return false;
    }

    QTextStream stream(&proc);
    while (!stream.atEnd())
    {
        QString line = stream.readLine();
        QString name = QString(line).section(':', 0, 0).toUpper().trimmed();
        QString value =QString(line).section(':', 1).trimmed();

        if (name == "SAMPLES/SEC")
        {
            mSampleRate = value.toInt();
            continue;
        }

        if (name == "CD QUALITY" && value.toUpper() == "YES")
        {
            mCdQuality = true;
            continue;
        }

        if (name == "LENGTH")
        {
            // 0h 0m 3s - Length:   0:03.00
            // 1h 2m 5s - Length:  62:05.00
            QRegExp re("(\\d+):(\\d+)\\.(\\d+)");
            if (re.exactMatch(value))
            {
                mDuration = re.cap(1).toInt() * 60 * 1000 +
                            re.cap(2).toInt() * 1000 +
                            re.cap(3).toInt();
            }
            continue;
        }
    }

    return true;
}

<commit_msg>Typos: faild should be failed. https://github.com/flacon/flacon/commit/3d4bcfc52f5a1fa1378a41f1151a5da1781ba2ef#commitcomment-15782924<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Flacon - audio File Encoder
 * https://github.com/flacon/flacon
 *
 * Copyright: 2012-2013
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * 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
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "inputaudiofile.h"
#include <settings.h>
#include <QProcess>
#include <QStringList>
#include <QByteArray>
#include <QTextStream>
#include <QDebug>
#include <QFileInfo>
#include <QDir>

void initInputAudioFormat(QList<InputAudioFormat> *formats)
{
    *formats << InputAudioFormat("APE",     "ape",  "mac");
    *formats << InputAudioFormat("FLAC",    "flac", "flac");
    *formats << InputAudioFormat("WavPack", "wv",   "wvunpack");
    *formats << InputAudioFormat("TTA",     "tta",  "ttaenc");
    *formats << InputAudioFormat("WAV",     "wav",  "");
}

/************************************************

 ************************************************/
InputAudioFormat::InputAudioFormat(const QString &name, const QString &ext, const QString &program):
    mName(name),
    mExt(ext),
    mProgram(program)
{
}

/************************************************

 ************************************************/
QList<InputAudioFormat> InputAudioFormat::allFormats()
{
    QList<InputAudioFormat> formats;
    if (formats.count() == 0)
        initInputAudioFormat(&formats);

    return formats;
}

/************************************************

 ************************************************/
InputAudioFile::InputAudioFile(const QString &fileName):
    mFileName(fileName),
    mValid(false),
    mSampleRate(0),
    mCdQuality(false),
    mDuration(0)

{
    mValid = load();
}

/************************************************

 ************************************************/
InputAudioFile::InputAudioFile(const InputAudioFile &other)
{
    mFileName    = other.mFileName;
    mValid       = other.mValid;
    mErrorString = other.mErrorString;
    mSampleRate  = other.mSampleRate;
    mCdQuality   = other.mCdQuality;
    mDuration    = other.mDuration;
}

/************************************************

 ************************************************/
bool InputAudioFile::load()
{
    if (mFileName == "")
    {
        qWarning() << "The audio file name is not set";
        mErrorString = QObject::tr("The audio file name is not set");
        return false;
    }

    if (!QFileInfo(mFileName).exists())
    {
        qWarning() << QString("The audio file \"%1\" does not exist").arg(mFileName);
        mErrorString = QObject::tr("The audio file \"%1\" does not exist").arg(mFileName);
        return false;
    }

    QString shntool = QDir::toNativeSeparators(settings->value(Settings::Prog_Shntool).toString());
    if (shntool.isEmpty())
    {
        qWarning() << "Program shntool not found.";
        mErrorString = QObject::tr("I can't find program %1.").arg("shntool");
        return false;
    }

    QProcess proc;

    QStringList args;
    args << "info";
    args << QDir::toNativeSeparators(mFileName);

    proc.start(shntool, args);

    if (!proc.waitForFinished())
    {
        qWarning("------------------------------------");
        qWarning() << "Test audio command:" << (shntool + " " + args.join(" "));
        qWarning() << "shntool info waitForFinished failed";
        qWarning() << proc.readAllStandardError();
        qWarning("------------------------------------");
        return false;
    }

    if (proc.exitCode() != 0)
    {
        qWarning("------------------------------------");
        qWarning() << "Test audio command:" << (shntool + " " + args.join(" "));
        qWarning() << "shntool info nonzero exit code:" << proc.exitCode();
        qWarning() << proc.readAllStandardError();
        qWarning("------------------------------------");
        mErrorString = QObject::tr("File %1 is not a supported audio file.
"
                                   "
Verify that all required programs are installed and in your preferences.").arg(mFileName);
        return false;
    }

    QTextStream stream(&proc);
    while (!stream.atEnd())
    {
        QString line = stream.readLine();
        QString name = QString(line).section(':', 0, 0).toUpper().trimmed();
        QString value =QString(line).section(':', 1).trimmed();

        if (name == "SAMPLES/SEC")
        {
            mSampleRate = value.toInt();
            continue;
        }

        if (name == "CD QUALITY" && value.toUpper() == "YES")
        {
            mCdQuality = true;
            continue;
        }

        if (name == "LENGTH")
        {
            // 0h 0m 3s - Length:   0:03.00
            // 1h 2m 5s - Length:  62:05.00
            QRegExp re("(\\d+):(\\d+)\\.(\\d+)");
            if (re.exactMatch(value))
            {
                mDuration = re.cap(1).toInt() * 60 * 1000 +
                            re.cap(2).toInt() * 1000 +
                            re.cap(3).toInt();
            }
            continue;
        }
    }

    return true;
}

<|endoftext|>