#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>

#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <glad/glad.h>

#ifdef __APPLE__
#ifndef GL_SILENCE_DEPRECATION
#define GL_SILENCE_DEPRECATION
#endif
#endif

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

// ---------------------------------------------
// Shader utils
// ---------------------------------------------
static GLuint compileShader(GLenum type, const char* src)
{
    GLuint s = glCreateShader(type);
    glShaderSource(s, 1, &src, nullptr);
    glCompileShader(s);
    GLint ok = 0;

    glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
    if (!ok)
    {
        GLint len = 0;
        glGetShaderiv(s, GL_INFO_LOG_LENGTH, &len);
        std::string log(len, '\0');
        glGetShaderInfoLog(s, len, nullptr, log.data());
        std::cerr << "Shader compile error:\n" << log << std::endl;
        std::exit(1);
    }
    return s;
}
static GLuint linkProgram(const char* vs, const char* fs)
{
    GLuint v = compileShader(GL_VERTEX_SHADER, vs);
    GLuint f = compileShader(GL_FRAGMENT_SHADER, fs);
    GLuint p = glCreateProgram();
    glAttachShader(p, v);
    glAttachShader(p, f);
    glLinkProgram(p);
    GLint ok = 0;
    glGetProgramiv(p, GL_LINK_STATUS, &ok);
    if (!ok)
    {
        GLint len = 0;
        glGetProgramiv(p, GL_INFO_LOG_LENGTH, &len);
        std::string log(len, '\0');
        glGetProgramInfoLog(p, len, nullptr, log.data());
        std::cerr << "Program link error:\n" << log << std::endl;
        std::exit(1);
    }
    glDeleteShader(v);
    glDeleteShader(f);
    return p;
}

// ---------------------------------------------
// Geometry: cube helpers
// ---------------------------------------------
struct Mesh
{
    GLuint vao = 0, vbo = 0, ebo = 0;
    GLsizei count = 0;
};
static Mesh makeUnitCube(bool withNormals)
{
    struct VN
    {
        float x, y, z, nx, ny, nz;
    };
    struct V
    {
        float x, y, z;
    };
    static const unsigned idx[] = {0,  1,  2,  2,  3,  0,  4,  5,  6,  6,  7,  4,  8,  9,  10, 10, 11, 8,
                                   12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20};
    const float p = 0.5f;
    Mesh m;
    glGenVertexArrays(1, &m.vao);
    glBindVertexArray(m.vao);
    glGenBuffers(1, &m.vbo);
    glBindBuffer(GL_ARRAY_BUFFER, m.vbo);
    glGenBuffers(1, &m.ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m.ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(idx), idx, GL_STATIC_DRAW);
    if (withNormals)
    {
        const VN verts[] = {{-p, -p, p, 0, 0, 1},   {p, -p, p, 0, 0, 1},   {p, p, p, 0, 0, 1},   {-p, p, p, 0, 0, 1},
                            {-p, -p, -p, 0, 0, -1}, {-p, p, -p, 0, 0, -1}, {p, p, -p, 0, 0, -1}, {p, -p, -p, 0, 0, -1},
                            {p, -p, -p, 1, 0, 0},   {p, p, -p, 1, 0, 0},   {p, p, p, 1, 0, 0},   {p, -p, p, 1, 0, 0},
                            {-p, -p, -p, -1, 0, 0}, {-p, -p, p, -1, 0, 0}, {-p, p, p, -1, 0, 0}, {-p, p, -p, -1, 0, 0},
                            {-p, p, -p, 0, 1, 0},   {-p, p, p, 0, 1, 0},   {p, p, p, 0, 1, 0},   {p, p, -p, 0, 1, 0},
                            {-p, -p, -p, 0, -1, 0}, {p, -p, -p, 0, -1, 0}, {p, -p, p, 0, -1, 0}, {-p, -p, p, 0, -1, 0}};
        glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
    }
    else
    {
        const V verts[] = {{-p, -p, p},  {p, -p, p},  {p, p, p},    {-p, p, p},  {-p, -p, -p}, {-p, p, -p},
                           {p, p, -p},   {p, -p, -p}, {p, -p, -p},  {p, p, -p},  {p, p, p},    {p, -p, p},
                           {-p, -p, -p}, {-p, -p, p}, {-p, p, p},   {-p, p, -p}, {-p, p, -p},  {-p, p, p},
                           {p, p, p},    {p, p, -p},  {-p, -p, -p}, {p, -p, -p}, {p, -p, p},   {-p, -p, p}};
        glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    }
    glBindVertexArray(0);
    m.count = (GLsizei)(sizeof(idx) / sizeof(idx[0]));
    return m;
}
static void drawMesh(const Mesh& m)
{
    glBindVertexArray(m.vao);
    glDrawElements(GL_TRIANGLES, m.count, GL_UNSIGNED_INT, 0);
}

// ---------------------------------------------
// Shaders
// ---------------------------------------------
static const char* depthVS = R"GLSL(
#version 410 core
layout(location=0) in vec3 aPos;
uniform mat4 uModel;
uniform mat4 uVP;
out vec3 WorldPos;
void main(){
    vec4 world = uModel * vec4(aPos,1.0);
    WorldPos = world.xyz;
    gl_Position = uVP * world;
}
)GLSL";

static const char* depthFS = R"GLSL(
#version 410


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

int main(){
	//declaration des variables et les tableaux
		int i,j,k,nombreOperation,cmp=0,cmpHistorique=0;
	    int prix,quantite,nombreLivres,nouvelleQuantite;
		char titreRechercher[100];
		char auteur[100],TableTitre[100][20],TableAuteur[100][20],titre[100];
		char TableTitreHistorique[100][20],TableAuteurHistorique[100][20];
	    int TablePrix[100],TableQuantite[100];
	    int TablePrixHistorique[100],TableQuantiteHistorique[100];
		int repeter ;

		//utiliser do while pour repeter le menu pour chaque operation
	    do{
	    	// Menu
		    printf("Menu : \n");
		    printf(" 1-Pour ajouter un Livre \n");
		    printf(" 2-Pour afficher tous les Livres \n");
		    printf(" 3-Pour mise a jour la quantite d`un livre \n");
		    printf(" 4-Pour supprimer un livre \n");
		    printf(" 5-Pour afficher le total de tous les livres\n");
		    printf(" 6-Pour afficher tous les livres supprimer\n");
		    printf(" Entrez votre numero pour votre operation : ");
		    scanf("%d",&nombreOperation);
		    //switch pour les operation qui a choisi par l utilisateur
		    switch(nombreOperation){
		    	// case 1 pour ajouter les livres
		    	case 1:

		    		printf("Donner le titre de Livre :");
		    		getchar();
		    		scanf("%[^\n]", &TableTitre[cmp]);

		    		printf("\n Donner le auteur de Livre : ");
		    		getchar();
			        scanf("%[^\n]", &TableAuteur[cmp]);
			        printf("\n Donner le prix de Livre :");
			        scanf("%d", &TablePrix[cmp]);

			        printf("\n Donner la quantite  de Livre :");
			        scanf("%d", &TableQuantite[cmp]);

			        cmp += 1;
			        printf("Le Livre est Bien Ajouter ");

			        break;

			    //case 2 pour afficher tous les info pour chaque livre
			    case 2:
			    	if(cmp ==0){
			    		printf("Aucun livre trouver  ");
					}else{
						for(i = 0;i < cmp;i++ ){
							printf("Le Livre %d Titre :%s , Auteur :%s , Prix :%d , Qunatite :%d \n",i+1,TableTitre[i],TableAuteur[i],TablePrix[i],TableQuantite[i]);
						}
					}

					break;

				// case 3 pour modifier la quantite dun livre par sons titre
				case 3:
					printf("Donner le titre de Livre :");
					getchar();
					scanf("%[^\n]",&titreRechercher);

					printf("Donner la nouvelle quantite de Livre :");
					scanf("%d",&nouvelleQuantite);

					for(i = 0;i < cmp;i++ ){
						if (strcmp(TableTitre[i],titreRechercher)==0){
							TableQuantite[i] = nouvelleQuantite;
							printf("mise quantite de %s avec success :",titreRechercher);
							break;
						}
					}

					printf("le livre ne pas exist");
					break;
				// case 3 pour supprimer un livre par sons titre
				case 4:

					printf("Donner le titre de Livre que tu veux supprimer :");
					getchar();
					scanf("%[^\n]",&titreRechercher);

					for(i = 0;i < cmp;i++ ){
						if (strcmp(titreRechercher,TableTitre[i])==0){
							// ajouter dans historique tables
							strcpy(TableTitreHistorique[cmpHistorique],TableTitre[i]);
							strcpy(TableAuteurHistorique[cmpHistorique],TableTitre[i]);
							TablePrixHistorique[cmpHistorique ]= TablePrix[i];
							TableQuantite[cmpHistorique] = TableQuantite[i];
							cmpHistorique += 1;

							//	 pour Supprimer le element de tableau
							for(j =  i;j < cmp;j++ ){
								strcpy(TableTitre[j],TableTitre[j+1]);
								strcpy(TableAuteur[j] ,TableAuteur[j+1]);
								TablePrix[j] = TablePrix[j+1];
								TableQuantite[j] = TableQuantite[j+1];

								printf("le livre  %s est supprimer avec success :",titreRechercher);
							}
							// decrasser le tableaux
							cmp--;
						}
					}
					break;
				// case 5 pour calcul le total de bibliotheque
				case 5:
					int somme = 0;
					for (i = 0 ;i > cmp; i++ ){
						somme += TableQuantite[i];
					}
					printf("le nombre total de stock c est %d",somme);
					break;

				//case 6 pour afficher tous les histoque  pour des  livre  livre supprimer
			    case 6:

			    	for(i = 0;i < cmpHistorique;i++ ){
						printf("Le Livre %d Titre :%s , Auteur :%s , Prix :%d , Qunatite :%d \n",i+1,TableTitreHistorique[i],TableAuteurHistorique[i],TablePrixHistorique[i],TableQuantiteHistorique[i]);
					}
					break;

			    default :
			    	printf("please entrer un nombre exist dans menu ");
			    	break;

			}

			printf("\n tu peux continuer(1 ou  0) : ");
			scanf("%d",&repeter);

		}while(repeter == 1);

	return 0;
}


#include "flutter_window.h"

#include <optional>

#include "flutter/generated_plugin_registrant.h"

FlutterWindow::FlutterWindow(const flutter::DartProject& project)
    : project_(project) {}

FlutterWindow::~FlutterWindow() {}

bool FlutterWindow::OnCreate() {
  if (!Win32Window::OnCreate()) {
    return false;
  }

  RECT frame = GetClientArea();

  // The size here must match the window dimensions to avoid unnecessary surface
  // creation / destruction in the startup path.
  flutter_controller_ = std::make_unique<flutter::FlutterViewController>(
      frame.right - frame.left, frame.bottom - frame.top, project_);
  // Ensure that basic setup of the controller was successful.
  if (!flutter_controller_->engine() || !flutter_controller_->view()) {
    return false;
  }
  RegisterPlugins(flutter_controller_->engine());
  SetChildContent(flutter_controller_->view()->GetNativeWindow());

  flutter_controller_->engine()->SetNextFrameCallback([&]() {
    this->Show();
  });

  // Flutter can complete the first frame before the "show window" callback is
  // registered. The following call ensures a frame is pending to ensure the
  // window is shown. It is a no-op if the first frame hasn't completed yet.
  flutter_controller_->ForceRedraw();

  return true;
}

void FlutterWindow::OnDestroy() {
  if (flutter_controller_) {
    flutter_controller_ = nullptr;
  }

  Win32Window::OnDestroy();
}

LRESULT
FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
                              WPARAM const wparam,
                              LPARAM const lparam) noexcept {
  // Give Flutter, including plugins, an opportunity to handle window messages.
  if (flutter_controller_) {
    std::optional<LRESULT> result =
        flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,
                                                      lparam);
    if (result) {
      return *result;
    }
  }

  switch (message) {
    case WM_FONTCHANGE:
      flutter_controller_->engine()->ReloadSystemFonts();
      break;
  }

  return Win32Window::MessageHandler(hwnd, message, wparam, lparam);
}


#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"flutter_application_2", origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

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

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


#include <iostream>
#include <cstdlib>   // für rand(), srand()
#include <ctime>     // für time()
using namespace std;

int main()
{
    srand(time(0));

    cout << "Hallo, Wilkommen zu dem Speil Zahlenraten!\n";
    cout << "Tippe eine Zahl von 1-3 um den Schwierigskeitsgrad, des Spieles, fest zu legen. \n";
    cout << "1 = Zahlenraum von 1 - 25\n";
    cout << "2 = Zahlenraum von 1 - 100\n";
    cout << "3 = Zahlenraum von 1 - 1000\n";
    cout << "Gebe deine Zahl ein!\n\n";

    int wahl = 0;
    bool gueltig = false;

    while (!gueltig) {

        cin >> wahl;

        if (wahl == 1 || wahl == 2 || wahl == 3) {
            gueltig = true;
        }
        else
        {
            cout << "Ungültige Zahl, versuche es noch einmal!\n";
        }
    }
        int computerzahl;
        if (wahl == 1) {
                computerzahl = rand() % 25 + 1;
        }
        else if (wahl == 2) {
            computerzahl = rand() % 100 + 1;
        }
        else {
            computerzahl = rand() % 1000 + 1;
        }

        cout << "gebe deine Zahl ein\n";

        int guess = -1;

        while (true) {
            cin >> guess;
            if (computerzahl == guess) {
                cout << "Gut gemacht, das war die Richtige Zahl!\n";
                break;
            }

            else if (guess < computerzahl) {
                cout << "Die Zahl ist zu niedrig.\n";
            }
            else if (guess > computerzahl){
                cout << "Die Zahl ist zu hoch!\n";
            }
        }

}


#include "CloudscapeFactory.h"

#if WITH_EDITOR

#include "Engine/VolumeTexture.h"

/* OpenVDB Includes */
THIRD_PARTY_INCLUDES_START
#undef check /* <- Otherwise we cannot compile... */
#include "openvdb/openvdb.h"
#include "openvdb/Grid.h"
#include "openvdb/tools/Interpolation.h"
#include "openvdb/tools/FastSweeping.h"
#include <openvdb/tools/GridTransformer.h>
#include <openvdb/tools/Filter.h>
#undef UpdateResource /* <- Windows header included somewhere... */
THIRD_PARTY_INCLUDES_END

#define LOCTEXT_NAMESPACE "UCloudscapeFactory"

UCloudscapeFactory::UCloudscapeFactory(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) {
	SupportedClass = UVolumeTexture::StaticClass();
	Formats.Add(TEXT("vdb;OpenVDB Format"));
	bCreateNew = false;
	bEditorImport = true;
	bEditAfterNew = true;
	ImportPriority = DefaultImportPriority;
}

FText UCloudscapeFactory::GetDisplayName() const {
	return LOCTEXT("CloudscapeFactoryDescription", "Cloudscape");
}

bool UCloudscapeFactory::DoesSupportClass(UClass* Class) {
	return Class == UVolumeTexture::StaticClass();
}

UClass* UCloudscapeFactory::ResolveSupportedClass() {
	return UVolumeTexture::StaticClass();
}

bool UCloudscapeFactory::FactoryCanImport(const FString& Filename) {
	return FPaths::GetExtension(Filename).Equals(TEXT("vdb"), ESearchCase::IgnoreCase);
}

UObject* UCloudscapeFactory::FactoryCreateFile(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, const FString& Filename, const TCHAR* Parms, FFeedbackContext* Warn, bool& bOutOperationCanceled) {
	bOutOperationCanceled = false;
	if (!FactoryCanImport(Filename)) return nullptr;

	return CreateVolumeTextureFromVDB(Filename, InParent, InName, Flags);
}

/* Volume texture size */
constexpr uint32 VTEX_X = 64;
constexpr uint32 VTEX_Y = 64;
constexpr uint32 VTEX_Z = 64;

/** @brief Re-sample a VDB float grid as density field. */
void ResampleDensityField(UVolumeTexture& Output, openvdb::FloatGrid& Input) {
	/* Get the extent of the grid in world space */
	const openvdb::math::Transform GridTransform = Input.transform();
	const openvdb::CoordBBox AABB = Input.evalActiveVoxelBoundingBox();
	const openvdb::Vec3d GridMin = GridTransform.indexToWorld(AABB.min());
	const openvdb::Vec3d GridExtent = GridTransform.indexToWorld(AABB.max()) - GridMin;

	/* Calculate the step size along each axis */
	const double StepX = GridExtent.x() / VTEX_X;
	const double StepY = GridExtent.y() / VTEX_Y;
	const double StepZ = GridExtent.z() / VTEX_Z;
	const double StepSize = std::max(std::max(StepX, StepY), StepZ);

	/* Find the min and max density in the grid */
	float MinDensity = 0.0f;
	float MaxDensity = 0.0f;
	Input.evalMinMax(MinDensity, MaxDensity);
	const float DensityRange = MaxDensity - MinDensity;

	/* Pre-filter the input grid for down-sampling */
	openvdb::tools::Filter<openvdb::FloatGrid> Filter(Input);
	Filter.gaussian(StepSize, 1);

	/* Create a grid sampler and lock the volume texture data */
	openvdb::tools::GridSampler<openvdb::FloatGrid, openvdb::tools::BoxSampler> sampler(Input);
	uint8* TextureData = Output.Source.LockMip(0);

	/* Re-sample the density grid */
	for (int32 z = 0; z < VTEX_Z; ++z) {
		for (int32 y = 0; y < VTEX_Y; ++y) {
			for (int32 x = 0; x < VTEX_X; ++x) {
				const openvdb::Vec3d WorldPos(
					GridMin.x() + x * StepSize,
					GridMin.y() + y * StepSize,
					GridMin.z() + z * StepSize
				);

				/* Sample the density grid */
				const float Density = sampler.wsSample(WorldPos) / DensityRange;
				const uint8 DensityData = (uint8)(Density * 255.0f);

				/* Calculate the texture index and write our density data */
				const int32 index = x + (y * VTEX_X) + (z * VTEX_X * VTEX_Y);
				TextureData[index] = DensityData;
			}
		}
	}

	/* Unlock the volume texture data */
	Output.Source.UnlockMip(0);

	/* Set all the volume texture settings */
	Output.MipGenSettings = TMGS_NoMipmaps;
	Output.CompressionSettings = TC_Grayscale;
	Output.SRGB = false;
	Output.Filter = TF_Bilinear;
	Output.AddressMode = TA_Wrap;

	/* Update the volume texture resource */
	Output.UpdateResource();
}

/** @brief Re-sample a VDB float grid as signed distance field. */
void ResampleSignedDistanceField(UVolumeTexture& Output, openvdb::FloatGrid& Input) {
	/* Convert the density grid data to a signed distance field */
	//const openvdb::FloatGrid::Ptr SdfGrid = openvdb::tools::fogToSdf(Input, 0.01f);

	/* Get the extent of the grid in world space */
	//const openvdb::math::Transform GridTransform = SdfGrid->transform();
	//const openvdb::CoordBBox AABB = SdfGrid->evalActiveVoxelBoundingBox();
	//const openvdb::Vec3d GridMin = GridTransform.indexToWorld(AABB.min());
	//const openvdb::Vec3d GridExtent = GridTransform.indexToWorld(AABB.max()) - GridMin;

	/* Calculate the step size along each axis */
	//const double StepX = GridExtent.x() / VTEX_X;
	//const double StepY = GridExtent.y() / VTEX_Y;
	//const double StepZ = GridExtent.z() / VTEX_Z;
	//const double StepSize = std::max(std::max(StepX, Ste


#include <Arduino.h>
#include <config/config.h>
#include <mqtt/mqtt_manager.h>
#include <web/web_interface.h>
#include <wifi/wifi_manager.h>
#include <control/control.h>

void setup()
{
  Serial.begin(115200);
  Serial.println("\n\n--- Inicializando ---");

  pinMode(0, INPUT_PULLUP);

  // Carregar configurações da EEPROM
  loadConfiguration();

  // Inicializa pinos do hardware
  setupHardware();

  // Tentar conectar ao WiFi
  if (!connectToWifi())
  {
    startConfigMode();
    return;
  }

  // Configurar e conectar ao MQTT
  setupMqtt();
  reconnectMqtt();
}

void loop()
{
  static unsigned long buttonPressTime = millis();

  if (digitalRead(0) == LOW)
  {
    if (millis() - buttonPressTime > 5000) // Pressionado por 2 segundos
    {
      buttonPressTime = millis(); // Reinicia o tempo
      Serial.println("Botão pressionado por 5s: reiniciando...");
      resetConfiguration();
    }
  }

  if (Serial.available())
  {
    String comando = Serial.readStringUntil('\n');
    comando.trim(); // remove espaços e quebras de linha

    if (comando == "reset")
    {
      Serial.println("Reiniciando...");
      resetConfiguration();
    }
  }

  if (configMode)
  {
    dnsServer.processNextRequest();
    server.handleClient();
    return;
  }

  if (!mqttClient.connected())
  {
    reconnectMqtt();
  }
  mqttClient.loop();

  // Verifica periodicamente a conexão WiFi
  static unsigned long lastWifiCheck = 0;
  if (millis() - lastWifiCheck > 30000)
  { // A cada 30s
    verifyConnection();
    lastWifiCheck = millis();
  }

  static unsigned long lastKeepAlive = 0;
  if (millis() - lastKeepAlive > 10000)
  { // A cada 10s
    keepAlive();
    lastKeepAlive = millis();
  }
}


#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <array>
#include <vector>
#include <unistd.h>

using namespace std;

// TODO:
// Write your own restore
// Handle applications not visible to hyprland using lookup tables and if's
// check if the hyprctl clients is longer after u dispatch, if it isnt moveo  n
vector<string> lines;
void save();
void restore();
int checkIfAppOpen();
string find_in_path(const std::string& app);
int main(){
    save();
    return 0;
}

void dispatch(int workspace, string application, int monitor){
    int before = checkIfAppOpen();
    sleep(2);

    string command = "hyprctl dispatch exec \"[workspace " + std::to_string(workspace) + " silent] " + application + "\"";

    cout << command << endl;
    system(command.c_str());

    sleep(2);
    int after = checkIfAppOpen();

    if(before == after){
        // make a list of special cases??:
        if(application == "libreoffice-impress")
            system("hyprctl dispatch exec \"libreoffice --impress\" ");
        cout << "Trying..";
        string path = find_in_path(application);
        string pathCommand = "hyprctl dispatch exec \"[workspace " +to_string(workspace) + " silent] " + path + "\"";
        cout << "hyprctl dispatch exec \"" + path + "\"";

        system(pathCommand.c_str());
    }
    string monitorCommand;
    cout << "Moving to monitor, " << monitor << endl;
    monitorCommand = "hyprctl dispatch moveworkspacetomonitor " + to_string(workspace) + " " + to_string(monitor);
    system(monitorCommand.c_str());
}
std::string shell_escape_spaces(const std::string& path) {
    std::string escaped;
    for (char c : path) {
        if (c == ' ') {
            escaped += "\\ ";
        } else {
            escaped += c;
        }
    }
    return escaped;
}

std::string find_in_path(const std::string& app) {
    std::string cmd = "which " + app + " 2>/dev/null";
    std::array<char, 4096> buffer;
    std::string result;
    FILE* pipe = popen(cmd.c_str(), "r");
    if (!pipe) return "";
    if (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
        result = buffer.data();
        if (!result.empty() && result.back() == '\n')
            result.pop_back();
    }
    pclose(pipe);

    return shell_escape_spaces(result);
}
int checkIfAppOpen(){

    std::vector<std::string> clients;
    char buffer[4096];
    FILE* pipe = popen("hyprctl clients", "r");

    while (fgets(buffer, sizeof(buffer), pipe)) {
        std::string line(buffer);
        if (!line.empty() && line.back() == '\n')
            line.erase(line.size() - 1);
        clients.push_back(line);
    }
    pclose(pipe);
    for( int x = 0; x< clients.size(); x++)
        cout << clients[x] << endl;
    return clients.size();

}

void restore() {
    ifstream readFile("HyprSaveSession.txt");
    string line;
    while(getline(readFile, line)){
        lines.push_back(line);
    }

    int workspace, monitor;
    string application;
    int x;
    for(x = 0; x < lines.size() - 1; x=x+26){

        workspace =  stoi(lines[x+5].substr(12,1));
        monitor = stoi(lines[x+8].substr(9));
        application = lines[x+9].substr(8);
        cout << "dispatching: " << application << endl;
        dispatch(workspace, application, monitor);
    }

}
void save(){
    array<char, 5000> buffer;
    string clients;
    ofstream writeFile("HyprSaveSession.txt");
    system("hyprctl clients");
    FILE* pipe = popen("hyprctl clients","r");
    if(!pipe){

    }
    while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
        clients += buffer.data();
    }
    writeFile << clients;
    writeFile.close();
}


#include <cstdio>
#include <climits> // Dla INT_MAX

#define MAX_DIM  2005
#define MAX_TOTAL_LIFTS 10005
#define MAX_QUEUE (MAX_DIM * MAX_DIM)

struct State {
    int time;
    int x, y;
};

State heap[MAX_QUEUE];
int heap_size = 0;

// Funkcja dodaj¹ca element do kopca (utrzymuje w³asnoœæ kopca minimum)
void push(const State& s) {
    if (heap_size >= MAX_QUEUE) {
        // fprintf(stderr, "Heap overflow! Attempted to push state (time: %d, x: %d, y: %d) to full heap (size: %d).\n", s.time, s.x, s.y, heap_size);
        return;
    }
    int i = heap_size++;
    heap[i] = s;

    while (i > 0) {
        int p = (i - 1) / 2;
        if (heap[p].time <= heap[i].time) break;
        State tmp = heap[p];
        heap[p] = heap[i];
        heap[i] = tmp;
        i = p;
    }
}

// Funkcja usuwaj¹ca i zwracaj¹ca element o najmniejszym priorytecie (korzeñ kopca)
State pop() {
    State ret = heap[0];
    heap[0] = heap[--heap_size];

    int i = 0;
    while (true) {
        int left_child = i * 2 + 1;
        int right_child = i * 2 + 2;
        int smallest = i;

        if (left_child < heap_size && heap[left_child].time < heap[smallest].time) {
            smallest = left_child;
        }
        if (right_child < heap_size && heap[right_child].time < heap[smallest].time) {
            smallest = right_child;
        }

        if (smallest == i) break;

        State tmp = heap[i];
        heap[i] = heap[smallest];
        heap[smallest] = tmp;
        i = smallest;
    }
    return ret;
}
// --- Koniec implementacji kolejki priorytetowej ---

// Struktura przechowuj¹ca informacje o windzie w globalnej tablicy
struct LiftInfo {
    int sx, sy;
    int ex, ey;
    int travel_time;
    int interval;
    int next_lift_idx;
};

// Globalne tablice
int heights[MAX_DIM][MAX_DIM];
int dist[MAX_DIM][MAX_DIM];

LiftInfo all_lifts_storage[MAX_TOTAL_LIFTS];
int lift_head[MAX_DIM][MAX_DIM];
int current_lift_storage_idx = 0;

int width, height;

int main() {
    int start_x, start_y, end_x, end_y, n_lifts_total;

    scanf("%d%d", &width, &height);
    scanf("%d%d", &start_x, &start_y);
    scanf("%d%d", &end_x, &end_y);
    scanf("%d", &n_lifts_total);

    // Inicjalizacja lift_head
    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            lift_head[y][x] = -1; // -1 oznacza brak wind z tego pola
        }
    }

    // Wczytywanie informacji o windach i budowanie list s¹siedztwa
    for (int i = 0; i < n_lifts_total; ++i) {
        int sx, sy, ex, ey, travel_time, interval_val; // Zmieniono nazwê interval na interval_val, aby unikn¹æ konfliktu
        scanf("%d%d%d%d%d%d", &sx, &sy, &ex, &ey, &travel_time, &interval_val);

        // Sprawdzenie poprawnoœci wspó³rzêdnych startowych i docelowych windy
        if (sx >= 0 && sx < width && sy >= 0 && sy < height &&
            ex >= 0 && ex < width && ey >= 0 && ey < height) {

            if (current_lift_storage_idx < MAX_TOTAL_LIFTS) {
                all_lifts_storage[current_lift_storage_idx].sx = sx;
                all_lifts_storage[current_lift_storage_idx].sy = sy;
                all_lifts_storage[current_lift_storage_idx].ex = ex;
                all_lifts_storage[current_lift_storage_idx].ey = ey;
                all_lifts_storage[current_lift_storage_idx].travel_time = travel_time;
                all_lifts_storage[current_lift_storage_idx].interval = interval_val;
                all_lifts_storage[current_lift_storage_idx].next_lift_idx = lift_head[sy][sx];
                lift_head[sy][sx] = current_lift_storage_idx;
                current_lift_storage_idx++;
            }
            else {
                // fprintf(stderr, "Warning: Exceeded MAX_TOTAL_LIFTS. Skipping lift.\n");
            }
        }
        else {
            // fprintf(stderr, "Warning: Invalid coordinates for a lift. Start (%d,%d) to End (%d,%d). Skipping lift.\n", sx, sy, ex, ey);
        }
    }

    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            scanf("%d", &heights[y][x]);
        }
    }

    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            dist[y][x] = INT_MAX;
        }
    }

    if (!(start_x >= 0 && start_x < width && start_y >= 0 && start_y < height &&
        end_x >= 0 && end_x < width && end_y >= 0 && end_y < height)) {
        printf("-1\n");
        return 0;
    }

    dist[start_y][start_x] = 0;
    heap_size = 0;
    push({ 0, start_x, start_y });

    int dirs[4][2] = { {0,1}, {0,-1}, {1,0}, {-1,0} };

    while (heap_size > 0) {
        State s = pop();
        int time = s.time;
        int x = s.x;
        int y = s.y;

        if (x == end_x && y == end_y) {
            printf("%d\n", time);
            return 0;
        }

        if (time > dist[y][x]) {
            continue;
        }

        // Ruchy na s¹siednie pola
        for (int d = 0; d < 4; ++d) {
            int nx = x + dirs[d][0];


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void print(vector<pair<string, vector<pair<int, int>>>> pairs) {
    for (pair<string, vector<pair<int, int>>> p : pairs) {
        cout << "Word : \"" << p.first << "\"" << endl;
        cout << "Coordinates : ";
        for (pair<int, int> c : p.second){
            cout << "(" << c.first << "," << c.second << ") ";
        }
        cout << endl << endl;
    }
}

bool contains(vector<string> words, string word) {
    for (string w : words) {
        if (w == word) return true;
    }

    return false;
}

vector<pair<string, vector<pair<int, int>>>>
findWords(vector<vector<char>> &grid, vector<string> words) {

    vector<pair<string, vector<pair<int, int>>>> result;

    int rows = grid.size();
    int columns = (grid[0]).size();

    // Scanning the rows from left to right
    for (int col = 0; col < columns; col++) { // Looping over columns

        for (int row = 0; row < rows; row++) { // Looping over rows
        vector<pair<int, int>> coords;
        string word = "";

            for (int start = col; start < columns; start++) { // Scanning the row along columns
                word += grid[row][start];
                coords.push_back({row, start});
                if (contains(words, word)) {
                    result.push_back({word, coords});
                    break;
                }
            }
        }
    }

    // Scanning the rows from right to left
    for (int col = columns - 1; col >= 0; col--) { // Looping over columns

        for (int row = 0; row < rows; row++) { // Looping over rows
        vector<pair<int, int>> coords;
        string word = "";

            for (int start = col; start >= 0; start--) { // Scanning the row along columns
                word += grid[row][start];
                coords.push_back({row, start});
                if (contains(words, word)) {
                    result.push_back({word, coords});
                    break;
                }
            }
        }
    }

    return result;

}

int main() {
    vector<vector<char>> grid = {
        {'J','S','O','L','U','T','I','S'},
        {'S','U','N','A','R','U','U','A'},
        {'N','E','P','T','U','N','E','T'},
        {'S','O','N','I','E','I','S','U'},
        {'R','C','E','V','T','R','E','R'},
        {'A','H','T','R','A','E','S','N'},
        {'M','M','E','R','C','U','R','Y'}
    };

    vector<string> words = {"EARTH", "JUPITER", "MARS", "MERCURY",
                            "NEPTUNE", "SATURN", "URANUS", "VENUS"};

    vector<pair<string, vector<pair<int, int>>>> result;

    result = findWords(grid, words);

    print(result);

    return 0;
}


#pragma once

/*
* SDK generated by Dumper-7
*
* https://github.com/Encryqed/Dumper-7
*/

// Package: UIW_Record

#include "Basic.hpp"

#include "UIW_Record_classes.hpp"
#include "UIW_Record_parameters.hpp"

namespace SDK
{

// Function UIW_Record.UIW_Record_C.ExecuteUbergraph_UIW_Record
// (Final, UbergraphFunction, HasDefaults)
// Parameters:
// int32                                   EntryPoint                                             (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)

void UUIW_Record_C::ExecuteUbergraph_UIW_Record(int32 EntryPoint)
{
	static class UFunction* Func = nullptr;

	if (Func == nullptr)
		Func = Class->GetFunction("UIW_Record_C", "ExecuteUbergraph_UIW_Record");

	Params::UIW_Record_C_ExecuteUbergraph_UIW_Record Parms{};

	Parms.EntryPoint = EntryPoint;

	UObject::ProcessEvent(Func, &Parms);
}

// Function UIW_Record.UIW_Record_C.Construct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)

void UUIW_Record_C::Construct()
{
	static class UFunction* Func = nullptr;

	if (Func == nullptr)
		Func = Class->GetFunction("UIW_Record_C", "Construct");

	UObject::ProcessEvent(Func, nullptr);
}

// Function UIW_Record.UIW_Record_C.BndEvt__UIW_Record_Btn_Stop_K2Node_ComponentBoundEvent_3_OnActive__DelegateSignature
// (BlueprintEvent)
// Parameters:
// class UUIW_Btn_Key_C*                   BtnKey                                                 (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)

void UUIW_Record_C::BndEvt__UIW_Record_Btn_Stop_K2Node_ComponentBoundEvent_3_OnActive__DelegateSignature(class UUIW_Btn_Key_C* BtnKey)
{
	static class UFunction* Func = nullptr;

	if (Func == nullptr)
		Func = Class->GetFunction("UIW_Record_C", "BndEvt__UIW_Record_Btn_Stop_K2Node_ComponentBoundEvent_3_OnActive__DelegateSignature");

	Params::UIW_Record_C_BndEvt__UIW_Record_Btn_Stop_K2Node_ComponentBoundEvent_3_OnActive__DelegateSignature Parms{};

	Parms.BtnKey = BtnKey;

	UObject::ProcessEvent(Func, &Parms);
}

// Function UIW_Record.UIW_Record_C.Tick
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
// const struct FGeometry&                 MyGeometry                                             (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor)
// float                                   InDeltaTime                                            (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)

void UUIW_Record_C::Tick(const struct FGeometry& MyGeometry, float InDeltaTime)
{
	static class UFunction* Func = nullptr;

	if (Func == nullptr)
		Func = Class->GetFunction("UIW_Record_C", "Tick");

	Params::UIW_Record_C_Tick Parms{};

	Parms.MyGeometry = std::move(MyGeometry);
	Parms.InDeltaTime = InDeltaTime;

	UObject::ProcessEvent(Func, &Parms);
}

// Function UIW_Record.UIW_Record_C.Destruct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)

void UUIW_Record_C::Destruct()
{
	static class UFunction* Func = nullptr;

	if (Func == nullptr)
		Func = Class->GetFunction("UIW_Record_C", "Destruct");

	UObject::ProcessEvent(Func, nullptr);
}

// Function UIW_Record.UIW_Record_C.BndEvt__Btn_Close_K2Node_ComponentBoundEvent_2_OnActive__DelegateSignature
// (BlueprintEvent)
// Parameters:
// class UUIW_Btn_Key_C*                   BtnKey                                                 (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)

void UUIW_Record_C::BndEvt__Btn_Close_K2Node_ComponentBoundEvent_2_OnActive__DelegateSignature(class UUIW_Btn_Key_C* BtnKey)
{
	static class UFunction* Func = nullptr;

	if (Func == nullptr)
		Func = Class->GetFunction("UIW_Record_C", "BndEvt__Btn_Close_K2Node_ComponentBoundEvent_2_OnActive__DelegateSignature");

	Params::UIW_Record_C_BndEvt__Btn_Close_K2Node_ComponentBoundEvent_2_OnActive__DelegateSignature Parms{};

	Parms.BtnKey = BtnKey;

	UObject::ProcessEvent(Func, &Parms);
}

// Function UIW_Record.UIW_Record_C.BndEvt__Btn_Detail_K2Node_ComponentBoundEvent_1_OnActive__DelegateSignature
// (BlueprintEvent)
// Parameters:
// class UUIW_Btn_Key_C*                   BtnKey                                                 (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)

void UUIW_Record_C::BndEvt__Btn_Detail_K2Node_ComponentBoundEvent_1_OnActive__DelegateSignature(class UUIW_Btn_Key_C* BtnKey)
{
	static class UFunction* Func = nullptr;

	if (Func == nullptr)
		Func = Class->GetFunction("UIW_Record_C", "BndEvt__Btn_Detail_K2Node_ComponentBoundEvent_1_OnActive__DelegateSignature");

	Params::UIW_Record_C_BndEvt__Btn_Detail_K2Node_ComponentBoundEvent_1_OnActive__DelegateSignature Parms{};

	Parms.BtnKey = BtnKey;

	UObject::ProcessEvent(Func, &Parms);
}

// Fu


#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"flutter_application_8", origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

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

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


/*
Imagine sockets are like telephones:

SimpleSocket: buys you a new phone, but doesn’t give it a number yet.
BindingSocket: goes to the telephone company and says "assign me number 8080 so people can call me".
*/

#include "BindingSocket.hpp"
// Constructor
HDE::BindingSocket::BindingSocket(int domain, int service, int protocol, int port, u_long intrface) : SimpleSocket(domain, service, protocol, port, intrface) // Constructor forwarding: So when you create a BindingSocket, it first runs the SimpleSocket constructor with the given arguments.
{
    int connection = connect_to_network(get_sock(), get_address());
    set_connection(connection);
    test_connection(connection);
}

// Implementation to connect_to_network function
int HDE::BindingSocket::connect_to_network(int sock, struct sockaddr_in address)
/*
First argument = socket file descriptor (integer ID) returned by the socket() call (refer SimpleSocket Class)
Second argument = pointer to the address you want to bind.
Third argument = size of that address struct.
*/
{
    // Note*
    // bind() expects its second parameter to be a pointer to struct sockaddr, not sockaddr_in.
    // sockaddr_in is a specialized version of sockaddr so we are explicitly casting sockaddr_in to sockaddr
    return bind(sock, (struct sockaddr *)&address, sizeof(address));
}


#include "handlers.h"
#include "database.h"
#include <crow.h>
#include <iostream>
#include <memory>

using namespace task_api;

int main() {
    try {
        std::cout << "C++ Task REST Server" << std::endl;
        std::cout << "====================" << std::endl;

        // Initialize database
        auto db = std::make_shared<TaskDatabase>("tasks.db");
        if (!db->initialize()) {
            std::cerr << "Failed to initialize database" << std::endl;
            return 1;
        }

        // Create sample data
        if (!db->create_sample_data()) {
            std::cerr << "Failed to create sample data" << std::endl;
            return 1;
        }

        std::cout << "Database initialized successfully" << std::endl;

        // Create Crow app with CORS middleware
        crow::App<crow::CORSHandler> app;

        // Initialize handlers
        TaskHandlers handlers(db);
        handlers.register_routes(app);

        // Add health check endpoint
        CROW_ROUTE(app, "/health")
        ([]() {
            return crow::response(200, "OK");
        });

        // Add root endpoint with API info
        CROW_ROUTE(app, "/")
        ([]() {
            nlohmann::json info = {
                {"name", "C++ Task Management API"},
                {"version", "1.0.0"},
                {"description", "A REST API for task management built with C++ and Crow"},
                {"endpoints", {
                    {"GET /api/tasks", "List all tasks with optional filtering"},
                    {"GET /api/tasks/{id}", "Get a specific task"},
                    {"POST /api/tasks", "Create a new task"},
                    {"PUT /api/tasks/{id}", "Update a task"},
                    {"PATCH /api/tasks/{id}/status", "Update task status"},
                    {"DELETE /api/tasks/{id}", "Delete a task"}
                }}
            };

            crow::response res(200);
            res.set_header("Content-Type", "application/json");
            res.write(info.dump(2));
            return res;
        });

        std::cout << "Starting server on http://localhost:8080" << std::endl;
        std::cout << "API endpoints available at http://localhost:8080/api/tasks" << std::endl;
        std::cout << "Health check available at http://localhost:8080/health" << std::endl;
        std::cout << "Press Ctrl+C to stop the server" << std::endl;

        // Start the server
        app.port(8080)
           .multithreaded()
           .run();

    } catch (const std::exception& e) {
        std::cerr << "Server error: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}


#include<iostream>
using namespace std;

#define N 9
void printgrid(int grid[N][N])

{
    cout<<"-------------------------------"<<endl;
    for(int row = 0; row < N; row++)
    {
        cout<<"| ";
        for(int col = 0; col < N; col++)
        {
            if(grid[row][col] == 0)
                cout<<". ";
            else
                cout<<grid[row][col]<<" ";
            if((col + 1) % 3 == 0)
                cout<<"| ";
        }
        cout<<endl;
        if((row + 1) % 3 == 0)
            cout<<"-------------------------------"<<endl;
    }
}

bool isSafe(int grid[N][N], int row, int col, int num)
{
    for(int x = 0; x < N; x++)
        if(grid[row][x] == num || grid[x][col] == num)
            return false;

    int startRow = row - row % 3, startCol = col - col % 3;
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 3; j++)
            if(grid[i + startRow][j + startCol] == num)
                return false;
    return true;
}

bool solveSudoku(int grid[N][N])
{
    for(int row = 0; row < N; row++)
    {
        for(int col = 0; col < N; col++)
        {
            if(grid[row][col] == 0)
            {
                for(int num = 1; num <= 9; num++)
                {
                    if(isSafe(grid, row, col, num))
                    {
                        grid[row][col] = num;
                        if(solveSudoku(grid))
                            return true;
                        grid[row][col] = 0;
                    }
                }
                return false;
            }
        }
    }
}

bool iscompleteAndValid(int g[N][N])
{
    for(int i=0;i<9;i++){
        bool r[10]={0},c[10]={0};
        for(int j=0;j<9;++j){
            int a=g[i][j],b=g[j][i];
            if(a<1 || a>9 || b<1 || b>9 )return false;
            if(r[a] || c[b])return false;
            r[a]=c[b]=true;
        }
    }
    for(int br=0;br<3;br++){
        for(int bc=0;bc<3;bc++){
            bool seen[10]={0};
            for(int i=0;i<3;i++){
                for(int j=0;j<3;j++){
                    int v=g[br*3+i][bc*3+j];
                    if(seen[v])return false;
                    seen[v]=true;
                }
            }
        }
    }
    return true;
}

bool isSolutionValid(int original[N][N], int solved[N][N])
{
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++)
        {
            if(original[i][j] != 0 && original[i][j] != solved[i][j])
                return false;
        }
    }
    return iscompleteAndValid(solved);
}

int main()
{
    int grid[N][N],original[N][N];
    cout<<"Enter the Sudoku puzzle (use 0 for empty cells):"<<endl;
    for(int i = 0; i < N; i++){
        cout<<"Enter row "<<i+1<<": ";
        for(int j = 0; j < N; j++){
            cin>>grid[i][j];
            original[i][j]=grid[i][j];
        }
    }
    cout<<"\nHere is the puzzle you Entered:"<<endl;
    printgrid(grid);
    cout<<"\nDo you want to solve this puzzle? (Yes/No): ";
    string choice;
    cin>>choice;
    if(choice == "Yes" ){
        if(solveSudoku(grid) && iscompleteAndValid(grid)){
            cout<<"\nSolution Found:"<<endl;
            printgrid(grid);
        }
        else{
            cout<<"\nSolver Failed ?"<<endl;
        }

    }
    else{
            cout<<"Okay,You can try solving it on your own!"<<endl;
        }
    int usergrid[N][N];
    cout<<"\nPlease enter your completed Sudoku solution(9x9): "<<endl;
    for(int i = 0; i < N; i++){
        cout<<"Enter row "<<i+1<<": ";
        for(int j = 0; j < N; j++){
            cin>>usergrid[i][j];
        }
    }
    if(isSolutionValid(original, usergrid)){
        cout<<"\nCongratulations! Your solution is correct."<<endl;
    }
    else{
        cout<<"\nSorry, your solution is incorrect."<<endl;
        cout<<"\nThe correct solution is:"<<endl;
        if (solveSudoku(grid)) {
            printgrid(grid);
        } else {
            cout << "No solution exists." << endl;
        }
    }
return 0;

}


/**************************************************************************/
/*  register_types.cpp                                                    */
/**************************************************************************/
/*                         This file is part of:                          */
/*                             GODOT ENGINE                               */
/*                        https://godotengine.org                         */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur.                  */
/*                                                                        */
/* Permission is hereby granted, free of charge, to any person obtaining  */
/* a copy of this software and associated documentation files (the        */
/* "Software"), to deal in the Software without restriction, including    */
/* without limitation the rights to use, copy, modify, merge, publish,    */
/* distribute, sublicense, and/or sell copies of the Software, and to     */
/* permit persons to whom the Software is furnished to do so, subject to  */
/* the following conditions:                                              */
/*                                                                        */
/* The above copyright notice and this permission notice shall be         */
/* included in all copies or substantial portions of the Software.        */
/*                                                                        */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,        */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF     */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY   */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,   */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE      */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                 */
/**************************************************************************/

#include "register_types.h"

#include "godot_vscode_ide_plugin.h"

#ifdef TOOLS_ENABLED
#include "editor/plugins/editor_plugin.h"
#endif

void initialize_godot_vscode_ide_module(ModuleInitializationLevel p_level) {
#ifdef TOOLS_ENABLED
	if (p_level == MODULE_INITIALIZATION_LEVEL_EDITOR) {
		GDREGISTER_CLASS(GodotIDEPlugin);
		EditorPlugins::add_by_type<GodotIDEPlugin>();
	}
#endif
}

void uninitialize_godot_vscode_ide_module(ModuleInitializationLevel p_level) {
	// Nothing to do here
}


#include <iostream>
using namespace std;

int main() {
    const int MAX_CUSTOMERS = 50;
    float itemp[MAX_CUSTOMERS] = {0};  // array to store total price per customer
    int customerCount = 0;

    while (customerCount < MAX_CUSTOMERS) {
        int vegn;
        string vegt;
        float itemkg, sum = 0;
        float pp = 0, po = 0, pg = 0;

        cout << "\nWELCOME\n\n";
        cout << "Enter number of your items: ";
        cin >> vegn;

        for (int i = 0; i < vegn; i++) {
            float itemPrice = 0;

            cout << "\nEnter your item type (potato, onion, garlic): ";
            cin >> vegt;

            if (vegt == "potato") {
                cout << "Enter Potato's weight in Kg: ";
                cin >> itemkg;
                itemPrice = itemkg * 138;
                pp += itemPrice;
                cout << "Potato = Rs: " << itemPrice << endl;
            }
            else if (vegt == "onion") {
                cout << "Enter Onion's weight in Kg: ";
                cin >> itemkg;
                itemPrice = itemkg * 23;
                po += itemPrice;
                cout << "Onion = Rs: " << itemPrice << endl;
            }
            else if (vegt == "garlic") {
                cout << "Enter Garlic's weight in Kg: ";
                cin >> itemkg;
                itemPrice = itemkg * 790;
                pg += itemPrice;
                cout << "Garlic = Rs: " << itemPrice << endl;
            }
            else {
                cout << "Invalid Item Name" << endl;
            }
        }

        // Print final bill for this customer
        cout << "\nYour Bill\n\n";
        if (pp > 0) cout << "Potato = Rs " << pp << endl;
        if (po > 0) cout << "Onion = Rs " << po << endl;
        if (pg > 0) cout << "Garlic = Rs " << pg << endl;

        sum = pp + po + pg;
        cout << "\nTotal Price = Rs " << sum << endl;
        cout << "\nThank you, come again!!\n";

        // Store total in array
        itemp[customerCount] = sum;
        customerCount++;

        // Ask user to continue or exit
        if (customerCount < MAX_CUSTOMERS) {
            char choice;
            cout << "\nDo you want to continue for next customer? (y/n): ";
            cin >> choice;
            if (choice != 'y' && choice != 'Y') break;
        }
    }

    // Print total sales for all customers
    cout << "\nSales Summary:\n";
    float totalSales = 0;
    for (int i = 0; i < customerCount; i++) {
        cout << "Customer #" << (i + 1) << " Total = Rs " << itemp[i] << endl;
        totalSales += itemp[i];
    }
    cout << "\nTotal Sales = Rs " << totalSales << endl;

    return 0;
}


// APeripheralPyramid.cpp
#include "APeripheralPyramid.h"
#include "Components/ArrowComponent.h"
#include "DrawDebugHelpers.h"
#include "URayUtils.h"
#include "Engine/World.h"
#include "Math/UnrealMathUtility.h"

APeripheralPyramid::APeripheralPyramid()
{
    PrimaryActorTick.bCanEverTick = false; // this was set to false, unsure what true does to it...

    ArrowComponent = CreateDefaultSubobject<UArrowComponent>(TEXT("ArrowComponent"));
    RootComponent = ArrowComponent;

    PeripheralGridDimension = 27;
    PeripheralPyramidAngleDegrees = 8.0f;
    PeripheralMaxRange = 15000.0f;
    bShowPeripheralRays = false; // CHANGE THIS TO FALSE TO TURN OFF RAYS
}

void APeripheralPyramid::BeginPlay()
{
    Super::BeginPlay();
}

int32 APeripheralPyramid::GetWidth() const
{
    // Aspect ratio 1.5:1 (width : height)
    return FMath::RoundToInt(PeripheralGridDimension * 1.5f);
}

int32 APeripheralPyramid::GetHeight() const
{
    return PeripheralGridDimension;
}

TArray<float> APeripheralPyramid::ComputePeripheralFlags()
{
    const int32 H = GetHeight();
    const int32 W = GetWidth();
    const int32 Total = W * H;
    TArray<float> Flags;
    Flags.Reserve(Total);

    FVector Origin = ArrowComponent->GetComponentLocation();
    FVector Forward = ArrowComponent->GetForwardVector().GetSafeNormal();
    FVector Right = ArrowComponent->GetRightVector().GetSafeNormal();
    FVector Up = ArrowComponent->GetUpVector().GetSafeNormal();

    float MaxAngRad = FMath::DegreesToRadians(PeripheralPyramidAngleDegrees);
    float VertScale = FMath::Tan(MaxAngRad);
    float HorzScale = 1.5f * VertScale;
    float CenterX = (W - 1) * 0.5f;
    float CenterY = (H - 1) * 0.5f;

    UWorld* World = GetWorld();
    if (!World)
    {
        Flags.Init(0.0f, Total);
        return Flags;
    }

    // ROW-MAJOR: for each row (j) then each column (i)
    for (int32 j = 0; j < H; ++j)         // j = 0 -> top
    {
        float NormY = (CenterY - j) / CenterY;
        for (int32 i = 0; i < W; ++i)     // i = 0 -> left
        {
            float NormX = (i - CenterX) / CenterX;

            FVector Perturb = Right * (NormX * HorzScale)
                + Up * (NormY * VertScale);
            FVector Dir = (Forward + Perturb).GetSafeNormal();

            float flag = URayUtils::ComputeRayData(Origin, Dir, PeripheralMaxRange, World).OnTargetInt;
            Flags.Add(flag);

            if (bShowPeripheralRays)
                DrawDebugLine(World, Origin, Origin + Dir * PeripheralMaxRange, FColor::Green, false, 0, 0, 1.5f);
        }
    }

    return Flags;
}


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
// class Solution {
// public:
//     // 将数据存到 string 里面判断
//     bool isPalindrome(ListNode* head) {
//         ListNode* cur = head;
//         string s;
//         while (cur) {
//             s += to_string(cur->val);
//             cur = cur->next;
//         }
//         string tmp = s;
//         reverse(s.begin(), s.end());
//         if (tmp == s)
//             return true;
//         return false;
//     }
// };

class Solution {
public:
    // 快慢指针 找中点 反转后面的链表 从两边遍历
    ListNode* FindMid(ListNode* head) {
        ListNode* fast = head;
        ListNode* low = head;
        while (fast && fast->next) {
            fast = fast->next->next;
            low = low->next;
        }
        return low;
    }
    ListNode* Reverse(ListNode* head) {
        ListNode* Prev = nullptr;
        ListNode* Cur = head;
        ListNode* Next = nullptr;
        while (Cur) {
            // 保存下一个节点
            Next = Cur->next;
            // 改变指针指向
            Cur->next = Prev;
            // 往后迭代
            Prev = Cur;
            Cur = Next;
        }
        return Prev;
    }
    bool isPalindrome(ListNode* head) {
        if (head->next == nullptr)
            return true;
        ListNode* mid = FindMid(head);
        ListNode* tail = Reverse(mid);
        while (head != nullptr && tail != nullptr) {
            if (head->val != tail->val)
                return false;
            head = head->next;
            tail = tail->next;
        }
        return true;
    }
};

// link : https://leetcode.cn/problems/palindrome-linked-list/?envType=study-plan-v2&envId=top-100-liked


#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"my_first_app", origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

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

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


#include "./filtered_string_view.h"
#include <catch2/catch.hpp>
#include <iostream>

TEST_CASE("CONSTRUCTORS") {
    SECTION("default constructor initialises empty view") {
        auto s = fsv::filtered_string_view();
        CHECK(s.size() == 0);
    }

    auto const str = std::string{"cat"};
    SECTION("std::string constructor initialises correct values") {
        auto s = fsv::filtered_string_view{str};
        CHECK(s.size() == 3);
        auto ptr = s.data();
        auto result = std::string{};
        while (*ptr) {
            result += *ptr++;
        }
        CHECK(result == "cat");
    }

    auto pred = [](const char& c) { return c == 'a'; };
    SECTION("std::string constructor with predicate") {
        auto s = fsv::filtered_string_view{str, pred};
        CHECK(s.size() == 1);
        auto ptr = s.data();
        auto result = std::string{};
        while (*ptr) {
            result += *ptr++;
        }
        CHECK(result == "cat");
    }

    SECTION("null terminated constructor") {
        auto s = fsv::filtered_string_view{"cat"};
        CHECK(s.size() == 3);
        auto ptr = s.data();
        auto result = std::string{};
        while (*ptr) {
            result += *ptr++;
        }
        CHECK(result == "cat");
    }

    SECTION("null terminated constructor with predicate") {
        auto s = fsv::filtered_string_view{"cat", pred};
        CHECK(s.size() == 1);
        auto ptr = s.data();
        auto result = std::string{};
        while (*ptr) {
            result += *ptr++;
        }
        CHECK(result == "cat");
    }

    SECTION("copy constructor") {}

    SECTION("move constructor") {}
}

TEST_CASE("MEMBER FUNCTIONS") {
    SECTION("empty - false case") {
        auto s = fsv::filtered_string_view{"Australian Shephard"};
        CHECK(s.empty() == false);
    }
    SECTION("empty - true case") {
        auto s = fsv::filtered_string_view{};
        CHECK(s.empty() == true);
    }

    SECTION("data - spaces") {
        auto s = fsv::filtered_string_view{"Answer to life is 42", [](const char&) { return false; }};
        auto ptr = s.data();
        auto result = std::string{};
        while (*ptr) {
            result += *ptr++;
        }

        CHECK(result == "Answer to life is 42");
    }

    SECTION("data - special characters") {
        auto s = fsv::filtered_string_view{"@ngryb!rd5"};
        auto ptr = s.data();
        auto result = std::string{};
        while (*ptr) {
            result += *ptr++;
        }

        CHECK(result == "@ngryb!rd5");
    }

    SECTION("predicate - works") {
        const auto pred = [](const char&) {
            std::cout << "hi!";
            return true;
        };

        auto s = fsv::filtered_string_view{"doggo", pred};

        const auto& p = s.predicate();
        CHECK(p('a'));
    }
}

TEST_CASE("NON-MEMBER OPERATORS") {
    auto apples = fsv::filtered_string_view{"apples"};
    SECTION("equality - true") {
        CHECK(apples == apples);
    }
    auto ban = fsv::filtered_string_view{"bananas"};
    SECTION("equality - false") {
        CHECK(apples != ban);
    }
    auto fban = fsv::filtered_string_view{"bananas", [](char const& c) { return c != 'a' && c != ' '; }};
    auto bnns = fsv::filtered_string_view{"bnns"};
    SECTION("equality - filtered true") {
        CHECK(fban == bnns);
    }
    SECTION("equality - filtered false") {
        CHECK_FALSE(ban == fban);
        CHECK(ban != fban);
    }

    // TESTING >
    SECTION("gt - true") {
        CHECK(ban > apples);
    }
    SECTION("gt - false") {
        CHECK_FALSE(apples > ban);
    }
    auto lo = fsv::filtered_string_view{"horn"};
    auto hi = fsv::filtered_string_view{"a mule", [](char const& c) { return c != 'a' && c != ' '; }};
    SECTION("gt - filtered true") {
        CHECK(hi > lo);
    }
    SECTION("gt - filtered false") {
        CHECK_FALSE(lo > hi);
    }

    // TESTING >=
    SECTION("gte - true") {
        CHECK(fban >= bnns);
        CHECK(ban >= apples);
        CHECK(hi >= lo);
    }
    SECTION("gte - false") {
        CHECK_FALSE(apples >= ban);
        CHECK_FALSE(lo >= hi);
    }

    // TESTING <
    SECTION("lt - true") {
        CHECK(apples < ban);
    }
    SECTION("lt - false") {
        CHECK_FALSE(ban < apples);
    }
    SECTION("lt - filtered true") {
        CHECK(lo < hi);
    }
    SECTION("lt - filtered false") {
        CHECK_FALSE(hi < lo);
    }

    // TESTING <=
    SECTION("lte - true") {
        CHECK(fban <= bnns);
        CHECK(apples <= ban);
        CHECK(lo <= hi);
    }
    SECTION("lte - false") {
        CHECK_FALSE(ban <= apples);
        CHECK_FALSE(hi <= lo);
    }

    auto oss = std::ostringstream{};
    SECTION("output - full string") {
        auto view = fsv::filtered_string_view{"jumpingjacks"};
        oss << view;
        CHECK(oss.str() == "jumpingjacks");
    }
    SECTION("output - filtered") {
        auto view = fsv::filtered_string_view{"c++ > rust > java", [](const char& c)


#include <iostream>
#include <cmath>

using namespace std;

int main() {
	float x, y;
	int pause = 1;
	char islem;

	while (pause == 1) {
		cout << "x = ";
		cin >> x;
		cout << endl;

		cout << "y = ";
		cin >> y;
		cout << endl;

		cout << "Toplama = 1" << endl;
		cout << "Cikarma = 2" << endl;
		cout << "Carpma = 3" << endl;
		cout << "Bolme = 4" << endl;
		cout << "Kuvvet Alma = 5" << endl;
		cout << "Cikmak icin herhangi bir þey tuslayin." << endl;
		cout << "Islem Secin = ";
		cin >> islem;
		cout << endl;

		if (islem == '1') {
			cout << x << "+" << y << "=" << x + y << endl;
		}
		else if (islem == '2') {
			cout << x << "-" << y << "=" << x - y << endl;
		}
		else if (islem == '3') {
			cout << x << "*" << y << "=" << x * y << endl;
		}
		else if (islem == '4') {
			if (y == 0) {
				cout << "HATA: Sifira (0) bolemezsin." << endl;
			}
			else {
				cout << x << "/" << y << "=" << x / y << endl;
			}
		}
		else if (islem == '5') {
			cout << pow(x,y) << endl;
		}
		else {
			cout << "Cikis Yapiliyor." << endl;
		}
	}
}


#include "drowsynetwork/Socket.hpp"

namespace DrowsyNetwork {

Socket::Socket(Executor& IOContext, std::unique_ptr<TcpSocket>&& Socket) :
    m_Strand(IOContext.get_executor()),
    m_Socket(std::move(Socket)),
    m_IsWriting(false),
    m_IsActive(false) {
    static std::atomic<uint64_t> s_NextId(1);
    m_Id = s_NextId.fetch_add(1);

    LOG_DEBUG("Socket {} created", m_Id);
}

Socket::~Socket() {
    // asio sockets will clean after themselves when they go out of scope but let's show intent
    Socket::HandleDisconnect(); // Make sure we properly clean the resources

    LOG_DEBUG("Socket {} destroyed", m_Id);
}

TcpSocket* Socket::GetSocket() const {
    return m_Socket.get();
}

void Socket::Setup() {
    asio::post(m_Strand, [self = weak_from_this()]() {
        if (auto Socket = self.lock()) {
            Socket->SetActive(true);
            Socket->HandleRead();
        }
    });
}

void Socket::HandleWrite() {
    if (!IsActive() || m_WriteQueue.empty())
        return;

    auto& Instance = m_WriteQueue.front();

    asio::async_write(*m_Socket, asio::buffer(Instance->data(), Instance->size()),
        asio::bind_executor(m_Strand, [self = weak_from_this()](asio::error_code ErrorCode, std::size_t BytesTransferred) {
            if (auto Socket = self.lock()) {
                Socket->FinishWrite(ErrorCode, BytesTransferred);
            } else {
                // Handle invalid socket
                LOG_ERROR("Invalid socket at handle write");
            }
    }));
}

void Socket::FinishWrite(asio::error_code ErrorCode, std::size_t BytesTransferred) {
    if (!IsActive())
        return;

    if (ErrorCode) {
        LOG_ERROR("Socket {} write failed: {}", m_Id, ErrorCode.message());
        // For write errors, always consider them fatal and close the connection
        // Partial writes are handled by asio::async_write, so any error here is serious
        Disconnect();
        return;
    }

    auto& Instance = m_WriteQueue.front();
    LOG_DEBUG("Socket {} sent {} bytes, remaining {} ref count", m_Id, Instance->size(), Instance.use_count());
    m_WriteQueue.pop_front();
    if (!m_WriteQueue.empty())
        HandleWrite();
    else
        m_IsWriting = false;
}

void Socket::HandleRead() {
    asio::async_read(*m_Socket, m_ReadBuffer, asio::transfer_at_least(1),
        asio::bind_executor(m_Strand,
        [self = weak_from_this()](asio::error_code ErrorCode, std::size_t BytesTransferred) {
            if (auto socket = self.lock()) {
                socket->FinishRead(ErrorCode, BytesTransferred);
            }
        }
    ));
}

void Socket::FinishRead(asio::error_code ErrorCode, std::size_t BytesTransferred) {
    if (!IsActive())
        return;

    if (ErrorCode) {
        LOG_ERROR("Socket {} read failed: {}", m_Id, ErrorCode.message());
        if (IsFatalError(ErrorCode) && IsActive()) {
            Disconnect();
        } else if (IsActive()) {
            HandleRead();
        }
        return;
    }

    const auto Data = m_ReadBuffer.data();

    OnRead(static_cast<const uint8_t*>(Data.data()), Data.size());

    m_ReadBuffer.consume(BytesTransferred);
    HandleRead();
}

void Socket::SetActive(bool ActiveStatus) {
    m_IsActive = ActiveStatus;
}

void Socket::Disconnect() {
    asio::dispatch(m_Strand, [self = weak_from_this()]() {
        if (auto Socket = self.lock()) {
            Socket->HandleDisconnect();
        }
    });
}

void Socket::HandleDisconnect() {
    if (m_Socket->is_open()) {
        asio::error_code ErrorCode;
        m_Socket->shutdown(asio::socket_base::shutdown_both, ErrorCode);
        if (ErrorCode && ErrorCode != asio::error::not_connected) {
            LOG_ERROR("Socket {} disconnect (shutdown): {}", m_Id, ErrorCode.message());
        }

        m_Socket->close(ErrorCode);
        if (ErrorCode && ErrorCode != asio::error::not_connected) {
            LOG_ERROR("Socket {} disconnect (close): {}", m_Id, ErrorCode.message());
        }
    }

    SetActive(false);
    m_WriteQueue.clear(); // Clear message queue
    m_IsWriting = false;

    LOG_DEBUG("Socket {} disconnected", m_Id);

    OnDisconnect();
}

bool Socket::IsActive() const {
    return m_IsActive;
}

bool Socket::IsFatalError(const asio::error_code& ErrorCode) {
    return ErrorCode == asio::error::eof ||
           ErrorCode == asio::error::connection_reset ||
           ErrorCode == asio::error::connection_aborted ||
           ErrorCode == asio::error::network_down ||
           ErrorCode == asio::error::network_unreachable ||
           ErrorCode == asio::error::timed_out ||
           ErrorCode == asio::error::broken_pipe ||
           ErrorCode == asio::error::operation_aborted;
}

} // namespace DrowsyNetwork


#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"calculadora_imc", origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

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

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


/*
    sha1.cpp - source code of

    ============
    SHA-1 in C++
    ============

    100% Public Domain.

    Original C Code
        -- Steve Reid <steve@edmweb.com>
    Small changes to fit into bglibs
        -- Bruce Guenter <bruce@untroubled.org>
    Translation to simpler C++ Code
        -- Volker Grabsch <vog@notjusthosting.com>
    Fixing bugs and improving style
        -- Eugene Hopkinson <slowriot at voxelstorm dot com>
*/

#include "sha1.h"
#include <sstream>
#include <iomanip>
#include <fstream>

/* Help macros */
#define SHA1_ROL(value, bits) (((value) << (bits)) | (((value) & 0xffffffff) >> (32 - (bits))))
#define SHA1_BLK(i) (block[i&15] = SHA1_ROL(block[(i+13)&15] ^ block[(i+8)&15] ^ block[(i+2)&15] ^ block[i&15],1))

/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
#define SHA1_R0(v,w,x,y,z,i) z += ((w&(x^y))^y)     + block[i]    + 0x5a827999 + SHA1_ROL(v,5); w=SHA1_ROL(w,30);
#define SHA1_R1(v,w,x,y,z,i) z += ((w&(x^y))^y)     + SHA1_BLK(i) + 0x5a827999 + SHA1_ROL(v,5); w=SHA1_ROL(w,30);
#define SHA1_R2(v,w,x,y,z,i) z += (w^x^y)           + SHA1_BLK(i) + 0x6ed9eba1 + SHA1_ROL(v,5); w=SHA1_ROL(w,30);
#define SHA1_R3(v,w,x,y,z,i) z += (((w|x)&y)|(w&x)) + SHA1_BLK(i) + 0x8f1bbcdc + SHA1_ROL(v,5); w=SHA1_ROL(w,30);
#define SHA1_R4(v,w,x,y,z,i) z += (w^x^y)           + SHA1_BLK(i) + 0xca62c1d6 + SHA1_ROL(v,5); w=SHA1_ROL(w,30);

SHA1::SHA1()
{
    reset();
}

void SHA1::update(const std::string &s)
{
    std::istringstream is(s);
    update(is);
}

void SHA1::update(std::istream &is)
{
    std::string rest_of_buffer;
    read(is, rest_of_buffer, BLOCK_BYTES - buffer.size());
    buffer += rest_of_buffer;

    while (is)
    {
        uint32_t block[BLOCK_INTS];
        buffer_to_block(buffer, block);
        transform(block);
        read(is, buffer, BLOCK_BYTES);
    }
}

/*
 * Add padding and return the message digest.
 */

std::string SHA1::final()
{
    /* Total number of hashed bits */
    uint64_t total_bits = (transforms*BLOCK_BYTES + buffer.size()) * 8;

    /* Padding */
    buffer += 0x80;
    unsigned int orig_size = buffer.size();
    while (buffer.size() < BLOCK_BYTES)
    {
        buffer += (char)0x00;
    }

    uint32_t block[BLOCK_INTS];
    buffer_to_block(buffer, block);

    if (orig_size > BLOCK_BYTES - 8)
    {
        transform(block);
        for (unsigned int i = 0; i < BLOCK_INTS - 2; i++)
        {
            block[i] = 0;
        }
    }

    /* Append total_bits, split this uint64_t into two uint32_t */
    block[BLOCK_INTS - 1] = total_bits;
    block[BLOCK_INTS - 2] = (total_bits >> 32);
    transform(block);

    /* Hex std::string */
    std::ostringstream result;
    for (unsigned int i = 0; i < DIGEST_INTS; i++)
    {
        result << std::hex << std::setfill('0') << std::setw(8);
        result << (digest[i] & 0xffffffff);
    }

    /* Reset for next run */
    reset();

    return result.str();
}

std::string SHA1::from_file(const std::string &filename)
{
    std::ifstream stream(filename.c_str(), std::ios::binary);
    SHA1 checksum;
    checksum.update(stream);
    return checksum.final();
}

void SHA1::reset()
{
    /* SHA1 initialization constants */
    digest[0] = 0x67452301;
    digest[1] = 0xefcdab89;
    digest[2] = 0x98badcfe;
    digest[3] = 0x10325476;
    digest[4] = 0xc3d2e1f0;

    /* Reset counters */
    transforms = 0;
    buffer = "";
}

/*
 * Hash a single 512-bit block. This is the core of the algorithm.
 */

void SHA1::transform(uint32_t block[BLOCK_BYTES])
{
    /* Copy digest[] to working vars */
    uint32_t a = digest[0];
    uint32_t b = digest[1];
    uint32_t c = digest[2];
    uint32_t d = digest[3];
    uint32_t e = digest[4];

    /* 4 rounds of 20 operations each. Loop unrolled. */
    SHA1_R0(a,b,c,d,e, 0);
    SHA1_R0(e,a,b,c,d, 1);
    SHA1_R0(d,e,a,b,c, 2);
    SHA1_R0(c,d,e,a,b, 3);
    SHA1_R0(b,c,d,e,a, 4);
    SHA1_R0(a,b,c,d,e, 5);
    SHA1_R0(e,a,b,c,d, 6);
    SHA1_R0(d,e,a,b,c, 7);
    SHA1_R0(c,d,e,a,b, 8);
    SHA1_R0(b,c,d,e,a, 9);
    SHA1_R0(a,b,c,d,e,10);
    SHA1_R0(e,a,b,c,d,11);
    SHA1_R0(d,e,a,b,c,12);
    SHA1_R0(c,d,e,a,b,13);
    SHA1_R0(b,c,d,e,a,14);
    SHA1_R0(a,b,c,d,e,15);
    SHA1_R1(e,a,b,c,d,16);
    SHA1_R1(d,e,a,b,c,17);
    SHA1_R1(c,d,e,a,b,18);
    SHA1_R1(b,c,d,e,a,19);
    SHA1_R2(a,b,c,d,e,20);
    SHA1_R2(e,a,b,c,d,21);
    SHA1_R2(d,e,a,b,c,22);
    SHA1_R2(c,d,e,a,b,23);
    SHA1_R2(b,c,d,e,a,24);
    SHA1_R2(a,b,c,d,e,25);
    SHA1_R2(e,a,b,c,d,26);
    SHA1_R2(d,e,a,b,c,27);
    SHA1_R2(c,d,e,a,b,28);
    SHA1_R2(b,c,d,e,a,29);
    SHA1_R2(a,b,c,d,e,30);
    SHA1_R2(e,a,b,c,d,31);
    SHA1_R2(d,e,a,b,c,32);
    SHA1_R2(c,d,e,a,b,33);
    SHA1_R2(b,c,d,e,a,34);
    SHA1_R2(a,b,c,d,e,35);
    SHA1_R2(e,a,b,c,d,36);
    SHA1_R2(d,e,a,b,c,37);
    SHA1_R2(c,d,e,a,b,38);
    SHA1_R2(b,c,d,e,a,39);
    SHA1_R3(a,b,c,d,e,40);
    SHA1_R3(e,a,b,c,d,41);
    SHA1_R3(d,e,a,b,c,42);
    SHA1_R3(c,d,e,a,b,43);
    SHA1_R3(b,c,d,e,a,44);
    SHA1_R3(a,b,


#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();
  }
  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;
}


#include <iostream>
#include <vector>
#include <fstream>
#include "sparseMatrix.hpp"
#include "gmres.hpp"

using RESULT=std::tuple<int, float, double>;

void loadBinToCSR(SpM<double> &A, std::string mtx_path)
{
    std::ifstream binFile(mtx_path, std::ios::in | std::ios::binary);

    if (!binFile.is_open()) {
        std::cerr << "can not open output file!" << std::endl;
        return;
    }
    binFile.read(reinterpret_cast<char*>(&A.nrows), sizeof(A.nrows));
    binFile.read(reinterpret_cast<char*>(&A.ncols), sizeof(A.ncols));
    binFile.read(reinterpret_cast<char*>(&A.nnz), sizeof(A.nnz));

    A.rows = (uint *)malloc((A.nrows + 1) * sizeof(uint));
    A.cols = (uint *)malloc(A.nnz * sizeof(uint));
    A.vals = (double *)malloc(A.nnz * sizeof(double));

    binFile.read(reinterpret_cast<char*>(A.rows), (A.nrows + 1) * sizeof(uint));
    binFile.read(reinterpret_cast<char*>(A.cols), A.nnz * sizeof(uint));
    binFile.read(reinterpret_cast<char*>(A.vals), A.nnz * sizeof(double));
    binFile.close();
}

int main(int argc, char *argv[])
{
    string mtx_name = argv[1];
    mtx_name.erase(mtx_name.begin(), mtx_name.begin() + mtx_name.rfind('/') + 1);
    mtx_name.erase(mtx_name.begin() + mtx_name.find('.'), mtx_name.end());

    SpM<double> A_double;                      //禁止修改
    loadBinToCSR(A_double, argv[1]); //禁止修改

    std::cout << mtx_name << ": M = " << A_double.nrows << ", N = "  << A_double.ncols << std::endl;

    std::vector<double> x_double(A_double.nrows, 0); //禁止修改
    std::vector<double> b_double(A_double.nrows, 1); //禁止修改
    initialize(&A_double, &x_double[0], &b_double[0]);

    std::cout << "start running gmres" << std::endl;
    auto res = gmres(&A_double, &x_double[0], &b_double[0]); // GMRES算法核心，需重点优化

    std::cout << "iters = " << std::get<0>(res) << ", time = "  << std::get<1>(res) << "ms, resid = " << std::get<2>(res) << std::endl;

    // ==============禁止修改下列结果输出==============
    std::ofstream outfile("gmres_time.txt", std::ios::app);
    if (!outfile.is_open()) {
        std::cerr << "can not open output file!" << std::endl;
        return 1;
    }
    outfile << mtx_name << " " << std::get<0>(res) << " " << std::get<1>(res) << " " << std::get<2>(res) << "\n";
    outfile.close();
    // ==============禁止修改上列结果输出==============

    return 0;
}


#include <iostream>
#include <map>
#include <string>
#include <algorithm>

std::string toLower(const std::string &str) {
    std::string lower = str;
    std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
    return lower;
}

int main() {
    std::map<std::string, std::string> shortcuts = {
        {"copy", "Command + C"},
        {"paste", "Command + V"},
        {"cut", "Command + X"},
        {"undo", "Command + Z"},
        {"redo", "Command + Shift + Z"},
        {"select all", "Command + A"},
        {"find", "Command + F"},
        {"screenshot", "Command + Shift + 4"},
        {"spotlight search", "Command + Space"},
        {"quit app", "Command + Q"},
        {"force quit", "Command + Option + Escape"},
        {"new window", "Command + N"},
        {"new tab", "Command + T"},
        {"close window", "Command + W"},
        {"save", "Command + S"},
        {"print", "Command + P"}
    };

    int choice;
    std::string input;

    while (true) {
        std::cout << "\n=== MacBook Shortcut Finder ===\n";
        std::cout << "1. Search by shortcut name\n";
        std::cout << "2. Search by key combination\n";
        std::cout << "3. Show all shortcuts\n";
        std::cout << "4. Exit\n";
        std::cout << "Enter choice: ";
        std::cin >> choice;
        std::cin.ignore();

        if (choice == 1) {
            std::cout << "Enter shortcut name: ";
            std::getline(std::cin, input);
            input = toLower(input);

            bool found = false;
            for (auto &s : shortcuts) {
                if (toLower(s.first) == input) {
                    std::cout << "Shortcut for '" << s.first << "' is: " << s.second << "\n";
                    found = true;
                    break;
                }
            }
            if (!found) std::cout << "Shortcut not found.\n";

        } else if (choice == 2) {
            std::cout << "Enter key combination (e.g., Command + C): ";
            std::getline(std::cin, input);

            bool found = false;
            for (auto &s : shortcuts) {
                if (toLower(s.second) == toLower(input)) {
                    std::cout << "Key combination '" << s.second << "' is for: " << s.first << "\n";
                    found = true;
                    break;
                }
            }
            if (!found) std::cout << "Shortcut not found.\n";

        } else if (choice == 3) {
            std::cout << "\n--- All Shortcuts ---\n";
            for (auto &s : shortcuts) {
                std::cout << s.first << " -> " << s.second << "\n";
            }

        } else if (choice == 4) {
            std::cout << "Exiting... Goodbye!\n";
            break;

        } else {
            std::cout << "Invalid choice. Try again.\n";
        }
    }

    return 0;
}


#include <iostream>
#include <ctime>
using std::cin;
using std::cout;
using std::endl;

#define delimiter "\n--------------------------------------------------------\n"
#define tab "\t"
//#define DEBUG

class Element
{
	int Data;		//Значение элемента
	Element* pNext;	//Значение следующего элемента
	static int count;
public:
	Element(int Data, Element* pNext = nullptr)
	{
		this->Data = Data;
		this->pNext = pNext;
		count++;
#ifdef DEBUG
		cout << "EConstructor:\t" << this << endl;
#endif // DEBUG

	}
	~Element()
	{
		count--;
#ifdef DEBUG
		cout << "EDestructor:\t" << this << endl;
#endif // DEBUG

	}
	friend class ForwardList;	//приватные поля этого класса доступны другу "ForwardList"
	friend class Iterator;
	friend ForwardList operator+(const ForwardList& left, const ForwardList& right);
};
int Element::count = 0;

class Iterator
{
	Element* Temp;
public:
	Iterator(Element* Temp = nullptr) : Temp(Temp)
	{
		cout << "ItConstructor:\t" << this << endl;
	}
	~Iterator()
	{
		cout << "ItDesturctor:\t" << this << endl;
	}
	Iterator& operator++()
	{
		Temp = Temp->pNext;
		return *this;
	}
	Iterator operator++(int)
	{
		Iterator old = *this;
		Temp = Temp->pNext;
		return old;
	}
	bool operator==(const Iterator& other) const
	{
		return this->Temp == other.Temp;
	}
	bool operator!=(const Iterator& other) const
	{
		return this->Temp != other.Temp;
	}
	int operator*() const
	{
		return Temp->Data;
	}
	int& operator*()
	{
		return Temp->Data;
	}
};

class ForwardList
{
	Element* Head;
	size_t size;
public:
	Element* get_Head()const
	{
		return Head;
	}
	size_t get_size()const
	{
		return size;
	}
	Iterator begin()
	{
		return Head;
	}
	Iterator end()
	{
		return nullptr;
	}
	ForwardList()
	{
		//Конструктор по умолчанию - создаёт пустой список
		Head = nullptr;	//Если список пуст, то его голова указывает на 0
		size = 0;
		cout << "FLConstructor:\t" << this << endl;
	}
	ForwardList(int size) :ForwardList()
	{
		while (size--)push_front(0);
		cout << "FLSizeConstructor:\t" << this << endl;
	}
	ForwardList(const std::initializer_list<int>& il) :ForwardList()
	{
		for (int const* it = il.begin(); it != il.end(); it++)
		{
			push_back(*it);
		}
		cout << "FLitConstructor:\t" << this << endl;
	}
	ForwardList(const ForwardList& other) :ForwardList()
	{
		//Deep copy (Побитовое копирование)
		*this = other;
		cout << "FLCopyConstructor:\t" << this << endl;
	}
	ForwardList(ForwardList&& other) :ForwardList()
	{
		*this = std::move(other);
		cout << "FLMoveConstructor:\t" << this << endl;
	}
	~ForwardList()
	{
		clock_t t_start = clock();
		while (Head)pop_front();
		clock_t t_end = clock();
		cout << "FLDestructor:\t" << this << "\tcomplete for " << double(t_end - t_start) / CLOCKS_PER_SEC << endl;
		size = 0;
		/*while (Head)
		{
			Element* Temp = Head;
			Head = Head->pNext;
			delete Temp;
		}*/
	}

	//			Operators:
	ForwardList& operator=(const ForwardList& other)
	{
		if (this == &other)return *this;	//0) Проверяем, не является ли 'this' и 'other' одним объектом.
		while (Head)pop_front();			//1) Старое значение объекта удаляется из памяти
		//2)Deep copy (Побитовое копирование)
		for (Element* Temp = other.Head; Temp; Temp = Temp->pNext)
			push_front(Temp->Data);
		reverse();
		cout << "FLCopyAssignment:\t" << this << endl;
		return *this;

	}
	ForwardList& operator=(ForwardList&& other)
	{
		if (this == &other)return *this;
		while (Head) pop_front();
		this->Head = other.Head;
		this->size = other.size;
		other.Head = 0;
		other.size = 0;
		cout << "FLMoveAssignment:\t" << this << endl;
		return *this;

		/*if (this == &other)return *this;
		while (Head)pop_front();
		Element* last_element = nullptr;
		for (Element* Temp = other.Head; Temp; Temp = Temp->pNext)
		{
			Element* NewData = new Element(Temp->Data);
			if (!Head) Head = last_element = NewData;
			else
			{
				last_element->pNext = NewData;
				last_element = NewData;
			}
			size++;
		}
		cout << "FLMoveAssignment:\t" << this << endl;
		return *this;*/
	}

	int operator[](int size)const
	{
		Element* Temp = Head;
		for (int i = 0; i < size; i++)Temp = Temp->pNext;
		return Temp->Data;
	}
	int& operator[](int size)
	{
		Element* Temp = Head;
		for (int i = 0; i < size; i++)Temp = Temp->pNext;
		return Temp->Data;
	}

	//			Adding element:
	void push_front(int Data)
	{
		////1) Создаём элемент и сохраняем в него добавляемое значение
		//Element* New = new Element(Data);

		////2) Привязываем новый созданный элемент к началу списка
		//New->pNext = Head;

		////3) Переносим голову на новый элемент (Отправляем новый элемент в голову):
		//Head = New;
		Head = new Element(Data, Head);
		size++;
	}
	void push_back(int Data)
	{
		if (Head == nullptr)return push_front(Data);
		Element* Temp = Head;
		while (Temp->pNext)Temp = Temp->pNext;
		Temp->pNext = new Element(Data);
		size++;
		/*if (Head == nullptr)
		{
			Head = new Element(Data);
			return;
		}
		Element* Temp = Head;
		while (Temp->pNext != nullptr)
			Temp = Temp->pNext;
		Temp->pNext = new E


#include <gtest/gtest.h>
#include <vector>
#include <iostream>
#include "document.hpp"
using namespace std;

namespace test_strings{
    string content4="\"Artificial Intelligence - arXiv\" and \"Journal of Artificial Intelligence Research\" "
    "are excellent resources for academic research papers. ArXiv is a repository for pre-print "
    "papers in various scientific fields, including AI. The Journal of Artificial Intelligence "
    "Research (JAIR) publishes peer-reviewed articles on all areas of AI.\"AI researchers lured "
    "with high salaries are leaving Meta, quoting Mark Zuckerberg’s own advice on their way out\" "
    "from The Economic Times. This article provides insight into the competitive landscape of AI "
    "research, discussing the \"talent war\" between major tech companies and what motivates top researchers.";;
    string content3="\"AI Apocalypse? Why language surrounding tech is sounding increasingly religious\" from the Associated Press. "
"This article discusses the growing debate around the potential of AI to bring about a technological \"apocalypse\" or a new age of human evolution. "
"It highlights different perspectives from researchers and tech CEOs.\""
"Are AI bots now ‘digital beings’ with rights? New group fuels global debate on consciousness and human morality\" from The Economic Times. "
"This article delves into the complex and emerging debate over whether AI systems could one day be considered \"conscious\" and deserve rights. "
"It mentions a group advocating for \"AI rights\" and counter-arguments from tech leaders.";
    string content2="\"AI boosts career, does not replace it: Real work lessons from engineer who uses AI as second brain\" from The Economic Times. "
"This piece focuses on how AI is being used as a tool to enhance human productivity rather than replace jobs. "
"It includes an example of a software engineer who uses AI to accelerate projects and improve his workflow.\""
"AI bringing dinosaurs to life: How scientists are turning Jurassic Park into reality\" from The Times of India. "
"This article explores how AI is being used in paleontology to reconstruct fossils, generate realistic visuals of dinosaurs, "
"and even hypothesize genetic sequences.";
    string content1="\"The birth of Artificial Intelligence (AI) research\" by Lawrence Livermore National Laboratory. "
"This article provides a timeline of key events, starting with Alan Turing's 1950 paper \"Computing Machinery and Intelligence\" "
"and the 1956 Dartmouth workshop where the term \"artificial intelligence\" was coined. "
"It also discusses the early boom and subsequent \"AI winters\" in funding and interest.\""
"The History of AI: A Timeline of Artificial Intelligence\" from Coursera. "
"This article offers a detailed timeline, including historical and fictional precedents for AI, "
"such as Jonathan Swift's \"Gulliver's Travels,\" and key early developments like the creation of the first chatbot, ELIZA, in 1966.";
}
TEST(Load_Test,first_test){
    DomLoad dom_obj;
    string ds="../../random_name";
    EXPECT_THROW(dom_obj.load_data(ds),invalid_argument);

}
TEST(Load_Test,second_test){
    DomLoad dom_obj;
    string ds="../../README.md";
    EXPECT_THROW(dom_obj.load_data(ds),invalid_argument);

}
TEST(Load_Test,third_test){
    DomLoad dom_obj;
    string ds="../../data";
    vector<Document> docs = dom_obj.load_data(ds);
    sort(docs.begin(),docs.end());
    vector<string> names;
    vector<string> expected_names={"art1.txt","art2.txt","art3.txt","art4.txt"};
    for(int i=0;i<docs.size();i++){
        names.push_back(docs[i].get_file_name());
    }
    EXPECT_EQ(names,expected_names);
}
TEST(Load_Test,fourth_test){
    DomLoad dom_obj;
    Document doc("art1.txt",test_strings::content1);
    Document doc1("art2.txt",test_strings::content2);
    Document doc2("art3.txt",test_strings::content3);
    Document doc3("art4.txt",test_strings::content4);
    string ds="../../data";
    vector<Document> vt = dom_obj.load_data(ds);
    vector<Document> expected_vector={doc,doc1,doc2,doc3};
    sort(vt.begin(),vt.end());
    sort(expected_vector.begin(),expected_vector.end());
    for(size_t i=0;i<vt.size();++i){
      EXPECT_EQ(vt[i].get_file_content(), expected_vector[i].get_file_content());
      EXPECT_EQ(vt[i].get_file_name(), expected_vector[i].get_file_name());
    }

}
TEST(Load_Test,fifth_test){
    DomLoad dom_obj;
    string ds="../../data";
    vector<Document> vt = dom_obj.load_data(ds);
    sort(vt.begin(),vt.end());
    EXPECT_EQ(vt[0].get_file_content(),test_strings::content1);
    EXPECT_EQ(vt[1].get_file_content(),test_strings::content2);
    EXPECT_EQ(vt[2].get_file_content(),test_strings::content3);
    EXPECT_EQ(vt[3].get_file_content(),test_strings::content4);
}
TEST(Tokenization,first_Test){
    Document obj("art.txt","DomLoad is a class");
    string cont= obj.get_file_content();
    icu::UnicodeString norm_string = helpers::normalization(cont);
    obj.set_normaliz


#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;

struct Habit {
    string name;
    int completedDays;
    int totalDays;
};

vector<Habit> loadHabits() {
    vector<Habit> habits;
    ifstream file("habits.txt");
    if(file.is_open()) {
        string line;
        while(getline(file, line)) {
            stringstream ss(line);
            Habit h;
            getline(ss, h.name, '|');   // habit name until '|'
            ss >> h.completedDays >> h.totalDays;
            habits.push_back(h);
        }
        file.close();
    } else {
        cout << "No existing habit file found. Starting fresh!\n";
    }
    return habits;
}

void saveHabits(const vector<Habit>& habits) {
    ofstream file("habits.txt");
    for(const auto& h : habits) {
        file << h.name << "|" << h.completedDays << " " << h.totalDays << endl;
    }
    file.close();
}

void addHabit(vector<Habit>& habits) {
    Habit h;
    cout << "Enter habit name: ";
    cin.ignore();  // clear leftover newline
    getline(cin, h.name);
    h.completedDays = 0;
    h.totalDays = 0;
    habits.push_back(h);
    saveHabits(habits);
    cout << "Habit added successfully!\n";
}

void markHabit(vector<Habit>& habits) {
    cout << "Enter habit number to mark completed:\n";
    for(int i=0; i<habits.size(); i++)
        cout << i+1 << ". " << habits[i].name << endl;
    int choice; cin >> choice;
    if(choice > 0 && choice <= habits.size()) {
        habits[choice-1].completedDays++;
        habits[choice-1].totalDays++;
        saveHabits(habits);
        cout << "Habit marked completed!\n";
    } else {
        cout << "Invalid choice!\n";
    }
}

void viewHabits(const vector<Habit>& habits) {
    cout << "\nYour Habits:\n";
    for(const auto& h : habits) {
        double progress = (h.totalDays==0 ? 0 : (double)h.completedDays/h.totalDays*100);
        cout << h.name << " - " << h.completedDays << "/" << h.totalDays
             << " (" << progress << "%)\n";
    }
}

int main() {
    vector<Habit> habits = loadHabits();
    int choice;
    do {
        cout << "\nHabit Tracker Menu:\n";
        cout << "1. Add Habit\n2. Mark Habit Completed\n3. View Habits\n4. Exit\n";
        cin >> choice;
        switch(choice) {
            case 1: addHabit(habits); break;
            case 2: markHabit(habits); break;
            case 3: viewHabits(habits); break;
            case 4: cout << "Exiting...\n"; break;
            default: cout << "Invalid choice!\n";
        }
    } while(choice != 4);
    return 0;
}


#include "calculator.h"

Calculator::Calculator() {
    m_operations = {
        {"+", CalculatorOperations::ADDITION},
        {"-", CalculatorOperations::SUBSTRACTION},
        {"*", CalculatorOperations::MULTIPLAY},
        {"/", CalculatorOperations::DIVISION},
    };
}

int Calculator::Reset() {
    m_value1 = 0.0;
    m_value2 = 0.0;
    oper = CalculatorOperations::EMPTY;
    m_result = 0.0;
    m_isDecimalPart = false;
    m_calculationDone = false;
    m_decimalPlace = 0.1;
    m_displayString.clear();
    return 0;
}

int Calculator::Digit(int d) {
    if (m_calculationDone) {
        Reset();
    }

    if (oper == CalculatorOperations::EMPTY) {
        if (!m_isDecimalPart) {
            m_value1 = m_value1 * 10 + d;
        } else {
            m_value1 = m_value1 + d * m_decimalPlace;
            m_decimalPlace *= 0.1;
        }
    } else {
        if (!m_isDecimalPart) {
            m_value2 = m_value2 * 10 + d;
        } else {
            m_value2 = m_value2 + d * m_decimalPlace;
            m_decimalPlace *= 0.1;
        }
    }
    m_displayString.append(QString::number(d));
    return 0;
}

void Calculator::AddDecimalPoint() {
    if (!m_isDecimalPart) {
        if (m_calculationDone) {
            Reset();
        }
        m_isDecimalPart = true;
        m_decimalPlace = 0.1;
        m_displayString.append(".");
    }
}

int Calculator::ApplyUnaryOperation(const QString& operation) {
    double currentValue;
    if (oper == CalculatorOperations::EMPTY) {
        currentValue = m_value1;
    } else {
        currentValue = m_value2;

    }

    if (operation == "sqrt") {
        if (currentValue < 0) {
            return -1;
        }
        m_result = std::sqrt(currentValue);
    } else

        if (operation == "x^2") {
        m_result = currentValue * currentValue;
    } else

        if (operation == "%") {
        m_result = currentValue / 100.0;
    } else {
        return -1;
    }

    //Обновляем значение и пересобираем строку для отображения
    if (oper == CalculatorOperations::EMPTY) {
        m_value1 = m_result;
         m_displayString = QString::number(m_value1);
    } else {
        m_value2 = m_result;
        int lastSpace = m_displayString.lastIndexOf(' ');
        if (lastSpace != -1) {
            m_displayString.truncate(lastSpace + 1);
        }
        m_displayString.append(QString::number(m_value2));
    }

    return 0;
}

int Calculator::Operation(Calculator::CalculatorOperations operation) {
    if (oper != CalculatorOperations::EMPTY && !m_calculationDone) {
        Calculate();
    }

    m_calculationDone = false;
    m_isDecimalPart = false;

    m_decimalPlace = 0.1;
    oper = operation;
    m_displayString.append(" " + GetOperationSymbol() + " ");
    return 0;
}

int Calculator::Calculate() {
    switch (oper) {
        case CalculatorOperations::ADDITION:
            m_result = m_value1 + m_value2;
            break;
        case CalculatorOperations::SUBSTRACTION:
            m_result = m_value1 - m_value2;
            break;
        case CalculatorOperations::MULTIPLAY:
            m_result = m_value1 * m_value2;
            break;
        case CalculatorOperations::DIVISION:
            if (m_value2 == 0.0) {
                return -1;
            }
            m_result = m_value1 / m_value2;
            break;
    }

    m_value1 = m_result;
    m_value2 = 0.0;
    m_displayString.append(" = " + QString::number(m_result));
    m_calculationDone = true;
    return 0;
}

QString Calculator::GetDisplayText() {
    if (m_displayString.isEmpty()) {
        return "0";
    }
    return m_displayString;
}

QString Calculator::GetOperationSymbol() { return m_operations.key(oper); }

QMap<QString, Calculator::CalculatorOperations>* Calculator::GetOperations() {
    return &m_operations;
}


#include "Title.h"
#include "TestScene.h"

using namespace LWP;
using namespace LWP::Input;

Title::~Title()
{
	bgm_.Stop();
}

// 初期化
void Title::Initialize() {
#if DEMO
#else
	LWP::Window::ChangeFullScreenMode();
#endif

	drawing_.Initialize();
	playerMouseOperation_.Initialize();
	minion_.Initialize();

	titleSprite_.LoadTexture("Title.png");
	titleSprite_.worldTF.translation = { 1920.0f / 2.0f, 1080.0f / 2.0f, 0.0f };

	sceneTransitionBlackOut_.Initialize();
	sceneTransitionBlackOut_.SetIsFadeIn(false);

	backGround_.Initialize();

	nextSprite_.Initialize();

	bgm_.LoadShortPath("title.mp3");
	bgm_.PlayLoop();
	bgm_.SetVolume(0.1f);

}

// 更新
void Title::Update() {

	if (!sceneTransitionBlackOut_.GetStoppingUpdates()) {
		sceneTransitionBlackOut_.Update();
		if (sceneTransitionBlackOut_.GetSwitchScene()) {
			nextSceneFunction = []() { return new TestScene(); };
		}
	}
	else {
		if (drawing_.GetGameStart()) {
			sceneTransitionBlackOut_.Reset();	// 次のシーンに行くための処理
		}
	}

	playerMouseOperation_.Update();

	drawing_.Update(playerMouseOperation_.GetIsDragging());

	minion_.Update();

	nextSprite_.Update();

}