<commit_before>#if(GUI == 0)
#include <ace/console/eapplication.h>
#else
#include <ace/gui/eapplication.h>
#endif
#include "core/analyticfactory.h"
#include "core/datafactory.h"

using namespace std;

int main(int argc, char *argv[])
{
   EApplication application(""
                            ,"kinc"
                            ,MAJOR_VERSION
                            ,MINOR_VERSION
                            ,REVISION
                            ,unique_ptr<DataFactory>(new DataFactory)
                            ,unique_ptr<AnalyticFactory>(new AnalyticFactory)
                            ,argc
                            ,argv);
   return application.exec();
}
<commit_msg>Set organization name to SystemsGenetics<commit_after>#if(GUI == 0)
#include <ace/console/eapplication.h>
#else
#include <ace/gui/eapplication.h>
#endif
#include "core/analyticfactory.h"
#include "core/datafactory.h"

using namespace std;

int main(int argc, char *argv[])
{
   EApplication application("SystemsGenetics"
                            ,"kinc"
                            ,MAJOR_VERSION
                            ,MINOR_VERSION
                            ,REVISION
                            ,unique_ptr<DataFactory>(new DataFactory)
                            ,unique_ptr<AnalyticFactory>(new AnalyticFactory)
                            ,argc
                            ,argv);
   return application.exec();
}
<|endoftext|>


<commit_before>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);
	// Read galaxies
	Gals G;
    if(F.Ascii){
        G=read_galaxies_ascii(F);}
    else{
        G = read_galaxies(F);
    }
	F.Ngal = G.size();
	printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());
    std::vector<int> count=count_galaxies(const Gasl& G);
    for(int i=0;i<8;i++){printf ("   %d  \n",count[i])};
    // make MTL
    MTL M=make_MTL(G,F);
    for(int i=0;i<M.priority_list.size();++i){
        printf(" priority   %f",M.priority_list[i]);
    }
    printf(" \n");
    printf("Read fiber center positions and compute related things\n");
	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1;
    printf("spectrometer has to be identified from 0 to F.Npetal-1\n");
	F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F); pp.compute_fibsofsp(F);
    printf("get neighbors of each fiber;\n");
                                                //for each spectrometer, get list of fibers

    printf("Read plates in order they are to be observed\n ");

	Plates P_original = read_plate_centers(F);
    F.Nplate=P_original.size();
    printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n");
    Plates P;
    P.resize(F.Nplate);
    List permut = random_permut(F.Nplate);
    for (int jj=0; jj<F.Nplate; jj++){
        P[jj]=P_original[permut[jj]];
    }

	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

	// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
	F.cb = create_cb(); // cb=central body
	F.fh = create_fh(); // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01;
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct target> T(M,MinTreeSize);
	print_time(time,"# ... took :");//T.stats();

	// For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
	collect_galaxies_for_all(M,T,P,pp,F);

	// For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
	collect_available_tilefibers(M,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf("before assignment\n");
	Assignment A(M,F);
	print_time(t,"# Start assignment at : ");

	// Make a plan ----------------------------------------------------
	//new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars
                                   // assumes maximum number of observations needed for QSOs, LRGs
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);

    simple_assign(M,P,pp,F,A);

	print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
                                    // Want to have even distribution of unused fibers
                                    // so we can put in sky fibers and standard stars

	// Smooth out distribution of free fibers, and increase the number of assignments
	for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly
	for (int i=0; i<1; i++) {                           // more iterations will improve performance slightly
		improve(M,P,pp,F,A);
		redistribute_tf(M,P,pp,F,A);
		redistribute_tf(M,P,pp,F,A);
	}
	for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);

	print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);

	// Still not updated, so all QSO targets have multiple observations etc
	// Apply and update the plan --------------------------------------
	init_time_at(time,"# Begin real time assignment",t);
	for (int jj=0; jj<F.Nplate; jj++) {
		int j = A.next_plate;
		//printf(" - Plate %d :",j);
		//assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation
		assign_unused(j,M,P,pp,F,A);
		//if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies

		//printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl();
		// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
		if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n");
		A.next_plate++;
		// Redistribute and improve on various occasions  add more times if desired

		if ( j==2000 || j==4000) {
			redistribute_tf(M,P,pp,F,A);
			redistribute_tf(M,P,pp,F,A);
			improve(M,P,pp,F,A);
			redistribute_tf(M,P,pp,F,A);
		}
	}
	print_time(time,"# ... took :");

	// Results -------------------------------------------------------
	if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output
	display_results("doc/figs/",M,P,pp,F,A,true);
	if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane

	print_time(t,"# Finished !... in");

	return(0);

}
<commit_msg>prints number of galaxies by type<commit_after>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);
	// Read galaxies
	Gals G;
    if(F.Ascii){
        G=read_galaxies_ascii(F);}
    else{
        G = read_galaxies(F);
    }
	F.Ngal = G.size();
	printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());
    std::vector<int> count=count_galaxies(const Gals& G);
    for(int i=0;i<8;i++){printf ("   %d  \n",count[i])};
    // make MTL
    MTL M=make_MTL(G,F);
    for(int i=0;i<M.priority_list.size();++i){
        printf(" priority   %f",M.priority_list[i]);
    }
    printf(" \n");
    printf("Read fiber center positions and compute related things\n");
	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1;
    printf("spectrometer has to be identified from 0 to F.Npetal-1\n");
	F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F); pp.compute_fibsofsp(F);
    printf("get neighbors of each fiber;\n");
                                                //for each spectrometer, get list of fibers

    printf("Read plates in order they are to be observed\n ");

	Plates P_original = read_plate_centers(F);
    F.Nplate=P_original.size();
    printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n");
    Plates P;
    P.resize(F.Nplate);
    List permut = random_permut(F.Nplate);
    for (int jj=0; jj<F.Nplate; jj++){
        P[jj]=P_original[permut[jj]];
    }

	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

	// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
	F.cb = create_cb(); // cb=central body
	F.fh = create_fh(); // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01;
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct target> T(M,MinTreeSize);
	print_time(time,"# ... took :");//T.stats();

	// For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
	collect_galaxies_for_all(M,T,P,pp,F);

	// For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
	collect_available_tilefibers(M,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf("before assignment\n");
	Assignment A(M,F);
	print_time(t,"# Start assignment at : ");

	// Make a plan ----------------------------------------------------
	//new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars
                                   // assumes maximum number of observations needed for QSOs, LRGs
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);

    simple_assign(M,P,pp,F,A);

	print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
                                    // Want to have even distribution of unused fibers
                                    // so we can put in sky fibers and standard stars

	// Smooth out distribution of free fibers, and increase the number of assignments
	for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly
	for (int i=0; i<1; i++) {                           // more iterations will improve performance slightly
		improve(M,P,pp,F,A);
		redistribute_tf(M,P,pp,F,A);
		redistribute_tf(M,P,pp,F,A);
	}
	for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);

	print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);

	// Still not updated, so all QSO targets have multiple observations etc
	// Apply and update the plan --------------------------------------
	init_time_at(time,"# Begin real time assignment",t);
	for (int jj=0; jj<F.Nplate; jj++) {
		int j = A.next_plate;
		//printf(" - Plate %d :",j);
		//assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation
		assign_unused(j,M,P,pp,F,A);
		//if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies

		//printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl();
		// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
		if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n");
		A.next_plate++;
		// Redistribute and improve on various occasions  add more times if desired

		if ( j==2000 || j==4000) {
			redistribute_tf(M,P,pp,F,A);
			redistribute_tf(M,P,pp,F,A);
			improve(M,P,pp,F,A);
			redistribute_tf(M,P,pp,F,A);
		}
	}
	print_time(time,"# ... took :");

	// Results -------------------------------------------------------
	if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output
	display_results("doc/figs/",M,P,pp,F,A,true);
	if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane

	print_time(t,"# Finished !... in");

	return(0);

}
<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
#include <vector>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;

int status;

int main(int argc, char **argv)
{
	bool finish = false;
	string login = getlogin();
	if(getlogin() == NULL)
	{
		login = "";
		perror("get login failed");
	}
	char hostarray[64];
	gethostname(hostarray, 64);
	if(gethostname(hostarray, 64) == -1)
		perror("get host name failed");

	//rshell loop
	while(!finish)
	{
		bool syntaxerror = false;
		int semicolon= 0;
		int ampersand = 0;
		int pipe = 0;
		string command = "";
		vector <string> commands;

		//login name and host info prompt
		if(getlogin() != NULL)
			cout << login << "@" << hostarray;

		//ready prompt
		cout << "$ ";

		//take in command from user
		getline(cin, command);
	//	cout << command << endl;

		//account for #
		if(command.find("#") != string::npos)
		{
			command = command.substr(0, command.find("#"));
		//	cout << command << endl;
		}

		//account for empty command
		if(command == "")
			continue;

		//tokenizer init
		char_separator<char> delim(" ;&|#",";&|#", keep_empty_tokens);
		tokenizer< char_separator<char> > mytok(command, delim);

		//token check
		//for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
		//{
		//	cout << "(" << *it << ")" << " ";
		//}
		//cout << "listed the arguements" << endl;

		string temp;
		//command list formatting
		for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
		{
			//cout << "; = " << semicolon << ", & = " << ampersand << ", | =" << pipe << endl;
			//cout << *it << endl;

			if(*it == ""); //do nothing

			else if(*it == ";") //semicolon handling
			{
				semicolon++;
				if(semicolon > 1)
				{
					perror("Syntax error. Too many ; characters.");
					syntaxerror = true;
					break;
				}
				else if(semicolon == 1)
				{
					if(ampersand == 0 && pipe == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
							break;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back(";");
						semicolon = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else if(*it == "&") //ampersand handling
			{
				ampersand++;
				if(ampersand > 2)
				{
					perror("Syntax error. Too many & characters");
					syntaxerror = true;
					break;
				}
				else if(ampersand == 2)
				{
					if(semicolon == 0 && pipe == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back("&&");
						ampersand = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else if(*it == "|") //pipe handling
			{
				pipe++;
				if(pipe > 2)
				{
					perror("Syntax error. Too many | characters.");
					syntaxerror = true;
					break;
				}
				else if(pipe == 2)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
							break;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back("||");
						pipe = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else
			{
				if(semicolon != 0 || ampersand != 0 || pipe != 0)
				{
					perror("Syntax error. Improper use of connectors.");
					//cout << semicolon << " " << ampersand << " " << pipe << endl;
					syntaxerror = true;
					break;
				}
				if(temp != "")
					temp += ' ';
				temp += *it;
			}
		}
		commands.push_back(temp.c_str());
		temp = "";

		//check commands
		//for(int i = 0; i < commands.size(); i++)
		//{
		//	cout << "(" << commands.at(i) << ") ";
		//}
		//cout << "combined arguements into groups" << endl;
		if(!syntaxerror)
		{
			char *input[999];
			//exec commands
			for(unsigned int i = 0; i < commands.size(); i++)
			{
				string current = "";
				string word = "";
				int k = 0;
				for(unsigned int j = 0; j < commands.at(i).size(); j++) //itterate through letters
				{
					current = commands.at(i);
					if(current[j] == ' ')
					{
						input[k] = new char[word.size() + 1];
						strcpy(input[k], word.c_str());
						k++;
						word = "";
					}
					else
						word += current[j]; //add letter
				}
				input[k] = new char[word.size() + 1];
				strcpy(input[k], word.c_str());
				k++;

				input[k] = new char[1]; //add the NULL char *
				input[k] = NULL;

				if(commands.at(i) ==  "exit") //exit command
				{
					finish = true;
					cout << "ending session...";
					break;
				}

				else if(commands.at(i) == ";") //semicolon case
				{
					continue;
				}

				else if(commands.at(i) == "||") //pipe case
				{
					if(status)
						continue;
					else
					{
						i++;
						continue;
					}
				}

				else if(commands.at(i) == "&&") //ampersand case
				{
					if(status == 0)
						continue;
					else
					{
						i++;
						continue;
					}
				}

				//execute command. based off of in-lecture notes
				int pid = fork();
				if(pid == -1)
				{
					perror("There was an error with fork(). ");
					exit(1);
				}
				else if(pid == 0) //in child
				{
					//cout << "CHILD IS RUNNING :D" << endl;
					//cout << input << endl;
					status = execvp(input[0], input);
					if(-1 == status)
					{
						perror("There was an error in execvp.");

					}
					exit(1);
				}
				else if(pid > 0) //in parent
				{
					if(-1 == waitpid(pid, &status, 0)) //wait for child to finish
						perror("There was an error with wait().");

				}

			}

			//shell termination
			if(finish)
			{
				cout << "good-bye!" << endl;
				break;
			}
		}
	}
	return 0;
}
<commit_msg>rshell recognizes signle pipe input<commit_after>#include <iostream>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
#include <vector>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;

int status;

int main(int argc, char **argv)
{
	bool finish = false;
	string login = getlogin();
	if(getlogin() == NULL)
	{
		login = "";
		perror("get login failed");
	}
	char hostarray[64];
	gethostname(hostarray, 64);
	if(gethostname(hostarray, 64) == -1)
		perror("get host name failed");

	//rshell loop
	while(!finish)
	{
		bool syntaxerror = false;
		int semicolon= 0;
		int ampersand = 0;
		int pipe = 0;
		string command = "";
		vector <string> commands;

		//login name and host info prompt
		if(getlogin() != NULL)
			cout << login << "@" << hostarray;

		//ready prompt
		cout << "$ ";

		//take in command from user
		getline(cin, command);
	//	cout << command << endl;

		//account for #
		if(command.find("#") != string::npos)
		{
			command = command.substr(0, command.find("#"));
		//	cout << command << endl;
		}

		//account for empty command
		if(command == "")
			continue;

		//tokenizer init
		char_separator<char> delim(" ",";&|#");
		tokenizer< char_separator<char> > mytok(command, delim);

		//token check
		//for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
		//{
		//	cout << "(" << *it << ")" << " ";
		//}
		//cout << "listed the arguements" << endl;

		for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
		{
			cout << "(" << *it << ")" << " ";
		}
		cout << "listed the arguements" << endl;

		string temp;
		//command list formatting
		for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
		{
			//cout << "; = " << semicolon << ", & = " << ampersand << ", | =" << pipe << endl;
			//if(*it == ""); //do nothing

			if(*it == ";") //semicolon handling
			{
				semicolon++;
				if(semicolon > 1)
				{
					perror("Syntax error. Too many ; characters.");
					syntaxerror = true;
					break;
				}
				else if(semicolon == 1)
				{
					if(ampersand == 0 && pipe == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
							break;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back(";");
						semicolon = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else if(*it == "&") //ampersand handling
			{
				ampersand++;
				if(ampersand > 2)
				{
					perror("Syntax error. Too many & characters");
					syntaxerror = true;
					break;
				}
				else if(ampersand == 2)
				{
					if(semicolon == 0 && pipe == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back("&&");
						ampersand = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else if(*it == "|") //pipe handling
			{
				//cout << "PIPE!!!!!!!!!!!" << endl;
				pipe++;
				if(pipe > 2)
				{
					perror("Syntax error. Too many | characters.");
					syntaxerror = true;
					break;
				}
				else if(pipe == 1)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
							break;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back("|");
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}

				}
				else if(pipe == 2)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						commands.push_back("|");
						pipe = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else
			{
				if(semicolon != 0 || ampersand != 0)
				{
					perror("Syntax error. Improper use of connectors.");
					//cout << semicolon << " " << ampersand << " " << pipe << endl;
					syntaxerror = true;
					break;
				}
				if(temp != "")
				{
					temp += ' ';
				}
				temp += *it;
				if(pipe == 1)
					pipe = 0;
			}
		}
		commands.push_back(temp.c_str());
		temp = "";

		//combine two pipes together
		bool prevpipe = false;
		for(unsigned int i = 1; i < commands.size(); i++)
		{
			if(commands.at(i - 1) == "|")
				prevpipe = true;
			else
				prevpipe = false;

			if(prevpipe)
			{
				if(commands.at(i) == "|")
				{
					commands.at(i - 1) = "||";
					commands.erase(commands.begin() + i);
					i--;
				}
			}
		}

		//check commands
		for(unsigned int i = 0; i < commands.size(); i++)
		{
			cout << "(" << commands.at(i) << ") ";
		}

		cout << "combined arguements into groups" << endl;
		if(!syntaxerror)
		{
			char *input[999];
			//exec commands
			for(unsigned int i = 0; i < commands.size(); i++)
			{
				string current = "";
				string word = "";
				int k = 0;
				for(unsigned int j = 0; j < commands.at(i).size(); j++) //itterate through letters
				{
					current = commands.at(i);
					if(current[j] == ' ')
					{
						input[k] = new char[word.size() + 1];
						strcpy(input[k], word.c_str());
						k++;
						word = "";
					}
					else
						word += current[j]; //add letter
				}
				input[k] = new char[word.size() + 1];
				strcpy(input[k], word.c_str());
				k++;

				input[k] = new char[1]; //add the NULL char *
				input[k] = NULL;

				if(commands.at(i) ==  "exit") //exit command
				{
					finish = true;
					cout << "ending session...";
					break;
				}

				else if(commands.at(i) == ";") //semicolon case
				{
					continue;
				}

				else if(commands.at(i) == "||") //pipe case
				{
					if(status)
						continue;
					else
					{
						i++;
						continue;
					}
				}

				else if(commands.at(i) == "&&") //ampersand case
				{
					if(status == 0)
						continue;
					else
					{
						i++;
						continue;
					}
				}

				//execute command. based off of in-lecture notes
				int pid = fork();
				if(pid == -1)
				{
					perror("There was an error with fork(). ");
					exit(1);
				}
				else if(pid == 0) //in child
				{
					//cout << "CHILD IS RUNNING :D" << endl;
					//cout << input << endl;
					status = execvp(input[0], input);
					if(-1 == status)
					{
						perror("There was an error in execvp.");

					}
					exit(1);
				}
				else if(pid > 0) //in parent
				{
					if(-1 == waitpid(pid, &status, 0)) //wait for child to finish
						perror("There was an error with wait().");

				}

			}

			//shell termination
			if(finish)
			{
				cout << "good-bye!" << endl;
				break;
			}
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>#include <loom/args.hpp>
#include <loom/protobuf_stream.hpp>
#include <loom/logger.hpp>
#include <loom/loom.hpp>

const char * help_message =
"Usage: query CONFIG_IN MODEL_IN GROUPS_IN REQUESTS_IN RESPONSES_OUT LOG_OUT"
"\nArguments:"
"\n  CONFIG_IN     filename of config (e.g. config.pb.gz)"
"\n  MODEL_IN      filename of model (e.g. model.pb.gz)"
"\n  GROUPS_IN     dirname containing per-kind group files"
"\n  REQUESTS_IN    filename of requests stream (e.g. requests.pbs.gz)"
"\n  RESPONSES_OUT   filename of responses stream (e.g. responses.pbs.gz)"
"\n  LOG_OUT       filename of log (e.g. log.pbs.gz)"
"\n                or --none to not log"
"\nNotes:"
"\n  Any filename can end with .gz to indicate gzip compression."
"\n  Any filename can be '-' or '-.gz' to indicate stdin/stdout."
;

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

    Args args(argc, argv, help_message);
    const char * config_in = args.pop();
    const char * model_in = args.pop();
    const char * groups_in = args.pop();
    const char * requests_in = args.pop();
    const char * responses_out = args.pop();
    const char * log_out = args.pop_optional_file();
    args.done();

    if (log_out) {
        loom::logger.open(log_out);
    }

    const auto config = loom::protobuf_load<loom::protobuf::Config>(config_in);
    loom::rng_t rng(config.seed());
    loom::Loom engine(rng, config, model_in, groups_in);

    engine.query(rng, requests_in, responses_out);

    return 0;
}
<commit_msg>align spaces in help message<commit_after>#include <loom/args.hpp>
#include <loom/protobuf_stream.hpp>
#include <loom/logger.hpp>
#include <loom/loom.hpp>

const char * help_message =
"Usage: query CONFIG_IN MODEL_IN GROUPS_IN REQUESTS_IN RESPONSES_OUT LOG_OUT"
"\nArguments:"
"\n  CONFIG_IN       filename of config (e.g. config.pb.gz)"
"\n  MODEL_IN        filename of model (e.g. model.pb.gz)"
"\n  GROUPS_IN       dirname containing per-kind group files"
"\n  REQUESTS_IN     filename of requests stream (e.g. requests.pbs.gz)"
"\n  RESPONSES_OUT   filename of responses stream (e.g. responses.pbs.gz)"
"\n  LOG_OUT         filename of log (e.g. log.pbs.gz)"
"\n                  or --none to not log"
"\nNotes:"
"\n  Any filename can end with .gz to indicate gzip compression."
"\n  Any filename can be '-' or '-.gz' to indicate stdin/stdout."
;

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

    Args args(argc, argv, help_message);
    const char * config_in = args.pop();
    const char * model_in = args.pop();
    const char * groups_in = args.pop();
    const char * requests_in = args.pop();
    const char * responses_out = args.pop();
    const char * log_out = args.pop_optional_file();
    args.done();

    if (log_out) {
        loom::logger.open(log_out);
    }

    const auto config = loom::protobuf_load<loom::protobuf::Config>(config_in);
    loom::rng_t rng(config.seed());
    loom::Loom engine(rng, config, model_in, groups_in);

    engine.query(rng, requests_in, responses_out);

    return 0;
}
<|endoftext|>


<commit_before>#include "tensor.h"
#include "error.h"
#include <iostream>
using namespace nnlib;
using namespace std;

int main()
{
	size_t inps = 2, outs = 3;
	Tensor<double> weights(outs, inps), input(inps), bias(outs), target(outs);

	weights(0, 0) = 1;
	weights(0, 1) = 0;
	weights(1, 0) = 0;
	weights(1, 1) = 1;
	weights(2, 0) = 1;
	weights(2, 1) = 1;

	input(0) = 3.14;
	input(1) = 10.0;

	bias(0) = 0;
	bias(1) = 1;
	bias(2) = 2;

	target(0) = 3.14;
	target(1) = 11.0;
	target(2) = 15.14;

	Tensor<double> result = weights * input + bias;

	for(size_t i = 0; i < outs; ++i)
		Assert(result(i) == target(i), "Linear::forward failed!");

	cout << "Passed all tests!" << endl;

	return 0;
}
<commit_msg>Implemented efficiency test; it is faster than armadillo.<commit_after>#include "tensor.h"
#include "error.h"
#include <iostream>
#include <chrono>
using namespace nnlib;
using namespace std;

void testCorrectness();
double testEfficiency(size_t inps, size_t outs, size_t epochs, function<void()> &start, function<void()> &end);

int main()
{
	size_t inps				= 100000;
	size_t outs				= 1000;
	size_t epochs			= 10;

	using clock = chrono::high_resolution_clock;
	clock::time_point start;
	function<void()> startFn = [&](void) { start = clock::now(); };
	function<void()> endFn = [&](void) { cout << "took " << chrono::duration<double>(clock::now() - start).count() / epochs << " seconds per epoch" << endl; };

	testCorrectness();
	testEfficiency(inps, outs, epochs, startFn, endFn);

	return 0;
}

void testCorrectness()
{
	size_t inps = 2, outs = 3;
	Tensor<double> weights(outs, inps), input(inps), bias(outs), target(outs);

	weights(0, 0) = 1;
	weights(0, 1) = 0;
	weights(1, 0) = 0;
	weights(1, 1) = 1;
	weights(2, 0) = 1;
	weights(2, 1) = 1;

	input(0) = 3.14;
	input(1) = 10.0;

	bias(0) = 0;
	bias(1) = 1;
	bias(2) = 2;

	target(0) = 3.14;
	target(1) = 11.0;
	target(2) = 15.14;

	Tensor<double> result = weights * input + bias;
	for(size_t i = 0; i < outs; ++i)
		Assert(result(i) == target(i), "Linear::forward failed!");

	cout << "Passed all tests!" << endl;
}

double testEfficiency(size_t inps, size_t outs, size_t epochs, function<void()> &start, function<void()> &end)
{
	Tensor<double> weights(outs, inps);
	Tensor<double> input(inps), bias(outs), result(outs);

	weights.fillNormal();
	input.fillNormal();
	bias.fillNormal();
	result.fill(0.0);

	start();
	for(size_t i = 0; i < epochs; ++i)
		result += weights * input + bias;
	end();

	double resultSum = 0.0;
	for(size_t i = 0; i < outs; ++i)
		resultSum += result[i];

	return resultSum;
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <sys/wait.h>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>

using namespace std;

void connectors(string userinput, vector<int> &x, vector<int> &y, bool &first, bool &multiple) {
	x.clear();
	y.clear();
	for(unsigned int i = 0; i < userinput.size() - 1; i++) {
		if((userinput.at(i) == '|') && (userinput.at(i + 1) == '|')) {
			x.push_back(0);
			y.push_back(i);
		}
		else if((userinput.at(i) == '&') && (userinput.at(i + 1) == '&')) {
			x.push_back(1);
			y.push_back(i);
		}
		else if((userinput.at(i) == ';')) {
			x.push_back(2);
			y.push_back(i);

		}
	}
	y.push_back(userinput.size());
	for(unsigned int i = 0; i < y.size() - 1; i++) {
		if(y.at(i + 1) == y.at(i) + 1)
			multiple = true;
		//if((userinput.find("&") != string::npos || userinput.find("|") != string::npos) && x.size() == 0)
		//	multiple = true;
	}
	if(userinput.at(0) == '&' || userinput.at(0) == '|' || userinput.at(0) == ';')
		first = true;
	x.push_back(userinput.size());
}

int main() {
	string userinput;
	string login;
	if(!getlogin())
		perror("getlogin");
	else
		login = getlogin();
	char hostname[128];
	if(gethostname(hostname, sizeof hostname))
		perror("gethostname");
	bool ext  = false;
	string exit_status = "exit";
	while(!ext) {
		cout << getlogin() << "@" << hostname << " $ ";
		char *command_a;
		char *command;
		getline(cin, userinput);
		if(userinput.find("#") != string::npos)
			userinput.erase(userinput.find("#"), userinput.size());
		//if(userinput.size() == 0)
		//	userinput+="#";
		command = new char[userinput.size()];
		vector<int> c_pat;
		vector<int> c_pos;
		bool first = false;
		bool multiple = false;
		if(userinput.size() != 0)
			connectors(userinput, c_pat, c_pos, first, multiple);
		int x = 0;
		unsigned int b = 0;
		int y = 0;
		char *arg[100000];
		int status;
		if(userinput.size() != 0) {
			while(userinput.substr(x, 1) != "") {
				if(multiple) {
					cout << "Error: Incorrect connector config" << endl;
					break;
				}
				if(first) {
					cout << "Error: file does not exist" << endl;
					break;
				}
				strcpy(command, userinput.substr(x, c_pos.at(y) - x).c_str());
				if(userinput.substr(x, c_pos.at(y) - x).find("echo") != string::npos)
					command_a = strtok(command, "\" \t");
				else
					command_a = strtok(command, "&;| \t");
				while(command_a != NULL) {
					if(command_a[0] == '#') {
						break;
					}
					arg[b] = command_a;
					if(userinput.substr(x, c_pos.at(y) - x).find("echo") != string::npos)
						command_a = strtok(NULL, "\" \t");
					else
						command_a = strtok(NULL, "&;| \t");
					b++;
				}
				if(userinput.substr(x, c_pos.at(y) - x).find("exit") != string::npos && b==1) {
					ext = true;
					break;
				}
				int i = fork();
				if(i ==  -1)
					perror("fork");
				if(i == 0) {
					if(execvp(arg[0], arg) == -1) {
						perror("execvp");
						exit(-1);
					}
					exit(0);
				}
				wait(&status);
				x = c_pos.at(y);
				unsigned int help = c_pat.at(y);
				for(unsigned int i = 0; i < b; i++)
					arg[i] = NULL;
				if(help == 0 && status == 0 && (userinput.find("&&", y) != string::npos || userinput.find(";", y) != string::npos)) {
					y++;
					cout << "0 not only ";
				}
				else if(help == 0 && status == 0) {
					y++;
					cout << "0 only ";
					break;
				}
				else if(help == 1 && status != 0 && (userinput.find("||", y) != string::npos || userinput.find(";", y) != string::npos)) {
					y++;
					cout << "1 not only ";
				}
				else if(help == 1 && status != 0) {
					y++;
					cout << "1 only ";
					break;
				}
				else
					y++;
				b = 0;
			}
		}
	}
	return 0;
}
<commit_msg>got rid of connector code to find a better way<commit_after>#include <cstdlib>
#include <sys/wait.h>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>

using namespace std;

void connectors(string userinput, vector<int> &x, vector<int> &y, bool &first, bool &multiple) {
	x.clear();
	y.clear();
	for(unsigned int i = 0; i < userinput.size() - 1; i++) {
		if((userinput.at(i) == '|') && (userinput.at(i + 1) == '|')) {
			x.push_back(0);
			y.push_back(i);
		}
		else if((userinput.at(i) == '&') && (userinput.at(i + 1) == '&')) {
			x.push_back(1);
			y.push_back(i);
		}
		else if((userinput.at(i) == ';')) {
			x.push_back(2);
			y.push_back(i);

		}
	}
	y.push_back(userinput.size());
	for(unsigned int i = 0; i < y.size() - 1; i++) {
		if(y.at(i + 1) == y.at(i) + 1)
			multiple = true;
		//if((userinput.find("&") != string::npos || userinput.find("|") != string::npos) && x.size() == 0)
		//	multiple = true;
	}
	if(userinput.at(0) == '&' || userinput.at(0) == '|' || userinput.at(0) == ';')
		first = true;
	x.push_back(userinput.size());
}

int main() {
	string userinput;
	string login;
	if(!getlogin())
		perror("getlogin");
	else
		login = getlogin();
	char hostname[128];
	if(gethostname(hostname, sizeof hostname))
		perror("gethostname");
	bool ext  = false;
	string exit_status = "exit";
	while(!ext) {
		cout << getlogin() << "@" << hostname << " $ ";
		char *command_a;
		char *command;
		getline(cin, userinput);
		if(userinput.find("#") != string::npos)
			userinput.erase(userinput.find("#"), userinput.size());
		//if(userinput.size() == 0)
		//	userinput+="#";
		command = new char[userinput.size()];
		vector<int> c_pat;
		vector<int> c_pos;
		bool first = false;
		bool multiple = false;
		if(userinput.size() != 0)
			connectors(userinput, c_pat, c_pos, first, multiple);
		int x = 0;
		unsigned int b = 0;
		int y = 0;
		char *arg[100000];
		int status;
		if(userinput.size() != 0) {
			while(userinput.substr(x, 1) != "") {
				if(multiple) {
					cout << "Error: Incorrect connector config" << endl;
					break;
				}
				if(first) {
					cout << "Error: file does not exist" << endl;
					break;
				}
				strcpy(command, userinput.substr(x, c_pos.at(y) - x).c_str());
				if(userinput.substr(x, c_pos.at(y) - x).find("echo") != string::npos)
					command_a = strtok(command, "\" \t");
				else
					command_a = strtok(command, "&;| \t");
				while(command_a != NULL) {
					if(command_a[0] == '#') {
						break;
					}
					arg[b] = command_a;
					if(userinput.substr(x, c_pos.at(y) - x).find("echo") != string::npos)
						command_a = strtok(NULL, "\" \t");
					else
						command_a = strtok(NULL, "&;| \t");
					b++;
				}
				if(userinput.substr(x, c_pos.at(y) - x).find("exit") != string::npos && b==1) {
					ext = true;
					break;
				}
				int i = fork();
				if(i ==  -1)
					perror("fork");
				if(i == 0) {
					if(execvp(arg[0], arg) == -1) {
						perror("execvp");
						exit(-1);
					}
					exit(0);
				}
				wait(&status);
				x = c_pos.at(y);
				unsigned int help = c_pat.at(y);
				for(unsigned int i = 0; i < b; i++)
					arg[i] = NULL;
				//conncector config code to go here

				b = 0;
			}
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Networks and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// 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

#include <iostream>
#include <string>
#include <exception>
#include <vector>

#include <msgpack.hpp>
#include <jubatus/core/common/big_endian.hpp>
#include <jubatus/core/common/jsonconfig/config.hpp>
#include <jubatus/core/common/jsonconfig/cast.hpp>
#include <jubatus/util/data/serialization/unordered_map.h>
#include <jubatus/util/text/json.h>
#include <jubatus/util/lang/cast.h>

#include "third_party/cmdline/cmdline.h"

#include "jubatus/dump/classifier.hpp"
#include "jubatus/dump/recommender.hpp"
#include "jubatus/dump/anomaly.hpp"
#include "jubatus/dump/unsupported.hpp"

using std::runtime_error;
using jubatus::core::common::read_big_endian;
using jubatus::util::lang::lexical_cast;
using jubatus::util::text::json::from_json;

namespace jubatus {
namespace dump {

struct model {
  std::string type_;
  jubatus::core::common::jsonconfig::config config_;
  std::vector<char> user_data_;
};

void read(std::ifstream& ifs, model& m) {
  // TODO(unno): This implementation ignores checksums, version, and all other
  // check codes. We need to re-implemenet such process like
  // jubatus::server::framework::save_server/load_server, or to use these
  // methods to show file format errors.

  ifs.exceptions(std::ifstream::failbit);

  std::vector<char> system_data_buf;
  try {
    char header_buf[48];
    ifs.read(header_buf, 48);

    uint64_t system_data_size = read_big_endian<uint64_t>(&header_buf[32]);
    system_data_buf.resize(system_data_size);
    ifs.read(&system_data_buf[0], system_data_size);

    uint64_t user_data_size = read_big_endian<uint64_t>(&header_buf[40]);
    m.user_data_.resize(user_data_size);
    ifs.read(&m.user_data_[0], user_data_size);
  } catch (std::ios_base::failure& e) {
    throw runtime_error("Input stream reached end of file.");
  }

  if (ifs.peek() != -1) {
    std::ifstream::pos_type pos = ifs.tellg();
    throw runtime_error("Input stream remains. Position: " +
        lexical_cast<std::string>(pos));
  }
  ifs.close();

  msgpack::unpacked msg;
  msgpack::unpack(&msg, system_data_buf.data(), system_data_buf.size());
  msgpack::object system_data = msg.get();
  std::string config;
  system_data.via.array.ptr[2].convert(&m.type_);
  system_data.via.array.ptr[4].convert(&config);
  m.config_ = jubatus::core::common::jsonconfig::config(
      jubatus::util::lang::lexical_cast<
          jubatus::util::text::json::json>(config));
}

template <typename T, typename D>
void dump(model& m, jubatus::util::text::json::json& js) {
  msgpack::unpacked msg_user;
  msgpack::unpack(&msg_user, m.user_data_.data(), m.user_data_.size());

  // obj[0] is the version of the saved model file
  T data;
  msg_user.get().via.array.ptr[1].convert(&data);

  D dump(data);
  js = jubatus::util::text::json::to_json(dump);
}

int run(const std::string& path) try {
  std::ifstream ifs(path.c_str());
  if (!ifs) {
    throw runtime_error("Cannot open: " + path);
  }

  model m;
  jubatus::util::text::json::json js;

  try {
    read(ifs, m);
  } catch (const std::exception& e) {
    throw runtime_error(std::string("invalid model file structure: ") +
                        e.what());
  }

  if (m.type_ == "classifier") {
    std::string method;
    from_json<std::string>(m.config_["method"].get(), method);
    if (method != "NN") {
      dump<classifier<local_storage>,
          classifier_dump<local_storage, local_storage_dump> >(m, js);
    } else {
      throw runtime_error("classifier method \"" + method +
                          "\" is not supported for dump");
    }
  } else if (m.type_ == "regression") {
    // same model data structure as classifier
    dump<classifier<local_storage>,
        classifier_dump<local_storage, local_storage_dump> >(m, js);
  } else if (m.type_ == "recommender") {
    std::string method;
    from_json<std::string>(m.config_["method"].get(), method);
    if (method == "inverted_index") {
      dump<recommender<inverted_index>,
           recommender_dump<inverted_index_recommender_dump> >(m, js);
    } else {
      throw runtime_error("recommender method \"" + method +
                          "\" is not supported for dump");
    }
  } else if (m.type_ == "anomaly") {
    std::string method, backend_method;
    from_json<std::string>(m.config_["method"].get(), method);
    from_json<std::string>(m.config_["parameter"]["method"].get(),
                           backend_method);
    if (method == "lof") {
      if (backend_method == "inverted_index") {
        dump<
            anomaly<lof<inverted_index> >,
            anomaly_dump<lof<inverted_index>, lof_dump<
                inverted_index, inverted_index_recommender_dump> > >(m, js);
      } else {
        std::cerr << "Warning: backend recommender method \""
                  << backend_method << "\" is not supported for dump"
                  << std::endl;
        dump<
            anomaly<lof<unsupported_data> >,
            anomaly_dump<lof<unsupported_data>, lof_dump<
                unsupported_data, unsupported_data_dump> > >(m, js);
      }
    } else {
      throw runtime_error("anomaly method \"" + method +
                          "\" is not supported for dump");
    }
  } else {
    throw runtime_error("type \"" + m.type_ +
                        "\" is not supported for dump");
  }

  js.pretty(std::cout, true);
  return 0;
} catch (const std::exception& e) {
  std::cerr << "Error: failed to dump \"" << path
            << "\": " << e.what() << std::endl;
  return -1;
}

}  // namespace dump
}  // namespace jubatus

int main(int argc, char* argv[]) {
  cmdline::parser p;
  p.add<std::string>("input", 'i', "Input file");
  p.parse_check(argc, argv);

  return jubatus::dump::run(p.get<std::string>("input"));
}
<commit_msg>add fallback anomaly method dump<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Networks and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// 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

#include <iostream>
#include <string>
#include <exception>
#include <vector>

#include <msgpack.hpp>
#include <jubatus/core/common/big_endian.hpp>
#include <jubatus/core/common/jsonconfig/config.hpp>
#include <jubatus/core/common/jsonconfig/cast.hpp>
#include <jubatus/util/data/serialization/unordered_map.h>
#include <jubatus/util/text/json.h>
#include <jubatus/util/lang/cast.h>

#include "third_party/cmdline/cmdline.h"

#include "jubatus/dump/classifier.hpp"
#include "jubatus/dump/recommender.hpp"
#include "jubatus/dump/anomaly.hpp"
#include "jubatus/dump/unsupported.hpp"

using std::runtime_error;
using jubatus::core::common::read_big_endian;
using jubatus::util::lang::lexical_cast;
using jubatus::util::text::json::from_json;

namespace jubatus {
namespace dump {

struct model {
  std::string type_;
  jubatus::core::common::jsonconfig::config config_;
  std::vector<char> user_data_;
};

void read(std::ifstream& ifs, model& m) {
  // TODO(unno): This implementation ignores checksums, version, and all other
  // check codes. We need to re-implemenet such process like
  // jubatus::server::framework::save_server/load_server, or to use these
  // methods to show file format errors.

  ifs.exceptions(std::ifstream::failbit);

  std::vector<char> system_data_buf;
  try {
    char header_buf[48];
    ifs.read(header_buf, 48);

    uint64_t system_data_size = read_big_endian<uint64_t>(&header_buf[32]);
    system_data_buf.resize(system_data_size);
    ifs.read(&system_data_buf[0], system_data_size);

    uint64_t user_data_size = read_big_endian<uint64_t>(&header_buf[40]);
    m.user_data_.resize(user_data_size);
    ifs.read(&m.user_data_[0], user_data_size);
  } catch (std::ios_base::failure& e) {
    throw runtime_error("Input stream reached end of file.");
  }

  if (ifs.peek() != -1) {
    std::ifstream::pos_type pos = ifs.tellg();
    throw runtime_error("Input stream remains. Position: " +
        lexical_cast<std::string>(pos));
  }
  ifs.close();

  msgpack::unpacked msg;
  msgpack::unpack(&msg, system_data_buf.data(), system_data_buf.size());
  msgpack::object system_data = msg.get();
  std::string config;
  system_data.via.array.ptr[2].convert(&m.type_);
  system_data.via.array.ptr[4].convert(&config);
  m.config_ = jubatus::core::common::jsonconfig::config(
      jubatus::util::lang::lexical_cast<
          jubatus::util::text::json::json>(config));
}

template <typename T, typename D>
void dump(model& m, jubatus::util::text::json::json& js) {
  msgpack::unpacked msg_user;
  msgpack::unpack(&msg_user, m.user_data_.data(), m.user_data_.size());

  // obj[0] is the version of the saved model file
  T data;
  msg_user.get().via.array.ptr[1].convert(&data);

  D dump(data);
  js = jubatus::util::text::json::to_json(dump);
}

int run(const std::string& path) try {
  std::ifstream ifs(path.c_str());
  if (!ifs) {
    throw runtime_error("Cannot open: " + path);
  }

  model m;
  jubatus::util::text::json::json js;

  try {
    read(ifs, m);
  } catch (const std::exception& e) {
    throw runtime_error(std::string("invalid model file structure: ") +
                        e.what());
  }

  if (m.type_ == "classifier") {
    std::string method;
    from_json<std::string>(m.config_["method"].get(), method);
    if (method != "NN") {
      dump<classifier<local_storage>,
          classifier_dump<local_storage, local_storage_dump> >(m, js);
    } else {
      throw runtime_error("classifier method \"" + method +
                          "\" is not supported for dump");
    }
  } else if (m.type_ == "regression") {
    // same model data structure as classifier
    dump<classifier<local_storage>,
        classifier_dump<local_storage, local_storage_dump> >(m, js);
  } else if (m.type_ == "recommender") {
    std::string method;
    from_json<std::string>(m.config_["method"].get(), method);
    if (method == "inverted_index") {
      dump<recommender<inverted_index>,
           recommender_dump<inverted_index_recommender_dump> >(m, js);
    } else {
      throw runtime_error("recommender method \"" + method +
                          "\" is not supported for dump");
    }
  } else if (m.type_ == "anomaly") {
    std::string method, backend_method;
    from_json<std::string>(m.config_["method"].get(), method);
    from_json<std::string>(m.config_["parameter"]["method"].get(),
                           backend_method);
    if (method == "lof") {
      if (backend_method == "inverted_index") {
        dump<
            anomaly<lof<inverted_index> >,
            anomaly_dump<lof<inverted_index>, lof_dump<
                inverted_index, inverted_index_recommender_dump> > >(m, js);
      } else {
        std::cerr << "Warning: backend recommender method \""
                  << backend_method << "\" is not supported for dump"
                  << std::endl;
        dump<
            anomaly<lof<unsupported_data> >,
            anomaly_dump<lof<unsupported_data>, lof_dump<
                unsupported_data, unsupported_data_dump> > >(m, js);
      }
    } else {
      std::cerr << "Warning: anomaly method \""
                << method << "\" is not fully supported for dump"
                << std::endl;
      dump<
          anomaly<unsupported_data>,
          anomaly_dump<unsupported_data, unsupported_data_dump> >(m, js);
    }
  } else {
    throw runtime_error("type \"" + m.type_ +
                        "\" is not supported for dump");
  }

  js.pretty(std::cout, true);
  return 0;
} catch (const std::exception& e) {
  std::cerr << "Error: failed to dump \"" << path
            << "\": " << e.what() << std::endl;
  return -1;
}

}  // namespace dump
}  // namespace jubatus

int main(int argc, char* argv[]) {
  cmdline::parser p;
  p.add<std::string>("input", 'i', "Input file");
  p.parse_check(argc, argv);

  return jubatus::dump::run(p.get<std::string>("input"));
}
<|endoftext|>


<commit_before>#include <ncurses.h>

#include <string>

#include "game.h"

using namespace std;

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

    int initStatus = init();
    if (initStatus == 0) run();

    close();

    printf("GAME OVER\n");

    return 0;
}
<commit_msg>Remove unnecessary variable assignment (is implicit return, imho)<commit_after>#include <ncurses.h>

#include <string>

#include "game.h"

using namespace std;

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

    if (init() == 0) run();

    close();

    printf("GAME OVER\n");

    return 0;
}
<|endoftext|>


<commit_before>#include <getopt.h>
#include <cstring>
#include "gfakluge.hpp"

using namespace std;
using namespace gfak;

int gfakluge_package_help(char** argv){
    cerr << "GFAK: manipulate GFA files from the command line." << endl <<
        "Usage: " << argv[0] << " {command} [OPTIONS] <gfa_file> [...]" << endl <<
        "commands: " << endl <<
        "   convert: " << endl <<
        "   diff:   " << endl <<
        "   extract: " << endl <<
        "   ids:  "  << endl <<
        "   merge:  " << endl <<
        "   sort: " << endl <<
        "   stats: " << endl <<
        "   subset: " << endl <<
        endl;
    return 1;

}

void extract_help(char** argv){
    cerr << "gfak extract: extract a FASTA file from GFA" << endl
        << "Usage: gfak extract [ -p ] <GFA_FILE> > file.fa " << endl
            << "-p / --include-paths  include paths in output (might be contigs?? We nevr know)" << endl
        << endl;
}

/**
 * Output a fasta file from input GFA
 */

int extract_main(int argc, char** argv){
    string gfa_file = "";
    bool include_paths = false;

    if (argc < 3){
        cerr << "No GFA file given as input." << endl << endl;
        extract_help(argv);
        exit(0);
    }

    int c;
    optind = 2;
    while (true){
        static struct option long_options[] =
        {
            {"help", no_argument, 0, 'h'},
            {"inlude-paths", no_argument, 0, 'p'},
            {0,0,0,0}
        };

        int option_index = 0;
        c = getopt_long(argc, argv, "hp", long_options, &option_index);
        if (c == -1){
            break;
        }

        switch (c){
            case 'i':
                gfa_file = optarg;
                break;

            case '?':
            case 'h':
                extract_help(argv);
                exit(0);
            case 'p':
                include_paths= true;
                break;
            default:
                abort();
        }
    }
    gfa_file = argv[optind];

    GFAKluge gg;
    gg.parse_gfa_file(gfa_file);

    map<string, sequence_elem, custom_key> seqs = gg.get_name_to_seq();

    for (auto name_seq : seqs){
        cout << ">" << name_seq.second.name << endl
            << name_seq.second.sequence << endl
            << endl;
    }
    // Do the same for groups/walks/paths, as the concated
    // sequences of the oriented seq_elems create a path (e.g. a chromosome or contig)
    if (include_paths){
        for (auto p : gg.get_groups()){
            stringstream pstr;
            if (p.second.ordered){

                pstr << ">" << p.second.id << endl;
                for (int i = 0; i < p.second.items.size(); i++){
                    string seqname = p.second.items[i];
                    bool ori = p.second.orientations[i];
                    pstr << ( ori ? seqs[seqname].sequence : string((seqs[seqname]).sequence.rbegin(), (seqs[seqname]).sequence.rend()));
                }
                pstr << endl;
                cout << pstr.str() << endl;
                pstr.str("");
            }
        }
    }

	return 0;
}

/**
 * Return whether two GFA files are identical
 * in "structure" (number of links, segments, etC)
 */
int diff_main(int argc, char** argv){

}

/**
 *  Convert a GFA file to another GFA version,
 *  FASTA, or Cytoscape
 */
int convert_main(int argc, char** argv){

}

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

}

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

}

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

}

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

}

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

}

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

    if (argc < 2){
       cerr << "No command provided. Please provide a second argument to GFA kluge to tell it what to do." << endl;
       return gfakluge_package_help(argv);
    }

    if (argv[1] == "convert"){
        //return convert_main(argc, argv);
    }
    else if (argv[1] == "diff"){

    }
    else if (strcmp(argv[1], "extract") == 0){
        return extract_main(argc, argv);
    }
    else if (argv[1] == "ids"){

    }
    else if (argv[1] == "merge"){

    }
    else if (argv[1] == "sort"){

    }
    else if (argv[1] == "stats"){

    }
    else if (argv[1] == "subset"){

    }
    else {
        cerr << "No command " << '"' << argv[1] << '"' << endl;
        cerr << "Please use one of the valid gfak commands:" << endl;
        gfakluge_package_help(argv);
    }
    return 0;
}
<commit_msg>Update help text and refactor diff_main<commit_after>#include <getopt.h>
#include <cstring>
#include "gfakluge.hpp"

using namespace std;
using namespace gfak;

int gfakluge_package_help(char** argv){
    cerr << "GFAK: manipulate GFA files from the command line." << endl <<
        "Usage: " << argv[0] << " {command} [OPTIONS] <gfa_file> [...]" << endl <<
        "commands: " << endl <<
        "   convert: Convert between GFA 0.1 <-> 1.0 <-> 2.0" << endl <<
        "   diff:    Determine whether two GFA files have identical graphs" << endl <<
        "   extract: Convert the S lines of a GFA file to FASTA format." << endl <<
        "   ids:     Coordinate the ID spaces of multiple GFA graphs."  << endl <<
        "   concat:  Merge GFA graphs (without ID collisions)." << endl <<
        "   sort:    Print a GFA file in HSLP / HSEFGUO order." << endl <<
        "   stats:   Get assembly statistics (e.g. N50) for a GFA file." << endl <<
        "   subset:  Extract the subgraph between two IDs in a graph." << endl <<
        endl;
    return 1;

}

void extract_help(char** argv){
    cerr << argv[0] <<  " extract: extract a FASTA file from GFA" << endl
        << "Usage: " << argv[0] << "extract [ -p ] <GFA_FILE> > file.fa " << endl
            << "-p / --include-paths  include paths in output (might be contigs?? We nevr know)" << endl
        << endl;
}

void diff_help(char** argv){
    cerr << argv[0] << " diff: determine whether two GFA files are the same." << endl
      << "Usage: " << argv[0] << " diff [] <GFA_File_1> <GFA_File_2>" << endl;
}

/**
 * Output a fasta file from input GFA
 */

int extract_main(int argc, char** argv){
    string gfa_file = "";
    bool include_paths = false;

    if (argc < 3){
        cerr << "No GFA file given as input." << endl << endl;
        extract_help(argv);
        exit(0);
    }

    int c;
    optind = 2;
    while (true){
        static struct option long_options[] =
        {
            {"help", no_argument, 0, 'h'},
            {"inlude-paths", no_argument, 0, 'p'},
            {0,0,0,0}
        };

        int option_index = 0;
        c = getopt_long(argc, argv, "hp", long_options, &option_index);
        if (c == -1){
            break;
        }

        switch (c){
            case 'i':
                gfa_file = optarg;
                break;

            case '?':
            case 'h':
                extract_help(argv);
                exit(0);
            case 'p':
                include_paths= true;
                break;
            default:
                abort();
        }
    }
    gfa_file = argv[optind];

    GFAKluge gg;
    gg.parse_gfa_file(gfa_file);

    map<string, sequence_elem, custom_key> seqs = gg.get_name_to_seq();

    for (auto name_seq : seqs){
        cout << ">" << name_seq.second.name << endl
            << name_seq.second.sequence << endl
            << endl;
    }
    // Do the same for groups/walks/paths, as the concated
    // sequences of the oriented seq_elems create a path (e.g. a chromosome or contig)
    if (include_paths){
        for (auto p : gg.get_groups()){
            stringstream pstr;
            if (p.second.ordered){

                pstr << ">" << p.second.id << endl;
                for (int i = 0; i < p.second.items.size(); i++){
                    string seqname = p.second.items[i];
                    bool ori = p.second.orientations[i];
                    pstr << ( ori ? seqs[seqname].sequence : string((seqs[seqname]).sequence.rbegin(), (seqs[seqname]).sequence.rend()));
                }
                pstr << endl;
                cout << pstr.str() << endl;
                pstr.str("");
            }
        }
    }

	return 0;
}

/**
 * Return whether two GFA files are identical
 * in "structure" (number of links, segments, etC)
 */
int diff_main(int argc, char** argv){
    if (argc < 4){
        cerr << "diff requires two GFA files as input." << endl << endl;
        diff_help(argv);
        exit(0);
    }

    int c;
    optind = 2;
    while (true){
        static struct option long_options[] =
        {
            {"help", no_argument, 0, 'h'},
            {0,0,0,0}
        };

        int option_index = 0;
        c = getopt_long(argc, argv, "h", long_options, &option_index);
        if (c == -1){
            break;
        }

        switch (c){
            case '?':
            case 'h':
                diff_help(argv);
                exit(0);
            default:
                abort();
        }
    }

    GFAKluge ff;
    GFAKluge gg;
    ff.parse_gfa_file(argv[optind]);
    optind++;
    gg.parse_gfa_file(argv[optind]);
    optind++;
    map<std::string, sequence_elem, custom_key> seq_1 = ff.get_name_to_seq();
    map<std::string, sequence_elem, custom_key> seq_2 = gg.get_name_to_seq();
    map<std::string, vector<edge_elem>> e_1 = ff.get_seq_to_edges();
    map<std::string, vector<edge_elem>> e_2 = ff.get_seq_to_edges();
    if (seq_1.size() != seq_2.size()){
        cerr << "Graphs have different numbers of sequences." << endl;
        return -1;
    }
    else{
        // Check if all node IDs are the same.

        // Check if the edges of every node ID are the same in both graphs.

        // Check that the graphs both have identical paths.

        // Check fragments and other GFA2 specific items.

    }

    return 0;
}

/**
 *  Convert a GFA file to another GFA version,
 *  FASTA, or Cytoscape
 */
int convert_main(int argc, char** argv){

}

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

}

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

}

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

}

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

}

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

}

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

    if (argc < 2){
       cerr << "No command provided. Please provide a second argument to GFA kluge to tell it what to do." << endl;
       return gfakluge_package_help(argv);
    }

    if (argv[1] == "convert"){
        //return convert_main(argc, argv);
    }
    else if (strcmp(argv[1], "diff") == 0){
        return diff_main(argc, argv);
    }
    else if (strcmp(argv[1], "extract") == 0){
        return extract_main(argc, argv);
    }
    else if (argv[1] == "ids"){

    }
    else if (argv[1] == "merge"){

    }
    else if (argv[1] == "sort"){

    }
    else if (argv[1] == "stats"){

    }
    else if (argv[1] == "subset"){

    }
    else {
        cerr << "No command " << '"' << argv[1] << '"' << endl;
        cerr << "Please use one of the valid gfak commands:" << endl;
        gfakluge_package_help(argv);
    }
    return 0;
}
<|endoftext|>


<commit_before>#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <iostream>
#include <queue>
#include <stdio.h>
#include <math.h>

#include "constants.h"
#include "findEyeCenter.h"
#include "findEyeCorner.h"

/** Constants **/

/** Function Headers */
void detectAndDisplay( cv::Mat frame );

/** Global variables */
//-- Note, either copy these two files from opencv/data/haarscascades to your current folder, or change these locations
cv::String face_cascade_name = "../../../res/haarcascade_frontalface_alt.xml";
cv::CascadeClassifier face_cascade;
std::string main_window_name = "Capture - Face detection";
std::string face_window_name = "Capture - Face";
cv::RNG rng(12345);
cv::Mat debugImage;
cv::Mat skinCrCbHist = cv::Mat::zeros(cv::Size(256, 256), CV_8UC1);

/**
 * @function main
 */
int main( int argc, const char** argv ) {
  cv::Mat frame;

  // Load the cascades
  if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading face cascade, please change face_cascade_name in source code.\n"); return -1; };

  cv::namedWindow(main_window_name,CV_WINDOW_NORMAL);
  cv::moveWindow(main_window_name, 400, 100);
  cv::namedWindow(face_window_name,CV_WINDOW_NORMAL);
  cv::moveWindow(face_window_name, 10, 100);
  cv::namedWindow("Right Eye",CV_WINDOW_NORMAL);
  cv::moveWindow("Right Eye", 10, 600);
  cv::namedWindow("Left Eye",CV_WINDOW_NORMAL);
  cv::moveWindow("Left Eye", 10, 800);
  cv::namedWindow("aa",CV_WINDOW_NORMAL);
  cv::moveWindow("aa", 10, 800);
  cv::namedWindow("aaa",CV_WINDOW_NORMAL);
  cv::moveWindow("aaa", 10, 800);

  createCornerKernels();
  ellipse(skinCrCbHist, cv::Point(113, 155.6), cv::Size(23.4, 15.2),
          43.0, 0.0, 360.0, cv::Scalar(255, 255, 255), -1);

  // I make an attempt at supporting both 2.x and 3.x OpenCV
#if CV_MAJOR_VERSION < 3
  CvCapture* capture = cvCaptureFromCAM( -1 );
  if( capture ) {
    while( true ) {
      frame = cvQueryFrame( capture );
#else
  cv::VideoCapture capture(-1);
  if( capture.isOpened() ) {
    while( true ) {
      capture.read(frame);
#endif
      // mirror it
      cv::flip(frame, frame, 1);
      frame.copyTo(debugImage);

      // Apply the classifier to the frame
      if( !frame.empty() ) {
        detectAndDisplay( frame );
      }
      else {
        printf(" --(!) No captured frame -- Break!");
        break;
      }

      imshow(main_window_name,debugImage);

      int c = cv::waitKey(10);
      if( (char)c == 'c' ) { break; }
      if( (char)c == 'f' ) {
        imwrite("frame.png",frame);
      }

    }
  }

  releaseCornerKernels();

  return 0;
}

void findEyes(cv::Mat frame_gray, cv::Rect face) {
  cv::Mat faceROI = frame_gray(face);
  cv::Mat debugFace = faceROI;

  if (kSmoothFaceImage) {
    double sigma = kSmoothFaceFactor * face.width;
    GaussianBlur( faceROI, faceROI, cv::Size( 0, 0 ), sigma);
  }
  //-- Find eye regions and draw them
  int eye_region_width = face.width * (kEyePercentWidth/100.0);
  int eye_region_height = face.width * (kEyePercentHeight/100.0);
  int eye_region_top = face.height * (kEyePercentTop/100.0);
  cv::Rect leftEyeRegion(face.width*(kEyePercentSide/100.0),
                         eye_region_top,eye_region_width,eye_region_height);
  cv::Rect rightEyeRegion(face.width - eye_region_width - face.width*(kEyePercentSide/100.0),
                          eye_region_top,eye_region_width,eye_region_height);

  //-- Find Eye Centers
  cv::Point leftPupil = findEyeCenter(faceROI,leftEyeRegion,"Left Eye");
  cv::Point rightPupil = findEyeCenter(faceROI,rightEyeRegion,"Right Eye");
  // get corner regions
  cv::Rect leftRightCornerRegion(leftEyeRegion);
  leftRightCornerRegion.width -= leftPupil.x;
  leftRightCornerRegion.x += leftPupil.x;
  leftRightCornerRegion.height /= 2;
  leftRightCornerRegion.y += leftRightCornerRegion.height / 2;
  cv::Rect leftLeftCornerRegion(leftEyeRegion);
  leftLeftCornerRegion.width = leftPupil.x;
  leftLeftCornerRegion.height /= 2;
  leftLeftCornerRegion.y += leftLeftCornerRegion.height / 2;
  cv::Rect rightLeftCornerRegion(rightEyeRegion);
  rightLeftCornerRegion.width = rightPupil.x;
  rightLeftCornerRegion.height /= 2;
  rightLeftCornerRegion.y += rightLeftCornerRegion.height / 2;
  cv::Rect rightRightCornerRegion(rightEyeRegion);
  rightRightCornerRegion.width -= rightPupil.x;
  rightRightCornerRegion.x += rightPupil.x;
  rightRightCornerRegion.height /= 2;
  rightRightCornerRegion.y += rightRightCornerRegion.height / 2;
  rectangle(debugFace,leftRightCornerRegion,200);
  rectangle(debugFace,leftLeftCornerRegion,200);
  rectangle(debugFace,rightLeftCornerRegion,200);
  rectangle(debugFace,rightRightCornerRegion,200);
  // change eye centers to face coordinates
  rightPupil.x += rightEyeRegion.x;
  rightPupil.y += rightEyeRegion.y;
  leftPupil.x += leftEyeRegion.x;
  leftPupil.y += leftEyeRegion.y;
  // draw eye centers
  circle(debugFace, rightPupil, 3, 1234);
  circle(debugFace, leftPupil, 3, 1234);

  //-- Find Eye Corners
  if (kEnableEyeCorner) {
    cv::Point2f leftRightCorner = findEyeCorner(faceROI(leftRightCornerRegion), true, false);
    leftRightCorner.x += leftRightCornerRegion.x;
    leftRightCorner.y += leftRightCornerRegion.y;
    cv::Point2f leftLeftCorner = findEyeCorner(faceROI(leftLeftCornerRegion), true, true);
    leftLeftCorner.x += leftLeftCornerRegion.x;
    leftLeftCorner.y += leftLeftCornerRegion.y;
    cv::Point2f rightLeftCorner = findEyeCorner(faceROI(rightLeftCornerRegion), false, true);
    rightLeftCorner.x += rightLeftCornerRegion.x;
    rightLeftCorner.y += rightLeftCornerRegion.y;
    cv::Point2f rightRightCorner = findEyeCorner(faceROI(rightRightCornerRegion), false, false);
    rightRightCorner.x += rightRightCornerRegion.x;
    rightRightCorner.y += rightRightCornerRegion.y;
    circle(faceROI, leftRightCorner, 3, 200);
    circle(faceROI, leftLeftCorner, 3, 200);
    circle(faceROI, rightLeftCorner, 3, 200);
    circle(faceROI, rightRightCorner, 3, 200);
  }

  imshow(face_window_name, faceROI);
//  cv::Rect roi( cv::Point( 0, 0 ), faceROI.size());
//  cv::Mat destinationROI = debugImage( roi );
//  faceROI.copyTo( destinationROI );
}

cv::Mat findSkin (cv::Mat &frame) {
  cv::Mat input;
  cv::Mat output = cv::Mat(frame.rows,frame.cols, CV_8U);

  cvtColor(frame, input, CV_BGR2YCrCb);

  for (int y = 0; y < input.rows; ++y) {
    const cv::Vec3b *Mr = input.ptr<cv::Vec3b>(y);
//    uchar *Or = output.ptr<uchar>(y);
    cv::Vec3b *Or = frame.ptr<cv::Vec3b>(y);
    for (int x = 0; x < input.cols; ++x) {
      cv::Vec3b ycrcb = Mr[x];
//      Or[x] = (skinCrCbHist.at<uchar>(ycrcb[1], ycrcb[2]) > 0) ? 255 : 0;
      if(skinCrCbHist.at<uchar>(ycrcb[1], ycrcb[2]) == 0) {
        Or[x] = cv::Vec3b(0,0,0);
      }
    }
  }
  return output;
}

/**
 * @function detectAndDisplay
 */
void detectAndDisplay( cv::Mat frame ) {
  std::vector<cv::Rect> faces;
  //cv::Mat frame_gray;

  std::vector<cv::Mat> rgbChannels(3);
  cv::split(frame, rgbChannels);
  cv::Mat frame_gray = rgbChannels[2];

  //cvtColor( frame, frame_gray, CV_BGR2GRAY );
  //equalizeHist( frame_gray, frame_gray );
  //cv::pow(frame_gray, CV_64F, frame_gray);
  //-- Detect faces
  face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE|CV_HAAR_FIND_BIGGEST_OBJECT, cv::Size(150, 150) );
//  findSkin(debugImage);

  for( int i = 0; i < faces.size(); i++ )
  {
    rectangle(debugImage, faces[i], 1234);
  }
  //-- Show what you got
  if (faces.size() > 0) {
    findEyes(frame_gray, faces[0]);
  }
}
<commit_msg>change VideoCapture -1 to 0 for mac driver<commit_after>#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <iostream>
#include <queue>
#include <stdio.h>
#include <math.h>

#include "constants.h"
#include "findEyeCenter.h"
#include "findEyeCorner.h"

/** Constants **/

/** Function Headers */
void detectAndDisplay( cv::Mat frame );

/** Global variables */
//-- Note, either copy these two files from opencv/data/haarscascades to your current folder, or change these locations
cv::String face_cascade_name = "../../../res/haarcascade_frontalface_alt.xml";
cv::CascadeClassifier face_cascade;
std::string main_window_name = "Capture - Face detection";
std::string face_window_name = "Capture - Face";
cv::RNG rng(12345);
cv::Mat debugImage;
cv::Mat skinCrCbHist = cv::Mat::zeros(cv::Size(256, 256), CV_8UC1);

/**
 * @function main
 */
int main( int argc, const char** argv ) {
  cv::Mat frame;

  // Load the cascades
  if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading face cascade, please change face_cascade_name in source code.\n"); return -1; };

  cv::namedWindow(main_window_name,CV_WINDOW_NORMAL);
  cv::moveWindow(main_window_name, 400, 100);
  cv::namedWindow(face_window_name,CV_WINDOW_NORMAL);
  cv::moveWindow(face_window_name, 10, 100);
  cv::namedWindow("Right Eye",CV_WINDOW_NORMAL);
  cv::moveWindow("Right Eye", 10, 600);
  cv::namedWindow("Left Eye",CV_WINDOW_NORMAL);
  cv::moveWindow("Left Eye", 10, 800);
  cv::namedWindow("aa",CV_WINDOW_NORMAL);
  cv::moveWindow("aa", 10, 800);
  cv::namedWindow("aaa",CV_WINDOW_NORMAL);
  cv::moveWindow("aaa", 10, 800);

  createCornerKernels();
  ellipse(skinCrCbHist, cv::Point(113, 155.6), cv::Size(23.4, 15.2),
          43.0, 0.0, 360.0, cv::Scalar(255, 255, 255), -1);

  // I make an attempt at supporting both 2.x and 3.x OpenCV
#if CV_MAJOR_VERSION < 3
  CvCapture* capture = cvCaptureFromCAM( 0 );
  if( capture ) {
    while( true ) {
      frame = cvQueryFrame( capture );
#else
  cv::VideoCapture capture(0);
  if( capture.isOpened() ) {
    while( true ) {
      capture.read(frame);
#endif
      // mirror it
      cv::flip(frame, frame, 1);
      frame.copyTo(debugImage);

      // Apply the classifier to the frame
      if( !frame.empty() ) {
        detectAndDisplay( frame );
      }
      else {
        printf(" --(!) No captured frame -- Break!");
        break;
      }

      imshow(main_window_name,debugImage);

      int c = cv::waitKey(10);
      if( (char)c == 'c' ) { break; }
      if( (char)c == 'f' ) {
        imwrite("frame.png",frame);
      }

    }
  }

  releaseCornerKernels();

  return 0;
}

void findEyes(cv::Mat frame_gray, cv::Rect face) {
  cv::Mat faceROI = frame_gray(face);
  cv::Mat debugFace = faceROI;

  if (kSmoothFaceImage) {
    double sigma = kSmoothFaceFactor * face.width;
    GaussianBlur( faceROI, faceROI, cv::Size( 0, 0 ), sigma);
  }
  //-- Find eye regions and draw them
  int eye_region_width = face.width * (kEyePercentWidth/100.0);
  int eye_region_height = face.width * (kEyePercentHeight/100.0);
  int eye_region_top = face.height * (kEyePercentTop/100.0);
  cv::Rect leftEyeRegion(face.width*(kEyePercentSide/100.0),
                         eye_region_top,eye_region_width,eye_region_height);
  cv::Rect rightEyeRegion(face.width - eye_region_width - face.width*(kEyePercentSide/100.0),
                          eye_region_top,eye_region_width,eye_region_height);

  //-- Find Eye Centers
  cv::Point leftPupil = findEyeCenter(faceROI,leftEyeRegion,"Left Eye");
  cv::Point rightPupil = findEyeCenter(faceROI,rightEyeRegion,"Right Eye");
  // get corner regions
  cv::Rect leftRightCornerRegion(leftEyeRegion);
  leftRightCornerRegion.width -= leftPupil.x;
  leftRightCornerRegion.x += leftPupil.x;
  leftRightCornerRegion.height /= 2;
  leftRightCornerRegion.y += leftRightCornerRegion.height / 2;
  cv::Rect leftLeftCornerRegion(leftEyeRegion);
  leftLeftCornerRegion.width = leftPupil.x;
  leftLeftCornerRegion.height /= 2;
  leftLeftCornerRegion.y += leftLeftCornerRegion.height / 2;
  cv::Rect rightLeftCornerRegion(rightEyeRegion);
  rightLeftCornerRegion.width = rightPupil.x;
  rightLeftCornerRegion.height /= 2;
  rightLeftCornerRegion.y += rightLeftCornerRegion.height / 2;
  cv::Rect rightRightCornerRegion(rightEyeRegion);
  rightRightCornerRegion.width -= rightPupil.x;
  rightRightCornerRegion.x += rightPupil.x;
  rightRightCornerRegion.height /= 2;
  rightRightCornerRegion.y += rightRightCornerRegion.height / 2;
  rectangle(debugFace,leftRightCornerRegion,200);
  rectangle(debugFace,leftLeftCornerRegion,200);
  rectangle(debugFace,rightLeftCornerRegion,200);
  rectangle(debugFace,rightRightCornerRegion,200);
  // change eye centers to face coordinates
  rightPupil.x += rightEyeRegion.x;
  rightPupil.y += rightEyeRegion.y;
  leftPupil.x += leftEyeRegion.x;
  leftPupil.y += leftEyeRegion.y;
  // draw eye centers
  circle(debugFace, rightPupil, 3, 1234);
  circle(debugFace, leftPupil, 3, 1234);

  //-- Find Eye Corners
  if (kEnableEyeCorner) {
    cv::Point2f leftRightCorner = findEyeCorner(faceROI(leftRightCornerRegion), true, false);
    leftRightCorner.x += leftRightCornerRegion.x;
    leftRightCorner.y += leftRightCornerRegion.y;
    cv::Point2f leftLeftCorner = findEyeCorner(faceROI(leftLeftCornerRegion), true, true);
    leftLeftCorner.x += leftLeftCornerRegion.x;
    leftLeftCorner.y += leftLeftCornerRegion.y;
    cv::Point2f rightLeftCorner = findEyeCorner(faceROI(rightLeftCornerRegion), false, true);
    rightLeftCorner.x += rightLeftCornerRegion.x;
    rightLeftCorner.y += rightLeftCornerRegion.y;
    cv::Point2f rightRightCorner = findEyeCorner(faceROI(rightRightCornerRegion), false, false);
    rightRightCorner.x += rightRightCornerRegion.x;
    rightRightCorner.y += rightRightCornerRegion.y;
    circle(faceROI, leftRightCorner, 3, 200);
    circle(faceROI, leftLeftCorner, 3, 200);
    circle(faceROI, rightLeftCorner, 3, 200);
    circle(faceROI, rightRightCorner, 3, 200);
  }

  imshow(face_window_name, faceROI);
//  cv::Rect roi( cv::Point( 0, 0 ), faceROI.size());
//  cv::Mat destinationROI = debugImage( roi );
//  faceROI.copyTo( destinationROI );
}

cv::Mat findSkin (cv::Mat &frame) {
  cv::Mat input;
  cv::Mat output = cv::Mat(frame.rows,frame.cols, CV_8U);

  cvtColor(frame, input, CV_BGR2YCrCb);

  for (int y = 0; y < input.rows; ++y) {
    const cv::Vec3b *Mr = input.ptr<cv::Vec3b>(y);
//    uchar *Or = output.ptr<uchar>(y);
    cv::Vec3b *Or = frame.ptr<cv::Vec3b>(y);
    for (int x = 0; x < input.cols; ++x) {
      cv::Vec3b ycrcb = Mr[x];
//      Or[x] = (skinCrCbHist.at<uchar>(ycrcb[1], ycrcb[2]) > 0) ? 255 : 0;
      if(skinCrCbHist.at<uchar>(ycrcb[1], ycrcb[2]) == 0) {
        Or[x] = cv::Vec3b(0,0,0);
      }
    }
  }
  return output;
}

/**
 * @function detectAndDisplay
 */
void detectAndDisplay( cv::Mat frame ) {
  std::vector<cv::Rect> faces;
  //cv::Mat frame_gray;

  std::vector<cv::Mat> rgbChannels(3);
  cv::split(frame, rgbChannels);
  cv::Mat frame_gray = rgbChannels[2];

  //cvtColor( frame, frame_gray, CV_BGR2GRAY );
  //equalizeHist( frame_gray, frame_gray );
  //cv::pow(frame_gray, CV_64F, frame_gray);
  //-- Detect faces
  face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE|CV_HAAR_FIND_BIGGEST_OBJECT, cv::Size(150, 150) );
//  findSkin(debugImage);

  for( int i = 0; i < faces.size(); i++ )
  {
    rectangle(debugImage, faces[i], 1234);
  }
  //-- Show what you got
  if (faces.size() > 0) {
    findEyes(frame_gray, faces[0]);
  }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>

//getlogin() and gethostname().
#include <unistd.h>

//perror.
#include <stdio.h>

//fork,wait and execvp.
#include <sys/types.h>
#include <sys/wait.h>

//boost!
#include "boost/algorithm/string.hpp"
#include "boost/tokenizer.hpp"
#include "boost/foreach.hpp"

//that one class.
#include "Command.h"

using namespace std;
using namespace boost;

//execute command.
void execute(const vector<string> & s);

//replaces char in string.
void replace_char(string &s, char o, char r);

//takes a string and returns vector of parsed string.
vector<string> parseInput(string s);

//display vector.
template<typename unit>
void display_vector(vector<unit> v);

//helper function that finds amount of character.
int find_char_amount(const string s,char c);

//removes comment from input.
void remove_comment(string &s);

//removes char in string.
void remove_char(string &s, char c);

int main()
{

    //grab the login.
    char* login = getlogin();

    //start a flag.
    bool login_check = true;

    if((!login) != 0)
    {
        //check flag.
        login_check = false;

        //output error.
        perror("Error: could not retrieve login name");
    }

    //hold c-string for host name.
    char host[150];

    //start another flag.
    bool host_check = true;

    //gets hostname while checking if it actually grabbed it.
    if(gethostname(host,sizeof(host)) != 0)
    {
        //check flag.
        host_check = false;

        //output error.
        perror("Error: could not rerieve host name.");
    }

    //warn user of upcoming trouble.
    if(login_check == false || host_check == false)
        cout << "Unable to display login and/or host information." << endl;

    //string to hold user input.
    string input;

    while(true)
    {
        //output login@hostname.
        if(login_check && host_check)
            cout << login << '@' << host << ' ';

        //bash money.
        cout << "$ ";

        //placeholder to tell its the program.
        cout << " (program) ";

        //geting input as a string.
        getline(cin,input);

        //remove extra white space.
        trim(input);

        //remove comments.
        remove_comment(input);

        //trim again just in case.
        trim(input);

        //break.
        //if(input == "exit")
            //exit(0);

        //testing parse.
        cout << "Testing parse" << endl;
        display_vector(parseInput(input));

        //execute command.
        execute(parseInput(input));

    }

    cout << "End of program" << endl;

    return 0;
}

void execute(const vector<string> &s)
{
    //check to see if user wants to quit and its the only command.
    if(s.size() == 1)
        for(unsigned int i = 0; i < s.size(); ++i)
            if(s.at(i) == "exit")
                exit(0);

    //c-string to hold command.
    char* args[2048];

    //place and convert commands.
//    for(unsigned int i = 0; i < s.size(); ++i)
//        args[i] = (char*)s.at(i).c_str();
//    args[s.size()] = NULL;

    //place, remove comments and convert commands.
    for(unsigned int i = 0; i < s.size(); ++i)
    {
        string temp = s.at(i);
        replace_char(temp,'\"',' ');
        args[i] = (char*)temp.c_str();
    }
    args[s.size()] = NULL;

    pid_t pid = fork();

    if(pid == -1)
    {
        //fork didn't work.
        perror("fork");
    }
    if(pid ==0)
    {
        if(execvp(args[0], args) == -1)
        {
            //execute didn't work.
            perror("execvp");

            //break out of shadow realm.
            exit(1);
        }

    }
    if(pid > 0)
    {
        //wait for child to die.
        if(wait(0) == -1)
        {
            //didnt wait.
            perror("wait");
        }
    }

    return;
}

vector<string> parseInput(string s)
{

    //replace spaces.
    replace_char(s,' ','*');

    //make temp vector to hold parsed strings.
    vector<string> temp;

    //create boost magic function.
    char_separator<char> sep(" ;||&&(){}", ";||&&()[]",keep_empty_tokens);

    //create boost magic holder thingy.
    tokenizer< char_separator<char> > cm(s,sep);

    //for each loop to grab each peice and push it into a vector.
    for(tokenizer< char_separator<char> >::iterator it = cm.begin(); it != cm.end(); ++it)
        if(*it != "")
        {
            //fix string.
            string temp_string = *it;
            replace_char(temp_string,'*',' ');
            temp.push_back(temp_string);
        }

    //return that vector.
    return temp;
}

void replace_char(string &s, char o, char r)
{
    //different use for the function.
    if(o == '\"')
    {
        //nothing to replace.
        if(s.find(o) == string::npos)
            return;

        //replace.
        for(unsigned int i = 0; i < s.size(); ++i)
            if(s.at(i) == o)
                s.at(i) = r;

        return;

    }

    //no quotes.
    if(s.find("\"") == string::npos)
        return;
    else if(s.find(o) == string::npos)
        return;

    //vector to hold quote positions.
    vector<int> pos;

    //place positions of char into vector.
    for(unsigned int i = 0; i < s.size(); ++i)
        if(s.at(i) == '\"')
            pos.push_back(i);

    //count position.
    unsigned int count = 0;

    //replace.
    while(count < pos.size())
    {
        for(int i = pos.at(count); i < pos.at(count+1); ++i)
            if(s.at(i) == o)
                s.at(i) = r;

        count++;
        count++;
    }

    return;
}

template<typename unit>
void display_vector(vector<unit> v)
{
    for(unsigned int i = 0; i < v.size(); ++i)
        cout << i+1 << ": " << v.at(i) << endl;
    return;
}

void remove_comment(string &s)
{
    //just add a " to the end to avoid errors.
    if(find_char_amount(s,'\"') % 2 != 0)
        s += '\"';

    //delete everything!
    if(s.find("#") == 0)
    {
        s = "";
        return;
    }

    //return if no comments.
    if(s.find("#") == string::npos)
    {
        return;
    }

    //if no comments then delets everything from hash forward.
    if(s.find("\"") == string::npos && s.find("#") != string::npos)
    {
        s = s.substr(0,s.find("#"));
        return;
    }

    //if comment before quote then delete.
    if(s.find("\"") > s.find("#"))
    {
        s = s.substr(0,s.find("#"));
        return;
    }

    //advanced situations.
    //get a vector to hold positions of quotes and hash.
    vector<int> quotePos;
    vector<int> hashPos;

    //grab pos.
    for(unsigned int i = 0; i < s.size(); ++i)
    {
        if(s.at(i) == '\"')
            quotePos.push_back(i);
        else if(s.at(i) == '#')
            hashPos.push_back(i);
    }

    //no comments or hash for some reason.
    if(hashPos.size() == 0 || quotePos.size() == 0)
        return;

    //just in case.
    if(quotePos.size() % 2 != 0)
        quotePos.push_back(0);

    //overall check;
    vector<bool> check;

    //start it up.
    for(unsigned int i = 0; i < hashPos.size(); ++i)
        check.push_back(true);

    //check if hash is in quotes.
    for(unsigned int i = 0; i < hashPos.size(); ++i )
        for(unsigned int j = 0; j < quotePos.size(); j+=2 )
        {
            if(hashPos.at(i) > quotePos.at(j) && hashPos.at(i) < quotePos.at(j+1))
            {
                check.at(i) = true;
                break;
            }
            else
                check.at(i) = false;
        }

    //check bool vector to delete string.
    for(unsigned int i = 0; i < check.size(); ++i)
        if(!check.at(i))
        {
            s = s.substr(0,hashPos.at(i));
            return;
        }

    //if comment at end then kill it.
    if(hashPos.at(hashPos.size()-1) > quotePos.at(quotePos.size()-1))
        s = s.substr(0,hashPos.at(hashPos.size()-1));

    return;
}

int find_char_amount(const string s, char c)
{
    if(s.find(c) == string::npos)
        return 0;

    int count = 0;
    for(unsigned int i = 0; i < s.size(); ++i)
        if(s.at(i) == c)
            count++;
    return count;

}

//broken.
void remove_char(string &s, char c)
{
    //if not there then just return.
    if(s.find(c) == string::npos)
        return;
    else if(s.size() == 1 && s.at(0) == c)
    {
        s = "";
        return;
    }

    //vector to hold positions of char.
    vector<int> pos;

    //grab pos of char.
    for(unsigned int i = 0; i < s.size(); ++i)
        if(s.at(i) == c)
            pos.push_back(i);

    //start removing.
    for(unsigned int i = 0; i < pos.size(); ++i)
    {
        if(pos.at(i) == 0)
            s = s.substr(i+1);
        else if(static_cast<unsigned>(pos.at(i)) == s.size() - 1)
            s = s.substr(0,s.size() - 1);
        else
            s = s.substr(0,pos.at(i)) + s.substr(pos.at(i)+1);

        //because you delete a index, you remove a index from the positions.
        if(pos.size() != 0)
            for(unsigned int j = i; j < pos.size(); ++j)
                if(pos.at(i) >= 1)
                    pos.at(i) -= 1;
    }

    return;
}

<commit_msg>bad stuff<commit_after>#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>

//getlogin() and gethostname().
#include <unistd.h>

//perror.
#include <stdio.h>

//fork,wait and execvp.
#include <sys/types.h>
#include <sys/wait.h>

//boost!
#include "boost/algorithm/string.hpp"
#include "boost/tokenizer.hpp"
#include "boost/foreach.hpp"

//that one class.
#include "Command.h"

using namespace std;
using namespace boost;

//execute command.
void execute(const vector<string> & s);

//replaces char in string.
void replace_char(string &s, char o, char r);

//takes a string and returns vector of parsed string.
vector<string> parseInput(string s);

//display vector.
template<typename unit>
void display_vector(vector<unit> v);

//helper function that finds amount of character.
int find_char_amount(const string s,char c);

//removes comment from input.
void remove_comment(string &s);

//removes char in string.
void remove_char(string &s, char c);

int main()
{

    //grab the login.
    char* login = getlogin();

    //start a flag.
    bool login_check = true;

    if((!login) != 0)
    {
        //check flag.
        login_check = false;

        //output error.
        perror("Error: could not retrieve login name");
    }

    //hold c-string for host name.
    char host[150];

    //start another flag.
    bool host_check = true;

    //gets hostname while checking if it actually grabbed it.
    if(gethostname(host,sizeof(host)) != 0)
    {
        //check flag.
        host_check = false;

        //output error.
        perror("Error: could not rerieve host name.");
    }

    //warn user of upcoming trouble.
    if(login_check == false || host_check == false)
        cout << "Unable to display login and/or host information." << endl;

    //string to hold user input.
    string input;

    while(true)
    {
        //output login@hostname.
        if(login_check && host_check)
            cout << login << '@' << host << ' ';

        //bash money.
        cout << "$ ";

        //placeholder to tell its the program.
        cout << " (program) ";

        //geting input as a string.
        getline(cin,input);

        //remove extra white space.
        trim(input);

        //remove comments.
        remove_comment(input);

        //trim again just in case.
        trim(input);

        //break.
        //if(input == "exit")
            //exit(0);

        //testing parse.
        cout << "Testing parse" << endl;
        display_vector(parseInput(input));

        //execute command.
        execute(parseInput(input));

    }

    cout << "End of program" << endl;

    return 0;
}

void execute(const vector<string> &s)
{
    //check to see if user wants to quit and its the only command.
    if(s.size() == 1)
        for(unsigned int i = 0; i < s.size(); ++i)
            if(s.at(i) == "exit")
                exit(0);

    //c-string to hold command.
    char* args[2048];

    //place and convert commands.
//    for(unsigned int i = 0; i < s.size(); ++i)
//        args[i] = (char*)s.at(i).c_str();
//    args[s.size()] = NULL;

    //place, remove comments and convert commands.
    for(unsigned int i = 0; i < s.size(); ++i)
    {
        string temp = s.at(i);
        replace_char(temp,'\"',' ');
        args[i] = (char*)temp.c_str();
    }
    args[s.size()] = NULL;

    pid_t pid = fork();

    if(pid == -1)
    {
        //fork didn't work.
        perror("fork");
    }
    if(pid ==0)
    {
        if(execvp(args[0], args) == -1)
        {
            //execute didn't work.
            perror("execvp");

            //break out of shadow realm.
            exit(1);
        }

    }
    if(pid > 0)
    {
        //wait for child to die.
        if(wait(0) == -1)
        {
            //didnt wait.
            perror("wait");
        }
    }

    return;
}

vector<string> parseInput(string s)
{

    //replace spaces.
    replace_char(s,' ','*');

    //make temp vector to hold parsed strings.
    vector<string> temp;

    //create boost magic function.
    char_separator<char> sep(" ;||&&(){}", ";||&&()[]",keep_empty_tokens);

    //create boost magic holder thingy.
    tokenizer< char_separator<char> > cm(s,sep);

    //for each loop to grab each peice and push it into a vector.
    for(tokenizer< char_separator<char> >::iterator it = cm.begin(); it != cm.end(); ++it)
        if(*it != "")
        {
            //fix string.
            string temp_string = *it;
            replace_char(temp_string,'*',' ');
            temp.push_back(temp_string);
        }

    //return that vector.
    return temp;
}

void replace_char(string &s, char o, char r)
{
    //different use for the function.
    if(o == '\"')
    {
        //nothing to replace.
        if(s.find(o) == string::npos)
            return;

        //replace.
        for(unsigned int i = 0; i < s.size(); ++i)
            if(s.at(i) == o)
                s.at(i) = r;

        return;

    }

    //no quotes.
    if(s.find("\"") == string::npos)
        return;
    else if(s.find(o) == string::npos)
        return;

    //vector to hold quote positions.
    vector<int> pos;

    //place positions of char into vector.
    for(unsigned int i = 0; i < s.size(); ++i)
        if(s.at(i) == '\"')
            pos.push_back(i);

    //count position.
    unsigned int count = 0;

    //replace.
    while(count < pos.size())
    {
        for(int i = pos.at(count); i < pos.at(count+1); ++i)
            if(s.at(i) == o)
                s.at(i) = r;

        count++;
        count++;
    }

    return;
}

template<typename unit>
void display_vector(vector<unit> v)
{
    for(unsigned int i = 0; i < v.size(); ++i)
        cout << i+1 << ": " << v.at(i) << endl;
    return;
}

void remove_comment(string &s)
{
    //just add a " to the end to avoid errors.
    if(find_char_amount(s,'\"') % 2 != 0)
        s += '\"';

    //delete everything!
    if(s.find("#") == 0)
    {
        s = "";
        return;
    }

    //return if no comments.
    if(s.find("#") == string::npos)
    {
        return;
    }

    //if no comments then deletes everything from hash forward.
    if(s.find("\"") == string::npos && s.find("#") != string::npos)
    {
        s = s.substr(0,s.find("#"));
        return;
    }

    //if comment before quote then delete.
    if(s.find("\"") > s.find("#"))
    {
        s = s.substr(0,s.find("#"));
        return;
    }

    //advanced situations.
    //get a vector to hold positions of quotes and hash.
    vector<int> quotePos;
    vector<int> hashPos;

    //grab pos.
    for(unsigned int i = 0; i < s.size(); ++i)
    {
        if(s.at(i) == '\"')
            quotePos.push_back(i);
        else if(s.at(i) == '#')
            hashPos.push_back(i);
    }

    //no comments or hash for some reason.
    if(hashPos.size() == 0 || quotePos.size() == 0)
        return;

    //just in case.
    if(quotePos.size() % 2 != 0)
        quotePos.push_back(0);

    //overall check;
    vector<bool> check;

    //start it up.
    for(unsigned int i = 0; i < hashPos.size(); ++i)
        check.push_back(true);

    //check if hash is in quotes.
    for(unsigned int i = 0; i < hashPos.size(); ++i )
        for(unsigned int j = 0; j < quotePos.size(); j+=2 )
        {
            if(hashPos.at(i) > quotePos.at(j) && hashPos.at(i) < quotePos.at(j+1))
            {
                check.at(i) = true;
                break;
            }
            else
                check.at(i) = false;
        }

    //check bool vector to delete string.
    for(unsigned int i = 0; i < check.size(); ++i)
        if(!check.at(i))
        {
            s = s.substr(0,hashPos.at(i));
            return;
        }

    //if comment at end then kill it.
    if(hashPos.at(hashPos.size()-1) > quotePos.at(quotePos.size()-1))
        s = s.substr(0,hashPos.at(hashPos.size()-1));

    return;
}

int find_char_amount(const string s, char c)
{
    if(s.find(c) == string::npos)
        return 0;

    int count = 0;
    for(unsigned int i = 0; i < s.size(); ++i)
        if(s.at(i) == c)
            count++;
    return count;

}

//broken.
void remove_char(string &s, char c)
{
    //if not there then just return.
    if(s.find(c) == string::npos)
        return;
    else if(s.size() == 1 && s.at(0) == c)
    {
        s = "";
        return;
    }

    //vector to hold positions of char.
    vector<int> pos;

    //grab pos of char.
    for(unsigned int i = 0; i < s.size(); ++i)
        if(s.at(i) == c)
            pos.push_back(i);

    //start removing.
    for(unsigned int i = 0; i < pos.size(); ++i)
    {
        if(pos.at(i) == 0)
            s = s.substr(i+1);
        else if(static_cast<unsigned>(pos.at(i)) == s.size() - 1)
            s = s.substr(0,s.size() - 1);
        else
            s = s.substr(0,pos.at(i)) + s.substr(pos.at(i)+1);

        //because you delete a index, you remove a index from the positions.
        if(pos.size() != 0)
            for(unsigned int j = i; j < pos.size(); ++j)
                if(pos.at(i) >= 1)
                    pos.at(i) -= 1;
    }

    return;
}

<|endoftext|>