<commit_before>#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>

using namespace std;

/* BUGS:
 * 1. out of range error when ending with a connector '<' or '>' */

//ONCE YOU ARE DONE, MERGE THIS FILE WITH RSHELL AND DELETE TARGET IN MAKEFILE

/* function1: prints out any type */
#define printVec(x) for(unsigned int i = 0; i < x.size(); i++) \
                        cout << x.at(i) << ' '; \
                    cout << endl;

/* function2: prints out any regular variable */
template<typename T>
void printReg(T &sample){
    cout << sample << endl;
    return;
}

/* function3: extract componenets in a vector using strtok */
vector<char*> getParts(string &wut){
    /* vector of each piece to return*/
    vector<char*> brokenParts;

    /* convert to const char* to allow for parameter match*/
    const char* wut_cstring = wut.c_str();

    /* cast it to allow char* paramter cabability*/
    char* wut_cstring_2 = const_cast<char*>(wut_cstring);

    /* each individual command will be stored here temporarily*/
    char* token;

    /* extract with delimeters*/
    token = strtok(wut_cstring_2, " ");

    /* counter for list of argument parameters*/
    int pos = 0;

    /*extract until end of line*/
    while(token != NULL){
        /* output each token */
        //cout << "token" << pos << ": " << token << endl;

        /* push each token onto vector */
        brokenParts.push_back(token);

        /* keep tokenizing*/
        token = strtok(NULL, " ");

        /*increment counter */
        pos++;
    }

    /* return vector of char* */
    return brokenParts;
}

/* function4: performs input redirection */
/* parmeter1: command that you will run on the files*/
/* parmeter2: the vector of files to open and redirect input on */
/* parmeter3: list of all arguments (needed for execvp) */
void inputRedirection(char* command, vector<char*> files, char **argv){
    /* flush standard in so that, if the forked child writes to standard
     * error because of a problem, there will be no extraneous duplicated
     * output.*/
    fflush(STDIN_FILENO);

    /*open up all the files in the vector of files */
    for(unsigned int i = 0; i < files.size(); i++){
        int fd0 = open(files.at(i), O_RDONLY);
        if(fd0 == -1){
            perror(files.at(i));
            exit(1);
        }
        /* duplicate the file descriptor */
        dup2(fd0, STDIN_FILENO);

        /* close the file descriptor */
        close(fd0);
    }

    /* pid gets the value of fork*/
    int pid = fork();

    /* based on the value of fork, perform the following operations */
    if(pid == -1){ //fork straight up failed you...
        perror("fork() failed");
        exit(1);
    }
    else if(pid == 0){ //child process = good *thumbs up*
        /* run the command passed in */
        if( execvp(command, argv) == -1){
            perror("error running execvp");
            exit(1);
        }
    }
    else if(pid > 0){ //we have to wait for the child process to die
        if ( -1 == wait(0)){
            perror("there was an error with wait");
        }
    }
    return;
}

/* function5: performs output redirection */
/* parmeter1: command that you will run on the files*/
/* parmeter2: the vector of files to open and redirect output on */
/* parmeter3: list of all arguments (needed for execvp) */

void outputRedirection(char* command, vector<char*> files, char** argv){
    /* flush standard out so that, if the forked child writes to standard
     * error because of a problem, there will be no extraneous duplicated
     * output.*/
    fflush(stdout);

     /*open up all the files in the vector of files */
    for(unsigned int i = 0; i < files.size(); i++){
        int fd1 = open(files.at(i), O_WRONLY | O_TRUNC | O_CREAT,
                                    S_IRGRP | S_IWGRP | S_IWUSR);

        if(fd1 == -1){
            perror(files.at(i));
            exit(1);
        }

        /* duplicate file descriptor */
        dup2(fd1, STDOUT_FILENO);

        /* close the file descriptor */
        close(fd1);
    }

    /* pid gets the value of fork*/
    int pid = fork();

    /* based on the value of fork, perform the following operations */
    if(pid == -1){ //fork straight up failed you...
        perror("fork() failed");
        exit(1);
    }
    else if(pid == 0){ //child process = good *thumbs up*
        /* run the command passed in */
        if( execvp(command, argv) == -1){
            perror("error running execvp");
            exit(1);
        }
    }
    else if(pid > 0){ //we have to wait for the child process to die
        if ( -1 == wait(0)){
            perror("there was an error with wait");
        }
    }
    return;
}

/* function6: in_out_redirection */
/* this function perform input and output redirection together
 * if '<' and '>' are spotted on the same line */
/* parmeter1: command that you will run on the files*/
/* parmeter2: the vector of files to open and redirect output on */
/* parmeter3: list of all arguments (needed for execvp) */

void in_out_redirection(char* command, vector<char*> files,
                        vector<char*> connectors, char** argv){
    /* flush both STDIN and STDOUT */
    fflush(STDIN_FILENO);
    fflush(stdout);
    vector<char*> infiles;
    vector<char*> outfiles;
    for(unsigned int i = 0; i < files.size(); i++){
        if(*(connectors.at(i)) == '<'){
            infiles.push_back(files.at(i));
        }
        else if(*(connectors.at(i)) == '>'){
            outfiles.push_back(files.at(i));
        }
    }

    for(unsigned int x = 0; x < infiles.size(); x++){
        int in = open(infiles.at(x), O_RDONLY);
        if(in == -1){
            perror("open");
            exit(1);
        }
        dup2(in, STDIN_FILENO);
        close(in);
    }

    for(unsigned int z = 0; z < outfiles.size(); z++){
        int out = open(outfiles.at(z), O_WRONLY | O_TRUNC | O_CREAT,
                                      S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
        if(out == -1){
            perror("open");
            exit(1);
        }
        dup2(out, STDOUT_FILENO);
        close(out);
    }

    /* pid gets the value of fork*/
    int pid = fork();

    /* based on the value of fork, perform the following operations */
    if(pid == -1){ //fork straight up failed you...
        perror("fork() failed");
        exit(1);
    }
    else if(pid == 0){ //child process = good *thumbs up*
        /* run the command passed in */
        if( execvp(command, argv) == -1){
            perror("error running execvp");
            exit(1);
        }
    }
    else if(pid > 0){ //we have to wait for the child process to die
        if ( -1 == wait(0)){
            perror("there was an error with wait");
        }
    }

    return;
}

/* function7: extracts connectors */
/* this function extracts the connectors and stores them in one vector
 * and the rest of the files and/or commands into another vector*/
/* parameter1: the vector of ALL the words and connectors
 * parameter2: the vectors of words we will extract from the first parameter*/
vector<char*> extractConnectors(vector<char*> &commands, vector<char*> &words){
    /* create a vector for connectors*/
    vector<char*> connectors;

    /* loop through the commands vectors and push back all connectors onto
     * the connectors vector */
    for(unsigned int i = 0; i < commands.size(); i++){
        /* if you find a '<' push it onto connectors vector*/
        if(*(commands.at(i)) == '<'){
            connectors.push_back(commands.at(i));
        }
        /* if you find a '>' push it onto the connectors vector*/
        else if(*(commands.at(i)) == '>'){
            connectors.push_back(commands.at(i));
        }
        /* if you find a '|' push it onto the connectors vector*/
        else if(*(commands.at(i)) == '|'){
            connectors.push_back(commands.at(i));
        }
        /* if you fail to find any of the connectors above, then push the file
         * or command onto the words vector*/
        else{
            words.push_back(commands.at(i));
        }
    }

    return connectors;
}

/* function8: perform logic - IO/pipe */
void logic(vector<char*> &connectors, vector<char*> &words, char **argv){
    /* we assume that the first input is a command and the rest of the
     * componenets in the vector will be files that are either created
     * or will be created */
    char* command = words.at(0);

    /* erase the first element in the vector<char*> words as it is the
     * command and we should not parse through that */
    words.erase(words.begin());

    /* 1. if there is only connector then only execute inputRedirection
     * once*/
    if(connectors.size() == 1 && *(connectors.at(0)) == '<'){
        inputRedirection(command, words, argv);
        return;
    }
    /* if the vector contain's all '<' signs, then only call
     * inputRedirection once. */
    /* in other words, if you ever see a '>' or '|' sign then stop*/
    else if(connectors.size() > 1 && *(connectors.at(0)) == '<'){
        for(unsigned int i = 0; i < connectors.size(); i++){
           if(*(connectors.at(i)) == '>' || *(connectors.at(i)) == '|'){
               in_out_redirection(command, words, connectors, argv);
               return;
           }
        }
        /* the vector contains all '<' sign so call inputRedirection once!*/
        inputRedirection(command, words, argv);
    }
    /* if there is only one '>' connector, then only execute
     * outputRedirection once*/
    else if(connectors.size() == 1 && *(connectors.at(0)) == '>'){
        outputRedirection(command, words, argv);
        return;
    }
    /* if the vector contain's all '>' signs, then only call
     * outputRedirection once. */
    else if(connectors.size() > 1 && *(connectors.at(0)) == '>'){
        for(unsigned int i = 0; i < connectors.size(); i++){
           if(*(connectors.at(i)) == '<' || *(connectors.at(i)) == '|'){
               //specialcase();
               return;
           }

           /* the vector contains all '>' signs so call outputRedirection
            * once! */
           outputRedirection(command, words, argv);
        }
    }
    return;
}

int main(int argc, char** argv){
    /* user input */
    string input;

    /* get user input */
    getline(cin, input);

    /* extract components */
    vector<char*> components;
    components = getParts(input);

    /* 1. separate connectors from files and/or commands */
    /* 2. create a vector for the files and/or commands to parse through*/
    vector<char*> words;
    /* 3. create a connectors vector that the extractConnects should return */
    vector<char*> connectors;

    /* call extractconnectors command to retrieve all the connectors*/
    connectors = extractConnectors(components, words);

    /*perform appropriate logic*/
    logic(connectors, words, argv);
    return 0;
}
<commit_msg>added<commit_after>#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>

using namespace std;

/* BUGS:
 * 1. out of range error when ending with a connector '<' or '>'
 * 2. ls > output < input doesn't work the way bash does
 * 3. echo hello > file.txt doesn't work the way bash does. it creates
 *    two files called "hello" and "file.txt" */

//ONCE YOU ARE DONE, MERGE THIS FILE WITH RSHELL AND DELETE TARGET IN MAKEFILE

/* function1: prints out any type */
#define printVec(x) for(unsigned int i = 0; i < x.size(); i++) \
                        cout << x.at(i) << ' '; \
                    cout << endl;

/* function2: prints out any regular variable */
template<typename T>
void printReg(T &sample){
    cout << sample << endl;
    return;
}

/* function3: extract componenets in a vector using strtok */
vector<char*> getParts(string &wut){
    /* vector of each piece to return*/
    vector<char*> brokenParts;

    /* convert to const char* to allow for parameter match*/
    const char* wut_cstring = wut.c_str();

    /* cast it to allow char* paramter cabability*/
    char* wut_cstring_2 = const_cast<char*>(wut_cstring);

    /* each individual command will be stored here temporarily*/
    char* token;

    /* extract with delimeters*/
    token = strtok(wut_cstring_2, " ");

    /* counter for list of argument parameters*/
    int pos = 0;

    /*extract until end of line*/
    while(token != NULL){
        /* output each token */
        //cout << "token" << pos << ": " << token << endl;

        /* push each token onto vector */
        brokenParts.push_back(token);

        /* keep tokenizing*/
        token = strtok(NULL, " ");

        /*increment counter */
        pos++;
    }

    /* return vector of char* */
    return brokenParts;
}

/* function4: performs input redirection */
/* parmeter1: command that you will run on the files*/
/* parmeter2: the vector of files to open and redirect input on */
/* parmeter3: list of all arguments (needed for execvp) */
void inputRedirection(char* command, vector<char*> files, char **argv){
    /* flush standard in so that, if the forked child writes to standard
     * error because of a problem, there will be no extraneous duplicated
     * output.*/
    fflush(STDIN_FILENO);

    /*open up all the files in the vector of files */
    for(unsigned int i = 0; i < files.size(); i++){
        int fd0 = open(files.at(i), O_RDONLY);
        if(fd0 == -1){
            perror(files.at(i));
            exit(1);
        }
        /* duplicate the file descriptor */
        dup2(fd0, STDIN_FILENO);

        /* close the file descriptor */
        close(fd0);
    }

    /* pid gets the value of fork*/
    int pid = fork();

    /* based on the value of fork, perform the following operations */
    if(pid == -1){ //fork straight up failed you...
        perror("fork() failed");
        exit(1);
    }
    else if(pid == 0){ //child process = good *thumbs up*
        /* run the command passed in */
        if( execvp(command, argv) == -1){
            perror("error running execvp");
            exit(1);
        }
    }
    else if(pid > 0){ //we have to wait for the child process to die
        if ( -1 == wait(0)){
            perror("there was an error with wait");
        }
    }
    return;
}

/* function5: performs output redirection */
/* parmeter1: command that you will run on the files*/
/* parmeter2: the vector of files to open and redirect output on */
/* parmeter3: list of all arguments (needed for execvp) */

void outputRedirection(char* command, vector<char*> files, char** argv){
    /* flush standard out so that, if the forked child writes to standard
     * error because of a problem, there will be no extraneous duplicated
     * output.*/
    fflush(stdout);

     /*open up all the files in the vector of files */
    for(unsigned int i = 0; i < files.size(); i++){
        int fd1 = open(files.at(i), O_WRONLY | O_TRUNC | O_CREAT,
                                    S_IRGRP | S_IWGRP | S_IWUSR);

        if(fd1 == -1){
            perror(files.at(i));
            exit(1);
        }

        /* duplicate file descriptor */
        dup2(fd1, STDOUT_FILENO);

        /* close the file descriptor */
        close(fd1);
    }

    /* pid gets the value of fork*/
    int pid = fork();

    /* based on the value of fork, perform the following operations */
    if(pid == -1){ //fork straight up failed you...
        perror("fork() failed");
        exit(1);
    }
    else if(pid == 0){ //child process = good *thumbs up*
        /* run the command passed in */
        if( execvp(command, argv) == -1){
            perror("error running execvp");
            exit(1);
        }
    }
    else if(pid > 0){ //we have to wait for the child process to die
        if ( -1 == wait(0)){
            perror("there was an error with wait");
        }
    }
    return;
}

/* function6: in_out_redirection */
/* this function perform input and output redirection together
 * if '<' and '>' are spotted on the same line */
/* parmeter1: command that you will run on the files*/
/* parmeter2: the vector of files to open and redirect output on */
/* parmeter3: list of all arguments (needed for execvp) */

void in_out_redirection(char* command, vector<char*> files,
                        vector<char*> connectors, char** argv, bool special){
    /* flush both STDIN and STDOUT */
    //fflush(STDIN_FILENO);
    //fflush(stdout);
    vector<char*> infiles;
    vector<char*> outfiles;

    for(unsigned int i = 0; i < files.size(); i++){
        char* temp_connector = connectors.at(0);
        unsigned int connector_length = sizeof(temp_connector);

        if(*(connectors.at(i)) == '<'){
            infiles.push_back(files.at(i));
        }
        else if(connector_length > 1 && temp_connector[0] == '>'
                                     && temp_connector[1] == '>'){
            outfiles.push_back(files.at(i));
        }
        else if(*(connectors.at(i)) == '>'){
            outfiles.push_back(files.at(i));
        }
    }

    for(unsigned int x = 0; x < infiles.size(); x++){
        int in = open(infiles.at(x), O_RDONLY);
        if(in == -1){
            perror("open");
            exit(1);
        }
        dup2(in, STDIN_FILENO);
        close(in);
    }

    if(special == true){
        for(unsigned int z = 0; z < outfiles.size(); z++){
            int out = open(outfiles.at(z), O_WRONLY | O_APPEND, 0644);
            if(out == -1){
                perror("open");
                exit(1);
            }
            dup2(out, STDOUT_FILENO);
            close(out);
        }
    }
    else{
        for(unsigned int z = 0; z < outfiles.size(); z++){
            int out = open(outfiles.at(z), O_RDWR | O_CREAT | O_APPEND, 0644);
            if(out == -1){
                perror("open");
                exit(1);
            }
            dup2(out, STDOUT_FILENO);
            close(out);
        }
    }

    /* pid gets the value of fork*/
    int pid = fork();

    /* based on the value of fork, perform the following operations */
    if(pid == -1){ //fork straight up failed you...
        perror("fork() failed");
        exit(1);
    }
    else if(pid == 0){ //child process = good *thumbs up*
        /* run the command passed in */
        if( execvp(command, argv) == -1){
            perror("error running execvp");
            exit(1);
        }
    }
    else if(pid > 0){ //we have to wait for the child process to die
        if ( -1 == wait(0)){
            perror("there was an error with wait");
        }
    }

    return;
}

/* function7: extracts connectors */
/* this function extracts the connectors and stores them in one vector
 * and the rest of the files and/or commands into another vector*/
/* parameter1: the vector of ALL the words and connectors
 * parameter2: the vectors of words we will extract from the first parameter*/
vector<char*> extractConnectors(vector<char*> &commands, vector<char*> &words){
    /* create a vector for connectors*/
    vector<char*> connectors;

    /* loop through the commands vectors and push back all connectors onto
     * the connectors vector */
    for(unsigned int i = 0; i < commands.size(); i++){
        /* create a temporary string to check for a ">>" connector */
        string temp_connector;
        temp_connector.assign(commands.at(i));

        /* need the length to differentiate between a '>' and ">>" */
        unsigned int connector_length = temp_connector.size();

        /* if you find a '<' push it onto connectors vector*/
        if(connector_length == 1 && *(commands.at(i)) == '<'){
            connectors.push_back(commands.at(i));
        }
        /* if you find a '>' push it onto the connectors vector*/
        else if(connector_length == 1 && *(commands.at(i)) == '>'){
            connectors.push_back(commands.at(i));
        }
        else if(connector_length > 1 && temp_connector[0] == '>' &&
                                        temp_connector[1] == '>'){
            //cout << "the special character exists" << endl;
            connectors.push_back(commands.at(i));
        }
        /* if you find a '|' push it onto the connectors vector*/
        else if(connector_length == 1 && *(commands.at(i)) == '|'){
            connectors.push_back(commands.at(i));
        }
        /* if you fail to find any of the connectors above, then push the file
         * or command onto the words vector*/
        else{
            words.push_back(commands.at(i));
        }
    }

    return connectors;
}

/* function8: perform logic - IO/pipe */
void logic(vector<char*> &connectors, vector<char*> &words, char **argv){
    /* bool to signify it is a ">>" sign */
    bool appended = false;

    /* we assume that the first input is a command and the rest of the
     * componenets in the vector will be files that are either created
     * or will be created */
    char* command = words.at(0);

    /* erase the first element in the vector<char*> words as it is the
     * command and we should not parse through that */
    words.erase(words.begin());

    /* 1. if there is only connector then only execute inputRedirection
     * once*/
    if(connectors.size() == 1 && *(connectors.at(0)) == '<'){
        inputRedirection(command, words, argv);
        return;
    }
    /* if the vector contain's all '<' signs, then only call
     * inputRedirection once. */
    /* in other words, if you ever see a '>' or '|' sign then stop*/
    else if(connectors.size() > 1 && *(connectors.at(0)) == '<'){
        for(unsigned int i = 0; i < connectors.size(); i++){
           if(*(connectors.at(i)) == '>' || *(connectors.at(i)) == '|'){
               in_out_redirection(command, words, connectors, argv, appended);
               return;
           }
        }
        /* the vector contains all '<' sign so call inputRedirection once!*/
        inputRedirection(command, words, argv);
    }
    /* if there is only one '>' connector, then only execute
     * outputRedirection once*/
    else if(connectors.size() == 1 && *(connectors.at(0)) == '>'){
        string temp_connector;
        temp_connector.assign(connectors.at(0));

        unsigned int connector_length = temp_connector.size();

        if(connector_length > 1 && temp_connector[0] == '>' && temp_connector[1] == '>'){
            /* the bool that signifies the ">>" connector */
            appended = true;
            in_out_redirection(command, words, connectors, argv, appended);
            return;
        }
        outputRedirection(command, words, argv);
        return;
    }
    /* if the vector contain's all '>' signs, then only call
     * outputRedirection once. */
    else if(connectors.size() > 1 && *(connectors.at(0)) == '>'){
        for(unsigned int i = 0; i < connectors.size(); i++){
           string temp_connector;
           temp_connector.assign(connectors.at(i));

           unsigned int connector_length = temp_connector.size();
           if(connector_length > 1 && temp_connector[0] == '>' && temp_connector[1] == '>'){
               in_out_redirection(command, words, connectors, argv, appended);
               return;
           }
           if(*(connectors.at(i)) == '<' || *(connectors.at(i)) == '|'){
               in_out_redirection(command, words, connectors, argv, appended);
               return;
           }

           /* the vector contains all '>' signs so call outputRedirection
            * once! */
           outputRedirection(command, words, argv);
        }
    }
    return;
}

int main(int argc, char** argv){
    /* user input */
    string input;

    /* get user input */
    getline(cin, input);

    /* extract components */
    vector<char*> components;
    components = getParts(input);

    /* 1. separate connectors from files and/or commands */
    /* 2. create a vector for the files and/or commands to parse through*/
    vector<char*> words;
    /* 3. create a connectors vector that the extractConnects should return */
    vector<char*> connectors;

    /* call extractconnectors command to retrieve all the connectors*/
    connectors = extractConnectors(components, words);

    /*perform appropriate logic*/
    logic(connectors, words, argv);
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>commit code<commit_after><|endoftext|>


<commit_before><commit_msg>Made CopyFileToLocalDisk set position after each loop to avoid corruption<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include "YetAnotherRegularExpressionEngine.h"
#include <ctime>
#ifdef _DEBUG
#include <conio.h>
#endif
#ifdef _MSC_VER
#include <intrin.h>
#pragma intrinsic(__rdtsc)
#endif
void expect(const char *expr, bool ex, bool ac){
	const char* e = ex ? "true" : "false";
	const char *a = ac ? "true" : "false";
	if (ex == ac){
		std::cout << "passed: " << expr << " = " << e << std::endl;
	}
	else{
		std::cout << "!!error: expect " << expr << " = " << e << ", get " << a << " instead." << std::endl;
	}
}
class TestException{
	FA2 fa;
	std::string re;
public:
	TestException(const char *re) :fa(re), re(re){}
	TestException& operator ,(const char *p){
		try{
			fa << p;
		}
		catch (FA1::SyntaxErrorException&){
			std::cout << "passed: expected exception received for RE /" << re << "/" << std::endl;
			return *this;
		}
		std::cout << "!!error: expected exception was not caught." << std::endl;
		return *this;
	}
};
class Expect{
	bool assert;
public:
	explicit Expect(bool b) :assert(b){}
	bool GetAssert(){ return assert; }
};
class Test{
	bool assert;
	FA1 faCompare;
	FA2 fa;
public:
	Test(const char *re, Expect e) :fa(re), faCompare(re), assert(e.GetAssert()){
		std::cout << "Testing RE /" << re << "/ :" << std::endl;
	}
	Test& operator ,(const char*p){
		using namespace std;
		if (*p == '\0'){
			expect("<Empty String>", assert, fa << p);
		}
		else{
			expect(p, assert, fa << p);
		}
#ifdef _MSC_VER
		unsigned __int64 start;
		start = __rdtsc();
		for (int i = 0; i < 999; ++i){
			faCompare << p;
		}
		unsigned __int64 time1 = __rdtsc() - start;
		cout << "nfa took " << time1 << " clock cycles to calulate for 999 times" << endl;
		start = __rdtsc();
		for (int i = 0; i < 999; ++i){
			fa << p;
		}
		unsigned __int64 time2 = __rdtsc() - start;
		cout << "dfa took " << time2 << " clock cycles to calulate for 999 times" << endl;
		cout << "factor: " << time1 / time2 << endl;
#else
		time_t tm;
		tm = time(0);
		for (int i = 0; i < 1000000; ++i){
			faCompare << p;
		}
		cout << "nfa took " << (time(0) - tm) << " seconds to calulate for e6 times" << endl;
		tm = time(0);
		for (int i = 0; i < 1000000; ++i){
			fa << p;
		}
		cout << "dfa took " << (time(0) - tm) << " seconds to calulate for e6 times" << endl;
#endif
		return *this;
	}
};
int main(){
	Test("", Expect(true)), "";
	Test("", Expect(false)), "a";
	Test("a", Expect(true)), "a";
	Test("a", Expect(false)), "b", "abc", "";
	Test("ab", Expect(true)), "ab";
	Test("ab", Expect(false)), "", "a", "b", "c";
	Test("a|b", Expect(true)), "a", "b";
	Test("a|b", Expect(false)), "abc", "ab", "";
	Test("ab|c", Expect(true)), "ab", "c";
	Test("ab|c", Expect(false)), "a", "b", "abc";
	Test("ab|a", Expect(true)), "ab", "a";
	Test("ab|a", Expect(false)), "b", "c", "abc";
	Test("a|bc", Expect(true)), "a", "bc";
	Test("a|bc", Expect(false)), "ab", "c", "";
	Test("a*", Expect(true)), "", "a", "aaa";
	Test("a*", Expect(false)), "b", "ab", "ba";
	Test("ab*", Expect(true)), "a", "abb";
	Test("ab*", Expect(false)), "b", "bb", "bc", "abc", "";
	Test("a*b", Expect(true)), "b", "aaab", "ab";
	Test("a*b", Expect(false)), "aa", "ac", "";
	Test("a*ab", Expect(true)), "ab", "aab", "aaaab";
	Test("a*ab", Expect(false)), "a", "b", "c";
	Test("aa*b", Expect(true)), "ab", "aab", "aaaab";
	Test("aa*b", Expect(false)), "a", "b", "c";
	Test("a*|b", Expect(true)), "aaa", "b", "";
	Test("a*|b", Expect(false)), "abc", "ba", "cb", "ab";
	Test("a|b*", Expect(true)), "a", "bb", "";
	Test("a|b*", Expect(false)), "aa", "ab", "bc";
	Test("a|b|c", Expect(true)), "a", "b", "c";
	Test("a|b|c", Expect(false)), "ab", "d", "";
	Test("a|", Expect(true)), "a", "";
	Test("a|", Expect(false)), "b", "aa";
	Test("|a", Expect(true)), "a", "";
	Test("|a", Expect(false)), "b";
	Test("||", Expect(true)), "";
	Test("||", Expect(false)), "a";
	TestException("*"), "", "a", "b";
	TestException("|*"), "", "a", "b";
	TestException("**"), "", "a", "b";
	TestException("*|*"), "", "a", "b";
	TestException("*||*"), "", "a", "b";
	TestException("||*"), "", "a", "b";
#ifdef _DEBUG
#ifdef _MSC_VER
	_CrtCheckMemory();
	_CrtDumpMemoryLeaks();
#endif
	_getch();
#endif
	return 0;
}
<commit_msg>为处理器类型兼容增加预编译指令<commit_after>#include <iostream>
#include <string>
#include "YetAnotherRegularExpressionEngine.h"
#include <ctime>
#ifdef _DEBUG
#include <conio.h>
#endif
#if defined(_MSC_VER) && (_M_IX86 >= 500 || defined(_M_AMD64))
#include <intrin.h>
#pragma intrinsic(__rdtsc)
#endif
void expect(const char *expr, bool ex, bool ac){
	const char* e = ex ? "true" : "false";
	const char *a = ac ? "true" : "false";
	if (ex == ac){
		std::cout << "passed: " << expr << " = " << e << std::endl;
	}
	else{
		std::cout << "!!error: expect " << expr << " = " << e << ", get " << a << " instead." << std::endl;
	}
}
class TestException{
	FA2 fa;
	std::string re;
public:
	TestException(const char *re) :fa(re), re(re){}
	TestException& operator ,(const char *p){
		try{
			fa << p;
		}
		catch (FA1::SyntaxErrorException&){
			std::cout << "passed: expected exception received for RE /" << re << "/" << std::endl;
			return *this;
		}
		std::cout << "!!error: expected exception was not caught." << std::endl;
		return *this;
	}
};
class Expect{
	bool assert;
public:
	explicit Expect(bool b) :assert(b){}
	bool GetAssert(){ return assert; }
};
class Test{
	bool assert;
	FA1 faCompare;
	FA2 fa;
public:
	Test(const char *re, Expect e) :fa(re), faCompare(re), assert(e.GetAssert()){
		std::cout << "Testing RE /" << re << "/ :" << std::endl;
	}
	Test& operator ,(const char*p){
		using namespace std;
		if (*p == '\0'){
			expect("<Empty String>", assert, fa << p);
		}
		else{
			expect(p, assert, fa << p);
		}
#if defined(_MSC_VER) && (_M_IX86 >= 500 || defined(_M_AMD64))
		unsigned __int64 start;
		start = __rdtsc();
		for (int i = 0; i < 9999; ++i){
			faCompare << p;
		}
		unsigned __int64 time1 = __rdtsc() - start;
		cout << "nfa took " << time1 << " clock cycles to calulate for 9999 times" << endl;
		start = __rdtsc();
		for (int i = 0; i < 9999; ++i){
			fa << p;
		}
		unsigned __int64 time2 = __rdtsc() - start;
		cout << "dfa took " << time2 << " clock cycles to calulate for 9999 times" << endl;
		cout << "factor: " << time1 / time2 << endl;
#else
		time_t tm;
		tm = time(0);
		for (int i = 0; i < 1000000; ++i){
			faCompare << p;
		}
		cout << "nfa took " << (time(0) - tm) << " seconds to calulate for e6 times" << endl;
		tm = time(0);
		for (int i = 0; i < 1000000; ++i){
			fa << p;
		}
		cout << "dfa took " << (time(0) - tm) << " seconds to calulate for e6 times" << endl;
#endif
		return *this;
	}
};
int main(){
	Test("", Expect(true)), "";
	Test("", Expect(false)), "a";
	Test("a", Expect(true)), "a";
	Test("a", Expect(false)), "b", "abc", "";
	Test("ab", Expect(true)), "ab";
	Test("ab", Expect(false)), "", "a", "b", "c";
	Test("a|b", Expect(true)), "a", "b";
	Test("a|b", Expect(false)), "abc", "ab", "";
	Test("ab|c", Expect(true)), "ab", "c";
	Test("ab|c", Expect(false)), "a", "b", "abc";
	Test("ab|a", Expect(true)), "ab", "a";
	Test("ab|a", Expect(false)), "b", "c", "abc";
	Test("a|bc", Expect(true)), "a", "bc";
	Test("a|bc", Expect(false)), "ab", "c", "";
	Test("a*", Expect(true)), "", "a", "aaa";
	Test("a*", Expect(false)), "b", "ab", "ba";
	Test("ab*", Expect(true)), "a", "abb";
	Test("ab*", Expect(false)), "b", "bb", "bc", "abc", "";
	Test("a*b", Expect(true)), "b", "aaab", "ab";
	Test("a*b", Expect(false)), "aa", "ac", "";
	Test("a*ab", Expect(true)), "ab", "aab", "aaaab";
	Test("a*ab", Expect(false)), "a", "b", "c";
	Test("aa*b", Expect(true)), "ab", "aab", "aaaab";
	Test("aa*b", Expect(false)), "a", "b", "c";
	Test("a*|b", Expect(true)), "aaa", "b", "";
	Test("a*|b", Expect(false)), "abc", "ba", "cb", "ab";
	Test("a|b*", Expect(true)), "a", "bb", "";
	Test("a|b*", Expect(false)), "aa", "ab", "bc";
	Test("a|b|c", Expect(true)), "a", "b", "c";
	Test("a|b|c", Expect(false)), "ab", "d", "";
	Test("a|", Expect(true)), "a", "";
	Test("a|", Expect(false)), "b", "aa";
	Test("|a", Expect(true)), "a", "";
	Test("|a", Expect(false)), "b";
	Test("||", Expect(true)), "";
	Test("||", Expect(false)), "a";
	TestException("*"), "", "a", "b";
	TestException("|*"), "", "a", "b";
	TestException("**"), "", "a", "b";
	TestException("*|*"), "", "a", "b";
	TestException("*||*"), "", "a", "b";
	TestException("||*"), "", "a", "b";
#ifdef _DEBUG
#ifdef _MSC_VER
	_CrtCheckMemory();
	_CrtDumpMemoryLeaks();
#endif
	_getch();
#endif
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include "YetAnotherRegularExpressionEngine.h"
#ifdef _DEBUG
#include <conio.h>
#endif
#if defined(_MSC_VER) && (_M_IX86 >= 500 || defined(_M_AMD64))
#include <intrin.h>
#pragma intrinsic(__rdtsc)
#else
#include <limits>
#include <ctime>
#endif
void expect(const char *expr, bool ex, bool ac){
	const char* e = ex ? "true" : "false";
	const char *a = ac ? "true" : "false";
	if (ex == ac){
		std::cout << "passed: " << expr << " = " << e << std::endl;
	}
	else{
		std::cout << "!!error: expect " << expr << " = " << e << ", get " << a << " instead." << std::endl;
	}
}
class TestException{
	FA2 fa;
	std::string re;
public:
	TestException(const char *re) :fa(re), re(re){}
	TestException& operator ,(const char *p){
		using namespace std;
		try{
			fa << p;
		}
		catch (FA1::SyntaxErrorException&){
			cout << "passed:"
			" expected exception received for RE /" << re << "/" << endl;
			return *this;
		}
		cout << "!!error: expected exception was not caught." << endl;
		return *this;
	}
};
class Expect{
	bool assert;
public:
	explicit Expect(bool b) :assert(b){}
	bool GetAssert(){ return assert; }
};
class Test{
	bool assert;
	FA1 faCompare;
	FA2 fa;
public:
	Test(const char *re, Expect e)
 		:fa(re), faCompare(re), assert(e.GetAssert()){
		std::cout << "Testing RE /" << re << "/ :" << std::endl;
	}
	Test& operator ,(const char*p){
		using namespace std;
		if (*p == '\0'){
			expect("<Empty String>", assert, fa << p);
		}
		else{
			expect(p, assert, fa << p);
		}
#if defined(_MSC_VER) && (_M_IX86 >= 500 || defined(_M_AMD64))
		unsigned __int64 start;
		start = __rdtsc();
		for (int i = 0; i < 9999; ++i){
			faCompare << p;
		}
		unsigned __int64 time1 = __rdtsc() - start;
		cout << "nfa took " << time1
			<< " clock cycles to calulate for 9999 times" << endl;
		start = __rdtsc();
		for (int i = 0; i < 9999; ++i){
			fa << p;
		}
		unsigned __int64 time2 = __rdtsc() - start;
		cout << "dfa took " << time2 <<
		" clock cycles to calulate for 9999 times" << endl;
		cout << "factor: " << time1 / time2 << endl;
#else
		time_t tm;
		tm = time(0);
		for (int i = 0; i < 1000000; ++i){
			faCompare << p;
		}
		cout << "nfa took " << (time(0) - tm)
		<< " seconds to calulate for e6 times" << endl;
		tm = time(0);
		for (int i = 0; i < 1000000; ++i){
			fa << p;
		}
		cout << "dfa took " << (time(0) - tm) <<
		" seconds to calulate for e6 times" << endl;
#endif
		return *this;
	}
};
int main(){
	Test("", Expect(true)), "";
	Test("", Expect(false)), "a";
	Test("a", Expect(true)), "a";
	Test("a", Expect(false)), "b", "abc", "";
	Test("ab", Expect(true)), "ab";
	Test("ab", Expect(false)), "", "a", "b", "c";
	Test("a|b", Expect(true)), "a", "b";
	Test("a|b", Expect(false)), "abc", "ab", "";
	Test("ab|c", Expect(true)), "ab", "c";
	Test("ab|c", Expect(false)), "a", "b", "abc";
	Test("ab|a", Expect(true)), "ab", "a";
	Test("ab|a", Expect(false)), "b", "c", "abc";
	Test("a|bc", Expect(true)), "a", "bc";
	Test("a|bc", Expect(false)), "ab", "c", "";
	Test("a*", Expect(true)), "", "a", "aaa";
	Test("a*", Expect(false)), "b", "ab", "ba";
	Test("ab*", Expect(true)), "a", "abb";
	Test("ab*", Expect(false)), "b", "bb", "bc", "abc", "";
	Test("a*b", Expect(true)), "b", "aaab", "ab";
	Test("a*b", Expect(false)), "aa", "ac", "";
	Test("a*ab", Expect(true)), "ab", "aab", "aaaab";
	Test("a*ab", Expect(false)), "a", "b", "c";
	Test("aa*b", Expect(true)), "ab", "aab", "aaaab";
	Test("aa*b", Expect(false)), "a", "b", "c";
	Test("a*|b", Expect(true)), "aaa", "b", "";
	Test("a*|b", Expect(false)), "abc", "ba", "cb", "ab";
	Test("a|b*", Expect(true)), "a", "bb", "";
	Test("a|b*", Expect(false)), "aa", "ab", "bc";
	Test("a|b|c", Expect(true)), "a", "b", "c";
	Test("a|b|c", Expect(false)), "ab", "d", "";
	Test("a|", Expect(true)), "a", "";
	Test("a|", Expect(false)), "b", "aa";
	Test("|a", Expect(true)), "a", "";
	Test("|a", Expect(false)), "b";
	Test("||", Expect(true)), "";
	Test("||", Expect(false)), "a";
	TestException("*"), "", "a", "b";
	TestException("|*"), "", "a", "b";
	TestException("**"), "", "a", "b";
	TestException("*|*"), "", "a", "b";
	TestException("*||*"), "", "a", "b";
	TestException("||*"), "", "a", "b";
#ifdef _DEBUG
#ifdef _MSC_VER
	_CrtCheckMemory();
	_CrtDumpMemoryLeaks();
#endif
	_getch();
#endif
	return 0;
}
<commit_msg>调整预编译指令以适应接下来为*nix兼容性所要增加的修改<commit_after>#include <iostream>
#include <string>
#include "YetAnotherRegularExpressionEngine.h"
#ifdef _DEBUG
#include <conio.h>
#endif
#if defined(_MSC_VER) && (_M_IX86 >= 500 || defined(_M_AMD64))
#include <intrin.h>
#pragma intrinsic(__rdtsc)
#define rdtsc __rdtsc
typedef unsigned __int64 rdtsc_t;
#else
#include <limits>
#include <ctime>
#endif
void expect(const char *expr, bool ex, bool ac){
	const char* e = ex ? "true" : "false";
	const char *a = ac ? "true" : "false";
	if (ex == ac){
		std::cout << "passed: " << expr << " = " << e << std::endl;
	}
	else{
		std::cout << "!!error: expect " << expr << " = " << e << ", get " << a << " instead." << std::endl;
	}
}
class TestException{
	FA2 fa;
	std::string re;
public:
	TestException(const char *re) :fa(re), re(re){}
	TestException& operator ,(const char *p){
		using namespace std;
		try{
			fa << p;
		}
		catch (FA1::SyntaxErrorException&){
			cout << "passed:"
			" expected exception received for RE /" << re << "/" << endl;
			return *this;
		}
		cout << "!!error: expected exception was not caught." << endl;
		return *this;
	}
};
class Expect{
	bool assert;
public:
	explicit Expect(bool b) :assert(b){}
	bool GetAssert(){ return assert; }
};
class Test{
	bool assert;
	FA1 faCompare;
	FA2 fa;
public:
	Test(const char *re, Expect e)
 		:fa(re), faCompare(re), assert(e.GetAssert()){
		std::cout << "Testing RE /" << re << "/ :" << std::endl;
	}
	Test& operator ,(const char*p){
		using namespace std;
		if (*p == '\0'){
			expect("<Empty String>", assert, fa << p);
		}
		else{
			expect(p, assert, fa << p);
		}
#ifdef rdtsc
		unsigned __int64 start;
		start = rdtsc();
		for (int i = 0; i < 9999; ++i){
			faCompare << p;
		}
		rdtsc_t time1 = rdtsc() - start;
		cout << "nfa took " << time1
			<< " clock cycles to calulate for 9999 times" << endl;
		start = rdtsc();
		for (int i = 0; i < 9999; ++i){
			fa << p;
		}
		rdtsc_t time2 = rdtsc() - start;
		cout << "dfa took " << time2 <<
		" clock cycles to calulate for 9999 times" << endl;
		cout << "factor: " << time1 / time2 << endl;
#else
		time_t tm;
		tm = time(0);
		for (int i = 0; i < 1000000; ++i){
			faCompare << p;
		}
		cout << "nfa took " << (time(0) - tm)
		<< " seconds to calulate for e6 times" << endl;
		tm = time(0);
		for (int i = 0; i < 1000000; ++i){
			fa << p;
		}
		cout << "dfa took " << (time(0) - tm) <<
		" seconds to calulate for e6 times" << endl;
#endif
		return *this;
	}
};
int main(){
	Test("", Expect(true)), "";
	Test("", Expect(false)), "a";
	Test("a", Expect(true)), "a";
	Test("a", Expect(false)), "b", "abc", "";
	Test("ab", Expect(true)), "ab";
	Test("ab", Expect(false)), "", "a", "b", "c";
	Test("a|b", Expect(true)), "a", "b";
	Test("a|b", Expect(false)), "abc", "ab", "";
	Test("ab|c", Expect(true)), "ab", "c";
	Test("ab|c", Expect(false)), "a", "b", "abc";
	Test("ab|a", Expect(true)), "ab", "a";
	Test("ab|a", Expect(false)), "b", "c", "abc";
	Test("a|bc", Expect(true)), "a", "bc";
	Test("a|bc", Expect(false)), "ab", "c", "";
	Test("a*", Expect(true)), "", "a", "aaa";
	Test("a*", Expect(false)), "b", "ab", "ba";
	Test("ab*", Expect(true)), "a", "abb";
	Test("ab*", Expect(false)), "b", "bb", "bc", "abc", "";
	Test("a*b", Expect(true)), "b", "aaab", "ab";
	Test("a*b", Expect(false)), "aa", "ac", "";
	Test("a*ab", Expect(true)), "ab", "aab", "aaaab";
	Test("a*ab", Expect(false)), "a", "b", "c";
	Test("aa*b", Expect(true)), "ab", "aab", "aaaab";
	Test("aa*b", Expect(false)), "a", "b", "c";
	Test("a*|b", Expect(true)), "aaa", "b", "";
	Test("a*|b", Expect(false)), "abc", "ba", "cb", "ab";
	Test("a|b*", Expect(true)), "a", "bb", "";
	Test("a|b*", Expect(false)), "aa", "ab", "bc";
	Test("a|b|c", Expect(true)), "a", "b", "c";
	Test("a|b|c", Expect(false)), "ab", "d", "";
	Test("a|", Expect(true)), "a", "";
	Test("a|", Expect(false)), "b", "aa";
	Test("|a", Expect(true)), "a", "";
	Test("|a", Expect(false)), "b";
	Test("||", Expect(true)), "";
	Test("||", Expect(false)), "a";
	TestException("*"), "", "a", "b";
	TestException("|*"), "", "a", "b";
	TestException("**"), "", "a", "b";
	TestException("*|*"), "", "a", "b";
	TestException("*||*"), "", "a", "b";
	TestException("||*"), "", "a", "b";
#ifdef _DEBUG
#ifdef _MSC_VER
	_CrtCheckMemory();
	_CrtDumpMemoryLeaks();
#endif
	_getch();
#endif
	return 0;
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include <fstream>
#include <queue>
#include "omp.h"

struct Settings {
	Settings(): extract(),
				compress(),
   				verbose(),
				output() {}
	bool extract;
	bool compress;
	bool verbose;
	bool output;
	std::string name;
};

void helpCheck(int argc, char *argv[]) {
	if (argc == 1) {
		std::cout << "ERROR: ptxz was passed no parameters. \"ptxz -h\" for help." << std::endl;
		exit(0);
	}

	if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
		std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl;
		exit(0);
	}
}

void getSettings(int argc, char *argv[], Settings *instance) {
	std::queue<std::string> settings;
	for (int i = 1; i < argc; ++i) {
		settings.push(argv[i]);
	}

	while (!settings.empty()) {
		std::string arg = settings.front();

		if (arg == "-x") {
			if ((*instance).compress) {
				std::cout << "ERROR: ptxz cannot both compress and extract. \"ptxz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).extract = true;
		} else if (arg == "-c") {
			if ((*instance).extract) {
				std::cout << "ERROR: ptxz cannot both compress and extract. \"ptxz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).compress = true;
		} else if (arg == "-v"){
			(*instance).verbose = true;
		} else if (arg == "-o") {
			(*instance).output = true;
		} else {
			if (settings.size() > 1) {
				std::cout << "ERROR: ptxz was called incorrectly. \"ptxz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).output = true;
			(*instance).name = arg;
		}

		settings.pop();
	}

	if (!(*instance).output) {
		std::cout << "ERROR: No output file name given. \"ptxz -h\" for help." << std::endl;
		exit(0);
	}
}

void findAll(int *numFiles, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					findAll(numFiles, filePath.c_str());
				} else {
					*numFiles += 1;
				}
			}
		}
		closedir(dir);
	}
}

void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/");
				} else {
					filePaths->push_back(rootPath + fileBuff);
				}
			}
		}
		closedir(dir);
	}
}

void compression(std::vector<std::string> *filePaths, std::string name) {
	unsigned long long int filePathSize = filePaths->size();
	unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1;
	std::vector<std::string> *tarNames = new std::vector<std::string>(filePaths->size());

	#pragma omp parallel for schedule(dynamic)
	for (int i = 0; i < omp_get_max_threads() * 10; ++i) {
		unsigned long long int start = blockSize * i;
		if (start < filePathSize) {
			std::string xzCommand = "XZ_OPT=-1 tar cJf test." + std::to_string(i) + ".tar.xz";
			for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) {
				xzCommand += " " + filePaths->at(j);
			}
			system(xzCommand.c_str());

			tarNames->at(i) = name + "." + std::to_string(i) + ".tar.xz";
			std::cout << tarNames->at(i) + "\n";
		}
	}

	std::string tarCommand = "tar cf " + name + ".ptxz.tar";
	for (int i = 0; i < tarNames->size(); ++i) {
		tarCommand += " " + tarNames->at(i);
	}
	system(tarCommand.c_str());

	std::string rmCommand = "rm";
	for (int i = 0; i < tarNames->size(); ++i) {
		rmCommand += " " + tarNames->at(i);
	}
	system(rmCommand.c_str());

	tarNames->clear();
	delete(tarNames);
}

void extraction() {

}

char cwd [PATH_MAX];

int main(int argc, char *argv[]) {
	Settings *instance = new Settings;
	int *numFiles = new int(0);
	std::vector<std::string> *filePaths = new std::vector<std::string>();

	helpCheck(argc, argv);
	getSettings(argc, argv, instance);
	getcwd(cwd, PATH_MAX);
	findAll(numFiles, cwd);
	getPaths(filePaths, cwd, "");

	if ((*instance).compress) {
		compression(filePaths, (*instance).name);
	} else {
		extraction();
	}

	delete(instance);
	delete(numFiles);
	filePaths->clear();
	delete(filePaths);
	return 0;
}
<commit_msg>fixed tarball misnaming error<commit_after>#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include <fstream>
#include <queue>
#include "omp.h"

struct Settings {
	Settings(): extract(),
				compress(),
   				verbose(),
				output() {}
	bool extract;
	bool compress;
	bool verbose;
	bool output;
	std::string name;
};

void helpCheck(int argc, char *argv[]) {
	if (argc == 1) {
		std::cout << "ERROR: ptxz was passed no parameters. \"ptxz -h\" for help." << std::endl;
		exit(0);
	}

	if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
		std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl;
		exit(0);
	}
}

void getSettings(int argc, char *argv[], Settings *instance) {
	std::queue<std::string> settings;
	for (int i = 1; i < argc; ++i) {
		settings.push(argv[i]);
	}

	while (!settings.empty()) {
		std::string arg = settings.front();

		if (arg == "-x") {
			if ((*instance).compress) {
				std::cout << "ERROR: ptxz cannot both compress and extract. \"ptxz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).extract = true;
		} else if (arg == "-c") {
			if ((*instance).extract) {
				std::cout << "ERROR: ptxz cannot both compress and extract. \"ptxz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).compress = true;
		} else if (arg == "-v"){
			(*instance).verbose = true;
		} else if (arg == "-o") {
			(*instance).output = true;
		} else {
			if (settings.size() > 1) {
				std::cout << "ERROR: ptxz was called incorrectly. \"ptxz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).output = true;
			(*instance).name = arg;
		}

		settings.pop();
	}

	if (!(*instance).output) {
		std::cout << "ERROR: No output file name given. \"ptxz -h\" for help." << std::endl;
		exit(0);
	}
}

void findAll(int *numFiles, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					findAll(numFiles, filePath.c_str());
				} else {
					*numFiles += 1;
				}
			}
		}
		closedir(dir);
	}
}

void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/");
				} else {
					filePaths->push_back(rootPath + fileBuff);
				}
			}
		}
		closedir(dir);
	}
}

void compression(std::vector<std::string> *filePaths, std::string name) {
	unsigned long long int filePathSize = filePaths->size();
	unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1;
	std::vector<std::string> *tarNames = new std::vector<std::string>(filePaths->size());

	#pragma omp parallel for schedule(dynamic)
	for (int i = 0; i < omp_get_max_threads() * 10; ++i) {
		unsigned long long int start = blockSize * i;
		if (start < filePathSize) {
			std::string xzCommand = "XZ_OPT=-1 tar cJf " + name +"." + std::to_string(i) + ".tar.xz";
			for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) {
				xzCommand += " " + filePaths->at(j);
			}
			system(xzCommand.c_str());

			tarNames->at(i) = name + "." + std::to_string(i) + ".tar.xz";
			std::cout << tarNames->at(i) + "\n";
		}
	}

	std::string tarCommand = "tar cf " + name + ".ptxz.tar";
	for (int i = 0; i < tarNames->size(); ++i) {
		tarCommand += " " + tarNames->at(i);
	}
	system(tarCommand.c_str());

	std::string rmCommand = "rm";
	for (int i = 0; i < tarNames->size(); ++i) {
		rmCommand += " " + tarNames->at(i);
	}
	system(rmCommand.c_str());

	tarNames->clear();
	delete(tarNames);
}

void extraction() {

}

char cwd [PATH_MAX];

int main(int argc, char *argv[]) {
	Settings *instance = new Settings;
	int *numFiles = new int(0);
	std::vector<std::string> *filePaths = new std::vector<std::string>();

	helpCheck(argc, argv);
	getSettings(argc, argv, instance);
	getcwd(cwd, PATH_MAX);
	findAll(numFiles, cwd);
	getPaths(filePaths, cwd, "");

	if ((*instance).compress) {
		compression(filePaths, (*instance).name);
	} else {
		extraction();
	}

	delete(instance);
	delete(numFiles);
	filePaths->clear();
	delete(filePaths);
	return 0;
}
<|endoftext|>


<commit_before><commit_msg>Catch the exception thrown when trying to run against the latest SteamVR.<commit_after><|endoftext|>


<commit_before>#include <optional>
#include <string>
#include <tmxpp.hpp>
#include <tmxpp/impl/Xml.hpp>
#include <tmxpp/impl/exceptions.hpp>
#include <tmxpp/impl/read_utility.hpp>
#include <tmxpp/impl/tmx_info.hpp>
#include <tmxpp/impl/to_color.hpp>

namespace tmxpp {

namespace impl {
namespace {

using namespace tmx_info;

iSize read_isize(Xml::Element element)
{
    return iSize{from_string<iSize::Dimension>(value(element, size_width)),
                 from_string<iSize::Dimension>(value(element, size_height))};
}

pxSize read_tile_size(Xml::Element element)
{
    return pxSize{
        from_string<pxSize::Dimension>(value(element, tile_size_width)),
        from_string<pxSize::Dimension>(value(element, tile_size_height))};
}

namespace properties {

Property::Value read_value(Xml::Element property)
{
    auto value{optional_value(property, property_value)};

    if (!value)
        return std::string{get(property.value())};

    auto alternative{optional_value(property, property_alternative)};

    if (!alternative || *alternative == property_alternative_string)
        return std::string{get(*value)};
    if (*alternative == property_alternative_int)
        return from_string<int>(*value);
    if (*alternative == property_alternative_double)
        return from_string<double>(*value);
    if (*alternative == property_alternative_bool) {
        if (*value == property_value_true)
            return true;
        if (*value == property_value_false)
            return false;
        throw Exception{"Bad property bool value: " + std::string{get(*value)}};
    }
    if (*alternative == property_alternative_color)
        return to_color(*value);
    if (*alternative == property_alternative_file)
        return File{get(*value)};

    throw Invalid_attribute{property_alternative, *alternative};
}

std::string read_name(Xml::Element property)
{
    return std::string{get(value(property, property_name))};
}

Property read_property(Xml::Element property)
{
    return {read_name(property), read_value(property)};
}

Properties read_properties(Xml::Element element)
{
    auto properties{element.optional_child(tmx_info::properties)};

    if (!properties)
        return {};

    return transform<Properties>(properties->children(property), read_property);
}

} // namespace properties

using properties::read_properties;

namespace map {

std::string read_version(Xml::Element map)
{
    return std::string{get(value(map, map_version))};
}

Map::Staggered::Axis read_axis(Xml::Element map)
{
    auto axis{value(map, map_staggered_axis)};

    if (axis == map_staggered_axis_x)
        return Map::Staggered::Axis::x;
    if (axis == map_staggered_axis_y)
        return Map::Staggered::Axis::y;

    throw Invalid_attribute{map_staggered_axis, axis};
}

Map::Staggered::Index read_index(Xml::Element map)
{
    auto index{value(map, map_staggered_index)};

    if (index == map_staggered_index_even)
        return Map::Staggered::Index::even;
    if (index == map_staggered_index_odd)
        return Map::Staggered::Index::odd;

    throw Invalid_attribute{map_staggered_index, index};
}

Pixel read_side_length(Xml::Element map)
{
    return from_string<Pixel>(value(map, map_hexagonal_side_legth));
}

Map::Orientation read_orientation(Xml::Element map)
{
    auto orientation{value(map, map_orientation)};

    if (orientation == map_orthogonal)
        return Map::Orthogonal{};
    if (orientation == map_isometric)
        return Map::Isometric{};
    if (orientation == map_staggered)
        return Map::Staggered{read_axis(map), read_index(map)};
    if (orientation == map_hexagonal)
        return Map::Hexagonal{read_axis(map), read_index(map),
                              read_side_length(map)};

    throw Invalid_attribute{map_orientation, orientation};
}

Map::Render_order read_render_order(Xml::Element map)
{
    auto render_order{optional_value(map, map_render_order)};

    if (!render_order || *render_order == map_render_order_right_down)
        return Map::Render_order::right_down;
    if (*render_order == map_render_order_right_up)
        return Map::Render_order::right_up;
    if (*render_order == map_render_order_left_down)
        return Map::Render_order::left_down;
    if (*render_order == map_render_order_left_up)
        return Map::Render_order::left_up;

    throw Invalid_attribute{map_render_order, *render_order};
}

std::optional<Color> read_background(Xml::Element map)
{
    if (auto color{optional_value(map, map_background)})
        return to_color(*color);
    return {};
}

Unique_id read_next_unique_id(Xml::Element map)
{
    return from_string<Unique_id>(value(map, map_next_unique_id));
}

Map read_map(Xml::Element map)
{
    return {read_version(map),        read_orientation(map),
            read_render_order(map),   read_isize(map),
            read_tile_size(map),      read_background(map),
            read_next_unique_id(map), read_properties(map)};
}

} // namespace map

using map::read_map;

} // namespace
} // namespace impl

Map read_tmx(const std::string& path)
{
    const impl::Xml tmx{path};

    auto map{tmx.root()};

    if (map.name() == impl::tmx_info::map)
        return impl::read_map(map);

    throw impl::Invalid_element{map.name()};
}

Map::Tile_set read_tsx(const std::string& path);
Tile_set read_tile_set(const std::string& path);
Image_collection read_image_collection(const std::string& path);

} // namespace tmxpp
<commit_msg>Read Tile_set and Image_collection attributes<commit_after>#include <optional>
#include <string>
#include <tmxpp.hpp>
#include <tmxpp/impl/Xml.hpp>
#include <tmxpp/impl/exceptions.hpp>
#include <tmxpp/impl/read_utility.hpp>
#include <tmxpp/impl/tmx_info.hpp>
#include <tmxpp/impl/to_color.hpp>

namespace tmxpp {

namespace impl {
namespace {

using namespace tmx_info;

iSize read_isize(Xml::Element element)
{
    return iSize{from_string<iSize::Dimension>(value(element, size_width)),
                 from_string<iSize::Dimension>(value(element, size_height))};
}

pxSize read_tile_size(Xml::Element element)
{
    return pxSize{
        from_string<pxSize::Dimension>(value(element, tile_size_width)),
        from_string<pxSize::Dimension>(value(element, tile_size_height))};
}

namespace properties {

Property::Value read_value(Xml::Element property)
{
    auto value{optional_value(property, property_value)};

    if (!value)
        return std::string{get(property.value())};

    auto alternative{optional_value(property, property_alternative)};

    if (!alternative || *alternative == property_alternative_string)
        return std::string{get(*value)};
    if (*alternative == property_alternative_int)
        return from_string<int>(*value);
    if (*alternative == property_alternative_double)
        return from_string<double>(*value);
    if (*alternative == property_alternative_bool) {
        if (*value == property_value_true)
            return true;
        if (*value == property_value_false)
            return false;
        throw Exception{"Bad property bool value: " + std::string{get(*value)}};
    }
    if (*alternative == property_alternative_color)
        return to_color(*value);
    if (*alternative == property_alternative_file)
        return File{get(*value)};

    throw Invalid_attribute{property_alternative, *alternative};
}

std::string read_name(Xml::Element property)
{
    return std::string{get(value(property, property_name))};
}

Property read_property(Xml::Element property)
{
    return {read_name(property), read_value(property)};
}

Properties read_properties(Xml::Element element)
{
    auto properties{element.optional_child(tmx_info::properties)};

    if (!properties)
        return {};

    return transform<Properties>(properties->children(property), read_property);
}

} // namespace properties

using properties::read_properties;

namespace tile_set {

Tile_id read_first_global_id(Xml::Element tile_set)
{
    return from_string<Tile_id>(value(tile_set, tile_set_first_global_id));
}

File read_tsx(Xml::Element tile_set)
{
    if (auto tsx{optional_value(tile_set, tile_set_tsx)})
        return get(*tsx);
    return {};
}

std::string read_name(Xml::Element tile_set)
{
    if (auto name{optional_value(tile_set, tile_set_name)})
        return std::string{get(*name)};
    return {};
}

int read_tile_count(Xml::Element tile_set)
{
    return from_string<int>(value(tile_set, tile_set_tile_count));
}

int read_columns(Xml::Element tile_set)
{
    return from_string<int>(value(tile_set, tile_set_columns));
}

namespace tile_set {

Pixel read_spacing(Xml::Element tile_set)
{
    if (auto spacing{optional_value(tile_set, tile_set_spacing)})
        return from_string<Pixel>(*spacing);
    return {};
}

Pixel read_margin(Xml::Element tile_set)
{
    if (auto margin{optional_value(tile_set, tile_set_margin)})
        return from_string<Pixel>(*margin);
    return {};
}

iSize read_size(Xml::Element tile_set)
{
    auto tile_count{read_tile_count(tile_set)};
    auto columns{read_columns(tile_set)};

    if (columns == 0)
        throw Exception{"Invalid columns value: 0"};

    return {columns, tile_count / columns};
}

Tile_set read_tile_set(Xml::Element tile_set)
{
    return {read_first_global_id(tile_set),
            read_tsx(tile_set),
            read_name(tile_set),
            read_tile_size(tile_set),
            read_spacing(tile_set),
            read_margin(tile_set),
            read_size(tile_set)};
}

} // namespace tile_set

Image_collection read_image_collection(Xml::Element image_collection)
{
    return {read_first_global_id(image_collection),
            read_tsx(image_collection),
            read_name(image_collection),
            read_tile_size(image_collection),
            read_tile_count(image_collection),
            read_columns(image_collection)};
}

} // namespace tile_set

using tile_set::tile_set::read_tile_set;
using tile_set::read_image_collection;

namespace map {

std::string read_version(Xml::Element map)
{
    return std::string{get(value(map, map_version))};
}

Map::Staggered::Axis read_axis(Xml::Element map)
{
    auto axis{value(map, map_staggered_axis)};

    if (axis == map_staggered_axis_x)
        return Map::Staggered::Axis::x;
    if (axis == map_staggered_axis_y)
        return Map::Staggered::Axis::y;

    throw Invalid_attribute{map_staggered_axis, axis};
}

Map::Staggered::Index read_index(Xml::Element map)
{
    auto index{value(map, map_staggered_index)};

    if (index == map_staggered_index_even)
        return Map::Staggered::Index::even;
    if (index == map_staggered_index_odd)
        return Map::Staggered::Index::odd;

    throw Invalid_attribute{map_staggered_index, index};
}

Pixel read_side_length(Xml::Element map)
{
    return from_string<Pixel>(value(map, map_hexagonal_side_legth));
}

Map::Orientation read_orientation(Xml::Element map)
{
    auto orientation{value(map, map_orientation)};

    if (orientation == map_orthogonal)
        return Map::Orthogonal{};
    if (orientation == map_isometric)
        return Map::Isometric{};
    if (orientation == map_staggered)
        return Map::Staggered{read_axis(map), read_index(map)};
    if (orientation == map_hexagonal)
        return Map::Hexagonal{read_axis(map), read_index(map),
                              read_side_length(map)};

    throw Invalid_attribute{map_orientation, orientation};
}

Map::Render_order read_render_order(Xml::Element map)
{
    auto render_order{optional_value(map, map_render_order)};

    if (!render_order || *render_order == map_render_order_right_down)
        return Map::Render_order::right_down;
    if (*render_order == map_render_order_right_up)
        return Map::Render_order::right_up;
    if (*render_order == map_render_order_left_down)
        return Map::Render_order::left_down;
    if (*render_order == map_render_order_left_up)
        return Map::Render_order::left_up;

    throw Invalid_attribute{map_render_order, *render_order};
}

std::optional<Color> read_background(Xml::Element map)
{
    if (auto color{optional_value(map, map_background)})
        return to_color(*color);
    return {};
}

Unique_id read_next_unique_id(Xml::Element map)
{
    return from_string<Unique_id>(value(map, map_next_unique_id));
}

Map read_map(Xml::Element map)
{
    return {read_version(map),        read_orientation(map),
            read_render_order(map),   read_isize(map),
            read_tile_size(map),      read_background(map),
            read_next_unique_id(map), read_properties(map)};
}

} // namespace map

using map::read_map;

} // namespace
} // namespace impl

Map read_tmx(const std::string& path)
{
    const impl::Xml tmx{path};

    auto map{tmx.root()};

    if (map.name() == impl::tmx_info::map)
        return impl::read_map(map);

    throw impl::Invalid_element{map.name()};
}

Map::Tile_set read_tsx(const std::string& path);
Tile_set read_tile_set(const std::string& path);
Image_collection read_image_collection(const std::string& path);

} // namespace tmxpp
<|endoftext|>


<commit_before>#include "twister.h"

const unsigned CYCLE = 0x100;

const unsigned C_TRANS_ = 0xff;
int block_units[][0x10] = {
	0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65
  };
int triad_units[][0x03] = {
	0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73
};
const int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,
                               0xcf, 0xad, 0xdf, 0xff, 0xce,
                               0x32, 0x40, 0xd3, 0x27, 0x82,
                               0xda, 0xee, 0xff, 0xfc, 0xbf,
                               0x1c, 0x90, 0x13, 0x4a, 0xa5,
                               0xe0, 0x21, 0x9f, 0xe1, 0xc6,
                               0xe4, 0x38, 0x1f, 0x60, 0x24,
                               0x0c, 0x35, 0x51, 0x32, 0xcf,
                               0x12, 0x9a, 0x30, 0x44, 0x72,
                               0x04, 0x1c, 0x52, 0xca, 0xdf,
                               0xf2, 0xca, 0xa2, 0x51, 0xc6,
                               0xcb, 0xbd, 0xba, 0xac, 0xdf,
                               0xdf, 0xde, 0xcd, 0xfd, 0xca };

unsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)
{
	return (*s)(pos)^a;
}

void transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
  for(unsigned i = 0; i<data.size(); i++)
  {
    unsigned char d = data[i];
    for(unsigned j=0; j<CYCLE; j++)
    {
      d = (*f)(d)^base(d, g, d);
    }
    data[i] = d;
  }
}
void transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
  for(unsigned i = 0; i<data.size(); i++)
  {
    unsigned char d = data[i];
    for(unsigned j=0; j<CYCLE; j++)
    {
      d = (*f)(d)^(*g)(d);
    }
    data[i] = d;
  }
}

void trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char))
{
  for(unsigned i = 0; i<data.size(); i++)
  {
    unsigned char d = data[i];
    for(unsigned j=0; j<CYCLE; j++)
    {
      d = (*f)(d);
    }
    data[i] = d;
  }
}

vector<double> f_dist(vector<unsigned char>& in)
{
  vector<double> fdist;
  fdist.resize(256);
  for(unsigned i = 0; i<in.size(); i++)
  {
    fdist[in[i]]++;
  }

  for(unsigned i=0; i<fdist.size(); i++)
  {
    fdist[i] = (fdist[i] / in.size()) * 100;
  }

  return fdist;
}

double s_entropy(vector<double> v)
{
  double entropy = 0;
  double p;

  for(unsigned i = 0; i < v.size(); i++)
  {
    p = v[i] / 100;
    if (p == 0) continue;
    entropy += p * std::log(p) / std::log(2);
  }
  return -entropy;
}
void rms(const string& s, string& r)
{
  for(unsigned int i=0; i<s.size(); i++)
  {
    if(::isspace(s[i])) continue;
    r+= s[i];
  }
}

double sw(double weight, int i, int j, int (*inv)(int, int))
{
  return weight*(*inv)(i, j);
}
void hPerm(int s, int n, void (*p)(int), void (*inv)(int, int))
{
  if(s == 1)
  {
    (*p)(n);
    return;
  }
  for(int i=0; i< s; i++)
  {
    hPerm(s-1, n, p, inv);
    if(s%2 == 1)
      (*inv)(0, s-1);
    else
      (*inv)(i, s-1);
  }
}

double ic(const string& t)
{
  string text; rms(t, text);
  vector<double> freq(256,0);
  for(unsigned int i=0; i<text.size(); i++)
  {
    if(text[i] == ' ') continue;
    freq[text[i]] ++;
  }
  double sum=0;
  for(unsigned int i=0; i<freq.size(); i++)
  {
    if(freq[i] != 0)
    {
      double c = freq[i];
      if(c != 0)
        sum += c * (c - 1);
    }
  }
  double ic = 26 * sum / (text.size() * (text.size() - 1));
  return ic;
}
<commit_msg>util test, stream<commit_after>#include "twister.h"

const unsigned CYCLE = 0x100;

const unsigned C_TRANS_ = 0xff;
int block_units[][0x10] = {
	0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65
  };
int triad_units[][0x03] = {
	0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73
};
const int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,
                               0xcf, 0xad, 0xdf, 0xff, 0xce,
                               0x32, 0x40, 0xd3, 0x27, 0x82,
                               0xda, 0xee, 0xff, 0xfc, 0xbf,
                               0x1c, 0x90, 0x13, 0x4a, 0xa5,
                               0xe0, 0x21, 0x9f, 0xe1, 0xc6,
                               0xe4, 0x38, 0x1f, 0x60, 0x24,
                               0x0c, 0x35, 0x51, 0x32, 0xcf,
                               0x12, 0x9a, 0x30, 0x44, 0x72,
                               0x04, 0x1c, 0x52, 0xca, 0xdf,
                               0x12, 0x0b, 0x30, 0xa0, 0x1e,
                               0xf2, 0xca, 0xa2, 0x51, 0xc6,
                               0xcb, 0xbd, 0xba, 0xac, 0xdf,
                               0xdf, 0xde, 0xcd, 0xfd, 0xca };

unsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)
{
	return (*s)(pos)^a;
}

void transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
  for(unsigned i = 0; i<data.size(); i++)
  {
    unsigned char d = data[i];
    for(unsigned j=0; j<CYCLE; j++)
    {
      d = (*f)(d)^base(d, g, d);
    }
    data[i] = d;
  }
}
void transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
  for(unsigned i = 0; i<data.size(); i++)
  {
    unsigned char d = data[i];
    for(unsigned j=0; j<CYCLE; j++)
    {
      d = (*f)(d)^(*g)(d);
    }
    data[i] = d;
  }
}

void trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char))
{
  for(unsigned i = 0; i<data.size(); i++)
  {
    unsigned char d = data[i];
    for(unsigned j=0; j<CYCLE; j++)
    {
      d = (*f)(d);
    }
    data[i] = d;
  }
}

vector<double> f_dist(vector<unsigned char>& in)
{
  vector<double> fdist;
  fdist.resize(256);
  for(unsigned i = 0; i<in.size(); i++)
  {
    fdist[in[i]]++;
  }

  for(unsigned i=0; i<fdist.size(); i++)
  {
    fdist[i] = (fdist[i] / in.size()) * 100;
  }

  return fdist;
}

double s_entropy(vector<double> v)
{
  double entropy = 0;
  double p;

  for(unsigned i = 0; i < v.size(); i++)
  {
    p = v[i] / 100;
    if (p == 0) continue;
    entropy += p * std::log(p) / std::log(2);
  }
  return -entropy;
}
void rms(const string& s, string& r)
{
  for(unsigned int i=0; i<s.size(); i++)
  {
    if(::isspace(s[i])) continue;
    r+= s[i];
  }
}

double sw(double weight, int i, int j, int (*inv)(int, int))
{
  return weight*(*inv)(i, j);
}
void hPerm(int s, int n, void (*p)(int), void (*inv)(int, int))
{
  if(s == 1)
  {
    (*p)(n);
    return;
  }
  for(int i=0; i< s; i++)
  {
    hPerm(s-1, n, p, inv);
    if(s%2 == 1)
      (*inv)(0, s-1);
    else
      (*inv)(i, s-1);
  }
}

double ic(const string& t)
{
  string text; rms(t, text);
  vector<double> freq(256,0);
  for(unsigned int i=0; i<text.size(); i++)
  {
    if(text[i] == ' ') continue;
    freq[text[i]] ++;
  }
  double sum=0;
  for(unsigned int i=0; i<freq.size(); i++)
  {
    if(freq[i] != 0)
    {
      double c = freq[i];
      if(c != 0)
        sum += c * (c - 1);
    }
  }
  double ic = 26 * sum / (text.size() * (text.size() - 1));
  return ic;
}
<|endoftext|>


<commit_before>#include "GS.h"

#include "value_editors/Value_Editor_Factory.h"
#include "utils/Clock.h"

#include <QInputDialog>
#include <QMessageBox>

static GL_Widget* s_gl_widget = nullptr;

void bind_context()
{
    s_gl_widget->makeCurrent();
}

GS::GS(QWidget *parent)
    : QMainWindow(parent)
//    , m_hal(m_comms)
    , m_ts()
    , m_comms(m_ts)
{
    QGLFormat format(QGL::DepthBuffer | QGL::Rgba | QGL::NoStencilBuffer | QGL::SingleBuffer);
    format.setSwapInterval(0);
    QGLFormat::setDefaultFormat(format);

    m_editor_factory = std::make_shared<Value_Editor_Factory>();
    m_editor_factory->register_standard_editors();

    m_ui.setupUi(this);

    s_gl_widget = m_ui.gl_widget;
    bind_context();

    QObject::connect(m_ui.tabWidget, &QTabWidget::currentChanged, [this](int index)
    {
        for (int i = 0; i < m_ui.tabWidget->count(); i++)
        {
            if (ITab_Widget* t = dynamic_cast<ITab_Widget*>(m_ui.tabWidget->widget(i)))
            {
                t->set_active(false);
            }
        }
        if (ITab_Widget* t = dynamic_cast<ITab_Widget*>(m_ui.tabWidget->widget(index)))
        {
            t->set_active(true);
        }
    });

    m_ui.uav_descriptor_widget->init(m_ui.toolbar, m_comms, *m_ui.properties_browser);
    m_ui.nodes_widget->init(m_ui.toolbar, m_comms, *m_ui.properties_browser);
    m_ui.properties_browser->init(m_editor_factory);

    m_process_last_tp = Clock::now();

    auto* timer = new QTimer(this);
    timer->setSingleShot(false);
    timer->start(1);
    connect(timer, &QTimer::timeout, this, &GS::process, Qt::QueuedConnection);

    show();

    {
        QSettings settings;
        set_remote_address(settings.value("address", "").toString().toLatin1().data());
    }

    QObject::connect(m_ui.action_connect, &QAction::triggered, [this] (bool triggered)
    {
        bool ok;
        QString text = QInputDialog::getText(this, "Enter UAV IP", "IP", QLineEdit::Normal, m_remote_address.c_str(), &ok);
        if (ok)
        {
            set_remote_address(text.toLatin1().data());
        }
    });

    m_comms.sig_type_system_reset.connect([this]()
    {
       m_ui.uav_descriptor_widget->refresh();
       m_ui.nodes_widget->refresh();
    });

    //set_remote_address("10.10.10.10");
    //set_remote_address("127.0.0.1");

    read_settings();
}

GS::~GS()
{
//    m_comms.disconnect();
}

void GS::closeEvent(QCloseEvent* event)
{
    QSettings settings;
    settings.setValue("geometry", saveGeometry());
    settings.setValue("windowState", saveState());
//    settings.setValue("hal_window/geometry", m_hal_window->saveGeometry());
//    settings.setValue("hal_window/windowState", m_hal_window->saveState());
//    settings.setValue("multi_config_window/geometry", m_multi_config_window->saveGeometry());
//    settings.setValue("multi_config_window/windowState", m_multi_config_window->saveState());
//    settings.setValue("sim_window/geometry", m_sim_window->saveGeometry());
//    settings.setValue("sim_window/windowState", m_sim_window->saveState());

    QMainWindow::closeEvent(event);
}

void GS::read_settings()
{
    QSettings settings;
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("windowState").toByteArray());
//    m_hal_window->restoreGeometry(settings.value("hal_window/geometry").toByteArray());
//    m_hal_window->restoreState(settings.value("hal_window/windowState").toByteArray());
//    m_multi_config_window->restoreGeometry(settings.value("multi_config_window/geometry").toByteArray());
//    m_multi_config_window->restoreState(settings.value("multi_config_window/windowState").toByteArray());
//    m_sim_window->restoreGeometry(settings.value("sim_window/geometry").toByteArray());
//    m_sim_window->restoreState(settings.value("sim_window/windowState").toByteArray());
}

void GS::set_remote_address(std::string const& address)
{
    if (address.empty())
    {
        m_remote_address = address;
    }
    else
    {
        try
        {
            boost::asio::ip::address ip_address = boost::asio::ip::address::from_string(address);
            m_comms.start_udp(ip_address, 8006, 8005);

            m_remote_address = address;
            QSettings settings;
            settings.setValue("address", address.c_str());
        }
        catch(std::exception const& e)
        {
            QMessageBox::critical(this, "Error", ("Address '" + m_remote_address + "' is invalid: " + e.what()).c_str());
        }
    }
}

void GS::process()
{
    if (m_comms.is_connected())
    {
        m_ui.statusbar->showMessage(("Connected to " + m_remote_address).c_str());
    }
    else
    {
        m_ui.statusbar->showMessage("");
    }
//    if (!m_comms.is_connected() && !m_remote_address.empty())
//    {
//        m_comms.start_udp(boost::asio::ip::address::from_string(m_remote_address), 8001, 8000);
//        //m_comms.start_rfmon("wlp0s20u1u4", 3);
//    }

    bind_context();

    m_comms.process_rcp();

    auto now = Clock::now();
    auto dt = now - m_process_last_tp;
    if (dt >= std::chrono::milliseconds(33))
    {
        m_process_last_tp = now;

        q::System::inst().get_renderer()->begin_frame();

        m_comms.process();
        m_ui.nodes_widget->process();

        q::System::inst().get_renderer()->end_frame();
    }
}

<commit_msg>Fixed crash<commit_after>#include "GS.h"

#include "value_editors/Value_Editor_Factory.h"
#include "utils/Clock.h"

#include <QInputDialog>
#include <QMessageBox>

static GL_Widget* s_gl_widget = nullptr;

void bind_context()
{
    s_gl_widget->makeCurrent();
}

GS::GS(QWidget *parent)
    : QMainWindow(parent)
//    , m_hal(m_comms)
    , m_ts()
    , m_comms(m_ts)
{
    QGLFormat format(QGL::DepthBuffer | QGL::Rgba | QGL::NoStencilBuffer | QGL::SingleBuffer);
    format.setSwapInterval(0);
    QGLFormat::setDefaultFormat(format);

    m_editor_factory = std::make_shared<Value_Editor_Factory>();
    m_editor_factory->register_standard_editors();

    m_ui.setupUi(this);

    s_gl_widget = m_ui.gl_widget;
    bind_context();

    QObject::connect(m_ui.tabWidget, &QTabWidget::currentChanged, [this](int index)
    {
        for (int i = 0; i < m_ui.tabWidget->count(); i++)
        {
            if (ITab_Widget* t = dynamic_cast<ITab_Widget*>(m_ui.tabWidget->widget(i)))
            {
                t->set_active(false);
            }
        }
        if (ITab_Widget* t = dynamic_cast<ITab_Widget*>(m_ui.tabWidget->widget(index)))
        {
            t->set_active(true);
        }
    });

    m_ui.uav_descriptor_widget->init(m_ui.toolbar, m_comms, *m_ui.properties_browser);
    m_ui.nodes_widget->init(m_ui.toolbar, m_comms, *m_ui.properties_browser);
    m_ui.properties_browser->init(m_editor_factory);

    m_process_last_tp = Clock::now();

    auto* timer = new QTimer(this);
    timer->setSingleShot(false);
    timer->start(1);
    connect(timer, &QTimer::timeout, this, &GS::process, Qt::QueuedConnection);

    show();

    {
        QSettings settings;
        set_remote_address(settings.value("address", "").toString().toLatin1().data());
    }

    QObject::connect(m_ui.action_connect, &QAction::triggered, [this] (bool triggered)
    {
        bool ok;
        QString text = QInputDialog::getText(this, "Enter UAV IP", "IP", QLineEdit::Normal, m_remote_address.c_str(), &ok);
        if (ok)
        {
            set_remote_address(text.toLatin1().data());
        }
    });

    m_comms.sig_type_system_reset.connect([this]()
    {
       m_ui.uav_descriptor_widget->refresh();
       m_ui.nodes_widget->refresh();
    });

    //set_remote_address("10.10.10.10");
    //set_remote_address("127.0.0.1");

    read_settings();
}

GS::~GS()
{
//    m_comms.disconnect();
}

void GS::closeEvent(QCloseEvent* event)
{
    QSettings settings;
    settings.setValue("geometry", saveGeometry());
    settings.setValue("windowState", saveState());
//    settings.setValue("hal_window/geometry", m_hal_window->saveGeometry());
//    settings.setValue("hal_window/windowState", m_hal_window->saveState());
//    settings.setValue("multi_config_window/geometry", m_multi_config_window->saveGeometry());
//    settings.setValue("multi_config_window/windowState", m_multi_config_window->saveState());
//    settings.setValue("sim_window/geometry", m_sim_window->saveGeometry());
//    settings.setValue("sim_window/windowState", m_sim_window->saveState());

    QMainWindow::closeEvent(event);
}

void GS::read_settings()
{
    QSettings settings;
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("windowState").toByteArray());
//    m_hal_window->restoreGeometry(settings.value("hal_window/geometry").toByteArray());
//    m_hal_window->restoreState(settings.value("hal_window/windowState").toByteArray());
//    m_multi_config_window->restoreGeometry(settings.value("multi_config_window/geometry").toByteArray());
//    m_multi_config_window->restoreState(settings.value("multi_config_window/windowState").toByteArray());
//    m_sim_window->restoreGeometry(settings.value("sim_window/geometry").toByteArray());
//    m_sim_window->restoreState(settings.value("sim_window/windowState").toByteArray());
}

void GS::set_remote_address(std::string const& address)
{
    if (address.empty())
    {
        m_remote_address = address;
    }
    else
    {
        try
        {
            boost::asio::ip::address ip_address = boost::asio::ip::address::from_string(address);
            m_comms.start_udp(ip_address, 8006, 8005);

            m_remote_address = address;
            QSettings settings;
            settings.setValue("address", address.c_str());
        }
        catch(std::exception const& e)
        {
            QMessageBox::critical(this, "Error", ("Address '" + m_remote_address + "' is invalid: " + e.what()).c_str());
        }
    }
}

void GS::process()
{
    if (m_comms.is_connected())
    {
        m_ui.statusbar->showMessage(("Connected to " + m_remote_address).c_str());
    }
    else
    {
        m_ui.statusbar->showMessage("");
    }
//    if (!m_comms.is_connected() && !m_remote_address.empty())
//    {
//        m_comms.start_udp(boost::asio::ip::address::from_string(m_remote_address), 8001, 8000);
//        //m_comms.start_rfmon("wlp0s20u1u4", 3);
//    }

    bind_context();

    m_comms.process_rcp();

    auto now = Clock::now();
    auto dt = now - m_process_last_tp;
    if (dt >= std::chrono::milliseconds(33))
    {
        m_process_last_tp = now;

        if (q::System::has_inst())
        {
            q::System::inst().get_renderer()->begin_frame();
        }

        m_comms.process();
        m_ui.nodes_widget->process();

        if (q::System::has_inst())
        {
            q::System::inst().get_renderer()->end_frame();
        }
    }
}

<|endoftext|>


<commit_before>#pragma once

#include <cassert>
#include <type_traits>

namespace euler::numbers {

/**
 * Return true if x is a palindromic number.
 */
template<typename Int>
constexpr bool is_palindrome(Int x) {
    static_assert(std::is_integral<Int>::value, "Integral required.");

    Int t = x, m = 0;
    do {
        m = m * 10 + t % 10;
    } while (t /= 10);

    return x == m;
}

}
<commit_msg>Add digit sum function to eulertools.<commit_after>#pragma once

#include <cassert>
#include <type_traits>

namespace euler::numbers {

/**
 * Return true if x is a palindromic number.
 */
template<typename Int>
constexpr bool is_palindrome(Int x) {
    static_assert(std::is_integral<Int>::value, "Integral required.");

    Int t = x, m = 0;
    do {
        m = m * 10 + t % 10;
    } while (t /= 10);

    return x == m;
}

/**
 * Return the digit sum of a base-10 number.
 */
template<typename Int>
constexpr bool digit_sum(Int x) {
    static_assert(std::is_integral<Int>::value, "Integral required.");

    Int s = 0;
    do {
        s += x % 10;
    } while (x /= 10);

    return s;
}
}
<|endoftext|>


<commit_before>#include "Line.hpp"

Line::Line():m_baseline(0){

}

void Line::setBaseline(int y)
{
	for(std::vector<ConnectedComponent>::iterator it = m_ListCC.begin(); it != m_ListCC.end(); ++it)
		if(it->getBaseline() == m_baseline)
    	it->setBaseline(y);
  m_baseline = y;
}

int Line::getBaseline() const
{
  return m_baseline;
}

void Line::addCC(const ConnectedComponent &cc)
{
  m_ListCC.push_back(cc);
}

std::vector<ConnectedComponent> Line::getListCC() const
{
  return m_ListCC;
}

ConnectedComponent Line::getConnectedComponentAtIndex(int index) const{
	return m_ListCC.at(index);
}

void Line::setBoundingBoxAtIndex(int index, int up, int down, int left, int right){
	m_ListCC[index].setBoundingBox(up, down, left, right);
}

void Line::computeBaseLine(){
	sort(m_ListCC.begin(), m_ListCC.end(), [](ConnectedComponent &c1, ConnectedComponent &c2){
        return cv::boundingRect(c1.getListPoint()).x < cv::boundingRect(c2.getListPoint()).x;
    });

  int median = (int)m_ListCC.size()/2;
  cv::Rect bb = cv::boundingRect(m_ListCC[median].getListPoint());
  setBaseline(bb.y + bb.height);
	for(int unsigned i=0;i<m_ListCC.size();i++)
	{
		m_ListCC[i].setBaseline(bb.y + bb.height);
	}
}

void Line::setBaselineAtIndex(int index, int value)
{
	m_ListCC[index].setBaseline(value);
}
<commit_msg>bug fix<commit_after>#include "Line.hpp"

Line::Line():m_baseline(0){

}

void Line::setBaseline(int y)
{
	for(std::vector<ConnectedComponent>::iterator it = m_ListCC.begin(); it != m_ListCC.end(); ++it)
		if(it->getBaseline() == m_baseline)
    	it->setBaseline(y);
  m_baseline = y;
}

int Line::getBaseline() const
{
  return m_baseline;
}

void Line::addCC(const ConnectedComponent &cc)
{
  m_ListCC.push_back(cc);
}

std::vector<ConnectedComponent> Line::getListCC() const
{
  return m_ListCC;
}

ConnectedComponent Line::getConnectedComponentAtIndex(int index) const{
	return m_ListCC.at(index);
}

void Line::setBoundingBoxAtIndex(int index, int up, int down, int left, int right){
	m_ListCC[index].setBoundingBox(up, down, left, right);
}

void Line::computeBaseLine(){
	sort(m_ListCC.begin(), m_ListCC.end(), [](const ConnectedComponent c1, const ConnectedComponent c2){
        return cv::boundingRect(c1.getListPoint()).x < cv::boundingRect(c2.getListPoint()).x;
    });

  int median = (int)m_ListCC.size()/2;
  cv::Rect bb = cv::boundingRect(m_ListCC[median].getListPoint());
  setBaseline(bb.y + bb.height);
	for(int unsigned i=0;i<m_ListCC.size();i++)
	{
		m_ListCC[i].setBaseline(bb.y + bb.height);
	}
}

void Line::setBaselineAtIndex(int index, int value)
{
	m_ListCC[index].setBaseline(value);
}
<|endoftext|>