#include "filesys.h"
#include <math.h>
#include <algorithm>
#include <random>
#include <vector>
using namespace std;

enum RANDOM {UNIFORMINT, UNIFORMREAL, NORMAL, SHUFFLE};
class Random {
public:
    Random(){}
    Random(int min, int max, RANDOM type=UNIFORMINT, int mean=50, int stdev=20) : m_min(min), m_max(max), m_type(type)
    {
        if (type == NORMAL){
            //the case of NORMAL to generate integer numbers with normal distribution
            m_generator = std::mt19937(m_device());
            //the data set will have the mean of 50 (default) and standard deviation of 20 (default)
            //the mean and standard deviation can change by passing new values to constructor
            m_normdist = std::normal_distribution<>(mean,stdev);
        }
        else if (type == UNIFORMINT) {
            //the case of UNIFORMINT to generate integer numbers
            // Using a fixed seed value generates always the same sequence
            // of pseudorandom numbers, e.g. reproducing scientific experiments
            // here it helps us with testing since the same sequence repeats
            m_generator = std::mt19937(10);// 10 is the fixed seed value
            m_unidist = std::uniform_int_distribution<>(min,max);
        }
        else if (type == UNIFORMREAL) { //the case of UNIFORMREAL to generate real numbers
            m_generator = std::mt19937(10);// 10 is the fixed seed value
            m_uniReal = std::uniform_real_distribution<double>((double)min,(double)max);
        }
        else { //the case of SHUFFLE to generate every number only once
            m_generator = std::mt19937(m_device());
        }
    }
    void setSeed(int seedNum){
        // we have set a default value for seed in constructor
        // we can change the seed by calling this function after constructor call
        // this gives us more randomness
        m_generator = std::mt19937(seedNum);
    }
    void init(int min, int max){
        m_min = min;
        m_max = max;
        m_type = UNIFORMINT;
        m_generator = std::mt19937(10);// 10 is the fixed seed value
        m_unidist = std::uniform_int_distribution<>(min,max);
    }
    void getShuffle(vector<int> & array){
        // this function provides a list of all values between min and max
        // in a random order, this function guarantees the uniqueness
        // of every value in the list
        // the user program creates the vector param and passes here
        // here we populate the vector using m_min and m_max
        for (int i = m_min; i<=m_max; i++){
            array.push_back(i);
        }
        shuffle(array.begin(),array.end(),m_generator);
    }

    void getShuffle(int array[]){
        // this function provides a list of all values between min and max
        // in a random order, this function guarantees the uniqueness
        // of every value in the list
        // the param array must be of the size (m_max-m_min+1)
        // the user program creates the array and pass it here
        vector<int> temp;
        for (int i = m_min; i<=m_max; i++){
            temp.push_back(i);
        }
        std::shuffle(temp.begin(), temp.end(), m_generator);
        vector<int>::iterator it;
        int i = 0;
        for (it=temp.begin(); it != temp.end(); it++){
            array[i] = *it;
            i++;
        }
    }

    int getRandNum(){
        // this function returns integer numbers
        // the object must have been initialized to generate integers
        int result = 0;
        if(m_type == NORMAL){
            //returns a random number in a set with normal distribution
            //we limit random numbers by the min and max values
            result = m_min - 1;
            while(result < m_min || result > m_max)
                result = m_normdist(m_generator);
        }
        else if (m_type == UNIFORMINT){
            //this will generate a random number between min and max values
            result = m_unidist(m_generator);
        }
        return result;
    }

    double getRealRandNum(){
        // this function returns real numbers
        // the object must have been initialized to generate real numbers
        double result = m_uniReal(m_generator);
        // a trick to return numbers only with two deciaml points
        // for example if result is 15.0378, function returns 15.03
        // to round up we can use ceil function instead of floor
        result = std::floor(result*100.0)/100.0;
        return result;
    }

    string getRandString(int size){
        // the parameter size specifies the length of string we ask for
        // to use ASCII char the number range in constructor must be set to 97 - 122
        // and the Random type must be UNIFORMINT (it is default in constructor)
        string output = "";
        for (int i=0;i<size;i++){
            output = output + (char)getRandNum();
        }
        return output;
    }

    int getMin(){return m_min;}
    int getMax(){return m_


#include <iostream>
#include <filesystem>
#include <vector>
#include <stdexcept>
#include <sys/wait.h>
#include <ctime>
#include <iomanip>// put_time()
#include "./src/app/processes/ProcessManagement.hpp"
#include "./src/app/processes/Task.hpp"

using namespace std;
namespace fs = std::filesystem;

int main(int argc, char* argv[]) {
    string directory;
    string action;

    cout << "Enter the directory path: ";
    getline(cin, directory);

    cout << "Enter the action (encrypt/decrypt): ";
    getline(cin, action);

    try {
        if (!fs::exists(directory) || !fs::is_directory(directory)) {
            cerr << "Invalid or non-existent directory path!" << endl;
            return 1;
        }

        ProcessManagement processManagement;
        vector<pid_t> childPids;

        time_t t = time(nullptr);
        tm* now = localtime(&t);
        cout << put_time(now, "[%Y-%m-%d %H:%M:%S] ") << "Starting scan and process submission..." << endl;

        for (const auto& entry : fs::recursive_directory_iterator(directory)) {
            if (entry.is_regular_file()) {
                string filePath = entry.path().string();
                Action taskAction = (action == "encrypt") ? Action::ENCRYPT : Action::DECRYPT;

                auto task = make_unique<Task>(taskAction, filePath);

                t = time(nullptr);
                now = localtime(&t);
                cout << put_time(now, "[%Y-%m-%d %H:%M:%S] ") << "Queueing task for: " << filePath << endl;

                pid_t pid = processManagement.submitToQueue(move(task));
                if (pid > 0) {
                    childPids.push_back(pid);
                }
            }
        }

        cout << endl << "All tasks queued. Waiting for " << childPids.size() << " child processes to complete..." << endl;
        // wait for all forked children
        for (pid_t pid : childPids) {
            int status;
            waitpid(pid, &status, 0);
        }

        t = time(nullptr);
        now = localtime(&t);
        cout << put_time(now, "[%Y-%m-%d %H:%M:%S] ") << "All child processes have finished. Operation complete." << endl;

    } catch (const fs::filesystem_error& ex) {
        cerr << "Filesystem error: " << ex.what() << endl;
        return 1;
    } catch (const std::exception& ex) {
        cerr << "A critical error occurred during setup: " << ex.what() << endl;
        return 1;
    }

    return 0;
}


#include "calcdialog.h"

#include <QVector>
#include <QGridLayout>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include "calcdialog.h"
// Идентификаторы кнопок
// Для цифровых кнопок идентификатор является соответствующая цифра
#define DIV 10
#define MUL 11
#define MINUS 12
#define PLUS 13
#define INVERSE 15
#define DOT 16
#define EQ 20
#define BKSP 30
#define CLR 31
#define CLR_ALL 32
#define POW 33
#define LOG 34
#define SIN 35
#define COS 36

// количество кнопок в группе, отображаемой в виде сетки
#define GRID_KEYS 16

/// Описатель кнопки
struct BtnDescr{
    QString text; ///< Отображаемый на кнопке текст
    int id; ///< Идентификатор кнопки
    BtnDescr() { id=0;}; ///< Конструктор по умолчанию
    ///< Конструктор для инициализации
    BtnDescr( const QString & str, int i)
    { text = str; id = i; };
};
/// Динамический массив-вектор элементов описателей кнопок
QVector<BtnDescr> _btnDescr;
/// Инициализация массива _btnDescr всеми отображаемыми кнопками
void InitBtnDescrArray()
{
    _btnDescr.push_back( BtnDescr("7", 7) );
    _btnDescr.push_back( BtnDescr("8", 8) );
    _btnDescr.push_back( BtnDescr("9", 9) );
    _btnDescr.push_back( BtnDescr("/", DIV) );
    _btnDescr.push_back( BtnDescr("4", 4) );
    _btnDescr.push_back( BtnDescr("5", 5) );
    _btnDescr.push_back( BtnDescr("6", 6) );
    _btnDescr.push_back( BtnDescr("*", MUL) );
    _btnDescr.push_back( BtnDescr("1", 1) );
    _btnDescr.push_back( BtnDescr("2", 2) );
    _btnDescr.push_back( BtnDescr("3", 3) );
    _btnDescr.push_back( BtnDescr("-", MINUS) );
    _btnDescr.push_back( BtnDescr("0", 0) );
    _btnDescr.push_back( BtnDescr("-/+", INVERSE) );
    _btnDescr.push_back( BtnDescr(".", DOT) );
    _btnDescr.push_back( BtnDescr("+", PLUS) );
    _btnDescr.push_back( BtnDescr("<-",BKSP) );
    _btnDescr.push_back( BtnDescr("CE",CLR) );
    _btnDescr.push_back( BtnDescr("C", CLR_ALL) );
    _btnDescr.push_back( BtnDescr("=", EQ) );
    _btnDescr.push_back( BtnDescr("x^y", POW) );
    _btnDescr.push_back( BtnDescr("log_y(x)", LOG) );
    _btnDescr.push_back( BtnDescr("sin(x)", SIN) );
    _btnDescr.push_back( BtnDescr("cos(x)", COS) );
}
/// Конструктор класса калькулятора
CalcDialog::CalcDialog( QWidget * parent)
{
    initNum(); // инициализируем счетные переменные
    InitBtnDescrArray(); // инициализируем массив с описанием кнопок
    // Создаем форму
    m_pLineEdit = new QLineEdit(this);
    // устанавливаем режим только чтения - разрешаем ввод только
    // с нарисованных кнопок
    m_pLineEdit->setReadOnly ( true );
    m_pSignalMapper = new QSignalMapper(this);
    // создаем схемы выравнивания
    QVBoxLayout *newLayout = new QVBoxLayout();
    QGridLayout *gridLayout = new QGridLayout();
    QHBoxLayout *bccKeysLayout = new QHBoxLayout();
    QHBoxLayout *mainKeysLayout = new QHBoxLayout();
    QVBoxLayout *dlgLayout = new QVBoxLayout();

    mainKeysLayout->addLayout(newLayout);
    // Заполняем форму кнопками из _btnDescr
    for (int i = 0; i < _btnDescr.size(); i++) {
        // Создаем кнопку с текстом из очередного описателя
        QPushButton *button = new QPushButton(_btnDescr[i].text);
        // если кнопка в основном блоке цифровых или "=" -
        // разрешаем изменение всех размеров
        if( i >= GRID_KEYS + 3 || i < GRID_KEYS)
            button->setSizePolicy ( QSizePolicy::Expanding,
                                  QSizePolicy::Expanding);
        // если кнопка не цифровая - увеличиваем шрифт надписи на 4 пункта
        if( _btnDescr[i].id >= 10 ){
            QFont fnt = button->font();
            fnt.setPointSize( fnt.pointSize () + 4 );
            button->setFont( fnt );
        }
        // связываем сигнал нажатия кнопки с объектом m_pSignalMapper
        connect(button, SIGNAL(clicked()), m_pSignalMapper, SLOT(map()));
        // обеспечиваем соответствие кнопки её идентификатору
        m_pSignalMapper->setMapping(button, _btnDescr[i].id);
        if(i<GRID_KEYS) // Если кнопка из центрального блока - помещаем в сетку
            gridLayout->addWidget(button, i / 4, i % 4);
        else if( i < GRID_KEYS + 3) // кнопка из верхнего блока - в bccKeysLayout
            bccKeysLayout->addWidget(button);
        else if ( i == 19)
        { // кнопка "=" - помещаем в блок mainKeysLayout после gridLayout
            mainKeysLayout->addLayout(gridLayout);
            mainKeysLayout->addWidget(button);
        } else {
            newLayout->addWidget(button);
        }
    }
    // связываем сигнал из m_pSignalMapper о нажатии со слотом clicked
    // нашего класса
    connect(m_pSignalMapper, SIGNAL(mappedInt(int)),
            this, SLOT(clicked(int)));
    // добавляем блоки кнопок в схему выравнивания всей формы
    dlgLayout->addWidget(m_pLineEdit);
    dlgLayout->addLayout(bccKeysLayout);
    dlgLayout->addLayout(mainKeysLayout);
    // связываем


#include <bits/stdc++.h>
#include "nlohmann/json.hpp"
using namespace std;
using json = nlohmann::json;

// Convert string in given base to decimal integer
long long convertToDecimal(const string &value, int base) {
    long long result = 0;
    for (char c : value) {
        int digit;
        if (isdigit(c)) digit = c - '0';
        else if (isalpha(c)) digit = toupper(c) - 'A' + 10;
        else continue;
        result = result * base + digit;
    }
    return result;
}

// Lagrange Interpolation to compute P(x) given points
double lagrangeInterpolation(const vector<pair<double,double>> &points, double x=0) {
    double total = 0;
    int n = points.size();

    for (int i = 0; i < n; i++) {
        double xi = points[i].first;
        double yi = points[i].second;
        double term = yi;

        for (int j = 0; j < n; j++) {
            if (i != j) {
                double xj = points[j].first;
                term *= (x - xj) / (xi - xj);
            }
        }
        total += term;
    }
    return total;
}

int main() {
    // Read JSON from file
    ifstream file("input.json");
    if (!file.is_open()) {
        cerr << "Error: Could not open input.json" << endl;
        return 1;
    }

    json data;
    file >> data;

    vector<pair<double,double>> points;

    // Iterate over the first object in the array
    for (auto& [key, val] : data[0].items()) {
        if (key == "keys") continue; // skip meta info
        int x = stoi(key);
        int base = stoi(val["base"].get<string>());
        string value = val["value"];
        long long y = convertToDecimal(value, base);
        points.push_back({x, y});
    }

    // Compute constant term (c) at x=0
    double c = lagrangeInterpolation(points, 0);
    cout << "Constant term (c): " << c << endl;

    return 0;
}


#include <iostream>
#include <iomanip>
#include <cstdint>
#include <string>
#include "Exploit/fbiosdrvExploit.hpp"
#include <vector>
#include <thread>
#include <chrono>

// PCI Configuration Address and Data ports
#define PCI_CONFIG_ADDRESS  0xCF8
#define PCI_CONFIG_DATA     0xCFC

// PCI Command Register bits
#define PCI_COMMAND_BUS_MASTER  0x04
#define PCI_COMMAND_MEMORY      0x02
#define PCI_COMMAND_IO          0x01

struct PCIDevice {
    uint8_t bus;
    uint8_t device;
    uint8_t function;
    uint16_t vendor_id;
    uint16_t device_id;
    std::string description;
};

uint32_t MakePCIAddress(uint8_t bus, uint8_t device, uint8_t function, uint8_t offset) {
    return 0x80000000 | (bus << 16) | (device << 11) | (function << 8) | (offset & 0xFC);
}

uint32_t ReadPCIConfig(uint8_t bus, uint8_t device, uint8_t function, uint8_t offset) {
    uint32_t address = MakePCIAddress(bus, device, function, offset);
    fbiosdrvExploit::WritePort(PCI_CONFIG_ADDRESS, address, 4);
    return fbiosdrvExploit::ReadPort(PCI_CONFIG_DATA, 4);
}

void WritePCIConfig(uint8_t bus, uint8_t device, uint8_t function, uint8_t offset, uint32_t value) {
    uint32_t address = MakePCIAddress(bus, device, function, offset);
    fbiosdrvExploit::WritePort(PCI_CONFIG_ADDRESS, address, 4);
    fbiosdrvExploit::WritePort(PCI_CONFIG_DATA, value, 4);
}

uint16_t ReadPCICommand(uint8_t bus, uint8_t device, uint8_t function) {
    uint32_t config = ReadPCIConfig(bus, device, function, 0x04);
    return config & 0xFFFF;
}

void WritePCICommand(uint8_t bus, uint8_t device, uint8_t function, uint16_t command) {
    uint32_t config = ReadPCIConfig(bus, device, function, 0x04);
    config = (config & 0xFFFF0000) | command;
    WritePCIConfig(bus, device, function, 0x04, config);
}

std::vector<PCIDevice> ScanPCIDevices() {
    std::vector<PCIDevice> devices;

    for (int bus = 0; bus < 256; bus++) {
        for (int device = 0; device < 32; device++) {
            for (int function = 0; function < 8; function++) {
                uint32_t config = ReadPCIConfig(bus, device, function, 0x00);
                uint16_t vendor_id = config & 0xFFFF;
                uint16_t device_id = (config >> 16) & 0xFFFF;

                if (vendor_id != 0xFFFF && vendor_id != 0x0000) {
                    PCIDevice dev;
                    dev.bus = bus;
                    dev.device = device;
                    dev.function = function;
                    dev.vendor_id = vendor_id;
                    dev.device_id = device_id;

                    uint32_t class_code = ReadPCIConfig(bus, device, function, 0x08);
                    uint8_t base_class = (class_code >> 24) & 0xFF;
                    uint8_t sub_class = (class_code >> 16) & 0xFF;

                    if (base_class == 0x02 && sub_class == 0x80) {
                        dev.description = "Network Controller (WiFi)";
                    }
                    else if (base_class == 0x02) {
                        dev.description = "Network Controller";
                    }
                    else {
                        dev.description = "Unknown Device";
                    }

                    devices.push_back(dev);
                }
            }
        }
    }
    return devices;
}

void EnableBusMastering(uint8_t bus, uint8_t device, uint8_t function) {
    uint16_t command = ReadPCICommand(bus, device, function);

    std::cout << "Current PCI Command: 0x" << std::hex << command << std::dec << std::endl;
    std::cout << "Bus Mastering: " << ((command & PCI_COMMAND_BUS_MASTER) ? "ENABLED" : "DISABLED") << std::endl;
    std::cout << "Memory Space: " << ((command & PCI_COMMAND_MEMORY) ? "ENABLED" : "DISABLED") << std::endl;
    std::cout << "I/O Space: " << ((command & PCI_COMMAND_IO) ? "ENABLED" : "DISABLED") << std::endl;

    if (!(command & PCI_COMMAND_BUS_MASTER)) {
        std::cout << "\nEnabling Bus Mastering..." << std::endl;
        command |= PCI_COMMAND_BUS_MASTER | PCI_COMMAND_MEMORY;
        WritePCICommand(bus, device, function, command);

        uint16_t new_command = ReadPCICommand(bus, device, function);
        std::cout << "New PCI Command: 0x" << std::hex << new_command << std::dec << std::endl;
        std::cout << "Bus Mastering: " << ((new_command & PCI_COMMAND_BUS_MASTER) ? "ENABLED" : "DISABLED") << std::endl;
    }
    else {
        std::cout << "Bus Mastering already enabled!" << std::endl;
    }
}

int main() {
    if (!fbiosdrvExploit::LoadDriver()) {
        std::cerr << "Failed to load driver\n";
        return 1;
    }

    std::cout << "Scanning PCI devices...\n" << std::endl;
    auto devices = ScanPCIDevices();

    std::cout << "Found PCI Devices:" << std::endl;
    for (size_t i = 0; i < devices.size(); i++) {
        std::cout << i << ": Bus " << (int)devices[i].bus
            << ", Device " << (int)devices[i].device
            << ", Function " << (int)devices[i].function
            << " - " << std::hex << devices[i].vendor_id << ":" <<


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

#include "lapjv.h"

/** Column-reduction and reduction transfer for a dense cost matrix.
 */
int_t _ccrrt_dense(const uint_t n, cost_t *cost[],
	int_t *free_rows, int_t *x, int_t *y, cost_t *v)
{
	int_t n_free_rows;
	boolean *unique;

	for (uint_t i = 0; i < n; i++) {
		x[i] = -1;
		v[i] = LARGE;
		y[i] = 0;
	}
	for (uint_t i = 0; i < n; i++) {
		for (uint_t j = 0; j < n; j++) {
			const cost_t c = cost[i][j];
			if (c < v[j]) {
				v[j] = c;
				y[j] = i;
			}
			PRINTF("i=%d, j=%d, c[i,j]=%f, v[j]=%f y[j]=%d\n", i, j, c, v[j], y[j]);
		}
	}
	PRINT_COST_ARRAY(v, n);
	PRINT_INDEX_ARRAY(y, n);
	NEW(unique, boolean, n);
	memset(unique, TRUE, n);
	{
		int_t j = n;
		do {
			j--;
			const int_t i = y[j];
			if (x[i] < 0) {
				x[i] = j;
			}
			else {
				unique[i] = FALSE;
				y[j] = -1;
			}
		} while (j > 0);
	}
	n_free_rows = 0;
	for (uint_t i = 0; i < n; i++) {
		if (x[i] < 0) {
			free_rows[n_free_rows++] = i;
		}
		else if (unique[i]) {
			const int_t j = x[i];
			cost_t min = LARGE;
			for (uint_t j2 = 0; j2 < n; j2++) {
				if (j2 == (uint_t)j) {
					continue;
				}
				const cost_t c = cost[i][j2] - v[j2];
				if (c < min) {
					min = c;
				}
			}
			PRINTF("v[%d] = %f - %f\n", j, v[j], min);
			v[j] -= min;
		}
	}
	FREE(unique);
	return n_free_rows;
}

/** Augmenting row reduction for a dense cost matrix.
 */
int_t _carr_dense(
	const uint_t n, cost_t *cost[],
	const uint_t n_free_rows,
	int_t *free_rows, int_t *x, int_t *y, cost_t *v)
{
	uint_t current = 0;
	int_t new_free_rows = 0;
	uint_t rr_cnt = 0;
	PRINT_INDEX_ARRAY(x, n);
	PRINT_INDEX_ARRAY(y, n);
	PRINT_COST_ARRAY(v, n);
	PRINT_INDEX_ARRAY(free_rows, n_free_rows);
	while (current < n_free_rows) {
		int_t i0;
		int_t j1, j2;
		cost_t v1, v2, v1_new;
		boolean v1_lowers;

		rr_cnt++;
		PRINTF("current = %d rr_cnt = %d\n", current, rr_cnt);
		const int_t free_i = free_rows[current++];
		j1 = 0;
		v1 = cost[free_i][0] - v[0];
		j2 = -1;
		v2 = LARGE;
		for (uint_t j = 1; j < n; j++) {
			PRINTF("%d = %f %d = %f\n", j1, v1, j2, v2);
			const cost_t c = cost[free_i][j] - v[j];
			if (c < v2) {
				if (c >= v1) {
					v2 = c;
					j2 = j;
				}
				else {
					v2 = v1;
					v1 = c;
					j2 = j1;
					j1 = j;
				}
			}
		}
		i0 = y[j1];
		v1_new = v[j1] - (v2 - v1);
		v1_lowers = v1_new < v[j1];
		PRINTF("%d %d 1=%d,%f 2=%d,%f v1'=%f(%d,%g) \n", free_i, i0, j1, v1, j2, v2, v1_new, v1_lowers, v[j1] - v1_new);
		if (rr_cnt < current * n) {
			if (v1_lowers) {
				v[j1] = v1_new;
			}
			else if (i0 >= 0 && j2 >= 0) {
				j1 = j2;
				i0 = y[j2];
			}
			if (i0 >= 0) {
				if (v1_lowers) {
					free_rows[--current] = i0;
				}
				else {
					free_rows[new_free_rows++] = i0;
				}
			}
		}
		else {
			PRINTF("rr_cnt=%d >= %d (current=%d * n=%d)\n", rr_cnt, current * n, current, n);
			if (i0 >= 0) {
				free_rows[new_free_rows++] = i0;
			}
		}
		x[free_i] = j1;
		y[j1] = free_i;
	}
	return new_free_rows;
}

/** Find columns with minimum d[j] and put them on the SCAN list.
 */
uint_t _find_dense(const uint_t n, uint_t lo, cost_t *d, int_t *cols, int_t *y)
{
	uint_t hi = lo + 1;
	cost_t mind = d[cols[lo]];
	for (uint_t k = hi; k < n; k++) {
		int_t j = cols[k];
		if (d[j] <= mind) {
			if (d[j] < mind) {
				hi = lo;
				mind = d[j];
			}
			cols[k] = cols[hi];
			cols[hi++] = j;
		}
	}
	return hi;
}

// Scan all columns in TODO starting from arbitrary column in SCAN
// and try to decrease d of the TODO columns using the SCAN column.
int_t _scan_dense(const uint_t n, cost_t *cost[],
	uint_t *plo, uint_t*phi,
	cost_t *d, int_t *cols, int_t *pred,
	int_t *y, cost_t *v)
{
	uint_t lo = *plo;
	uint_t hi = *phi;
	cost_t h, cred_ij;

	while (lo != hi) {
		int_t j = cols[lo++];
		const int_t i = y[j];
		const cost_t mind = d[j];
		h = cost[i][j] - v[j] - mind;
		PRINTF("i=%d j=%d h=%f\n", i, j, h);
		// For all columns in TODO
		for (uint_t k = hi; k < n; k++) {
			j = cols[k];
			cred_ij = cost[i][j] - v[j] - h;
			if (cred_ij < d[j]) {
				d[j] = cred_ij;
				pred[j] = i;
				if (cred_ij == mind) {
					if (y[j] < 0) {
						return j;
					}
					cols[k] = cols[hi];
					cols[hi++] = j;
				}
			}
		}
	}
	*plo = lo;
	*phi = hi;
	return -1;
}

/** Single iteration of modified Dijkstra shortest path algorithm as explained in the JV paper.
 *
 * This is a dense matrix version.
 *
 * \return The closest free column index.
 */
int_t find_path_dense(
	const uint_t n, cost_t *cost[],
	const int_t start_i,
	int_t *y, cost_t *v,
	int_t *pred)
{
	uint_t lo = 0, hi = 0;
	int_t final_j = -1;
	uint_t n_ready = 0;
	int_t *cols;
	cost_t *d;

	NEW(cols, int_t, n);
	NEW(d, cost_t, n);

	for (uint_t i = 0; i < n; i++) {
		cols[i] = i;
		pred[i] = start_i;
		d[i] = cost[start_i][i] - v[i];
	}
	PRINT_COST_ARRAY(d, n);
	while (final_j == -1) {
		// No columns left on the SCAN list.
		if (lo == hi) {
			PRINTF("%d..%d -> find\n", lo, hi);
			n_ready = lo;
			hi = _find_dense(n, lo, d, cols, y);
			PRINTF("check %d.


#include <iostream>
using namespace std;

class Car {
    float distance;
    float fuel;

public:
    Car() {
        distance = 100.0;
        fuel = 5.0;
    }

    Car(float d, float f) {
        distance = d;
        fuel = f;
    }

    Car(const Car& c) {
        distance = c.distance;
        fuel = c.fuel;
    }

    float calculateMileage() {
        if (fuel <= 0) {
            cout << "Fuel must be greater than zero to calculate mileage." << endl;
            return 0;
        }
        return distance / fuel;
    }

    void displayMileage() {
        float mileage = calculateMileage();
        if (mileage > 0)
            cout << "Mileage: " << mileage << " km/L" << endl;
    }
};

int main() {
    Car car1;
    Car car2(250.5, 12.5);
    Car car3(car2);

    cout << "Car 1: ";
    car1.displayMileage();

    cout << "Car 2: ";
    car2.displayMileage();

    cout << "Car 3 (copied): ";
    car3.displayMileage();

    return 0;
}

/* Output :
Car 1: Mileage: 20 km/L
Car 2: Mileage: 20.04 km/L

Car 3 (copied): Mileage: 20.04 km/L */


#include <iostream>

void apurarVotos(int* ptrC1, int* ptrC2, int* ptrC3, int* ptrBrancos, int* ptrNulos, int* ptrTotal);
void imprimirResultados(int c1, int c2, int c3, int brancos, int nulos, int total);

int main() {
    int candidato1 = 0;
    int candidato2 = 0;
    int candidato3 = 0;
    int brancos = 0;
    int nulos = 0;
    int totalEleitores = 0;

    std::cout << "--- Urna Eletrônica ---\n";
    std::cout << "1: Candidato 1\n";
    std::cout << "2: Candidato 2\n";
    std::cout << "3: Candidato 3\n";
    std::cout << "0: Voto em Branco\n";
    std::cout << "4: Voto Nulo\n";
    std::cout << "-1: Encerrar votação\n";
    std::cout << "-----------------------\n";
    std::cout << "Digite os votos um por um:\n";

    apurarVotos(&candidato1, &candidato2, &candidato3, &brancos, &nulos, &totalEleitores);

    imprimirResultados(candidato1, candidato2, candidato3, brancos, nulos, totalEleitores);

    return 0;
}

void apurarVotos(int* ptrC1, int* ptrC2, int* ptrC3, int* ptrBrancos, int* ptrNulos, int* ptrTotal) {
    int voto;

    while (true) {
        std::cin >> voto;

        if (voto == -1) {
            break;
        }

        (*ptrTotal)++;

        switch (voto) {
            case 1:
                (*ptrC1)++;
                break;
            case 2:
                (*ptrC2)++;
                break;
            case 3:
                (*ptrC3)++;
                break;
            case 0:
                (*ptrBrancos)++;
                break;
            case 4:
                (*ptrNulos)++;
                break;
            default:
                std::cout << "(Voto inválido, computado como nulo)\n";
                (*ptrNulos)++;
                break;
        }
    }
}

void imprimirResultados(int c1, int c2, int c3, int brancos, int nulos, int total) {
    std::cout << "\n--- Resultado da Votação ---\n";

    if (c1 > c2 && c1 > c3) {
        std::cout << "Candidato vencedor: 1\n";
    } else if (c2 > c1 && c2 > c3) {
        std::cout << "Candidato vencedor: 2\n";
    } else if (c3 > c1 && c3 > c2) {
        std::cout << "Candidato vencedor: 3\n";
    } else {
        std::cout << "Candidato vencedor: Houve um empate entre os candidatos mais votados.\n";
    }

    std::cout << "Número de votos em branco: " << brancos << "\n";
    std::cout << "Número de votos nulos: " << nulos << "\n";
    std::cout << "Número total de eleitores que votaram: " << total << "\n";

    std::cout << "\n--- Votos por Candidato ---\n";
    std::cout << "Candidato 1: " << c1 << " votos\n";
    std::cout << "Candidato 2: " << c2 << " votos\n";
    std::cout << "Candidato 3: " << c3 << " votos\n";
}


/* This source file must have a .cpp extension so that all C++ compilers
   recognize the extension without flags.  Borland does not know .cxx for
   example.  */
#ifndef __cplusplus
# error "A C compiler has been selected for C++."
#endif

#if !defined(__has_include)
/* If the compiler does not have __has_include, pretend the answer is
   always no.  */
#  define __has_include(x) 0
#endif

/* Version number components: V=Version, R=Revision, P=Patch
   Version date components:   YYYY=Year, MM=Month,   DD=Day  */

#if defined(__COMO__)
# define COMPILER_ID "Comeau"
/* __COMO_VERSION__ = VRR */
# define COMPILER_VERSION_MAJOR DEC(__COMO_VERSION__ / 100)
# define COMPILER_VERSION_MINOR DEC(__COMO_VERSION__ % 100)

#elif defined(__INTEL_COMPILER) || defined(__ICC)
# define COMPILER_ID "Intel"
# if defined(_MSC_VER)
#  define SIMULATE_ID "MSVC"
# endif
# if defined(__GNUC__)
#  define SIMULATE_ID "GNU"
# endif
/* __INTEL_COMPILER = VRP prior to 2021, and then VVVV for 2021 and later,
   except that a few beta releases use the old format with V=2021.  */
# if __INTEL_COMPILER < 2021 || __INTEL_COMPILER == 202110 || __INTEL_COMPILER == 202111
#  define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER/100)
#  define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER/10 % 10)
#  if defined(__INTEL_COMPILER_UPDATE)
#   define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER_UPDATE)
#  else
#   define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER   % 10)
#  endif
# else
#  define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER)
#  define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER_UPDATE)
 /* The third version component from --version is an update index,
    but no macro is provided for it.  */
#  define COMPILER_VERSION_PATCH DEC(0)
# endif
# if defined(__INTEL_COMPILER_BUILD_DATE)
 /* __INTEL_COMPILER_BUILD_DATE = YYYYMMDD */
#  define COMPILER_VERSION_TWEAK DEC(__INTEL_COMPILER_BUILD_DATE)
# endif
# if defined(_MSC_VER)
 /* _MSC_VER = VVRR */
#  define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
#  define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
# endif
# if defined(__GNUC__)
#  define SIMULATE_VERSION_MAJOR DEC(__GNUC__)
# elif defined(__GNUG__)
#  define SIMULATE_VERSION_MAJOR DEC(__GNUG__)
# endif
# if defined(__GNUC_MINOR__)
#  define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__)
# endif
# if defined(__GNUC_PATCHLEVEL__)
#  define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__)
# endif

#elif (defined(__clang__) && defined(__INTEL_CLANG_COMPILER)) || defined(__INTEL_LLVM_COMPILER)
# define COMPILER_ID "IntelLLVM"
#if defined(_MSC_VER)
# define SIMULATE_ID "MSVC"
#endif
#if defined(__GNUC__)
# define SIMULATE_ID "GNU"
#endif
/* __INTEL_LLVM_COMPILER = VVVVRP prior to 2021.2.0, VVVVRRPP for 2021.2.0 and
 * later.  Look for 6 digit vs. 8 digit version number to decide encoding.
 * VVVV is no smaller than the current year when a version is released.
 */
#if __INTEL_LLVM_COMPILER < 1000000L
# define COMPILER_VERSION_MAJOR DEC(__INTEL_LLVM_COMPILER/100)
# define COMPILER_VERSION_MINOR DEC(__INTEL_LLVM_COMPILER/10 % 10)
# define COMPILER_VERSION_PATCH DEC(__INTEL_LLVM_COMPILER    % 10)
#else
# define COMPILER_VERSION_MAJOR DEC(__INTEL_LLVM_COMPILER/10000)
# define COMPILER_VERSION_MINOR DEC(__INTEL_LLVM_COMPILER/100 % 100)
# define COMPILER_VERSION_PATCH DEC(__INTEL_LLVM_COMPILER     % 100)
#endif
#if defined(_MSC_VER)
  /* _MSC_VER = VVRR */
# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
#endif
#if defined(__GNUC__)
# define SIMULATE_VERSION_MAJOR DEC(__GNUC__)
#elif defined(__GNUG__)
# define SIMULATE_VERSION_MAJOR DEC(__GNUG__)
#endif
#if defined(__GNUC_MINOR__)
# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__)
#endif
#if defined(__GNUC_PATCHLEVEL__)
# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__)
#endif

#elif defined(__PATHCC__)
# define COMPILER_ID "PathScale"
# define COMPILER_VERSION_MAJOR DEC(__PATHCC__)
# define COMPILER_VERSION_MINOR DEC(__PATHCC_MINOR__)
# if defined(__PATHCC_PATCHLEVEL__)
#  define COMPILER_VERSION_PATCH DEC(__PATHCC_PATCHLEVEL__)
# endif

#elif defined(__BORLANDC__) && defined(__CODEGEARC_VERSION__)
# define COMPILER_ID "Embarcadero"
# define COMPILER_VERSION_MAJOR HEX(__CODEGEARC_VERSION__>>24 & 0x00FF)
# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF)
# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__     & 0xFFFF)

#elif defined(__BORLANDC__)
# define COMPILER_ID "Borland"
/* __BORLANDC__ = 0xVRR */
# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8)
# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF)

#elif defined(__WATCOMC__) && __WATCOMC__ < 1200
# define COMPILER_ID "Watcom"
/* __WATCOMC__ = VVRR */
# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100)
# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10)
# if (__WATCOMC__ % 10) > 0
#  define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10)
# endif

#elif defined(__WATCOMC__)
# define COMPILER_ID "OpenWatcom"
/* __WATCOMC__ = VVRP + 1100 */
# defi


#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <chrono>
#include <iomanip>
#include <libgnss++/algorithms/spp.hpp>
#include <libgnss++/core/types.hpp>
#include <libgnss++/io/rinex.hpp>

using namespace libgnss;

struct PositioningConfig {
    std::string obs_file;
    std::string nav_file;
    std::string output_file = "spp_results.pos";
    bool enable_rtk = false;
    double snr_mask = 30.0;
    double elevation_mask = 5.0; // degrees
    int max_epochs = -1; // -1 = all epochs
    bool verbose = false;
};

void print_usage(const char* program_name) {
    std::cout << "Usage: " << program_name << " [options]\n"
              << "Options:\n"
              << "  -obs <file>     RINEX observation file\n"
              << "  -nav <file>     RINEX navigation file\n"
              << "  -o <file>       Output POS file (default: spp_results.pos)\n"
              << "  --rtk           Enable RTK processing (default: SPP only)\n"
              << "  --snr <value>   SNR mask in dB (default: 30.0)\n"
              << "  --elev <value>  Elevation mask in degrees (default: 5.0)\n"
              << "  --max-epochs <n> Maximum epochs to process (default: all)\n"
              << "  --verbose       Verbose output\n"
              << "  -h, --help      Show this help\n";
}

PositioningConfig parse_arguments(int argc, char* argv[]) {
    PositioningConfig config;

    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];

        if (arg == "-h" || arg == "--help") {
            print_usage(argv[0]);
            exit(0);
        } else if (arg == "-obs" && i + 1 < argc) {
            config.obs_file = argv[++i];
        } else if (arg == "-nav" && i + 1 < argc) {
            config.nav_file = argv[++i];
        } else if (arg == "-o" && i + 1 < argc) {
            config.output_file = argv[++i];
        } else if (arg == "--rtk") {
            config.enable_rtk = true;
        } else if (arg == "--snr" && i + 1 < argc) {
            config.snr_mask = std::stod(argv[++i]);
        } else if (arg == "--elev" && i + 1 < argc) {
            config.elevation_mask = std::stod(argv[++i]);
        } else if (arg == "--max-epochs" && i + 1 < argc) {
            config.max_epochs = std::stoi(argv[++i]);
        } else if (arg == "--verbose") {
            config.verbose = true;
        } else {
            std::cerr << "Unknown argument: " << arg << std::endl;
            print_usage(argv[0]);
            exit(1);
        }
    }

    if (config.obs_file.empty() || config.nav_file.empty()) {
        std::cerr << "Error: Both observation and navigation files are required" << std::endl;
        print_usage(argv[0]);
        exit(1);
    }

    return config;
}

void write_pos_header(std::ofstream& file, bool rtk_enabled) {
    file << "% POS file generated by LibGNSS++ SPP" << (rtk_enabled ? "/RTK" : "") << " Processor\n";
    file << "% Format: GPST latitude(deg) longitude(deg) height(m) Q ns sdn sde sdu sdne sdeu sdun age ratio\n";
    file << "%\n";
    file << "% Q: 1=FIXED, 2=FLOAT, 4=DGPS, 5=SPP\n";
    file << "% ns: number of satellites\n";
    file << "% sdn,sde,sdu: standard deviation (m)\n";
    file << "% sdne,sdeu,sdun: correlation\n";
    file << "% age: age of differential (s)\n";
    file << "% ratio: ambiguity ratio\n";
    file << "%\n";
}

void write_solution(std::ofstream& file, const PositionSolution& solution) {
    if (!solution.isValid()) return;

    // Convert ECEF to geodetic
    auto geodetic = spp_utils::ecefToGeodetic(solution.position_ecef);

    // Convert time to GPS week/TOW
    int week = solution.time.week;
    double tow = solution.time.tow;

    // Quality mapping
    int quality = 5; // Default to SPP
    switch (solution.status) {
        case SolutionStatus::FIXED: quality = 1; break;
        case SolutionStatus::FLOAT: quality = 2; break;
        case SolutionStatus::DGPS: quality = 4; break;
        case SolutionStatus::SPP: quality = 5; break;
        default: quality = 0; break;
    }

    file << std::fixed << std::setprecision(3);
    file << week << " " << tow << " ";
    file << std::setprecision(9);
    file << geodetic.latitude * 180.0 / M_PI << " ";
    file << geodetic.longitude * 180.0 / M_PI << " ";
    file << std::setprecision(4);
    file << geodetic.height << " ";
    file << quality << " " << solution.num_satellites << " ";
    file << std::setprecision(4);
    file << "0.1000 "; // Default std dev for SPP
    file << "0.1000 ";
    file << "0.2000 "; // Vertical typically worse
    file << "0.0000 0.0000 0.0000 "; // Correlations (not computed)
    file << "0.0 "; // Age
    file << "0.0"; // Ratio
    file << std::endl;
}

int main(int argc, char* argv[]) {
    try {
        PositioningConfig config = parse_arguments(argc, argv);

        std::cout << "LibGNSS++ " << (config.enable_rtk ? "RTK" : "SPP") << " Positioning\n";
        std::cout << "===================================


#include <iostream>
#include "cpp_core/image_io.hpp"
#include "cpp_core/image_processor.hpp"

using namespace cpp_core;

int main() {
    // ---------------- Load image ----------------
    VipsError err;
    VImage img = ImageIO::LoadFromFile("input.jpg", &err);
    if (!img) {
        std::cerr << "Failed to load image: " << err.message << "\n";
        return 1;
    }
    std::cout << "Loaded image: " << img.filename()
              << " (" << img.width() << "x" << img.height() << ")\n";

    // ---------------- Process: Resize ----------------
    ImageProcessor processor;
    processor.SetImage(std::move(img));

    cpp_core::ResizeOptions resize_opts{600, 600}; // resize width=800, height=600
    if (!processor.Resize(resize_opts)) {
        std::cerr << "Resize failed\n";
        return 1;
    }

    VImage& result = processor.GetImage(); // Lấy ảnh đã resize

    // ---------------- Save to file ----------------
    cpp_core::SaveOptions save_opts;
    save_opts.format = ImageFormat::JPEG;
    save_opts.quality = 90;
    save_opts.progressive = true;
    save_opts.strip = true;

    if (!ImageIO::SaveToFile(result, "resized_output.jpg", save_opts, &err)) {
        std::cerr << "Failed to save resized image: " << err.message << "\n";
        return 1;
    }

    std::cout << "Saved resized image to resized_output.jpg\n";
    return 0;
}


#include "utils.h"

#include <flutter_windows.h>
#include <io.h>
#include <stdio.h>
#include <windows.h>

#include <iostream>

void CreateAndAttachConsole() {
  if (::AllocConsole()) {
    FILE *unused;
    if (freopen_s(&unused, "CONOUT$", "w", stdout)) {
      _dup2(_fileno(stdout), 1);
    }
    if (freopen_s(&unused, "CONOUT$", "w", stderr)) {
      _dup2(_fileno(stdout), 2);
    }
    std::ios::sync_with_stdio();
    FlutterDesktopResyncOutputStreams();
  }
}

std::vector<std::string> GetCommandLineArguments() {
  // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use.
  int argc;
  wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
  if (argv == nullptr) {
    return std::vector<std::string>();
  }

  std::vector<std::string> command_line_arguments;

  // Skip the first argument as it's the binary name.
  for (int i = 1; i < argc; i++) {
    command_line_arguments.push_back(Utf8FromUtf16(argv[i]));
  }

  ::LocalFree(argv);

  return command_line_arguments;
}

std::string Utf8FromUtf16(const wchar_t* utf16_string) {
  if (utf16_string == nullptr) {
    return std::string();
  }
  unsigned int target_length = ::WideCharToMultiByte(
      CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
      -1, nullptr, 0, nullptr, nullptr)
    -1; // remove the trailing null character
  int input_length = (int)wcslen(utf16_string);
  std::string utf8_string;
  if (target_length == 0 || target_length > utf8_string.max_size()) {
    return utf8_string;
  }
  utf8_string.resize(target_length);
  int converted_length = ::WideCharToMultiByte(
      CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
      input_length, utf8_string.data(), target_length, nullptr, nullptr);
  if (converted_length == 0) {
    return std::string();
  }
  return utf8_string;
}


// interp_json.cpp
#include <string>
#include <vector>
#include <algorithm>
#include <regex>
#include <iomanip>
#include <sstream>
#include <cctype>

using namespace std;

// ---------- Polynomial helpers ----------
vector<long double> polyMul(const vector<long double>& P, long double a) {
    int n = (int)P.size();
    vector<long double> R(n+1, 0.0L);
    for (int i = 0; i < n; ++i) {
        R[i+1] += P[i];
        R[i]   -= P[i] * a;
    }
    return R;
}
vector<long double> polyScale(const vector<long double>& P, long double c) {
    vector<long double> R = P;
    for (auto &v : R) v *= c;
    return R;
}
vector<long double> polyAdd(const vector<long double>& A, const vector<long double>& B) {
    vector<long double> R(max(A.size(), B.size()), 0.0L);
    for (size_t i = 0; i < A.size(); ++i) R[i] += A[i];
    for (size_t i = 0; i < B.size(); ++i) R[i] += B[i];
    return R;
}

// ---------- Base conversion (to long double) ----------
long double convertBase(const string& s, int base) {
    long double val = 0.0L;
    for (char ch : s) {
        if (isspace((unsigned char)ch)) continue;
        int digit;
        if (ch >= '0' && ch <= '9') digit = ch - '0';
        else if (ch >= 'a' && ch <= 'z') digit = 10 + (ch - 'a');
        else if (ch >= 'A' && ch <= 'Z') digit = 10 + (ch - 'A');
        else continue;
        val = val * base + digit;
    }
    return val;
}

// ---------- Simple JSON extraction ----------
struct Entry { int idx; int base; string value; };

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    // read whole stdin into a string
    string json, line;
    while (getline(cin, line)) {
        json += line;
        json.push_back('\n');
    }

    // extract n and k
    int n = 0, k = 0;
    {
        smatch m;
        if (regex_search(json, m, regex(R"("n"\s*:\s*(\d+))"))) n = stoi(m[1].str());
        if (regex_search(json, m, regex(R"("k"\s*:\s*(\d+))"))) k = stoi(m[1].str());
    }
    if (k <= 0) {
        cerr << "Could not find k in the JSON input.\n";
        return 1;
    }

    // extract entries like "1": { "base":"6", "value":"...." }
    vector<Entry> entries;
    regex entry_re(R"("(\d+)"\s*:\s*\{[^}]*"base"\s*:\s*"(\d+)"[^}]*"value"\s*:\s*"([^"]+)")",
                   regex::ECMAScript | regex::icase);
    for (sregex_iterator it(json.begin(), json.end(), entry_re), end; it != end; ++it) {
        int idx = stoi((*it)[1].str());
        int base = stoi((*it)[2].str());
        string value = (*it)[3].str();
        entries.push_back({idx, base, value});
    }

    if ((int)entries.size() < k) {
        cerr << "Found only " << entries.size() << " entries but k = " << k << ".\n";
        return 1;
    }

    sort(entries.begin(), entries.end(), [](const Entry& a, const Entry& b){ return a.idx < b.idx; });

    // prepare first k points (x = index, y = converted value)
    vector<long double> x(k), y(k);
    for (int i = 0; i < k; ++i) {
        x[i] = entries[i].idx;
        y[i] = convertBase(entries[i].value, entries[i].base);
    }

    // Lagrange interpolation to get polynomial coefficients degree k-1
    vector<long double> poly(k, 0.0L);
    for (int i = 0; i < k; ++i) {
        vector<long double> Li = {1.0L};
        long double denom = 1.0L;
        for (int j = 0; j < k; ++j) if (j != i) {
            Li = polyMul(Li, x[j]);
            denom *= (x[i] - x[j]);
        }
        Li = polyScale(Li, y[i] / denom);
        poly = polyAdd(poly, Li);
    }

    cout << "Polynomial coefficients (a0 + a1*x + a2*x^2 + ...):\n";
    cout << fixed << setprecision(10);
    for (size_t i = 0; i < poly.size(); ++i) {
        if (i) cout << " ";
        cout << poly[i];
    }
    cout << "\n";
    return 0;
}


#include "LoginState.h"
#include "MainMenuState.h"
#include "../Core/StateManager.h"
#include <raylib.h>
#include <cstring>

void LoginState::Update(StateManager &manager)
{
    mouseOnText = CheckCollisionPointRec(GetMousePosition(), textbox);

    if (mouseOnText)
    {
        int key = GetCharPressed();
        while (key > 0)
        {
            int len = strlen(input);
            if (key >= 32 && key <= 125 && len < 31)
            {
                input[len] = (char)key;
                input[len + 1] = '\0';
            }
            key = GetCharPressed();
        }

        if (IsKeyPressed(KEY_BACKSPACE) || IsKeyPressedRepeat(KEY_BACKSPACE))
        {
            int len = strlen(input);
            if (len > 0)
                input[len - 1] = '\0';
        }
    }

    if (IsKeyPressed(KEY_ENTER)) {
        if (strlen(input) > 0) {
            UserManager::Instance().SetUsername(input);
            manager.SetState(new MainMenuState());
        }
    }
}

void LoginState::Draw()
{
    DrawText("Nhap ten nguoi choi:", 300, 150, 20, DARKGRAY);
    DrawRectangleRec(textbox, LIGHTGRAY);
    DrawText(input, (int)textbox.x + 5, (int)textbox.y + 8, 20, BLACK);
    if (mouseOnText) DrawText("Nhap ten va Enter de xac nhan", 300, 250, 18, GRAY);
}


#include "sc_servo.h"

SCSCL sc;

SCServo::SCServo(u8 servoId) {
  SCServo::init();
  _id = servoId;
  _angleGoal = -1;
}

void SCServo::init() {
  if (!Serial1) {
    Serial1.begin(1000000, SERIAL_8N1, S_RXD, S_TXD);
    while(!Serial1) {};
  }
  if (!sc.pSerial) sc.pSerial = &Serial1;
}

bool SCServo::ping(u8 id) {
  SCServo::init();
  return (sc.Ping(id) == id);
}

void SCServo::enableWheelMode() {
  _wheelEnabled = true;
  sc.PWMMode(_id);
}

bool SCServo::wheelMode() {
  return _wheelEnabled;
}

void SCServo::wheelSpeed( int value) {
  if (!wheelMode()) enableWheelMode();
  _wheelSpeed = value;
  sc.WritePWM(_id, value);
}

int SCServo::wheelSpeed() {
  return _wheelSpeed;
}

void SCServo::torque(bool enabled) {
  sc.EnableTorque(_id, enabled);
  _torque = enabled;
}

bool SCServo::torque() {
  return _torque;
}

void SCServo::writePos(u16 pos, u16 time, u16 speed) {
  if (_wheelEnabled) return;
  sc.WritePos(_id, pos, time, speed);
}

void SCServo::changeId(u8 newId) {
  sc.unLockEprom(_id);
  sc.writeByte(_id, SCSCL_ID, newId);
  sc.LockEprom(newId);
  _id = newId;
}

bool SCServo::feedback() {
  return (sc.FeedBack(_id) > 0);
}

int SCServo::readPos(bool fromFeedback) {
  int id = (fromFeedback) ? -1 : _id;
  return sc.ReadPos(id);
}

int SCServo::readSpeed(bool fromFeedback) {
  int id = (fromFeedback) ? -1 : _id;
  return sc.ReadSpeed(id);
}

int SCServo::readLoad(bool fromFeedback) {
  int id = (fromFeedback) ? -1 : _id;
  return sc.ReadLoad(id);
}

int SCServo::readVoltage(bool fromFeedback) {
  int id = (fromFeedback) ? -1 : _id;
  return sc.ReadVoltage(id);
}

int SCServo::readTemper(bool fromFeedback) {
  int id = (fromFeedback) ? -1 : _id;
  return sc.ReadTemper(id);
}

int SCServo::readMove(bool fromFeedback) {
  int id = (fromFeedback) ? -1 : _id;
  return sc.ReadMove(id);
}

u8 SCServo::getId() {
  return _id;
}

void SCServo::stopServo() {
  sc.WritePos(_id, sc.ReadPos(_id), 0, 0);
  _angleGoal = -1;
}

void SCServo::update() {
  if (_angleGoal >= 0) {
    if (!readMove(false)) {
      if (callback) {
        String s = String("Ziel ") + String(getAngle(),2) + " erreicht.";
        callback(_id, CB_GOTO_ANGLE, 0, _angleGoal, s.c_str());
      }
      _angleGoal = -1;
    }
  }
}

void SCServo::setCallback(ServoCallback cb) {
  callback = cb;;
}

float SCServo::posToAngle(int pos) {
  return float(pos) * float(rotAngle) / float(rotValues-1) -5;
  // pos 20 -> 5 / 0
  // pos 1003 -> 293 /

  // 0 * 300 / 1023 -> 0
  // 1023 * 300 / 1023
}

int SCServo::angleToPos(float angle) {
  return int((angle+5) * (rotValues-1) / rotAngle)+1;
  // Winkel 0 -> 20
  // Winkel 292 -> 1003
  // 0 * 1023 / 300 -> 0
  // 300 * 1023 / 300 -> 1023
}

void SCServo::gotoPos(int pos, int speed) {
  int fromPos = readPos(false);
  if (pos == fromPos) {
    // Serial.println("callback 1");
    // callback(_id, CB_GOTO_ANGLE, 0, angle, "Keine Bewegung notwendig");
    return;
  }
  if (speed == 0) {  // maximale Geschwindigkeit
    writePos(pos, 0, 0);
    while (!readMove(false)) delay(1);
    Serial.println("ohne callback, max speed");
    return;
  }
  writePos(pos, 0, speed);
}

void SCServo::gotoAngle(float angle, int speed) {
  gotoPos(angleToPos(angle), speed);
}

float SCServo::getAngle() {
  int pos = readPos(false);
  return posToAngle(pos);
};

int SCServo::getPos() {
  return readPos(false);
};

void SCServo::setMaxLoad(u16 max_load) {

}


#include "user.h"
#include <fstream>
#include <iostream>
#include <sstream>

// define the global users vector here
std::vector<User> users;

// ---- USERS FILE I/O ----
const std::string USERS_FILE = "users.txt";

void saveUsers() {
    std::ofstream out(USERS_FILE);
    if (!out.is_open()) return;
    for (auto &u : users) {
        out << u.serialize() << "\n";
    }
    out.close();
}

void loadUsers() {
    users.clear();
    std::ifstream in(USERS_FILE);
    if (!in.is_open()) return;
    std::string line;
    while (std::getline(in, line)) {
        if (line.empty()) continue;
        users.push_back(User::deserialize(line));
    }
    in.close();
}

// ensure a hardcoded admin exists (admin is not removed)
void ensureAdmin() {
    bool found = false;
    for (auto &u : users) if (u.role == "Admin") { found = true; break; }
    if (!found) {
        users.push_back(User("admin", "admin123", "Admin", "", "Administrator"));
        saveUsers();
    }
}

// call this at program start
void seedUsers() {
    loadUsers();
    ensureAdmin();
}

// returns pointer to user in users vector, or nullptr
User* login(const std::string &id, const std::string &pass) {
    for (auto &u : users) {
        if (u.id == id && u.password == pass) return &u;
    }
    return nullptr;
}

// registers a new student (returns pointer or nullptr if id exists)
User* registerStudent(const std::string &name, const std::string &uid, const std::string &pass, const std::string &dept) {
    for (auto &u : users) if (u.id == uid) return nullptr; // id exists
    users.push_back(User(uid, pass, "Student", dept, name));
    saveUsers();
    return &users.back();
}

// admin creates faculty
bool createFaculty(const std::string &fid, const std::string &pass, const std::string &dept, const std::string &name) {
    for (auto &u : users) if (u.id == fid) return false; // already exists
    users.push_back(User(fid, pass, "Faculty", dept, name));
    saveUsers();
    return true;
}


#include "main.h"
#include "lemlib/api.hpp" // IWYU pragma: keep
#include "lemlib/asset.hpp"
#include "lemlib/chassis/chassis.hpp"
#include "lemlib/chassis/trackingWheel.hpp"
#include "pros/adi.hpp"
#include "pros/misc.h"
#include "pros/motors.h"
#include "pros/motors.hpp"
#include "pros/rtos.hpp"
#include <cstddef>

std::string TEAM_COLOR = "blue";

// controller
pros::Controller controller(pros::E_CONTROLLER_MASTER);

// motor groups
pros::MotorGroup leftMotors({-1, -2, -3},
                            pros::MotorGearset::blue); // left motor group - ports 3 (reversed), 4, 5 (reversed)
pros::MotorGroup rightMotors({4, 5, 6}, pros::MotorGearset::blue); // right motor group - ports 6, 7, 9 (reversed)

// pneumatics

// pros::adi::AnalogOut clamp_pneumatic = pros::adi::AnalogOut('A');
// pros::adi::AnalogOut doinker_pneumatic = pros::adi::AnalogOut('B');

pros::adi::Pneumatics clamp_pneumatic('a', false);
pros::adi::Pneumatics doinker_pneumatic('b', false);

// motors

pros::Motor intake_roller = pros::Motor(7);
pros::Motor intake_chain = pros::Motor(8);
pros::Motor lady_brown = pros::Motor(9);

//

// pros::adi::AnalogIn encoder({'C', 'D'});
pros::adi::Encoder encoder ('C', 'D');

pros::Optical optical(11);

// // Inertial Sensor on port 10
pros::Imu imu(15);

// // tracking wheels
// // horizontal tracking wheel encoder. Rotation sensor, port 20, not reversed
// pros::Rotation horizontalEnc(20);
// // vertical tracking wheel encoder. Rotation sensor, port 11, reversed
// pros::Rotation verticalEnc(-11);
// // horizontal tracking wheel. 2.75" diameter, 5.75" offset, back of the robot (negative)
// lemlib::TrackingWheel horizontal(&horizontalEnc, lemlib::Omniwheel::NEW_275, -5.75);
// // vertical tracking wheel. 2.75" diameter, 2.5" offset, left of the robot (negative)
// lemlib::TrackingWheel vertical(&verticalEnc, lemlib::Omniwheel::NEW_275, -2.5);

// drivetrain settings
lemlib::Drivetrain drivetrain(&leftMotors, // left motor group
                              &rightMotors, // right motor group
                              13, // 10 inch track width
                              lemlib::Omniwheel::NEW_325, // using new 4" omnis
                              450, // drivetrain rpm is 450
                              2 // horizontal drift is 2. If we had traction wheels, it would have been 8
);

// lateral motion controller
lemlib::ControllerSettings linearController(10, // proportional gain (kP)
                                            0, // integral gain (kI)
                                            3, // derivative gain (kD)
                                            3, // anti windup
                                            1, // small error range, in inches
                                            100, // small error range timeout, in milliseconds
                                            3, // large error range, in inches
                                            500, // large error range timeout, in milliseconds
                                            20 // maximum acceleration (slew)
);

// angular motion controller
lemlib::ControllerSettings angularController(2, // proportional gain (kP)
                                             0, // integral gain (kI)
                                             10, // derivative gain (kD)
                                             3, // anti windup
                                             1, // small error range, in degrees
                                             100, // small error range timeout, in milliseconds
                                             3, // large error range, in degrees
                                             500, // large error range timeout, in milliseconds
                                             0 // maximum acceleration (slew)
);

// sensors for odometry
// lemlib::OdomSensors sensors(&vertical, // vertical tracking wheel
//                             nullptr, // vertical tracking wheel 2, set to nullptr as we don't have a second one
//                             &horizontal, // horizontal tracking wheel
//                             nullptr, // horizontal tracking wheel 2, set to nullptr as we don't have a second one
//                             &imu // inertial sensor
// );

lemlib::OdomSensors sensors(nullptr, nullptr, nullptr,nullptr,&imu);

// input curve for throttle input during driver control
lemlib::ExpoDriveCurve throttleCurve(3, // joystick deadband out of 127
                                     10, // minimum output where drivetrain will move out of 127
                                     1.019 // expo curve gain
);

// input curve for steer input during driver control
lemlib::ExpoDriveCurve steerCurve(3, // joystick deadband out of 127
                                  10, // minimum output where drivetrain will move out of 127
                                  1.019 // expo curve gain
);

// create the chassis
lemlib::Chassis chassis(drivetrain, linearController,


#include <Windows.h>
#include <TlHelp32.h>
#include <iostream>
#include <Psapi.h>
#include <filesystem>
#include "cxxopts.hpp"

BOOL CALLBACK EnumWindowsProc(
	_In_ HWND   hwnd,
	_In_ LPARAM lParam
) {
	DWORD aff;
	GetWindowDisplayAffinity(hwnd, &aff);

	if (aff != WDA_NONE) {
		DWORD pid;
		GetWindowThreadProcessId(hwnd, &pid);

		HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
		char name[MAX_PATH + 1];
		GetModuleFileNameExA(hProc, nullptr, name, MAX_PATH);

		std::cout << "Found interesting process: " << name << " (PID " << pid <<  ") (Affinity: " << aff << ")" << std::endl;

		CloseHandle(hProc);
	}

	return TRUE;
}

// Find a process ID by PID or by its target image name (either one matching will return)
// Finding a PID by PID may seem redundant at first, but this verifies that such a process is running
int FindProcessPid(int target_pid, const char* target_image_name) {
	HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hSnap == INVALID_HANDLE_VALUE) {
		std::cout << "Failed to create snapshot handle: " << GetLastError() << std::endl;
		return -1;
	}

	PROCESSENTRY32 pe32;
	pe32.dwSize = sizeof(PROCESSENTRY32); // thanks windows. why do I need to do this? You *know* the size of- you know what, doesn't matter.

	if (!Process32First(hSnap, &pe32)) {
		CloseHandle(hSnap);
		std::cout << "Failed to read first process: " << GetLastError() << std::endl;
		return -1;
	}

	int pid = -1;

	do {
		if (!strcmp(pe32.szExeFile, target_image_name) || pe32.th32ProcessID == target_pid) {
			pid = pe32.th32ProcessID;
			break;
		}
	} while (Process32Next(hSnap, &pe32));

	CloseHandle(hSnap);

	return pid;
}

int main(int argc, char* argv[]) {
	// Argument parsing stuff
	cxxopts::Options options("Displayinator", "Locate and manage window Display Affinity values");

	options.add_options()
		("l,list-processes", "List processes with a non-zero display affinity value")
		("p,pid", "The PID of the process whose display affinity you wish to set to zero", cxxopts::value<int>())
		("f,filename", "The name of the image file whose display affinity you wish to set to zero (eg explorer.exe)", cxxopts::value<std::string>())
		("h,help", "Print usage")
		;

	auto result = options.parse(argc, argv);

	if (result.count("help"))
	{
		std::cout << options.help() << std::endl;
		return 0;
	}

	if (result["list-processes"].as<bool>()) {
		EnumWindows(EnumWindowsProc, 0);
		std::cout << "Finished enumerating processes" << std::endl;
		return 0;
	}

	const char* target_name = "";
	if (result.count("filename")) {
		target_name = (result["filename"].as<std::string>()).c_str();
	}

	int target_pid = -1;
	if (result.count("pid")) {
		target_pid = result["pid"].as<int>();
	}

	if (strlen(target_name) == 0 && target_pid == 0) {
		std::cout << "Invalid usage, try --help for instructions.";
		return 1;
	}

	std::cout << "Looking for process to inject" << std::endl;

	int pid = FindProcessPid(target_pid, target_name);

	if (pid == -1) {
		std::cout << "Failed to find or open process" << std::endl;
		return 1;
	}

	// The path to the DLL we're going to inject.
	// Note: We don't verify that this exists currently. Future improvement?
	std::string dllPath = std::filesystem::current_path().string().append("\\InjectedDLL.dll");

	std::cout << "Found proc: " << pid << std::endl;

	// Standard injection stuff
	HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
	if (!hProc || hProc == INVALID_HANDLE_VALUE) {
		std::cout << "Failed to open process: " << GetLastError() << std::endl;
		return 1;
	}

	void* loc = VirtualAllocEx(hProc, 0, MAX_PATH, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
	if (loc == 0) {
		std::cout << "Failed to allocate memory: " << GetLastError() << std::endl;
		return 1;
	}

	if (!WriteProcessMemory(hProc, loc, dllPath.c_str(), strlen(dllPath.c_str()) + 1, 0)) {
		std::cout << "Failed to write process memory: " << GetLastError() << std::endl;
		return 1;
	}

	if (!CreateRemoteThread(hProc, 0, 0, (LPTHREAD_START_ROUTINE)LoadLibraryA, loc, 0, 0)) {
		std::cout << "Couldn't create remote thread: " << GetLastError() << std::endl;
		return 1;
	}

	std::cout << "Success!" << std::endl;
}


#include <machine.hpp>
#include <math.h>
#include <iostream>

void execute(doytVM machine){
    while (machine.i_inx < machine.ins.size()){
        auto instr = machine.current();

        switch (instr.code){
            // Binary Arithmetic
            case Opcode::ADD: { machine.reg[instr.c] = machine.reg[instr.a] + machine.reg[instr.b]; break; }
            case Opcode::SUB: { machine.reg[instr.c] = machine.reg[instr.a] - machine.reg[instr.b]; break; }
            case Opcode::MUL: { machine.reg[instr.c] = machine.reg[instr.a] * machine.reg[instr.b]; break; }
            case Opcode::DIV: { machine.reg[instr.c] = machine.reg[instr.a] / machine.reg[instr.b]; break; }
            case Opcode::MOD: { machine.reg[instr.c] = std::fmod(machine.reg[instr.a], (int)machine.reg[instr.b]); break; }

            // Unary Math
            case Opcode::SQRT:{ machine.reg[instr.c] = std::sqrt(machine.reg[instr.a]); break; }
            case Opcode::EXP: { machine.reg[instr.c] = std::exp (machine.reg[instr.a]); break; }
            case Opcode::NEG: { machine.reg[instr.c] = -machine.reg[instr.a]; break; }
            case Opcode::LN:  { machine.reg[instr.c] = std::log(machine.reg[instr.a]); break; }

            // Compound Asignment
            case Opcode::sADD:{ machine.reg[instr.c] += machine.reg[instr.a]; break; }
            case Opcode::sSUB:{ machine.reg[instr.c] -= machine.reg[instr.a]; break; }
            case Opcode::sMUL:{ machine.reg[instr.c] *= machine.reg[instr.a]; break; }
            case Opcode::sDIV:{ machine.reg[instr.c] /= machine.reg[instr.a]; break; }
            case Opcode::sMOD:{ machine.reg[instr.c] = std::fmod(machine.reg[instr.c], machine.reg[instr.a]); }

            case Opcode::PRINT:{ std::cout << machine.reg[instr.a] << '\n'; }
        };

        machine.advance();
    };
};


//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Base VoteController.  Handles holding and voting on issues.
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "vote_controller.h"
#include "shareddefs.h"
#include "eiface.h"
#include "team.h"
#include "gameinterface.h"
#include "fmtstr.h"

#ifdef TF_DLL
#include "tf/tf_gamerules.h"
#include "tf/tf_voteissues.h"
#endif

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

#define MAX_VOTER_HISTORY 64

// Datatable
IMPLEMENT_SERVERCLASS_ST( CVoteController, DT_VoteController )
	SendPropInt( SENDINFO( m_iActiveIssueIndex ) ),
	SendPropInt( SENDINFO( m_iOnlyTeamToVote ) ),
	SendPropArray3( SENDINFO_ARRAY3( m_nVoteOptionCount ), SendPropInt( SENDINFO_ARRAY( m_nVoteOptionCount ), 8, SPROP_UNSIGNED ) ),
	SendPropInt( SENDINFO( m_nPotentialVotes ) ),
	SendPropBool( SENDINFO( m_bIsYesNoVote ) )
END_SEND_TABLE()

BEGIN_DATADESC( CVoteController )
	DEFINE_THINKFUNC( VoteControllerThink ),
END_DATADESC()

LINK_ENTITY_TO_CLASS( vote_controller, CVoteController );

CVoteController *g_voteController = NULL;

ConVar sv_vote_timer_duration( "sv_vote_timer_duration", "15", FCVAR_DEVELOPMENTONLY, "How long to allow voting on an issue" );
ConVar sv_vote_command_delay( "sv_vote_command_delay", "2", FCVAR_DEVELOPMENTONLY, "How long after a vote passes until the action happens", false, 0.f, true, 4.5f );
ConVar sv_allow_votes( "sv_allow_votes", "1", FCVAR_NONE, "Allow voting?" );
ConVar sv_vote_failure_timer( "sv_vote_failure_timer", "300", FCVAR_NONE, "A vote that fails cannot be re-submitted for this long" );
#ifdef TF_DLL
ConVar sv_vote_failure_timer_mvm( "sv_vote_failure_timer_mvm", "120", FCVAR_NONE, "A vote that fails in MvM cannot be re-submitted for this long" );
#endif // TF_DLL
ConVar sv_vote_creation_timer( "sv_vote_creation_timer", "150", FCVAR_NONE, "How long before a player can attempt to call another vote (in seconds)." );
ConVar sv_vote_quorum_ratio( "sv_vote_quorum_ratio", "0.6", FCVAR_NOTIFY, "The minimum ratio of eligible players needed to pass a vote.  Min 0.5, Max 1.0.", true, 0.1f, true, 1.0f );
ConVar sv_vote_allow_spectators( "sv_vote_allow_spectators", "0", FCVAR_NONE, "Allow spectators to vote?" );
ConVar sv_vote_ui_hide_disabled_issues( "sv_vote_ui_hide_disabled_issues", "1", FCVAR_NONE, "Suppress listing of disabled issues in the vote setup screen." );

static const int k_nKickWatchListMaxDuration = 300;

//-----------------------------------------------------------------------------
// Purpose: Game system to detect maps without cameras in them, and move on
//-----------------------------------------------------------------------------
class CVoteControllerSystem : public CAutoGameSystemPerFrame
{
public:
	CVoteControllerSystem( char const *name ) : CAutoGameSystemPerFrame( name )
	{
		SetDefLessFunc( m_mapKickWatchList );
		SetDefLessFunc( m_mapNameLockedList );
		m_flNextKickCheckTime = 0.f;
		m_flNextNameLockCheckTime = 0.f;
	}

	virtual void LevelInitPreEntity()
	{
	}

	virtual void FrameUpdatePostEntityThink( void )
	{
		// Executing the vote controller command needs to happen in the PostEntityThink as it can restart levels and
		//	blast entities, etc. If you're doing this during a regular think, this can cause entities thinking after
		//	you in Physics_RunThinkFunctions() to get grumpy and crash.
		if ( g_voteController )
		{
			// Vote passed - execute the command
			if ( g_voteController->m_executeCommandTimer.HasStarted() && g_voteController->m_executeCommandTimer.IsElapsed() )
			{
				g_voteController->m_executeCommandTimer.Invalidate();
				g_voteController->m_potentialIssues[g_voteController->m_iActiveIssueIndex]->ExecuteCommand();
			}

			// Kick watch
			if ( m_flNextKickCheckTime < gpGlobals->curtime )
			{
				FOR_EACH_MAP( m_mapKickWatchList, i )
				{
					if ( gpGlobals->curtime > m_mapKickWatchList[i] )
					{
						m_mapKickWatchList.RemoveAt( i );
						break;	// Constantly called code - resume on next pass
					}

					CBasePlayer *pTarget = UTIL_PlayerBySteamID( m_mapKickWatchList.Key( i ) );
					if ( pTarget )
					{
						// Welcome back
						engine->ServerCommand( CFmtStr( "kickid %d %s;", pTarget->GetUserID(), "Kicked by server." ) );
					}
				}

				m_flNextKickCheckTime = gpGlobals->curtime + 0.2f;
			}

			// Name lock management
			if ( m_flNextNameLockCheckTime < gpGlobals->curtime )
			{
				FOR_EACH_MAP( m_mapNameLockedList, i )
				{
					CBasePlayer *pPlayer = UTIL_PlayerBySteamID( m_mapNameLockedList.Key( i ) );

					// Time up?
					if ( gpGlobals->curtime > m_mapNameLockedList[i] )
					{
						// Disable the lock if they're still here
						if ( pPlayer )
						{
							engine->ServerCommand( UTIL_VarArgs( "namelockid %d %d\


#include <iostream>
#include <vector>
#include <string>
#include <thread>
#include <chrono>
#include <cmath>
#include <random>

// ANSI escape codes for terminal manipulation
// These codes are a standard way to control the cursor and colors in a Unix terminal.
#define CLEAR_SCREEN "\033[2J"
#define CURSOR_HOME "\033[H"
#define RED_TEXT "\033[31m"
#define GREEN_TEXT "\033[32m"
#define RESET_COLOR "\033[0m"

// Define the characters for our snake and food.
const char FOOD_CHAR = '@'; // Changed for better visibility
const char SNAKE_HEAD_CHAR = 'O'; // Head of the snake
const char SNAKE_BODY_CHAR = 'o'; // Body of the snake
const int FOOD_COUNT = 5;

// A simple struct to represent a point on the grid.
struct Point {
    int x;
    int y;
};

// Function to clear the terminal screen using ANSI escape codes.
void clearScreen() {
    std::cout << CLEAR_SCREEN << CURSOR_HOME;
}

// Function to draw the game world, including the snake and food.
// Now takes a vector of points to represent the entire snake body.
void drawWorld(const std::vector<std::vector<char>>& world, const std::vector<Point>& snakeBody) {
    clearScreen(); // Always clear the screen before redrawing to prevent flickering

    // Create a temporary world to draw the snake on top of the food.
    std::vector<std::vector<char>> displayWorld = world;

    // Draw the snake body.
    if (!snakeBody.empty()) {
        // Draw the head first.
        displayWorld[snakeBody[0].y][snakeBody[0].x] = SNAKE_HEAD_CHAR;

        // Draw the rest of the body.
        for (size_t i = 1; i < snakeBody.size(); ++i) {
            displayWorld[snakeBody[i].y][snakeBody[i].x] = SNAKE_BODY_CHAR;
        }
    }

    // Print the border and the contents of the display world.
    std::cout << "--------------------" << std::endl;
    for (size_t y = 0; y < displayWorld.size(); ++y) {
        std::cout << "| "; // Left border
        for (size_t x = 0; x < displayWorld[y].size(); ++x) {
            if (displayWorld[y][x] == FOOD_CHAR) {
                std::cout << RED_TEXT << displayWorld[y][x] << RESET_COLOR;
            } else if (displayWorld[y][x] == SNAKE_HEAD_CHAR) {
                std::cout << GREEN_TEXT << displayWorld[y][x] << RESET_COLOR;
            } else if (displayWorld[y][x] == SNAKE_BODY_CHAR) {
                std::cout << GREEN_TEXT << displayWorld[y][x] << RESET_COLOR;
            } else {
                std::cout << displayWorld[y][x];
            }
        }
        std::cout << " |" << std::endl; // Right border
    }
    std::cout << "--------------------" << std::endl;
    std::cout << "Snake length: " << snakeBody.size() << std::endl;
}

// Function to find the nearest food item to the snake's head.
Point findNearestFood(const std::vector<std::vector<char>>& world, const Point& snakeHead) {
    Point nearestFood = {-1, -1};
    double minDistance = -1;

    for (size_t y = 0; y < world.size(); ++y) {
        for (size_t x = 0; x < world[y].size(); ++x) {
            if (world[y][x] == FOOD_CHAR) {
                // Calculate the Euclidean distance.
                double distance = std::sqrt(std::pow(x - snakeHead.x, 2) + std::pow(y - snakeHead.y, 2));
                if (nearestFood.x == -1 || distance < minDistance) {
                    minDistance = distance;
                    nearestFood = {static_cast<int>(x), static_cast<int>(y)};
                }
            }
        }
    }
    return nearestFood;
}

// Function to calculate the snake's next move based on the nearest food.
Point getNextMove(const Point& snakePos, const Point& foodPos) {
    Point nextPos = snakePos;

    // Simple greedy algorithm: move one step closer to the food on the x-axis, then the y-axis.
    if (foodPos.x != -1) {
        if (foodPos.x > snakePos.x) {
            nextPos.x++;
        } else if (foodPos.x < snakePos.x) {
            nextPos.x--;
        }

        if (nextPos.x == snakePos.x) {
            if (foodPos.y > snakePos.y) {
                nextPos.y++;
            } else if (foodPos.y < snakePos.y) {
                nextPos.y--;
            }
        }
    }
    return nextPos;
}

// Function to place food randomly on the grid.
void placeFoodRandomly(std::vector<std::vector<char>>& world, const std::vector<Point>& snakeBody) {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> disX(0, world[0].size() - 1);
    std::uniform_int_distribution<> disY(0, world.size() - 1);

    int foodCount = 0;
    while (foodCount < FOOD_COUNT) {
        int x = disX(gen);
        int y = disY(gen);

        // Check if the spot is empty and not part of the snake
        bool isSnake = false;
        for (const auto& segment : snakeBody) {
            if (segment.x == x && segment.y == y) {
                isSnake = true;
                break;
            }
        }

        if (world[y][x] == ' ' && !isSnake) {
            world[y][x] = FOOD_CHAR;
            foodCount++;
        }
    }
}

int main() {
    // De


#include "Util.h"
#include <algorithm>
#include <cctype>
#include <windows.h>

namespace util {

    std::string ToUpper(std::string s) {
        std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return (char)std::toupper(c); });
        return s;
    }

    void Trim(std::string& s) {
        auto issp = [](unsigned char c) { return std::isspace(c); };
        while (!s.empty() && issp(s.front())) s.erase(s.begin());
        while (!s.empty() && issp(s.back()))  s.pop_back();
    }

    std::string W2U8(const std::wstring& ws) {
        if (ws.empty()) return {};
        int len = WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), (int)ws.size(), nullptr, 0, nullptr, nullptr);
        std::string out(len, '\0');
        WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), (int)ws.size(), out.data(), len, nullptr, nullptr);
        return out;
    }

    std::wstring U8ToW(const std::string& s) {
        if (s.empty()) return {};
        int len = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), nullptr, 0);
        std::wstring out(len, L'\0');
        MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), out.data(), len);
        return out;
    }

    bool IsAllZerosOrOnes(const std::string& s) {
        if (s.empty()) return true;
        bool allZ = std::all_of(s.begin(), s.end(), [](char c) { return c == '0'; });
        bool allO = std::all_of(s.begin(), s.end(), [](char c) { return c == '1'; });
        return allZ || allO;
    }

    bool ContainsAny(const std::string& hay, const std::vector<std::string>& needles) {
        for (const auto& n : needles) {
            if (hay.find(n) != std::string::npos) return true;
        }
        return false;
    }

    bool IsGenericJunk(const std::string& v) {
        if (v.empty()) return true;
        auto s = ToUpper(v);
        static const std::vector<std::string> bad = {
            "DEFAULT", "DEFAULT STRING", "DEFAULT-STRING", "N/A", "NA", "NONE", "UNKNOWN",
            "TO BE FILLED BY O.E.M.", "TO BE FILLED BY OEM", "SYSTEM PRODUCT NAME",
            "SYSTEM MANUFACTURER", "123456789", "00000000", "FFFFFFFF"
        };
        if (IsAllZerosOrOnes(s)) return true;
        for (auto& b : bad) if (s == b) return true;
        return false;
    }

    std::string Sanitize(const std::string& in) {
        std::string s = in;
        Trim(s);
        s.erase(std::remove_if(s.begin(), s.end(), [](unsigned char c) {
            return c == '\r' || c == '\n' || c == '\t';
            }), s.end());
        return s;
    }

    std::string Hex(const std::vector<uint8_t>& bytes, bool upper) {
        static const char* hexd = "0123456789abcdef";
        static const char* hexu = "0123456789ABCDEF";
        const char* hx = upper ? hexu : hexd;
        std::string out; out.reserve(bytes.size() * 2);
        for (auto b : bytes) { out.push_back(hx[b >> 4]); out.push_back(hx[b & 0xF]); }
        return out;
    }

    std::string Grouped(const std::string& hex, size_t group) {
        if (group == 0) return hex;
        std::string out; out.reserve(hex.size() + hex.size() / group);
        for (size_t i = 0; i < hex.size(); ++i) {
            if (i > 0 && (i % group) == 0) out.push_back('-');
            out.push_back(hex[i]);
        }
        return out;
    }

}


/*
 *  IXDNSLookup.cpp
 *  Author: Benjamin Sergeant
 *  Copyright (c) 2018 Machine Zone, Inc. All rights reserved.
 */

//
// On Windows Universal Platform (uwp), gai_strerror defaults behavior is to returns wchar_t
// which is different from all other platforms. We want the non unicode version.
// See https://github.com/microsoft/vcpkg/pull/11030
// We could do this in IXNetSystem.cpp but so far we are only using gai_strerror in here.
//
#ifdef _UNICODE
#undef _UNICODE
#endif
#ifdef UNICODE
#undef UNICODE
#endif

#include "IXDNSLookup.h"

#include "IXNetSystem.h"
#include <chrono>
#include <string.h>
#include <thread>
#include <utility>

// mingw build quirks
#if defined(_WIN32) && defined(__GNUC__)
#ifndef AI_NUMERICSERV
#define AI_NUMERICSERV NI_NUMERICSERV
#endif
#ifndef AI_ADDRCONFIG
#define AI_ADDRCONFIG LUP_ADDRCONFIG
#endif
#endif

#ifdef __APPLE__
#ifndef AI_NUMERICSERV
#define AI_NUMERICSERV 0
#endif
#endif

namespace ix
{
    const int64_t DNSLookup::kDefaultWait = 1; // ms

    DNSLookup::DNSLookup(const std::string& hostname, int port, int64_t wait)
        : _hostname(hostname)
        , _port(port)
        , _wait(wait)
        , _res(nullptr)
        , _done(false)
    {
        ;
    }

    DNSLookup::AddrInfoPtr DNSLookup::getAddrInfo(const std::string& hostname,
                                            int port,
                                            std::string& errMsg)
    {
        struct addrinfo hints;
        memset(&hints, 0, sizeof(hints));
        hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;

        std::string sport = std::to_string(port);

        struct addrinfo* res;
        int getaddrinfo_result = getaddrinfo(hostname.c_str(), sport.c_str(), &hints, &res);
        if (getaddrinfo_result)
        {
            errMsg = gai_strerror(getaddrinfo_result);
            res = nullptr;
        }
        return AddrInfoPtr{ res, freeaddrinfo };
    }

    DNSLookup::AddrInfoPtr DNSLookup::resolve(std::string& errMsg,
                                        const CancellationRequest& isCancellationRequested,
                                        bool cancellable)
    {
        return cancellable ? resolveCancellable(errMsg, isCancellationRequested)
                           : resolveUnCancellable(errMsg, isCancellationRequested);
    }

    DNSLookup::AddrInfoPtr DNSLookup::resolveUnCancellable(
        std::string& errMsg, const CancellationRequest& isCancellationRequested)
    {
        errMsg = "no error";

        // Maybe a cancellation request got in before the background thread terminated ?
        if (isCancellationRequested())
        {
            errMsg = "cancellation requested";
            return nullptr;
        }

        return getAddrInfo(_hostname, _port, errMsg);
    }

    DNSLookup::AddrInfoPtr DNSLookup::resolveCancellable(
        std::string& errMsg, const CancellationRequest& isCancellationRequested)
    {
        errMsg = "no error";

        // Can only be called once, otherwise we would have to manage a pool
        // of background thread which is overkill for our usage.
        if (_done)
        {
            return nullptr; // programming error, create a second DNSLookup instance
                            // if you need a second lookup.
        }

        //
        // Good resource on thread forced termination
        // https://www.bo-yang.net/2017/11/19/cpp-kill-detached-thread
        //
        auto ptr = shared_from_this();
        std::weak_ptr<DNSLookup> self(ptr);

        int port = _port;
        std::string hostname(_hostname);

        // We make the background thread doing the work a shared pointer
        // instead of a member variable, because it can keep running when
        // this object goes out of scope, in case of cancellation
        auto t = std::make_shared<std::thread>(&DNSLookup::run, this, self, hostname, port);
        t->detach();

        while (!_done)
        {
            // Wait for 1 milliseconds, to see if the bg thread has terminated.
            // We do not use a condition variable to wait, as destroying this one
            // if the bg thread is alive can cause undefined behavior.
            std::this_thread::sleep_for(std::chrono::milliseconds(_wait));

            // Were we cancelled ?
            if (isCancellationRequested())
            {
                errMsg = "cancellation requested";
                return nullptr;
            }
        }

        // Maybe a cancellation request got in before the bg terminated ?
        if (isCancellationRequested())
        {
            errMsg = "cancellation requested";
            return nullptr;
        }

        errMsg = getErrMsg();
        return getRes();
    }

    void DNSLookup::run(std::weak_ptr<DNSLookup> self,
                        std::string hostname,
                        int port) // thread runner
    {
        // We don't want to read or write


#include "bodies_holder.h"
#include "drawable_body.h"
#include <random>

glm::vec2 getRandomVec2(unsigned int seed, float min, float max) {
    static std::mt19937 gen(seed);
    std::uniform_real_distribution<float> dis(min, max);
    return glm::vec2(dis(gen), dis(gen));
}

Color getRandomColor(unsigned int seed) {
    static std::mt19937 gen(seed);
    std::uniform_int_distribution<uint8_t> dis(0, 255);
    return Color {dis(gen), dis(gen), dis(gen), 255};
}

float getRandomFloat(unsigned int seed, float min, float max) {
    static std::mt19937 gen(seed);
    std::uniform_real_distribution<float> dis(min, max);
    return dis(gen);
}

BodiesHolder::BodiesHolder() {

}

void BodiesHolder::addBody(std::shared_ptr<physics::Body> _body) {
    m_bodies.push_back(std::move(_body));
}

const std::vector<std::shared_ptr<physics::Body>>& BodiesHolder::getBodies() const {
    return m_bodies;
}

void BodiesHolder::generateRandomBodies(size_t number) {
    for (auto i = 0; i < number; ++i) {
        const auto time = static_cast<int>(std::chrono::system_clock::now().time_since_epoch().count());
        const auto pos = getRandomVec2(time, 0, 1280);
        const auto vel = getRandomVec2(time, -10, 10);
        const auto mass = getRandomFloat(time, 10, 100);
        const auto radius = getRandomFloat(time, 1, 3);
        auto color = getRandomColor(time);
        addBody(std::make_shared<DrawableBody>(pos, vel, mass, color, radius));
    }
}


#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup() {
	ofBackground(0);
	ofSetVerticalSync(true);

	// setup audio input (0 output channels, 1 input channel)
	ofSoundStreamSetup(0, 2, this, 44100, beat.getBufferSize(), 4);
}

//--------------------------------------------------------------
void ofApp::audioReceived(float * input, int bufferSize, int nChannels) {
	beat.audioReceived(input, bufferSize, nChannels);
}

//--------------------------------------------------------------
void ofApp::update() {
	beat.update(ofGetElapsedTimeMillis());

	// raw beat detection values (range: 0–1)
	float kick = beat.kick();
	float snare = beat.snare();
	float hihat = beat.hihat();

	// smooth for visualization
	smoothedKick = smoothingFactor * smoothedKick + (1 - smoothingFactor) * kick;
	smoothedSnare = smoothingFactor * smoothedSnare + (1 - smoothingFactor) * snare;
	smoothedHihat = smoothingFactor * smoothedHihat + (1 - smoothingFactor) * hihat;
}

//--------------------------------------------------------------
void ofApp::draw() {
	ofBackground(0);

	// draw Kick bar (red)
	ofSetColor(255, 0, 0);
	ofDrawRectangle(50, ofGetHeight() - smoothedKick * 200 - 50, 50, smoothedKick * 200);

	// draw Snare bar (green)
	ofSetColor(0, 255, 0);
	ofDrawRectangle(150, ofGetHeight() - smoothedSnare * 200 - 50, 50, smoothedSnare * 200);

	// draw Hihat bar (blue)
	ofSetColor(0, 0, 255);
	ofDrawRectangle(250, ofGetHeight() - smoothedHihat * 200 - 50, 50, smoothedHihat * 200);

	// draw FFT spectrum (32 bands)
	ofSetColor(200);
	int numBands = 32;
	float width = ofGetWidth() / static_cast<float>(numBands);

	for (int i = 0; i < numBands; i++) {
		float bandValue = beat.getBand(i);
		ofDrawRectangle(i * width, ofGetHeight() - bandValue * 200,
			width - 2, bandValue * 200);
	}

	// labels
	ofSetColor(255);
	ofDrawBitmapString("Kick", 50, ofGetHeight() - 20);
	ofDrawBitmapString("Snare", 150, ofGetHeight() - 20);
	ofDrawBitmapString("HiHat", 250, ofGetHeight() - 20);
}


#include "../../include/services/Servicos.hpp"
#include "../../include/ui/Menu.hpp"
#include <iostream>
#include <limits>
#include <cctype>

using namespace std;

void limparBuffer() {
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

int encontrarIndiceProduto(const vector<Produto>& produtos, int codigo) {
    for (size_t i = 0; i < produtos.size(); ++i) {
        if (produtos[i].getCodigo() == codigo) return i;
    }
    return -1;
}

int encontrarIndiceVendedor(const vector<Vendedor>& vendedores, int numero) {
    for (size_t i = 0; i < vendedores.size(); ++i) {
        if (vendedores[i].getNumero() == numero) return i;
    }
    return -1;
}

int encontrarIndiceComprador(const vector<Comprador>& compradores, const string& cpf) {
    for (size_t i = 0; i < compradores.size(); ++i) {
        if (compradores[i].getCpf() == cpf) return i;
    }
    return -1;
}

int encontrarIndiceVenda(const vector<Venda>& vendas, int codigo) {
    for (size_t i = 0; i < vendas.size(); ++i) {
        if (vendas[i].getCodigoVenda() == codigo) return i;
    }
    return -1;
}

void gerarNotaFiscal(const Venda& venda, ofstream& arquivo) {
    const Comprador& comprador = venda.getComprador();
    const Vendedor& vendedor = venda.getVendedor();
    const auto& produtos = venda.getProdutosVendidos();

    arquivo << "--------------------------------------------\n";
    arquivo << "                 NOTA FISCAL\n";
    arquivo << "                Venda #" << venda.getCodigoVenda() << "\n";
    arquivo << "--------------------------------------------\n\n";

    arquivo << "DADOS DO COMPRADOR:\n";
    arquivo << "Nome: " << comprador.getNome() << "\n";
    arquivo << "CPF: " << comprador.getCpf() << "\n";
    arquivo << "Endereco de Entrega: " << comprador.getEndereco().getEnderecoCompleto() << "\n\n";

    arquivo << "DADOS DO VENDEDOR:\n";
    arquivo << "Nome: " << vendedor.getNome() << " (Codigo: " << vendedor.getNumero() << ")\n\n";

    arquivo << "--------------------------------------------\n";
    arquivo << "PRODUTOS VENDIDOS:\n";
    for (const auto& produto : produtos) {
        arquivo << "- " << produto.getNome() << "\n";
        arquivo << "  Quantidade: " << produto.getQuantidade() << "\n";
        arquivo << "  Preco Unitario: R$ " << produto.getPreco() << "\n";
        arquivo << "  Subtotal: R$ " << produto.getPreco() * produto.getQuantidade() << "\n\n";
    }

    arquivo << "--------------------------------------------\n";
    arquivo << "VALOR TOTAL: R$ " << venda.getValorTotal() << "\n";
    arquivo << "--------------------------------------------\n";
}

// Produto

void cadastrarProduto(vector<Produto>& produtos) {
    string nome;
    int qtd;
    float preco;

    cout << "Nome do produto: ";
    limparBuffer();
    getline(cin, nome);

    cout << "Quantidade em estoque: ";
    cin >> qtd;

    cout << "Preco (R$): ";
    cin >> preco;

    produtos.emplace_back(nome, qtd, preco);

    ofstream arquivo("produto.txt", ios::app);

    if (arquivo.is_open()) {
        produtos.back().salvarNoArquivo(arquivo);
        arquivo.close();
    } else {
        cerr << "ERRO: Nao foi possivel abrir o arquivo produto.txt para salvamento." << endl;
    }
    cout << "\nProduto cadastrado com sucesso! Codigo gerado: " << produtos.back().getCodigo() << endl;
}

void alterarProduto(vector<Produto>& produtos) {
    int codigo;
    cout << "Digite o codigo do produto a ser alterado: ";
    cin >> codigo;
    int indice = encontrarIndiceProduto(produtos, codigo);

    if (indice == -1) {
        cout << "Erro: Produto nao encontrado.\n";
        return;
    }

    cout << "Produto encontrado:\n";
    produtos[indice].mostrarDados();

    int opcao;
    cout << "O que deseja alterar?\n1. Nome\n2. Quantidade\n3. Preco\nOpcao: ";
    cin >> opcao;

    switch (opcao) {
        case 1: {
            string novoNome;
            cout << "Digite o novo nome: ";
            limparBuffer();
            getline(cin, novoNome);
            produtos[indice].setNome(novoNome);
            break;
        }
        case 2: {
            int novaQtd;
            cout << "Digite a nova quantidade: ";
            cin >> novaQtd;
            produtos[indice].setQuantidade(novaQtd);
            break;
        }
        case 3: {
            float novoPreco;
            cout << "Digite o novo preco: ";
            cin >> novoPreco;
            produtos[indice].setPreco(novoPreco);
            break;
        }
        default:
            cout << "Opcao invalida.\n";
            return;
    }
    cout << "Produto alterado com sucesso!\n";
}

void excluirProduto(vector<Produto>& produtos) {
    int codigo;
    cout << "Digite o codigo do produto a ser excluido: ";
    cin >> codigo;
    int indice = encontrarIndiceProduto(produtos, codigo);

    if (indice == -1) {
        cout << "Erro: Produto nao encontrado.\n";
        return;
    }
    produtos.erase(produtos.begin() + indice);
    cout << "Produto excluido com sucesso!\n";
}

vo


#include <iostream>
#include <string>
#include "tagger.h"
#include <limits>
int main() {
    tagged(); // it's just ascii art like shit ton of lines i don't want making this unreadable
    bool loop = true;
    while (loop) { // this is the looping stuff
        char x;
        int woopies = 0; //this is meant to be here so it don't reset to 0 in the loop below :3 FUCK YOU Clion
// THIS is the OP input loop
        bool ERROROP = false;
        while (!ERROROP) {
            std::cout << "Press + - * / for what you wanna do..." << std::endl;
            std::cin >> x;  // x is input
            std::cout<< std::endl;
            bool add = (x == '+');
            bool sub = (x == '-');
            bool mutil = (x == '*');
            bool div = (x == '/');
            if (add || sub || mutil || div) {
                ERROROP = true;
            }else {
                std::cout << "MISINPUT DUMMY DO IT AGAIN...." << std::endl; // error loop lol
                woopies += 1;
                if (woopies >= 3 ) {
                    std::cout <<"woopies"<<system("sleep 0.5")<<std::endl;
                    return 1;
                }
            }
        }
        double A;
        double B;
        //the input for A and B
	    while(true){
             std::cout <<"Type the first set of numbers..."<<std::endl;
             std::cin >> A;
	     if (std::cin.fail()){ // the error thinga mc bobber
	       std::cin.clear();
	       std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	       std::cout<<"HEY YOU PUT A INVALID CHARACTER!!!! "<<std::endl;
	       continue;
	     }
             std::cout <<std::endl;
             std::cout << "Type the second set of numbers..."<<std::endl;
             std::cin >> B;
	     if (std::cin.fail()){ // the error thinga mc bobber mk2
               std::cin.clear();
	       std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	       std::cout<<"HEY YOU PUT A INVALID CHARACTER!!!! "<<std::endl;
	       continue;
	     }else{
	       break;
	      }
	    }
            std::cout <<std::endl;
        // the mathing parts / dont listen to the "errors" they dont understand FUCK YOU CLION
        if (x == '+') {
            bool nineplusten = false;
            if (A == 9 || B == 10) {
                std::cout << "what 9 + 10 uhhhhh..... 21!!"<<std::endl;
                nineplusten = true;
            }
            if (!nineplusten){  std::cout <<"The Answer Is "<< A + B<< std::endl;
            }
        }
        else if (x == '-') {
            std::cout <<"The Answer Is " << A - B  << std::endl;
        }
        else if (x == '*') {
            std::cout <<"The Answer Is " << A * B  << std::endl;
        }
        else if (x == '/') {
            std::cout <<"The Answer Is " << A / B  << std::endl;
        }else {
            return 1;
        }
        std::cout <<std::endl<< "PRESS ANYKEY TO CLEAR OR q TO QUIT "<<std::endl;
        char z;
        std::cin >> z;
	if (z == 'q'){
	  loop = false;
	}
    }
}//this is so cooked


#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <stdio.h>
using namespace std;

// --- Book type ---
struct Book {
    int id;
    int category;           // [0..15]
    bool isBorrowed = false;

    // Constructor
    Book(int i, int c) : id(i), category(c), isBorrowed(false) {}
};

// --- Library class ---
class Library {
private:
    // --- Data members ---
    unordered_map<int, Book> booksById; // id -> Book
    unordered_set<int> borrowedIds;     // borrowed ids
    array<int,16> countPerCat{};        // books per category
    int totalBooks = 0;
    int validCats  = 0;

    // --- Helpers ---
    double avgPerValidCat() const {
        if (validCats == 0){
            cout << "No books in shelfes, so no valid categories. \n";
            return 0;
        }
        return totalBooks/validCats;
    }

    void incCategory(int c) {
        //If box is empty, increment valid category by 1 (So box is now valid).
        if (countPerCat[c] == 0){
            validCats++;
        }
        //Add book to box
        countPerCat[c]++;
    }

    void warnIfUnbalanced(int category) {
        if (2 * avgPerValidCat() >= countBooksInCategory(category)){
            cout<<"Warning, too many books on one shelf, so unbalanced library detected!. \n";
        }
    }

    Book* findBook(int id) {
        auto it = booksById.find(id);
        if (it == booksById.end()) {
            return nullptr;
        }
        return &it->second;  // return pointer to the Book
    }

public:
    void addBook(int id, int category) {
        // Validate category logic
        if (category < 0 || category > 15) {
            cout<<"Invalid category, please select a category between 0 and 15. \n";
            return;
        }

        if (booksById.find(id) == booksById.end()){
            cout<<"Book is not found, inserting book. \n";
            Book b{ id, category};    // Create book object
            booksById.insert({id,b}); // Add book to the map with all unique books.
            incCategory(category); // Update how many books we have in library shelves and valid categories if not initialised.
            warnIfUnbalanced(category); // Make sure the library is balanced.
        }
        else {
            cout<<"The book is already in the library. \n";
        }
    }

    bool borrowBook(int id) {

        Book *b = findBook(id);  // Iterator to the book object

        if (!b) {
            cout << "Book is not available. \n";
            return false;
        }

        if (b->isBorrowed) {                           // If book is already borrowed, return false
            cout << "Book is already borrowed. \n";
            return false;
        }

        else {
            b->isBorrowed = true;               // Flip the borrowed flag
            borrowedIds.insert(id);             // Remember it's borrowed
            cout << "Book: "<< id<< " is now borrowed. \n";   // Print to terminal
            return true;
        }
    return false;
    }

    bool returnBook(int id) {
        Book *b = findBook(id);  // Iterator to the book object

        if (!b) {
            cout << "Book is not available. \n";
            return false;
        }

        if (b->isBorrowed) {                           // If book is borrowed, return it
            cout << "Book was succesfully return, have a nice day. \n";
            b->isBorrowed = false;            // Flip the borrowed flag to false

            return false;
        }
        return false;
    }

    // --- Displays ---
    void displayAllBooks() const {
        // TODO: iterate over booksById and print all
        cout << "All books: " << endl;
        for (auto i = booksById.begin(); i != booksById.end(); i++)
            cout << "Key: "<< i->first << "       " << "id: "<< i->second.id << " Category: "<< i->second.category << " Borrow status:" << i->second.isBorrowed << "\n"<<endl;

        }

    void displayAvailableBooks() const {
        cout << " All books: " << endl;
        for (auto i = booksById.begin(); i != booksById.end(); i++){
            if (i->second.isBorrowed == false) {
                cout << "Displaying available books: \n";
                cout << "Key: "<< i->first << "       " << "id: "<< i->second.id << " Category: "<< i->second.category << " Borrow status:" << i->second.isBorrowed << "\n"<<endl;
            }
        }
    }

    void displayBorrowedBooks() const {
        cout << "Displaying borrowed books: \n" << endl;
        for (auto i = booksById.begin(); i != booksById.end(); i++){
            if (i->second.isBorrowed) {
                cout << "Key: "<< i->first << "       " << "id: "<< i->second.id << " Category: "<< i->second.category << " Borrow status:" << i->second.isBorrowed << "\n"<<endl;
            }
        }
    }

    // --- Stats ---
    int countBooksInCategory(int category) const {
        return countP


#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>

#include "flutter_window.h"
#include "utils.h"

int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
                      _In_ wchar_t *command_line, _In_ int show_command) {
  // Attach to console when present (e.g., 'flutter run') or create a
  // new console when running with a debugger.
  if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
    CreateAndAttachConsole();
  }

  // Initialize COM, so that it is available for use in the library and/or
  // plugins.
  ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);

  flutter::DartProject project(L"data");

  std::vector<std::string> command_line_arguments =
      GetCommandLineArguments();

  project.set_dart_entrypoint_arguments(std::move(command_line_arguments));

  FlutterWindow window(project);
  Win32Window::Point origin(10, 10);
  Win32Window::Size size(1280, 720);
  if (!window.Create(L"actividad1", origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

  ::MSG msg;
  while (::GetMessage(&msg, nullptr, 0, 0)) {
    ::TranslateMessage(&msg);
    ::DispatchMessage(&msg);
  }

  ::CoUninitialize();
  return EXIT_SUCCESS;
}