<commit_before>#include <string>
#include <iostream>
#include <sstream>
#include "toyfs.hpp"

#define PRMPT "sh> "

int test_fs(const std::string filename) {
    ToyFS(filename, 100000, 1024);
    return 0;
}

void repl(const std::string filename) {
    using namespace std;

    ToyFS(filename, 100000, 1024);

    string cmd;
    vector<string> args;
    string token;

    cout << PRMPT;
    while(getline(cin, cmd)) {
        args.clear();
        istringstream iss(cmd);
        while (iss >> token) { args.push_back(token); }
        if(args.size() == 0) {
            cout << PRMPT;
            continue;
        }

        if(args[0] == "mkfs") {
        } else if(args[0] == "open") {
        } else if(args[0] == "read") {
        } else if(args[0] == "write") {
        } else if(args[0] == "seek") {
        } else if(args[0] == "close") {
        } else if(args[0] == "mkdir") {
        } else if(args[0] == "rmdir") {
        } else if(args[0] == "cd") {
        } else if(args[0] == "link") {
        } else if(args[0] == "unlink") {
        } else if(args[0] == "stat") {
        } else if(args[0] == "ls") {
        } else if(args[0] == "cat") {
        } else if(args[0] == "cp") {
        } else if(args[0] == "tree") {
        } else if(args[0] == "import") {
        } else if(args[0] == "export") {
        } else {
            std::cout << "unknown command: " << args[0] << std::endl;
        }
        cout << PRMPT;
    }

}

int main(int argc, char **argv) {
    if(argc != 2) {
        std::cerr << "usage: " << argv[0] << " filename" << std::endl;
        return 1;
    }

#ifdef DEBUG
    test_fs(std::string(argv[1]));
#else
    repl(std::string(argv[1]));
#endif
    return 0;
}

<commit_msg>implemented mkfs and added an exit command<commit_after>#include <string>
#include <iostream>
#include <sstream>
#include "toyfs.hpp"

#define PRMPT "sh> "
#define DISKSIZE 102400
#define BLOCKSIZE 1024

int test_fs(const std::string filename) {
    ToyFS(filename, DISKSIZE, BLOCKSIZE);
    return 0;
}

void repl(const std::string filename) {
    using namespace std;

    ToyFS *fs = new ToyFS(filename, DISKSIZE, BLOCKSIZE);

    string cmd;
    vector<string> args;
    string token;

    cout << PRMPT;
    while(getline(cin, cmd)) {
        args.clear();
        istringstream iss(cmd);
        while (iss >> token) { args.push_back(token); }
        if(args.size() == 0) {
            cout << PRMPT;
            continue;
        }

        if(args[0] == "mkfs") {
            delete(fs);
            fs = new ToyFS(filename, DISKSIZE, BLOCKSIZE);
        } else if(args[0] == "open") {
        } else if(args[0] == "read") {
        } else if(args[0] == "write") {
        } else if(args[0] == "seek") {
        } else if(args[0] == "close") {
        } else if(args[0] == "mkdir") {
        } else if(args[0] == "rmdir") {
        } else if(args[0] == "cd") {
        } else if(args[0] == "link") {
        } else if(args[0] == "unlink") {
        } else if(args[0] == "stat") {
        } else if(args[0] == "ls") {
        } else if(args[0] == "cat") {
        } else if(args[0] == "cp") {
        } else if(args[0] == "tree") {
        } else if(args[0] == "import") {
        } else if(args[0] == "export") {
        } else if(args[0] == "exit") {
            break;
        } else {
            std::cout << "unknown command: " << args[0] << std::endl;
        }
        cout << PRMPT;
    }

    delete(fs);
    return;
}

int main(int argc, char **argv) {
    if(argc != 2) {
        std::cerr << "usage: " << argv[0] << " filename" << std::endl;
        return 1;
    }

#ifdef DEBUG
    test_fs(std::string(argv[1]));
#else
    repl(std::string(argv[1]));
#endif
    return 0;
}

<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   main.cpp
 * Author: aybar
 *
 * Created on September 14, 2017, 4:59 PM
 */

#include <iostream>
#include <map>  // Para coleccionar menu.
#include <fstream> // Para archivo punto.txt.
#include <string>
#include <cctype> // toupper();
#include "Punto.h"
//-------------------------
using std::cout;
using std::cin;
using std::endl;
using std::toupper;
using std::string;
//-------------------------

enum class Menu {
    AGREGAR = 1, ELIMINAR, BUSCAR, SALIR = 0
};
// ------------------------
unsigned short mostrarMenu();
bool haSalido();
void agregarPunto(Punto&);
void eliminarPunto(Punto&);
void buscarPunto(Punto&);
//------------------------

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

    // Opciones a comparar con switch case;
    std::map<unsigned short, Menu> opciones;
    opciones[1] = Menu::AGREGAR;
    opciones[2] = Menu::ELIMINAR;
    opciones[3] = Menu::BUSCAR;
    opciones[0] = Menu::SALIR;
    unsigned short opcion;
    // ---------------------------------------

    Punto punto;

    bool haTerminado = false;
    while (!haTerminado) {
        try {
            opcion = mostrarMenu();

            switch (opciones[opcion]) {
                case Menu::AGREGAR:
                    agregarPunto(punto);
                    break;
                case Menu::ELIMINAR:
                    eliminarPunto(punto);
                    break;
                case Menu::BUSCAR:
                    buscarPunto(punto);
                    break;
                default:
                    haTerminado = haSalido();
            }
        } catch (string e) {
            cout << e;
        }

        cout << "\n\n";
        cout << "Presione ENTER para continuar...";
        cin.ignore();
        cin.get();
        cout << "\n\n";
    }

    return 0;
}

unsigned short mostrarMenu() {
    unsigned short opcion;
    const unsigned short SALIR = 0;
    const unsigned short ULTIMA = 4;
    bool esValida = false;
    while (!esValida) {
        cout << "\t\tElija la opcion que desea dentro del plano: \n";
        cout << "1. Agregar un punto.\n";
        cout << "2. Eliminar un punto.\n";
        cout << "3. Buscar un punto.\n";
        cout << "0. Salir.\n\n";
        cin >> opcion;

        esValida = opcion >= SALIR && opcion <= ULTIMA;
        cout << "\n\n";
    }

    return opcion;
}

bool haSalido() {
    char salir;
    bool esValida = false; // Valida entrada por teclado del siguiente mensaje.
    while (!esValida) {
        cout << "Desea salir del programa?[S/N]: ";
        cin >> salir;

        salir = toupper(salir); // Convierte a mayuscula la opcion.
        esValida = salir == 'S' || salir == 'N'; // Condicion de entrada por teclado.
    }

    return (salir == 'S');

}

void agregarPunto(Punto& punto) {
    int x, y;
    cout << "Ingrese valor de eje x: ";
    cin >> x;

    cout << "Ingrese valor de eje y: ";
    cin >> y;

    if (punto.alta(x, y)) {
        cout << "El punto P(" << x << ", " << y << ") ha sido agregado correctamente." << endl;
    } else {
        throw "El punto P (" + std::to_string(x) + ", " + std::to_string(y) + ")"
                "no fue agregado correctamente. Intente de nuevo. ";
    }

}

void eliminarPunto(Punto& punto) {
    int pos;
    cout << "Ingrese la posicion del elemento que desea eliminar: ";
    cin >> pos;

    int x = punto.buscar(pos).getAbscisa();
    int y = punto.buscar(pos).getOrdenada();

    punto.baja(pos);
    cout << "El punto P(" << x << ", " << y << ") del vector ha sido eliminado";

}

void buscarPunto(Punto& punto) {
    unsigned i;
    cout << "Ingrese indice de elemento a buscar [0-n]: ";
    cin >> i;

    const Punto p = punto.buscar(i);

    string x = std::to_string(p.getAbscisa());
    string y = std::to_string(p.getOrdenada());
    cout << "El punto #" << i << "  del vector corresponde al punto P(" + x + ", " + y + ")\n";

}
<commit_msg>fix: Entrada invalida por menu.<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   main.cpp
 * Author: aybar
 *
 * Created on September 14, 2017, 4:59 PM
 */

#include <iostream>
#include <map>  // Para coleccionar menu.
#include <fstream> // Para archivo punto.txt.
#include <string>
#include <cctype>
#include <limits> // toupper();
#include "Punto.h"
//-------------------------
using std::cout;
using std::cin;
using std::endl;
using std::toupper;
using std::string;
// Valida entrada por teclado.
using std::streamsize;
//-------------------------

enum class Menu {
    AGREGAR = 1, ELIMINAR, BUSCAR, SALIR = 0
};
// ------------------------
unsigned short mostrarMenu();
bool haSalido();
void agregarPunto(Punto&);
void eliminarPunto(Punto&);
void buscarPunto(Punto&);
//------------------------

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

    // Opciones a comparar con switch case;
    std::map<unsigned short, Menu> opciones;
    opciones[1] = Menu::AGREGAR;
    opciones[2] = Menu::ELIMINAR;
    opciones[3] = Menu::BUSCAR;
    opciones[0] = Menu::SALIR;
    unsigned short opcion;
    // ---------------------------------------

    Punto punto;

    bool haTerminado = false;
    while (!haTerminado) {
        try {
            opcion = mostrarMenu();

            switch (opciones[opcion]) {
                case Menu::AGREGAR:
                    agregarPunto(punto);
                    break;
                case Menu::ELIMINAR:
                    eliminarPunto(punto);
                    break;
                case Menu::BUSCAR:
                    buscarPunto(punto);
                    break;
                default:
                    haTerminado = haSalido();
            }
        } catch (string e) {
            cout << e;
        }

        cout << "\n\n";
        cout << "Presione ENTER para continuar...";
        cin.ignore();
        cin.get();
        cout << "\n\n";
    }

    return 0;
}

unsigned short mostrarMenu() {
    unsigned short opcion;
    const unsigned short SALIR = 0;
    const unsigned short ULTIMA = 4;
    bool esValida = false;
    while (!esValida) {
        cout << "\t\tElija la opcion que desea dentro del plano: \n";
        cout << "1. Agregar un punto.\n";
        cout << "2. Eliminar un punto.\n";
        cout << "3. Buscar un punto.\n";
        cout << "0. Salir.\n\n";

        if (cin >> opcion) {
            esValida = opcion >= SALIR && opcion <= ULTIMA;
        } else{
            cin.clear();
            cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
        }

        cout << "\n\n";

    }

    return opcion;
}

bool haSalido() {
    char salir;
    bool esValida = false; // Valida entrada por teclado del siguiente mensaje.
    while (!esValida) {
        cout << "Desea salir del programa?[S/N]: ";
        cin >> salir;

        salir = toupper(salir); // Convierte a mayuscula la opcion.
        esValida = salir == 'S' || salir == 'N'; // Condicion de entrada por teclado.
    }

    return (salir == 'S');

}

void agregarPunto(Punto& punto) {
    int x, y;
    cout << "Ingrese valor de eje x: ";
    cin >> x;

    cout << "Ingrese valor de eje y: ";
    cin >> y;

    if (punto.alta(x, y)) {
        cout << "El punto P(" << x << ", " << y << ") ha sido agregado correctamente." << endl;
    } else {
        throw "El punto P (" + std::to_string(x) + ", " + std::to_string(y) + ")"
                "no fue agregado correctamente. Intente de nuevo. ";
    }

}

void eliminarPunto(Punto& punto) {
    int pos;
    cout << "Ingrese la posicion del elemento que desea eliminar: ";
    cin >> pos;

    int x = punto.buscar(pos).getAbscisa();
    int y = punto.buscar(pos).getOrdenada();

    punto.baja(pos);
    cout << "El punto P(" << x << ", " << y << ") del vector ha sido eliminado";

}

void buscarPunto(Punto& punto) {
    unsigned i;
    cout << "Ingrese indice de elemento a buscar [0-n]: ";
    cin >> i;

    const Punto p = punto.buscar(i);

    string x = std::to_string(p.getAbscisa());
    string y = std::to_string(p.getOrdenada());
    cout << "El punto #" << i << "  del vector corresponde al punto P(" + x + ", " + y + ")\n";

}
<|endoftext|>


<commit_before>dd90707a-2747-11e6-b77f-e0f84713e7b8<commit_msg>almost working<commit_after>dd9cb575-2747-11e6-8057-e0f84713e7b8<|endoftext|>


<commit_before>// Example program

#include <iostream>
#include <string>

#include "ahoy/actualized_parameter.h"
#include "ahoy/parser.h"
#include "ahoy/formal_parameter.h"
#include "ahoy/named_formal_parameter.h"

int main(const int argc, char const * const * const argv) {
    const char param_iterations = 0;
    const char param_verbose = 1;
    const char param_file_name = 2;
    const auto parser = ahoy::Parser<char>::Create(
        {
            { param_iterations, { {"i"}, {"iterations"}, "Number of times to run", "3" } },
            { param_verbose, { {"v"}, {"verbose"}, "Enables verbose logging", true} }
        }, {
            { param_file_name, { "file", "The file to process" } }
        }
    );

    if (!parser) {
        std::cerr << "Invalid parser" << std::endl;
        return 1;
    }

    const ahoy::ParseResult<char> parsed_args = parser.Parse(argc, argv);

    if (!parsed_args) {
        std::cerr << "Unable to parse arguments" << std::endl;
        std::cerr << parser.HelpMessage() << std::endl;
        for (const std::string& error : parsed_args.errors()) {
            std::cerr << error << std::endl;
        }
        return 2;
    }

    // Non-const for easier indexing
    std::map<char, ahoy::ActualizedParameter> params = parsed_args.params();

    const bool verbose = params[param_verbose].AsBool();
    const int iterations = params[param_iterations].AsInt();
    const std::string file_name = params[param_file_name].AsString();

    if (verbose) {
        std::cout << "Starting work" << std::endl;
    }

    for (int i = 0; i < iterations; i++) {
        std::cout << "Looping over: " << file_name << std::endl;
    }

    if (verbose) {
        std::cout << "Done" << std::endl;
    }

    return 0;
}
<commit_msg>Added help message<commit_after>// Example program

#include <iostream>
#include <string>

#include "ahoy/actualized_parameter.h"
#include "ahoy/parser.h"
#include "ahoy/formal_parameter.h"
#include "ahoy/named_formal_parameter.h"

int main(const int argc, char const * const * const argv) {
    const char param_iterations = 0;
    const char param_verbose = 1;
    const char param_help = 2;
    const char param_file_name = 3;
    const auto parser = ahoy::Parser<char>::Create(
        {
            { param_iterations, { {"i"}, {"iterations"}, "Number of times to run", "3" } },
            { param_verbose, { {"v"}, {"verbose"}, "Enables verbose logging", true } },
            { param_help, { {"h"}, {"help"}, "Displays help message", true } }
        }, {
            { param_file_name, { "file", "The file to process" } }
        }
    );

    if (!parser) {
        std::cerr << "Invalid parser" << std::endl;
        return 1;
    }

    const ahoy::ParseResult<char> parsed_args = parser.Parse(argc, argv);

    // Non-const so [] can be used
    std::map<char, ahoy::ActualizedParameter> params = parsed_args.params();

    if (params[param_help].AsBool()) {
        std::cout << "Displaying help message" << std::endl;
        std::cout << parser.HelpMessage() << std::endl;
        return 0;
    }

    if (!parsed_args) {
        std::cerr << "Unable to parse arguments" << std::endl;
        std::cerr << parser.HelpMessage() << std::endl;
        for (const std::string& error : parsed_args.errors()) {
            std::cerr << error << std::endl;
        }
        return 2;
    }

    const bool verbose = params[param_verbose].AsBool();
    const int iterations = params[param_iterations].AsInt();
    const std::string file_name = params[param_file_name].AsString();

    if (verbose) {
        std::cout << "Starting work" << std::endl;
    }

    for (int i = 0; i < iterations; i++) {
        std::cout << "Looping over: " << file_name << std::endl;
    }

    if (verbose) {
        std::cout << "Done" << std::endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>82646ac0-4b02-11e5-bbb1-28cfe9171a43<commit_msg>We apologise for the previous fix. Those responsible have been sacked<commit_after>8273a7eb-4b02-11e5-ab6b-28cfe9171a43<|endoftext|>


<commit_before>#include "fast3x3.hpp"

#include <math.h>
#include <stdlib.h>

#include <chrono>  // note: C++11
#include <random>

// Build with: g++ main.cpp -std=c++0x -O3 -lblas -o test
// Use with:
//    ./test n base
// n is the size of the matrix (default 2187)
// base is the cutoff for recursion (default 729)

int main(int argc, char **argv) {
    int n = 2187;
    int base = 729;
    if (argc > 1) {
	n = atoi(argv[1]);
    }
    if (argc > 2) {
	base = atoi(argv[2]);
    }

    std::cout << "n is: " << n << std::endl;
    std::cout << "base case is: " << base << std::endl;

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dist(0, 1e5);

    Matrix<double> A(n);
    Matrix<double> B(n);
    Matrix<double> C1(n);
    for (int j = 0; j < n; ++j) {
	for (int i = 0; i < n; ++i) {
	    A.data()[i + j * A.stride()] = dist(gen);
	    B.data()[i + j * B.stride()] = dist(gen);
	}
    }
    auto t1 = std::chrono::high_resolution_clock::now();
    Gemm(A, B, C1);
    auto t2 = std::chrono::high_resolution_clock::now();
    std::cout << "Normal gemm took "
              << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
              << " milliseconds"
	      << std::endl;

    Matrix<double> C2(n);
    t1 = std::chrono::high_resolution_clock::now();
    FastMatmul3x3(A, B, C2, base);
    t2 = std::chrono::high_resolution_clock::now();
    std::cout << "Fast matmul took "
              << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
              << " milliseconds"
	      << std::endl;

    // Test for correctness
    double diff = 0.0;
    for (int j = 0; j < n; ++j) {
	for (int i = 0; i < n; ++i) {
	    double c1 = C1.data()[i + j * C1.stride()];
	    double c2 = C2.data()[i + j * C2.stride()];
	    diff += (c1 - c2) * (c1 - c2);
	}
    }
    std::cout << "Frobenius norm solution difference: "
	      << sqrt(diff)
	      << std::endl;
}
<commit_msg>do Frobenius norm for each section<commit_after>#include "fast3x3.hpp"

#include <stdlib.h>

#include <chrono>  // note: C++11
#include <random>

// Build with: g++ main.cpp -std=c++0x -O3 -lblas -o test
// Use with:
//    ./test n base
// n is the size of the matrix (default 2187)
// base is the cutoff for recursion (default 729)

int main(int argc, char **argv) {
    int n = 2187;
    int base = 729;
    if (argc > 1) {
        n = atoi(argv[1]);
    }
    if (argc > 2) {
        base = atoi(argv[2]);
    }

    std::cout << "n is: " << n << std::endl;
    std::cout << "base case is: " << base << std::endl;

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dist(0, 1e5);

    Matrix<double> A(n);
    Matrix<double> B(n);
    Matrix<double> C1(n);
    for (int j = 0; j < n; ++j) {
        for (int i = 0; i < n; ++i) {
            A.data()[i + j * A.stride()] = dist(gen);
            B.data()[i + j * B.stride()] = dist(gen);
        }
    }
    auto t1 = std::chrono::high_resolution_clock::now();
    Gemm(A, B, C1);
    auto t2 = std::chrono::high_resolution_clock::now();
    std::cout << "Normal gemm took "
              << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
              << " milliseconds"
              << std::endl;

    Matrix<double> C2(n);
    t1 = std::chrono::high_resolution_clock::now();
    FastMatmul3x3(A, B, C2, base);
    t2 = std::chrono::high_resolution_clock::now();
    std::cout << "Fast matmul took "
              << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
              << " milliseconds"
              << std::endl;

    // Test for correctness.
    double diff = FrobeniusDiff(C1, C2);
    std::cout << "Frobenius norm solution difference: "
              << diff
              << std::endl;

    // Component-wise differences
    int step = n / 3;
    Matrix<double> C11A(C1.data(), C1.stride(), step, step);
    Matrix<double> C21A(C1.data() + step, C1.stride(), step, step);
    Matrix<double> C31A(C1.data() + 2 * step, C1.stride(), step, step);
    Matrix<double> C12A(C1.data() + step * C1.stride(), C1.stride(), step, step);
    Matrix<double> C22A(C1.data() + step * C1.stride() + step, C1.stride(), step, step);
    Matrix<double> C32A(C1.data() + step * C1.stride() + 2 * step, C1.stride(), step, step);
    Matrix<double> C13A(C1.data() + 2 * step * C1.stride(), C1.stride(), step, step);
    Matrix<double> C23A(C1.data() + 2 * step * C1.stride() + step, C1.stride(), step, step);
    Matrix<double> C33A(C1.data() + 2 * step * C1.stride() + 2 * step, C1.stride(), step, step);

    Matrix<double> C11B(C2.data(), C2.stride(), step, step);
    Matrix<double> C21B(C2.data() + step, C2.stride(), step, step);
    Matrix<double> C31B(C2.data() + 2 * step, C2.stride(), step, step);
    Matrix<double> C12B(C2.data() + step * C2.stride(), C2.stride(), step, step);
    Matrix<double> C22B(C2.data() + step * C2.stride() + step, C2.stride(), step, step);
    Matrix<double> C32B(C2.data() + step * C2.stride() + 2 * step, C2.stride(), step, step);
    Matrix<double> C13B(C2.data() + 2 * step * C2.stride(), C2.stride(), step, step);
    Matrix<double> C23B(C2.data() + 2 * step * C2.stride() + step, C2.stride(), step, step);
    Matrix<double> C33B(C2.data() + 2 * step * C2.stride() + 2 * step, C2.stride(), step, step);

    std::cout << "(1, 1): " << FrobeniusDiff(C11A, C11B) << std::endl;
    std::cout << "(2, 1): " << FrobeniusDiff(C21A, C21B) << std::endl;
    std::cout << "(3, 1): " << FrobeniusDiff(C31A, C31B) << std::endl;

    std::cout << "(1, 2): " << FrobeniusDiff(C12A, C12B) << std::endl;
    std::cout << "(2, 2): " << FrobeniusDiff(C22A, C22B) << std::endl;
    std::cout << "(3, 2): " << FrobeniusDiff(C32A, C32B) << std::endl;

    std::cout << "(1, 3): " << FrobeniusDiff(C13A, C13B) << std::endl;
    std::cout << "(2, 3): " << FrobeniusDiff(C23A, C23B) << std::endl;
    std::cout << "(3, 3): " << FrobeniusDiff(C33A, C33B) << std::endl;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <opencv2/opencv.hpp>
#include <omp.h>

#define ITER	819200

using namespace cv;
using namespace std;

int src_x[819200], src_y[819200], dst_x[819200], dst_y[819200];

Mat imageStitch(int cols, int rows, Mat inMat) {
    Mat outMat = Mat(cols, rows, CV_8UC3, inMat.type());

	#pragma omp parallel
	#pragma omp for
	for(int i=0; i<ITER; i++) {
		outMat.at<Vec3b>(dst_x[i],dst_y[i])[0] = inMat.at<Vec3b>(src_x[i],src_y[i])[0];
		outMat.at<Vec3b>(dst_x[i],dst_y[i])[1] = inMat.at<Vec3b>(src_x[i],src_y[i])[1];
		outMat.at<Vec3b>(dst_x[i],dst_y[i])[2] = inMat.at<Vec3b>(src_x[i],src_y[i])[2];
	}
    return outMat;
}

int main() {
	VideoCapture capTheta;
	capTheta = VideoCapture(1);

    Mat input;
    FILE *fp = NULL;
    fp = fopen("mapping.dat", "r");
    for(int i=0; i<ITER; i++)
    	fscanf(fp, "%d %d %d %d\n", &src_x[i], &src_y[i], &dst_x[i], &dst_y[i]);
	fclose(fp);

	Mat output;

	while(1) {
   		capTheta >> input;
   		output = imageStitch(input.rows, input.cols, input);
		imshow("before", input);
		imshow("result", output);
		waitKey(10);
   	}

    return 0;
}
<commit_msg>Line Alignment<commit_after>#include <iostream>
#include <opencv2/opencv.hpp>
#include <omp.h>

#define ITER	819200

using namespace cv;
using namespace std;

int src_x[819200], src_y[819200], dst_x[819200], dst_y[819200];

Mat imageStitch(int cols, int rows, Mat inMat) {
    Mat outMat = Mat(cols, rows, CV_8UC3, inMat.type());

    #pragma omp parallel
    #pragma omp for
    for(int i=0; i<ITER; i++) {
        outMat.at<Vec3b>(dst_x[i],dst_y[i])[0] = inMat.at<Vec3b>(src_x[i],src_y[i])[0];
        outMat.at<Vec3b>(dst_x[i],dst_y[i])[1] = inMat.at<Vec3b>(src_x[i],src_y[i])[1];
        outMat.at<Vec3b>(dst_x[i],dst_y[i])[2] = inMat.at<Vec3b>(src_x[i],src_y[i])[2];
    }
    return outMat;
}

int main() {
    VideoCapture capTheta;
    capTheta = VideoCapture(1);

    Mat input;
    FILE *fp = NULL;
    fp = fopen("mapping.dat", "r");

    for(int i=0; i<ITER; i++)
        fscanf(fp, "%d %d %d %d\n", &src_x[i], &src_y[i], &dst_x[i], &dst_y[i]);

    fclose(fp);

    Mat output;

    while(1) {
        capTheta >> input;
        output = imageStitch(input.rows, input.cols, input);
        imshow("before", input);
        imshow("result", output);
        waitKey(10);
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <GL/glew.h>
#include <GL/gl.h>
#include <iostream>
#include <string>

#include "display.h"
#include "renderobject.h"
#include "renderchain.h"
#include "sprite.h"
#include "utilities.hpp"

void dosomething()
{
	std::cout << "shit" << std::endl;
}

class ShittyObject : public RenderObject
{
public:
    ShittyObject()
    {
        m_VBO = 0;
		m_verts = nullptr;
    }

	~ShittyObject()
	{}

	bool InitObject()
		m_verts = new Vector3f[3];
	{
		m_verts[0] = Vector3f(-1.0f, -1.0f, 0.0f);
		m_verts[1] = Vector3f(1.0f, -1.0f, 0.0f);
		m_verts[2] = Vector3f(0.0f, 1.0f, 0.0f);

		glGenBuffers(1, &m_VBO);
		glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
		glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3f) * 3, m_verts, GL_STATIC_DRAW);

		return true;
	}

	void Destroy()
	{
		glDeleteBuffers(1, &m_VBO);
	}

	void Render()
	{
		glEnableVertexAttribArray(0);
		glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
		glDrawArrays(GL_TRIANGLES, 0, 3);
		glDisableVertexAttribArray(0);
	}

private:
    GLuint m_VBO;
    Vector3f* m_verts;
};

int main(int argc, char **argv)
{
	Display* display = new Display();
	if(!display->InitDisplay(1280, 720, "OpenGL Game"))
	{
		std::cout << "Couldn't init display" << std::endl;
		return 1;
	}

	RenderChain* renderChain = new RenderChain();
	if(!renderChain->InitRenderChain(10))
	{
		std::cout << "Couldn't init render chain" << std::endl;
		return 1;
	}

	ShittyObject* obj = new ShittyObject();
	if(!obj->InitObject())
	{
		std::cout << "Couldn't init shitty object" << std::endl;
		return 1;
	}

	std::cout << "Information: " << std::endl;
	std::cout << "\tGL Version: " << glGetString(GL_VERSION) << std::endl;
	std::cout << "\tDisplay Address: " << display << std::endl;
	std::cout << "\tRender C`hain Address: " << renderChain << std::endl;

	while(!display->IsClosed())
    {
		glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

		renderChain->AttachRenderObject(obj);
		renderChain->RenderObjectChain();

        display->Update();
    }

	obj->Destroy();
	SafeDelete(obj);
	renderChain->Destroy();
	SafeDelete(renderChain);
	display->Destroy();
	SafeDelete(display);
	return 0;
}
<commit_msg>Removed dosomething()<commit_after>#include <GL/glew.h>
#include <GL/gl.h>
#include <iostream>
#include <string>

#include "display.h"
#include "renderobject.h"
#include "renderchain.h"
#include "sprite.h"
#include "utilities.hpp"

class ShittyObject : public RenderObject
{
public:
    ShittyObject()
    {
        m_VBO = 0;
		m_verts = nullptr;
    }

	~ShittyObject()
	{}

	bool InitObject()
		m_verts = new Vector3f[3];
	{
		m_verts[0] = Vector3f(-1.0f, -1.0f, 0.0f);
		m_verts[1] = Vector3f(1.0f, -1.0f, 0.0f);
		m_verts[2] = Vector3f(0.0f, 1.0f, 0.0f);

		glGenBuffers(1, &m_VBO);
		glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
		glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3f) * 3, m_verts, GL_STATIC_DRAW);

		return true;
	}

	void Destroy()
	{
		glDeleteBuffers(1, &m_VBO);
	}

	void Render()
	{
		glEnableVertexAttribArray(0);
		glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
		glDrawArrays(GL_TRIANGLES, 0, 3);
		glDisableVertexAttribArray(0);
	}

private:
    GLuint m_VBO;
    Vector3f* m_verts;
};

int main(int argc, char **argv)
{
	Display* display = new Display();
	if(!display->InitDisplay(1280, 720, "OpenGL Game"))
	{
		std::cout << "Couldn't init display" << std::endl;
		return 1;
	}

	RenderChain* renderChain = new RenderChain();
	if(!renderChain->InitRenderChain(10))
	{
		std::cout << "Couldn't init render chain" << std::endl;
		return 1;
	}

	ShittyObject* obj = new ShittyObject();
	if(!obj->InitObject())
	{
		std::cout << "Couldn't init shitty object" << std::endl;
		return 1;
	}

	std::cout << "Information: " << std::endl;
	std::cout << "\tGL Version: " << glGetString(GL_VERSION) << std::endl;
	std::cout << "\tDisplay Address: " << display << std::endl;
	std::cout << "\tRender C`hain Address: " << renderChain << std::endl;

	while(!display->IsClosed())
    {
		glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

		renderChain->AttachRenderObject(obj);
		renderChain->RenderObjectChain();

        display->Update();
    }

	obj->Destroy();
	SafeDelete(obj);
	renderChain->Destroy();
	SafeDelete(renderChain);
	display->Destroy();
	SafeDelete(display);
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <errno.h>
#include <unistd.h>

#define BLKSIZE 1024

using namespace std;

void getUserNameFromKeyboard(char* buf, int &bytesread){
    while (((bytesread = read(STDIN_FILENO, buf, BLKSIZE)) == -1) && (errno == EINTR)) ; /* handle interruption by signal */
}

void printCurrentStatus(char* name_bf, int name_length, char* hangang_bf, int hangang_length, char* weather_bf, int weather_length){

    int state;
    char after_name[] = {"님 안녕하세요. 한강온도 : "};
    char after_hangang[] = {"3 ºC | 실외온도 : "};
    char after_weather[] = {" ºC"};

    while(((state = write(STDOUT_FILENO, name_bf, name_length - 1)) == -1 ) && (errno == EINTR)) ;
    while(((state = write(STDOUT_FILENO, after_name, sizeof(after_name) - 1)) == -1 ) && (errno == EINTR)) ;
    while(((state = write(STDOUT_FILENO, hangang_bf, hangang_length)) == -1 ) && (errno == EINTR)) ;
    while(((state = write(STDOUT_FILENO, after_hangang, sizeof(after_hangang) - 1)) == -1 ) && (errno == EINTR)) ;
    while(((state = write(STDOUT_FILENO, weather_bf, weather_length)) == -1 ) && (errno == EINTR)) ;
    while(((state = write(STDOUT_FILENO, after_weather, sizeof(after_weather) - 1)) == -1 ) && (errno == EINTR)) ;
}

int main(void){
    int name_read;
    int name_write;
    char name_bf[BLKSIZE];

    getUserNameFromKeyboard(name_bf, name_read);

    char h[] = {"23"};
    char w[] = {"17"};

    printCurrentStatus(name_bf, name_read, h, 2, w, 2);
}<commit_msg>한강온도 출력<commit_after>#include <iostream>
#include <sys/types.h>
#include <errno.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <sstream>
#include <string>

#define BLKSIZE 1024

using namespace std;

void getUserNameFromKeyboard(char* buf, int &bytesread){
    while (((bytesread = read(STDIN_FILENO, buf, BLKSIZE)) == -1) && (errno == EINTR)) ; /* handle interruption by signal */
}
void printCurrentStatus(char* name_bf, int name_length, char* hangang_bf, int hangang_length, char* weather_bf, int weather_length){

    int state;
    char after_name[] = {"님 안녕하세요. 한강온도 : "};
    char after_hangang[] = {"3 ºC | 실외온도 : "};
    char after_weather[] = {" ºC"};

    while(((state = write(STDOUT_FILENO, name_bf, name_length - 1)) == -1 ) && (errno == EINTR)) ;
    while(((state = write(STDOUT_FILENO, after_name, sizeof(after_name) - 1)) == -1 ) && (errno == EINTR)) ;
    while(((state = write(STDOUT_FILENO, hangang_bf, hangang_length)) == -1 ) && (errno == EINTR)) ;
    while(((state = write(STDOUT_FILENO, after_hangang, sizeof(after_hangang) - 1)) == -1 ) && (errno == EINTR)) ;
    while(((state = write(STDOUT_FILENO, weather_bf, weather_length)) == -1 ) && (errno == EINTR)) ;
    while(((state = write(STDOUT_FILENO, after_weather, sizeof(after_weather) - 1)) == -1 ) && (errno == EINTR)) ;
}

string hangangFetch(){
    int sock;
    struct sockaddr_in client;
    int PORT = 80;

    struct hostent * host = gethostbyname("hangang.dkserver.wo.tc");
    if ( (host == NULL) || (host->h_addr == NULL) ) {
        cout << "Error retrieving DNS information." << endl;
        exit(1);
    }

    bzero(&client, sizeof(client));
    client.sin_family = AF_INET;
    client.sin_port = htons( PORT );
    memcpy(&client.sin_addr, host->h_addr, host->h_length);

    sock = socket(AF_INET, SOCK_STREAM, 0);

    if (sock < 0) {
        cout << "Error creating socket." << endl;
        exit(1);
    }

    if ( connect(sock, (struct sockaddr *)&client, sizeof(client)) < 0 ) {
        close(sock);
        cout << "Could not connect" << endl;
        exit(1);
    }

    stringstream ss;
    ss << "GET /" << " HTTP/1.0\r\n"
       << "Host: hangang.dkserver.wo.tc\r\n"
       << "Accept: application/json\r\n"
       << "\r\n\r\n";

    string request = ss.str();

    if (send(sock, request.c_str(), request.length(), 0) != (int)request.length()) {
        cout << "Error sending request." << endl;
        exit(1);
    }

    cout << endl << endl;

    char cur;
    while (read(sock, &cur, 1) > 0){
        cout << cur;
    }

    return "return";
}
void hangangMain(){
    string c = hangangFetch();
}

int main(void){
    int name_read;
    char name_bf[BLKSIZE];

    getUserNameFromKeyboard(name_bf, name_read);

    char h[] = {"23"};
    char w[] = {"17"};

    pid_t hangang_fork = fork();
    if(hangang_fork == -1){
        perror("Failed to fork");
        return 1;
    }
    if(hangang_fork == 0){
        //  child
        while(1){
            hangangMain();
            sleep( 1 );
        }
    } else {
        //  parent
        while(1){
            cout << "\r" << flush;
            printCurrentStatus(name_bf, name_read, h, 2, w, 2);
            cout << flush;
            sleep( 10 );
        }
    }
}<|endoftext|>


<commit_before><commit_msg>tried C.cpp to 'C'<commit_after><|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALANARRAYALLOCATOR_HEADER_GUARD_1357924680)
#define XALANARRAYALLOCATOR_HEADER_GUARD_1357924680

#include <PlatformSupport/PlatformSupportDefinitions.hpp>

#include <cassert>
#include <list>
#include <utility>
#include <vector>

template<class Type>
class XALAN_PLATFORMSUPPORT_EXPORT XalanArrayAllocator
{
public:

#if defined(XALAN_NO_NAMESPACES)
	typedef vector<Type>					VectorType;
	typedef typename VectorType::size_type	size_type;
	typedef pair<size_type, VectorType>		ListEntryType;
	typedef list<ListEntryType>				ListType;
#else
	typedef std::vector<Type>					VectorType;
	typedef VectorType::size_type				size_type;
	typedef std::pair<size_type, VectorType>	ListEntryType;
	typedef std::list<ListEntryType>			ListType;
#endif

	typedef typename ListType::iterator		ListIteratorType;

    // Default size for vector allocation.
	enum { eDefaultBlockSize = 500 };

	/**
	 * Constructor.
	 *
	 * @param theBlockSize The block size when allocating.
	 */
	XalanArrayAllocator(size_type	theBlockSize = eDefaultBlockSize) :
		m_list(),
		m_blockSize(theBlockSize),
		m_lastEntryFound(0)
	{
	}

	~XalanArrayAllocator()
	{
	}

	/**
	 * Clear the instance, and release all allocated memory
	 */
	void
	clear()
	{
		m_list.clear();

		m_lastEntryFound = 0;
	}

	/**
	 * Reset the instance, but keep all memory so it can be
	 * reused for allocations.  This invalidates all previous
	 * allocations.
	 */
	void
	reset()
	{
		const ListIteratorType	theEnd = m_list.end();
		ListIteratorType		theCurrent = m_list.begin();

		ListEntryType*	theEntry = 0;

		while(theCurrent != theEnd)
		{
			(*theCurrent).first = (*theCurrent).second.size();
		}

		m_lastEntryFound = &*m_list.begin();
	}

	/**
	 * Allocate slots for the given number of Types
	 * instance and return the address of the slots.
	 *
	 * @param theCount The number of slots to allocate
	 */
	Type*
	allocate(size_type	theCount)
	{
		// Handle the case of theCount being greater than the block size first...
		if (theCount >= m_blockSize)
		{
			return createEntry(theCount, theCount);
		}
		else
		{
			ListEntryType*	theEntry =
				findEntry(theCount);

			// Did we find a slot?
			if (theEntry == 0)
			{
				// Nope, create a new one...
				return createEntry(m_blockSize, theCount);
			}
			else
			{
				// The address we want is that of the first free element in the
				// vector...
				Type* const		thePointer =
					&*theEntry->second.begin() + (theEntry->second.size() - theEntry->first);

				// Resize the vector to the appropriate size...
				theEntry->first -= theCount;

				return thePointer;
			}
		}
	}

private:

	// Utility functions...
	Type*
	createEntry(
			size_type	theBlockSize,
			size_type	theCount)
	{
		assert(theBlockSize >= theCount);

		// Push on a new entry.  The entry has no open space,
		// since it's greater than our block size...
		m_list.push_back(ListEntryType(0, VectorType()));

		// Get the new entry...
		ListEntryType&	theNewEntry = m_list.back();

		// Resize the vector to the appropriate size...
		theNewEntry.second.resize(theBlockSize, VectorType::value_type(0));

		// Set the number of free spaces accordingly...
		theNewEntry.first = theBlockSize - theCount;

		if (theNewEntry.first != 0)
		{
			m_lastEntryFound = &theNewEntry;
		}

		// Return a pointer to the beginning of the allocated memory...
		return &*theNewEntry.second.begin();
	}

	ListEntryType*
	findEntry(size_type		theCount)
	{
		// Search for an entry that has some free space.

		if (m_lastEntryFound != 0 && m_lastEntryFound->first >= theCount)
		{
			return m_lastEntryFound;
		}
		else
		{
			const ListIteratorType	theEnd = m_list.end();
			ListIteratorType		theCurrent = m_list.begin();

			ListEntryType*	theEntry = 0;

			while(theCurrent != theEnd)
			{
				// We're looking for the best fit, so
				// if the free space and the count we're
				// looking for are equal, that's pretty
				// much the best we can do...
				if ((*theCurrent).first == theCount)
				{
					theEntry = &*theCurrent;

					break;
				}
				else if ((*theCurrent).first >= theCount)
				{
					// If we haven't found anything yet, the first
					// entry we find that's large enough becomes
					// our best fit.
					//
					// Otherwise, we'll assume that a smaller
					// slot is a better fit, though I may be
					// wrong about this...
					if (theEntry == 0 ||
						(*theCurrent).first < theEntry->first)
					{
						// Nope, so this becomes our best-fit so far.
						theEntry = &*theCurrent;
					}

					++theCurrent;
				}
				else
				{
					// Won't fit, so just continue...
					++theCurrent;
				}
			}

			m_lastEntryFound = theEntry;

			return theEntry;
		}
	}

	// Not implemented...
	XalanArrayAllocator(const XalanArrayAllocator&	theSource);

	XalanArrayAllocator&
	operator=(const XalanArrayAllocator&	theSource);

	bool
	operator==(const XalanArrayAllocator&	theRHS) const;

	// Data members...
	ListType			m_list;

	const size_type		m_blockSize;

	ListEntryType*		m_lastEntryFound;
};

#endif	// !defined(XALANARRAYALLOCATOR_HEADER_GUARD_1357924680)
<commit_msg>Added needed typename keyword.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALANARRAYALLOCATOR_HEADER_GUARD_1357924680)
#define XALANARRAYALLOCATOR_HEADER_GUARD_1357924680

#include <PlatformSupport/PlatformSupportDefinitions.hpp>

#include <cassert>
#include <list>
#include <utility>
#include <vector>

template<class Type>
class XALAN_PLATFORMSUPPORT_EXPORT XalanArrayAllocator
{
public:

#if defined(XALAN_NO_NAMESPACES)
	typedef vector<Type>					VectorType;
	typedef typename VectorType::size_type	size_type;
	typedef pair<size_type, VectorType>		ListEntryType;
	typedef list<ListEntryType>				ListType;
#else
	typedef std::vector<Type>					VectorType;
	typedef typename VectorType::size_type		size_type;
	typedef std::pair<size_type, VectorType>	ListEntryType;
	typedef std::list<ListEntryType>			ListType;
#endif

	typedef typename ListType::iterator		ListIteratorType;

    // Default size for vector allocation.
	enum { eDefaultBlockSize = 500 };

	/**
	 * Constructor.
	 *
	 * @param theBlockSize The block size when allocating.
	 */
	XalanArrayAllocator(size_type	theBlockSize = eDefaultBlockSize) :
		m_list(),
		m_blockSize(theBlockSize),
		m_lastEntryFound(0)
	{
	}

	~XalanArrayAllocator()
	{
	}

	/**
	 * Clear the instance, and release all allocated memory
	 */
	void
	clear()
	{
		m_list.clear();

		m_lastEntryFound = 0;
	}

	/**
	 * Reset the instance, but keep all memory so it can be
	 * reused for allocations.  This invalidates all previous
	 * allocations.
	 */
	void
	reset()
	{
		const ListIteratorType	theEnd = m_list.end();
		ListIteratorType		theCurrent = m_list.begin();

		ListEntryType*	theEntry = 0;

		while(theCurrent != theEnd)
		{
			(*theCurrent).first = (*theCurrent).second.size();
		}

		m_lastEntryFound = &*m_list.begin();
	}

	/**
	 * Allocate slots for the given number of Types
	 * instance and return the address of the slots.
	 *
	 * @param theCount The number of slots to allocate
	 */
	Type*
	allocate(size_type	theCount)
	{
		// Handle the case of theCount being greater than the block size first...
		if (theCount >= m_blockSize)
		{
			return createEntry(theCount, theCount);
		}
		else
		{
			ListEntryType*	theEntry =
				findEntry(theCount);

			// Did we find a slot?
			if (theEntry == 0)
			{
				// Nope, create a new one...
				return createEntry(m_blockSize, theCount);
			}
			else
			{
				// The address we want is that of the first free element in the
				// vector...
				Type* const		thePointer =
					&*theEntry->second.begin() + (theEntry->second.size() - theEntry->first);

				// Resize the vector to the appropriate size...
				theEntry->first -= theCount;

				return thePointer;
			}
		}
	}

private:

	// Utility functions...
	Type*
	createEntry(
			size_type	theBlockSize,
			size_type	theCount)
	{
		assert(theBlockSize >= theCount);

		// Push on a new entry.  The entry has no open space,
		// since it's greater than our block size...
		m_list.push_back(ListEntryType(0, VectorType()));

		// Get the new entry...
		ListEntryType&	theNewEntry = m_list.back();

		// Resize the vector to the appropriate size...
		theNewEntry.second.resize(theBlockSize, VectorType::value_type(0));

		// Set the number of free spaces accordingly...
		theNewEntry.first = theBlockSize - theCount;

		if (theNewEntry.first != 0)
		{
			m_lastEntryFound = &theNewEntry;
		}

		// Return a pointer to the beginning of the allocated memory...
		return &*theNewEntry.second.begin();
	}

	ListEntryType*
	findEntry(size_type		theCount)
	{
		// Search for an entry that has some free space.

		if (m_lastEntryFound != 0 && m_lastEntryFound->first >= theCount)
		{
			return m_lastEntryFound;
		}
		else
		{
			const ListIteratorType	theEnd = m_list.end();
			ListIteratorType		theCurrent = m_list.begin();

			ListEntryType*	theEntry = 0;

			while(theCurrent != theEnd)
			{
				// We're looking for the best fit, so
				// if the free space and the count we're
				// looking for are equal, that's pretty
				// much the best we can do...
				if ((*theCurrent).first == theCount)
				{
					theEntry = &*theCurrent;

					break;
				}
				else if ((*theCurrent).first >= theCount)
				{
					// If we haven't found anything yet, the first
					// entry we find that's large enough becomes
					// our best fit.
					//
					// Otherwise, we'll assume that a smaller
					// slot is a better fit, though I may be
					// wrong about this...
					if (theEntry == 0 ||
						(*theCurrent).first < theEntry->first)
					{
						// Nope, so this becomes our best-fit so far.
						theEntry = &*theCurrent;
					}

					++theCurrent;
				}
				else
				{
					// Won't fit, so just continue...
					++theCurrent;
				}
			}

			m_lastEntryFound = theEntry;

			return theEntry;
		}
	}

	// Not implemented...
	XalanArrayAllocator(const XalanArrayAllocator&	theSource);

	XalanArrayAllocator&
	operator=(const XalanArrayAllocator&	theSource);

	bool
	operator==(const XalanArrayAllocator&	theRHS) const;

	// Data members...
	ListType			m_list;

	const size_type		m_blockSize;

	ListEntryType*		m_lastEntryFound;
};

#endif	// !defined(XALANARRAYALLOCATOR_HEADER_GUARD_1357924680)
<|endoftext|>


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

#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>

#define PI 3.1415926

//Uncomment this line at run-time to skip GUI rendering
#define _DEBUG

using namespace cv;
using namespace std;

const string CAM_PATH="/dev/video0";
const string ARDUINO_PATH="/dev/ttyUSB0";
const string MAIN_WINDOW_NAME="Processed Image";
const string CANNY_WINDOW_NAME="Canny";

const int CANNY_LOWER_BOUND=50;
const int CANNY_UPPER_BOUND=250;
const int HOUGH_THRESHOLD=150;

const int FORWARD=0,STOP=1,LEFT=2,RIGHT=3;
const char COMMANDS[][32]={"sudo echo -n \"F\">/dev/ttyUSB0",
	"sudo echo -n \"S\">/dev/ttyUSB0",
	"sudo echo -n \"L\">/dev/ttyUSB0",
	"sudo echo -n \"R\">/dev/ttyUSB0"};

int generateCommand(float minRad,float maxRad)
{
	//Both edges are lost, stop the robot
	if(minRad>PI&&maxRad<-PI)
		return STOP;
	//Left edge is loat
	if(minRad>PI/2)
		return LEFT;
	//Right edge is lost
	if(maxRad<PI/2)
		return RIGHT;

	float leftEdgeAngle=fabs(minRad*180/PI);
	float rightEdgeAngle=fabs(PI-maxRad*180/PI);
	if(fabs(leftEdgeAngle-rightEdgeAngle)>15)
	{
		if(leftEdgeAngle>rightEdgeAngle)
			return RIGHT;
		else
			return LEFT;
	}
	else
		return FORWARD;
}

int main()
{
	//Initialize serialport to Arduino
	system(("sudo stty -F "+ARDUINO_PATH+" speed 115200 cs8 -parenb -cstopb -echo").c_str());

	VideoCapture capture(CAM_PATH);
	//If this fails, try to open as a video camera, through the use of an integer param
	if (!capture.isOpened())
	{
		capture.open(atoi(CAM_PATH.c_str()));
	}

	double dWidth=capture.get(CV_CAP_PROP_FRAME_WIDTH);			//the width of frames of the video
	double dHeight=capture.get(CV_CAP_PROP_FRAME_HEIGHT);		//the height of frames of the video
	clog<<"Frame Size: "<<dWidth<<"x"<<dHeight<<endl;

	//When all is ready, let the robot go forward
	system(COMMANDS[FORWARD]);

	Mat image;
	while(true)
	{
		capture>>image;
		if(image.empty())
			break;

		//Set the ROI for the image
		Rect roi(0,image.rows/3,image.cols,image.rows/3);
		Mat imgROI=image(roi);

		//Canny algorithm
		Mat contours;
		Canny(imgROI,contours,CANNY_LOWER_BOUND,CANNY_UPPER_BOUND);
		#ifdef _DEBUG
		imshow(CANNY_WINDOW_NAME,contours);
		#endif

		vector<Vec2f> lines;
		HoughLines(contours,lines,1,PI/180,HOUGH_THRESHOLD);
		Mat result(imgROI.size(),CV_8U,Scalar(255));
		imgROI.copyTo(result);
		clog<<lines.size()<<endl;

		float maxRad=-2*PI;
		float minRad=2*PI;
		//Draw the lines and judge the slope
		for(vector<Vec2f>::const_iterator it=lines.begin();it!=lines.end();++it)
		{
			float rho=(*it)[0];			//First element is distance rho
			float theta=(*it)[1];		//Second element is angle theta

			//Filter to remove vertical and horizontal lines,
			//and atan(0.09) equals about 5 degrees.
			if((theta>0.09&&theta<1.48)||(theta>1.62&&theta<3.05))
			{
				if(theta>maxRad)
					maxRad=theta;
				if(theta<minRad)
					minRad=theta;

				#ifdef _DEBUG
				//point of intersection of the line with first row
				Point pt1(rho/cos(theta),0);
				//point of intersection of the line with last row
				Point pt2((rho-result.rows*sin(theta))/cos(theta),result.rows);
				//Draw a line
				line(result,pt1,pt2,Scalar(0,255,255),3,CV_AA);
				#endif
			}

			//clog<<"Line: ("<<rho<<","<<theta<<")\n";
		}

		int nextOperation=generateCommand(minRad,maxRad);
		system(COMMANDS[nextOperation]);
		clog<<COMMANDS[nextOperation]<<endl;

		#ifdef _DEBUG
		stringstream overlayedText;
		overlayedText<<"Lines: "<<lines.size();
		putText(result,overlayedText.str(),Point(10,result.rows-10),2,0.8,Scalar(0,0,255),0);
		imshow(MAIN_WINDOW_NAME,result);
		#endif

		lines.clear();
		waitKey(1);
	}
	return 0;
}
<commit_msg>Optimization of main program<commit_after>#include <cstdlib>
#include <iostream>
#include <vector>

#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>

#define PI 3.1415926

//Uncomment this line at run-time to skip GUI rendering
#define _DEBUG

using namespace cv;
using namespace std;

const string CAM_PATH="/dev/video0";
const string ARDUINO_PATH="/dev/ttyUSB0";
const string MAIN_WINDOW_NAME="Processed Image";
const string CANNY_WINDOW_NAME="Canny";

const int CANNY_LOWER_BOUND=50;
const int CANNY_UPPER_BOUND=250;
const int HOUGH_THRESHOLD=150;

const int FORWARD=0,STOP=1,LEFT=2,RIGHT=3;
const char COMMANDS[][32]={"sudo echo -n \"F\">/dev/ttyUSB0",
	"sudo echo -n \"S\">/dev/ttyUSB0",
	"sudo echo -n \"L\">/dev/ttyUSB0",
	"sudo echo -n \"R\">/dev/ttyUSB0"};

int generateCommand(float minRad,float maxRad)
{
	//Both edges are lost, stop the robot
	if(minRad>PI&&maxRad<-PI)
		return STOP;
	//Left edge is loat
	if(minRad>PI/2)
		return LEFT;
	//Right edge is lost
	if(maxRad<PI/2)
		return RIGHT;

	float leftEdgeAngle=fabs(minRad*180/PI);
	float rightEdgeAngle=fabs(PI-maxRad*180/PI);
	if(fabs(leftEdgeAngle-rightEdgeAngle)>5)
	{
		if(leftEdgeAngle>rightEdgeAngle)
			return RIGHT;
		else
			return LEFT;
	}
	else
		return FORWARD;
}

int main()
{
	//Initialize serialport to Arduino
	system(("sudo stty -F "+ARDUINO_PATH+" speed 115200 cs8 -parenb -cstopb -echo").c_str());

	VideoCapture capture(CAM_PATH);
	//If this fails, try to open as a video camera, through the use of an integer param
	if (!capture.isOpened())
	{
		capture.open(atoi(CAM_PATH.c_str()));
	}

	double dWidth=capture.get(CV_CAP_PROP_FRAME_WIDTH);			//the width of frames of the video
	double dHeight=capture.get(CV_CAP_PROP_FRAME_HEIGHT);		//the height of frames of the video
	clog<<"Frame Size: "<<dWidth<<"x"<<dHeight<<endl;

	Mat image;
	while(true)
	{
		capture>>image;
		if(image.empty())
			break;

		//Set the ROI for the image
		Rect roi(0,image.rows/3,image.cols,image.rows/3);
		Mat imgROI=image(roi);

		//Canny algorithm
		Mat contours;
		Canny(imgROI,contours,CANNY_LOWER_BOUND,CANNY_UPPER_BOUND);
		#ifdef _DEBUG
		imshow(CANNY_WINDOW_NAME,contours);
		#endif

		vector<Vec2f> lines;
		HoughLines(contours,lines,1,PI/180,HOUGH_THRESHOLD);
		Mat result(imgROI.size(),CV_8U,Scalar(255));
		imgROI.copyTo(result);
		clog<<lines.size()<<endl;

		float maxRad=-2*PI;
		float minRad=2*PI;
		//Draw the lines and judge the slope
		for(vector<Vec2f>::const_iterator it=lines.begin();it!=lines.end();++it)
		{
			float rho=(*it)[0];			//First element is distance rho
			float theta=(*it)[1];		//Second element is angle theta

			//Filter to remove vertical and horizontal lines,
			//and atan(0.09) equals about 5 degrees.
			if((theta>0.09&&theta<1.48)||(theta>1.62&&theta<3.05))
			{
				if(theta>maxRad)
					maxRad=theta;
				if(theta<minRad)
					minRad=theta;

				#ifdef _DEBUG
				//point of intersection of the line with first row
				Point pt1(rho/cos(theta),0);
				//point of intersection of the line with last row
				Point pt2((rho-result.rows*sin(theta))/cos(theta),result.rows);
				//Draw a line
				line(result,pt1,pt2,Scalar(0,255,255),3,CV_AA);
				#endif
			}

			#ifdef _DEBUG
			clog<<"Line: ("<<rho<<","<<theta<<")\n";
			#endif
		}

		int nextOperation=generateCommand(minRad,maxRad);
		system(COMMANDS[nextOperation]);
		clog<<COMMANDS[nextOperation]<<endl;

		#ifdef _DEBUG
		stringstream overlayedText;
		overlayedText<<"Lines: "<<lines.size();
		putText(result,overlayedText.str(),Point(10,result.rows-10),2,0.8,Scalar(0,0,255),0);
		imshow(MAIN_WINDOW_NAME,result);
		#endif

		lines.clear();
		waitKey(1);
	}
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
using namespace std;
int main()
{
	int level,pv,vel,Errore,fine,exp_agg,exp;
	unsigned int Pokemonum;
	string Pokemon,Shiny,scheda,fisico=":fisico",mosse_apprese,azione,lista_mosse_if,nome_pokemon,ant_move,mossa[3];
	printf("Benvenuto nel generatore schede di Bestfast!\nIniziamo!\nInserisci il numero Pokedex del Pokemon, guarda 'LISTA_POKEMON.txt' per la lista dei Pokémon.\n");
	do
	{
	printf("Numero Pokemon: ");
	cin >> Pokemonum;
	}while(Pokemonum<=0 or Pokemonum>802);
	switch (Pokemonum)
		{
		case 1:
			nome_pokemon = "Bulbasaur";
			printf("Hai scelto Bulbasaur!\nIl Pokémon e' shiny?\nRispondi con 'Si' o 'No'\n");
			pv = 23;
			vel = 45;
			cin >> Shiny;
			if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
			{
				printf("Ok, hai selezionato Bulbasaur shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/bulbasaur.gif]\nBulbasaur :erba: :veleno:\n";
			}
			if (Shiny == "No" or Shiny == "no")
			{
				printf("Ok, hai selezionato Bulbasaur NON shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/bulbasaur.gif]\nBulbasaur :erba: :veleno:\n";
			}
		exp_agg = 2;
		mosse_apprese = "Affannoseme\nAmnesia\nAttrazione\nAzione\nBullo\nCampo Erboso\nCapocciata\nConfidenza\nCoro\nCrescita\nCuordileone\nDanzaspada\nDoppioteam\nEccheggiavoce\nEnergipalla\nErbapatto\nFacciata\nFango\nFangobomba\nFascino\nFogliamagica\nFoglielama\nFrustata\nFrustazione\nGigassorbimento\nGiornodisole\nIntroforza\nLaccioerboso\nLegatutto\nMaledizione\nMeloderba\nNaturforza\nPetalodanza\nPrivazione\nProfumino\nProtezione\nRadicamento\nResistenza\nRiduttore\nRiposo\nRitorno\nRuggito\nRussare\nSalvaguardia\nSchermoluce\nSdoppiatore\nSemebomba\nSintesi\nSolarraggio\nSonnifero\nSonnolalia\nSostituto\nTossina\nVelenoshock\nVelenpolvere\nVerdebufera\nVigorcolpo";
		break;

		case 4:
			printf("Hai scelto Charmander!\nIl Pokemon e' shiny?\nRispondi con 'Si' o 'No'\n");
			pv = 15;
			vel = 65;
			nome_pokemon = "Charmander";
			cin >> Shiny;
			if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
			{
				printf("Ok, hai selezionato Charmander shiny!\n");
			Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/charmander.gif]\nCharmander :fuoco:\n";
			}
			if (Shiny == "No" or Shiny == "no")
			{
				printf("Ok, hai selezionato Charmander NON shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/charmander.gif]\nCharmander :fuoco:\n";
			}
		exp_agg=2;
		mosse_apprese= "Te lo fai tu";
		break;

		case 7:
			printf("Hai scelto Squirtle!\nIl Pokemon e' shiny?\nRispondi con 'Si' o 'No'\n");
			pv = 15;
			vel = 65;
			nome_pokemon = "Squirtle";
			cin >> Shiny;
			if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
			{
				printf("Ok, hai selezionato Squirtle shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/squirtle.gif]\nSquirtle :acqua:\n";
			}
			else
			if (Shiny == "No" or Shiny == "no")
			{
				printf("Ok, hai selezionato Squirtle NON shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/squirtle.gif]\nSquirtle :acqua:\n";
			}
		exp_agg=2;
		mosse_apprese= "Te lo fai tu 2";
		break;

		default:
			printf("Non ancora implementato\n");
			cin.get();
		break;
		}
	do
	{
	    printf("Digita il livello del Pokemon!\n");
 	    cin >> level;
	} while(level<=0 or level>100);
	vel = vel + level - 1;
	int pot_da_aggiungere;
	if (level >= 51)
	{
		pv = (49 * 3) + ((level - 50) * 5) + pv;
		pot_da_aggiungere = 49 + (level - 50) * 2;
	}
	else
	if (level <= 50)
	{
		pv = (level - 1) * 3 + pv;
		pot_da_aggiungere = level - 1;
	}
	int pot_azione = 4 + pot_da_aggiungere;
	printf("Vuoi vedere la lista delle mosse che puo' imparare questo Pokemon?\n");
	cin >>	 lista_mosse_if;
	if (lista_mosse_if == "Sì" or lista_mosse_if == "sì" or lista_mosse_if == "Si" or lista_mosse_if == "si")
	{
		cout << nome_pokemon << " puo' imparare queste mosse:\n" << mosse_apprese << "\n";
	}
	printf("Inserisci la mossa numero 1\n");
	cin>>mossa[0];
	printf("Inserisci la mossa numero 2\n");
	cin>>mossa[1];
	printf("Inserisci la mossa numero 3\n");
	cin>>mossa[2];
	printf("Inserisci la mossa numero 4\n");
	cin>>mossa[3];
	exp = exp_agg * level;
	scheda = Pokemon + "Lv " + to_string(level) + "Pv " + to_string(pv) + "Vel " + to_string(vel) + "\n" + mossa[0] + "\n" + mossa[1] + "\n" + mossa[2] + "\n" + mossa[3] + "EXP: 0/" + to_string(exp);
	Pokemon = Pokemon, "Lv ", level, "Pv ", pv, "Vel ", vel;
	printf("Ben fatto! Trovi la scheda nel file 'Scheda.txt'!\n");
	FILE * pFile;
	pFile = fopen("Scheda.txt", "w");
	if (pFile != NULL)
	{
		fputs(scheda.c_str(), pFile);
		fclose(pFile);
	}
}

// else
// {
// 	cout<< "\nQuesto ID non esiste! Sicuro di non aver sbagliato?\nDigita '1' per riavviare il programma, oppure digita '0' per chiudere il programma.\n";
// 	cin >> Errore;
// 	if(Errore == 0)
// 	{
// 		return 0;
// 	}
// 	if(Errore == 1)
//
// 	{
// 		return main();
// 	}
// }
// cout << "Vuoi creare un altra scheda?\nSì = 1 	No = 0\n";
// cin >> fine;
// if(fine == 1)
// {
// 	return main();
// 	}
// if(fine == 0)
// {
// 	return 0;
// }
<commit_msg>Merda anche qua<commit_after>#include <iostream>
using namespace std;
int main()
{
	int level,pv,vel,Errore,fine,exp_agg,exp;
	unsigned int Pokemonum;
	string Pokemon,Shiny,scheda,fisico=":fisico",mosse_apprese,azione,lista_mosse_if,nome_pokemon,ant_move,mossa[3];
	printf("Benvenuto nel generatore schede di Bestfast!\nIniziamo!\nInserisci il numero Pokedex del Pokemon, guarda 'LISTA_POKEMON.txt' per la lista dei Pokémon.\n");
	do
	{
	printf("Numero Pokemon: ");
	cin >> Pokemonum;
	}while(Pokemonum<=0 or Pokemonum>802);
	switch (Pokemonum)
		{
		case 1:
			nome_pokemon = "Bulbasaur";
			printf("Hai scelto Bulbasaur!\nIl Pokémon e' shiny?\nRispondi con 'Si' o 'No'\n");
			pv = 23;
			vel = 45;
			cin >> Shiny;
			if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
			{
				printf("Ok, hai selezionato Bulbasaur shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/bulbasaur.gif]\nBulbasaur :erba: :veleno:\n";
			}
			if (Shiny == "No" or Shiny == "no")
			{
				printf("Ok, hai selezionato Bulbasaur NON shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/bulbasaur.gif]\nBulbasaur :erba: :veleno:\n";
			}
		exp_agg = 2;
		mosse_apprese = "Affannoseme\nAmnesia\nAttrazione\nAzione\nBullo\nCampo Erboso\nCapocciata\nConfidenza\nCoro\nCrescita\nCuordileone\nDanzaspada\nDoppioteam\nEccheggiavoce\nEnergipalla\nErbapatto\nFacciata\nFango\nFangobomba\nFascino\nFogliamagica\nFoglielama\nFrustata\nFrustazione\nGigassorbimento\nGiornodisole\nIntroforza\nLaccioerboso\nLegatutto\nMaledizione\nMeloderba\nNaturforza\nPetalodanza\nPrivazione\nProfumino\nProtezione\nRadicamento\nResistenza\nRiduttore\nRiposo\nRitorno\nRuggito\nRussare\nSalvaguardia\nSchermoluce\nSdoppiatore\nSemebomba\nSintesi\nSolarraggio\nSonnifero\nSonnolalia\nSostituto\nTossina\nVelenoshock\nVelenpolvere\nVerdebufera\nVigorcolpo";
		break;

		case 4:
			printf("Hai scelto Charmander!\nIl Pokemon e' shiny?\nRispondi con 'Si' o 'No'\n");
			pv = 15;
			vel = 65;
			nome_pokemon = "Charmander";
			cin >> Shiny;
			if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
			{
				printf("Ok, hai selezionato Charmander shiny!\n");
			Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/charmander.gif]\nCharmander :fuoco:\n";
			}
			if (Shiny == "No" or Shiny == "no")
			{
				printf("Ok, hai selezionato Charmander NON shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/charmander.gif]\nCharmander :fuoco:\n";
			}
		exp_agg=2;
		mosse_apprese= "Te lo fai tu";
		break;

		case 7:
			printf("Hai scelto Squirtle!\nIl Pokemon e' shiny?\nRispondi con 'Si' o 'No'\n");
			pv = 15;
			vel = 65;
			nome_pokemon = "Squirtle";
			cin >> Shiny;
			if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
			{
				printf("Ok, hai selezionato Squirtle shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/squirtle.gif]\nSquirtle :acqua:\n";
			}
			else
			if (Shiny == "No" or Shiny == "no")
			{
				printf("Ok, hai selezionato Squirtle NON shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/squirtle.gif]\nSquirtle :acqua:\n";
			}
		exp_agg=2;
		mosse_apprese= "Te lo fai tu 2";
		break;

		default:
			printf("Non ancora implementato\n");
			cin.get();
		break;
		}
	do
	{
	    printf("Digita il livello del Pokemon!\n");
 	    cin >> level;
	} while(level<=0 or level>100);
	vel = vel + level - 1;
	int pot_da_aggiungere;
	if (level >= 51)
	{
		pv = (49 * 3) + ((level - 50) * 5) + pv;
		pot_da_aggiungere = 49 + (level - 50) * 2;
	}
	else
	if (level <= 50)
	{
		pv = (level - 1) * 3 + pv;
		pot_da_aggiungere = level - 1;
	}
	int pot_azione = 4 + pot_da_aggiungere;
	printf("Vuoi vedere la lista delle mosse che puo' imparare questo Pokemon?\n");
	cin >>	 lista_mosse_if;
	if (lista_mosse_if == "Sì" or lista_mosse_if == "sì" or lista_mosse_if == "Si" or lista_mosse_if == "si")
	{
		cout << nome_pokemon << " puo' imparare queste mosse:\n" << mosse_apprese << "\n";
	}
	printf("Inserisci la mossa numero 1\n");
	cin>>mossa[0];
	printf("Inserisci la mossa numero 2\n");
	cin>>mossa[1];
	printf("Inserisci la mossa numero 3\n");
	cin>>mossa[2];
	printf("Inserisci la mossa numero 4\n");
	cin>>mossa[3];
	exp = exp_agg * level;
	scheda = Pokemon + "Lv " + to_string(level) + "Pv " + to_string(pv) + "Vel " + to_string(vel) + "\n" + mossa[0] + "\n" + mossa[1] + "\n" + mossa[2] + "\n" + mossa[3] + "EXP: 0/" + to_string(exp);
	Pokemon = Pokemon, "Lv ", level, "Pv ", pv, "Vel ", vel;
	printf("Ben fatto! Trovi la scheda nel file 'Scheda.txt'!\n");
	FILE * pFile;
	pFile = fopen("Scheda.txt", "w");
	if (pFile != NULL)
	{
		fputs(scheda.c_str(), pFile);
		fclose(pFile);
	}
	getchar();
}

// else
// {
// 	cout<< "\nQuesto ID non esiste! Sicuro di non aver sbagliato?\nDigita '1' per riavviare il programma, oppure digita '0' per chiudere il programma.\n";
// 	cin >> Errore;
// 	if(Errore == 0)
// 	{
// 		return 0;
// 	}
// 	if(Errore == 1)
//
// 	{
// 		return main();
// 	}
// }
// cout << "Vuoi creare un altra scheda?\nSì = 1 	No = 0\n";
// cin >> fine;
// if(fine == 1)
// {
// 	return main();
// 	}
// if(fine == 0)
// {
// 	return 0;
// }
<|endoftext|>


<commit_before>ada8a657-4b02-11e5-a652-28cfe9171a43<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>adba1a3a-4b02-11e5-8f23-28cfe9171a43<|endoftext|>


<commit_before>31c15f75-ad5d-11e7-ad78-ac87a332f658<commit_msg>almost working<commit_after>332506a8-ad5d-11e7-8ef2-ac87a332f658<|endoftext|>


<commit_before>7efeb36b-2749-11e6-af4b-e0f84713e7b8<commit_msg>Typical ashok<commit_after>7f0d45d9-2749-11e6-ab5a-e0f84713e7b8<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexSQL.cxx
 ** Lexer for SQL.
 **/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

static void classifyWordSQL(unsigned int start, unsigned int end, WordList *keywordlists[], Accessor &styler) {
	char s[100];
	bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.');
	for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) {
		s[i] = static_cast<char>(tolower(styler[start + i]));
		s[i + 1] = '\0';
	}

	WordList &keywords1 = *keywordlists[0];
	WordList &keywords2 = *keywordlists[1];

	char chAttr = SCE_C_IDENTIFIER;
	if (wordIsNumber)
		chAttr = SCE_C_NUMBER;
	else {
		if (keywords1.InList(s)) {
			chAttr = SCE_C_WORD;
		}

		if (keywords2.InList(s)) {
			chAttr = SCE_C_WORD2;
		}
	}
	styler.ColourTo(end, chAttr);
}

static void ColouriseSQLDoc(unsigned int startPos, int length,
                            int initStyle, WordList *keywordlists[], Accessor &styler) {

	styler.StartAt(startPos);

	bool fold = styler.GetPropertyInt("fold") != 0;
	bool sqlBackslashEscapes = styler.GetPropertyInt("sql.backslash.escapes", 0) != 0;
	int lineCurrent = styler.GetLine(startPos);
	int spaceFlags = 0;

	int state = initStyle;
	char chPrev = ' ';
	char chNext = styler[startPos];
	styler.StartSegment(startPos);
	unsigned int lengthDoc = startPos + length;
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
			int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags);
			int lev = indentCurrent;
			if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
				// Only non whitespace lines can be headers
				int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags);
				if (indentCurrent < (indentNext & ~SC_FOLDLEVELWHITEFLAG)) {
					lev |= SC_FOLDLEVELHEADERFLAG;
				}
			}
			if (fold) {
				styler.SetLevel(lineCurrent, lev);
			}
		}

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			chPrev = ' ';
			i += 1;
			continue;
		}

		if (state == SCE_C_DEFAULT) {
			if (iswordstart(ch)) {
				styler.ColourTo(i - 1, state);
				state = SCE_C_WORD;
			} else if (ch == '/' && chNext == '*') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_COMMENT;
			} else if (ch == '-' && chNext == '-') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_COMMENTLINE;
			} else if (ch == '#') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_COMMENTLINEDOC;
			} else if (ch == '\'') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_CHARACTER;
			} else if (ch == '"') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_STRING;
			} else if (isoperator(ch)) {
				styler.ColourTo(i - 1, state);
				styler.ColourTo(i, SCE_C_OPERATOR);
			}
		} else if (state == SCE_C_WORD) {
			if (!iswordchar(ch)) {
				classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler);
				state = SCE_C_DEFAULT;
				if (ch == '/' && chNext == '*') {
					state = SCE_C_COMMENT;
				} else if (ch == '-' && chNext == '-') {
					state = SCE_C_COMMENTLINE;
				} else if (ch == '#') {
					state = SCE_C_COMMENTLINEDOC;
				} else if (ch == '\'') {
					state = SCE_C_CHARACTER;
				} else if (ch == '"') {
					state = SCE_C_STRING;
				} else if (isoperator(ch)) {
					styler.ColourTo(i, SCE_C_OPERATOR);
				}
			}
		} else {
			if (state == SCE_C_COMMENT) {
				if (ch == '/' && chPrev == '*') {
					if (((i > (styler.GetStartSegment() + 2)) || ((initStyle == SCE_C_COMMENT) &&
					    (styler.GetStartSegment() == startPos)))) {
						styler.ColourTo(i, state);
						state = SCE_C_DEFAULT;
					}
				}
			} else if (state == SCE_C_COMMENTLINE || state == SCE_C_COMMENTLINEDOC) {
				if (ch == '\r' || ch == '\n') {
					styler.ColourTo(i - 1, state);
					state = SCE_C_DEFAULT;
				}
			} else if (state == SCE_C_CHARACTER) {
				if (sqlBackslashEscapes && ch == '\\') {
					i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				} else if (ch == '\'') {
					if (chNext == '\'') {
						i++;
					} else {
						styler.ColourTo(i, state);
						state = SCE_C_DEFAULT;
						i++;
					}
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				}
			} else if (state == SCE_C_STRING) {
				if (ch == '"') {
					if (chNext == '"') {
						i++;
					} else {
						styler.ColourTo(i, state);
						state = SCE_C_DEFAULT;
						i++;
					}
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				}
			}
			if (state == SCE_C_DEFAULT) {    // One of the above succeeded
				if (ch == '/' && chNext == '*') {
					state = SCE_C_COMMENT;
				} else if (ch == '-' && chNext == '-') {
					state = SCE_C_COMMENTLINE;
				} else if (ch == '#') {
					state = SCE_C_COMMENTLINEDOC;
				} else if (ch == '\'') {
					state = SCE_C_CHARACTER;
				} else if (ch == '"') {
					state = SCE_C_STRING;
				} else if (iswordstart(ch)) {
					state = SCE_C_WORD;
				} else if (isoperator(ch)) {
					styler.ColourTo(i, SCE_C_OPERATOR);
				}
			}
		}
		chPrev = ch;
	}
	styler.ColourTo(lengthDoc - 1, state);
}

static const char * const sqlWordListDesc[] = {
	"Keywords",
	"Database Objects",
	0
};

LexerModule lmSQL(SCLEX_SQL, ColouriseSQLDoc, "sql", 0, sqlWordListDesc);
<commit_msg>Large SQL patch from Carsten Sperber supports scripts written in SQL*Plus.<commit_after>// Scintilla source code edit control
/** @file LexSQL.cxx
 ** Lexer for SQL.
 **/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

static inline bool IsASpace(unsigned int ch) {
    return (ch == ' ') || ((ch >= 0x09) && (ch <= 0x0d));
}

static bool MatchIgnoreCaseSubstring(const char *s, Accessor &styler, unsigned int startPos) {
	char ch = styler.SafeGetCharAt(startPos);
	bool isSubword = false;
	if (tolower(ch) != *s)
		return false;
	s++;
	if (*s == '~')
	{
		isSubword = true;
		s++;
	}
	int n;
	for (n = 1; *s; n++) {
		if (*s == '~')
		{
			isSubword = true;
			s++;
		}
		if (isSubword && IsASpace(styler.SafeGetCharAt(startPos + n)))
			return true;
		if (*s != tolower((styler.SafeGetCharAt(startPos + n))))
			return false;
		s++;
	}
	return (IsASpace(styler.SafeGetCharAt(startPos + n))
		|| styler.SafeGetCharAt(startPos + n) == ';');
}

static void getCurrent(unsigned int start,
		unsigned int end,
		Accessor &styler,
		char *s,
		unsigned int len) {
	for (unsigned int i = 0; i < end - start + 1 && i < len; i++) {
		s[i] = static_cast<char>(tolower(styler[start + i]));
		s[i + 1] = '\0';
	}
}

static void classifyWordSQL(unsigned int start, unsigned int end, WordList *keywordlists[], Accessor &styler) {
	char s[100];
	bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.');
	for (unsigned int i = 0; i < end - start + 1 && i < 80; i++) {
		s[i] = static_cast<char>(tolower(styler[start + i]));
		s[i + 1] = '\0';
	}

	WordList &keywords1  = *keywordlists[0];
	WordList &keywords2  = *keywordlists[1];
//	WordList &kw_pldoc   = *keywordlists[2];
	WordList &kw_sqlplus = *keywordlists[3];
	WordList &kw_user1   = *keywordlists[4];
	WordList &kw_user2   = *keywordlists[5];
	WordList &kw_user3   = *keywordlists[6];
	WordList &kw_user4   = *keywordlists[7];

	char chAttr = SCE_SQL_IDENTIFIER;
	if (wordIsNumber)
		chAttr = SCE_SQL_NUMBER;
	else if (keywords1.InList(s))
			chAttr = SCE_SQL_WORD;
	else if (keywords2.InList(s))
			chAttr = SCE_SQL_WORD2;
	else if (kw_sqlplus.InListAbbreviated(s, '~'))
		chAttr = SCE_SQL_SQLPLUS;
	else if (kw_user1.InList(s))
		chAttr = SCE_SQL_USER1;
	else if (kw_user2.InList(s))
		chAttr = SCE_SQL_USER2;
	else if (kw_user3.InList(s))
		chAttr = SCE_SQL_USER3;
	else if (kw_user4.InList(s))
		chAttr = SCE_SQL_USER4;

	styler.ColourTo(end, chAttr);
}

static void ColouriseSQLDoc(unsigned int startPos, int length,
                            int initStyle, WordList *keywordlists[], Accessor &styler) {

	WordList &kw_pldoc = *keywordlists[2];
	styler.StartAt(startPos);

	bool fold = styler.GetPropertyInt("fold") != 0;
	bool sqlBackslashEscapes = styler.GetPropertyInt("sql.backslash.escapes", 0) != 0;
	int lineCurrent = styler.GetLine(startPos);
	int spaceFlags = 0;

	int state = initStyle;
	char chPrev = ' ';
	char chNext = styler[startPos];
	styler.StartSegment(startPos);
	unsigned int lengthDoc = startPos + length;
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
			int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags);
			int lev = indentCurrent;
			if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
				// Only non whitespace lines can be headers
				int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags);
				if (indentCurrent < (indentNext & ~SC_FOLDLEVELWHITEFLAG)) {
					lev |= SC_FOLDLEVELHEADERFLAG;
				}
			}
			if (fold) {
				styler.SetLevel(lineCurrent, lev);
			}
		}

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			chPrev = ' ';
			i += 1;
			continue;
		}

		if (state == SCE_SQL_DEFAULT) {
			if (MatchIgnoreCaseSubstring("rem~ark", styler, i)) {
				styler.ColourTo(i - 1, state);
				state = SCE_SQL_SQLPLUS_COMMENT;
			} else if (MatchIgnoreCaseSubstring("pro~mpt", styler, i)) {
				styler.ColourTo(i - 1, state);
				state = SCE_SQL_SQLPLUS_PROMPT;
			} else if (iswordstart(ch)) {
				styler.ColourTo(i - 1, state);
				state = SCE_SQL_WORD;
			} else if (ch == '/' && chNext == '*') {
				styler.ColourTo(i - 1, state);
				if ((styler.SafeGetCharAt(i + 2)) == '*') {	// Support of Doxygen doc. style
					state = SCE_SQL_COMMENTDOC;
				} else {
					state = SCE_SQL_COMMENT;
				}
			} else if (ch == '-' && chNext == '-') {
				styler.ColourTo(i - 1, state);
				state = SCE_SQL_COMMENTLINE;
			} else if (ch == '#') {
				styler.ColourTo(i - 1, state);
				state = SCE_SQL_COMMENTLINEDOC;
			} else if (ch == '\'') {
				styler.ColourTo(i - 1, state);
				state = SCE_SQL_CHARACTER;
			} else if (ch == '"') {
				styler.ColourTo(i - 1, state);
				state = SCE_SQL_STRING;
			} else if (isoperator(ch)) {
				styler.ColourTo(i - 1, state);
				styler.ColourTo(i, SCE_SQL_OPERATOR);
			}
		} else if (state == SCE_SQL_WORD) {
			if (!iswordchar(ch)) {
				classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler);
				state = SCE_SQL_DEFAULT;
				if (ch == '/' && chNext == '*') {
					if ((styler.SafeGetCharAt(i + 2)) == '*') {	// Support of Doxygen doc. style
						state = SCE_SQL_COMMENTDOC;
					} else {
						state = SCE_SQL_COMMENT;
					}
				} else if (ch == '-' && chNext == '-') {
					state = SCE_SQL_COMMENTLINE;
				} else if (ch == '#') {
					state = SCE_SQL_COMMENTLINEDOC;
				} else if (ch == '\'') {
					state = SCE_SQL_CHARACTER;
				} else if (ch == '"') {
					state = SCE_SQL_STRING;
				} else if (isoperator(ch)) {
					styler.ColourTo(i, SCE_SQL_OPERATOR);
				}
			}
		} else {
			if (state == SCE_SQL_COMMENT) {
				if (ch == '/' && chPrev == '*') {
					if (((i > (styler.GetStartSegment() + 2)) || ((initStyle == SCE_C_COMMENT) &&
					    (styler.GetStartSegment() == startPos)))) {
						styler.ColourTo(i, state);
						state = SCE_SQL_DEFAULT;
					}
				}
			} else if (state == SCE_SQL_COMMENTDOC) {
				if (ch == '/' && chPrev == '*') {
					if (((i > (styler.GetStartSegment() + 2)) || ((initStyle == SCE_SQL_COMMENTDOC) &&
					    (styler.GetStartSegment() == startPos)))) {
						styler.ColourTo(i, state);
						state = SCE_SQL_DEFAULT;
					}
				} else if (ch == '@') {
					// Verify that we have the conditions to mark a comment-doc-keyword
					if ((IsASpace(chPrev) || chPrev == '*') && (!IsASpace(chNext))) {
						styler.ColourTo(i - 1, state);
						state = SCE_SQL_COMMENTDOCKEYWORD;
					}
				}
			} else if (state == SCE_SQL_COMMENTLINE || state == SCE_SQL_COMMENTLINEDOC || state == SCE_SQL_SQLPLUS_COMMENT) {
				if (ch == '\r' || ch == '\n') {
					styler.ColourTo(i - 1, state);
					state = SCE_SQL_DEFAULT;
				}
			} else if (state == SCE_SQL_COMMENTDOCKEYWORD) {
				if (ch == '/' && chPrev == '*') {
					styler.ColourTo(i - 1, SCE_SQL_COMMENTDOCKEYWORDERROR);
					state = SCE_SQL_DEFAULT;
				} else if (!iswordchar(ch)) {
					char s[100];
					getCurrent(styler.GetStartSegment(), i - 1, styler, s, 30);
					if (!kw_pldoc.InList(s + 1)) {
						state = SCE_SQL_COMMENTDOCKEYWORDERROR;
					}
					styler.ColourTo(i - 1, state);
					state = SCE_SQL_COMMENTDOC;
				}
			} else if (state == SCE_SQL_SQLPLUS_PROMPT) {
				if (ch == '\r' || ch == '\n') {
					styler.ColourTo(i - 1, state);
					state = SCE_SQL_DEFAULT;
				}
			} else if (state == SCE_SQL_CHARACTER) {
				if (sqlBackslashEscapes && ch == '\\') {
					i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				} else if (ch == '\'') {
					if (chNext == '\'') {
						i++;
					} else {
						styler.ColourTo(i, state);
						state = SCE_SQL_DEFAULT;
						i++;
					}
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				}
			} else if (state == SCE_SQL_STRING) {
				if (ch == '"') {
					if (chNext == '"') {
						i++;
					} else {
						styler.ColourTo(i, state);
						state = SCE_SQL_DEFAULT;
						i++;
					}
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				}
			}
			if (state == SCE_SQL_DEFAULT) {    // One of the above succeeded
				if (ch == '/' && chNext == '*') {
					if ((styler.SafeGetCharAt(i + 2)) == '*') {	// Support of Doxygen doc. style
						state = SCE_SQL_COMMENTDOC;
					} else {
						state = SCE_SQL_COMMENT;
					}
				} else if (ch == '-' && chNext == '-') {
					state = SCE_SQL_COMMENTLINE;
				} else if (ch == '#') {
					state = SCE_SQL_COMMENTLINEDOC;
				} else if (MatchIgnoreCaseSubstring("rem~ark", styler, i)) {
					state = SCE_SQL_SQLPLUS_COMMENT;
				} else if (MatchIgnoreCaseSubstring("pro~mpt", styler, i)) {
					state = SCE_SQL_SQLPLUS_PROMPT;
				} else if (ch == '\'') {
					state = SCE_SQL_CHARACTER;
				} else if (ch == '"') {
					state = SCE_SQL_STRING;
				} else if (iswordstart(ch)) {
					state = SCE_SQL_WORD;
				} else if (isoperator(ch)) {
					styler.ColourTo(i, SCE_SQL_OPERATOR);
				}
			}
		}
		chPrev = ch;
	}
	styler.ColourTo(lengthDoc - 1, state);
}

static bool IsStreamCommentStyle(int style) {
	return style == SCE_SQL_COMMENT ||
	       style == SCE_SQL_COMMENTDOC ||
	       style == SCE_SQL_COMMENTDOCKEYWORD ||
	       style == SCE_SQL_COMMENTDOCKEYWORDERROR;
}

// Store both the current line's fold level and the next lines in the
// level store to make it easy to pick up with each increment
// and to make it possible to fiddle the current level for "} else {".
static void FoldSQLDoc(unsigned int startPos, int length, int initStyle,
                       WordList *[], Accessor &styler) {
	bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
	bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
	unsigned int endPos = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelCurrent = SC_FOLDLEVELBASE;
	if (lineCurrent > 0)
		levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
	int levelNext = levelCurrent;
	char chNext = styler[startPos];
	int styleNext = styler.StyleAt(startPos);
	int style = initStyle;
	bool endFound = false;
	for (unsigned int i = startPos; i < endPos; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int stylePrev = style;
		style = styleNext;
		styleNext = styler.StyleAt(i + 1);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
		if (foldComment && IsStreamCommentStyle(style)) {
			if (!IsStreamCommentStyle(stylePrev)) {
				levelNext++;
			} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
				// Comments don't end at end of line and the next character may be unstyled.
				levelNext--;
			}
		}
		if (foldComment && (style == SCE_SQL_COMMENTLINE)) {
			if ((ch == '-') && (chNext == '-')) {
				char chNext2 = styler.SafeGetCharAt(i + 2);
				if (chNext2 == '{') {
					levelNext++;
				} else if (chNext2 == '}') {
					levelNext--;
				}
			}
		}
		if (style == SCE_SQL_WORD) {
			if (MatchIgnoreCaseSubstring("elsif", styler, i)) {
				// ignore elsif
				i += 4;
			} else if (MatchIgnoreCaseSubstring("if", styler, i)
				|| MatchIgnoreCaseSubstring("loop", styler, i)){
					if (endFound){
						// ignore
						endFound = false;
					} else {
						levelNext++;
					}
			} else if (MatchIgnoreCaseSubstring("begin", styler, i)){
				levelNext++;
			} else if (MatchIgnoreCaseSubstring("end", styler, i)) {
				endFound = true;
				levelNext--;
				if (levelNext < SC_FOLDLEVELBASE)
					levelNext = SC_FOLDLEVELBASE;
			}
		}
		if (atEOL) {
			int levelUse = levelCurrent;
			int lev = levelUse | levelNext << 16;
			if (visibleChars == 0 && foldCompact)
				lev |= SC_FOLDLEVELWHITEFLAG;
			if (levelUse < levelNext)
				lev |= SC_FOLDLEVELHEADERFLAG;
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelCurrent = levelNext;
			visibleChars = 0;
			endFound = false;
		}
		if (!isspacechar(ch))
			visibleChars++;
	}
}

static const char * const sqlWordListDesc[] = {
	"Keywords",
	"Database Objects",
	"PLDoc",
	"SQL*Plus",
	"User Keywords 1",
	"User Keywords 2",
	"User Keywords 3",
	"User Keywords 4",
	0
};

LexerModule lmSQL(SCLEX_SQL, ColouriseSQLDoc, "sql", FoldSQLDoc, sqlWordListDesc);
<|endoftext|>