<commit_before>#include "opengl.h"

#include <SDL.h>

int Abs(int num) {
	return num > 0 ? num : -num;
}

int PingPong(int num, int length) {
	return length - Abs((num % (length * 2)) - length);
}

int main() {

	const int WindowWidth = 960;
	const int WindowHeight = 720;

	if (SDL_Init(SDL_INIT_EVERYTHING)) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	SDL_Window* window = SDL_CreateWindow("SDL OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WindowWidth, WindowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
	if (!window) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	//// OpenGL Setup

	// Options
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	// Connect window
	SDL_GLContext context = SDL_GL_CreateContext(window);

	if (!context) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	OpenGL_Init();

	{
		int value = 0;
		SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value);
		SDL_Log("SDL_GL_CONTEXT_MAJOR_VERSION: %d\n", value);

		SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value);
		SDL_Log("SDL_GL_CONTEXT_MINOR_VERSION: %d\n", value);
	}

	int r, g, b = 0;
	glViewport(0, 0, WindowWidth, WindowHeight);
	glClearColor(0.39f, 0.58f, 0.92f, 1.0f);

	// Triangle data
	GLuint vertexArrayID;
	glGenVertexArrays(1, &vertexArrayID);
	glBindVertexArray(vertexArrayID);

	static const GLfloat vertices[] = {
		-0.5f, -0.5f, 0.0f,
		0.5f, -0.5f, 0.0f,
		0.0f,  0.5f, 0.0f,
	};

	GLuint vertexBufferObjects; // store the buffer in here
	glGenBuffers(1, &vertexBufferObjects); // generated the buffer
	glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjects); // bind our buffer
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

	// Shaders
	const GLchar* vertexShaderSource = "#version 330 core\n"
		"layout (location = 0) in vec3 position;\n"
		"void main()\n"
		"{\n"
		"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
		"}\0";

	const GLchar* fragmentShaderSource = "#version 330 core\n"
		"out vec4 color;\n"
		"void main()\n"
		"{\n"
		"color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
		"}\n\0";

	GLint success;
	GLchar logBuffer[512];

	// Vertex
	GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
	glCompileShader(vertexShader);

	glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
	if (!success) {
		glGetShaderInfoLog(vertexShader, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vertex Compile Error: %s", logBuffer);
	}

	// Fragment
	GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
	glCompileShader(fragmentShader);

	glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
	if (!success) {
		glGetShaderInfoLog(fragmentShader, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Fragment Compile Error: %s", logBuffer);
	}

	// Program
	GLuint shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, vertexShader);
	glAttachShader(shaderProgram, fragmentShader);
	glLinkProgram(shaderProgram);

	glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
	if (!success) {
		glGetProgramInfoLog(shaderProgram, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shader Linking Error: %s", logBuffer);
	}

	glDeleteShader(vertexShader);
	glDeleteShader(fragmentShader);

	bool running = true;
	SDL_Event event;
	while (running) {

		// Input
		while(SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT) {
				running = false;
				break;
			}

			if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) {
				int x = event.window.data1;
				int y = event.window.data2;
				glViewport(0, 0, x, y);
			}
		}

		r = (r + 2) % (255 * 2);
		g = (g + 4) % (255 * 2);
		b = (b + 8) % (255 * 2);

		//Rendering
		glClearColor((float)PingPong(r, 255) / 255, (float)PingPong(g, 255) / 255, (float)PingPong(b, 255) / 255, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// Draw Triangle
		glUseProgram(shaderProgram);
		glEnableVertexAttribArray(0);
		glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjects);
		glVertexAttribPointer(0 /* layout */, /* size */ 3, /* type */ GL_FLOAT, /* normalised? */ GL_FALSE, /* stride */ 0, /* array buffer offset */ (void*)0);

		glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0, draw 3 vertices

		glDisableVertexAttribArray(0);

		SDL_GL_SwapWindow(window);
	}
	return 0;
}<commit_msg>Enabled blending.<commit_after>#include "opengl.h"

#include <SDL.h>

int Abs(int num) {
	return num > 0 ? num : -num;
}

int PingPong(int num, int length) {
	return length - Abs((num % (length * 2)) - length);
}

int main() {

	const int WindowWidth = 960;
	const int WindowHeight = 720;

	if (SDL_Init(SDL_INIT_EVERYTHING)) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	SDL_Window* window = SDL_CreateWindow("SDL OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WindowWidth, WindowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
	if (!window) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	//// OpenGL Setup

	// Options
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	// Connect window
	SDL_GLContext context = SDL_GL_CreateContext(window);

	if (!context) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	OpenGL_Init();

	{
		int value = 0;
		SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value);
		SDL_Log("SDL_GL_CONTEXT_MAJOR_VERSION: %d\n", value);

		SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value);
		SDL_Log("SDL_GL_CONTEXT_MINOR_VERSION: %d\n", value);
	}

	int r, g, b = 0;
	glViewport(0, 0, WindowWidth, WindowHeight);
	glClearColor(0.39f, 0.58f, 0.92f, 1.0f);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	// Triangle data
	GLuint vertexArrayID;
	glGenVertexArrays(1, &vertexArrayID);
	glBindVertexArray(vertexArrayID);

	static const GLfloat vertices[] = {
		-0.5f, -0.5f, 0.0f,
		0.5f, -0.5f, 0.0f,
		0.0f,  0.5f, 0.0f,
	};

	GLuint vertexBufferObjects; // store the buffer in here
	glGenBuffers(1, &vertexBufferObjects); // generated the buffer
	glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjects); // bind our buffer
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

	// Shaders
	const GLchar* vertexShaderSource = "#version 330 core\n"
		"layout (location = 0) in vec3 position;\n"
		"void main()\n"
		"{\n"
		"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
		"}\0";

	const GLchar* fragmentShaderSource = "#version 330 core\n"
		"out vec4 color;\n"
		"void main()\n"
		"{\n"
		"color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
		"}\n\0";

	GLint success;
	GLchar logBuffer[512];

	// Vertex
	GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
	glCompileShader(vertexShader);

	glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
	if (!success) {
		glGetShaderInfoLog(vertexShader, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vertex Compile Error: %s", logBuffer);
	}

	// Fragment
	GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
	glCompileShader(fragmentShader);

	glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
	if (!success) {
		glGetShaderInfoLog(fragmentShader, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Fragment Compile Error: %s", logBuffer);
	}

	// Program
	GLuint shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, vertexShader);
	glAttachShader(shaderProgram, fragmentShader);
	glLinkProgram(shaderProgram);

	glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
	if (!success) {
		glGetProgramInfoLog(shaderProgram, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shader Linking Error: %s", logBuffer);
	}

	glDeleteShader(vertexShader);
	glDeleteShader(fragmentShader);

	bool running = true;
	SDL_Event event;
	while (running) {

		// Input
		while(SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT) {
				running = false;
				break;
			}

			if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) {
				int x = event.window.data1;
				int y = event.window.data2;
				glViewport(0, 0, x, y);
			}
		}

		r = (r + 2) % (255 * 2);
		g = (g + 4) % (255 * 2);
		b = (b + 8) % (255 * 2);

		//Rendering
		glClearColor((float)PingPong(r, 255) / 255, (float)PingPong(g, 255) / 255, (float)PingPong(b, 255) / 255, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// Draw Triangle
		glUseProgram(shaderProgram);
		glEnableVertexAttribArray(0);
		glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjects);
		glVertexAttribPointer(0 /* layout */, /* size */ 3, /* type */ GL_FLOAT, /* normalised? */ GL_FALSE, /* stride */ 0, /* array buffer offset */ (void*)0);

		glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0, draw 3 vertices

		glDisableVertexAttribArray(0);

		SDL_GL_SwapWindow(window);
	}
	return 0;
}<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <string.h>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <stdio.h>
#include <vector>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>

using namespace std;

#define MAXSIZE 10000

void printNoArguments(vector<string> &output)
{
	//cout << "ls with no arguments" << endl; //REMOVE
	for(int i = 0; i < output.size(); i++)
	{
		if(output[i][0] == '.')
		{
			//file is hidden
		}
		else
		{
			cout << output[i] << " ";
		}
	}
	cout << endl;
}
void printAll(vector<string> &output)
{
	//cout << "printAll" << endl; //REMOVE
	for(int i = 0; i < output.size(); i++)
	{
		cout << output[i] << " ";
	}
	cout << endl;
}
void printLong(vector<string> &output)
{
	cout << "printLong" << endl; //REMOVE

}
void printRecursive(vector<string> &output)
{
	cout << "printRecursive" << endl; //REMOVE

}
void printAllLong(vector<string> &output)
{
	cout << "printAllLong" << endl; //REMOVE

}
void printAllRecursive(vector<string> &output)
{
	cout << "printAllRecursive" << endl; //REMOVE

}
void printLongRecursive(vector<string> &output)
{
	cout << "printLongRecursive" << endl; //REMOVE

}
void printAllLongRecursive(vector<string> &output)
{
	cout << "printAllLongRecursive" << endl; //REMOVE

}

void fileSpecs(string &args, vector<string> &output)
{
	//cout << "filespecs" << endl;
	DIR *dirp;
	dirp = opendir(args.c_str());
	if(NULL == dirp)
	{
		perror("opendir()");
		//cout << "opendir" << endl;
		exit(1);
	}
	struct dirent *filespecs;
	while(NULL != (filespecs = readdir(dirp)))
	{
		//cout << "out" << endl;
		output.push_back(filespecs->d_name);
	}
	if(-1 == closedir(dirp))
	{
		//cout << "closedir" << endl;
		perror("closedir");
		exit(1);
	}
}

void ls_define(int argc, char* argv[])//insert parameters
{
	//ls functionality

	//cout << "ls" << endl;//REMOVE

	//fileSpecs(argc, directory_name);

	char* arguments_v[argc];
	string hold_args;
	vector<string> destination;
	int arguments = 0; //000
	int a = 0;
	int args_so_far = 0;
	while(a < argc)
	{
		if(a != 0 && argv[a][0] != '-')
		{
			hold_args = argv[a];
			arguments_v[args_so_far] = argv[a];
			args_so_far++;
		}
		else if(argv[a][0] == '-')
		{
			int b = 0;
			while(argv[a][b] != '\0')
			{
				if(argv[a][b] == 'a')
				{
					arguments = arguments | 1;
				}
				else if(argv[a][b] == 'l')
				{
					arguments = arguments | 2;
				}
				else if(argv[a][b] == 'R')
				{
					arguments = arguments | 4;
				}
				b++;
			}
		}
		a++;
	}
	//cout << args_so_far << endl;

	vector<string> output;

	arguments_v[args_so_far] = NULL;
	if(hold_args == "")
	{
		hold_args = ".";
	}
	if(args_so_far > 0)
	{
		for(int i = 0; i < args_so_far; i++)
		{
			//cout << arguments_v[i] << endl;
		}
		//fileSpecs(hold_args, output);
	}
	fileSpecs(hold_args, output);
	for(int i = 0; i < output.size(); i++)
	{
		//cout << output[i] << endl;
	}
	//cout << "here" << endl;
	sort(output.begin(), output.end());
	switch(arguments)
	{
		case 0:
			printNoArguments(output);
			break;
		case 1:
			printAll(output);
			break;
		case 2:
			printLong(output);
			break;
		case 3:
			printAllLong(output);
			break;
		case 4:
			printRecursive(output);
			break;
		case 5:
			printAllRecursive(output);
			break;
		case 6:
			printLongRecursive(output);
			break;
		case 7:
			printAllLongRecursive(output);
			break;
		default:
			cout << "Something went wrong" << endl; //REMOVE
			break;
	}

}

void get_input(string& usr_input)
{
	char arr[MAXSIZE];
	char* argv[MAXSIZE];
	char* argvcmd[MAXSIZE];

	for(unsigned i = 0; i < MAXSIZE; i++)
	{
		arr[i] = 0;
		argv[i] = 0;
		argvcmd[i] = 0;
	}

	int index = 0;
	int start = 0;
	int j = 0;
	int n = 0;
	int c_cnt = 0;
	int tmp;

	for(unsigned i = 0; i < usr_input.size(); i++)
	{
		tmp = usr_input.at(i);
		if(tmp == ' ' || tmp == ';' || tmp == '&' || tmp == '|' || tmp == '#')
		{
			if(c_cnt > 0)
			{
				argv[j] = (char*)&arr[start];
				j++;
				c_cnt = 0;
				arr[n] = '\0';
				n++;
			}
			start = n;
			if(tmp != ' ')
			{
				if(tmp == '#')
				{
					start = n;
					arr[n++] = ';';
					argv[j] = (char*)&arr[start];
					c_cnt = 0;
					i = usr_input.size();
					j++;
				}
				else if(tmp == ';')
				{
					arr[n++] = ';';
					arr[n++] = '\0';
					argv[j] = (char*)&arr[start];
					start = n;
					j++;
					c_cnt = 0;
				}
				else if(tmp == '&')
				{
					if(usr_input.at(i+1) == '&')
					{
						arr[n++] = '&';
						arr[n++] = '&';
						arr[n++] = '\0';
						argv[j] = (char*)&arr[start];
						j++;
						start = n;
						c_cnt = 0;
						i++;
					}
				}
				else if(tmp == '|')
				{
					if(usr_input.at(i+1) == '|')
					{
						arr[n++] = '|';
						arr[n++] = '|';
						arr[n++] = '\0';
						argv[j] = (char*)&arr[start];
						j++;
						start = n;
						c_cnt = 0;
						i++;
					}
				}
			}
		}
		else
		{
			arr[n] = usr_input.at(i);
			c_cnt++;
			n++;
			if(i == usr_input.size() - 1)
			{
				argv[j] = (char*)&arr[start];
				n++;
				j++;
			}
		}
	}
	if(strcmp(argv[j-1], ";") != 0)
	{
		n++;
		start = n;
		arr[n++] = ';';
		argv[j] = (char*)&arr[start];
		j++;
	}
	argv[j] = (char*)NULL;
	int status;
	for(int i = 0; i < j; i++)
	{
		if(strcmp(argv[i], "&&") == 0 || strcmp(argv[i], "||") == 0 || strcmp(argv[i], ";") == 0)
		{
			int pid;
			pid = fork();
			if(pid < 0)
			{
				perror("fork");
			}
			else if(pid == 0)
			{
				argvcmd[index] = NULL;

				if(!(strcmp(argvcmd[0], "ls")))
				{
					ls_define(index, argvcmd);
				}
				else
				{
					status = execvp(argvcmd[0], argvcmd);
				}

				if(status == -1)
				{
					perror("execvp");
					int x;
					int next = -1;
					if(strcmp(argv[i], "&&") == 0)
					{
						for(x = i + 1; x < j; x++)
						{
							if(strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0)
							{
								next = x;
								break;
							}
						}
						if(next > 0)
						{
							i = next;
						}
					}
				}
				index = 0;
				exit(status);
			}
			else
			{
			}
			waitpid(-1, &status, 0);
			if(strcmp(argv[i], "&&") == 0 && (status > 0))
			{
				int x;
				int next = -1;
				x = i + 1;
				while(x < j)
				{
					if(strcmp(argv[x], "&&") == 0 || strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0)
					{
						next = x;
						break;
					}
					x++;
				}
				if(next > 0)
				{
					i = next;
					next = -1;
				}
			}
			if(strcmp(argv[i], "||") == 0 && (status == 0))
			{
				int x;
				int next = -1;
				x = i + 1;
				while(x < j)
				{
					if(strcmp(argv[x], "&&") == 0 || strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0)
					{
						next = x;
						break;
					}
					x++;
				}
				if(next > 0)
				{
					i = next;
					next = -1;
				}
			}
			index = 0;
		}
		else
		{
			if(index == 0 && (strcmp(argv[i], "exit")) == 0)
			{
				exit(1);
			}
			argvcmd[index] = argv[i];
			index++;
		}
	}
}

void output()
{
	char host[255];
	string login = getlogin();
	gethostname(host, 255);
	cout << login << "@" << host << " ";
	string usr_input;
	cout << "$";
	cout << " ";
	getline(cin, usr_input);
	get_input(usr_input);
}

int main(int argc, char *argv[])
{
	while(1)
	{
		output();
	}
	return 0;
}
<commit_msg>Fixed alphabetical order<commit_after>#include <iostream>
#include <iomanip>
#include <algorithm>
#include <map>
#include <string>
#include <string.h>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <stdio.h>
#include <vector>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>

using namespace std;

#define MAXSIZE 10000
#define TABLE_SIZE 30
void printNoArguments(vector<string> &output)
{
	//cout << "ls with no arguments" << endl; //REMOVE
	for(int unsigned i = 0; i < output.size(); i++)
	{
		if(output[i][0] == '.')
		{
			//file is hidden
		}
		else
		{
			//cout << setw(4);
			cout << output[i] << "  ";
		}
	}
	cout << endl;
}
void printAll(vector<string> &output)
{
	//cout << "printAll" << endl; //REMOVE
	for(unsigned i = 0; i < output.size(); i++)
	{
		//cout << setw(4);
		cout << output[i] << "  ";
	}
	cout << endl;
}
void printLong(vector<string> &output)
{
	cout << "printLong" << endl; //REMOVE

}
void printRecursive(vector<string> &output)
{
	cout << "printRecursive" << endl; //REMOVE

}
void printAllLong(vector<string> &output)
{
	cout << "printAllLong" << endl; //REMOVE

}
void printAllRecursive(vector<string> &output)
{
	cout << "printAllRecursive" << endl; //REMOVE

}
void printLongRecursive(vector<string> &output)
{
	cout << "printLongRecursive" << endl; //REMOVE

}
void printAllLongRecursive(vector<string> &output)
{
	cout << "printAllLongRecursive" << endl; //REMOVE

}
void permissions()
{

}
void fileSpecs(string &args, vector<string> &output)
{
	//cout << "filespecs" << endl;
	DIR *dirp;
	dirp = opendir(args.c_str());
	if(NULL == dirp)
	{
		perror("opendir()");
		//cout << "opendir" << endl;
		exit(1);
	}
	struct dirent *filespecs;
	while(NULL != (filespecs = readdir(dirp)))
	{
		//cout << "out" << endl;
		output.push_back(filespecs->d_name);
	}
	if(-1 == closedir(dirp))
	{
		//cout << "closedir" << endl;
		perror("closedir");
		exit(1);
	}
	//sort(output.begin(), output.end());
}

bool changeCaseCompare(string c1, string c2)
{
	for(int i = 0; i < c1.size(); i++)
	{
		c1.at(i) = tolower(c1.at(i));
	}
	for(int i = 0; i < c2.size(); i++)
	{
		c2.at(i) = tolower(c2.at(i));
	}
	return c1.compare(c2) < 0;
}

void ls_define(int argc, char* argv[])//insert parameters
{
	//ls functionality

	//cout << "ls" << endl;//REMOVE

	//fileSpecs(argc, directory_name);

	//char* arguments_v[10000];
	string hold_args;
	vector<string> destination;
	int arguments = 0; //000
	int a = 0;
	int args_so_far = 0;
	while(a < argc)
	{
		if(a != 0 && argv[a][0] != '-')
		{
			hold_args = argv[a];
			//arguments_v[args_so_far] = argv[a];
			args_so_far++;
		}
		else if(argv[a][0] == '-')
		{
			int b = 0;
			while(argv[a][b] != '\0')
			{
				if(argv[a][b] == 'a')
				{
					arguments = arguments | 1;
				}
				else if(argv[a][b] == 'l')
				{
					arguments = arguments | 2;
				}
				else if(argv[a][b] == 'R')
				{
					arguments = arguments | 4;
				}
				b++;
			}
		}
		a++;
	}
	//cout << args_so_far << endl;

	vector<string> output;

	//arguments_v[args_so_far] = NULL;
	if(hold_args == "")
	{
		hold_args = ".";
	}
	if(args_so_far > 0)
	{
		for(int i = 0; i < args_so_far; i++)
		{
			//cout << arguments_v[i] << endl;
		}
		//fileSpecs(hold_args, output);
	}
	fileSpecs(hold_args, output);
	for(unsigned i = 0; i < output.size(); i++)
	{
		//cout << output[i] << endl;
	}
	//cout << "here" << endl;
	sort(output.begin(), output.end(), changeCaseCompare);
	switch(arguments)
	{
		case 0:
			printNoArguments(output);
			break;
		case 1:
			printAll(output);
			break;
		case 2:
			printLong(output);
			break;
		case 3:
			printAllLong(output);
			break;
		case 4:
			printRecursive(output);
			break;
		case 5:
			printAllRecursive(output);
			break;
		case 6:
			printLongRecursive(output);
			break;
		case 7:
			printAllLongRecursive(output);
			break;
		default:
			cout << "Something went wrong" << endl; //REMOVE
			break;
	}

}

void get_input(string& usr_input)
{
	char arr[MAXSIZE];
	char* argv[MAXSIZE];
	char* argvcmd[MAXSIZE];

	for(unsigned i = 0; i < MAXSIZE; i++)
	{
		arr[i] = 0;
		argv[i] = 0;
		argvcmd[i] = 0;
	}

	int index = 0;
	int start = 0;
	int j = 0;
	int n = 0;
	int c_cnt = 0;
	int tmp;

	for(unsigned i = 0; i < usr_input.size(); i++)
	{
		tmp = usr_input.at(i);
		if(tmp == ' ' || tmp == ';' || tmp == '&' || tmp == '|' || tmp == '#')
		{
			if(c_cnt > 0)
			{
				argv[j] = (char*)&arr[start];
				j++;
				c_cnt = 0;
				arr[n] = '\0';
				n++;
			}
			start = n;
			if(tmp != ' ')
			{
				if(tmp == '#')
				{
					start = n;
					arr[n++] = ';';
					argv[j] = (char*)&arr[start];
					c_cnt = 0;
					i = usr_input.size();
					j++;
				}
				else if(tmp == ';')
				{
					arr[n++] = ';';
					arr[n++] = '\0';
					argv[j] = (char*)&arr[start];
					start = n;
					j++;
					c_cnt = 0;
				}
				else if(tmp == '&')
				{
					if(usr_input.at(i+1) == '&')
					{
						arr[n++] = '&';
						arr[n++] = '&';
						arr[n++] = '\0';
						argv[j] = (char*)&arr[start];
						j++;
						start = n;
						c_cnt = 0;
						i++;
					}
				}
				else if(tmp == '|')
				{
					if(usr_input.at(i+1) == '|')
					{
						arr[n++] = '|';
						arr[n++] = '|';
						arr[n++] = '\0';
						argv[j] = (char*)&arr[start];
						j++;
						start = n;
						c_cnt = 0;
						i++;
					}
				}
			}
		}
		else
		{
			arr[n] = usr_input.at(i);
			c_cnt++;
			n++;
			if(i == usr_input.size() - 1)
			{
				argv[j] = (char*)&arr[start];
				n++;
				j++;
			}
		}
	}
	if(strcmp(argv[j-1], ";") != 0)
	{
		n++;
		start = n;
		arr[n++] = ';';
		argv[j] = (char*)&arr[start];
		j++;
	}
	argv[j] = (char*)NULL;
	int status;
	for(int i = 0; i < j; i++)
	{
		if(strcmp(argv[i], "&&") == 0 || strcmp(argv[i], "||") == 0 || strcmp(argv[i], ";") == 0)
		{
			int pid;
			pid = fork();
			if(pid < 0)
			{
				perror("fork");
			}
			else if(pid == 0)
			{
				argvcmd[index] = NULL;

				if(!(strcmp(argvcmd[0], "ls")))
				{
					ls_define(index, argvcmd);
				}
				else
				{
					status = execvp(argvcmd[0], argvcmd);
				}

				if(status == -1)
				{
					perror("execvp");
					int x;
					int next = -1;
					if(strcmp(argv[i], "&&") == 0)
					{
						for(x = i + 1; x < j; x++)
						{
							if(strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0)
							{
								next = x;
								break;
							}
						}
						if(next > 0)
						{
							i = next;
						}
					}
				}
				index = 0;
				exit(status);
			}
			else
			{
			}
			waitpid(-1, &status, 0);
			if(strcmp(argv[i], "&&") == 0 && (status > 0))
			{
				int x;
				int next = -1;
				x = i + 1;
				while(x < j)
				{
					if(strcmp(argv[x], "&&") == 0 || strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0)
					{
						next = x;
						break;
					}
					x++;
				}
				if(next > 0)
				{
					i = next;
					next = -1;
				}
			}
			if(strcmp(argv[i], "||") == 0 && (status == 0))
			{
				int x;
				int next = -1;
				x = i + 1;
				while(x < j)
				{
					if(strcmp(argv[x], "&&") == 0 || strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0)
					{
						next = x;
						break;
					}
					x++;
				}
				if(next > 0)
				{
					i = next;
					next = -1;
				}
			}
			index = 0;
		}
		else
		{
			if(index == 0 && (strcmp(argv[i], "exit")) == 0)
			{
				exit(1);
			}
			argvcmd[index] = argv[i];
			index++;
		}
	}
}

void output()
{
	char host[255];
	string login = getlogin();
	gethostname(host, 255);
	cout << login << "@" << host << " ";
	string usr_input;
	cout << "$";
	cout << " ";
	getline(cin, usr_input);
	get_input(usr_input);
}

int main(int argc, char *argv[])
{
	while(1)
	{
		output();
	}
	return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "core/framework/debug_node_inputs_outputs_utils.h"

#include <fstream>

#include "gtest/gtest.h"

#include "core/framework/tensorprotoutils.h"
#include "core/platform/env.h"
#include "core/platform/path_lib.h"
#include "test/providers/provider_test_utils.h"
#include "test/util/include/scoped_env_vars.h"
#include "test/util/include/temp_dir.h"

namespace onnxruntime {
namespace test {

namespace {
template <typename T>
void VerifyTensorProtoFileData(const PathString& tensor_proto_path, gsl::span<const T> expected_data) {
  std::ifstream tensor_proto_stream{tensor_proto_path};

  ONNX_NAMESPACE::TensorProto tensor_proto{};
  ASSERT_TRUE(tensor_proto.ParseFromIstream(&tensor_proto_stream));

  std::vector<T> actual_data{};
  actual_data.resize(expected_data.size());
  ASSERT_STATUS_OK(utils::UnpackTensor(tensor_proto, Path{}, actual_data.data(), actual_data.size()));

  ASSERT_EQ(gsl::make_span(actual_data), expected_data);
}
}  // namespace

namespace env_vars = utils::debug_node_inputs_outputs_env_vars;

TEST(DebugNodeInputsOutputs, BasicFileOutput) {
  TemporaryDirectory temp_dir{ORT_TSTR("debug_node_inputs_outputs_utils_test")};
  ScopedEnvironmentVariables scoped_env_vars{
      EnvVarMap{
          {env_vars::kDumpInputData, "1"},
          {env_vars::kDumpOutputData, "1"},
          {env_vars::kNameFilter, nullopt},
          {env_vars::kOpTypeFilter, nullopt},
          {env_vars::kDumpDataDestination, "files"},
          {env_vars::kAppendRankToFileName, nullopt},
          {env_vars::kOutputDir, ToUTF8String(temp_dir.Path())},
          {env_vars::kDumpingDataToFilesForAllNodesIsOk, "1"},
      }};

  OpTester tester{"Round", 11, kOnnxDomain};
  const std::vector<float> input{0.9f, 1.8f};
  tester.AddInput<float>("x", {static_cast<int64_t>(input.size())}, input);
  const std::vector<float> output{1.0f, 2.0f};
  tester.AddOutput<float>("y", {static_cast<int64_t>(output.size())}, output);

  auto verify_file_data =
      [&temp_dir, &input, &output](
          const std::vector<OrtValue>& fetches,
          const std::string& /*provider_type*/) {
        ASSERT_EQ(fetches.size(), 1u);
        FetchTensor(fetches[0]);
        VerifyTensorProtoFileData(
            temp_dir.Path() + ORT_TSTR("/x.tensorproto"),
            gsl::make_span(input));
        VerifyTensorProtoFileData(
            temp_dir.Path() + ORT_TSTR("/y.tensorproto"),
            gsl::make_span(output));
      };

  tester.SetCustomOutputVerifier(verify_file_data);

  tester.Run();
}

}  // namespace test
}  // namespace onnxruntime
<commit_msg>Bug Fix - WASM build break (#13699)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "core/framework/debug_node_inputs_outputs_utils.h"

#include <fstream>

#include "gtest/gtest.h"

#include "core/framework/tensorprotoutils.h"
#include "core/platform/env.h"
#include "core/platform/path_lib.h"
#include "test/providers/provider_test_utils.h"
#include "test/util/include/scoped_env_vars.h"
#include "test/util/include/temp_dir.h"

namespace onnxruntime {
namespace test {

namespace {
template <typename T>
void VerifyTensorProtoFileData(const PathString& tensor_proto_path, gsl::span<const T> expected_data) {
  std::ifstream tensor_proto_stream{tensor_proto_path};

  ONNX_NAMESPACE::TensorProto tensor_proto{};
  ASSERT_TRUE(tensor_proto.ParseFromIstream(&tensor_proto_stream));

  std::vector<T> actual_data{};
  actual_data.resize(expected_data.size());
  ASSERT_STATUS_OK(utils::UnpackTensor(tensor_proto, Path{}, actual_data.data(), actual_data.size()));

  ASSERT_EQ(gsl::span<const T>(actual_data), expected_data);
}
}  // namespace

namespace env_vars = utils::debug_node_inputs_outputs_env_vars;

TEST(DebugNodeInputsOutputs, BasicFileOutput) {
  TemporaryDirectory temp_dir{ORT_TSTR("debug_node_inputs_outputs_utils_test")};
  ScopedEnvironmentVariables scoped_env_vars{
      EnvVarMap{
          {env_vars::kDumpInputData, "1"},
          {env_vars::kDumpOutputData, "1"},
          {env_vars::kNameFilter, nullopt},
          {env_vars::kOpTypeFilter, nullopt},
          {env_vars::kDumpDataDestination, "files"},
          {env_vars::kAppendRankToFileName, nullopt},
          {env_vars::kOutputDir, ToUTF8String(temp_dir.Path())},
          {env_vars::kDumpingDataToFilesForAllNodesIsOk, "1"},
      }};

  OpTester tester{"Round", 11, kOnnxDomain};
  const std::vector<float> input{0.9f, 1.8f};
  tester.AddInput<float>("x", {static_cast<int64_t>(input.size())}, input);
  const std::vector<float> output{1.0f, 2.0f};
  tester.AddOutput<float>("y", {static_cast<int64_t>(output.size())}, output);

  auto verify_file_data =
      [&temp_dir, &input, &output](
          const std::vector<OrtValue>& fetches,
          const std::string& /*provider_type*/) {
        ASSERT_EQ(fetches.size(), 1u);
        FetchTensor(fetches[0]);
        VerifyTensorProtoFileData(
            temp_dir.Path() + ORT_TSTR("/x.tensorproto"),
            gsl::make_span(input));
        VerifyTensorProtoFileData(
            temp_dir.Path() + ORT_TSTR("/y.tensorproto"),
            gsl::make_span(output));
      };

  tester.SetCustomOutputVerifier(verify_file_data);

  tester.Run();
}

}  // namespace test
}  // namespace onnxruntime
<|endoftext|>


<commit_before>#include <iostream>

#include <boost/program_options.hpp>
namespace po = boost::program_options;

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

    // Declare the supported options.
    po::options_description desc("Allowed options");
    desc.add_options()
            ("help", "produce help message");

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << "\n";
        return 1;
    }
    return 0;
}<commit_msg>Updated arguments parsing<commit_after>#include <iostream>
#include <string>

#include <boost/program_options.hpp>
namespace po = boost::program_options;

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

    // Add visibles options
    po::options_description desc("Options");
    desc.add_options()
            ("help,h", "display help");

    // Add hidden options (to specify current operation)
    po::options_description hidden("Hidden options");
    hidden.add_options()
            ("operation", po::value<std::string>(), "operation");

    // Set operation as positional arg
    po::positional_options_description op;
    op.add("operation", -1);

    // Set args and parse them
    po::options_description cmdline_options;
    cmdline_options.add(desc).add(hidden);
    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).
                    options(cmdline_options).positional(op).run(), vm);
    po::notify(vm);

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

    return 0;
}<|endoftext|>


<commit_before>#include <cstdlib>
#include <cstdio>
#include <signal.h>
#include <getopt.h>

int main(int argc, char** argv)
{
	unsigned num_conn = 1;
	unsigned rem_port = 0;
	unsigned loc_port = 0;
	unsigned interval = 0;
	unsigned length = 0;

	int opt;
	while ((opt = getopt(argc, argv, ":hc:p:q:n:i:")) != -1) {
		char* ptr;
		switch (opt) {
			case ':':
				fprintf(stderr, "Option %s requires a value\n", argv[optind-1]);
				return ':';

			case '?':
				fprintf(stderr, "Ignoring unknown option '%c'\n", optopt);
				break;

			case 'h':
				// TODO: Give usage
				return 'h';

			case 'c':
				ptr = NULL;
				if ((num_conn = strtoul(optarg, &ptr, 0)) > 1024 || num_conn < 1 || ptr == NULL || *ptr != '\0') {
					fprintf(stderr, "Option -c requires a valid number of connections [1-1024]\n");
					return 'c';
				}
				break;

			case 'p':
				ptr = NULL;
				if ((rem_port = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') {
					fprintf(stderr, "Option -p requires a valid port number [0-65535]\n");
					return 'p';
				}
				break;

			case 'q':
				ptr = NULL;
				if ((loc_port = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') {
					fprintf(stderr, "Option -q requires a valid port number [0-65535]\n");
					return 'p';
				}
				break;

			case 'n':
				ptr = NULL;
				if ((length = strtoul(optarg, &ptr, 0)) > BUFFER_SIZE || ptr == NULL || *ptr != '\0') {
					fprintf(stderr, "Option -n requires a chunk size in bytes [1-%d] or 0 for off\n", BUFFER_SIZE);
					return 'n';
				}
				break;

			case 'i':
				ptr = NULL;
				if ((interval = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') {
					fprintf(stderr, "Option -i requires an interval in milliseconds [1-65535] or 0 for off\n");
					return 'i';
				}
				break;
		}
	}

	if (optind < argc && rem_port == 0) {
		fprintf(stderr, "Option -p is required for client\n");
		return 'p';
	} else if (optind == argc && loc_port == 0) {
		fprintf(stderr, "Option -q is required for server\n");
		return 'q';
	}

	return 0;
}
<commit_msg>added comments<commit_after>#include <tr1/memory>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <signal.h>
#include <getopt.h>
#include "barrier.h"

using std::vector;
using std::tr1::shared_ptr;

void terminate(void)
{
}

int main(int argc, char** argv)
{
	unsigned num_conn = 1;
	unsigned rem_port = 0;
	unsigned loc_port = 0;
	unsigned interval = 0;
	unsigned length = 0;

	// Parse program arguments and options
	int opt;
	while ((opt = getopt(argc, argv, ":hc:p:q:n:i:")) != -1) {
		char* ptr;
		switch (opt) {

			// Missing a value for the option
			case ':':
				fprintf(stderr, "Option %s requires a value\n", argv[optind-1]);
				return ':';

			// Unknown option was given
			case '?':
				fprintf(stderr, "Ignoring unknown option '%c'\n", optopt);
				break;

			// Print program usage and quit
			case 'h':
				// TODO: Give usage
				return 'h';

			// Set number of connections
			case 'c':
				ptr = NULL;
				if ((num_conn = strtoul(optarg, &ptr, 0)) > 1024 || num_conn < 1 || ptr == NULL || *ptr != '\0') {
					fprintf(stderr, "Option -c requires a valid number of connections [1-1024]\n");
					return 'c';
				}
				break;

			// Set the remote starting port
			case 'p':
				ptr = NULL;
				if ((rem_port = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') {
					fprintf(stderr, "Option -p requires a valid port number [0-65535]\n");
					return 'p';
				}
				break;

			// Set the local starting port
			case 'q':
				ptr = NULL;
				if ((loc_port = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') {
					fprintf(stderr, "Option -q requires a valid port number [0-65535]\n");
					return 'p';
				}
				break;

			// Set the size of the byte chunk to be sent
			case 'n':
				ptr = NULL;
				if ((length = strtoul(optarg, &ptr, 0)) > BUFFER_SIZE || ptr == NULL || *ptr != '\0') {
					fprintf(stderr, "Option -n requires a chunk size in bytes [1-%d] or 0 for off\n", BUFFER_SIZE);
					return 'n';
				}
				break;

			// Set the interval between each time a chunk is sent
			case 'i':
				ptr = NULL;
				if ((interval = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') {
					fprintf(stderr, "Option -i requires an interval in milliseconds [1-65535] or 0 for off\n");
					return 'i';
				}
				break;
		}
	}

	// Check if all mandatory options were set
	if (optind < argc && rem_port == 0) {
		fprintf(stderr, "Option -p is required for client\n");
		return 'p';
	} else if (optind == argc && loc_port == 0) {
		fprintf(stderr, "Option -q is required for server\n");
		return 'q';
	}

	// Handle interrupt signal
	signal(SIGINT, (void (*)(int)) &terminate);

	// Create a barrier
	Barrier barrier(num_conn);

	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

//GLEW
#define GLEW_STATIC
#include <G:\My Documents\comp 371\assgt2\glew-1.13.0-win32\glew-1.13.0\include\GL\glew.h>

//GLFW
#include <G:\My Documents\comp 371\assgt2\glfw-3.1.2.bin.WIN32\glfw-3.1.2.bin.WIN32\include\GLFW\glfw3.h>

// GLM
#include <G:\My Documents\comp 371\assgt2\glm-0.9.6.3\glm\glm\gtc\matrix_transform.hpp>
#include <G:\My Documents\comp 371\assgt2\glm-0.9.6.3\glm\glm\gtc\type_ptr.hpp>
#include <G:\My Documents\comp 371\assgt2\glm-0.9.6.3\glm\glm\glm.hpp>

#include <G:\My Documents\comp 371\assgt2\assgt2\Shader.h>

//set my window dimensions
const GLuint WIDTH = 800, HEIGHT = 800;

//set callback functions here
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods);
void cursor_position_callback(GLFWwindow* window, double xpos,double ypos);
//certain useful variables
double xpos, ypos;
int numOfPoints;
int pointsLeft;
int currentIndex;
bool keys[1024];
GLfloat fov = 45.0f;
glm::vec3 arrayCoordinate[25];
glm::vec3 bezierCoordinate[800];
bool draw = false;

//set certain functions
float bezierX(double p1x, double p2x, double p3x, double p4x, double t);
float bezierY(double p1y, double p2y, double p3y, double p4y, double t);
void drawBezier(GLfloat controlPoints[], int j);
int askForPoints();
GLfloat bezierCurve(float t, GLfloat P0, GLfloat P1, GLfloat P2, GLfloat P3);
void bezierfunction(glm::vec3 array[]);

GLfloat deltaTime = 0.0f;	// Time between current frame and last frame
GLfloat lastFrame = 0.0f;  	// Time of last frame

//CAMERA SETUP
glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 7.0f);
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);

//main program
int main()
{
	pointsLeft = askForPoints();
	numOfPoints = pointsLeft;
	currentIndex = 0;
	//GLFW init
	glfwInit();

	//All required options to make it work
	// Set all the required options for GLFW
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
	//double buffering here
	glfwWindowHint(GLFW_DOUBLEBUFFER, GL_TRUE);
	//make window here
	GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Assignment 2", nullptr, nullptr);
	glfwMakeContextCurrent(window);

	// Set the required callback functions
	//keys
	glfwSetKeyCallback(window, key_callback);
	glfwSetMouseButtonCallback(window, mouse_button_callback);
	glfwSetCursorPosCallback(window, cursor_position_callback);

	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);

	// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
	glewExperimental = GL_TRUE;
	// Initialize GLEW to setup the OpenGL Function pointers
	glewInit();

	// Define the viewport dimensions
	int width, height;
	glfwGetFramebufferSize(window, &width, &height);
	glViewport(0, 0, width, height);

	// Setup OpenGL options
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_PROGRAM_POINT_SIZE);

	//Shader
	Shader ourShader("<G:\My Documents\comp 371\assgt2\assgt2\Shader.vs>","<G:\My Documents\comp 371\assgt2\assgt2\Shader.frag>");
	//use this do draw the points after
	GLfloat vertices[] = {
		0.0f, 0.0f, 0.0f, 1.0f, 0.0f
	};
	//make the arrays
	GLuint VBO, VAO;

	glGenVertexArrays(1, &VAO);
	glGenBuffers(1, &VBO);
	glBindVertexArray(VAO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
	// Position attribute
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); // specifies how vertex array will be processed.
	glEnableVertexAttribArray(0); // enables the setting above

	// Color attribute
	glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); //specifies what position in data is refered to for color.
	glEnableVertexAttribArray(2); // enables the setting above.

	glBindVertexArray(0); // Unbinds the VAO
	glPointSize(4.5f);

	//loop
	while (!glfwWindowShouldClose(window))
	{
		// Calculate deltatime of current frame
		GLfloat currentFrame = glfwGetTime();
		deltaTime = currentFrame - lastFrame;
		lastFrame = currentFrame;

		// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
		glfwPollEvents();
		glfwSetMouseButtonCallback(window, mouse_button_callback);
		glfwGetCursorPos(window, &xpos, &ypos);

		glClearColor(0.5f, 0.0f, 1.0f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		ourShader.Use();

		glm::mat4 view;
		glm::mat4 projection;
		projection = glm::ortho(0.0f, (GLfloat)WIDTH, (GLfloat)HEIGHT, 0.0f, 0.1f, 100.0f);
		view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
		//get locations
		GLint modelLoc = glGetUniformLocation(ourShader.Program, "model");
		GLint viewLoc = glGetUniformLocation(ourShader.Program, "view");
		GLint projLoc = glGetUniformLocation(ourShader.Program, "projection");

		//pass to shaders

		glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
		glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));

		// Draw points
		glBindVertexArray(VAO);
		if (draw == false)
		{
			for (GLuint j = 0; j < numOfPoints; j++)
			{
				glm::mat4 model;
				glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
				model = glm::translate(model, arrayCoordinate[j]);
				glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
				glDrawArrays(GL_POINTS, 0, 1);
			}
		}
		else
		{
			for (int i = 0; i < sizeof(bezierCoordinate); i++)
			{
				glm::mat4 model;
				glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
				model = glm::translate(model, bezierCoordinate[i]);
				glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
				glDrawArrays(GL_POINTS, 0, 1);
			}
		}

		glBindVertexArray(0);
		glfwSwapBuffers(window);
	}
	//clean up memory
	glDeleteVertexArrays(1, &VAO);
	glDeleteBuffers(1, &VBO);
	glfwTerminate();
	return 0;
}

int askForPoints()
{
	bool done = false;
	while (!done)
	{
		std::cout << "Please enter a number of points (N) for the Bezier Splines"<< std::endl;
		std::cin >> numOfPoints;
		if (numOfPoints <= 3)
		{
			std::cout << "The number you entered is not valid, please enter another number of points (N) for the bezier Splines (greater than 3)" << std::endl;
		}
		else
		{
			std::cout << "Your number of points (N) is :" << numOfPoints<< std::endl;
			done = true;
		}
	}
	return numOfPoints;
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
	//escape closes window
	if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){
		glfwSetWindowShouldClose(window, GL_TRUE);
	}
	if (key == GLFW_KEY_L && action == GLFW_PRESS) //draw spline as line
	{
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	}
	if (key == GLFW_KEY_H && action == GLFW_PRESS)
	{
		bezierfunction(arrayCoordinate);
		/*glPointSize(5.0);
		glColor3f(1.0, 1.0, 0.0);
		glBegin(GL_POINTS);
		for (int i = 0; i < sizeof(bezierCoordinate); i++){
			GLfloat holder[1][3];
			holder[0][0] = bezierCoordinate[i].x;
			holder[0][1] = bezierCoordinate[i].y;
			holder[0][2] = bezierCoordinate[i].z;
			glVertex3fv(holder[0]);
		}
		glEnd();
		glFlush();*/
		draw = true;
	}
	if (key == GLFW_KEY_ENTER && action == GLFW_PRESS)// draw spline as fill
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

	if (key == GLFW_KEY_P && action == GLFW_PRESS) // draw spline as points
	{
		glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
	}
}
void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
{

}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
	if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS)
	{
		if (pointsLeft != 0)
		{
			//double xpos, ypos;
			glfwGetCursorPos(window, &xpos, &ypos);
			std::cout << "X :" << xpos << std::endl;
			std::cout << "Y :" << ypos << std::endl;
			//save them in an array
			arrayCoordinate[currentIndex].x = (GLfloat)xpos;
			arrayCoordinate[currentIndex].y = (GLfloat)ypos;//to fix inverted Y axis, do HEIGHT - ypos
			arrayCoordinate[currentIndex].z = 0.0f;
			currentIndex++;
			pointsLeft--;
			std::cout << "You have " << pointsLeft << " points left to chose." << std::endl;
		}
	}
}

//B(t) = (1-t^3)P0 + 3(1-t)^2P1 + 3(1-t)t^2P2 + t^3P3
float bezierX(double p1x, double p2x, double p3x, double p4x, double t)
{
	float answer;
	answer = (pow((1-t),3.0)*p1x)+(3*pow((1-t),2)*t*p2x)+(3*(1-t)*t*t*p3x)+(pow(t,3)*p4x);
	return answer;
}

float bezierY(double p1y, double p2y, double p3y, double p4y, double t)
{
	float answer;
	answer = (pow((1 - t), 3.0)*p1y) + (3 * pow((1 - t), 2)*t*p2y) + (3 * (1 - t)*t*t*p3y) + (pow(t, 3)*p4y);
	return answer;
}
void drawBezier(GLfloat controlPoints[], int j)
{
	double t;
	float x;
	float y;
	for (int i = 1; i <= 40; i++)//40 is the number of segments we want in each one of our bezier splines
	{
		//go through T values
		t = i / 40.0;
		//calculate x coordinate and y coordinate
		x=bezierX(controlPoints[0], controlPoints[2], controlPoints[4], controlPoints[6],t);
		y=bezierY(controlPoints[1], controlPoints[3], controlPoints[5], controlPoints[7],t);
		//now save x and y into a new array, which only holds values of points on the spline
		bezierCoordinate[i-1+j*40].x = x;
		bezierCoordinate[i-1+j*40].y = y;
		bezierCoordinate[i-1+j*40].z = 0.0f;
		//DRAW THE bezierCoordinate array now

	}

}
void bezierfunction(glm::vec3 array[])
{
	int splineNum;
	GLfloat controlPoints[8];
	splineNum = ((numOfPoints - 4) / 3) + 1;//number of seperate bezier splines we will print
	std::cout << "You will have " << splineNum << " bezier splines." << std::endl;
	for (int i = 0; i < splineNum; i++)//for each of these splines, save 4 clicked points (in the right order)
	{
		controlPoints[0] = (GLfloat)array[i*3].x;
		controlPoints[1] = (GLfloat)array[i * 3].y;

		controlPoints[2] = (GLfloat)array[i * 3 + 1].x;
		controlPoints[3] = (GLfloat)array[i * 3 + 1].y;

		controlPoints[4] = (GLfloat)array[i * 3 + 2].x;
		controlPoints[5] = (GLfloat)array[i * 3 + 2].y;

		controlPoints[6] = (GLfloat)array[i * 3 + 3].x;
		controlPoints[7] = (GLfloat)array[i * 3 + 3].y;

		drawBezier(controlPoints, i);
	}
}

<commit_msg>Delete main.cpp<commit_after><|endoftext|>


<commit_before>a3ee839c-4b02-11e5-9f8d-28cfe9171a43<commit_msg>Too poor for Dropbox<commit_after>a3fd22d1-4b02-11e5-b580-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>

#include <boost/mpl/unique.hpp>
#include <boost/mpl/equal.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/placeholders.hpp>

#include <boost/fusion/container/map.hpp>
#include <boost/fusion/include/map.hpp>
#include <boost/fusion/container/map/map_fwd.hpp>
#include <boost/fusion/include/map_fwd.hpp>
#include <boost/fusion/support/pair.hpp>
#include <boost/fusion/include/pair.hpp>
#include <boost/fusion/sequence/intrinsic/has_key.hpp>
#include <boost/fusion/include/has_key.hpp>
#include <boost/fusion/sequence/intrinsic/at_key.hpp>
#include <boost/fusion/include/at_key.hpp>

#include <boost/type_traits/is_same.hpp>

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

template<typename... Types>
struct impl_container {
	template<typename... Args>
	impl_container(const Args&... args)
		:cont(boost::fusion::make_pair<Types>(args...)...)
	{}

	template<typename Iface>
	Iface& get() {
		enum { value = boost::fusion::result_of::has_key<cont_type, Iface>::value };
		static_assert(value, "doesn't contain implementation with this type");
		return checker_helper<void, value>::template apply<Iface>(cont);
	}

	template<typename Iface>
	const Iface& get() const {
		enum { value = boost::fusion::result_of::has_key<cont_type, Iface>::value };
		static_assert(value, "doesn't contain implementation with this type");
		return checker_helper<void, value>::template apply<Iface>(cont);
	}

private:
	template<typename, bool>
	struct checker_helper;

	template<typename Fake>
	struct checker_helper<Fake, true> {
		template<typename T, typename Map>
		static const T& apply(const Map& map) {
			return boost::fusion::at_key<T>(map);
		}

		template<typename T, typename Map>
		static T& apply(Map& map) {
			return boost::fusion::at_key<T>(map);
		}
	};
	template<typename Fake>
	struct checker_helper<Fake, false> {
		template<typename T, typename Map>
		static const T& apply(const Map&) {}

		template<typename T, typename Map>
		static T& apply(Map&) {}
	};

private:
	using cont_type = boost::fusion::map<
		boost::fusion::pair<Types, Types>...
	>;

	cont_type cont;

private:
	using _1 = boost::mpl::placeholders::_1;
	using _2 = boost::mpl::placeholders::_2;

	using types = boost::mpl::vector<Types...>;
	static_assert(
		 boost::mpl::size<
			typename boost::mpl::unique<types, boost::is_same<_1, _2>>::type
		 >::value == sizeof...(Types)
		,"only unique types allowed"
	);
};

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

struct type1 {
	int v;
	type1(int v)
		:v(v)
	{}
	int m() const { return v+v; }
};
struct type2 {
	int v;
	type2(int v)
		:v(v)
	{}
	int m() const { return v+v+v; }
};
struct type3 {
	int v;
	type3(int v)
		:v(v)
	{}
	int m() const { return v+v+v+v; }
};

struct type4 {
	int v;
	type4(int v)
		:v(v)
	{}
	int m() const { return v+v+v+v+v; }
};

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

int main() {
	//impl_container<type1, type1> cont(2); // static assertion: 'only unique types allowed'
	impl_container<type1, type2, type3> cont(2);

	std::cout << cont.get<type1>().m() << std::endl; // 4
	std::cout << cont.get<type2>().m() << std::endl; // 6
	std::cout << cont.get<type3>().m() << std::endl; // 8
	//std::cout << cont.get<type4>().m() << std::endl; // static assertion: 'doesn't contains implementation with this type'
}

/***************************************************************************/
<commit_msg>static assertion message fixed<commit_after>#include <iostream>

#include <boost/mpl/unique.hpp>
#include <boost/mpl/equal.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/placeholders.hpp>

#include <boost/fusion/container/map.hpp>
#include <boost/fusion/include/map.hpp>
#include <boost/fusion/container/map/map_fwd.hpp>
#include <boost/fusion/include/map_fwd.hpp>
#include <boost/fusion/support/pair.hpp>
#include <boost/fusion/include/pair.hpp>
#include <boost/fusion/sequence/intrinsic/has_key.hpp>
#include <boost/fusion/include/has_key.hpp>
#include <boost/fusion/sequence/intrinsic/at_key.hpp>
#include <boost/fusion/include/at_key.hpp>

#include <boost/type_traits/is_same.hpp>

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

template<typename... Types>
struct impl_container {
	template<typename... Args>
	impl_container(const Args&... args)
		:cont(boost::fusion::make_pair<Types>(args...)...)
	{}

	template<typename Iface>
	Iface& get() {
		enum { value = boost::fusion::result_of::has_key<cont_type, Iface>::value };
		static_assert(value, "impl_container doesn't contains implementation with this type");
		return checker_helper<void, value>::template apply<Iface>(cont);
	}

	template<typename Iface>
	const Iface& get() const {
		enum { value = boost::fusion::result_of::has_key<cont_type, Iface>::value };
		static_assert(value, "impl_container doesn't contains implementation with this type");
		return checker_helper<void, value>::template apply<Iface>(cont);
	}

private:
	template<typename, bool>
	struct checker_helper;

	template<typename Fake>
	struct checker_helper<Fake, true> {
		template<typename T, typename Map>
		static const T& apply(const Map& map) {
			return boost::fusion::at_key<T>(map);
		}

		template<typename T, typename Map>
		static T& apply(Map& map) {
			return boost::fusion::at_key<T>(map);
		}
	};
	template<typename Fake>
	struct checker_helper<Fake, false> {
		template<typename T, typename Map>
		static const T& apply(const Map&) {}

		template<typename T, typename Map>
		static T& apply(Map&) {}
	};

private:
	using cont_type = boost::fusion::map<
		boost::fusion::pair<Types, Types>...
	>;

	cont_type cont;

private:
	using _1 = boost::mpl::placeholders::_1;
	using _2 = boost::mpl::placeholders::_2;

	using types = boost::mpl::vector<Types...>;
	static_assert(
		 boost::mpl::size<
			typename boost::mpl::unique<types, boost::is_same<_1, _2>>::type
		 >::value == sizeof...(Types)
		,"only unique types allowed"
	);
};

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

struct type1 {
	int v;
	type1(int v)
		:v(v)
	{}
	int m() const { return v+v; }
};
struct type2 {
	int v;
	type2(int v)
		:v(v)
	{}
	int m() const { return v+v+v; }
};
struct type3 {
	int v;
	type3(int v)
		:v(v)
	{}
	int m() const { return v+v+v+v; }
};

struct type4 {
	int v;
	type4(int v)
		:v(v)
	{}
	int m() const { return v+v+v+v+v; }
};

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

int main() {
	//impl_container<type1, type1> cont(2); // static assertion: 'only unique types allowed'
	impl_container<type1, type2, type3> cont(2);

	std::cout << cont.get<type1>().m() << std::endl; // 4
	std::cout << cont.get<type2>().m() << std::endl; // 6
	std::cout << cont.get<type3>().m() << std::endl; // 8
	//std::cout << cont.get<type4>().m() << std::endl; // static assertion: 'doesn't contains implementation with this type'
}

/***************************************************************************/
<|endoftext|>


<commit_before>404dd882-ad58-11e7-af0b-ac87a332f658<commit_msg>add file<commit_after>40b6b2cf-ad58-11e7-aa81-ac87a332f658<|endoftext|>


<commit_before>/******************************************************************************
 Copyright 2013 Allied Telesis Labs Ltd. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
       this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/

#include <buildsys.h>
#include <color.h>

static bool quietly = false;

void buildsys::log(const char *package, const char *fmt, ...)
{
	char *message = NULL;
	va_list args;
	va_start(args, fmt);
	vasprintf(&message, fmt, args);
	va_end(args);

	fprintf(stderr, "%s: %s\n", package, message);
	free(message);
}

void buildsys::log(Package * P, const char *fmt, ...)
{
	char *message = NULL;
	va_list args;
	va_start(args, fmt);
	vasprintf(&message, fmt, args);
	va_end(args);

	fprintf(quietly ? P->getLogFile() : stderr, "%s,%s: %s\n",
		P->getNS()->getName().c_str(), P->getName().c_str(), message);
	free(message);
}

static inline const char *get_color(const char *mesg)
{
	if(strstr(mesg, "error:"))
		return COLOR_BOLD_RED;
	else if(strstr(mesg, "warning:"))
		return COLOR_BOLD_BLUE;

	return NULL;
}

void buildsys::program_output(Package * P, const char *mesg)
{
	static int isATTY = isatty(fileno(stdout));
	const char *color;

	if(!quietly && isATTY && ((color = get_color(mesg)) != NULL))
		fprintf(stdout, "%s,%s: %s%s%s\n",
			P->getNS()->getName().c_str(), P->getName().c_str(), color, mesg,
			COLOR_RESET);
	else
		fprintf(quietly ? P->getLogFile() : stdout, "%s,%s: %s\n",
			P->getNS()->getName().c_str(), P->getName().c_str(), mesg);
}

int main(int argc, char *argv[])
{
	struct timespec start, end;

	clock_gettime(CLOCK_REALTIME, &start);

	log("BuildSys", "Buildsys (C++ version)");
	log("BuildSys", "Built: %s %s", __TIME__, __DATE__);

	if(argc <= 1) {
		error("At least 1 parameter is required");
		exit(-1);
	}

	World *WORLD = new World(argv[0]);
	hash_setup();

	// process arguments ...
	// first we take a list of package names to exclusevily build
	// this will over-ride any dependency checks and force them to be built
	// without first building their dependencies
	int a = 2;
	bool foundDashDash = false;
	while(a < argc && !foundDashDash) {
		if(!strcmp(argv[a], "--clean")) {
			WORLD->setCleaning();
		} else if(!strcmp(argv[a], "--no-output-prefix")
			  || !strcmp(argv[a], "--nop")) {
			WORLD->clearOutputPrefix();
		} else if(!strcmp(argv[a], "--cache-server") || !strcmp(argv[a], "--ff")) {
			WORLD->setFetchFrom(argv[a + 1]);
			a++;
		} else if(!strcmp(argv[a], "--tarball-cache")) {
			log("BuildSys", "Setting tarball cache to %s", argv[a + 1]);
			WORLD->setTarballCache(argv[a + 1]);
			a++;
		} else if(!strcmp(argv[a], "--overlay")) {
			WORLD->addOverlayPath(std::string(argv[a + 1]));
			a++;
		} else if(!strcmp(argv[a], "--extract-only")) {
			WORLD->setExtractOnly();
		} else if(!strcmp(argv[a], "--build-info-ignore-fv")) {
			WORLD->ignoreFeature(std::string(argv[a + 1]));
			a++;
		} else if(!strcmp(argv[a], "--parse-only")) {
			WORLD->setParseOnly();
		} else if(!strcmp(argv[a], "--keep-going")) {
			WORLD->setKeepGoing();
		} else if(!strcmp(argv[a], "--quietly")) {
			quietly = true;
		} else if(!strcmp(argv[a], "--parallel-packages") || !strcmp(argv[a], "-j")) {
			WORLD->setThreadsLimit(atoi(argv[a + 1]));
			a++;
		} else if(!strcmp(argv[a], "--")) {
			foundDashDash = true;
		} else {
			WORLD->forceBuild(argv[a]);
		}
		a++;
	}
	// then we find a --
	if(foundDashDash) {
		// then we can preload the feature set
		while(a < argc) {
			if(!WORLD->setFeature(argv[a])) {
				error("setFeature: Failed");
				exit(-1);
			}
			a++;
		}
	}
	std::string target("");
	int tn_len = strlen(argv[1]);
	if(argv[1][tn_len - 4] != '.') {
		target = string_format("%s.lua", argv[1]);
	} else {
		target = std::string(argv[1]);
	}

	if(WORLD->noIgnoredFeatures()) {
		// Implement old behaviour
		WORLD->ignoreFeature("job-limit");
		WORLD->ignoreFeature("load-limit");
	}

	if(!WORLD->basePackage(target)) {
		error("Building: Failed");
		if(WORLD->areKeepGoing()) {
			delete WORLD;
			hash_shutdown();
		}
		exit(-1);
	}

	if(WORLD->areParseOnly()) {
		// Print all the feature/values
		WORLD->printFeatureValues();
	}
	// Write out the dependency graph
	WORLD->output_graph();

	clock_gettime(CLOCK_REALTIME, &end);

	if(end.tv_nsec >= start.tv_nsec)
		log(argv[1], "Total time: %ds and %dms",
		    (end.tv_sec - start.tv_sec), (end.tv_nsec - start.tv_nsec) / 1000000);
	else
		log(argv[1], "Total time: %ds and %dms",
		    (end.tv_sec - start.tv_sec - 1),
		    (1000 + end.tv_nsec / 1000000) - start.tv_nsec / 1000000);

	delete WORLD;
	hash_shutdown();

	return 0;
}
<commit_msg>main: Use stack memory for WORLD, rather than heap<commit_after>/******************************************************************************
 Copyright 2013 Allied Telesis Labs Ltd. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
       this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/

#include <buildsys.h>
#include <color.h>

static bool quietly = false;

void buildsys::log(const char *package, const char *fmt, ...)
{
	char *message = NULL;
	va_list args;
	va_start(args, fmt);
	vasprintf(&message, fmt, args);
	va_end(args);

	fprintf(stderr, "%s: %s\n", package, message);
	free(message);
}

void buildsys::log(Package * P, const char *fmt, ...)
{
	char *message = NULL;
	va_list args;
	va_start(args, fmt);
	vasprintf(&message, fmt, args);
	va_end(args);

	fprintf(quietly ? P->getLogFile() : stderr, "%s,%s: %s\n",
		P->getNS()->getName().c_str(), P->getName().c_str(), message);
	free(message);
}

static inline const char *get_color(const char *mesg)
{
	if(strstr(mesg, "error:"))
		return COLOR_BOLD_RED;
	else if(strstr(mesg, "warning:"))
		return COLOR_BOLD_BLUE;

	return NULL;
}

void buildsys::program_output(Package * P, const char *mesg)
{
	static int isATTY = isatty(fileno(stdout));
	const char *color;

	if(!quietly && isATTY && ((color = get_color(mesg)) != NULL))
		fprintf(stdout, "%s,%s: %s%s%s\n",
			P->getNS()->getName().c_str(), P->getName().c_str(), color, mesg,
			COLOR_RESET);
	else
		fprintf(quietly ? P->getLogFile() : stdout, "%s,%s: %s\n",
			P->getNS()->getName().c_str(), P->getName().c_str(), mesg);
}

int main(int argc, char *argv[])
{
	struct timespec start, end;

	clock_gettime(CLOCK_REALTIME, &start);

	log("BuildSys", "Buildsys (C++ version)");
	log("BuildSys", "Built: %s %s", __TIME__, __DATE__);

	if(argc <= 1) {
		error("At least 1 parameter is required");
		exit(-1);
	}

	World WORLD(argv[0]);
	hash_setup();

	// process arguments ...
	// first we take a list of package names to exclusevily build
	// this will over-ride any dependency checks and force them to be built
	// without first building their dependencies
	int a = 2;
	bool foundDashDash = false;
	while(a < argc && !foundDashDash) {
		if(!strcmp(argv[a], "--clean")) {
			WORLD.setCleaning();
		} else if(!strcmp(argv[a], "--no-output-prefix")
			  || !strcmp(argv[a], "--nop")) {
			WORLD.clearOutputPrefix();
		} else if(!strcmp(argv[a], "--cache-server") || !strcmp(argv[a], "--ff")) {
			WORLD.setFetchFrom(argv[a + 1]);
			a++;
		} else if(!strcmp(argv[a], "--tarball-cache")) {
			log("BuildSys", "Setting tarball cache to %s", argv[a + 1]);
			WORLD.setTarballCache(argv[a + 1]);
			a++;
		} else if(!strcmp(argv[a], "--overlay")) {
			WORLD.addOverlayPath(std::string(argv[a + 1]));
			a++;
		} else if(!strcmp(argv[a], "--extract-only")) {
			WORLD.setExtractOnly();
		} else if(!strcmp(argv[a], "--build-info-ignore-fv")) {
			WORLD.ignoreFeature(std::string(argv[a + 1]));
			a++;
		} else if(!strcmp(argv[a], "--parse-only")) {
			WORLD.setParseOnly();
		} else if(!strcmp(argv[a], "--keep-going")) {
			WORLD.setKeepGoing();
		} else if(!strcmp(argv[a], "--quietly")) {
			quietly = true;
		} else if(!strcmp(argv[a], "--parallel-packages") || !strcmp(argv[a], "-j")) {
			WORLD.setThreadsLimit(atoi(argv[a + 1]));
			a++;
		} else if(!strcmp(argv[a], "--")) {
			foundDashDash = true;
		} else {
			WORLD.forceBuild(argv[a]);
		}
		a++;
	}
	// then we find a --
	if(foundDashDash) {
		// then we can preload the feature set
		while(a < argc) {
			if(!WORLD.setFeature(argv[a])) {
				error("setFeature: Failed");
				exit(-1);
			}
			a++;
		}
	}
	std::string target("");
	int tn_len = strlen(argv[1]);
	if(argv[1][tn_len - 4] != '.') {
		target = string_format("%s.lua", argv[1]);
	} else {
		target = std::string(argv[1]);
	}

	if(WORLD.noIgnoredFeatures()) {
		// Implement old behaviour
		WORLD.ignoreFeature("job-limit");
		WORLD.ignoreFeature("load-limit");
	}

	if(!WORLD.basePackage(target)) {
		error("Building: Failed");
		if(WORLD.areKeepGoing()) {
			hash_shutdown();
		}
		exit(-1);
	}

	if(WORLD.areParseOnly()) {
		// Print all the feature/values
		WORLD.printFeatureValues();
	}
	// Write out the dependency graph
	WORLD.output_graph();

	clock_gettime(CLOCK_REALTIME, &end);

	if(end.tv_nsec >= start.tv_nsec)
		log(argv[1], "Total time: %ds and %dms",
		    (end.tv_sec - start.tv_sec), (end.tv_nsec - start.tv_nsec) / 1000000);
	else
		log(argv[1], "Total time: %ds and %dms",
		    (end.tv_sec - start.tv_sec - 1),
		    (1000 + end.tv_nsec / 1000000) - start.tv_nsec / 1000000);

	hash_shutdown();

	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <sstream>
#include <tuple>
using namespace std;

class ChildStuntedness5 {
  // 普通の
  int testType;
  int scenario;
  vector<string> training;
  vector<string> testing;
  // 自分の
  vector< vector<string> > test_case_st;
  //  main theorems
public:
  vector<double> predict(int _testType, int _scenario,
                         vector<string> _training, vector<string> _testing) {
    testType = _testType;
    scenario = _scenario;
    training = _training;
    testing = _testing;
    make_training();
    vector<double> X;
    return X;
  }
  // lemmas
private:
  vector<string> split(string S) { // コンマでsprit
    vector<string> ans;
    stringstream ss;
    string s;
    while(getline(ss, s, ',')) {
      ans.push_back(s);
    }
    return ans;
  }
  void make_test_case_st() {
    int N = testing.size();
    for (auto i=0; i<N; i++) {
      vector<string> sps = split(testing[i]);
      test_case_st.push_back(sps);
    }
  }
  void make_training() {

  }
};
<commit_msg>残差2乗和まで<commit_after>#include <iostream>
#include <vector>
#include <sstream>
#include <tuple>
#include <algorithm>
using namespace std;

class ChildStuntedness5 {
private:
  // 普通の
  int testType;
  int scenario;
  vector<string> training;
  vector<string> testing;
  // 定数
  const double NA = -1000;
  const int IQ_col = 26;
  const vector< vector<int> > used_col =
    { {11, 13, 14, 15, 16, 17},
      {1, 2, 3, 4, 5, 6, 7, 8, 9},
      {10, 12, 18, 19, 20, 21, 22, 23, 24, 25}
    };
  // 自分の
  vector< vector<string> > test_case_st;
  vector< vector<double> > test_case;
  double A[100]; // 係数部分
  double B[100]; // 定数部分 IQ = Ax + B
  double zansa[100];
  // lemmas
  vector<string> split(string S) { // コンマでsprit
    vector<string> ans;
    stringstream ss(S);
    string s;
    while(getline(ss, s, ',')) {
      ans.push_back(s);
    }
    return ans;
  }
  void make_test_case_st() { // testingをsplit
    int N = testing.size();
    for (auto i=0; i<N; i++) {
      vector<string> sps = split(testing[i]);
      test_case_st.push_back(sps);
    }
  }
  void convert_double() { // doubleにする
    test_case = vector< vector<double> >(test_case_st.size(),
                                         vector<double>());
    for (auto i=0; i<test_case_st.size(); i++) {
      for (auto j=0; j<test_case_st[i].size(); j++) {
        if (test_case_st[i][j] == "NA") {
          test_case[i][j] = NA;
        } else {
          test_case[i][j] = stof(test_case_st[i][j]);
        }
      }
    }
  }
  void fill_iq() { // iq埋める
    int iq = NA;
    unsigned int ind = 0;
    while (ind < test_case.size()) {
      if (test_case[ind][IQ_col] == NA) {
        unsigned int atari = ind+1;
        while (test_case[atari][ind] == NA) atari++;
        iq = test_case[atari][ind];
        for (auto i=ind; i<atari; i++) {
          test_case[i][IQ_col] = iq;
        }
        ind = atari;
      }
      ind++;
    }
  }
  bool issameline(int row, int col, vector< vector<double> >::iterator it) {
    return (row > 1 && it[row-1][0] == it[row][0]
            && it[row-1][col] == it[row][col]);
  }
  void calc_AB(int col) { // ABする
    int n = 0;
    int sumx = 0;
    int sumy = 0;
    int sumxy = 0;
    int sumx2 = 0;
    for (auto i=0; i<test_case.size(); i++) {
      if (issameline(i, col, test_case.begin())) {
        continue;
      }
      n++;
      double x = test_case[i][col];
      double y = test_case[i][IQ_col];
      sumx += x;
      sumy += y;
      sumxy += x * y;
      sumx2 += x * x;
    }
    A[col] = (n * sumxy - sumx * sumy) / (n * sumx2 - sumx * sumx);
    B[col] = (sumx2 * sumy - sumxy * sumx) / (n * sumx2 - sumx * sumx);
  }
  void zansa_2jouwa(int col) {
    zansa[col] = 0;
    int n = 0;
    for (auto i=0; i<test_case.size(); i++) {
      if (issameline(i, col, test_case.begin())) {
        continue;
      }
      n++;
      double x = test_case[i][col];
      double y = test_case[i][IQ_col];
      double sa = y - A[col] * x - B[col];
      zansa[col] += sa * sa;
    }
    zansa[col] /= n;
    cerr << col << ": " << zansa[col] << endl;
  }
  void calc_all() {
    for (auto i=0; i<=scenario; i++) {
      for (auto j=0; j<used_col[i].size(); j++) {
        calc_AB(used_col[i][j]);
        zansa_2jouwa(used_col[i][j]);
      }
    }
  }
  void ranking() {

  }
  void make_training() {
    make_test_case_st();
    convert_double();
    fill_iq();
    calc_all();
    ranking();
  }
  //  main theorems
public:
  vector<double> predict(int _testType, int _scenario,
                         vector<string> _training, vector<string> _testing) {
    testType = _testType;
    scenario = _scenario;
    training = _training;
    testing = _testing;
    make_training();
    vector<double> X;
    return X;
  }
};
<|endoftext|>


<commit_before><commit_msg>whoops. need to undef it too.<commit_after><|endoftext|>


<commit_before>1c3ae3fd-ad58-11e7-948e-ac87a332f658<commit_msg>fixed bug<commit_after>1c9850a1-ad58-11e7-8e2d-ac87a332f658<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 *  Created on: Sep 21, 2013
 *      Author: tomas
 */

#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
#include <iostream> // TODO unused?
#include <math.h>       /* fabs */
using namespace std;

#define GRID_SIZE 32

int windowSizeH = 600;
int windowSizeV = 600;

bool shouldDrawUserLine = false;
bool shouldDrawBresenhamLine = false;
bool snapToGrid = true;

float beginX = 0;
float beginY = 0;
float endX = 0;
float endY = 0;

// TODO better titles
int gridBeginX = 0;
int gridBeginY = 0;
int gridEndX = 0;
int gridEndY = 0;

void transformScreenToWorldCoordinates(int screenX, int screenY, float &worldX, float &worldY) {

	worldX = ((float)screenX / (float)windowSizeH) * 2 - 1;
	worldY = ((float)screenY / (float)windowSizeV) * -2 + 1;
}

void transformWorldToGridCoordinates(float worldX, float worldY, int &gridX, int &gridY){
	gridX = (int)( ( ( worldX+1)/2 ) * GRID_SIZE );
	gridY = (int)( ( (-worldY+1)/2 ) * GRID_SIZE );
}

void transformGridToWorldCoordinates(int gridX, int gridY, float &worldX, float &worldY){

	float cornerLength = (float)(1.0/(GRID_SIZE/2)); // TODO optimize

	worldX = ( ( (float)gridX / GRID_SIZE) * 2 ) - 1 + (cornerLength/2);
	worldY = ( ( (float)gridY / GRID_SIZE) * -2 ) + 1 - (cornerLength/2);
}

void colorGridCell(int x, int y) {

	float cornerLength = (float)(1.0/(GRID_SIZE/2)); // TODO optimize
	float topLeftX = (cornerLength * x) - 1;
	float topLeftY = ((cornerLength * y) - 1) * -1;

	glColor3f(0, 0.5, 0.5);

	glBegin(GL_QUADS);
		glVertex2f(topLeftX, topLeftY);
		glVertex2f(topLeftX + cornerLength, topLeftY);

		glVertex2f(topLeftX + cornerLength, topLeftY - cornerLength);
		glVertex2f(topLeftX, topLeftY - cornerLength);
	glEnd();

}

void drawBresenhamLine(int gridBeginX, int gridBeginY, int gridEndX, int gridEndY){

	bool steep = abs(gridEndY - gridBeginY) > abs(gridEndX - gridBeginX);
	if (steep){
		swap(gridBeginX, gridBeginY);
		swap(gridEndX,   gridEndY);
	}

	if (gridBeginX > gridEndX){
        swap(gridBeginX, gridEndX);
        swap(gridBeginY, gridEndY);
	}

	int deltaX = gridEndX - gridBeginX;
	int deltay = abs (gridEndY - gridBeginY);
	int error = deltaX / 2;
	int currentY = gridBeginY;

	int yStep = 1;
	if (gridBeginY >= gridEndY){
		yStep = -1;
	}

	for (int currentX = gridBeginX; currentX <= gridEndX; currentX++) {
		if (steep) {
			colorGridCell(currentY, currentX);
		} else {
			colorGridCell(currentX, currentY);
		}

		error = error - deltay;
		if (error < 0) {
			currentY = currentY + yStep;
			error = error + deltaX;
		}
	}
}

void mouseClickCallback (int button, int state, int x, int y){

	if (button == GLUT_LEFT_BUTTON){

		if ((state == GLUT_DOWN)){
			transformScreenToWorldCoordinates(x, y, beginX, beginY);
			endX = beginX;
			endY = beginY;
			shouldDrawUserLine = true;

			transformWorldToGridCoordinates(beginX, beginY, gridBeginX, gridBeginY);
			gridEndX = gridBeginX;
			gridEndY = gridBeginY;
			shouldDrawBresenhamLine = true;
		}
//		else if (state == GLUT_UP) {
//			transformWorldToGridCoordinates(beginX, beginY, gridBeginX, gridBeginY);
//			transformWorldToGridCoordinates(endX, endY, gridEndX, gridEndY);
//
//		}
		glutPostRedisplay();
	}
}

void mouseDragCallback(int x, int y){

	transformScreenToWorldCoordinates(x, y, endX, endY);
	transformWorldToGridCoordinates(endX, endY, gridEndX, gridEndY);

	glutPostRedisplay();
}

void drawUserLine(){

	float lineBeginX = 0;
	float lineBeginY = 0;
	float lineEndX = 0;
	float lineEndY = 0;

	if (snapToGrid) {
		transformGridToWorldCoordinates(gridBeginX, gridBeginY, lineBeginX, lineBeginY);
		transformGridToWorldCoordinates(gridEndX, gridEndY, lineEndX, lineEndY);
	} else {
		lineBeginX = beginX;
		lineBeginY = beginY;
		lineEndX = endX;
		lineEndY = endY;
	}

	glColor3f(1.0, 0.0, 0.0);

	glBegin(GL_LINES);
		glVertex2f(lineBeginX, lineBeginY);
		glVertex2f(lineEndX, lineEndY);
	glEnd();
}

void drawGrid(){

	glColor3f(0.5, 0.5, 0.5);
	int i;

	glBegin(GL_LINES);
	for (i = -(GRID_SIZE / 2); i <= (GRID_SIZE / 2); i++) { //TODO optimize
		float x = i / (float) (GRID_SIZE / 2);
		glVertex2f(x, -1.0);
		glVertex2f(x, 1.0);

		glVertex2f(-1.0, x);
		glVertex2f(1.0, x);
	}
	glEnd();
}

void display(void) {

	glClear(GL_COLOR_BUFFER_BIT);

	drawGrid();

	if (shouldDrawBresenhamLine){
		drawBresenhamLine(gridBeginX, gridBeginY, gridEndX, gridEndY);
	}

	if (shouldDrawUserLine) {
		drawUserLine();
	}

	glFlush();
}

void init(void) {
}

int main(int argc, char *argv[]) {
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
	glutInitWindowSize(windowSizeH, windowSizeV);
	glutInitWindowPosition(100, 50);
	glutCreateWindow("CG1");
	init();
	glutDisplayFunc(display);

	glutMouseFunc(mouseClickCallback);
	glutMotionFunc(mouseDragCallback);

	glutMainLoop();
	return 0;
}
<commit_msg>Added line drawing algorithm execution time test<commit_after>/*
 * main.cpp
 *
 *  Created on: Sep 21, 2013
 *      Author: tomas
 */

#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
#include <iostream> // TODO unused?
#include <math.h>       /* fabs */
#include <sys/time.h>
#include <unistd.h>
using namespace std;

#define GRID_SIZE 32
#define RAND_SEED 1

int windowSizeH = 600;
int windowSizeV = 600;

bool shouldDrawUserLine = false;
bool shouldDrawBresenhamLine = false;
bool snapToGrid = true;

float beginX = 0;
float beginY = 0;
float endX = 0;
float endY = 0;

// TODO better titles
int gridBeginX = 0;
int gridBeginY = 0;
int gridEndX = 0;
int gridEndY = 0;

void transformScreenToWorldCoordinates(int screenX, int screenY, float &worldX, float &worldY) {

	worldX = ((float)screenX / (float)windowSizeH) * 2 - 1;
	worldY = ((float)screenY / (float)windowSizeV) * -2 + 1;
}

void transformWorldToGridCoordinates(float worldX, float worldY, int &gridX, int &gridY){
	gridX = (int)( ( ( worldX+1)/2 ) * GRID_SIZE );
	gridY = (int)( ( (-worldY+1)/2 ) * GRID_SIZE );
}

void transformGridToWorldCoordinates(int gridX, int gridY, float &worldX, float &worldY){

	float cornerLength = (float)(1.0/(GRID_SIZE/2)); // TODO optimize

	worldX = ( ( (float)gridX / GRID_SIZE) * 2 ) - 1 + (cornerLength/2);
	worldY = ( ( (float)gridY / GRID_SIZE) * -2 ) + 1 - (cornerLength/2);
}

void colorGridCell(int x, int y) {

	float cornerLength = (float)(1.0/(GRID_SIZE/2)); // TODO optimize
	float topLeftX = (cornerLength * x) - 1;
	float topLeftY = ((cornerLength * y) - 1) * -1;

	glColor3f(0, 0.5, 0.5);

	glBegin(GL_QUADS);
		glVertex2f(topLeftX, topLeftY);
		glVertex2f(topLeftX + cornerLength, topLeftY);

		glVertex2f(topLeftX + cornerLength, topLeftY - cornerLength);
		glVertex2f(topLeftX, topLeftY - cornerLength);
	glEnd();

}

void drawBresenhamLine(int gridBeginX, int gridBeginY, int gridEndX,
		int gridEndY, bool useInts, bool draw) {

	bool steep = abs(gridEndY - gridBeginY) > abs(gridEndX - gridBeginX);
	if (steep) {
		swap(gridBeginX, gridBeginY);
		swap(gridEndX, gridEndY);
	}

	if (gridBeginX > gridEndX) {
		swap(gridBeginX, gridEndX);
		swap(gridBeginY, gridEndY);
	}

	if (useInts) {
		int deltaX = gridEndX - gridBeginX;
		int deltay = abs(gridEndY - gridBeginY);
		int error = deltaX / 2;
		int currentY = gridBeginY;

		int yStep = 1;
		if (gridBeginY >= gridEndY) {
			yStep = -1;
		}

		for (int currentX = gridBeginX; currentX <= gridEndX; currentX++) {

			if (draw) {
				if (steep) {
					colorGridCell(currentY, currentX);
				} else {
					colorGridCell(currentX, currentY);
				}
			}

			error = error - deltay;
			if (error < 0) {
				currentY = currentY + yStep;
				error = error + deltaX;
			}
		}
	} else {
		int deltaX = gridEndX - gridBeginX;
		int deltay = abs(gridEndY - gridBeginY);
		float error = 0;
		float deltaError = fabs((float) deltay / (float) deltaX);
		int currentY = gridBeginY;

		int yStep = 1;
		if (gridBeginY >= gridEndY) {
			yStep = -1;
		}

		for (int currentX = gridBeginX; currentX <= gridEndX; currentX++) {
			if (draw){
				if (steep) {
					colorGridCell(currentY, currentX);
				} else {
					colorGridCell(currentX, currentY);
				}
			}

			error = error + deltaError;
			if (error >= 0.5) {
				currentY = currentY + yStep;
				error = error - 1.0;
			}
		}
	}
}

void mouseClickCallback (int button, int state, int x, int y){

	if (button == GLUT_LEFT_BUTTON){

		if ((state == GLUT_DOWN)){
			transformScreenToWorldCoordinates(x, y, beginX, beginY);
			endX = beginX;
			endY = beginY;
			shouldDrawUserLine = true;

			transformWorldToGridCoordinates(beginX, beginY, gridBeginX, gridBeginY);
			gridEndX = gridBeginX;
			gridEndY = gridBeginY;
			shouldDrawBresenhamLine = true;
		}
//		else if (state == GLUT_UP) {
//			transformWorldToGridCoordinates(beginX, beginY, gridBeginX, gridBeginY);
//			transformWorldToGridCoordinates(endX, endY, gridEndX, gridEndY);
//
//		}
		glutPostRedisplay();
	}
}

void mouseDragCallback(int x, int y){

	transformScreenToWorldCoordinates(x, y, endX, endY);
	transformWorldToGridCoordinates(endX, endY, gridEndX, gridEndY);

	glutPostRedisplay();
}

void drawUserLine(){

	float lineBeginX = 0;
	float lineBeginY = 0;
	float lineEndX = 0;
	float lineEndY = 0;

	if (snapToGrid) {
		transformGridToWorldCoordinates(gridBeginX, gridBeginY, lineBeginX, lineBeginY);
		transformGridToWorldCoordinates(gridEndX, gridEndY, lineEndX, lineEndY);
	} else {
		lineBeginX = beginX;
		lineBeginY = beginY;
		lineEndX = endX;
		lineEndY = endY;
	}

	glColor3f(1.0, 0.0, 0.0);

	glBegin(GL_LINES);
		glVertex2f(lineBeginX, lineBeginY);
		glVertex2f(lineEndX, lineEndY);
	glEnd();
}

void drawGrid(){

	glColor3f(0.5, 0.5, 0.5);
	int i;

	glBegin(GL_LINES);
	for (i = -(GRID_SIZE / 2); i <= (GRID_SIZE / 2); i++) { //TODO optimize
		float x = i / (float) (GRID_SIZE / 2);
		glVertex2f(x, -1.0);
		glVertex2f(x, 1.0);

		glVertex2f(-1.0, x);
		glVertex2f(1.0, x);
	}
	glEnd();
}

void display(void) {

	glClear(GL_COLOR_BUFFER_BIT);

	drawGrid();

	if (shouldDrawBresenhamLine){
		drawBresenhamLine(gridBeginX, gridBeginY, gridEndX, gridEndY, false, true);
	}

	if (shouldDrawUserLine) {
		drawUserLine();
	}

	glFlush();
}

int getRandomIntInRange(int min, int max) {
	return min + (rand() % (int)(max - min + 1)); // TODO review algorithm
	// TODO make random seed always the same
}

long getLineDrawingExecutionSpeedMicroseconds(bool useInts, long lineDraws){

	int min = 0;
	int max = GRID_SIZE - 1;

	int randBeginX;
	int randBeginY;
	int randEndX;
	int randEndY;

	srand(RAND_SEED);

	struct timeval start, end;

	gettimeofday(&start, NULL);

	for (long i = 0; i < lineDraws; i++) {
		randBeginX = getRandomIntInRange(min, max);
		randBeginY = getRandomIntInRange(min, max);
		randEndX = getRandomIntInRange(min, max);
		randEndY = getRandomIntInRange(min, max);

		drawBresenhamLine(randBeginX, randBeginY, randEndX, randEndY, useInts, false);

		//		cout << randBeginX << " " << randBeginX << " to " << randEndX << " " << randEndY << endl;
	}

	gettimeofday(&end, NULL);

	return end.tv_usec - start.tv_usec;
}

void testBresenhamLineAlgorithmExecutionSpeed(long numberOfCalls){

	long execTimeUsingInt   = getLineDrawingExecutionSpeedMicroseconds(true, numberOfCalls);
	long execTimeUsingFloat = getLineDrawingExecutionSpeedMicroseconds(false, numberOfCalls);

	cout << execTimeUsingInt << " " << execTimeUsingFloat << endl;
}

void init(void) {
}

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

//	testBresenhamLineAlgorithmExecutionSpeed(10000);
//	return 0;

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
	glutInitWindowSize(windowSizeH, windowSizeV);
	glutInitWindowPosition(100, 50);
	glutCreateWindow("CG1");
	init();
	glutDisplayFunc(display);

	glutMouseFunc(mouseClickCallback);
	glutMotionFunc(mouseDragCallback);

	glutMainLoop();
	return 0;
}
<|endoftext|>


<commit_before>e00e8e5c-ad58-11e7-9520-ac87a332f658<commit_msg>Does anyone even read these anymore???<commit_after>e081d7c2-ad58-11e7-9ac3-ac87a332f658<|endoftext|>


<commit_before>87928214-4b02-11e5-af5f-28cfe9171a43<commit_msg>I finished programming, there is nothing left to program<commit_after>879f3df5-4b02-11e5-a3d9-28cfe9171a43<|endoftext|>


<commit_before>#include <sstream>
#include <fstream>
#include <stdio.h>
#include <iostream>
#include <string>

using namespace std;

int similarity_score(char a, char b) {
  int score;
  if ((a == b) || (a == '?' || b == '?')) {
    score = 2;
  } else {
    score = -1;
  }
  return score;
}

int max_score(int scores[]) {
  int score = 0;
  for (int i = 0; i < 3; i++) {
    if (scores[i] > score) {
      score = scores[i];
    }
  }
  return score;
}

string slurp(const string &filename) {
  ifstream in(filename, ifstream::in);
  stringstream sstr;
  sstr << in.rdbuf();
  string file = sstr.str();
  return file;
}

int main(int argc, char *argv[]) {
  int c;
  bool showtime = false;
  string file1 = argv[1];
  string file2 = argv[2];
  if (argc > 1) {
    for (c = 1; c < argc; c++) {
      if (strcmp(argv[c], "-t") == 0) {
        showtime = true;
      }
    }
  }

  if (argc < 3) {
    cout << "Usage: sequence-alignment filename_sequence_a filename_sequence_b "
            "[-t]";
    return 0;
  }
  cout << "Starting alignment with files: " << file1 << ", " << file2 << endl;

  clock_t begin_read = clock();
  string seq_a = slurp(file1);
  string seq_b = slurp(file2);
  clock_t end_read = clock();
  double elapsed_secs_read = double(end_read - begin_read) / CLOCKS_PER_SEC;

  // create the matrices
  size_t length_m = seq_a.size();
  size_t length_n = seq_b.size();
  cout << "length m " << length_m << endl;
  cout << "length n " << length_n << endl;
  int H_matrix[length_m + 1][length_n + 1];

  // set first row and first column to zero
  for (int i = 0; i < length_m + 1; i++) {
    H_matrix[0][i] = 0;
  }
  for (int j = 0; j < length_n + 1; j++) {
    H_matrix[j][0] = 0;
  }

  int max_options[3];
  for (int i = 1; i < length_m + 1; i++) {
    for (int j = 1; j < length_n + 1; j++) {
      max_options[0] = H_matrix[i - 1][j - 1] +
                       similarity_score(seq_a.at(i - 1), seq_b.at(j - 1));
      max_options[1] = H_matrix[i - 1][j] - 2;
      max_options[2] = H_matrix[i][j - 1] - 2;
      H_matrix[i][j] = max_score(max_options);
    }
  }

  for (int i = 0; i < length_m + 1; i++) {
    for (int j = 0; j < length_n + 1; j++) {
      cout << H_matrix[i][j] << ' ';
    }
    cout << endl;
  }

  return 0;
}
<commit_msg>non threaded version<commit_after>#include <sstream>
#include <fstream>
#include <stdio.h>
#include <iostream>
#include <string>
#include <pthread.h>

using namespace std;

#define MATCH 1
#define GAP_PENALTY 2
#define MISMATCH_PENALTY 1

int similarity_score(char a, char b) {
  int score;
  if ((a == b) || (a == '?' || b == '?')) {
    score = MATCH;
  } else {
    score = -MISMATCH_PENALTY;
  }
  return score;
}

int max_score(int scores[]) {
  int score = 0;
  for (int i = 0; i < 3; i++) {
    if (scores[i] > score) {
      score = scores[i];
    }
  }
  return score;
}

string slurp(const string &filename) {
  ifstream in(filename, ifstream::in);
  stringstream sstr;
  sstr << in.rdbuf();
  string file = sstr.str();
  return file;
}

int main(int argc, char *argv[]) {
  int c;
  bool showtime = false;
  string file1 = argv[1];
  string file2 = argv[2];
  if (argc > 1) {
    for (c = 1; c < argc; c++) {
      if (strcmp(argv[c], "-t") == 0) {
        showtime = true;
      }
    }
  }

  if (argc < 3) {
    cout << "Usage: sequence-alignment filename_sequence_a filename_sequence_b "
            "[-t]";
    return 0;
  }
  cout << "Starting alignment with files: " << file1 << ", " << file2 << endl;

  clock_t begin_read = clock();
  string seq_a = slurp(file1);
  string seq_b = slurp(file2);
  clock_t end_read = clock();
  double elapsed_secs_read = double(end_read - begin_read) / CLOCKS_PER_SEC;

  // create the matrices
  size_t length_m = seq_a.size();
  size_t length_n = seq_b.size();
  // cout << "length m " << length_m << endl;
  // cout << "length n " << length_n << endl;
  int H_matrix[length_m][length_n];

  // set first row and first column to zero
  for (int i = 0; i < length_m; i++) {
    H_matrix[0][i] = 0;
  }
  for (int j = 0; j < length_n; j++) {
    H_matrix[j][0] = 0;
  }

  int max_options[3];
  clock_t begin_matrix_calc = clock();
  for (int i = 1; i < length_m; i++) {
    for (int j = 1; j < length_n; j++) {
      max_options[0] = H_matrix[i - 1][j - 1] +
                       similarity_score(seq_a.at(i - 1), seq_b.at(j - 1));
      max_options[1] = H_matrix[i - 1][j] - GAP_PENALTY;
      max_options[2] = H_matrix[i][j - 1] - GAP_PENALTY;
      H_matrix[i][j] = max_score(max_options);
    }
  }
  clock_t end_matrix_calc = clock();
  double elapsed_secs_matrix_calc =
      double(end_matrix_calc - begin_matrix_calc) / CLOCKS_PER_SEC;

  for (int i = 0; i < length_m; i++) {
    for (int j = 0; j < length_n; j++) {
      cout << H_matrix[i][j] << ' ';
    }
    cout << endl;
  }

  cout << "Elapsed Calculation Time: " << elapsed_secs_matrix_calc << endl;
  return 0;
}
<|endoftext|>