<commit_before>// Copyright 2015 Adam Grandquist

#include "./catch.hpp"
#include "./test.hpp"
#include "./reql/types.h"

void
reql_test_cur_end_cb(void *data) {
  *static_cast<int*>(data) = 0;
}

void
reql_test_cur_error_cb(void *res, void *data) {
  if (res != nullptr) {
    *static_cast<int*>(data) = 0;
  }
}

int
reql_test_cur_each_cb(void *res, void *data) {
  if (res != nullptr) {
    ++(*static_cast<int*>(data));
  }
  return res == nullptr;
}

int
reql_test_cur_each_inf_cb(void *res, void *data) {
  int *num = static_cast<int*>(data);
  if (res != nullptr) {
    ++(*num);
  }
  if (*num > 99) {
    return 1;
  }
  return 0;
}

template <typename type>
int
_add(ReQL_Parse_t *, type, size_t);

template <typename type>
int
_add(ReQL_Parse_t *, type);

int
_add(ReQL_Parse_t *);

int
_end_array(ReQL_Parse_t *);

int
_end_element(ReQL_Parse_t *);

int
_end_key_value(ReQL_Parse_t *, const char *, size_t);

int
_end_object(ReQL_Parse_t *);

int
_end_parse(ReQL_Parse_t *);

void
_error(ReQL_Parse_t *);

int
_start_array(ReQL_Parse_t *);

int
_start_element(ReQL_Parse_t *);

int
_start_key_value(ReQL_Parse_t *);

int
_start_object(ReQL_Parse_t *);

int
_start_parse(ReQL_Parse_t *);

Event::Event(std::string name) : p_name(name) {}
Event::Event(std::string name, bool val) : p_bool(val), p_name(name) {}
Event::Event(std::string name, std::string val) : p_name(name), p_str(val) {}
Event::Event(std::string name, double val) : p_name(name), p_num(val) {}

bool Event::operator==(const Event &other) const {
  return p_bool == other.p_bool &&
  p_name == other.p_name &&
  p_num == Approx(other.p_num) &&
  p_str == other.p_str;
}

Parser::Parser() : p_events(), p_parser(new ReQL_Parse_t()) {
  p_parser->add_bool = _add;
  p_parser->add_null = _add;
  p_parser->add_number = _add;
  p_parser->add_string = _add;
  p_parser->data = this;
  p_parser->end_array = _end_array;
  p_parser->end_element = _end_element;
  p_parser->end_key_value = _end_key_value;
  p_parser->end_object = _end_object;
  p_parser->end_parse = _end_parse;
  p_parser->error = _error;
  p_parser->start_array = _start_array;
  p_parser->start_element = _start_element;
  p_parser->start_key_value = _start_key_value;
  p_parser->start_object = _start_object;
  p_parser->start_parse = _start_parse;
}

Parser::~Parser() {
  delete p_parser;
}

ReQL_Parse_t *Parser::get_parser() {
  return p_parser;
}

void Parser::add() {
  p_events.push_back(Event("add"));
}

void Parser::end_array() {
  p_events.push_back(Event("end_array"));
}

void Parser::end_element() {
  p_events.push_back(Event("end_element"));
}

void Parser::end_key_value(std::string key) {
  p_events.push_back(Event("end_key_value", key));
}

void Parser::end_object() {
  p_events.push_back(Event("end_object"));
}

void Parser::end_parse() {
  p_events.push_back(Event("end_parse"));
}

void Parser::error() {
  p_events.push_back(Event("error"));
}

void Parser::start_array() {
  p_events.push_back(Event("start_array"));
}

void Parser::start_element() {
  p_events.push_back(Event("start_element"));
}

void Parser::start_key_value() {
  p_events.push_back(Event("start_key_value"));
}

void Parser::start_object() {
  p_events.push_back(Event("start_object"));
}

void Parser::start_parse() {
  p_events.push_back(Event("start_parse"));
}

int
_add(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->add();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_end_array(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->end_array();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_end_element(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->end_element();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_end_key_value(ReQL_Parse_t *p, const char *key, size_t length) {
  try {
    reinterpret_cast<Parser *>(p->data)->end_key_value(std::string(key, length));
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_end_object(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->end_object();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_end_parse(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->end_parse();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

void
_error(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->error();
  } catch (std::exception) {
  }
}

int
_start_array(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->start_array();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_start_element(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->start_element();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_start_key_value(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->start_key_value();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_start_object(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->start_object();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_start_parse(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->start_parse();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}
<commit_msg>Don't declare twice.<commit_after>// Copyright 2015 Adam Grandquist

#include "./catch.hpp"
#include "./test.hpp"
#include "./reql/types.h"

void
reql_test_cur_end_cb(void *data) {
  *static_cast<int*>(data) = 0;
}

void
reql_test_cur_error_cb(void *res, void *data) {
  if (res != nullptr) {
    *static_cast<int*>(data) = 0;
  }
}

int
reql_test_cur_each_cb(void *res, void *data) {
  if (res != nullptr) {
    ++(*static_cast<int*>(data));
  }
  return res == nullptr;
}

int
reql_test_cur_each_inf_cb(void *res, void *data) {
  int *num = static_cast<int*>(data);
  if (res != nullptr) {
    ++(*num);
  }
  if (*num > 99) {
    return 1;
  }
  return 0;
}

Event::Event(std::string name) : p_name(name) {}
Event::Event(std::string name, bool val) : p_bool(val), p_name(name) {}
Event::Event(std::string name, std::string val) : p_name(name), p_str(val) {}
Event::Event(std::string name, double val) : p_name(name), p_num(val) {}

bool Event::operator==(const Event &other) const {
  return p_bool == other.p_bool &&
  p_name == other.p_name &&
  p_num == Approx(other.p_num) &&
  p_str == other.p_str;
}

Parser::Parser() : p_events(), p_parser(new ReQL_Parse_t()) {
  p_parser->add_bool = _add;
  p_parser->add_null = _add;
  p_parser->add_number = _add;
  p_parser->add_string = _add;
  p_parser->data = this;
  p_parser->end_array = _end_array;
  p_parser->end_element = _end_element;
  p_parser->end_key_value = _end_key_value;
  p_parser->end_object = _end_object;
  p_parser->end_parse = _end_parse;
  p_parser->error = _error;
  p_parser->start_array = _start_array;
  p_parser->start_element = _start_element;
  p_parser->start_key_value = _start_key_value;
  p_parser->start_object = _start_object;
  p_parser->start_parse = _start_parse;
}

Parser::~Parser() {
  delete p_parser;
}

ReQL_Parse_t *Parser::get_parser() {
  return p_parser;
}

void Parser::add() {
  p_events.push_back(Event("add"));
}

void Parser::end_array() {
  p_events.push_back(Event("end_array"));
}

void Parser::end_element() {
  p_events.push_back(Event("end_element"));
}

void Parser::end_key_value(std::string key) {
  p_events.push_back(Event("end_key_value", key));
}

void Parser::end_object() {
  p_events.push_back(Event("end_object"));
}

void Parser::end_parse() {
  p_events.push_back(Event("end_parse"));
}

void Parser::error() {
  p_events.push_back(Event("error"));
}

void Parser::start_array() {
  p_events.push_back(Event("start_array"));
}

void Parser::start_element() {
  p_events.push_back(Event("start_element"));
}

void Parser::start_key_value() {
  p_events.push_back(Event("start_key_value"));
}

void Parser::start_object() {
  p_events.push_back(Event("start_object"));
}

void Parser::start_parse() {
  p_events.push_back(Event("start_parse"));
}

int
_add(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->add();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_end_array(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->end_array();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_end_element(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->end_element();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_end_key_value(ReQL_Parse_t *p, const char *key, size_t length) {
  try {
    reinterpret_cast<Parser *>(p->data)->end_key_value(std::string(key, length));
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_end_object(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->end_object();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_end_parse(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->end_parse();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

void
_error(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->error();
  } catch (std::exception) {
  }
}

int
_start_array(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->start_array();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_start_element(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->start_element();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_start_key_value(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->start_key_value();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_start_object(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->start_object();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}

int
_start_parse(ReQL_Parse_t *p) {
  try {
    reinterpret_cast<Parser *>(p->data)->start_parse();
  } catch (std::exception) {
    return -1;
  }
  return 0;
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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.

*/

#ifndef TEST_HPP
#define TEST_HPP

#include <boost/config.hpp>
#include <exception>
#include <sstream>

#include "libtorrent/config.hpp"

#ifdef TORRENT_BUILDING_TEST_SHARED
#define EXPORT BOOST_SYMBOL_EXPORT
#else
#define EXPORT BOOST_SYMBOL_IMPORT
#endif

// the unit tests need access to these.
// they are built into the unit test library as well.
// not exported from libtorrent itself
extern "C"
{
	int EXPORT ed25519_create_seed(unsigned char *seed);
	void EXPORT ed25519_create_keypair(unsigned char *public_key, unsigned char *private_key, const unsigned char *seed);
	void EXPORT ed25519_sign(unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *public_key, const unsigned char *private_key);
	int EXPORT ed25519_verify(const unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *private_key);
	void EXPORT ed25519_add_scalar(unsigned char *public_key, unsigned char *private_key, const unsigned char *scalar);
	void EXPORT ed25519_key_exchange(unsigned char *shared_secret, const unsigned char *public_key, const unsigned char *private_key);
}

void EXPORT report_failure(char const* err, char const* file, int line);

#if defined(_MSC_VER)
#define COUNTER_GUARD(x)
#else
#define COUNTER_GUARD(type) \
    struct BOOST_PP_CAT(type, _counter_guard) \
    { \
        ~BOOST_PP_CAT(type, _counter_guard()) \
        { \
            TEST_CHECK(counted_type<type>::count == 0); \
        } \
    } BOOST_PP_CAT(type, _guard)
#endif

#define TEST_REPORT_AUX(x, line, file) \
	report_failure(x, line, file)

#ifdef BOOST_NO_EXCEPTIONS
#define TEST_CHECK(x) \
	if (!(x)) \
		TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__);
#define TEST_EQUAL(x, y) \
	if (x != y) { \
		std::stringstream s__; \
		s__ << "TEST_EQUAL_ERROR:\n" #x ": " << x << "\nexpected: " << y << std::endl; \
		TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \
	}
#else
#define TEST_CHECK(x) \
	try \
	{ \
		if (!(x)) \
			TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__); \
	} \
	catch (std::exception& e) \
	{ \
		TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}

#define TEST_EQUAL(x, y) \
	try { \
		if (x != y) { \
			std::stringstream s__; \
			s__ << "TEST_EQUAL_ERROR: " #x ": " << x << " expected: " << y << std::endl; \
			TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \
		} \
	} \
	catch (std::exception& e) \
	{ \
		TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}
#endif

#define TEST_ERROR(x) \
	TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__)

#define TEST_NOTHROW(x) \
	try \
	{ \
		x; \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}

#endif // TEST_HPP

<commit_msg>one more attempt at fixing windows linking of test<commit_after>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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.

*/

#ifndef TEST_HPP
#define TEST_HPP

#include <boost/config.hpp>
#include <exception>
#include <sstream>

#include "libtorrent/config.hpp"

#ifdef TORRENT_BUILDING_TEST_SHARED
#define EXPORT BOOST_SYMBOL_EXPORT
#else
#define EXPORT BOOST_SYMBOL_IMPORT
#endif

// the unit tests need access to these.
// they are built into the unit test library as well.
// not exported from libtorrent itself
extern "C"
{
	int EXPORT ed25519_create_seed(unsigned char *seed);
	void EXPORT ed25519_create_keypair(unsigned char *public_key, unsigned char *private_key, const unsigned char *seed);
	void EXPORT ed25519_sign(unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *public_key, const unsigned char *private_key);
	int EXPORT ed25519_verify(const unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *private_key);
	void EXPORT ed25519_add_scalar(unsigned char *public_key, unsigned char *private_key, const unsigned char *scalar);
	void EXPORT ed25519_key_exchange(unsigned char *shared_secret, const unsigned char *public_key, const unsigned char *private_key);
}

void EXPORT report_failure(char const* err, char const* file, int line);
int EXPORT print_failures();

#if defined(_MSC_VER)
#define COUNTER_GUARD(x)
#else
#define COUNTER_GUARD(type) \
    struct BOOST_PP_CAT(type, _counter_guard) \
    { \
        ~BOOST_PP_CAT(type, _counter_guard()) \
        { \
            TEST_CHECK(counted_type<type>::count == 0); \
        } \
    } BOOST_PP_CAT(type, _guard)
#endif

#define TEST_REPORT_AUX(x, line, file) \
	report_failure(x, line, file)

#ifdef BOOST_NO_EXCEPTIONS
#define TEST_CHECK(x) \
	if (!(x)) \
		TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__);
#define TEST_EQUAL(x, y) \
	if (x != y) { \
		std::stringstream s__; \
		s__ << "TEST_EQUAL_ERROR:\n" #x ": " << x << "\nexpected: " << y << std::endl; \
		TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \
	}
#else
#define TEST_CHECK(x) \
	try \
	{ \
		if (!(x)) \
			TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__); \
	} \
	catch (std::exception& e) \
	{ \
		TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}

#define TEST_EQUAL(x, y) \
	try { \
		if (x != y) { \
			std::stringstream s__; \
			s__ << "TEST_EQUAL_ERROR: " #x ": " << x << " expected: " << y << std::endl; \
			TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \
		} \
	} \
	catch (std::exception& e) \
	{ \
		TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}
#endif

#define TEST_ERROR(x) \
	TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__)

#define TEST_NOTHROW(x) \
	try \
	{ \
		x; \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}

#endif // TEST_HPP

<|endoftext|>


<commit_before>#include <iostream>
#include <cstdint>
#include <random>
#include <chrono>
#include <vector>
#include <boost/dynamic_bitset.hpp>
#include <bitset>
#include <numeric>

/**
 * Lessons learned so far:
 * - SIMD registers are used as soon as we compile with -03
 * - If we want to get the real speed up (and use all SIMD registers by unfolding both loops,
 *   we have to know both, input-size and number of comparisons, at compile time.
 * - Otherwise, only some of the SIMD registers are used, and speedup is 0, compared to
 *   code optimized with 02.
 * - Example compile command: g++ -std=c++11 -march=native -O3 simd.cpp -o simd
 * - Command for getting assembly code: g++ -std=c++11 -march=native -O3 -S simd.cpp
 */

typedef std::mt19937 Engine;
typedef std::uniform_int_distribution<unsigned> Intdistr;

template <typename T, typename U>
void smaller (const T *input, U outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) {

    for (unsigned i = 0; i < array_size; ++i)
    {
        for (unsigned m = 0; m < comparisons; ++m) {
            outputs[m*array_size+i] = (float) (input[i] < comparison_values[m]);
        }
    }
}

template <typename T>
void pretty_print (T *arr, unsigned size, std::string s = "Pretty Print") {
    std::cout << s << ":" << std::endl;
    for (auto r = arr; r < arr+size; ++r ) {
        std::cout << *r << std::endl;
    }
}

template <typename T>
void compute_stats(const std::vector<T> stats, double &mean, double &stdev) {
    double sum = std::accumulate(stats.begin(), stats.end(), 0.0);
    mean = sum / stats.size();

    std::vector<double> diff(stats.size());
    std::transform(stats.begin(), stats.end(), diff.begin(),
                   std::bind2nd(std::minus<double>(), mean));
    double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
    stdev = std::sqrt(sq_sum / stats.size());
}

template <typename T>
void fill (T *arr, unsigned size) {
    Engine engine (0);
    Intdistr distr (0, 100000);
    for (auto r = arr; r < arr+size; ++r ) {
        *r = distr(engine);
    }
}

int main (int argc, char *argv[]) {
    //**** PARAMS ****/
    typedef unsigned TestType;
    static constexpr unsigned repetitions = 10000;

    constexpr unsigned input_size = 2000000;
    constexpr unsigned comparisons = 17;    // 17 seems to be a magic number...

//    if (argc != 3)
//    {
//        std::cout << "Usage: ./simd <input-size> <comparisons>" << std::endl;
//        return -1;
//    }
//    unsigned long input_size = std::stoi(argv[1]);
//    unsigned comparisons = std::stoi(argv[2]);

    std::cout << "input size: " << input_size << std::endl;
    std::cout << "comparisons: " << comparisons<< std::endl;

    //**** INPUT ****/
    TestType test_input [input_size];
    fill(test_input, input_size);
//    pretty_print(test_input, input_size, "Input");

    TestType comparison_values [comparisons];
    for (unsigned c = 0; c < comparisons; ++c) {
        comparison_values[c] = test_input[c];
    }
//    pretty_print(comparison_values, comparisons, "Comparison values");

    //**** COMPUTE ****/
    std::vector<unsigned long> stats (repetitions);
//    bool results [comparisons * input_size];
    std::bitset<comparisons*input_size> results;
//    std::vector<bool> results (comparisons * input_size);
//    boost::dynamic_bitset<> results(comparisons * input_size);

    for (unsigned i = 0; i < repetitions; ++i) {
        auto start = std::chrono::high_resolution_clock::now();
        smaller(test_input, results, comparison_values, input_size, comparisons);
        auto end = std::chrono::high_resolution_clock::now();
        stats [i] =
            std::chrono::duration_cast<std::chrono::microseconds>(end-start).count();
    }

    //**** REPORT ****/
    double mean, stdev;
    compute_stats(stats, mean, stdev);
    std::cout
//              << "Avg Time [microsecs]: "
              << mean
              << "\t"
//              << "(+/- "
              << stdev
//              << ")"
              << std::endl;
//    pretty_print(stats.data(), repetitions, "Stats");

//    for (unsigned c = 0; c < comparisons; ++c) {
//        pretty_print(&results[c*input_size], input_size, "Result");
//    }

    return 0;
}
<commit_msg>templated comparisons seem to work fine<commit_after>#include <iostream>
#include <cstdint>
#include <random>
#include <chrono>
#include <vector>
#include <boost/dynamic_bitset.hpp>
#include <bitset>
#include <numeric>
#include <functional>

/**
 * Lessons learned so far:
 * - SIMD registers are used as soon as we compile with -03
 * - If we want to get the real speed up (and use all SIMD registers by unfolding both loops,
 *   we have to know both, input-size and number of comparisons, at compile time.
 * - Otherwise, only some of the SIMD registers are used, and speedup is 0, compared to
 *   code optimized with 02.
 * - Example compile command: g++ -std=c++11 -march=native -O3 simd.cpp -o simd
 * - Command for getting assembly code: g++ -std=c++11 -march=native -O3 -S simd.cpp
 * - Function pointers (array of std::function) are very slow. On the other hand, templated functions seem promissing :-)
 */

typedef std::mt19937 Engine;
typedef std::uniform_int_distribution<unsigned> Intdistr;

/**
 * takes a bunch of comparison values and an input array and compares each array value
 * with each comparison value (with smaller), outputting an array of booleans
 */
template <typename T, typename U>
void smaller (const T *input, U &outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) {
    for (unsigned i = 0; i < array_size; ++i)
    {
        for (unsigned m = 0; m < comparisons; ++m) {
            outputs[m*array_size+i] = (input[i] < comparison_values[m]);
        }
    }
}

/**
 * takes a bunch of comparison values and an input array and compares each array value
 * with each comparison value (alternating smaller and larger), outputting an array of booleans
 */
template <typename T, typename U>
void smaller_greater (const T *input, U &outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) {
    for (unsigned i = 0; i < array_size; ++i)
    {
        for (unsigned m = 0; m < comparisons; m+=2) {
            outputs[m*array_size+i] = (input[i] < comparison_values[m]);
            outputs[(m+1)*array_size+i] = (input[i] > comparison_values[m+1]);
        }
    }
}

template <typename T, typename U>
void general_compare (const T *input, U &outputs, const T *comparison_values,
                      const unsigned array_size, const unsigned comparisons,
                      std::function<bool(T,T)>* comparators) {
    for (unsigned i = 0; i < array_size; ++i)
    {
        for (unsigned m = 0; m < comparisons; ++m) {
            outputs[m*array_size+i] = comparators[m](input[i],comparison_values[m]);
        }
    }
}

template <typename T, typename U, typename Compare>
void templated_compare (const T *input, U &outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) {
    Compare comp;
    for (unsigned i = 0; i < array_size; ++i)
    {
        for (unsigned m = 0; m < comparisons; ++m) {
            outputs[m*array_size+i] = comp (input[i],comparison_values[m]);
        }
    }
}

template <typename T>
void pretty_print (T arr, unsigned size, std::string s = "Pretty Print", unsigned index = 0) {
//    std::cout << s << ":" << std::endl;
//    for (unsigned i = 0; i < size; ++i) {
//        std::cout << arr[index*size + i] << std::endl;
//    }
}

template <typename T>
void compute_stats(const std::vector<T> stats, double &mean, double &stdev) {
    double sum = std::accumulate(stats.begin(), stats.end(), 0.0);
    mean = sum / stats.size();

    std::vector<double> diff(stats.size());
    std::transform(stats.begin(), stats.end(), diff.begin(),
                   std::bind2nd(std::minus<double>(), mean));
    double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
    stdev = std::sqrt(sq_sum / stats.size());
}

template <typename T>
void fill (T *arr, unsigned size) {
    Engine engine (0);
    Intdistr distr (0, 100000);
    for (auto r = arr; r < arr+size; ++r ) {
        *r = distr(engine);
    }
}

template <typename T>
void fillRandomComparators(std::function<bool(T,T)> *comparators, unsigned size)
{
    Engine engine (0);
    Intdistr distr (0, 5);
    unsigned comp;
    for (unsigned i = 0; i < size; ++i) {
        comp = distr(engine);
        switch (comp) {
            case 0:
                comparators[i] = std::greater<T>();
                break;
            case 1:
                comparators[i] = std::greater_equal<T>();
                break;
            case 2:
                comparators[i] = std::equal_to<T>();
                break;
            case 3:
                comparators[i] = std::not_equal_to<T>();
                break;
            case 4:
                comparators[i] = std::less_equal<T>();
                break;
            case 5:
                comparators[i] = std::less<T>();
                break;
        }
//        std::cout << "Comparator: " << comp << std::endl;
    }
}

int main (int argc, char *argv[]) {
    //**** PARAMS ****/
    typedef unsigned TestType;
    static constexpr unsigned repetitions = 10000;

    constexpr unsigned input_size = 500000;
    constexpr unsigned comparisons = 1;    // 17 seems to be a magic number...

//    if (argc != 3)
//    {
//        std::cout << "Usage: ./simd <input-size> <comparisons>" << std::endl;
//        return -1;
//    }
//    unsigned long input_size = std::stoi(argv[1]);
//    unsigned comparisons = std::stoi(argv[2]);

    std::cout << "input size: " << input_size << std::endl;
    std::cout << "comparisons: " << comparisons<< std::endl;

    //**** INPUT ****/
    TestType test_input [input_size];
    fill(test_input, input_size);
    pretty_print(test_input, input_size, "Input");

    TestType comparison_values [comparisons];
    for (unsigned c = 0; c < comparisons; ++c) {
        comparison_values[c] = test_input[c];
    }
    pretty_print(comparison_values, comparisons, "Comparison values");

    std::function<bool(TestType,TestType)> comparators [comparisons];
    fillRandomComparators(comparators, comparisons);
//    std::function<bool(TestType,TestType)> comparators [] = {std::less_equal<TestType>()};

    //**** COMPUTE ****/
    std::vector<unsigned long> stats (repetitions);
//    bool results [comparisons * input_size];
    std::bitset<comparisons*input_size> results;
//    std::vector<bool> results (comparisons * input_size);
//    boost::dynamic_bitset<> results(comparisons * input_size);

    for (unsigned i = 0; i < repetitions; ++i) {
        auto start = std::chrono::high_resolution_clock::now();
//        smaller(test_input, results, comparison_values, input_size, comparisons);
//        smaller_greater(test_input, results, comparison_values, input_size, comparisons);
//        general_compare(test_input, results, comparison_values, input_size, comparisons, comparators);
        templated_compare<TestType, decltype(results), std::greater<TestType>>(test_input, results, comparison_values, input_size, comparisons);
        auto end = std::chrono::high_resolution_clock::now();
        stats [i] =
            std::chrono::duration_cast<std::chrono::microseconds>(end-start).count();
    }

    //**** REPORT ****/
    double mean, stdev;
    compute_stats(stats, mean, stdev);
    std::cout
//              << "Avg Time [microsecs]: "
              << mean
              << "\t"
//              << "(+/- "
              << stdev
//              << ")"
              << std::endl;

//    for (unsigned c = 0; c < comparisons; ++c) {
//        pretty_print(results, input_size, std::string("Result"), c);
//    }

//    std::cout << "Result: " << results << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************************
 *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program is free software; you can redistribute it and/or                    *
 *  modify it under the terms of the GNU General Public License                      *
 *  as published by the Free Software Foundation; either version 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  This program is distributed in the hope that it will be useful,                  *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *
 *  GNU General Public License for more details.                                     *
 *                                                                                *
 *  You should have received a copy of the GNU General Public License                *
 *  along with this program; if not, write to the Free Software                      *
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *
 *************************************************************************************/

#include "daemon.h"
#include "serializer.h"
#include "generator.h"
#include "device.h"

#include <QtCore/QTimer>
#include <QtCore/QDebug>

#include <kdemacros.h>
#include <kaction.h>
#include <KLocalizedString>
#include <KActionCollection>
#include <KPluginFactory>

#include <kscreen/config.h>
#include <kscreen/configmonitor.h>

K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();)
K_EXPORT_PLUGIN(KScreenDaemonFactory("kscreen", "kscreen"))

KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& )
 : KDEDModule(parent)
 , m_iteration(0)
 , m_monitoredConfig(0)
 , m_pendingSave(false)
 , m_monitoring(false)
 , m_timer(new QTimer())
{
    setenv("KSCREEN_BACKEND", "XRandR", 1);
    KActionCollection *coll = new KActionCollection(this);
    KAction* action = coll->addAction("display");
    action->setText(i18n("Switch Display" ));
    action->setGlobalShortcut(KShortcut(Qt::Key_Display));

    connect(Device::self(), SIGNAL(lidIsClosedChanged(bool,bool)), SLOT(lidClosedChanged()));

    m_timer->setInterval(300);
    m_timer->setSingleShot(true);
    connect(m_timer, SIGNAL(timeout()), SLOT(applyGenericConfig()));
    connect(action, SIGNAL(triggered(bool)), SLOT(displayButton()));
    connect(Generator::self(), SIGNAL(ready()), SLOT(init()));
}

KScreenDaemon::~KScreenDaemon()
{
    Generator::destroy();
    Device::destroy();
}

void KScreenDaemon::init()
{
    applyConfig();
}

void KScreenDaemon::applyConfig()
{
    qDebug() << "Applying config";
    if (Serializer::configExists()) {
        applyKnownConfig();
        return;
    }

    applyIdealConfig();
}

void KScreenDaemon::applyKnownConfig()
{
    setMonitorForChanges(false);
    KScreen::Config::setConfig(Serializer::config(Serializer::currentId()));
    setMonitorForChanges(true);
}

void KScreenDaemon::applyIdealConfig()
{
    setMonitorForChanges(true);
    KScreen::Config::setConfig(Generator::self()->idealConfig());
}

void KScreenDaemon::configChanged()
{
    qDebug() << "Change detected";
    if (m_pendingSave) {
        return;
    }

    qDebug() << "Scheduling screen save";
    m_pendingSave = true;
    QMetaObject::invokeMethod(this, "saveCurrentConfig", Qt::QueuedConnection);
}

void KScreenDaemon::saveCurrentConfig()
{
    qDebug() << "Saving current config";
    m_pendingSave = false;
    Serializer::saveConfig(KScreen::Config::current());
}

void KScreenDaemon::displayButton()
{
    qDebug() << "displayBtn triggered";
    if (m_timer->isActive()) {
        qDebug() << "Too fast cowboy";
        return;
    }

    m_timer->start();
}

void KScreenDaemon::applyGenericConfig()
{
    if (m_iteration == 5) {
        m_iteration = 0;
    }

    m_iteration++;
    qDebug() << "displayButton: " << m_iteration;
    KScreen::Config::setConfig(Generator::self()->displaySwitch(m_iteration));
}

void KScreenDaemon::lidClosedChanged()
{
    applyIdealConfig();
}

void KScreenDaemon::setMonitorForChanges(bool enabled)
{
    if (m_monitoring == enabled) {
        return;
    }
    if (!m_monitoredConfig) {
        m_monitoredConfig = KScreen::Config::current();
        KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig);
    }

    m_monitoring = enabled;

    KScreen::OutputList outputs = m_monitoredConfig->outputs();
    Q_FOREACH(KScreen::Output* output, outputs) {
        if (m_monitoring) {
            enableMonitor(output);
        } else {
            disableMonitor(output);
        }
    }
}

void KScreenDaemon::enableMonitor(KScreen::Output* output)
{
    connect(output, SIGNAL(isConnectedChanged()), SLOT(applyConfig()));

    connect(output, SIGNAL(currentModeChanged()), SLOT(configChanged()));
    connect(output, SIGNAL(isEnabledChanged()), SLOT(configChanged()));
    connect(output, SIGNAL(isPrimaryChanged()), SLOT(configChanged()));
    connect(output, SIGNAL(outputChanged()), SLOT(configChanged()));
    connect(output, SIGNAL(clonesChanged()), SLOT(configChanged()));
    connect(output, SIGNAL(posChanged()), SLOT(configChanged()));
    connect(output, SIGNAL(rotationChanged()), SLOT(configChanged()));
}

void KScreenDaemon::disableMonitor(KScreen::Output* output)
{
    output->disconnect();
}<commit_msg>Also monitor for changes when display switch is used<commit_after>/*************************************************************************************
 *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program is free software; you can redistribute it and/or                    *
 *  modify it under the terms of the GNU General Public License                      *
 *  as published by the Free Software Foundation; either version 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  This program is distributed in the hope that it will be useful,                  *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *
 *  GNU General Public License for more details.                                     *
 *                                                                                *
 *  You should have received a copy of the GNU General Public License                *
 *  along with this program; if not, write to the Free Software                      *
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *
 *************************************************************************************/

#include "daemon.h"
#include "serializer.h"
#include "generator.h"
#include "device.h"

#include <QtCore/QTimer>
#include <QtCore/QDebug>

#include <kdemacros.h>
#include <kaction.h>
#include <KLocalizedString>
#include <KActionCollection>
#include <KPluginFactory>

#include <kscreen/config.h>
#include <kscreen/configmonitor.h>

K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();)
K_EXPORT_PLUGIN(KScreenDaemonFactory("kscreen", "kscreen"))

KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& )
 : KDEDModule(parent)
 , m_iteration(0)
 , m_monitoredConfig(0)
 , m_pendingSave(false)
 , m_monitoring(false)
 , m_timer(new QTimer())
{
    setenv("KSCREEN_BACKEND", "XRandR", 1);
    KActionCollection *coll = new KActionCollection(this);
    KAction* action = coll->addAction("display");
    action->setText(i18n("Switch Display" ));
    action->setGlobalShortcut(KShortcut(Qt::Key_Display));

    connect(Device::self(), SIGNAL(lidIsClosedChanged(bool,bool)), SLOT(lidClosedChanged()));

    m_timer->setInterval(300);
    m_timer->setSingleShot(true);
    connect(m_timer, SIGNAL(timeout()), SLOT(applyGenericConfig()));
    connect(action, SIGNAL(triggered(bool)), SLOT(displayButton()));
    connect(Generator::self(), SIGNAL(ready()), SLOT(init()));
}

KScreenDaemon::~KScreenDaemon()
{
    Generator::destroy();
    Device::destroy();
}

void KScreenDaemon::init()
{
    applyConfig();
}

void KScreenDaemon::applyConfig()
{
    qDebug() << "Applying config";
    if (Serializer::configExists()) {
        applyKnownConfig();
        return;
    }

    applyIdealConfig();
}

void KScreenDaemon::applyKnownConfig()
{
    setMonitorForChanges(false);
    KScreen::Config::setConfig(Serializer::config(Serializer::currentId()));
    setMonitorForChanges(true);
}

void KScreenDaemon::applyIdealConfig()
{
    setMonitorForChanges(true);
    KScreen::Config::setConfig(Generator::self()->idealConfig());
}

void KScreenDaemon::configChanged()
{
    qDebug() << "Change detected";
    if (m_pendingSave) {
        return;
    }

    qDebug() << "Scheduling screen save";
    m_pendingSave = true;
    QMetaObject::invokeMethod(this, "saveCurrentConfig", Qt::QueuedConnection);
}

void KScreenDaemon::saveCurrentConfig()
{
    qDebug() << "Saving current config";
    m_pendingSave = false;
    Serializer::saveConfig(KScreen::Config::current());
}

void KScreenDaemon::displayButton()
{
    qDebug() << "displayBtn triggered";
    if (m_timer->isActive()) {
        qDebug() << "Too fast cowboy";
        return;
    }

    m_timer->start();
}

void KScreenDaemon::applyGenericConfig()
{
    if (m_iteration == 5) {
        m_iteration = 0;
    }

    setMonitorForChanges(true);
    m_iteration++;
    qDebug() << "displayButton: " << m_iteration;
    KScreen::Config::setConfig(Generator::self()->displaySwitch(m_iteration));
}

void KScreenDaemon::lidClosedChanged()
{
    applyIdealConfig();
}

void KScreenDaemon::setMonitorForChanges(bool enabled)
{
    if (m_monitoring == enabled) {
        return;
    }
    if (!m_monitoredConfig) {
        m_monitoredConfig = KScreen::Config::current();
        KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig);
    }

    m_monitoring = enabled;

    KScreen::OutputList outputs = m_monitoredConfig->outputs();
    Q_FOREACH(KScreen::Output* output, outputs) {
        if (m_monitoring) {
            enableMonitor(output);
        } else {
            disableMonitor(output);
        }
    }
}

void KScreenDaemon::enableMonitor(KScreen::Output* output)
{
    connect(output, SIGNAL(isConnectedChanged()), SLOT(applyConfig()));

    connect(output, SIGNAL(currentModeChanged()), SLOT(configChanged()));
    connect(output, SIGNAL(isEnabledChanged()), SLOT(configChanged()));
    connect(output, SIGNAL(isPrimaryChanged()), SLOT(configChanged()));
    connect(output, SIGNAL(outputChanged()), SLOT(configChanged()));
    connect(output, SIGNAL(clonesChanged()), SLOT(configChanged()));
    connect(output, SIGNAL(posChanged()), SLOT(configChanged()));
    connect(output, SIGNAL(rotationChanged()), SLOT(configChanged()));
}

void KScreenDaemon::disableMonitor(KScreen::Output* output)
{
    output->disconnect();
}<|endoftext|>


<commit_before>
#include "stdafx.h"

#include "gtest\gtest.h"
#include "kbase\auto_reset.h"

#include <string>
#include <vector>

using namespace kbase;

namespace {

std::vector<std::string> origin {"hello", "world", "kc"};

}   // namespace

TEST(AutoResetTest, AutoReset)
{
    std::vector<std::string> v = origin;
    {
        AutoReset<decltype(v)> value_guard(&v);
        v.pop_back();
        v.push_back("this is a test");
        EXPECT_NE(origin, v);
    }

    EXPECT_EQ(origin, v);
}<commit_msg>unittest: update auto reset's unittest<commit_after>
#include "stdafx.h"

#include "gtest\gtest.h"
#include "kbase\auto_reset.h"

#include <string>
#include <vector>

namespace {

std::vector<std::string> value {"hello", "world", "kc"};

}   // namespace

TEST(AutoResetTest, AutoReset)
{
    auto vec = value;
    {
        kbase::AutoReset<decltype(vec)> value_guard(&vec);
        vec.pop_back();
        vec.push_back("this is a test");
        EXPECT_NE(value, vec);
    }

    EXPECT_EQ(value, vec);
}<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "create_blueprint_visitor_helper.h"
#include "leaf_blueprints.h"
#include "dot_product_blueprint.h"
#include "get_weight_from_node.h"
#include "wand/parallel_weak_and_blueprint.h"
#include "simple_phrase_blueprint.h"
#include "weighted_set_term_blueprint.h"
#include "split_float.h"

namespace search::queryeval {

CreateBlueprintVisitorHelper::CreateBlueprintVisitorHelper(Searchable &searchable, const FieldSpec &field, const IRequestContext & requestContext)
    : _requestContext(requestContext),
      _searchable(searchable),
      _field(field),
      _result()
{}

CreateBlueprintVisitorHelper::~CreateBlueprintVisitorHelper() = default;

Blueprint::UP
CreateBlueprintVisitorHelper::getResult()
{
    return _result
        ? std::move(_result)
        : std::make_unique<EmptyBlueprint>(_field);
}

void
CreateBlueprintVisitorHelper::visitPhrase(query::Phrase &n) {
    auto phrase = std::make_unique<SimplePhraseBlueprint>(_field, _requestContext, n.is_expensive());
    for (const query::Node * child : n.getChildren()) {
        FieldSpecList fields;
        fields.add(phrase->getNextChildField(_field));
        phrase->addTerm(_searchable.createBlueprint(_requestContext, fields, *child));
    }
    setResult(std::move(phrase));
}

void
CreateBlueprintVisitorHelper::handleNumberTermAsText(query::NumberTerm &n)
{
    vespalib::string termStr = termAsString(n);
    queryeval::SplitFloat splitter(termStr);
    if (splitter.parts() > 1) {
        query::SimplePhrase phraseNode(n.getView(), n.getId(), n.getWeight());
        phraseNode.setStateFrom(n);
        for (size_t i = 0; i < splitter.parts(); ++i) {
            phraseNode.append(std::make_unique<query::SimpleStringTerm>(splitter.getPart(i), "", 0, query::Weight(0)));
        }
        visitPhrase(phraseNode);
    } else {
        if (splitter.parts() == 1) {
            termStr = splitter.getPart(0);
        }
        query::SimpleStringTerm stringNode(termStr, n.getView(), n.getId(), n.getWeight());
        stringNode.setStateFrom(n);
        visit(stringNode);
    }
}

template <typename WS, typename NODE>
void
CreateBlueprintVisitorHelper::createWeightedSet(std::unique_ptr<WS> bp, NODE &n) {
    FieldSpecList fields;
    for (size_t i = 0; i < n.getNumTerms(); ++i) {
        fields.clear();
        fields.add(bp->getNextChildField(_field));
        const auto & term = n.getAsString(i);
        query::SimpleStringTerm node(term.first, n.getView(), 0, term.second); // TODO Temporary
        bp->addTerm(_searchable.createBlueprint(_requestContext, fields, node), term.second.percent());
    }
    setResult(std::move(bp));
}
void
CreateBlueprintVisitorHelper::visitWeightedSetTerm(query::WeightedSetTerm &n) {
    createWeightedSet(std::make_unique<WeightedSetTermBlueprint>(_field), n);
}
void
CreateBlueprintVisitorHelper::visitDotProduct(query::DotProduct &n) {
    createWeightedSet(std::make_unique<DotProductBlueprint>(_field), n);
}
void
CreateBlueprintVisitorHelper::visitWandTerm(query::WandTerm &n) {
    createWeightedSet(std::make_unique<ParallelWeakAndBlueprint>(_field, n.getTargetNumHits(),
                                                                 n.getScoreThreshold(), n.getThresholdBoostFactor()),
                      n);
}

}
<commit_msg>Keep a local instance instead of a const reference.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "create_blueprint_visitor_helper.h"
#include "leaf_blueprints.h"
#include "dot_product_blueprint.h"
#include "get_weight_from_node.h"
#include "wand/parallel_weak_and_blueprint.h"
#include "simple_phrase_blueprint.h"
#include "weighted_set_term_blueprint.h"
#include "split_float.h"

namespace search::queryeval {

CreateBlueprintVisitorHelper::CreateBlueprintVisitorHelper(Searchable &searchable, const FieldSpec &field, const IRequestContext & requestContext)
    : _requestContext(requestContext),
      _searchable(searchable),
      _field(field),
      _result()
{}

CreateBlueprintVisitorHelper::~CreateBlueprintVisitorHelper() = default;

Blueprint::UP
CreateBlueprintVisitorHelper::getResult()
{
    return _result
        ? std::move(_result)
        : std::make_unique<EmptyBlueprint>(_field);
}

void
CreateBlueprintVisitorHelper::visitPhrase(query::Phrase &n) {
    auto phrase = std::make_unique<SimplePhraseBlueprint>(_field, _requestContext, n.is_expensive());
    for (const query::Node * child : n.getChildren()) {
        FieldSpecList fields;
        fields.add(phrase->getNextChildField(_field));
        phrase->addTerm(_searchable.createBlueprint(_requestContext, fields, *child));
    }
    setResult(std::move(phrase));
}

void
CreateBlueprintVisitorHelper::handleNumberTermAsText(query::NumberTerm &n)
{
    vespalib::string termStr = termAsString(n);
    queryeval::SplitFloat splitter(termStr);
    if (splitter.parts() > 1) {
        query::SimplePhrase phraseNode(n.getView(), n.getId(), n.getWeight());
        phraseNode.setStateFrom(n);
        for (size_t i = 0; i < splitter.parts(); ++i) {
            phraseNode.append(std::make_unique<query::SimpleStringTerm>(splitter.getPart(i), "", 0, query::Weight(0)));
        }
        visitPhrase(phraseNode);
    } else {
        if (splitter.parts() == 1) {
            termStr = splitter.getPart(0);
        }
        query::SimpleStringTerm stringNode(termStr, n.getView(), n.getId(), n.getWeight());
        stringNode.setStateFrom(n);
        visit(stringNode);
    }
}

template <typename WS, typename NODE>
void
CreateBlueprintVisitorHelper::createWeightedSet(std::unique_ptr<WS> bp, NODE &n) {
    FieldSpecList fields;
    for (size_t i = 0; i < n.getNumTerms(); ++i) {
        fields.clear();
        fields.add(bp->getNextChildField(_field));
        auto term = n.getAsString(i);
        query::SimpleStringTerm node(term.first, n.getView(), 0, term.second); // TODO Temporary
        bp->addTerm(_searchable.createBlueprint(_requestContext, fields, node), term.second.percent());
    }
    setResult(std::move(bp));
}
void
CreateBlueprintVisitorHelper::visitWeightedSetTerm(query::WeightedSetTerm &n) {
    createWeightedSet(std::make_unique<WeightedSetTermBlueprint>(_field), n);
}
void
CreateBlueprintVisitorHelper::visitDotProduct(query::DotProduct &n) {
    createWeightedSet(std::make_unique<DotProductBlueprint>(_field), n);
}
void
CreateBlueprintVisitorHelper::visitWandTerm(query::WandTerm &n) {
    createWeightedSet(std::make_unique<ParallelWeakAndBlueprint>(_field, n.getTargetNumHits(),
                                                                 n.getScoreThreshold(), n.getThresholdBoostFactor()),
                      n);
}

}
<|endoftext|>


<commit_before><commit_msg>Prevent client crash for starting constructions of other players.<commit_after><|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/canbus/vehicle/lincoln/protocol/brake_60.h"

#include "gtest/gtest.h"

namespace apollo {
namespace canbus {
namespace lincoln {

class Brake60Test : public ::testing::Test {
 public:
  virtual void SetUp() {}
};

TEST_F(Brake60Test, simple) {
  Brake60 brake;
  EXPECT_EQ(brake.GetPeriod(), 20 * 1000);
  uint8_t data = 0x64;
  brake.UpdateData(&data);
}

}  // namespace lincoln
}  // namespace apollo
}  // namespace canbus
<commit_msg>fixed brake60_test<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/canbus/vehicle/lincoln/protocol/brake_60.h"

#include "gtest/gtest.h"

#include <bitset>
#include <iostream>

namespace apollo {
namespace canbus {
namespace lincoln {

class Brake60Test : public ::testing::Test {
 public:
  virtual void SetUp() {}
};

TEST_F(Brake60Test, simple) {
  Brake60 brake;
  EXPECT_EQ(brake.GetPeriod(), 20 * 1000);
  uint8_t data[8] = {0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68};
  brake.UpdateData(data);
  /* output should be:
          00000000
          00000000
          01100010
          01100100
          01100101
          01100110
          01100111
          00000000
  */
  EXPECT_EQ(data[0], 0b00000000);
  EXPECT_EQ(data[1], 0b00000000);
  EXPECT_EQ(data[2], 0b01100010);
  EXPECT_EQ(data[3], 0b01100100);
  EXPECT_EQ(data[4], 0b01100101);
  EXPECT_EQ(data[5], 0b01100110);
  EXPECT_EQ(data[6], 0b01100111);
  EXPECT_EQ(data[7], 0b00000000);
}

}  // namespace lincoln
}  // namespace apollo
}  // namespace canbus
<|endoftext|>


<commit_before>#include "3DScene.hpp"

namespace Slic3r {

// caller is responsible for supplying NO lines with zero length
void
_3DScene::_extrusionentity_to_verts_do(const Lines &lines, const std::vector<double> &widths,
        const std::vector<double> &heights, bool closed, double top_z, const Point &copy,
        GLVertexArray* qverts, GLVertexArray* tverts)
{
    /* It looks like it's faster without reserving capacity...
    // each segment has 4 quads, thus 16 vertices; + 2 caps
    qverts->reserve_more(3 * 4 * (4 * lines.size() + 2));

    // two triangles for each corner
    tverts->reserve_more(3 * 3 * 2 * (lines.size() + 1));
    */

    Line prev_line;
    Pointf prev_b1, prev_b2;
    Vectorf3 prev_xy_left_normal, prev_xy_right_normal;

    // loop once more in case of closed loops
    bool first_done = false;
    for (size_t i = 0; i <= lines.size(); ++i) {
        if (i == lines.size()) i = 0;

        const Line &line = lines.at(i);
        if (i == 0 && first_done && !closed) break;

        double len = line.length();
        double unscaled_len = unscale(len);

        double bottom_z = top_z - heights.at(i);
        double middle_z = (top_z + bottom_z) / 2;
        double dist = widths.at(i)/2;  // scaled

        Vectorf v = Vectorf::new_unscale(line.vector());
        v.scale(1/unscaled_len);

        Pointf a = Pointf::new_unscale(line.a);
        Pointf b = Pointf::new_unscale(line.b);
        Pointf a1 = a;
        Pointf a2 = a;
        a1.translate(+dist*v.y, -dist*v.x);
        a2.translate(-dist*v.y, +dist*v.x);
        Pointf b1 = b;
        Pointf b2 = b;
        b1.translate(+dist*v.y, -dist*v.x);
        b2.translate(-dist*v.y, +dist*v.x);

        // calculate new XY normals
        Vector n = line.normal();
        Vectorf3 xy_right_normal = Vectorf3::new_unscale(n.x, n.y, 0);
        xy_right_normal.scale(1/unscaled_len);
        Vectorf3 xy_left_normal = xy_right_normal;
        xy_left_normal.scale(-1);

        if (first_done) {
            // if we're making a ccw turn, draw the triangles on the right side, otherwise draw them on the left side
            double ccw = line.b.ccw(prev_line);
            if (ccw > EPSILON) {
                // top-right vertex triangle between previous line and this one
                {
                    // use the normal going to the right calculated for the previous line
                    tverts->push_norm(prev_xy_right_normal);
                    tverts->push_vert(prev_b1.x, prev_b1.y, middle_z);

                    // use the normal going to the right calculated for this line
                    tverts->push_norm(xy_right_normal);
                    tverts->push_vert(a1.x, a1.y, middle_z);

                    // normal going upwards
                    tverts->push_norm(0,0,1);
                    tverts->push_vert(a.x, a.y, top_z);
                }
                // bottom-right vertex triangle between previous line and this one
                {
                    // use the normal going to the right calculated for the previous line
                    tverts->push_norm(prev_xy_right_normal);
                    tverts->push_vert(prev_b1.x, prev_b1.y, middle_z);

                    // normal going downwards
                    tverts->push_norm(0,0,-1);
                    tverts->push_vert(a.x, a.y, bottom_z);

                    // use the normal going to the right calculated for this line
                    tverts->push_norm(xy_right_normal);
                    tverts->push_vert(a1.x, a1.y, middle_z);
                }
            } else if (ccw < -EPSILON) {
                // top-left vertex triangle between previous line and this one
                {
                    // use the normal going to the left calculated for the previous line
                    tverts->push_norm(prev_xy_left_normal);
                    tverts->push_vert(prev_b2.x, prev_b2.y, middle_z);

                    // normal going upwards
                    tverts->push_norm(0,0,1);
                    tverts->push_vert(a.x, a.y, top_z);

                    // use the normal going to the right calculated for this line
                    tverts->push_norm(xy_left_normal);
                    tverts->push_vert(a2.x, a2.y, middle_z);
                }
                // bottom-left vertex triangle between previous line and this one
                {
                    // use the normal going to the left calculated for the previous line
                    tverts->push_norm(prev_xy_left_normal);
                    tverts->push_vert(prev_b2.x, prev_b2.y, middle_z);

                    // use the normal going to the right calculated for this line
                    tverts->push_norm(xy_left_normal);
                    tverts->push_vert(a2.x, a2.y, middle_z);

                    // normal going downwards
                    tverts->push_norm(0,0,-1);
                    tverts->push_vert(a.x, a.y, bottom_z);
                }
            }
        }

        // if this was the extra iteration we were only interested in the triangles
        if (first_done && i == 0) break;

        prev_line = line;
        prev_b1 = b1;
        prev_b2 = b2;
        prev_xy_right_normal = xy_right_normal;
        prev_xy_left_normal  = xy_left_normal;

        if (!closed) {
            // terminate open paths with caps
            if (i == 0) {
                // normal pointing downwards
                qverts->push_norm(0,0,-1);
                qverts->push_vert(a.x, a.y, bottom_z);

                // normal pointing to the right
                qverts->push_norm(xy_right_normal);
                qverts->push_vert(a1.x, a1.y, middle_z);

                // normal pointing upwards
                qverts->push_norm(0,0,1);
                qverts->push_vert(a.x, a.y, top_z);

                // normal pointing to the left
                qverts->push_norm(xy_left_normal);
                qverts->push_vert(a2.x, a2.y, middle_z);
            }
            // we don't use 'else' because both cases are true if we have only one line
            if (i == lines.size()-1) {
                // normal pointing downwards
                qverts->push_norm(0,0,-1);
                qverts->push_vert(b.x, b.y, bottom_z);

                // normal pointing to the left
                qverts->push_norm(xy_left_normal);
                qverts->push_vert(b2.x, b2.y, middle_z);

                // normal pointing upwards
                qverts->push_norm(0,0,1);
                qverts->push_vert(b.x, b.y, top_z);

                // normal pointing to the right
                qverts->push_norm(xy_right_normal);
                qverts->push_vert(b1.x, b1.y, middle_z);
            }
        }

        // bottom-right face
        {
            // normal going downwards
            qverts->push_norm(0,0,-1);
            qverts->push_norm(0,0,-1);
            qverts->push_vert(a.x, a.y, bottom_z);
            qverts->push_vert(b.x, b.y, bottom_z);

            qverts->push_norm(xy_right_normal);
            qverts->push_norm(xy_right_normal);
            qverts->push_vert(b1.x, b1.y, middle_z);
            qverts->push_vert(a1.x, a1.y, middle_z);
        }

        // top-right face
        {
            qverts->push_norm(xy_right_normal);
            qverts->push_norm(xy_right_normal);
            qverts->push_vert(a1.x, a1.y, middle_z);
            qverts->push_vert(b1.x, b1.y, middle_z);

            // normal going upwards
            qverts->push_norm(0,0,1);
            qverts->push_norm(0,0,1);
            qverts->push_vert(b.x, b.y, top_z);
            qverts->push_vert(a.x, a.y, top_z);
        }

        // top-left face
        {
            qverts->push_norm(0,0,1);
            qverts->push_norm(0,0,1);
            qverts->push_vert(a.x, a.y, top_z);
            qverts->push_vert(b.x, b.y, top_z);

            qverts->push_norm(xy_left_normal);
            qverts->push_norm(xy_left_normal);
            qverts->push_vert(b2.x, b2.y, middle_z);
            qverts->push_vert(a2.x, a2.y, middle_z);
        }

        // bottom-left face
        {
            qverts->push_norm(xy_left_normal);
            qverts->push_norm(xy_left_normal);
            qverts->push_vert(a2.x, a2.y, middle_z);
            qverts->push_vert(b2.x, b2.y, middle_z);

            // normal going downwards
            qverts->push_norm(0,0,-1);
            qverts->push_norm(0,0,-1);
            qverts->push_vert(b.x, b.y, bottom_z);
            qverts->push_vert(a.x, a.y, bottom_z);
        }

        first_done = true;
    }
}

void
GLVertexArray::load_mesh(const TriangleMesh &mesh)
{
    this->reserve_more(3 * 3 * mesh.facets_count());

    for (int i = 0; i < mesh.stl.stats.number_of_facets; ++i) {
        stl_facet &facet = mesh.stl.facet_start[i];
        for (int j = 0; j <= 2; ++j) {
            this->push_norm(facet.normal.x, facet.normal.y, facet.normal.z);
            this->push_vert(facet.vertex[j].x, facet.vertex[j].y, facet.vertex[j].z);
        }
    }
}

}
<commit_msg>Bugfix: rare crash when loading 3D preview. #3636<commit_after>#include "3DScene.hpp"

namespace Slic3r {

// caller is responsible for supplying NO lines with zero length
void
_3DScene::_extrusionentity_to_verts_do(const Lines &lines, const std::vector<double> &widths,
        const std::vector<double> &heights, bool closed, double top_z, const Point &copy,
        GLVertexArray* qverts, GLVertexArray* tverts)
{
    if (lines.empty()) return;

    /* It looks like it's faster without reserving capacity...
    // each segment has 4 quads, thus 16 vertices; + 2 caps
    qverts->reserve_more(3 * 4 * (4 * lines.size() + 2));

    // two triangles for each corner
    tverts->reserve_more(3 * 3 * 2 * (lines.size() + 1));
    */

    Line prev_line;
    Pointf prev_b1, prev_b2;
    Vectorf3 prev_xy_left_normal, prev_xy_right_normal;

    // loop once more in case of closed loops
    bool first_done = false;
    for (size_t i = 0; i <= lines.size(); ++i) {
        if (i == lines.size()) i = 0;

        const Line &line = lines.at(i);
        if (i == 0 && first_done && !closed) break;

        double len = line.length();
        double unscaled_len = unscale(len);

        double bottom_z = top_z - heights.at(i);
        double middle_z = (top_z + bottom_z) / 2;
        double dist = widths.at(i)/2;  // scaled

        Vectorf v = Vectorf::new_unscale(line.vector());
        v.scale(1/unscaled_len);

        Pointf a = Pointf::new_unscale(line.a);
        Pointf b = Pointf::new_unscale(line.b);
        Pointf a1 = a;
        Pointf a2 = a;
        a1.translate(+dist*v.y, -dist*v.x);
        a2.translate(-dist*v.y, +dist*v.x);
        Pointf b1 = b;
        Pointf b2 = b;
        b1.translate(+dist*v.y, -dist*v.x);
        b2.translate(-dist*v.y, +dist*v.x);

        // calculate new XY normals
        Vector n = line.normal();
        Vectorf3 xy_right_normal = Vectorf3::new_unscale(n.x, n.y, 0);
        xy_right_normal.scale(1/unscaled_len);
        Vectorf3 xy_left_normal = xy_right_normal;
        xy_left_normal.scale(-1);

        if (first_done) {
            // if we're making a ccw turn, draw the triangles on the right side, otherwise draw them on the left side
            double ccw = line.b.ccw(prev_line);
            if (ccw > EPSILON) {
                // top-right vertex triangle between previous line and this one
                {
                    // use the normal going to the right calculated for the previous line
                    tverts->push_norm(prev_xy_right_normal);
                    tverts->push_vert(prev_b1.x, prev_b1.y, middle_z);

                    // use the normal going to the right calculated for this line
                    tverts->push_norm(xy_right_normal);
                    tverts->push_vert(a1.x, a1.y, middle_z);

                    // normal going upwards
                    tverts->push_norm(0,0,1);
                    tverts->push_vert(a.x, a.y, top_z);
                }
                // bottom-right vertex triangle between previous line and this one
                {
                    // use the normal going to the right calculated for the previous line
                    tverts->push_norm(prev_xy_right_normal);
                    tverts->push_vert(prev_b1.x, prev_b1.y, middle_z);

                    // normal going downwards
                    tverts->push_norm(0,0,-1);
                    tverts->push_vert(a.x, a.y, bottom_z);

                    // use the normal going to the right calculated for this line
                    tverts->push_norm(xy_right_normal);
                    tverts->push_vert(a1.x, a1.y, middle_z);
                }
            } else if (ccw < -EPSILON) {
                // top-left vertex triangle between previous line and this one
                {
                    // use the normal going to the left calculated for the previous line
                    tverts->push_norm(prev_xy_left_normal);
                    tverts->push_vert(prev_b2.x, prev_b2.y, middle_z);

                    // normal going upwards
                    tverts->push_norm(0,0,1);
                    tverts->push_vert(a.x, a.y, top_z);

                    // use the normal going to the right calculated for this line
                    tverts->push_norm(xy_left_normal);
                    tverts->push_vert(a2.x, a2.y, middle_z);
                }
                // bottom-left vertex triangle between previous line and this one
                {
                    // use the normal going to the left calculated for the previous line
                    tverts->push_norm(prev_xy_left_normal);
                    tverts->push_vert(prev_b2.x, prev_b2.y, middle_z);

                    // use the normal going to the right calculated for this line
                    tverts->push_norm(xy_left_normal);
                    tverts->push_vert(a2.x, a2.y, middle_z);

                    // normal going downwards
                    tverts->push_norm(0,0,-1);
                    tverts->push_vert(a.x, a.y, bottom_z);
                }
            }
        }

        // if this was the extra iteration we were only interested in the triangles
        if (first_done && i == 0) break;

        prev_line = line;
        prev_b1 = b1;
        prev_b2 = b2;
        prev_xy_right_normal = xy_right_normal;
        prev_xy_left_normal  = xy_left_normal;

        if (!closed) {
            // terminate open paths with caps
            if (i == 0) {
                // normal pointing downwards
                qverts->push_norm(0,0,-1);
                qverts->push_vert(a.x, a.y, bottom_z);

                // normal pointing to the right
                qverts->push_norm(xy_right_normal);
                qverts->push_vert(a1.x, a1.y, middle_z);

                // normal pointing upwards
                qverts->push_norm(0,0,1);
                qverts->push_vert(a.x, a.y, top_z);

                // normal pointing to the left
                qverts->push_norm(xy_left_normal);
                qverts->push_vert(a2.x, a2.y, middle_z);
            }
            // we don't use 'else' because both cases are true if we have only one line
            if (i == lines.size()-1) {
                // normal pointing downwards
                qverts->push_norm(0,0,-1);
                qverts->push_vert(b.x, b.y, bottom_z);

                // normal pointing to the left
                qverts->push_norm(xy_left_normal);
                qverts->push_vert(b2.x, b2.y, middle_z);

                // normal pointing upwards
                qverts->push_norm(0,0,1);
                qverts->push_vert(b.x, b.y, top_z);

                // normal pointing to the right
                qverts->push_norm(xy_right_normal);
                qverts->push_vert(b1.x, b1.y, middle_z);
            }
        }

        // bottom-right face
        {
            // normal going downwards
            qverts->push_norm(0,0,-1);
            qverts->push_norm(0,0,-1);
            qverts->push_vert(a.x, a.y, bottom_z);
            qverts->push_vert(b.x, b.y, bottom_z);

            qverts->push_norm(xy_right_normal);
            qverts->push_norm(xy_right_normal);
            qverts->push_vert(b1.x, b1.y, middle_z);
            qverts->push_vert(a1.x, a1.y, middle_z);
        }

        // top-right face
        {
            qverts->push_norm(xy_right_normal);
            qverts->push_norm(xy_right_normal);
            qverts->push_vert(a1.x, a1.y, middle_z);
            qverts->push_vert(b1.x, b1.y, middle_z);

            // normal going upwards
            qverts->push_norm(0,0,1);
            qverts->push_norm(0,0,1);
            qverts->push_vert(b.x, b.y, top_z);
            qverts->push_vert(a.x, a.y, top_z);
        }

        // top-left face
        {
            qverts->push_norm(0,0,1);
            qverts->push_norm(0,0,1);
            qverts->push_vert(a.x, a.y, top_z);
            qverts->push_vert(b.x, b.y, top_z);

            qverts->push_norm(xy_left_normal);
            qverts->push_norm(xy_left_normal);
            qverts->push_vert(b2.x, b2.y, middle_z);
            qverts->push_vert(a2.x, a2.y, middle_z);
        }

        // bottom-left face
        {
            qverts->push_norm(xy_left_normal);
            qverts->push_norm(xy_left_normal);
            qverts->push_vert(a2.x, a2.y, middle_z);
            qverts->push_vert(b2.x, b2.y, middle_z);

            // normal going downwards
            qverts->push_norm(0,0,-1);
            qverts->push_norm(0,0,-1);
            qverts->push_vert(b.x, b.y, bottom_z);
            qverts->push_vert(a.x, a.y, bottom_z);
        }

        first_done = true;
    }
}

void
GLVertexArray::load_mesh(const TriangleMesh &mesh)
{
    this->reserve_more(3 * 3 * mesh.facets_count());

    for (int i = 0; i < mesh.stl.stats.number_of_facets; ++i) {
        stl_facet &facet = mesh.stl.facet_start[i];
        for (int j = 0; j <= 2; ++j) {
            this->push_norm(facet.normal.x, facet.normal.y, facet.normal.z);
            this->push_vert(facet.vertex[j].x, facet.vertex[j].y, facet.vertex[j].z);
        }
    }
}

}
<|endoftext|>


<commit_before>/*
 * opencog/benchmark/BenchmarkModule.cc
 *
 * Copyright (C) 2014 Cosmo Harrigan
 * All Rights Reserved
 *
 * Written by Cosmo Harrigan
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <future>
#include <iostream>
#include <iomanip>
#include <thread>
#include <time.h>

#include <boost/range/irange.hpp>

#include <opencog/dynamics/attention/atom_types.h>
#include <opencog/server/CogServer.h>
#include <opencog/util/Logger.h>
#include <opencog/util/Config.h>
#include <opencog/util/oc_omp.h>

#include "BenchmarkModule.h"

using namespace std;
using namespace opencog;

DECLARE_MODULE(BenchmarkModule)

BenchmarkModule::BenchmarkModule(CogServer& cs) : Module(cs)
{
    logger().info("[BenchmarkModule] constructor");
    this->as = &cs.getAtomSpace();

    do_fullyConnectedTest_register();
}

void BenchmarkModule::init(void)
{
    logger().info("Initializing BenchmarkModule.");
}

void BenchmarkModule::run()
{
}

BenchmarkModule::~BenchmarkModule()
{
    logger().info("Terminating BenchmarkModule.");

    do_fullyConnectedTest_unregister();
}

int BenchmarkModule::fullyConnectedTestConcurrent(int numAtoms)
{
    // Multithreaded using GNU libstdc++ parallel mode
    // Add numAtoms ConceptNodes
    auto ir = boost::irange((size_t)0, (size_t)numAtoms);
    vector<size_t> indices(ir.begin(), ir.end());

    OMP_ALGO::for_each(indices.begin(), indices.end(), [this](int index)
    {
        as->addPrefixedNode(CONCEPT_NODE, "test_atom_");
    });

    // Retrieve all the ConceptNodes into an iterator
    HandleSeq atoms;
    as->getHandlesByType(back_inserter(atoms), CONCEPT_NODE);

    // Create a fully connected graph between them with bidirectional directed
    // edges: requires n^2 - n edges
    OMP_ALGO::for_each(atoms.begin(), atoms.end(),
    [&atoms, this](Handle handleSource)
    {
        for_each(atoms.begin(), atoms.end(),
            [&handleSource, this](Handle handleTarget)
        {
            as->addLink(ASYMMETRIC_HEBBIAN_LINK, handleSource, handleTarget);
        });
    });

    return atoms.size();
}

int BenchmarkModule::updateSTITestConcurrent()
{
    srand(time(NULL));

    HandleSeq atoms;
    as->getHandlesByType(back_inserter(atoms), ATOM, true);

    OMP_ALGO::for_each(atoms.begin(), atoms.end(),
        [this](Handle handle)
    {
        int newSTI = rand() % 1000;
        as->setSTI(handle, newSTI);
    });

    return atoms.size();
}

std::string
BenchmarkModule::do_fullyConnectedTest(Request *dummy,
                                       std::list<std::string> args)
{
    std::vector<std::string> argv{ std::begin(args), std::end(args) };

    std::string option = argv.size() > 0 ? argv[0] : "concurrent";

    int numNewNodes;
    try
    {
        numNewNodes = argv.size() > 1 ? std::stoi(argv[1]) : 500;
    }
    catch(std::invalid_argument& e)
    {
        return "Error: argument COUNT must be an integer.\n";
    }

    int numThreads;
    try
    {
        // User can specify the number of threads. Otherwise, defaults to 2
        numThreads = argv.size() > 2 ? std::stoi(argv[2]) : 2;
    }
    catch(std::invalid_argument& e)
    {
        return "Error: argument THREADS must be an integer.\n";
    }
    // Set the number of threads for OpenMP parallelization
    setting_omp(numThreads);

    const clock_t begin_time_cpu = clock();
    const time_t begin_time_wall = time(NULL);

    int numNodes;
    std::string result;

    if (option == "reset")
    {
        // Delete all ConceptNodes and their incoming sets
        HandleSeq atoms;
        as->getHandlesByType(back_inserter(atoms), CONCEPT_NODE);

        OMP_ALGO::for_each(atoms.begin(), atoms.end(),
            [this](Handle handle)
        {
            as->deleteAtom(handle, true);
        });

        return "All ConceptNodes and their incoming sets deleted.\n";
    }
    else if (option == "concurrent")
    {
        numNodes = fullyConnectedTestConcurrent(numNewNodes);
        result = "Fully connected graph of " +
                std::to_string(numNodes) +
                " total nodes including " +
                std::to_string(numNewNodes) +
                " new nodes.\n";
    }
    else if (option == "sti")
    {
        int numAtoms = updateSTITestConcurrent();
        result = std::to_string(numAtoms) +
                " atoms updated with random STI values.\n";
    }
    else
    {
        return "Error, unrecognized argument. Usage:\n"
               "  benchmark-fully-connected OPTION COUNT THREADS\n"
               "where OPTION is 'concurrent' or 'reset', COUNT is an integer "
               "number of nodes,\nand THREADS is an integer number of threads. "
               "If no arguments are specified,\ndefaults to:\n"
               "  concurrent 500 2\n";
    }

    const clock_t end_time_cpu = clock();
    const time_t end_time_wall = time(NULL);

    std::string message;
    message = result +
            "Wall clock time: " +
            std::to_string(end_time_wall - begin_time_wall) +
            " seconds\nCPU clock time: " +
            std::to_string((end_time_cpu - begin_time_cpu) / CLOCKS_PER_SEC) +
            " seconds\nNumber of threads used: " +
            std::to_string(numThreads) + "\n";
    return message;
}
<commit_msg>Update benchmark module instructions & truth value<commit_after>/*
 * opencog/benchmark/BenchmarkModule.cc
 *
 * Copyright (C) 2014 Cosmo Harrigan
 * All Rights Reserved
 *
 * Written by Cosmo Harrigan
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <future>
#include <iostream>
#include <iomanip>
#include <thread>
#include <time.h>

#include <boost/range/irange.hpp>

#include <opencog/dynamics/attention/atom_types.h>
#include <opencog/server/CogServer.h>
#include <opencog/util/Logger.h>
#include <opencog/util/Config.h>
#include <opencog/util/oc_omp.h>

#include "BenchmarkModule.h"

using namespace std;
using namespace opencog;

DECLARE_MODULE(BenchmarkModule)

BenchmarkModule::BenchmarkModule(CogServer& cs) : Module(cs)
{
    logger().info("[BenchmarkModule] constructor");
    this->as = &cs.getAtomSpace();

    do_fullyConnectedTest_register();
}

void BenchmarkModule::init(void)
{
    logger().info("Initializing BenchmarkModule.");
}

void BenchmarkModule::run()
{
}

BenchmarkModule::~BenchmarkModule()
{
    logger().info("Terminating BenchmarkModule.");

    do_fullyConnectedTest_unregister();
}

int BenchmarkModule::fullyConnectedTestConcurrent(int numAtoms)
{
    // Multithreaded using GNU libstdc++ parallel mode
    // Add numAtoms ConceptNodes
    auto ir = boost::irange((size_t)0, (size_t)numAtoms);
    vector<size_t> indices(ir.begin(), ir.end());

    OMP_ALGO::for_each(indices.begin(), indices.end(), [this](int index)
    {
        as->addPrefixedNode(CONCEPT_NODE, "test_atom_");
    });

    // Retrieve all the ConceptNodes into an iterator
    HandleSeq atoms;
    as->getHandlesByType(back_inserter(atoms), CONCEPT_NODE);

    // Create a fully connected graph between them with bidirectional directed
    // edges: requires n^2 - n edges
    OMP_ALGO::for_each(atoms.begin(), atoms.end(),
    [&atoms, this](Handle handleSource)
    {
        for_each(atoms.begin(), atoms.end(),
            [&handleSource, this](Handle handleTarget)
        {
            as->addLink(ASYMMETRIC_HEBBIAN_LINK, handleSource, handleTarget,
                        SimpleTruthValue::createTV(0, 1));
        });
    });

    return atoms.size();
}

int BenchmarkModule::updateSTITestConcurrent()
{
    srand(time(NULL));

    HandleSeq atoms;
    as->getHandlesByType(back_inserter(atoms), ATOM, true);

    OMP_ALGO::for_each(atoms.begin(), atoms.end(),
        [this](Handle handle)
    {
        int newSTI = rand() % 1000;
        as->setSTI(handle, newSTI);
    });

    return atoms.size();
}

std::string
BenchmarkModule::do_fullyConnectedTest(Request *dummy,
                                       std::list<std::string> args)
{
    std::vector<std::string> argv{ std::begin(args), std::end(args) };

    std::string option = argv.size() > 0 ? argv[0] : "concurrent";

    int numNewNodes;
    try
    {
        numNewNodes = argv.size() > 1 ? std::stoi(argv[1]) : 500;
    }
    catch(std::invalid_argument& e)
    {
        return "Error: argument COUNT must be an integer.\n";
    }

    int numThreads;
    try
    {
        // User can specify the number of threads. Otherwise, defaults to 2
        numThreads = argv.size() > 2 ? std::stoi(argv[2]) : 2;
    }
    catch(std::invalid_argument& e)
    {
        return "Error: argument THREADS must be an integer.\n";
    }
    // Set the number of threads for OpenMP parallelization
    setting_omp(numThreads);

    const clock_t begin_time_cpu = clock();
    const time_t begin_time_wall = time(NULL);

    int numNodes;
    std::string result;

    if (option == "reset")
    {
        // Delete all ConceptNodes and their incoming sets
        HandleSeq atoms;
        as->getHandlesByType(back_inserter(atoms), CONCEPT_NODE);

        OMP_ALGO::for_each(atoms.begin(), atoms.end(),
            [this](Handle handle)
        {
            as->deleteAtom(handle, true);
        });

        return "All ConceptNodes and their incoming sets deleted.\n";
    }
    else if (option == "concurrent")
    {
        numNodes = fullyConnectedTestConcurrent(numNewNodes);
        result = "Fully connected graph of " +
                std::to_string(numNodes) +
                " total nodes including " +
                std::to_string(numNewNodes) +
                " new nodes.\n";
    }
    else if (option == "sti")
    {
        int numAtoms = updateSTITestConcurrent();
        result = std::to_string(numAtoms) +
                " atoms updated with random STI values.\n";
    }
    else
    {
        return "Error, unrecognized argument. Usage:\n"
               "  benchmark-fully-connected OPTION COUNT THREADS\n"
               "where OPTION is 'concurrent', 'reset' or 'sti', COUNT is an "
               "integer number of nodes,\nand THREADS is an integer number of "
               "threads. If no arguments are specified,\ndefaults to:\n"
               "  concurrent 500 2\n";
    }

    const clock_t end_time_cpu = clock();
    const time_t end_time_wall = time(NULL);

    std::string message;
    message = result +
            "Wall clock time: " +
            std::to_string(end_time_wall - begin_time_wall) +
            " seconds\nCPU clock time: " +
            std::to_string((end_time_cpu - begin_time_cpu) / CLOCKS_PER_SEC) +
            " seconds\nNumber of threads used: " +
            std::to_string(numThreads) + "\n";
    return message;
}
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/planning/integration_tests/planning_test_base.h"

#include "modules/common/log.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

using common::adapter::AdapterManager;

DEFINE_string(test_data_dir, "", "the test data folder");
DEFINE_bool(test_update_golden_log, false,
            "true to update decision golden log file.");
DEFINE_string(test_routing_response_file, "garage_routing.pb.txt",
              "The routing file used in test");
DEFINE_string(test_localization_file, "garage_localization.pb.txt",
              "The localization test file");
DEFINE_string(test_chassis_file, "garage_chassis.pb.txt",
              "The chassis test file");
DEFINE_string(test_prediction_file, "", "The prediction module test file");

void PlanningTestBase::SetUpTestCase() {
  FLAGS_planning_config_file =
      "modules/planning/testdata/conf/planning_config.pb.txt";
  FLAGS_adapter_config_path = "modules/planning/testdata/conf/adapter.conf";
  FLAGS_map_dir = "modules/planning/testdata";
  FLAGS_test_localization_file = "garage_localization.pb.txt";
  FLAGS_test_chassis_file = "garage_chassis.pb.txt";
  FLAGS_test_prediction_file = "garage_prediction.pb.txt";
  FLAGS_align_prediction_time = false;
}

bool PlanningTestBase::SetUpAdapters() {
  if (!AdapterManager::Initialized()) {
    AdapterManager::Init(FLAGS_adapter_config_path);
  }
  if (!AdapterManager::GetRoutingResponse()) {
    AERROR << "routing is not registered in adapter manager, check adapter "
              "config file."
           << FLAGS_adapter_config_path;
    return false;
  }
  auto routing_response_file =
      FLAGS_test_data_dir + "/" + FLAGS_test_routing_response_file;
  if (!AdapterManager::FeedRoutingResponseFile(routing_response_file)) {
    AERROR << "failed to routing file: " << routing_response_file;
    return false;
  }
  AINFO << "Using Routing " << routing_response_file;
  auto localization_file =
      FLAGS_test_data_dir + "/" + FLAGS_test_localization_file;
  if (!AdapterManager::FeedLocalizationFile(localization_file)) {
    AERROR << "Failed to load localization file: " << localization_file;
    return false;
  }
  AINFO << "Using Localization file: " << localization_file;
  auto chassis_file = FLAGS_test_data_dir + "/" + FLAGS_test_chassis_file;
  if (!AdapterManager::FeedChassisFile(chassis_file)) {
    AERROR << "Failed to load chassis file: " << chassis_file;
    return false;
  }
  AINFO << "Using Chassis file: " << chassis_file;
  auto prediction_file = FLAGS_test_data_dir + "/" + FLAGS_test_prediction_file;
  if (!FLAGS_test_prediction_file.empty() &&
      !AdapterManager::FeedPredictionFile(prediction_file)) {
    AERROR << "Failed to load prediction file: " << prediction_file;
    return false;
  }
  AINFO << "Using Prediction file: " << prediction_file;
  return true;
}

void PlanningTestBase::SetUp() {
  CHECK(SetUpAdapters()) << "Failed to setup adapters";
  planning_.Init();
}

void PlanningTestBase::TrimPlanning(ADCTrajectory* origin) {
  origin->clear_latency_stats();
  origin->clear_debug();
  origin->mutable_header()->clear_radar_timestamp();
  origin->mutable_header()->clear_lidar_timestamp();
  origin->mutable_header()->clear_timestamp_sec();
  origin->mutable_header()->clear_camera_timestamp();
}

bool PlanningTestBase::RunPlanning(const std::string& test_case_name,
                                   int case_num) {
  const std::string golden_result_file = apollo::common::util::StrCat(
      "result_", test_case_name, "_", case_num, ".pb.txt");
  std::string tmp_golden_path = "/tmp/" + golden_result_file;
  std::string full_golden_path = FLAGS_test_data_dir + "/" + golden_result_file;
  planning_.RunOnce();

  const ADCTrajectory* trajectory_pointer =
      AdapterManager::GetPlanning()->GetLatestPublished();
  if (!trajectory_pointer) {
    AERROR << " did not get latest adc trajectory";
    return false;
  }

  adc_trajectory_ = *trajectory_pointer;
  TrimPlanning(&adc_trajectory_);
  if (FLAGS_test_update_golden_log) {
    AINFO << "The golden file is regenerated:" << full_golden_path;
    ::apollo::common::util::SetProtoToASCIIFile(adc_trajectory_,
                                                full_golden_path);
  } else {
    ADCTrajectory golden_result;
    bool load_success = ::apollo::common::util::GetProtoFromASCIIFile(
        full_golden_path, &golden_result);
    if (!load_success) {
      AERROR << "Failed to load golden file: " << full_golden_path;
      ::apollo::common::util::SetProtoToASCIIFile(adc_trajectory_,
                                                  tmp_golden_path);
      AINFO << "Current result is written to " << tmp_golden_path;
      return false;
    }
    bool same_result =
        ::apollo::common::util::IsProtoEqual(golden_result, adc_trajectory_);
    if (!same_result) {
      std::string tmp_planning_file = tmp_golden_path + ".tmp";
      ::apollo::common::util::SetProtoToASCIIFile(adc_trajectory_,
                                                  tmp_planning_file);
      AERROR << "found diff " << tmp_planning_file << " " << full_golden_path;
      return false;
    }
  }
  return true;
}

void PlanningTestBase::export_sl_points(
    const std::vector<std::vector<common::SLPoint>>& points,
    const std::string& filename) {
  AINFO << "Write sl_points to file " << filename;
  std::ofstream ofs(filename);
  ofs << "level, s, l" << std::endl;
  int level = 0;
  for (const auto& level_points : points) {
    for (const auto& point : level_points) {
      ofs << level << ", " << point.s() << ", " << point.l() << std::endl;
    }
    ++level;
  }
  ofs.close();
}

void PlanningTestBase::export_path_data(const PathData& path_data,
                                        const std::string& filename) {
  AINFO << "Write path_data to file " << filename;
  std::ofstream ofs(filename);
  ofs << "s, l, dl, ddl, x, y, z" << std::endl;
  const auto& frenet_path = path_data.frenet_frame_path();
  const auto& discrete_path = path_data.discretized_path();
  if (frenet_path.NumOfPoints() != discrete_path.NumOfPoints()) {
    AERROR << "frenet_path and discrete path have different number of points";
    return;
  }
  for (uint32_t i = 0; i < frenet_path.NumOfPoints(); ++i) {
    const auto& frenet_point = frenet_path.PointAt(i);
    const auto& discrete_point = discrete_path.PathPointAt(i);
    ofs << frenet_point.s() << ", " << frenet_point.l() << ", "
        << frenet_point.dl() << ", " << frenet_point.ddl() << discrete_point.x()
        << ", " << discrete_point.y() << ", " << discrete_point.z()
        << std::endl;
  }
  ofs.close();
}

}  // namespace planning
}  // namespace apollo
<commit_msg>planning: make each temporary golden file path unique<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/planning/integration_tests/planning_test_base.h"

#include "modules/common/log.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

using common::adapter::AdapterManager;

DEFINE_string(test_data_dir, "", "the test data folder");
DEFINE_bool(test_update_golden_log, false,
            "true to update decision golden log file.");
DEFINE_string(test_routing_response_file, "garage_routing.pb.txt",
              "The routing file used in test");
DEFINE_string(test_localization_file, "garage_localization.pb.txt",
              "The localization test file");
DEFINE_string(test_chassis_file, "garage_chassis.pb.txt",
              "The chassis test file");
DEFINE_string(test_prediction_file, "", "The prediction module test file");

void PlanningTestBase::SetUpTestCase() {
  FLAGS_planning_config_file =
      "modules/planning/testdata/conf/planning_config.pb.txt";
  FLAGS_adapter_config_path = "modules/planning/testdata/conf/adapter.conf";
  FLAGS_map_dir = "modules/planning/testdata";
  FLAGS_test_localization_file = "garage_localization.pb.txt";
  FLAGS_test_chassis_file = "garage_chassis.pb.txt";
  FLAGS_test_prediction_file = "garage_prediction.pb.txt";
  FLAGS_align_prediction_time = false;
}

bool PlanningTestBase::SetUpAdapters() {
  if (!AdapterManager::Initialized()) {
    AdapterManager::Init(FLAGS_adapter_config_path);
  }
  if (!AdapterManager::GetRoutingResponse()) {
    AERROR << "routing is not registered in adapter manager, check adapter "
              "config file."
           << FLAGS_adapter_config_path;
    return false;
  }
  auto routing_response_file =
      FLAGS_test_data_dir + "/" + FLAGS_test_routing_response_file;
  if (!AdapterManager::FeedRoutingResponseFile(routing_response_file)) {
    AERROR << "failed to routing file: " << routing_response_file;
    return false;
  }
  AINFO << "Using Routing " << routing_response_file;
  auto localization_file =
      FLAGS_test_data_dir + "/" + FLAGS_test_localization_file;
  if (!AdapterManager::FeedLocalizationFile(localization_file)) {
    AERROR << "Failed to load localization file: " << localization_file;
    return false;
  }
  AINFO << "Using Localization file: " << localization_file;
  auto chassis_file = FLAGS_test_data_dir + "/" + FLAGS_test_chassis_file;
  if (!AdapterManager::FeedChassisFile(chassis_file)) {
    AERROR << "Failed to load chassis file: " << chassis_file;
    return false;
  }
  AINFO << "Using Chassis file: " << chassis_file;
  auto prediction_file = FLAGS_test_data_dir + "/" + FLAGS_test_prediction_file;
  if (!FLAGS_test_prediction_file.empty() &&
      !AdapterManager::FeedPredictionFile(prediction_file)) {
    AERROR << "Failed to load prediction file: " << prediction_file;
    return false;
  }
  AINFO << "Using Prediction file: " << prediction_file;
  return true;
}

void PlanningTestBase::SetUp() {
  CHECK(SetUpAdapters()) << "Failed to setup adapters";
  planning_.Init();
}

void PlanningTestBase::TrimPlanning(ADCTrajectory* origin) {
  origin->clear_latency_stats();
  origin->clear_debug();
  origin->mutable_header()->clear_radar_timestamp();
  origin->mutable_header()->clear_lidar_timestamp();
  origin->mutable_header()->clear_timestamp_sec();
  origin->mutable_header()->clear_camera_timestamp();
}

bool PlanningTestBase::RunPlanning(const std::string& test_case_name,
                                   int case_num) {
  const std::string golden_result_file = apollo::common::util::StrCat(
      "result_", test_case_name, "_", case_num, ".pb.txt");
  std::string tmp_golden_path = "/tmp/" + std::string(std::tmpnam(nullptr));
  std::string full_golden_path = FLAGS_test_data_dir + "/" + golden_result_file;
  planning_.RunOnce();

  const ADCTrajectory* trajectory_pointer =
      AdapterManager::GetPlanning()->GetLatestPublished();
  if (!trajectory_pointer) {
    AERROR << " did not get latest adc trajectory";
    return false;
  }

  adc_trajectory_ = *trajectory_pointer;
  TrimPlanning(&adc_trajectory_);
  if (FLAGS_test_update_golden_log) {
    AINFO << "The golden file is regenerated:" << full_golden_path;
    ::apollo::common::util::SetProtoToASCIIFile(adc_trajectory_,
                                                full_golden_path);
  } else {
    ADCTrajectory golden_result;
    bool load_success = ::apollo::common::util::GetProtoFromASCIIFile(
        full_golden_path, &golden_result);
    if (!load_success) {
      AERROR << "Failed to load golden file: " << full_golden_path;
      ::apollo::common::util::SetProtoToASCIIFile(adc_trajectory_,
                                                  tmp_golden_path);
      AINFO << "Current result is written to " << tmp_golden_path;
      return false;
    }
    bool same_result =
        ::apollo::common::util::IsProtoEqual(golden_result, adc_trajectory_);
    if (!same_result) {
      std::string tmp_planning_file = tmp_golden_path + ".tmp";
      ::apollo::common::util::SetProtoToASCIIFile(adc_trajectory_,
                                                  tmp_planning_file);
      AERROR << "found\ndiff " << tmp_planning_file << " " << full_golden_path;
      return false;
    }
  }
  return true;
}

void PlanningTestBase::export_sl_points(
    const std::vector<std::vector<common::SLPoint>>& points,
    const std::string& filename) {
  AINFO << "Write sl_points to file " << filename;
  std::ofstream ofs(filename);
  ofs << "level, s, l" << std::endl;
  int level = 0;
  for (const auto& level_points : points) {
    for (const auto& point : level_points) {
      ofs << level << ", " << point.s() << ", " << point.l() << std::endl;
    }
    ++level;
  }
  ofs.close();
}

void PlanningTestBase::export_path_data(const PathData& path_data,
                                        const std::string& filename) {
  AINFO << "Write path_data to file " << filename;
  std::ofstream ofs(filename);
  ofs << "s, l, dl, ddl, x, y, z" << std::endl;
  const auto& frenet_path = path_data.frenet_frame_path();
  const auto& discrete_path = path_data.discretized_path();
  if (frenet_path.NumOfPoints() != discrete_path.NumOfPoints()) {
    AERROR << "frenet_path and discrete path have different number of points";
    return;
  }
  for (uint32_t i = 0; i < frenet_path.NumOfPoints(); ++i) {
    const auto& frenet_point = frenet_path.PointAt(i);
    const auto& discrete_point = discrete_path.PathPointAt(i);
    ofs << frenet_point.s() << ", " << frenet_point.l() << ", "
        << frenet_point.dl() << ", " << frenet_point.ddl() << discrete_point.x()
        << ", " << discrete_point.y() << ", " << discrete_point.z()
        << std::endl;
  }
  ofs.close();
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>