#include <iostream>
#include "auth_lib.h"
#include <thread>
#include <chrono>

using namespace std;
using namespace AuthLib;

int main() {

    Initialize();

    cout << "=== Authentication Test Program ===" << endl;

    string licenseKey;
    cout << "Enter license key: ";
    cin >> licenseKey;

    Authenticate(licenseKey, [](bool success, const string& message) {
        cout << "\nAuthentication result: " << message << endl;
        if (success) {
            cout << "Remaining days: " << GetRemainingDays() << endl;
        }
        });

    string loadingText = "Loading...";
    int index = 0;

    while (!IsAuthenticated() && GetAuthMessage().empty()) {
        cout << "\r" << loadingText.substr(0, index + 1) << flush;
        this_thread::sleep_for(chrono::milliseconds(1));
        index = (index + 1) % loadingText.size();
    }

    cout << "\r" << string(loadingText.size(), ' ') << "\r";

    if (!GetAuthMessage().empty() && !IsAuthenticated()) {
        cout << "Error: " << GetAuthMessage() << endl;
    }

    if (IsAuthenticated()) {
        cout << "=== ACCESS GRANTED ===" << endl;

    }
    else {
        cout << "=== ACCESS DENIED ===" << endl;
    }
    system("pause");
    return 0;
}


#include <SFML/Graphics.hpp>
#include <iostream>
#include <stack>
using namespace std;
using namespace sf;

struct Box
{
    int x;
    int y;
    bool isEmpty;
    int parentRow;
    int parentCol;
    int row;
    int col;
    bool isVisited;
    bool isPath;
    bool isExplored;
};

vector<vector<Box>> boxList(40);

Box start;
Box finish;

string bfsLength = "0";
string dijkstraLength = "0";
string dfsLength = "0";

void drawWindow(RectangleShape box, bool isStartSelected, bool isFinishSelected, RenderWindow &win, string time, Text txt, int boxSize, string algo)
{
    for (int r = 0; r < 40; r++)
    {
        for (int c = 0; c < 50; c++)
        {
            box.setPosition(Vector2f(boxList[r][c].x, boxList[r][c].y));
            if (boxList[r][c].x == start.x && boxList[r][c].y == start.y && isStartSelected)
            {
                box.setFillColor(Color::Green);
                win.draw(box);
                continue;
            }
            else if (boxList[r][c].x == finish.x && boxList[r][c].y == finish.y && isFinishSelected)
            {
                box.setFillColor(Color::Red);
                win.draw(box);
                continue;
            }
            if (!boxList[r][c].isEmpty)
            {
                box.setFillColor(Color(50, 73, 97));
                win.draw(box);
            }
            else if (boxList[r][c].isVisited && boxList[r][c].isPath)
            {
                box.setFillColor(Color::Yellow);
                win.draw(box);
            }
            else if (boxList[r][c].isVisited)
            {
                box.setFillColor(Color(75, 156, 237));
                win.draw(box);
            }
            else if (boxList[r][c].isExplored)
            {
                box.setFillColor(Color::Cyan);
            }
            else
            {
                box.setFillColor(Color::White);
                win.draw(box);
            }
        }
    }
    txt.setString(algo + " :");
    txt.setPosition(Vector2f(boxSize * 60 - 40, boxSize * 20 + 15));
    win.draw(txt);
    txt.setString(time);
    if (algo == "bfs")
    {
        txt.setPosition(Vector2f(boxSize * 60 + 25, boxSize * 20 + 15));
    }
    else
    {
        txt.setPosition(Vector2f(boxSize * 61 + 65, boxSize * 20 + 15));
    }
    win.draw(txt);
}

class Algorithms
{

public:
    string applyBFS(Text txt, Clock clock, string time, RenderWindow &win, RectangleShape &box, int boxSize, bool isStartSelected, bool isFinishSelected)
    {

        int rows = boxList.size();
        int cols = boxList[0].size();
        queue<Box> q;

        int nextRows[] = {1, -1, 0, 0};
        int nextCols[] = {0, 0, 1, -1};

        q.push(start);
        start.isVisited = true;

        bool isFound = false;

        while (!q.empty())
        {
            Box current = q.front();
            q.pop();

            if (current.row == finish.row && current.col == finish.col)
            {
                finish = current;
                isFound = true;
                break;
            }

            for (int i = 0; i < 4; i++)
            {
                int nextRow = current.row + nextRows[i];
                int nextCol = current.col + nextCols[i];

                if (nextRow < 0 || nextRow >= rows || nextCol < 0 || nextCol >= cols)
                {
                    continue;
                }

                if (boxList[nextRow][nextCol].isEmpty && !boxList[nextRow][nextCol].isVisited)
                {
                    boxList[nextRow][nextCol].isVisited = true;
                    boxList[nextRow][nextCol].parentRow = current.row;
                    boxList[nextRow][nextCol].parentCol = current.col;
                    q.push(boxList[nextRow][nextCol]);

                    // Update time during BFS execution
                    float timeCount = clock.getElapsedTime().asSeconds();
                    time = to_string(timeCount);

                    win.clear();
                    drawWindow(box, isStartSelected, isFinishSelected, win, time, txt, boxSize, "BFS");
                    win.display();
                    sf::sleep(sf::milliseconds(2));
                }
            }
        }

        vector<Box> path;
        boxList[start.row][start.col].parentRow = -1;
        boxList[start.row][start.col].parentCol = -1;
        if (isFound)
        {
            Box current = finish;
            while (current.parentRow != -1 && path.size() < 2000)
            {
                path.push_back(current);
                boxList[current.row][current.col].isPath = true;
                current = boxList[current.parentRow][current.parentCol];

                win.clear();
                drawWindow(box, isStartSelected, isFinishSelected, win, time, txt, boxSize, "BFS");
                win.display();
                sf::sleep(sf::milliseconds(100)); // Slower delay for path visualization
            }
            path.push_back(start);
            bfsLength = to_string(path.size() -


#include <string>
#include <regex>
#include <iostream>
#include <sstream>
#include <optional>
#include <cmath>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#include "tyme.h"

using std::ceil;

using namespace std;

namespace tyme {
    bool AbstractCulture::equals(const Culture *o) const {
        return o && o->to_string() == to_string();
    }

    string AbstractCulture::get_name() const {
        return "";
    }

    string AbstractCulture::to_string() const {
        return get_name();
    }

    int AbstractCulture::index_of(const int index, const int size) {
        const int i = index % size;
        return i < 0 ? i + size : i;
    }

    int LoopTyme::get_index() const {
        return index;
    }

    int LoopTyme::get_size() const {
        return static_cast<int>(names.size());
    }

    string LoopTyme::get_name() const {
        return names[index];
    }

    int LoopTyme::index_of(const string &name) const {
        for (int i = 0, j = get_size(); i < j; i++) {
            if (name == names[i]) {
                return i;
            }
        }
        throw invalid_argument("illegal name: " + name);
    }

    int LoopTyme::index_of(const int index) const {
        return AbstractCulture::index_of(index, get_size());
    }

    int LoopTyme::next_index(const int n) const {
        return index_of(index + n);
    }

    int LoopTyme::steps_to(const int target_index) const {
        return index_of(target_index - index);
    }

    const vector<string> Animal::NAMES = {
        "蛟", "龙", "貉", "兔", "狐", "虎", "豹", "獬", "牛", "蝠", "鼠", "燕", "猪", "獝", "狼", "狗", "彘", "鸡", "乌", "猴", "猿", "犴", "羊", "獐", "马", "鹿", "蛇", "蚓"
    };

    Animal Animal::from_index(const int index) {
        return Animal(index);
    }

    Animal Animal::from_name(const string &name) {
        return Animal(name);
    }

    Animal Animal::next(const int n) const {
        return from_index(next_index(n));
    }

    TwentyEightStar Animal::get_twenty_eight_star() const {
        return TwentyEightStar::from_index(index);
    }

    const vector<string> Beast::NAMES = {
        "青龙", "玄武", "白虎", "朱雀"
    };

    Beast Beast::from_index(const int index) {
        return Beast(index);
    }

    Beast Beast::from_name(const string &name) {
        return Beast(name);
    }

    Beast Beast::next(const int n) const {
        return from_index(next_index(n));
    }

    Zone Beast::get_zone() const {
        return Zone::from_index(index);
    }

    const vector<string> Constellation::NAMES = {
        "白羊", "金牛", "双子", "巨蟹", "狮子", "处女", "天秤", "天蝎", "射手", "摩羯", "水瓶", "双鱼"
    };

    Constellation Constellation::from_index(const int index) {
        return Constellation(index);
    }

    Constellation Constellation::from_name(const string &name) {
        return Constellation(name);
    }

    Constellation Constellation::next(const int n) const {
        return from_index(next_index(n));
    }

    /**
     * @brief 依据后天八卦排序（0坎北, 1坤西南, 2震东, 3巽东南, 4中, 5乾西北, 6兑西, 7艮东北, 8离南）
     */
    const vector<string> Direction::NAMES = {
        "北", "西南", "东", "东南", "中", "西北", "西", "东北", "南"
    };

    Direction Direction::from_index(const int index) {
        return Direction(index);
    }

    Direction Direction::from_name(const string &name) {
        return Direction(name);
    }

    Direction Direction::next(const int n) const {
        return from_index(next_index(n));
    }

    Land Direction::get_land() const {
        return Land::from_index(index);
    }

    Element Direction::get_element() const {
        const int indices[9] = {4, 2, 0, 0, 2, 3, 3, 2, 1};
        return Element::from_index(indices[index]);
    }

    const vector<string> Duty::NAMES = {
        "建", "除", "满", "平", "定", "执", "破", "危", "成", "收", "开", "闭"
    };

    Duty Duty::from_index(const int index) {
        return Duty(index);
    }

    Duty Duty::from_name(const string &name) {
        return Duty(name);
    }

    Duty Duty::next(const int n) const {
        return from_index(next_index(n));
    }

    const vector<string> Element::NAMES = {
        "木", "火", "土", "金", "水"
    };

    Element Element::from_index(const int index) {
        return Element(index);
    }

    Element Element::from_name(const string &name) {
        return Element(name);
    }

    Element Element::next(const int n) const {
        return from_index(next_index(n));
    }

    bool Element::equals(const Element &other) const {
        return to_string() == other.to_string();
    }

    Element Element::get_reinforce() const {
        return next(1);
    }

    Element Element::get_restrain() const {
        return next(2);
    }

    Element Element::get_reinforced() const {
        return next(-1);
    }

    Element Element::get_restrained() const {
        return next(-2);
    }

    Direction Element::get_direction() const {
        const int indices[5] = {2, 8, 4, 6, 0};
        return Direction::from_index(indices[index]);
    }

    const vec


// https://github.com/CedricGuillemet/ImGuizmo
// v1.91.3 WIP
//
// The MIT License(MIT)
//
// Copyright(c) 2021 Cedric Guillemet
//
// 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.
//

#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui/imgui.h"
#include "imgui/imgui_internal.h"
#include "ImGuizmo.h"

#if defined(_MSC_VER) || defined(__MINGW32__)
#include <malloc.h>
#endif
#if !defined(_MSC_VER) && !defined(__MINGW64_VERSION_MAJOR)
#define _malloca(x) alloca(x)
#define _freea(x)
#endif

// includes patches for multiview from
// https://github.com/CedricGuillemet/ImGuizmo/issues/15

namespace IMGUIZMO_NAMESPACE
{
   static const float ZPI = 3.14159265358979323846f;
   static const float RAD2DEG = (180.f / ZPI);
   static const float DEG2RAD = (ZPI / 180.f);
   const float screenRotateSize = 0.06f;
   // scale a bit so translate axis do not touch when in universal
   const float rotationDisplayFactor = 1.2f;

   static OPERATION operator&(OPERATION lhs, OPERATION rhs)
   {
     return static_cast<OPERATION>(static_cast<int>(lhs) & static_cast<int>(rhs));
   }

   static bool operator!=(OPERATION lhs, int rhs)
   {
     return static_cast<int>(lhs) != rhs;
   }

   static bool Intersects(OPERATION lhs, OPERATION rhs)
   {
     return (lhs & rhs) != 0;
   }

   // True if lhs contains rhs
   static bool Contains(OPERATION lhs, OPERATION rhs)
   {
     return (lhs & rhs) == rhs;
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
   // utility and math

   void FPU_MatrixF_x_MatrixF(const float* a, const float* b, float* r)
   {
      r[0] = a[0] * b[0] + a[1] * b[4] + a[2] * b[8] + a[3] * b[12];
      r[1] = a[0] * b[1] + a[1] * b[5] + a[2] * b[9] + a[3] * b[13];
      r[2] = a[0] * b[2] + a[1] * b[6] + a[2] * b[10] + a[3] * b[14];
      r[3] = a[0] * b[3] + a[1] * b[7] + a[2] * b[11] + a[3] * b[15];

      r[4] = a[4] * b[0] + a[5] * b[4] + a[6] * b[8] + a[7] * b[12];
      r[5] = a[4] * b[1] + a[5] * b[5] + a[6] * b[9] + a[7] * b[13];
      r[6] = a[4] * b[2] + a[5] * b[6] + a[6] * b[10] + a[7] * b[14];
      r[7] = a[4] * b[3] + a[5] * b[7] + a[6] * b[11] + a[7] * b[15];

      r[8] = a[8] * b[0] + a[9] * b[4] + a[10] * b[8] + a[11] * b[12];
      r[9] = a[8] * b[1] + a[9] * b[5] + a[10] * b[9] + a[11] * b[13];
      r[10] = a[8] * b[2] + a[9] * b[6] + a[10] * b[10] + a[11] * b[14];
      r[11] = a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11] * b[15];

      r[12] = a[12] * b[0] + a[13] * b[4] + a[14] * b[8] + a[15] * b[12];
      r[13] = a[12] * b[1] + a[13] * b[5] + a[14] * b[9] + a[15] * b[13];
      r[14] = a[12] * b[2] + a[13] * b[6] + a[14] * b[10] + a[15] * b[14];
      r[15] = a[12] * b[3] + a[13] * b[7] + a[14] * b[11] + a[15] * b[15];
   }

   void Frustum(float left, float right, float bottom, float top, float znear, float zfar, float* m16)
   {
      float temp, temp2, temp3, temp4;
      temp = 2.0f * znear;
      temp2 = right - left;
      temp3 = top - bottom;
      temp4 = zfar - znear;
      m16[0] = temp / temp2;
      m16[1] = 0.0;
      m16[2] = 0.0;
      m16[3] = 0.0;
      m16[4] = 0.0;
      m16[5] = temp / temp3;
      m16[6] = 0.0;
      m16[7] = 0.0;
      m16[8] = (right + left) / temp2;
      m16[9] = (top + bottom) / temp3;
      m16[10] = (-zfar - znear) / temp4;
      m16[11] = -1.0f;
      m16[12] = 0.0;
      m16[13] = 0.0;
      m16[14] = (-temp * zfar) / temp4;
      m16[15] = 0.0;
   }

   void Perspective(float fovyInDegrees, float aspectRatio, float znear, float zfar, float* m16)
   {
      float ymax, xmax;
      ymax = znear * tanf(fovyInDegrees * DEG2RAD);
      xmax = ymax * aspectRatio;
      Frustum(-xmax, xmax, -ymax, ymax, znear, zfar, m16);
   }

   void Cross(const float* a, const float* b, float* r)
   {
      r[0] = a[1] * b[2] - a[2] * b[1];
      r[1] = a[2] * b[0] - a[0] * b[2];
      r[2]


#include <iostream>
#include "BTree.h"

bool checkTest(std::string testName, int whatItShouldBe, int whatItIs);
BTree<int> populateTree();

int main() {
  BTree<int> myTree = populateTree();
  myTree.preOrder();
   std::cout << std::endl << std::endl;
  myTree.postOrder();
   std::cout << std::endl << std::endl;
  myTree.inOrder();
  std::cout << std::endl << std::endl;
  checkTest("Test #1, number of nodes", 35, myTree.nodeCount());

  return 0;
}

BTree <int> populateTree(){
  BTree<int> myTree;
  int values[] = {37, 32, 73, 95, 42, 12, 0, 49, 98, 7, 27, 17, 47, 87, 77, 97, 67, 85, 15, 5, 35, 55, 65, 75, 25, 45, 3, 93, 83, 53, 63, 23, 13, 43, 33};
  int size = (sizeof(values)/sizeof(*values));

  for(int i = 0; i < size; i++){
      myTree.insert(values[i]);
  }
  return myTree;

}

//Helps with Testing
bool checkTest(std::string testName, int whatItShouldBe, int whatItIs) {

  if (whatItShouldBe == whatItIs) {
    std::cout << "Passed " << testName << std::endl;
    return true;
  }
  else {
    std::cout << "***Failed test " << testName << " *** " << std::endl << "   Output was " << whatItIs << std::endl << "   Output should have been " << whatItShouldBe << std::endl;
    return false;
  }
}


#include "CentipedesPNC.h"
#include "components/components.h"
#include "Pipelines/CentipedePipeline.h"

UCentipedesPNC::UCentipedesPNC()
{
	PrimaryComponentTick.bCanEverTick = true;
}

void UCentipedesPNC::BeginPlay()
{
    Super::BeginPlay();

    InstancedMeshComponent = this->GetOwner()->GetComponentByClass<UInstancedStaticMeshComponent>();
    verifyf(InstancedMeshComponent, TEXT("Requires a UInstancedStaticMeshComponent component"));

    // create all our component types
    const PNC::ComponentType* typePosition = AddComponentType<CoPosition>();
    const PNC::ComponentType* typeRotation = AddComponentType<CoRotation>();
    const PNC::ComponentType* typeScale = AddComponentType<CoScale>();
    const PNC::ComponentType* typeFInstancedStaticMeshInstanceData = AddComponentType<CoFInstancedStaticMeshInstanceData>();
    const PNC::ComponentType* typePositionPrevious = AddComponentType<CoPositionPrevious>();
    const PNC::ComponentType* typeVelocity = AddComponentType<CoVelocity>();
    const PNC::ComponentType* typeMass = AddComponentType<CoMass>();
    const PNC::ComponentType* typeSoftBodyNode = AddComponentType<CoSoftBodyNode>();
    const PNC::ComponentType* typeCentipede = AddComponentType<CoCentipede>();
    const PNC::ComponentType* typeCentipedeBodyNode = AddComponentType<CoCentipedeBodyNode>();

    CentipedeBodyChunkStructure = AddChunkStructure({
        typePosition,
        typePositionPrevious,
        typeRotation,
        typeScale,
        typeVelocity,
        typeMass,
        typeSoftBodyNode,
        typeFInstancedStaticMeshInstanceData,
        typeCentipede,
        typeCentipedeBodyNode,
    });

    const PNC::ComponentType* typeLocalTransform = AddComponentType<CoLocalTransform>();
    const PNC::ComponentType* typeCentipedeLegNode = AddComponentType<CoCentipedeLegNode>();
    const PNC::ComponentType* typeSingleParentOutsideChunk = AddComponentType<PNC::CoSingleParentOutsideChunk>();
    const PNC::ComponentType* typeCoParentInChunk = AddComponentType<PNC::CoParentInChunk>();

    LegChunkStructure = AddChunkStructure({
        typeSingleParentOutsideChunk,
        typeCoParentInChunk,
        typePosition,
        typeRotation,
        typeScale,
        typeLocalTransform,
        typeFInstancedStaticMeshInstanceData,
        typeCentipedeLegNode,
        });

    // Create all our centipedes
    for (int32 i = 0; i < CentipedeCount; ++i)
        CreateCentipede();

    TickPipeline = new CentipedePipeline(this);
}

PNC::KChunkTree& UCentipedesPNC::CreateCentipede()
{
    auto segementCount = FMath::RandRange(CentipedeSegmentsMin, CentipedeSegmentsMin + CentipedeSegmentsRange);
    PNC::KChunkTree& centipedeChunk = AddChunk(CentipedeBodyChunkStructure, segementCount, segementCount);
    ChunksCentipede.Add(centipedeChunk);

    uint32 legNodesPerSegment = LegPerSegment * NodePerLeg * 2; // * 2 for left and right legs;
    uint32 totalLegNodes = segementCount * legNodesPerSegment;

    // Initialize the chunks data.
    InitCentipede(this).Run(centipedeChunk);
    CopyPreviousPosition().Run(centipedeChunk);

    // run the centipede logic once to move the centipede
    CentipedeLogic(this, 0).Run(centipedeChunk);

    // make sure all segment of the centipede are together at the correct length
    ConstrainSoftBodyPositions().Run(centipedeChunk);

    PNC::KChunkArrayTree& legChunkArray = AddChunkArray(LegChunkStructure, legNodesPerSegment, segementCount, segementCount, legNodesPerSegment);
    InitCentipedeLegs(segementCount, LegPerSegment, NodePerLeg, LegNodeLength, LegScale, LegScale2).Run(legChunkArray);

    // attach legs chunk to the centipede body chunk
    centipedeChunk.InsertFirstChild(&legChunkArray);

    return centipedeChunk;
}

void UCentipedesPNC::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
    Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

    // Compute the total number of nodes that will need to be rendered and resize
    // the InstancedMeshComponent accordingly.
    {
        TRACE_CPUPROFILER_EVENT_SCOPE(TEXT("Centipede Reserve space"));
        int32 totalNodes = 0;
        for (auto cw : ChunksCentipede)
        {
            auto& c = cw.get();
            totalNodes += c->GetNodeCount();

            auto firstChild = c.GetFirstChildChunk();
            auto currentChild = firstChild;
            if (currentChild != nullptr)
                do
                {
                    totalNodes += currentChild->GetChunk().GetNodeCount();
                    currentChild = currentChild->GetNextSiblingChunk();
                } while (currentChild != firstChild);

        }
        auto availableCount = InstancedMeshComponent->GetInstanceCount();
        auto neededCount = totalNodes;
        while (availableCount < neededCount)
        {
            InstancedMeshComponent->AddInstance(FTransform::Identity);
            ++availableCount;
        }
        while (availableCount


// Fill out your copyright notice in the Description page of Project Settings.

#include "Weapon/WeaponBase.h"

#include "Kismet/KismetMathLibrary.h"

#include "Weapon/BulletBase.h"
#include "Character/CharacterBase.h"
#include "Character/PlayerBase.h"
#include <AI/AIControllerBase.h>

// Sets default values
AWeaponBase::AWeaponBase()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	Mesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Mesh"));
	Mesh->SetupAttachment(RootComponent);

	MuzzleOffset = CreateDefaultSubobject<USceneComponent>(TEXT("MuzzleOffset"));
	MuzzleOffset->SetupAttachment(Mesh);
}

// Called when the game starts or when spawned
void AWeaponBase::BeginPlay()
{
	Super::BeginPlay();

}

void AWeaponBase::Fire()
{
	UAnimInstance* AnimInstance = Mesh->GetAnimInstance();
	if (IsValid(AnimInstance) && IsValid(FireAnimMontage)) {
		AnimInstance->Montage_Play(FireAnimMontage);
	}

	if (IsValid(BulletClass)) {
		FRotator SpawnRotation = MuzzleOffset->GetComponentRotation();
		FVector SpawnLocation = MuzzleOffset->GetComponentLocation();

		FActorSpawnParameters SpawnParams;
		SpawnParams.Owner = this;

		// APlayerBase로 캐스팅 하면 안되나? Enemy가 총을 쏠 수 있잖아..
		// PlayerController->GetViewportSize(x, y); 이래.. 그럼 이것도 오버라이딩해서 에너미랑 플레이어로 구분하는게 좋을듯..
		ACharacterBase* WeaponOwner = Cast<APlayerBase>(GetOwner());
		if (!IsValid(WeaponOwner)) return;

		AController* WeaponOwnerController = WeaponOwner->GetController();
		if (!IsValid(WeaponOwner)) return;

		if (APlayerController* PlayerController = Cast<APlayerController>(WeaponOwnerController))
		{
			int32 x, y;
			PlayerController->GetViewportSize(x, y);

			// WorldCenter의 존재 이유가 뭘까???
			FVector WorldCenter;
			FVector WorldFront;
			PlayerController->DeprojectScreenPositionToWorld(x * 0.5f, y * 0.5f, WorldCenter, WorldFront);

			//UE_LOG(LogTemp, Display, TEXT("World Center: %s"), *WorldCenter.ToCompactString());

			WorldCenter += WorldFront * 10000;
			SpawnRotation = UKismetMathLibrary::FindLookAtRotation(SpawnLocation, WorldCenter);

			GetWorld()->SpawnActor<ABulletBase>(BulletClass, SpawnLocation, SpawnRotation, SpawnParams);
		}
		else if (AAIControllerBase* AIController = Cast<AAIControllerBase>(WeaponOwnerController))
		{
			APawn* TargetPawn = GetWorld()->GetFirstPlayerController()->GetPawn();

			SpawnRotation = UKismetMathLibrary::FindLookAtRotation(SpawnLocation, TargetPawn->GetActorLocation());
			GetWorld()->SpawnActor<ABulletBase>(BulletClass, SpawnLocation, SpawnRotation, SpawnParams);
		}
	}
}


#include <eng/main.hpp>
#include "camera.hpp"

camera_t::camera_t() {
        this->m_position = glm::vec3(0.0f, 0.0f, 10.0f);
        this->m_angle = glm::vec2(0.f, 0.f); // (0,0,-1) righthanded (elevation angle, angle arround y axis)

        this->m_mouse_sensitivity = 0.2f;
        this->m_mouse_locked = false;

	this->m_lock_mouse();
}

void camera_t::m_lock_mouse() {
	this->m_center_position = sf::Vector2f(eng::window.getSize().x / 2.f, eng::window.getSize().y / 2.f);
	eng::window.setMouseCursorVisible(false);
	sf::Mouse::setPosition(
		eng::window.mapCoordsToPixel({ this->m_center_position.x, this->m_center_position.y }),
		eng::window);
	this->m_mouse_locked = true;
}

void camera_t::m_handle_mouse_movement() {
        if (!this->m_mouse_locked) {
            this->m_lock_mouse();
            return;
        }

        sf::Vector2f mouse_position = (sf::Vector2f)sf::Mouse::getPosition(eng::window);
        sf::Vector2f mouse_delta = mouse_position - this->m_center_position;

        this->m_angle.y -= mouse_delta.x * this->m_mouse_sensitivity * 0.0174533f;
        this->m_angle.x -= mouse_delta.y * this->m_mouse_sensitivity * 0.0174533f;

        sf::Mouse::setPosition(
		eng::window.mapCoordsToPixel({ this->m_center_position.x, this->m_center_position.y }),
		eng::window);
}

void camera_t::pass_data_to_shader() {
	eng::window.set_uniform("camera_position", this->get_position());
	eng::window.set_uniform("camera_angle", this->get_angle());
}

void camera_t::move() {
	this->m_handle_mouse_movement();

	float fixed_speed = 1.0f * eng::delta_time;
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::LControl)) {
		fixed_speed *= 10;
	}

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
		this->m_position.x -= std::sin(this->m_angle.y) * fixed_speed;
		this->m_position.z -= std::cos(this->m_angle.y) * fixed_speed;
	}

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
		this->m_position.x += std::sin(this->m_angle.y) * fixed_speed;
		this->m_position.z += std::cos(this->m_angle.y) * fixed_speed;
	}

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
		this->m_position.x += std::sin(this->m_angle.y - 3.14159f/2.f) * fixed_speed;
		this->m_position.z += std::cos(this->m_angle.y - 3.14159f/2.f) * fixed_speed;
	}

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
		this->m_position.x -= std::sin(this->m_angle.y - 3.14159f/2.f) * fixed_speed;
		this->m_position.z -= std::cos(this->m_angle.y - 3.14159f/2.f) * fixed_speed;
	}

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
		this->m_position.y += fixed_speed;
	}

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift)) {
		this->m_position.y -= fixed_speed;
	}

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::C)) {
		eng::window.set_uniform("FAR", -100.f);
		this->m_mouse_sensitivity = 0.02f;
        } else {
		eng::window.set_uniform("FAR", -10.f);
		this->m_mouse_sensitivity = 0.2f;
	}
}


#include "DisplayManager.h"

void DisplayManager::init() {
    tft.begin();
    tft.setRotation(3);
    clearScreen();
}

void DisplayManager::updateDisplay(const SensorData& data, SystemStatus status) {
    clearScreen();
    drawHeader(status);
    drawSensorData(data);
    drawRecommendations(status, data);
}

void DisplayManager::drawHeader(SystemStatus status) {
    tft.setTextSize(2);
    tft.setTextColor(TEXT_COLOR);

    tft.setCursor(10, 10);
    tft.print("Status: ");

    switch (status) {
    case STATUS_GOOD:
        tft.setTextColor(GOOD_COLOR);
        tft.print("GOOD");
        break;
    case STATUS_WARNING:
        tft.setTextColor(WARNING_COLOR);
        tft.print("WARNING");
        break;
    case STATUS_CRITICAL:
        tft.setTextColor(CRITICAL_COLOR);
        tft.print("CRITICAL");
        break;
    }

    tft.drawLine(0, 35, 320, 35, TEXT_COLOR);
}

void DisplayManager::drawSensorData(const SensorData& data) {
    tft.setTextSize(2);
    tft.setTextColor(TEXT_COLOR);

    tft.setCursor(10, 50);
    tft.print("Temp: ");
    tft.print(data.temperature, 1);
    tft.print(" C");

    tft.setCursor(10, 80);
    tft.print("Humidity: ");
    tft.print(data.humidity, 1);
    tft.print(" %");

    tft.setCursor(10, 110);
    tft.print("Light: ");
    tft.print(data.lightLevel);
    tft.print(" lx");

    tft.drawLine(0, 140, 320, 140, TEXT_COLOR);
}

void DisplayManager::drawRecommendations(SystemStatus status, const SensorData& data) {
    tft.setTextSize(1);
    tft.setTextColor(TEXT_COLOR);

    tft.setCursor(10, 150);
    tft.print("Recommendations:");

    String recommendations = getRecommendationText(status, data);
    tft.setCursor(10, 170);
    tft.setTextSize(1);

    int currentY = 170;
    int lineHeight = 15;

    String currentLine = "";
    for (int i = 0; i < recommendations.length(); i++) {
        char c = recommendations[i];
        if (c == '\n' || currentLine.length() > 35) {
            tft.setCursor(10, currentY);
            tft.print(currentLine);
            currentLine = "";
            currentY += lineHeight;
            if (c == '\n') continue;
        }
        currentLine += c;
    }

    if (currentLine.length() > 0) {
        tft.setCursor(10, currentY);
        tft.print(currentLine);
    }
}

String DisplayManager::getRecommendationText(SystemStatus status, const SensorData& data) {
    if (status == STATUS_GOOD) {
        return "All parameters optimal! Maintain current conditions.";
    }

    String recommendations = "";

    if (data.temperature < 18) {
        recommendations += "! Increase temperature (heater)\n";
    }
    else if (data.temperature > 26) {
        recommendations += "! Decrease temperature (AC/ventilation)\n";
    }

    if (data.humidity < 30) {
        recommendations += "! Increase humidity (humidifier)\n";
    }
    else if (data.humidity > 60) {
        recommendations += "! Decrease humidity (dehumidifier)\n";
    }

    if (data.lightLevel < 100) {
        recommendations += "! Increase lighting (more light)\n";
    }
    else if (data.lightLevel > 800) {
        recommendations += "! Decrease lighting (curtains/shades)\n";
    }

    return recommendations;
}

void DisplayManager::clearScreen() {
    tft.fillScreen(BACKGROUND_COLOR);
}

void DisplayManager::showSplashScreen() {
    clearScreen();
    tft.setTextSize(2);
    tft.setTextColor(ILI9341_CYAN);
    tft.setCursor(50, 100);
    tft.print("Environment Monitor by NMRB_CPP");
    tft.setTextColor(ILI9341_WHITE);
    tft.setCursor(80, 130);
    tft.print("Starting");

    for (int i = 0; i < 3; i++) {
        tft.setCursor(180 + i * 12, 130);
        tft.print(".");
        delay(500);
    }
}


// made by const - github.com/yfz

#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

const std::string spotify_path = std::string(std::getenv("APPDATA")) + "\\Spotify\\Spotify.exe";
const std::string hosts_path = "C:\\Windows\\System32\\drivers\\etc\\hosts";

const std::vector<std::string> allahyok = {
    "0.0.0.0 audio-ads.spotify.com",
    "0.0.0.0 pubads.g.doubleclick.net",
    "0.0.0.0 googleads.g.doubleclick.net",
    "0.0.0.0 spclient.wg.spotify.com"
};

enum class log_level { info, success, error };

void log(log_level level, const std::string& message) {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    static const struct { const char* prefix; WORD color; } settings[] = {
        { "[#] ", FOREGROUND_RED | FOREGROUND_GREEN },
        { "[+] ", FOREGROUND_GREEN | FOREGROUND_INTENSITY },
        { "[-] ", FOREGROUND_RED | FOREGROUND_INTENSITY }
    };

    auto& [prefix, color] = settings[static_cast<size_t>(level)];

    SetConsoleTextAttribute(hConsole, color);
    std::cout << prefix;

    SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
    std::cout << message << std::endl;
}

void hi_spotify() {
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (snapshot == INVALID_HANDLE_VALUE) return;

    PROCESSENTRY32 pe{ sizeof(PROCESSENTRY32) };
    bool killed = false;

    if (Process32First(snapshot, &pe)) {
        do {
            if (!_wcsicmp(pe.szExeFile, L"Spotify.exe")) {
                HANDLE proc = OpenProcess(PROCESS_TERMINATE, FALSE, pe.th32ProcessID);
                if (proc) {
                    TerminateProcess(proc, 0);
                    CloseHandle(proc);
                    killed = true;
                }
            }
        } while (Process32Next(snapshot, &pe));
    }

    CloseHandle(snapshot);

    if (killed) {
        log(log_level::success, "Operation completed: Spotify process has been successfully terminated.");
    }
    else {
        log(log_level::info, "Status check: Spotify process was not found among running applications. No action required.");
    }
}

void start_spotify() {
    if (GetFileAttributesA(spotify_path.c_str()) == INVALID_FILE_ATTRIBUTES) {
        log(log_level::error, "Unable to locate Spotify. Please ensure Spotify is installed correctly at: " + spotify_path);
        return;
    }

    ShellExecuteA(NULL, "open", spotify_path.c_str(), nullptr, nullptr, SW_SHOW);
    log(log_level::success, "Launching Spotify... Please wait for initialization to complete.");
}

bool write_hosts(const std::string& content, std::ios_base::openmode mode) {
    std::ofstream hosts(hosts_path, mode);
    if (!hosts) return false;
    hosts << content;
    hosts.close();
    return true;
}

void update_hosts() {
    std::string content = "\n# Block Spotify advertisements - made by Const\n";
    for (const auto& line : allahyok) content += line + "\n";

    if (write_hosts(content, std::ios::app)) {
        log(log_level::success, "Hosts file successfully updated with Spotify advertisement blocking rules." +
            std::to_string(allahyok.size()) + " domains have been blocked.");
    } else {
        log(log_level::error, "Failed to modify hosts file. Access denied. Please run the application with administrator privileges to apply changes.");
    }
}

int main() {
    SetConsoleTitleA("Spotify AdBlock Tool | made by const");

    log(log_level::info, "Starting Spotify AdBlock Tool initialization process...");

    log(log_level::info, "Scanning system for active Spotify processes...");
    hi_spotify();

    log(log_level::info, "Updating system hosts file with advertisement domain blocks...");
    update_hosts();

    log(log_level::info, "Launching Spotify application with advertisement protection...");
    start_spotify();

    log(log_level::info, "AdBlock completed. press enter to exit...");
    log(log_level::info, "Thank you for using Spotify AdBlock Tool! Please remember: this tool is provided as-is, and any use is your own responsibility. If you want to reach me, you can do so here: https://t.me/xconst");

    std::cin.get();

    return 0;
}


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

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

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


// uacctl - Ajuste centralizado do UAC (Windows)
// Autor: MicDog (Michael Douglas)
// Licença: MIT
// Compilar: CMake + MSVC/MinGW. Requer advapi32.
//
// Este utilitário NÃO contorna o UAC nem executa elevação por conta própria.
// Ele apenas grava as chaves oficiais de política do Windows quando
// executado com privilégios de administrador (recomendado rodar como "Local System"
// via PDQ Deploy/SCCM/GPO Startup Script).

#include <windows.h>
#include <sddl.h>
#include <iostream>
#include <string>
#include <vector>
#include <optional>
#include <cwchar>

constexpr const wchar_t* REG_PATH = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";

struct Argv {
    bool modeNeverNotify = false;
    bool modeFullDisable = false;
    bool modeRollback    = false;
    bool modeStatus      = false;
};

bool IsRunningAsAdmin() {
    BOOL isAdmin = FALSE;
    PSID adminGroup = nullptr;
    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;

    if (AllocateAndInitializeSid(&NtAuthority, 2,
                                 SECURITY_BUILTIN_DOMAIN_RID,
                                 DOMAIN_ALIAS_RID_ADMINS,
                                 0,0,0,0,0,0, &adminGroup)) {
        CheckTokenMembership(NULL, adminGroup, &isAdmin);
        FreeSid(adminGroup);
    }
    return isAdmin == TRUE;
}

LONG SetDword(const std::wstring& name, DWORD value) {
    HKEY hKey;
    LONG s = RegCreateKeyExW(HKEY_LOCAL_MACHINE, REG_PATH, 0, NULL,
                             REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hKey, NULL);
    if (s != ERROR_SUCCESS) return s;
    s = RegSetValueExW(hKey, name.c_str(), 0, REG_DWORD, reinterpret_cast<const BYTE*>(&value), sizeof(DWORD));
    RegCloseKey(hKey);
    return s;
}

std::optional<DWORD> GetDword(const std::wstring& name) {
    HKEY hKey;
    DWORD data = 0, type = 0, size = sizeof(DWORD);
    LONG s = RegOpenKeyExW(HKEY_LOCAL_MACHINE, REG_PATH, 0, KEY_QUERY_VALUE, &hKey);
    if (s != ERROR_SUCCESS) return std::nullopt;
    s = RegQueryValueExW(hKey, name.c_str(), 0, &type, reinterpret_cast<LPBYTE>(&data), &size);
    RegCloseKey(hKey);
    if (s == ERROR_SUCCESS && type == REG_DWORD) return data;
    return std::nullopt;
}

bool ApplyValues(const std::vector<std::pair<std::wstring, DWORD>>& pairs) {
    for (const auto& kv : pairs) {
        LONG s = SetDword(kv.first, kv.second);
        if (s != ERROR_SUCCESS) {
            std::wcerr << L"[ERRO] Falha ao gravar " << kv.first << L" (code " << s << L")\n";
            return false;
        }
    }
    return true;
}

void PrintStatus() {
    auto print = [](const wchar_t* name){
        auto v = GetDword(name);
        if (v.has_value())
            std::wcout << L" - " << name << L" = " << v.value() << L"\n";
        else
            std::wcout << L" - " << name << L" = <não definido>\n";
    };
    std::wcout << L"[Status atual - " << REG_PATH << L"]\n";
    print(L"EnableLUA");
    print(L"ConsentPromptBehaviorAdmin");
    print(L"ConsentPromptBehaviorUser");
    print(L"PromptOnSecureDesktop");
    print(L"EnableInstallerDetection");

    auto enableLUA = GetDword(L"EnableLUA").value_or(1);
    auto admin = GetDword(L"ConsentPromptBehaviorAdmin").value_or(5);
    auto user  = GetDword(L"ConsentPromptBehaviorUser").value_or(3);
    auto secure= GetDword(L"PromptOnSecureDesktop").value_or(1);
    auto inst  = GetDword(L"EnableInstallerDetection").value_or(1);

    std::wcout << L"\n[Interpretação]\n";
    if (enableLUA == 0) {
        std::wcout << L" UAC: DESATIVADO (requer reinicialização se acabou de alterar).\n";
    } else if (admin == 0 && user == 0 && secure == 0 && inst == 0) {
        std::wcout << L" UAC: ATIVO, nível 'Nunca notificar' (sem prompts).\n";
    } else {
        std::wcout << L" UAC: ATIVO com configuração personalizada/padrão.\n";
    }
}

void PrintHelp() {
    std::wcout << L"uacctl - Ajustar o nível do UAC via console\n\n"
               << L"USO:\n"
               << L"  uacctl --status           Mostra valores atuais\n"
               << L"  uacctl --never-notify     Nível 'Nunca notificar' (UAC ativo, sem prompts)\n"
               << L"  uacctl --full-disable     Desativa totalmente o UAC (EnableLUA=0) *requer reboot*\n"
               << L"  uacctl --rollback         Restaura valores recomendados (prompts padrão)\n\n"
               << L"Observação: é necessário executar como Administrador. Não há como alterar\n"
               << L"o UAC sem privilégios elevados. Para automação, execute como 'Local System'\n"
               << L"(PDQ Deploy/SCCM/GPO Startup Script).\n";
}

Argv Parse(int argc, wchar_t** argv) {
    Argv a;
    for (int i = 1; i < argc; ++i) {
        std::wstring s = argv[i];
        if (s == L"--never-notify") a.modeNeverNotify = true;
        else if (s == L"--full-disable") a.modeFullDisable = true;
        else if (s == L"--rollback") a.modeRollback = true;
        else if (s == L"--status") a.modeStatus = true;
        else {
            std::wcout


/* Tests by Claude.ai (and the author) */

#include <mintest/suit.h>
#include <mintest/utils.h>
#include <mintest/assertions/headers.h>
#include <vector>
#include <array>
#include <string>
#include <iostream>

void test_expect_eq_primitives()
{
    // Integer types
    EXPECT_EQ(42, 42);
    EXPECT_EQ(int(10), int(10));
    EXPECT_EQ(long(100L), long(100L));
    EXPECT_EQ(short(5), short(5));

    // Floating point
    EXPECT_EQ(3.14, 3.14);
    EXPECT_EQ(2.5f, 2.5f);
    EXPECT_EQ(double(1.0), double(1.0));

    // Character types
    EXPECT_EQ('a', 'a');
    EXPECT_EQ(char('z'), char('z'));

    // Boolean
    EXPECT_EQ(true, true);
    EXPECT_EQ(false, false);
}

void test_expect_eq_container()
{
    // Vector comparison
    std::vector<int> vec1 = {1, 2, 3, 4, 5};
    std::vector<int> vec2 = {1, 2, 3, 4, 5};
    EXPECT_EQ_CONTAINER(vec1, vec2);

    std::vector<std::string> vec_str1 = {"Hello"};
    std::vector<std::string> vec_str2 = {"Hello"};
    EXPECT_EQ_CONTAINER(vec_str1, vec_str2);

    // Different element types
    std::vector<double> vec_double1 = {1.1, 2.2, 3.3};
    std::vector<double> vec_double2 = {1.1, 2.2, 3.3};
    EXPECT_EQ_CONTAINER(vec_double1, vec_double2);

    // Array containers
    std::array<int, 4> arr1 = {10, 20, 30, 40};
    std::array<int, 4> arr2 = {10, 20, 30, 40};
    EXPECT_EQ_CONTAINER(arr1, arr2);

    // Empty containers
    std::vector<int> empty1, empty2;
    EXPECT_EQ_CONTAINER(empty1, empty2);
}

void test_expect_eq_array()
{
    // Integer arrays
    int* arr1 = new int[4]{1, 2, 3, 4};
    int* arr2 = new int[4]{1, 2, 3, 4};
    EXPECT_EQ_ARRAY(arr1, 4, arr2, 4);
    delete[] arr1;
    delete[] arr2;

    // Double arrays
    double* darr1 = new double[3]{1.1, 2.2, 3.3};
    double* darr2 = new double[3]{1.1, 2.2, 3.3};
    EXPECT_EQ_ARRAY(darr1, 3, darr2, 3);
    delete[] darr1;
    delete[] darr2;

    // Character arrays
    char* carr1 = new char[3]{'a', 'b', 'c'};
    char* carr2 = new char[3]{'a', 'b', 'c'};
    EXPECT_EQ_ARRAY(carr1, 3, carr2, 3);
    delete[] carr1;
    delete[] carr2;

    // Stack arrays (cast to pointer)
    int stack_arr1[] = {10, 20, 30};
    int stack_arr2[] = {10, 20, 30};
    EXPECT_EQ_ARRAY(static_cast<int*>(stack_arr1), 3, static_cast<int*>(stack_arr2), 3);

    // Zero-size arrays
    int* null_arr1 = nullptr;
    int* null_arr2 = nullptr;
    EXPECT_EQ_ARRAY(null_arr1, 0, null_arr2, 0);
}

void test_expect_eq_str()
{
    // Basic string comparison
    std::string s1 = "hello";
    std::string s2 = "hello";
    EXPECT_EQ_STR(s1, s2);

    // Empty strings
    EXPECT_EQ_STR(std::string(""), std::string(""));

    // Concatenated strings
    std::string base = "test";
    EXPECT_EQ_STR(base + "_suffix", std::string("test_suffix"));

    // String literals to std::string
    EXPECT_EQ_STR(std::string("literal"), std::string("literal"));

    // Long strings
    std::string long1 = "This is a very long string for testing purposes";
    std::string long2 = "This is a very long string for testing purposes";
    EXPECT_EQ_STR(long1, long2);
}

int main()
{
    TestSuit TS;

    TS.add_test("EXPECT_EQ with Primitives", &test_expect_eq_primitives);
    TS.add_test("EXPECT_EQ_CONTAINER", &test_expect_eq_container);
    TS.add_test("EXPECT_EQ_ARRAY", &test_expect_eq_array);
    TS.add_test("EXPECT_EQ_STR", &test_expect_eq_str);

    TS.run_tests();
    return 0;
}


#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <future>
#include <numeric>
#include <stdexcept>
#include <algorithm>

// ===========================
// 1. MAIN FUNCTION
// ===========================

/*
Question 1: Write a program that prints the number of command-line arguments it receives and
then lists each argument on a new line.
*/

// The main function is the entry point of a C++ program.
// Its signature for handling command-line arguments is:
// int main(int argc, char* argv[])
// Java's equivalent is: public static void main(String[] args)
int main_function_example(int argc, char* argv[]) {
    std::cout << "Number of arguments received: " << argc << std::endl;

    std::cout << "Arguments are:" << std::endl;
    for (int i = 0; i < argc; ++i) {
        // argv[0] is always the name of the program itself
        std::cout << "Argument " << i << ": " << argv[i] << std::endl;
    }

    // A return value of 0 typically indicates successful execution
    return 0;
}

/*
Question 2: What is the primary purpose of the 'main' function? Why is it typically declared as 'static' in Java?

Answer: The main function serves as the entry point of a program. It's where program execution begins.
In Java, main is declared as 'static' because:
1. The JVM needs to call main without creating an instance of the class
2. Static methods belong to the class itself, not to any particular instance
3. This allows the program to start without needing to instantiate objects first

Question 3: How does the 'main' function signature differ between C++ and Java in terms of return type, parameters, and access modifiers?

Answer:
C++: int main(int argc, char* argv[])
- Return type: int (exit status)
- Parameters: argc (argument count), argv (argument vector)
- No explicit access modifiers (global function)

Java: public static void main(String[] args)
- Return type: void
- Parameters: String array of arguments
- Access modifiers: public (accessible from anywhere), static (class-level method)

Question 4: What does the integer return value from the 'main' function signify? How is a non-zero exit status typically achieved in Java?

Answer: The integer return value indicates the program's exit status:
- 0: Successful execution
- Non-zero: Error or abnormal termination

In Java, since main returns void, you use System.exit(int status) to achieve non-zero exit status.
*/

// ===========================
// 2. VARIABLES
// ===========================

/*
Question 1: Write a program to declare two integer variables, assign them values, and then swap
their values without using a third temporary variable.
*/

void variables_example() {
    int a = 10;
    int b = 20;

    std::cout << "Before swap: a = " << a << ", b = " << b << std::endl;

    // Swapping using arithmetic operations. This logic works in both C++ and Java.
    a = a + b; // a becomes 30
    b = a - b; // b becomes 10 (30 - 20)
    a = a - b; // a becomes 20 (30 - 10)

    std::cout << "After swap: a = " << a << ", b = " << b << std::endl;
}

/*
Question 2: Explain the difference between primitive types (like 'int', 'double') and reference types (objects, pointers) in terms of memory allocation and storage.

Answer:
Primitive types:
- Stored directly in memory (stack for local variables)
- Fixed size
- Direct value storage
- Fast access
- Examples: int, double, char, bool

Reference types:
- Store memory addresses/references to objects
- Objects stored in heap memory
- Variable size
- Indirect access through references/pointers
- Examples: objects, arrays, pointers

Question 3: What is 'scope' in the context of variables? Describe local scope (within a method/function) and class-level/static scope.

Answer:
Scope defines where a variable can be accessed:

Local scope:
- Variables declared inside functions/methods
- Only accessible within that function
- Destroyed when function exits
- Lives on the stack

Class-level scope:
- Member variables of a class
- Accessible throughout the class
- Lifetime tied to object instance

Static scope:
- Variables shared across all instances
- Exists for the program's lifetime
- One copy per class, not per instance

Question 4: Both C++ and Java are statically-typed languages. Explain what this means and contrast it with dynamic typing.

Answer:
Static typing:
- Variable types determined at compile time
- Type checking occurs during compilation
- Better performance (no runtime type checks)
- Catch type errors early
- Examples: C++, Java, C#

Dynamic typing:
- Variable types determined at runtime
- Type checking occurs during execution
- More flexibility but potential runtime errors
- Variables can change types
- Examples: Python, JavaScript, Ruby
*/

// ===========================
// 3. CONTROL FLOW
// ===========================

/*
Question 1: Write a program that uses a 'for' loop to print the first 10 numbers of the Fibonacci sequence, starting with 0 and 1.
*/

void control_flow_ex


/*
Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "NSynth.h"

#include "MidiUtils.h"
#include <fstream>
#include <sstream>
#include <chrono>
#include <cmath>

void NSynth::setup(int resolution, const std::vector<int>& pitches, int length, int sampleRate) {
    this->resolution = resolution;
    this->pitches = pitches;
    int rows = resolution * resolution * pitches.size();
    std::cout << "[NSynth] setup: " << rows << "x" << length << std::endl;
    Multisampler::setup(rows, length, sampleRate);
}

bool NSynth::load(std::string filename) {
    if(filename == current_filename) {
        std::cout << "[NSynth] already loaded" << std::endl;
        return true;
    }

    clear();
    current_filename = "";

    auto start = get_time_ms();
    if(sources.load(filename + ".bin", rows(), cols()) != 0) {
        return false;
    }
    auto stop = get_time_ms();
    std::cout << "[NSynth] load time: " << (stop - start) << "ms" << std::endl;

    base_lookup = buildMultisampleLookup(pitches);
    set_interpolation_position(x, y);
    current_filename = filename;
    return true;
}

void NSynth::set_interpolation_position(float x, float y) {
    this->x = x;
    this->y = y;

    int xi = (int) round(x * (resolution - 1));
    int yi = (int) round(y * (resolution - 1));
    int index = yi * resolution + xi;
    int row_offset = index * pitches.size();

    lookup = base_lookup;
    for(auto& row_rate : lookup) {
        row_rate.first += row_offset;
    }
}


//
// Created by DexrnZacAttack on 9/12/25 using zPc-i2.
//
#include "FSEditScreen.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QSplitter>

namespace LPP::GUI::Screens::Edit {
    // I feel like this should be gutted out and have it's main init code moved to EditScreen
    FSEditScreen::FSEditScreen(IO::FileType type, QWidget *parent) : EditScreen(type, parent) {
        QSplitter *splitter = new QSplitter(Qt::Horizontal, this);

        // side layout
        QWidget* rightLayout = new QWidget();
        mRightLayout = new QGridLayout(rightLayout);

        // setup tabs
        this->mTabs = new QTabWidget(this);

        // make filelist
        this->mFileList = new Widgets::FileListWidget(type, this);

        // make toolbar
        QWidget *toolbar = new QWidget();
        QHBoxLayout *toolbarLayout = new QHBoxLayout(toolbar);
        toolbarLayout->setContentsMargins(0, 0, 0, 0);

        // make toolbar shit
        // QLabel* fileName = new QLabel("No file has been chosen", toolbar);
        mChooseFileButton = new QPushButton(QIcon::fromTheme("document-open"), "Choose a file", toolbar);
        connect(mChooseFileButton, &QPushButton::clicked, this, [type, this]() {
            onChooseFileButton(type);
        });

        mAddFileButton = new QPushButton(QIcon::fromTheme("document-new"), "Add file", toolbar);
        connect(mAddFileButton, &QPushButton::clicked, this->mFileList, &Widgets::FileListWidget::onAddFile);

        // add the shit to toolbar layout
        toolbarLayout->addWidget(mChooseFileButton);
        toolbarLayout->addWidget(mAddFileButton);

        // create left layout
        QWidget* leftLayout = new QWidget();
        mLeftLayout = new QVBoxLayout(leftLayout);

        // add tabs
        mRightLayout->addWidget(mTabs, 0, Qt::AlignTop);

        // add widgets
        mLeftLayout->addWidget(toolbar);
        mLeftLayout->addWidget(this->mFileList);

        splitter->addWidget(leftLayout);
        splitter->addWidget(rightLayout);

        this->mMainLayout->addWidget(splitter, 0);
    }

    bool FSEditScreen::onChooseFileButton(IO::FileType type) {
        // grab file
        QString fileName = QFileDialog::getOpenFileName(mFileList, "Choose a file");

        if (!fileName.isEmpty()) {
            // clear so that we don't have duplicates
            mFileList->clear();
            mTabs->clear();

            // read
            std::ifstream stream(fileName.toStdString(), std::ifstream::binary);

            std::vector<uint8_t> bytes(std::filesystem::file_size(fileName.toStdString()));
            stream.read(reinterpret_cast<char *>(bytes.data()), bytes.size());

            try {
                // read file
                lce::fs::Filesystem *file;
                switch (type) {
                    default:
                    case IO::eFileType::BASIC:
                        file = new lce::fs::Filesystem();
                        break;
                    case IO::eFileType::SAVE_FILE_OLD:
                    case IO::eFileType::SAVE_FILE:
                        file = lce::save::SaveFileCommons::deserializeAuto(bytes);
                        break;
                    case IO::eFileType::ARCHIVE:
                        file = new lce::arc::Archive(bytes);
                        break;
                    case IO::eFileType::SOUNDBANK:
                        if (!lce::msscmp::Soundbank::isSoundbank(bytes.data())) {
                            QMessageBox::critical(this, "Invalid File", "This file is not a valid MSSCMP file");
                            return false;
                        }

                        file = new lce::msscmp::Soundbank(bytes);
                        break;
                }

                // add tab
                QWidget *saveTab = new QWidget();
                QVBoxLayout *saveTabLayout = new QVBoxLayout(saveTab);
                saveTabLayout->setSpacing(10);

                // TODO: make panel based on chosen file type
                // // create info strings
                // std::string v = "Version: " + std::to_string(file->getVersion());
                // std::string mv = "Original Version: " + std::to_string(file->getOriginalVersion());
                //
                // // add widgets
                // saveTabLayout->addWidget(new QLabel(v.c_str()));
                // saveTabLayout->addWidget(new QLabel(mv.c_str()));
                //
                // saveTabLayout->addStretch();

                // add the tab
                mTabs->addTab(saveTab, "Save File");

                // create list items in file list
                // TODO: this should read files and directories (recursively) instead of seeing all top level items as a file
                this->mFileList->create(file);
            } catch (const std::exception& e) {
                // Too Bad!
                std::string err = "Exception thrown whilst trying to read '" + fileName.toStdString() + "': " + e.what()


#include<iostream>
#include<vector>
#include<queue>

using namespace std;
vector<vector<int>> dir={{1,0},{-1,0},{0,1},{0,-1}};//i,j  -> i+1,j ->i-1,j ->i,j-1 ->i,j+1
int rows;
int cols;
vector<vector<int>> h;

vector<vector<bool>> bfs(queue<pair<int,int>> &qu){
  vector<vector<bool>> visited(rows,vector<bool> (cols,false));
  while(!qu.empty()){
    auto cell =qu.front();
    qu.pop();
    int i = cell.first;
    int j = cell.second;
    visited[i][j] =true;
    for(int d=0;d<4;d++){
      int newRow = i+dir[d][0];
      int newCol = j+dir[d][1];
      if(newRow<0 or newCol<0 or newRow>=rows or newCol >=cols) continue;//you exited the grid
      if(visited[newRow][newCol]) continue;
      if(h[newRow][newCol] <h[i][j]) continue;
      qu.push({newRow,newCol});
    }
  }
return visited;
}

vector<vector<int>> PacificAtlantic(vector<vector<int>> &heights){
rows=heights.size();
cols=heights[0].size();
h=heights;
queue<pair<int,int>> pacificBfs;
queue<pair<int,int>> atlanticBfs;

//Multi Source Bfs
for (int i = 0; i < rows; i++)
{
  pacificBfs.push({i,0});
  atlanticBfs.push({i,cols-1});
}

for (int i = 1; i < cols; i++)
{
  pacificBfs.push({0,i});
}

for (int j =0; j <cols-1; j++)
{
  atlanticBfs.push({rows-1,j});
}

vector<vector<bool>> pacific=bfs(pacificBfs);
vector<vector<bool>> atlantic=bfs(atlanticBfs);

vector<vector<int>> result;
for (int i = 0; i < rows; i++)
{
  for (int j = 0; j < cols;j++)
  {
    if(pacific[i][j] and atlantic[i][j]) result.push_back({i,j});
  }

}

return result;
}

int main(){
vector<vector<int>> heights ={{1,2,2,3,5},
                              {3,2,3,4,4},
                              {2,4,5,3,1},
                              {6,7,1,4,5},
                              {5,1,1,2,4}};

vector<vector<int>>  r = PacificAtlantic(heights);
for(auto ele: r){
    for(int i=0;i<ele.size();i++){
      cout<<ele[i]<<" ";
    }
    cout<<endl;
}

    return 0;
}


// Farxod Qarshiyev 220090
// Tuesday 14:00
// Mobile Programming Programming Lab Week 2

// Q1
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
  cout << "Number of arguments received: " << argc << endl;
  cout << "Arguments are:" << endl;

  for (int i = 0; i < argc; ++i)
  {
    cout << "Argument " << i << ": " << argv[i] << endl;
  }

  return 0;
}

// Q2
// In C++, main is the entry point where execution begins. learned this in class

// Q3
// In JAVA it returns nothing (void) and always public static, while in C++ returns an integer exit code

// Q4
// In C++, 0 means success non zero is error. System.exit(code) - used in JAVA to signal exit codes. not sure about this one

// VARIABLES
// Q1
#include <iostream>
using namespace std;

int main()
{
  int a = 10, b = 20;

  cout << "Before swap: a = " << a << ", b = " << b << endl;

  a = a + b;
  b = a - b;
  a = a - b;

  cout << "After swap: a = " << a << ", b = " << b << endl;
  return 0;
}

// Q2
// primitive store actual values, reference ones store memory addresses. need to study this more

// Q3
// local scope variable exists only in block or function, classic/static exists across all objects. got this from lecture

// Q4
// types checked at compile time

// CONTROL FLOW

// Q1
#include <iostream>
using namespace std;

int main()
{
  int n1 = 0, n2 = 1, nextTerm;
  cout << "First 10 Fibonacci numbers: ";
  // using for loop to generate fibonacci sequence

  for (int i = 1; i <= 10; ++i)
  {
    if (i == 1)
    {
      cout << n1 << " ";
      continue;
    }
    if (i == 2)
    {
      cout << n2 << " ";
      continue;
    }
    nextTerm = n1 + n2;
    n1 = n2;
    n2 = nextTerm;
    cout << nextTerm << " ";
  }
  cout << endl;
  return 0;
}

// Q2
// while checks before loop, may run 0 times. do-while checks after, runs at least once. important difference!

// Q3
// switch is a multi-branch decision structure. Uses case, break, and default.

// Q4
// Short-circuit evaluation stops once result is known:  if (x != 0 && (10 / x > 1)) { ... } - Prevents division by zero. cool trick

// FUNCTION METHODS

// Q1
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

bool isPalindrome(const string &str)
{
  return equal(str.begin(), str.begin() + str.size() / 2, str.rbegin());
  // this checks if string is same forwards and backwards
}

int main()
{
  cout << "madam is palindrome? " << (isPalindrome("madam") ? "true" : "false") << endl;
  cout << "hello is palindrome? " << (isPalindrome("hello") ? "true" : "false") << endl;
  return 0;
}

// Q2
// C++: by value, by reference, or by pointer. Java: always by value. C++ is more flexible

// Q3
// Function overloading requires different parameters (number/type). Return type alone not enough. tried this and it didnt work

// Q4
// Recursion is a function calling itself. Base case prevents infinite recursion.

// COMMENTS
// Q1
#include <iostream>
using namespace std;

/**
 * Documentation comment using Doxygen/Javadoc style
 */
int main()
{
  // Single line comment
  int x = 5; // inline comment

  /*
     Multi-line comment
     explaining code
  */
  cout << "Comments example" << endl;
  return 0;
}

// Q2
// Comments aid maintainability and team collaboration. teacher always says this

// Q3
// Javadoc/Doxygen generate structured documentation.

// Q4
// Good code is self-documenting, but comments explain algorithms, edge cases. still learning this

// CLASSES
// Q1
#include <iostream>
using namespace std;

class BankAccount
{
private:
  double balance;

public:
  BankAccount(double initial)
  {
    balance = (initial >= 0) ? initial : 0;  // check if initial is positive
  }
  void deposit(double amount)
  {
    if (amount > 0)
      balance += amount;
  }
  double getBalance()
  {
    return balance;
  }
};

int main()
{
  BankAccount acc(100.5);
  cout << "Initial: " << acc.getBalance() << endl;
  acc.deposit(50.25);
  cout << "After deposit: " << acc.getBalance() << endl;
  return 0;
}

// Q2
// Class is blueprint, object is instance. like a template

// Q3
// Public = everywhere, Private = inside class, Protected = class + derived. access modifiers

// Q4
// Constructor initializes. Default constructor = no args, auto-generated if none provided.

// ENUMS
// Q1
#include <iostream>
#include <string>
using namespace std;

enum class Season
{
  SPRING,
  SUMMER,
  AUTUMN,
  WINTER
};

string recommendActivity(Season s)
{
  switch (s)
  {
  case Season::SPRING:
    return "Plant flowers";
  case Season::SUMMER:
    return "Go to the beach";
  case Season::AUTUMN:
    return "Rake leaves";  // fixed typo
  case Season::WINTER:
    return "Build a snowman";
  default:
    return "Rest";
  }
}

int main()
{
  Season now = Season::AUTUMN;
  cout << recommendActivity(now) << endl;
  return 0;
}

// Q2
// Enums safer than int/string constants. prevents errors

// Q3
// Improve type safety and readability.

// Q4
// C++11 enums are strongly typed. Java enums


#include "kml/serdes.hpp"
#include "kml/color_parser.hpp"

#include "indexer/classificator.hpp"

#include "coding/hex.hpp"
#include "coding/string_utf8_multilang.hpp"

#include "geometry/mercator.hpp"

#include "base/assert.hpp"
#include "base/stl_helpers.hpp"
#include "base/string_utils.hpp"
#include "base/timer.hpp"

namespace kml
{
namespace
{
std::string_view constexpr kPlacemark = "Placemark";
std::string_view constexpr kStyle = "Style";
std::string_view constexpr kDocument = "Document";
std::string_view constexpr kStyleMap = "StyleMap";
std::string_view constexpr kStyleUrl = "styleUrl";
std::string_view constexpr kPair = "Pair";
std::string_view constexpr kExtendedData = "ExtendedData";
std::string const kCompilation = "mwm:compilation";

std::string_view const kCoordinates = "coordinates";

bool IsTrack(std::string const & s)
{
  return s == "Track" || s == "gx:Track";
}

bool IsCoord(std::string const & s)
{
  return s == "coord" || s == "gx:coord";
}

bool IsTimestamp(std::string const & s)
{
  return s == "when";
}

std::string_view constexpr kKmlHeader =
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
    "<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\">\n"
    "<Document>\n";

std::string_view constexpr kKmlFooter =
    "</Document>\n"
    "</kml>\n";

std::string_view constexpr kExtendedDataHeader = "<ExtendedData xmlns:mwm=\"https://omaps.app\">\n";

std::string_view constexpr kExtendedDataFooter = "</ExtendedData>\n";

std::string const kCompilationFooter = "</" + kCompilation + ">\n";

PredefinedColor ExtractPlacemarkPredefinedColor(std::string const & s)
{
  if (s == "#placemark-red")
    return PredefinedColor::Red;
  if (s == "#placemark-blue")
    return PredefinedColor::Blue;
  if (s == "#placemark-purple")
    return PredefinedColor::Purple;
  if (s == "#placemark-yellow")
    return PredefinedColor::Yellow;
  if (s == "#placemark-pink")
    return PredefinedColor::Pink;
  if (s == "#placemark-brown")
    return PredefinedColor::Brown;
  if (s == "#placemark-green")
    return PredefinedColor::Green;
  if (s == "#placemark-orange")
    return PredefinedColor::Orange;
  if (s == "#placemark-deeppurple")
    return PredefinedColor::DeepPurple;
  if (s == "#placemark-lightblue")
    return PredefinedColor::LightBlue;
  if (s == "#placemark-cyan")
    return PredefinedColor::Cyan;
  if (s == "#placemark-teal")
    return PredefinedColor::Teal;
  if (s == "#placemark-lime")
    return PredefinedColor::Lime;
  if (s == "#placemark-deeporange")
    return PredefinedColor::DeepOrange;
  if (s == "#placemark-gray")
    return PredefinedColor::Gray;
  if (s == "#placemark-bluegray")
    return PredefinedColor::BlueGray;

  // Default color.
  return PredefinedColor::Red;
}

std::string GetStyleForPredefinedColor(PredefinedColor color)
{
  switch (color)
  {
  case PredefinedColor::Red: return "placemark-red";
  case PredefinedColor::Blue: return "placemark-blue";
  case PredefinedColor::Purple: return "placemark-purple";
  case PredefinedColor::Yellow: return "placemark-yellow";
  case PredefinedColor::Pink: return "placemark-pink";
  case PredefinedColor::Brown: return "placemark-brown";
  case PredefinedColor::Green: return "placemark-green";
  case PredefinedColor::Orange: return "placemark-orange";
  case PredefinedColor::DeepPurple: return "placemark-deeppurple";
  case PredefinedColor::LightBlue: return "placemark-lightblue";
  case PredefinedColor::Cyan: return "placemark-cyan";
  case PredefinedColor::Teal: return "placemark-teal";
  case PredefinedColor::Lime: return "placemark-lime";
  case PredefinedColor::DeepOrange: return "placemark-deeporange";
  case PredefinedColor::Gray: return "placemark-gray";
  case PredefinedColor::BlueGray: return "placemark-bluegray";
  case PredefinedColor::None:
  case PredefinedColor::Count: return {};
  }
  UNREACHABLE();
}

BookmarkIcon GetIcon(std::string const & iconName)
{
  for (size_t i = 0; i < static_cast<size_t>(BookmarkIcon::Count); ++i)
  {
    auto const icon = static_cast<BookmarkIcon>(i);
    if (iconName == ToString(icon))
      return icon;
  }
  return BookmarkIcon::None;
}

void SaveStyle(Writer & writer, std::string const & style, std::string_view const & indent)
{
  if (style.empty())
    return;

  writer << indent << kIndent2 << "<Style id=\"" << style << "\">\n"
         << indent << kIndent4 << "<IconStyle>\n"
         << indent << kIndent6 << "<Icon>\n"
         << indent << kIndent8 << "<href>https://omaps.app/placemarks/" << style << ".png</href>\n"
         << indent << kIndent6 << "</Icon>\n"
         << indent << kIndent4 << "</IconStyle>\n"
         << indent << kIndent2 << "</Style>\n";
}

void SaveColorToABGR(Writer & writer, uint32_t rgba)
{
  writer << NumToHex(static_cast<uint8_t>(rgba & 0xFF)) << NumToHex(static_cast<uint8_t>((rgba >> 8) & 0xFF))
         << NumToHex(static_cast<uint8_t>((rgba >> 16) & 0xFF)) << NumToHex(static_cast<uint8_t>((rgba >> 24) & 0xFF));
}


#include "../common/daf_types.h"
#include "../storage/redis_client_production.h"
#include "production_coordinator.h"
#include <iostream>
#include <memory>
#include <thread>
#include <chrono>
#include <string>
#include <sstream>
#include <random>
#include <unordered_map>
#include <vector>
#include <algorithm>

// Simple HTTP server for REST API
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SOCKET int
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define closesocket close
#endif

namespace daf {

class JobManager {
private:
    std::unique_ptr<RedisClient> redis_;
    std::unordered_map<std::string, std::string> active_jobs_;

public:
    JobManager(std::unique_ptr<RedisClient> redis)
        : redis_(std::move(redis)) {}

    std::string generateJobId() {
        static std::random_device rd;
        static std::mt19937 gen(rd());
        static std::uniform_int_distribution<> dis(100000, 999999);
        return "job_" + std::to_string(dis(gen));
    }

    std::string submitJob(const std::string& plugin_name, const std::string& config_json) {
        std::string job_id = generateJobId();

        // Store job metadata using Redis hash operations
        redis_->SetHash("job:" + job_id, "plugin", plugin_name);
        redis_->SetHash("job:" + job_id, "config", config_json);
        redis_->SetHash("job:" + job_id, "status", "pending");
        redis_->SetHash("job:" + job_id, "created_at", std::to_string(std::time(nullptr)));
        redis_->SetHash("job:" + job_id, "progress", "0");

        // Add to job queue
        redis_->PushLeft("job_queue", job_id);

        std::cout << "[INFO] Job submitted: " << job_id << " (plugin: " << plugin_name << ")" << std::endl;

        return job_id;
    }

    std::string getJobStatus(const std::string& job_id) {
        std::string status, progress, created_at, completed_tasks, total_tasks;

        redis_->GetHash("job:" + job_id, "status", status);
        redis_->GetHash("job:" + job_id, "progress", progress);
        redis_->GetHash("job:" + job_id, "created_at", created_at);
        redis_->GetHash("job:" + job_id, "completed_tasks", completed_tasks);
        redis_->GetHash("job:" + job_id, "total_tasks", total_tasks);

        if (status.empty()) {
            return R"({"error": "Job not found"})";
        }

        return R"({
    "job_id": ")" + job_id + R"(",
    "status": ")" + status + R"(",
    "progress_percent": )" + (!progress.empty() ? progress : "0") + R"(,
    "completed_tasks": )" + (!completed_tasks.empty() ? completed_tasks : "0") + R"(,
    "total_tasks": )" + (!total_tasks.empty() ? total_tasks : "0") + R"(,
    "created_at": )" + (!created_at.empty() ? created_at : "0") + R"(
})";
    }

    void processJobs() {
        // Get pending jobs from Redis queue with enterprise-grade processing
        int queue_length = redis_->GetListLength("job_queue");

        if (queue_length > 0) {
            std::string job_id;
            if (redis_->PopRight("job_queue", job_id)) {
                // Production job processing with full task distribution
                redis_->SetHash("job:" + job_id, "status", "processing");
                redis_->SetHash("job:" + job_id, "total_tasks", "10");

                // Simulate progress
                std::string progress_str;
                redis_->GetHash("job:" + job_id, "progress", progress_str);
                int progress = progress_str.empty() ? 0 : std::stoi(progress_str);

                if (progress < 100) {
                    progress += 10 + (rand() % 20); // Random progress increment
                    if (progress > 100) progress = 100;

                    redis_->SetHash("job:" + job_id, "progress", std::to_string(progress));
                    redis_->SetHash("job:" + job_id, "completed_tasks", std::to_string(progress / 10));

                    if (progress >= 100) {
                        redis_->SetHash("job:" + job_id, "status", "completed");
                        std::cout << "[INFO] Job completed: " << job_id << std::endl;
                    } else {
                        // Put job back in queue for continued processing
                        redis_->PushLeft("job_queue", job_id);
                    }
                }
            }
        }
    }
};

class SimpleHTTPServer {
private:
    SOCKET server_socket_;
    JobManager* job_manager_;

public:
    SimpleHTTPServer(JobManager* job_manager)
        : job_manager_(job_manager), server_socket_(INVALID_SOCKET) {}

    ~SimpleHTTPServer() {
        if (server_socket_ != INVALID_SOCKET) {
            closesocket(server_socket_);
        }
#ifdef _WIN32
        WSACleanup();
#endif
    }

    bool s


#include<iostream>
#include"LIST.hpp"

 void List()
{
	int ListCount = 0;
	int choice;
	char exit='N';
	DynamicLinkedList<int> LIST;
	do
	{
		if (ListCount++ != 0)
			system("CLS");//清屏
		std::cout<<"\t\t********************************************\n";
		std::cout<<"\t\t*  1.创建一个单链表  .................(1)  *\n";
		//std::cout<<"\t\t*  2.在单链表中查找元表的位序.........(2)  *\n";
		//std::cout<<"\t\t*  3.在单链表中插入元表...............(3)  *\n";
		//std::cout<<"\t\t*  4.在单链表中删除元表...............(4)  *\n";
		//std::cout<<"\t\t*  5.逆转列表.........................(5)  *\n";
		//std::cout<<"\t\t*  6.删除链表所有想要删除的值.........(6)  *\n";
		std::cout<<"\t\t*  7.退出              ...............(7)  *\n";
		std::cout<<"\t\t********************************************\n";
		std::cout<<"\n请选择操作代码：";
		//std::cin.ignore();
		std::cin >> choice;
		switch (choice)
		{
		case 1 :
			std::cout<<"Please enter a string of number"
				<<"separated by a space(END WITH q):";
			int list_number;
			while (std::cin >> list_number)
			{
				if (!LIST.CreatList(list_number))
				{
					std::cerr << "FALSE!" << std::endl;
				}
			}
			std::cin.ignore();
			std::cin.clear();
			std::cout << "Before is your list which you created:"
				<< std::endl;
			if (!LIST.ShowList())
				std::cout << "Failed to display the linked list!" << std::endl;
			system("pause");
			std::cin.ignore();
			break;
		case 7:
			std::cin.ignore();
			std::cout << "Please enter Y or y to confirm exit:";
			exit = std::cin.get();
			std::cin.ignore();
			break;
		default:
			std::cerr << "Invalid iputs!" << std::endl;
		}

	} while (exit != 'y' && exit != 'Y');
}


/*
 * @lc app=leetcode.cn id=438 lang=cpp
 *
 * [438] 找到字符串中所有字母异位词
 */

// @lc code=start
class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        int window=p.size(),index=0;;
        vector<int> ans;
        unordered_map<char,int> goal,cur;
        for(int i=0;i<window;++i){
            if(goal.find(p[i])==goal.end()){
                goal[p[i]]=1;
            }
            else{
                goal.at(p[i])++;
            }
        }
        for(int i=0;i<s.size();++i){
            if(cur.find(s[i])==cur.end()){
                cur[s[i]]=1;
            }
            else{
                cur.at(s[i])++;
            }
            if(i>=window){
                if(cur[s[i-window]]==1){
                    cur.erase(s[i-window]);
                }
                else{
                    cur[s[i-window]]--;
                }
            }
            if(cur==goal){
                ans.push_back(i-window+1);
            }
        }
        return ans;
    }
};
// @lc code=end


#include "Dashboard.h"

// ===== ===== ===== ===== ===== ===== ===== ===== ===== =====
// 막대 초기화
// 사전 조건:
//          *graphics = Graphics 객체에 대한 포인터
//          *textureM = TextureManager 객체에 대한 포인터
//          left, top = 화면 위치
//          scale = 스케일링 (확대/축소) 양
//          color = 막대 색상
// 사후 조건:
//          성공 시 true, 오류 시 false 반환
// ===== ===== ===== ===== ===== ===== ===== ===== ===== =====
bool Bar::initialize(Graphics* graphics, TextureManager* textureM, int left,
    int top, float scale, COLOR_ARGB color)
{
    try {
        Image::initialize(graphics, dashboardNS::IMAGE_SIZE, dashboardNS::IMAGE_SIZE,
            dashboardNS::TEXTURE_COLS, textureM);
        setCurrentFrame(dashboardNS::BAR_FRAME);
        spriteData.x = (float)left;
        spriteData.y = (float)top;
        spriteData.scale = scale;
        colorFilter = color;
    }
    catch (...)
    {
        return false;
    }
    // 성공 반환
    return true;
}

// ===== ===== ===== ===== ===== ===== ===== ===== ===== =====
// 막대 크기 설정
// ===== ===== ===== ===== ===== ===== ===== ===== ===== =====
void Bar::set(float p)
{
    if (p < 0)
        p = 0;
    else if (p > 100)
        p = 100;
    spriteData.rect.right = spriteData.rect.left + (LONG)(spriteData.width * p / 100);
}


/* Title: List.cpp
 *
 * Description: implementation of the list class
 *
 * Author: Monem Moheq
 *
 * Date: July 2025
*/

#include <iostream>
#include "List.h"
#include "Node.h"

using std::cin;
using std::cout;

//default constructor
List::List(){}

//destructor
//This is going to start from the head and move its way along the list
//deleting the allocated memory,
List::~List(){

    Node * Current = head;
    Node * Next = head;

    for(unsigned int index = 0; index < elementCount; index++){

        Next = Current->next;
        delete Current;
        Current = Next;

    }

    head = nullptr;
    elementCount = 0;

}

// Description: Returns the current number of elements in the List.
// Postcondition: List unchanged.
// Time Efficicency: O(1)
unsigned int List::getElementCount() const{
    return elementCount;
}

// Description: Insert "newElement" at "position" in the List.
  //              If 1 <= "position" <= getElementCount() + 1 and the insertion
  //              is successful, "newElement" is at "position" in the List,
  //              the other elements, located after "newElement", "have moved" 1
  //              position up and "true" is returned. Otherwise, "false" is returned.
  // Time Efficicency: O(n)
bool List::insert( unsigned int position, int newElement ){

    bool successful = true;
    Node * Current = head;

    //validate position
    if(position >= 1 && position <= elementCount + 1){

        //if it's going into the first position, we don't need a loop
        if(position == 1){
            Node * newNode = new Node(newElement, head);
            head = newNode;
            elementCount++;
            return successful;
        }

        //loop through until you reach the position
        for(unsigned int index = 1; index < position - 1; index++){

            //make the next pointer point to next
            Current = Current->next;

        }

        //create new node, make it point to the next node
        Node * newNode = new Node(newElement, Current->next);

        //change previous nodes next pointer to point at the new node
        Current->next = newNode;
        elementCount++;

    }else{
        //if parameter was wrong then this has failed
        successful = false;
    }

    return successful;
}

// Description: Removes the element at "position" in the List
  //              If 1 <= "position" <= getElementCount() and the removal
  //              is successful, the element at "position" in the List is
  //              removed, and other elements "have moved" 1 position down,
  //              and "true" is returned. Otherwise, "false" is returned.
  // Time Efficicency: O(n)
bool List::remove( unsigned int position ){

    if(position < 1 || position > elementCount) return false;

    Node * Current = head;

    if(position == 1){

        head = Current->next;
        delete Current;
        elementCount--;
        return true;

    }

    Node * Last = head;

    //want to find pointers to the element we want to delete, as well as the element before it
    for(unsigned int index = 1; index < position; index++){
        Last = Current;
        Current = Current->next;
    }

    //set the pointer of the last node to the one after the node to be deleted
    Last->next = Current->next;

    //delete node;
    delete Current;

    elementCount--;
    return true;

}

// Description: Returns the element at "position" in the List
  //              in *toBeReturned if 1 <= position <= getElementCount().
  //              If successful, returns "true". Otherwise, returns "false".
  // Postcondition: List unchanged.
  // Time Efficicency: O(n)
bool List::getElement( unsigned int position, int * toBeReturned ) const{

    //validate position
    if(position < 1 || position > elementCount) return false;

    //create pointer
    Node * Current = head;

    //in case we only need the first pointer
    if(position == 1){

        *toBeReturned = head->data;
        return true;
    }

    //loop to the needed position in the list
    for(unsigned int index = 1; index < position; index++){
        Current = Current->next;
    }

    *toBeReturned = Current->data;

    return true;
}

// Description: Replaces the element at "position" in the List by "newElement".
  //              if 1 <= "position" <= getElementCount().
  //              If successful, returns "true". Otherwise, returns "false".
  // Time Efficicency: O(n)
bool List::setElement( unsigned int position, int newElement ){

    if(position < 1 || position > elementCount) return false;

    //create pointer
    Node * Current = head;

    //loop to the needed position in the list
    for(unsigned int index = 1; index < position; index++){
        Current = Current->next;
    }

    //change element
    Current->data = newElement;

    return true;

}

// Description: Prints all elements in the List.
  // Format: "This List has <el


#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

bool in(char a, string b){
    for (char c : b) if (a==c) return true;
    return false;
}

string vowels = "eariotnslc";
int misvow = (1<<10);
vector< vector<string> > groups(misvow);

int let = 26;
ll letmask = (1<<let);
vector< vector<string> > dp(letmask, vector<string>(1, ":("));

int transmask(ll mask){
    int new_mask = 0;
    for (int i=0;i<10;i++){
        if (mask & (1<<(vowels[i]-'a'))){
            new_mask |= (1<<i);
        }
    }
    return new_mask;
}

vector<string> max_w(ll mask){
    if (dp[mask].size() && dp[mask][0] == ":("){
        dp[mask] = vector<string>();
        int opt_mask = transmask(mask);
        for (int i=0;i<groups[opt_mask].size();i++){
            string guess = groups[opt_mask][i];
            ll guess_mask = 0;
            for (int j=0;j<guess.size();j++){
                guess_mask |= (1<<(guess[j]-'a'));
            }
            if (mask & guess_mask) continue;
            vector<string> candidate = max_w(mask | guess_mask);
            candidate.push_back(guess);
            if (candidate.size() > dp[mask].size()){
                dp[mask] = candidate;
            }
        }
        cout<<mask<<": ";
        for (int i=0;i<dp[mask].size();i++){
            cout<<dp[mask][i]<<" ";
        }
        cout<<endl;
    }
    return dp[mask];
}

int main(){
    // read answers.txt
    ifstream answersFile("answers.txt");
    vector<string> answers;
    string line;
    while (getline(answersFile, line)) {
        answers.push_back(line);
    }
    answersFile.close();

    // read guesses.txt
    ifstream guessesFile("guesses.txt");
    vector<string> guesses;
    while (getline(guessesFile, line)) {
        guesses.push_back(line);
    }
    guessesFile.close();

    for (int i=0;i<misvow;i++){
        for (const string& guess : guesses) {
            bool ok = true;
            for (int j=0;j<10 && ok;j++){
                if (i & (1<<j)){
                    if (in(vowels[j], guess)) ok = false;
                }
            }
            if (ok) groups[i].push_back(guess);
        }
    }

    for (int i=0;i<answers.size();i++){
        ll answers_mask = 0;
        for (int j=0;j<5;j++) answers_mask |= (1<<(answers[i][j]-'a'));
        vector<string> max_words = max_w(answers_mask);
        ofstream outputFile("output.txt", ios::app);
        outputFile << "For answer: " << answers[i] << endl;
        for (const string& word : max_words) {
            outputFile << word << endl;
        }
        outputFile << endl;
        outputFile.close();
    }

    return 0;
}


// Turns Transformation GUI (C) 2025
// Version with percentage control, multiple choice variant selection, and GUI without dependencies
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <random>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <stdexcept>
#include <cstdlib>
#include <cstring>
#include <memory>

// Helper to get note name (from MIDI number)
std::string getNoteName(int noteNumber) {
    static const std::string noteNames[] = {
        "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"
    };
    int octave = noteNumber / 12 - 1;
    int noteIndex = noteNumber % 12;
    return noteNames[noteIndex] + std::to_string(octave);
}

// Helper to get MIDI number from note name
int getNoteNumber(const std::string& noteName) {
    static const std::string noteNames[] = {
        "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"
    };

    // Extract note and octave
    std::string baseNote = noteName.substr(0, noteName.size() - 1);
    int octave = std::stoi(noteName.substr(noteName.size() - 1));

    // Find base note index
    auto it = std::find(std::begin(noteNames), std::end(noteNames), baseNote);
    if (it == std::end(noteNames)) {
        throw std::invalid_argument("Invalid note name: " + noteName);
    }
    int noteIndex = std::distance(std::begin(noteNames), it);

    return (octave + 1) * 12 + noteIndex;
}

// Enum for TimeMeter
enum TimeMeter {
    DUPLE,
    TRIPLE
};

// Helper functions for Turn variants
void handleTurnMeter(std::vector<std::pair<int, int>>& EmbRet, int upper, int principal, int lower, int pi, int durPi, TimeMeter meter) {
    if (meter == DUPLE) {
        int segment = durPi / 4;
        EmbRet.push_back({upper, segment});
        EmbRet.push_back({principal, segment});
        EmbRet.push_back({lower, segment});
        EmbRet.push_back({principal, durPi - 3 * segment}); // Remaining duration
    } else if (meter == TRIPLE) {
        int segment = durPi / 4;
        EmbRet.push_back({upper, segment});
        EmbRet.push_back({principal, segment});
        EmbRet.push_back({lower, segment});
        EmbRet.push_back({principal, durPi - 3 * segment}); // Remaining duration
    }
}

void handleTurnMeterFB(std::vector<std::pair<int, int>>& EmbRet, int upper, int pi, int lower, int underlower, int lower2, int pi2, int durPi, TimeMeter meter) {
    if (meter == DUPLE) {
        int segment = durPi / 8;
        EmbRet.push_back({upper, segment});
        EmbRet.push_back({pi, segment});
        EmbRet.push_back({lower, segment});
        EmbRet.push_back({underlower, segment});
        EmbRet.push_back({lower, segment});
        EmbRet.push_back({pi, durPi - 5 * segment}); // Remaining duration
    } else if (meter == TRIPLE) {
        int segment = durPi / 5;
        EmbRet.push_back({upper, segment});
        EmbRet.push_back({pi, segment});
        EmbRet.push_back({lower, segment});
        EmbRet.push_back({pi, segment});
        EmbRet.push_back({upper, durPi - 4 * segment}); // Remaining duration
    }
}

void handleTurnMeterBetween(std::vector<std::pair<int, int>>& EmbRet, int pi, int upper, int pi2, int lower, int pi3, int durPi, TimeMeter meter) {
    if (meter == DUPLE) {
        int segment = durPi / 8;
        EmbRet.push_back({pi, durPi / 2});
        EmbRet.push_back({upper, segment});
        EmbRet.push_back({pi2, segment});
        EmbRet.push_back({lower, segment});
        EmbRet.push_back({pi3, durPi - (durPi / 2 + 3 * segment)}); // Remaining duration
    } else if (meter == TRIPLE) {
        int segment = durPi / 8;
        EmbRet.push_back({pi, segment});
        EmbRet.push_back({upper, durPi / 4});
        EmbRet.push_back({pi2, durPi / 4});
        EmbRet.push_back({lower, durPi / 4});
        EmbRet.push_back({pi3, durPi - (segment + durPi / 4 + durPi / 4 + durPi / 4)}); // Remaining duration
    }
}

void handleTurnMeterTrille(std::vector<std::pair<int, int>>& EmbRet, int upper, int principal, int lower, int durPi, TimeMeter meter) {
    if (meter == DUPLE) {
        int segment = durPi / 8;
        EmbRet.push_back({upper, segment});
        EmbRet.push_back({principal, segment});
        EmbRet.push_back({upper, segment});
        EmbRet.push_back({principal, segment});
        EmbRet.push_back({lower, segment});
        EmbRet.push_back({principal, durPi - 5 * segment}); // Remaining duration
    } else if (meter == TRIPLE) {
        int segment = durPi / 8;
        EmbRet.push_back({upper, segment});
        EmbRet.push_back({principal, segment});
        EmbRet.push_back({upper, segment});
        EmbRet.push_back({principal, segment});
        EmbRet.push_back({lower, segment});
        EmbRet.push_back({principal, durPi - 5 * segment}); // Remaining duration
    }
}

void handleTurnMeterP32(std::vector<std::pair<int, int>>& EmbRet, int upper, int principal, int lower, int durPi, TimeMeter meter) {
    if (met


// Dongzhuo Li 04/22/2018

#include "Parameter.h"
#include <fstream>
#include <iostream>
#include <string>
// #define VERBOSE

using namespace std;
using namespace rapidjson;

Parameter::Parameter() {
  cout << "ERROR: You need to input parameter file name!" << endl;
  exit(1);
}

Parameter::Parameter(const std::string &para_fname) {

  string line;
  ifstream parafile;

  // open parameter file
  parafile.open(para_fname);
  if (!parafile.is_open()) {
    cout << "Error opening parameter file" << endl;
    exit(1);
  }

  // read the whole line of json file
  getline(parafile, line);
  parafile.close();

  Document json_para;
  json_para.Parse<0>(line.c_str());
  assert(json_para.IsObject());

#ifdef VERBOSE
  cout << "----------Reading Parameter File------------" << endl;
#endif
  assert(json_para.HasMember("nz"));
  assert(json_para["nz"].IsInt());
  nz_ = json_para["nz"].GetInt();

#ifdef VERBOSE
  cout << "	nz = " << nz_ << endl;
#endif

  assert(json_para.HasMember("nx"));
  assert(json_para["nx"].IsInt());
  nx_ = json_para["nx"].GetInt();
#ifdef VERBOSE
  cout << "	nx = " << nx_ << endl;
#endif

  assert(json_para.HasMember("dz"));
  assert(json_para["dz"].IsNumber());
  dz_ = json_para["dz"].GetDouble();
#ifdef VERBOSE
  cout << "	dz = " << dz_ << endl;
#endif

  assert(json_para.HasMember("dx"));
  assert(json_para["dx"].IsNumber());
  dx_ = json_para["dx"].GetDouble();
#ifdef VERBOSE
  cout << "	dx = " << dx_ << endl;
#endif

  assert(json_para.HasMember("nt"));
  assert(json_para["nt"].IsInt());
  nt_ = json_para["nt"].GetInt();
#ifdef VERBOSE
  cout << "	nt = " << nt_ << endl;
#endif

  assert(json_para.HasMember("npml"));
  assert(json_para["npml"].IsInt());
  npml_ = json_para["npml"].GetInt();
#ifdef VERBOSE
  cout << "	npml = " << npml_ << endl;
#endif

  assert(json_para.HasMember("ISURF"));
  assert(json_para["ISURF"].IsInt());
  ISURF_ = json_para["ISURF"].GetInt();
#ifdef VERBOSE
cout << "	isurf = " << ISURF_ << endl;
#endif

  assert(json_para.HasMember("npad"));
  assert(json_para["npad"].IsInt());
  npad_ = json_para["npad"].GetInt();
#ifdef VERBOSE
  cout << "	npad = " << npad_ << endl;
#endif

  assert(json_para.HasMember("dt"));
  assert(json_para["dt"].IsDouble());
  dt_ = json_para["dt"].GetDouble();
#ifdef VERBOSE
  cout << "	dt = " << dt_ << endl;
#endif

  assert(json_para.HasMember("f0"));
  f0_ = json_para["f0"].GetDouble();
#ifdef VERBOSE
  cout << "	f0 = " << f0_ << endl;
#endif

  assert(json_para.HasMember("weight_pr"));
  weight_pr_ = json_para["weight_pr"].GetDouble();
#ifdef VERBOSE
  cout << "	weight_pr = " << weight_pr_ << endl;
#endif

  assert(json_para.HasMember("weight_vx"));
  weight_vx_ = json_para["weight_vx"].GetDouble();
#ifdef VERBOSE
  cout << "	weight_vx = " << weight_vx_ << endl;
#endif

  assert(json_para.HasMember("weight_vz"));
  weight_vz_ = json_para["weight_vz"].GetDouble();
#ifdef VERBOSE
  cout << "	weight_vz = " << weight_vz_ << endl;
#endif

  assert(json_para.HasMember("weight_et"));
  weight_et_ = json_para["weight_et"].GetDouble();
#ifdef VERBOSE
  cout << "	weight_et = " << weight_et_ << endl;
#endif

  assert(json_para.HasMember("survey_fname"));
  assert(json_para["survey_fname"].IsString());
  survey_fname_ = json_para["survey_fname"].GetString();
#ifdef VERBOSE
  cout << "	survey_fname = " << survey_fname_ << endl;
#endif

  assert(json_para.HasMember("data_dir_name"));
  assert(json_para["data_dir_name"].IsString());
  data_dir_name_ = json_para["data_dir_name"].GetString();
#ifdef VERBOSE
  cout << "	data_dir_name = " << data_dir_name_ << endl;
#endif

  if (json_para.HasMember("scratch_dir_name")) {
    if_save_scratch_ = true;
    assert(json_para["scratch_dir_name"].IsString());
    scratch_dir_name_ = json_para["scratch_dir_name"].GetString();
#ifdef VERBOSE
    cout << "	scratch_dir_name = " << scratch_dir_name_ << endl;
#endif
  }

  if_win_ = false;
  if (json_para.HasMember("if_win")) {
    assert(json_para["if_win"].IsBool());
    if_win_ = json_para["if_win"].GetBool();
  }
#ifdef VERBOSE
  cout << "	With Window Selection = " << if_win_ << endl;
#endif

  if_filter_ = false;
  if (json_para.HasMember("filter")) {
    if_filter_ = true;
    assert(json_para["filter"].IsArray());
    const Value &js_filter = json_para["filter"];
    for (SizeType ii = 0; ii < js_filter.Size(); ii++) {
      filter_[ii] = js_filter[ii].GetDouble();
    }
#ifdef VERBOSE
    cout << "	With Filtering = " << if_filter_ << endl;
#endif
    printf("	filter = [%.2f, %.2f, %.2f, %.2f]\n", filter_[0], filter_[1],
           filter_[2], filter_[3]);
  }

  if_src_update_ = false;
  if (json_para.HasMember("if_src_update")) {
    assert(json_para["if_src_update"].IsBool());
    if_src_update_ = json_para["if_src_update"].GetBool();
  }
#ifdef VERBOSE
  cout << "	With Source Update = " << if_src_update_ << endl;
#endif

  if (json_para.HasMember("if_cross_misfit")) {
    assert(json_para["if_cross_misfit"].IsBool());
    if_cross_misfit_ = json_para["if_