<commit_before>#include <node.h>

#include <stdint.h>
#include <cstring>
#include <string>
#include <tuple>

#include "../argon2/include/argon2.h"
#include "argon2_node.h"

namespace NodeArgon2 {

#define GET_ARG(type, index) Nan::To<type>(info[index]).FromJust()

using size_type = std::string::size_type;
const auto HASH_LEN = 32u;

constexpr auto log(uint64_t number, uint64_t base = 2u) -> decltype(number)
{
    return (number > 1) ? 1u + log(number / base, base) : 0u;
}

constexpr auto base64Length(size_type length) -> decltype(length)
{
    return static_cast<decltype(length)>(std::ceil(length / 3.0)) * 4u;
}

auto encodedLength(size_type saltLength) -> decltype(saltLength)
{
    /* statically calculate maximum encoded hash length */
    constexpr size_type extraLength = sizeof "$argon2x$m=,t=,p=$$" +
        log(ARGON2_MAX_MEMORY + 1u, 10u) + log(ARGON2_MAX_TIME + 1u, 10u) +
        log(ARGON2_MAX_LANES + 1u, 10u) + base64Length(HASH_LEN);

    /* (number + 3) & ~3 rounds up to the nearest 4-byte boundary */
    return extraLength + base64Length(saltLength);
}

HashAsyncWorker::HashAsyncWorker(std::string&& plain, std::string&& salt,
        std::tuple<uint32_t, uint32_t, uint32_t, argon2_type>&& params):
    Nan::AsyncWorker{nullptr}, plain{plain}, salt{salt},
    time_cost{std::get<0>(params)}, memory_cost{std::get<1>(params)},
    parallelism{std::get<2>(params)}, type{std::get<3>(params)}, output{}
{ }

void HashAsyncWorker::Execute()
{
    const auto ENCODED_LEN = encodedLength(salt.size());
    output.reset(new char[ENCODED_LEN]);

    auto result = argon2_hash(time_cost, memory_cost, parallelism,
            plain.c_str(), plain.size(), salt.c_str(), salt.size(), nullptr,
            HASH_LEN, output.get(), ENCODED_LEN, type);

    if (result != ARGON2_OK) {
        /* LCOV_EXCL_START */
        SetErrorMessage(argon2_error_message(result));
        /* LCOV_EXCL_STOP */
    }
}

void HashAsyncWorker::HandleOKCallback()
{
    using namespace v8;
    using std::strlen;

    Nan::HandleScope scope;

    auto promise = GetFromPersistent(1).As<Promise::Resolver>();
    auto value = Nan::Encode(output.get(), strlen(output.get()));
    promise->Resolve(Nan::GetCurrentContext(), value);
}

/* LCOV_EXCL_START */
void HashAsyncWorker::HandleErrorCallback()
{
    using namespace v8;

    Nan::HandleScope scope;

    auto promise = GetFromPersistent(1).As<Promise::Resolver>();
    auto reason = Nan::New(ErrorMessage()).ToLocalChecked();
    promise->Reject(Nan::GetCurrentContext(), Exception::Error(reason));
}
/* LCOV_EXCL_STOP */

NAN_METHOD(Hash) {
    using namespace node;
    using namespace v8;

    assert(info.Length() >= 6);

    const auto plain = Nan::To<Object>(info[0]).ToLocalChecked();
    const auto salt = Nan::To<Object>(info[1]).ToLocalChecked();

    auto worker = new HashAsyncWorker{
            {Buffer::Data(plain), Buffer::Length(plain)},
            {Buffer::Data(salt), Buffer::Length(salt)},
            std::make_tuple(GET_ARG(uint32_t, 2), 1u << GET_ARG(uint32_t, 3),
                GET_ARG(uint32_t, 4), GET_ARG(bool, 5) ? Argon2_d : Argon2_i)};

    auto resolver = Promise::Resolver::New(Nan::GetCurrentContext()).ToLocalChecked();
    worker->SaveToPersistent(1, resolver);

    Nan::AsyncQueueWorker(worker);
    info.GetReturnValue().Set(resolver->GetPromise());
}

NAN_METHOD(HashSync) {
    using namespace node;
    using namespace v8;
    using std::strlen;

    assert(info.Length() >= 6);

    const auto plain = Nan::To<Object>(info[0]).ToLocalChecked();
    const auto salt = Nan::To<Object>(info[1]).ToLocalChecked();

    const auto ENCODED_LEN = encodedLength(Buffer::Length(salt));
    auto output = std::unique_ptr<char[]>{new char[ENCODED_LEN]};

    auto result = argon2_hash(GET_ARG(uint32_t, 2), 1u << GET_ARG(uint32_t, 3),
            GET_ARG(uint32_t, 4), Buffer::Data(plain), Buffer::Length(plain),
            Buffer::Data(salt), Buffer::Length(salt), nullptr, HASH_LEN,
            output.get(), ENCODED_LEN, GET_ARG(bool, 5) ? Argon2_d : Argon2_i);

    if (result != ARGON2_OK) {
        /* LCOV_EXCL_START */
        Nan::ThrowError(argon2_error_message(result));
        return;
        /* LCOV_EXCL_STOP */
    }

    info.GetReturnValue().Set(Nan::Encode(output.get(), strlen(output.get())));
}

VerifyAsyncWorker::VerifyAsyncWorker(std::string&& hash, std::string&& plain,
        argon2_type type):
    Nan::AsyncWorker{nullptr}, hash{hash}, plain{plain}, type{type}, output{}
{ }

void VerifyAsyncWorker::Execute()
{
    auto result = argon2_verify(hash.c_str(), plain.c_str(), plain.size(), type);

    switch (result) {
        case ARGON2_OK:
        case ARGON2_VERIFY_MISMATCH:
            output = result == ARGON2_OK;
            break;
        default:
            /* LCOV_EXCL_START */
            SetErrorMessage(argon2_error_message(result));
            break;
            /* LCOV_EXCL_STOP */
    }
}

void VerifyAsyncWorker::HandleOKCallback()
{
    using namespace v8;

    Nan::HandleScope scope;

    auto promise = GetFromPersistent(1).As<Promise::Resolver>();
    promise->Resolve(Nan::GetCurrentContext(), Nan::New(output));
}

/* LCOV_EXCL_START */
void VerifyAsyncWorker::HandleErrorCallback()
{
    using namespace v8;

    Nan::HandleScope scope;

    auto promise = GetFromPersistent(1).As<Promise::Resolver>();
    auto reason = Nan::New(ErrorMessage()).ToLocalChecked();
    promise->Reject(Nan::GetCurrentContext(), Exception::Error(reason));
}
/* LCOV_EXCL_STOP */

NAN_METHOD(Verify) {
    using namespace node;
    using namespace v8;

    assert(info.Length() >= 3);

    Nan::Utf8String hash{Nan::To<String>(info[0]).ToLocalChecked()};
    const auto plain = Nan::To<Object>(info[1]).ToLocalChecked();
    auto type = GET_ARG(bool, 2) ? Argon2_d : Argon2_i;

    auto worker = new VerifyAsyncWorker(*hash,
            {Buffer::Data(plain), Buffer::Length(plain)}, type);

    auto resolver = Promise::Resolver::New(Nan::GetCurrentContext()).ToLocalChecked();
    worker->SaveToPersistent(1, resolver);

    Nan::AsyncQueueWorker(worker);
    info.GetReturnValue().Set(resolver->GetPromise());
}

NAN_METHOD(VerifySync) {
    using namespace node;
    using namespace v8;

    assert(info.Length() >= 3);

    Nan::Utf8String hash{Nan::To<String>(info[0]).ToLocalChecked()};
    const auto plain = Nan::To<Object>(info[1]).ToLocalChecked();

    auto result = argon2_verify(*hash, Buffer::Data(plain),
            Buffer::Length(plain), GET_ARG(bool, 2) ? Argon2_d : Argon2_i);

    switch (result) {
        case ARGON2_OK:
        case ARGON2_VERIFY_MISMATCH:
            info.GetReturnValue().Set(result == ARGON2_OK);
            break;
        default:
            /* LCOV_EXCL_START */
            Nan::ThrowError(argon2_error_message(result));
            break;
            /* LCOV_EXCL_STOP */
    }
}

NAN_MODULE_INIT(init) {
    using namespace v8;

    auto limits = Nan::New<Object>();

    #define setMaxMin(target, max, min) \
        auto target = Nan::New<Object>(); \
        Nan::Set(target, Nan::New("max").ToLocalChecked(), Nan::New<Number>(max)); \
        Nan::Set(target, Nan::New("min").ToLocalChecked(), Nan::New<Number>(min)); \
        Nan::Set(limits, Nan::New(#target).ToLocalChecked(), target);

    setMaxMin(memoryCost, log(ARGON2_MAX_MEMORY), log(ARGON2_MIN_MEMORY));
    setMaxMin(timeCost, ARGON2_MAX_TIME, ARGON2_MIN_TIME);
    setMaxMin(parallelism, ARGON2_MAX_LANES, ARGON2_MIN_LANES);

    #undef setMaxMin

    Nan::Set(target, Nan::New("limits").ToLocalChecked(), limits);
    Nan::Export(target, "hash", Hash);
    Nan::Export(target, "hashSync", HashSync);
    Nan::Export(target, "verify", Verify);
    Nan::Export(target, "verifySync", VerifySync);
}

#undef GET_ARG

}

NODE_MODULE(argon2_lib, NodeArgon2::init);
<commit_msg>Use a simpler version of base64 length formula<commit_after>#include <node.h>

#include <stdint.h>
#include <cstring>
#include <string>
#include <tuple>

#include "../argon2/include/argon2.h"
#include "argon2_node.h"

namespace NodeArgon2 {

#define GET_ARG(type, index) Nan::To<type>(info[index]).FromJust()

using size_type = std::string::size_type;
const auto HASH_LEN = 32u;

constexpr auto log(uint64_t number, uint64_t base = 2u) -> decltype(number)
{
    return (number > 1) ? 1u + log(number / base, base) : 0u;
}

constexpr auto base64Length(size_type length) -> decltype(length)
{
    return ((length  + 2u) / 3u) * 4u;
}

auto encodedLength(size_type saltLength) -> decltype(saltLength)
{
    /* statically calculate maximum encoded hash length */
    constexpr size_type extraLength = sizeof "$argon2x$m=,t=,p=$$" +
        log(ARGON2_MAX_MEMORY + 1u, 10u) + log(ARGON2_MAX_TIME + 1u, 10u) +
        log(ARGON2_MAX_LANES + 1u, 10u) + base64Length(HASH_LEN);

    /* (number + 3) & ~3 rounds up to the nearest 4-byte boundary */
    return extraLength + base64Length(saltLength);
}

HashAsyncWorker::HashAsyncWorker(std::string&& plain, std::string&& salt,
        std::tuple<uint32_t, uint32_t, uint32_t, argon2_type>&& params):
    Nan::AsyncWorker{nullptr}, plain{plain}, salt{salt},
    time_cost{std::get<0>(params)}, memory_cost{std::get<1>(params)},
    parallelism{std::get<2>(params)}, type{std::get<3>(params)}, output{}
{ }

void HashAsyncWorker::Execute()
{
    const auto ENCODED_LEN = encodedLength(salt.size());
    output.reset(new char[ENCODED_LEN]);

    auto result = argon2_hash(time_cost, memory_cost, parallelism,
            plain.c_str(), plain.size(), salt.c_str(), salt.size(), nullptr,
            HASH_LEN, output.get(), ENCODED_LEN, type);

    if (result != ARGON2_OK) {
        /* LCOV_EXCL_START */
        SetErrorMessage(argon2_error_message(result));
        /* LCOV_EXCL_STOP */
    }
}

void HashAsyncWorker::HandleOKCallback()
{
    using namespace v8;
    using std::strlen;

    Nan::HandleScope scope;

    auto promise = GetFromPersistent(1).As<Promise::Resolver>();
    auto value = Nan::Encode(output.get(), strlen(output.get()));
    promise->Resolve(Nan::GetCurrentContext(), value);
}

/* LCOV_EXCL_START */
void HashAsyncWorker::HandleErrorCallback()
{
    using namespace v8;

    Nan::HandleScope scope;

    auto promise = GetFromPersistent(1).As<Promise::Resolver>();
    auto reason = Nan::New(ErrorMessage()).ToLocalChecked();
    promise->Reject(Nan::GetCurrentContext(), Exception::Error(reason));
}
/* LCOV_EXCL_STOP */

NAN_METHOD(Hash) {
    using namespace node;
    using namespace v8;

    assert(info.Length() >= 6);

    const auto plain = Nan::To<Object>(info[0]).ToLocalChecked();
    const auto salt = Nan::To<Object>(info[1]).ToLocalChecked();

    auto worker = new HashAsyncWorker{
            {Buffer::Data(plain), Buffer::Length(plain)},
            {Buffer::Data(salt), Buffer::Length(salt)},
            std::make_tuple(GET_ARG(uint32_t, 2), 1u << GET_ARG(uint32_t, 3),
                GET_ARG(uint32_t, 4), GET_ARG(bool, 5) ? Argon2_d : Argon2_i)};

    auto resolver = Promise::Resolver::New(Nan::GetCurrentContext()).ToLocalChecked();
    worker->SaveToPersistent(1, resolver);

    Nan::AsyncQueueWorker(worker);
    info.GetReturnValue().Set(resolver->GetPromise());
}

NAN_METHOD(HashSync) {
    using namespace node;
    using namespace v8;
    using std::strlen;

    assert(info.Length() >= 6);

    const auto plain = Nan::To<Object>(info[0]).ToLocalChecked();
    const auto salt = Nan::To<Object>(info[1]).ToLocalChecked();

    const auto ENCODED_LEN = encodedLength(Buffer::Length(salt));
    auto output = std::unique_ptr<char[]>{new char[ENCODED_LEN]};

    auto result = argon2_hash(GET_ARG(uint32_t, 2), 1u << GET_ARG(uint32_t, 3),
            GET_ARG(uint32_t, 4), Buffer::Data(plain), Buffer::Length(plain),
            Buffer::Data(salt), Buffer::Length(salt), nullptr, HASH_LEN,
            output.get(), ENCODED_LEN, GET_ARG(bool, 5) ? Argon2_d : Argon2_i);

    if (result != ARGON2_OK) {
        /* LCOV_EXCL_START */
        Nan::ThrowError(argon2_error_message(result));
        return;
        /* LCOV_EXCL_STOP */
    }

    info.GetReturnValue().Set(Nan::Encode(output.get(), strlen(output.get())));
}

VerifyAsyncWorker::VerifyAsyncWorker(std::string&& hash, std::string&& plain,
        argon2_type type):
    Nan::AsyncWorker{nullptr}, hash{hash}, plain{plain}, type{type}, output{}
{ }

void VerifyAsyncWorker::Execute()
{
    auto result = argon2_verify(hash.c_str(), plain.c_str(), plain.size(), type);

    switch (result) {
        case ARGON2_OK:
        case ARGON2_VERIFY_MISMATCH:
            output = result == ARGON2_OK;
            break;
        default:
            /* LCOV_EXCL_START */
            SetErrorMessage(argon2_error_message(result));
            break;
            /* LCOV_EXCL_STOP */
    }
}

void VerifyAsyncWorker::HandleOKCallback()
{
    using namespace v8;

    Nan::HandleScope scope;

    auto promise = GetFromPersistent(1).As<Promise::Resolver>();
    promise->Resolve(Nan::GetCurrentContext(), Nan::New(output));
}

/* LCOV_EXCL_START */
void VerifyAsyncWorker::HandleErrorCallback()
{
    using namespace v8;

    Nan::HandleScope scope;

    auto promise = GetFromPersistent(1).As<Promise::Resolver>();
    auto reason = Nan::New(ErrorMessage()).ToLocalChecked();
    promise->Reject(Nan::GetCurrentContext(), Exception::Error(reason));
}
/* LCOV_EXCL_STOP */

NAN_METHOD(Verify) {
    using namespace node;
    using namespace v8;

    assert(info.Length() >= 3);

    Nan::Utf8String hash{Nan::To<String>(info[0]).ToLocalChecked()};
    const auto plain = Nan::To<Object>(info[1]).ToLocalChecked();
    auto type = GET_ARG(bool, 2) ? Argon2_d : Argon2_i;

    auto worker = new VerifyAsyncWorker(*hash,
            {Buffer::Data(plain), Buffer::Length(plain)}, type);

    auto resolver = Promise::Resolver::New(Nan::GetCurrentContext()).ToLocalChecked();
    worker->SaveToPersistent(1, resolver);

    Nan::AsyncQueueWorker(worker);
    info.GetReturnValue().Set(resolver->GetPromise());
}

NAN_METHOD(VerifySync) {
    using namespace node;
    using namespace v8;

    assert(info.Length() >= 3);

    Nan::Utf8String hash{Nan::To<String>(info[0]).ToLocalChecked()};
    const auto plain = Nan::To<Object>(info[1]).ToLocalChecked();

    auto result = argon2_verify(*hash, Buffer::Data(plain),
            Buffer::Length(plain), GET_ARG(bool, 2) ? Argon2_d : Argon2_i);

    switch (result) {
        case ARGON2_OK:
        case ARGON2_VERIFY_MISMATCH:
            info.GetReturnValue().Set(result == ARGON2_OK);
            break;
        default:
            /* LCOV_EXCL_START */
            Nan::ThrowError(argon2_error_message(result));
            break;
            /* LCOV_EXCL_STOP */
    }
}

NAN_MODULE_INIT(init) {
    using namespace v8;

    auto limits = Nan::New<Object>();

    #define setMaxMin(target, max, min) \
        auto target = Nan::New<Object>(); \
        Nan::Set(target, Nan::New("max").ToLocalChecked(), Nan::New<Number>(max)); \
        Nan::Set(target, Nan::New("min").ToLocalChecked(), Nan::New<Number>(min)); \
        Nan::Set(limits, Nan::New(#target).ToLocalChecked(), target);

    setMaxMin(memoryCost, log(ARGON2_MAX_MEMORY), log(ARGON2_MIN_MEMORY));
    setMaxMin(timeCost, ARGON2_MAX_TIME, ARGON2_MIN_TIME);
    setMaxMin(parallelism, ARGON2_MAX_LANES, ARGON2_MIN_LANES);

    #undef setMaxMin

    Nan::Set(target, Nan::New("limits").ToLocalChecked(), limits);
    Nan::Export(target, "hash", Hash);
    Nan::Export(target, "hashSync", HashSync);
    Nan::Export(target, "verify", Verify);
    Nan::Export(target, "verifySync", VerifySync);
}

#undef GET_ARG

}

NODE_MODULE(argon2_lib, NodeArgon2::init);
<|endoftext|>


<commit_before>#include "echoS.h"

#include <iostream>

class Server : public CORBA::servant_traits<Example::Echo>::base_type
{
public:
  Server() = default;
  virtual ~Server() {};
  virtual std::string echoString(const std::string& mesg) override;
};

std::string Server::echoString(const std::string& mesg)
{
  std::cout << "Got \"" << mesg << "\", sending it back." << std::endl;
  return mesg;
}

int main(int argc, char** argv)
{
  try {
    IDL::traits<CORBA::ORB>::ref_type orb = CORBA::ORB_init (argc, argv);
    IDL::traits<CORBA::Object>::ref_type obj = orb->resolve_initial_references ("RootPOA");
    IDL::traits<PortableServer::POA>::ref_type poa = IDL::traits<PortableServer::POA>::narrow (obj);

   CORBA::servant_traits<Example::Echo>::ref_type server = CORBA::make_reference<Server> ();

   PortableServer::ObjectId id = poa->activate_object (server);

   std::string sior(orb->object_to_string(server->_this()));
   std::cout << sior << std::endl;

   IDL::traits<PortableServer::POAManager>::ref_type pman = poa->the_POAManager ();

   pman->activate();

   orb->run();
   orb->destroy();
  }
  catch (CORBA::SystemException& ex) {
    std::cerr << "Caught CORBA::" << ex << std::endl;
  }
  catch (CORBA::Exception& ex) {
    std::cerr << "Caught CORBA::Exception: " << ex << std::endl;
  }
  catch (std::exception& ex) {
    std::cerr << "Caught std exception: " << ex.what() << std::endl;
  }
  return 0;
}
<commit_msg>Layout changes     * cxx11/server.cpp:<commit_after>#include "echoS.h"

#include <iostream>

class Server : public CORBA::servant_traits<Example::Echo>::base_type
{
public:
  Server() = default;
  virtual ~Server() {};
  virtual std::string echoString(const std::string& mesg) override;
};

std::string Server::echoString(const std::string& mesg)
{
  std::cout << "Got \"" << mesg << "\", sending it back." << std::endl;
  return mesg;
}

int main(int argc, char** argv)
{
  try {
    IDL::traits<CORBA::ORB>::ref_type orb = CORBA::ORB_init (argc, argv);
    IDL::traits<CORBA::Object>::ref_type obj = orb->resolve_initial_references ("RootPOA");
    IDL::traits<PortableServer::POA>::ref_type poa = IDL::traits<PortableServer::POA>::narrow (obj);

    CORBA::servant_traits<Example::Echo>::ref_type server = CORBA::make_reference<Server> ();

    PortableServer::ObjectId id = poa->activate_object (server);

    std::string sior(orb->object_to_string(server->_this()));
    std::cout << sior << std::endl;

    IDL::traits<PortableServer::POAManager>::ref_type pman = poa->the_POAManager ();

    pman->activate();

    orb->run();
    orb->destroy();
  }
  catch (CORBA::SystemException& ex) {
    std::cerr << "Caught CORBA::" << ex << std::endl;
  }
  catch (CORBA::Exception& ex) {
    std::cerr << "Caught CORBA::Exception: " << ex << std::endl;
  }
  catch (std::exception& ex) {
    std::cerr << "Caught std exception: " << ex.what() << std::endl;
  }
  return 0;
}
<|endoftext|>


<commit_before>#pragma once

#include <faucet/Handled.hpp>
#include <faucet/Writable.hpp>

#include <boost/integer.hpp>
#include <vector>
#include <string>
#include <algorithm>

class Buffer : public Handled, public Writable {
	std::vector<uint8_t> data;
	std::vector<uint8_t>::iterator readIterator;
public:
	Buffer() : data(), readIterator(data.begin()) {}

	/**
	 * Empty the buffer.
	 */
	void clear() {
		data.clear();
		readIterator = data.begin();
	}

	/**
	 * Return the number of bytes currently in the buffer.
	 */
	size_t size() const {
		return data.size();
	}

	/**
	 * Return the number of bytes still remaining to be read.
	 */
	size_t bytesRemaining() const {
		return data.end()-readIterator;
	}

	/**
	 * Set the read position to the given byte index in the buffer.
	 */
	void setReadpos(size_t pos) {
		if(pos<=data.size()) {
			readIterator = data.begin()+pos;
		} else {
			readIterator = data.end();
		}
	}

	/**
	 * Append the given array to the end of the buffer.
	 */
	void write(const uint8_t *in, size_t size) {
		data.insert(data.end(), in, in+size);
	}

	/**
	 * Copy size bytes from the current read position of the buffer
	 * into the provided array. If less data is available,
	 * as much data as available is copied, and the rest of the
	 * provided array is not changed. The number of bytes
	 * actually read is returned.
	 */
	size_t read(uint8_t* out, size_t size) {
		size = std::min(size, bytesRemaining());
		std::copy(readIterator, readIterator+size, out);
		readIterator += size;
		return size;
	}

	/**
	 * Append a string to the buffer
	 *
	 * @param str A 0-terminated string
	 * @param withDelimiter Whether or not to copy the
	 * terminating 0 to the buffer
	 */
	void writeString(const char *str, bool withDelimiter) {
		size_t len = strlen(str);
		if(withDelimiter) {
			len++;
		}
		write(reinterpret_cast<const uint8_t *>(str), len);
	}

	/**
	 * Read len characters from the buffer and
	 * return them as a 0-terminated string. If less than len characters
	 * are available, the returned string will be shorter.
	 *
	 * Deleting the pointer is the caller's responsibility.
	 */
	char *readString(size_t len) {
		len = std::min(len, bytesRemaining());
		char *result = new char[len+1];
		read(reinterpret_cast<uint8_t *>(result), len);
		result[len] = 0;
		return result;
	}

	/**
	 * Read a 0-terminated string from the buffer and
	 * return it. If the buffer contains no 0
	 * value, the entire buffer plus an added 0
	 * will be returned in the string.
	 *
	 * Deleting the pointer is the caller's responsibility.
	 */
	char *readString() {
		size_t len = std::find(readIterator, data.end(), 0) - readIterator;
		char *result = readString(len);

		// Remove the separator too, unless we just read the entire buffer
		if(readIterator != data.end()) {
			++readIterator;
		}
		return result;
	}

	/**
	 * Get a pointer to the buffer contents
	 */
	const uint8_t *getData() const {
		return data.data();
	}
};
<commit_msg>Fixed buffer implementation (iterator member was being invalidated)<commit_after>#pragma once

#include <faucet/Handled.hpp>
#include <faucet/Writable.hpp>

#include <boost/integer.hpp>
#include <vector>
#include <string>
#include <algorithm>

class Buffer : public Handled, public Writable {
	std::vector<uint8_t> data;
	size_t readIndex;
public:
	Buffer() : data(), readIndex(0) {}

	/**
	 * Empty the buffer.
	 */
	void clear() {
		data.clear();
		readIndex = 0;
	}

	/**
	 * Return the number of bytes currently in the buffer.
	 */
	size_t size() const {
		return data.size();
	}

	/**
	 * Return the number of bytes still remaining to be read.
	 */
	size_t bytesRemaining() const {
		return size()-readIndex;
	}

	/**
	 * Set the read position to the given byte index in the buffer.
	 */
	void setReadpos(size_t pos) {
		if(pos<=data.size()) {
			readIndex = pos;
		} else {
			readIndex = size();
		}
	}

	/**
	 * Append the given array to the end of the buffer.
	 */
	void write(const uint8_t *in, size_t size) {
		data.insert(data.end(), in, in+size);
	}

	/**
	 * Copy size bytes from the current read position of the buffer
	 * into the provided array. If less data is available,
	 * as much data as available is copied, and the rest of the
	 * provided array is not changed. The number of bytes
	 * actually read is returned.
	 */
	size_t read(uint8_t* out, size_t size) {
		size = std::min(size, bytesRemaining());
		memcpy(out, data.data()+readIndex, size);
		readIndex += size;
		return size;
	}

	/**
	 * Append a string to the buffer
	 *
	 * @param str A 0-terminated string
	 * @param withDelimiter Whether or not to copy the
	 * terminating 0 to the buffer
	 */
	void writeString(const char *str, bool withDelimiter) {
		size_t len = strlen(str);
		if(withDelimiter) {
			len++;
		}
		write(reinterpret_cast<const uint8_t *>(str), len);
	}

	/**
	 * Read len characters from the buffer and
	 * return them as a 0-terminated string. If less than len characters
	 * are available, the returned string will be shorter.
	 *
	 * Deleting the pointer is the caller's responsibility.
	 */
	char *readString(size_t len) {
		len = std::min(len, bytesRemaining());
		char *result = new char[len+1];
		read(reinterpret_cast<uint8_t *>(result), len);
		result[len] = 0;
		return result;
	}

	/**
	 * Read a 0-terminated string from the buffer and
	 * return it. If the buffer contains no 0
	 * value, the entire buffer plus an added 0
	 * will be returned in the string.
	 *
	 * Deleting the pointer is the caller's responsibility.
	 */
	char *readString() {
		std::vector<uint8_t>::iterator readIterator = data.begin()+readIndex;
		size_t len = std::find(readIterator, data.end(), 0) - readIterator;
		char *result = readString(len);

		// Remove the separator too, unless we just read the entire buffer
		if(readIndex < size()) {
			++readIndex;
		}
		return result;
	}

	/**
	 * Get a pointer to the buffer contents
	 */
	const uint8_t *getData() const {
		return data.data();
	}
};
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 midnightBITS
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#ifndef __DBCONN_H__
#define __DBCONN_H__

#include <memory>
#include <utils.hpp>

namespace db
{
	struct Cursor;
	struct Statement;
	struct Connection;
	typedef std::shared_ptr<Connection> ConnectionPtr;
	typedef std::shared_ptr<Statement> StatementPtr;
	typedef std::shared_ptr<Cursor> CursorPtr;

	struct Cursor
	{
		virtual ~Cursor() {}
		virtual bool next() = 0;
		virtual size_t columnCount() = 0;
		virtual int getInt(int column) = 0;
		virtual long getLong(int column) = 0;
		virtual long long getLongLong(int column) = 0;
		virtual tyme::time_t getTimestamp(int column) = 0;
		virtual const char* getText(int column) = 0;
		virtual bool isNull(int column) = 0;
	};

	struct Statement
	{
		virtual ~Statement() {}
		virtual bool bind(int arg, int value) = 0;
		virtual bool bind(int arg, short value) = 0;
		virtual bool bind(int arg, long value) = 0;
		virtual bool bind(int arg, long long value) = 0;
		virtual bool bind(int arg, const char* value) = 0;
		virtual bool bindTime(int arg, tyme::time_t value) = 0;
		virtual bool bindNull(int arg) = 0;
		virtual bool execute() = 0;
		virtual CursorPtr query() = 0;
		virtual const char* errorMessage() = 0;
	};

	struct Connection
	{
		virtual ~Connection() {}
		virtual bool isStillAlive() = 0;
		virtual bool beginTransaction() = 0;
		virtual bool rollbackTransaction() = 0;
		virtual bool commitTransaction() = 0;
		virtual bool exec(const char* sql) = 0;
		virtual StatementPtr prepare(const char* sql) = 0;
		virtual StatementPtr prepare(const char* sql, long lowLimit, long hiLimit) = 0;
		virtual const char* errorMessage() = 0;
		virtual bool reconnect() = 0;
		static ConnectionPtr open(const char* path);
	};

	struct Transaction
	{
		enum State
		{
			UNKNOWN,
			BEGAN,
			COMMITED,
			REVERTED
		};

		State m_state;
		ConnectionPtr m_conn;
		Transaction(ConnectionPtr conn): m_state(UNKNOWN), m_conn(conn) {}
		~Transaction()
		{
			if (m_state == BEGAN)
				m_conn->rollbackTransaction();
		}
		bool begin()
		{
			if (m_state != UNKNOWN)
				return false;
			if (!m_conn->beginTransaction())
				return false;
			m_state = BEGAN;
			return true;
		}
		bool commit()
		{
			if (m_state != BEGAN)
				return false;
			m_state = COMMITED;
			return m_conn->commitTransaction();
		}
		bool rollback()
		{
			if (m_state != BEGAN)
				return false;
			m_state = REVERTED;
			return m_conn->rollbackTransaction();
		}
	};

	struct environment
	{
		bool failed;
		environment();
		~environment();
	};
};

#endif //__DBCONN_H__
<commit_msg>Column selectors for template programming<commit_after>/*
 * Copyright (C) 2013 midnightBITS
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#ifndef __DBCONN_H__
#define __DBCONN_H__

#include <memory>
#include <utils.hpp>

namespace db
{
	struct Cursor;
	struct Statement;
	struct Connection;
	typedef std::shared_ptr<Connection> ConnectionPtr;
	typedef std::shared_ptr<Statement> StatementPtr;
	typedef std::shared_ptr<Cursor> CursorPtr;

	struct Cursor
	{
		virtual ~Cursor() {}
		virtual bool next() = 0;
		virtual size_t columnCount() = 0;
		virtual int getInt(int column) = 0;
		virtual long getLong(int column) = 0;
		virtual long long getLongLong(int column) = 0;
		virtual tyme::time_t getTimestamp(int column) = 0;
		virtual const char* getText(int column) = 0;
		virtual bool isNull(int column) = 0;
	};

	struct time_tag {};

	template <typename Type> struct Selector;

	template <>
	struct Selector<int> { static int get(const CursorPtr& c, int column) { return c->getInt(column); } };

	template <>
	struct Selector<long> { static long get(const CursorPtr& c, int column) { return c->getLong(column); } };

	template <>
	struct Selector<long long> { static long long get(const CursorPtr& c, int column) { return c->getLongLong(column); } };

	template <>
	struct Selector<time_tag> { static tyme::time_t get(const CursorPtr& c, int column) { return c->getTimestamp(column); } };

	template <>
	struct Selector<const char*> { static const char* get(const CursorPtr& c, int column) { return c->getText(column); } };

	struct Statement
	{
		virtual ~Statement() {}
		virtual bool bind(int arg, int value) = 0;
		virtual bool bind(int arg, short value) = 0;
		virtual bool bind(int arg, long value) = 0;
		virtual bool bind(int arg, long long value) = 0;
		virtual bool bind(int arg, const char* value) = 0;
		virtual bool bindTime(int arg, tyme::time_t value) = 0;
		virtual bool bindNull(int arg) = 0;
		virtual bool execute() = 0;
		virtual CursorPtr query() = 0;
		virtual const char* errorMessage() = 0;
	};

	struct Connection
	{
		virtual ~Connection() {}
		virtual bool isStillAlive() = 0;
		virtual bool beginTransaction() = 0;
		virtual bool rollbackTransaction() = 0;
		virtual bool commitTransaction() = 0;
		virtual bool exec(const char* sql) = 0;
		virtual StatementPtr prepare(const char* sql) = 0;
		virtual StatementPtr prepare(const char* sql, long lowLimit, long hiLimit) = 0;
		virtual const char* errorMessage() = 0;
		virtual bool reconnect() = 0;
		static ConnectionPtr open(const char* path);
	};

	struct Transaction
	{
		enum State
		{
			UNKNOWN,
			BEGAN,
			COMMITED,
			REVERTED
		};

		State m_state;
		ConnectionPtr m_conn;
		Transaction(ConnectionPtr conn): m_state(UNKNOWN), m_conn(conn) {}
		~Transaction()
		{
			if (m_state == BEGAN)
				m_conn->rollbackTransaction();
		}
		bool begin()
		{
			if (m_state != UNKNOWN)
				return false;
			if (!m_conn->beginTransaction())
				return false;
			m_state = BEGAN;
			return true;
		}
		bool commit()
		{
			if (m_state != BEGAN)
				return false;
			m_state = COMMITED;
			return m_conn->commitTransaction();
		}
		bool rollback()
		{
			if (m_state != BEGAN)
				return false;
			m_state = REVERTED;
			return m_conn->rollbackTransaction();
		}
	};

	struct environment
	{
		bool failed;
		environment();
		~environment();
	};
};

#endif //__DBCONN_H__
<|endoftext|>


<commit_before><commit_msg>Move setupwizard modify handler code.<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sqlmessage.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-07-10 15:33:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef _DBAUI_SQLMESSAGE_HXX_
#define _DBAUI_SQLMESSAGE_HXX_

#ifndef _BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_BTNDLG_HXX
#include <vcl/btndlg.hxx>
#endif

#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif

#include <memory>

// some forwards
namespace com { namespace sun { namespace star {
    namespace sdb {
        class SQLContext;
    }
    namespace sdbc {
        class SQLException;
    }
} } }

//.........................................................................
namespace dbaui
{
//.........................................................................

//==================================================================
// OSQLMessageBox
//==================================================================
struct SQLMessageBox_Impl;
class OSQLMessageBox : public ButtonDialog
{
    FixedImage      m_aInfoImage;
    FixedText       m_aTitle;
    FixedText       m_aMessage;

    ::std::auto_ptr< SQLMessageBox_Impl >   m_pImpl;

public:
    enum MessageType
    {
        Info,
        Error,
        Warning,
        Query,

        AUTO
    };

public:
    /** display an SQLException with auto-recognizing a main and a detailed message

        The first two messages from the exception chain are used as main and detailed message (recognizing the
        detailed field of an <type scope="com::sun::star::sdb">SQLContext</type>).

        If only one message is present, a default title ("error reading ...") is used
    */
    OSQLMessageBox(Window* _pParent,
                const ::com::sun::star::sdbc::SQLException& _rError,
                WinBits _nStyle = WB_OK | WB_DEF_OK,
                MessageType _eImage = Error);

    /** display an SQLException with auto-recognizing a main and a detailed message

        The first two messages from the exception chain are used as main and detailed message (recognizing the
        detailed field of an <type scope="com::sun::star::sdb">SQLContext</type>).

        If only one message is present, a default title ("error reading ...") is used
    */
    OSQLMessageBox(Window* _pParent,
                const dbtools::SQLExceptionInfo& _rException,
                WinBits _nStyle = WB_OK | WB_DEF_OK,
                MessageType _eImage = AUTO);

    /** display a database related error message

        @param  rTitle      the title to display
        @param  rMessage    the detailed message to display
        @param  eImage      determines the image to use. AUTO is disallowed in this constructor version
    */
    OSQLMessageBox(Window* pParent,
                const UniString& rTitle,
                const UniString& rMessage,
                WinBits nStyle = WB_OK | WB_DEF_OK,
                MessageType eImage = Info);

    ~OSQLMessageBox();

private:
    void Construct( WinBits nStyle, MessageType eImage );

    DECL_LINK(ButtonClickHdl, Button* );

private:
    void    impl_positionControls();
    void    impl_initImage( MessageType _eImage );
    void    impl_createStandardButtons( WinBits _nStyle );
    void    impl_addDetailsButton();
};

//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // _DBAUI_SQLMESSAGE_HXX_

<commit_msg>INTEGRATION: CWS dba23a (1.5.118); FILE MERGED 2007/03/14 12:16:12 fs 1.5.118.1: #i75261# additional exception info a ctor without SQL exceptions<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sqlmessage.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 10:33:38 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef _DBAUI_SQLMESSAGE_HXX_
#define _DBAUI_SQLMESSAGE_HXX_

#ifndef _BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_BTNDLG_HXX
#include <vcl/btndlg.hxx>
#endif

#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif

#include <memory>

// some forwards
namespace com { namespace sun { namespace star {
    namespace sdb {
        class SQLContext;
    }
    namespace sdbc {
        class SQLException;
    }
} } }

//.........................................................................
namespace dbaui
{
//.........................................................................

//==================================================================
// OSQLMessageBox
//==================================================================
struct SQLMessageBox_Impl;
class OSQLMessageBox : public ButtonDialog
{
    FixedImage      m_aInfoImage;
    FixedText       m_aTitle;
    FixedText       m_aMessage;

    ::std::auto_ptr< SQLMessageBox_Impl >   m_pImpl;

public:
    enum MessageType
    {
        Info,
        Error,
        Warning,
        Query,

        AUTO
    };

public:
    /** display an SQLException with auto-recognizing a main and a detailed message

        The first two messages from the exception chain are used as main and detailed message (recognizing the
        detailed field of an <type scope="com::sun::star::sdb">SQLContext</type>).

        If only one message is present, a default title ("error reading ...") is used
    */
    OSQLMessageBox(Window* _pParent,
                const ::com::sun::star::sdbc::SQLException& _rError,
                WinBits _nStyle = WB_OK | WB_DEF_OK,
                MessageType _eImage = Error);

    /** display an SQLException with auto-recognizing a main and a detailed message

        The first two messages from the exception chain are used as main and detailed message (recognizing the
        detailed field of an <type scope="com::sun::star::sdb">SQLContext</type>).

        If only one message is present, a default title ("error reading ...") is used
    */
    OSQLMessageBox(Window* _pParent,
                const dbtools::SQLExceptionInfo& _rException,
                WinBits _nStyle = WB_OK | WB_DEF_OK,
                MessageType _eImage = AUTO);

    /** display a database related error message

        @param  rTitle      the title to display
        @param  rMessage    the detailed message to display
        @param  eImage      determines the image to use. AUTO is disallowed in this constructor version
    */
    OSQLMessageBox(Window* pParent,
                const UniString& rTitle,
                const UniString& rMessage,
                WinBits nStyle = WB_OK | WB_DEF_OK,
                MessageType eImage = Info,
                const ::dbtools::SQLExceptionInfo* _pAdditionalErrorInfo = NULL );

    ~OSQLMessageBox();

private:
    void Construct( WinBits nStyle, MessageType eImage );

    DECL_LINK(ButtonClickHdl, Button* );

private:
    void    impl_positionControls();
    void    impl_initImage( MessageType _eImage );
    void    impl_createStandardButtons( WinBits _nStyle );
    void    impl_addDetailsButton();
};

//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // _DBAUI_SQLMESSAGE_HXX_

<|endoftext|>


<commit_before>/**
 * \file demoOptimizationDmp.cpp
 * \author Freek Stulp
 * \brief  Demonstrates how to run an evolution strategy to optimize a Dmp.
 *
 * \ingroup Demos
 * \ingroup DMP_BBO
 *
 * This file is part of DmpBbo, a set of libraries and programs for the
 * black-box optimization of dynamical movement primitives.
 * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech
 *
 * DmpBbo 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 of the License, or
 * (at your option) any later version.
 *
 * DmpBbo 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 DmpBbo.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <string>
#include <set>
#include <eigen3/Eigen/Core>

#include "dmp_bbo/tasks/TaskViapoint.hpp"
#include "dmp_bbo/TaskSolverDmp.hpp"
#include "dmp_bbo/runOptimizationTask.hpp"

#include "dmp/Dmp.hpp"
#include "functionapproximators/ModelParametersLWR.hpp"
#include "functionapproximators/FunctionApproximatorLWR.hpp"

#include "bbo/DistributionGaussian.hpp"
#include "bbo/Updater.hpp"
#include "bbo/updaters/UpdaterCovarDecay.hpp"

#include "dmpbbo_io/EigenFileIO.hpp"

using namespace std;
using namespace Eigen;
using namespace DmpBbo;

/** Main function
 * \param[in] n_args Number of arguments
 * \param[in] args Arguments themselves
 * \return Success of exection. 0 if successful.
 */
int main(int n_args, char* args[])
{
  int n_dims = 1;
  string directory;
  if (n_args!=3)
  {
      cout << "Usage: " << args[0] << " n_dims directory" << endl;
      return -1;
  }
  else
  {
    n_dims = atoi(args[1]);
    directory = string(args[2]);
  }

  // Make the task
  VectorXd viapoint = VectorXd::Constant(n_dims,2.0);
  viapoint[0] = 2.5;
  double viapoint_time = 0.5;
  TaskViapoint* task = new TaskViapoint(viapoint,viapoint_time);

  // Some DMP parameters
  double tau = 1;
  VectorXd y_init = VectorXd::Constant(n_dims,1.0);
  VectorXd y_attr = VectorXd::Constant(n_dims,3.0);

  // Make the initial function approximators (LWR with zero slopes)
  int n_basis_functions = 4;
  VectorXd centers = VectorXd::LinSpaced(n_basis_functions,0,1);
  VectorXd widths  = VectorXd::Constant(n_basis_functions,0.2);
  VectorXd slopes  = VectorXd::Zero(n_basis_functions);
  VectorXd offsets = VectorXd::Zero(n_basis_functions);
  ModelParametersLWR* model_parameters = new ModelParametersLWR(centers,widths,slopes,offsets);
  vector<FunctionApproximator*> function_approximators(n_dims);
  for (int i_dim=0; i_dim<n_dims; i_dim++)
    function_approximators[i_dim] = new FunctionApproximatorLWR(model_parameters);

  Dmp* dmp = new Dmp(tau, y_init, y_attr, function_approximators, Dmp::KULVICIUS_2012_JOINING);

  // Make the task solver
  set<string> parameters_to_optimize;
  parameters_to_optimize.insert("offsets");
  parameters_to_optimize.insert("slopes");
  double dt=0.01;
  double integrate_dmp_beyond_tau_factor=1.2;
  bool use_normalized_parameter=true;
  TaskSolverDmp* task_solver = new TaskSolverDmp(dmp,parameters_to_optimize,
                                       dt,integrate_dmp_beyond_tau_factor,use_normalized_parameter);
  // task_solver->set_perturbation(1.0); // Add perturbations

  // Make the initial distribution
  VectorXd mean_init;
  dmp->getParameterVectorSelected(mean_init);

  MatrixXd covar_init = 1000.0*MatrixXd::Identity(mean_init.size(),mean_init.size());

  DistributionGaussian* distribution = new DistributionGaussian(mean_init,covar_init);

  // Make the parameter updater
  double eliteness = 10;
  double covar_decay_factor = 0.8;
  string weighting_method("PI-BB");
  Updater* updater = new UpdaterCovarDecay(eliteness, covar_decay_factor, weighting_method);

  // Run the optimization
  int n_updates = 40;
  int n_samples_per_update = 15;
  bool overwrite = true;
  saveMatrix(directory, "viapoint.txt",viapoint,overwrite);
  runOptimizationTask(task, task_solver, distribution, updater, n_updates, n_samples_per_update,directory,overwrite);

}<commit_msg>Use RBFN instead of LWR in demo<commit_after>/**
 * \file demoOptimizationDmp.cpp
 * \author Freek Stulp
 * \brief  Demonstrates how to run an evolution strategy to optimize a Dmp.
 *
 * \ingroup Demos
 * \ingroup DMP_BBO
 *
 * This file is part of DmpBbo, a set of libraries and programs for the
 * black-box optimization of dynamical movement primitives.
 * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech
 *
 * DmpBbo 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 of the License, or
 * (at your option) any later version.
 *
 * DmpBbo 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 DmpBbo.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <string>
#include <set>
#include <eigen3/Eigen/Core>

#include "dmp_bbo/tasks/TaskViapoint.hpp"
#include "dmp_bbo/TaskSolverDmp.hpp"
#include "dmp_bbo/runOptimizationTask.hpp"

#include "dmp/Dmp.hpp"
#include "functionapproximators/ModelParametersRBFN.hpp"
#include "functionapproximators/FunctionApproximatorRBFN.hpp"

#include "bbo/DistributionGaussian.hpp"
#include "bbo/Updater.hpp"
#include "bbo/updaters/UpdaterCovarDecay.hpp"

#include "dmpbbo_io/EigenFileIO.hpp"

using namespace std;
using namespace Eigen;
using namespace DmpBbo;

/** Main function
 * \param[in] n_args Number of arguments
 * \param[in] args Arguments themselves
 * \return Success of exection. 0 if successful.
 */
int main(int n_args, char* args[])
{
  int n_dims = 1;
  string directory;
  if (n_args!=3)
  {
      cout << "Usage: " << args[0] << " n_dims directory" << endl;
      return -1;
  }
  else
  {
    n_dims = atoi(args[1]);
    directory = string(args[2]);
  }

  // Make the task
  VectorXd viapoint = VectorXd::Constant(n_dims,2.0);
  viapoint[0] = 2.5;
  double viapoint_time = 0.5;
  TaskViapoint* task = new TaskViapoint(viapoint,viapoint_time);

  // Some DMP parameters
  double tau = 1;
  VectorXd y_init = VectorXd::Constant(n_dims,1.0);
  VectorXd y_attr = VectorXd::Constant(n_dims,3.0);

  // Make the initial function approximators (RBFN with zero slopes)
  int n_basis_functions = 8;
  VectorXd centers = VectorXd::LinSpaced(n_basis_functions,0.0,1.0);
  VectorXd widths  = VectorXd::Constant(n_basis_functions,0.2);
  VectorXd weights = VectorXd::Zero(n_basis_functions);
  ModelParametersRBFN* model_parameters = new ModelParametersRBFN(centers,widths,weights);
  vector<FunctionApproximator*> function_approximators(n_dims);
  for (int i_dim=0; i_dim<n_dims; i_dim++)
    function_approximators[i_dim] = new FunctionApproximatorRBFN(model_parameters);

  Dmp* dmp = new Dmp(tau, y_init, y_attr, function_approximators, Dmp::KULVICIUS_2012_JOINING);

  // Make the task solver
  set<string> parameters_to_optimize;
  parameters_to_optimize.insert("weights");
  double dt=0.01;
  double integrate_dmp_beyond_tau_factor=1.2;
  bool use_normalized_parameter=true;
  TaskSolverDmp* task_solver = new TaskSolverDmp(dmp,parameters_to_optimize,
                                       dt,integrate_dmp_beyond_tau_factor,use_normalized_parameter);
  // task_solver->set_perturbation(1.0); // Add perturbations

  // Make the initial distribution
  VectorXd mean_init;
  dmp->getParameterVectorSelected(mean_init);

  MatrixXd covar_init = 1000.0*MatrixXd::Identity(mean_init.size(),mean_init.size());

  DistributionGaussian* distribution = new DistributionGaussian(mean_init,covar_init);

  // Make the parameter updater
  double eliteness = 10;
  double covar_decay_factor = 0.8;
  string weighting_method("PI-BB");
  Updater* updater = new UpdaterCovarDecay(eliteness, covar_decay_factor, weighting_method);

  // Run the optimization
  int n_updates = 40;
  int n_samples_per_update = 15;
  bool overwrite = true;
  saveMatrix(directory, "viapoint.txt",viapoint,overwrite);
  runOptimizationTask(task, task_solver, distribution, updater, n_updates, n_samples_per_update,directory,overwrite);

}<|endoftext|>


<commit_before>/************************************************************************************
This source file is part of the Theora Video Playback Library
For latest info, see http://libtheoraplayer.sourceforge.net/
*************************************************************************************
Copyright (c) 2008-2012 Kresimir Spes (kspes@cateia.com)
This program is free software; you can redistribute it and/or modify it under
the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php
*************************************************************************************/

/************************************************************************************
COPYRIGHT INFO: The room 3D models and lightmap textures and textures are licensed
                under the terms of the GNU General Public License (GPL).
*************************************************************************************/
#define __3D_PROJECTION
#define __ZBUFFER
#include "demo_basecode.h"
#include <theoraplayer/TheoraPlayer.h>
#include <theoraplayer/TheoraDataSource.h>
#include "ObjModel.h"
#include "tga.h"
#include <math.h>

unsigned int tex_id, diffuse_map;
TheoraVideoManager* mgr;
TheoraVideoClip *light[3];
std::string window_name="lightmap_demo";
bool started=1;
int window_w=1024,window_h=768;

ObjModel room;
float anglex=0,angley=0;
unsigned char *light_data[3], *tex_data;
bool update_tex = 0;
bool light_switch[3] = {1, 0, 0};
float light_scale[3][3] = { {1, 1, 1}, {2, 0, 0}, {0, 2, 0}  };
int framew, frameh;

void multiTexFunc(float u, float v)
{
	glMultiTexCoord2fARB(GL_TEXTURE0_ARB, u, v);
	glMultiTexCoord2fARB(GL_TEXTURE1_ARB, u, v);
}

void draw()
{
	glClearColor(27/255.0f, 188/255.0f, 224/255.0f, 1);
	glBindTexture(GL_TEXTURE_2D,tex_id);

	glLoadIdentity();
	gluLookAt(sin(anglex)*100-100,angley+50,cos(anglex)*100-100,  -100,50,-100,  0,1,0);

	TheoraVideoFrame* f;
	for (int i = 0; i < 3; i++)
	{
		f = light[i]->getNextFrame();
		if (f)
		{
			memcpy(light_data[i], f->getBuffer(), framew * frameh * 3);
			light[i]->popFrame();
			update_tex = 1;
		}
	}

	if (update_tex)
	{
		int i, x, y;
		memset(tex_data, 0, framew * frameh * 3);
		unsigned char *ptr[3] = { light_data[0], light_data[1], light_data[2] };
		unsigned char *tex;
		unsigned int r, g, b;
		for (i = 0; i < 3; i++)
		{
			if (light_switch[i] == 0) continue;
			tex = tex_data;
			for (y = 0; y < frameh; y++)
			{
				for (x = 0; x < framew; x++)
				{
					r = tex[0] + ptr[i][0] * light_scale[i][0];
					g = tex[1] + ptr[i][1] * light_scale[i][1];
					b = tex[2] + ptr[i][2] * light_scale[i][2];
					tex[0] = r > 255 ? 255 : r;
					tex[1] = g > 255 ? 255 : g;
					tex[2] = b > 255 ? 255 : b;
					tex += 3;
					ptr[i] += 3;
				}
			}
		}
		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, framew, frameh, GL_RGB, GL_UNSIGNED_BYTE, tex_data);
		update_tex = 0;
	}

	glActiveTextureARB(GL_TEXTURE0_ARB);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, diffuse_map);
	glActiveTextureARB(GL_TEXTURE1_ARB);
	glEnable(GL_TEXTURE_2D);
	glTexEnvi(GL_TEXTURE_2D, GL_TEXTURE_ENV_MODE, GL_COMBINE);
	glTexEnvi(GL_TEXTURE_2D, GL_COMBINE_RGB_ARB, GL_MODULATE);
	glEnable(GL_CULL_FACE);
	room.draw(multiTexFunc);
	glDisable(GL_CULL_FACE);
}

void update(float time_increase)
{
	float x,y;
	getCursorPos(&x,&y);
	anglex=-4*3.14f*x/window_w;
	angley=1500*(y-300)/window_h;

	mgr->update(time_increase);
}

void OnKeyPress(int key)
{
	if (key == '1' || key == '2' || key == '3')
	{
		int i = key - '1';
		light_switch[i] = !light_switch[i];
		if (!light_switch[i]) light[i]->pause();
		else light[i]->play();
		update_tex = 1;
	}
}

void OnClick(float x,float y)
{

}

void setDebugTitle(char* out)
{
	sprintf(out, "lights: %d, %d, %d (press keys 1,2,3 to toggle lights)", (int) light_switch[0], (int) light_switch[1], (int) light_switch[2]);
}

void init()
{
	mgr=new TheoraVideoManager(3);
	light[0] = mgr->createVideoClip(new TheoraMemoryFileDataSource("media/lightmap/light1.ogg"), TH_RGB);
	light[1] = mgr->createVideoClip(new TheoraMemoryFileDataSource("media/lightmap/light2.ogg"), TH_RGB);
	light[2] = mgr->createVideoClip(new TheoraMemoryFileDataSource("media/lightmap/light3.ogg"), TH_RGB);
	light[0]->setAutoRestart(1); light[0]->setPlaybackSpeed(1.0f);
	light[1]->setAutoRestart(1); light[1]->setPlaybackSpeed(0.935f);
	light[2]->setAutoRestart(1); light[2]->setPlaybackSpeed(0.876f);
	if (!light_switch[0]) light[0]->pause();
	if (!light_switch[1]) light[1]->pause();
	if (!light_switch[2]) light[2]->pause();

	framew = light[0]->getWidth();
	frameh = light[0]->getHeight();
	int size = framew * frameh * 3;
	light_data[0] = new unsigned char[size];
	light_data[1] = new unsigned char[size];
	light_data[2] = new unsigned char[size];
	tex_data = new unsigned char[size];

	tex_id = createTexture(nextPow2(framew), nextPow2(frameh));
	diffuse_map = loadTexture("media/lightmap/diffuse_map.tga");

	room.load("media/lightmap/room.obj", tex_id);

	glDisable(GL_CULL_FACE);
	glCullFace(GL_BACK);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	glEnable(GL_COLOR_MATERIAL);
	getMultiTextureExtensionFuncPointers();
}

void destroy()
{
	delete [] light_data[0];
	delete [] light_data[1];
	delete [] light_data[2];
	delete [] tex_data;
	delete mgr;
}
<commit_msg>lightmap demo: defaulting to white texture when all lights are disabled<commit_after>/************************************************************************************
This source file is part of the Theora Video Playback Library
For latest info, see http://libtheoraplayer.sourceforge.net/
*************************************************************************************
Copyright (c) 2008-2012 Kresimir Spes (kspes@cateia.com)
This program is free software; you can redistribute it and/or modify it under
the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php
*************************************************************************************/

/************************************************************************************
COPYRIGHT INFO: The room 3D models and lightmap textures and textures are licensed
                under the terms of the GNU General Public License (GPL).
*************************************************************************************/
#define __3D_PROJECTION
#define __ZBUFFER
#include "demo_basecode.h"
#include <theoraplayer/TheoraPlayer.h>
#include <theoraplayer/TheoraDataSource.h>
#include "ObjModel.h"
#include "tga.h"
#include <math.h>

unsigned int tex_id, diffuse_map;
TheoraVideoManager* mgr;
TheoraVideoClip *light[3];
std::string window_name="lightmap_demo";
bool started=1;
int window_w=1024,window_h=768;

ObjModel room;
float anglex=0,angley=0;
unsigned char *light_data[3], *tex_data;
bool update_tex = 0;
bool light_switch[3] = {1, 0, 0};
float light_scale[3][3] = { {1, 1, 1}, {2, 0, 0}, {0, 2, 0}  };
int framew, frameh;

void multiTexFunc(float u, float v)
{
	glMultiTexCoord2fARB(GL_TEXTURE0_ARB, u, v);
	glMultiTexCoord2fARB(GL_TEXTURE1_ARB, u, v);
}

void draw()
{
	glClearColor(27/255.0f, 188/255.0f, 224/255.0f, 1);
	glBindTexture(GL_TEXTURE_2D,tex_id);

	glLoadIdentity();
	gluLookAt(sin(anglex)*100-100,angley+50,cos(anglex)*100-100,  -100,50,-100,  0,1,0);

	TheoraVideoFrame* f;
	for (int i = 0; i < 3; i++)
	{
		f = light[i]->getNextFrame();
		if (f)
		{
			memcpy(light_data[i], f->getBuffer(), framew * frameh * 3);
			light[i]->popFrame();
			update_tex = 1;
		}
	}

	if (update_tex)
	{
		int i, x, y;
		memset(tex_data, light_switch[0] == 0 && light_switch[1] == 0 && light_switch[2] == 0 ? 255 : 0, framew * frameh * 3);
		unsigned char *ptr[3] = { light_data[0], light_data[1], light_data[2] };
		unsigned char *tex;
		unsigned int r, g, b;
		for (i = 0; i < 3; i++)
		{
			if (light_switch[i] == 0) continue;
			tex = tex_data;
			for (y = 0; y < frameh; y++)
			{
				for (x = 0; x < framew; x++)
				{
					r = tex[0] + ptr[i][0] * light_scale[i][0];
					g = tex[1] + ptr[i][1] * light_scale[i][1];
					b = tex[2] + ptr[i][2] * light_scale[i][2];
					tex[0] = r > 255 ? 255 : r;
					tex[1] = g > 255 ? 255 : g;
					tex[2] = b > 255 ? 255 : b;
					tex += 3;
					ptr[i] += 3;
				}
			}
		}
		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, framew, frameh, GL_RGB, GL_UNSIGNED_BYTE, tex_data);
		update_tex = 0;
	}

	glActiveTextureARB(GL_TEXTURE0_ARB);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, diffuse_map);
	glActiveTextureARB(GL_TEXTURE1_ARB);
	glEnable(GL_TEXTURE_2D);
	glTexEnvi(GL_TEXTURE_2D, GL_TEXTURE_ENV_MODE, GL_COMBINE);
	glTexEnvi(GL_TEXTURE_2D, GL_COMBINE_RGB_ARB, GL_MODULATE);
	glEnable(GL_CULL_FACE);
	room.draw(multiTexFunc);
	glDisable(GL_CULL_FACE);
}

void update(float time_increase)
{
	float x,y;
	getCursorPos(&x,&y);
	anglex=-4*3.14f*x/window_w;
	angley=1500*(y-300)/window_h;

	mgr->update(time_increase);
}

void OnKeyPress(int key)
{
	if (key == '1' || key == '2' || key == '3')
	{
		int i = key - '1';
		light_switch[i] = !light_switch[i];
		if (!light_switch[i]) light[i]->pause();
		else light[i]->play();
		update_tex = 1;
	}
}

void OnClick(float x,float y)
{

}

void setDebugTitle(char* out)
{
	sprintf(out, "lights: %d, %d, %d (press keys 1,2,3 to toggle lights)", (int) light_switch[0], (int) light_switch[1], (int) light_switch[2]);
}

void init()
{
	mgr=new TheoraVideoManager(3);
	light[0] = mgr->createVideoClip(new TheoraMemoryFileDataSource("media/lightmap/light1.ogg"), TH_RGB);
	light[1] = mgr->createVideoClip(new TheoraMemoryFileDataSource("media/lightmap/light2.ogg"), TH_RGB);
	light[2] = mgr->createVideoClip(new TheoraMemoryFileDataSource("media/lightmap/light3.ogg"), TH_RGB);
	light[0]->setAutoRestart(1); light[0]->setPlaybackSpeed(1.0f);
	light[1]->setAutoRestart(1); light[1]->setPlaybackSpeed(0.935f);
	light[2]->setAutoRestart(1); light[2]->setPlaybackSpeed(0.876f);
	if (!light_switch[0]) light[0]->pause();
	if (!light_switch[1]) light[1]->pause();
	if (!light_switch[2]) light[2]->pause();

	framew = light[0]->getWidth();
	frameh = light[0]->getHeight();
	int size = framew * frameh * 3;
	light_data[0] = new unsigned char[size];
	light_data[1] = new unsigned char[size];
	light_data[2] = new unsigned char[size];
	tex_data = new unsigned char[size];

	tex_id = createTexture(nextPow2(framew), nextPow2(frameh));
	diffuse_map = loadTexture("media/lightmap/diffuse_map.tga");

	room.load("media/lightmap/room.obj", tex_id);

	glDisable(GL_CULL_FACE);
	glCullFace(GL_BACK);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	glEnable(GL_COLOR_MATERIAL);
	getMultiTextureExtensionFuncPointers();
}

void destroy()
{
	delete [] light_data[0];
	delete [] light_data[1];
	delete [] light_data[2];
	delete [] tex_data;
	delete mgr;
}
<|endoftext|>


<commit_before>#include <x0/flow/FlowToken.h>
#include <cstdio>
#include <assert.h>

namespace x0 {

bool FlowTokenTraits::isKeyword(FlowToken t)
{
	switch (t) {
		case FlowToken::Var:
		case FlowToken::On:
		case FlowToken::Do:
		case FlowToken::If:
		case FlowToken::Match:
		case FlowToken::Then:
		case FlowToken::Else:
		case FlowToken::Unless:
		case FlowToken::Import:
		case FlowToken::From:
		case FlowToken::Handler:
			return true;
		default:
			return false;
	}
}

bool FlowTokenTraits::isReserved(FlowToken t)
{
	switch (t) {
		default:
			return false;
	}
}

bool FlowTokenTraits::isType(FlowToken t)
{
	switch (t) {
		case FlowToken::VoidType:
		case FlowToken::BoolType:
		case FlowToken::NumberType:
		case FlowToken::StringType:
			return true;
		default:
			printf("unknown token: %d\n", (int)t);
			return false;
	}
}

bool FlowTokenTraits::isOperator(FlowToken t)
{
	switch (t) {
		case FlowToken::Assign:
		case FlowToken::Question:
		case FlowToken::And:
		case FlowToken::Or:
		case FlowToken::Xor:
		case FlowToken::Equal:
		case FlowToken::UnEqual:
		case FlowToken::Less:
		case FlowToken::Greater:
		case FlowToken::LessOrEqual:
		case FlowToken::GreaterOrEqual:
		case FlowToken::PrefixMatch:
		case FlowToken::SuffixMatch:
		case FlowToken::RegexMatch:
		case FlowToken::HashRocket:
		case FlowToken::Plus:
		case FlowToken::Minus:
		case FlowToken::Mul:
		case FlowToken::Div:
		case FlowToken::Shl:
		case FlowToken::Shr:
		case FlowToken::Comma:
		case FlowToken::Pow:
			return true;
		default:
			return false;
	}
}

bool FlowTokenTraits::isUnaryOp(FlowToken t)
{
	// token Plus and Minus can be both, unary and binary
	switch (t) {
		case FlowToken::Minus:
		case FlowToken::Plus:
		case FlowToken::Not:
			return true;
		default:
			return false;
	}
}

bool FlowTokenTraits::isPrimaryOp(FlowToken t)
{
	return false;
}

bool FlowTokenTraits::isRelOp(FlowToken t)
{
    switch (t) {
		case FlowToken::Equal:
		case FlowToken::UnEqual:
		case FlowToken::Less:
		case FlowToken::Greater:
		case FlowToken::LessOrEqual:
		case FlowToken::GreaterOrEqual:
		case FlowToken::PrefixMatch:
		case FlowToken::SuffixMatch:
		case FlowToken::RegexMatch:
            return true;
        default:
            return false;
    }
}

bool FlowTokenTraits::isLiteral(FlowToken t)
{
	switch (t) {
		case FlowToken::InterpolatedStringFragment:
		case FlowToken::InterpolatedStringEnd:
		case FlowToken::Boolean:
		case FlowToken::Number:
		case FlowToken::String:
		case FlowToken::RawString:
		case FlowToken::RegExp:
		case FlowToken::IP:
		case FlowToken::Cidr:
        case FlowToken::NamedParam:
			return true;
		default:
			return false;
	}
}

const char *FlowToken::c_str() const throw()
{
	switch (value_) {
		case FlowToken::Unknown: return "Unknown";
		case FlowToken::Boolean: return "Boolean";
		case FlowToken::Number: return "Number";
		case FlowToken::String: return "String";
		case FlowToken::RawString: return "RawString";
		case FlowToken::RegExp: return "RegExp";
		case FlowToken::IP: return "IP";
		case FlowToken::Cidr: return "CIDR";
		case FlowToken::Assign: return "=";
		case FlowToken::OrAssign: return "|=";
		case FlowToken::AndAssign: return "&=";
		case FlowToken::PlusAssign: return "+=";
		case FlowToken::MinusAssign: return "-=";
		case FlowToken::MulAssign: return "*=";
		case FlowToken::DivAssign: return "/=";
		case FlowToken::Semicolon: return ";";
		case FlowToken::Question: return "?";
		case FlowToken::Colon: return ":";
		case FlowToken::And: return "and";
		case FlowToken::Or: return "or";
		case FlowToken::Xor: return "xor";
		case FlowToken::Equal: return "==";
		case FlowToken::UnEqual: return "!=";
		case FlowToken::Less: return "<";
		case FlowToken::Greater: return ">";
		case FlowToken::LessOrEqual: return "<=";
		case FlowToken::GreaterOrEqual: return ">=";
		case FlowToken::PrefixMatch: return "=^";
		case FlowToken::SuffixMatch: return "=$";
		case FlowToken::RegexMatch: return "=~";
		case FlowToken::HashRocket: return "=>";
		case FlowToken::In: return "in";
		case FlowToken::Plus: return "+";
		case FlowToken::Minus: return "-";
		case FlowToken::Mul: return "*";
		case FlowToken::Div: return "/";
		case FlowToken::Mod: return "%";
		case FlowToken::Shl: return "shl";
		case FlowToken::Shr: return "shr";
		case FlowToken::Comma: return ",";
		case FlowToken::Pow: return "**";
		case FlowToken::Not: return "not";
		case FlowToken::BitOr: return "|";
		case FlowToken::BitAnd: return "&";
		case FlowToken::BitXor: return "^";
		case FlowToken::BrOpen: return "[";
		case FlowToken::BrClose: return "]";
		case FlowToken::RndOpen: return "(";
		case FlowToken::RndClose: return ")";
		case FlowToken::Begin: return "{";
		case FlowToken::End: return "}";
		case FlowToken::Var: return "var";
		case FlowToken::Do: return "do";
		case FlowToken::If: return "if";
		case FlowToken::Then: return "then";
		case FlowToken::Else: return "else";
		case FlowToken::Unless: return "unless";
		case FlowToken::Match: return "match";
		case FlowToken::On: return "on";
		case FlowToken::Import: return "import";
		case FlowToken::From: return "from";
		case FlowToken::Handler: return "handler";
		case FlowToken::VoidType: return "void()";
		case FlowToken::BoolType: return "bool()";
		case FlowToken::NumberType: return "int()";
		case FlowToken::StringType: return "string()";
		case FlowToken::Ident: return "Ident";
		case FlowToken::Period: return "Period";
		case FlowToken::DblPeriod: return "DblPeriod";
		case FlowToken::Ellipsis: return "Ellipsis";
		case FlowToken::Comment: return "Comment";
		case FlowToken::Eof: return "EOF";
        case FlowToken::NamedParam: return "NamedParam";
		case FlowToken::InterpolatedStringFragment: return "InterpolatedStringFragment";
		case FlowToken::InterpolatedStringEnd: return "InterpolatedStringEnd";
		default:
            assert(!"FIXME: Invalid Token.");
            abort();
	}
}

} // namespace x0
<commit_msg>[flow] FlowToken: adds missing include (fixes compile error on Ubuntu 12.04+clang3.4 aka. Travis-CI)<commit_after>#include <x0/flow/FlowToken.h>
#include <cstdio>
#include <cstdlib>
#include <assert.h>

namespace x0 {

bool FlowTokenTraits::isKeyword(FlowToken t)
{
	switch (t) {
		case FlowToken::Var:
		case FlowToken::On:
		case FlowToken::Do:
		case FlowToken::If:
		case FlowToken::Match:
		case FlowToken::Then:
		case FlowToken::Else:
		case FlowToken::Unless:
		case FlowToken::Import:
		case FlowToken::From:
		case FlowToken::Handler:
			return true;
		default:
			return false;
	}
}

bool FlowTokenTraits::isReserved(FlowToken t)
{
	switch (t) {
		default:
			return false;
	}
}

bool FlowTokenTraits::isType(FlowToken t)
{
	switch (t) {
		case FlowToken::VoidType:
		case FlowToken::BoolType:
		case FlowToken::NumberType:
		case FlowToken::StringType:
			return true;
		default:
			printf("unknown token: %d\n", (int)t);
			return false;
	}
}

bool FlowTokenTraits::isOperator(FlowToken t)
{
	switch (t) {
		case FlowToken::Assign:
		case FlowToken::Question:
		case FlowToken::And:
		case FlowToken::Or:
		case FlowToken::Xor:
		case FlowToken::Equal:
		case FlowToken::UnEqual:
		case FlowToken::Less:
		case FlowToken::Greater:
		case FlowToken::LessOrEqual:
		case FlowToken::GreaterOrEqual:
		case FlowToken::PrefixMatch:
		case FlowToken::SuffixMatch:
		case FlowToken::RegexMatch:
		case FlowToken::HashRocket:
		case FlowToken::Plus:
		case FlowToken::Minus:
		case FlowToken::Mul:
		case FlowToken::Div:
		case FlowToken::Shl:
		case FlowToken::Shr:
		case FlowToken::Comma:
		case FlowToken::Pow:
			return true;
		default:
			return false;
	}
}

bool FlowTokenTraits::isUnaryOp(FlowToken t)
{
	// token Plus and Minus can be both, unary and binary
	switch (t) {
		case FlowToken::Minus:
		case FlowToken::Plus:
		case FlowToken::Not:
			return true;
		default:
			return false;
	}
}

bool FlowTokenTraits::isPrimaryOp(FlowToken t)
{
	return false;
}

bool FlowTokenTraits::isRelOp(FlowToken t)
{
    switch (t) {
		case FlowToken::Equal:
		case FlowToken::UnEqual:
		case FlowToken::Less:
		case FlowToken::Greater:
		case FlowToken::LessOrEqual:
		case FlowToken::GreaterOrEqual:
		case FlowToken::PrefixMatch:
		case FlowToken::SuffixMatch:
		case FlowToken::RegexMatch:
            return true;
        default:
            return false;
    }
}

bool FlowTokenTraits::isLiteral(FlowToken t)
{
	switch (t) {
		case FlowToken::InterpolatedStringFragment:
		case FlowToken::InterpolatedStringEnd:
		case FlowToken::Boolean:
		case FlowToken::Number:
		case FlowToken::String:
		case FlowToken::RawString:
		case FlowToken::RegExp:
		case FlowToken::IP:
		case FlowToken::Cidr:
        case FlowToken::NamedParam:
			return true;
		default:
			return false;
	}
}

const char *FlowToken::c_str() const throw()
{
	switch (value_) {
		case FlowToken::Unknown: return "Unknown";
		case FlowToken::Boolean: return "Boolean";
		case FlowToken::Number: return "Number";
		case FlowToken::String: return "String";
		case FlowToken::RawString: return "RawString";
		case FlowToken::RegExp: return "RegExp";
		case FlowToken::IP: return "IP";
		case FlowToken::Cidr: return "CIDR";
		case FlowToken::Assign: return "=";
		case FlowToken::OrAssign: return "|=";
		case FlowToken::AndAssign: return "&=";
		case FlowToken::PlusAssign: return "+=";
		case FlowToken::MinusAssign: return "-=";
		case FlowToken::MulAssign: return "*=";
		case FlowToken::DivAssign: return "/=";
		case FlowToken::Semicolon: return ";";
		case FlowToken::Question: return "?";
		case FlowToken::Colon: return ":";
		case FlowToken::And: return "and";
		case FlowToken::Or: return "or";
		case FlowToken::Xor: return "xor";
		case FlowToken::Equal: return "==";
		case FlowToken::UnEqual: return "!=";
		case FlowToken::Less: return "<";
		case FlowToken::Greater: return ">";
		case FlowToken::LessOrEqual: return "<=";
		case FlowToken::GreaterOrEqual: return ">=";
		case FlowToken::PrefixMatch: return "=^";
		case FlowToken::SuffixMatch: return "=$";
		case FlowToken::RegexMatch: return "=~";
		case FlowToken::HashRocket: return "=>";
		case FlowToken::In: return "in";
		case FlowToken::Plus: return "+";
		case FlowToken::Minus: return "-";
		case FlowToken::Mul: return "*";
		case FlowToken::Div: return "/";
		case FlowToken::Mod: return "%";
		case FlowToken::Shl: return "shl";
		case FlowToken::Shr: return "shr";
		case FlowToken::Comma: return ",";
		case FlowToken::Pow: return "**";
		case FlowToken::Not: return "not";
		case FlowToken::BitOr: return "|";
		case FlowToken::BitAnd: return "&";
		case FlowToken::BitXor: return "^";
		case FlowToken::BrOpen: return "[";
		case FlowToken::BrClose: return "]";
		case FlowToken::RndOpen: return "(";
		case FlowToken::RndClose: return ")";
		case FlowToken::Begin: return "{";
		case FlowToken::End: return "}";
		case FlowToken::Var: return "var";
		case FlowToken::Do: return "do";
		case FlowToken::If: return "if";
		case FlowToken::Then: return "then";
		case FlowToken::Else: return "else";
		case FlowToken::Unless: return "unless";
		case FlowToken::Match: return "match";
		case FlowToken::On: return "on";
		case FlowToken::Import: return "import";
		case FlowToken::From: return "from";
		case FlowToken::Handler: return "handler";
		case FlowToken::VoidType: return "void()";
		case FlowToken::BoolType: return "bool()";
		case FlowToken::NumberType: return "int()";
		case FlowToken::StringType: return "string()";
		case FlowToken::Ident: return "Ident";
		case FlowToken::Period: return "Period";
		case FlowToken::DblPeriod: return "DblPeriod";
		case FlowToken::Ellipsis: return "Ellipsis";
		case FlowToken::Comment: return "Comment";
		case FlowToken::Eof: return "EOF";
        case FlowToken::NamedParam: return "NamedParam";
		case FlowToken::InterpolatedStringFragment: return "InterpolatedStringFragment";
		case FlowToken::InterpolatedStringEnd: return "InterpolatedStringEnd";
		default:
            assert(!"FIXME: Invalid Token.");
            abort();
	}
}

} // namespace x0
<|endoftext|>


<commit_before>// -*- mode: c++, encoding: utf-8 -*-
/**
 * tbrpg – Text based roll playing game
 *
 * Copyright © 2012  Mattias Andrée (maandree@kth.se)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "BasicSenario.hpp"

/**
 * Text based roll playing game
 *
 * DD2387 Program construction with C++
 * Laboration 3
 *
 * @author  Mattias Andrée <maandree@kth.se>
 */
namespace tbrpg
{
  /**
   * Constructor
   */
  BasicSenario::BasicSenario()
  {
    this->rules.partySize = 6;
    this->rules.partyStartSize = 6;
  }

  /**
   * Destructor
   */
  BasicSenario::~BasicSenario()
  {
    // do nothing
  }

}

<commit_msg>party size change<commit_after>// -*- mode: c++, encoding: utf-8 -*-
/**
 * tbrpg – Text based roll playing game
 *
 * Copyright © 2012  Mattias Andrée (maandree@kth.se)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "BasicSenario.hpp"

/**
 * Text based roll playing game
 *
 * DD2387 Program construction with C++
 * Laboration 3
 *
 * @author  Mattias Andrée <maandree@kth.se>
 */
namespace tbrpg
{
  /**
   * Constructor
   */
  BasicSenario::BasicSenario()
  {
    this->rules.partySize = 2;
    this->rules.partyStartSize = 2;
  }

  /**
   * Destructor
   */
  BasicSenario::~BasicSenario()
  {
    // do nothing
  }

}

<|endoftext|>


<commit_before>/// @file
/// @version 3.3
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause

#if defined(_ANDROID) || defined(__APPLE__)
#include <unistd.h>
#endif

#include <hltypes/harray.h>
#include <hltypes/hmap.h>
#include <hltypes/hmutex.h>
#include <hltypes/hstream.h>
#include <hltypes/hstring.h>

#include "xal.h"
#include "Buffer.h"
#include "BufferAsync.h"

namespace xal
{
	harray<Buffer*> BufferAsync::buffers;
	int BufferAsync::loaded = 0;
	hmutex BufferAsync::queueMutex;

	hthread BufferAsync::readerThread(&BufferAsync::_read, "APRIL async loader");
	bool BufferAsync::readerRunning = false;

	harray<hthread*> BufferAsync::decoderThreads;

	static int cpus = 0; // needed, because certain calls are made when fetching SystemInfo that are not allowed to be made in secondary threads on some platforms

	void BufferAsync::update()
	{
		hmutex::ScopeLock lock(&BufferAsync::queueMutex);
		if (BufferAsync::readerRunning && !BufferAsync::readerThread.isRunning())
		{
			BufferAsync::readerThread.join();
			BufferAsync::readerRunning = false;
		}
		if (!BufferAsync::readerRunning && BufferAsync::buffers.size() > 0) // new textures got queued in the meantime
		{
			BufferAsync::readerRunning = true;
			BufferAsync::readerThread.start();
		}
	}

	bool BufferAsync::queueLoad(Buffer* buffer)
	{
		if (cpus == 0)
		{
#ifdef _WIN32
			SYSTEM_INFO w32info;
			GetNativeSystemInfo(&w32info);
			cpus = w32info.dwNumberOfProcessors;
#elif defined(__APPLE__) // not sure why, but for Apple hardware the ONLN one is used (possibly some hardware may have locked available cores)
			cpus = sysconf(_SC_NPROCESSORS_ONLN);
#else // on Android and other Unix it's better to use CONF since they are more flexible than Apple's hardware and might switch cores on/off dynamically
			cpus = sysconf(_SC_NPROCESSORS_CONF);
#endif
		}
		hmutex::ScopeLock lock(&BufferAsync::queueMutex);
		if (!BufferAsync::buffers.contains(buffer))
		{
			BufferAsync::buffers += buffer;
			if (!BufferAsync::readerRunning)
			{
				BufferAsync::readerRunning = true;
				BufferAsync::readerThread.start();
			}
			return true;
		}
		return false;
	}

	bool BufferAsync::prioritizeLoad(Buffer* buffer)
	{
		hmutex::ScopeLock lock(&BufferAsync::queueMutex);
		if (BufferAsync::buffers.contains(buffer))
		{
			int index = BufferAsync::buffers.index_of(buffer);
			if (index >= BufferAsync::loaded) // if not loaded from disk yet
			{
				if (index > BufferAsync::loaded) // if not already at the front
				{
					BufferAsync::buffers.remove_at(index);
					BufferAsync::buffers.insert_at(loaded, buffer);
				}
			}
			else if (index > 0) // if data was already loaded in RAM, but not decoded and not already at the front
			{
				BufferAsync::buffers.remove_at(index);
				BufferAsync::buffers.push_first(buffer);
			}
			return true;
		}
		return false;
	}

	bool BufferAsync::isRunning()
	{
		hmutex::ScopeLock lock(&BufferAsync::queueMutex);
		return BufferAsync::readerRunning;
	}

	void BufferAsync::_read(hthread* thread)
	{
		Buffer* buffer = NULL;
		bool streamLoaded = true;
		hthread* decoderThread = NULL;
		int size = 0;
		bool running = true;
		hmutex::ScopeLock lock;
		while (running)
		{
			running = false;
			// check for new queued textures
			lock.acquire(&BufferAsync::queueMutex);
			if (BufferAsync::buffers.size() > loaded)
			{
				running = true;
				buffer = BufferAsync::buffers[loaded];
				lock.release();
				streamLoaded = buffer->_prepareAsyncStream();
				lock.acquire(&BufferAsync::queueMutex);
				int index = BufferAsync::buffers.index_of(buffer); // it's possible that the queue was rearranged in the meantime
				if (streamLoaded)
				{
					if (index >= BufferAsync::loaded)
					{
						if (index > BufferAsync::loaded) // if texture was moved towards the back of the queue
						{
							// put it back to the current decoder position
							BufferAsync::buffers.remove_at(index);
							BufferAsync::buffers.insert_at(BufferAsync::loaded, buffer);
						}
					}
					++loaded;
				}
				else // it was canceled
				{
					BufferAsync::buffers.remove_at(index);
				}
			}
			size = BufferAsync::loaded;
			lock.release();
			// create new worker threads if needed
			if (size > 0)
			{
				running = true;
				size = hmin(size, cpus) - BufferAsync::decoderThreads.size();
				for_iter (i, 0, size)
				{
					decoderThread = new hthread(&BufferAsync::_decode, "XAL async decoder");
					BufferAsync::decoderThreads += decoderThread;
					decoderThread->start();
				}
			}
			// check current worker threads' status
			if (BufferAsync::decoderThreads.size() > 0)
			{
				running = true;
				for_iter (i, 0, BufferAsync::decoderThreads.size())
				{
					if (!BufferAsync::decoderThreads[i]->isRunning())
					{
						decoderThread = BufferAsync::decoderThreads.remove_at(i);
						decoderThread->join();
						delete decoderThread;
						--i;
					}
				}
			}
		}
	}

	void BufferAsync::_decode(hthread* thread)
	{
		hmutex::ScopeLock lock;
		while (true)
		{
			lock.acquire(&BufferAsync::queueMutex);
			if (BufferAsync::loaded == 0)
			{
				break;
			}
			Buffer* buffer = BufferAsync::buffers.remove_first();
			--BufferAsync::loaded;
			lock.release();
			buffer->_decodeFromAsyncStream();
		}
	}

}
<commit_msg>- small update<commit_after>/// @file
/// @version 3.3
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause

#if defined(_ANDROID) || defined(__APPLE__)
#include <unistd.h>
#endif

#include <hltypes/harray.h>
#include <hltypes/hmap.h>
#include <hltypes/hmutex.h>
#include <hltypes/hstream.h>
#include <hltypes/hstring.h>

#include "xal.h"
#include "Buffer.h"
#include "BufferAsync.h"

namespace xal
{
	harray<Buffer*> BufferAsync::buffers;
	int BufferAsync::loaded = 0;
	hmutex BufferAsync::queueMutex;

	hthread BufferAsync::readerThread(&BufferAsync::_read, "XAL async loader");
	bool BufferAsync::readerRunning = false;

	harray<hthread*> BufferAsync::decoderThreads;

	static int cpus = 0; // needed, because certain calls are made when fetching SystemInfo that are not allowed to be made in secondary threads on some platforms

	void BufferAsync::update()
	{
		hmutex::ScopeLock lock(&BufferAsync::queueMutex);
		if (BufferAsync::readerRunning && !BufferAsync::readerThread.isRunning())
		{
			BufferAsync::readerThread.join();
			BufferAsync::readerRunning = false;
		}
		if (!BufferAsync::readerRunning && BufferAsync::buffers.size() > 0) // new textures got queued in the meantime
		{
			BufferAsync::readerRunning = true;
			BufferAsync::readerThread.start();
		}
	}

	bool BufferAsync::queueLoad(Buffer* buffer)
	{
		if (cpus == 0)
		{
#ifdef _WIN32
			SYSTEM_INFO w32info;
			GetNativeSystemInfo(&w32info);
			cpus = w32info.dwNumberOfProcessors;
#elif defined(__APPLE__) // not sure why, but for Apple hardware the ONLN one is used (possibly some hardware may have locked available cores)
			cpus = sysconf(_SC_NPROCESSORS_ONLN);
#else // on Android and other Unix it's better to use CONF since they are more flexible than Apple's hardware and might switch cores on/off dynamically
			cpus = sysconf(_SC_NPROCESSORS_CONF);
#endif
		}
		hmutex::ScopeLock lock(&BufferAsync::queueMutex);
		if (BufferAsync::buffers.contains(buffer))
		{
			return false;
		}
		BufferAsync::buffers += buffer;
		if (!BufferAsync::readerRunning)
		{
			BufferAsync::readerRunning = true;
			BufferAsync::readerThread.start();
		}
		return true;
	}

	bool BufferAsync::prioritizeLoad(Buffer* buffer)
	{
		hmutex::ScopeLock lock(&BufferAsync::queueMutex);
		if (!BufferAsync::buffers.contains(buffer))
		{
			return false;
		}
		int index = BufferAsync::buffers.index_of(buffer);
		if (index >= BufferAsync::loaded) // if not loaded from disk yet
		{
			if (index > BufferAsync::loaded) // if not already at the front
			{
				BufferAsync::buffers.remove_at(index);
				BufferAsync::buffers.insert_at(loaded, buffer);
			}
		}
		else if (index > 0) // if data was already loaded in RAM, but not decoded and not already at the front
		{
			BufferAsync::buffers.remove_at(index);
			BufferAsync::buffers.push_first(buffer);
		}
		return true;
	}

	bool BufferAsync::isRunning()
	{
		hmutex::ScopeLock lock(&BufferAsync::queueMutex);
		return BufferAsync::readerRunning;
	}

	void BufferAsync::_read(hthread* thread)
	{
		Buffer* buffer = NULL;
		bool streamLoaded = true;
		hthread* decoderThread = NULL;
		int index = 0;
		int size = 0;
		bool running = true;
		hmutex::ScopeLock lock;
		while (running)
		{
			running = false;
			// check for new queued textures
			lock.acquire(&BufferAsync::queueMutex);
			if (BufferAsync::buffers.size() > BufferAsync::loaded)
			{
				running = true;
				buffer = BufferAsync::buffers[BufferAsync::loaded];
				lock.release();
				streamLoaded = buffer->_prepareAsyncStream();
				lock.acquire(&BufferAsync::queueMutex);
				index = BufferAsync::buffers.index_of(buffer); // it's possible that the queue was rearranged in the meantime
				if (streamLoaded)
				{
					if (index >= BufferAsync::loaded)
					{
						if (index > BufferAsync::loaded) // if texture was moved towards the back of the queue
						{
							// put it back to the current decoder position
							BufferAsync::buffers.remove_at(index);
							BufferAsync::buffers.insert_at(BufferAsync::loaded, buffer);
						}
					}
					++BufferAsync::loaded;
				}
				else // it was canceled
				{
					BufferAsync::buffers.remove_at(index);
				}
			}
			size = BufferAsync::loaded;
			lock.release();
			// create new worker threads if needed
			if (size > 0)
			{
				running = true;
				size = hmin(size, cpus) - BufferAsync::decoderThreads.size();
				for_iter (i, 0, size)
				{
					decoderThread = new hthread(&BufferAsync::_decode, "XAL async decoder");
					BufferAsync::decoderThreads += decoderThread;
					decoderThread->start();
				}
			}
			// check current worker threads' status
			if (BufferAsync::decoderThreads.size() > 0)
			{
				running = true;
				for_iter (i, 0, BufferAsync::decoderThreads.size())
				{
					if (!BufferAsync::decoderThreads[i]->isRunning())
					{
						decoderThread = BufferAsync::decoderThreads.remove_at(i);
						decoderThread->join();
						delete decoderThread;
						--i;
					}
				}
			}
		}
	}

	void BufferAsync::_decode(hthread* thread)
	{
		Buffer* buffer = NULL;
		hmutex::ScopeLock lock(&BufferAsync::queueMutex);
		while (BufferAsync::loaded > 0)
		{
			buffer = BufferAsync::buffers.remove_first();
			--BufferAsync::loaded;
			lock.release();
			buffer->_decodeFromAsyncStream();
			lock.acquire(&BufferAsync::queueMutex);
		}
	}

}
<|endoftext|>