<commit_before>
#include <string>
#include <vector>
#include <memory>

#include <glm/glm.hpp>

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

#include "Mesh.h"
#include "Scene.h"
#include "Window.h"
#include "Renderer.h"
#include "Renderable.h"
#include "ModelLoader.h"
#include "ImGuiAdapter.h"
#include "DiffuseMaterial.h"

int main(int argc, char *argv[])
{
	//
	// Logging etc.
	//

	int width = 1280;
	int height = 720;
	bool fullscreen = false;
	bool vsync = false;

#if defined(_DEBUG) or defined(DEBUG)
	Logger::Heading("Rendeer - debug build");
#else
	Logger::Heading("Rendeer - release build");
#endif
	Logger::Log(" - Resolution:\t %dx%d", width, height);
	Logger::Log(" - Fullscreen:\t %s", Logger::BoolToString(fullscreen));
	Logger::Log(" - Vsync:\t\t %s", Logger::BoolToString(vsync));

	Logger::Subheading("Scene setup begin");
	Logger::LogTimestamp();
	Logger::EmptyLine();

	//
	// Setup
	//

	Window window{ width, height, fullscreen, vsync };
	Renderer renderer{ &window };
	ImGuiAdapter::Init(&window);

	//
	// Define scene
	//

	Scene scene;

	auto camera = std::make_shared<Camera>(
		glm::vec3{ 0, 1.7f, -5.0f },
		glm::angleAxis(0.15f, glm::vec3{ 1, 0, 0 })
	);
	scene.AddChild(camera);

	scene.SetSkybox(std::make_shared<TextureCube>(
		Bitmap{"textures/skybox_sunset/left.png"},
		Bitmap{"textures/skybox_sunset/right.png"},
		Bitmap{"textures/skybox_sunset/bottom.png"},
		Bitmap{"textures/skybox_sunset/top.png"},
		Bitmap{"textures/skybox_sunset/front.png"},
		Bitmap{"textures/skybox_sunset/back.png"}
	));

	scene.SetAmbientColor(glm::vec3{ 0.02f, 0.02f, 0.02f });

	auto teapot = ModelLoader::Load("models/teapot/teapot.obj");
	scene.AddChild(teapot)->GetTransform().SetScale(0.032f);

	auto sponza = ModelLoader::Load("models/dabrovic-sponza/sponza.obj");
	scene.AddChild(sponza);

	//auto directionalLight = scene.NewChild();
	//directionalLight->GetTransform().SetOrientation(glm::quat{ 0.00873f, 0.0f, 0.0f, 0.99996f });
	//directionalLight->AddComponent(std::make_shared<DirectionalLight>(glm::vec3{ 0.92f, 0.95f, 0.88f }, 1.5f));

	auto pointLight = scene.NewChild();
	pointLight->AddComponent(std::make_shared<PointLight>(glm::vec3{ 1.0f, 0.1f, 0.15f }, 1.35f));

	auto spotLight = scene.NewChild();
	spotLight->GetTransform()
		.SetPosition(glm::vec3{ 0, 10.0f, 0 })
		.SetOrientation(glm::angleAxis(3.141592f / 2.0f, glm::vec3{1, 0, 0 }));
	spotLight->AddComponent(std::make_shared<SpotLight>(glm::vec3{ 1.0f, 0.6f, 0.6f }, 12.0f, glm::radians(40.0f), glm::radians(5.0f)));

	// Set up the extra camera
	auto extraCamera = std::make_shared<CameraComponent>(16.0f / 9.0f, 0.1f, 1000.0f, glm::radians(50.0f));
	auto extraCameraTexture = std::make_shared<Texture2D>(853, 480, GL_RGBA, GL_RGBA8, GL_CLAMP_TO_EDGE, GL_NEAREST, GL_NEAREST);
	auto extraCameraTarget = std::make_shared<FrameBuffer>();
	extraCameraTarget->Attach(extraCameraTexture.get(), GL_COLOR_ATTACHMENT0);
	extraCamera->SetTarget(extraCameraTarget);
	spotLight->NewChild()->AddComponent(extraCamera);

	// Set up the extra camera target model
	auto tv = ModelLoader::Load("models/cube.obj");
	tv->GetTransform()
		.SetPosition(15.0f, 2.3f, 0)
		.SetScale(1.8f).Scale(0.05f, 16.0f / 9.0f, 1) // TODO: Fix mirroring etc.
		.Rotate(glm::vec3{1,0,0}, 3.1415f / 2.0f);
	scene.AddChild(tv);
	{
		// HACK!!! There needs to be a real nice way to search for a component in a scene graph!
		auto renderable = tv->GetDirectChildren().front()->GetComponent<Renderable>();
		auto mat = std::dynamic_pointer_cast<DiffuseMaterial>(renderable->GetMaterial());
		mat->diffuseTexture = extraCameraTexture;
		mat->specularIntensity = 0.0f;
		mat->emissive = 0.25f;
	}

	//
	// Render/game loop
	//

	Logger::Subheading("Render loop begin");
	Logger::LogTimestamp();
	Logger::EmptyLine();

	glfwSetTime(0.0);
	double currentTime = 0.0;
	double previousTime = glfwGetTime();

	float animation = 0.0f;

	bool stickDirectionalLightToCamera = false;

	window.Focus();
	while (!window.IsCloseRequested())
	{
		currentTime = glfwGetTime();
		const double dt = currentTime - previousTime;
		const float deltaTime = static_cast<float>(dt);
		previousTime = currentTime;

		window.PollEvents();
		ImGuiAdapter::NewFrame(deltaTime);

		if (window.IsCursorHidden())
		{
			camera->Update(deltaTime, window);
		}

		if (window.WasKeyPressed(GLFW_KEY_LEFT_ALT))
		{
			window.SetCursorHidden(!window.IsCursorHidden());
		}

		animation += deltaTime;

		teapot->GetTransform()
			.SetOrientation(glm::vec3(0, 1, 0), 0.7f * animation)
			.SetPosition(0, 0.4f + 0.2f * cosf(2.0f * animation), 0);

		pointLight->GetTransform().SetPosition(
			6.0f * cosf(1.3f * animation),
			1.4f + 0.6f * cosf(sinf(animation)),
			6.0f * sinf(1.3f * animation)
		);

		if (window.WasKeyPressed(GLFW_KEY_LEFT_CONTROL))
		{
			stickDirectionalLightToCamera = !stickDirectionalLightToCamera;
		}

		if (stickDirectionalLightToCamera)
		{
			// (Spot light must be attached directly to root node / scene for this to work properly)
			auto cameraPosition = camera->GetTransform().GetPositionInWorld();
			auto cameraOrientation = camera->GetTransform().GetOrientationInWorld();
			spotLight->GetTransform().SetPosition(cameraPosition).SetOrientation(cameraOrientation);
		}

		renderer.Render(scene);

		ImGui::ShowTestWindow();
		ImGui::Render();

		window.SwapBuffers();
	}

	//
	// Deinit
	//

	Logger::Subheading("Render loop end");
	Logger::LogTimestamp();

	ImGuiAdapter::Deinit();

	return 0;
}
<commit_msg>Add custom UI features<commit_after>
#include <string>
#include <vector>
#include <memory>

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

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

#include "Mesh.h"
#include "Scene.h"
#include "Window.h"
#include "Renderer.h"
#include "Renderable.h"
#include "ModelLoader.h"
#include "ImGuiAdapter.h"
#include "DiffuseMaterial.h"

int main(int argc, char *argv[])
{
	//
	// Logging etc.
	//

	int width = 1280;
	int height = 720;
	bool fullscreen = false;
	bool vsync = false;

#if defined(_DEBUG) or defined(DEBUG)
	Logger::Heading("Rendeer - debug build");
#else
	Logger::Heading("Rendeer - release build");
#endif
	Logger::Log(" - Resolution:\t %dx%d", width, height);
	Logger::Log(" - Fullscreen:\t %s", Logger::BoolToString(fullscreen));
	Logger::Log(" - Vsync:\t\t %s", Logger::BoolToString(vsync));

	Logger::Subheading("Scene setup begin");
	Logger::LogTimestamp();
	Logger::EmptyLine();

	//
	// Setup
	//

	Window window{ width, height, fullscreen, vsync };
	Renderer renderer{ &window };
	ImGuiAdapter::Init(&window);

	//
	// Define scene
	//

	Scene scene;

	auto camera = std::make_shared<Camera>(
		glm::vec3{ 0, 1.7f, -5.0f },
		glm::angleAxis(0.15f, glm::vec3{ 1, 0, 0 })
	);
	scene.AddChild(camera);

	scene.SetSkybox(std::make_shared<TextureCube>(
		Bitmap{"textures/skybox_sunset/left.png"},
		Bitmap{"textures/skybox_sunset/right.png"},
		Bitmap{"textures/skybox_sunset/bottom.png"},
		Bitmap{"textures/skybox_sunset/top.png"},
		Bitmap{"textures/skybox_sunset/front.png"},
		Bitmap{"textures/skybox_sunset/back.png"}
	));

	scene.SetAmbientColor(glm::vec3{ 0.012f, 0.020f, 0.032f });

	auto teapot = ModelLoader::Load("models/teapot/teapot.obj");
	scene.AddChild(teapot)->GetTransform().SetScale(0.032f);

	auto sponza = ModelLoader::Load("models/dabrovic-sponza/sponza.obj");
	scene.AddChild(sponza);

	//auto directionalLight = scene.NewChild();
	//directionalLight->GetTransform().SetOrientation(glm::quat{ 0.00873f, 0.0f, 0.0f, 0.99996f });
	//directionalLight->AddComponent(std::make_shared<DirectionalLight>(glm::vec3{ 0.92f, 0.95f, 0.88f }, 1.5f));

	auto pointLight = scene.NewChild();
	pointLight->AddComponent(std::make_shared<PointLight>(glm::vec3{ 1.0f, 0.1f, 0.15f }, 1.35f));

	auto spotLight = scene.NewChild();
	spotLight->GetTransform()
		.SetPosition(glm::vec3{ 0, 10.0f, 0 })
		.SetOrientation(glm::angleAxis(3.141592f / 2.0f, glm::vec3{1, 0, 0 }));
	spotLight->AddComponent(std::make_shared<SpotLight>(glm::vec3{ 1.0f, 0.6f, 0.6f }, 12.0f, glm::radians(40.0f), glm::radians(5.0f)));

	// Set up the extra camera
	auto extraCamera = std::make_shared<CameraComponent>(16.0f / 9.0f, 0.1f, 1000.0f, glm::radians(50.0f));
	auto extraCameraTexture = std::make_shared<Texture2D>(853, 480, GL_RGBA, GL_RGBA8, GL_CLAMP_TO_EDGE, GL_NEAREST, GL_NEAREST);
	auto extraCameraTarget = std::make_shared<FrameBuffer>();
	extraCameraTarget->Attach(extraCameraTexture.get(), GL_COLOR_ATTACHMENT0);
	extraCamera->SetTarget(extraCameraTarget);
	spotLight->NewChild()->AddComponent(extraCamera);

	// Set up the extra camera target model
	auto tv = ModelLoader::Load("models/cube.obj");
	tv->GetTransform()
		.SetPosition(15.0f, 2.3f, 0)
		.SetScale(1.8f).Scale(0.05f, 16.0f / 9.0f, 1) // TODO: Fix mirroring etc.
		.Rotate(glm::vec3{1,0,0}, 3.1415f / 2.0f);
	scene.AddChild(tv);
	{
		// HACK!!! There needs to be a real nice way to search for a component in a scene graph!
		auto renderable = tv->GetDirectChildren().front()->GetComponent<Renderable>();
		auto mat = std::dynamic_pointer_cast<DiffuseMaterial>(renderable->GetMaterial());
		mat->diffuseTexture = extraCameraTexture;
		mat->specularIntensity = 0.0f;
		mat->emissive = 0.25f;
	}

	//
	// Render/game loop
	//

	Logger::Subheading("Render loop begin");
	Logger::LogTimestamp();
	Logger::EmptyLine();

	glfwSetTime(0.0);
	double currentTime = 0.0;
	double previousTime = glfwGetTime();

	float animation = 0.0f;

	bool stickDirectionalLightToCamera = false;

	window.Focus();
	while (!window.IsCloseRequested())
	{
		currentTime = glfwGetTime();
		const double dt = currentTime - previousTime;
		const float deltaTime = static_cast<float>(dt);
		previousTime = currentTime;

		window.PollEvents();
		ImGuiAdapter::NewFrame(deltaTime);

		if (window.IsCursorHidden())
		{
			camera->Update(deltaTime, window);
		}

		if (window.WasKeyPressed(GLFW_KEY_LEFT_ALT))
		{
			window.SetCursorHidden(!window.IsCursorHidden());
		}

		animation += deltaTime;

		teapot->GetTransform()
			.SetOrientation(glm::vec3(0, 1, 0), 0.7f * animation)
			.SetPosition(0, 0.4f + 0.2f * cosf(2.0f * animation), 0);

		pointLight->GetTransform().SetPosition(
			6.0f * cosf(1.3f * animation),
			1.4f + 0.6f * cosf(sinf(animation)),
			6.0f * sinf(1.3f * animation)
		);

		if (window.WasKeyPressed(GLFW_KEY_LEFT_CONTROL))
		{
			stickDirectionalLightToCamera = !stickDirectionalLightToCamera;
		}

		if (stickDirectionalLightToCamera)
		{
			// (Spot light must be attached directly to root node / scene for this to work properly)
			auto cameraPosition = camera->GetTransform().GetPositionInWorld();
			auto cameraOrientation = camera->GetTransform().GetOrientationInWorld();
			spotLight->GetTransform().SetPosition(cameraPosition).SetOrientation(cameraOrientation);
		}

		ImGui::Begin("Rendeer");
		{
			static bool showMetrics = false;
			ImGui::Checkbox("Show metrics", &showMetrics);

			if (showMetrics)
			{
				ImGui::ShowMetricsWindow();
			}

			static glm::vec3 ambientColor = scene.GetAmbientColor();
			ImGui::ColorEdit3("Ambient color", glm::value_ptr(ambientColor));
			scene.SetAmbientColor(ambientColor);
		}
		ImGui::End();

		renderer.Render(scene);
		ImGui::Render();
		window.SwapBuffers();
	}

	//
	// Deinit
	//

	Logger::Subheading("Render loop end");
	Logger::LogTimestamp();

	ImGuiAdapter::Deinit();

	return 0;
}
<|endoftext|>


<commit_before>/* vim: set ai et ts=4 sw=4: */

/**
 * @mainpage HurmaDB
 *
 * HurmaDB is an experimental NoSQL database. It uses RocksDB as a disk backend and provides REST API.
 */

#include <HttpServer.h>
#include <PersistentStorage.h>
#include <TcpServer.h>
#include <atomic>
#include <iostream>
#include <map>
#include <signal.h>
#include <sstream>
#include <string>
#include <unistd.h>
#include <utility>

PersistentStorage storage;

static std::atomic_bool terminate_flag(false);

static void httpIndexGetHandler(const HttpRequest&, HttpResponse& resp) {
    resp.setStatus(HTTP_STATUS_OK);

    std::ostringstream oss;
    oss << "HurmaDB is " << (terminate_flag.load() ? "terminating" : "running") << "!\n\n";
    resp.setBody(oss.str());
}

static void httpKVGetHandler(const HttpRequest& req, HttpResponse& resp) {
    bool found;
    const std::string& key = req.getQueryMatch(0);
    const std::string& value = storage.get(key, &found);
    resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
    resp.setBody(value);
}

/**
 * @todo Rewrite using Storage::getRange instead of deprecated getRangeJson
 */
static void httpKVGetRangeHandler(const HttpRequest& req, HttpResponse& resp) {
    const std::string& key_from = req.getQueryMatch(0);
    const std::string& key_to = req.getQueryMatch(1);
    const std::string& valuesJson = storage.getRangeJson(key_from, key_to);
    resp.setStatus(HTTP_STATUS_OK);
    resp.setBody(valuesJson);
}

static void httpKVPutHandler(const HttpRequest& req, HttpResponse& resp) {
    const std::string& key = req.getQueryMatch(0);
    const std::string& value = req.getBody();
    bool ok = true;
    try {
        storage.set(key, value);
    } catch(const std::runtime_error& e) {
        // Most likely validation failed
        ok = false;
    }

    resp.setStatus(ok ? HTTP_STATUS_OK : HTTP_STATUS_BAD_REQUEST);
}

static void httpKVDeleteHandler(const HttpRequest& req, HttpResponse& resp) {
    bool found = false;
    const std::string& key = req.getQueryMatch(0);
    storage.del(key, &found);
    resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
}

/* Required for generating code coverage report */
static void httpStopPutHandler(const HttpRequest&, HttpResponse& resp) {
    terminate_flag.store(true);
    resp.setStatus(HTTP_STATUS_OK);
}

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

    int c;
    bool httpPortSet = false;
    int httpPort = 8080;

    while((c = getopt(argc, argv, "p:h:")) != -1)
        switch(c) {
            case 'h':
                httpPort = atoi(optarg);
                httpPortSet = true;
                break;
        }

    if(!httpPortSet) {
        std::cerr << "Usage: " << argv[0] << " -h http_port" << std::endl;
        return 2;
    }

    if(httpPort <= 0 || httpPort >= 65536) {
        std::cerr << "Invalid HTTP port number!" << std::endl;
        return 2;
    }

    HttpServer httpServer;

    httpServer.addHandler(HTTP_GET, "(?i)^/$", &httpIndexGetHandler);
    httpServer.addHandler(HTTP_PUT, "(?i)^/v1/_stop/?$", &httpStopPutHandler);
    httpServer.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVGetHandler);
    httpServer.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/([\\w-]+)/?$", &httpKVGetRangeHandler);
    httpServer.addHandler(HTTP_PUT, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVPutHandler);
    httpServer.addHandler(HTTP_DELETE, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVDeleteHandler);

    std::cout << "Starting HTTP server on port " << httpPort << std::endl;
    httpServer.listen("127.0.0.1", httpPort);

    // Unlike POSIX accept() procedure none of these .accept methods is blocking
    while(!terminate_flag.load()) {
        httpServer.accept(terminate_flag);
    }

    return 0;
}
<commit_msg>Minor changes<commit_after>/* vim: set ai et ts=4 sw=4: */

/**
 * @mainpage HurmaDB
 *
 * HurmaDB is an experimental NoSQL database. It uses RocksDB as a disk backend and provides REST API.
 */

#include <HttpServer.h>
#include <PersistentStorage.h>
#include <TcpServer.h>
#include <atomic>
#include <iostream>
#include <map>
#include <signal.h>
#include <sstream>
#include <string>
#include <unistd.h>
#include <utility>

PersistentStorage storage;

static std::atomic_bool terminate_flag(false);

static void httpIndexGetHandler(const HttpRequest&, HttpResponse& resp) {
    resp.setStatus(HTTP_STATUS_OK);

    std::ostringstream oss;
    oss << "HurmaDB is " << (terminate_flag.load() ? "terminating" : "running") << "!\n\n";
    resp.setBody(oss.str());
}

static void httpKVGetHandler(const HttpRequest& req, HttpResponse& resp) {
    bool found;
    const std::string& key = req.getQueryMatch(0);
    const std::string& value = storage.get(key, &found);
    resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
    resp.setBody(value);
}

/**
 * @todo Rewrite using Storage::getRange instead of deprecated getRangeJson
 */
static void httpKVGetRangeHandler(const HttpRequest& req, HttpResponse& resp) {
    const std::string& key_from = req.getQueryMatch(0);
    const std::string& key_to = req.getQueryMatch(1);
    const std::string& valuesJson = storage.getRangeJson(key_from, key_to);
    resp.setStatus(HTTP_STATUS_OK);
    resp.setBody(valuesJson);
}

static void httpKVPutHandler(const HttpRequest& req, HttpResponse& resp) {
    const std::string& key = req.getQueryMatch(0);
    const std::string& value = req.getBody();
    bool ok = true;
    try {
        storage.set(key, value);
    } catch(const std::runtime_error& e) {
        // Most likely validation failed
        ok = false;
    }

    resp.setStatus(ok ? HTTP_STATUS_OK : HTTP_STATUS_BAD_REQUEST);
}

static void httpKVDeleteHandler(const HttpRequest& req, HttpResponse& resp) {
    bool found = false;
    const std::string& key = req.getQueryMatch(0);
    storage.del(key, &found);
    resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
}

/* Required for generating code coverage report */
static void httpStopPutHandler(const HttpRequest&, HttpResponse& resp) {
    terminate_flag.store(true);
    resp.setStatus(HTTP_STATUS_OK);
}

int main(int argc, char** argv) {
    bool httpPortSet = false;
    int httpPort = 8080;

    for(;;) {
        int ch = getopt(argc, argv, "h:");
        if(ch == -1) {
            break;
        } else if(ch == 'h') {
            httpPort = atoi(optarg);
            httpPortSet = true;
        }
    }

    if(!httpPortSet) {
        std::cerr << "Usage: " << argv[0] << " -h http_port" << std::endl;
        return 2;
    }

    if(httpPort <= 0 || httpPort >= 65536) {
        std::cerr << "Invalid HTTP port number!" << std::endl;
        return 2;
    }

    HttpServer httpServer;

    httpServer.addHandler(HTTP_GET, "(?i)^/$", &httpIndexGetHandler);
    httpServer.addHandler(HTTP_PUT, "(?i)^/v1/_stop/?$", &httpStopPutHandler);
    httpServer.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVGetHandler);
    httpServer.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/([\\w-]+)/?$", &httpKVGetRangeHandler);
    httpServer.addHandler(HTTP_PUT, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVPutHandler);
    httpServer.addHandler(HTTP_DELETE, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVDeleteHandler);

    std::cout << "Starting HTTP server on port " << httpPort << std::endl;
    httpServer.listen("127.0.0.1", httpPort);

    while(!terminate_flag.load()) {
        httpServer.accept(terminate_flag);
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <cv.h>
#include "opencv2/opencv.hpp"
#include "SongLoader.h"
#include "SongPlayer.h"
#include "videoStream.hpp"
#include <MusicBar.h>

//for the rasperry pi
#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif
extern "C" {
    #include <SDL.h>
    #include <SDL_ttf.h>
}
#include <stdio.h>
#include <unistd.h>

#ifdef __amd64__
    #ifndef RUNNINGONINTEL
    #define RUNNINGONINTEL
    #endif
#else
    #ifndef RUNNINGONPI
    #define RUNNINGONPI
    #endif
    #include "WiringPiButtons.hpp"
#endif

#define SCREEN_HEIGHT 768
#define SCREEN_WIDTH 1232

void processEvents();
void signalToQuit();
void close();

SDL_Renderer* renderer = NULL;
SDL_Window* window = NULL;

SDL_Rect videoRect;
SDL_Rect musicBarRect;
int noSongs;

VideoStream backupCamera;

int quit;

SongPlayer musicPlayer;
MusicBar gordonMusic(&musicPlayer);

/***********************************************************************
/*                          SDL functions
/***********************************************************************/
// Initializes SDL window / renderer for use

bool init_SDL()
{
    bool success = true;

    if (SDL_Init(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) < 0)
    {
        printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
        success = false;
    }
    else
    {
        window = SDL_CreateWindow("Video Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        if (window == NULL)
        {
            printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
            success = false;
        }
        else
        {
            renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
            if (renderer == NULL)
            {
                printf("Renderer could not be created. SDL_Error: %s \n", SDL_GetError());
                success = false;
            }
            else
            {
                SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
            }
        }
    }
    return success;
}

bool init_CameraSettings()
{
    int w, h;
    bool success = true;
    SDL_GetWindowSize(window, &w, &h);
    videoRect.x = 0;
    videoRect.y = 0;
    videoRect.w = w;
    videoRect.h = h-50; //change 50 to whatever height we want for the PI cam

    musicBarRect.x = 0;
    musicBarRect.y = h-49;
    musicBarRect.w = w;
    musicBarRect.h = 49;
    //cameraWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH);
    //cameraHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
    //printf("Camera Width %d, Camera Height %d \n",cameraWidth,cameraHeight);

    return success;
}

// Shows an individual frame of the supplied video
int show_Camera()
{
    if(backupCamera.imageReady())
    {
        IplImage* img = NULL;
        img = backupCamera.getFrame();
        SDL_Surface* surface = SDL_CreateRGBSurfaceFrom((void*)img->imageData,
            img->width,
            img->height,
            img->depth * img->nChannels,
            img->widthStep,
            0xff0000, 0x00ff00, 0x0000ff, 0
            );

        SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
        SDL_FreeSurface(surface);
        surface = NULL;
        #ifdef RUNNINGONPI
        SDL_RendererFlip flip = SDL_FLIP_VERTICAL;
        #else
        SDL_RendererFlip flip = SDL_FLIP_HORIZONTAL;
        #endif
        SDL_RenderCopyEx(renderer, texture, NULL, &videoRect ,0, NULL, flip);
        SDL_DestroyTexture(texture);
        return 1;
    }
    return 0;
}

void processEvents()
{
    SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            switch(event.type)
            {
                case SDL_QUIT:
                    printf("SDL_QUIT was called\n");
                    signalToQuit();
                    close();
                    break;

                case SDL_KEYDOWN:
                    switch(event.key.keysym.sym)
                    {
                        case SDLK_ESCAPE:
                            printf("Esc was Pressed!\n");
                            signalToQuit();
                            close();
                            break;
                        case SDLK_LEFT:
                            printf("Left arrow was Pressed!\n");
                            musicPlayer.previousSong();
                            break;
                        case SDLK_RIGHT:
                            printf("Right arrow was Pressed!\n");
                            musicPlayer.nextSong();
                            break;
                        case SDLK_UP:
                            musicPlayer.changeVolume(0.02);
                            break;
                        case SDLK_DOWN:
                            musicPlayer.changeVolume(-0.02);
                            break;
                        case SDLK_SPACE:
                            printf("Space was pressed!\n");
                            musicPlayer.playPause();
                    }
            }
        }
}
#ifdef RUNNINGONPI
void processGPIO(WiringPiButtons::Button button)
{
    switch(button)
    {
        case WiringPiButtons::PREVIOUS:
	    musicPlayer.previousSong();
	    break;
	case WiringPiButtons::NEXT:
	    musicPlayer.nextSong();
	    break;
	case WiringPiButtons::VOLUMEUP:
	    musicPlayer.changeVolume(0.02);
	    break;
	case WiringPiButtons::VOLUMEDOWN:
	    musicPlayer.changeVolume(-0.02);
	    break;
	case WiringPiButtons::TOGGLEPLAY:
	    musicPlayer.playPause();
	default:
	    break;
    }
}
#endif

/* Signals all the threads to quit and then waits for the threads */
void signalToQuit()
{
    backupCamera.signalToQuit();
    musicPlayer.songQuit();
}

/* Cleans up and should free everything used in the program*/
void close()
{
    musicPlayer.closeSongPlayer();
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    window = NULL;
    renderer = NULL;
    SDL_Quit();
    exit(0);
}

int main(int argc, char* argv[])
{
    #ifdef RUNNINGONPI
        WiringPiButtons buttonManager;
    #endif

    if (!init_SDL())
    {
        fprintf(stderr, "Could not initialize SDL!\n");
        return -1;
    }
    if (!init_CameraSettings())
    {
        printf("Failed to load settings!\n");
        return -1;
    }

    if (musicPlayer.initSongPlayer())
    {
        fprintf(stderr, "No SongLibrary Folder! Not creating Music Thread!\n");
    }
    else
    {
        musicPlayer.StartInternalThread();
    }
    backupCamera.StartInternalThread();

    while (!quit)
    {
        processEvents();
        #ifdef RUNNINGONPI
        processGPIO(buttonManager.getEvents());
        #endif

        if (show_Camera())
        {
            SDL_Surface* surfaceBar;
            gordonMusic.update();
            surfaceBar = gordonMusic.returnMusicBar();
            #ifdef RUNNINGONPI
            SDL_RendererFlip flip = SDL_RendererFlip((int)SDL_FLIP_HORIZONTAL | (int)SDL_FLIP_VERTICAL);
            #else
            SDL_RendererFlip flip = SDL_FLIP_NONE;
            #endif
            SDL_Texture* textureMusicBar = SDL_CreateTextureFromSurface(renderer, surfaceBar);
            SDL_RenderCopyEx(renderer, textureMusicBar, NULL, &musicBarRect ,0, NULL, flip);
            SDL_DestroyTexture(textureMusicBar);
            SDL_RenderPresent(renderer);
            SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
            SDL_RenderClear(renderer);
        }
    }

    musicPlayer.WaitForInternalThreadToExit();
    backupCamera.WaitForInternalThreadToExit();
    return 0;
}
<commit_msg>Changed main to be no longer dependent on the music bar<commit_after>#include <cv.h>
#include "opencv2/opencv.hpp"
#include "SongLoader.h"
#include "SongPlayer.h"
#include "videoStream.hpp"
#include <MusicBar.h>

//for the rasperry pi
#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif
extern "C" {
    #include <SDL.h>
    #include <SDL_ttf.h>
}
#include <stdio.h>
#include <unistd.h>

#ifdef __amd64__
    #ifndef RUNNINGONINTEL
    #define RUNNINGONINTEL
    #endif
#else
    #ifndef RUNNINGONPI
    #define RUNNINGONPI
    #endif
    #include "WiringPiButtons.hpp"
#endif

#define SCREEN_HEIGHT 768
#define SCREEN_WIDTH 1232

void processEvents();
void signalToQuit();
void close();

SDL_Renderer* renderer = NULL;
SDL_Window* window = NULL;

SDL_Rect videoRect;
SDL_Rect musicBarRect;

VideoStream backupCamera;

int quit;

int noSongs;
SongPlayer musicPlayer;
MusicBar gordonMusic(&musicPlayer);

/***********************************************************************
/*                          SDL functions
/***********************************************************************/
// Initializes SDL window / renderer for use

bool init_SDL()
{
    bool success = true;

    if (SDL_Init(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) < 0)
    {
        printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
        success = false;
    }
    else
    {
        window = SDL_CreateWindow("Video Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        if (window == NULL)
        {
            printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
            success = false;
        }
        else
        {
            renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
            if (renderer == NULL)
            {
                printf("Renderer could not be created. SDL_Error: %s \n", SDL_GetError());
                success = false;
            }
            else
            {
                SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
            }
        }
    }
    return success;
}

bool init_CameraSettings()
{
    int w, h;
    bool success = true;
    SDL_GetWindowSize(window, &w, &h);
    videoRect.x = 0;
    videoRect.y = 0;
    videoRect.w = w;
    videoRect.h = h-50; //change 50 to whatever height we want for the PI cam

    musicBarRect.x = 0;
    musicBarRect.y = h-49;
    musicBarRect.w = w;
    musicBarRect.h = 49;
    //cameraWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH);
    //cameraHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
    //printf("Camera Width %d, Camera Height %d \n",cameraWidth,cameraHeight);

    return success;
}

// Shows an individual frame of the supplied video
int show_Camera()
{
    if(backupCamera.imageReady())
    {
        IplImage* img = NULL;
        img = backupCamera.getFrame();
        SDL_Surface* surface = SDL_CreateRGBSurfaceFrom((void*)img->imageData,
            img->width,
            img->height,
            img->depth * img->nChannels,
            img->widthStep,
            0xff0000, 0x00ff00, 0x0000ff, 0
            );

        SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
        SDL_FreeSurface(surface);
        surface = NULL;
        #ifdef RUNNINGONPI
        SDL_RendererFlip flip = SDL_FLIP_VERTICAL;
        #else
        SDL_RendererFlip flip = SDL_FLIP_HORIZONTAL;
        #endif
        SDL_RenderCopyEx(renderer, texture, NULL, &videoRect ,0, NULL, flip);
        SDL_DestroyTexture(texture);
        return 1;
    }
    return 0;
}

void processEvents()
{
    SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            switch(event.type)
            {
                case SDL_QUIT:
                    printf("SDL_QUIT was called\n");
                    signalToQuit();
                    close();
                    break;

                case SDL_KEYDOWN:
                    switch(event.key.keysym.sym)
                    {
                        case SDLK_ESCAPE:
                            printf("Esc was Pressed!\n");
                            signalToQuit();
                            close();
                            break;
                        case SDLK_LEFT:
                            printf("Left arrow was Pressed!\n");
                            musicPlayer.previousSong();
                            break;
                        case SDLK_RIGHT:
                            printf("Right arrow was Pressed!\n");
                            musicPlayer.nextSong();
                            break;
                        case SDLK_UP:
                            musicPlayer.changeVolume(0.02);
                            break;
                        case SDLK_DOWN:
                            musicPlayer.changeVolume(-0.02);
                            break;
                        case SDLK_SPACE:
                            printf("Space was pressed!\n");
                            musicPlayer.playPause();
                    }
            }
        }
}
#ifdef RUNNINGONPI
void processGPIO(WiringPiButtons::Button button)
{
    switch(button)
    {
        case WiringPiButtons::PREVIOUS:
	    musicPlayer.previousSong();
	    break;
	case WiringPiButtons::NEXT:
	    musicPlayer.nextSong();
	    break;
	case WiringPiButtons::VOLUMEUP:
	    musicPlayer.changeVolume(0.02);
	    break;
	case WiringPiButtons::VOLUMEDOWN:
	    musicPlayer.changeVolume(-0.02);
	    break;
	case WiringPiButtons::TOGGLEPLAY:
	    musicPlayer.playPause();
	default:
	    break;
    }
}
#endif

/* Signals all the threads to quit and then waits for the threads */
void signalToQuit()
{
    backupCamera.signalToQuit();
    musicPlayer.songQuit();
}

/* Cleans up and should free everything used in the program*/
void close()
{
    musicPlayer.closeSongPlayer();
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    window = NULL;
    renderer = NULL;
    SDL_Quit();
    exit(0);
}

int showMusicBar()
{

    SDL_Surface* surfaceBar;
    gordonMusic.update();
    surfaceBar = gordonMusic.returnMusicBar();
    SDL_Texture* textureMusicBar = SDL_CreateTextureFromSurface(renderer, surfaceBar);
    #ifdef RUNNINGONPI
    SDL_RendererFlip flip = SDL_RendererFlip((int)SDL_FLIP_HORIZONTAL | (int)SDL_FLIP_VERTICAL);
    #else
    SDL_RendererFlip flip = SDL_FLIP_NONE;
    #endif
    SDL_RenderCopyEx(renderer, textureMusicBar, NULL, &musicBarRect ,0, NULL, flip);
    SDL_DestroyTexture(textureMusicBar);

    return 0;
}

int main(int argc, char* argv[])
{
    #ifdef RUNNINGONPI
        WiringPiButtons buttonManager;
    #endif

    if (!init_SDL())
    {
        fprintf(stderr, "Could not initialize SDL!\n");
        return -1;
    }
    if (!init_CameraSettings())
    {
        printf("Failed to load settings!\n");
        return -1;
    }

    if (musicPlayer.initSongPlayer())
    {
        noSongs = true;
        fprintf(stderr, "No SongLibrary Folder! Not creating Music Thread!\n");
    }
    else
    {
        musicPlayer.StartInternalThread();
    }
    backupCamera.StartInternalThread();

    while (!quit)
    {
        processEvents();
        #ifdef RUNNINGONPI
        processGPIO(buttonManager.getEvents());
        #endif

        if (show_Camera())
        {
            #ifdef RUNNINGONPI
            SDL_RendererFlip flip = SDL_RendererFlip((int)SDL_FLIP_HORIZONTAL | (int)SDL_FLIP_VERTICAL);
            #else
            SDL_RendererFlip flip = SDL_FLIP_NONE;
            #endif
            if (!noSongs)
            {
                showMusicBar();
            }
            SDL_RenderPresent(renderer);
            SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
            SDL_RenderClear(renderer);
            }
    }
    backupCamera.WaitForInternalThreadToExit();
    return 0;
}
<|endoftext|>


<commit_before>#include "callback_parameter.hpp"
#include "callback_object.hpp"
#include "cpp/ylikuutio/common/any_value.hpp"

// Include standard headers
#include <string> // std::string
#include <vector> // std::vector

namespace callback_system
{
    CallbackParameter::CallbackParameter(std::string name, AnyValue any_value, bool is_reference, callback_system::CallbackObject* callback_object)
    {
        // constructor.
        this->name = name;
        this->any_value = any_value;
        this->is_reference = is_reference;
    }
}
<commit_msg>Poistettu tarpeeton `#include`-rivi.<commit_after>#include "callback_parameter.hpp"
#include "callback_object.hpp"
#include "cpp/ylikuutio/common/any_value.hpp"

// Include standard headers
#include <string> // std::string

namespace callback_system
{
    CallbackParameter::CallbackParameter(std::string name, AnyValue any_value, bool is_reference, callback_system::CallbackObject* callback_object)
    {
        // constructor.
        this->name = name;
        this->any_value = any_value;
        this->is_reference = is_reference;
    }
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

    Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
    See OTBCopyright.txt for details.

    Some parts of this code are derived from libgalib. See GALIBCopyright.txt
    for details.

    This software is distributed WITHOUT ANY WARRANTY; without even
    the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
    PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// this file defines the otbMultiScaleTest for the test driver
// and all it expects is that you have a function called RegisterTests
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include "otbTestMain.h"

void RegisterTests()
{
REGISTER_TEST(galibTests4);
}
/* ----------------------------------------------------------------------------
  ex4.C
  mbwall 28jul94
  Copyright (c) 1995-1996  Massachusetts Institute of Technology

 DESCRIPTION:
   Example program for the SteadyStateGA class and 3DBinaryStringGenome
class.  This program tries to fill the 3Dgenome with alternating 1's and
0's.  Notice that the steady state ga needs many more 'generations' than the
simple ga, but it will usually converge to the optimum with fewer evaluations
of the objective function.  So if you have a compute-intensive objective
function, steady state ga may be the way to go.
  You can control the amount of overlap in a steady-state GA by using the
pReplacement member function.
  This example also illustrates some of the statistics members of the genetic
algorithm object.
---------------------------------------------------------------------------- */
#include <stdio.h>

#include <ga/GASStateGA.h>	// include the steady-state GA header
#include <ga/GA3DBinStrGenome.h> // and the header for the genome we'll use
#include <ga/std_stream.h>

#define cout STD_COUT

float objective(GAGenome &);

int
galibTests4(int argc, char * argv[])
{
  cout << "Example 4\n\n";
  cout << "This program tries to fill a 3DBinaryStringGenome with\n";
  cout << "alternating 1s and 0s using a SteadyStateGA\n\n"; cout.flush();

// See if we've been given a seed to use (for testing purposes).  When you
// specify a random seed, the evolution will be exactly the same each time
// you use that seed number.

  const char * outputfile = argv[1];
  for(int ii=1; ii<argc; ii++) {
    if(strcmp(argv[ii],"seed") == 0) {
      GARandomSeed((unsigned int)atoi(argv[ii+1]));
    }
  }

  int depth    = 3;
  int width    = 10;
  int height   = 5;

// Now create the GA and run it.  First we create a genome of the type that
// we want to use in the GA.  The ga doesn't use this genome in the
// optimization - it just uses it to clone a population of genomes.

  GA3DBinaryStringGenome genome(width, height, depth, objective);

// Now that we have the genome, we create the genetic algorithm and set
// its parameters - number of generations, mutation probability, and crossover
// probability.  By default the GA keeps track of the best of generation scores
// and also keeps one genome as the 'best of all' - the best genome
// that it encounters from all of the generations.  Here we tell the GA to
// keep track of all scores, not just the best-of-generation.
  const char * outputfilename = argv[1];

  GASteadyStateGA ga(genome);
  ga.populationSize(100);
  ga.pReplacement(0.50);	// replace 50% of population each generation
//  ga.nReplacement(4);	          // number of individuals to replace each gen
  ga.nGenerations(200);
  ga.pMutation(0.001);
  ga.pCrossover(0.9);
  ga.scoreFilename(outputfilename);//"bog.dat");	// name of file for scores
  ga.scoreFrequency(10);	// keep the scores of every 10th generation
  ga.flushFrequency(50);	// specify how often to write the score to disk
  ga.selectScores(GAStatistics::AllScores);
  ga.evolve();

// Now we print out the best genome.

  cout << "the ga generated:\n" << ga.statistics().bestIndividual() << "\n";
  cout << "best of generation data are in '"<<ga.scoreFilename()<<"'\n";

// That's it!

  return 0;
}

// This is the objective function.  All it does is give one point for every
// odd bit that is set and one point for every even bit that is not set.

float
objective(GAGenome& g)
{
  GA3DBinaryStringGenome & genome = (GA3DBinaryStringGenome &)g;
  float value=0.0;
  int count=0;
  int I=genome.width(), J=genome.height(), K=genome.depth();
  for(int i=0; i<I; i++){
    for(int j=0; j<J; j++){
      for(int k=0; k<K; k++){
	if(genome.gene(i,j,k) == 0 && count%2 == 0)
	  value += 1.0;
	else if(genome.gene(i,j,k) == 1 && count%2 != 0)
	  value += 1.0;
	count++;
      }
    }
  }
  return value;
}
<commit_msg>Simple correction.<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

    Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
    See OTBCopyright.txt for details.

    Some parts of this code are derived from libgalib. See GALIBCopyright.txt
    for details.

    This software is distributed WITHOUT ANY WARRANTY; without even
    the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
    PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// this file defines the otbMultiScaleTest for the test driver
// and all it expects is that you have a function called RegisterTests
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include "otbTestMain.h"

void RegisterTests()
{
REGISTER_TEST(galibTests4);
}
/* ----------------------------------------------------------------------------
  ex4.C
  mbwall 28jul94
  Copyright (c) 1995-1996  Massachusetts Institute of Technology

 DESCRIPTION:
   Example program for the SteadyStateGA class and 3DBinaryStringGenome
class.  This program tries to fill the 3Dgenome with alternating 1's and
0's.  Notice that the steady state ga needs many more 'generations' than the
simple ga, but it will usually converge to the optimum with fewer evaluations
of the objective function.  So if you have a compute-intensive objective
function, steady state ga may be the way to go.
  You can control the amount of overlap in a steady-state GA by using the
pReplacement member function.
  This example also illustrates some of the statistics members of the genetic
algorithm object.
---------------------------------------------------------------------------- */
#include <stdio.h>

#include <ga/GASStateGA.h>	// include the steady-state GA header
#include <ga/GA3DBinStrGenome.h> // and the header for the genome we'll use
#include <ga/std_stream.h>

#define cout STD_COUT

float objective(GAGenome &);

int
galibTests4(int argc, char * argv[])
{
  cout << "Example 4\n\n";
  cout << "This program tries to fill a 3DBinaryStringGenome with\n";
  cout << "alternating 1s and 0s using a SteadyStateGA\n\n"; cout.flush();

// See if we've been given a seed to use (for testing purposes).  When you
// specify a random seed, the evolution will be exactly the same each time
// you use that seed number.

  for(int ii=1; ii<argc; ii++) {
    if(strcmp(argv[ii],"seed") == 0) {
      GARandomSeed((unsigned int)atoi(argv[ii+1]));
    }
  }

  int depth    = 3;
  int width    = 10;
  int height   = 5;

// Now create the GA and run it.  First we create a genome of the type that
// we want to use in the GA.  The ga doesn't use this genome in the
// optimization - it just uses it to clone a population of genomes.

  GA3DBinaryStringGenome genome(width, height, depth, objective);

// Now that we have the genome, we create the genetic algorithm and set
// its parameters - number of generations, mutation probability, and crossover
// probability.  By default the GA keeps track of the best of generation scores
// and also keeps one genome as the 'best of all' - the best genome
// that it encounters from all of the generations.  Here we tell the GA to
// keep track of all scores, not just the best-of-generation.
  const char * outputfilename = argv[1];

  GASteadyStateGA ga(genome);
  ga.populationSize(100);
  ga.pReplacement(0.50);	// replace 50% of population each generation
//  ga.nReplacement(4);	          // number of individuals to replace each gen
  ga.nGenerations(200);
  ga.pMutation(0.001);
  ga.pCrossover(0.9);
  ga.scoreFilename(outputfilename);//"bog.dat");	// name of file for scores
  ga.scoreFrequency(10);	// keep the scores of every 10th generation
  ga.flushFrequency(50);	// specify how often to write the score to disk
  ga.selectScores(GAStatistics::AllScores);
  ga.evolve();

// Now we print out the best genome.

  cout << "the ga generated:\n" << ga.statistics().bestIndividual() << "\n";
  cout << "best of generation data are in '"<<ga.scoreFilename()<<"'\n";

// That's it!

  return 0;
}

// This is the objective function.  All it does is give one point for every
// odd bit that is set and one point for every even bit that is not set.

float
objective(GAGenome& g)
{
  GA3DBinaryStringGenome & genome = (GA3DBinaryStringGenome &)g;
  float value=0.0;
  int count=0;
  int I=genome.width(), J=genome.height(), K=genome.depth();
  for(int i=0; i<I; i++){
    for(int j=0; j<J; j++){
      for(int k=0; k<K; k++){
	if(genome.gene(i,j,k) == 0 && count%2 == 0)
	  value += 1.0;
	else if(genome.gene(i,j,k) == 1 && count%2 != 0)
	  value += 1.0;
	count++;
      }
    }
  }
  return value;
}
<|endoftext|>


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

/*
 * $Log$
 * Revision 1.5  2003/05/18 14:02:06  knoaman
 * Memory manager implementation: pass per instance manager.
 *
 * Revision 1.4  2003/05/15 18:48:27  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.3  2002/11/04 14:54:58  tng
 * C++ Namespace Support.
 *
 * Revision 1.2  2002/09/24 19:48:39  tng
 * Performance: use XMLString::equals instead of XMLString::compareString
 *
 * Revision 1.1.1.1  2002/02/01 22:22:37  peiyongz
 * sane_include
 *
 * Revision 1.3  2001/11/21 14:30:13  knoaman
 * Fix for UPA checking.
 *
 * Revision 1.2  2001/08/27 12:19:00  tng
 * Schema: AllContentModel UPA Check typo fix
 *
 * Revision 1.1  2001/08/24 12:48:48  tng
 * Schema: AllContentModel
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/RuntimeException.hpp>
#include <xercesc/framework/XMLElementDecl.hpp>
#include <xercesc/framework/XMLValidator.hpp>
#include <xercesc/validators/common/ContentSpecNode.hpp>
#include <xercesc/validators/common/AllContentModel.hpp>
#include <xercesc/validators/schema/SubstitutionGroupComparator.hpp>
#include <xercesc/validators/schema/XercesElementWildcard.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  AllContentModel: Constructors and Destructor
// ---------------------------------------------------------------------------
AllContentModel::AllContentModel( ContentSpecNode* const parentContentSpec
                                , const bool             isMixed
                                , MemoryManager* const   manager) :
   fMemoryManager(manager)
 , fCount(0)
 , fChildren(0)
 , fChildOptional(0)
 , fNumRequired(0)
 , fIsMixed(isMixed)
{
    //
    //  Create a vector of unsigned ints that will be filled in with the
    //  ids of the child nodes. It will be expanded as needed but we give
    //  it an initial capacity of 64 which should be more than enough for
    //  99% of the scenarios.
    //

    ValueVectorOf<QName*> children(64, fMemoryManager);
    ValueVectorOf<bool> childOptional(64, fMemoryManager);

    //
    //  Get the parent element's content spec. This is the head of the tree
    //  of nodes that describes the content model. We will iterate this
    //  tree.
    //
    ContentSpecNode* curNode = parentContentSpec;
    if (!curNode)
        ThrowXML(RuntimeException, XMLExcepts::CM_NoParentCSN);

    // And now call the private recursive method that iterates the tree
    buildChildList(curNode, children, childOptional);

    //
    //  And now we know how many elements we need in our member list. So
    //  fill them in.
    //
    fCount = children.size();
    fChildren = (QName**) fMemoryManager->allocate(fCount * sizeof(QName*)); //new QName*[fCount];
    fChildOptional = (bool*) fMemoryManager->allocate(fCount * sizeof(bool)); //new bool[fCount];
    for (unsigned int index = 0; index < fCount; index++) {
        fChildren[index] = children.elementAt(index);
        fChildOptional[index] = childOptional.elementAt(index);
    }
}

AllContentModel::~AllContentModel()
{
    fMemoryManager->deallocate(fChildren); //delete [] fChildren;
    fMemoryManager->deallocate(fChildOptional); //delete [] fChildOptional;
}

// ---------------------------------------------------------------------------
//  AllContentModel: Implementation of the ContentModel virtual interface
// ---------------------------------------------------------------------------
//
//Under the XML Schema mixed model,
//the order and number of child elements appearing in an instance
//must agree with
//the order and number of child elements specified in the model.
//
int
AllContentModel::validateContent( QName** const         children
                                , const unsigned int    childCount
                                , const unsigned int    emptyNamespaceId) const
{
    // If <all> had minOccurs of zero and there are
    // no children to validate, trivially validate
    if (!fNumRequired && !childCount)
        return -1;

    // Check for duplicate element
    bool* elementSeen = (bool*) fMemoryManager->allocate(fCount*sizeof(bool)); //new bool[fCount];

    // initialize the array
    for (unsigned int i = 0; i < fCount; i++)
        elementSeen[i] = false;

    // keep track of the required element seen
    unsigned int numRequiredSeen = 0;

    for (unsigned int outIndex = 0; outIndex < childCount; outIndex++) {
        // Get the current child out of the source index
        const QName* curChild = children[outIndex];

        // If its PCDATA, then we just accept that
        if (fIsMixed && curChild->getURI() == XMLElementDecl::fgPCDataElemId)
            continue;

        // And try to find it in our list
        unsigned int inIndex = 0;
        for (; inIndex < fCount; inIndex++)
        {
            const QName* inChild = fChildren[inIndex];
            if ((inChild->getURI() == curChild->getURI()) &&
                (XMLString::equals(inChild->getLocalPart(), curChild->getLocalPart()))) {
                // found it
                // If this element was seen already, indicate an error was
                // found at the duplicate index.
                if (elementSeen[inIndex]) {
                    fMemoryManager->deallocate(elementSeen); //delete [] elementSeen;
                    return outIndex;
                }
                else
                    elementSeen[inIndex] = true;

                if (!fChildOptional[inIndex])
                    numRequiredSeen++;

                break;
            }
        }

        // We did not find this one, so the validation failed
        if (inIndex == fCount) {
            fMemoryManager->deallocate(elementSeen); //delete [] elementSeen;
            return outIndex;
        }

    }

    fMemoryManager->deallocate(elementSeen); //delete [] elementSeen;

    // Were all the required elements of the <all> encountered?
    if (numRequiredSeen != fNumRequired) {
        return childCount;
    }

    // Everything seems to be ok, so return success
    // success
    return -1;
}

int AllContentModel::validateContentSpecial(QName** const           children
                                          , const unsigned int      childCount
                                          , const unsigned int      emptyNamespaceId
                                          , GrammarResolver*  const pGrammarResolver
                                          , XMLStringPool*    const pStringPool) const
{

    SubstitutionGroupComparator comparator(pGrammarResolver, pStringPool);

    // If <all> had minOccurs of zero and there are
    // no children to validate, trivially validate
    if (!fNumRequired && !childCount)
        return -1;

    // Check for duplicate element
    bool* elementSeen = (bool*) fMemoryManager->allocate(fCount*sizeof(bool)); //new bool[fCount];

    // initialize the array
    for (unsigned int i = 0; i < fCount; i++)
        elementSeen[i] = false;

    // keep track of the required element seen
    unsigned int numRequiredSeen = 0;

    for (unsigned int outIndex = 0; outIndex < childCount; outIndex++) {
        // Get the current child out of the source index
        QName* const curChild = children[outIndex];

        // If its PCDATA, then we just accept that
        if (fIsMixed && curChild->getURI() == XMLElementDecl::fgPCDataElemId)
            continue;

        // And try to find it in our list
        unsigned int inIndex = 0;
        for (; inIndex < fCount; inIndex++)
        {
            QName* const inChild = fChildren[inIndex];
            if ( comparator.isEquivalentTo(curChild, inChild)) {
                // match
                // If this element was seen already, indicate an error was
                // found at the duplicate index.
                if (elementSeen[inIndex]) {
                    fMemoryManager->deallocate(elementSeen); //delete [] elementSeen;
                    return outIndex;
                }
                else
                    elementSeen[inIndex] = true;

                if (!fChildOptional[inIndex])
                    numRequiredSeen++;

                break;
            }
        }

        // We did not find this one, so the validation failed
        if (inIndex == fCount) {
            fMemoryManager->deallocate(elementSeen); //delete [] elementSeen;
            return outIndex;
        }

    }

    fMemoryManager->deallocate(elementSeen); //delete [] elementSeen;

    // Were all the required elements of the <all> encountered?
    if (numRequiredSeen != fNumRequired) {
        return childCount;
    }

    // Everything seems to be ok, so return success
    // success
    return -1;

}

void AllContentModel::checkUniqueParticleAttribution
    (
        SchemaGrammar*    const pGrammar
      , GrammarResolver*  const pGrammarResolver
      , XMLStringPool*    const pStringPool
      , XMLValidator*     const pValidator
      , unsigned int*     const pContentSpecOrgURI
    )
{
    SubstitutionGroupComparator comparator(pGrammarResolver, pStringPool);

    unsigned int i, j;

    // rename back
    for (i = 0; i < fCount; i++) {
        unsigned int orgURIIndex = fChildren[i]->getURI();
        fChildren[i]->setURI(pContentSpecOrgURI[orgURIIndex]);
    }

    // check whether there is conflict between any two leaves
    for (i = 0; i < fCount; i++) {
        for (j = i+1; j < fCount; j++) {
            // If this is text in a Schema mixed content model, skip it.
            if ( fIsMixed &&
                 (( fChildren[i]->getURI() == XMLElementDecl::fgPCDataElemId) ||
                  ( fChildren[j]->getURI() == XMLElementDecl::fgPCDataElemId)))
                continue;

            if (XercesElementWildcard::conflict(pGrammar,
                                                ContentSpecNode::Leaf,
                                                fChildren[i],
                                                ContentSpecNode::Leaf,
                                                fChildren[j],
                                                &comparator)) {
                pValidator->emitError(XMLValid::UniqueParticleAttributionFail,
                                      fChildren[i]->getRawName(),
                                      fChildren[j]->getRawName());
             }
         }
    }
}

// ---------------------------------------------------------------------------
//  AllContentModel: Private helper methods
// ---------------------------------------------------------------------------
void
AllContentModel::buildChildList(ContentSpecNode* const       curNode
                              , ValueVectorOf<QName*>&       toFill
                              , ValueVectorOf<bool>&         toOptional)
{
    // Get the type of spec node our current node is
    const ContentSpecNode::NodeTypes curType = curNode->getType();

    if (curType == ContentSpecNode::All)
    {
        // Get both the child node pointers
        ContentSpecNode* leftNode = curNode->getFirst();
        ContentSpecNode* rightNode = curNode->getSecond();

        // Recurse on the left and right nodes
        buildChildList(leftNode, toFill, toOptional);
        buildChildList(rightNode, toFill, toOptional);
    }
    else if (curType == ContentSpecNode::Leaf)
    {
        // At leaf, add the element to list of elements permitted in the all
        toFill.addElement(curNode->getElement());
        toOptional.addElement(false);
        fNumRequired++;
    }
    else if (curType == ContentSpecNode::ZeroOrOne)
    {
        // At ZERO_OR_ONE node, subtree must be an element
        // that was specified with minOccurs=0, maxOccurs=1
        ContentSpecNode* leftNode = curNode->getFirst();
        if (leftNode->getType() != ContentSpecNode::Leaf)
            ThrowXML(RuntimeException, XMLExcepts::CM_UnknownCMSpecType);

        toFill.addElement(leftNode->getElement());
        toOptional.addElement(true);
    }
    else
        ThrowXML(RuntimeException, XMLExcepts::CM_UnknownCMSpecType);
}

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

/*
 * $Log$
 * Revision 1.6  2003/11/20 18:09:18  knoaman
 * Store a copy of each child, instead of a reference, as the content spec node
 * tree is not guaranteed to be persistent.
 *
 * Revision 1.5  2003/05/18 14:02:06  knoaman
 * Memory manager implementation: pass per instance manager.
 *
 * Revision 1.4  2003/05/15 18:48:27  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.3  2002/11/04 14:54:58  tng
 * C++ Namespace Support.
 *
 * Revision 1.2  2002/09/24 19:48:39  tng
 * Performance: use XMLString::equals instead of XMLString::compareString
 *
 * Revision 1.1.1.1  2002/02/01 22:22:37  peiyongz
 * sane_include
 *
 * Revision 1.3  2001/11/21 14:30:13  knoaman
 * Fix for UPA checking.
 *
 * Revision 1.2  2001/08/27 12:19:00  tng
 * Schema: AllContentModel UPA Check typo fix
 *
 * Revision 1.1  2001/08/24 12:48:48  tng
 * Schema: AllContentModel
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/RuntimeException.hpp>
#include <xercesc/framework/XMLElementDecl.hpp>
#include <xercesc/framework/XMLValidator.hpp>
#include <xercesc/validators/common/ContentSpecNode.hpp>
#include <xercesc/validators/common/AllContentModel.hpp>
#include <xercesc/validators/schema/SubstitutionGroupComparator.hpp>
#include <xercesc/validators/schema/XercesElementWildcard.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  AllContentModel: Constructors and Destructor
// ---------------------------------------------------------------------------
AllContentModel::AllContentModel( ContentSpecNode* const parentContentSpec
                                , const bool             isMixed
                                , MemoryManager* const   manager) :
   fMemoryManager(manager)
 , fCount(0)
 , fChildren(0)
 , fChildOptional(0)
 , fNumRequired(0)
 , fIsMixed(isMixed)
{
    //
    //  Create a vector of unsigned ints that will be filled in with the
    //  ids of the child nodes. It will be expanded as needed but we give
    //  it an initial capacity of 64 which should be more than enough for
    //  99% of the scenarios.
    //

    ValueVectorOf<QName*> children(64, fMemoryManager);
    ValueVectorOf<bool> childOptional(64, fMemoryManager);

    //
    //  Get the parent element's content spec. This is the head of the tree
    //  of nodes that describes the content model. We will iterate this
    //  tree.
    //
    ContentSpecNode* curNode = parentContentSpec;
    if (!curNode)
        ThrowXML(RuntimeException, XMLExcepts::CM_NoParentCSN);

    // And now call the private recursive method that iterates the tree
    buildChildList(curNode, children, childOptional);

    //
    //  And now we know how many elements we need in our member list. So
    //  fill them in.
    //
    fCount = children.size();
    fChildren = (QName**) fMemoryManager->allocate(fCount * sizeof(QName*)); //new QName*[fCount];
    fChildOptional = (bool*) fMemoryManager->allocate(fCount * sizeof(bool)); //new bool[fCount];
    for (unsigned int index = 0; index < fCount; index++) {
        fChildren[index] = new (fMemoryManager) QName(*(children.elementAt(index)));
        fChildOptional[index] = childOptional.elementAt(index);
    }
}

AllContentModel::~AllContentModel()
{
    for (unsigned int index = 0; index < fCount; index++)
        delete fChildren[index];
    fMemoryManager->deallocate(fChildren); //delete [] fChildren;
    fMemoryManager->deallocate(fChildOptional); //delete [] fChildOptional;
}

// ---------------------------------------------------------------------------
//  AllContentModel: Implementation of the ContentModel virtual interface
// ---------------------------------------------------------------------------
//
//Under the XML Schema mixed model,
//the order and number of child elements appearing in an instance
//must agree with
//the order and number of child elements specified in the model.
//
int
AllContentModel::validateContent( QName** const         children
                                , const unsigned int    childCount
                                , const unsigned int    emptyNamespaceId) const
{
    // If <all> had minOccurs of zero and there are
    // no children to validate, trivially validate
    if (!fNumRequired && !childCount)
        return -1;

    // Check for duplicate element
    bool* elementSeen = (bool*) fMemoryManager->allocate(fCount*sizeof(bool)); //new bool[fCount];

    // initialize the array
    for (unsigned int i = 0; i < fCount; i++)
        elementSeen[i] = false;

    // keep track of the required element seen
    unsigned int numRequiredSeen = 0;

    for (unsigned int outIndex = 0; outIndex < childCount; outIndex++) {
        // Get the current child out of the source index
        const QName* curChild = children[outIndex];

        // If its PCDATA, then we just accept that
        if (fIsMixed && curChild->getURI() == XMLElementDecl::fgPCDataElemId)
            continue;

        // And try to find it in our list
        unsigned int inIndex = 0;
        for (; inIndex < fCount; inIndex++)
        {
            const QName* inChild = fChildren[inIndex];
            if ((inChild->getURI() == curChild->getURI()) &&
                (XMLString::equals(inChild->getLocalPart(), curChild->getLocalPart()))) {
                // found it
                // If this element was seen already, indicate an error was
                // found at the duplicate index.
                if (elementSeen[inIndex]) {
                    fMemoryManager->deallocate(elementSeen); //delete [] elementSeen;
                    return outIndex;
                }
                else
                    elementSeen[inIndex] = true;

                if (!fChildOptional[inIndex])
                    numRequiredSeen++;

                break;
            }
        }

        // We did not find this one, so the validation failed
        if (inIndex == fCount) {
            fMemoryManager->deallocate(elementSeen); //delete [] elementSeen;
            return outIndex;
        }

    }

    fMemoryManager->deallocate(elementSeen); //delete [] elementSeen;

    // Were all the required elements of the <all> encountered?
    if (numRequiredSeen != fNumRequired) {
        return childCount;
    }

    // Everything seems to be ok, so return success
    // success
    return -1;
}

int AllContentModel::validateContentSpecial(QName** const           children
                                          , const unsigned int      childCount
                                          , const unsigned int      emptyNamespaceId
                                          , GrammarResolver*  const pGrammarResolver
                                          , XMLStringPool*    const pStringPool) const
{

    SubstitutionGroupComparator comparator(pGrammarResolver, pStringPool);

    // If <all> had minOccurs of zero and there are
    // no children to validate, trivially validate
    if (!fNumRequired && !childCount)
        return -1;

    // Check for duplicate element
    bool* elementSeen = (bool*) fMemoryManager->allocate(fCount*sizeof(bool)); //new bool[fCount];

    // initialize the array
    for (unsigned int i = 0; i < fCount; i++)
        elementSeen[i] = false;

    // keep track of the required element seen
    unsigned int numRequiredSeen = 0;

    for (unsigned int outIndex = 0; outIndex < childCount; outIndex++) {
        // Get the current child out of the source index
        QName* const curChild = children[outIndex];

        // If its PCDATA, then we just accept that
        if (fIsMixed && curChild->getURI() == XMLElementDecl::fgPCDataElemId)
            continue;

        // And try to find it in our list
        unsigned int inIndex = 0;
        for (; inIndex < fCount; inIndex++)
        {
            QName* const inChild = fChildren[inIndex];
            if ( comparator.isEquivalentTo(curChild, inChild)) {
                // match
                // If this element was seen already, indicate an error was
                // found at the duplicate index.
                if (elementSeen[inIndex]) {
                    fMemoryManager->deallocate(elementSeen); //delete [] elementSeen;
                    return outIndex;
                }
                else
                    elementSeen[inIndex] = true;

                if (!fChildOptional[inIndex])
                    numRequiredSeen++;

                break;
            }
        }

        // We did not find this one, so the validation failed
        if (inIndex == fCount) {
            fMemoryManager->deallocate(elementSeen); //delete [] elementSeen;
            return outIndex;
        }

    }

    fMemoryManager->deallocate(elementSeen); //delete [] elementSeen;

    // Were all the required elements of the <all> encountered?
    if (numRequiredSeen != fNumRequired) {
        return childCount;
    }

    // Everything seems to be ok, so return success
    // success
    return -1;

}

void AllContentModel::checkUniqueParticleAttribution
    (
        SchemaGrammar*    const pGrammar
      , GrammarResolver*  const pGrammarResolver
      , XMLStringPool*    const pStringPool
      , XMLValidator*     const pValidator
      , unsigned int*     const pContentSpecOrgURI
    )
{
    SubstitutionGroupComparator comparator(pGrammarResolver, pStringPool);

    unsigned int i, j;

    // rename back
    for (i = 0; i < fCount; i++) {
        unsigned int orgURIIndex = fChildren[i]->getURI();
        fChildren[i]->setURI(pContentSpecOrgURI[orgURIIndex]);
    }

    // check whether there is conflict between any two leaves
    for (i = 0; i < fCount; i++) {
        for (j = i+1; j < fCount; j++) {
            // If this is text in a Schema mixed content model, skip it.
            if ( fIsMixed &&
                 (( fChildren[i]->getURI() == XMLElementDecl::fgPCDataElemId) ||
                  ( fChildren[j]->getURI() == XMLElementDecl::fgPCDataElemId)))
                continue;

            if (XercesElementWildcard::conflict(pGrammar,
                                                ContentSpecNode::Leaf,
                                                fChildren[i],
                                                ContentSpecNode::Leaf,
                                                fChildren[j],
                                                &comparator)) {
                pValidator->emitError(XMLValid::UniqueParticleAttributionFail,
                                      fChildren[i]->getRawName(),
                                      fChildren[j]->getRawName());
             }
         }
    }
}

// ---------------------------------------------------------------------------
//  AllContentModel: Private helper methods
// ---------------------------------------------------------------------------
void
AllContentModel::buildChildList(ContentSpecNode* const       curNode
                              , ValueVectorOf<QName*>&       toFill
                              , ValueVectorOf<bool>&         toOptional)
{
    // Get the type of spec node our current node is
    const ContentSpecNode::NodeTypes curType = curNode->getType();

    if (curType == ContentSpecNode::All)
    {
        // Get both the child node pointers
        ContentSpecNode* leftNode = curNode->getFirst();
        ContentSpecNode* rightNode = curNode->getSecond();

        // Recurse on the left and right nodes
        buildChildList(leftNode, toFill, toOptional);
        buildChildList(rightNode, toFill, toOptional);
    }
    else if (curType == ContentSpecNode::Leaf)
    {
        // At leaf, add the element to list of elements permitted in the all
        toFill.addElement(curNode->getElement());
        toOptional.addElement(false);
        fNumRequired++;
    }
    else if (curType == ContentSpecNode::ZeroOrOne)
    {
        // At ZERO_OR_ONE node, subtree must be an element
        // that was specified with minOccurs=0, maxOccurs=1
        ContentSpecNode* leftNode = curNode->getFirst();
        if (leftNode->getType() != ContentSpecNode::Leaf)
            ThrowXML(RuntimeException, XMLExcepts::CM_UnknownCMSpecType);

        toFill.addElement(leftNode->getElement());
        toOptional.addElement(true);
    }
    else
        ThrowXML(RuntimeException, XMLExcepts::CM_UnknownCMSpecType);
}

XERCES_CPP_NAMESPACE_END
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_SCAL_META_PARTIALS_RETURN_TYPE_HPP
#define STAN_MATH_PRIM_SCAL_META_PARTIALS_RETURN_TYPE_HPP

#include <stan/math/prim/scal/meta/partials_type.hpp>
#include <stan/math/rev/core/var.hpp>
#include <stan/math/rev/scal/meta/partials_type.hpp>
#include <stan/math/fwd/core/fvar.hpp>
#include <stan/math/fwd/scal/meta/partials_type.hpp>
#include <stan/math/prim/scal/meta/scalar_type.hpp>
#include <boost/math/tools/promotion.hpp>

namespace stan {

  /**
   * Template metaprogram to calculate the base scalar return type resulting
   * from promoting all the scalar types of the template parameters. The
   * metaprogram can take an arbitrary number of template parameters.
   *
   * All C++ primitive types (except long double) are automatically
   * promoted to double.
   *
   * partials_return_type<...> is a class defining a single public
   * typedef type that is var if there is a forward
   * mode variable type and is double otherwise (this is the most
   * common case).
   * Example usage:
   *
   *  - return_type<int,double,var>::type is double
   *  - The same thing with var replaced with a forward mode type
   *  like fvar<T> will return T.
   *
   * @tparam T (required) A type
   * @tparam T_pack (optional) A parameter pack containing further types.
   */

template <typename T, typename... T_pack>
struct partials_return_type {
  typedef typename boost::math::tools::promote_args<
      double, typename partials_type<typename scalar_type<T>::type>::type,
      typename partials_return_type<T_pack...>::type>::type type;
};

template <typename T>
struct partials_return_type<T> {
  typedef typename boost::math::tools::promote_args<
      double, typename partials_type<typename scalar_type<T>::type>::type>::type
      type;
};

}  // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags/google/stable/2017-11-14)<commit_after>#ifndef STAN_MATH_PRIM_SCAL_META_PARTIALS_RETURN_TYPE_HPP
#define STAN_MATH_PRIM_SCAL_META_PARTIALS_RETURN_TYPE_HPP

#include <stan/math/prim/scal/meta/partials_type.hpp>
#include <stan/math/rev/core/var.hpp>
#include <stan/math/rev/scal/meta/partials_type.hpp>
#include <stan/math/fwd/core/fvar.hpp>
#include <stan/math/fwd/scal/meta/partials_type.hpp>
#include <stan/math/prim/scal/meta/scalar_type.hpp>
#include <boost/math/tools/promotion.hpp>

namespace stan {

/**
 * Template metaprogram to calculate the base scalar return type resulting
 * from promoting all the scalar types of the template parameters. The
 * metaprogram can take an arbitrary number of template parameters.
 *
 * All C++ primitive types (except long double) are automatically
 * promoted to double.
 *
 * partials_return_type<...> is a class defining a single public
 * typedef type that is var if there is a forward
 * mode variable type and is double otherwise (this is the most
 * common case).
 * Example usage:
 *
 *  - return_type<int,double,var>::type is double
 *  - The same thing with var replaced with a forward mode type
 *  like fvar<T> will return T.
 *
 * @tparam T (required) A type
 * @tparam T_pack (optional) A parameter pack containing further types.
 */

template <typename T, typename... T_pack>
struct partials_return_type {
  typedef typename boost::math::tools::promote_args<
      double, typename partials_type<typename scalar_type<T>::type>::type,
      typename partials_return_type<T_pack...>::type>::type type;
};

template <typename T>
struct partials_return_type<T> {
  typedef typename boost::math::tools::promote_args<
      double, typename partials_type<typename scalar_type<T>::type>::type>::type
      type;
};

}  // namespace stan
#endif
<|endoftext|>


<commit_before>// Standard headers
#include <cmath>
#include <thread>
#include <iostream>
#include <algorithm>

// Local headers
#include "Math.hpp"
#include "Barrier.hpp"

const double PI = 3.141592653589793238462643;

mpz factorial(const mpz& n) {
  return (n == 1 || n == 0) ? mpz(1) : factorial(n - 1) * n;
}

mpf Cosine::calculatePrecision(int exponent) {
  mpf epsilon;
  mpf_pow_ui(epsilon.get_mpf_t(), mpf(0.1).get_mpf_t(), exponent);
  return epsilon;
}

mpf Cosine::fixRadians_impl(const mpf& radians) {
  if (radians > 2*PI)
    return fixRadians_impl(radians - 2*PI);
  return radians;
}

mpf Cosine::fixRadians(const mpf& radians) {
  return fixRadians_impl(abs(radians));
}

mpf Cosine::calculateTerm(const mpf& radians, unsigned int n) {
  mpf aux = 0; int signal = n % 2 == 0 ? 1 : -1;
  mpf_pow_ui(aux.get_mpf_t(), radians.get_mpf_t(), 2*n);
  return signal * (aux / factorial(2*n));
}

mpf Cosine::singleThreadedCosine() {
  mpf cos = 0, aux = 0;

  mpf fixed_radians { fixRadians(radians) };

  for (unsigned int n = 0; true; n++) {
    aux = std::move(calculateTerm(radians, n));
    cos += aux;
    if (abs(aux) < precision) break;
  }

  return cos;
}

///////////////////////////////////////////////////////////////////////////////

Cosine::Cosine(const mpf& radians,
               int exponent,
               char stop_criteria,
               unsigned int num_threads)
    : radians(radians),
      stop_criteria(stop_criteria),
      num_threads(num_threads),
      terms(num_threads, 0),
      barrier(num_threads) {
  precision = calculatePrecision(exponent);
}

void Cosine::worker(unsigned int offset) {
  terms[offset] = std::move(calculateTerm(radians, iteration * terms.size() + offset));
}

bool Cosine::coordinator() {
  mpf aux = 0;
  for (auto &term : terms) aux += term;

  cos += aux;

  if (stop_criteria == 'f') {
    if (abs(aux) < precision) return true;
  } else if (stop_criteria == 'm') {
    if (std::any_of(terms.begin(), terms.end(),
                    [this] (const mpf& t) { return abs(t) < precision; }))
      return true;
  }
  return false;
}

void Cosine::asyncCalculateTerm(unsigned int offset,
                                bool is_coordinator) {
  while (!stop) {
    worker(offset);
    barrier.wait();

    if (is_coordinator) {
      stop = coordinator();
      iteration++;
    }
    barrier.wait();
  }
}

mpf Cosine::multiThreadedCosine() {

  mpf fixed_radians { fixRadians(radians) };

  std::vector<std::thread> threads;

  for (unsigned int offset = 0; offset < num_threads-1; offset++) {
    threads.emplace_back(&Cosine::asyncCalculateTerm, this, offset, false);
  }

  asyncCalculateTerm(num_threads-1, true);

  for (auto &thread : threads) thread.join();

  return cos;
}
<commit_msg>Extract correction of 'radians'<commit_after>// Standard headers
#include <cmath>
#include <thread>
#include <iostream>
#include <algorithm>

// Local headers
#include "Math.hpp"
#include "Barrier.hpp"

const double PI = 3.141592653589793238462643;

mpz factorial(const mpz& n) {
  return (n == 1 || n == 0) ? mpz(1) : factorial(n - 1) * n;
}

mpf Cosine::calculatePrecision(int exponent) {
  mpf epsilon;
  mpf_pow_ui(epsilon.get_mpf_t(), mpf(0.1).get_mpf_t(), exponent);
  return epsilon;
}

mpf Cosine::fixRadians_impl(const mpf& radians) {
  if (radians > 2*PI)
    return fixRadians_impl(radians - 2*PI);
  return radians;
}

mpf Cosine::fixRadians(const mpf& radians) {
  return fixRadians_impl(abs(radians));
}

mpf Cosine::calculateTerm(const mpf& radians, unsigned int n) {
  mpf aux = 0; int signal = n % 2 == 0 ? 1 : -1;
  mpf_pow_ui(aux.get_mpf_t(), radians.get_mpf_t(), 2*n);
  return signal * (aux / factorial(2*n));
}

mpf Cosine::singleThreadedCosine() {
  mpf cos = 0, aux = 0;

  for (unsigned int n = 0; true; n++) {
    aux = std::move(calculateTerm(radians, n));
    cos += aux;
    if (abs(aux) < precision) break;
  }

  return cos;
}

///////////////////////////////////////////////////////////////////////////////

Cosine::Cosine(const mpf& radians,
               int exponent,
               char stop_criteria,
               unsigned int num_threads)
    : radians(fixRadians(radians)),
      precision(calculatePrecision(exponent)),
      stop_criteria(stop_criteria),
      num_threads(num_threads),
      terms(num_threads, 0),
      barrier(num_threads) {
}

void Cosine::worker(unsigned int offset) {
  terms[offset] = std::move(calculateTerm(radians, iteration * terms.size() + offset));
}

bool Cosine::coordinator() {
  mpf aux = 0;
  for (auto &term : terms) aux += term;

  cos += aux;

  if (stop_criteria == 'f') {
    if (abs(aux) < precision) return true;
  } else if (stop_criteria == 'm') {
    if (std::any_of(terms.begin(), terms.end(),
                    [this] (const mpf& t) { return abs(t) < precision; }))
      return true;
  }
  return false;
}

void Cosine::asyncCalculateTerm(unsigned int offset,
                                bool is_coordinator) {
  while (!stop) {
    worker(offset);
    barrier.wait();

    if (is_coordinator) {
      stop = coordinator();
      iteration++;
    }
    barrier.wait();
  }
}

mpf Cosine::multiThreadedCosine() {

  std::vector<std::thread> threads;

  for (unsigned int offset = 0; offset < num_threads-1; offset++) {
    threads.emplace_back(&Cosine::asyncCalculateTerm, this, offset, false);
  }

  asyncCalculateTerm(num_threads-1, true);

  for (auto &thread : threads) thread.join();

  return cos;
}
<|endoftext|>


<commit_before>#include <ucontext.h>

namespace factor
{

inline static void *ucontext_stack_pointer(void *uap)
{
	ucontext_t *ucontext = (ucontext_t *)uap;
	return (void *)ucontext->uc_mcontext.gregs[7];
}

inline static unsigned int uap_fpu_status(void *uap)
{
	// XXX mxcsr not available in i386 ucontext
	ucontext_t *ucontext = (ucontext_t *)uap;
	return ucontext->uc_mcontext.fpregs->sw;
}

inline static void uap_clear_fpu_status(void *uap)
{
	ucontext_t *ucontext = (ucontext_t *)uap;
	ucontext->uc_mcontext.fpregs->sw = 0;
}

#define UAP_PROGRAM_COUNTER(ucontext) \
	(((ucontext_t *)(ucontext))->uc_mcontext.gregs[14])

}
<commit_msg>more secret sauce to tease mxcsr out of linux-x86.32 ucontext<commit_after>#include <ucontext.h>

namespace factor
{

// glibc lies about the contents of the fpstate the kernel provides, hiding the FXSR
// environment
struct _fpstate {
	/* Regular FPU environment */
	unsigned long   cw;
	unsigned long   sw;
	unsigned long   tag;
	unsigned long   ipoff;
	unsigned long   cssel;
	unsigned long   dataoff;
	unsigned long   datasel;
	struct _fpreg   _st[8];
	unsigned short  status;
	unsigned short  magic;          /* 0xffff = regular FPU data only */

	/* FXSR FPU environment */
	unsigned long   _fxsr_env[6];   /* FXSR FPU env is ignored */
	unsigned long   mxcsr;
	unsigned long   reserved;
	struct _fpxreg  _fxsr_st[8];    /* FXSR FPU reg data is ignored */
	struct _xmmreg  _xmm[8];
	unsigned long   padding[56];
};

#define X86_FXSR_MAGIC          0x0000

inline static void *ucontext_stack_pointer(void *uap)
{
	ucontext_t *ucontext = (ucontext_t *)uap;
	return (void *)ucontext->uc_mcontext.gregs[7];
}

inline static unsigned int uap_fpu_status(void *uap)
{
	ucontext_t *ucontext = (ucontext_t *)uap;
	struct _fpstate *fpregs = (struct _fpstate *)uap->uc_mcontext.fpregs;
	if (fpregs->magic == X86_FXSR_MAGIC)
	    return fpregs->sw | fpregs->mxcsr;
	else
	    return fpregs->sw;
}

inline static void uap_clear_fpu_status(void *uap)
{
	ucontext_t *ucontext = (ucontext_t *)uap;
	struct _fpstate *fpregs = (struct _fpstate *)uap->uc_mcontext.fpregs;
	fpregs->sw = 0;
	if (fpregs->magic == X86_FXSR_MAGIC)
	    fpregs->mxcsr &= 0xffffffc0;
}

#define UAP_PROGRAM_COUNTER(ucontext) \
	(((ucontext_t *)(ucontext))->uc_mcontext.gregs[14])

}
<|endoftext|>