<commit_before>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <Windows.h>
#include <Chaos/Except/SystemError.h>
#include <Chaos/Concurrent/Mutex.h>
#include <Chaos/IO/ColorIO.h>

namespace Chaos::ColorIO {

static Mutex g_color_mutex;

static WORD windows_color(ColorType color) {
  switch (color) {
  case ColorType::COLORTYPE_INVALID:
    __chaos_throw_exception(std::logic_error("invalid color type"));
    break;
  case ColorType::COLORTYPE_FG_BLACK:
    return FOREGROUND_RED & FOREGROUND_GREEN & FOREGROUND_GREEN;
  case ColorType::COLORTYPE_FG_RED:
    return FOREGROUND_RED;
  case ColorType::COLORTYPE_FG_GREEN:
    return FOREGROUND_GREEN;
  case ColorType::COLORTYPE_FG_YELLOW:
    return FOREGROUND_RED | FOREGROUND_GREEN;
  case ColorType::COLORTYPE_FG_BLUE:
    return FOREGROUND_BLUE;
  case ColorType::COLORTYPE_FG_MAGENTA:
    return FOREGROUND_RED | FOREGROUND_BLUE;
  case ColorType::COLORTYPE_FG_CYAN:
    return FOREGROUND_GREEN | FOREGROUND_BLUE;
  case ColorType::COLORTYPE_FG_WHITE:
    return FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
  case ColorType::COLORTYPE_FG_GRAY:
    return FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTRED:
    return FOREGROUND_RED | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTGREEN:
    return FOREGROUND_GREEN | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTYELLOW:
    return FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTBLUE:
    return FOREGROUND_BLUE | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTMAGENTA:
    return FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTCYAN:
    return FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTWHITE:
    return FOREGROUND_RED |
      FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_BLACK:
    return BACKGROUND_RED & BACKGROUND_GREEN & BACKGROUND_BLUE;
  case ColorType::COLORTYPE_BG_RED:
    return BACKGROUND_RED;
  case ColorType::COLORTYPE_BG_GREEN:
    return BACKGROUND_GREEN;
  case ColorType::COLORTYPE_BG_YELLOW:
    return BACKGROUND_RED | BACKGROUND_GREEN;
  case ColorType::COLORTYPE_BG_BLUE:
    return BACKGROUND_BLUE;
  case ColorType::COLORTYPE_BG_MAGENTA:
    return BACKGROUND_RED | BACKGROUND_BLUE;
  case ColorType::COLORTYPE_BG_CYAN:
    return BACKGROUND_GREEN | BACKGROUND_BLUE;
  case ColorType::COLORTYPE_BG_WHITE:
    return BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE;
  case ColorType::COLORTYPE_BG_GRAY:
    return BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTRED:
    return BACKGROUND_RED | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTGREEN:
    return BACKGROUND_GREEN | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTYELLOW:
    return BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTBLUE:
    return BACKGROUND_BLUE | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTMAGENTA:
    return BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTCYAN:
    return BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTWHITE:
    return BACKGROUND_RED |
      BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_COUNTER:
    break;
  }
  return 0;
}

static int vfprintf_impl(
    std::FILE* stream, WORD color, const char* format, std::va_list ap) {
  HANDLE out_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  CONSOLE_SCREEN_BUFFER_INFO info;
  GetConsoleScreenBufferInfo(out_handle, &info);
  WORD old_color = info.wAttributes;

  int n{};
  {
    ScopedLock<Mutex> guard(g_color_mutex);
    SetConsoleTextAttribute(out_handle, color);
    n = std::vfprintf(stream, format, ap);
    SetConsoleTextAttribute(out_handle, old_color);
  }

  return n;
}

int vfprintf(
    std::FILE* stream, ColorType color, const char* format, std::va_list ap) {
  return vfprintf_impl(stream, windows_color(color), format, ap);
}

int vfprintf(std::FILE* stream,
    ColorType fcolor, ColorType bcolor, const char* format, std::va_list ap) {
  auto color = windows_color(fcolor) | windows_color(bcolor);
  return vfprintf_impl(stream, color, format, ap);
}

}
<commit_msg>:construction: chore(colorio): colorio for windows<commit_after>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <Windows.h>
#include <Chaos/Except/SystemError.h>
#include <Chaos/Concurrent/Mutex.h>
#include <Chaos/IO/ColorIO.h>

namespace Chaos::ColorIO {

static Mutex g_color_mutex;

static WORD windows_color(ColorType color) {
  switch (color) {
  case ColorType::COLORTYPE_INVALID:
    __chaos_throw_exception(std::logic_error("invalid color type"));
    break;
  case ColorType::COLORTYPE_FG_BLACK:
    return FOREGROUND_RED & FOREGROUND_GREEN & FOREGROUND_GREEN;
  case ColorType::COLORTYPE_FG_RED:
    return FOREGROUND_RED;
  case ColorType::COLORTYPE_FG_GREEN:
    return FOREGROUND_GREEN;
  case ColorType::COLORTYPE_FG_YELLOW:
    return FOREGROUND_RED | FOREGROUND_GREEN;
  case ColorType::COLORTYPE_FG_BLUE:
    return FOREGROUND_BLUE;
  case ColorType::COLORTYPE_FG_MAGENTA:
    return FOREGROUND_RED | FOREGROUND_BLUE;
  case ColorType::COLORTYPE_FG_CYAN:
    return FOREGROUND_GREEN | FOREGROUND_BLUE;
  case ColorType::COLORTYPE_FG_WHITE:
    return FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
  case ColorType::COLORTYPE_FG_GRAY:
    return FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTRED:
    return FOREGROUND_RED | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTGREEN:
    return FOREGROUND_GREEN | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTYELLOW:
    return FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTBLUE:
    return FOREGROUND_BLUE | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTMAGENTA:
    return FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTCYAN:
    return FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_FG_LIGHTWHITE:
    return FOREGROUND_RED |
      FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_BLACK:
    return BACKGROUND_RED & BACKGROUND_GREEN & BACKGROUND_BLUE;
  case ColorType::COLORTYPE_BG_RED:
    return BACKGROUND_RED;
  case ColorType::COLORTYPE_BG_GREEN:
    return BACKGROUND_GREEN;
  case ColorType::COLORTYPE_BG_YELLOW:
    return BACKGROUND_RED | BACKGROUND_GREEN;
  case ColorType::COLORTYPE_BG_BLUE:
    return BACKGROUND_BLUE;
  case ColorType::COLORTYPE_BG_MAGENTA:
    return BACKGROUND_RED | BACKGROUND_BLUE;
  case ColorType::COLORTYPE_BG_CYAN:
    return BACKGROUND_GREEN | BACKGROUND_BLUE;
  case ColorType::COLORTYPE_BG_WHITE:
    return BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE;
  case ColorType::COLORTYPE_BG_GRAY:
    return BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTRED:
    return BACKGROUND_RED | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTGREEN:
    return BACKGROUND_GREEN | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTYELLOW:
    return BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTBLUE:
    return BACKGROUND_BLUE | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTMAGENTA:
    return BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTCYAN:
    return BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_BG_LIGHTWHITE:
    return BACKGROUND_RED |
      BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY;
  case ColorType::COLORTYPE_COUNTER:
    break;
  }
  return 0;
}

static int vfprintf_impl(
    std::FILE* stream, WORD color, const char* format, std::va_list ap) {
  HANDLE out_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  CONSOLE_SCREEN_BUFFER_INFO info;
  GetConsoleScreenBufferInfo(out_handle, &info);
  WORD old_color = info.wAttributes;

  int n{};
  {
    ScopedLock<Mutex> guard(g_color_mutex);
    SetConsoleTextAttribute(out_handle, color);
    n = std::vfprintf(stream, format, ap);
    SetConsoleTextAttribute(out_handle, old_color);
  }

  return n;
}

int vfprintf(
    std::FILE* stream, ColorType color, const char* format, std::va_list ap) {
  return vfprintf_impl(stream, windows_color(color), format, ap);
}

int vfprintf(std::FILE* stream,
    ColorType fcolor, ColorType bcolor, const char* format, std::va_list ap) {
  auto color = windows_color(fcolor) | windows_color(bcolor);
  return vfprintf_impl(stream, color, format, ap);
}

std::ostream& set_colorful(std::ostream& stream, ColorType color) noexcept {
  static WORD wDefaultAttributes = 0;

  HANDLE hTerminal = INVALID_HANDLE_VALUE;
  if (&stream == &std::cout)
    hTerminal = ::GetStdHandle(STD_OUTPUT_HANDLE);
  else if (&stream == &std::cerr)
    hTerminal = ::GetStdHandle(STD_ERROR_HANDLE);

  if (!wDefaultAttributes) {
    CONSOLE_SCREEN_BUFFER_INFO info;
    if (!::GetConsoleScreenBufferInfo(hTerminal, &info))
      return stream;
    wDefaultAttributes = info.wAttributes;
  }

  WORD wAttributes;
  if (color == ColorType::COLORTYPE_RESET)
    wAttributes = wDefaultAttributes;
  else
    wAttributes = windows_color(color);

  {
    ScopedLock<Mutex> guard(g_color_mutex);
    SetConsoleTextAttribute(hTerminal, wAttributes);
  }

  return stream;
}

std::ostream& set_foreground_colorful(std::ostream& stream, ColorType color) noexcept {
  return set_colorful(stream, color);
}

std::ostream& set_background_colorful(std::ostream& stream, ColorType color) noexcept {
  return set_colorful(stream, color);
}

}
<|endoftext|>


<commit_before>/*
 * Bayes++ the Bayesian Filtering Library
 * Copyright (c) 2004 Michael Stevens
 * See accompanying Bayes++.html for terms and conditions of use.
 *
 * $Header$
 */

/*
 * SLAM : Simultaneous Locatization and Mapping
 *  Kalman filter representing representation of SLAM
 */

		// Bayes++ Bayesian filtering schemes
#include "BayesFilter/bayesFlt.hpp"
		// Bayes++ SLAM
#include "SLAM.hpp"
#include "kalmanSLAM.hpp"

namespace SLAM_filter
{

template <class Base>
inline void zero(FM::ublas::matrix_range<Base> A)
// Zero a matrix_range
{	// Note A cannot be a reference
	typedef typename Base::value_type Base_value_type;
//TODO	FM::noalias(A) = FM::ublas::scalar_matrix<Base_value_type>(A.size1(),A.size2(), Base_value_type(0));
	FM::noalias(A) = FM::ublas::zero_matrix<Base_value_type>(A.size1(),A.size2());
}

Kalman_SLAM::Kalman_SLAM( Kalman_filter_generator& filter_generator ) :
	SLAM(),
	fgenerator(filter_generator),
	full(0)
{
	nL = 0;
	nM = 0;
}

Kalman_SLAM::~Kalman_SLAM()
{
	fgenerator.dispose (full);
}

void Kalman_SLAM::init_kalman (const FM::Vec& x, const FM::SymMatrix& X)
{
	// TODO maintain map states on reinit
	nL = x.size();
	nM = 0;
	if (full) fgenerator.dispose (full);
		// generate full filter
	full = fgenerator.generate(nL);
		// initialise location states
	FM::noalias (full->x.sub_range(0,nL)) = x;
	FM::noalias (full->X.sub_matrix(0,nL,0,nL)) = X;
	full->init();
}

void Kalman_SLAM::predict( BF::Linear_predict_model& lpred )
{
		// build full predict model by augmenting location predict with map identity predict model
	BF::Linear_predict_model fullpred (full->x.size(), lpred.q.size());
	FM::identity (fullpred.Fx);
	fullpred.Fx.sub_matrix(0,lpred.Fx.size1(),0,lpred.Fx.size2()) = lpred.Fx;
	fullpred.G.clear ();
	fullpred.G.sub_matrix(0,lpred.G.size1(), 0,lpred.G.size2()) = lpred.G;
	fullpred.q = lpred.q;
		// predict
	full->predict (fullpred);
}

void Kalman_SLAM::observe( unsigned feature, const Feature_observe& fom, const FM::Vec& z )
{
	const std::size_t z_size = z.size();
		// size consistency, single state feature
	if (fom.Hx.size1() != z_size)
		error (BF::Logic_exception("observation and model size inconsistent"));
	if (fom.Hx.size2() != nL+1)
		error (BF::Logic_exception("fom and location  size inconsistent"));

	if (feature >= nM) {
		error (BF::Logic_exception("Observe non existing feature"));
		return;
	}
	// TODO Implement nonlinear form
		// create a augmented sparse observe model for full states
	BF::Linear_uncorrelated_observe_model fullobs(full->x.size(), z_size);
	fullobs.Hx.clear();
	fullobs.Hx.sub_matrix(0,z_size, 0,nL) = fom.Hx.sub_matrix(0,z_size, 0,nL);
	fullobs.Hx.sub_matrix(0,z_size, nL+feature,nL+feature+1) = fom.Hx.sub_matrix(0,z_size, nL,nL+1);
	fullobs.Zv = fom.Zv;
	full->observe(fullobs, z);
}

void Kalman_SLAM::observe_new( unsigned feature, const Feature_observe_inverse& fom, const FM::Vec& z )
// fom: must have a the special from required for SLAM::obeserve_new
// Feature numbers must be sequential for efficiency, otherwise state is sparse
{
		// size consistency, single state feature
	if (fom.Hx.size1() != 1)
		error (BF::Logic_exception("observation and model size inconsistent"));

		// make new filter with additional (uninitialized) feature state
	if (feature >= nM)
	{
		nM = feature+1;
		Kalman_filter_generator::Filter_type* nf = fgenerator.generate(nL+nM);
		FM::noalias(nf->x.sub_range(0,full->x.size())) = full->x;
		FM::noalias(nf->X.sub_matrix(0,full->x.size(),0,full->x.size())) = full->X;

		fgenerator.dispose(full);
		full = nf;
	}
		// build augmented location and observation
	FM::Vec sz(nL+z.size());
	sz.sub_range(0,nL) = full->x.sub_range(0,nL);
	sz.sub_range(nL,nL+z.size() )= z;

	// TODO use named references rather then explict Ha Hb
	FM::Matrix Ha (fom.Hx.sub_matrix(0,1, 0,nL) );
	FM::Matrix Hb (fom.Hx.sub_matrix(0,1, nL,nL+z.size()) );
	FM::Matrix tempHa (1,nL);
	FM::Matrix tempHb (1,sz.size());

		// feature covariance with existing location and features
        // X+ = [0 Ha] X [0 Ha]' + Hb Z Hb'
        // - zero exisiting feature covariance
	zero( full->X.sub_matrix(0,full->X.size1(), nL+feature,nL+feature+1) );
	// full->X.sub_matrix(nL+feature,nL+feature+1,0,nL+nM) = prod(Ha,full->X.sub_matrix(0,nL, 0,nL+nM) );
	{	// ISSUE uBLAS has problems assigning to symmetric proxy as above, go element by element
		const FM::Matrix cross (FM::prod(Ha, full->X.sub_matrix(0,nL, 0,nL+nM)) );
		for (std::size_t i = 0; i != nL+nM-1; ++i)
			full->X(nL+feature, i) = cross(0,i);
	}
		// feature state and variance
	full->x[nL+feature] = fom.h(sz)[0];
	full->X(nL+feature,nL+feature) = ( FM::prod_SPD(Ha,full->X.sub_matrix(0,nL, 0,nL),tempHa) +
													  FM::prod_SPD(Hb,fom.Zv,tempHb)
													 ) (0,0);

	full->init ();
}

void Kalman_SLAM::observe_new( unsigned feature, const FM::Float& t, const FM::Float& T )
// Feature numbers must be sequential for efficiency, otherwise state is sparse
{
		// make new filter with additional feature state
	if (feature >= nM)
	{
		nM = feature+1;
		Kalman_filter_generator::Filter_type* nf = fgenerator.generate(nL+nM);
		FM::noalias(nf->x.sub_range(0,full->x.size())) = full->x;
		FM::noalias(nf->X.sub_matrix(0,full->x.size(),0,full->x.size())) = full->X;
		zero( nf->X.sub_matrix(0,nf->X.size1(), nL+nM,nf->X.size2()) );

		fgenerator.dispose(full);
		full = nf;
	}
	else
	{
		full->x[nL+feature] = t;
		full->X(nL+feature,nL+feature) = T;
	}
	full->init ();
}

void Kalman_SLAM::forget( unsigned feature, bool must_exist )
{
	full->x[nL+feature] = 0.;
			// zero upper row and column
	zero( full->X.sub_matrix(0,nL+feature, nL+feature,nL+feature+1) );
	zero( full->X.sub_matrix(nL+feature,nL+feature+1, nL+feature,full->X.size1()) );
	full->init();
}

void Kalman_SLAM::statistics_sparse( BF::Kalman_state& kstats ) const
{
	const std::size_t k = std::min(kstats.x.size(), full->x.size());
	kstats.x.clear(); kstats.X.clear();
	kstats.x.sub_range(0,k) = full->x.sub_range(0,k);
	kstats.X.sub_matrix(0,k, 0,k) = full->X.sub_matrix(0,k, 0,k);
}

void Kalman_SLAM::decorrelate( Bayesian_filter::Bayes_base::Float d )
// Reduce correlation by scaling cross-correlation terms
{
	std::size_t i,j;
	const std::size_t n = full->X.size1();
	for (i = 1; i < n; ++i)
	{
		FM::SymMatrix::Row Xi(full->X,i);
		for (j = 0; j < i; ++j)
		{
			Xi[j] *= d;
		}
		for (j = i+1; j < n; ++j)
		{
			Xi[j] *= d;
		}
	}
	full->init();
}

}//namespace SLAM
<commit_msg>Remove TODO<commit_after>/*
 * Bayes++ the Bayesian Filtering Library
 * Copyright (c) 2004 Michael Stevens
 * See accompanying Bayes++.html for terms and conditions of use.
 *
 * $Header$
 */

/*
 * SLAM : Simultaneous Locatization and Mapping
 *  Kalman filter representing representation of SLAM
 */

		// Bayes++ Bayesian filtering schemes
#include "BayesFilter/bayesFlt.hpp"
		// Bayes++ SLAM
#include "SLAM.hpp"
#include "kalmanSLAM.hpp"

namespace SLAM_filter
{

template <class Base>
inline void zero(FM::ublas::matrix_range<Base> A)
// Zero a matrix_range
{	// Note A cannot be a reference
	typedef typename Base::value_type Base_value_type;
	FM::noalias(A) = FM::ublas::zero_matrix<Base_value_type>(A.size1(),A.size2());
}

Kalman_SLAM::Kalman_SLAM( Kalman_filter_generator& filter_generator ) :
	SLAM(),
	fgenerator(filter_generator),
	full(0)
{
	nL = 0;
	nM = 0;
}

Kalman_SLAM::~Kalman_SLAM()
{
	fgenerator.dispose (full);
}

void Kalman_SLAM::init_kalman (const FM::Vec& x, const FM::SymMatrix& X)
{
	// TODO maintain map states on reinit
	nL = x.size();
	nM = 0;
	if (full) fgenerator.dispose (full);
		// generate full filter
	full = fgenerator.generate(nL);
		// initialise location states
	FM::noalias (full->x.sub_range(0,nL)) = x;
	FM::noalias (full->X.sub_matrix(0,nL,0,nL)) = X;
	full->init();
}

void Kalman_SLAM::predict( BF::Linear_predict_model& lpred )
{
		// build full predict model by augmenting location predict with map identity predict model
	BF::Linear_predict_model fullpred (full->x.size(), lpred.q.size());
	FM::identity (fullpred.Fx);
	fullpred.Fx.sub_matrix(0,lpred.Fx.size1(),0,lpred.Fx.size2()) = lpred.Fx;
	fullpred.G.clear ();
	fullpred.G.sub_matrix(0,lpred.G.size1(), 0,lpred.G.size2()) = lpred.G;
	fullpred.q = lpred.q;
		// predict
	full->predict (fullpred);
}

void Kalman_SLAM::observe( unsigned feature, const Feature_observe& fom, const FM::Vec& z )
{
	const std::size_t z_size = z.size();
		// size consistency, single state feature
	if (fom.Hx.size1() != z_size)
		error (BF::Logic_exception("observation and model size inconsistent"));
	if (fom.Hx.size2() != nL+1)
		error (BF::Logic_exception("fom and location  size inconsistent"));

	if (feature >= nM) {
		error (BF::Logic_exception("Observe non existing feature"));
		return;
	}
	// TODO Implement nonlinear form
		// create a augmented sparse observe model for full states
	BF::Linear_uncorrelated_observe_model fullobs(full->x.size(), z_size);
	fullobs.Hx.clear();
	fullobs.Hx.sub_matrix(0,z_size, 0,nL) = fom.Hx.sub_matrix(0,z_size, 0,nL);
	fullobs.Hx.sub_matrix(0,z_size, nL+feature,nL+feature+1) = fom.Hx.sub_matrix(0,z_size, nL,nL+1);
	fullobs.Zv = fom.Zv;
	full->observe(fullobs, z);
}

void Kalman_SLAM::observe_new( unsigned feature, const Feature_observe_inverse& fom, const FM::Vec& z )
// fom: must have a the special from required for SLAM::obeserve_new
// Feature numbers must be sequential for efficiency, otherwise state is sparse
{
		// size consistency, single state feature
	if (fom.Hx.size1() != 1)
		error (BF::Logic_exception("observation and model size inconsistent"));

		// make new filter with additional (uninitialized) feature state
	if (feature >= nM)
	{
		nM = feature+1;
		Kalman_filter_generator::Filter_type* nf = fgenerator.generate(nL+nM);
		FM::noalias(nf->x.sub_range(0,full->x.size())) = full->x;
		FM::noalias(nf->X.sub_matrix(0,full->x.size(),0,full->x.size())) = full->X;

		fgenerator.dispose(full);
		full = nf;
	}
		// build augmented location and observation
	FM::Vec sz(nL+z.size());
	sz.sub_range(0,nL) = full->x.sub_range(0,nL);
	sz.sub_range(nL,nL+z.size() )= z;

	// TODO use named references rather then explict Ha Hb
	FM::Matrix Ha (fom.Hx.sub_matrix(0,1, 0,nL) );
	FM::Matrix Hb (fom.Hx.sub_matrix(0,1, nL,nL+z.size()) );
	FM::Matrix tempHa (1,nL);
	FM::Matrix tempHb (1,sz.size());

		// feature covariance with existing location and features
        // X+ = [0 Ha] X [0 Ha]' + Hb Z Hb'
        // - zero exisiting feature covariance
	zero( full->X.sub_matrix(0,full->X.size1(), nL+feature,nL+feature+1) );
	// full->X.sub_matrix(nL+feature,nL+feature+1,0,nL+nM) = prod(Ha,full->X.sub_matrix(0,nL, 0,nL+nM) );
	{	// ISSUE uBLAS has problems assigning to symmetric proxy as above, go element by element
		const FM::Matrix cross (FM::prod(Ha, full->X.sub_matrix(0,nL, 0,nL+nM)) );
		for (std::size_t i = 0; i != nL+nM-1; ++i)
			full->X(nL+feature, i) = cross(0,i);
	}
		// feature state and variance
	full->x[nL+feature] = fom.h(sz)[0];
	full->X(nL+feature,nL+feature) = ( FM::prod_SPD(Ha,full->X.sub_matrix(0,nL, 0,nL),tempHa) +
													  FM::prod_SPD(Hb,fom.Zv,tempHb)
													 ) (0,0);

	full->init ();
}

void Kalman_SLAM::observe_new( unsigned feature, const FM::Float& t, const FM::Float& T )
// Feature numbers must be sequential for efficiency, otherwise state is sparse
{
		// make new filter with additional feature state
	if (feature >= nM)
	{
		nM = feature+1;
		Kalman_filter_generator::Filter_type* nf = fgenerator.generate(nL+nM);
		FM::noalias(nf->x.sub_range(0,full->x.size())) = full->x;
		FM::noalias(nf->X.sub_matrix(0,full->x.size(),0,full->x.size())) = full->X;
		zero( nf->X.sub_matrix(0,nf->X.size1(), nL+nM,nf->X.size2()) );

		fgenerator.dispose(full);
		full = nf;
	}
	else
	{
		full->x[nL+feature] = t;
		full->X(nL+feature,nL+feature) = T;
	}
	full->init ();
}

void Kalman_SLAM::forget( unsigned feature, bool must_exist )
{
	full->x[nL+feature] = 0.;
			// zero upper row and column
	zero( full->X.sub_matrix(0,nL+feature, nL+feature,nL+feature+1) );
	zero( full->X.sub_matrix(nL+feature,nL+feature+1, nL+feature,full->X.size1()) );
	full->init();
}

void Kalman_SLAM::statistics_sparse( BF::Kalman_state& kstats ) const
{
	const std::size_t k = std::min(kstats.x.size(), full->x.size());
	kstats.x.clear(); kstats.X.clear();
	kstats.x.sub_range(0,k) = full->x.sub_range(0,k);
	kstats.X.sub_matrix(0,k, 0,k) = full->X.sub_matrix(0,k, 0,k);
}

void Kalman_SLAM::decorrelate( Bayesian_filter::Bayes_base::Float d )
// Reduce correlation by scaling cross-correlation terms
{
	std::size_t i,j;
	const std::size_t n = full->X.size1();
	for (i = 1; i < n; ++i)
	{
		FM::SymMatrix::Row Xi(full->X,i);
		for (j = 0; j < i; ++j)
		{
			Xi[j] *= d;
		}
		for (j = i+1; j < n; ++j)
		{
			Xi[j] *= d;
		}
	}
	full->init();
}

}//namespace SLAM
<|endoftext|>


<commit_before>// Time:  O(nlogn)
// Space: O(n)

// BST solution.
class Solution {
public:
    vector<pair<int, int> > getSkyline(vector<vector<int> >& buildings) {
        unordered_map<int, vector<int>> start_point_to_heights;
        unordered_map<int, vector<int>> end_point_to_heights;
        set<int> points;

        for (int i = 0; i < buildings.size(); ++i) {
            start_point_to_heights[buildings[i][0]].emplace_back(buildings[i][2]);
            end_point_to_heights[buildings[i][1]].emplace_back(buildings[i][2]);
            points.emplace(buildings[i][0]);
            points.emplace(buildings[i][1]);
        }

        vector<pair<int, int>> res;
        map<int, int> height_to_count;
        int curr_max = 0;
        // Enumerate each point in increasing order.
        for (auto it = points.begin(); it != points.end(); ++it) {
            vector<int> start_point_heights = start_point_to_heights[*it];
            vector<int> end_point_heights = end_point_to_heights[*it];

            for (int i = 0; i < start_point_heights.size(); ++i) {
                ++height_to_count[start_point_heights[i]];
            }

            for (int i = 0; i < end_point_heights.size(); ++i) {
                --height_to_count[end_point_heights[i]];
                if (height_to_count[end_point_heights[i]] == 0) {
                    height_to_count.erase(end_point_heights[i]);
                }
            }

            if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) {
                curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first;
                res.emplace_back(*it, curr_max);
            }
        }
        return res;
    }
};

// Time:  O(nlogn)
// Space: O(n)
// Divide and conquer solution.
class Solution2 {
public:
    enum {start, end, height};

    vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
        const auto intervals = move(ComputeSkylineInInterval(buildings, 0, buildings.size()));

        vector<pair<int, int>> res;
        int last_end = -1;
        for (const auto& interval : intervals) {
            if (last_end != -1 && last_end < interval[start]) {
                res.emplace_back(last_end, 0);
            }
            res.emplace_back(interval[start], interval[height]);
            last_end = interval[end];
        }
        if (last_end != -1) {
            res.emplace_back(last_end, 0);
        }
        return res;
    }

    // Divide and Conquer.
    vector<vector<int>> ComputeSkylineInInterval(const vector<vector<int>>& buildings,
                                                 int left_endpoint, int right_endpoint) {
        if (right_endpoint - left_endpoint <= 1) {  // 0 or 1 skyline, just copy it.
            return {buildings.cbegin() + left_endpoint,
                    buildings.cbegin() + right_endpoint};
        }
        int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2);
        auto left_skyline = move(ComputeSkylineInInterval(buildings, left_endpoint, mid));
        auto right_skyline = move(ComputeSkylineInInterval(buildings, mid, right_endpoint));
        return MergeSkylines(left_skyline, right_skyline);
    }

    // Merge Sort
    vector<vector<int>> MergeSkylines(vector<vector<int>>& left_skyline, vector<vector<int>>& right_skyline) {
        int i = 0, j = 0;
        vector<vector<int>> merged;

        while (i < left_skyline.size() && j < right_skyline.size()) {
            if (left_skyline[i][end] < right_skyline[j][start]) {
                merged.emplace_back(move(left_skyline[i++]));
            } else if (right_skyline[j][end] < left_skyline[i][start]) {
                merged.emplace_back(move(right_skyline[j++]));
            } else if (left_skyline[i][start] <= right_skyline[j][start]) {
                MergeIntersectSkylines(merged, left_skyline[i], i,
                                       right_skyline[j], j);
            } else {  // left_skyline[i][start] > right_skyline[j][start].
                MergeIntersectSkylines(merged, right_skyline[j], j,
                                       left_skyline[i], i);
            }
        }

        // Insert the remaining skylines.
        merged.insert(merged.end(), left_skyline.begin() + i, left_skyline.end());
        merged.insert(merged.end(), right_skyline.begin() + j, right_skyline.end());
        return merged;
    }

    // a[start] <= b[start]
    void MergeIntersectSkylines(vector<vector<int>>& merged, vector<int>& a, int& a_idx,
                                vector<int>& b, int& b_idx) {
        if (a[end] <= b[end]) {
            if (a[height] > b[height]) {  // |aaa|
                if (b[end] != a[end]) {   // |abb|b
                    b[start] = a[end];
                    merged.emplace_back(move(a)), ++a_idx;
                } else {        // aaa
                    ++b_idx;    // abb
                }
            } else if (a[height] == b[height]) { // abb
                b[start] = a[start], ++a_idx;    // abb
            } else {  // a[height] < b[height].
                if (a[start] != b[start]) {                                           //    bb
                    merged.emplace_back(move(vector<int>{a[start], b[start], a[height]}));  // |a|bb
                }
                ++a_idx;
            }
        } else {  // a[end] > b[end].
            if (a[height] >= b[height]) {  // aaaa
                ++b_idx;                   // abba
            } else {
                //    |bb|
                // |a||bb|a
                if (a[start] != b[start]) {
                    merged.emplace_back(move(vector<int>{a[start], b[start], a[height]}));
                }
                a[start] = b[end];
                merged.emplace_back(move(b)), ++b_idx;
            }
        }
    }
};
<commit_msg>Update the-skyline-problem.cpp<commit_after>// Time:  O(nlogn)
// Space: O(n)

// BST solution.
class Solution {
public:
    vector<pair<int, int> > getSkyline(vector<vector<int> >& buildings) {
        unordered_map<int, vector<int>> start_point_to_heights;
        unordered_map<int, vector<int>> end_point_to_heights;
        set<int> points;

        for (int i = 0; i < buildings.size(); ++i) {
            start_point_to_heights[buildings[i][0]].emplace_back(buildings[i][2]);
            end_point_to_heights[buildings[i][1]].emplace_back(buildings[i][2]);
            points.emplace(buildings[i][0]);
            points.emplace(buildings[i][1]);
        }

        vector<pair<int, int>> res;
        map<int, int> height_to_count;
        int curr_max = 0;
        // Enumerate each point in increasing order.
        for (auto it = points.begin(); it != points.end(); ++it) {
            vector<int> start_point_heights = start_point_to_heights[*it];
            vector<int> end_point_heights = end_point_to_heights[*it];

            for (int i = 0; i < start_point_heights.size(); ++i) {
                ++height_to_count[start_point_heights[i]];
            }

            for (int i = 0; i < end_point_heights.size(); ++i) {
                --height_to_count[end_point_heights[i]];
                if (height_to_count[end_point_heights[i]] == 0) {
                    height_to_count.erase(end_point_heights[i]);
                }
            }

            if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) {
                curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first;
                res.emplace_back(*it, curr_max);
            }
        }
        return res;
    }
};

// Time:  O(nlogn)
// Space: O(n)
// Divide and conquer solution.
class Solution2 {
public:
    enum {start, end, height};

    vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
        const auto intervals = move(ComputeSkylineInInterval(buildings, 0, buildings.size()));

        vector<pair<int, int>> res;
        int last_end = -1;
        for (const auto& interval : intervals) {
            if (last_end != -1 && last_end < interval[start]) {
                res.emplace_back(last_end, 0);
            }
            res.emplace_back(interval[start], interval[height]);
            last_end = interval[end];
        }
        if (last_end != -1) {
            res.emplace_back(last_end, 0);
        }
        return res;
    }

    // Divide and Conquer.
    vector<vector<int>> ComputeSkylineInInterval(const vector<vector<int>>& buildings,
                                                 int left_endpoint, int right_endpoint) {
        if (right_endpoint - left_endpoint <= 1) {  // 0 or 1 skyline, just copy it.
            return {buildings.cbegin() + left_endpoint,
                    buildings.cbegin() + right_endpoint};
        }
        int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2);
        auto left_skyline = move(ComputeSkylineInInterval(buildings, left_endpoint, mid));
        auto right_skyline = move(ComputeSkylineInInterval(buildings, mid, right_endpoint));
        return MergeSkylines(left_skyline, right_skyline);
    }

    // Merge Sort
    vector<vector<int>> MergeSkylines(vector<vector<int>>& left_skyline, vector<vector<int>>& right_skyline) {
        int i = 0, j = 0;
        vector<vector<int>> merged;

        while (i < left_skyline.size() && j < right_skyline.size()) {
            if (left_skyline[i][end] < right_skyline[j][start]) {
                merged.emplace_back(move(left_skyline[i++]));
            } else if (right_skyline[j][end] < left_skyline[i][start]) {
                merged.emplace_back(move(right_skyline[j++]));
            } else if (left_skyline[i][start] <= right_skyline[j][start]) {
                MergeIntersectSkylines(merged, left_skyline[i], i,
                                       right_skyline[j], j);
            } else {  // left_skyline[i][start] > right_skyline[j][start].
                MergeIntersectSkylines(merged, right_skyline[j], j,
                                       left_skyline[i], i);
            }
        }

        // Insert the remaining skylines.
        merged.insert(merged.end(), left_skyline.begin() + i, left_skyline.end());
        merged.insert(merged.end(), right_skyline.begin() + j, right_skyline.end());
        return merged;
    }

    // a[start] <= b[start]
    void MergeIntersectSkylines(vector<vector<int>>& merged, vector<int>& a, int& a_idx,
                                vector<int>& b, int& b_idx) {
        if (a[end] <= b[end]) {
            if (a[height] > b[height]) {  // |aaa|
                if (b[end] != a[end]) {   // |abb|b
                    b[start] = a[end];
                    merged.emplace_back(move(a)), ++a_idx;
                } else {        // aaa
                    ++b_idx;    // abb
                }
            } else if (a[height] == b[height]) { // abb
                b[start] = a[start], ++a_idx;    // abb
            } else {  // a[height] < b[height].
                if (a[start] != b[start]) {                                                 //    bb
                    merged.emplace_back(move(vector<int>{a[start], b[start], a[height]}));  // |a|bb
                }
                ++a_idx;
            }
        } else {  // a[end] > b[end].
            if (a[height] >= b[height]) {  // aaaa
                ++b_idx;                   // abba
            } else {
                //    |bb|
                // |a||bb|a
                if (a[start] != b[start]) {
                    merged.emplace_back(move(vector<int>{a[start], b[start], a[height]}));
                }
                a[start] = b[end];
                merged.emplace_back(move(b)), ++b_idx;
            }
        }
    }
};
<|endoftext|>


<commit_before>//=====================================================================//
/*! @file
    @brief  ファースト・サンプル（LED 点滅） @n
			RX64M, RX71M, RX72M: @n
					12MHz のベースクロックを使用する @n
			　　　　P07 ピンにLEDを接続する @n
			RX65N (Renesas Envision kit RX65N): @n
					12MHz のベースクロックを使用する @n
			　　　　P70 に接続された LED を利用する @n
			RX63T @n
					12MHz のベースクロックを使用する @n
					PB7 に接続された LED を利用する @n
			RX24T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する @n
			RX66T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"

#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/cmt_io.hpp"

#include "common/format.hpp"
#include "common/input.hpp"

#include "FreeRTOS.h"
#include "task.h"

// RX64Mで、GR-KAEDE の場合有効にする
#define GR_KAEDE

extern "C" {
	void vTickISR(void);
	void vSoftwareInterruptISR(void);
};

namespace {

/// ベースクリスタルの定義
/// LED 接続ポートの定義
#if defined(SIG_RX71M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#elif defined(SIG_RX72M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#elif defined(SIG_RX64M)
	typedef device::system_io<12000000> SYSTEM_IO;
#ifdef GR_KAEDE
	typedef device::PORT<device::PORTC, device::bitpos::B1> LED;
	typedef device::PORT<device::PORTC, device::bitpos::B0> LED2;
#else
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#endif
#elif defined(SIG_RX65N)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
#elif defined(SIG_RX63T)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORTB, device::bitpos::B7> LED;
#elif defined(SIG_RX24T)
	typedef device::system_io<10000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
#elif defined(SIG_RX66T)
	typedef device::system_io<10000000, 160000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
#endif

	typedef device::cmt_io<device::CMT0> CMT;
	CMT			cmt_;
}

extern "C" {

	void vApplicationMallocFailedHook( void )
	{
		/* Called if a call to pvPortMalloc() fails because there is insufficient
		free memory available in the FreeRTOS heap.  pvPortMalloc() is called
		internally by FreeRTOS API functions that create tasks, queues, software
		timers, and semaphores.  The size of the FreeRTOS heap is set by the
		configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. */
		taskDISABLE_INTERRUPTS();
		for( ;; );
	}

	void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
	{
		( void ) pcTaskName;
		( void ) pxTask;

		/* Run time stack overflow checking is performed if
		configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2.  This hook
		function is called if a stack overflow is detected. */
		taskDISABLE_INTERRUPTS();
		for( ;; );
	}

	void vApplicationIdleHook( void )
	{
		/// volatile size_t xFreeHeapSpace;

		/* This is just a trivial example of an idle hook.  It is called on each
		cycle of the idle task.  It must *NOT* attempt to block.  In this case the
		idle task just queries the amount of FreeRTOS heap that remains.  See the
		memory management section on the http://www.FreeRTOS.org web site for memory
		management options.  If there is a lot of heap memory free then the
		configTOTAL_HEAP_SIZE value in FreeRTOSConfig.h can be reduced to free up
		RAM. */
///		xFreeHeapSpace = xPortGetFreeHeapSize();

		/* Remove compiler warning about xFreeHeapSpace being set but never used. */
///		( void ) xFreeHeapSpace;
	}

	void vApplicationTickHook( void )
	{
	}

	void vAssertCalled( void )
	{
		volatile unsigned long ul = 0;

		taskENTER_CRITICAL();
		{
			/* Use the debugger to set ul to a non-zero value in order to step out
			of this function to determine why it was called. */
			while( ul == 0 )
			{
				portNOP();
			}
		}
		taskEXIT_CRITICAL();
	}

	void vApplicationSetupTimerInterrupt( void )
	{
		uint8_t intr = configKERNEL_INTERRUPT_PRIORITY;
		cmt_.start(configTICK_RATE_HZ, intr, vTickISR);

		device::icu_mgr::set_task(device::ICU::VECTOR::SWINT, vSoftwareInterruptISR);
		device::icu_mgr::set_level(device::ICU::VECTOR::SWINT, configKERNEL_INTERRUPT_PRIORITY);
	}
};

namespace {

	void vTask1(void *pvParameters)
	{
		while(1) {
			vTaskEnterCritical();
			LED::P = !LED::P();
			vTaskExitCritical();
			vTaskDelay(500 / portTICK_PERIOD_MS);
		}
	}

	void vTask2(void *pvParameters)
	{
		while(1) {
			vTaskEnterCritical();
#ifdef GR_KAEDE
			LED2::P = !LED2::P();
#else
			LED::P = !LED::P();
#endif
			vTaskExitCritical();
			vTaskDelay(100 / portTICK_PERIOD_MS);
		}
	}
}

int main(int argc, char** argv);

int main(int argc, char** argv)
{
	SYSTEM_IO::setup_system_clock();

	LED::OUTPUT();  // LED ポートを出力に設定
	LED::P = 1;		// Off
#ifdef GR_KAEDE
	LED2::OUTPUT();
	LED2::P = 1;
#endif

	{
		uint32_t stack_size = 512;
		void* param = nullptr;
		uint32_t prio = 1;
		xTaskCreate(vTask1, "Task1", stack_size, param, prio, nullptr);
		xTaskCreate(vTask2, "Task2", stack_size, param, prio, nullptr);
	}

	vTaskStartScheduler();

	// タスクスケジューラーが正常なら実行されない
	while(1) {
		utils::delay::milli_second(250);
		LED::P = !LED::P();
		utils::delay::milli_second(250);
		LED::P = !LED::P();
	}
}
<commit_msg>Update: cleanup<commit_after>//=====================================================================//
/*! @file
    @brief  ファースト・サンプル（LED 点滅） @n
			RX64M, RX71M, RX72M: @n
					12MHz のベースクロックを使用する @n
			　　　　P07 ピンにLEDを接続する @n
			RX65N (Renesas Envision kit RX65N): @n
					12MHz のベースクロックを使用する @n
			　　　　P70 に接続された LED を利用する @n
			RX63T @n
					12MHz のベースクロックを使用する @n
					PB7 に接続された LED を利用する @n
			RX24T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する @n
			RX66T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"

#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/cmt_io.hpp"

#include "common/format.hpp"
#include "common/input.hpp"

#include "FreeRTOS.h"
#include "task.h"

#ifdef SIG_RX64M
// RX64Mで、GR-KAEDE の場合有効にする
#define GR_KAEDE
#endif

extern "C" {
	void vTickISR(void);
	void vSoftwareInterruptISR(void);
};

namespace {

/// ベースクリスタルの定義
/// LED 接続ポートの定義
#if defined(SIG_RX71M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#elif defined(SIG_RX72M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#elif defined(SIG_RX64M)
	typedef device::system_io<12000000> SYSTEM_IO;
#ifdef GR_KAEDE
	typedef device::PORT<device::PORTC, device::bitpos::B1> LED;
	typedef device::PORT<device::PORTC, device::bitpos::B0> LED2;
#else
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#endif
#elif defined(SIG_RX65N)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
#elif defined(SIG_RX63T)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORTB, device::bitpos::B7> LED;
#elif defined(SIG_RX24T)
	typedef device::system_io<10000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
#elif defined(SIG_RX66T)
	typedef device::system_io<10000000, 160000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
#endif

	typedef device::cmt_io<device::CMT0> CMT;
	CMT			cmt_;
}

extern "C" {

	void vApplicationMallocFailedHook( void )
	{
		/* Called if a call to pvPortMalloc() fails because there is insufficient
		free memory available in the FreeRTOS heap.  pvPortMalloc() is called
		internally by FreeRTOS API functions that create tasks, queues, software
		timers, and semaphores.  The size of the FreeRTOS heap is set by the
		configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. */
		taskDISABLE_INTERRUPTS();
		for( ;; );
	}

	void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
	{
		( void ) pcTaskName;
		( void ) pxTask;

		/* Run time stack overflow checking is performed if
		configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2.  This hook
		function is called if a stack overflow is detected. */
		taskDISABLE_INTERRUPTS();
		for( ;; );
	}

	void vApplicationIdleHook( void )
	{
		/// volatile size_t xFreeHeapSpace;

		/* This is just a trivial example of an idle hook.  It is called on each
		cycle of the idle task.  It must *NOT* attempt to block.  In this case the
		idle task just queries the amount of FreeRTOS heap that remains.  See the
		memory management section on the http://www.FreeRTOS.org web site for memory
		management options.  If there is a lot of heap memory free then the
		configTOTAL_HEAP_SIZE value in FreeRTOSConfig.h can be reduced to free up
		RAM. */
///		xFreeHeapSpace = xPortGetFreeHeapSize();

		/* Remove compiler warning about xFreeHeapSpace being set but never used. */
///		( void ) xFreeHeapSpace;
	}

	void vApplicationTickHook( void )
	{
	}

	void vAssertCalled( void )
	{
		volatile unsigned long ul = 0;

		taskENTER_CRITICAL();
		{
			/* Use the debugger to set ul to a non-zero value in order to step out
			of this function to determine why it was called. */
			while( ul == 0 )
			{
				portNOP();
			}
		}
		taskEXIT_CRITICAL();
	}

	void vApplicationSetupTimerInterrupt( void )
	{
		uint8_t intr = configKERNEL_INTERRUPT_PRIORITY;
		cmt_.start(configTICK_RATE_HZ, intr, vTickISR);

		device::icu_mgr::set_task(device::ICU::VECTOR::SWINT, vSoftwareInterruptISR);
		device::icu_mgr::set_level(device::ICU::VECTOR::SWINT, configKERNEL_INTERRUPT_PRIORITY);
	}
};

namespace {

	void vTask1(void *pvParameters)
	{
		while(1) {
			vTaskEnterCritical();
			LED::P = !LED::P();
			vTaskExitCritical();
			vTaskDelay(500 / portTICK_PERIOD_MS);
		}
	}

	void vTask2(void *pvParameters)
	{
		while(1) {
			vTaskEnterCritical();
#ifdef GR_KAEDE
			LED2::P = !LED2::P();
#else
			LED::P = !LED::P();
#endif
			vTaskExitCritical();
			vTaskDelay(100 / portTICK_PERIOD_MS);
		}
	}
}

int main(int argc, char** argv);

int main(int argc, char** argv)
{
	SYSTEM_IO::setup_system_clock();

	LED::OUTPUT();  // LED ポートを出力に設定
	LED::P = 1;		// Off
#ifdef GR_KAEDE
	LED2::OUTPUT();
	LED2::P = 1;
#endif

	{
		uint32_t stack_size = 512;
		void* param = nullptr;
		uint32_t prio = 1;
		xTaskCreate(vTask1, "Task1", stack_size, param, prio, nullptr);
		xTaskCreate(vTask2, "Task2", stack_size, param, prio, nullptr);
	}

	vTaskStartScheduler();

	// タスクスケジューラーが正常なら実行されない
	while(1) {
		utils::delay::milli_second(250);
		LED::P = !LED::P();
		utils::delay::milli_second(250);
		LED::P = !LED::P();
	}
}
<|endoftext|>


<commit_before>#include "HelloWorldScene.h"

USING_NS_CC;

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();

    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    auto daSquareBro = Sprite::createWithSpriteFrameName("daSquareBro.png");
    daSquareBro->setPosition(100, 200);

    this->addChild(daSquareBro,0);

    return true;
}

void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
	MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
    return;
#endif

    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}
<commit_msg>Fiddling with hierarcy and scene building<commit_after>#include "HelloWorldScene.h"

USING_NS_CC;

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();

    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    // Loading SquareBro from the SpriteSheet
    auto daSquareBro = Sprite::createWithSpriteFrameName("daSquareBro.png");
    daSquareBro->setPosition(100, 200);

    auto daSquareSis = Sprite::createWithSpriteFrameName("daSquareSis.png");
    daSquareSis->setPosition(100,200);

    // Adding SquareBro as a node under the scene
    this->addChild(daSquareBro,0);
    // daSquareSis is an SquareImouto, actually, so it's under SquareBro
    daSquareBro->addChild(daSquareSis,0);

    return true;
}

void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
	MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
    return;
#endif

    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkDynamicLoader.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkDynamicLoader.h"

#include "vtkDebugLeaks.h"

// This file is actually 3 different implementations.
// 1. HP machines which uses shl_load
// 2. Apple OSX which uses NSLinkModule
// 3. Windows which uses LoadLibrary
// 4. Most unix systems which use dlopen (default )
// Each part of the ifdef contains a complete implementation for
// the static methods of vtkDynamicLoader.

vtkCxxRevisionMacro(vtkDynamicLoader, "1.19");

//----------------------------------------------------------------------------
// Needed when we don't use the vtkStandardNewMacro.
vtkInstantiatorNewMacro(vtkDynamicLoader);

//----------------------------------------------------------------------------
vtkDynamicLoader* vtkDynamicLoader::New()
{
#ifdef VTK_DEBUG_LEAKS
  vtkDebugLeaks::ConstructClass("vtkDynamicLoader");
#endif
  return new vtkDynamicLoader;
}

// ---------------------------------------------------------------
// 1. Implementation for HPUX  machines
#ifdef __hpux
#define VTKDYNAMICLOADER_DEFINED 1
#include <dl.h>

vtkLibHandle vtkDynamicLoader::OpenLibrary(const char* libname )
{
  return shl_load(libname, BIND_DEFERRED | DYNAMIC_PATH, 0L);
}

int vtkDynamicLoader::CloseLibrary(vtkLibHandle lib)
{
  return 0;
}

void* vtkDynamicLoader::GetSymbolAddress(vtkLibHandle lib, const char* sym)
{
  void* addr;
  int status;

  status = shl_findsym (&lib, sym, TYPE_PROCEDURE, &addr);
  return (status < 0) ? (void*)0 : addr;
}

const char* vtkDynamicLoader::LibPrefix()
{
  return "lib";
}

const char* vtkDynamicLoader::LibExtension()
{
  return ".sl";
}

const char* vtkDynamicLoader::LastError()
{
  return 0;
}
#endif

// ---------------------------------------------------------------
// 2. Implementation for Darwin (including OSX) Machines

#ifdef __APPLE__
#define VTKDYNAMICLOADER_DEFINED

// Visual Age Compiler for Mac OSX does not understand this extension.
#if defined(__IBMCPP__) && !defined(__private_extern__)
# define __private_extern__
#endif

#include <mach-o/dyld.h>

vtkLibHandle vtkDynamicLoader::OpenLibrary(const char* libname )
{
  NSObjectFileImageReturnCode rc;
  NSObjectFileImage image;

  rc = NSCreateObjectFileImageFromFile(libname, &image);
  return NSLinkModule(image, libname, TRUE);
}

int vtkDynamicLoader::CloseLibrary(vtkLibHandle)
{
  return 0;
}

void* vtkDynamicLoader::GetSymbolAddress(vtkLibHandle, const char* sym)
{
  void *result = 0;
  if( NSIsSymbolNameDefined(sym) )
    {
    cout << sym << " is defined!" << endl;
    NSSymbol symbol= NSLookupAndBindSymbol(sym);
    if(symbol)
      {
      result = NSAddressOfSymbol(symbol);
      }
    }
  else
    {
    cout << sym << " is not defined!" << endl;
    }

  return result;
}

const char* vtkDynamicLoader::LibPrefix()
{
  return "lib";
}

const char* vtkDynamicLoader::LibExtension()
{
  return ".so";
}

const char* vtkDynamicLoader::LastError()
{
  return 0;
}

#endif

// ---------------------------------------------------------------
// 3. Implementation for Windows win32 code
#ifdef _WIN32
#include <windows.h>
#define VTKDYNAMICLOADER_DEFINED 1

vtkLibHandle vtkDynamicLoader::OpenLibrary(const char* libname )
{
#ifdef UNICODE
  wchar_t *libn = new wchar_t [mbstowcs(NULL, libname, 32000)+1];
  mbstowcs(libn, libname, 32000);
  vtkLibHandle ret = LoadLibrary(libn);
  delete [] libn;
  return ret;
#else
  return LoadLibrary(libname);
#endif
}

int vtkDynamicLoader::CloseLibrary(vtkLibHandle lib)
{
  return (int)FreeLibrary(lib);
}

void* vtkDynamicLoader::GetSymbolAddress(vtkLibHandle lib, const char* sym)
{
#if defined (UNICODE) && !defined(_MSC_VER)
  wchar_t *wsym = new wchar_t [mbstowcs(NULL, sym, 32000)+1];
  mbstowcs(wsym, sym, 32000);
  // Force GetProcAddress to return void* with a c style cast
  // This is because you can not cast a function to a void* without
  // an error on gcc 3.2 and ANSI C++,
  void *ret = (void*)GetProcAddress(lib, wsym);
  delete [] wsym;
  return ret;
#else
  return (void*)GetProcAddress(lib, sym);
#endif
}

const char* vtkDynamicLoader::LibPrefix()
{
  return "";
}

const char* vtkDynamicLoader::LibExtension()
{
  return ".dll";
}

const char* vtkDynamicLoader::LastError()
{
  LPVOID lpMsgBuf;

  FormatMessage(
                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                NULL,
                GetLastError(),
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                (LPTSTR) &lpMsgBuf,
                0,
                NULL
                );

  // Free the buffer.
  static char* str = 0;
  delete [] str;
  if (lpMsgBuf)
    {
    str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf);
    LocalFree( lpMsgBuf );
    }
  return str;
}

#endif

// ---------------------------------------------------------------
// 4. Implementation for default UNIX machines.
// if nothing has been defined then use this
#ifndef VTKDYNAMICLOADER_DEFINED
#define VTKDYNAMICLOADER_DEFINED
// Setup for most unix machines
#include <dlfcn.h>

vtkLibHandle vtkDynamicLoader::OpenLibrary(const char* libname )
{
  return dlopen(libname, RTLD_LAZY);
}

int vtkDynamicLoader::CloseLibrary(vtkLibHandle lib)
{
  // dlclose returns 0 on success, and non-zero on error.
  return !((int)dlclose(lib));
}

void* vtkDynamicLoader::GetSymbolAddress(vtkLibHandle lib, const char* sym)
{
  return dlsym(lib, sym);
}

const char* vtkDynamicLoader::LibPrefix()
{
  return "lib";
}

const char* vtkDynamicLoader::LibExtension()
{
  return ".so";
}

const char* vtkDynamicLoader::LastError()
{
  return dlerror();
}
#endif
<commit_msg>BUG: Fix Bug #985 - vtkDynamicLoader::GetSymbolAddress on OSX, symbol should be prepend an underscore to really have a cross plateform behavior<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkDynamicLoader.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkDynamicLoader.h"

#include "vtkDebugLeaks.h"

// This file is actually 3 different implementations.
// 1. HP machines which uses shl_load
// 2. Apple OSX which uses NSLinkModule
// 3. Windows which uses LoadLibrary
// 4. Most unix systems which use dlopen (default )
// Each part of the ifdef contains a complete implementation for
// the static methods of vtkDynamicLoader.

vtkCxxRevisionMacro(vtkDynamicLoader, "1.20");

//----------------------------------------------------------------------------
// Needed when we don't use the vtkStandardNewMacro.
vtkInstantiatorNewMacro(vtkDynamicLoader);

//----------------------------------------------------------------------------
vtkDynamicLoader* vtkDynamicLoader::New()
{
#ifdef VTK_DEBUG_LEAKS
  vtkDebugLeaks::ConstructClass("vtkDynamicLoader");
#endif
  return new vtkDynamicLoader;
}

// ---------------------------------------------------------------
// 1. Implementation for HPUX  machines
#ifdef __hpux
#define VTKDYNAMICLOADER_DEFINED 1
#include <dl.h>

vtkLibHandle vtkDynamicLoader::OpenLibrary(const char* libname )
{
  return shl_load(libname, BIND_DEFERRED | DYNAMIC_PATH, 0L);
}

int vtkDynamicLoader::CloseLibrary(vtkLibHandle lib)
{
  return 0;
}

void* vtkDynamicLoader::GetSymbolAddress(vtkLibHandle lib, const char* sym)
{
  void* addr;
  int status;

  status = shl_findsym (&lib, sym, TYPE_PROCEDURE, &addr);
  return (status < 0) ? (void*)0 : addr;
}

const char* vtkDynamicLoader::LibPrefix()
{
  return "lib";
}

const char* vtkDynamicLoader::LibExtension()
{
  return ".sl";
}

const char* vtkDynamicLoader::LastError()
{
  return 0;
}
#endif

// ---------------------------------------------------------------
// 2. Implementation for Darwin (including OSX) Machines

#ifdef __APPLE__
#define VTKDYNAMICLOADER_DEFINED

// Visual Age Compiler for Mac OSX does not understand this extension.
#if defined(__IBMCPP__) && !defined(__private_extern__)
# define __private_extern__
#endif

#include <mach-o/dyld.h>

vtkLibHandle vtkDynamicLoader::OpenLibrary(const char* libname )
{
  NSObjectFileImageReturnCode rc;
  NSObjectFileImage image;

  rc = NSCreateObjectFileImageFromFile(libname, &image);
  return NSLinkModule(image, libname, TRUE);
}

int vtkDynamicLoader::CloseLibrary(vtkLibHandle)
{
  return 0;
}

void* vtkDynamicLoader::GetSymbolAddress(vtkLibHandle, const char* sym)
{
  void *result = 0;
  // global 'C' symbols names are preceded with an underscore '_'
  char *_sym = new char[ strlen(sym) + 2 ];
  strcpy( _sym + 1, sym );
  _sym[0] = '_';
  if( NSIsSymbolNameDefined(_sym) )
    {
    cout << _sym << " is defined!" << endl;
    NSSymbol symbol = NSLookupAndBindSymbol(_sym);
    if(symbol)
      {
      result = NSAddressOfSymbol(symbol);
      }
    }
  else
    {
    cout << _sym << " is not defined!" << endl;
    }

  delete[] _sym;
  return result;
}

const char* vtkDynamicLoader::LibPrefix()
{
  return "lib";
}

const char* vtkDynamicLoader::LibExtension()
{
  return ".so";
}

const char* vtkDynamicLoader::LastError()
{
  return 0;
}

#endif

// ---------------------------------------------------------------
// 3. Implementation for Windows win32 code
#ifdef _WIN32
#include <windows.h>
#define VTKDYNAMICLOADER_DEFINED 1

vtkLibHandle vtkDynamicLoader::OpenLibrary(const char* libname )
{
#ifdef UNICODE
  wchar_t *libn = new wchar_t [mbstowcs(NULL, libname, 32000)+1];
  mbstowcs(libn, libname, 32000);
  vtkLibHandle ret = LoadLibrary(libn);
  delete [] libn;
  return ret;
#else
  return LoadLibrary(libname);
#endif
}

int vtkDynamicLoader::CloseLibrary(vtkLibHandle lib)
{
  return (int)FreeLibrary(lib);
}

void* vtkDynamicLoader::GetSymbolAddress(vtkLibHandle lib, const char* sym)
{
#if defined (UNICODE) && !defined(_MSC_VER)
  wchar_t *wsym = new wchar_t [mbstowcs(NULL, sym, 32000)+1];
  mbstowcs(wsym, sym, 32000);
  // Force GetProcAddress to return void* with a c style cast
  // This is because you can not cast a function to a void* without
  // an error on gcc 3.2 and ANSI C++,
  void *ret = (void*)GetProcAddress(lib, wsym);
  delete [] wsym;
  return ret;
#else
  return (void*)GetProcAddress(lib, sym);
#endif
}

const char* vtkDynamicLoader::LibPrefix()
{
  return "";
}

const char* vtkDynamicLoader::LibExtension()
{
  return ".dll";
}

const char* vtkDynamicLoader::LastError()
{
  LPVOID lpMsgBuf;

  FormatMessage(
                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                NULL,
                GetLastError(),
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                (LPTSTR) &lpMsgBuf,
                0,
                NULL
                );

  // Free the buffer.
  static char* str = 0;
  delete [] str;
  if (lpMsgBuf)
    {
    str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf);
    LocalFree( lpMsgBuf );
    }
  return str;
}

#endif

// ---------------------------------------------------------------
// 4. Implementation for default UNIX machines.
// if nothing has been defined then use this
#ifndef VTKDYNAMICLOADER_DEFINED
#define VTKDYNAMICLOADER_DEFINED
// Setup for most unix machines
#include <dlfcn.h>

vtkLibHandle vtkDynamicLoader::OpenLibrary(const char* libname )
{
  return dlopen(libname, RTLD_LAZY);
}

int vtkDynamicLoader::CloseLibrary(vtkLibHandle lib)
{
  // dlclose returns 0 on success, and non-zero on error.
  return !((int)dlclose(lib));
}

void* vtkDynamicLoader::GetSymbolAddress(vtkLibHandle lib, const char* sym)
{
  return dlsym(lib, sym);
}

const char* vtkDynamicLoader::LibPrefix()
{
  return "lib";
}

const char* vtkDynamicLoader::LibExtension()
{
  return ".so";
}

const char* vtkDynamicLoader::LastError()
{
  return dlerror();
}
#endif
<|endoftext|>


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

#include "AdBlock/CustomList.hpp"

#include "Application.hpp"

#include "AdBlock/Manager.hpp"
#include "AdBlock/Rule.hpp"

namespace Sn {
namespace ADB {

CustomList::CustomList(QObject* parent) :
	Subscription(tr("Custom Rules"), parent)
{
	setFilePath(Application::instance()->paths()[Application::P_Data] + QLatin1String("/adblock/customlist.txt"));
}

void CustomList::loadSubscription(const QStringList& disabledRules)
{
	//TODO: Why not add own Sielo subscription ?
	Subscription::loadSubscription(disabledRules);
}

void CustomList::saveSubscription()
{
	QFile file{filePath()};

	if (!file.open(QFile::ReadWrite | QFile::Truncate)) {
		qWarning() << "ADB::Subscription: " << __FUNCTION__ << " Unable to open adblock file for writing "
				   << filePath();
		return;
	}

	QTextStream textStream{};

	textStream.setCodec("UTF-8");
	textStream << "Title: " << title() << endl;
	textStream << "Url: " << url().toString() << endl;
	textStream << "[Adblock Plus 2.0]" << endl;

		foreach (const Rule* rule, m_rules) textStream << rule->filter() << endl;

	file.close();
}

bool CustomList::containsFilter(const QString& filter) const
{
		foreach (const Rule* rule, m_rules) {
			if (rule->filter() == filter)
				return true;
		}

	return false;
}

bool CustomList::removeFilter(const QString& filter)
{
	for (int i{0}; i < m_rules.count(); ++i) {
		const Rule* rule{m_rules[i]};

		if (rule->filter() == filter)
			return removeRule(i);
	}

	return false;
}

int CustomList::addRule(Rule* rule)
{
	m_rules.append(rule);

	emit subscriptionChanged();

	if (rule->isCSSRule())
		Application::instance()->reloadUserStyleSheet();

	return m_rules.count() - 1;
}

bool CustomList::removeRule(int offset)
{
	if (!(offset >= 0 && m_rules.count() > offset))
		return false;

	Rule* rule{m_rules[offset]};
	const QString filter{rule->filter()};

	m_rules.remove(offset);

	emit subscriptionChanged();

	if (rule->isCSSRule())
		Application::instance()->reloadUserStyleSheet();

	Manager::instance()->removeDisabledRule(filter);

	delete rule;

	return true;
}

const Rule* CustomList::replaceRule(Rule* rule, int offset)
{
	if (!(offset >= 0 && m_rules.count() > offset))
		return nullptr;

	Rule* oldRule{m_rules[offset]};
	m_rules[offset] = rule;

	emit subscriptionChanged();

	if (rule->isCSSRule())
		Application::instance()->reloadUserStyleSheet();

	delete oldRule;

	return m_rules[offset];
}

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

#include "AdBlock/CustomList.hpp"

#include "Application.hpp"

#include "AdBlock/Manager.hpp"
#include "AdBlock/Rule.hpp"

namespace Sn {
namespace ADB {

CustomList::CustomList(QObject* parent) :
	Subscription(tr("Custom Rules"), parent)
{
	setFilePath(Application::instance()->paths()[Application::P_Data] + QLatin1String("/adblock/customlist.txt"));
}

void CustomList::loadSubscription(const QStringList& disabledRules)
{
	QFile file(filePath());
	if (!file.exists()) {
		saveSubscription();
	}

	//TODO: Why not add own Sielo subscription ?
	Subscription::loadSubscription(disabledRules);
}

void CustomList::saveSubscription()
{
	QFile file{filePath()};

	if (!file.open(QFile::ReadWrite | QFile::Truncate)) {
		qWarning() << "ADB::Subscription: " << __FUNCTION__ << " Unable to open adblock file for writing "
				   << filePath();
		return;
	}

	QTextStream textStream{&file};

	textStream.setCodec("UTF-8");
	textStream << "Title: " << title() << endl;
	textStream << "Url: " << url().toString() << endl;
	textStream << "[Adblock Plus 2.0]" << endl;

		foreach (const Rule* rule, m_rules) textStream << rule->filter() << endl;

	file.close();
}

bool CustomList::containsFilter(const QString& filter) const
{
		foreach (const Rule* rule, m_rules) {
			if (rule->filter() == filter)
				return true;
		}

	return false;
}

bool CustomList::removeFilter(const QString& filter)
{
	for (int i{0}; i < m_rules.count(); ++i) {
		const Rule* rule{m_rules[i]};

		if (rule->filter() == filter)
			return removeRule(i);
	}

	return false;
}

int CustomList::addRule(Rule* rule)
{
	m_rules.append(rule);

	emit subscriptionChanged();

	if (rule->isCSSRule())
		Application::instance()->reloadUserStyleSheet();

	return m_rules.count() - 1;
}

bool CustomList::removeRule(int offset)
{
	if (!(offset >= 0 && m_rules.count() > offset))
		return false;

	Rule* rule{m_rules[offset]};
	const QString filter{rule->filter()};

	m_rules.remove(offset);

	emit subscriptionChanged();

	if (rule->isCSSRule())
		Application::instance()->reloadUserStyleSheet();

	Manager::instance()->removeDisabledRule(filter);

	delete rule;

	return true;
}

const Rule* CustomList::replaceRule(Rule* rule, int offset)
{
	if (!(offset >= 0 && m_rules.count() > offset))
		return nullptr;

	Rule* oldRule{m_rules[offset]};
	m_rules[offset] = rule;

	emit subscriptionChanged();

	if (rule->isCSSRule())
		Application::instance()->reloadUserStyleSheet();

	delete oldRule;

	return m_rules[offset];
}

}
}<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
$Log$
Revision 1.2  2001/11/12 14:31:00  morsch
Memory leaks fixed. (M. Bondila)

Revision 1.1  2001/11/09 09:11:24  morsch
Realisation of AliGenReader that reads the kine tree (TreeK).

*/
#include <TFile.h>
#include <TTree.h>
#include <TParticle.h>

#include "AliGenReaderTreeK.h"
#include "AliStack.h"
#include "AliHeader.h"
#include "AliRun.h"

ClassImp(AliGenReaderTreeK);

AliGenReaderTreeK::AliGenReaderTreeK():AliGenReader()
{
//  Default constructor
    fFileName       = NULL;
    fStack          = 0;
    fHeader         = 0;
    fNcurrent       = 0;
    fNparticle      = 0;
    fFile           = 0;
    fBaseFile       = 0;
    fTreeE          = 0;
}

AliGenReaderTreeK::AliGenReaderTreeK(const AliGenReaderTreeK &reader)
{
    ;
}

AliGenReaderTreeK::~AliGenReaderTreeK()
{
// Destructor
    delete fTreeE;
}

void AliGenReaderTreeK::Init()
{
// Initialization
// Connect base file and file to read from

    TTree *ali = gAlice->TreeE();
    if (ali) {
	fBaseFile = ali->GetCurrentFile();
    } else {
	printf("\n Warning: Basefile cannot be found !\n");
    }
    fFile = new TFile(fFileName);
}

Int_t AliGenReaderTreeK::NextEvent()
{
// Read the next event
//  cd to file with old kine tree
    if (!fBaseFile) Init();
    if (fStack) delete fStack;
    fStack = new AliStack(1000);
    fFile->cd();
//  Connect treeE
    if (fTreeE) {
	delete fTreeE;
    } else {
	fTreeE = (TTree*)gDirectory->Get("TE");
    }

    if (fHeader) delete fHeader;
    fHeader = 0;
    fTreeE->SetBranchAddress("Header", &fHeader);
//  Get next event
    fTreeE->GetEntry(fNcurrent);
    fStack = fHeader->Stack();
    fStack->GetEvent(fNcurrent);

//  cd back to base file
    fBaseFile->cd();
//
    fNcurrent++;
    fNparticle = 0;
    Int_t ntrack =  fStack->GetNtrack();
    printf("\n Next event contains %d particles", ntrack);

    return  ntrack;
}

TParticle* AliGenReaderTreeK::NextParticle()
{
//  Return next particle
    TParticle* part = fStack->Particle(fNparticle);
    fNparticle++;
    return part;
}

AliGenReaderTreeK& AliGenReaderTreeK::operator=(const  AliGenReaderTreeK& rhs)
{
// Assignment operator
    return *this;
}

<commit_msg>TreeE connected correctly.<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
$Log$
Revision 1.3  2001/12/12 11:21:37  morsch
Dummy copy constructor added.

Revision 1.2  2001/11/12 14:31:00  morsch
Memory leaks fixed. (M. Bondila)

Revision 1.1  2001/11/09 09:11:24  morsch
Realisation of AliGenReader that reads the kine tree (TreeK).

*/
#include <TFile.h>
#include <TTree.h>
#include <TParticle.h>

#include "AliGenReaderTreeK.h"
#include "AliStack.h"
#include "AliHeader.h"
#include "AliRun.h"

ClassImp(AliGenReaderTreeK);

AliGenReaderTreeK::AliGenReaderTreeK():AliGenReader()
{
//  Default constructor
    fFileName       = NULL;
    fStack          = 0;
    fHeader         = 0;
    fNcurrent       = 0;
    fNparticle      = 0;
    fFile           = 0;
    fBaseFile       = 0;
    fTreeE          = 0;
}

AliGenReaderTreeK::AliGenReaderTreeK(const AliGenReaderTreeK &reader)
{
    ;
}

AliGenReaderTreeK::~AliGenReaderTreeK()
{
// Destructor
    delete fTreeE;
}

void AliGenReaderTreeK::Init()
{
// Initialization
// Connect base file and file to read from

    TTree *ali = gAlice->TreeE();
    if (ali) {
	fBaseFile = ali->GetCurrentFile();
    } else {
	printf("\n Warning: Basefile cannot be found !\n");
    }
    if (!fFile) fFile  = new TFile(fFileName);
}

Int_t AliGenReaderTreeK::NextEvent()
{
//  Read the next event
//  cd to file with old kine tree
    if (!fBaseFile) Init();
    fFile->cd();
//  Connect header tree
    if (!fTreeE) fTreeE = (TTree*)gDirectory->Get("TE");
    if (fHeader) delete fHeader;
    fHeader = 0;
    fTreeE->SetBranchAddress("Header", &fHeader);
//  Get next event
    fTreeE->GetEntry(fNcurrent);
//  Connect Stack
    if (fStack) delete fStack;
    fStack = fHeader->Stack();
    fStack->GetEvent(fNcurrent);
//  cd back to base file
    fBaseFile->cd();
//
    fNcurrent++;
    fNparticle = 0;
    Int_t ntrack =  fStack->GetNtrack();
    printf("\n Next event contains %d particles", ntrack);
//
    return  ntrack;
}

TParticle* AliGenReaderTreeK::NextParticle()
{
//  Return next particle
    TParticle* part = fStack->Particle(fNparticle);
    fNparticle++;
    return part;
}

AliGenReaderTreeK& AliGenReaderTreeK::operator=(const  AliGenReaderTreeK& rhs)
{
// Assignment operator
    return *this;
}

<|endoftext|>