<commit_before>#include "text/cmdline.h"
#include "math/random.h"
#include "math/epsilon.h"
#include "functions/test.h"
#include "solver_stoch.h"
#include "benchmark_solvers.h"

using namespace nano;

template <typename tostats>
static void check_function(const function_t& function, const strings_t& solvers,
        const size_t trials, const size_t epochs, const size_t epoch_size, const scalar_t epsilon, tostats& gstats)
{
        auto rgen = make_rng(scalar_t(-1), scalar_t(+1));

        // generate fixed random trials
        std::vector<vector_t> x0s(trials);
        for (auto& x0 : x0s)
        {
                x0.resize(function.size());
                rgen(x0.data(), x0.data() + x0.size());
        }

        // per-problem statistics
        tostats stats;

        // evaluate all solvers
        for (const auto& id : solvers)
        {
                const auto solver = get_stoch_solvers().get(id);
                const auto params = stoch_params_t(epochs, epoch_size, epsilon);
                const auto& name = id;

                solver->tune(params, function, x0s[0]);
                benchmark::benchmark_function(solver, params, function, x0s, name, stats, gstats);
        }

        // show per-problem statistics
        benchmark::show_table(function.name(), stats);
}

int main(int argc, const char* argv[])
{
        // parse the command line
        cmdline_t cmdline("benchmark stochastic solvers");
        cmdline.add("", "solvers",      "use this regex to select the solvers to benchmark", ".+");
        cmdline.add("", "min-dims",     "minimum number of dimensions for each test function (if feasible)", "10");
        cmdline.add("", "max-dims",     "maximum number of dimensions for each test function (if feasible)", "100");
        cmdline.add("", "trials",       "number of random trials for each test function", "100");
        cmdline.add("", "epochs",       "optimization: number of epochs", "1000");
        cmdline.add("", "epoch-size",   "optimization: number of iterations per epoch", "100");
        cmdline.add("", "epsilon",      "convergence criteria", 1e-4);
        cmdline.add("", "convex",       "use only convex test functions");

        cmdline.process(argc, argv);

        // check arguments and options
        const auto min_dims = cmdline.get<tensor_size_t>("min-dims");
        const auto max_dims = cmdline.get<tensor_size_t>("max-dims");
        const auto trials = cmdline.get<size_t>("trials");
        const auto epochs = cmdline.get<size_t>("epochs");
        const auto epoch_size = cmdline.get<size_t>("epoch-size");
        const auto epsilon = cmdline.get<scalar_t>("epsilon");
        const auto is_convex = cmdline.has("convex");

        const auto solvers = get_stoch_solvers().ids(std::regex(cmdline.get<string_t>("solvers")));

        std::map<std::string, benchmark::solver_stat_t> gstats;

        const auto functions = (is_convex ? make_convex_functions : make_functions)(min_dims, max_dims);
        foreach_test_function(functions, [&] (const function_t& function)
        {
                check_function(function, solvers, trials, epochs, epoch_size, epsilon, gstats);
        });

        // show global statistics
        benchmark::show_table(std::string(), gstats);

        // OK
        return EXIT_SUCCESS;
}
<commit_msg>have the number of tuning epochs configurable during benchmark<commit_after>#include "text/cmdline.h"
#include "math/random.h"
#include "math/epsilon.h"
#include "functions/test.h"
#include "solver_stoch.h"
#include "benchmark_solvers.h"

using namespace nano;

template <typename tostats>
static void check_function(const function_t& function, const strings_t& solvers, const size_t trials,
        const size_t epochs, const size_t tune_epochs, const size_t epoch_size, const scalar_t epsilon,
        tostats& gstats)
{
        auto rgen = make_rng(scalar_t(-1), scalar_t(+1));

        // generate fixed random trials
        std::vector<vector_t> x0s(trials);
        for (auto& x0 : x0s)
        {
                x0.resize(function.size());
                rgen(x0.data(), x0.data() + x0.size());
        }

        // per-problem statistics
        tostats stats;

        // evaluate all solvers
        for (const auto& id : solvers)
        {
                const auto solver = get_stoch_solvers().get(id);
                const auto tune_params = stoch_params_t(tune_epochs, epoch_size, epsilon);
                const auto params = stoch_params_t(epochs, epoch_size, epsilon);
                const auto& name = id;

                solver->tune(tune_params, function, x0s[0]);
                benchmark::benchmark_function(solver, params, function, x0s, name, stats, gstats);
        }

        // show per-problem statistics
        benchmark::show_table(function.name(), stats);
}

int main(int argc, const char* argv[])
{
        // parse the command line
        cmdline_t cmdline("benchmark stochastic solvers");
        cmdline.add("", "solvers",      "use this regex to select the solvers to benchmark", ".+");
        cmdline.add("", "min-dims",     "minimum number of dimensions for each test function (if feasible)", "10");
        cmdline.add("", "max-dims",     "maximum number of dimensions for each test function (if feasible)", "100");
        cmdline.add("", "trials",       "number of random trials for each test function", "100");
        cmdline.add("", "epochs",       "optimization: number of epochs", "1000");
        cmdline.add("", "epoch-size",   "optimization: number of iterations per epoch", "100");
        cmdline.add("", "tune-epochs",  "optimization: number of epochs to use for tuning", "100");
        cmdline.add("", "epsilon",      "convergence criteria", 1e-4);
        cmdline.add("", "convex",       "use only convex test functions");

        cmdline.process(argc, argv);

        // check arguments and options
        const auto min_dims = cmdline.get<tensor_size_t>("min-dims");
        const auto max_dims = cmdline.get<tensor_size_t>("max-dims");
        const auto trials = cmdline.get<size_t>("trials");
        const auto epochs = cmdline.get<size_t>("epochs");
        const auto epoch_size = cmdline.get<size_t>("epoch-size");
        const auto tune_epochs = cmdline.get<size_t>("tune-epochs");
        const auto epsilon = cmdline.get<scalar_t>("epsilon");
        const auto is_convex = cmdline.has("convex");

        const auto solvers = get_stoch_solvers().ids(std::regex(cmdline.get<string_t>("solvers")));

        std::map<std::string, benchmark::solver_stat_t> gstats;

        const auto functions = (is_convex ? make_convex_functions : make_functions)(min_dims, max_dims);
        foreach_test_function(functions, [&] (const function_t& function)
        {
                check_function(function, solvers, trials, epochs, tune_epochs, epoch_size, epsilon, gstats);
        });

        // show global statistics
        benchmark::show_table(std::string(), gstats);

        // OK
        return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser_url_handler.h"

#include "base/string_util.h"
#include "chrome/browser/browser_about_handler.h"
#include "chrome/browser/dom_ui/dom_ui_factory.h"
#include "chrome/browser/extensions/extension_dom_ui.h"
#include "chrome/browser/profile.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/gurl.h"

// Handles rewriting view-source URLs for what we'll actually load.
static bool HandleViewSource(GURL* url, Profile* profile) {
  if (url->SchemeIs(chrome::kViewSourceScheme)) {
    // Load the inner URL instead.
    *url = GURL(url->path());
    return true;
  }
  return false;
}

// Handles URLs for DOM UI. These URLs need no rewriting.
static bool HandleDOMUI(GURL* url, Profile* profile) {
  if (!DOMUIFactory::UseDOMUIForURL(*url))
    return false;
  return true;
}

std::vector<BrowserURLHandler::URLHandler> BrowserURLHandler::url_handlers_;

// static
void BrowserURLHandler::InitURLHandlers() {
  if (!url_handlers_.empty())
    return;

  // Add the default URL handlers.
  url_handlers_.push_back(&ExtensionDOMUI::HandleChromeURLOverride);
  url_handlers_.push_back(&WillHandleBrowserAboutURL);  // about:
  url_handlers_.push_back(&HandleDOMUI);                // chrome: & friends.
  url_handlers_.push_back(&HandleViewSource);           // view-source:
}

// static
void BrowserURLHandler::RewriteURLIfNecessary(GURL* url, Profile* profile) {
  if (url_handlers_.empty())
    InitURLHandlers();
  for (size_t i = 0; i < url_handlers_.size(); ++i) {
    if ((*url_handlers_[i])(url, profile))
      return;
  }
}
<commit_msg>Prevent 'view-source' from being abused by disabling anything other than http, https, ftp or file protocols in it.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser_url_handler.h"

#include "base/string_util.h"
#include "chrome/browser/browser_about_handler.h"
#include "chrome/browser/dom_ui/dom_ui_factory.h"
#include "chrome/browser/extensions/extension_dom_ui.h"
#include "chrome/browser/profile.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/gurl.h"

// Handles rewriting view-source URLs for what we'll actually load.
static bool HandleViewSource(GURL* url, Profile* profile) {
  if (url->SchemeIs(chrome::kViewSourceScheme)) {
    // Load the inner URL instead.
    *url = GURL(url->path());

    // Bug 26129: limit view-source to view the content and not any
    // other kind of 'active' url scheme like 'javascript' or 'data'.
    static const char* const allowed_sub_schemes[] = {
      chrome::kHttpScheme, chrome::kHttpsScheme, chrome::kFtpScheme,
      chrome::kChromeUIScheme
    };

    bool is_sub_scheme_allowed = false;
    for (size_t i = 0; i < arraysize(allowed_sub_schemes); i++) {
      if (url->SchemeIs(allowed_sub_schemes[i])) {
        is_sub_scheme_allowed = true;
        break;
      }
    }

    if (!is_sub_scheme_allowed) {
      *url = GURL(chrome::kAboutBlankURL);
      return false;
    }

    return true;
  }
  return false;
}

// Handles URLs for DOM UI. These URLs need no rewriting.
static bool HandleDOMUI(GURL* url, Profile* profile) {
  if (!DOMUIFactory::UseDOMUIForURL(*url))
    return false;
  return true;
}

std::vector<BrowserURLHandler::URLHandler> BrowserURLHandler::url_handlers_;

// static
void BrowserURLHandler::InitURLHandlers() {
  if (!url_handlers_.empty())
    return;

  // Add the default URL handlers.
  url_handlers_.push_back(&ExtensionDOMUI::HandleChromeURLOverride);
  url_handlers_.push_back(&WillHandleBrowserAboutURL);  // about:
  url_handlers_.push_back(&HandleDOMUI);                // chrome: & friends.
  url_handlers_.push_back(&HandleViewSource);           // view-source:
}

// static
void BrowserURLHandler::RewriteURLIfNecessary(GURL* url, Profile* profile) {
  if (url_handlers_.empty())
    InitURLHandlers();
  for (size_t i = 0; i < url_handlers_.size(); ++i) {
    if ((*url_handlers_[i])(url, profile))
      return;
  }
}
<|endoftext|>


<commit_before>#include "dungeon_serializer.h"
#include "dungeon_exit.h"
#include "dungeon_room.h"
#include <sstream>
#include "utils.h"

using namespace std;

extern vector<DungeonExit*> g_exitList;

DungeonExit::DungeonExit()
{
	isDoor = false;
	isOpen = true;
	distance = 1;
	room = nullptr;
	uid = getUID();
	g_exitList.push_back(this);
}

DungeonExit::DungeonExit(string json)
{

}

DungeonExit::~DungeonExit()
{

}

string DungeonExit::toJSON()
{
	ostringstream sout;
	sout << writeInt(uid);
	sout << writeVectorString(names);
	sout << writeBool(isOpen);
	sout << writeBool(isDoor);
	sout << writeInt(distance);
	sout << writeString(openingText);
	sout << writeString(closingText);
	sout << writeString(openText);
	sout << writeString(closedText);
	sout << _writeInt("links",room->uid);
	return sout.str();
}
<commit_msg>use new writeEntity macro<commit_after>#include "dungeon_serializer.h"
#include "dungeon_exit.h"
#include "dungeon_room.h"
#include <sstream>
#include "utils.h"

using namespace std;

extern vector<DungeonExit*> g_exitList;

DungeonExit::DungeonExit()
{
	isDoor = false;
	isOpen = true;
	distance = 1;
	room = nullptr;
	uid = getUID();
	g_exitList.push_back(this);
}

DungeonExit::DungeonExit(string json)
{

}

DungeonExit::~DungeonExit()
{

}

string DungeonExit::toJSON()
{
	ostringstream sout;
	sout << writeInt(uid);
	sout << writeVectorString(names);
	sout << writeBool(isOpen);
	sout << writeBool(isDoor);
	sout << writeInt(distance);
	sout << writeString(openingText);
	sout << writeString(closingText);
	sout << writeString(openText);
	sout << writeString(closedText);
	sout << writeEntity(room);
	return sout.str();
}
<|endoftext|>


<commit_before>#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <cstdarg>
#include <cstdio>
#include <unistd.h>

#include <time.h>
#include <string.h>
#include <openssl/sha.h>
#include <stdio.h>
#include <openssl/des.h>
#include <stdbool.h>
#include <openssl/hmac.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <stdint.h>

#include <curl/curl.h>

#include "utils.h"

#include <string>
#include <sstream>
using std::string;

#include <iomanip>

bool gethttpnow(char datebuf[65]) {  //('D, d M Y H:i:s T')
    struct tm *tm_info;
    time_t t;
    if (!datebuf) {
        return false;
    }
    time(&t);
    tm_info = localtime(&t);
    strftime(datebuf, 64, "%a, %d %b %Y %H:%M:%S %z", tm_info);
    return true;
}

bool lowercase(char *out, const char *in) {
    if (!out || !in) {  // invalid string params
        return false;
    }
    while (*in) {
        //*out++ = (*in >= 'A' && *in <= 'Z') ? *in|0x60 : *in;
        *out++ = *in;
        in++;
    }
    *out = 0;
    return true;
}

void tolower(char *buf) {
    do {
        if (*buf >= 'A' && *buf <= 'Z') *buf |= 0x60;
    } while (*buf++);
    return;
}

bool trim(char *out, const char *in, const char *trimed) {
    int targetlen;

    if (!out || !in) {  // invalid string params
        return false;
    }

    targetlen = strlen(in);

    while (targetlen > 0) {
        if (strchr(trimed, in[targetlen - 1]) ==
            NULL)  // can't find stripped char
            break;
        else
            targetlen--;
    }

    while (targetlen > 0) {
        if (strchr(trimed, *in) == NULL)  // normal string
            break;
        else {
            in++;
            targetlen--;
        }
    }

    memcpy(out, in, targetlen);
    out[targetlen] = 0;
    return true;
}

//! return value is malloced
char *Base64Encode(const char *buffer,
                   size_t length) {  // Encodes a binary safe base 64 string
    BIO *bio, *b64;
    BUF_MEM *bufferPtr;
    char *ret;
    b64 = BIO_new(BIO_f_base64());
    bio = BIO_new(BIO_s_mem());
    bio = BIO_push(b64, bio);

    BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);  // Ignore newlines - write
                                                 // everything in one line
    BIO_write(bio, buffer, length);
    BIO_flush(bio);
    BIO_get_mem_ptr(bio, &bufferPtr);

    ret = (char *)malloc(bufferPtr->length + 1);
    memcpy(ret, bufferPtr->data, bufferPtr->length);
    ret[bufferPtr->length] = 0;

    BIO_set_close(bio, BIO_NOCLOSE);
    BIO_free_all(bio);

    return ret;  // s
}

bool sha256(char *string, char outputBuffer[65]) {
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    if (!string) return false;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, string, strlen(string));
    SHA256_Final(hash, &sha256);
    int i = 0;
    for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
    }
    outputBuffer[64] = 0;
    return true;
}

char *sha1hmac(const char *str, const char *secret) {
    return (char *)HMAC(EVP_sha1(), secret, strlen(secret),
                        (const unsigned char *)str, strlen(str), NULL, NULL);
}

bool sha256hmac(char *str, char out[65], char *secret) {
    unsigned char hash[32];
    unsigned int len = 32;
    int i;
    HMAC_CTX hmac;
    HMAC_CTX_init(&hmac);
    HMAC_Init_ex(&hmac, secret, strlen(secret), EVP_sha256(), NULL);
    HMAC_Update(&hmac, (unsigned char *)str, strlen(str));

    HMAC_Final(&hmac, hash, &len);
    for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        sprintf(out + (i * 2), "%02x", hash[i]);
    }
    HMAC_CTX_cleanup(&hmac);
    out[64] = 0;
    return true;
}

// return malloced because Base64Encode
char *SignatureV2(const char *date, const char *path, const char *key) {
    int maxlen, len;
    char *tmpbuf, *outbuf;
    if (!date || !path || !key) {
        return NULL;
    }
    maxlen = strlen(date) + strlen(path) + 20;
    tmpbuf = (char *)alloca(maxlen);
    sprintf(tmpbuf, "GET\n\n\n%s\n%s", date, path);
    // printf("%s\n",tmpbuf);
    outbuf = sha1hmac(tmpbuf, key);
    len = strlen(outbuf);
    return Base64Encode(outbuf, len);
}

char *SignatureV4(const char *date, const char *path, const char *key) {
    return NULL;
}

CURL *CreateCurlHandler(const char *path) {
    CURL *curl = NULL;
    if (!path) {
        return NULL;
    } else {
        curl = curl_easy_init();
    }

    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, path);
        // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    }
    return curl;
}

size_t find_Nth(const string &str,  // where to work
                unsigned N,         // N'th ocurrence
                const string &find  // what to 'find'
                ) {
    if (0 == N) {
        return string::npos;
    }
    size_t pos, from = 0;
    unsigned i = 0;
    while (i < N) {
        pos = str.find(find, from);
        if (string::npos == pos) {
            break;
        }
        from = pos + 1;  // from = pos + find.size();
        ++i;
    }
    return pos;
    /**
It would be more efficient to use a variation of KMP to
benefit from the failure function.
- Algorithm inspired by James Kanze.
- http://stackoverflow.com/questions/20406744/
    */
}

static int logsock = -1;
static struct sockaddr_in si_logserver;

void InitLog() {
    if (logsock == -1) {
        si_logserver.sin_family = AF_INET;
        si_logserver.sin_port = htons(1111);
        if (inet_aton("127.0.0.1", &si_logserver.sin_addr) == 0) {  // error
            // log error here
            return;
        }
        logsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    }
}

void EXTLOG(const char *fmt, ...) {
    char buf[1024];
    va_list args;
    va_start(args, fmt);
    vsnprintf(buf, 1023, fmt, args);
    va_end(args);
    buf[1023] = 0;
    sendto(logsock, buf, strlen(buf), 0, (struct sockaddr *)&si_logserver,
           sizeof(sockaddr_in));
}

MD5Calc::MD5Calc() {
    memset(this->md5, 0, 17);
    MD5_Init(&this->c);
}

bool MD5Calc::Update(const char *data, int len) {
    MD5_Update(&this->c, data, len);
    return true;
}

const char *MD5Calc::Get() {
    MD5_Final(this->md5, &c);
    std::stringstream ss;
    for (int i = 0; i < 16; i++)
        ss << std::hex << std::setw(2) << std::setfill('0')
           << (int)this->md5[i];
    this->result = ss.str();

    // Reset MD5 context
    memset(this->md5, 0, 17);
    MD5_Init(&this->c);
    return this->result.c_str();
}
<commit_msg>remove redundant lowercase()<commit_after>#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <cstdarg>
#include <cstdio>
#include <unistd.h>

#include <time.h>
#include <string.h>
#include <openssl/sha.h>
#include <stdio.h>
#include <openssl/des.h>
#include <stdbool.h>
#include <openssl/hmac.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <stdint.h>

#include <curl/curl.h>

#include "utils.h"

#include <string>
#include <sstream>
using std::string;

#include <iomanip>

bool gethttpnow(char datebuf[65]) {  //('D, d M Y H:i:s T')
    struct tm *tm_info;
    time_t t;
    if (!datebuf) {
        return false;
    }
    time(&t);
    tm_info = localtime(&t);
    strftime(datebuf, 64, "%a, %d %b %Y %H:%M:%S %z", tm_info);
    return true;
}

void tolower(char *buf) {
    do {
        if (*buf >= 'A' && *buf <= 'Z') *buf |= 0x60;
    } while (*buf++);
    return;
}

bool trim(char *out, const char *in, const char *trimed) {
    int targetlen;

    if (!out || !in) {  // invalid string params
        return false;
    }

    targetlen = strlen(in);

    while (targetlen > 0) {
        if (strchr(trimed, in[targetlen - 1]) ==
            NULL)  // can't find stripped char
            break;
        else
            targetlen--;
    }

    while (targetlen > 0) {
        if (strchr(trimed, *in) == NULL)  // normal string
            break;
        else {
            in++;
            targetlen--;
        }
    }

    memcpy(out, in, targetlen);
    out[targetlen] = 0;
    return true;
}

//! return value is malloced
char *Base64Encode(const char *buffer,
                   size_t length) {  // Encodes a binary safe base 64 string
    BIO *bio, *b64;
    BUF_MEM *bufferPtr;
    char *ret;
    b64 = BIO_new(BIO_f_base64());
    bio = BIO_new(BIO_s_mem());
    bio = BIO_push(b64, bio);

    BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);  // Ignore newlines - write
                                                 // everything in one line
    BIO_write(bio, buffer, length);
    BIO_flush(bio);
    BIO_get_mem_ptr(bio, &bufferPtr);

    ret = (char *)malloc(bufferPtr->length + 1);
    memcpy(ret, bufferPtr->data, bufferPtr->length);
    ret[bufferPtr->length] = 0;

    BIO_set_close(bio, BIO_NOCLOSE);
    BIO_free_all(bio);

    return ret;  // s
}

bool sha256(const char *string, char outputBuffer[65]) {
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    if (!string) return false;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, string, strlen(string));
    SHA256_Final(hash, &sha256);
    int i = 0;
    for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
    }
    outputBuffer[64] = 0;
    return true;
}

// not returning the normal hex result
char *sha1hmac(const char *str, const char *secret) {
    return (char *)HMAC(EVP_sha1(), secret, strlen(secret),
                        (const unsigned char *)str, strlen(str), NULL, NULL);
}

bool sha256hmac(const char *str, char out[65], const char *secret) {
    unsigned char hash[32];
    unsigned int len = 32;
    int i;
    HMAC_CTX hmac;
    HMAC_CTX_init(&hmac);
    HMAC_Init_ex(&hmac, secret, strlen(secret), EVP_sha256(), NULL);
    HMAC_Update(&hmac, (unsigned char *)str, strlen(str));

    HMAC_Final(&hmac, hash, &len);
    for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        sprintf(out + (i * 2), "%02x", hash[i]);
    }
    HMAC_CTX_cleanup(&hmac);
    out[64] = 0;
    return true;
}

// return malloced because Base64Encode
char *SignatureV2(const char *date, const char *path, const char *key) {
    int maxlen, len;
    char *tmpbuf, *outbuf;
    if (!date || !path || !key) {
        return NULL;
    }
    maxlen = strlen(date) + strlen(path) + 20;
    tmpbuf = (char *)alloca(maxlen);
    sprintf(tmpbuf, "GET\n\n\n%s\n%s", date, path);
    // printf("%s\n",tmpbuf);
    outbuf = sha1hmac(tmpbuf, key);
    len = strlen(outbuf);
    return Base64Encode(outbuf, len);
}

char *SignatureV4(const char *date, const char *path, const char *key) {
    return NULL;
}

CURL *CreateCurlHandler(const char *path) {
    CURL *curl = NULL;
    if (!path) {
        return NULL;
    } else {
        curl = curl_easy_init();
    }

    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, path);
        // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    }
    return curl;
}

size_t find_Nth(const string &str,  // where to work
                unsigned N,         // N'th ocurrence
                const string &find  // what to 'find'
                ) {
    if (0 == N) {
        return string::npos;
    }
    size_t pos, from = 0;
    unsigned i = 0;
    while (i < N) {
        pos = str.find(find, from);
        if (string::npos == pos) {
            break;
        }
        from = pos + 1;  // from = pos + find.size();
        ++i;
    }
    return pos;
    /**
It would be more efficient to use a variation of KMP to
benefit from the failure function.
- Algorithm inspired by James Kanze.
- http://stackoverflow.com/questions/20406744/
    */
}

static int logsock = -1;
static struct sockaddr_in si_logserver;

void InitLog() {
    if (logsock == -1) {
        si_logserver.sin_family = AF_INET;
        si_logserver.sin_port = htons(1111);
        if (inet_aton("127.0.0.1", &si_logserver.sin_addr) == 0) {  // error
            // log error here
            return;
        }
        logsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    }
}

void EXTLOG(const char *fmt, ...) {
    char buf[1024];
    va_list args;
    va_start(args, fmt);
    vsnprintf(buf, 1023, fmt, args);
    va_end(args);
    buf[1023] = 0;
    sendto(logsock, buf, strlen(buf), 0, (struct sockaddr *)&si_logserver,
           sizeof(sockaddr_in));
}

MD5Calc::MD5Calc() {
    memset(this->md5, 0, 17);
    MD5_Init(&this->c);
}

bool MD5Calc::Update(const char *data, int len) {
    MD5_Update(&this->c, data, len);
    return true;
}

const char *MD5Calc::Get() {
    MD5_Final(this->md5, &c);
    std::stringstream ss;
    for (int i = 0; i < 16; i++)
        ss << std::hex << std::setw(2) << std::setfill('0')
           << (int)this->md5[i];
    this->result = ss.str();

    // Reset MD5 context
    memset(this->md5, 0, 17);
    MD5_Init(&this->c);
    return this->result.c_str();
}
<|endoftext|>


<commit_before>#pragma once

#include <list>
#include <unordered_map>
#include <string>
#include <iostream>
#include <iomanip>
#include <chrono>
#include <functional>
#include <unistd.h>

/**
 * @namespace testy
 * Simple tool to easly manage unit tests.
 */
namespace testy {

/**
 * @macro Suite
 * The macro used to create the test suite.
 */
#define Suite(name, code) \
  int main() { \
    testy::TestSuite testSuite(name); \
    code \
    return testSuite.run(); \
  }

/**
 * @macro describe
 * Describe one entity of the suite.
 */
#define describe(name, ...) \
  testSuite.addTest(name, { \
    __VA_ARGS__ \
  });

/**
 * @macro example
 */
#define example(name, ...) \
  testSuite.addExample(name, [&] () { \
    __VA_ARGS__ \
  });

/**
 * @macro it
 * Test one action of the suite.
 */
#define it(text, ...) \
  {text, [&] () { \
      __VA_ARGS__ \
      return ""; \
    }}

/**
 * @macro test
 * Test if the given expr is true.
 */
#define test(expr) if (!(expr)) return #expr;

/**
 * @macro testRange
 * Test if the given expr is in the given range.
 */
#define testRange(expr, begin, end) \
  { \
    auto const &val = expr; \
    if (val > end || val < begin) \
      return #expr; \
  }

/**
 * @macro testThrow
 * Test if the given `expr` throw the given `except`.
 */
#define testThrow(expr, except) try { expr } catch (except) {}

/**
 * TestSuite
 * Simple test suite in which you can register units and run all unit tests.
 */
class TestSuite {
 public:
  /**
   * @typedef Unit
   * Describe a unit to test.
   */
  typedef std::list<std::pair<std::string, std::function<std::string()>>> Unit;
  TestSuite(std::string const &name) : _name(name) {}
  ~TestSuite() {}
  inline void displayTitle(std::string const &title);
  inline void displaySubtitle(std::string const &subTitle);
  inline void addTest(std::string const &desc, Unit const &unit);
  inline void addExample(std::string const &, std::function<void()> const &);
  inline int run();
 private:
  std::string _name;
  std::list<std::pair<std::string, Unit>> _tests;
  std::list<std::pair<std::string, std::function<void()>>> _examples;
};

inline void TestSuite::displayTitle(std::string const &title) {
    std::cout << std::endl << "  \e[1m" << title << std::endl;
    std::cout << "  ";
    for (size_t i = 0; i < title.size(); ++i)
      std::cout << "=";
    std::cout << "\e[m"<< std::endl;
}

inline void TestSuite::displaySubtitle(std::string const &subTitle) {
  std::cout << "  \e[m## " << subTitle << std::endl << std::endl;
}

/**
 * Register a new unit test.
 * @param desc The description of this unit.
 * @param unit The unit which contains all tests.
 */
inline void TestSuite::addTest(std::string const &desc,
                               TestSuite::Unit const &unit) {
  _tests.push_back(std::make_pair(desc, unit));
}

/**
 * Register an example, with a simple "classic" output.
 */
inline void TestSuite::addExample(std::string const &desc,
                                  std::function<void()> const &fn) {
  _examples.push_back(std::make_pair(desc, fn));
}

/**
 * Return all unit tests.
 * @return Returns the number of failures or 0 on success.
 */
inline int TestSuite::run() {
  std::chrono::steady_clock::time_point prev;
  int fail = 0;
  int total = 0;
  size_t duration = 0;

  if (!_tests.empty()) {

    displayTitle(_name + "'s module unit tests");
    std::cout << std::endl;
    for (auto &unit : _tests) {

      // Display the test description
      displaySubtitle(unit.first);

      for (auto &test : unit.second) {

        // Run the test and display the fail or success message

        prev = std::chrono::steady_clock::now();
        std::cout << "    ";
        std::string error;
        try {
          error = test.second();
          if (!error.empty()) { // message isnt empty
            ++fail;
            std::cout << "\e[0;31m✗ ";
          } else { // succeed otherwise
            std::cout << "\e[0;32m✓ \e[1;30m";
          }
        } catch (...) { // fail if an unexpected exception is thrown.
          ++fail;
          std::cout << "\e[0;31m✗ ";
        }

        // and duration of the function call

        size_t delta = (std::chrono::steady_clock::now() - prev).count() / 1000;
        duration += delta;
        std::cout << test.first << " ("
                  << std::fixed << delta
                  << "ms)" << std::endl;

        // display error message

        if (!error.empty())
          std::cout << "        tested code `" << error << "`" << std::endl;

        ++total;
      }
      std::cout << std::endl;

    }

    // Display the result of the tests

    if (fail) {
      std::cout << "  \e[0;31m✗ " << fail << " of "
                << total << " tests failed "
                << "(" << duration << "ms)";
    } else {
      std::cout << "  \e[0;32m✓ " << total
                << " tests completed "
                << "(" << duration << "ms)";
    }
    std::cout << "\e[m" << std::endl << std::endl;
  }

  if (!_examples.empty()) {
    displayTitle(_name + "'s module examples");
    std::cout << std::endl;
    for (auto const &example : _examples) {
      displaySubtitle(example.first);
      example.second();
      std::cout << std::endl;
    }
    std::cout << std::endl;
  }

// Wait for keyboard press on windows to keep the output console opened.
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
  std::cout << "  [ Press any key to quit ]" << std::endl << std::endl;
  std::cin.get();
#endif

  return fail;
}

}
<commit_msg>Update wording<commit_after>#pragma once

#include <list>
#include <unordered_map>
#include <string>
#include <iostream>
#include <iomanip>
#include <chrono>
#include <functional>
#include <unistd.h>

/**
 * @namespace testy
 * Simple tool to easly manage unit tests.
 */
namespace testy {

/**
 * @macro Suite
 * The macro used to create the test suite.
 */
#define Suite(name, code) \
  int main() { \
    testy::TestSuite testSuite(name); \
    code \
    return testSuite.run(); \
  }

/**
 * @macro describe
 * Describe one entity of the suite.
 */
#define describe(name, ...) \
  testSuite.addTest(name, { \
    __VA_ARGS__ \
  });

/**
 * @macro example
 */
#define example(name, ...) \
  testSuite.addExample(name, [&] () { \
    __VA_ARGS__ \
  });

/**
 * @macro it
 * Test one action of the suite.
 */
#define it(text, ...) \
  {text, [&] () { \
      __VA_ARGS__ \
      return ""; \
    }}

/**
 * @macro test
 * Test if the given expr is true.
 */
#define test(expr) if (!(expr)) return #expr;

/**
 * @macro testRange
 * Test if the given expr is in the given range.
 */
#define testRange(expr, begin, end) \
  { \
    auto const &val = expr; \
    if (val > end || val < begin) \
      return #expr; \
  }

/**
 * @macro testThrow
 * Test if the given `expr` throw the given `except`.
 */
#define testThrow(expr, except) try { expr } catch (except) {}

/**
 * TestSuite
 * Simple test suite in which you can register units and run all unit tests.
 */
class TestSuite {
 public:
  /**
   * @typedef Unit
   * Describe a unit to test.
   */
  typedef std::list<std::pair<std::string, std::function<std::string()>>> Unit;
  TestSuite(std::string const &name) : _name(name) {}
  ~TestSuite() {}
  inline void displayTitle(std::string const &title);
  inline void displaySubtitle(std::string const &subTitle);
  inline void addTest(std::string const &desc, Unit const &unit);
  inline void addExample(std::string const &, std::function<void()> const &);
  inline int run();
 private:
  std::string _name;
  std::list<std::pair<std::string, Unit>> _tests;
  std::list<std::pair<std::string, std::function<void()>>> _examples;
};

inline void TestSuite::displayTitle(std::string const &title) {
    std::cout << std::endl << "  \e[1m" << title << std::endl;
    std::cout << "  ";
    for (size_t i = 0; i < title.size(); ++i)
      std::cout << "=";
    std::cout << "\e[m"<< std::endl;
}

inline void TestSuite::displaySubtitle(std::string const &subTitle) {
  std::cout << "  \e[m## " << subTitle << std::endl << std::endl;
}

/**
 * Register a new unit test.
 * @param desc The description of this unit.
 * @param unit The unit which contains all tests.
 */
inline void TestSuite::addTest(std::string const &desc,
                               TestSuite::Unit const &unit) {
  _tests.push_back(std::make_pair(desc, unit));
}

/**
 * Register an example, with a simple "classic" output.
 */
inline void TestSuite::addExample(std::string const &desc,
                                  std::function<void()> const &fn) {
  _examples.push_back(std::make_pair(desc, fn));
}

/**
 * Return all unit tests.
 * @return Returns the number of failures or 0 on success.
 */
inline int TestSuite::run() {
  std::chrono::steady_clock::time_point prev;
  int fail = 0;
  int total = 0;
  size_t duration = 0;

  if (!_tests.empty()) {

    displayTitle(_name + "'s tests");
    std::cout << std::endl;
    for (auto &unit : _tests) {

      // Display the test description
      displaySubtitle(unit.first);

      for (auto &test : unit.second) {

        // Run the test and display the fail or success message

        prev = std::chrono::steady_clock::now();
        std::cout << "    ";
        std::string error;
        try {
          error = test.second();
          if (!error.empty()) { // message isnt empty
            ++fail;
            std::cout << "\e[0;31mâœ— ";
          } else { // succeed otherwise
            std::cout << "\e[0;32mâœ“ \e[1;30m";
          }
        } catch (...) { // fail if an unexpected exception is thrown.
          ++fail;
          std::cout << "\e[0;31mâœ— ";
        }

        // and duration of the function call

        size_t delta = (std::chrono::steady_clock::now() - prev).count() / 1000;
        duration += delta;
        std::cout << test.first << " ("
                  << std::fixed << delta
                  << "ms)" << std::endl;

        // display error message

        if (!error.empty())
          std::cout << "        failed with `" << error << "`" << std::endl;

        ++total;
      }
      std::cout << std::endl;

    }

    // Display the result of the tests

    if (fail) {
      std::cout << "  \e[0;31mâœ— " << fail << " of "
                << total << " tests failed "
                << "(" << duration << "ms)";
    } else {
      std::cout << "  \e[0;32mâœ“ " << total
                << " tests completed "
                << "(" << duration << "ms)";
    }
    std::cout << "\e[m" << std::endl << std::endl;
  }

  if (!_examples.empty()) {
    displayTitle(_name + "'s examples");
    std::cout << std::endl;
    for (auto const &example : _examples) {
      displaySubtitle(example.first);
      example.second();
      std::cout << std::endl;
    }
    std::cout << std::endl;
  }

// Wait for keyboard press on windows to keep the output console opened.
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
  std::cout << "  [ Press any key to quit ]" << std::endl << std::endl;
  std::cin.get();
#endif

  return fail;
}

}
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2013-2018 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include "volumeslice.h"
#include <inviwo/core/interaction/events/keyboardevent.h>
#include <inviwo/core/interaction/events/wheelevent.h>
#include <inviwo/core/interaction/events/gestureevent.h>

#include <inviwo/core/datastructures/volume/volume.h>
#include <inviwo/core/datastructures/volume/volumeramprecision.h>
#include <inviwo/core/datastructures/image/imageram.h>
#include <inviwo/core/datastructures/image/layerramprecision.h>

#include <inviwo/core/util/indexmapper.h>

namespace inviwo {

const ProcessorInfo VolumeSlice::processorInfo_{
    "org.inviwo.VolumeSlice",  // Class identifier
    "Volume Slice",            // Display name
    "Volume Operation",        // Category
    CodeState::Stable,         // Code state
    Tags::CPU,                 // Tags
};
const ProcessorInfo VolumeSlice::getProcessorInfo() const {
    return processorInfo_;
}

VolumeSlice::VolumeSlice()
    : Processor()
    , inport_("inputVolume")
    , outport_("outputImage", DataVec4UInt8::get(), false)
    , sliceAlongAxis_("sliceAxis", "Slice along axis",
                      {{"x", "X axis", CartesianCoordinateAxis::X},
                       {"y", "Y axis", CartesianCoordinateAxis::Y},
                       {"z", "Z axis", CartesianCoordinateAxis::Z}},
                      0)
    , sliceNumber_("sliceNumber", "Slice Number", 4, 1, 8)
    , handleInteractionEvents_("handleEvents", "Handle interaction events", true,
                               InvalidationLevel::Valid)
    , mouseShiftSlice_("mouseShiftSlice", "Mouse Slice Shift",
                       [this](Event* e) { eventShiftSlice(e); },
                       util::make_unique<WheelEventMatcher>())

    , stepSliceUp_("stepSliceUp", "Key Slice Up", [this](Event* e) { eventStepSliceUp(e); },
                   IvwKey::W, KeyState::Press)

    , stepSliceDown_("stepSliceDown", "Key Slice Down", [this](Event* e) { eventStepSliceDown(e); },
                     IvwKey::S, KeyState::Press)

    , gestureShiftSlice_(
          "gestureShiftSlice", "Gesture Slice Shift",
          [this](Event* e) { eventGestureShiftSlice(e); },
          util::make_unique<GestureEventMatcher>(GestureType::Pan, GestureStates(flags::any), 3)) {

    addPort(inport_);
    addPort(outport_);
    addProperty(sliceAlongAxis_);
    addProperty(sliceNumber_);
    addProperty(handleInteractionEvents_);

    addProperty(stepSliceUp_);
    addProperty(stepSliceDown_);

    mouseShiftSlice_.setVisible(false);
    mouseShiftSlice_.setCurrentStateAsDefault();
    addProperty(mouseShiftSlice_);

    gestureShiftSlice_.setVisible(false);
    gestureShiftSlice_.setCurrentStateAsDefault();
    addProperty(gestureShiftSlice_);
}

VolumeSlice::~VolumeSlice() = default;

void VolumeSlice::invokeEvent(Event* event) {
    if (!handleInteractionEvents_) return;
    Processor::invokeEvent(event);
}

void VolumeSlice::shiftSlice(int shift) {
    auto newSlice = static_cast<size_t>(sliceNumber_.get() + shift);
    if (newSlice >= sliceNumber_.getMinValue() && newSlice <= sliceNumber_.getMaxValue()) {
        sliceNumber_.set(newSlice);
    }
}

void VolumeSlice::process() {
    auto vol = inport_.getData();

    const auto dims(vol->getDimensions());
    double pos {sliceNumber_.get() / static_cast<double>(sliceNumber_.getMaxValue())};
    switch (sliceAlongAxis_.get()) {
        case CartesianCoordinateAxis::X:
            if (dims.x != sliceNumber_.getMaxValue()) {
                sliceNumber_.setMaxValue(dims.x);
                sliceNumber_.set(static_cast<size_t>(pos * dims.x));
            }
            break;
        case CartesianCoordinateAxis::Y:
            if (dims.y != sliceNumber_.getMaxValue()) {
                sliceNumber_.setMaxValue(dims.y);
                sliceNumber_.set(static_cast<size_t>(pos * dims.y));
            }
            break;
        case CartesianCoordinateAxis::Z:
            if (dims.z != sliceNumber_.getMaxValue()) {
                sliceNumber_.setMaxValue(dims.z);
                sliceNumber_.set(static_cast<size_t>(pos * dims.z));
            }
            break;
    }

    auto image =
        vol->getRepresentation<VolumeRAM>()
            ->dispatch<std::shared_ptr<Image>, dispatching::filter::All>([
                axis = static_cast<CartesianCoordinateAxis>(sliceAlongAxis_.get()),
                slice = static_cast<size_t>(sliceNumber_.get() - 1), &cache = imageCache_
            ](const auto vrprecision) {
                using T = util::PrecsionValueType<decltype(vrprecision)>;

                const T* voldata = vrprecision->getDataTyped();
                const auto voldim = vrprecision->getDimensions();

                const auto imgdim = [&]() {
                    switch (axis) {
                        default:
                            return size2_t(voldim.z, voldim.y);
                        case CartesianCoordinateAxis::X:
                            return size2_t(voldim.z, voldim.y);
                        case CartesianCoordinateAxis::Y:
                            return size2_t(voldim.x, voldim.z);
                        case CartesianCoordinateAxis::Z:
                            return size2_t(voldim.x, voldim.y);
                    }
                }();

                auto res = cache.getTypedUnused<T>(imgdim);
                auto sliceImage = res.first;
                auto layerrep = res.second;
                auto layerdata = layerrep->getDataTyped();

                switch (util::extent<T, 0>::value) {
                    case 1:
                        layerrep->setSwizzleMask({{ImageChannel::Red, ImageChannel::Zero,
                                                   ImageChannel::Zero, ImageChannel::One}});
                    case 2:
                        layerrep->setSwizzleMask({{ImageChannel::Red, ImageChannel::Green,
                                                   ImageChannel::Zero, ImageChannel::One}});
                    case 3:
                        layerrep->setSwizzleMask({{ImageChannel::Red, ImageChannel::Green,
                                                   ImageChannel::Blue, ImageChannel::One}});
                    default:
                    case 4:
                        layerrep->setSwizzleMask({{ImageChannel::Red, ImageChannel::Green,
                                                   ImageChannel::Blue, ImageChannel::Alpha}});
                }

                size_t offsetVolume;
                size_t offsetImage;
                switch (axis) {
                    case CartesianCoordinateAxis::X: {
                        util::IndexMapper3D vm(voldim);
                        util::IndexMapper2D im(imgdim);
                        auto x = glm::clamp(slice, size_t{0}, voldim.x - 1);
                        for (size_t z = 0; z < voldim.z; z++) {
                            for (size_t y = 0; y < voldim.y; y++) {
                                offsetVolume = vm(x, y, z);
                                offsetImage = im(z, y);
                                layerdata[offsetImage] = voldata[offsetVolume];
                            }
                        }
                        break;
                    }
                    case CartesianCoordinateAxis::Y: {
                        auto y = glm::clamp(slice, size_t{0}, voldim.y - 1);
                        const size_t dataSize = voldim.x;
                        const size_t initialStartPos = y * voldim.x;
                        for (size_t j = 0; j < voldim.z; j++) {
                            offsetVolume = (j * voldim.x * voldim.y) + initialStartPos;
                            offsetImage = j * voldim.x;
                            std::copy(voldata + offsetVolume, voldata + offsetVolume + dataSize,
                                      layerdata + offsetImage);
                        }
                        break;
                    }
                    case CartesianCoordinateAxis::Z: {
                        auto z = glm::clamp(slice, size_t{0}, voldim.z - 1);
                        const size_t dataSize = voldim.x * voldim.y;
                        const size_t initialStartPos = z * voldim.x * voldim.y;

                        std::copy(voldata + initialStartPos, voldata + initialStartPos + dataSize,
                                  layerdata);
                        break;
                    }
                }
                cache.add(sliceImage);
                return sliceImage;
            });

    outport_.setData(image);
}

void VolumeSlice::eventShiftSlice(Event* event) {
    auto wheelEvent = static_cast<WheelEvent*>(event);
    int steps = static_cast<int>(wheelEvent->delta().y);
    shiftSlice(steps);
}

void VolumeSlice::eventStepSliceUp(Event*) { shiftSlice(1); }

void VolumeSlice::eventStepSliceDown(Event*) { shiftSlice(-1); }

void VolumeSlice::eventGestureShiftSlice(Event* event) {
    GestureEvent* gestureEvent = static_cast<GestureEvent*>(event);
    if (gestureEvent->deltaPos().y < 0)
        shiftSlice(1);
    else if (gestureEvent->deltaPos().y > 0)
        shiftSlice(-1);
}

}  // inviwo namespace

<commit_msg>Base: VolumeSlice: Swizzeling fix (and code formating)<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2013-2018 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include "volumeslice.h"
#include <inviwo/core/interaction/events/keyboardevent.h>
#include <inviwo/core/interaction/events/wheelevent.h>
#include <inviwo/core/interaction/events/gestureevent.h>

#include <inviwo/core/datastructures/volume/volume.h>
#include <inviwo/core/datastructures/volume/volumeramprecision.h>
#include <inviwo/core/datastructures/image/imageram.h>
#include <inviwo/core/datastructures/image/layerramprecision.h>

#include <inviwo/core/util/indexmapper.h>

namespace inviwo {

const ProcessorInfo VolumeSlice::processorInfo_{
    "org.inviwo.VolumeSlice",  // Class identifier
    "Volume Slice",            // Display name
    "Volume Operation",        // Category
    CodeState::Stable,         // Code state
    Tags::CPU,                 // Tags
};
const ProcessorInfo VolumeSlice::getProcessorInfo() const { return processorInfo_; }

VolumeSlice::VolumeSlice()
    : Processor()
    , inport_("inputVolume")
    , outport_("outputImage", DataVec4UInt8::get(), false)
    , sliceAlongAxis_("sliceAxis", "Slice along axis",
                      {{"x", "X axis", CartesianCoordinateAxis::X},
                       {"y", "Y axis", CartesianCoordinateAxis::Y},
                       {"z", "Z axis", CartesianCoordinateAxis::Z}},
                      0)
    , sliceNumber_("sliceNumber", "Slice Number", 4, 1, 8)
    , handleInteractionEvents_("handleEvents", "Handle interaction events", true,
                               InvalidationLevel::Valid)
    , mouseShiftSlice_("mouseShiftSlice", "Mouse Slice Shift",
                       [this](Event* e) { eventShiftSlice(e); },
                       util::make_unique<WheelEventMatcher>())

    , stepSliceUp_("stepSliceUp", "Key Slice Up", [this](Event* e) { eventStepSliceUp(e); },
                   IvwKey::W, KeyState::Press)

    , stepSliceDown_("stepSliceDown", "Key Slice Down", [this](Event* e) { eventStepSliceDown(e); },
                     IvwKey::S, KeyState::Press)

    , gestureShiftSlice_(
          "gestureShiftSlice", "Gesture Slice Shift",
          [this](Event* e) { eventGestureShiftSlice(e); },
          util::make_unique<GestureEventMatcher>(GestureType::Pan, GestureStates(flags::any), 3)) {

    addPort(inport_);
    addPort(outport_);
    addProperty(sliceAlongAxis_);
    addProperty(sliceNumber_);
    addProperty(handleInteractionEvents_);

    addProperty(stepSliceUp_);
    addProperty(stepSliceDown_);

    mouseShiftSlice_.setVisible(false);
    mouseShiftSlice_.setCurrentStateAsDefault();
    addProperty(mouseShiftSlice_);

    gestureShiftSlice_.setVisible(false);
    gestureShiftSlice_.setCurrentStateAsDefault();
    addProperty(gestureShiftSlice_);
}

VolumeSlice::~VolumeSlice() = default;

void VolumeSlice::invokeEvent(Event* event) {
    if (!handleInteractionEvents_) return;
    Processor::invokeEvent(event);
}

void VolumeSlice::shiftSlice(int shift) {
    auto newSlice = static_cast<size_t>(sliceNumber_.get() + shift);
    if (newSlice >= sliceNumber_.getMinValue() && newSlice <= sliceNumber_.getMaxValue()) {
        sliceNumber_.set(newSlice);
    }
}

void VolumeSlice::process() {
    auto vol = inport_.getData();

    const auto dims(vol->getDimensions());
    double pos{sliceNumber_.get() / static_cast<double>(sliceNumber_.getMaxValue())};
    switch (sliceAlongAxis_.get()) {
        case CartesianCoordinateAxis::X:
            if (dims.x != sliceNumber_.getMaxValue()) {
                sliceNumber_.setMaxValue(dims.x);
                sliceNumber_.set(static_cast<size_t>(pos * dims.x));
            }
            break;
        case CartesianCoordinateAxis::Y:
            if (dims.y != sliceNumber_.getMaxValue()) {
                sliceNumber_.setMaxValue(dims.y);
                sliceNumber_.set(static_cast<size_t>(pos * dims.y));
            }
            break;
        case CartesianCoordinateAxis::Z:
            if (dims.z != sliceNumber_.getMaxValue()) {
                sliceNumber_.setMaxValue(dims.z);
                sliceNumber_.set(static_cast<size_t>(pos * dims.z));
            }
            break;
    }

    auto image =
        vol->getRepresentation<VolumeRAM>()
            ->dispatch<std::shared_ptr<Image>, dispatching::filter::All>([
                axis = static_cast<CartesianCoordinateAxis>(sliceAlongAxis_.get()),
                slice = static_cast<size_t>(sliceNumber_.get() - 1), &cache = imageCache_
            ](const auto vrprecision) {
                using T = util::PrecsionValueType<decltype(vrprecision)>;

                const T* voldata = vrprecision->getDataTyped();
                const auto voldim = vrprecision->getDimensions();

                const auto imgdim = [&]() {
                    switch (axis) {
                        default:
                            return size2_t(voldim.z, voldim.y);
                        case CartesianCoordinateAxis::X:
                            return size2_t(voldim.z, voldim.y);
                        case CartesianCoordinateAxis::Y:
                            return size2_t(voldim.x, voldim.z);
                        case CartesianCoordinateAxis::Z:
                            return size2_t(voldim.x, voldim.y);
                    }
                }();

                auto res = cache.getTypedUnused<T>(imgdim);
                auto sliceImage = res.first;
                auto layerrep = res.second;
                auto layerdata = layerrep->getDataTyped();

                switch (util::extent<T, 0>::value) {
                    case 0:  // util::extent<T, 0>::value returns zero for non-glm types
                    case 1:
                        layerrep->setSwizzleMask({{ImageChannel::Red, ImageChannel::Red,
                                                   ImageChannel::Red, ImageChannel::One}});
                        break;
                    case 2:
                        layerrep->setSwizzleMask({{ImageChannel::Red, ImageChannel::Green,
                                                   ImageChannel::Zero, ImageChannel::One}});
                        break;
                    case 3:
                        layerrep->setSwizzleMask({{ImageChannel::Red, ImageChannel::Green,
                                                   ImageChannel::Blue, ImageChannel::One}});
                        break;
                    default:
                    case 4:
                        layerrep->setSwizzleMask({{ImageChannel::Red, ImageChannel::Green,
                                                   ImageChannel::Blue, ImageChannel::Alpha}});
                }

                size_t offsetVolume;
                size_t offsetImage;
                switch (axis) {
                    case CartesianCoordinateAxis::X: {
                        util::IndexMapper3D vm(voldim);
                        util::IndexMapper2D im(imgdim);
                        auto x = glm::clamp(slice, size_t{0}, voldim.x - 1);
                        for (size_t z = 0; z < voldim.z; z++) {
                            for (size_t y = 0; y < voldim.y; y++) {
                                offsetVolume = vm(x, y, z);
                                offsetImage = im(z, y);
                                layerdata[offsetImage] = voldata[offsetVolume];
                            }
                        }
                        break;
                    }
                    case CartesianCoordinateAxis::Y: {
                        auto y = glm::clamp(slice, size_t{0}, voldim.y - 1);
                        const size_t dataSize = voldim.x;
                        const size_t initialStartPos = y * voldim.x;
                        for (size_t j = 0; j < voldim.z; j++) {
                            offsetVolume = (j * voldim.x * voldim.y) + initialStartPos;
                            offsetImage = j * voldim.x;
                            std::copy(voldata + offsetVolume, voldata + offsetVolume + dataSize,
                                      layerdata + offsetImage);
                        }
                        break;
                    }
                    case CartesianCoordinateAxis::Z: {
                        auto z = glm::clamp(slice, size_t{0}, voldim.z - 1);
                        const size_t dataSize = voldim.x * voldim.y;
                        const size_t initialStartPos = z * voldim.x * voldim.y;

                        std::copy(voldata + initialStartPos, voldata + initialStartPos + dataSize,
                                  layerdata);
                        break;
                    }
                }
                cache.add(sliceImage);
                return sliceImage;
            });

    outport_.setData(image);
}

void VolumeSlice::eventShiftSlice(Event* event) {
    auto wheelEvent = static_cast<WheelEvent*>(event);
    int steps = static_cast<int>(wheelEvent->delta().y);
    shiftSlice(steps);
}

void VolumeSlice::eventStepSliceUp(Event*) { shiftSlice(1); }

void VolumeSlice::eventStepSliceDown(Event*) { shiftSlice(-1); }

void VolumeSlice::eventGestureShiftSlice(Event* event) {
    GestureEvent* gestureEvent = static_cast<GestureEvent*>(event);
    if (gestureEvent->deltaPos().y < 0)
        shiftSlice(1);
    else if (gestureEvent->deltaPos().y > 0)
        shiftSlice(-1);
}

}  // namespace inviwo
<|endoftext|>


<commit_before>#include "motor.h"
#include "timer_encoder.h"
#include "interrupt_encoder.h"
#include "irsensor.h"
#include "gyro.h"
#include "pid.h"
#include "digital_output.h"
#include "distance_sensor.h"

#include "stdlib.h"

#include "mbed.h"

#ifndef BTSERIAL
Serial serial(PA_2, PA_3);
#endif
#ifdef BTSERIAL
Serial serial(PA_9, PA_10);
#endif

HAL::Timer motor_timer(HAL::Timer::TIMER3, HAL::Timer::CPU);
HAL::Timer::Channel lbwd(motor_timer, HAL::Timer::CH1, HAL::Timer::Channel::COMPARE_PWM1, PC_6);
HAL::Timer::Channel lfwd(motor_timer, HAL::Timer::CH2, HAL::Timer::Channel::COMPARE_PWM1, PC_7);
HAL::Timer::Channel rbwd(motor_timer, HAL::Timer::CH4, HAL::Timer::Channel::COMPARE_PWM1, PC_9);
HAL::Timer::Channel rfwd(motor_timer, HAL::Timer::CH3, HAL::Timer::Channel::COMPARE_PWM1, PC_8);
Motor left_motor(lfwd, lbwd);
Motor right_motor(rfwd, rbwd);

TimerEncoder left_encoder(HAL::Timer::TIMER2, PA_1, PA_0);
InterruptEncoder right_encoder(PB_3, PA_15, InterruptEncoder::X4);

DigitalInput sw1(PB_12);
DigitalInput sw2(PB_1);
DigitalInput sw3(PB_0);
DigitalInput sw4(PA_7);

DigitalOutput red(PB_15);
DigitalOutput green(PB_14);
DigitalOutput blue(PB_13);

DistanceSensor left_sensor(PC_3, PB_6, DistanceSensor::LOGISTIC, 1925.5, 0.4, 4073.8, 7.7);
DistanceSensor right_sensor(PC_0, PB_8, DistanceSensor::LOGISTIC, 2298.3, 0.4, 4129.8, 6.5);
DistanceSensor left_side_sensor(PC_2, PB_7, DistanceSensor::EXPONENTIAL, 2638.0, 0.3236, 955.0, 0.0);
DistanceSensor right_side_sensor(PC_1, PB_9, DistanceSensor::EXPONENTIAL, 2245.0, 0.2564, 1394.0, 0.0);

Pid combined_controller(20, 0.0, 5);
Pid ir_controller(800, 0, 50);
Pid turn_controller(1, 0, 0.1);

enum Direction {
    FORWARD = 0,
    LEFT = -1,
    RIGHT = 1,
};

double battery_level();
bool is_side_wall(double reading, double distance);
bool is_front_wall(double left, double right, double distance);
void forward(bool is_left_wall, bool is_right_wall, double left_side, double right_side);
void stop();
bool turn(Direction direction);

const int CELL_LENGTH = 795;
bool is_green = true;

int main()
{
    motor_timer.set_period(511);
    motor_timer.enable(true);
    int cell_count = 0;
    Direction mode = FORWARD;
    bool ir_pid = true;
    int turn_counter = 0;
    int stop_counter = 0;
    bool left_opening = false;
    bool right_opening = false;
    green.write(is_green);
    while(true) {
        if(battery_level() < 7.4) {
            red.write(1);
        } else {
            red.write(0);
        }
        if(!sw1.read()) {
            double left = left_sensor.read();
            double right = right_sensor.read();
            double left_side = left_side_sensor.read();
            double right_side = right_side_sensor.read();
            bool is_left_wall = is_side_wall(left_side, 6);
            bool is_right_wall = is_side_wall(right_side, 6);
            left_opening |= !is_left_wall;
            right_opening |= !is_right_wall;
            //blue.write(ir_pid);
            int pos = (left_encoder.count() + right_encoder.count()) / 2;
            if(mode == FORWARD && pos > (CELL_LENGTH * (cell_count + 1))) {
                cell_count++;
                is_green = !is_green;
                green.write(is_green);
                if(sw2.read() || (sw3.read() && (rand() % 2))) {
                    if(left_opening) {
                        stop();
                        mode = LEFT;
                    } else if(right_opening) {
                        stop();
                        mode = RIGHT;
                    }
                }
                left_opening = false;
                right_opening = false;
            }
            if(mode == FORWARD && is_front_wall(left, right, 10)) {
                if(left_opening) {
                    stop();
                    mode = LEFT;
                } else if(right_opening) {
                    stop();
                    mode = RIGHT;
                } else if(rand() % 2) {
                    stop();
                    mode = LEFT;
                } else {
                    stop();
                    mode = RIGHT;
                }
            }
            if(mode == FORWARD && ir_pid && (!is_left_wall || !is_right_wall)) {
                ir_pid = false;
            } else if(mode == FORWARD && !ir_pid && (is_left_wall && is_right_wall)) {
                ir_pid = true;
            }
            switch(mode) {
                case FORWARD:
                    forward(is_left_wall, is_right_wall, left_side, right_side);
                    break;
                case LEFT:
                case RIGHT:
                    if(stop_counter < 1000) {
                        stop_counter++;
                    } else if(turn(mode)) {
                        turn_counter++;
                    }
                    if(turn_counter == 1000) {
                        mode = FORWARD;
                        stop_counter = 0;
                        turn_counter = 0;
                        left_opening = false;
                        right_opening = false;
                        cell_count = 0;
                        left_encoder.reset();
                        right_encoder.reset();
                        turn_controller.reset();
                        combined_controller.reset();
                    }
                    break;
            }
        } else {
            stop();
            serial.printf("l %d\r\n", left_encoder.count());
            serial.printf("r %d\r\n", right_encoder.count());
            wait(1);
        }
    }
}

void stop()
{
    left_motor.brake();
    right_motor.brake();
}

void forward(bool is_left_wall, bool is_right_wall, double left_side, double right_side)
{
    const int BASE_SPEED = 20;
    const int MAX_SPEED = 100;
    const int LEFT_SETPOINT = 3;
    const int RIGHT_SETPOINT = 3;
    int left_speed = BASE_SPEED;
    int right_speed = BASE_SPEED;
    int correction;
    if(is_left_wall && is_right_wall) {
        correction = (int)combined_controller.correction(100*(left_side-right_side)+left_encoder.count()-right_encoder.count());
        //correction = (int)ir_controller.correction(is_left_wall*(left_side - LEFT_SETPOINT) -
         //                                           is_right_wall*(right_side - RIGHT_SETPOINT));
    } else {
        correction = (int)combined_controller.correction(left_encoder.count() - right_encoder.count());
    }
    if(correction > 0) {
        right_speed += correction;
    } else {
        left_speed += correction;
    }
    left_speed = ((unsigned) left_speed > MAX_SPEED) ? MAX_SPEED : left_speed;
    right_speed = ((unsigned) right_speed > MAX_SPEED) ? MAX_SPEED : right_speed;
    left_motor.set_speed(left_speed);
    right_motor.set_speed(right_speed);
}

bool turn(Direction direction)
{
    const int MAX_SPEED = 30;
    int left_speed, right_speed;
    double error = left_encoder.count() - right_encoder.count() - direction * 555;
    int correction = (int)turn_controller.correction(error);
    right_speed = correction;
    right_speed = (right_speed > MAX_SPEED) ? MAX_SPEED : right_speed;
    right_speed = (right_speed < -1 * MAX_SPEED) ? -1 * MAX_SPEED : right_speed;
    left_speed = -1 * right_speed;
    left_motor.set_speed(left_speed);
    right_motor.set_speed(right_speed);
    return turn_controller.get_derivative() == 0;
}

double battery_level()
{
    AnalogIn voltage_divider(PC_5);
    return (8.3 / 54700) * voltage_divider.read_u16();
}

bool is_side_wall(double reading, double distance)
{
    return !isnan(reading) && reading < distance;
}

bool is_front_wall(double left, double right, double distance)
{
    return !isnan(left) && !isnan(right) && left < distance && right < distance;
}
<commit_msg>tunings from competition<commit_after>#include "motor.h"
#include "timer_encoder.h"
#include "interrupt_encoder.h"
#include "irsensor.h"
#include "gyro.h"
#include "pid.h"
#include "digital_output.h"
#include "distance_sensor.h"

#include "stdlib.h"

#include "mbed.h"

#ifndef BTSERIAL
Serial serial(PA_2, PA_3);
#endif
#ifdef BTSERIAL
Serial serial(PA_9, PA_10);
#endif

HAL::Timer motor_timer(HAL::Timer::TIMER3, HAL::Timer::CPU);
HAL::Timer::Channel lbwd(motor_timer, HAL::Timer::CH1, HAL::Timer::Channel::COMPARE_PWM1, PC_6);
HAL::Timer::Channel lfwd(motor_timer, HAL::Timer::CH2, HAL::Timer::Channel::COMPARE_PWM1, PC_7);
HAL::Timer::Channel rbwd(motor_timer, HAL::Timer::CH4, HAL::Timer::Channel::COMPARE_PWM1, PC_9);
HAL::Timer::Channel rfwd(motor_timer, HAL::Timer::CH3, HAL::Timer::Channel::COMPARE_PWM1, PC_8);
Motor left_motor(lfwd, lbwd);
Motor right_motor(rfwd, rbwd);

TimerEncoder left_encoder(HAL::Timer::TIMER2, PA_1, PA_0);
InterruptEncoder right_encoder(PB_3, PA_15, InterruptEncoder::X4);

DigitalInput sw1(PB_12);
DigitalInput sw2(PB_1);
DigitalInput sw3(PB_0);
DigitalInput sw4(PA_7);

DigitalOutput red(PB_15);
DigitalOutput green(PB_14);
DigitalOutput blue(PB_13);

DistanceSensor left_sensor(PC_3, PB_6, DistanceSensor::LOGISTIC, 1925.5, 0.4, 4073.8, 7.7);
DistanceSensor right_sensor(PC_0, PB_8, DistanceSensor::LOGISTIC, 2298.3, 0.4, 4129.8, 6.5);
DistanceSensor left_side_sensor(PC_2, PB_7, DistanceSensor::EXPONENTIAL, 2395.0, 0.3236, 1367.0, 0.0);
DistanceSensor right_side_sensor(PC_1, PB_9, DistanceSensor::EXPONENTIAL, 1637.0, 0.2564, 2053.0, 0.0);

Pid combined_controller(20, 0.0, 5);
Pid ir_controller(800, 0, 50);
Pid turn_controller(1, 0, 0.1);

enum Direction {
    FORWARD = 0,
    LEFT = -1,
    RIGHT = 1,
};

double battery_level();
bool is_side_wall(double reading, double distance);
bool is_front_wall(double left, double right, double distance);
void forward(bool is_left_wall, bool is_right_wall, double left_side, double right_side);
void stop();
bool turn(Direction direction);

const int CELL_LENGTH = 795;
bool is_green = true;

int main()
{
    motor_timer.set_period(511);
    motor_timer.enable(true);
    srand(left_side_sensor.raw_read() % 16);
    int cell_count = 0;
    Direction mode = FORWARD;
    bool ir_pid = true;
    int turn_counter = 0;
    int stop_counter = 0;
    bool left_opening = false;
    bool right_opening = false;
    green.write(is_green);
    while(true) {
        if(battery_level() < 7.4) {
            red.write(1);
        } else {
            red.write(0);
        }
        if(!sw1.read()) {
            double left = left_sensor.read();
            double right = right_sensor.read();
            double left_side = left_side_sensor.read();
            double right_side = right_side_sensor.read();
            bool is_left_wall = is_side_wall(left_side, 7.8);
            bool is_right_wall = is_side_wall(right_side, 9.5);
            left_opening |= !is_left_wall;
            right_opening |= !is_right_wall;
            blue.write(ir_pid);
            int pos = (left_encoder.count() + right_encoder.count()) / 2;
            if(mode == FORWARD && pos > (CELL_LENGTH * (cell_count + 1))) {
                cell_count++;
                is_green = !is_green;
                green.write(is_green);
                if(sw2.read() || (sw3.read() && (rand() % 2))) {
                    bool only_one = left_opening ^ right_opening;
                    if(!sw4.read() || only_one) {
                        if(left_opening) {
                            stop();
                            mode = LEFT;
                        } else if(right_opening) {
                            stop();
                            mode = RIGHT;
                        }
                    }
                }
                left_opening = false;
                right_opening = false;
            }
            if(mode == FORWARD && is_front_wall(left, right, 5.0)) {
                if(left_opening) {
                    stop();
                    mode = LEFT;
                } else if(right_opening) {
                    stop();
                    mode = RIGHT;
                } else if(rand() % 2) {
                    stop();
                    mode = LEFT;
                } else {
                    stop();
                    mode = RIGHT;
                }
            }
            if(mode == FORWARD && ir_pid && (!is_left_wall || !is_right_wall)) {
                ir_pid = false;
            } else if(mode == FORWARD && !ir_pid && (is_left_wall && is_right_wall)) {
                ir_pid = true;
            }
            switch(mode) {
                case FORWARD:
                    forward(is_left_wall, is_right_wall, left_side, right_side);
                    break;
                case LEFT:
                case RIGHT:
                    if(stop_counter < 1000) {
                        stop_counter++;
                    } else if(turn(mode)) {
                        turn_counter++;
                    }
                    if(turn_counter == 1000) {
                        mode = FORWARD;
                        stop_counter = 0;
                        turn_counter = 0;
                        left_opening = false;
                        right_opening = false;
                        cell_count = 0;
                        left_encoder.reset();
                        right_encoder.reset();
                        turn_controller.reset();
                        combined_controller.reset();
                    }
                    break;
            }
        } else {
            stop();
            serial.printf("l %d\r\n", left_side_sensor.raw_read());
            serial.printf("l %f\r\n", left_side_sensor.read());
            serial.printf("r %d\r\n", right_side_sensor.raw_read());
            serial.printf("r %f\r\n", right_side_sensor.read());
            wait(1);
        }
    }
}

void stop()
{
    left_motor.brake();
    right_motor.brake();
}

void forward(bool is_left_wall, bool is_right_wall, double left_side, double right_side)
{
    const int BASE_SPEED = 20;
    const int MAX_SPEED = 100;
    const int LEFT_SETPOINT = 3;
    const int RIGHT_SETPOINT = 3;
    int left_speed = BASE_SPEED;
    int right_speed = BASE_SPEED;
    int correction;
    if(is_left_wall && is_right_wall) {
        correction = (int)combined_controller.correction(100*(left_side-right_side)+left_encoder.count()-right_encoder.count());
        //correction = (int)ir_controller.correction(is_left_wall*(left_side - LEFT_SETPOINT) -
         //                                           is_right_wall*(right_side - RIGHT_SETPOINT));
    } else {
        correction = (int)combined_controller.correction(left_encoder.count() - right_encoder.count());
    }
    if(correction > 0) {
        right_speed += correction;
    } else {
        left_speed += correction;
    }
    left_speed = ((unsigned) left_speed > MAX_SPEED) ? MAX_SPEED : left_speed;
    right_speed = ((unsigned) right_speed > MAX_SPEED) ? MAX_SPEED : right_speed;
    left_motor.set_speed(left_speed);
    right_motor.set_speed(right_speed);
}

bool turn(Direction direction)
{
    const int MAX_SPEED = 30;
    int left_speed, right_speed;
    double error = left_encoder.count() - right_encoder.count() - direction * 555;
    int correction = (int)turn_controller.correction(error);
    right_speed = correction;
    right_speed = (right_speed > MAX_SPEED) ? MAX_SPEED : right_speed;
    right_speed = (right_speed < -1 * MAX_SPEED) ? -1 * MAX_SPEED : right_speed;
    left_speed = -1 * right_speed;
    left_motor.set_speed(left_speed);
    right_motor.set_speed(right_speed);
    return turn_controller.get_derivative() == 0;
}

double battery_level()
{
    AnalogIn voltage_divider(PC_5);
    return (8.3 / 54700) * voltage_divider.read_u16();
}

bool is_side_wall(double reading, double distance)
{
    return !isnan(reading) && reading < distance;
}

bool is_front_wall(double left, double right, double distance)
{
    return !isnan(left) && !isnan(right) && left < distance && right < distance;
}
<|endoftext|>


<commit_before>#include "Globals.h"

const char* g_version = "5.5";
const char* g_app_name = "Command Line Utility";
const char* g_developer_name = "Shai Roitman";
<commit_msg>Bumped minor version<commit_after>#include "Globals.h"

const char* g_version = "5.5.1";
const char* g_app_name = "Command Line Utility";
const char* g_developer_name = "Shai Roitman";
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief V8 Traverser
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "v8.h"
#include "V8/v8-conv.h"
#include "V8/v8-utils.h"
#include "V8Server/v8-vocbaseprivate.h"
#include "V8Server/v8-wrapshapedjson.h"
#include "V8Server/v8-vocindex.h"
#include "V8Server/v8-collection.h"
#include "Utils/transactions.h"
#include "Utils/V8ResolverGuard.h"
#include "Utils/CollectionNameResolver.h"
#include "Traverser.h"
#include "VocBase/key-generator.h"

using namespace std;
using namespace triagens::basics;
using namespace triagens::arango;

class SimpleEdgeExpander {

  private:
    TRI_edge_direction_e forwardDirection;
    TRI_edge_direction_e backwardDirection;
    TRI_document_collection_t* edgeCollection;
    CollectionNameResolver const* resolver;

  public:
    void operator() ( Traverser::VertexId source,
                      Traverser::Direction dir,
                      vector<Traverser::Neighbor>& result
                    ) {
      std::vector<TRI_doc_mptr_copy_t> edges;
      // Process Vertex Id!
      size_t split;
      char const* str = source.c_str();
      if (!TRI_ValidateDocumentIdKeyGenerator(str, &split)) {
        // TODO Error Handling
        return;
      }
      std::unique_ptr<char[]>& key;
      string& collectionName = string(str, split);
      auto const length = str->length() - split - 1;
      auto buffer = new char[length + 1];
      memcpy(buffer, *str + split + 1, length);
      buffer[length] = '\0';
      key.reset(buffer);

      auto col = resolver->getCollectionStruct(collectionName);
      if (col == nullptr) {
        // collection not found
        throw TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND;
      }
      auto collectionCId = col->_cid;
      if (dir == Traverser::FORWARD) {
        edges = TRI_LookupEdgesDocumentCollection(edgeCollection, forwardDirection, collectionCId, key.get());
      } else {
        edges = TRI_LookupEdgesDocumentCollection(edgeCollection, backwardDirection, collectionCId, key.get());
      }

      // TODO Build result
    }
    SimpleEdgeExpander(
      TRI_edge_direction_e edgeDirection,
      TRI_document_collection_t* edgeCollection,
      CollectionNameResolver const* resolver
    ) :
      edgeCollection(edgeCollection),
      resolver(resolver)
    {
      if (edgeDirection == TRI_EDGE_OUT) {
        forwardDirection = TRI_EDGE_OUT;
        backwardDirection = TRI_EDGE_IN;
      } else if (edgeDirection == TRI_EDGE_IN) {
        forwardDirection = TRI_EDGE_IN;
        backwardDirection = TRI_EDGE_OUT;
      } else {
        forwardDirection = TRI_EDGE_ANY;
        backwardDirection = TRI_EDGE_ANY;
      }
    };
}

struct LocalCollectionGuard {
  LocalCollectionGuard (TRI_vocbase_col_t* collection)
    : _collection(collection) {
  }

  ~LocalCollectionGuard () {
    if (_collection != nullptr && ! _collection->_isLocal) {
      FreeCoordinatorCollection(_collection);
    }
  }

  TRI_vocbase_col_t* _collection;
};

void TRI_RunDijkstraSearch (const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope scope(isolate);

  if (args.Length() < 4 || args.Length() > 5) {
    TRI_V8_THROW_EXCEPTION_USAGE("AQL_SHORTEST_PATH(<vertexcollection>, <edgecollection>, <start>, <end>, <options>)");
  }

  std::unique_ptr<char[]> key;
  TRI_vocbase_t* vocbase;
  TRI_vocbase_col_t const* col = nullptr;

  vocbase = GetContextVocBase(isolate);

  vector<string> readCollections;
  vector<string> writeCollections;
  TRI_voc_cid_t vertexCollectionCId;
  TRI_voc_cid_t edgeCollectionCId;
  TRI_voc_rid_t rid;

  double lockTimeout = (double) (TRI_TRANSACTION_DEFAULT_LOCK_TIMEOUT / 1000000ULL);
  bool embed = false;
  bool waitForSync = false;

  // get the vertex collection
  if (! args[0]->IsString()) {
    TRI_V8_THROW_TYPE_ERROR("expecting string for <vertexcollection>");
  }
  string vertexCollectionName = TRI_ObjectToString(args[0]);

  // get the edge collection
  if (! args[1]->IsString()) {
    TRI_V8_THROW_TYPE_ERROR("expecting string for <edgecollection>");
  }
  string const edgeCollectionName = TRI_ObjectToString(args[1]);

  vocbase = GetContextVocBase(isolate);

  if (vocbase == nullptr) {
    TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
  }
  V8ResolverGuard resolver(vocbase);

  readCollections.push_back(vertexCollectionName);
  readCollections.push_back(edgeCollectionName);

  if (! args[2]->IsString()) {
    TRI_V8_THROW_TYPE_ERROR("expecting string for <startVertex>");
  }

  std::string vertexColName;

  if (! ExtractDocumentHandle(isolate, args[2], vertexColName, key, rid)) {
    TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD);
  }

  if (key.get() == nullptr) {
    TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD);
  }

  TRI_ASSERT(key.get() != nullptr);

  // IHHF isCoordinator

  // Start Transaction to collect all parts of the path
  ExplicitTransaction trx(
    vocbase,
    readCollections,
    writeCollections,
    lockTimeout,
    waitForSync,
    embed
  );

  int res = trx.begin();

  if (res != TRI_ERROR_NO_ERROR) {
    TRI_V8_THROW_EXCEPTION(res);
  }

  col = resolver.getResolver()->getCollectionStruct(vertexCollectionName);
  if (col == nullptr) {
    // collection not found
    TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND);
  }
  vertexCollectionCId = col->_cid;
  if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) {
    TRI_V8_THROW_EXCEPTION_MEMORY();
  }

  col = resolver.getResolver()->getCollectionStruct(edgeCollectionName);
  if (col == nullptr) {
    // collection not found
    TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND);
  }
  edgeCollectionCId = col->_cid;
  if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) {
    TRI_V8_THROW_EXCEPTION_MEMORY();
  }

  v8::Handle<v8::Value> result;
  v8::Handle<v8::Array> documents;

  // This is how to get the data out of the collections!
  // Vertices
  TRI_doc_mptr_copy_t document;
  res = trx.readSingle(trx.trxCollection(vertexCollectionCId), &document, key.get());

  // Edges TRI_EDGE_OUT is hardcoded
  TRI_document_collection_t* ecol = trx.trxCollection(edgeCollectionCId)->_collection->_collection;
  std::vector<TRI_doc_mptr_copy_t>&& edges = TRI_LookupEdgesDocumentCollection(ecol, TRI_EDGE_OUT, vertexCollectionCId, key.get());

  // Add Dijkstra here

  // Now build up the result use Subtransactions for each used collection
  if (res == TRI_ERROR_NO_ERROR) {
    {
      // Collect all vertices
      SingleCollectionReadOnlyTransaction subtrx(new V8TransactionContext(true), vocbase, vertexCollectionCId);

      res = subtrx.begin();

      if (res != TRI_ERROR_NO_ERROR) {
        TRI_V8_THROW_EXCEPTION(res);
      }

      result = TRI_WrapShapedJson(isolate, subtrx, vertexCollectionCId, document.getDataPtr());

      if (document.getDataPtr() == nullptr) {
        res = TRI_ERROR_ARANGO_DOCUMENT_NOT_FOUND;
        TRI_V8_THROW_EXCEPTION(res);
      }

      res = subtrx.finish(res);
    }

    {
      // Collect all edges
      SingleCollectionReadOnlyTransaction subtrx2(new V8TransactionContext(true), vocbase, edgeCollectionCId);

      res = subtrx2.begin();

      if (res != TRI_ERROR_NO_ERROR) {
        TRI_V8_THROW_EXCEPTION(res);
      }

      bool error = false;

      uint32_t const n = static_cast<uint32_t>(edges.size());
      documents = v8::Array::New(isolate, static_cast<int>(n));
      for (size_t j = 0;  j < n;  ++j) {
        v8::Handle<v8::Value> doc = TRI_WrapShapedJson(isolate, subtrx2, edgeCollectionCId, edges[j].getDataPtr());

        if (doc.IsEmpty()) {
          error = true;
          break;
        }
        else {
          documents->Set(static_cast<uint32_t>(j), doc);
        }
      }
      if (error) {
        TRI_V8_THROW_EXCEPTION_MEMORY();
      }

      res = subtrx2.finish(res);
    }
  }
  res = trx.finish(res);

  // Not yet correct. Needs to build an object first.
  // TRI_V8_RETURN(result);
  TRI_V8_RETURN(documents);
}
<commit_msg>Make it compile. Probably still fishy.<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief V8 Traverser
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "v8.h"
#include "V8/v8-conv.h"
#include "V8/v8-utils.h"
#include "V8Server/v8-vocbaseprivate.h"
#include "V8Server/v8-wrapshapedjson.h"
#include "V8Server/v8-vocindex.h"
#include "V8Server/v8-collection.h"
#include "Utils/transactions.h"
#include "Utils/V8ResolverGuard.h"
#include "Utils/CollectionNameResolver.h"
#include "Traverser.h"
#include "VocBase/key-generator.h"

using namespace std;
using namespace triagens::basics;
using namespace triagens::arango;

class SimpleEdgeExpander {

  private:
    TRI_edge_direction_e forwardDirection;
    TRI_edge_direction_e backwardDirection;
    TRI_document_collection_t* edgeCollection;
    CollectionNameResolver const* resolver;

  public:
    void operator() ( Traverser::VertexId source,
                      Traverser::Direction dir,
                      vector<Traverser::Neighbor>& result
                    ) {
      std::vector<TRI_doc_mptr_copy_t> edges;
      // Process Vertex Id!
      size_t split;
      char const* str = source.c_str();
      if (!TRI_ValidateDocumentIdKeyGenerator(str, &split)) {
        // TODO Error Handling
        return;
      }
      std::unique_ptr<char> key;
      string collectionName = string(str, split);
      auto const length = source.size() - split - 1;
      auto buffer = new char[length + 1];
      memcpy(buffer, str + split + 1, length);
      buffer[length] = '\0';
      key.reset(buffer);

      auto col = resolver->getCollectionStruct(collectionName);
      if (col == nullptr) {
        // collection not found
        throw TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND;
      }
      auto collectionCId = col->_cid;
      if (dir == Traverser::FORWARD) {
        edges = TRI_LookupEdgesDocumentCollection(edgeCollection, forwardDirection, collectionCId, key.get());
      } else {
        edges = TRI_LookupEdgesDocumentCollection(edgeCollection, backwardDirection, collectionCId, key.get());
      }

      // TODO Build result
    }
    SimpleEdgeExpander(
      TRI_edge_direction_e edgeDirection,
      TRI_document_collection_t* edgeCollection,
      CollectionNameResolver const* resolver
    ) :
      edgeCollection(edgeCollection),
      resolver(resolver)
    {
      if (edgeDirection == TRI_EDGE_OUT) {
        forwardDirection = TRI_EDGE_OUT;
        backwardDirection = TRI_EDGE_IN;
      } else if (edgeDirection == TRI_EDGE_IN) {
        forwardDirection = TRI_EDGE_IN;
        backwardDirection = TRI_EDGE_OUT;
      } else {
        forwardDirection = TRI_EDGE_ANY;
        backwardDirection = TRI_EDGE_ANY;
      }
    };
};

struct LocalCollectionGuard {
  LocalCollectionGuard (TRI_vocbase_col_t* collection)
    : _collection(collection) {
  }

  ~LocalCollectionGuard () {
    if (_collection != nullptr && ! _collection->_isLocal) {
      FreeCoordinatorCollection(_collection);
    }
  }

  TRI_vocbase_col_t* _collection;
};

void TRI_RunDijkstraSearch (const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope scope(isolate);

  if (args.Length() < 4 || args.Length() > 5) {
    TRI_V8_THROW_EXCEPTION_USAGE("AQL_SHORTEST_PATH(<vertexcollection>, <edgecollection>, <start>, <end>, <options>)");
  }

  std::unique_ptr<char[]> key;
  TRI_vocbase_t* vocbase;
  TRI_vocbase_col_t const* col = nullptr;

  vocbase = GetContextVocBase(isolate);

  vector<string> readCollections;
  vector<string> writeCollections;
  TRI_voc_cid_t vertexCollectionCId;
  TRI_voc_cid_t edgeCollectionCId;
  TRI_voc_rid_t rid;

  double lockTimeout = (double) (TRI_TRANSACTION_DEFAULT_LOCK_TIMEOUT / 1000000ULL);
  bool embed = false;
  bool waitForSync = false;

  // get the vertex collection
  if (! args[0]->IsString()) {
    TRI_V8_THROW_TYPE_ERROR("expecting string for <vertexcollection>");
  }
  string vertexCollectionName = TRI_ObjectToString(args[0]);

  // get the edge collection
  if (! args[1]->IsString()) {
    TRI_V8_THROW_TYPE_ERROR("expecting string for <edgecollection>");
  }
  string const edgeCollectionName = TRI_ObjectToString(args[1]);

  vocbase = GetContextVocBase(isolate);

  if (vocbase == nullptr) {
    TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
  }
  V8ResolverGuard resolver(vocbase);

  readCollections.push_back(vertexCollectionName);
  readCollections.push_back(edgeCollectionName);

  if (! args[2]->IsString()) {
    TRI_V8_THROW_TYPE_ERROR("expecting string for <startVertex>");
  }

  std::string vertexColName;

  if (! ExtractDocumentHandle(isolate, args[2], vertexColName, key, rid)) {
    TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD);
  }

  if (key.get() == nullptr) {
    TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD);
  }

  TRI_ASSERT(key.get() != nullptr);

  // IHHF isCoordinator

  // Start Transaction to collect all parts of the path
  ExplicitTransaction trx(
    vocbase,
    readCollections,
    writeCollections,
    lockTimeout,
    waitForSync,
    embed
  );

  int res = trx.begin();

  if (res != TRI_ERROR_NO_ERROR) {
    TRI_V8_THROW_EXCEPTION(res);
  }

  col = resolver.getResolver()->getCollectionStruct(vertexCollectionName);
  if (col == nullptr) {
    // collection not found
    TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND);
  }
  vertexCollectionCId = col->_cid;
  if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) {
    TRI_V8_THROW_EXCEPTION_MEMORY();
  }

  col = resolver.getResolver()->getCollectionStruct(edgeCollectionName);
  if (col == nullptr) {
    // collection not found
    TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND);
  }
  edgeCollectionCId = col->_cid;
  if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) {
    TRI_V8_THROW_EXCEPTION_MEMORY();
  }

  v8::Handle<v8::Value> result;
  v8::Handle<v8::Array> documents;

  // This is how to get the data out of the collections!
  // Vertices
  TRI_doc_mptr_copy_t document;
  res = trx.readSingle(trx.trxCollection(vertexCollectionCId), &document, key.get());

  // Edges TRI_EDGE_OUT is hardcoded
  TRI_document_collection_t* ecol = trx.trxCollection(edgeCollectionCId)->_collection->_collection;
  std::vector<TRI_doc_mptr_copy_t>&& edges = TRI_LookupEdgesDocumentCollection(ecol, TRI_EDGE_OUT, vertexCollectionCId, key.get());

  // Add Dijkstra here

  // Now build up the result use Subtransactions for each used collection
  if (res == TRI_ERROR_NO_ERROR) {
    {
      // Collect all vertices
      SingleCollectionReadOnlyTransaction subtrx(new V8TransactionContext(true), vocbase, vertexCollectionCId);

      res = subtrx.begin();

      if (res != TRI_ERROR_NO_ERROR) {
        TRI_V8_THROW_EXCEPTION(res);
      }

      result = TRI_WrapShapedJson(isolate, subtrx, vertexCollectionCId, document.getDataPtr());

      if (document.getDataPtr() == nullptr) {
        res = TRI_ERROR_ARANGO_DOCUMENT_NOT_FOUND;
        TRI_V8_THROW_EXCEPTION(res);
      }

      res = subtrx.finish(res);
    }

    {
      // Collect all edges
      SingleCollectionReadOnlyTransaction subtrx2(new V8TransactionContext(true), vocbase, edgeCollectionCId);

      res = subtrx2.begin();

      if (res != TRI_ERROR_NO_ERROR) {
        TRI_V8_THROW_EXCEPTION(res);
      }

      bool error = false;

      uint32_t const n = static_cast<uint32_t>(edges.size());
      documents = v8::Array::New(isolate, static_cast<int>(n));
      for (size_t j = 0;  j < n;  ++j) {
        v8::Handle<v8::Value> doc = TRI_WrapShapedJson(isolate, subtrx2, edgeCollectionCId, edges[j].getDataPtr());

        if (doc.IsEmpty()) {
          error = true;
          break;
        }
        else {
          documents->Set(static_cast<uint32_t>(j), doc);
        }
      }
      if (error) {
        TRI_V8_THROW_EXCEPTION_MEMORY();
      }

      res = subtrx2.finish(res);
    }
  }
  res = trx.finish(res);

  // Not yet correct. Needs to build an object first.
  // TRI_V8_RETURN(result);
  TRI_V8_RETURN(documents);
}
<|endoftext|>