<commit_before>// meta_programming.cpp: playground to experiment with meta programming techniques to generalize functions and algorithms
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include "common.hpp"
#include <complex>

// when you define POSIT_VERBOSE_OUTPUT executing an ADD the code will print intermediate results
//#define POSIT_VERBOSE_OUTPUT
#define POSIT_TRACE_CONVERSION
// enable posit arithmetic exceptions
#define POSIT_THROW_ARITHMETIC_EXCEPTION 1
#include <universal/posit/posit>

int main(int argc, char** argv)
try {
	using namespace sw::unum;
	bool bSuccess = true;

	posit<32, 2> x(1.0), y(-1.0), p(0);
	std::complex< posit<32, 2> > c(x,y),d;

	return (bSuccess ? EXIT_SUCCESS : EXIT_FAILURE);
}
catch (char const* msg) {
	std::cerr << msg << std::endl;
	return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
	std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const quire_exception& err) {
	std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
	std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
	std::cerr << "Uncaught runtime exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (...) {
	std::cerr << "Caught unknown exception" << std::endl;
	return EXIT_FAILURE;
}
<commit_msg>WIP: meta programming to dispatch depending on type<commit_after>// meta_programming.cpp: playground to experiment with meta programming techniques to generalize functions and algorithms
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include "common.hpp"
#include <complex>

// when you define POSIT_VERBOSE_OUTPUT executing an ADD the code will print intermediate results
//#define POSIT_VERBOSE_OUTPUT
#define POSIT_TRACE_CONVERSION
// enable posit arithmetic exceptions
#define POSIT_THROW_ARITHMETIC_EXCEPTION 1
#include <universal/posit/posit>

template<typename T>
struct hasSerialize {
	typedef char yes[1];
	typedef char no[2];

	// helper to determine if serialize is a function
	template<typename T, T function>
	struct reallyHas;

	template<typename T> static yes& test(reallyHas<std::string(T::*)(), &T::serialize>* /*unused*/) {}
	template<typename T> static yes& test(reallyHas<std::string(T::*)() const, &T::serialize>* /*unused*/) {}

	template<typename T> static no& test(...) {}

	// constant used as return value for the test
	static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};

struct A {};

std::string to_string(const A& a) {
	return "I am an A";
}

struct B {
	std::string serialize() const {
		return "I am a B";
	}
};

struct C {
	std::string serialize;
};

std::string to_string(const C& c) {
	return "I am a C";
}

namespace sw {
	// typeless struct, will always fail substitution
	template<bool b, typename T = void>
	struct enable_if {};

	// specialization for type T
	template<typename T>
	struct enable_if<true, T> {
		using type = T;
	};

	template<typename T>
	typename enable_if<hasSerialize<T>::value, std::string>::type serialize(const T& obj) {
		return obj.serialize();
	}
	template<typename T>
	typename enable_if<!hasSerialize<T>::value, std::string>::type serialize(const T& obj) {
		return to_string(obj);
	}
}

int main(int argc, char** argv)
try {
	using namespace std;
	bool bSuccess = true;

	A a;
	B b;
	C c;

	/* goal
	cout << serialize(a) << endl;
	cout << serialize(b) << endl;
	cout << serialize(c) << endl;
	*/

	cout << hasSerialize<A>::value << endl;
	cout << hasSerialize<B>::value << endl;
	cout << hasSerialize<C>::value << endl;

	// pedantic
	sw::enable_if<true, int>::type t1; // type t1 is an int
	sw::enable_if<hasSerialize<B>::value, int>::type t2; // t2 is an int
	// enable_if<false, int>::type t3;  doesn't compile as enable_if<false, ...> doesn't have a type type
	// enable_if<hasSerialize<A>::value, int>::type t4; doesn't compile as enable_if<false, ...> doesn't have a type type

	// with enable_if we have the indirection to dispatch the right function: serialize or to_string
	cout << sw::serialize(a) << endl;
	cout << sw::serialize(b) << endl;
	cout << sw::serialize(c) << endl;

	return (bSuccess ? EXIT_SUCCESS : EXIT_FAILURE);
}
catch (char const* msg) {
	std::cerr << msg << std::endl;
	return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
	std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const quire_exception& err) {
	std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
	std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
	std::cerr << "Uncaught runtime exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (...) {
	std::cerr << "Caught unknown exception" << std::endl;
	return EXIT_FAILURE;
}
<|endoftext|>


<commit_before>//
// Created by ZhangMing on 02-26-17
//

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "function.h"
#include <QDebug>
#include <QUrl>
#include <QDesktopServices>
#include <QMessageBox>
#include <QInputDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_ServiceHub_triggered()
{
    const QUrl url("http://hub.hust.edu.cn/index.jsp");
    qDebug() << url.scheme();
    qDebug() << url.port();
    QDesktopServices::openUrl(url);
}

void MainWindow::on_ServiceHubEmail_triggered()
{
    const QUrl url("https://mail.hust.edu.cn/");
    qDebug() << url.scheme();
    qDebug() << url.port();
    QDesktopServices::openUrl(url);
}

void MainWindow::on_ServiceGithub_triggered()
{
    const QUrl url("https://github.com/");
    qDebug() << url.scheme();
    qDebug() << url.port();
    QDesktopServices::openUrl(url);
}

void MainWindow::on_FunCourseTree_triggered()
{
    CourseTree *p;
    if(BuildCourseTree() == false)
    {
        QMessageBox::information(this,"error","No File");
        return;
    }
    else
    {
        bool ok;
        QString name = QInputDialog::getText(NULL,QObject::tr("查询"),QObject::tr("请输入正确课程名"),QLineEdit::Normal,QString(),&ok);
        if(!ok)// click cancle
            return;
        // click ok
        if(name.isEmpty())
        {
            QMessageBox::information(this,"error","输入为空");
            return;
        }
        else if((p = QueryCourse(name)) == nullptr)
        {
            QMessageBox::information(this,"error","查无此课程");
        }
        else
        {
            //Web Page,use p
        }
    }
}
<commit_msg>Update mainwindow.cpp<commit_after>//
// Created by ZhangMing on 02-26-17
//

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "function.h"
#include <QDebug>
#include <QUrl>
#include <QDesktopServices>
#include <QMessageBox>
#include <QInputDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_ServiceHub_triggered()
{
    const QUrl url("http://hub.hust.edu.cn/index.jsp");
    qDebug() << url.scheme();
    qDebug() << url.port();
    QDesktopServices::openUrl(url);
}

void MainWindow::on_ServiceHubEmail_triggered()
{
    const QUrl url("https://mail.hust.edu.cn/");
    qDebug() << url.scheme();
    qDebug() << url.port();
    QDesktopServices::openUrl(url);
}

void MainWindow::on_ServiceGithub_triggered()
{
    const QUrl url("https://github.com/");
    qDebug() << url.scheme();
    qDebug() << url.port();
    QDesktopServices::openUrl(url);
}

void MainWindow::on_FunCourseTree_triggered()
{
    CourseTree *p;
    if(BuildCourseTree() == false)
    {
        QMessageBox::information(this,"error","No File");
        return;
    }
    else
    {
        bool ok;
        QString name = QInputDialog::getText(NULL,QObject::tr("查询"),QObject::tr("请输入正确课程名"),QLineEdit::Normal,QString(),&ok);
        if(!ok)// click cancle
            return;
        // click ok
        if(name.isEmpty())
        {
            QMessageBox::information(this,"error","输入为空");
            return;
        }
        else if((p = QueryCourse(name)) == nullptr)
        {
            QMessageBox::information(this,"error","查无此课程");
            return;
        }
        else
        {
            //Web Page,use p
        }
    }
}
<|endoftext|>


<commit_before>//
// Created by monty on 23/11/15.
//

#include <GLES2/gl2.h>
#include <android/log.h>

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

#include <string>
#include "GLES2Lesson.h"
#include "NdkGlue.h"

GLint GLES2Lesson::vertexAttributePosition = 0;
GLint GLES2Lesson::modelMatrixAttributePosition = 0;
GLint GLES2Lesson::projectionMatrixAttributePosition = 0;
GLuint GLES2Lesson::gProgram = 0;

//Counter Clockwise
float GLES2Lesson::triangleVertices[] = {
//     1
//    / \
//   /   \
// 2/____ \3

        0.0f, 1.0f, 0.0f,
        -1.0f, -1.0f, 0.0f,
        1.0f, -1.0f, 0.0f
};

float GLES2Lesson::squareVertices[]{
//  2___1
//  |\  |
//  | \ |
//  |___3
        1.0f, 1.0f, 0.0f,
        -1.0f, 1.0f, 0.0f,
        1.0f, -1.0f, 0.0f,
//  2____
//  |\  |
//  | \ |
//  3___1
        1.0f, -1.0f, 0.0f,
        -1.0f, 1.0f, 0.0f,
        -1.0f, -1.0f, 0.0f
};

//start off as identity - late we will init it with proper values.
glm::mat4 GLES2Lesson::triangleTransformMatrix = glm::mat4( 1.0f );
glm::mat4 GLES2Lesson::squareTransformMatrix = glm::mat4( 1.0f );
glm::mat4 GLES2Lesson::projectionMatrix = glm::mat4( 1.0f );

extern void printGLString(const char *name, GLenum s) {
    const char *v = (const char *) glGetString(s);
    LOGI("GL %s = %s\n", name, v);
}

extern void checkGlError(const char *op) {
    for (GLint error = glGetError(); error; error = glGetError()) {
        LOGI("after %s() glError (0x%x)\n", op, error);
    }
}

GLuint loadShader(GLenum shaderType, const char *pSource) {
    GLuint shader = glCreateShader(shaderType);
    if (shader) {
        glShaderSource(shader, 1, &pSource, NULL);
        glCompileShader(shader);
        GLint compiled = 0;
        glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
        if (!compiled) {
            GLint infoLen = 0;
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
            if (infoLen) {
                char *buf = (char *) malloc(infoLen);
                if (buf) {
                    glGetShaderInfoLog(shader, infoLen, NULL, buf);
                    LOGE("Could not compile shader %d:\n%s\n", shaderType, buf);
                    free(buf);
                }
                glDeleteShader(shader);
                shader = 0;
            }
        }
    }
    return shader;
}

GLuint createProgram(const char *pVertexSource, const char *pFragmentSource) {
    GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource);
    if (!vertexShader) {
        return 0;
    }

    GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource);
    if (!pixelShader) {
        return 0;
    }

    GLuint program = glCreateProgram();
    if (program) {
        glAttachShader(program, vertexShader);
        checkGlError("glAttachShader");
        glAttachShader(program, pixelShader);
        checkGlError("glAttachShader");
        glLinkProgram(program);
        GLint linkStatus = GL_FALSE;
        glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
        if (linkStatus != GL_TRUE) {
            GLint bufLength = 0;
            glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
            if (bufLength) {
                char *buf = (char *) malloc(bufLength);
                if (buf) {
                    glGetProgramInfoLog(program, bufLength, NULL, buf);
                    LOGE("Could not link program:\n%s\n", buf);
                    free(buf);
                }
            }
            glDeleteProgram(program);
            program = 0;
        }
    }
    return program;
}

bool GLES2Lesson::init(float w, float h, const char* vertexShader,
                       const char* fragmentShader) {
    printGLString("Version", GL_VERSION);
    printGLString("Vendor", GL_VENDOR);
    printGLString("Renderer", GL_RENDERER);
    printGLString("Extensions", GL_EXTENSIONS);

    LOGI("setupGraphics(%d, %d)", w, h);
    GLES2Lesson::gProgram = createProgram(vertexShader, fragmentShader);

    if (!GLES2Lesson::gProgram) {
        LOGE("Could not create program.");
        return false;
    }

    GLES2Lesson::vertexAttributePosition = glGetAttribLocation(GLES2Lesson::gProgram, "aPosition");
    GLES2Lesson::modelMatrixAttributePosition = glGetUniformLocation(GLES2Lesson::gProgram,
                                                                     "uModel");

    GLES2Lesson::projectionMatrixAttributePosition = glGetUniformLocation(GLES2Lesson::gProgram,
                                                                          "uProjection");
    glEnableVertexAttribArray(vertexAttributePosition);

    glViewport(0, 0, w, h);
    checkGlError("glViewport");

    GLES2Lesson::triangleTransformMatrix = glm::translate( glm::mat4(1.0f), glm::vec3( -1.5f, 0.0f, -6.0f ) );

    GLES2Lesson::squareTransformMatrix = glm::translate( glm::mat4(1.0f), glm::vec3( 1.5f, 0.0f, -6.0f ) );
    GLES2Lesson::projectionMatrix = glm::perspective(45.0f, w / h, 0.1f, 100.0f );

    return true;
}

void GLES2Lesson::render() {
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    checkGlError("glClearColor");
    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
    checkGlError("glClear");

    glUseProgram(gProgram);
    checkGlError("glUseProgram");

    glUniformMatrix4fv(projectionMatrixAttributePosition, 1, false, &GLES2Lesson::projectionMatrix[ 0 ][ 0 ]);

    glUniformMatrix4fv(modelMatrixAttributePosition, 1, false,
                       &GLES2Lesson::triangleTransformMatrix[ 0 ][ 0 ]);
    glVertexAttribPointer(vertexAttributePosition, 3, GL_FLOAT, GL_FALSE, 0,
                          GLES2Lesson::triangleVertices);

    glDrawArrays(GL_TRIANGLES, 0, 3);

    glUniformMatrix4fv(modelMatrixAttributePosition, 1, false, &GLES2Lesson::squareTransformMatrix[ 0 ][ 0 ]);
    glVertexAttribPointer(vertexAttributePosition, 3, GL_FLOAT, GL_FALSE, 0,
                          GLES2Lesson::squareVertices);

    glDrawArrays(GL_TRIANGLES, 0, 6);
}

void GLES2Lesson::shutdown() {
    LOGI("Shutdown!\n");
}
<commit_msg>Fix types in logging format<commit_after>//
// Created by monty on 23/11/15.
//

#include <GLES2/gl2.h>
#include <android/log.h>

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

#include <string>
#include "GLES2Lesson.h"
#include "NdkGlue.h"

GLint GLES2Lesson::vertexAttributePosition = 0;
GLint GLES2Lesson::modelMatrixAttributePosition = 0;
GLint GLES2Lesson::projectionMatrixAttributePosition = 0;
GLuint GLES2Lesson::gProgram = 0;

//Counter Clockwise
float GLES2Lesson::triangleVertices[] = {
//     1
//    / \
//   /   \
// 2/____ \3

        0.0f, 1.0f, 0.0f,
        -1.0f, -1.0f, 0.0f,
        1.0f, -1.0f, 0.0f
};

float GLES2Lesson::squareVertices[]{
//  2___1
//  |\  |
//  | \ |
//  |___3
        1.0f, 1.0f, 0.0f,
        -1.0f, 1.0f, 0.0f,
        1.0f, -1.0f, 0.0f,
//  2____
//  |\  |
//  | \ |
//  3___1
        1.0f, -1.0f, 0.0f,
        -1.0f, 1.0f, 0.0f,
        -1.0f, -1.0f, 0.0f
};

//start off as identity - late we will init it with proper values.
glm::mat4 GLES2Lesson::triangleTransformMatrix = glm::mat4( 1.0f );
glm::mat4 GLES2Lesson::squareTransformMatrix = glm::mat4( 1.0f );
glm::mat4 GLES2Lesson::projectionMatrix = glm::mat4( 1.0f );

extern void printGLString(const char *name, GLenum s) {
    const char *v = (const char *) glGetString(s);
    LOGI("GL %s = %s\n", name, v);
}

extern void checkGlError(const char *op) {
    for (GLint error = glGetError(); error; error = glGetError()) {
        LOGI("after %s() glError (0x%x)\n", op, error);
    }
}

GLuint loadShader(GLenum shaderType, const char *pSource) {
    GLuint shader = glCreateShader(shaderType);
    if (shader) {
        glShaderSource(shader, 1, &pSource, NULL);
        glCompileShader(shader);
        GLint compiled = 0;
        glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
        if (!compiled) {
            GLint infoLen = 0;
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
            if (infoLen) {
                char *buf = (char *) malloc(infoLen);
                if (buf) {
                    glGetShaderInfoLog(shader, infoLen, NULL, buf);
                    LOGE("Could not compile shader %d:\n%s\n", shaderType, buf);
                    free(buf);
                }
                glDeleteShader(shader);
                shader = 0;
            }
        }
    }
    return shader;
}

GLuint createProgram(const char *pVertexSource, const char *pFragmentSource) {
    GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource);
    if (!vertexShader) {
        return 0;
    }

    GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource);
    if (!pixelShader) {
        return 0;
    }

    GLuint program = glCreateProgram();
    if (program) {
        glAttachShader(program, vertexShader);
        checkGlError("glAttachShader");
        glAttachShader(program, pixelShader);
        checkGlError("glAttachShader");
        glLinkProgram(program);
        GLint linkStatus = GL_FALSE;
        glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
        if (linkStatus != GL_TRUE) {
            GLint bufLength = 0;
            glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
            if (bufLength) {
                char *buf = (char *) malloc(bufLength);
                if (buf) {
                    glGetProgramInfoLog(program, bufLength, NULL, buf);
                    LOGE("Could not link program:\n%s\n", buf);
                    free(buf);
                }
            }
            glDeleteProgram(program);
            program = 0;
        }
    }
    return program;
}

bool GLES2Lesson::init(float w, float h, const char* vertexShader,
                       const char* fragmentShader) {
    printGLString("Version", GL_VERSION);
    printGLString("Vendor", GL_VENDOR);
    printGLString("Renderer", GL_RENDERER);
    printGLString("Extensions", GL_EXTENSIONS);

    LOGI("setupGraphics(%f, %f)", w, h);
    GLES2Lesson::gProgram = createProgram(vertexShader, fragmentShader);

    if (!GLES2Lesson::gProgram) {
        LOGE("Could not create program.");
        return false;
    }

    GLES2Lesson::vertexAttributePosition = glGetAttribLocation(GLES2Lesson::gProgram, "aPosition");
    GLES2Lesson::modelMatrixAttributePosition = glGetUniformLocation(GLES2Lesson::gProgram,
                                                                     "uModel");

    GLES2Lesson::projectionMatrixAttributePosition = glGetUniformLocation(GLES2Lesson::gProgram,
                                                                          "uProjection");
    glEnableVertexAttribArray(vertexAttributePosition);

    glViewport(0, 0, w, h);
    checkGlError("glViewport");

    GLES2Lesson::triangleTransformMatrix = glm::translate( glm::mat4(1.0f), glm::vec3( -1.5f, 0.0f, -6.0f ) );

    GLES2Lesson::squareTransformMatrix = glm::translate( glm::mat4(1.0f), glm::vec3( 1.5f, 0.0f, -6.0f ) );
    GLES2Lesson::projectionMatrix = glm::perspective(45.0f, w / h, 0.1f, 100.0f );

    return true;
}

void GLES2Lesson::render() {
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    checkGlError("glClearColor");
    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
    checkGlError("glClear");

    glUseProgram(gProgram);
    checkGlError("glUseProgram");

    glUniformMatrix4fv(projectionMatrixAttributePosition, 1, false, &GLES2Lesson::projectionMatrix[ 0 ][ 0 ]);

    glUniformMatrix4fv(modelMatrixAttributePosition, 1, false,
                       &GLES2Lesson::triangleTransformMatrix[ 0 ][ 0 ]);
    glVertexAttribPointer(vertexAttributePosition, 3, GL_FLOAT, GL_FALSE, 0,
                          GLES2Lesson::triangleVertices);

    glDrawArrays(GL_TRIANGLES, 0, 3);

    glUniformMatrix4fv(modelMatrixAttributePosition, 1, false, &GLES2Lesson::squareTransformMatrix[ 0 ][ 0 ]);
    glVertexAttribPointer(vertexAttributePosition, 3, GL_FLOAT, GL_FALSE, 0,
                          GLES2Lesson::squareVertices);

    glDrawArrays(GL_TRIANGLES, 0, 6);
}

void GLES2Lesson::shutdown() {
    LOGI("Shutdown!\n");
}
<|endoftext|>


<commit_before>/* The MIT License (MIT)

Copyright (c) 2013 QuantumCD

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

#include "stdafx.h"
#include <windows.h>
#include <string>
#include <vector>
#include <fstream>

// This little bit simply gets rid of the console window
#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")

int main(int argc, char* argv[])
{
	std::vector<std::wstring> parameters;
	std::wstring paramString;
	std::wstring applicationExecutable;

	// We start at argv[1] as that is the second parameter passed, etc.
	// The first is always the program itself (possibly a path instead).
	for (int i = 1; i < argc; i++)
	{
		// Convert to wide string
		std::string standardString(argv[i]);
		std::wstring wideString;

		// This is a handy way you can convert strings to wide strings ;)
		wideString.assign(standardString.begin(), standardString.end());

		parameters.push_back(wideString);
	}

	// C++11 ;)
	for (auto &str : parameters)
		paramString += L" " + str;

	std::ifstream configFileStream;
	configFileStream.open("RunAsAdmin.cfg", std::ifstream::in);

	// Make sure the file is open for reading.
	if (configFileStream.is_open())
	{
		std::string applicationNameFromConfig;
		std::getline(configFileStream, applicationNameFromConfig);

		std::wstring wApplicationNameFromConfig;
		wApplicationNameFromConfig.assign(applicationNameFromConfig.begin(), applicationNameFromConfig.end());

		std::ifstream checkIfExists(wApplicationNameFromConfig);

		// Make sure the config executable actually exists.
		if (checkIfExists)
		{
			applicationExecutable = wApplicationNameFromConfig;
		}
		else
		{
			MessageBox(NULL, L"Unable to locate suitable executable.\nCheck your configuration file.\n"
				L"(Have you created a configuration file?)",
				L"Run As Admin - Error", MB_OK | MB_ICONERROR);
			return -1;
		}

		std::string commandLineParametersFromConfig;
		std::getline(configFileStream, commandLineParametersFromConfig);

		// This is just a fallback. Use the provided parameters before anything else,
		// i.e. the ones passed to this application (argv)
		if (!commandLineParametersFromConfig.empty() && paramString.empty())
		{
			paramString.assign(commandLineParametersFromConfig.begin(), commandLineParametersFromConfig.end());
		}

		configFileStream.close();
	}
	else if (applicationExecutable.empty()) // This triggers if a) the file can't be opened and
											// b) there is no default file name provided in the source.
	{
		MessageBox(NULL, L"Unable to open configuration file.\n(Have you created a configuration file?)",
			L"Run As Admin - Error", MB_OK | MB_ICONERROR);

		return -2;
	}

	// This launches the application with the UAC prompt, and administrator rights are requested.
	ShellExecute(NULL, _T("RUNAS"), (LPCWSTR)applicationExecutable.c_str(), (LPCWSTR)paramString.c_str(), NULL,
		SW_SHOWNORMAL);

	return 0;
}

<commit_msg>Moved executable not found error.<commit_after>/* The MIT License (MIT)

Copyright (c) 2013 QuantumCD

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

#include "stdafx.h"
#include <windows.h>
#include <string>
#include <vector>
#include <fstream>

// This little bit simply gets rid of the console window
#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")

int main(int argc, char* argv[])
{
	std::vector<std::wstring> parameters;
	std::wstring paramString;
	std::wstring applicationExecutable;

	// We start at argv[1] as that is the second parameter passed, etc.
	// The first is always the program itself (possibly a path instead).
	for (int i = 1; i < argc; i++)
	{
		// Convert to wide string
		std::string standardString(argv[i]);
		std::wstring wideString;

		// This is a handy way you can convert strings to wide strings ;)
		wideString.assign(standardString.begin(), standardString.end());

		parameters.push_back(wideString);
	}

	// C++11 ;)
	for (auto &str : parameters)
		paramString += L" " + str;

	std::ifstream configFileStream;
	configFileStream.open("RunAsAdmin.cfg", std::ifstream::in);

	// Make sure the file is open for reading.
	if (configFileStream.is_open())
	{
		std::string applicationNameFromConfig;
		std::getline(configFileStream, applicationNameFromConfig);

		std::wstring wApplicationNameFromConfig;
		wApplicationNameFromConfig.assign(applicationNameFromConfig.begin(), applicationNameFromConfig.end());

		applicationExecutable = wApplicationNameFromConfig;

		std::string commandLineParametersFromConfig;
		std::getline(configFileStream, commandLineParametersFromConfig);

		// This is just a fallback. Use the provided parameters before anything else,
		// i.e. the ones passed to this application (argv)
		if (!commandLineParametersFromConfig.empty() && paramString.empty())
		{
			paramString.assign(commandLineParametersFromConfig.begin(), commandLineParametersFromConfig.end());
		}

		configFileStream.close();
	}
	else if (applicationExecutable.empty()) // This triggers if a) the file can't be opened and
											// b) there is no default file name provided in the source.
	{
		MessageBox(NULL, L"Unable to open configuration file.\n(Have you created a configuration file?)",
			L"Run As Admin - Error", MB_OK | MB_ICONERROR);

		return -2;
	}

	// This launches the application with the UAC prompt, and administrator rights are requested.
	HINSTANCE shellResult = ShellExecute(NULL, _T("RUNAS"), (LPCWSTR)applicationExecutable.c_str(), (LPCWSTR)paramString.c_str(), NULL,
		SW_SHOWNORMAL);

	int returnCode = (int)shellResult;

	// ShellExecute returns a value less than 32 if it fails
	if (returnCode < 32)
	{
		switch (returnCode)
		{
		case ERROR_FILE_NOT_FOUND:
			MessageBox(NULL, L"Could not find executable.", L"Run As Admin - Error", MB_OK | MB_ICONERROR);
		default:
			break;
		}
	}

	return 0;
}

<|endoftext|>


<commit_before>#include "Renderer.h"
#include <SFML/Graphics.hpp>
#include "SFData.h"

float Renderer::TileScale;
float Renderer::SpriteScale;

void Renderer::CreateWindow(int width, int height, std::string title)
{
	SFData::Window = new sf::RenderWindow(sf::VideoMode(width, height), title);
	SFData::Window->setFramerateLimit(60);
}

bool Renderer::WindowOpen()
{
	return SFData::Window->isOpen();
}

int Renderer::CreateSprite(std::string texpath)
{
	sf::Sprite sprite;
	sprite.setTexture(SFData::GetTexture(texpath));
	sprite.setScale(sf::Vector2f(SpriteScale, SpriteScale));
	sprite.setOrigin(sf::Vector2f(8, 8));

	int index = SFData::Sprites.size();
	SFData::Sprites.push_back(sprite);
	return index;
}

int Renderer::LoadFont(std::string fontpath)
{
	sf::Font font;
	font.loadFromFile(fontpath);
	int index = SFData::Fonts.size();
	SFData::Fonts.push_back(font);
	return index;
}

void Renderer::Clear()
{
	SFData::Window->clear();
}

void Renderer::Display()
{
	SFData::Window->display();
}

void Renderer::DrawSprite(const Sprite &s, int x, int y, float theta,
		bool flip, int anim, int frame)
{
	sf::Sprite &sprite = SFData::Sprites[s.Index];
	int tx, ty, tw, th;
	s.Animations[anim].GetRect(frame, tx, ty, tw, th);
	sprite.setTextureRect(sf::IntRect(tx, ty, tw, th));
	sprite.setPosition(x * TileScale, y * TileScale);
	sprite.setRotation(theta);
	sprite.setScale(flip ? -SpriteScale : SpriteScale, SpriteScale);
	SFData::Window->draw(sprite);
}

void Renderer::DrawText(int fontIndex, std::string text,
		unsigned int charSize, int x, int y)
{
	const sf::Font &font = SFData::Fonts[fontIndex];
	const sf::Texture &texture = font.getTexture(charSize);
	float xi = (float)x;
	std::wstring wtext;
	wtext.assign(text.begin(), text.end());
	for (unsigned int i = 0, size = wtext.size(); i < size; i++)
	{
		const sf::Glyph &glyph = font.getGlyph(wtext[i], charSize, false);
		sf::Vertex vertices[] =
		{
			sf::Vertex(
					sf::Vector2f(
						xi + glyph.bounds.left,
						y + glyph.bounds.top),
					sf::Vector2f(
						glyph.textureRect.left,
						glyph.textureRect.top)),
			sf::Vertex(
					sf::Vector2f(
						xi + glyph.bounds.left + glyph.bounds.width,
						y + glyph.bounds.top),
					sf::Vector2f(
							glyph.textureRect.left + glyph.textureRect.width,
							glyph.textureRect.top)),
			sf::Vertex(
					sf::Vector2f(
						xi + glyph.bounds.left,
						y + glyph.bounds.top + glyph.bounds.height),
					sf::Vector2f(
							glyph.textureRect.left,
							glyph.textureRect.top + glyph.textureRect.height)),
			sf::Vertex(
					sf::Vector2f(
						xi + glyph.bounds.left + glyph.bounds.width,
						y + glyph.bounds.top + glyph.bounds.height),
					sf::Vector2f(
							glyph.textureRect.left + glyph.textureRect.width,
							glyph.textureRect.top + glyph.textureRect.height)),
		};
		SFData::Window->draw(
				vertices, 4, sf::TrianglesStrip, sf::RenderStates(&texture));
		xi += glyph.advance;
	}
}

void Renderer::Deinit()
{
	SFData::Window->close();
	delete SFData::Window;
}
<commit_msg>Text drawing reduced to one draw call using swaps<commit_after>#include "Renderer.h"
#include <SFML/Graphics.hpp>
#include "SFData.h"

float Renderer::TileScale;
float Renderer::SpriteScale;

void Renderer::CreateWindow(int width, int height, std::string title)
{
	SFData::Window = new sf::RenderWindow(sf::VideoMode(width, height), title);
	SFData::Window->setFramerateLimit(60);
}

bool Renderer::WindowOpen()
{
	return SFData::Window->isOpen();
}

int Renderer::CreateSprite(std::string texpath)
{
	sf::Sprite sprite;
	sprite.setTexture(SFData::GetTexture(texpath));
	sprite.setScale(sf::Vector2f(SpriteScale, SpriteScale));
	sprite.setOrigin(sf::Vector2f(8, 8));

	int index = SFData::Sprites.size();
	SFData::Sprites.push_back(sprite);
	return index;
}

int Renderer::LoadFont(std::string fontpath)
{
	sf::Font font;
	font.loadFromFile(fontpath);
	int index = SFData::Fonts.size();
	SFData::Fonts.push_back(font);
	return index;
}

void Renderer::Clear()
{
	SFData::Window->clear();
}

void Renderer::Display()
{
	SFData::Window->display();
}

void Renderer::DrawSprite(const Sprite &s, int x, int y, float theta,
		bool flip, int anim, int frame)
{
	sf::Sprite &sprite = SFData::Sprites[s.Index];
	int tx, ty, tw, th;
	s.Animations[anim].GetRect(frame, tx, ty, tw, th);
	sprite.setTextureRect(sf::IntRect(tx, ty, tw, th));
	sprite.setPosition(x * TileScale, y * TileScale);
	sprite.setRotation(theta);
	sprite.setScale(flip ? -SpriteScale : SpriteScale, SpriteScale);
	SFData::Window->draw(sprite);
}

void Renderer::DrawText(int fontIndex, std::string text,
		unsigned int charSize, int x, int y)
{
	const sf::Font &font = SFData::Fonts[fontIndex];
	const sf::Texture &texture = font.getTexture(charSize);
	float xi = (float)x;
	std::wstring wtext;
	wtext.assign(text.begin(), text.end());
	std::size_t len = wtext.size();
	sf::Vertex *vertices = (sf::Vertex *)malloc(len * 6 * sizeof(sf::Vertex));
	for (unsigned int i = 0; i < len; i++)
	{
		const sf::Glyph &glyph = font.getGlyph(wtext[i], charSize, false);
		sf::Vertex topleft = sf::Vertex(
				sf::Vector2f(xi + glyph.bounds.left, y + glyph.bounds.top),
				sf::Vector2f(glyph.textureRect.left, glyph.textureRect.top));
		sf::Vertex topright = sf::Vertex(
				sf::Vector2f(
					xi + glyph.bounds.left + glyph.bounds.width,
					y + glyph.bounds.top),
				sf::Vector2f(
					glyph.textureRect.left + glyph.textureRect.width,
					glyph.textureRect.top));
		sf::Vertex botleft = sf::Vertex(
				sf::Vector2f(
					xi + glyph.bounds.left,
					y + glyph.bounds.top + glyph.bounds.height),
				sf::Vector2f(
					glyph.textureRect.left,
					glyph.textureRect.top + glyph.textureRect.height));
		sf::Vertex botright = sf::Vertex(
				sf::Vector2f(
					xi + glyph.bounds.left + glyph.bounds.width,
					y + glyph.bounds.top + glyph.bounds.height),
				sf::Vector2f(
					glyph.textureRect.left + glyph.textureRect.width,
					glyph.textureRect.top + glyph.textureRect.height));
		vertices[0 + 6 * i] = topleft;
		vertices[1 + 6 * i] = topleft;
		vertices[2 + 6 * i] = botleft;
		vertices[3 + 6 * i] = topright;
		vertices[4 + 6 * i] = botright;
		vertices[5 + 6 * i] = botright;
		SFData::Window->draw(
				vertices, 4, sf::TrianglesStrip, sf::RenderStates(&texture));
		xi += glyph.advance;
	}
	SFData::Window->draw(
			vertices + 1,
			len * 6 - 2,
			sf::TrianglesStrip,
			sf::RenderStates(&texture));
	free(vertices);
}

void Renderer::Deinit()
{
	SFData::Window->close();
	delete SFData::Window;
}
<|endoftext|>


<commit_before><commit_msg>Use more sensible defaults for spot light inner outer cone angles (#4607)<commit_after><|endoftext|>


<commit_before>#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>

#include <Eigen/Core>

#include "genrp/genrp.h"

namespace py = pybind11;

class PicklableBandSolver : public genrp::solver::BandSolver<double> {
public:
  auto serialize () const {
    return std::make_tuple(this->computed_, this->n_, this->p_real_, this->p_complex_, this->log_det_,
                           this->a_, this->al_, this->ipiv_);
  };

  void deserialize (bool computed, int n, int p_real, int p_complex, double log_det,
                    Eigen::MatrixXd a, Eigen::MatrixXd al, Eigen::VectorXi ipiv) {
    this->computed_ = computed;
    this->n_ = n;
    this->p_real_ = p_real;
    this->p_complex_ = p_complex;
    this->log_det_ = log_det;
    this->a_ = a;
    this->al_ = al;
    this->ipiv_ = ipiv;
  };

};

PYBIND11_PLUGIN(_genrp) {
  py::module m("_genrp", "GenRP extension");

  m.def("get_library_version", []() {
      return GENRP_VERSION_STRING;
    }
  );

  m.def("get_kernel_value",
    [](
      const Eigen::VectorXd& alpha_real,
      const Eigen::VectorXd& beta_real,
      const Eigen::VectorXd& alpha_complex_real,
      const Eigen::VectorXd& alpha_complex_imag,
      const Eigen::VectorXd& beta_complex_real,
      const Eigen::VectorXd& beta_complex_imag,
      py::array_t<double> tau
    ) {
      auto get_kernel_value_closure = [
        alpha_real, beta_real, alpha_complex_real, alpha_complex_imag, beta_complex_real, beta_complex_imag
      ] (double t) {
        return genrp::get_kernel_value(
          alpha_real, beta_real, alpha_complex_real, alpha_complex_imag, beta_complex_real, beta_complex_imag, t
        );
      };
      return py::vectorize(get_kernel_value_closure)(tau);
    }
  );

  m.def("get_psd_value",
    [](
      const Eigen::VectorXd& alpha_real,
      const Eigen::VectorXd& beta_real,
      const Eigen::VectorXd& alpha_complex_real,
      const Eigen::VectorXd& alpha_complex_imag,
      const Eigen::VectorXd& beta_complex_real,
      const Eigen::VectorXd& beta_complex_imag,
      py::array_t<double> omega
    ) {
      auto get_psd_value_closure = [
        alpha_real, beta_real, alpha_complex_real, alpha_complex_imag, beta_complex_real, beta_complex_imag
      ] (double t) {
        return genrp::get_psd_value(
          alpha_real, beta_real, alpha_complex_real, alpha_complex_imag, beta_complex_real, beta_complex_imag, t
        );
      };
      return py::vectorize(get_psd_value_closure)(omega);
    }
  );

  m.def("check_coefficients",
    [](
      const Eigen::VectorXd& alpha_real,
      const Eigen::VectorXd& beta_real,
      const Eigen::VectorXd& alpha_complex_real,
      const Eigen::VectorXd& alpha_complex_imag,
      const Eigen::VectorXd& beta_complex_real,
      const Eigen::VectorXd& beta_complex_imag
    ) {
      return genrp::check_coefficients(
        alpha_real,
        beta_real,
        alpha_complex_real,
        alpha_complex_imag,
        beta_complex_real,
        beta_complex_imag
      );
    }
  );

  py::class_<PicklableBandSolver > solver(m, "Solver");
  solver.def(py::init<>());

  solver.def("compute", [](PicklableBandSolver& solver,
      const Eigen::VectorXd& alpha_real,
      const Eigen::VectorXd& beta_real,
      const Eigen::VectorXd& alpha_complex_real,
      const Eigen::VectorXd& alpha_complex_imag,
      const Eigen::VectorXd& beta_complex_real,
      const Eigen::VectorXd& beta_complex_imag,
      const Eigen::VectorXd& x,
      const Eigen::VectorXd& diag) {
    return solver.compute(
      alpha_real,
      beta_real,
      alpha_complex_real,
      alpha_complex_imag,
      beta_complex_real,
      beta_complex_imag,
      x,
      diag
    );
  });

  solver.def("solve", [](PicklableBandSolver& solver, const Eigen::MatrixXd& b) {
    return solver.solve(b);
  });

  solver.def("dot_solve", [](PicklableBandSolver& solver, const Eigen::MatrixXd& b) {
    return solver.dot_solve(b);
  });

  solver.def("log_determinant", [](PicklableBandSolver& solver) {
    return solver.log_determinant();
  });

  solver.def("computed", [](PicklableBandSolver& solver) {
      return solver.computed();
  });

  solver.def("__getstate__", [](const PicklableBandSolver& solver) {
    return solver.serialize();
  });

  solver.def("__setstate__", [](PicklableBandSolver& solver, py::tuple t) {
    if (t.size() != 8)
    throw std::runtime_error("Invalid state!");

    new (&solver) PicklableBandSolver();

    solver.deserialize(
      t[0].cast<bool>(),
      t[1].cast<int>(),
      t[2].cast<int>(),
      t[3].cast<int>(),
      t[4].cast<double>(),
      t[5].cast<Eigen::MatrixXd>(),
      t[6].cast<Eigen::MatrixXd>(),
      t[7].cast<Eigen::VectorXi>()
    );
  });

  return m.ptr();
}
<commit_msg>nothing [ci skip]<commit_after>#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>

#include <Eigen/Core>

#include "genrp/genrp.h"

namespace py = pybind11;

class PicklableBandSolver : public genrp::solver::BandSolver<double> {
public:
  auto serialize () const {
    return std::make_tuple(this->computed_, this->n_, this->p_real_, this->p_complex_, this->log_det_,
                           this->a_, this->al_, this->ipiv_);
  };

  void deserialize (bool computed, int n, int p_real, int p_complex, double log_det,
                    Eigen::MatrixXd a, Eigen::MatrixXd al, Eigen::VectorXi ipiv) {
    this->computed_ = computed;
    this->n_ = n;
    this->p_real_ = p_real;
    this->p_complex_ = p_complex;
    this->log_det_ = log_det;
    this->a_ = a;
    this->al_ = al;
    this->ipiv_ = ipiv;
  };

};

PYBIND11_PLUGIN(_genrp) {
  py::module m("_genrp", "GenRP extension");

  m.def("get_library_version", []() {
      return GENRP_VERSION_STRING;
    }
  );

  m.def("get_kernel_value",
    [](
      const Eigen::VectorXd& alpha_real,
      const Eigen::VectorXd& beta_real,
      const Eigen::VectorXd& alpha_complex_real,
      const Eigen::VectorXd& alpha_complex_imag,
      const Eigen::VectorXd& beta_complex_real,
      const Eigen::VectorXd& beta_complex_imag,
      py::array_t<double> tau
    ) {
      auto get_kernel_value_closure = [
        alpha_real, beta_real, alpha_complex_real, alpha_complex_imag, beta_complex_real, beta_complex_imag
      ] (double t) {
        return genrp::get_kernel_value(
          alpha_real, beta_real, alpha_complex_real, alpha_complex_imag, beta_complex_real, beta_complex_imag, t
        );
      };
      return py::vectorize(get_kernel_value_closure)(tau);
    }
  );

  m.def("get_psd_value",
    [](
      const Eigen::VectorXd& alpha_real,
      const Eigen::VectorXd& beta_real,
      const Eigen::VectorXd& alpha_complex_real,
      const Eigen::VectorXd& alpha_complex_imag,
      const Eigen::VectorXd& beta_complex_real,
      const Eigen::VectorXd& beta_complex_imag,
      py::array_t<double> omega
    ) {
      auto get_psd_value_closure = [
        alpha_real, beta_real, alpha_complex_real, alpha_complex_imag, beta_complex_real, beta_complex_imag
      ] (double t) {
        return genrp::get_psd_value(
          alpha_real, beta_real, alpha_complex_real, alpha_complex_imag, beta_complex_real, beta_complex_imag, t
        );
      };
      return py::vectorize(get_psd_value_closure)(omega);
    }
  );

  m.def("check_coefficients",
    [](
      const Eigen::VectorXd& alpha_real,
      const Eigen::VectorXd& beta_real,
      const Eigen::VectorXd& alpha_complex_real,
      const Eigen::VectorXd& alpha_complex_imag,
      const Eigen::VectorXd& beta_complex_real,
      const Eigen::VectorXd& beta_complex_imag
    ) {
      return genrp::check_coefficients(
        alpha_real,
        beta_real,
        alpha_complex_real,
        alpha_complex_imag,
        beta_complex_real,
        beta_complex_imag
      );
    }
  );

  py::class_<PicklableBandSolver> solver(m, "Solver");
  solver.def(py::init<>());

  solver.def("compute", [](PicklableBandSolver& solver,
      const Eigen::VectorXd& alpha_real,
      const Eigen::VectorXd& beta_real,
      const Eigen::VectorXd& alpha_complex_real,
      const Eigen::VectorXd& alpha_complex_imag,
      const Eigen::VectorXd& beta_complex_real,
      const Eigen::VectorXd& beta_complex_imag,
      const Eigen::VectorXd& x,
      const Eigen::VectorXd& diag) {
    return solver.compute(
      alpha_real,
      beta_real,
      alpha_complex_real,
      alpha_complex_imag,
      beta_complex_real,
      beta_complex_imag,
      x,
      diag
    );
  });

  solver.def("solve", [](PicklableBandSolver& solver, const Eigen::MatrixXd& b) {
    return solver.solve(b);
  });

  solver.def("dot_solve", [](PicklableBandSolver& solver, const Eigen::MatrixXd& b) {
    return solver.dot_solve(b);
  });

  solver.def("log_determinant", [](PicklableBandSolver& solver) {
    return solver.log_determinant();
  });

  solver.def("computed", [](PicklableBandSolver& solver) {
      return solver.computed();
  });

  solver.def("__getstate__", [](const PicklableBandSolver& solver) {
    return solver.serialize();
  });

  solver.def("__setstate__", [](PicklableBandSolver& solver, py::tuple t) {
    if (t.size() != 8)
    throw std::runtime_error("Invalid state!");

    new (&solver) PicklableBandSolver();

    solver.deserialize(
      t[0].cast<bool>(),
      t[1].cast<int>(),
      t[2].cast<int>(),
      t[3].cast<int>(),
      t[4].cast<double>(),
      t[5].cast<Eigen::MatrixXd>(),
      t[6].cast<Eigen::MatrixXd>(),
      t[7].cast<Eigen::VectorXi>()
    );
  });

  return m.ptr();
}
<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

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

#include "mitkDataStorage.h"

#include "mitkDataTreeNode.h"
#include "mitkProperties.h"
#include "mitkNodePredicateBase.h"

mitk::DataStorage::DataStorage()
: itk::Object(), m_ManageCompleteTree(true) // true by default until all Reliver functionalities use the datastorage properly
{
  m_DataTree = NULL;
}

mitk::DataStorage::~DataStorage()
{
  m_DataTree = NULL;
}

void mitk::DataStorage::Initialize(mitk::DataTree* tree)
{
  if (tree == NULL)
    throw 1;  // insert exception handling here
  m_DataTree = tree;
}

inline bool mitk::DataStorage::IsInitialized()
{
  return m_DataTree.IsNotNull();
}

void mitk::DataStorage::Add(mitk::DataTreeNode* node, const mitk::DataStorage::SetOfObjects* parents)
{
  if (!IsInitialized())
    throw 1;  // insert exception handling here
  /* Check, if node is already in the DataTree */
  if (m_DataTree->Contains(node))
    throw 2;
  /* save node in tree */
  mitk::DataTreePreOrderIterator it(m_DataTree);
  node->SetProperty("IsDataStoreManaged", new mitk::BoolProperty(true));
  it.Add(node);
  /* save node and parentlist in relations map */
  m_CreatedByRelations.insert(make_pair(node, parents));

}

void mitk::DataStorage::Update(mitk::DataTreeNode* node)
{
}

mitk::DataStorage::SetOfObjects::ConstPointer mitk::DataStorage::GetSubset(const NodePredicateBase& condition)
{
  if (!IsInitialized())
    throw 1;  // insert exception handling here

  /* Fill resultset with objects that fullfill the condition */
  mitk::DataTreePreOrderIterator it(m_DataTree);
  mitk::DataStorage::SetOfObjects::Pointer resultset = mitk::DataStorage::SetOfObjects::New();
  unsigned int index = 0;
  if (m_ManageCompleteTree == true)
    for (it.GoToBegin(); !it.IsAtEnd(); it++)
    {
      mitk::DataTreeNode* node = it.Get();
      if (node == NULL)
        continue;
      if (condition.CheckNode(node) == true)  // check all elements in the datatree
        resultset->InsertElement(index++, node);
    }
  else
    for (it.GoToBegin(); !it.IsAtEnd(); it++)
    {
      mitk::DataTreeNode* node = it.Get();
      if (node == NULL)
        continue;
      if ((node->IsOn("IsDataStoreManaged",NULL, false) == true) && (condition.CheckNode(node) == true))  // check if node is managed by the datastorage object
        resultset->InsertElement(index++, node);
    }
  return SetOfObjects::ConstPointer( resultset );
}

mitk::DataStorage::SetOfObjects::ConstPointer mitk::DataStorage::GetAll()
{
  mitk::DataTreePreOrderIterator it(m_DataTree);
  mitk::DataStorage::SetOfObjects::Pointer resultset = mitk::DataStorage::SetOfObjects::New();
  /* Fill resultset with all objects that are managed by the DataStorage object */
  unsigned int index = 0;
  if (m_ManageCompleteTree == true)
    for (it.GoToBegin(); !it.IsAtEnd(); it++)
    {
      mitk::DataTreeNode* node = it.Get();
      if (node == NULL)
        continue;
      resultset->InsertElement(index++, node);
    }
  else
    for (it.GoToBegin(); !it.IsAtEnd(); it++)
    {
      mitk::DataTreeNode* node = it.Get();
      if (node == NULL)
        continue;
      if (node->IsOn("IsDataStoreManaged",NULL, false) == true)  // check if node is managed by the datastorage object
        resultset->InsertElement(index++, node);
    }
  return SetOfObjects::ConstPointer( resultset );
}
<commit_msg>add missing std::<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

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

#include "mitkDataStorage.h"

#include "mitkDataTreeNode.h"
#include "mitkProperties.h"
#include "mitkNodePredicateBase.h"

mitk::DataStorage::DataStorage()
: itk::Object(), m_ManageCompleteTree(true) // true by default until all Reliver functionalities use the datastorage properly
{
  m_DataTree = NULL;
}

mitk::DataStorage::~DataStorage()
{
  m_DataTree = NULL;
}

void mitk::DataStorage::Initialize(mitk::DataTree* tree)
{
  if (tree == NULL)
    throw 1;  // insert exception handling here
  m_DataTree = tree;
}

inline bool mitk::DataStorage::IsInitialized()
{
  return m_DataTree.IsNotNull();
}

void mitk::DataStorage::Add(mitk::DataTreeNode* node, const mitk::DataStorage::SetOfObjects* parents)
{
  if (!IsInitialized())
    throw 1;  // insert exception handling here
  /* Check, if node is already in the DataTree */
  if (m_DataTree->Contains(node))
    throw 2;
  /* save node in tree */
  mitk::DataTreePreOrderIterator it(m_DataTree);
  node->SetProperty("IsDataStoreManaged", new mitk::BoolProperty(true));
  it.Add(node);
  /* save node and parentlist in relations map */
  m_CreatedByRelations.insert(std::make_pair(node, parents));

}

void mitk::DataStorage::Update(mitk::DataTreeNode* node)
{
}

mitk::DataStorage::SetOfObjects::ConstPointer mitk::DataStorage::GetSubset(const NodePredicateBase& condition)
{
  if (!IsInitialized())
    throw 1;  // insert exception handling here

  /* Fill resultset with objects that fullfill the condition */
  mitk::DataTreePreOrderIterator it(m_DataTree);
  mitk::DataStorage::SetOfObjects::Pointer resultset = mitk::DataStorage::SetOfObjects::New();
  unsigned int index = 0;
  if (m_ManageCompleteTree == true)
    for (it.GoToBegin(); !it.IsAtEnd(); it++)
    {
      mitk::DataTreeNode* node = it.Get();
      if (node == NULL)
        continue;
      if (condition.CheckNode(node) == true)  // check all elements in the datatree
        resultset->InsertElement(index++, node);
    }
  else
    for (it.GoToBegin(); !it.IsAtEnd(); it++)
    {
      mitk::DataTreeNode* node = it.Get();
      if (node == NULL)
        continue;
      if ((node->IsOn("IsDataStoreManaged",NULL, false) == true) && (condition.CheckNode(node) == true))  // check if node is managed by the datastorage object
        resultset->InsertElement(index++, node);
    }
  return SetOfObjects::ConstPointer( resultset );
}

mitk::DataStorage::SetOfObjects::ConstPointer mitk::DataStorage::GetAll()
{
  mitk::DataTreePreOrderIterator it(m_DataTree);
  mitk::DataStorage::SetOfObjects::Pointer resultset = mitk::DataStorage::SetOfObjects::New();
  /* Fill resultset with all objects that are managed by the DataStorage object */
  unsigned int index = 0;
  if (m_ManageCompleteTree == true)
    for (it.GoToBegin(); !it.IsAtEnd(); it++)
    {
      mitk::DataTreeNode* node = it.Get();
      if (node == NULL)
        continue;
      resultset->InsertElement(index++, node);
    }
  else
    for (it.GoToBegin(); !it.IsAtEnd(); it++)
    {
      mitk::DataTreeNode* node = it.Get();
      if (node == NULL)
        continue;
      if (node->IsOn("IsDataStoreManaged",NULL, false) == true)  // check if node is managed by the datastorage object
        resultset->InsertElement(index++, node);
    }
  return SetOfObjects::ConstPointer( resultset );
}
<|endoftext|>


<commit_before>#include <p2.h>
#include <boost/python.hpp>
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/utility.hpp>
using namespace boost::python;
using namespace boost::python::api;

class P2Wrap : public P2, public wrapper<P2>
{
public:
  P2Wrap(std::string hostname, std::string port)
    : P2(hostname, port) {};

  CallbackHandlePtr subscribe(string tableName, object callback) {
    return P2::subscribe(tableName, boost::function<void (TuplePtr)>(callback));
  }
};

void export_p2()
{
scope outer =
  class_<P2Wrap, boost::shared_ptr<P2Wrap>, boost::noncopyable>
        ("P2", init<string, string>())
    .def("run",         &P2::run)
    .def("install",     &P2::install)
    .def("subscribe",   &P2Wrap::subscribe)
    .def("unsubscribe", &P2::unsubscribe)
    .def("tuple",       &P2::tuple)
  ;

  class_<P2::CallbackHandle, P2::CallbackHandlePtr, boost::noncopyable>
        ("CallbackHandle", no_init)
  ;
}
<commit_msg>*** empty log message ***<commit_after>#include <p2.h>
#include <boost/python.hpp>
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/utility.hpp>
using namespace boost::python;
using namespace boost::python::api;

class P2Wrap : public P2, public wrapper<P2>
{
public:
  P2Wrap(std::string hostname, std::string port, P2::TransportConf conf=P2::NONE)
    : P2(hostname, port, conf) {};

  CallbackHandlePtr subscribe(string tableName, object callback) {
    return P2::subscribe(tableName, boost::function<void (TuplePtr)>(callback));
  }
};

void export_p2()
{
scope outer =
  class_<P2Wrap, boost::shared_ptr<P2Wrap>, boost::noncopyable>
        ("P2", init<string, string, optional<P2::TransportConf> >())
    .def("run",         &P2::run)
    .def("install",     &P2::install)
    .def("subscribe",   &P2Wrap::subscribe)
    .def("unsubscribe", &P2::unsubscribe)
    .def("tuple",       &P2::tuple)
  ;

  class_<P2::CallbackHandle, P2::CallbackHandlePtr, boost::noncopyable>
        ("CallbackHandle", no_init)
  ;

  enum_<P2::TransportConf>("TransportConf")
    .value("NONE",     P2::NONE)
    .value("RELIABLE", P2::RELIABLE)
    .value("ORDERED",  P2::ORDERED)
    .value("CC",       P2::CC)
    .value("RCC",      P2::RCC)
  ;
}
<|endoftext|>


<commit_before>/*
**  Copyright (C) 2013 Aldebaran Robotics
**  See COPYING for the license
*/
#include "pysignal.hpp"
#include <boost/python.hpp>
#include <boost/python/raw_function.hpp>
#include <qitype/signal.hpp>
#include <qitype/anyobject.hpp>
#include <qimessaging/python-gil.hpp>
#include <qi/periodictask.hpp>
#include "error.hpp"
#include "pyfuture.hpp"
#include "pyobject.hpp"
#include "pythreadsafeobject.hpp"

qiLogCategory("py.async");

namespace qi { namespace py {

    static void pyPeriodicCb(const PyThreadSafeObject& callable) {
      GILScopedLock _gil;
      PY_CATCH_ERROR(callable.object()());
    }

    class PyPeriodicTask : public qi::PeriodicTask {
    public:
      void setCallback(boost::python::object callable) {
        if (!PyCallable_Check(callable.ptr()))
          throw std::runtime_error("Not a callable");
        qi::PeriodicTask::setCallback(boost::bind<void>(pyPeriodicCb, PyThreadSafeObject(callable)));
      }
    };

    static boost::python::object pyAsync(PyThreadSafeObject safeargs) {
      GILScopedLock _gil;

      boost::python::list args(safeargs.object());
      boost::python::object callable = args[0];

      args.pop(0);

      try {
        return callable(*boost::python::tuple(args));
      } catch (const boost::python::error_already_set &) {
        throw std::runtime_error(PyFormatError());
      }
    }

    static boost::python::object pyasyncParamShrinker(boost::python::tuple args, boost::python::dict kwargs) {
      //arg0 always exists
      //check args[0] is a callable
      boost::python::object callable = args[0];
      if (!PyCallable_Check(callable.ptr()))
        throw std::runtime_error("Not a callable");

      qi::uint64_t delay = boost::python::extract<qi::uint64_t>(kwargs.get("delay", 0));

      //Does not use PyThreadSafeObject, because, setValue will be done under the lock
      //and the the future will be a PyFuture, that will be destroyed and use in the python world
      //under the lock too.
      boost::function<boost::python::object()> f = boost::bind(&pyAsync, PyThreadSafeObject(args));

      qi::Future<boost::python::object> fut = qi::getEventLoop()->async(f, delay);

      return boost::python::object(qi::py::toPyFuture(fut));
    }

    void export_pyasync() {
      boost::python::object async = boost::python::raw_function(&pyasyncParamShrinker, 1);

      async.attr("__doc__") = "async(callback [, delay=usec] [, arg1, ..., argn]) -> future\n"
                              ":param callback: the callback that will be called\n"
                              ":param delay: an optional delay in microseconds\n"
                              ":return: a future with the return value of the function\n"
                              "\n";

      boost::python::def("async", async);

      boost::python::class_<PyPeriodicTask, boost::shared_ptr<PyPeriodicTask>, boost::noncopyable >("PeriodicTask")
        .def(boost::python::init<>())
        .def("setCallback", &PyPeriodicTask::setCallback,
             "setCallback(callable)\n"
             ":param callable: a python callable, could be a method or a function\n"
             "\n"
             "set the callback used by the periodictask, this function can only be called once")
        .def("setUsPeriod", &PyPeriodicTask::setUsPeriod,
             "setUsPeriod(usPeriod)\n"
             ":param usPeriod: the period in microseconds\n"
             "\n"
             "Set the call interval in microseconds.\n"
             "This call will wait until next callback invocation to apply the change.\n"
             "To apply the change immediately, use: \n"
             "\n"
             ".. code-block:: python\n"
             "\n"
             "   task.stop()\n"
             "   task.setUsPeriod()\n"
             "   task.start()\n"
             "\n")
        .def("start", &PyPeriodicTask::start,
             "start(immediate)\n"
             ":param immediate: immediate if true, first schedule of the task will happen with no delay.\n"
             "\n"
             "start the periodic task at specified period. No effect if already running\n"
             "\n"
             ".. warning::\n"
             "   concurrent calls to start() and stop() will result in undefined behavior."
             "\n")
        .def("stop", &PyPeriodicTask::stop,
             "stop()\n"
             "Stop the periodic task. When this function returns, the callback will not be called anymore.\n"
             "Can be called from within the callback function\n"
             "\n"
             ".. warning::\n"
             "   concurrent calls to start() and stop() will result in undefined behavior."
             "\n")
        .def("asyncStop", &PyPeriodicTask::asyncStop,
             "asyncStop()\n"
             "Can be called from within the callback function"
             "Request for periodic task to stop asynchronously")
        .def("compensateCallbackTime", &PyPeriodicTask::compensateCallbackTime,
             "compensateCallbackTime(compensate)\n"
             ":param compensate: If true, call interval will take into account call duration to maintain the period.")
        .def("setName", &PyPeriodicTask::setName,
             "setName(name)\n"
             "Set name for debugging and tracking purpose")
        .def("isRunning", &PyPeriodicTask::isRunning,
             "isRunning() -> bool\n"
             ":return: true is task is running\n")
        .def("isStopping", &PyPeriodicTask::isStopping,
             "isStopping() -> bool\n"
             ":return: whether state is stopping or stopped.\n"
             "\n"
             "Can be called from within the callback to know if stop() or asyncStop()  was called.")
          ;
    }

  }
}
<commit_msg>missing \n. Bad doc generation.<commit_after>/*
**  Copyright (C) 2013 Aldebaran Robotics
**  See COPYING for the license
*/
#include "pysignal.hpp"
#include <boost/python.hpp>
#include <boost/python/raw_function.hpp>
#include <qitype/signal.hpp>
#include <qitype/anyobject.hpp>
#include <qimessaging/python-gil.hpp>
#include <qi/periodictask.hpp>
#include "error.hpp"
#include "pyfuture.hpp"
#include "pyobject.hpp"
#include "pythreadsafeobject.hpp"

qiLogCategory("py.async");

namespace qi { namespace py {

    static void pyPeriodicCb(const PyThreadSafeObject& callable) {
      GILScopedLock _gil;
      PY_CATCH_ERROR(callable.object()());
    }

    class PyPeriodicTask : public qi::PeriodicTask {
    public:
      void setCallback(boost::python::object callable) {
        if (!PyCallable_Check(callable.ptr()))
          throw std::runtime_error("Not a callable");
        qi::PeriodicTask::setCallback(boost::bind<void>(pyPeriodicCb, PyThreadSafeObject(callable)));
      }
    };

    static boost::python::object pyAsync(PyThreadSafeObject safeargs) {
      GILScopedLock _gil;

      boost::python::list args(safeargs.object());
      boost::python::object callable = args[0];

      args.pop(0);

      try {
        return callable(*boost::python::tuple(args));
      } catch (const boost::python::error_already_set &) {
        throw std::runtime_error(PyFormatError());
      }
    }

    static boost::python::object pyasyncParamShrinker(boost::python::tuple args, boost::python::dict kwargs) {
      //arg0 always exists
      //check args[0] is a callable
      boost::python::object callable = args[0];
      if (!PyCallable_Check(callable.ptr()))
        throw std::runtime_error("Not a callable");

      qi::uint64_t delay = boost::python::extract<qi::uint64_t>(kwargs.get("delay", 0));

      //Does not use PyThreadSafeObject, because, setValue will be done under the lock
      //and the the future will be a PyFuture, that will be destroyed and use in the python world
      //under the lock too.
      boost::function<boost::python::object()> f = boost::bind(&pyAsync, PyThreadSafeObject(args));

      qi::Future<boost::python::object> fut = qi::getEventLoop()->async(f, delay);

      return boost::python::object(qi::py::toPyFuture(fut));
    }

    void export_pyasync() {
      boost::python::object async = boost::python::raw_function(&pyasyncParamShrinker, 1);

      async.attr("__doc__") = "async(callback [, delay=usec] [, arg1, ..., argn]) -> future\n"
                              ":param callback: the callback that will be called\n"
                              ":param delay: an optional delay in microseconds\n"
                              ":return: a future with the return value of the function\n"
                              "\n";

      boost::python::def("async", async);

      boost::python::class_<PyPeriodicTask, boost::shared_ptr<PyPeriodicTask>, boost::noncopyable >("PeriodicTask")
        .def(boost::python::init<>())
        .def("setCallback", &PyPeriodicTask::setCallback,
             "setCallback(callable)\n"
             ":param callable: a python callable, could be a method or a function\n"
             "\n"
             "set the callback used by the periodictask, this function can only be called once")
        .def("setUsPeriod", &PyPeriodicTask::setUsPeriod,
             "setUsPeriod(usPeriod)\n"
             ":param usPeriod: the period in microseconds\n"
             "\n"
             "Set the call interval in microseconds.\n"
             "This call will wait until next callback invocation to apply the change.\n"
             "To apply the change immediately, use: \n"
             "\n"
             ".. code-block:: python\n"
             "\n"
             "   task.stop()\n"
             "   task.setUsPeriod()\n"
             "   task.start()\n"
             "\n")
        .def("start", &PyPeriodicTask::start,
             "start(immediate)\n"
             ":param immediate: immediate if true, first schedule of the task will happen with no delay.\n"
             "\n"
             "start the periodic task at specified period. No effect if already running\n"
             "\n"
             ".. warning::\n"
             "   concurrent calls to start() and stop() will result in undefined behavior."
             "\n")
        .def("stop", &PyPeriodicTask::stop,
             "stop()\n"
             "Stop the periodic task. When this function returns, the callback will not be called anymore.\n"
             "Can be called from within the callback function\n"
             "\n"
             ".. warning::\n"
             "   concurrent calls to start() and stop() will result in undefined behavior."
             "\n")
        .def("asyncStop", &PyPeriodicTask::asyncStop,
             "asyncStop()\n"
             "Can be called from within the callback function\n"
             "Request for periodic task to stop asynchronously")
        .def("compensateCallbackTime", &PyPeriodicTask::compensateCallbackTime,
             "compensateCallbackTime(compensate)\n"
             ":param compensate: If true, call interval will take into account call duration to maintain the period.")
        .def("setName", &PyPeriodicTask::setName,
             "setName(name)\n"
             "Set name for debugging and tracking purpose")
        .def("isRunning", &PyPeriodicTask::isRunning,
             "isRunning() -> bool\n"
             ":return: true is task is running\n")
        .def("isStopping", &PyPeriodicTask::isStopping,
             "isStopping() -> bool\n"
             ":return: whether state is stopping or stopped.\n"
             "\n"
             "Can be called from within the callback to know if stop() or asyncStop()  was called.")
          ;
    }

  }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2018-present Facebook, Inc.
 *
 * 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 <folly/hash/detail/ChecksumDetail.h>

#include <array>

#include <folly/Bits.h>
#include <folly/CPortability.h>
#include <folly/ConstexprMath.h>

namespace folly {

// Standard galois-field multiply.  The only modification is that a,
// b, m, and p are all bit-reflected.
//
// https://en.wikipedia.org/wiki/Finite_field_arithmetic
static constexpr uint32_t
gf_multiply_sw_1(size_t i, uint32_t p, uint32_t a, uint32_t b, uint32_t m) {
  // clang-format off
  return i == 32 ? p : gf_multiply_sw_1(
      /* i = */ i + 1,
      /* p = */ p ^ (-((b >> 31) & 1) & a),
      /* a = */ (a >> 1) ^ (-(a & 1) & m),
      /* b = */ b << 1,
      /* m = */ m);
  // clang-format on
}
static constexpr uint32_t gf_multiply_sw(uint32_t a, uint32_t b, uint32_t m) {
  return gf_multiply_sw_1(/* i = */ 0, /* p = */ 0, a, b, m);
}

static constexpr uint32_t gf_square_sw(uint32_t a, uint32_t m) {
  return gf_multiply_sw(a, a, m);
}

namespace {

template <size_t i, uint32_t m>
struct gf_powers_memo {
  static constexpr uint32_t value =
      gf_square_sw(gf_powers_memo<i - 1, m>::value, m);
};
template <uint32_t m>
struct gf_powers_memo<0, m> {
  static constexpr uint32_t value = m;
};

template <uint32_t m>
struct gf_powers_make {
  template <size_t... i>
  FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN constexpr auto operator()(
      index_sequence<i...>) const {
    return std::array<uint32_t, sizeof...(i)>{{gf_powers_memo<i, m>::value...}};
  }
};

} // namespace

#if FOLLY_SSE_PREREQ(4, 2)

// Reduction taken from
// https://www.nicst.de/crc.pdf
//
// This is an intrinsics-based implementation of listing 3.
static uint32_t gf_multiply_crc32c_hw(uint64_t crc1, uint64_t crc2, uint32_t) {
  const auto crc1_xmm = _mm_set_epi64x(0, crc1);
  const auto crc2_xmm = _mm_set_epi64x(0, crc2);
  const auto count = _mm_set_epi64x(0, 1);
  const auto res0 = _mm_clmulepi64_si128(crc2_xmm, crc1_xmm, 0x00);
  const auto res1 = _mm_sll_epi64(res0, count);

  // Use hardware crc32c to do reduction from 64 -> 32 bytes
  const auto res2 = _mm_cvtsi128_si64(res1);
  const auto res3 = _mm_crc32_u32(0, res2);
  const auto res4 = _mm_extract_epi32(res1, 1);
  return res3 ^ res4;
}

static uint32_t gf_multiply_crc32_hw(uint64_t crc1, uint64_t crc2, uint32_t) {
  const auto crc1_xmm = _mm_set_epi64x(0, crc1);
  const auto crc2_xmm = _mm_set_epi64x(0, crc2);
  const auto count = _mm_set_epi64x(0, 1);
  const auto res0 = _mm_clmulepi64_si128(crc2_xmm, crc1_xmm, 0x00);
  const auto res1 = _mm_sll_epi64(res0, count);

  // Do barrett reduction of 64 -> 32 bytes
  const auto mask32 = _mm_set_epi32(0, 0, 0, 0xFFFFFFFF);
  const auto barrett_reduction_constants =
      _mm_set_epi32(0x1, 0xDB710641, 0x1, 0xF7011641);
  const auto res2 = _mm_clmulepi64_si128(
      _mm_and_si128(res1, mask32), barrett_reduction_constants, 0x00);
  const auto res3 = _mm_clmulepi64_si128(
      _mm_and_si128(res2, mask32), barrett_reduction_constants, 0x10);
  return _mm_cvtsi128_si32(_mm_srli_si128(_mm_xor_si128(res3, res1), 4));
}

#else

static uint32_t gf_multiply_crc32c_hw(uint64_t, uint64_t, uint32_t) {
  return 0;
}
static uint32_t gf_multiply_crc32_hw(uint64_t, uint64_t, uint32_t) {
  return 0;
}

#endif

/*
 * Pre-calculated powers tables for crc32c and crc32.
 */
static constexpr std::array<uint32_t, 62> const crc32c_powers =
    gf_powers_make<0x82f63b78>{}(make_index_sequence<62>{});
static constexpr std::array<uint32_t, 62> const crc32_powers =
    gf_powers_make<0xedb88320>{}(make_index_sequence<62>{});

template <typename F>
static uint32_t crc32_append_zeroes(
    F mult,
    uint32_t crc,
    size_t len,
    uint32_t polynomial,
    std::array<uint32_t, 62> const& powers_array) {
  auto powers = powers_array.data();

  // Append by multiplying by consecutive powers of two of the zeroes
  // array
  len >>= 2;

  while (len) {
    // Advance directly to next bit set.
    auto r = findFirstSet(len) - 1;
    len >>= r;
    powers += r;

    crc = mult(crc, *powers, polynomial);

    len >>= 1;
    powers++;
  }

  return crc;
}

namespace detail {

uint32_t crc32_combine_sw(uint32_t crc1, uint32_t crc2, size_t crc2len) {
  return crc2 ^
      crc32_append_zeroes(
             gf_multiply_sw, crc1, crc2len, 0xEDB88320, crc32_powers);
}

uint32_t crc32_combine_hw(uint32_t crc1, uint32_t crc2, size_t crc2len) {
  return crc2 ^
      crc32_append_zeroes(
             gf_multiply_crc32_hw, crc1, crc2len, 0xEDB88320, crc32_powers);
}

uint32_t crc32c_combine_sw(uint32_t crc1, uint32_t crc2, size_t crc2len) {
  return crc2 ^
      crc32_append_zeroes(
             gf_multiply_sw, crc1, crc2len, 0x82F63B78, crc32c_powers);
}

uint32_t crc32c_combine_hw(uint32_t crc1, uint32_t crc2, size_t crc2len) {
  return crc2 ^
      crc32_append_zeroes(
             gf_multiply_crc32c_hw, crc1, crc2len, 0x82F63B78, crc32c_powers);
}

} // namespace detail

} // namespace folly
<commit_msg>Fix folly/hash/detail/Crc32CombineDetail.cpp with -Werror=attributes<commit_after>/*
 * Copyright 2018-present Facebook, Inc.
 *
 * 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 <folly/hash/detail/ChecksumDetail.h>

#include <array>

#include <folly/Bits.h>
#include <folly/ConstexprMath.h>

namespace folly {

// Standard galois-field multiply.  The only modification is that a,
// b, m, and p are all bit-reflected.
//
// https://en.wikipedia.org/wiki/Finite_field_arithmetic
static constexpr uint32_t
gf_multiply_sw_1(size_t i, uint32_t p, uint32_t a, uint32_t b, uint32_t m) {
  // clang-format off
  return i == 32 ? p : gf_multiply_sw_1(
      /* i = */ i + 1,
      /* p = */ p ^ (-((b >> 31) & 1) & a),
      /* a = */ (a >> 1) ^ (-(a & 1) & m),
      /* b = */ b << 1,
      /* m = */ m);
  // clang-format on
}
static constexpr uint32_t gf_multiply_sw(uint32_t a, uint32_t b, uint32_t m) {
  return gf_multiply_sw_1(/* i = */ 0, /* p = */ 0, a, b, m);
}

static constexpr uint32_t gf_square_sw(uint32_t a, uint32_t m) {
  return gf_multiply_sw(a, a, m);
}

namespace {

template <size_t i, uint32_t m>
struct gf_powers_memo {
  static constexpr uint32_t value =
      gf_square_sw(gf_powers_memo<i - 1, m>::value, m);
};
template <uint32_t m>
struct gf_powers_memo<0, m> {
  static constexpr uint32_t value = m;
};

template <uint32_t m>
struct gf_powers_make {
  template <size_t... i>
  constexpr auto operator()(index_sequence<i...>) const {
    return std::array<uint32_t, sizeof...(i)>{{gf_powers_memo<i, m>::value...}};
  }
};

} // namespace

#if FOLLY_SSE_PREREQ(4, 2)

// Reduction taken from
// https://www.nicst.de/crc.pdf
//
// This is an intrinsics-based implementation of listing 3.
static uint32_t gf_multiply_crc32c_hw(uint64_t crc1, uint64_t crc2, uint32_t) {
  const auto crc1_xmm = _mm_set_epi64x(0, crc1);
  const auto crc2_xmm = _mm_set_epi64x(0, crc2);
  const auto count = _mm_set_epi64x(0, 1);
  const auto res0 = _mm_clmulepi64_si128(crc2_xmm, crc1_xmm, 0x00);
  const auto res1 = _mm_sll_epi64(res0, count);

  // Use hardware crc32c to do reduction from 64 -> 32 bytes
  const auto res2 = _mm_cvtsi128_si64(res1);
  const auto res3 = _mm_crc32_u32(0, res2);
  const auto res4 = _mm_extract_epi32(res1, 1);
  return res3 ^ res4;
}

static uint32_t gf_multiply_crc32_hw(uint64_t crc1, uint64_t crc2, uint32_t) {
  const auto crc1_xmm = _mm_set_epi64x(0, crc1);
  const auto crc2_xmm = _mm_set_epi64x(0, crc2);
  const auto count = _mm_set_epi64x(0, 1);
  const auto res0 = _mm_clmulepi64_si128(crc2_xmm, crc1_xmm, 0x00);
  const auto res1 = _mm_sll_epi64(res0, count);

  // Do barrett reduction of 64 -> 32 bytes
  const auto mask32 = _mm_set_epi32(0, 0, 0, 0xFFFFFFFF);
  const auto barrett_reduction_constants =
      _mm_set_epi32(0x1, 0xDB710641, 0x1, 0xF7011641);
  const auto res2 = _mm_clmulepi64_si128(
      _mm_and_si128(res1, mask32), barrett_reduction_constants, 0x00);
  const auto res3 = _mm_clmulepi64_si128(
      _mm_and_si128(res2, mask32), barrett_reduction_constants, 0x10);
  return _mm_cvtsi128_si32(_mm_srli_si128(_mm_xor_si128(res3, res1), 4));
}

#else

static uint32_t gf_multiply_crc32c_hw(uint64_t, uint64_t, uint32_t) {
  return 0;
}
static uint32_t gf_multiply_crc32_hw(uint64_t, uint64_t, uint32_t) {
  return 0;
}

#endif

/*
 * Pre-calculated powers tables for crc32c and crc32.
 */
static constexpr std::array<uint32_t, 62> const crc32c_powers =
    gf_powers_make<0x82f63b78>{}(make_index_sequence<62>{});
static constexpr std::array<uint32_t, 62> const crc32_powers =
    gf_powers_make<0xedb88320>{}(make_index_sequence<62>{});

template <typename F>
static uint32_t crc32_append_zeroes(
    F mult,
    uint32_t crc,
    size_t len,
    uint32_t polynomial,
    std::array<uint32_t, 62> const& powers_array) {
  auto powers = powers_array.data();

  // Append by multiplying by consecutive powers of two of the zeroes
  // array
  len >>= 2;

  while (len) {
    // Advance directly to next bit set.
    auto r = findFirstSet(len) - 1;
    len >>= r;
    powers += r;

    crc = mult(crc, *powers, polynomial);

    len >>= 1;
    powers++;
  }

  return crc;
}

namespace detail {

uint32_t crc32_combine_sw(uint32_t crc1, uint32_t crc2, size_t crc2len) {
  return crc2 ^
      crc32_append_zeroes(
             gf_multiply_sw, crc1, crc2len, 0xEDB88320, crc32_powers);
}

uint32_t crc32_combine_hw(uint32_t crc1, uint32_t crc2, size_t crc2len) {
  return crc2 ^
      crc32_append_zeroes(
             gf_multiply_crc32_hw, crc1, crc2len, 0xEDB88320, crc32_powers);
}

uint32_t crc32c_combine_sw(uint32_t crc1, uint32_t crc2, size_t crc2len) {
  return crc2 ^
      crc32_append_zeroes(
             gf_multiply_sw, crc1, crc2len, 0x82F63B78, crc32c_powers);
}

uint32_t crc32c_combine_hw(uint32_t crc1, uint32_t crc2, size_t crc2len) {
  return crc2 ^
      crc32_append_zeroes(
             gf_multiply_crc32c_hw, crc1, crc2len, 0x82F63B78, crc32c_powers);
}

} // namespace detail

} // namespace folly
<|endoftext|>


<commit_before>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/concept/printable/stream.hpp"
#include "vast/concept/printable/vast/error.hpp"
#include "vast/concept/printable/vast/event.hpp"
#include "vast/concept/printable/vast/expression.hpp"
#include "vast/bitmap.hpp"

#include "vast/system/indexer.hpp"

#define SUITE indexer
#include "test.hpp"
#include "fixtures/actor_system_and_events.hpp"

using namespace caf;
using namespace vast;

namespace {

struct fixture : fixtures::deterministic_actor_system_and_events {
  void init(type event_type) {
    indexer = self->spawn(system::indexer, directory, event_type);
    run_exhaustively();
  }

  void init(std::vector<event> events) {
    VAST_ASSERT(!events.empty());
    auto event_type = events.front().type();
    init(event_type);
    VAST_ASSERT(std::all_of(events.begin(), events.end(), [&](const event& x) {
      return x.type() == event_type;
    }));
    self->send(indexer, std::move(events));
    run_exhaustively();
  }

  ids query(std::string_view what) {
    auto pred = unbox(to<expression>(what));
    return request<ids>(indexer, std::move(pred));
  }

  actor indexer;
};

} // namespace <anonymous>

FIXTURE_SCOPE(indexer_tests, fixture)

TEST(integer rows) {
  MESSAGE("ingest integer events");
  integer_type layout;
  std::vector<int> ints{1, 2, 3, 1, 2, 3, 1, 2, 3};
  std::vector<event> events;
  for (auto i : ints)
    events.emplace_back(event::make(i, layout, events.size()));
  auto res = [&](auto... args) {
    return make_ids({args...}, events.size());
  };
  init(events);
  sched.run();
  MESSAGE("verify table index");
  auto verify = [&] {
    CHECK_EQUAL(query(":int == +1"), res(0, 3, 6));
    CHECK_EQUAL(query(":int == +2"), res(1, 4, 7));
    CHECK_EQUAL(query(":int == +3"), res(2, 5, 8));
    CHECK_EQUAL(query(":int == +4"), res());
    CHECK_EQUAL(query(":int != +1"), res(1, 2, 4, 5, 7, 8));
    CHECK_EQUAL(query("!(:int == +1)"), res(1, 2, 4, 5, 7, 8));
    CHECK_EQUAL(query(":int > +1 && :int < +3"), res(1, 4, 7));
  };
  verify();
  MESSAGE("kill INDEXER");
  anon_send_exit(indexer, exit_reason::kill);
  run_exhaustively();
  MESSAGE("reload INDEXER from disk");
  init(layout);
  MESSAGE("verify table index again");
  verify();
}

TEST(bro conn logs) {
  MESSAGE("ingest bro conn log");
  init(bro_conn_log);
  MESSAGE("verify table index");
  auto verify = [&] {
    CHECK_EQUAL(rank(query("id.resp_p == 995/?")), 53u);
    CHECK_EQUAL(rank(query("id.resp_p == 5355/?")), 49u);
    CHECK_EQUAL(rank(query("id.resp_p == 995/? || id.resp_p == 5355/?")), 102u);
    CHECK_EQUAL(rank(query("&time > 1970-01-01")), bro_conn_log.size());
    CHECK_EQUAL(rank(query("proto == \"udp\"")), 5306u);
    CHECK_EQUAL(rank(query("proto == \"tcp\"")), 3135u);
    CHECK_EQUAL(rank(query("uid == \"nkCxlvNN8pi\"")), 1u);
    CHECK_EQUAL(rank(query("orig_bytes < 400")), 5332u);
    CHECK_EQUAL(rank(query("orig_bytes < 400 && proto == \"udp\"")), 4357u);
    CHECK_EQUAL(rank(query(":addr == 65.55.184.16")), 2u);
  };
  verify();
  MESSAGE("kill INDEXER");
  anon_send_exit(indexer, exit_reason::kill);
  run_exhaustively();
  MESSAGE("reload INDEXER from disk");
  init(bro_conn_log.front().type());
  MESSAGE("verify table index again");
  verify();
}

FIXTURE_SCOPE_END()
<commit_msg>Add query to INDEXER test<commit_after>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/concept/printable/stream.hpp"
#include "vast/concept/printable/vast/error.hpp"
#include "vast/concept/printable/vast/event.hpp"
#include "vast/concept/printable/vast/expression.hpp"
#include "vast/bitmap.hpp"

#include "vast/system/indexer.hpp"

#define SUITE indexer
#include "test.hpp"
#include "fixtures/actor_system_and_events.hpp"

using namespace caf;
using namespace vast;

namespace {

struct fixture : fixtures::deterministic_actor_system_and_events {
  void init(type event_type) {
    indexer = self->spawn(system::indexer, directory, event_type);
    run_exhaustively();
  }

  void init(std::vector<event> events) {
    VAST_ASSERT(!events.empty());
    auto event_type = events.front().type();
    init(event_type);
    VAST_ASSERT(std::all_of(events.begin(), events.end(), [&](const event& x) {
      return x.type() == event_type;
    }));
    self->send(indexer, std::move(events));
    run_exhaustively();
  }

  ids query(std::string_view what) {
    auto pred = unbox(to<expression>(what));
    return request<ids>(indexer, std::move(pred));
  }

  actor indexer;
};

} // namespace <anonymous>

FIXTURE_SCOPE(indexer_tests, fixture)

TEST(integer rows) {
  MESSAGE("ingest integer events");
  integer_type layout;
  std::vector<int> ints{1, 2, 3, 1, 2, 3, 1, 2, 3};
  std::vector<event> events;
  for (auto i : ints)
    events.emplace_back(event::make(i, layout, events.size()));
  auto res = [&](auto... args) {
    return make_ids({args...}, events.size());
  };
  init(events);
  sched.run();
  MESSAGE("verify table index");
  auto verify = [&] {
    CHECK_EQUAL(query(":int == +1"), res(0, 3, 6));
    CHECK_EQUAL(query(":int == +2"), res(1, 4, 7));
    CHECK_EQUAL(query(":int == +3"), res(2, 5, 8));
    CHECK_EQUAL(query(":int == +4"), res());
    CHECK_EQUAL(query(":int != +1"), res(1, 2, 4, 5, 7, 8));
    CHECK_EQUAL(query("!(:int == +1)"), res(1, 2, 4, 5, 7, 8));
    CHECK_EQUAL(query(":int > +1 && :int < +3"), res(1, 4, 7));
  };
  verify();
  MESSAGE("kill INDEXER");
  anon_send_exit(indexer, exit_reason::kill);
  run_exhaustively();
  MESSAGE("reload INDEXER from disk");
  init(layout);
  MESSAGE("verify table index again");
  verify();
}

TEST(bro conn logs) {
  MESSAGE("ingest bro conn log");
  init(bro_conn_log);
  MESSAGE("verify table index");
  auto res = [&](auto... args) {
    return make_ids({args...}, bro_conn_log.size());
  };
  auto verify = [&] {
    CHECK_EQUAL(rank(query("id.resp_p == 995/?")), 53u);
    CHECK_EQUAL(rank(query("id.resp_p == 5355/?")), 49u);
    CHECK_EQUAL(rank(query("id.resp_p == 995/? || id.resp_p == 5355/?")), 102u);
    CHECK_EQUAL(rank(query("&time > 1970-01-01")), bro_conn_log.size());
    CHECK_EQUAL(rank(query("proto == \"udp\"")), 5306u);
    CHECK_EQUAL(rank(query("proto == \"tcp\"")), 3135u);
    CHECK_EQUAL(rank(query("uid == \"nkCxlvNN8pi\"")), 1u);
    CHECK_EQUAL(rank(query("orig_bytes < 400")), 5332u);
    CHECK_EQUAL(rank(query("orig_bytes < 400 && proto == \"udp\"")), 4357u);
    CHECK_EQUAL(rank(query(":addr == 65.55.184.16")), 2u);
    CHECK_EQUAL(query(":addr == 169.254.225.22"), res(680, 682, 719, 720));
  };
  verify();
  MESSAGE("kill INDEXER");
  anon_send_exit(indexer, exit_reason::kill);
  run_exhaustively();
  MESSAGE("reload INDEXER from disk");
  init(bro_conn_log.front().type());
  MESSAGE("verify table index again");
  verify();
}

FIXTURE_SCOPE_END()
<|endoftext|>


<commit_before>// error: more than one ambiguous alternative succeeds

// originally found in package bzip2

struct S{ int x; } *s;

int foo() {
    s->x < 1 || 2 > (3);
}
<commit_msg>Added more test cases (the "s->z < 1 || 2 > (3)" fix didn't work for similar constructs in C)<commit_after>// error: more than one ambiguous alternative succeeds

// originally found in package bzip2

struct S{ int z; } *s;

int foo() {
    int x, y;

    s->z < 1 || 2 > (3);
    s->z < 1 && 2 > (3);

    x < 1 || y > (3);
    x < 1 && y > (3);

    x < 1 || 2 > (3);
    x < 1 && y > (3);
}
<|endoftext|>


<commit_before>// nested template class

// originally found in package 'monotone' (Boost headers)

// In state 159, I expected one of these tokens:
//   <name>,
// k0066.cc:12:19: Parse error (state 159) at <

// ERR-MATCH: Parse error .state 159. at <

template< template< typename T1 > class F >
struct S;
<commit_msg>State 157 or 159<commit_after>// nested template class

// originally found in package 'monotone' (Boost headers)

// In state 159, I expected one of these tokens:
//   <name>,
// k0066.cc:12:19: Parse error (state 159) at <

// ERR-MATCH: Parse error .state (157|159). at <

template< template< typename T1 > class F >
struct S;
<|endoftext|>