text:
/*
   Copyright (c) Marshall Clow 2012-2012.

   Distributed under the Boost Software License, Version 1.0. (See accompanying
   file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

    For more information, see http://www.boost.org
*/

#include <new>        // for placement new
#include <iostream>
#include <cstddef>    // for NULL, std::size_t, std::ptrdiff_t
#include <cstring>    // for std::strchr and std::strcmp
#include <cstdlib>    // for std::malloc and std::free

#include <boost/utility/string_view.hpp>
#include <boost/config.hpp>

#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

typedef boost::string_view string_view;

void ends_with ( const char *arg ) {
    const size_t sz = std::strlen ( arg );
    string_view sr ( arg );
    string_view sr2 ( arg );
    const char *p = arg;

    while ( *p ) {
        BOOST_CHECK ( sr.ends_with ( p ));
        ++p;
        }

    while ( !sr2.empty ()) {
        BOOST_CHECK ( sr.ends_with ( sr2 ));
        sr2.remove_prefix (1);
        }

    sr2 = arg;
    while ( !sr2.empty ()) {
        BOOST_CHECK ( sr.ends_with ( sr2 ));
        sr2.remove_prefix (1);
        }

    char ch = sz == 0 ? '\0' : arg [ sz - 1 ];
    sr2 = arg;
    if ( sz > 0 )
      BOOST_CHECK ( sr2.ends_with ( ch ));
    BOOST_CHECK ( !sr2.ends_with ( ++ch ));
    BOOST_CHECK ( sr2.ends_with ( string_view()));
    }

void starts_with ( const char *arg ) {
    const size_t sz = std::strlen ( arg );
    string_view sr  ( arg );
    string_view sr2 ( arg );
    const char *p = arg + std::strlen ( arg ) - 1;
    while ( p >= arg ) {
        std::string foo ( arg, p + 1 );
        BOOST_CHECK ( sr.starts_with ( foo ));
        --p;
        }

    while ( !sr2.empty ()) {
        BOOST_CHECK ( sr.starts_with ( sr2 ));
        sr2.remove_suffix (1);
        }

    char ch = *arg;
    sr2 = arg;
  if ( sz > 0 )
    BOOST_CHECK ( sr2.starts_with ( ch ));
    BOOST_CHECK ( !sr2.starts_with ( ++ch ));
    BOOST_CHECK ( sr2.starts_with ( string_view ()));
    }

void reverse ( const char *arg ) {
//  Round trip
    string_view sr1 ( arg );
    std::string string1 ( sr1.rbegin (), sr1.rend ());
    string_view sr2 ( string1 );
    std::string string2 ( sr2.rbegin (), sr2.rend ());

    BOOST_CHECK ( std::equal ( sr2.rbegin (), sr2.rend (), arg ));
    BOOST_CHECK ( string2 == arg );
    BOOST_CHECK ( std::equal ( sr1.begin (), sr1.end (), string2.begin ()));
    }

//  This helper function eliminates signed vs. unsigned warnings
string_view::size_type ptr_diff ( const char *res, const char *base ) {
    BOOST_CHECK ( res >= base );
    return static_cast<string_view::size_type> ( res - base );
    }

void find ( const char *arg ) {
    string_view sr1;
    string_view sr2;
    const char *p;

//  Look for each character in the string(searching from the start)
    p = arg;
    sr1 = arg;
    while ( *p ) {
      string_view::size_type pos = sr1.find(*p);
      BOOST_CHECK ( pos != string_view::npos && ( pos <= ptr_diff ( p, arg )));
      ++p;
      }

//  Look for each character in the string (searching from the end)
    p = arg;
    sr1 = arg;
    while ( *p ) {
      string_view::size_type pos = sr1.rfind(*p);
      BOOST_CHECK ( pos != string_view::npos && pos < sr1.size () && ( pos >= ptr_diff ( p, arg )));
      ++p;
      }

//  Look for pairs on characters (searching from the start)
    sr1 = arg;
    p = arg;
    while ( *p && *(p+1)) {
        string_view sr3 ( p, 2 );
        string_view::size_type pos = sr1.find ( sr3 );
        BOOST_CHECK ( pos != string_view::npos && pos <= static_cast<string_view::size_type>( p - arg ));
        p++;
        }

    sr1 = arg;
    p = arg;
//  for all possible chars, see if we find them in the right place.
//  Note that strchr will/might do the _wrong_ thing if we search for NULL
    for ( int ch = 1; ch < 256; ++ch ) {
        string_view::size_type pos = sr1.find(ch);
        const char *strp = std::strchr ( arg, ch );
        BOOST_CHECK (( strp == NULL ) == ( pos == string_view::npos ));
        if ( strp != NULL )
            BOOST_CHECK ( ptr_diff ( strp, arg ) == pos );
    }

    sr1 = arg;
    p = arg;
//  for all possible chars, see if we find them in the right place.
//  Note that strchr will/might do the _wrong_ thing if we search for NULL
    for ( int ch = 1; ch < 256; ++ch ) {
        string_view::size_type pos = sr1.rfind(ch);
        const char *strp = std::strrchr ( arg, ch );
        BOOST_CHECK (( strp == NULL ) == ( pos == string_view::npos ));
        if ( strp != NULL )
            BOOST_CHECK ( ptr_diff ( strp, arg ) == pos );
    }

//  Find everything at the start
    p = arg;
    sr1 = arg;
    while ( !sr1.empty ()) {
        string_view::size_type pos = sr1.find(*p);
        BOOST_CHECK ( pos == 0 );
        sr1.remove_prefix (1);
        ++p;
        }

//  Find everything at the end
    sr1  = arg;
    p    = arg + std::strlen ( arg ) - 1;
    while ( !sr1.empty ()) {
        string_view::size_type pos = sr1.rfind(*p);
        BOOST_CHECK ( pos == sr1.size () - 1 );
        sr1.remove_suffix (1);
        --p;
        }

//  Find everything at the start
    sr1  = arg;
    p    = arg;
    while ( !sr1.empty ()) {
        string_view::size_type pos = sr1.find_first_of(*p);
        BOOST_CHECK ( pos == 0 );
        sr1.remove_prefix (1);
        ++p;
        }

//  Find everything at the end
    sr1  = arg;
    p    = arg + std::strlen ( arg ) - 1;
    while ( !sr1.empty ()) {
        string_view::size_type pos = sr1.find_last_of(*p);
        BOOST_CHECK ( pos == sr1.size () - 1 );
        sr1.remove_suffix (1);
        --p;
        }

//  Basic sanity checking for "find_first_of / find_first_not_of"
    sr1 = arg;
    sr2 = arg;
    while ( !sr1.empty() ) {
        BOOST_CHECK ( sr1.find_first_of ( sr2 )     == 0 );
        BOOST_CHECK ( sr1.find_first_not_of ( sr2 ) == string_view::npos );
        sr1.remove_prefix ( 1 );
        }

    p = arg;
    sr1 = arg;
    while ( *p ) {
        string_view::size_type pos1 = sr1.find_first_of(*p);
        string_view::size_type pos2 = sr1.find_first_not_of(*p);
        BOOST_CHECK ( pos1 != string_view::npos && pos1 < sr1.size () && pos1 <= ptr_diff ( p, arg ));
        if ( pos2 != string_view::npos ) {
            for ( size_t i = 0 ; i < pos2; ++i )
                BOOST_CHECK ( sr1[i] == *p );
            BOOST_CHECK ( sr1 [ pos2 ] != *p );
            }

        BOOST_CHECK ( pos2 != pos1 );
        ++p;
        }

//  Basic sanity checking for "find_last_of / find_last_not_of"
    sr1 = arg;
    sr2 = arg;
    while ( !sr1.empty() ) {
        BOOST_CHECK ( sr1.find_last_of ( sr2 )     == ( sr1.size () - 1 ));
        BOOST_CHECK ( sr1.find_last_not_of ( sr2 ) == string_view::npos );
        sr1.remove_suffix ( 1 );
        }

    p = arg;
    sr1 = arg;
    while ( *p ) {
        string_view::size_type pos1 = sr1.find_last_of(*p);
        string_view::size_type pos2 = sr1.find_last_not_of(*p);
        BOOST_CHECK ( pos1 != string_view::npos && pos1 < sr1.size () && pos1 >= ptr_diff ( p, arg ));
        BOOST_CHECK ( pos2 == string_view::npos || pos1 < sr1.size ());
        if ( pos2 != string_view::npos ) {
            for ( size_t i = sr1.size () -1 ; i > pos2; --i )
                BOOST_CHECK ( sr1[i] == *p );
            BOOST_CHECK ( sr1 [ pos2 ] != *p );
            }

        BOOST_CHECK ( pos2 != pos1 );
        ++p;
        }

    }

template <typename T>
class custom_allocator {
public:
    typedef T value_type;
    typedef T* pointer;
    typedef const T* const_pointer;
    typedef void* void_pointer;
    typedef const void* const_void_pointer;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef T& reference;
    typedef const T& const_reference;

    template<class U>
    struct rebind {
        typedef custom_allocator<U> other;
        };

    custom_allocator() BOOST_NOEXCEPT {}
    template <typename U>
    custom_allocator(custom_allocator<U> const&) BOOST_NOEXCEPT {}

    pointer allocate(size_type n) const {
        return static_cast<pointer>(std::malloc(sizeof(value_type) * n));
        }
    void deallocate(pointer p, size_type) const BOOST_NOEXCEPT {
        std::free(p);
        }

    pointer address(reference value) const BOOST_NOEXCEPT {
        return &value;
        }

    const_pointer address(const_reference value) const BOOST_NOEXCEPT {
        return &value;
        }

    BOOST_CONSTEXPR size_type max_size() const BOOST_NOEXCEPT {
        return (~(size_type)0u) / sizeof(value_type);
        }

#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
    template <class U, class... Args>
    void construct(U* ptr, Args&&... args) const {
        ::new((void*)ptr) U(static_cast<Args&&>(args)...);
        }
#else
    template <class U, class V>
    void construct(U* ptr, V&& value) const {
        ::new((void*)ptr) U(static_cast<V&&>(value));
        }
#endif
#else
    template <class U, class V>
    void construct(U* ptr, const V& value) const {
        ::new((void*)ptr) U(value);
        }
#endif

    template <class U>
    void construct(U* ptr) const {
        ::new((void*)ptr) U();
        }

    template <class U>
    void destroy(U* ptr) const {
        (void)ptr;
        ptr->~U();
        }
    };

template <typename T, typename U>
BOOST_CONSTEXPR bool operator==(const custom_allocator<T> &, const custom_allocator<U> &) BOOST_NOEXCEPT {
    return true;
    }
template <typename T, typename U>
BOOST_CONSTEXPR bool operator!=(const custom_allocator<T> &, const custom_allocator<U> &) BOOST_NOEXCEPT {
    return false;
    }

void to_string ( const char *arg ) {
    string_view sr1;
    std::string str1;
    std::string str2;

    str1.assign ( arg );
    sr1 = arg;
//  str2 = sr1.to_string<std::allocator<char> > ();
    str2 = sr1.to_string ();
    BOOST_CHECK ( str1 == str2 );

    std::basic_string<char, std::char_traits<char>, custom_allocator<char> > str3 = sr1.to_string(custom_allocator<char>());
    BOOST_CHECK ( std::strcmp(str1.c_str(), str3.c_str()) == 0 );

#ifndef BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
    std::string str4 = static_cast<std::string> ( sr1 );
    BOOST_CHECK ( str1 == str4 );
#endif
    }

void compare ( const char *arg ) {
    string_view sr1;
    std::string str1;
    std::string str2 = str1;

    str1.assign ( arg );
    sr1 = arg;
    BOOST_CHECK ( sr1  == sr1);    // compare string_view and string_view
    BOOST_CHECK ( sr1  == str1);   // compare string and string_view
    BOOST_CHECK ( str1 == sr1 );   // compare string_view and string
    BOOST_CHECK ( sr1  == arg );   // compare string_view and pointer
    BOOST_CHECK ( arg  == sr1 );   // compare pointer and string_view

    if ( sr1.size () > 0 ) {
        (*str1.rbegin())++;
        BOOST_CHECK ( sr1  != str1 );
        BOOST_CHECK ( str1 != sr1 );
        BOOST_CHECK ( sr1 < str1 );
        BOOST_CHECK ( sr1 <= str1 );
        BOOST_CHECK ( str1 > sr1 );
        BOOST_CHECK ( str1 >= sr1 );

        (*str1.rbegin()) -= 2;
        BOOST_CHECK ( sr1  != str1 );
        BOOST_CHECK ( str1 != sr1 );
        BOOST_CHECK ( sr1 > str1 );
        BOOST_CHECK ( sr1 >= str1 );
        BOOST_CHECK ( str1 < sr1 );
        BOOST_CHECK ( str1 <= sr1 );
        }
    }

const char *test_strings [] = {
    "",
    "0",
    "abc",
    "AAA",  // all the same
    "adsfadadiaef;alkdg;aljt;j agl;sjrl;tjs;lga;lretj;srg[w349u5209dsfadfasdfasdfadsf",
    "abc\0asdfadsfasf",
    NULL
    };

BOOST_AUTO_TEST_CASE( test_main )
{
    const char **p = &test_strings[0];

    while ( *p != NULL ) {
        starts_with ( *p );
        ends_with ( *p );
        reverse ( *p );
        find ( *p );
        to_string ( *p );
        compare ( *p );

        p++;
        }
}

ext: cpp

max_stars_repo_name: ZCube/boost-cmake

max_issues_repo_name: ZCube/boost-cmake

max_forks_repo_name: ZCube/boost-cmake


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2015 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"

#include <Eigen/CXX11/Tensor>

struct Generator1D {
  Generator1D() { }

  float operator()(const array<Eigen::DenseIndex, 1>& coordinates) const {
    return coordinates[0];
  }
};

template <int DataLayout>
static void test_1D()
{
  Tensor<float, 1> vec(6);
  Tensor<float, 1> result = vec.generate(Generator1D());

  for (int i = 0; i < 6; ++i) {
    VERIFY_IS_EQUAL(result(i), i);
  }
}

struct Generator2D {
  Generator2D() { }

  float operator()(const array<Eigen::DenseIndex, 2>& coordinates) const {
    return 3 * coordinates[0] + 11 * coordinates[1];
  }
};

template <int DataLayout>
static void test_2D()
{
  Tensor<float, 2> matrix(5, 7);
  Tensor<float, 2> result = matrix.generate(Generator2D());

  for (int i = 0; i < 5; ++i) {
    for (int j = 0; j < 5; ++j) {
      VERIFY_IS_EQUAL(result(i, j), 3*i + 11*j);
    }
  }
}

template <int DataLayout>
static void test_gaussian()
{
  int rows = 32;
  int cols = 48;
  array<float, 2> means;
  means[0] = rows / 2.0f;
  means[1] = cols / 2.0f;
  array<float, 2> std_devs;
  std_devs[0] = 3.14f;
  std_devs[1] = 2.7f;
  internal::GaussianGenerator<float, Eigen::DenseIndex, 2> gaussian_gen(means, std_devs);

  Tensor<float, 2> matrix(rows, cols);
  Tensor<float, 2> result = matrix.generate(gaussian_gen);

  for (int i = 0; i < rows; ++i) {
    for (int j = 0; j < cols; ++j) {
      float g_rows = powf(rows/2.0f - i, 2) / (3.14f * 3.14f) * 0.5f;
      float g_cols = powf(cols/2.0f - j, 2) / (2.7f * 2.7f) * 0.5f;
      float gaussian = expf(-g_rows - g_cols);
      VERIFY_IS_EQUAL(result(i, j), gaussian);
    }
  }
}

void test_cxx11_tensor_generator()
{
  CALL_SUBTEST(test_1D<ColMajor>());
  CALL_SUBTEST(test_1D<RowMajor>());
  CALL_SUBTEST(test_2D<ColMajor>());
  CALL_SUBTEST(test_2D<RowMajor>());
  CALL_SUBTEST(test_gaussian<ColMajor>());
  CALL_SUBTEST(test_gaussian<RowMajor>());
}


text:
/**
 * @file pngimage.cxx
 * @desc PNG image module.
 */
#include <windows.h>
#include <assert.h>
#include <boost/log/trivial.hpp>
#include <png.h>
#include "pngimage.hxx"

PNGImage::~PNGImage()
{
	if (rowPointers)
		free(rowPointers);
	if (image)
		free(image);
}

PNGImage::PNGImage()
	: width(0), height(0), bitDepth(0), colorType(0)
	, imageSize(0), rowPointersSize(0), image(NULL), rowPointers(NULL)
{
}

PNGImage::PNGImage(const char *fileName)
	: width(0), height(0), bitDepth(0), colorType(0)
	, imageSize(0), rowPointersSize(0), image(NULL), rowPointers(NULL)
{
	if (!init(fileName))
		throw std::runtime_error("PNG is not loaded.");
}

bool PNGImage::init(const char *fileName)
{
	// This function was originally written by David Grayson for
	// https://github.com/DavidEGrayson/ahrs-visualizer
	FILE *fp = fopen(fileName, "rb");
	if (fp == 0) {
		BOOST_LOG_TRIVIAL(error) << "File cannot open.";
		return false;
	}

	// read the header
	png_byte header[8] = { 0 };
	fread(header, 1, 8, fp);
	if (png_sig_cmp(header, 0, 8)) {
		BOOST_LOG_TRIVIAL(error) << "File is not PNG image.";
		fclose(fp);
		return false;
	}

	// create png info struct
	png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	png_infop info_ptr = png_create_info_struct(png_ptr);
	if (!info_ptr) {
		BOOST_LOG_TRIVIAL(error) << "png_create_info_struct() returned NULL.";
		png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
		fclose(fp);
		return false;
	}

	// create png info struct
	png_infop end_info = png_create_info_struct(png_ptr);
	if (!end_info) {
		BOOST_LOG_TRIVIAL(error) << "png_create_info_struct() returned NULL.";
		png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
		fclose(fp);
		return false;
	}

	// the code in this if statement gets called if libpng encounters an error
	if (setjmp(png_jmpbuf(png_ptr)) != 0) {
		BOOST_LOG_TRIVIAL(error) << "libpng setjmp() error.";
		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
		fclose(fp);
		return false;
	}

	// init png reading
	png_init_io(png_ptr, fp);

	// let libpng know you already read the first 8 bytes
	png_set_sig_bytes(png_ptr, 8);

	// read all the info up to the image data
	png_read_info(png_ptr, info_ptr);

	// variables to pass to get info
	int bit_depth, color_type;
	png_uint_32 temp_width, temp_height;

	// get info about png
	png_get_IHDR(png_ptr, info_ptr, &temp_width, &temp_height, &bit_depth, &color_type, NULL, NULL, NULL);

	// Update the png info struct.
	png_read_update_info(png_ptr, info_ptr);

	// Row size in bytes.
	size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr);

	// glTexImage2d requires rows to be 4-byte aligned
	rowbytes += 3 - ((rowbytes - 1) % 4);

	// Allocate the image_data as a big block, to be given to opengl
	size_t image_data_size = rowbytes * temp_height * sizeof(png_byte) + 15;
	png_byte *image_data = (png_byte*)malloc(image_data_size);
	if (image_data == NULL) {
		BOOST_LOG_TRIVIAL(error) << "Not enough memory.";
		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
		fclose(fp);
		return false;
	}

	// row_pointers is for pointing to image_data for reading the png with libpng
	size_t row_pointers_size = temp_height * sizeof(png_byte*);
	png_byte **row_pointers = (png_byte**)malloc(row_pointers_size);
	if (row_pointers == NULL) {
		BOOST_LOG_TRIVIAL(error) << "Not enough memory for PNG row pointers.";
		free(image_data);
		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
		fclose(fp);
		return false;
	}

	// set the individual row_pointers to point at the correct offsets of image_data
	for (unsigned int i = 0; i < temp_height; i++) {
		row_pointers[temp_height - 1 - i] = image_data + i * rowbytes;
	}

	// read the png into image_data through row_pointers
	png_read_image(png_ptr, row_pointers);

	// deletes old image
	if (this->rowPointers)
		free(this->rowPointers);
	if (this->image)
		free(this->image);

	// copied new image
	this->width = png_get_image_width(png_ptr, info_ptr);
	this->height = png_get_image_height(png_ptr, info_ptr);
	this->bitDepth = png_get_bit_depth(png_ptr, info_ptr);
	this->colorType = png_get_color_type(png_ptr, info_ptr);
	this->imageSize = image_data_size;
	this->rowPointersSize = row_pointers_size;
	this->image = image_data;
	this->rowPointers = row_pointers;

	// closes resources
	png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
	fclose(fp);

	return true;
}

ext: cxx

max_stars_repo_name: taworn/capmangl

max_issues_repo_name: taworn/capmangl

max_forks_repo_name: taworn/capmangl


text:
//   Copyright 2015 Patrick Putnam
//
//   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 <boost/test/unit_test.hpp>

#include "../unittest_config.h"

#include "clotho/data_spaces/association_matrix.hpp"
#include "clotho/utility/bit_helper.hpp"
#include <vector>
#include <iostream>
#include <iomanip>

using namespace clotho::genetics;

BOOST_AUTO_TEST_SUITE( test_data_space )

BOOST_AUTO_TEST_CASE( association_matrix_sizing_test ) {

    typedef unsigned long long block_type;
    typedef clotho::utility::BitHelper< block_type > bit_helper_type;

    size_t exp_rows = 5, exp_cols = 2;

    size_t exp_size = exp_rows * exp_cols;
    size_t exp_alloc_size = (exp_cols / bit_helper_type::BITS_PER_BLOCK + 1) * exp_rows;

    association_matrix< block_type, column_aligned > amat( exp_rows, exp_cols );

    size_t obs_size = amat.size();
    size_t obs_alloc_size = amat.allocated_size();

    BOOST_REQUIRE_MESSAGE( obs_size == exp_size, "Unexpected matrix size; Observed size: " << obs_size << "; Expected size: " << exp_size );
    BOOST_REQUIRE_MESSAGE( obs_alloc_size == exp_alloc_size, "Unexpected allocated size: Observed allocated size: " << obs_alloc_size << "; Expected allocated size: " << exp_alloc_size );

}

BOOST_AUTO_TEST_CASE( association_matrix_flip_test ) {
    typedef unsigned long long block_type;
    typedef clotho::utility::BitHelper< block_type > bit_helper_type;

    size_t exp_rows = 5, exp_cols = 12;

    association_matrix< block_type, column_aligned > amat( exp_rows, exp_cols );

    size_t flip_row = 3, flip_col = 6;

    bool exp_state = !amat( flip_row, flip_col );

    amat.flip(flip_row, flip_col );
    bool obs_state = amat( flip_row, flip_col );

    BOOST_REQUIRE_MESSAGE( obs_state == exp_state, "Unexpected flip state; Observed state: " << obs_state << "; Expected state: " << exp_state );
}

BOOST_AUTO_TEST_CASE( association_matrix_raw_iterator_test ) {
    typedef unsigned long long block_type;

    typedef unsigned long long block_type;
    typedef clotho::utility::BitHelper< block_type >    bit_helper_type;

    typedef association_matrix< block_type, column_aligned >            association_type;
    typedef typename association_type::block_iterator   iterator;

    size_t exp_rows = 5, exp_cols = 240;

    association_type amat( exp_rows, exp_cols );

    size_t exp_blocks = exp_rows * (exp_cols / bit_helper_type::BITS_PER_BLOCK + 1);

    amat.clear();

    iterator it = amat.raw_iterator();

    size_t obs_blocks = 0;
    size_t i = 0, j = 0;
    while( it.hasNext() ) {
        block_type b = it.next();

        BOOST_REQUIRE_MESSAGE( b == 0, "Unexpected block state at row: " << i << ", column: " << j << "; Observed: " << b << "; Expected: 0" );

        if( ++j >= it.max_columns() ) {
            j = 0;
            ++i;
        }
        ++obs_blocks;
    }

    BOOST_REQUIRE_MESSAGE( exp_blocks == obs_blocks, "Unexpected number of raw blocks; Observed: " << obs_blocks << "; Expected: " << exp_blocks );
}

BOOST_AUTO_TEST_CASE( association_matrix_raw_iterator_test2 ) {
    typedef unsigned long long block_type;

    typedef unsigned long long block_type;
    typedef clotho::utility::BitHelper< block_type >    bit_helper_type;

    typedef association_matrix< block_type, column_aligned >            association_type;
    typedef typename association_type::block_iterator   iterator;

    size_t exp_rows = 5, exp_cols = 240;

    association_type amat( exp_rows, exp_cols );

    size_t exp_block_count = exp_rows * (exp_cols / bit_helper_type::BITS_PER_BLOCK + 1);

    amat.clear();

    std::vector< block_type > exp_blocks;

    size_t i = 0, j = 0, k = 0;
    block_type _b = 0;
    while( i < exp_rows ) {
        amat.flip( i, j );

        if( k != j / bit_helper_type::BITS_PER_BLOCK ) {
            exp_blocks.push_back(_b);
            _b = 0;
            ++k;
        }

        _b |= (1L << (j % bit_helper_type::BITS_PER_BLOCK));

        j += 15;
        if( j >= exp_cols ) {
            exp_blocks.push_back( _b );
            j = 0;
            k = 0;
            _b = 0;
            ++i;
        }
    }

    iterator it = amat.raw_iterator();

    size_t obs_blocks = 0;
    i = 0; j = 0;

    while( it.hasNext() ) {
        block_type b = it.next();

        size_t idx = j * it.max_rows() + i;

        BOOST_REQUIRE_MESSAGE( b == exp_blocks[idx], "Unexpected block state at row: " << std::dec << i << ", column: " << std::dec << j << "; Observed: " << std::hex << std::setw( sizeof( block_type ) * 2) << std::setfill('0') << b << "; Expected [" << idx << "]: " << std::hex << std::setw( sizeof(block_type) * 2) << std::setfill('0') << exp_blocks[idx] );

        if( ++j >= it.max_columns() ) {
            j = 0;
            ++i;
        }
        ++obs_blocks;
    }

    BOOST_REQUIRE_MESSAGE( exp_block_count == obs_blocks, "Unexpected number of raw blocks; Observed: " << obs_blocks << "; Expected: " << exp_block_count );
}

BOOST_AUTO_TEST_CASE( association_matrix_row_iterator_test ) {
    typedef unsigned long long block_type;

    typedef unsigned long long block_type;
    typedef clotho::utility::BitHelper< block_type >    bit_helper_type;

    typedef association_matrix< block_type, column_aligned >            association_type;
    typedef typename association_type::row_iterator   iterator;

    size_t exp_rows = 5, exp_cols = 240;

    association_type amat( exp_rows, exp_cols );

    size_t blocks_per_row = (exp_cols / bit_helper_type::BITS_PER_BLOCK + 1);

    amat.clear();

    std::vector< block_type > exp_blocks;

    size_t i = 0, j = 0, k = 0;
    block_type _b = 0;
    while( i < exp_rows ) {
        amat.flip( i, j );

        if( k != j / bit_helper_type::BITS_PER_BLOCK ) {
            exp_blocks.push_back(_b);
            _b = 0;
            ++k;
        }

        _b |= (1L << (j % bit_helper_type::BITS_PER_BLOCK));

        j += 15;
        if( j >= exp_cols ) {
            exp_blocks.push_back( _b );
            j = 0;
            k = 0;
            _b = 0;
            ++i;
        }
    }

    size_t obs_blocks = 0;
    i = 2; j = 0;

    iterator it = amat.getRowAt( i );

    while( it.hasNext() ) {
        block_type b = it.next();

        size_t idx = i * blocks_per_row + j;

        BOOST_REQUIRE_MESSAGE( b == exp_blocks[idx], "Unexpected block state at row: " << std::dec << i << ", column: " << std::dec << j << "; Observed: " << std::hex << std::setw( sizeof( block_type ) * 2) << std::setfill('0') << b << "; Expected [" << idx << "]: " << std::hex << std::setw( sizeof(block_type) * 2) << std::setfill('0') << exp_blocks[idx] );

        ++j;
        ++obs_blocks;
    }

    BOOST_REQUIRE_MESSAGE( blocks_per_row == obs_blocks, "Unexpected number of raw blocks; Observed: " << obs_blocks << "; Expected: " << blocks_per_row );
}

BOOST_AUTO_TEST_CASE( association_matrix_column_iterator_test ) {
    typedef unsigned long long block_type;

    typedef unsigned long long block_type;
    typedef clotho::utility::BitHelper< block_type >    bit_helper_type;

    typedef association_matrix< block_type, column_aligned >            association_type;
    typedef typename association_type::column_iterator  iterator;

    size_t exp_rows = 5, exp_cols = 240;

    association_type amat( exp_rows, exp_cols );

    size_t blocks_per_row = (exp_cols / bit_helper_type::BITS_PER_BLOCK + 1);
    size_t blocks_per_column = exp_rows;

    amat.clear();

    std::vector< block_type > exp_blocks;

    size_t i = 0, j = 0, k = 0;
    block_type _b = 0;
    while( i < exp_rows ) {
        amat.flip( i, j );

        if( k != j / bit_helper_type::BITS_PER_BLOCK ) {
            exp_blocks.push_back(_b);
            _b = 0;
            ++k;
        }

        _b |= (1L << (j % bit_helper_type::BITS_PER_BLOCK));

        j += 15;
        if( j >= exp_cols ) {
            exp_blocks.push_back( _b );
            j = 0;
            k = 0;
            _b = 0;
            ++i;
        }
    }

    size_t obs_blocks = 0;
    i = 2; j = 0;

    iterator it = amat.getColumnAt( i );

    while( it.hasNext() ) {
        block_type b = it.next();

        size_t idx = j * blocks_per_row + i;

        BOOST_REQUIRE_MESSAGE( b == exp_blocks[idx], "Unexpected block state at row: " << std::dec << i << ", column: " << std::dec << j << "; Observed: " << std::hex << std::setw( sizeof( block_type ) * 2) << std::setfill('0') << b << "; Expected [" << idx << "]: " << std::hex << std::setw( sizeof(block_type) * 2) << std::setfill('0') << exp_blocks[idx] );

        ++j;
        ++obs_blocks;
    }

    BOOST_REQUIRE_MESSAGE( blocks_per_column == obs_blocks, "Unexpected number of raw blocks; Observed: " << obs_blocks << "; Expected: " << blocks_per_column );
}
BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: putnampp/clotho

max_issues_repo_name: putnampp/clotho

max_forks_repo_name: putnampp/clotho


text:
#ifndef BOOST_ADAPTBX_GRAPH_VERTEX_MAP_H
#define BOOST_ADAPTBX_GRAPH_VERTEX_MAP_H

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/property_map/property_map.hpp>

#include <boost/mpl/if.hpp>
#include <boost/type_traits.hpp>

#include <map>
#include <vector>

namespace boost_adaptbx
{
namespace vertex_map
{

namespace detail
{

template< typename Graph, typename Value >
struct associative_vertex_map_impl
{
  typedef boost::graph_traits< Graph > graph_traits;
  typedef typename graph_traits::vertex_descriptor vertex_descriptor_type;
  typedef std::map< vertex_descriptor_type, Value > storage_type;
  typedef boost::associative_property_map< storage_type > property_map_type;
  typedef Value map_value_type;

  storage_type data_for_;
  property_map_type vertex_map_;

  associative_vertex_map_impl(Graph const& graph) : vertex_map_( data_for_ )
  {}

  property_map_type get()
  {
    return vertex_map_;
  }
};

template< typename Graph, typename Value >
struct serial_vertex_map_impl
{
  typedef std::vector< Value > storage_type;
  typedef typename storage_type::pointer property_map_type;
  typedef Value map_value_type;

  storage_type vertex_map_;

  serial_vertex_map_impl(Graph const& graph)
    : vertex_map_( boost::num_vertices( graph ) )
  {}

  property_map_type get()
  {
    return &vertex_map_[0];
  }
};

template< typename Graph, typename PropertyTag >
struct internal_vertex_map_impl
{
  typedef typename boost::mpl::if_<
    boost::is_const< Graph >,
    typename boost::property_map< Graph, PropertyTag >::const_type,
    typename boost::property_map< Graph, PropertyTag >::type
    >::type property_map_type;
  typedef typename boost::property_traits< property_map_type >::value_type
    map_value_type;

  property_map_type vertex_map_;

  internal_vertex_map_impl(Graph const& graph)
    : vertex_map_( boost::get( PropertyTag(), graph ) )
  {}

  property_map_type get()
  {
    return vertex_map_;
  }
};

template< typename Graph >
struct associative_index_map_impl
{
  typedef boost::graph_traits< Graph > graph_traits;
  typedef typename graph_traits::vertex_descriptor vertex_descriptor_type;
  typedef typename graph_traits::vertex_iterator vertex_iterator_type;
  typedef typename graph_traits::vertices_size_type vertex_index_type;
  typedef associative_vertex_map_impl< Graph, vertex_index_type > vertex_map_type;
  typedef typename vertex_map_type::property_map_type property_map_type;

  vertex_map_type vertex_map_;

  associative_index_map_impl(Graph const& graph) :vertex_map_( graph )
  {
    property_map_type vim( vertex_map_.get() );
    vertex_index_type index = 0;
    vertex_iterator_type di, dj;

    for ( boost::tie( di, dj ) = boost::vertices( graph ) ; di != dj; ++di )
    {
      boost::put( vim, *di, index++ );
    }
  }

  property_map_type get()
  {
    return vertex_map_.get();
  }
};

template< typename Graph >
struct property_index_map_impl
{
  typedef internal_vertex_map_impl< Graph, boost::vertex_index_t > vertex_map_type;
  typedef typename vertex_map_type::map_value_type vertex_index_type;
  typedef typename vertex_map_type::property_map_type property_map_type;

  vertex_map_type vertex_map_;

  property_index_map_impl(Graph const& graph) : vertex_map_( graph )
  {}

  property_map_type get()
  {
    return vertex_map_.get();
  }
};

} // namespace detail

template< typename Graph, typename Value >
struct generic_vertex_map
{
  typedef Graph graph_type;
  typedef Value value_type;
  typedef detail::associative_vertex_map_impl< graph_type, value_type > vertex_map_impl_type;
  typedef typename vertex_map_impl_type::property_map_type property_map_type;

  vertex_map_impl_type vertex_map_impl_;

  generic_vertex_map(Graph const& graph) : vertex_map_impl_( graph )
  {}

  property_map_type get()
  {
    return vertex_map_impl_.get();
  }
};

template<
  typename OutEdgeList,
  typename VertexList,
  typename Directed,
  typename VertexProperties,
  typename EdgeProperties,
  typename GraphProperties,
  typename EdgeList,
  typename Value
  >
struct generic_vertex_map<
  boost::adjacency_list<
    OutEdgeList,
    VertexList,
    Directed,
    VertexProperties,
    EdgeProperties,
    GraphProperties,
    EdgeList
    >,
  Value
  >
{
  typedef boost::adjacency_list<
    OutEdgeList,
    VertexList,
    Directed,
    VertexProperties,
    EdgeProperties,
    GraphProperties,
    EdgeList
    > graph_type;
  typedef Value value_type;
  typedef typename boost::mpl::if_<
    boost::is_same< typename graph_type::vertex_list_selector, boost::vecS >,
    detail::serial_vertex_map_impl< graph_type, value_type >,
    detail::associative_vertex_map_impl< graph_type, value_type >
    >::type vertex_map_impl_type;
  typedef typename vertex_map_impl_type::property_map_type property_map_type;

  vertex_map_impl_type vertex_map_impl_;

  generic_vertex_map(graph_type const& graph) : vertex_map_impl_( graph )
  {}

  property_map_type get()
  {
    return vertex_map_impl_.get();
  }
};

template< typename Graph >
struct index_map
{
  typedef Graph graph_type;
  typedef detail::associative_index_map_impl< graph_type > index_map_impl_type;
  typedef typename index_map_impl_type::property_map_type property_map_type;

  index_map_impl_type index_map_impl_;

  index_map(Graph const& graph) : index_map_impl_( graph )
  {}

  property_map_type get()
  {
    return index_map_impl_.get();
  }
};

template<
  typename OutEdgeList,
  typename VertexList,
  typename Directed,
  typename VertexProperties,
  typename EdgeProperties,
  typename GraphProperties,
  typename EdgeList
  >
struct index_map<
  boost::adjacency_list<
    OutEdgeList,
    VertexList,
    Directed,
    VertexProperties,
    EdgeProperties,
    GraphProperties,
    EdgeList
    >
  >
{
  typedef boost::adjacency_list<
    OutEdgeList,
    VertexList,
    Directed,
    VertexProperties,
    EdgeProperties,
    GraphProperties,
    EdgeList
    > graph_type;
  typedef typename boost::mpl::if_<
    boost::is_same< typename graph_type::vertex_list_selector, boost::vecS >,
    detail::property_index_map_impl< graph_type >,
    detail::associative_index_map_impl< graph_type >
    >::type index_map_impl_type;

  typedef typename index_map_impl_type::property_map_type property_map_type;

  index_map_impl_type index_map_impl_;

  index_map(graph_type const& graph) : index_map_impl_( graph )
  {}

  property_map_type get()
  {
    return index_map_impl_.get();
  }
};

} // namespace vertex_map

namespace edge_map
{

template< typename Graph, typename Value >
struct generic_edge_map
{
  typedef Graph graph_type;
  typedef Value value_type;
  typedef boost::graph_traits< Graph > graph_traits;
  typedef typename graph_traits::edge_descriptor edge_descriptor_type;
  typedef std::map< edge_descriptor_type, Value > storage_type;
  typedef boost::associative_property_map< storage_type > property_map_type;

  storage_type data_for_;
  property_map_type edge_map_;

  generic_edge_map(Graph const& graph) : edge_map_( data_for_ )
  {}

  property_map_type get()
  {
    return edge_map_;
  }
};

} // namespace edge_map
} // namespace boost_adaptbx

#endif // BOOST_ADAPTBX_GRAPH_VERTEX_MAP_H

ext: hpp


text:
//=================================================================================================
// Copyright (c) 2011, Stefan Kohlbrecher, TU Darmstadt
// 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 Simulation, Systems Optimization and Robotics
//       group, TU Darmstadt 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 HOLDER BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//=================================================================================================

#include "hector_geotiff/geotiff_writer.h"
#include "hector_geotiff/map_writer_plugin_interface.h"

#include <cstdio>
#include <ros/ros.h>
#include <ros/console.h>

#include <pluginlib/class_loader.h>

#include <boost/algorithm/string.hpp>

#include <geometry_msgs/Quaternion.h>
#include <nav_msgs/GetMap.h>
#include <std_msgs/String.h>
#include <hector_nav_msgs/GetRobotTrajectory.h>

#include <QApplication>

using namespace std;

namespace hector_geotiff{

/**
 * @brief Map generation node.
 */
class MapGenerator
{
public:
  MapGenerator()
    : geotiff_writer_(false)
    , pn_("~")
    , plugin_loader_(0)
    , running_saved_map_num_(0)
  {
    pn_.param("map_file_path", p_map_file_path_, std::string("."));
    geotiff_writer_.setMapFilePath(p_map_file_path_);
    geotiff_writer_.setUseUtcTimeSuffix(true);

    pn_.param("map_file_base_name", p_map_file_base_name_, std::string());

    pn_.param("draw_background_checkerboard", p_draw_background_checkerboard_, true);
    pn_.param("draw_free_space_grid", p_draw_free_space_grid_, true);

    sys_cmd_sub_ = n_.subscribe("syscommand", 1, &MapGenerator::sysCmdCallback, this);

    map_service_client_ = n_.serviceClient<nav_msgs::GetMap>("map");
    //object_service_client_ = n_.serviceClient<worldmodel_msgs::GetObjectModel>("worldmodel/get_object_model");
    path_service_client_ = n_.serviceClient<hector_nav_msgs::GetRobotTrajectory>("trajectory");

    double p_geotiff_save_period = 0.0;
    pn_.param("geotiff_save_period", p_geotiff_save_period, 0.0);

    if(p_geotiff_save_period > 0.0){
      //ros::Timer timer = pn_.createTimer(ros::Duration(p_geotiff_save_period), &MapGenerator::timerSaveGeotiffCallback, false);
      //publish_trajectory_timer_ = private_nh.createTimer(ros::Duration(1.0 / p_trajectory_publish_rate_), &PathContainer::publishTrajectoryTimerCallback, this, false);
      map_save_timer_ = pn_.createTimer(ros::Duration(p_geotiff_save_period), &MapGenerator::timerSaveGeotiffCallback, this, false );
    }

    pn_.param("plugins", p_plugin_list_, std::string(""));

    std::vector<std::string> plugin_list;
    boost::algorithm::split(plugin_list, p_plugin_list_, boost::is_any_of("\t "));

    //We always have at least one element containing "" in the string list
    if ((plugin_list.size() > 0) && (plugin_list[0].length() > 0)){
      plugin_loader_ = new pluginlib::ClassLoader<hector_geotiff::MapWriterPluginInterface>("hector_geotiff", "hector_geotiff::MapWriterPluginInterface");

      for (size_t i = 0; i < plugin_list.size(); ++i){
        try
        {
          boost::shared_ptr<hector_geotiff::MapWriterPluginInterface> tmp (plugin_loader_->createInstance(plugin_list[i]));
          tmp->initialize(plugin_loader_->getName(plugin_list[i]));
          plugin_vector_.push_back(tmp);
        }
        catch(pluginlib::PluginlibException& ex)
        {
          ROS_ERROR("The plugin failed to load for some reason. Error: %s", ex.what());
        }
      }
    }else{
      ROS_INFO("No plugins loaded for geotiff node");
    }

    ROS_INFO("Geotiff node started");
  }

  ~MapGenerator()
  {
    if (plugin_loader_){
      delete plugin_loader_;
    }
  }

  void writeGeotiff()
  {
    ros::Time start_time (ros::Time::now());

    std::stringstream ssStream;

    nav_msgs::GetMap srv_map;
    if (map_service_client_.call(srv_map))
    {
      ROS_INFO("GeotiffNode: Map service called successfully");
      const nav_msgs::OccupancyGrid& map (srv_map.response.map);

      std::string map_file_name = p_map_file_base_name_;
      std::string competition_name;
      std::string team_name;
      std::string mission_name;
      std::string postfix;
      if (n_.getParamCached("/competition", competition_name) && !competition_name.empty()) map_file_name = map_file_name + "_" + competition_name;
      if (n_.getParamCached("/team", team_name)               && !team_name.empty())        map_file_name = map_file_name + "_" + team_name;
      if (n_.getParamCached("/mission", mission_name)         && !mission_name.empty())     map_file_name = map_file_name + "_" + mission_name;
      if (pn_.getParamCached("map_file_postfix", postfix)     && !postfix.empty())          map_file_name = map_file_name + "_" + postfix;
      if (map_file_name.substr(0, 1) == "_") map_file_name = map_file_name.substr(1);
      if (map_file_name.empty()) map_file_name = "GeoTiffMap";
      geotiff_writer_.setMapFileName(map_file_name);
      bool transformSuccess = geotiff_writer_.setupTransforms(map);

      if(!transformSuccess){
        ROS_INFO("Couldn't set map transform");
        return;
      }

      geotiff_writer_.setupImageSize();

      if (p_draw_background_checkerboard_){
        geotiff_writer_.drawBackgroundCheckerboard();
      }

      geotiff_writer_.drawMap(map, p_draw_free_space_grid_);
      geotiff_writer_.drawCoords();

      //ROS_INFO("Sum: %ld", (long int)srv.response.sum);
    }
    else
    {
      ROS_ERROR("Failed to call map service");
      return;
    }

    for (size_t i = 0; i < plugin_vector_.size(); ++i){
      plugin_vector_[i]->draw(&geotiff_writer_);
    }

    /**
      * No Victims for now, first  agree on a common standard for representation
      */
    /*
    if (req_object_model_){
      worldmodel_msgs::GetObjectModel srv_objects;
      if (object_service_client_.call(srv_objects))
      {
        ROS_INFO("GeotiffNode: Object service called successfully");

        const worldmodel_msgs::ObjectModel& objects_model (srv_objects.response.model);

        size_t size = objects_model.objects.size();

        unsigned int victim_num  = 1;

        for (size_t i = 0; i < size; ++i){
          const worldmodel_msgs::Object& object (objects_model.objects[i]);

          if (object.state.state == worldmodel_msgs::ObjectState::CONFIRMED){
            geotiff_writer_.drawVictim(Eigen::Vector2f(object.pose.pose.position.x,object.pose.pose.position.y),victim_num);
            victim_num++;
          }
        }
      }
      else
      {
        ROS_ERROR("Failed to call objects service");
      }
    }
    */

    /*
    hector_nav_msgs::GetRobotTrajectory srv_path;

    if (path_service_client_.call(srv_path))
    {
      ROS_INFO("GeotiffNode: Path service called successfully");

      std::vector<geometry_msgs::PoseStamped>& traj_vector (srv_path.response.trajectory.poses);

      size_t size = traj_vector.size();

      std::vector<Eigen::Vector2f> pointVec;
      pointVec.resize(size);

      for (size_t i = 0; i < size; ++i){
        const geometry_msgs::PoseStamped& pose (traj_vector[i]);

        pointVec[i] = Eigen::Vector2f(pose.pose.position.x, pose.pose.position.y);
      }

      if (size > 0){
        //Eigen::Vector3f startVec(pose_vector[0].x,pose_vector[0].y,pose_vector[0].z);
        Eigen::Vector3f startVec(pointVec[0].x(),pointVec[0].y(),0.0f);
        geotiff_writer_.drawPath(startVec, pointVec);
      }
    }
    else
    {
      ROS_ERROR("Failed to call path service");
    }
    */

    geotiff_writer_.writeGeotiffImage();
    running_saved_map_num_++;

    ros::Duration elapsed_time (ros::Time::now() - start_time);

    ROS_INFO("GeoTiff created in %f seconds", elapsed_time.toSec());
  }

  void timerSaveGeotiffCallback(const ros::TimerEvent& e)
  {
    this->writeGeotiff();
  }

  void sysCmdCallback(const std_msgs::String& sys_cmd)
  {
    if ( !(sys_cmd.data == "savegeotiff")){
      return;
    }

    this->writeGeotiff();
  }

  std::string p_map_file_path_;
  std::string p_map_file_base_name_;
  std::string p_plugin_list_;
  bool p_draw_background_checkerboard_;
  bool p_draw_free_space_grid_;

  //double p_geotiff_save_period_;

  GeotiffWriter geotiff_writer_;

  ros::ServiceClient map_service_client_;// = n.serviceClient<beginner_tutorials::AddTwoInts>("add_two_ints");
  ros::ServiceClient object_service_client_;
  ros::ServiceClient path_service_client_;

  ros::Subscriber sys_cmd_sub_;

  ros::NodeHandle n_;
  ros::NodeHandle pn_;

  std::vector<boost::shared_ptr<hector_geotiff::MapWriterPluginInterface> > plugin_vector_;

  pluginlib::ClassLoader<hector_geotiff::MapWriterPluginInterface>* plugin_loader_;

  ros::Timer map_save_timer_;

  unsigned int running_saved_map_num_;
};

}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "geotiff_node");

  hector_geotiff::MapGenerator mg;

  //ros::NodeHandle pn_;
  //double p_geotiff_save_period = 60.0f;
  //pn_.param("geotiff_save_period", p_geotiff_save_period, 60.0);
  //ros::Timer timer = pn_.createTimer(ros::Duration(p_geotiff_save_period), &MapGenerator::timerSaveGeotiffCallback, &mg, false);

  ros::spin();

  return 0;
}


text:
/**
 * This file is part of the boostcache package.
 *
 * (c) Azat Khuzhin <a3at.mail@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#include "log.h"

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/log/core/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>

#if !defined(BOOST_LOG_NO_THREADS)
#include <boost/log/attributes/current_thread_id.hpp>
#endif

namespace Util
{
    void installLoggerLevel(int level)
    {
        const int maxLevel = 5;
        if (level > maxLevel) {
            level = maxLevel;
        }
        if (level < 0) {
            level = 0;
        }

        namespace trivial = boost::log::trivial;

        /**
         * Reversing because severity_level::trace = 0, while
         * severity_level::fatal = 5, so if we have level=5, we must revers it,
         * and get level=0 (means all messages)
         */
        int severityLevel = (trivial::severity_level)(maxLevel - level);

#define CASE_SEVERITY_LEVEL(level) {                              \
    case trivial::severity_level::level:                          \
        boost::log::core::get()->set_filter(                      \
            trivial::severity >= trivial::severity_level::level   \
        );                                                        \
        break;                                                    \
}

        switch (severityLevel) {
            // 0
            CASE_SEVERITY_LEVEL(trace)
            CASE_SEVERITY_LEVEL(debug)
            CASE_SEVERITY_LEVEL(info)
            CASE_SEVERITY_LEVEL(warning)
            CASE_SEVERITY_LEVEL(error)
            // 5
            CASE_SEVERITY_LEVEL(fatal)
        }
#undef CASE_SEVERITY_LEVEL
    }

    void installLoggerFile(const std::string &fileFormat)
    {
        using namespace boost::log;

        add_common_attributes();

        add_file_log
        (
            keywords::file_name = fileFormat,
            keywords::rotation_size = LOGGER_ROTATION_SIZE,
            keywords::auto_flush = true,
            keywords::open_mode = (std::ios::out | std::ios::app),
            keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0),
            keywords::format = (
                expressions::stream
                    << "[" << expressions::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S.%f") << "] "
#if !defined(BOOST_LOG_NO_THREADS)
                    // TODO: make it like in logger to tty/console
                    << "[" << expressions::attr< thread_id >("ThreadID") << "] "
#endif
                    << "[" << trivial::severity << "]    "
                    << expressions::message
            )
        );
    }
}

max_stars_repo_name: azat/boostcache

max_issues_repo_name: boostcache/boostcache

max_forks_repo_name: boostcache/boostcache


text:
#ifndef HAMILTONIANS_XYZNNNSTO2_HPP
#define HAMILTONIANS_XYZNNNSTO2_HPP
#include <Eigen/Eigen>
#include <nlohmann/json.hpp>

/* Stoquastic for |a|, |b| > 1*/
class XYZNNNSto2
{
private:
	int n_;
	double a_;
	double b_;
	constexpr static double J1 = -1.0;
	constexpr static double J2 = -1.0;
public:

	XYZNNNSto2(int n, double a, double b)
		: n_(n), a_(a), b_(b)
	{
	}

	nlohmann::json params() const
	{
		return nlohmann::json
		{
			{"name", "XYZNNNSto2"},
			{"n", n_},
			{"a", a_},
			{"b", b_}
		};
	}

	template<class State>
	typename State::Scalar operator()(const State& smp) const
	{
		typename State::Scalar s = 0.0;
		//Nearest-neighbor
		for(int i = 0; i < n_; i++)
		{
			double yysign = -smp.sigmaAt(i)*smp.sigmaAt((i+1)%n_);
			s += -J1*b_*yysign; //zz
			s += J1*(a_+1.0*yysign)*smp.ratio(i, (i+1)%n_); //xx+yy
		}
		//Next-nearest-neighbor
		for(int i = 0; i < n_; i++)
		{
			double yysign = -smp.sigmaAt(i)*smp.sigmaAt((i+2)%n_);
			s += -J2*a_*yysign; //zz
			s += J2*(b_+1.0*yysign)*smp.ratio(i, (i+2)%n_); //xx+yy
		}
		return s;
	}

	std::map<uint32_t, double> operator()(uint32_t col) const
	{
		std::map<uint32_t, double> m;
		for(int i = 0; i < n_; i++)
		{
			int b1 = (col >> i) & 1;
			int b2 = (col >> ((i+1)%n_)) & 1;
			int sgn = (1-2*b1)*(1-2*b2);
			long long int x = (1 << i) | (1 << ((i+1)%(n_)));
			m[col ^ x] += J1*(a_ - 1.0*sgn);
			m[col] += J1*b_*sgn;
		}
		for(int i = 0; i < n_; i++)
		{
			int b1 = (col >> i) & 1;
			int b2 = (col >> ((i+2)%n_)) & 1;
			int sgn = (1-2*b1)*(1-2*b2);
			long long int x = (1 << i) | (1 << ((i+2)%(n_)));
			m[col ^ x] += J2*(b_ - sgn*1.0);
			m[col] += J2*a_*sgn;
		}
		return m;
	}
};
#endif//HAMILTONIANS_XYZNNNSTO2_HPP

max_stars_repo_name: cecri/yannq

max_issues_repo_name: cecri/yannq

max_forks_repo_name: cecri/yannq


text:
/*
 * Copyright 2021 IBM Corporation
 *
 * 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 <SPL/Runtime/Common/RuntimeDebugAspect.h>
#include <SPL/Runtime/ProcessingElement/ElasticPortAdapter.h>
#include <SPL/Runtime/ProcessingElement/PEImpl.h>
#include <TRC/DistilleryDebug.h>

#include <boost/thread/thread.hpp>

#include <cmath>
#include <fstream>

using namespace SPL;
#define PERF_GROUP_NUM 9
#define PERF_GROUP_SIZE 40
#define GRANULARITY 0.1

/*Adjustment entry related functions */
ElasticPortAdapter::Adjustment::Adjustment(double& prevThroughput,
                                           std::vector<uint32_t>& operators,
                                           int& groupNum)
  : maxThroughput_(prevThroughput)
  , operators_(operators)
  , curGroup_(groupNum)
{
    initialize();
}

void ElasticPortAdapter::Adjustment::initialize()
{
    lastPositivePos_ = -1;
    size_ = (int)operators_.size();
    currLevel_ = size_;
    currAdjustment_ = new MetaAdjustment(size_, size_, 0, size_, 0);
    adjustInfo_[size_] = currAdjustment_;
    range_.first = 0;
    range_.second = size_;
}

ElasticPortAdapter::Adjustment::~Adjustment()
{
    for (std::map<int, MetaAdjustment*>::iterator it = adjustInfo_.begin(); it != adjustInfo_.end();
         ++it) {
        delete it->second;
    }
}

bool ElasticPortAdapter::Adjustment::trustAbove()
{
    if (adjustInfo_.find(currAdjustment_->aboveLevel) == adjustInfo_.end()) {
        return false;
    }
    return true;
}

bool ElasticPortAdapter::Adjustment::trustBelow()
{
    if (adjustInfo_.find(currAdjustment_->belowLevel) == adjustInfo_.end()) {
        return false;
    }
    return true;
}

bool ElasticPortAdapter::Adjustment::trendAbove()
{
    std::map<int, MetaAdjustment*>::iterator above = adjustInfo_.find(currAdjustment_->aboveLevel);
    if (above == adjustInfo_.end()) {
        return false;
    }

    MetaAdjustment* aboveAdjust = above->second;
    if (aboveAdjust->throughput > curThroughput_ &&
        (aboveAdjust->throughput - curThroughput_) > 0.05 * curThroughput_) {
        return true;
    }

    return false;
}

bool ElasticPortAdapter::Adjustment::trendBelow()
{
    std::map<int, MetaAdjustment*>::iterator below = adjustInfo_.find(currAdjustment_->belowLevel);
    if (below == adjustInfo_.end()) {
        return false;
    }

    MetaAdjustment* belowAdjust = below->second;
    if (curThroughput_ > belowAdjust->throughput &&
        (curThroughput_ - belowAdjust->throughput) > belowAdjust->throughput * 0.05) {
        return true;
    }

    return false;
}

/*
 *Evaluate the performance trend between the MetaAdjustment
 */
ElasticPortAdapter::AdjustDecision ElasticPortAdapter::Adjustment::nextStep(bool furtherRefine)
{
    ElasticPortAdapter::AdjustDecision decision;
    if (!furtherRefine) {
        searchMax(decision);
    } else {
        if ((trendBelow() && !trustAbove()) || trendAbove()) {
            // increase scheduler queue count
            int nextLevel_ = (currAdjustment_->upperBound + currLevel_) / 2;
            if ((nextLevel_ - currLevel_) <= 2) {
                // too small adjustment, stop
                searchMax(decision);
            } else {
                int newAboveLevel = currAdjustment_->upperBound;
                int newBelowLevel = currLevel_;
                MetaAdjustment* tmp = currAdjustment_;
                while (tmp->next != NULL) {
                    tmp = tmp->next;
                    // search for the adjustment above the current level
                    if (tmp->level > nextLevel_ && tmp->level < newAboveLevel) {
                        newAboveLevel = tmp->level;
                    }
                    if (tmp->level < nextLevel_ && tmp->level > newBelowLevel) {
                        newBelowLevel = tmp->level;
                    }
                }

                if ((newAboveLevel - nextLevel_) <= 2 || (nextLevel_ - newBelowLevel) <= 2) {
                    // the difference between previous adjustment is too small, stop
                    searchMax(decision);
                } else {
                    adjustRange_.first = currLevel_;
                    adjustRange_.second = nextLevel_;
                    range_.second = nextLevel_;
                    int newUpperBound = currAdjustment_->upperBound;
                    int newLowerBound = currLevel_;
                    currAdjustment_ = new MetaAdjustment(nextLevel_, newAboveLevel, newBelowLevel,
                                                         newUpperBound, newLowerBound);
                    insertAdjustment(newAboveLevel, newBelowLevel);
                    adjustInfo_[nextLevel_] = currAdjustment_;
                    currLevel_ = nextLevel_;
                    decision = CONTINUE_UP;
                }
            }
        } else if (currLevel_ == size_ || !trustBelow() || !trendBelow()) {
            // decrease the scheduler queue count
            int nextLevel_ = (currAdjustment_->lowerBound + currLevel_) / 2;
            if ((currLevel_ - nextLevel_) <= 2) {
                // too small adjustment, stop
                searchMax(decision);
            } else {
                int newAboveLevel = currLevel_;
                int newBelowLevel = currAdjustment_->lowerBound;
                MetaAdjustment* tmp = currAdjustment_;
                while (tmp->prev != NULL) {
                    tmp = tmp->prev;
                    if (tmp->level > nextLevel_ && tmp->level < newAboveLevel) {
                        newAboveLevel = tmp->level;
                    }
                    if (tmp->level < nextLevel_ && tmp->level > newBelowLevel) {
                        newBelowLevel = tmp->level;
                    }
                }

                if ((newAboveLevel - nextLevel_) <= 2 || (nextLevel_ - newBelowLevel) <= 2) {
                    searchMax(decision);
                } else {
                    adjustRange_.second = currLevel_;
                    adjustRange_.first = nextLevel_;
                    range_.second = nextLevel_;
                    int newUpperBound = currAdjustment_->aboveLevel;
                    int newLowerBound = currAdjustment_->lowerBound;
                    currAdjustment_ = new MetaAdjustment(nextLevel_, newAboveLevel, newBelowLevel,
                                                         newUpperBound, newLowerBound);
                    insertAdjustment(newAboveLevel, newBelowLevel);
                    adjustInfo_[nextLevel_] = currAdjustment_;
                    currLevel_ = nextLevel_;
                    decision = CONTINUE_DOWN;
                }
            }
        } else {
            // trendBelow & !trendAbove
            searchMax(decision);
        }
    }
    return decision;
}

void ElasticPortAdapter::Adjustment::insertAdjustment(int above, int below)
{
    std::map<int, MetaAdjustment*>::iterator it_above = adjustInfo_.find(above);
    std::map<int, MetaAdjustment*>::iterator it_below = adjustInfo_.find(below);
    if (it_above != adjustInfo_.end()) {
        MetaAdjustment* aboveAdjust = it_above->second;
        if (aboveAdjust->prev != NULL) {
            aboveAdjust->prev->next = currAdjustment_;
        }
        currAdjustment_->next = aboveAdjust;
        aboveAdjust->prev = currAdjustment_;
    }

    if (it_below != adjustInfo_.end()) {
        MetaAdjustment* belowAdjust = it_below->second;
        if (belowAdjust->next != NULL) {
            belowAdjust->next->prev = currAdjustment_;
        }
        currAdjustment_->prev = belowAdjust;
        belowAdjust->next = currAdjustment_;
    }
}

void ElasticPortAdapter::Adjustment::extend(std::vector<uint32_t>& ops, int c)
{
    curGroup_ = c;
    operators_.insert(operators_.end(), ops.begin(), ops.end());
    size_ = (int)operators_.size();
    currLevel_ = size_;
    adjustRange_.first = range_.second;
    adjustRange_.second = size_;
    range_.first = 0;
    range_.second = size_;
    for (std::map<int, MetaAdjustment*>::iterator it = adjustInfo_.begin(); it != adjustInfo_.end();
         ++it) {
        delete it->second;
    }
    adjustInfo_.clear();
    currAdjustment_ = new MetaAdjustment(size_, size_, 0, size_, 0);
    adjustInfo_[size_] = currAdjustment_;
}

void ElasticPortAdapter::Adjustment::incStat(double& throughput)
{
    curThroughput_ = throughput;
    currAdjustment_->throughput = throughput;
}

void ElasticPortAdapter::Adjustment::searchMax(ElasticPortAdapter::AdjustDecision& decision)
{
    for (std::map<int, MetaAdjustment*>::iterator it = adjustInfo_.begin(); it != adjustInfo_.end();
         ++it) {
        MetaAdjustment* tmp = it->second;
        if (tmp->throughput > maxThroughput_ &&
            (tmp->throughput - maxThroughput_) > 0.05 * maxThroughput_) {
            maxThroughput_ = tmp->throughput;
            lastPositivePos_ = it->first;
        }
    }
    if (lastPositivePos_ != -1) {
        decision = RESET;
    } else {
        decision = NEG_STOP;
    }
}
/*End Adjustment entry related functions */

/*ElasticPortAdapter related functions */
ElasticPortAdapter::ElasticPortAdapter(ScheduledQueue& sq)
  : _sq(sq)
{
    initialize(UP);
}

void ElasticPortAdapter::initialize(AdjustDirection dir)
{
    _trend = dir;
    _curAdjustment = NULL;
    _recordHist = false;
    _affectedPorts.clear();
}

void ElasticPortAdapter::clear()
{
    _sq.turnOffScheduledPort(_tmpExcludedSet);
    _tmpExcludedSet.clear();
    _affectedPorts.clear();
    initialize(UP);
}

void ElasticPortAdapter::adjust(double& t)
{
    if (_curAdjustment == NULL) {
        addNewAdjustment(t);
    } else {
        refine(t);
    }
}

/*
 *Evaluate whether to continue with QueueElasticity
 */
void ElasticPortAdapter::refine(double& t)
{
    _curAdjustment->incStat(t);
    bool furtherRefine =
      _curAdjustment->getSize() <= GRANULARITY * (int)_sq.getScheduledPortCount() ? false : true;
    AdjustDecision ad = _curAdjustment->nextStep(furtherRefine);
    switch (ad) {
        case CONTINUE:
            break;
        case RESET: {
            resetSchedulerQueuePlacement();
            confirmToRemove(_curAdjustment->getOperators(), _curAdjustment->getRange());

            double maxThroughput = _curAdjustment->getMaxThroughput();
            _affectedPorts.insert(_affectedPorts.end(), _curAdjustment->getOperators().begin(),
                                  _curAdjustment->getOperators().begin() +
                                    _curAdjustment->getEndPos());
            _recordHist = true;

            delete _curAdjustment;
            _curAdjustment = NULL;
            addNewAdjustment(maxThroughput);
        } break;

        case NEG_STOP: {
            bool toExtend =
              (_curAdjustment->getSize() > GRANULARITY * (int)_sq.getScheduledPortCount()) ? false
                                                                                : true;

            if (toExtend && extendAdjustment()) {
                if (_trend == UP) {
                    _sq.turnOnScheduledPort(_curAdjustment->getOperators(),
                                            _curAdjustment->getAdjustRange());
                } else {
                    _sq.turnOffScheduledPort(_curAdjustment->getOperators(),
                                             _curAdjustment->getAdjustRange());
                }
            } else {
                if (_trend == UP) {
                    _sq.turnOffScheduledPort(_curAdjustment->getOperators(),
                                             _curAdjustment->getRange());
                } else {
                    _sq.turnOnScheduledPort(_curAdjustment->getOperators(),
                                            _curAdjustment->getRange());
                }
                double maxThroughput = _curAdjustment->getMaxThroughput();
                delete _curAdjustment;
                _curAdjustment = NULL;
                _sq.adjustingDone(_recordHist, _trend, maxThroughput, _affectedPorts);
                _affectedPorts.clear();
            }
        } break;

        case CONTINUE_DOWN: {
            if (_trend == UP) {
                _sq.turnOffScheduledPort(_curAdjustment->getOperators(),
                                         _curAdjustment->getAdjustRange());
            } else {
                _sq.turnOnScheduledPort(_curAdjustment->getOperators(),
                                        _curAdjustment->getAdjustRange());
            }
        } break;

        case CONTINUE_UP: {
            if (_trend == UP) {
                _sq.turnOnScheduledPort(_curAdjustment->getOperators(),
                                        _curAdjustment->getAdjustRange());
            } else {
                _sq.turnOffScheduledPort(_curAdjustment->getOperators(),
                                         _curAdjustment->getAdjustRange());
            }
        } break;
    }
}

// reset the placement to the best performance configuration
void ElasticPortAdapter::resetSchedulerQueuePlacement()
{
    int end = _curAdjustment->getEndPos();
    int lastPositiveEnd = _curAdjustment->getLastPositivePos();
    if (_trend == UP) {
        if (lastPositiveEnd > end) {
            std::pair<int, int> ret = std::make_pair(end, lastPositiveEnd);
            _sq.turnOnScheduledPort(_curAdjustment->getOperators(), ret);
        } else if (lastPositiveEnd < end) {
            std::pair<int, int> ret = std::make_pair(lastPositiveEnd, end);
            _sq.turnOffScheduledPort(_curAdjustment->getOperators(), ret);
        }
    } else {
        if (lastPositiveEnd > end) {
            std::pair<int, int> ret = std::make_pair(end, lastPositiveEnd);
            _sq.turnOffScheduledPort(_curAdjustment->getOperators(), ret);
        } else if (lastPositiveEnd < end) {
            std::pair<int, int> ret = std::make_pair(lastPositiveEnd, end);
            _sq.turnOnScheduledPort(_curAdjustment->getOperators(), ret);
        }
    }
    _curAdjustment->reset();
}

bool ElasticPortAdapter::extendAdjustment()
{
    int i;
    if (_trend == UP) {
        i = getPrevGroupNum(_curAdjustment->getCurGroupNum());
    } else {
        i = getNextGroupNum(_curAdjustment->getCurGroupNum());
    }
    if (i != -1) {
        std::vector<uint32_t>& operators = _perfGroups[i];
        _curAdjustment->extend(operators, i);
        return true;
    } else {
        return false;
    }
}

void ElasticPortAdapter::addNewAdjustment(double& t)
{
    int curGroup;
    int i;

    groupOperators();

    if (_trend == UP) {
        i = getHeaviestGroupNum();
    } else {
        i = getLightestGroupNum();
    }

    if (i != -1) {
        curGroup = i;
        std::vector<uint32_t>& operators = _perfGroups[i];
        _curAdjustment = new Adjustment(t, operators, curGroup);
        if (_trend == UP) {
            _sq.turnOnScheduledPort(operators, _curAdjustment->getRange());
        } else {
            _sq.turnOffScheduledPort(operators, _curAdjustment->getRange());
        }
    } else {
        // no available queues for adjustment
        _sq.adjustingDone(false, _trend, 0.0, _affectedPorts);
    }
}

int ElasticPortAdapter::getNextGroupNum(int& i)
{
    if (i == PERF_GROUP_NUM - 1) {
        return -1;
    }
    assert(i + 1 >= 0);
    for (unsigned int j = i + 1; j < PERF_GROUP_NUM; j++) {
        assert(j <= PERF_GROUP_NUM - 1);
        if (_perfGroups[j].size() != 0) {
            return j;
        }
    }
    return -1;
}

int ElasticPortAdapter::getPrevGroupNum(int& i)
{
    if (i == 0) {
        return -1;
    }
    assert(i - 1 >= 0);
    for (unsigned int j = i - 1;; j--) {
        assert(j <= PERF_GROUP_NUM - 1);
        if (_perfGroups[j].size() != 0) {
            return j;
        }
        if (j == 0) {
            break;
        }
    }
    return -1;
}

int ElasticPortAdapter::getHeaviestGroupNum()
{
    int heaviestGroup = -1;
    for (unsigned int i = PERF_GROUP_NUM - 1;; i--) {
        if (_perfGroups[i].size() != 0) {
            heaviestGroup = i;
            break;
        }
        if (i == 0) {
            break;
        }
    }
    return heaviestGroup;
}

int ElasticPortAdapter::getLightestGroupNum()
{
    int cheapestGroup = -1;
    for (unsigned int i = 0; i < PERF_GROUP_NUM; i++) {
        if (_perfGroups[i].size() != 0) {
            cheapestGroup = i;
            break;
        }
    }
    return cheapestGroup;
}

void ElasticPortAdapter::groupOperators()
{
    _perfGroups.clear();
    _perfGroups.resize(PERF_GROUP_NUM);

    ThreadProfiler& tp = PEImpl::instance().getThreadProfiler();
    std::vector<double> relativeCost;
    relativeCost.resize(PEImpl::instance().getOperators().size(), 0);
    tp.getOperatorRelativeCost(relativeCost);

    if (_trend == DOWN) {
        //_trend DOWN fill the min bin first
        std::vector<uint32_t> relatedOperators;
        double min = 1;
        for (unsigned int i = 0; i < relativeCost.size(); i++) {
            if (_sq.hasScheduledPort(i)) {
                std::set<uint32_t>::iterator it = _tmpExcludedSet.find(i);
                if (_trend == DOWN && it != _tmpExcludedSet.end()) {
                    relatedOperators.push_back(i);
                    double counter = relativeCost[i];
                    if (counter > 0.0 && min > counter) {
                        min = counter;
                    }
                }
            }
        }

        for (unsigned int i = 0; i < relatedOperators.size(); i++) {
            unsigned int j = relatedOperators[i];
            int base = int(floor((double)relativeCost[j] / (double)min));
            if (base == 0) {
                _perfGroups[0].push_back(j);
            } else {
                base = floor(log2(base) / log2(2)) + 1;
                if (base >= PERF_GROUP_NUM) {
                    base = PERF_GROUP_NUM - 1;
                }
                _perfGroups[base].push_back(j);
            }
        }
    } else {
        //_trend UP fill the max bin first
        std::vector<uint32_t> relatedOperators;
        double max = 0;
        for (unsigned int i = 0; i < relativeCost.size(); i++) {
            if (_sq.hasScheduledPort(i)) {
                std::set<uint32_t>::iterator it = _tmpExcludedSet.find(i);
                if (_trend == UP && it == _tmpExcludedSet.end()) {
                    relatedOperators.push_back(i);
                    double counter = relativeCost[i];
                    if (counter > 0.0 && counter > max) {
                        max = counter;
                    }
                }
            }
        }

        for (unsigned int i = 0; i < relatedOperators.size(); i++) {
            unsigned int j = relatedOperators[i];
            if (relativeCost[j] <= 0.0) {
                _perfGroups[0].push_back(j);
            } else {
                int base = int(floor((double)max / (double)relativeCost[j]));
                base = PERF_GROUP_NUM - base;
                if (base < 0) {
                    base = 0;
                }
                _perfGroups[base].push_back(j);
            }
        }
    }
}

void ElasticPortAdapter::confirmToRemove(vector<uint32_t>& operators, pair<int, int>& range)
{
    if (_trend == UP) {
        _tmpExcludedSet.insert(operators.begin() + range.first, operators.begin() + range.second);
    } else {
        for (int i = range.first; i < range.second; i++) {
            _tmpExcludedSet.erase(operators[i]);
        }
    }
}

void ElasticPortAdapter::confirmToAdd(vector<uint32_t>& operators, pair<int, int>& range)
{
    if (_trend == DOWN) {
        _tmpExcludedSet.insert(operators.begin() + range.first, operators.begin() + range.second);
    } else {
        for (int i = range.first; i < range.second; i++) {
            _tmpExcludedSet.erase(operators[i]);
        }
    }
}

max_stars_repo_name: IBMStreams/OSStreams

max_issues_repo_name: xguerin/openstreams

max_forks_repo_name: IBMStreams/OSStreams


text:
/**
 * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved
 *
 * This file is part of GeoDa.
 *
 * GeoDa is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GeoDa is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/foreach.hpp>

#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include <wx/msgdlg.h>
#include "../DialogTools/ProgressDlg.h"
#include "../GenUtils.h"
#include "../DataViewer/TableInterface.h"
#include "WeightsManState.h"
#include "GeodaWeight.h"
#include "GalWeight.h"
#include "GwtWeight.h"
#include "WeightUtils.h"
#include "WeightsManager.h"
#include "../Project.h"
#include "../SaveButtonManager.h"
#include "../logger.h"
#include "../VarCalc/GdaLexer.h"

WeightsNewManager::WeightsNewManager(WeightsManState* w_man_state_,
									 TableInterface* table_int_)
: w_man_state(w_man_state_), table_int(table_int_)
{
}

WeightsNewManager::~WeightsNewManager()
{

	for (EmTypeCItr it=entry_map.begin(); it != entry_map.end(); ++it) {
        Entry e = it->second;
        if (e.gal_weight) {
            delete e.gal_weight;
            e.gal_weight = NULL;
        }
        if (e.geoda_weight) {
            delete e.geoda_weight;
            e.geoda_weight = NULL;
        }
	}
}

void WeightsNewManager::Init(const std::list<WeightsPtreeEntry>& entries)
{
	entry_map.clear();
	uuid_order.clear();
	// We will ignore existing titles from disk and instead
	// construct titles based on filename.
	std::set<wxString> titles;

	BOOST_FOREACH(const WeightsPtreeEntry& pte, entries) {
		wxString title = wxFileName(pte.wmi.filename).GetName();
		if (title.IsEmpty()) title = "weights";
		if (titles.find(title.Lower()) != titles.end()) {
			bool done = false;
			for (int i=0; i<1000 && !done; ++i) {
				wxString tmp = title;
				tmp << "_" << i+1;
				if (titles.find(tmp.Lower()) == titles.end()) {
					done = true;
					title = tmp;
				}
			}
		}
		titles.insert(title.Lower());
		Entry e(pte);
		e.wpte.title = title;
		boost::uuids::uuid u = boost::uuids::random_generator()();
		entry_map[u] = e;
		uuid_order.push_back(u);
	}
}

std::list<WeightsPtreeEntry> WeightsNewManager::GetPtreeEntries() const
{
	std::list<WeightsPtreeEntry> p;
	BOOST_FOREACH(const boost::uuids::uuid& w_uuid, uuid_order) {
		p.push_back(entry_map.find(w_uuid)->second.wpte);
	}
	return p;
}

/**
 This should only be used by CreatingWeights to associate a newly created
 gal with a newly added weights. If a GalWeight already exists, then it
 will be first deleted.  WeightsNewManager assumes ownership of GalWeight!
 If flase is returned, the caller should free GalWeight.
 */
bool WeightsNewManager::AssociateGal(boost::uuids::uuid w_uuid, GalWeight* gw)
{
	EmType::iterator it = entry_map.find(w_uuid);
	if (it == entry_map.end()) return false;
	if (it->second.gal_weight != 0) {
		delete it->second.gal_weight; it->second.gal_weight = 0;
	}
	it->second.gal_weight = gw;
	if (w_man_state) w_man_state->notifyObservers();
	return true;
}

void WeightsNewManager::GetIds(std::vector<boost::uuids::uuid>& ids) const
{
	ids.clear();
	BOOST_FOREACH(boost::uuids::uuid u, uuid_order) ids.push_back(u);
}

boost::uuids::uuid WeightsNewManager::FindIdByMetaInfo(const WeightsMetaInfo& wmi) const
{
	return FindUuid(wmi);
}

boost::uuids::uuid WeightsNewManager::FindIdByFilename(const wxString& file) const
{
	for (EmTypeCItr it=entry_map.begin(); it != entry_map.end(); ++it) {
		if (it->second.wpte.wmi.filename.CmpNoCase(file) == 0) return it->first;
	}
	return boost::uuids::nil_uuid();
}

boost::uuids::uuid WeightsNewManager::FindIdByTitle(const wxString& title) const
{
	for (EmTypeCItr it=entry_map.begin(); it != entry_map.end(); ++it) {
		if (it->second.wpte.title.CmpNoCase(title) == 0) return it->first;
	}
	return boost::uuids::nil_uuid();
}

boost::uuids::uuid WeightsNewManager::RequestWeights(const WeightsMetaInfo& wmi)
{
    //XXX: seems no need to check again
	//boost::uuids::uuid u = FindUuid(wmi);
	//if (!u.is_nil()) return u;
    boost::uuids::uuid u = boost::uuids::random_generator()();
	WeightsPtreeEntry pte(wmi);
	Entry e(pte);
	e.wpte.title = SuggestTitleFromFileName(wmi.filename);
	entry_map[u] = e;
	uuid_order.push_back(u);
	if (w_man_state) {
		w_man_state->SetAddEvtTyp(u);
		w_man_state->notifyObservers();
	}
	return u;
}

bool WeightsNewManager::WeightsExists(boost::uuids::uuid w_uuid) const
{
	return entry_map.find(w_uuid) != entry_map.end();
}

WeightsMetaInfo WeightsNewManager::GetMetaInfo(boost::uuids::uuid w_uuid) const
{
	if (!WeightsExists(w_uuid)) return WeightsMetaInfo();
	EmTypeCItr ci = entry_map.find(w_uuid);
	return (*ci).second.wpte.wmi;
}

wxString WeightsNewManager::GetShortDispName(boost::uuids::uuid w_uuid) const
{
	return GetTitle(w_uuid);
	//EmTypeCItr ci = entry_map.find(w_uuid);
	//if (ci == entry_map.end()) return "";
	//const WeightsPtreeEntry& pte = ci->second.wpte;
	//if (!pte.title.IsEmpty()) return pte.title;
	//if (!pte.wmi.filename.IsEmpty()) {
	//	return wxFileName(pte.wmi.filename).GetName();
	//}
	//return wxString(boost::uuids::to_string(w_uuid));
}

wxString WeightsNewManager::GetLongDispName(boost::uuids::uuid w_uuid) const
{
	return GetTitle(w_uuid);
	//EmTypeCItr ci = entry_map.find(w_uuid);
	//if (ci == entry_map.end()) return "";
	//const WeightsPtreeEntry& pte = ci->second.wpte;
	//if (!pte.title.IsEmpty()) return pte.title;
	//if (!pte.wmi.filename.IsEmpty()) {
	//	return wxFileName(pte.wmi.filename).GetName();
	//}
	//return wxString(boost::uuids::to_string(w_uuid));
}

std::list<boost::uuids::uuid> WeightsNewManager::GetIds() const
{
	return uuid_order;
}

WeightsMetaInfo::SymmetryEnum
	WeightsNewManager::IsSym(boost::uuids::uuid w_uuid) const
{
	EmTypeCItr it = entry_map.find(w_uuid);
	if (it == entry_map.end()) return WeightsMetaInfo::SYM_unknown;
	return it->second.wpte.wmi.sym_type;
}

WeightsMetaInfo::SymmetryEnum
	WeightsNewManager::CheckSym(boost::uuids::uuid w_uuid, ProgressDlg* p_dlg)
{
	if (IsSym(w_uuid) != WeightsMetaInfo::SYM_unknown) return IsSym(w_uuid);
	EmType::iterator it = entry_map.find(w_uuid);
	if (it == entry_map.end()) return WeightsMetaInfo::SYM_unknown;
	Entry& e = it->second;
	GalWeight* w = GetGal(w_uuid);
	if (w == 0 || w->gal == 0) {
		e.wpte.wmi.sym_type = WeightsMetaInfo::SYM_unknown;
	} else if (GdaWeightsTools::CheckGalSymmetry(w, p_dlg)) {
		e.wpte.wmi.sym_type = WeightsMetaInfo::SYM_symmetric;
	} else {
		e.wpte.wmi.sym_type = WeightsMetaInfo::SYM_asymmetric;
	}
	// if (w_man_state) w_man_state->notifyObservers();
	// should notify SaveButtonManager that meta-data changed.
	return e.wpte.wmi.sym_type;
}

bool WeightsNewManager::Lag(boost::uuids::uuid w_uuid, const GdaFlexValue& data,
							GdaFlexValue& result)
{
	if (!WeightsExists(w_uuid)) {
		return false;
	}
	if (data.GetObs() < 1) {
		return false;
	}
	if (data.GetObs() == 1) {
		// Will assume this is part of initial syntax checking stage and will
		// return original data;
		result = data;
		return true;
	}
	GalWeight* gw = GetGal(w_uuid);
	if (!gw || !gw->gal || !(gw->num_obs = data.GetObs())) {
		return false;
	}
	GalElement* W = gw->gal;
	const std::valarray<double>& x = data.GetConstValArrayRef();
	result.SetSize(data.GetObs(), data.GetTms());
	std::valarray<double>& y = result.GetValArrayRef();
	for (size_t t=0, tms=data.GetTms(); t<tms; ++t) {
		for (size_t i=0, obs=data.GetObs(); i<obs; ++i) {
			double s = 0;
			size_t nbrs = W[i].Size();
			for (size_t n=0; n<nbrs; ++n) {
				s += x[W[i][n]*tms+t];
			}
			y[i*tms+t] = s / ((double) nbrs);
		}
	}
	return true;
}

bool WeightsNewManager::GetCounts(boost::uuids::uuid w_uuid,
								  std::vector<long>& counts)
{
	counts.resize(table_int->GetNumberRows());
	GalWeight* gw = GetGal(w_uuid);
	if (gw == 0) {
		for (size_t i=0, sz=counts.size(); i<sz; ++i) {
			counts[i] = 0;
		}
		return false;
	}
	for (size_t i=0, sz=counts.size(); i<sz; ++i) {
		counts[i] = gw->gal[i].Size();
	}
	return true;
}

void WeightsNewManager::GetNbrsExclCores(boost::uuids::uuid w_uuid,
										 const std::set<long>& cores,
										 std::set<long>& nbrs)
{
	using namespace std;
	nbrs.clear();
	GalWeight* gw = GetGal(w_uuid);
	if (!gw || !gw->gal) return;
	GalElement* W = gw->gal;
	long num_obs = table_int->GetNumberRows();
	BOOST_FOREACH(long c, cores) {
		if (c >= num_obs || c < 0) continue;
		BOOST_FOREACH(long n, W[c].GetNbrs()) {
			if (cores.find(n) == cores.end()) nbrs.insert(n);
		}
	}
}

void WeightsNewManager::Remove(boost::uuids::uuid w_uuid)
{
	EmType::iterator it = entry_map.find(w_uuid);
	if (it == entry_map.end()) return;
	if (it->second.gal_weight) delete it->second.gal_weight;
	entry_map.erase(it);
	for (std::list<boost::uuids::uuid>::iterator it=uuid_order.begin();
		 it != uuid_order.end(); ++it) {
		if (w_uuid == (*it)) {
			uuid_order.erase(it);
			break;
		}
	}
	if (w_man_state) {
		w_man_state->SetRemoveEvtTyp(w_uuid);
		w_man_state->notifyObservers();
	}
}

wxString WeightsNewManager::RecNumToId(boost::uuids::uuid w_uuid, long rec_num)
{
	if (!InitRecNumToIdMap(w_uuid)) {
		wxString r;
		r << rec_num+1;
		return r;
	}
	EmType::iterator it = entry_map.find(w_uuid);
	return it->second.rec_num_to_id[rec_num];
}

/** If gal_weight doesn't yet exist, then create it from meta-data if
 possible. */
GalWeight* WeightsNewManager::GetGal(boost::uuids::uuid w_uuid)
{
	EmType::iterator it = entry_map.find(w_uuid);
	if (it == entry_map.end()) return 0;
	Entry& e = it->second;
    wxString tmpName = e.wpte.wmi.filename;
    if (e.gal_weight) {
        return e.gal_weight;
    }

	// Load file for first use
	wxFileName t_fn(e.wpte.wmi.filename);
	wxString ext = t_fn.GetExt().Lower();
	if (ext != "gal" && ext != "gwt") {
		return 0;
	}
	GalElement* gal=0;
	if (ext == "gal") {
		gal = WeightUtils::ReadGal(e.wpte.wmi.filename, table_int);
	} else { // ext == "gwt"
		gal = WeightUtils::ReadGwtAsGal(e.wpte.wmi.filename, table_int);
	}
	if (gal != 0) {
		GalWeight* w = new GalWeight();
		w->num_obs = table_int->GetNumberRows();
		w->wflnm = e.wpte.wmi.filename;
        w->id_field = e.wpte.wmi.id_var;
		w->title = e.wpte.title;
		w->gal = gal;
		e.gal_weight = w;
	}
	return e.gal_weight;
}

GeoDaWeight* WeightsNewManager::GetWeights(boost::uuids::uuid w_uuid)
{
	EmType::iterator it = entry_map.find(w_uuid);
	if (it == entry_map.end()) return 0;
	Entry& e = it->second;
    wxString tmpName = e.wpte.wmi.filename;

    wxFileName t_fn(tmpName);
    wxString ext = t_fn.GetExt().Lower();
    if (ext != "gal" && ext != "gwt") {
        return 0;
    }

	if (ext == "gal" && e.gal_weight) return e.gal_weight;

	// Load file for first use

	if (ext == "gal") {
        GalElement* gal = WeightUtils::ReadGal(e.wpte.wmi.filename, table_int);
    	if (gal != 0) {
    		GalWeight* w = new GalWeight();
    		w->num_obs = table_int->GetNumberRows();
    		w->wflnm = e.wpte.wmi.filename;
            w->id_field = e.wpte.wmi.id_var;
    		w->title = e.wpte.title;
    		w->gal = gal;
    		e.geoda_weight = (GeoDaWeight*)w;
    	}

	} else { // ext == "gwt"
        GwtElement* gwt = WeightUtils::ReadGwt(e.wpte.wmi.filename, table_int);
    	if (gwt != 0) {
    		GwtWeight* w = new GwtWeight();
    		w->num_obs = table_int->GetNumberRows();
    		w->wflnm = e.wpte.wmi.filename;
            w->id_field = e.wpte.wmi.id_var;
    		w->title = e.wpte.title;
    		w->gwt = gwt;
    		e.geoda_weight = (GeoDaWeight*)w;
    	}
	}
	return e.geoda_weight;
}

boost::uuids::uuid WeightsNewManager::GetDefault() const
{
	for (EmTypeCItr it=entry_map.begin(); it!=entry_map.end(); ++it) {
		if (it->second.wpte.is_default) return it->first;
	}
	if (uuid_order.empty()) {
		return boost::uuids::nil_uuid();
	} else {
		return uuid_order.front();
	}
}

void WeightsNewManager::MakeDefault(boost::uuids::uuid w_uuid)
{
	for (EmType::iterator it=entry_map.begin(); it!=entry_map.end(); ++it) {
		if (it->first == w_uuid) {
			it->second.wpte.is_default = true;
		} else {
			it->second.wpte.is_default = false;
		}
	}
}

boost::uuids::uuid WeightsNewManager::FindByTitle(const wxString& s) const
{
	for (EmTypeCItr it=entry_map.begin(); it!=entry_map.end(); ++it) {
		if (it->second.wpte.title.CmpNoCase(s) == 0) return it->first;
	}
	return boost::uuids::nil_uuid();
}

/** Suggests a new, unique title based on a filename. */
wxString WeightsNewManager::SuggestTitleFromFileName(const wxString& fname) const
{
	std::set<wxString> titles;
	BOOST_FOREACH(const boost::uuids::uuid& w_uuid, uuid_order) {
		titles.insert(GetTitle(w_uuid).Lower());
	}
	wxString title = wxFileName(fname).GetName();
	if (title.IsEmpty()) title = "weights";
	if (titles.find(title.Lower()) != titles.end()) {
		bool done = false;
		for (int i=0; i<1000 && !done; ++i) {
			wxString tmp = title;
			tmp << "_" << i+1;
			if (titles.find(tmp.Lower()) == titles.end()) {
				done = true;
				title = tmp;
			}
		}
	}
	return title;
}

wxString WeightsNewManager::GetTitle(boost::uuids::uuid w_uuid) const
{
	EmTypeCItr it = entry_map.find(w_uuid);
	if (it == entry_map.end()) return "";
	return it->second.wpte.title;
}

void WeightsNewManager::SetTitle(boost::uuids::uuid w_uuid, const wxString& s)
{
	EmType::iterator it = entry_map.find(w_uuid);
	if (it == entry_map.end()) return;
	it->second.wpte.title = s;
	if (w_man_state) {
		w_man_state->SetNameChangeEvtTyp(w_uuid);
		w_man_state->notifyObservers();
	}
}

bool WeightsNewManager::IsValid(boost::uuids::uuid w_uuid)
{
	// some logic to validate weight.  Does it load, are the dimensions correct?
	GalWeight* gw = GetGal(w_uuid);
	if (!gw || !gw->gal) return false;
	return true;
}

boost::uuids::uuid WeightsNewManager::FindUuid(const WeightsMetaInfo& wmi) const
{
	for (EmTypeCItr it=entry_map.begin(); it != entry_map.end(); ++it) {
		if (it->second.wpte.wmi == wmi)
            return it->first;
	}
	return boost::uuids::nil_uuid();
}

GalElement* WeightsNewManager::GetGalElemArray(boost::uuids::uuid w_uuid)
{
	GalWeight* gw = GetGal(w_uuid);
	if (!gw) return 0;
	return gw->gal;
}

/** If false then w_uuid could not be found. */
bool WeightsNewManager::InitRecNumToIdMap(boost::uuids::uuid w_uuid)
{
	EmType::iterator it = entry_map.find(w_uuid);
	if (it == entry_map.end()) return false;
	Entry& e = it->second;
	if (e.rec_num_to_id.size() > 0) return true;
	e.rec_num_to_id.resize(table_int->GetNumberRows());
	int col = table_int->FindColId(e.wpte.wmi.id_var);
	if (col >= 0) {
		if (table_int->GetColType(col) == GdaConst::string_type) {
			std::vector<wxString> v;
			table_int->GetColData(col, 0, v);
			for (size_t i=0, sz=v.size(); i<sz; i++) {
				e.rec_num_to_id[i] = v[i];
			}
		} else if (table_int->GetColType(col) == GdaConst::double_type) {
			std::vector<double> v;
			table_int->GetColData(col, 0, v);
			for (size_t i=0, sz=v.size(); i<sz; i++) {
				e.rec_num_to_id[i] << v[i];
			}
		} else {
			std::vector<wxInt64> v;
			table_int->GetColData(col, 0, v);
			for (size_t i=0, sz=v.size(); i<sz; i++) {
				e.rec_num_to_id[i] << v[i];
			}
		}
		return true;
	}
	for (size_t i=0, sz=e.rec_num_to_id.size(); i<sz; i++) {
		e.rec_num_to_id[i] << (i+1);
	}
	return false;
}

bool GdaWeightsTools::CheckWeightSymmetry(GeoDaWeight* w, ProgressDlg* p_dlg)
{
	if (!w->symmetry_checked) {
		if (w->weight_type == GeoDaWeight::gal_type) {
			w->is_symmetric = CheckGalSymmetry((GalWeight*) w, p_dlg);
		} else {
			w->is_symmetric = CheckGwtSymmetry((GwtWeight*) w, p_dlg);
		}
		w->symmetry_checked = true;
	}
	return w->is_symmetric;
}

bool GdaWeightsTools::CheckGalSymmetry(GalWeight* w, ProgressDlg* p_dlg)
{
    int obs = w->num_obs;
	int update_ival = (obs > 100 ? obs/100 : 1);

	GalElement* gal = w->gal;
	int tenth = GenUtils::max(1, obs/10);
	for (int i=0; i<obs; i++) {
		if (p_dlg && (i % tenth == 0)) {
			p_dlg->ValueUpdate(i/ (double) obs);
		}
		const GalElement& elm_i = gal[i];
		// for each neighbor j of i, check that i is a neighbor of j
		for (int j=0, sz_i=elm_i.Size(); j<sz_i; j++) {
			bool found = false;
			const GalElement& elm_j = gal[elm_i[j]];
			long sz_j = elm_j.Size();
			int k = 0;
			while (!found && k < sz_j) {
				if (elm_j[k++] == i) found = true;
			}
			if (!found) {
				p_dlg->ValueUpdate(1);

				return false;
			}
		}
	}
	p_dlg->ValueUpdate(1);
	return true;
}

bool GdaWeightsTools::CheckGwtSymmetry(GwtWeight* w, ProgressDlg* p_dlg)
{
	int obs = w->num_obs;
	int update_ival = (obs > 100 ? obs/100 : 1);

	GwtElement* gwt = w->gwt;
	int tenth = GenUtils::max(1, obs/10);
	for (int i=0; i<obs; i++) {
		if (p_dlg && (i % tenth == 0)) {
			p_dlg->ValueUpdate(i/ (double) obs);
		}
		GwtNeighbor* data_i = gwt[i].dt();
		long size_i = gwt[i].Size();
		// for each neighbor j of i, check that i is a neighbor of j
		for (int j=0; j<size_i; j++) {
			bool found = false;
			long size_j = gwt[data_i[j].nbx].Size();
			GwtNeighbor* data_j = gwt[data_i[j].nbx].dt();
			int k = 0;
			while (!found && k < size_j) {
				if (data_j[k++].nbx == i) found = true;
			}
			if (!found) {
				p_dlg->ValueUpdate(1);
				return false;
			}
		}
	}
	p_dlg->ValueUpdate(1);
	return true;
}

void GdaWeightsTools::DumpWeight(GeoDaWeight* w)
{
	if (w->weight_type == GeoDaWeight::gal_type) {
		DumpGal((GalWeight*) w);
	} else {
		DumpGwt((GwtWeight*) w);
	}
}

void GdaWeightsTools::DumpGal(GalWeight* w)
{
	GalElement* gal = w->gal;
	int obs = w->num_obs;
	for (int i=0; i<obs; i++) {
		const GalElement& elm_i = gal[i];
		wxString msg("");
		msg << i << ":";
		for (int j=0, jend=elm_i.Size(); j<jend; j++) {
			msg << " " << elm_i[j];
		}
	}
}

void GdaWeightsTools::DumpGwt(GwtWeight* w)
{
	GwtElement* gwt = w->gwt;
	int obs = w->num_obs;
	for (int i=0; i<obs; i++) {
		GwtNeighbor* data_i = gwt[i].dt();
		wxString msg("");
		msg << i << ":";
		for (int j=0, jend=gwt[i].Size(); j<jend; j++) {
			msg << " (" << data_i[j].nbx << ", " << data_i[j].weight << ")";
		}
	}
}

max_stars_repo_name: chenyoujie/GeoDa

max_issues_repo_name: chenyoujie/GeoDa

max_forks_repo_name: chenyoujie/GeoDa


text:
//==============================================================================
//         Copyright 2015 J.T. Lapreste
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#include <boost/simd/arithmetic/include/functions/tenpower.hpp>
#include <boost/simd/sdk/simd/native.hpp>
#include <boost/dispatch/functor/meta/call.hpp>
#include <nt2/sdk/unit/tests/ulp.hpp>
#include <nt2/sdk/unit/tests/type_expr.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <boost/simd/include/constants/one.hpp>
#include <boost/simd/include/constants/oneo_10.hpp>
#include <boost/simd/include/constants/zero.hpp>
#include <boost/simd/include/constants/mone.hpp>
#include <boost/simd/include/constants/two.hpp>
#include <boost/simd/include/constants/three.hpp>
#include <boost/simd/include/constants/hundred.hpp>
#include <boost/simd/include/functions/sqr.hpp>
#include <boost/simd/include/functions/splat.hpp>

NT2_TEST_CASE_TPL ( tenpower_unsigned_int, BOOST_SIMD_SIMD_UINT_CONVERT_TYPES)
{

  using boost::simd::tenpower;
  using boost::simd::tag::tenpower_;
  using boost::simd::native;
  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;
  typedef native<T,ext_t>                  vT;
  typedef typename boost::dispatch::meta::call<tenpower_(vT)>::type r_t;

  // specific values tests
  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::One<vT>()), boost::simd::Ten<r_t>(), 0.5);
  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Two<vT>()), boost::simd::Hundred<r_t>(), 0.5);
  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Zero<vT>()), boost::simd::One<r_t>(), 0.5);
} // end of test for unsigned_int_

NT2_TEST_CASE_TPL ( tenpower_signed_int,  BOOST_SIMD_SIMD_INT_CONVERT_TYPES)
{

  using boost::simd::tenpower;
  using boost::simd::tag::tenpower_;
  using boost::simd::native;
  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;
  typedef native<T,ext_t>                  vT;
  typedef typename boost::dispatch::meta::call<tenpower_(vT)>::type r_t;
  // specific values tests
  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Mone<vT>()), boost::simd::Oneo_10<r_t>(), 0.5);
  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::One<vT>()), boost::simd::Ten<r_t>(), 0.5);
  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Two<vT>()), boost::simd::Hundred<r_t>(), 0.5);
  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Three<vT>()),boost::simd::splat<r_t>(1000.0), 0.5);
  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Mtwo<vT>()), boost::simd::sqr(boost::simd::Oneo_10<r_t>()), 0.5);
  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Zero<vT>()), boost::simd::One<r_t>(), 0.5);
} // end of test for signed_int_


text:
#ifndef TSA_VU8_MODULE_HPP
#define TSA_VU8_MODULE_HPP

#include <v8.h>

#include <vu8/config.hpp>
#include <vu8/detail/MakeArgStorage.hpp>
#include <vu8/detail/Proto.hpp>
#include <vu8/detail/FromV8Arguments.hpp>
#include <vu8/ToV8.hpp>
#include <vu8/Throw.hpp>

#define BOOST_FUSION_INVOKE_MAX_ARITY VU8_PP_ITERATION_LIMIT
#include <boost/fusion/include/invoke.hpp>
#include <boost/fusion/container/vector.hpp>

namespace vu8 {

namespace fu = boost::fusion;
namespace mpl = boost::mpl;

template <class T, class F> struct Class;
template <class T>          struct Singleton;

struct Module {
    // register v8 style callback
    inline Module& operator()(char const            *name,
                              v8::InvocationCallback callback)
    {
        obj_->Set(v8::String::New(name), v8::FunctionTemplate::New(callback));
        return *this;
    }

    template <class T, class F>
    inline Module& operator()(char const *name, Class<T, F>& clss) {
        obj_->Set(v8::String::New(name), clss.JSFunctionTemplate()->GetFunction());

        clss.ClassFunctionTemplate()->SetClassName(v8::String::New(name));
        return *this;
    }

    template <class T>
    inline Module& operator()(char const *name, Singleton<T>& singleton) {
        obj_->Set(v8::String::New(name), singleton.NewInstance());

        singleton.ClassFunctionTemplate()->SetClassName(v8::String::New(name));
        return *this;
    }

    template <class T>
    inline Module& operator()(char const *name, T *t) {
        obj_->Set(v8::String::New(name), v8::External::New(t));
        return *this;
    }

    // Set = operator()
    inline Module& Set(char const *name, v8::InvocationCallback callback) {
        return (*this)(name, callback);
    }

    template <class T, class F>
    inline Module& Set(char const *name, Class<T, F>& clss) {
        return (*this)(name, clss);
    }

    template <class T>
    inline Module& Set(char const *name, T *t) {
        return (*this)(name, t);
    }

    // method with any prototype
    template <class P, typename detail::FunProto<P>::function_type Ptr>
    inline Module& Set(char const *name) {
        return Method< detail::Fun<P, Ptr> >(name);
    }

    // this is a local handle so make it persistent if needs be
    inline v8::Local<v8::Object> NewInstance() {
        return obj_->NewInstance();
    }

  private:
    template <class P>
    static inline typename P::return_type Invoke(const v8::Arguments& args) {
        // TODO: replace with CallFromV8
        typedef typename
            detail::MakeArgStorage<typename P::arguments>::type arg_tl;

        typename fu::result_of::as_vector<arg_tl>::type  cpp_args;
        detail::FromV8Arguments<0>(cpp_args, args);

        return boost::fusion::invoke(P::function_pointer, cpp_args);
    }

    template <class P>
    static inline typename boost::disable_if<
        boost::is_same<void, typename P::return_type>, ValueHandle >::type
    ForwardReturn(const v8::Arguments& args) {
        return ToV8(Invoke<P>(args));
    }

    template <class P>
    static inline typename boost::enable_if<
        boost::is_same<void, typename P::return_type>, ValueHandle >::type
    ForwardReturn(const v8::Arguments& args) {
        Invoke<P>(args);
        return v8::Undefined();
    }

    // TODO: handle adapting return type
    template <class P>
    static inline ValueHandle Forward(const v8::Arguments& args) {
        v8::HandleScope scope;
        try {
            return scope.Close(ForwardReturn<P>(args));
        }
        catch (std::runtime_error const& e) {
            return scope.Close(Throw(e.what()));
        }
    }

    template <class P>
    inline Module& Method(char const *name) {
        obj_->Set(v8::String::New(name), v8::FunctionTemplate::New(&Forward<P>));
        return *this;
    }

  public:
    Module() : obj_(v8::ObjectTemplate::New()) {}

  private:
    v8::Local<v8::ObjectTemplate> obj_;
};

}
#endif