<commit_before>// RUN: %clang_cc1 -DNO_DTORS -fno-c++-static-destructors -verify %s
// RUN: %clang_cc1 -verify %s

struct SecretDestructor {
#ifndef NO_DTORS
  // expected-note@+2 4 {{private}}
#endif
private: ~SecretDestructor(); // expected-note 2 {{private}}
};

SecretDestructor sd1;
thread_local SecretDestructor sd2;
void locals() {
  static SecretDestructor sd3;
  thread_local SecretDestructor sd4;
}

#ifndef NO_DTORS
// SecretDestructor sd1;                  // expected-error@-8 {{private}}
// thread_local SecretDestructor sd2;     // expected-error@-8 {{private}}
// void locals() {
//   static SecretDestructor sd3;         // expected-error@-8 {{private}}
//   thread_local SecretDestructor sd4;   // expected-error@-8 {{private}}
// }
#endif

[[clang::always_destroy]] SecretDestructor sd6; // expected-error{{private}}
[[clang::always_destroy]] thread_local SecretDestructor sd7; // expected-error{{private}}

[[clang::no_destroy]] SecretDestructor sd8;

int main() {
  [[clang::no_destroy]] int p; // expected-error{{no_destroy attribute can only be applied to a variable with static or thread storage duration}}
  [[clang::always_destroy]] int p2; // expected-error{{always_destroy attribute can only be applied to a variable with static or thread storage duration}}
  [[clang::no_destroy]] static int p3;
  [[clang::always_destroy]] static int p4;
}

[[clang::always_destroy]] [[clang::no_destroy]] int p; // expected-error{{'no_destroy' and 'always_destroy' attributes are not compatible}} // expected-note{{here}}
[[clang::no_destroy]] [[clang::always_destroy]] int p2; // expected-error{{'always_destroy' and 'no_destroy' attributes are not compatible}} // expected-note{{here}}
<commit_msg>[Sema] Fix bad merge of test/SemaCXX/no_destroy.cpp in commit 2b6d354.<commit_after>// RUN: %clang_cc1 -std=c++14 -DNO_DTORS -fno-c++-static-destructors -verify %s
// RUN: %clang_cc1 -std=c++14 -verify %s

struct SecretDestructor {
#ifndef NO_DTORS
  // expected-note@+2 4 {{private}}
#endif
private: ~SecretDestructor(); // expected-note 2 {{private}}
};

SecretDestructor sd1;
thread_local SecretDestructor sd2;
void locals() {
  static SecretDestructor sd3;
  thread_local SecretDestructor sd4;
}

#ifndef NO_DTORS
// SecretDestructor sd1;                  // expected-error@-8 {{private}}
// thread_local SecretDestructor sd2;     // expected-error@-8 {{private}}
// void locals() {
//   static SecretDestructor sd3;         // expected-error@-8 {{private}}
//   thread_local SecretDestructor sd4;   // expected-error@-8 {{private}}
// }
#endif

[[clang::always_destroy]] SecretDestructor sd6; // expected-error{{private}}
[[clang::always_destroy]] thread_local SecretDestructor sd7; // expected-error{{private}}

[[clang::no_destroy]] SecretDestructor sd8;

int main() {
  [[clang::no_destroy]] int p; // expected-error{{no_destroy attribute can only be applied to a variable with static or thread storage duration}}
  [[clang::always_destroy]] int p2; // expected-error{{always_destroy attribute can only be applied to a variable with static or thread storage duration}}
  [[clang::no_destroy]] static int p3;
  [[clang::always_destroy]] static int p4;
}

[[clang::always_destroy]] [[clang::no_destroy]] int p; // expected-error{{'always_destroy' and 'no_destroy' attributes are not compatible}} // expected-note{{here}}
[[clang::no_destroy]] [[clang::always_destroy]] int p2; // expected-error{{'no_destroy' and 'always_destroy' attributes are not compatible}} // expected-note{{here}}
<|endoftext|>


<commit_before>// GLAD will not include windows.h for APIENTRY if it was previously defined
#ifdef _WIN32
#define APIENTRY __stdcall
#endif

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

// confirm that neither GLAD nor GLFW didn't include windows.h
#ifdef _WINDOWS_
#error windows.h was included!
#endif

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

#include <cstdlib>
#include <string>
#include <cassert>
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>

const int WIDTH = 1280;
const int HEIGHT = 720;

float redOffset = 0.5f;
float greenOffset = 0.6f;
float blueOffset = 0.92f;

bool keys[512];
bool processedKeys[512];

const float SIZE = 50.f;

glm::vec2 topLeftPosition = glm::vec2(WIDTH / 2 - SIZE, HEIGHT / 2 - SIZE);

std::string readTextFile(const std::string& path);
void processInput();

int main(int argc, char* argv[])
{
    if (!glfwInit()) {
        std::cout << "Failed to initialize GLFW" << std::endl;
        return EXIT_FAILURE;
    }

//    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
//    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
//    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//    glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);

    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Fuzzy", nullptr, nullptr);
    if (!window) {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return EXIT_FAILURE;
    }

    GLFWmonitor* monitor = glfwGetPrimaryMonitor();
    const GLFWvidmode* vidmode = glfwGetVideoMode(monitor);

    glfwSetWindowPos(window, (vidmode->width - WIDTH) / 2, (vidmode->height - HEIGHT) / 2);

    glfwSetKeyCallback(window, [](GLFWwindow* window, int key, int scancode, int action, int mods) {
        if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
            glfwSetWindowShouldClose(window, GLFW_TRUE);
        }
        if (action == GLFW_PRESS) {
            keys[key] = true;
        } else if (action == GLFW_RELEASE) {
            keys[key] = false;
            processedKeys[key] = false;
        }
    });

    glfwSetFramebufferSizeCallback(window, [](GLFWwindow* window, int width, int height) {
        glViewport(0, 0, width, height);
    });

    glfwMakeContextCurrent(window);

    glfwSwapInterval(1);

    if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) {
        std::cout << "Failed to initialize OpenGL context" << std::endl;
        return EXIT_FAILURE;
    }

    std::cout << glGetString(GL_VERSION) << std::endl;

    glViewport(0, 0, WIDTH, HEIGHT);

    float vertices[] = {
        0.f, 0.f,
        0.f, 1.0f,
        1.0f, 0.f,
        1.0f, 1.0f
    };

    GLuint VBO;
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // vertex shader
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    std::string vertexShaderSource = readTextFile("shaders/basic.vert");
    const GLchar* vertexShaderSourcePtr = vertexShaderSource.c_str();
    glShaderSource(vertexShader, 1, &vertexShaderSourcePtr, nullptr);
    glCompileShader(vertexShader);

    GLint isVertexShaderCompiled;
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &isVertexShaderCompiled);
    if (!isVertexShaderCompiled) {
        GLint LOG_LENGTH;
        glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &LOG_LENGTH);

        std::vector<GLchar> errorLog(LOG_LENGTH);

        glGetShaderInfoLog(vertexShader, LOG_LENGTH, nullptr, &errorLog[0]);
        std::cerr << "Vertex shader compilation failed:" << std::endl << &errorLog[0] << std::endl;
    }
    assert(isVertexShaderCompiled);

    // fragment shader
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    std::string fragmentShaderSource = readTextFile("shaders/basic.frag");
    const GLchar* fragmentShaderSourcePtr = fragmentShaderSource.c_str();
    glShaderSource(fragmentShader, 1, &fragmentShaderSourcePtr, nullptr);
    glCompileShader(fragmentShader);

    GLint isFragmentShaderCompiled;
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &isFragmentShaderCompiled);
    if (!isFragmentShaderCompiled) {
        GLint LOG_LENGTH;
        glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &LOG_LENGTH);

        std::vector<GLchar> errorLog(LOG_LENGTH);

        glGetShaderInfoLog(fragmentShader, LOG_LENGTH, nullptr, &errorLog[0]);
        std::cerr << "Fragment shader compilation failed:" << std::endl << &errorLog[0] << std::endl;
    }
    assert(isFragmentShaderCompiled);

    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    GLint isShaderProgramLinked;
    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &isShaderProgramLinked);

    if (!isShaderProgramLinked) {
        GLint LOG_LENGTH;
        glGetProgramiv(shaderProgram, GL_INFO_LOG_LENGTH, &LOG_LENGTH);

        std::vector<GLchar> errorLog(LOG_LENGTH);

        glGetProgramInfoLog(shaderProgram, LOG_LENGTH, nullptr, &errorLog[0]);
        std::cerr << "Shader program linkage failed:" << std::endl << &errorLog[0] << std::endl;
    }
    assert(isShaderProgramLinked);

    glUseProgram(shaderProgram);

    glm::mat4 projection = glm::ortho(0.0f, (float) WIDTH, (float) HEIGHT, 0.0f);

    GLint projectionUniformLocation = glGetUniformLocation(shaderProgram, "projection");
    assert(projectionUniformLocation != -1);
    glUniformMatrix4fv(projectionUniformLocation, 1, GL_FALSE, glm::value_ptr(projection));

    GLint modelUniformLocation = glGetUniformLocation(shaderProgram, "model");
    assert(modelUniformLocation != -1);

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*) 0);
    glEnableVertexAttribArray(0);

    double lastTime = glfwGetTime();
    double currentTime;
    double delta;

    while (!glfwWindowShouldClose(window)) {
        currentTime = glfwGetTime();

        glfwPollEvents();

        processInput();

        glm::mat4 model = glm::mat4(1.0f);
        model = glm::translate(model, glm::vec3(topLeftPosition, 0.0f));
        model = glm::scale(model, glm::vec3(SIZE, SIZE, 1.0f));
        glUniformMatrix4fv(modelUniformLocation, 1, GL_FALSE, glm::value_ptr(model));

        glClearColor(redOffset, greenOffset, blueOffset, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        glfwSwapBuffers(window);

        delta = currentTime - lastTime;
        lastTime = currentTime;

//        std::cout << delta * 1000.f << " ms" << std::endl;
    }

    glfwTerminate();
    return EXIT_SUCCESS;
}

void processInput() {
    float step = 8.f;
    if (keys[GLFW_KEY_UP] == GLFW_PRESS) {
        if (topLeftPosition.y > 0.f) {
            topLeftPosition.y -= step;
        }
    }
    if (keys[GLFW_KEY_DOWN] == GLFW_PRESS) {
        if (topLeftPosition.y < HEIGHT - SIZE) {
            topLeftPosition.y += step;
        }
    }
    if (keys[GLFW_KEY_LEFT] == GLFW_PRESS) {
        if (topLeftPosition.x > 0.f) {
            topLeftPosition.x -= step;
        }
    }
    if (keys[GLFW_KEY_RIGHT] == GLFW_PRESS) {
        if (topLeftPosition.x < WIDTH - SIZE) {
            topLeftPosition.x += step;
        }
    }
    if (keys[GLFW_KEY_SPACE] == GLFW_PRESS && !processedKeys[GLFW_KEY_SPACE]) {
        processedKeys[GLFW_KEY_SPACE] = true;
        redOffset = (float) (rand()) / (float) RAND_MAX;
        greenOffset = (float) (rand()) / (float) RAND_MAX;
        blueOffset = (float) (rand()) / (float) RAND_MAX;
    }
}

std::string readTextFile(const std::string& path) {
    std::ifstream in(path);

    assert(in.good());

    std::ostringstream ss;
    ss << in.rdbuf();
    return ss.str();
}
<commit_msg>Move shader creation/compilation into seperate function<commit_after>// GLAD will not include windows.h for APIENTRY if it was previously defined
#ifdef _WIN32
#define APIENTRY __stdcall
#endif

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

// confirm that neither GLAD nor GLFW didn't include windows.h
#ifdef _WINDOWS_
#error windows.h was included!
#endif

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

#include <cstdlib>
#include <string>
#include <cassert>
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>

const int WIDTH = 1280;
const int HEIGHT = 720;

float redOffset = 0.5f;
float greenOffset = 0.6f;
float blueOffset = 0.92f;

bool keys[512];
bool processedKeys[512];

const float SIZE = 50.f;

glm::vec2 topLeftPosition = glm::vec2(WIDTH / 2 - SIZE, HEIGHT / 2 - SIZE);

std::string readTextFile(const std::string& path);
void processInput();

GLuint createAndCompileShader(GLenum shaderType, const std::string& path);

int main(int argc, char* argv[])
{
    if (!glfwInit()) {
        std::cout << "Failed to initialize GLFW" << std::endl;
        return EXIT_FAILURE;
    }

//    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
//    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
//    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//    glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);

    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Fuzzy", nullptr, nullptr);
    if (!window) {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return EXIT_FAILURE;
    }

    GLFWmonitor* monitor = glfwGetPrimaryMonitor();
    const GLFWvidmode* vidmode = glfwGetVideoMode(monitor);

    glfwSetWindowPos(window, (vidmode->width - WIDTH) / 2, (vidmode->height - HEIGHT) / 2);

    glfwSetKeyCallback(window, [](GLFWwindow* window, int key, int scancode, int action, int mods) {
        if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
            glfwSetWindowShouldClose(window, GLFW_TRUE);
        }
        if (action == GLFW_PRESS) {
            keys[key] = true;
        } else if (action == GLFW_RELEASE) {
            keys[key] = false;
            processedKeys[key] = false;
        }
    });

    glfwSetFramebufferSizeCallback(window, [](GLFWwindow* window, int width, int height) {
        glViewport(0, 0, width, height);
    });

    glfwMakeContextCurrent(window);

    glfwSwapInterval(1);

    if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) {
        std::cout << "Failed to initialize OpenGL context" << std::endl;
        return EXIT_FAILURE;
    }

    std::cout << glGetString(GL_VERSION) << std::endl;

    glViewport(0, 0, WIDTH, HEIGHT);

    float vertices[] = {
        0.f, 0.f,
        0.f, SIZE,
        SIZE, 0.f,
        SIZE, SIZE
    };

    GLuint VBO;
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    GLuint vertexShader = createAndCompileShader(GL_VERTEX_SHADER, "shaders/basic.vert");
    GLuint fragmentShader = createAndCompileShader(GL_FRAGMENT_SHADER, "shaders/basic.frag");

    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    GLint isShaderProgramLinked;
    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &isShaderProgramLinked);

    if (!isShaderProgramLinked) {
        GLint LOG_LENGTH;
        glGetProgramiv(shaderProgram, GL_INFO_LOG_LENGTH, &LOG_LENGTH);

        std::vector<GLchar> errorLog(LOG_LENGTH);

        glGetProgramInfoLog(shaderProgram, LOG_LENGTH, nullptr, &errorLog[0]);
        std::cerr << "Shader program linkage failed:" << std::endl << &errorLog[0] << std::endl;
    }
    assert(isShaderProgramLinked);

    glUseProgram(shaderProgram);

    glm::mat4 projection = glm::ortho(0.0f, (float) WIDTH, (float) HEIGHT, 0.0f);

    GLint projectionUniformLocation = glGetUniformLocation(shaderProgram, "projection");
    assert(projectionUniformLocation != -1);
    glUniformMatrix4fv(projectionUniformLocation, 1, GL_FALSE, glm::value_ptr(projection));

    GLint modelUniformLocation = glGetUniformLocation(shaderProgram, "model");
    assert(modelUniformLocation != -1);

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*) 0);
    glEnableVertexAttribArray(0);

    double lastTime = glfwGetTime();
    double currentTime;
    double delta;

    while (!glfwWindowShouldClose(window)) {
        currentTime = glfwGetTime();

        glfwPollEvents();

        processInput();

        glm::mat4 model = glm::mat4(1.0f);
        model = glm::translate(model, glm::vec3(topLeftPosition, 0.0f));
        glUniformMatrix4fv(modelUniformLocation, 1, GL_FALSE, glm::value_ptr(model));

        glClearColor(redOffset, greenOffset, blueOffset, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        glfwSwapBuffers(window);

        delta = currentTime - lastTime;
        lastTime = currentTime;

//        std::cout << delta * 1000.f << " ms" << std::endl;
    }

    glfwTerminate();
    return EXIT_SUCCESS;
}

void processInput() {
    float step = 8.f;
    if (keys[GLFW_KEY_UP] == GLFW_PRESS) {
        if (topLeftPosition.y > 0.f) {
            topLeftPosition.y -= step;
        }
    }
    if (keys[GLFW_KEY_DOWN] == GLFW_PRESS) {
        if (topLeftPosition.y < HEIGHT - SIZE) {
            topLeftPosition.y += step;
        }
    }
    if (keys[GLFW_KEY_LEFT] == GLFW_PRESS) {
        if (topLeftPosition.x > 0.f) {
            topLeftPosition.x -= step;
        }
    }
    if (keys[GLFW_KEY_RIGHT] == GLFW_PRESS) {
        if (topLeftPosition.x < WIDTH - SIZE) {
            topLeftPosition.x += step;
        }
    }
    if (keys[GLFW_KEY_SPACE] == GLFW_PRESS && !processedKeys[GLFW_KEY_SPACE]) {
        processedKeys[GLFW_KEY_SPACE] = true;
        redOffset = (float) (rand()) / (float) RAND_MAX;
        greenOffset = (float) (rand()) / (float) RAND_MAX;
        blueOffset = (float) (rand()) / (float) RAND_MAX;
    }
}

GLuint createAndCompileShader(GLenum shaderType, const std::string& path) {
    GLuint shader = glCreateShader(shaderType);
    std::string shaderSource = readTextFile(path);
    const GLchar* shaderSourcePtr = shaderSource.c_str();
    glShaderSource(shader, 1, &shaderSourcePtr, nullptr);
    glCompileShader(shader);

    GLint isShaderCompiled;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &isShaderCompiled);
    if (!isShaderCompiled) {
        GLint LOG_LENGTH;
        glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &LOG_LENGTH);

        std::vector<GLchar> errorLog(LOG_LENGTH);

        glGetShaderInfoLog(shader, LOG_LENGTH, nullptr, &errorLog[0]);
        std::cerr << "Shader compilation failed:" << std::endl << &errorLog[0] << std::endl;
    }
    assert(isShaderCompiled);

    return shader;
}

std::string readTextFile(const std::string& path) {
    std::ifstream in(path);

    assert(in.good());

    std::ostringstream ss;
    ss << in.rdbuf();
    return ss.str();
}
<|endoftext|>


<commit_before>#include "utils.h"

#include <iostream>
#include <sstream>

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <gsl/gsl>

#include "config/pattern.h"
#include "config/settingsNode.h"
#include "plugins/pluginUtils.h"

#include "base-utils/configFileWriter.h"
#include "base-utils/yaml.h"

#include "logger.h"

using std::initializer_list;
using std::endl;
using std::map;
using std::pair;
using std::reference_wrapper;
using std::string;
using std::stringstream;
using std::vector;

using boost::filesystem::ifstream;
using boost::filesystem::ofstream;
using boost::filesystem::path;
using gsl::not_null;

using execHelper::config::EnvironmentCollection;
using execHelper::config::EnvironmentValue;
using execHelper::config::Path;
using execHelper::config::Pattern;
using execHelper::config::PatternCombinations;
using execHelper::config::PatternKey;
using execHelper::config::PatternValue;
using execHelper::config::PatternKeys;
using execHelper::config::PatternValues;
using execHelper::config::SettingsKeys;
using execHelper::config::SettingsNode;
using execHelper::core::Task;
using execHelper::plugins::PatternPermutator;
using execHelper::plugins::replacePatternCombinations;

using execHelper::core::test::ExecutorStub;
using execHelper::test::baseUtils::ConfigFileWriter;
using execHelper::test::baseUtils::YamlWriter;

namespace {
    const string YAML_CONFIG_KEY_DELIMITER(": ");
    const string YAML_CONFIG_DELIMITER("\n");
    const string YAML_CONFIG_NESTED_CHARACTER("    ");
    const string YAML_CONFIG_OPTION_CHARACTER("- ");

    const string rootPatternKey("patterns");
}

namespace execHelper { namespace test { namespace utils {
   MainVariables::MainVariables(const Arguments& arguments) {
        argc = static_cast<int>(arguments.size());
        argv.reset(new char*[argc]);

        for(size_t i = 0; i < arguments.size(); ++i) {
            argv.get()[i] = const_cast<char*>(arguments[i].c_str());
        }
    }

   string convertToConfig(const initializer_list<string>& keys, const string& value, const string& prepend) noexcept {
        return convertToConfig(vector<string>(keys), {value}, prepend);
   }

   string convertToConfig(const initializer_list<string>& keys, const initializer_list<string>& values, const string& prepend) noexcept {
        return convertToConfig(vector<string>(keys), values, prepend);
   }

   string convertToConfig(const initializer_list<string>& keys, const vector<string>& values, const string& prepend ) noexcept {
        return convertToConfig(vector<string>(keys), vector<string>(values), prepend);
   }

   string convertToConfig(const vector<string>& keys, const initializer_list<string>& values, const string& prepend) noexcept {
        return convertToConfig(keys, vector<string>(values), prepend);
   }

   string convertToConfig(const vector<string>& keys, const vector<string>& values, const string& prepend) noexcept {
        string config;

        string nestedCharacters;
        for(const auto& key : keys) {
            config += prepend + nestedCharacters + key + YAML_CONFIG_KEY_DELIMITER + YAML_CONFIG_DELIMITER;
            nestedCharacters += YAML_CONFIG_NESTED_CHARACTER;
        }
        for(const auto& value : values) {
            config += prepend + nestedCharacters + YAML_CONFIG_OPTION_CHARACTER + value + YAML_CONFIG_DELIMITER;
        }
        config += YAML_CONFIG_DELIMITER;
        return config;
    }

    string convertToConfig(const string& key, const vector<string>& values, const string& prepend) {
        return convertToConfig(vector<string>({key}), values, prepend);
    }

    string convertToConfig(const Patterns& patterns) noexcept {
        stringstream stream;

        if(!patterns.empty()) {
            stream << rootPatternKey << YAML_CONFIG_KEY_DELIMITER << YAML_CONFIG_DELIMITER;
            for(auto& pattern : patterns) {
                string patternNestedCharacter = YAML_CONFIG_NESTED_CHARACTER;
                stream << patternNestedCharacter << pattern.getKey() << YAML_CONFIG_KEY_DELIMITER << YAML_CONFIG_DELIMITER;

                patternNestedCharacter += YAML_CONFIG_NESTED_CHARACTER;
                const auto shortOption = pattern.getShortOption();
                if(shortOption) {
                    stream << convertToConfig("short-option", string(1U, shortOption.get()), patternNestedCharacter);
                }
                const auto longOption = pattern.getLongOption();
                if(longOption) {
                    stream << convertToConfig("long-option", longOption.get(), patternNestedCharacter);
                }
                stream << convertToConfig("values", pattern.getValues(), patternNestedCharacter);
            }
        }
        return stream.str();
    }

    string convertToConfig(const SettingsNode& settings, const string& prepend) noexcept {
        stringstream stream;
        const string nestedCharacter(prepend);

        if(settings.values().empty()) {
            stream << prepend << YAML_CONFIG_OPTION_CHARACTER << settings.key() << YAML_CONFIG_DELIMITER;
        } else if (settings.values().size() == 1 && settings[settings.values().back()].values().empty()) {
            stream << prepend << settings.key() << YAML_CONFIG_KEY_DELIMITER << settings.values().back() << YAML_CONFIG_DELIMITER;
        } else {
            string valueNestedCharacter = nestedCharacter;
            stream << nestedCharacter << settings.key() << YAML_CONFIG_KEY_DELIMITER << YAML_CONFIG_DELIMITER;
            valueNestedCharacter += YAML_CONFIG_NESTED_CHARACTER;
            for(const auto& key : settings.values()) {
                stream << convertToConfig(settings[key], valueNestedCharacter);
            }
        }
        return stream.str();
    }

    string convertToConfig(const SettingsNode& settings, const Patterns& patterns, const string& prepend) noexcept {
        string result = convertToConfig(patterns);
        result += convertToConfig(settings, prepend);
        return result;
    }

    string convertToConfig(string key, string value, const string& prepend) {
        return prepend + key + YAML_CONFIG_KEY_DELIMITER + value + YAML_CONFIG_DELIMITER;
    }

    string convertToConfig(const string& key, const std::initializer_list<string>& values, const string& prepend) {
        std::vector<string> vectorValues(values);
        return convertToConfig(key, vectorValues, prepend);
    }

    string basename(const string& file) {
        unsigned int found = file.find_last_of("/\\");
        return file.substr(0,found);
    }

    YamlWriter toYaml(const SettingsNode& settings, const Patterns& patterns) noexcept {
        static string patternKey("patterns");
        YamlWriter yaml;
        for(const auto& pattern : patterns) {
            const auto longOption = pattern.getLongOption();
            if(longOption) {
                yaml[patternKey][pattern.getKey()]["long-option"] = longOption.get();
            }
            yaml[patternKey][pattern.getKey()]["default-values"] = pattern.getValues();
            const auto shortOption = pattern.getShortOption();
            if(shortOption) {
                yaml[patternKey][pattern.getKey()]["short-option"] = shortOption.get();
            }
        }
        for(const auto& subKey : settings.values()) {
            if(settings[subKey].values().empty()) {
                if(settings.values().size() == 1U) {
                    try {
                        yaml = subKey;
                    } catch(const YAML::InvalidNode&) {
                        LOG(error) << "Somehow the used YAML node is invalid";
                        assert(false);
                    }
                } else {
                    try {
                        yaml.push_back(subKey);
                    } catch(const YAML::InvalidNode&) {
                        LOG(error) << "Somehow the used YAML node is invalid";
                        assert(false);
                    }
                }
            } else {
                    yaml[subKey] = toYaml(settings[subKey], Patterns());
                } catch(const YAML::InvalidNode& e) {
                    LOG(error) << "Somehow the used YAML node is invalid";
                    assert(false);
                }
            }
        }
        return yaml;
    }

    void writeSettingsFile(not_null<ConfigFileWriter*> configFileWriter, const SettingsNode& settings, const Patterns& patterns) noexcept {
        YamlWriter yaml = toYaml(settings, patterns);
        configFileWriter->write(yaml);
    }

    PatternCombinations createPatternCombination(const initializer_list<PatternKey>& keys, const initializer_list<PatternValue>& values) noexcept {
        return createPatternCombination(PatternKeys(keys), values);
    }

    PatternCombinations createPatternCombination(const PatternKeys& keys, const PatternValues& values) noexcept {
        PatternCombinations combination;
        if(keys.size() != values.size()) {
            return combination;
        }

        for(size_t i = 0; i < keys.size(); ++i) {
            combination[keys[i]] = values[i];
        }
        return combination;
    }

    PatternPermutator makePatternPermutator(const Patterns& patterns) noexcept {
        map<PatternKey, PatternValues> patternValuesMatrix;
        for(const auto& pattern : patterns) {
            patternValuesMatrix.emplace(make_pair(pattern.getKey(), pattern.getValues()));
        }
        return PatternPermutator(patternValuesMatrix);
    }

    ExecutorStub::TaskQueue getExpectedTasks(const Task& task, const Patterns patterns) noexcept {
        ExecutorStub::TaskQueue result;
        for(const auto& combination : makePatternPermutator(patterns)) {
            result.emplace_back(replacePatternCombinations(task, combination));
        }
        return result;
    }

    ExecutorStub::TaskQueue getExpectedTasks(const ExecutorStub::TaskQueue& tasks, const Patterns patterns) noexcept {
        ExecutorStub::TaskQueue result;
        for(const auto& combination : makePatternPermutator(patterns)) {
            for(const auto& task : tasks) {
                result.emplace_back(replacePatternCombinations(task, combination));
            }
        }
        return result;
    }

    string toString(const SettingsNode& settings, unsigned int nbOfTabs) noexcept {
        string prefix;
        for(unsigned int i = 0; i < nbOfTabs; ++i) {
            prefix += "  ";
        }

        string result;
        result += prefix + "- " + settings.key();
        if(settings.values().empty()) {
            result += "\n";
           return result;
        } else {
           result += ":\n";
        }
        for(const auto& value : settings.values()) {
            result += toString(settings[value], nbOfTabs + 1);
        }
        return result;
    }
} } }
<commit_msg>Fix: Dev: Fixed build. !minor<commit_after>#include "utils.h"

#include <iostream>
#include <sstream>

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <gsl/gsl>

#include "config/pattern.h"
#include "config/settingsNode.h"
#include "plugins/pluginUtils.h"

#include "base-utils/configFileWriter.h"
#include "base-utils/yaml.h"

#include "logger.h"

using std::initializer_list;
using std::endl;
using std::map;
using std::pair;
using std::reference_wrapper;
using std::string;
using std::stringstream;
using std::vector;

using boost::filesystem::ifstream;
using boost::filesystem::ofstream;
using boost::filesystem::path;
using gsl::not_null;

using execHelper::config::EnvironmentCollection;
using execHelper::config::EnvironmentValue;
using execHelper::config::Path;
using execHelper::config::Pattern;
using execHelper::config::PatternCombinations;
using execHelper::config::PatternKey;
using execHelper::config::PatternValue;
using execHelper::config::PatternKeys;
using execHelper::config::PatternValues;
using execHelper::config::SettingsKeys;
using execHelper::config::SettingsNode;
using execHelper::core::Task;
using execHelper::plugins::PatternPermutator;
using execHelper::plugins::replacePatternCombinations;

using execHelper::core::test::ExecutorStub;
using execHelper::test::baseUtils::ConfigFileWriter;
using execHelper::test::baseUtils::YamlWriter;

namespace {
    const string YAML_CONFIG_KEY_DELIMITER(": ");
    const string YAML_CONFIG_DELIMITER("\n");
    const string YAML_CONFIG_NESTED_CHARACTER("    ");
    const string YAML_CONFIG_OPTION_CHARACTER("- ");

    const string rootPatternKey("patterns");
}

namespace execHelper { namespace test { namespace utils {
   MainVariables::MainVariables(const Arguments& arguments) {
        argc = static_cast<int>(arguments.size());
        argv.reset(new char*[argc]);

        for(size_t i = 0; i < arguments.size(); ++i) {
            argv.get()[i] = const_cast<char*>(arguments[i].c_str());
        }
    }

   string convertToConfig(const initializer_list<string>& keys, const string& value, const string& prepend) noexcept {
        return convertToConfig(vector<string>(keys), {value}, prepend);
   }

   string convertToConfig(const initializer_list<string>& keys, const initializer_list<string>& values, const string& prepend) noexcept {
        return convertToConfig(vector<string>(keys), values, prepend);
   }

   string convertToConfig(const initializer_list<string>& keys, const vector<string>& values, const string& prepend ) noexcept {
        return convertToConfig(vector<string>(keys), vector<string>(values), prepend);
   }

   string convertToConfig(const vector<string>& keys, const initializer_list<string>& values, const string& prepend) noexcept {
        return convertToConfig(keys, vector<string>(values), prepend);
   }

   string convertToConfig(const vector<string>& keys, const vector<string>& values, const string& prepend) noexcept {
        string config;

        string nestedCharacters;
        for(const auto& key : keys) {
            config += prepend + nestedCharacters + key + YAML_CONFIG_KEY_DELIMITER + YAML_CONFIG_DELIMITER;
            nestedCharacters += YAML_CONFIG_NESTED_CHARACTER;
        }
        for(const auto& value : values) {
            config += prepend + nestedCharacters + YAML_CONFIG_OPTION_CHARACTER + value + YAML_CONFIG_DELIMITER;
        }
        config += YAML_CONFIG_DELIMITER;
        return config;
    }

    string convertToConfig(const string& key, const vector<string>& values, const string& prepend) {
        return convertToConfig(vector<string>({key}), values, prepend);
    }

    string convertToConfig(const Patterns& patterns) noexcept {
        stringstream stream;

        if(!patterns.empty()) {
            stream << rootPatternKey << YAML_CONFIG_KEY_DELIMITER << YAML_CONFIG_DELIMITER;
            for(auto& pattern : patterns) {
                string patternNestedCharacter = YAML_CONFIG_NESTED_CHARACTER;
                stream << patternNestedCharacter << pattern.getKey() << YAML_CONFIG_KEY_DELIMITER << YAML_CONFIG_DELIMITER;

                patternNestedCharacter += YAML_CONFIG_NESTED_CHARACTER;
                const auto shortOption = pattern.getShortOption();
                if(shortOption) {
                    stream << convertToConfig("short-option", string(1U, shortOption.get()), patternNestedCharacter);
                }
                const auto longOption = pattern.getLongOption();
                if(longOption) {
                    stream << convertToConfig("long-option", longOption.get(), patternNestedCharacter);
                }
                stream << convertToConfig("values", pattern.getValues(), patternNestedCharacter);
            }
        }
        return stream.str();
    }

    string convertToConfig(const SettingsNode& settings, const string& prepend) noexcept {
        stringstream stream;
        const string nestedCharacter(prepend);

        if(settings.values().empty()) {
            stream << prepend << YAML_CONFIG_OPTION_CHARACTER << settings.key() << YAML_CONFIG_DELIMITER;
        } else if (settings.values().size() == 1 && settings[settings.values().back()].values().empty()) {
            stream << prepend << settings.key() << YAML_CONFIG_KEY_DELIMITER << settings.values().back() << YAML_CONFIG_DELIMITER;
        } else {
            string valueNestedCharacter = nestedCharacter;
            stream << nestedCharacter << settings.key() << YAML_CONFIG_KEY_DELIMITER << YAML_CONFIG_DELIMITER;
            valueNestedCharacter += YAML_CONFIG_NESTED_CHARACTER;
            for(const auto& key : settings.values()) {
                stream << convertToConfig(settings[key], valueNestedCharacter);
            }
        }
        return stream.str();
    }

    string convertToConfig(const SettingsNode& settings, const Patterns& patterns, const string& prepend) noexcept {
        string result = convertToConfig(patterns);
        result += convertToConfig(settings, prepend);
        return result;
    }

    string convertToConfig(string key, string value, const string& prepend) {
        return prepend + key + YAML_CONFIG_KEY_DELIMITER + value + YAML_CONFIG_DELIMITER;
    }

    string convertToConfig(const string& key, const std::initializer_list<string>& values, const string& prepend) {
        std::vector<string> vectorValues(values);
        return convertToConfig(key, vectorValues, prepend);
    }

    string basename(const string& file) {
        unsigned int found = file.find_last_of("/\\");
        return file.substr(0,found);
    }

    YamlWriter toYaml(const SettingsNode& settings, const Patterns& patterns) noexcept {
        static string patternKey("patterns");
        YamlWriter yaml;
        for(const auto& pattern : patterns) {
            const auto longOption = pattern.getLongOption();
            if(longOption) {
                yaml[patternKey][pattern.getKey()]["long-option"] = longOption.get();
            }
            yaml[patternKey][pattern.getKey()]["default-values"] = pattern.getValues();
            const auto shortOption = pattern.getShortOption();
            if(shortOption) {
                yaml[patternKey][pattern.getKey()]["short-option"] = shortOption.get();
            }
        }
        for(const auto& subKey : settings.values()) {
            if(settings[subKey].values().empty()) {
                if(settings.values().size() == 1U) {
                    try {
                        yaml = subKey;
                    } catch(const YAML::InvalidNode&) {
                        LOG(error) << "Somehow the used YAML node is invalid";
                        assert(false);
                    }
                } else {
                    try {
                        yaml.push_back(subKey);
                    } catch(const YAML::InvalidNode&) {
                        LOG(error) << "Somehow the used YAML node is invalid";
                        assert(false);
                    }
                }
            } else {
                try {
                    yaml[subKey] = toYaml(settings[subKey], Patterns());
                } catch(const YAML::InvalidNode& e) {
                    LOG(error) << "Somehow the used YAML node is invalid";
                    assert(false);
                }
            }
        }
        return yaml;
    }

    void writeSettingsFile(not_null<ConfigFileWriter*> configFileWriter, const SettingsNode& settings, const Patterns& patterns) noexcept {
        YamlWriter yaml = toYaml(settings, patterns);
        configFileWriter->write(yaml);
    }

    PatternCombinations createPatternCombination(const initializer_list<PatternKey>& keys, const initializer_list<PatternValue>& values) noexcept {
        return createPatternCombination(PatternKeys(keys), values);
    }

    PatternCombinations createPatternCombination(const PatternKeys& keys, const PatternValues& values) noexcept {
        PatternCombinations combination;
        if(keys.size() != values.size()) {
            return combination;
        }

        for(size_t i = 0; i < keys.size(); ++i) {
            combination[keys[i]] = values[i];
        }
        return combination;
    }

    PatternPermutator makePatternPermutator(const Patterns& patterns) noexcept {
        map<PatternKey, PatternValues> patternValuesMatrix;
        for(const auto& pattern : patterns) {
            patternValuesMatrix.emplace(make_pair(pattern.getKey(), pattern.getValues()));
        }
        return PatternPermutator(patternValuesMatrix);
    }

    ExecutorStub::TaskQueue getExpectedTasks(const Task& task, const Patterns patterns) noexcept {
        ExecutorStub::TaskQueue result;
        for(const auto& combination : makePatternPermutator(patterns)) {
            result.emplace_back(replacePatternCombinations(task, combination));
        }
        return result;
    }

    ExecutorStub::TaskQueue getExpectedTasks(const ExecutorStub::TaskQueue& tasks, const Patterns patterns) noexcept {
        ExecutorStub::TaskQueue result;
        for(const auto& combination : makePatternPermutator(patterns)) {
            for(const auto& task : tasks) {
                result.emplace_back(replacePatternCombinations(task, combination));
            }
        }
        return result;
    }

    string toString(const SettingsNode& settings, unsigned int nbOfTabs) noexcept {
        string prefix;
        for(unsigned int i = 0; i < nbOfTabs; ++i) {
            prefix += "  ";
        }

        string result;
        result += prefix + "- " + settings.key();
        if(settings.values().empty()) {
            result += "\n";
           return result;
        } else {
           result += ":\n";
        }
        for(const auto& value : settings.values()) {
            result += toString(settings[value], nbOfTabs + 1);
        }
        return result;
    }
} } }
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef RENDERER_HPP
#define RENDERER_HPP

#include "compare_images.hpp"

// stl
#include <sstream>
#include <iomanip>

// mapnik
#include <mapnik/map.hpp>
#include <mapnik/agg_renderer.hpp>
#if defined(HAVE_CAIRO)
#include <mapnik/cairo/cairo_renderer.hpp>
#include <mapnik/cairo/cairo_image_util.hpp>
#endif

// boost
#include <boost/filesystem.hpp>

namespace visual_tests
{

template <typename ImageType>
struct renderer_base
{
    using image_type = ImageType;

    unsigned compare(image_type const & actual, boost::filesystem::path const& reference) const
    {
        return compare_images(actual, reference.string());
    }

    void save(image_type const & image, boost::filesystem::path const& path) const
    {
        mapnik::save_to_file(image, path.string(), "png32");
    }
};

struct agg_renderer : renderer_base<mapnik::image_rgba8>
{
    static constexpr const char * name = "agg";

    image_type render(mapnik::Map const & map, double scale_factor) const
    {
        image_type image(map.width(), map.height());
        mapnik::agg_renderer<image_type> ren(map, image, scale_factor);
        ren.apply();
        return image;
    }
};

#if defined(HAVE_CAIRO)
struct cairo_renderer : renderer_base<mapnik::image_rgba8>
{
    static constexpr const char * name = "cairo";

    image_type render(mapnik::Map const & map, double scale_factor) const
    {
        mapnik::cairo_surface_ptr image_surface(
            cairo_image_surface_create(CAIRO_FORMAT_ARGB32, map.width(), map.height()),
            mapnik::cairo_surface_closer());
        mapnik::cairo_ptr image_context(mapnik::create_context(image_surface));
        mapnik::cairo_renderer<mapnik::cairo_ptr> ren(map, image_context, scale_factor);
        ren.apply();
        image_type image(map.width(), map.height());
        mapnik::cairo_image_to_rgba8(image, image_surface);
        return image;
    }
};
#endif

struct grid_renderer : renderer_base<mapnik::image_gray8>
{
    static constexpr const char * name = "grid";

    image_type render(mapnik::Map const & map, double scale_factor) const
    {
        image_type image(map.width(), map.height());
        // TODO: Render grid here.
        return image;
    }
};

template <typename Renderer>
class renderer
{
public:
    renderer(boost::filesystem::path const & output_dir, boost::filesystem::path const & reference_dir, bool overwrite)
        : output_dir(output_dir), reference_dir(reference_dir), overwrite(overwrite)
    {
    }

    result test(std::string const & name, mapnik::Map const & map, double scale_factor) const
    {
        typename Renderer::image_type image(ren.render(map, scale_factor));
        boost::filesystem::path reference = reference_dir / image_file_name(name, map.width(), map.height(), scale_factor, true);
        result res;

        res.state = STATE_OK;
        res.name = name;
        res.renderer_name = Renderer::name;
        res.scale_factor = scale_factor;
        res.size = map_size(map.width(), map.height());
        res.reference_image_path = reference;
        res.diff = ren.compare(image, reference);

        if (res.diff)
        {
            ensure_dir(output_dir);
            boost::filesystem::path path = output_dir / image_file_name(name, map.width(), map.height(), scale_factor);
            res.actual_image_path = path;
            res.state = STATE_FAIL;
            ren.save(image, path);

            if (overwrite)
            {
                ren.save(image, reference);
                res.state = STATE_OVERWRITE;
            }
        }

        return res;
    }

private:
    std::string image_file_name(std::string const & test_name,
                                double width,
                                double height,
                                double scale_factor,
                                bool reference=false) const
    {
        std::stringstream s;
        s << test_name << '-' << width << '-' << height << '-'
          << std::fixed << std::setprecision(1) << scale_factor
          << '-' << Renderer::name << (reference ? "-reference" : "") << ".png";
        return s.str();
    }

    Renderer ren;
    boost::filesystem::path const & output_dir;
    boost::filesystem::path const & reference_dir;
    const bool overwrite;
};

}

#endif
<commit_msg>handle styles with missing reference images<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef RENDERER_HPP
#define RENDERER_HPP

#include "compare_images.hpp"

// stl
#include <sstream>
#include <iomanip>

// mapnik
#include <mapnik/map.hpp>
#include <mapnik/util/fs.hpp>
#include <mapnik/agg_renderer.hpp>
#if defined(HAVE_CAIRO)
#include <mapnik/cairo/cairo_renderer.hpp>
#include <mapnik/cairo/cairo_image_util.hpp>
#endif

// boost
#include <boost/filesystem.hpp>

namespace visual_tests
{

template <typename ImageType>
struct renderer_base
{
    using image_type = ImageType;

    unsigned compare(image_type const & actual, boost::filesystem::path const& reference) const
    {
        return compare_images(actual, reference.string());
    }

    void save(image_type const & image, boost::filesystem::path const& path) const
    {
        mapnik::save_to_file(image, path.string(), "png32");
    }
};

struct agg_renderer : renderer_base<mapnik::image_rgba8>
{
    static constexpr const char * name = "agg";

    image_type render(mapnik::Map const & map, double scale_factor) const
    {
        image_type image(map.width(), map.height());
        mapnik::agg_renderer<image_type> ren(map, image, scale_factor);
        ren.apply();
        return image;
    }
};

#if defined(HAVE_CAIRO)
struct cairo_renderer : renderer_base<mapnik::image_rgba8>
{
    static constexpr const char * name = "cairo";

    image_type render(mapnik::Map const & map, double scale_factor) const
    {
        mapnik::cairo_surface_ptr image_surface(
            cairo_image_surface_create(CAIRO_FORMAT_ARGB32, map.width(), map.height()),
            mapnik::cairo_surface_closer());
        mapnik::cairo_ptr image_context(mapnik::create_context(image_surface));
        mapnik::cairo_renderer<mapnik::cairo_ptr> ren(map, image_context, scale_factor);
        ren.apply();
        image_type image(map.width(), map.height());
        mapnik::cairo_image_to_rgba8(image, image_surface);
        return image;
    }
};
#endif

struct grid_renderer : renderer_base<mapnik::image_gray8>
{
    static constexpr const char * name = "grid";

    image_type render(mapnik::Map const & map, double scale_factor) const
    {
        image_type image(map.width(), map.height());
        // TODO: Render grid here.
        return image;
    }
};

template <typename Renderer>
class renderer
{
public:
    renderer(boost::filesystem::path const & output_dir, boost::filesystem::path const & reference_dir, bool overwrite)
        : output_dir(output_dir), reference_dir(reference_dir), overwrite(overwrite)
    {
    }

    result test(std::string const & name, mapnik::Map const & map, double scale_factor) const
    {
        typename Renderer::image_type image(ren.render(map, scale_factor));
        boost::filesystem::path reference = reference_dir / image_file_name(name, map.width(), map.height(), scale_factor, true);
        bool reference_exists = mapnik::util::exists(reference.string());
        result res;

        res.state = reference_exists ? STATE_OK : STATE_OVERWRITE;
        res.name = name;
        res.renderer_name = Renderer::name;
        res.scale_factor = scale_factor;
        res.size = map_size(map.width(), map.height());
        res.reference_image_path = reference;
        res.diff = reference_exists ? ren.compare(image, reference) : 0;

        if (res.diff)
        {
            ensure_dir(output_dir);
            boost::filesystem::path path = output_dir / image_file_name(name, map.width(), map.height(), scale_factor);
            res.actual_image_path = path;
            res.state = STATE_FAIL;
            ren.save(image, path);
        }

        if ((res.diff && overwrite) || !reference_exists)
        {
            ren.save(image, reference);
            res.state = STATE_OVERWRITE;
        }

        return res;
    }

private:
    std::string image_file_name(std::string const & test_name,
                                double width,
                                double height,
                                double scale_factor,
                                bool reference=false) const
    {
        std::stringstream s;
        s << test_name << '-' << width << '-' << height << '-'
          << std::fixed << std::setprecision(1) << scale_factor
          << '-' << Renderer::name << (reference ? "-reference" : "") << ".png";
        return s.str();
    }

    Renderer ren;
    boost::filesystem::path const & output_dir;
    boost::filesystem::path const & reference_dir;
    const bool overwrite;
};

}

#endif
<|endoftext|>


<commit_before>/* Copyright 2018 The TensorFlow Authors. 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 "tensorflow/lite/experimental/micro/examples/micro_speech/timer.h"

#include <limits>

#include "tensorflow/lite/c/c_api_internal.h"
#include "tensorflow/lite/experimental/micro/micro_error_reporter.h"
#include "tensorflow/lite/experimental/micro/testing/micro_test.h"

TF_LITE_MICRO_TESTS_BEGIN

TF_LITE_MICRO_TEST(TestTimer) {
  // Make sure that the technically-undefined overflow behavior we rely on below
  // works on this platform. It's still not guaranteed, but at least this is a
  // sanity check.
  int32_t overflow_value = std::numeric_limits<int32_t>::max();
  overflow_value += 1;
  TF_LITE_MICRO_EXPECT_EQ(std::numeric_limits<int32_t>::min(), overflow_value);

  const int32_t first_time = TimeInMilliseconds();
  const int32_t second_time = TimeInMilliseconds();

  // It's possible that the timer may have wrapped around from +BIG_NUM to
  // -BIG_NUM between the first and second calls, since we're storing
  // milliseconds in a 32-bit integer. It's not reasonable that the call itself
  // would have taken more than 2^31 milliseconds though, so look at the
  // difference and rely on integer overflow to ensure it's accurate.
  const int32_t time_delta = (second_time - first_time);
  TF_LITE_MICRO_EXPECT_LE(0, time_delta);
}

TF_LITE_MICRO_TESTS_END
<commit_msg>Skip overflow testing when running with address sanitizer.<commit_after>/* Copyright 2018 The TensorFlow Authors. 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 "tensorflow/lite/experimental/micro/examples/micro_speech/timer.h"

#include <limits>

#include "tensorflow/lite/c/c_api_internal.h"
#include "tensorflow/lite/experimental/micro/micro_error_reporter.h"
#include "tensorflow/lite/experimental/micro/testing/micro_test.h"

TF_LITE_MICRO_TESTS_BEGIN

TF_LITE_MICRO_TEST(TestTimer) {
  // Make sure that the technically-undefined overflow behavior we rely on below
  // works on this platform. It's still not guaranteed, but at least this is a
  // sanity check.  Turn off when running with ASan, as it will complain about
  // the following undefined behavior.
#ifndef ADDRESS_SANITIZER
  int32_t overflow_value = std::numeric_limits<int32_t>::max();
  overflow_value += 1;
  TF_LITE_MICRO_EXPECT_EQ(std::numeric_limits<int32_t>::min(), overflow_value);
#endif

  const int32_t first_time = TimeInMilliseconds();
  const int32_t second_time = TimeInMilliseconds();

  // It's possible that the timer may have wrapped around from +BIG_NUM to
  // -BIG_NUM between the first and second calls, since we're storing
  // milliseconds in a 32-bit integer. It's not reasonable that the call itself
  // would have taken more than 2^31 milliseconds though, so look at the
  // difference and rely on integer overflow to ensure it's accurate.
  const int32_t time_delta = (second_time - first_time);
  TF_LITE_MICRO_EXPECT_LE(0, time_delta);
}

TF_LITE_MICRO_TESTS_END
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "../source/details/StackTrace.cpp"
#include "../source/details/DebugPrint.cpp"
#include <iostream>

#if defined(CPP_ASSERT_HAVE_BACKTRACE) || defined(_WIN32)

using namespace cppassert::internal;
TEST(StackTraceTest, constructor)
{
    StackTrace frames = StackTrace::getStackTrace();
    EXPECT_TRUE(frames.size()>0);
}

TEST(StackTraceTest, moveAssignment)
{
    StackTrace frames = StackTrace::getStackTrace();
    EXPECT_TRUE(frames.size()>0);
    StackTrace other = StackTrace::getStackTrace();
    EXPECT_TRUE(other.size()>0);
    other = std::move(frames);
    EXPECT_TRUE(other.size()>0);
}

TEST(StackTraceTest, moveOperator)
{
    StackTrace frames = StackTrace::getStackTrace();
    EXPECT_TRUE(frames.size()>0);
    StackTrace other(std::move(frames));
    EXPECT_TRUE(other.size()>0);
}

TEST(StackTraceTest, getStackTrace)
{
    StackTrace frames = StackTrace::getStackTrace();
    EXPECT_TRUE(frames.size()>0);
    const std::string functionName(frames[0].getSymbol());
    std::cout<<functionName<<std::endl;
    EXPECT_TRUE(functionName.find("getStackTrace")!=std::string::npos);
}

TEST(StackTraceTest, indexOperatorShouldThrowIfOutOfRange)
{
    StackTrace frames = StackTrace::getStackTrace();
    EXPECT_TRUE(frames.size()>0);
    EXPECT_THROW(frames[frames.size()], std::out_of_range);
}

#if defined(__linux__) || defined(__FreeBSD__)
TEST(StackTraceTest, demangler)
{
    const char *expectedSymbol =
#if defined(__linux__)
        "void testing::internal::HandleSehExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*)";
#elif defined(__FreeBSD__)
        "void testing::internal::HandleSehExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, testing::internal::HandleSehExceptionsInMethodIfSupported<testing::Test, void>(void::*)(void), char const*)";
#endif
    CppDemangler demangler;
    const char *demangledSymbol = demangler.demangle("_ZN7testing8internal38HandleSehExceptionsInMethodIfSupportedINS_4TestEvEET0_PT_MS4_FS3_vEPKc");
    EXPECT_STREQ(expectedSymbol, demangledSymbol);
}
#endif /* defined(__linux__) || defined(__FreeBSD__)*/

#endif /* defined(CPP_ASSERT_HAVE_BACKTRACE) || defined(_WIN32) */

<commit_msg>Added debugging output to be able to fix travis build<commit_after>#include <gtest/gtest.h>
#include "../source/details/StackTrace.cpp"
#include "../source/details/DebugPrint.cpp"
#include <iostream>

#if defined(CPP_ASSERT_HAVE_BACKTRACE) || defined(_WIN32)

using namespace cppassert::internal;
TEST(StackTraceTest, constructor)
{
    StackTrace frames = StackTrace::getStackTrace();
    EXPECT_TRUE(frames.size()>0);
}

TEST(StackTraceTest, moveAssignment)
{
    StackTrace frames = StackTrace::getStackTrace();
    EXPECT_TRUE(frames.size()>0);
    StackTrace other = StackTrace::getStackTrace();
    EXPECT_TRUE(other.size()>0);
    other = std::move(frames);
    EXPECT_TRUE(other.size()>0);
}

TEST(StackTraceTest, moveOperator)
{
    StackTrace frames = StackTrace::getStackTrace();
    EXPECT_TRUE(frames.size()>0);
    StackTrace other(std::move(frames));
    EXPECT_TRUE(other.size()>0);
}

TEST(StackTraceTest, getStackTrace)
{
    StackTrace frames = StackTrace::getStackTrace();
    EXPECT_TRUE(frames.size()>0);
    for(std::size_t i=0; i<frames.size(); ++i) {
         std::cout<<"Frame "<<i<<": "<<frames[i].getSymbol()<<std::endl;
    }
    const std::string functionName(frames[0].getSymbol());
    std::cout<<functionName<<std::endl;
    EXPECT_TRUE(functionName.find("getStackTrace")!=std::string::npos);
}

TEST(StackTraceTest, indexOperatorShouldThrowIfOutOfRange)
{
    StackTrace frames = StackTrace::getStackTrace();
    EXPECT_TRUE(frames.size()>0);
    EXPECT_THROW(frames[frames.size()], std::out_of_range);
}

#if defined(__linux__) || defined(__FreeBSD__)
TEST(StackTraceTest, demangler)
{
    const char *expectedSymbol =
#if defined(__linux__)
        "void testing::internal::HandleSehExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*)";
#elif defined(__FreeBSD__)
        "void testing::internal::HandleSehExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, testing::internal::HandleSehExceptionsInMethodIfSupported<testing::Test, void>(void::*)(void), char const*)";
#endif
    CppDemangler demangler;
    const char *demangledSymbol = demangler.demangle("_ZN7testing8internal38HandleSehExceptionsInMethodIfSupportedINS_4TestEvEET0_PT_MS4_FS3_vEPKc");
    EXPECT_STREQ(expectedSymbol, demangledSymbol);
}
#endif /* defined(__linux__) || defined(__FreeBSD__)*/

#endif /* defined(CPP_ASSERT_HAVE_BACKTRACE) || defined(_WIN32) */

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: basmgr.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ab $ $Date: 2000-11-13 12:43:17 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SFX_BASMGR_HXX
#define _SFX_BASMGR_HXX

#ifndef _BASMGR_HXX_
#include <basic/basmgr.hxx>
#endif

#ifndef _COM_SUN_STAR_SCRIPT_XSTARBASICACCESS_HPP_
#include <com/sun/star/script/XStarBasicAccess.hpp>
#endif

// Basic XML Import/Export
com::sun::star::uno::Reference< com::sun::star::script::XStarBasicAccess >
    getStarBasicAccess( BasicManager* pMgr );

class SfxBasicManager : public BasicManager
{
    friend class LibraryContainer_Impl;

private:
    BasicLibs*          pLibs;
    BasicErrorManager*  pErrorMgr;

    String              aName;
    String              aStorageName;
    BOOL                bBasMgrModified;

    void                Init();

protected:
    BOOL            ImpStoreLibary( StarBASIC* pLib, SvStorage& rStorage ) const;
    BOOL            ImpLoadLibary( BasicLibInfo* pLibInfo ) const;
    BOOL            ImpLoadLibary( BasicLibInfo* pLibInfo, SvStorage* pCurStorage, BOOL bInfosOnly = FALSE ) const;
    void            ImpCreateStdLib( StarBASIC* pParentFromStdLib );
    void            ImpMgrNotLoaded(  const String& rStorageName  );
    BasicLibInfo*   CreateLibInfo();
    void            LoadBasicManager( SvStorage& rStorage, BOOL bLoadBasics = TRUE );
    void            LoadOldBasicManager( SvStorage& rStorage );
    BOOL            ImplLoadBasic( SvStream& rStrm, StarBASICRef& rOldBasic ) const;
    void            ImplGetPassword( USHORT nLib ) const;
    BOOL            ImplEncryptStream( SvStream& rStream ) const;
    BasicLibInfo*   FindLibInfo( StarBASIC* pBasic ) const;
    void            CheckModules( StarBASIC* pBasic, BOOL bReference ) const;
    void            SetFlagToAllLibs( short nFlag, BOOL bSet ) const;
                    SfxBasicManager();  // Nur zum anpassen von Pfaden bei 'Speichern unter'.

public:
                    TYPEINFO();
                    SfxBasicManager( SvStorage& rStorage, StarBASIC* pParentFromStdLib = NULL, String* pLibPath = NULL );
                    SfxBasicManager( StarBASIC* pStdLib, String* pLibPath = NULL );
                    ~SfxBasicManager();

    void            SetStorageName( const String& rName )   { aStorageName = rName; }
    String          GetStorageName() const                  { return aStorageName; }
    void            SetName( const String& rName )          { aName = rName; }
    String          GetName() const                         { return aName; }

    static BOOL     HasBasicManager( const SvStorage& rStorage );
    static BOOL     CopyBasicData( SvStorage* pFrom, const String& rSourceURL, SvStorage* pTo);
    void            Merge(  SvStorage& rFromStorage );

    USHORT          GetLibCount() const;
    StarBASIC*      GetStdLib() const;
    StarBASIC*      GetLib( USHORT nLib ) const;
    StarBASIC*      GetLib( const String& rName ) const;
    USHORT          GetLibId( const String& rName ) const;
    USHORT          GetLibId( StarBASIC* pLib ) const;
    BOOL            HasLib( const String& rName ) const;

    void            Store( SvStorage& rStorage );
    void            Store( SvStorage& rStorage, BOOL bStoreLibs );

    BOOL            SetLibName( USHORT nLib, const String& rName );
    String          GetLibName( USHORT nLib );

    BOOL            SetLibStorageName( USHORT nLib, const String& rName );
    String          GetLibStorageName( USHORT nLib );
    String          GetRelLibStorageName( USHORT nLib );

    BOOL            IsLibLoaded( USHORT nLib ) const;
    BOOL            LoadLib( USHORT nLib );
    BOOL            UnloadLib( USHORT nLib );
    BOOL            StoreLib( USHORT nLib ) const;
    BOOL            RemoveLib( USHORT nLib );
    BOOL            RemoveLib( USHORT nLib, BOOL bDelBasicFromStorage );

    BOOL            IsReference( USHORT nLib );
    BOOL            IsExtern( USHORT nLib );

    StarBASIC*      CreateLib( const String& rLibName );
    // For XML import/export:
    StarBASIC*      CreateLib( const String& rLibName, const String& Password,
                               const String& ExternalSourceURL, const String& LinkTargetURL );
    StarBASIC*      AddLib( SvStorage& rStorage, const String& rLibName, BOOL bReference );
    void            AddLib( StarBASIC* pLib );
    BOOL            MoveLib( USHORT nLib, USHORT nNewPos );

    BOOL            HasPassword( USHORT nLib ) const;
    String          GetPassword( USHORT nLib ) const;
    void            SetPassword( USHORT nLib, const String& rNewPassword );

    // Der BasicManager gibt die Basics auch raus, wenn das Passwort nicht
    // geprueft wurde, da man auch ohne Passwort mit der Lib arbeiten kann.
    // Es ist Sache der App, was Sie dem Anwender ohne Passwort nicht gestattet,
    // also z.B. das Betrachten der Source oder das Anzeigen/Loeschen von Modulen.
    BOOL            IsPasswordVerified( USHORT nLib ) const;
    void            SetPasswordVerified( USHORT nLib );

    // Modify-Flag wird nur beim Speichern zurueckgesetzt.
    BOOL            IsModified() const;
    BOOL            IsBasicModified() const;
    BOOL            IsManagerModified() const { return bBasMgrModified; }

    BOOL            HasErrors();
    void            ClearErrors();
    BasicError*     GetFirstError();
    BasicError*     GetNextError();
};

#endif  //_SFX_BASMGR_HXX
<commit_msg>Added member for new dialog container<commit_after>/*************************************************************************
 *
 *  $RCSfile: basmgr.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: ab $ $Date: 2001-02-09 16:16:11 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SFX_BASMGR_HXX
#define _SFX_BASMGR_HXX

#ifndef _BASMGR_HXX_
#include <basic/basmgr.hxx>
#endif

#ifndef _COM_SUN_STAR_SCRIPT_XSTARBASICACCESS_HPP_
#include <com/sun/star/script/XStarBasicAccess.hpp>
#endif

// Basic XML Import/Export
com::sun::star::uno::Reference< com::sun::star::script::XStarBasicAccess >
    getStarBasicAccess( BasicManager* pMgr );

#if SUPD>620
class SfxDialogContainer;
#endif

class SfxBasicManager : public BasicManager
{
    friend class LibraryContainer_Impl;

private:
    BasicLibs*          pLibs;
    BasicErrorManager*  pErrorMgr;

    String              aName;
    String              aStorageName;
    BOOL                bBasMgrModified;

#if SUPD>620
    SfxDialogContainer* pDialogContainer;
#endif

    void                Init();

protected:
    BOOL            ImpStoreLibary( StarBASIC* pLib, SvStorage& rStorage ) const;
    BOOL            ImpLoadLibary( BasicLibInfo* pLibInfo ) const;
    BOOL            ImpLoadLibary( BasicLibInfo* pLibInfo, SvStorage* pCurStorage, BOOL bInfosOnly = FALSE ) const;
    void            ImpCreateStdLib( StarBASIC* pParentFromStdLib );
    void            ImpMgrNotLoaded(  const String& rStorageName  );
    BasicLibInfo*   CreateLibInfo();
    void            LoadBasicManager( SvStorage& rStorage, BOOL bLoadBasics = TRUE );
    void            LoadOldBasicManager( SvStorage& rStorage );
    BOOL            ImplLoadBasic( SvStream& rStrm, StarBASICRef& rOldBasic ) const;
    void            ImplGetPassword( USHORT nLib ) const;
    BOOL            ImplEncryptStream( SvStream& rStream ) const;
    BasicLibInfo*   FindLibInfo( StarBASIC* pBasic ) const;
    void            CheckModules( StarBASIC* pBasic, BOOL bReference ) const;
    void            SetFlagToAllLibs( short nFlag, BOOL bSet ) const;
                    SfxBasicManager();  // Nur zum anpassen von Pfaden bei 'Speichern unter'.

public:
                    TYPEINFO();
                    SfxBasicManager( SvStorage& rStorage, StarBASIC* pParentFromStdLib = NULL, String* pLibPath = NULL );
                    SfxBasicManager( StarBASIC* pStdLib, String* pLibPath = NULL );
                    ~SfxBasicManager();

    void            SetStorageName( const String& rName )   { aStorageName = rName; }
    String          GetStorageName() const                  { return aStorageName; }
    void            SetName( const String& rName )          { aName = rName; }
    String          GetName() const                         { return aName; }

    static BOOL     HasBasicManager( const SvStorage& rStorage );
    static BOOL     CopyBasicData( SvStorage* pFrom, const String& rSourceURL, SvStorage* pTo);
    void            Merge(  SvStorage& rFromStorage );

    USHORT          GetLibCount() const;
    StarBASIC*      GetStdLib() const;
    StarBASIC*      GetLib( USHORT nLib ) const;
    StarBASIC*      GetLib( const String& rName ) const;
    USHORT          GetLibId( const String& rName ) const;
    USHORT          GetLibId( StarBASIC* pLib ) const;
    BOOL            HasLib( const String& rName ) const;

    void            Store( SvStorage& rStorage );
    void            Store( SvStorage& rStorage, BOOL bStoreLibs );

    BOOL            SetLibName( USHORT nLib, const String& rName );
    String          GetLibName( USHORT nLib );

    BOOL            SetLibStorageName( USHORT nLib, const String& rName );
    String          GetLibStorageName( USHORT nLib );
    String          GetRelLibStorageName( USHORT nLib );

    BOOL            IsLibLoaded( USHORT nLib ) const;
    BOOL            LoadLib( USHORT nLib );
    BOOL            UnloadLib( USHORT nLib );
    BOOL            StoreLib( USHORT nLib ) const;
    BOOL            RemoveLib( USHORT nLib );
    BOOL            RemoveLib( USHORT nLib, BOOL bDelBasicFromStorage );

    BOOL            IsReference( USHORT nLib );
    BOOL            IsExtern( USHORT nLib );

    StarBASIC*      CreateLib( const String& rLibName );
    // For XML import/export:
    StarBASIC*      CreateLib( const String& rLibName, const String& Password,
                               const String& ExternalSourceURL, const String& LinkTargetURL );
    StarBASIC*      AddLib( SvStorage& rStorage, const String& rLibName, BOOL bReference );
    void            AddLib( StarBASIC* pLib );
    BOOL            MoveLib( USHORT nLib, USHORT nNewPos );

    BOOL            HasPassword( USHORT nLib ) const;
    String          GetPassword( USHORT nLib ) const;
    void            SetPassword( USHORT nLib, const String& rNewPassword );

    // Der BasicManager gibt die Basics auch raus, wenn das Passwort nicht
    // geprueft wurde, da man auch ohne Passwort mit der Lib arbeiten kann.
    // Es ist Sache der App, was Sie dem Anwender ohne Passwort nicht gestattet,
    // also z.B. das Betrachten der Source oder das Anzeigen/Loeschen von Modulen.
    BOOL            IsPasswordVerified( USHORT nLib ) const;
    void            SetPasswordVerified( USHORT nLib );

    // Modify-Flag wird nur beim Speichern zurueckgesetzt.
    BOOL            IsModified() const;
    BOOL            IsBasicModified() const;
    BOOL            IsManagerModified() const { return bBasMgrModified; }

    BOOL            HasErrors();
    void            ClearErrors();
    BasicError*     GetFirstError();
    BasicError*     GetNextError();
};

#endif  //_SFX_BASMGR_HXX
<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_FUNCTION_AFFINEPARAMETRIC_CHECKERBOARD_HH
#define DUNE_STUFF_FUNCTION_AFFINEPARAMETRIC_CHECKERBOARD_HH

#include <memory>
#include <vector>

#include <dune/common/shared_ptr.hh>

#include <dune/stuff/common/parameter.hh>
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/function/checkerboard.hh>

#include "../interface.hh"
#include "../checkerboard.hh"

namespace Dune {
namespace Stuff {

// forward, to allow for specialization
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols >
class AffineParametricFunctionCheckerboard;

template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class AffineParametricFunctionCheckerboard< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >
  : public AffineParametricFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >
{
  typedef AffineParametricFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > BaseType;
public:
  typedef AffineParametricFunctionCheckerboard< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > ThisType;

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const int                            dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType       DomainType;
  typedef typename BaseType::RangeFieldType   RangeFieldType;
//  static const int                            dimRange = BaseType::dimRange;
  typedef typename BaseType::RangeType        RangeType;

  typedef typename BaseType::ParamFieldType ParamFieldType;
  typedef typename BaseType::ParamType      ParamType;

  typedef typename BaseType::ComponentType    ComponentType;
  typedef typename BaseType::CoefficientType  CoefficientType;

  static const std::string id()
  {
    return BaseType::id() + ".checkerboard";
  }

  AffineParametricFunctionCheckerboard(const DomainType& _lowerLeft,
                                       const DomainType& _upperRight,
                                       const std::vector< size_t >& _numElements,
                                       const std::vector< ParamType >& _paramRange,
                                       const std::string _name = id())
    : paramSize_(1)
    , paramRange_(_paramRange)
    , name_(_name)
  {
    // build SeparableCheckerboard structure
    assert(int(_numElements.size()) >= dimDomain && "Please provide at least as many number of elements as dimensions!");
    for (int dd = 0; dd < dimDomain; ++dd) {
      assert(_lowerLeft[dd] <= _upperRight[dd]
             && "Given '_lowerLeft' has to be piecewise <= compared to given '_upperRight'!");
      assert(_numElements[dd] > 0 && "Please provide a positive number of elements per dimension!");
      paramSize_ *= _numElements[dd];
    }
    assert(_paramRange.size() == 2 && "Vector has wrong size!");
    assert(_paramRange[0].size() == paramSize_ && "Vector has wrong size!");
    assert(_paramRange[1].size() == paramSize_ && "Vector has wrong size!");
    for (size_t qq = 0; qq < paramSize_; ++qq) {
      assert(paramRange_[0][qq] <= paramRange_[1][qq]
          && "Given minimal parameter has to be piecewise <= maximum parameter!");
    }
    // create the coefficients and components
    typedef FunctionCheckerboard< DomainFieldType, dimDomain, RangeFieldType, 1 > NonparametricType;
    for (size_t ii = 0; ii < paramSize_; ++ii) {
      std::vector< RangeType > indicator(paramSize_, RangeType(0));
      indicator[ii] = RangeType(1);
      components_.emplace_back(new NonparametricType(_lowerLeft, _upperRight, _numElements, indicator));
      coefficients_.emplace_back(new CoefficientType("mu[" + DSC::toString(ii) + "]"));
    } // create the coefficients and components
    parameterExplanation_ = std::vector< std::string >(paramSize_, "");
    // create the explanations
    for (size_t ii = 0; ii < _numElements[0]; ++ii) {
      if (dimDomain == 1)
        parameterExplanation_[ii] = "value_in_subdomain_" + DSC::toString(ii);
      else
        for (unsigned int jj = 0; jj < _numElements[1]; ++jj) {
          if (dimDomain == 2)
            parameterExplanation_[ii + jj*_numElements[0]] = "value_in_subdomain_"
                + DSC::toString(ii)
                + "_" + DSC::toString(jj);
          else
            for (unsigned int kk = 0; kk < _numElements[2]; ++kk) {
              parameterExplanation_[ii + jj*_numElements[0] + kk*_numElements[0]*_numElements[1]] = "value_in_subdomain_"
                  + DSC::toString(ii)
                  + "_" + DSC::toString(jj)
                  + "_" + DSC::toString(kk);
            }
        }
    }
  } // AffineParametricFunctionCheckerboard(...)

  static Dune::ParameterTree defaultSettings(const std::string subName = "")
  {
    Dune::ParameterTree description;
    description["lowerLeft"] = "[0.0; 0.0; 0.0]";
    description["upperRight"] = "[1.0; 1.0; 1.0]";
    description["numElements"] = "[2; 2; 2]";
    description["paramMin"] = "[1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0]";
    description["paramMax"] = "[10.0; 20.0; 30.0; 40.0; 50.0; 60.0; 70.0; 80.0]";
    description["name"] = id();
    if (subName.empty())
      return description;
    else {
      DSC::ExtendedParameterTree extendedDescription;
      extendedDescription.add(description, subName);
      return extendedDescription;
    }
  } // ... defaultSettings(...)

  static ThisType* create(const DSC::ExtendedParameterTree settings)
  {
    // get data
    const std::string _name = settings.get< std::string >("name", id());
    const std::vector< DomainFieldType > lowerLefts = settings.getVector("lowerLeft", DomainFieldType(0), dimDomain);
    const std::vector< DomainFieldType > upperRights = settings.getVector("upperRight",
                                                                             DomainFieldType(1),
                                                                             dimDomain);
    const std::vector< size_t > numElements = settings.getVector("numElements", size_t(1), dimDomain);
    // get paramSize
    size_t paramSize = 1u;
    for (int dd = 0; dd < dimDomain; ++dd) {
      assert(numElements[dd] > 0 && "Please provide positive number of elements per dim!");
      paramSize *= numElements[dd];
    }
    const std::vector< ParamFieldType > paramMins = settings.getVector("paramMin",
                                                                          ParamFieldType(1),
                                                                          paramSize);
    const std::vector< ParamFieldType > paramMaxs = settings.getVector("paramMax",
                                                                          ParamFieldType(1),
                                                                          paramSize);
    // convert and leave the checks to the constructor
    DomainType lowerLeft;
    DomainType upperRight;
    for (int dd = 0; dd < dimDomain; ++dd) {
      lowerLeft[dd] = lowerLefts[dd];
      upperRight[dd] = upperRights[dd];
    }
    ParamType paramMin(paramSize);
    ParamType paramMax(paramSize);
    for (size_t qq = 0; qq < paramSize; ++qq) {
      paramMin[qq] = paramMins[qq];
      paramMax[qq] = paramMaxs[qq];
    }
    const std::vector< ParamType > paramRange = {paramMin, paramMax};
    // create and return
    return new ThisType(lowerLeft, upperRight, numElements, paramRange, _name);
  } // ... create(...)

  virtual int order() const
  {
    return 0;
  }

  virtual std::string name() const
  {
    return name_;
  }

  virtual size_t paramSize() const
  {
    return paramSize_;
  }

  virtual const std::vector< ParamType >& paramRange() const
  {
    return paramRange_;
  }

  virtual const std::vector< std::string >& paramExplanation() const
  {
    return parameterExplanation_;
  }

  virtual const std::vector< std::shared_ptr< const ComponentType > >& components() const
  {
    return components_;
  }

  virtual const std::vector< std::shared_ptr< const CoefficientType > >& coefficients() const
  {
    return coefficients_;
  }

  virtual void evaluate(const DomainType& _x, const ParamType& _mu, RangeType& _ret) const
  {
    assert(_mu.size() == paramSize());
    _ret = RangeFieldType(0);
    RangeType tmpComponentValue;
    for (unsigned int qq = 0; qq < paramSize_; ++qq) {
      components_[qq]->evaluate(_x, tmpComponentValue);
      tmpComponentValue *= coefficients_[qq]->evaluate(_mu);
      _ret += tmpComponentValue;
    }
  } // virtual void evaluate(const DomainType& x, const ParamType& mu, RangeType& ret) const

private:
  unsigned int paramSize_;
  std::vector< ParamType > paramRange_;
  std::string name_;
  std::vector< std::string > parameterExplanation_;
  std::vector< std::shared_ptr< const ComponentType > > components_;
  std::vector< std::shared_ptr< const CoefficientType > > coefficients_;
}; // class AffineParametricFunctionCheckerboard

} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_FUNCTION_AFFINEPARAMETRIC_CHECKERBOARD_HH
<commit_msg>[function.affineparametric.checkerboard] let rangeDimCOls default to 1<commit_after>#ifndef DUNE_STUFF_FUNCTION_AFFINEPARAMETRIC_CHECKERBOARD_HH
#define DUNE_STUFF_FUNCTION_AFFINEPARAMETRIC_CHECKERBOARD_HH

#include <memory>
#include <vector>

#include <dune/common/shared_ptr.hh>

#include <dune/stuff/common/parameter.hh>
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/function/checkerboard.hh>

#include "../interface.hh"
#include "../checkerboard.hh"

namespace Dune {
namespace Stuff {

// forward, to allow for specialization
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols = 1 >
class AffineParametricFunctionCheckerboard;

template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class AffineParametricFunctionCheckerboard< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >
  : public AffineParametricFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >
{
  typedef AffineParametricFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > BaseType;
public:
  typedef AffineParametricFunctionCheckerboard< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > ThisType;

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const int                            dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType       DomainType;
  typedef typename BaseType::RangeFieldType   RangeFieldType;
//  static const int                            dimRange = BaseType::dimRange;
  typedef typename BaseType::RangeType        RangeType;

  typedef typename BaseType::ParamFieldType ParamFieldType;
  typedef typename BaseType::ParamType      ParamType;

  typedef typename BaseType::ComponentType    ComponentType;
  typedef typename BaseType::CoefficientType  CoefficientType;

  static const std::string id()
  {
    return BaseType::id() + ".checkerboard";
  }

  AffineParametricFunctionCheckerboard(const DomainType& _lowerLeft,
                                       const DomainType& _upperRight,
                                       const std::vector< size_t >& _numElements,
                                       const std::vector< ParamType >& _paramRange,
                                       const std::string _name = id())
    : paramSize_(1)
    , paramRange_(_paramRange)
    , name_(_name)
  {
    // build SeparableCheckerboard structure
    assert(int(_numElements.size()) >= dimDomain && "Please provide at least as many number of elements as dimensions!");
    for (int dd = 0; dd < dimDomain; ++dd) {
      assert(_lowerLeft[dd] <= _upperRight[dd]
             && "Given '_lowerLeft' has to be piecewise <= compared to given '_upperRight'!");
      assert(_numElements[dd] > 0 && "Please provide a positive number of elements per dimension!");
      paramSize_ *= _numElements[dd];
    }
    assert(_paramRange.size() == 2 && "Vector has wrong size!");
    assert(_paramRange[0].size() == paramSize_ && "Vector has wrong size!");
    assert(_paramRange[1].size() == paramSize_ && "Vector has wrong size!");
    for (size_t qq = 0; qq < paramSize_; ++qq) {
      assert(paramRange_[0][qq] <= paramRange_[1][qq]
          && "Given minimal parameter has to be piecewise <= maximum parameter!");
    }
    // create the coefficients and components
    typedef FunctionCheckerboard< DomainFieldType, dimDomain, RangeFieldType, 1 > NonparametricType;
    for (size_t ii = 0; ii < paramSize_; ++ii) {
      std::vector< RangeType > indicator(paramSize_, RangeType(0));
      indicator[ii] = RangeType(1);
      components_.emplace_back(new NonparametricType(_lowerLeft, _upperRight, _numElements, indicator));
      coefficients_.emplace_back(new CoefficientType("mu[" + DSC::toString(ii) + "]"));
    } // create the coefficients and components
    parameterExplanation_ = std::vector< std::string >(paramSize_, "");
    // create the explanations
    for (size_t ii = 0; ii < _numElements[0]; ++ii) {
      if (dimDomain == 1)
        parameterExplanation_[ii] = "value_in_subdomain_" + DSC::toString(ii);
      else
        for (unsigned int jj = 0; jj < _numElements[1]; ++jj) {
          if (dimDomain == 2)
            parameterExplanation_[ii + jj*_numElements[0]] = "value_in_subdomain_"
                + DSC::toString(ii)
                + "_" + DSC::toString(jj);
          else
            for (unsigned int kk = 0; kk < _numElements[2]; ++kk) {
              parameterExplanation_[ii + jj*_numElements[0] + kk*_numElements[0]*_numElements[1]] = "value_in_subdomain_"
                  + DSC::toString(ii)
                  + "_" + DSC::toString(jj)
                  + "_" + DSC::toString(kk);
            }
        }
    }
  } // AffineParametricFunctionCheckerboard(...)

  static Dune::ParameterTree defaultSettings(const std::string subName = "")
  {
    Dune::ParameterTree description;
    description["lowerLeft"] = "[0.0; 0.0; 0.0]";
    description["upperRight"] = "[1.0; 1.0; 1.0]";
    description["numElements"] = "[2; 2; 2]";
    description["paramMin"] = "[1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0]";
    description["paramMax"] = "[10.0; 20.0; 30.0; 40.0; 50.0; 60.0; 70.0; 80.0]";
    description["name"] = id();
    if (subName.empty())
      return description;
    else {
      DSC::ExtendedParameterTree extendedDescription;
      extendedDescription.add(description, subName);
      return extendedDescription;
    }
  } // ... defaultSettings(...)

  static ThisType* create(const DSC::ExtendedParameterTree settings)
  {
    // get data
    const std::string _name = settings.get< std::string >("name", id());
    const std::vector< DomainFieldType > lowerLefts = settings.getVector("lowerLeft", DomainFieldType(0), dimDomain);
    const std::vector< DomainFieldType > upperRights = settings.getVector("upperRight",
                                                                             DomainFieldType(1),
                                                                             dimDomain);
    const std::vector< size_t > numElements = settings.getVector("numElements", size_t(1), dimDomain);
    // get paramSize
    size_t paramSize = 1u;
    for (int dd = 0; dd < dimDomain; ++dd) {
      assert(numElements[dd] > 0 && "Please provide positive number of elements per dim!");
      paramSize *= numElements[dd];
    }
    const std::vector< ParamFieldType > paramMins = settings.getVector("paramMin",
                                                                          ParamFieldType(1),
                                                                          paramSize);
    const std::vector< ParamFieldType > paramMaxs = settings.getVector("paramMax",
                                                                          ParamFieldType(1),
                                                                          paramSize);
    // convert and leave the checks to the constructor
    DomainType lowerLeft;
    DomainType upperRight;
    for (int dd = 0; dd < dimDomain; ++dd) {
      lowerLeft[dd] = lowerLefts[dd];
      upperRight[dd] = upperRights[dd];
    }
    ParamType paramMin(paramSize);
    ParamType paramMax(paramSize);
    for (size_t qq = 0; qq < paramSize; ++qq) {
      paramMin[qq] = paramMins[qq];
      paramMax[qq] = paramMaxs[qq];
    }
    const std::vector< ParamType > paramRange = {paramMin, paramMax};
    // create and return
    return new ThisType(lowerLeft, upperRight, numElements, paramRange, _name);
  } // ... create(...)

  virtual int order() const
  {
    return 0;
  }

  virtual std::string name() const
  {
    return name_;
  }

  virtual size_t paramSize() const
  {
    return paramSize_;
  }

  virtual const std::vector< ParamType >& paramRange() const
  {
    return paramRange_;
  }

  virtual const std::vector< std::string >& paramExplanation() const
  {
    return parameterExplanation_;
  }

  virtual const std::vector< std::shared_ptr< const ComponentType > >& components() const
  {
    return components_;
  }

  virtual const std::vector< std::shared_ptr< const CoefficientType > >& coefficients() const
  {
    return coefficients_;
  }

  virtual void evaluate(const DomainType& _x, const ParamType& _mu, RangeType& _ret) const
  {
    assert(_mu.size() == paramSize());
    _ret = RangeFieldType(0);
    RangeType tmpComponentValue;
    for (unsigned int qq = 0; qq < paramSize_; ++qq) {
      components_[qq]->evaluate(_x, tmpComponentValue);
      tmpComponentValue *= coefficients_[qq]->evaluate(_mu);
      _ret += tmpComponentValue;
    }
  } // virtual void evaluate(const DomainType& x, const ParamType& mu, RangeType& ret) const

private:
  unsigned int paramSize_;
  std::vector< ParamType > paramRange_;
  std::string name_;
  std::vector< std::string > parameterExplanation_;
  std::vector< std::shared_ptr< const ComponentType > > components_;
  std::vector< std::shared_ptr< const CoefficientType > > coefficients_;
}; // class AffineParametricFunctionCheckerboard

} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_FUNCTION_AFFINEPARAMETRIC_CHECKERBOARD_HH
<|endoftext|>