<commit_before>// Copyright (C) 2013 Oliver Schulz <oliver.schulz@tu-dortmund.de>

// This is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This software is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

#include "SDPeak.h"

#include <stdexcept>
#include <limits>
#include <cmath>
#include <cassert>

using namespace std;

namespace rspt {

double SDPeak::gauss(double x, double sigma)
	{ return (1. / (sigma * sqrt(2 * M_PI)) ) * exp( - pow(x / (sqrt(2) * sigma), 2.) ); }

double SDPeak::skewedGauss(double x, double sigma, double skewWidth) {
	double skew = skewWidth * sigma;
	return ( exp( x/skew + sigma*sigma/(2.*skew*skew) ) * erfc( x / (sqrt(2)*sigma) + sigma / (sqrt(2)*skew)) ) / (2.*skew);
}

double SDPeak::stepWithSigma(double x, double sigma)
	{ return 0.5 * erfc( x / (sqrt(2) * sigma) ); }

double SDPeak::peakShape(double x, double center, double area, double sigma, double stepAmpl, double skewFraction, double skewWidth) {
	double x_c = x - center;
	return area * (1 - skewFraction) * gauss(x_c, sigma)
	     + (skewFraction != 0 ? area * skewFraction * skewedGauss(x_c, sigma, skewWidth) : 0)
		 + stepAmpl * stepWithSigma(x_c, sigma);
}

SDPeak::SDPeak() {
}

SDPeak::~SDPeak() {
}

double MultiPeakShape::operator()(double *x, double* p) {
	double result = 0;
	if (m_bg != 0) {
		result = (*m_bg)(x, p);
		p += m_bg->GetNpar();
	}

	double skewFraction = 0, skewWidth = 0;
	if (m_skewEnabled) { skewFraction = *p++; skewWidth = *p++; }

	for (int i = 0; i < m_nPeaks; ++i) {
		double center = *p++, area = *p++, sigma = *p++, stepAmpl = *p++;
		result += SDPeak::peakShape(*x, center, area, sigma, stepAmpl, skewFraction, skewWidth);
	}
	return result;
}

TF1* MultiPeakShape::newTF1(const char* name, TSpectrum *spectrum, double sigma) {
	if (spectrum == 0) throw std::invalid_argument("Input spectrum cannot be a null pointer");
	if (m_nPeaks != spectrum->GetNPeaks()) throw std::invalid_argument("Number of peaks to fit doesn't match number of peaks in input spektrum");

	// double maxPos = numeric_limits<double>::max();
	// double maxPos = 1e10;

	static const int nPeakPar = 4;
	static const int nSkewPar = m_skewEnabled ? 2 : 0;

	Int_t nBgPar = (m_bg != 0) ? m_bg->GetNpar() : 0;
	TF1 *tf = new TF1(name, *this, 0, 16.0 + 16.0 * m_nPeaks , nBgPar + nSkewPar + m_nPeaks * nPeakPar);
	tf->SetNpx(1000);

	for (Int_t i = 0; i < nBgPar; ++i) {
		tf->SetParName(i, TString::Format("bg_%s", m_bg->GetParName(i)));
		tf->SetParameter(i, m_bg->GetParameter(i));
		double a, b;
		m_bg->GetParLimits(i, a, b);
		tf->SetParLimits(i, a, b);
	}

	Int_t p = nBgPar;

	if (m_skewEnabled) {
		tf->SetParName(p, "peak_skewFraction");
		tf->SetParLimits(p, 0, 1);
		tf->SetParameter(p, 0.2);
		++p;
		tf->SetParName(p, "peak_skewWidth");
		tf->SetParLimits(p, 0.2, 20.0);
		tf->SetParameter(p, 2.0);
		++p;
	}

	for (Int_t i = 0; i < m_nPeaks; ++i) {
		double center = spectrum->GetPositionX()[i];
		double height = spectrum->GetPositionY()[i];
		double area = height / SDPeak::gauss(0, sigma);
		double areaLimit = 1000 * area;

		tf->SetParName(p, TString::Format("peak%i_center",i+1));
		tf->SetParameter(p, center);
		++p;
		tf->SetParName(p, TString::Format("peak%i_area",i+1));
		if (areaLimit > 0) tf->SetParLimits(p, 0, areaLimit);
		tf->SetParameter(p, area);
		++p;
		tf->SetParName(p, TString::Format("peak%i_sigma",i+1));
		tf->SetParLimits(p, 0, 10000);
		tf->SetParameter(p, sigma);
		++p;
		tf->SetParName(p, TString::Format("peak%i_stepAmpl",i+1));
		tf->SetParLimits(p, 0, height);
		tf->SetParameter(p, 0.02);
		++p;
	}
	return tf;
}

MultiPeakShape::MultiPeakShape(Int_t n, bool enableSkew, TF1* bgModel)
	: m_nPeaks(n), m_skewEnabled(enableSkew), m_bg(bgModel)
{
	if (m_nPeaks < 0) throw invalid_argument("Number of peaks must be >= 0");
}

} // namespace rspt
<commit_msg>Changed skewWidth in SDPeak::peakShape to be relative to peak center<commit_after>// Copyright (C) 2013 Oliver Schulz <oliver.schulz@tu-dortmund.de>

// This is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This software is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

#include "SDPeak.h"

#include <stdexcept>
#include <limits>
#include <cmath>
#include <cassert>

using namespace std;

namespace rspt {

double SDPeak::gauss(double x, double sigma)
	{ return (1. / (sigma * sqrt(2 * M_PI)) ) * exp( - pow(x / (sqrt(2) * sigma), 2.) ); }

double SDPeak::skewedGauss(double x, double sigma, double skew)
	{ return ( exp( x/skew + sigma*sigma/(2.*skew*skew) ) * erfc( x / (sqrt(2)*sigma) + sigma / (sqrt(2)*skew)) ) / (2.*skew); }

double SDPeak::stepWithSigma(double x, double sigma)
	{ return 0.5 * erfc( x / (sqrt(2) * sigma) ); }

double SDPeak::peakShape(double x, double center, double area, double sigma, double stepAmpl, double skewFraction, double skewWidth) {
	double x_c = x - center;
	double skew = skewWidth * center;
	return area * (1 - skewFraction) * gauss(x_c, sigma)
	     + (skewFraction != 0 ? area * skewFraction * skewedGauss(x_c, sigma, skew) : 0)
		 + stepAmpl * stepWithSigma(x_c, sigma);
}

SDPeak::SDPeak() {
}

SDPeak::~SDPeak() {
}

double MultiPeakShape::operator()(double *x, double* p) {
	double result = 0;
	if (m_bg != 0) {
		result = (*m_bg)(x, p);
		p += m_bg->GetNpar();
	}

	double skewFraction = 0, skewWidth = 0;
	if (m_skewEnabled) { skewFraction = *p++; skewWidth = *p++; }

	for (int i = 0; i < m_nPeaks; ++i) {
		double center = *p++, area = *p++, sigma = *p++, stepAmpl = *p++;
		result += SDPeak::peakShape(*x, center, area, sigma, stepAmpl, skewFraction, skewWidth);
	}
	return result;
}

TF1* MultiPeakShape::newTF1(const char* name, TSpectrum *spectrum, double sigma) {
	if (spectrum == 0) throw std::invalid_argument("Input spectrum cannot be a null pointer");
	if (m_nPeaks != spectrum->GetNPeaks()) throw std::invalid_argument("Number of peaks to fit doesn't match number of peaks in input spektrum");

	// double maxPos = numeric_limits<double>::max();
	// double maxPos = 1e10;

	static const int nPeakPar = 4;
	static const int nSkewPar = m_skewEnabled ? 2 : 0;

	Int_t nBgPar = (m_bg != 0) ? m_bg->GetNpar() : 0;
	TF1 *tf = new TF1(name, *this, 0, 16.0 + 16.0 * m_nPeaks , nBgPar + nSkewPar + m_nPeaks * nPeakPar);
	tf->SetNpx(1000);

	for (Int_t i = 0; i < nBgPar; ++i) {
		tf->SetParName(i, TString::Format("bg_%s", m_bg->GetParName(i)));
		tf->SetParameter(i, m_bg->GetParameter(i));
		double a, b;
		m_bg->GetParLimits(i, a, b);
		tf->SetParLimits(i, a, b);
	}

	Int_t p = nBgPar;

	if (m_skewEnabled) {
		tf->SetParName(p, "peak_skewFraction");
		tf->SetParLimits(p, 0, 1);
		tf->SetParameter(p, 0.2);
		++p;
		tf->SetParName(p, "peak_skewWidth");
		tf->SetParLimits(p, 1e-4, 1e-1);
		tf->SetParameter(p, 1e-3);
		++p;
	}

	for (Int_t i = 0; i < m_nPeaks; ++i) {
		double center = spectrum->GetPositionX()[i];
		double height = spectrum->GetPositionY()[i];
		double area = height / SDPeak::gauss(0, sigma);
		double areaLimit = 1000 * area;

		tf->SetParName(p, TString::Format("peak%i_center",i+1));
		tf->SetParameter(p, center);
		++p;
		tf->SetParName(p, TString::Format("peak%i_area",i+1));
		if (areaLimit > 0) tf->SetParLimits(p, 0, areaLimit);
		tf->SetParameter(p, area);
		++p;
		tf->SetParName(p, TString::Format("peak%i_sigma",i+1));
		tf->SetParLimits(p, 0, 10000);
		tf->SetParameter(p, sigma);
		++p;
		tf->SetParName(p, TString::Format("peak%i_stepAmpl",i+1));
		tf->SetParLimits(p, 0, height);
		tf->SetParameter(p, 0.02);
		++p;
	}
	return tf;
}

MultiPeakShape::MultiPeakShape(Int_t n, bool enableSkew, TF1* bgModel)
	: m_nPeaks(n), m_skewEnabled(enableSkew), m_bg(bgModel)
{
	if (m_nPeaks < 0) throw invalid_argument("Number of peaks must be >= 0");
}

} // namespace rspt
<|endoftext|>


<commit_before><commit_msg>Single-line bugfix in l10n tools to fix compile on GCC 4.4.3 (Ubuntu)<commit_after><|endoftext|>


<commit_before>/*
 * json_request_handler.hpp
 *
 *  Created on: Oct 27, 2016
 *      Author: zmij
 */

#ifndef HTTP_SERVER_JSON_REQUEST_HANDLER_HPP_
#define HTTP_SERVER_JSON_REQUEST_HANDLER_HPP_

#include <tip/http/server/json_body_context.hpp>
#include <atomic>
#include <type_traits>

namespace tip {
namespace http {
namespace server {

struct json_reply {
public:
    explicit
    json_reply(reply r)
        : r_{r}, sent_{ ::std::make_shared< ::std::atomic_flag >(false) } {}
    json_reply(json_reply const&) = default;
    json_reply(json_reply&&) = default;

    json_reply&
    operator = (json_reply const&) = default;
    json_reply&
    operator = (json_reply&&) = default;

    tip::iri::path const&
    path() const
    { return r_.path(); }

    reply::query_type const&
    query() const
    { return r_.query(); }

    headers const&
    request_headers() const
    { return r_.request_headers(); }

    void
    add_header(header const& h) const
    {
        r_.add_header(h);
    }
    void
    add_header(header&& h) const
    {
        r_.add_header(::std::move(h));
    }

    void
    on_finish(reply::finished_func f)
    {
        r_.on_finish(f);
    }

    template < typename T >
    bool
    parse(T& val, bool allow_empty_body = false)
    {
        auto& json = use_context<json_body_context>(r_);
        if ((bool)json) {
            try {
                json.input(val);
                return true;
            } catch(::std::exception const& e) {
                throw json_error{e.what()};
            } catch(...) {
                throw json_error("Invalid JSON request");
            }
        }
        switch (json.status()) {
            case json_body_context::empty_body:
                if (!allow_empty_body)
                    throw json_error("Empty body (expected JSON object)");
                break;
            case json_body_context::invalid_json:
                throw json_error("Malformed JSON");
            default:
                throw json_error("Unknown JSON status");
        }
        return false;
    }

    template < typename T >
    void
    done(T&& body, response_status status = response_status::ok) const
    {
        if (!sent_->test_and_set()) {
            auto& json = use_context<json_body_context>(r_);
            json << ::std::forward<T>(body);
            r_.done(status);
        } else {
            log_already_sent();
        }
    }
    template < typename T >
    void
    operator()(T&& body, response_status status = response_status::ok) const
    { done(::std::forward<T>(body), status); }
    void
    error(http::server::error const& e) const
    {
        e.log_error();
        done(e, e.status());
    }
    void
    operator()(http::server::error const& e) const
    { error(e); }

    template < typename Context >
    friend bool
    has_context(json_reply& r);
    template < typename Context >
    friend Context&
    use_context(json_reply& r);
private:
    void
    log_already_sent() const;
    using shared_flag = ::std::shared_ptr<::std::atomic_flag>;

    reply mutable   r_;
    shared_flag     sent_;
};

template < typename Context >
bool
has_context(json_reply& r)
{
    return has_context<Context>(r.r_);
}

template < typename Context >
Context&
use_context(json_reply& r)
{
    return use_context<Context>(r.r_);
}

template < typename T >
struct json_request_handler {
    using handler_type = T;

    void
    operator()(reply r)
    {
        rebind()(json_reply{r});
    }
private:
    handler_type&
    rebind()
    {
        return static_cast<handler_type&>(*this);
    }
    handler_type&
    rebind() const
    {
        return static_cast<handler_type const&>(*this);
    }
};

template < typename T, typename BodyType >
struct json_transform_handler :
        json_request_handler< json_transform_handler<T, BodyType> >{
    using base_type = json_request_handler< json_transform_handler<T, BodyType> >;
    using handler_type = T;
    using request_body_type     = BodyType;
    using request_pointer       = ::std::shared_ptr<BodyType>;

    using base_type::operator();
    void
    operator()(json_reply r)
    {
        try {
            request_pointer req{ ::std::make_shared<request_body_type>() };
            if (r.parse(*req)) {
                rebind()(r, req);
            }
        } catch ( ::tip::http::server::error const& e ) {
            r.error(e);
        } catch (::std::exception const& e) {
            r.error(::tip::http::server::error{"REQUEST", e.what(), response_status::ok});
        } catch (...) {
            r.error(::tip::http::server::error{"REQUEST", "Unexpected exception", response_status::ok});
        }
    }
private:
    handler_type&
    rebind()
    {
        return static_cast<handler_type&>(*this);
    }
    handler_type&
    rebind() const
    {
        return static_cast<handler_type const&>(*this);
    }
};

}  /* namespace server */
}  /* namespace http */
}  /* namespace tip */

#endif /* HTTP_SERVER_JSON_REQUEST_HANDLER_HPP_ */
<commit_msg>AWM-6696 Clear responce body in case of second send<commit_after>/*
 * json_request_handler.hpp
 *
 *  Created on: Oct 27, 2016
 *      Author: zmij
 */

#ifndef HTTP_SERVER_JSON_REQUEST_HANDLER_HPP_
#define HTTP_SERVER_JSON_REQUEST_HANDLER_HPP_

#include <tip/http/server/json_body_context.hpp>
#include <atomic>
#include <type_traits>

namespace tip {
namespace http {
namespace server {

struct json_reply {
public:
    explicit
    json_reply(reply r)
        : r_{r}, sent_{ ::std::make_shared< ::std::atomic_flag >(false) } {}
    json_reply(json_reply const&) = default;
    json_reply(json_reply&&) = default;

    json_reply&
    operator = (json_reply const&) = default;
    json_reply&
    operator = (json_reply&&) = default;

    tip::iri::path const&
    path() const
    { return r_.path(); }

    reply::query_type const&
    query() const
    { return r_.query(); }

    headers const&
    request_headers() const
    { return r_.request_headers(); }

    void
    add_header(header const& h) const
    {
        r_.add_header(h);
    }
    void
    add_header(header&& h) const
    {
        r_.add_header(::std::move(h));
    }

    void
    on_finish(reply::finished_func f)
    {
        r_.on_finish(f);
    }

    template < typename T >
    bool
    parse(T& val, bool allow_empty_body = false)
    {
        auto& json = use_context<json_body_context>(r_);
        if ((bool)json) {
            try {
                json.input(val);
                return true;
            } catch(::std::exception const& e) {
                throw json_error{e.what()};
            } catch(...) {
                throw json_error("Invalid JSON request");
            }
        }
        switch (json.status()) {
            case json_body_context::empty_body:
                if (!allow_empty_body)
                    throw json_error("Empty body (expected JSON object)");
                break;
            case json_body_context::invalid_json:
                throw json_error("Malformed JSON");
            default:
                throw json_error("Unknown JSON status");
        }
        return false;
    }

    template < typename T >
    void
    done(T&& body, response_status status = response_status::ok) const
    {
        if (!sent_->test_and_set()) {
            r_.response_body().clear();
            auto& json = use_context<json_body_context>(r_);
            json << ::std::forward<T>(body);
            r_.done(status);
        } else {
            log_already_sent();
        }
    }
    template < typename T >
    void
    operator()(T&& body, response_status status = response_status::ok) const
    { done(::std::forward<T>(body), status); }
    void
    error(http::server::error const& e) const
    {
        e.log_error();
        done(e, e.status());
    }
    void
    operator()(http::server::error const& e) const
    { error(e); }

    template < typename Context >
    friend bool
    has_context(json_reply& r);
    template < typename Context >
    friend Context&
    use_context(json_reply& r);
private:
    void
    log_already_sent() const;
    using shared_flag = ::std::shared_ptr<::std::atomic_flag>;

    reply mutable   r_;
    shared_flag     sent_;
};

template < typename Context >
bool
has_context(json_reply& r)
{
    return has_context<Context>(r.r_);
}

template < typename Context >
Context&
use_context(json_reply& r)
{
    return use_context<Context>(r.r_);
}

template < typename T >
struct json_request_handler {
    using handler_type = T;

    void
    operator()(reply r)
    {
        rebind()(json_reply{r});
    }
private:
    handler_type&
    rebind()
    {
        return static_cast<handler_type&>(*this);
    }
    handler_type&
    rebind() const
    {
        return static_cast<handler_type const&>(*this);
    }
};

template < typename T, typename BodyType >
struct json_transform_handler :
        json_request_handler< json_transform_handler<T, BodyType> >{
    using base_type = json_request_handler< json_transform_handler<T, BodyType> >;
    using handler_type = T;
    using request_body_type     = BodyType;
    using request_pointer       = ::std::shared_ptr<BodyType>;

    using base_type::operator();
    void
    operator()(json_reply r)
    {
        try {
            request_pointer req{ ::std::make_shared<request_body_type>() };
            if (r.parse(*req)) {
                rebind()(r, req);
            }
        } catch ( ::tip::http::server::error const& e ) {
            r.error(e);
        } catch (::std::exception const& e) {
            r.error(::tip::http::server::error{"REQUEST", e.what(), response_status::ok});
        } catch (...) {
            r.error(::tip::http::server::error{"REQUEST", "Unexpected exception", response_status::ok});
        }
    }
private:
    handler_type&
    rebind()
    {
        return static_cast<handler_type&>(*this);
    }
    handler_type&
    rebind() const
    {
        return static_cast<handler_type const&>(*this);
    }
};

}  /* namespace server */
}  /* namespace http */
}  /* namespace tip */

#endif /* HTTP_SERVER_JSON_REQUEST_HANDLER_HPP_ */
<|endoftext|>


<commit_before>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay                     *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#ifndef XSIMD_ALIGNED_ALLOCATOR_HPP
#define XSIMD_ALIGNED_ALLOCATOR_HPP

#include <algorithm>
#include <memory>
#include <cstddef>
#include <stdlib.h>

#include "../config/xsimd_align.hpp"

#if defined(XSIMD_ALLOCA)
#if defined(__GNUC__)
#include <alloca.h>
#elif defined(_MSC_VER)
#include <malloc.h>
#endif
#endif

namespace xsimd
{

    /**
     * @class aligned_allocator
     * @brief Allocator for aligned memory
     *
     * The aligned_allocator class template is an allocator that
     * performs memory allocation aligned by the specified value.
     *
     * @tparam T type of objects to allocate.
     * @tparam Align alignment in bytes.
     */
    template <class T, size_t Align>
    class aligned_allocator
    {
    public:

        using value_type = T;
        using pointer = T*;
        using const_pointer = const T*;
        using reference = T&;
        using const_reference = const T&;
        using size_type = size_t;
        using difference_type = ptrdiff_t;

        static constexpr size_t alignment = Align;

        template <class U>
        struct rebind
        {
            using other = aligned_allocator<U, Align>;
        };

        aligned_allocator() noexcept;
        aligned_allocator(const aligned_allocator& rhs) noexcept;

        template <class U>
        aligned_allocator(const aligned_allocator<U, Align>& rhs) noexcept;

        ~aligned_allocator();

        pointer address(reference) noexcept;
        const_pointer address(const_reference) const noexcept;

        pointer allocate(size_type n, typename std::allocator<void>::const_pointer hint = 0);
        void deallocate(pointer p, size_type n);

        size_type size_max() const noexcept;

        template <class U, class... Args>
        void construct(U* p, Args&&... args);

        template <class U>
        void destroy(U* p);
    };

    template <class T1, size_t Align1, class T2, size_t Align2>
    bool operator==(const aligned_allocator<T1, Align1>& lhs,
                    const aligned_allocator<T2, Align2>& rhs) noexcept;

    template <class T1, size_t Align1, class T2, size_t Align2>
    bool operator!=(const aligned_allocator<T1, Align1>& lhs,
                    const aligned_allocator<T2, Align2>& rhs) noexcept;

    void* aligned_malloc(size_t size, size_t alignment);
    void aligned_free(void* ptr);

    template <class T>
    size_t get_alignment_offset(const T* p, size_t size, size_t block_size);

    /************************************
     * aligned_allocator implementation *
     ************************************/

    /**
     * Default constructor.
     */
    template <class T, size_t A>
    inline aligned_allocator<T, A>::aligned_allocator() noexcept
    {
    }

    /**
     * Copy constructor.
     */
    template <class T, size_t A>
    inline aligned_allocator<T, A>::aligned_allocator(const aligned_allocator&) noexcept
    {
    }

    /**
     * Extended copy constructor.
     */
    template <class T, size_t A>
    template <class U>
    inline aligned_allocator<T, A>::aligned_allocator(const aligned_allocator<U, A>&) noexcept
    {
    }

    /**
     * Destructor.
     */
    template <class T, size_t A>
    inline aligned_allocator<T, A>::~aligned_allocator()
    {
    }

    /**
     * Returns the actual address of \c r even in presence of overloaded \c operator&.
     * @param r the object to acquire address of.
     * @return the actual address of \c r.
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::address(reference r) noexcept -> pointer
    {
        return &r;
    }

    /**
     * Returns the actual address of \c r even in presence of overloaded \c operator&.
     * @param r the object to acquire address of.
     * @return the actual address of \c r.
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::address(const_reference r) const noexcept -> const_pointer
    {
        return &r;
    }

    /**
     * Allocates <tt>n * sizeof(T)</tt> bytes of uninitialized memory, aligned by \c A.
     * The alignment may require some extra memory allocation.
     * @param n the number of objects to allocate storage for.
     * @param hint unused parameter provided for standard compliance.
     * @return a pointer to the first byte of a memory block suitably aligned and sufficient to
     * hold an array of \c n objects of type \c T.
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::allocate(size_type n,
            typename std::allocator<void>::const_pointer) -> pointer
    {
        pointer res = reinterpret_cast<pointer>(aligned_malloc(sizeof(T) * n, A));
        if (res == nullptr)
            throw std::bad_alloc();
        return res;
    }

    /**
     * Deallocates the storage referenced by the pointer p, which must be a pointer obtained by
     * an earlier call to allocate(). The argument \c n must be equal to the first argument of the call
     * to allocate() that originally produced \c p; otherwise, the behavior is undefined.
     * @param p pointer obtained from allocate().
     * @param n number of objects earlier passed to allocate().
     */
    template <class T, size_t A>
    inline void aligned_allocator<T, A>::deallocate(pointer p, size_type)
    {
        aligned_free(p);
    }

    /**
     * Returns the maximum theoretically possible value of \ n, for which the
     * call allocate(n, 0) could succeed.
     * @return themaximum supported allocated size.
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::size_max() const noexcept -> size_type
    {
        return size_type(-1) / sizeof(T);
    }

    /**
     * Constructs an object of type \ T in allocated uninitialized memory
     * pointed to by \ p, using placement-new.
     * @param p pointer to allocated uninitialized memory.
     * @param args the constructor arguments to use.
     */
    template <class T, size_t A>
    template <class U, class... Args>
    inline void aligned_allocator<T, A>::construct(U* p, Args&&... args)
    {
        new ((void*)p) U(std::forward<Args>(args)...);
    }

    /**
     * Calls the destructor of the object pointed to by \c p.
     * @param p pointer to the object that is going to be destroyed.
     */
    template <class T, size_t A>
    template <class U>
    inline void aligned_allocator<T, A>::destroy(U* p)
    {
        p->~U();
    }

    /**
     * @defgroup allocator_comparison Comparison operators
     */

    /**
     * @ingroup allocator_comparison
     * Compares two aligned memory allocator for equality. Since allocators
     * are stateless, return \c true iff <tt>A1 == A2</tt>.
     * @param lhs aligned_allocator to compare.
     * @param rhs aligned_allocator to compare.
     * @return true if the allocators have the same alignment.
     */
    template <class T1, size_t A1, class T2, size_t A2>
    inline bool operator==(const aligned_allocator<T1, A1>& lhs,
                           const aligned_allocator<T2, A2>& rhs) noexcept
    {
        return lhs.alignment == rhs.alignment;
    }

    /**
    * @ingroup allocator_comparison
     * Compares two aligned memory allocator for inequality. Since allocators
     * are stateless, return \c true iff <tt>A1 != A2</tt>.
     * @param lhs aligned_allocator to compare.
     * @param rhs aligned_allocator to compare.
     * @return true if the allocators have different alignments.
     */
    template <class T1, size_t A1, class T2, size_t A2>
    inline bool operator!=(const aligned_allocator<T1, A1>& lhs,
                           const aligned_allocator<T2, A2>& rhs) noexcept
    {
        return !(lhs == rhs);
    }

    /****************************************
     * aligned malloc / free implementation *
     ****************************************/

    namespace detail
    {
        inline void* xaligned_malloc(size_t size, size_t alignment)
        {
            void* res = 0;
            void* ptr = malloc(size + alignment);
            if (ptr != 0)
            {
                res = reinterpret_cast<void*>(
                    (reinterpret_cast<size_t>(ptr) & ~(size_t(alignment - 1))) +
                    alignment);
                *(reinterpret_cast<void**>(res) - 1) = ptr;
            }
            return res;
        }

        inline void xaligned_free(void* ptr)
        {
            if (ptr != 0)
                free(*(reinterpret_cast<void**>(ptr) - 1));
        }
    }

    inline void* aligned_malloc(size_t size, size_t alignment)
    {
        return detail::xaligned_malloc(size, alignment);
    }

    inline void aligned_free(void* ptr)
    {
        detail::xaligned_free(ptr);
    }

    template <class T>
    inline size_t get_alignment_offset(const T* p, size_t size, size_t block_size)
    {
        // size_t block_size = simd_traits<T>::size;
        if (block_size == 1)
        {
            // The simd_block consists of exactly one scalar so that all
            // elements of the array
            // are "well" aligned.
            return 0;
        }
        else if (size_t(p) & (sizeof(T) - 1))
        {
            // The array is not aligned to the size of a single element, so that
            // no element
            // of the array is well aligned
            return size;
        }
        else
        {
            size_t block_mask = block_size - 1;
            return std::min<size_t>(
                (block_size - ((size_t(p) / sizeof(T)) & block_mask)) & block_mask,
                size);
        }
    };
}

#endif
<commit_msg>missing max_size method in aligned_allocator<commit_after>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay                     *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#ifndef XSIMD_ALIGNED_ALLOCATOR_HPP
#define XSIMD_ALIGNED_ALLOCATOR_HPP

#include <algorithm>
#include <memory>
#include <cstddef>
#include <stdlib.h>

#include "../config/xsimd_align.hpp"

#if defined(XSIMD_ALLOCA)
#if defined(__GNUC__)
#include <alloca.h>
#elif defined(_MSC_VER)
#include <malloc.h>
#endif
#endif

namespace xsimd
{

    /**
     * @class aligned_allocator
     * @brief Allocator for aligned memory
     *
     * The aligned_allocator class template is an allocator that
     * performs memory allocation aligned by the specified value.
     *
     * @tparam T type of objects to allocate.
     * @tparam Align alignment in bytes.
     */
    template <class T, size_t Align>
    class aligned_allocator
    {
    public:

        using value_type = T;
        using pointer = T*;
        using const_pointer = const T*;
        using reference = T&;
        using const_reference = const T&;
        using size_type = size_t;
        using difference_type = ptrdiff_t;

        static constexpr size_t alignment = Align;

        template <class U>
        struct rebind
        {
            using other = aligned_allocator<U, Align>;
        };

        aligned_allocator() noexcept;
        aligned_allocator(const aligned_allocator& rhs) noexcept;

        template <class U>
        aligned_allocator(const aligned_allocator<U, Align>& rhs) noexcept;

        ~aligned_allocator();

        pointer address(reference) noexcept;
        const_pointer address(const_reference) const noexcept;

        pointer allocate(size_type n, typename std::allocator<void>::const_pointer hint = 0);
        void deallocate(pointer p, size_type n);

        size_type max_size() const noexcept;
        size_type size_max() const noexcept;

        template <class U, class... Args>
        void construct(U* p, Args&&... args);

        template <class U>
        void destroy(U* p);
    };

    template <class T1, size_t Align1, class T2, size_t Align2>
    bool operator==(const aligned_allocator<T1, Align1>& lhs,
                    const aligned_allocator<T2, Align2>& rhs) noexcept;

    template <class T1, size_t Align1, class T2, size_t Align2>
    bool operator!=(const aligned_allocator<T1, Align1>& lhs,
                    const aligned_allocator<T2, Align2>& rhs) noexcept;

    void* aligned_malloc(size_t size, size_t alignment);
    void aligned_free(void* ptr);

    template <class T>
    size_t get_alignment_offset(const T* p, size_t size, size_t block_size);

    /************************************
     * aligned_allocator implementation *
     ************************************/

    /**
     * Default constructor.
     */
    template <class T, size_t A>
    inline aligned_allocator<T, A>::aligned_allocator() noexcept
    {
    }

    /**
     * Copy constructor.
     */
    template <class T, size_t A>
    inline aligned_allocator<T, A>::aligned_allocator(const aligned_allocator&) noexcept
    {
    }

    /**
     * Extended copy constructor.
     */
    template <class T, size_t A>
    template <class U>
    inline aligned_allocator<T, A>::aligned_allocator(const aligned_allocator<U, A>&) noexcept
    {
    }

    /**
     * Destructor.
     */
    template <class T, size_t A>
    inline aligned_allocator<T, A>::~aligned_allocator()
    {
    }

    /**
     * Returns the actual address of \c r even in presence of overloaded \c operator&.
     * @param r the object to acquire address of.
     * @return the actual address of \c r.
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::address(reference r) noexcept -> pointer
    {
        return &r;
    }

    /**
     * Returns the actual address of \c r even in presence of overloaded \c operator&.
     * @param r the object to acquire address of.
     * @return the actual address of \c r.
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::address(const_reference r) const noexcept -> const_pointer
    {
        return &r;
    }

    /**
     * Allocates <tt>n * sizeof(T)</tt> bytes of uninitialized memory, aligned by \c A.
     * The alignment may require some extra memory allocation.
     * @param n the number of objects to allocate storage for.
     * @param hint unused parameter provided for standard compliance.
     * @return a pointer to the first byte of a memory block suitably aligned and sufficient to
     * hold an array of \c n objects of type \c T.
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::allocate(size_type n,
            typename std::allocator<void>::const_pointer) -> pointer
    {
        pointer res = reinterpret_cast<pointer>(aligned_malloc(sizeof(T) * n, A));
        if (res == nullptr)
            throw std::bad_alloc();
        return res;
    }

    /**
     * Deallocates the storage referenced by the pointer p, which must be a pointer obtained by
     * an earlier call to allocate(). The argument \c n must be equal to the first argument of the call
     * to allocate() that originally produced \c p; otherwise, the behavior is undefined.
     * @param p pointer obtained from allocate().
     * @param n number of objects earlier passed to allocate().
     */
    template <class T, size_t A>
    inline void aligned_allocator<T, A>::deallocate(pointer p, size_type)
    {
        aligned_free(p);
    }

    /**
     * Returns the maximum theoretically possible value of \c n, for which the
     * call allocate(n, 0) could succeed.
     * @return the maximum supported allocated size.
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::max_size() const noexcept -> size_type
    {
        return size_type(-1) / sizeof(T);
    }

    /**
     * This method is deprecated, use max_size() instead
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::size_max() const noexcept -> size_type
    {
        return size_type(-1) / sizeof(T);
    }

    /**
     * Constructs an object of type \c T in allocated uninitialized memory
     * pointed to by \c p, using placement-new.
     * @param p pointer to allocated uninitialized memory.
     * @param args the constructor arguments to use.
     */
    template <class T, size_t A>
    template <class U, class... Args>
    inline void aligned_allocator<T, A>::construct(U* p, Args&&... args)
    {
        new ((void*)p) U(std::forward<Args>(args)...);
    }

    /**
     * Calls the destructor of the object pointed to by \c p.
     * @param p pointer to the object that is going to be destroyed.
     */
    template <class T, size_t A>
    template <class U>
    inline void aligned_allocator<T, A>::destroy(U* p)
    {
        p->~U();
    }

    /**
     * @defgroup allocator_comparison Comparison operators
     */

    /**
     * @ingroup allocator_comparison
     * Compares two aligned memory allocator for equality. Since allocators
     * are stateless, return \c true iff <tt>A1 == A2</tt>.
     * @param lhs aligned_allocator to compare.
     * @param rhs aligned_allocator to compare.
     * @return true if the allocators have the same alignment.
     */
    template <class T1, size_t A1, class T2, size_t A2>
    inline bool operator==(const aligned_allocator<T1, A1>& lhs,
                           const aligned_allocator<T2, A2>& rhs) noexcept
    {
        return lhs.alignment == rhs.alignment;
    }

    /**
    * @ingroup allocator_comparison
     * Compares two aligned memory allocator for inequality. Since allocators
     * are stateless, return \c true iff <tt>A1 != A2</tt>.
     * @param lhs aligned_allocator to compare.
     * @param rhs aligned_allocator to compare.
     * @return true if the allocators have different alignments.
     */
    template <class T1, size_t A1, class T2, size_t A2>
    inline bool operator!=(const aligned_allocator<T1, A1>& lhs,
                           const aligned_allocator<T2, A2>& rhs) noexcept
    {
        return !(lhs == rhs);
    }

    /****************************************
     * aligned malloc / free implementation *
     ****************************************/

    namespace detail
    {
        inline void* xaligned_malloc(size_t size, size_t alignment)
        {
            void* res = 0;
            void* ptr = malloc(size + alignment);
            if (ptr != 0)
            {
                res = reinterpret_cast<void*>(
                    (reinterpret_cast<size_t>(ptr) & ~(size_t(alignment - 1))) +
                    alignment);
                *(reinterpret_cast<void**>(res) - 1) = ptr;
            }
            return res;
        }

        inline void xaligned_free(void* ptr)
        {
            if (ptr != 0)
                free(*(reinterpret_cast<void**>(ptr) - 1));
        }
    }

    inline void* aligned_malloc(size_t size, size_t alignment)
    {
        return detail::xaligned_malloc(size, alignment);
    }

    inline void aligned_free(void* ptr)
    {
        detail::xaligned_free(ptr);
    }

    template <class T>
    inline size_t get_alignment_offset(const T* p, size_t size, size_t block_size)
    {
        // size_t block_size = simd_traits<T>::size;
        if (block_size == 1)
        {
            // The simd_block consists of exactly one scalar so that all
            // elements of the array
            // are "well" aligned.
            return 0;
        }
        else if (size_t(p) & (sizeof(T) - 1))
        {
            // The array is not aligned to the size of a single element, so that
            // no element
            // of the array is well aligned
            return size;
        }
        else
        {
            size_t block_mask = block_size - 1;
            return std::min<size_t>(
                (block_size - ((size_t(p) / sizeof(T)) & block_mask)) & block_mask,
                size);
        }
    };
}

#endif
<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 18503 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.

=========================================================================*/

#include "mitkDataStorageAccessRule.h"
#include <Poco/Exception.h>

mitk::DataStorageAccessRule
::DataStorageAccessRule (mitk::DataStorage::Pointer myDataStorage, mitk::DataTreeNode::Pointer myDataTreeNode,
                         mitk::DataStorageAccessRule::RuleType myRule)
 :m_Rule(myRule),
  m_sptrMyDataStorage(myDataStorage),
  m_sptrMyDataTreeNode(myDataTreeNode)

 {
   mitk::DataStorage::SetOfObjects::ConstPointer
   sptr_parentsNodesFirstRule = m_sptrMyDataStorage->GetSources(m_sptrMyDataTreeNode);
   // checks if the DataTreeNode does exists within the specified DataTree, if not an
   // Poco NotFoundException is thrown since the rule is useless
   bool exsists = false ;
   for(mitk::DataStorage::SetOfObjects::const_iterator it =
        sptr_parentsNodesFirstRule->begin(); it != sptr_parentsNodesFirstRule->end(); ++ it)
      {
        if (*it == m_sptrMyDataTreeNode ) exsists = true ;
      }
   if (exsists == false) throw  Poco::NotFoundException()  ;

 }

bool
  mitk::DataStorageAccessRule
   ::Contains(cherry::ISchedulingRule::Pointer rule)
  {
  DataStorageAccessRule::Pointer sptr_temp = rule.Cast<DataStorageAccessRule>();
  // test if the ISchedulingRule is a DataStorageAccessRule
  if( sptr_temp == 0 ) return false ;
  // test if the DataStorageAccessRule object is exactly the instance
  else {
    if ( this == sptr_temp.GetPointer() ) return true ;

    return false ;
    }
  }

bool
  mitk::DataStorageAccessRule
    ::IsConflicting(cherry::ISchedulingRule::Pointer sptr_otherISchedulingRule)
  {
     // test if the stored dataTreeNode
     // cast to check if the ISchedulingRule is a DataStorageAccessRule
    DataStorageAccessRule::Pointer sptr_DataStorageAccessRule = sptr_otherISchedulingRule.Cast<DataStorageAccessRule>();
     // checks if the Rule of the type ISchedulingRule is a DataStorageAccessRule
     if(sptr_DataStorageAccessRule == 0) return false ;

     // the rule to be compared with is a DataStorageAccessRule
     else
   {
     // testing if both jobs holding each rule do operate on the same DataStorage if not false is returned
     if( !CompareDataStorages(sptr_DataStorageAccessRule->GetDataStorage()) ) return false ;

     // checks if to rules to be compared are two add rules
     if (m_Rule == ADD_RULE && m_Rule == sptr_DataStorageAccessRule->GetRuleType())
       return CompareTwoAddorRemoveRules() ;

     // checks if to the two rules to be compared are two remove rules
     if(m_Rule == REMOVE_RULE && m_Rule == sptr_DataStorageAccessRule->GetRuleType())
       return CompareTwoAddorRemoveRules() ;

     // an add and remove rule needs to be compared
     else
       {
        return CompareAddandRemoveRules(sptr_DataStorageAccessRule) ;
       }

   }

  }

 bool
   mitk::DataStorageAccessRule
   ::CompareAddandRemoveRules(mitk::DataStorageAccessRule::Pointer sptr_otherDataStorageAccessRule) const
 {

      mitk::DataStorage::SetOfObjects::ConstPointer
        sptr_parentsNodesFirstRule = m_sptrMyDataStorage->GetSources(m_sptrMyDataTreeNode);
     // checks if the DataStorageNode of to be compared DataStorageAccessRule is a parent node
     // if so the job holding this DataStorageAccessRule need to wait until the operation on the parent node is performed
      for(mitk::DataStorage::SetOfObjects::const_iterator it =
        sptr_parentsNodesFirstRule->begin(); it != sptr_parentsNodesFirstRule->end(); ++ it)
      {
      if (*it == sptr_otherDataStorageAccessRule->GetDataTreeNode()) return true ;
      }
      mitk::DataStorage::SetOfObjects::ConstPointer
        sptr_derivedNodesRule = m_sptrMyDataStorage->GetDerivations(m_sptrMyDataTreeNode);
      // checks if the DataStorage node of to be compared DataStorageAccessRule is a child node
      // if so the job holding this DataStorageAccessRule needs to wait until the operation on the parent node is performed
      for(mitk::DataStorage::SetOfObjects::const_iterator it =
        sptr_derivedNodesRule->begin(); it != sptr_derivedNodesRule->end(); ++it)
      {
      if(*it == sptr_otherDataStorageAccessRule->GetDataTreeNode()) return true ;
      }

     // jobs operating on nodes on different branches do not cause conflicts thus they can be performed in different
     // threads concurrently
        return false ;
 }

 bool
   mitk::DataStorageAccessRule
   ::CompareDataStorages(mitk::DataStorage::Pointer otherDataStorage) const
   {
    if(m_sptrMyDataStorage == otherDataStorage) return true ;
    else return false;
   }

 bool
   mitk::DataStorageAccessRule
   ::CompareTwoAddorRemoveRules() const
   {
       return false ;
   }

 bool
   mitk::DataStorageAccessRule
   ::TestDataTreeNode(mitk::DataTreeNode::Pointer dataTreeToBeStored) const
  {
   mitk::DataStorage::SetOfObjects::ConstPointer tempAllNodes = m_sptrMyDataStorage->GetAll();
   for(mitk::DataStorage::SetOfObjects::const_iterator it = tempAllNodes->begin(); it !=tempAllNodes->end(); ++ it){
     if (m_sptrMyDataTreeNode == *it ) return true ;

     }
   return false ;

  }

 mitk::DataTreeNode::Pointer
   mitk::DataStorageAccessRule
    ::GetDataTreeNode() const
   {
    return mitk::DataStorageAccessRule::m_sptrMyDataTreeNode ;
   }

 mitk::DataStorage::Pointer
   mitk::DataStorageAccessRule
   ::GetDataStorage() const
  {
    return mitk::DataStorageAccessRule::m_sptrMyDataStorage ;
  }

 mitk::DataStorageAccessRule::RuleType
   mitk::DataStorageAccessRule
   ::GetRuleType() const
   {
   if (m_Rule == ADD_RULE)
     return ( mitk::DataStorageAccessRule::ADD_RULE ) ;
   else {
     return ( mitk::DataStorageAccessRule::RuleType::REMOVE_RULE ) ;

     }
   }

 <commit_msg>COMP: removing enum namespace<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 18503 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.

=========================================================================*/

#include "mitkDataStorageAccessRule.h"
#include <Poco/Exception.h>

mitk::DataStorageAccessRule
::DataStorageAccessRule (mitk::DataStorage::Pointer myDataStorage, mitk::DataTreeNode::Pointer myDataTreeNode,
                         mitk::DataStorageAccessRule::RuleType myRule)
 :m_Rule(myRule),
  m_sptrMyDataStorage(myDataStorage),
  m_sptrMyDataTreeNode(myDataTreeNode)

 {
   mitk::DataStorage::SetOfObjects::ConstPointer
   sptr_parentsNodesFirstRule = m_sptrMyDataStorage->GetSources(m_sptrMyDataTreeNode);
   // checks if the DataTreeNode does exists within the specified DataTree, if not an
   // Poco NotFoundException is thrown since the rule is useless
   bool exsists = false ;
   for(mitk::DataStorage::SetOfObjects::const_iterator it =
        sptr_parentsNodesFirstRule->begin(); it != sptr_parentsNodesFirstRule->end(); ++ it)
      {
        if (*it == m_sptrMyDataTreeNode ) exsists = true ;
      }
   if (exsists == false) throw  Poco::NotFoundException()  ;

 }

bool
  mitk::DataStorageAccessRule
   ::Contains(cherry::ISchedulingRule::Pointer rule)
  {
  DataStorageAccessRule::Pointer sptr_temp = rule.Cast<DataStorageAccessRule>();
  // test if the ISchedulingRule is a DataStorageAccessRule
  if( sptr_temp == 0 ) return false ;
  // test if the DataStorageAccessRule object is exactly the instance
  else {
    if ( this == sptr_temp.GetPointer() ) return true ;

    return false ;
    }
  }

bool
  mitk::DataStorageAccessRule
    ::IsConflicting(cherry::ISchedulingRule::Pointer sptr_otherISchedulingRule)
  {
     // test if the stored dataTreeNode
     // cast to check if the ISchedulingRule is a DataStorageAccessRule
    DataStorageAccessRule::Pointer sptr_DataStorageAccessRule = sptr_otherISchedulingRule.Cast<DataStorageAccessRule>();
     // checks if the Rule of the type ISchedulingRule is a DataStorageAccessRule
     if(sptr_DataStorageAccessRule == 0) return false ;

     // the rule to be compared with is a DataStorageAccessRule
     else
   {
     // testing if both jobs holding each rule do operate on the same DataStorage if not false is returned
     if( !CompareDataStorages(sptr_DataStorageAccessRule->GetDataStorage()) ) return false ;

     // checks if to rules to be compared are two add rules
     if (m_Rule == ADD_RULE && m_Rule == sptr_DataStorageAccessRule->GetRuleType())
       return CompareTwoAddorRemoveRules() ;

     // checks if to the two rules to be compared are two remove rules
     if(m_Rule == REMOVE_RULE && m_Rule == sptr_DataStorageAccessRule->GetRuleType())
       return CompareTwoAddorRemoveRules() ;

     // an add and remove rule needs to be compared
     else
       {
        return CompareAddandRemoveRules(sptr_DataStorageAccessRule) ;
       }

   }

  }

 bool
   mitk::DataStorageAccessRule
   ::CompareAddandRemoveRules(mitk::DataStorageAccessRule::Pointer sptr_otherDataStorageAccessRule) const
 {

      mitk::DataStorage::SetOfObjects::ConstPointer
        sptr_parentsNodesFirstRule = m_sptrMyDataStorage->GetSources(m_sptrMyDataTreeNode);
     // checks if the DataStorageNode of to be compared DataStorageAccessRule is a parent node
     // if so the job holding this DataStorageAccessRule need to wait until the operation on the parent node is performed
      for(mitk::DataStorage::SetOfObjects::const_iterator it =
        sptr_parentsNodesFirstRule->begin(); it != sptr_parentsNodesFirstRule->end(); ++ it)
      {
      if (*it == sptr_otherDataStorageAccessRule->GetDataTreeNode()) return true ;
      }
      mitk::DataStorage::SetOfObjects::ConstPointer
        sptr_derivedNodesRule = m_sptrMyDataStorage->GetDerivations(m_sptrMyDataTreeNode);
      // checks if the DataStorage node of to be compared DataStorageAccessRule is a child node
      // if so the job holding this DataStorageAccessRule needs to wait until the operation on the parent node is performed
      for(mitk::DataStorage::SetOfObjects::const_iterator it =
        sptr_derivedNodesRule->begin(); it != sptr_derivedNodesRule->end(); ++it)
      {
      if(*it == sptr_otherDataStorageAccessRule->GetDataTreeNode()) return true ;
      }

     // jobs operating on nodes on different branches do not cause conflicts thus they can be performed in different
     // threads concurrently
        return false ;
 }

 bool
   mitk::DataStorageAccessRule
   ::CompareDataStorages(mitk::DataStorage::Pointer otherDataStorage) const
   {
    if(m_sptrMyDataStorage == otherDataStorage) return true ;
    else return false;
   }

 bool
   mitk::DataStorageAccessRule
   ::CompareTwoAddorRemoveRules() const
   {
       return false ;
   }

 bool
   mitk::DataStorageAccessRule
   ::TestDataTreeNode(mitk::DataTreeNode::Pointer dataTreeToBeStored) const
  {
   mitk::DataStorage::SetOfObjects::ConstPointer tempAllNodes = m_sptrMyDataStorage->GetAll();
   for(mitk::DataStorage::SetOfObjects::const_iterator it = tempAllNodes->begin(); it !=tempAllNodes->end(); ++ it){
     if (m_sptrMyDataTreeNode == *it ) return true ;

     }
   return false ;

  }

 mitk::DataTreeNode::Pointer
   mitk::DataStorageAccessRule
    ::GetDataTreeNode() const
   {
    return mitk::DataStorageAccessRule::m_sptrMyDataTreeNode ;
   }

 mitk::DataStorage::Pointer
   mitk::DataStorageAccessRule
   ::GetDataStorage() const
  {
    return mitk::DataStorageAccessRule::m_sptrMyDataStorage ;
  }

 mitk::DataStorageAccessRule::RuleType
   mitk::DataStorageAccessRule
   ::GetRuleType() const
   {
   if (m_Rule == ADD_RULE)
     return ( mitk::DataStorageAccessRule::ADD_RULE ) ;
   else {
     return ( mitk::DataStorageAccessRule::REMOVE_RULE ) ;

     }
   }

<|endoftext|>


<commit_before>#include "Socket.h"

#include <algorithm>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sstream>
#include <iostream>

Socket::Socket()
{
	// No socket.
	fd = -1;
}
Socket::Socket(int sock)
{
	fd = sock;
}

Socket::~Socket()
{
	if (fd != -1)
		::close(fd);
}

bool Socket::connect4(const bytes& ip, uint16_t port)
{
	Socket::close();

	fd = socket(AF_INET, SOCK_STREAM, 0);

	sockaddr_in dest_addr;
	char* a = reinterpret_cast<char*>(&dest_addr.sin_addr.s_addr);
	a[0] = ip[0]; // Tested on sane little endian architecture.
	a[1] = ip[1]; // Does anyone still use big endian?
	a[2] = ip[2];
	a[3] = ip[3];
	dest_addr.sin_port = htons(port);
	dest_addr.sin_family = AF_INET;

	char output[INET_ADDRSTRLEN];
	inet_ntop(AF_INET, &(dest_addr.sin_addr), output, INET_ADDRSTRLEN);
	std::cerr << "Connecting to " << output << ":" << port << std::endl;

	if (::connect(fd, reinterpret_cast<sockaddr*>(&dest_addr), sizeof(dest_addr)) == -1)
	{
		::close(fd);
		fd = -1;
		return false;
	}
	return true;
}

bool Socket::connect6(const bytes& ip, uint16_t port)
{
	Socket::close();

	fd = socket(AF_INET6, SOCK_STREAM, 0);

	sockaddr_in6 dest_addr;
	for (int i = 0; i < 16; ++i)
		dest_addr.sin6_addr.s6_addr[i] = ip[i];
	dest_addr.sin6_port = htons(port);
	dest_addr.sin6_family = AF_INET;
	dest_addr.sin6_flowinfo = 0; // No idea what these do.
	dest_addr.sin6_scope_id = 0;

	char output[INET6_ADDRSTRLEN];
	inet_ntop(AF_INET6, &(dest_addr.sin6_port), output, INET6_ADDRSTRLEN);
	std::cerr << "Connecting to " << output << ":" << port << std::endl;

	if (::connect(fd, reinterpret_cast<sockaddr*>(&dest_addr), sizeof(dest_addr)) == -1)
	{
		::close(fd);
		fd = -1;
		return false;
	}
	return true;
}

bool Socket::connect(const std::string& domain, uint16_t port)
{
	Socket::close();

	std::cerr << "Connecting to " << domain << ":" << port << std::endl;

	std::stringstream service;
	service << port;

	addrinfo* addrs = nullptr;
	int r = getaddrinfo(domain.c_str(), service.str().c_str(), nullptr, &addrs);
	if (r != 0)
	{
		return false;
	}

	if (!addrs)
	{
		return false;
	}

	for (addrinfo* p = addrs; p->ai_next; p = p->ai_next)
	{
		if ((p->ai_family == AF_INET /*|| p->ai_family == AF_INET6*/) // TODO: IPv6!
				&& (p->ai_socktype == SOCK_STREAM))
		{
			// Ok use this one.
			fd = socket(p->ai_family, SOCK_STREAM, 0);
			if (::connect(fd, p->ai_addr, p->ai_addrlen) == -1)
			{
				freeaddrinfo(addrs);
				::close(fd);
				fd = -1;
				return false;
			}

			freeaddrinfo(addrs);
			return true;
		}
	}
	return false;
}

bool Socket::send(const bytes& d)
{
	if (fd == -1)
	{
		errno = EBADF;
		return false;
	}
	int s = ::send(fd, d.data(), d.size(), 0);
	return s != -1;
}

bool Socket::receive(bytes& d, int size)
{
	int flags = size > 0 ? MSG_WAITALL : 0;

	if (size <= 0)
		size = 4096;

	char buffer[4096];
	d.clear();

	if (fd == -1)
	{
		errno = EBADF;
		return false;
	}
	int s = ::recv(fd, buffer, size, flags);
	if (s == -1)
		return false;
	d.append(buffer, s);
	return true;
}

int Socket::descriptor()
{
	return fd;
}

void Socket::close()
{
	if (fd == -1)
		return;
	::close(fd);
	fd = -1;
}

#ifdef __linux__
bool Socket::originalDestination(uint32_t& ip, uint16_t& port) const
{
	ip = 0;
	port = 0;

	if (fd == -1)
	{
		errno = EBADF;
		return false;
	}

	sockaddr_in dest_addr;
	socklen_t dest_addr_len = sizeof(dest_addr);
	if (getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, &dest_addr, &dest_addr_len) == -1)
		return false;

	ip = ntohl(dest_addr.sin_addr.s_addr);
	port = ntohs(dest_addr.sin_port);
	return true;
}
#endif

int hexChar(char c)
{
	switch (c)
	{
	case '0':
		return 0;
	case '1':
		return 1;
	case '2':
		return 2;
	case '3':
		return 3;
	case '4':
		return 4;
	case '5':
		return 5;
	case '6':
		return 6;
	case '7':
		return 7;
	case '8':
		return 8;
	case '9':
		return 9;
	case 'a':
	case 'A':
		return 10;
	case 'b':
	case 'B':
		return 11;
	case 'c':
	case 'C':
		return 12;
	case 'd':
	case 'D':
		return 13;
	case 'e':
	case 'E':
		return 14;
	case 'f':
	case 'F':
		return 15;
	}
	return 0;
}

bytes hexBytes(const std::string& hb)
{
	bytes b;
	for (unsigned int i = 0; i < hb.size()/2; ++i)
	{
		unsigned char c = (hexChar(hb[2*i]) << 4) | hexChar(hb[2*i+1]);
		b.append(1, c);
	}
	return b;
}
<commit_msg>Disabled old hex conversion<commit_after>#include "Socket.h"

#include <algorithm>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sstream>
#include <iostream>
#include "Util.h"

Socket::Socket()
{
	// No socket.
	fd = -1;
}
Socket::Socket(int sock)
{
	fd = sock;
}

Socket::~Socket()
{
	if (fd != -1)
		::close(fd);
}

bool Socket::connect4(const bytes& ip, uint16_t port)
{
	Socket::close();

	fd = socket(AF_INET, SOCK_STREAM, 0);

	sockaddr_in dest_addr;
	char* a = reinterpret_cast<char*>(&dest_addr.sin_addr.s_addr);
	a[0] = ip[0]; // Tested on sane little endian architecture.
	a[1] = ip[1]; // Does anyone still use big endian?
	a[2] = ip[2];
	a[3] = ip[3];
	dest_addr.sin_port = htons(port);
	dest_addr.sin_family = AF_INET;

	char output[INET_ADDRSTRLEN];
	inet_ntop(AF_INET, &(dest_addr.sin_addr), output, INET_ADDRSTRLEN);
	std::cerr << "Connecting to " << output << ":" << port << std::endl;

	if (::connect(fd, reinterpret_cast<sockaddr*>(&dest_addr), sizeof(dest_addr)) == -1)
	{
		::close(fd);
		fd = -1;
		return false;
	}
	return true;
}

bool Socket::connect6(const bytes& ip, uint16_t port)
{
	Socket::close();

	fd = socket(AF_INET6, SOCK_STREAM, 0);

	sockaddr_in6 dest_addr;
	for (int i = 0; i < 16; ++i)
		dest_addr.sin6_addr.s6_addr[i] = ip[i];
	dest_addr.sin6_port = htons(port);
	dest_addr.sin6_family = AF_INET;
	dest_addr.sin6_flowinfo = 0; // No idea what these do.
	dest_addr.sin6_scope_id = 0;

	char output[INET6_ADDRSTRLEN];
	inet_ntop(AF_INET6, &(dest_addr.sin6_port), output, INET6_ADDRSTRLEN);
	std::cerr << "Connecting to " << output << ":" << port << std::endl;

	if (::connect(fd, reinterpret_cast<sockaddr*>(&dest_addr), sizeof(dest_addr)) == -1)
	{
		::close(fd);
		fd = -1;
		return false;
	}
	return true;
}

bool Socket::connect(const std::string& domain, uint16_t port)
{
	Socket::close();

	std::cerr << "Connecting to " << domain << ":" << port << std::endl;

	std::stringstream service;
	service << port;

	addrinfo* addrs = nullptr;
	int r = getaddrinfo(domain.c_str(), service.str().c_str(), nullptr, &addrs);
	if (r != 0)
	{
		return false;
	}

	if (!addrs)
	{
		return false;
	}

	for (addrinfo* p = addrs; p->ai_next; p = p->ai_next)
	{
		if ((p->ai_family == AF_INET /*|| p->ai_family == AF_INET6*/) // TODO: IPv6!
				&& (p->ai_socktype == SOCK_STREAM))
		{
			// Ok use this one.
			fd = socket(p->ai_family, SOCK_STREAM, 0);
			if (::connect(fd, p->ai_addr, p->ai_addrlen) == -1)
			{
				freeaddrinfo(addrs);
				::close(fd);
				fd = -1;
				return false;
			}

			freeaddrinfo(addrs);
			return true;
		}
	}
	return false;
}

bool Socket::send(const bytes& d)
{
	if (fd == -1)
	{
		errno = EBADF;
		return false;
	}
	int s = ::send(fd, d.data(), d.size(), 0);
	return s != -1;
}

bool Socket::receive(bytes& d, int size)
{
	int flags = size > 0 ? MSG_WAITALL : 0;

	if (size <= 0)
		size = 4096;

	char buffer[4096];
	d.clear();

	if (fd == -1)
	{
		errno = EBADF;
		return false;
	}
	int s = ::recv(fd, buffer, size, flags);
	if (s == -1)
		return false;
	d.append(buffer, s);
	return true;
}

int Socket::descriptor()
{
	return fd;
}

void Socket::close()
{
	if (fd == -1)
		return;
	::close(fd);
	fd = -1;
}

#ifdef __linux__
bool Socket::originalDestination(uint32_t& ip, uint16_t& port) const
{
	ip = 0;
	port = 0;

	if (fd == -1)
	{
		errno = EBADF;
		return false;
	}

	sockaddr_in dest_addr;
	socklen_t dest_addr_len = sizeof(dest_addr);
	if (getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, &dest_addr, &dest_addr_len) == -1)
		return false;

	ip = ntohl(dest_addr.sin_addr.s_addr);
	port = ntohs(dest_addr.sin_port);
	return true;
}
#endif

int hexChar(char c)
{
	switch (c)
	{
	case '0':
		return 0;
	case '1':
		return 1;
	case '2':
		return 2;
	case '3':
		return 3;
	case '4':
		return 4;
	case '5':
		return 5;
	case '6':
		return 6;
	case '7':
		return 7;
	case '8':
		return 8;
	case '9':
		return 9;
	case 'a':
	case 'A':
		return 10;
	case 'b':
	case 'B':
		return 11;
	case 'c':
	case 'C':
		return 12;
	case 'd':
	case 'D':
		return 13;
	case 'e':
	case 'E':
		return 14;
	case 'f':
	case 'F':
		return 15;
	}
	return 0;
}

bytes hexBytes(const std::string& hb)
{
	bytes b = Util::hexToString(hb); //ss.str();
	return b;
	/*
	for (unsigned int i = 0; i < hb.size()/2; ++i)
	{
		unsigned char c = (hexChar(hb[2*i]) << 4) | hexChar(hb[2*i+1]);
		b.append(1, c);
	}
	return b;
	*/
}
<|endoftext|>


<commit_before>/*
 * Copyright 2014-2018 Kacper Kasper <kacperkasper@gmail.com>
 * All rights reserved. Distributed under the terms of the MIT license.
 */

#include "Styler.h"

#include <unordered_map>
#include <vector>

#include <yaml-cpp/yaml.h>

#include <Alert.h>
#include <Directory.h>
#include <FindDirectory.h>
#include <Path.h>
#include <String.h>

#include "Editor.h"
#include "EditorWindow.h"
#include "Utils.h"

#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Styler"

namespace YAML {

namespace {

int
CSSToInt(const std::string cssColor)
{
	if(cssColor[0] != '#' || cssColor.length() != 7)
		return -1;

	std::string red = cssColor.substr(1, 2);
	std::string green = cssColor.substr(3, 2);
	std::string blue = cssColor.substr(5, 2);

	return std::stoi(blue + green + red, nullptr, 16);
}

}

template<>
struct convert<Styler::Style> {
	static Node encode(const Styler::Style& rhs) {
		// TODO
	}

	static bool decode(const Node& node, Styler::Style& rhs) {
		if(!node.IsMap()) {
			return false;
		}

		if(node["foreground"]) {
			rhs.fgColor = CSSToInt(node["foreground"].as<std::string>());
		}
		if(node["background"]) {
			rhs.bgColor = CSSToInt(node["background"].as<std::string>());
		}
		if(node["style"] && node["style"].IsSequence()) {
			rhs.style = 0;
			const auto styles = node["style"].as<std::vector<std::string>>();
			for(const auto& style : styles) {
				if(style == "bold")
					rhs.style |= 1;
				else if(style == "italic")
					rhs.style |= 2;
				else if(style == "underline")
					rhs.style |= 4;
			}
		}
		return true;
	}
};

}

std::unordered_map<int, Styler::Style>	Styler::sStylesMapping;

/* static */ void
Styler::ApplyGlobal(Editor* editor, const char* style)
{
	static bool alertShown = false;
	bool found = false;
	BPath dataPath;
	find_directory(B_SYSTEM_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
		found = true;
	} catch (YAML::BadFile &) {
	}
	find_directory(B_USER_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
		found = true;
	} catch (YAML::BadFile &) {
	}
	find_directory(B_SYSTEM_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
		found = true;
	} catch (YAML::BadFile &) {
	}
	find_directory(B_USER_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
		found = true;
	} catch (YAML::BadFile &) {
	}
	if(found == false && alertShown == false) {
		alertShown = true;
		BAlert* alert = new BAlert(B_TRANSLATE("Style files"),
			B_TRANSLATE("Couldn't find style files. Make sure you have them "
				"installed in one of your data directories."),
				B_TRANSLATE("OK"), nullptr, nullptr, B_WIDTH_AS_USUAL,
				B_WARNING_ALERT);
		alert->Go();
	}
}

/* static */ void
Styler::_ApplyGlobal(Editor* editor, const char* style, const BPath &path)
{
	BPath p(path);
	p.Append(gAppName);
	p.Append("styles");
	p.Append(style);
	const YAML::Node styles = YAML::LoadFile(std::string(p.Path()) + ".yaml");
	YAML::Node global;
	if(styles["Global"]) {
		global = styles["Global"];
	}

	int id;
	Style s;
	if(global["Default"]) {
		_GetAttributesFromNode(global["Default"], id, s);

		font_family fixed;
		be_fixed_font->GetFamilyAndStyle(&fixed, nullptr);
		editor->SendMessage(SCI_STYLESETFONT, 32, (sptr_t) fixed);
		editor->SendMessage(SCI_STYLESETSIZE, 32, (sptr_t) be_fixed_font->Size());
		_ApplyAttributes(editor, 32, s);
		editor->SendMessage(SCI_STYLECLEARALL, 0, 0);
		editor->SendMessage(SCI_STYLESETFONT, 36, (sptr_t) fixed);
		editor->SendMessage(SCI_STYLESETSIZE, 36, (sptr_t) (be_fixed_font->Size() / 1.3));
		editor->SendMessage(SCI_SETWHITESPACESIZE, be_fixed_font->Size() / 6, 0);

		// whitespace
		editor->SendMessage(SCI_INDICSETSTYLE, 0, INDIC_ROUNDBOX);
		editor->SendMessage(SCI_INDICSETFORE, 0, 0x0000FF);
		editor->SendMessage(SCI_INDICSETALPHA, 0, 100);
		// IME
		editor->SendMessage(SCI_INDICSETSTYLE, INDIC_IME, INDIC_FULLBOX);
		editor->SendMessage(SCI_INDICSETFORE, INDIC_IME, 0xFF0000);
		editor->SendMessage(SCI_INDICSETSTYLE, INDIC_IME+1, INDIC_FULLBOX);
		editor->SendMessage(SCI_INDICSETFORE, INDIC_IME+1, 0x0000FF);
	}
	for(const auto &node : global) {
		std::string name = node.first.as<std::string>();
		_GetAttributesFromNode(node.second, id, s);
		if(id != -1) {
			_ApplyAttributes(editor, id, s);
			sStylesMapping.emplace(id, s);
		} else {
			if(name == "Current line") {
				editor->SendMessage(SCI_SETCARETLINEBACK, s.bgColor, 0);
				//editor->SendMessage(SCI_SETCARETLINEBACKALPHA, 128, 0);
			}
			else if(name == "Whitespace") {
				if(s.fgColor != -1) {
					editor->SendMessage(SCI_SETWHITESPACEFORE, true, s.fgColor);
				}
				if(s.bgColor != -1) {
					editor->SendMessage(SCI_SETWHITESPACEBACK, true, s.bgColor);
				}
			}
			else if(name == "Selected text") {
				if(s.fgColor != -1) {
					editor->SendMessage(SCI_SETSELFORE, true, s.fgColor);
				}
				if(s.bgColor != -1) {
					editor->SendMessage(SCI_SETSELBACK, true, s.bgColor);
				}
			}
			else if(name == "Caret") {
				editor->SendMessage(SCI_SETCARETFORE, s.fgColor, 0);
			}
			else if(name == "Edge") {
				editor->SendMessage(SCI_SETEDGECOLOUR, s.fgColor, 0);
			}
			else if(name == "Fold") {
				if(s.fgColor != -1) {
					editor->SendMessage(SCI_SETFOLDMARGINHICOLOUR, true, s.fgColor);
				}
				if(s.bgColor != -1) {
					editor->SendMessage(SCI_SETFOLDMARGINCOLOUR, true, s.bgColor);
				}
			}
		}
	}
	for(const auto& style : styles) {
		if(style.first.as<std::string>() == "Global")
			continue;
		_GetAttributesFromNode(style.second, id, s);
		sStylesMapping.emplace(id, s);
	}
}

/* static */ void
Styler::ApplyLanguage(Editor* editor, const std::map<int, int>& styleMapping)
{
	for(const auto& mapping : styleMapping) {
		int scintillaId = mapping.first;
		int styleId = mapping.second;
		const auto it = sStylesMapping.find(styleId);
		if(it != sStylesMapping.end()) {
			Style s = it->second;
			_ApplyAttributes(editor, scintillaId, s);
		}
	}
}

/* static */ void
Styler::GetAvailableStyles(std::set<std::string> &styles)
{
	BPath dataPath;
	find_directory(B_SYSTEM_DATA_DIRECTORY, &dataPath);
	_GetAvailableStyles(styles, dataPath);
	find_directory(B_USER_DATA_DIRECTORY, &dataPath);
	_GetAvailableStyles(styles, dataPath);
	find_directory(B_SYSTEM_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	_GetAvailableStyles(styles, dataPath);
	find_directory(B_USER_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	_GetAvailableStyles(styles, dataPath);
}

/* static */ void
Styler::_GetAvailableStyles(std::set<std::string> &styles, const BPath &path)
{
	BPath p(path);
	p.Append(gAppName);
	p.Append("styles");
	BDirectory directory(p.Path());
	BEntry entry;
	char name[B_FILE_NAME_LENGTH];
	while(directory.GetNextEntry(&entry) == B_OK) {
		if(entry.IsDirectory())
			continue;
		entry.GetName(name);
		if(GetFileExtension(name) == "yaml") {
			styles.insert(GetFileName(name));
		}
	}
}

void
Styler::_GetAttributesFromNode(const YAML::Node &node, int& styleId, Styler::Style& style)
{
	styleId = node["id"] ? node["id"].as<int>() : -1;
	style = node.as<Style>();
}

void
Styler::_ApplyAttributes(Editor* editor, int styleId, Styler::Style style)
{
	if(style.fgColor != -1) {
		editor->SendMessage(SCI_STYLESETFORE, styleId, style.fgColor);
	}
	if(style.bgColor != -1) {
		editor->SendMessage(SCI_STYLESETBACK, styleId, style.bgColor);
	}
	if(style.style != -1) {
		if(style.style & 1) {
			editor->SendMessage(SCI_STYLESETBOLD, styleId, true);
		}
		if(style.style & 2) {
			editor->SendMessage(SCI_STYLESETITALIC, styleId, true);
		}
		if(style.style & 4) {
			editor->SendMessage(SCI_STYLESETUNDERLINE, styleId, true);
		}
	}
}
<commit_msg>Fix style reloading<commit_after>/*
 * Copyright 2014-2018 Kacper Kasper <kacperkasper@gmail.com>
 * All rights reserved. Distributed under the terms of the MIT license.
 */

#include "Styler.h"

#include <unordered_map>
#include <vector>

#include <yaml-cpp/yaml.h>

#include <Alert.h>
#include <Directory.h>
#include <FindDirectory.h>
#include <Path.h>
#include <String.h>

#include "Editor.h"
#include "EditorWindow.h"
#include "Utils.h"

#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Styler"

namespace YAML {

namespace {

int
CSSToInt(const std::string cssColor)
{
	if(cssColor[0] != '#' || cssColor.length() != 7)
		return -1;

	std::string red = cssColor.substr(1, 2);
	std::string green = cssColor.substr(3, 2);
	std::string blue = cssColor.substr(5, 2);

	return std::stoi(blue + green + red, nullptr, 16);
}

}

template<>
struct convert<Styler::Style> {
	static Node encode(const Styler::Style& rhs) {
		// TODO
	}

	static bool decode(const Node& node, Styler::Style& rhs) {
		if(!node.IsMap()) {
			return false;
		}

		if(node["foreground"]) {
			rhs.fgColor = CSSToInt(node["foreground"].as<std::string>());
		}
		if(node["background"]) {
			rhs.bgColor = CSSToInt(node["background"].as<std::string>());
		}
		if(node["style"] && node["style"].IsSequence()) {
			rhs.style = 0;
			const auto styles = node["style"].as<std::vector<std::string>>();
			for(const auto& style : styles) {
				if(style == "bold")
					rhs.style |= 1;
				else if(style == "italic")
					rhs.style |= 2;
				else if(style == "underline")
					rhs.style |= 4;
			}
		}
		return true;
	}
};

}

std::unordered_map<int, Styler::Style>	Styler::sStylesMapping;

/* static */ void
Styler::ApplyGlobal(Editor* editor, const char* style)
{
	static bool alertShown = false;
	bool found = false;
	BPath dataPath;
	find_directory(B_SYSTEM_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
		found = true;
	} catch (YAML::BadFile &) {
	}
	find_directory(B_USER_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
		found = true;
	} catch (YAML::BadFile &) {
	}
	find_directory(B_SYSTEM_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
		found = true;
	} catch (YAML::BadFile &) {
	}
	find_directory(B_USER_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
		found = true;
	} catch (YAML::BadFile &) {
	}
	if(found == false && alertShown == false) {
		alertShown = true;
		BAlert* alert = new BAlert(B_TRANSLATE("Style files"),
			B_TRANSLATE("Couldn't find style files. Make sure you have them "
				"installed in one of your data directories."),
				B_TRANSLATE("OK"), nullptr, nullptr, B_WIDTH_AS_USUAL,
				B_WARNING_ALERT);
		alert->Go();
	}
}

/* static */ void
Styler::_ApplyGlobal(Editor* editor, const char* style, const BPath &path)
{
	BPath p(path);
	p.Append(gAppName);
	p.Append("styles");
	p.Append(style);
	const YAML::Node styles = YAML::LoadFile(std::string(p.Path()) + ".yaml");
	YAML::Node global;
	if(styles["Global"]) {
		global = styles["Global"];
	}

	sStylesMapping.clear();

	int id;
	Style s;
	if(global["Default"]) {
		_GetAttributesFromNode(global["Default"], id, s);

		font_family fixed;
		be_fixed_font->GetFamilyAndStyle(&fixed, nullptr);
		editor->SendMessage(SCI_STYLESETFONT, 32, (sptr_t) fixed);
		editor->SendMessage(SCI_STYLESETSIZE, 32, (sptr_t) be_fixed_font->Size());
		_ApplyAttributes(editor, 32, s);
		editor->SendMessage(SCI_STYLECLEARALL, 0, 0);
		editor->SendMessage(SCI_STYLESETFONT, 36, (sptr_t) fixed);
		editor->SendMessage(SCI_STYLESETSIZE, 36, (sptr_t) (be_fixed_font->Size() / 1.3));
		editor->SendMessage(SCI_SETWHITESPACESIZE, be_fixed_font->Size() / 6, 0);

		// whitespace
		editor->SendMessage(SCI_INDICSETSTYLE, 0, INDIC_ROUNDBOX);
		editor->SendMessage(SCI_INDICSETFORE, 0, 0x0000FF);
		editor->SendMessage(SCI_INDICSETALPHA, 0, 100);
		// IME
		editor->SendMessage(SCI_INDICSETSTYLE, INDIC_IME, INDIC_FULLBOX);
		editor->SendMessage(SCI_INDICSETFORE, INDIC_IME, 0xFF0000);
		editor->SendMessage(SCI_INDICSETSTYLE, INDIC_IME+1, INDIC_FULLBOX);
		editor->SendMessage(SCI_INDICSETFORE, INDIC_IME+1, 0x0000FF);
	}
	for(const auto &node : global) {
		std::string name = node.first.as<std::string>();
		_GetAttributesFromNode(node.second, id, s);
		if(id != -1) {
			_ApplyAttributes(editor, id, s);
			sStylesMapping.emplace(id, s);
		} else {
			if(name == "Current line") {
				editor->SendMessage(SCI_SETCARETLINEBACK, s.bgColor, 0);
				//editor->SendMessage(SCI_SETCARETLINEBACKALPHA, 128, 0);
			}
			else if(name == "Whitespace") {
				if(s.fgColor != -1) {
					editor->SendMessage(SCI_SETWHITESPACEFORE, true, s.fgColor);
				}
				if(s.bgColor != -1) {
					editor->SendMessage(SCI_SETWHITESPACEBACK, true, s.bgColor);
				}
			}
			else if(name == "Selected text") {
				if(s.fgColor != -1) {
					editor->SendMessage(SCI_SETSELFORE, true, s.fgColor);
				}
				if(s.bgColor != -1) {
					editor->SendMessage(SCI_SETSELBACK, true, s.bgColor);
				}
			}
			else if(name == "Caret") {
				editor->SendMessage(SCI_SETCARETFORE, s.fgColor, 0);
			}
			else if(name == "Edge") {
				editor->SendMessage(SCI_SETEDGECOLOUR, s.fgColor, 0);
			}
			else if(name == "Fold") {
				if(s.fgColor != -1) {
					editor->SendMessage(SCI_SETFOLDMARGINHICOLOUR, true, s.fgColor);
				}
				if(s.bgColor != -1) {
					editor->SendMessage(SCI_SETFOLDMARGINCOLOUR, true, s.bgColor);
				}
			}
		}
	}
	for(const auto& style : styles) {
		if(style.first.as<std::string>() == "Global")
			continue;
		_GetAttributesFromNode(style.second, id, s);
		sStylesMapping.emplace(id, s);
	}
}

/* static */ void
Styler::ApplyLanguage(Editor* editor, const std::map<int, int>& styleMapping)
{
	for(const auto& mapping : styleMapping) {
		int scintillaId = mapping.first;
		int styleId = mapping.second;
		const auto it = sStylesMapping.find(styleId);
		if(it != sStylesMapping.end()) {
			Style s = it->second;
			_ApplyAttributes(editor, scintillaId, s);
		}
	}
}

/* static */ void
Styler::GetAvailableStyles(std::set<std::string> &styles)
{
	BPath dataPath;
	find_directory(B_SYSTEM_DATA_DIRECTORY, &dataPath);
	_GetAvailableStyles(styles, dataPath);
	find_directory(B_USER_DATA_DIRECTORY, &dataPath);
	_GetAvailableStyles(styles, dataPath);
	find_directory(B_SYSTEM_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	_GetAvailableStyles(styles, dataPath);
	find_directory(B_USER_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	_GetAvailableStyles(styles, dataPath);
}

/* static */ void
Styler::_GetAvailableStyles(std::set<std::string> &styles, const BPath &path)
{
	BPath p(path);
	p.Append(gAppName);
	p.Append("styles");
	BDirectory directory(p.Path());
	BEntry entry;
	char name[B_FILE_NAME_LENGTH];
	while(directory.GetNextEntry(&entry) == B_OK) {
		if(entry.IsDirectory())
			continue;
		entry.GetName(name);
		if(GetFileExtension(name) == "yaml") {
			styles.insert(GetFileName(name));
		}
	}
}

void
Styler::_GetAttributesFromNode(const YAML::Node &node, int& styleId, Styler::Style& style)
{
	styleId = node["id"] ? node["id"].as<int>() : -1;
	style = node.as<Style>();
}

void
Styler::_ApplyAttributes(Editor* editor, int styleId, Styler::Style style)
{
	if(style.fgColor != -1) {
		editor->SendMessage(SCI_STYLESETFORE, styleId, style.fgColor);
	}
	if(style.bgColor != -1) {
		editor->SendMessage(SCI_STYLESETBACK, styleId, style.bgColor);
	}
	if(style.style != -1) {
		if(style.style & 1) {
			editor->SendMessage(SCI_STYLESETBOLD, styleId, true);
		}
		if(style.style & 2) {
			editor->SendMessage(SCI_STYLESETITALIC, styleId, true);
		}
		if(style.style & 4) {
			editor->SendMessage(SCI_STYLESETUNDERLINE, styleId, true);
		}
	}
}
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief X11 Platform.
 *//*--------------------------------------------------------------------*/

#include "tcuX11Platform.hpp"
#include "vkWsiPlatform.hpp"

#include "deUniquePtr.hpp"
#include "gluPlatform.hpp"
#include "vkPlatform.hpp"
#include "tcuX11.hpp"
#include "tcuFunctionLibrary.hpp"
#include "deMemory.h"
#include "tcuX11VulkanPlatform.hpp"
#include "tcuX11EglPlatform.hpp"

#if defined (DEQP_SUPPORT_GLX)
#	include "tcuX11GlxPlatform.hpp"
#endif

#include <sys/utsname.h>

using de::MovePtr;
using de::UniquePtr;

namespace tcu
{
namespace x11
{

class X11GLPlatform : public glu::Platform
{
public:
	void		registerFactory	(de::MovePtr<glu::ContextFactory> factory)
	{
		m_contextFactoryRegistry.registerFactory(factory.release());
	}
};

class X11Platform : public tcu::Platform
{
public:
							X11Platform			(void);
	bool					processEvents		(void) { return !m_eventState.getQuitFlag(); }

	const vk::Platform&		getVulkanPlatform	(void) const { return m_vkPlatform; }
	const eglu::Platform&	getEGLPlatform		(void) const { return m_eglPlatform; }
	const glu::Platform&	getGLPlatform		(void) const { return m_glPlatform; }

private:
	EventState				m_eventState;
	x11::VulkanPlatform		m_vkPlatform;
	x11::egl::Platform		m_eglPlatform;
	X11GLPlatform			m_glPlatform;
};

X11Platform::X11Platform (void)
	: m_vkPlatform	(m_eventState)
	, m_eglPlatform	(m_eventState)
{
#if defined (DEQP_SUPPORT_GLX)
	m_glPlatform.registerFactory(glx::createContextFactory(m_eventState));
#endif // DEQP_SUPPORT_GLX

	m_glPlatform.registerFactory(m_eglPlatform.createContextFactory());
}

} // x11
} // tcu

tcu::Platform* createPlatform (void)
{
	return new tcu::x11::X11Platform();
}
<commit_msg>x11: Call XInitThreads() am: 5d11c9d2c0 am: 91a1b97b09 am: f7dc04d927<commit_after>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief X11 Platform.
 *//*--------------------------------------------------------------------*/

#include "tcuX11Platform.hpp"
#include "vkWsiPlatform.hpp"

#include "deUniquePtr.hpp"
#include "gluPlatform.hpp"
#include "vkPlatform.hpp"
#include "tcuX11.hpp"
#include "tcuFunctionLibrary.hpp"
#include "deMemory.h"
#include "tcuX11VulkanPlatform.hpp"
#include "tcuX11EglPlatform.hpp"

#if defined (DEQP_SUPPORT_GLX)
#	include "tcuX11GlxPlatform.hpp"
#endif

#include <sys/utsname.h>

using de::MovePtr;
using de::UniquePtr;

namespace tcu
{
namespace x11
{

class X11GLPlatform : public glu::Platform
{
public:
	void		registerFactory	(de::MovePtr<glu::ContextFactory> factory)
	{
		m_contextFactoryRegistry.registerFactory(factory.release());
	}
};

class X11Platform : public tcu::Platform
{
public:
							X11Platform			(void);
	bool					processEvents		(void) { return !m_eventState.getQuitFlag(); }

	const vk::Platform&		getVulkanPlatform	(void) const { return m_vkPlatform; }
	const eglu::Platform&	getEGLPlatform		(void) const { return m_eglPlatform; }
	const glu::Platform&	getGLPlatform		(void) const { return m_glPlatform; }

private:
	EventState				m_eventState;
	x11::VulkanPlatform		m_vkPlatform;
	x11::egl::Platform		m_eglPlatform;
	X11GLPlatform			m_glPlatform;
};

X11Platform::X11Platform (void)
	: m_vkPlatform	(m_eventState)
	, m_eglPlatform	(m_eventState)
{
#if defined (DEQP_SUPPORT_GLX)
	m_glPlatform.registerFactory(glx::createContextFactory(m_eventState));
#endif // DEQP_SUPPORT_GLX

	m_glPlatform.registerFactory(m_eglPlatform.createContextFactory());
}

} // x11
} // tcu

tcu::Platform* createPlatform (void)
{
	// From man:XinitThreads(3):
	//
	//     The XInitThreads function initializes Xlib support for concurrent
	//     threads.  This function must be the first Xlib function
	//     a multi-threaded program calls, and it must complete before any other
	//     Xlib call is made.
	DE_CHECK_RUNTIME_ERR(XInitThreads() != 0);

	return new tcu::x11::X11Platform();
}
<|endoftext|>


<commit_before>#include "opencv2/core.hpp"

#include "Viewer.hpp"

Viewer::Viewer()
:
	_log("PCL"),
	_viewer("Point Cloud")
{
	// Set viewer settings
	_viewer.setShowFPS(true);
	_viewer.setWindowBorders(false);

	_viewer.setBackgroundColor(0.1, 0.1, 0.1);
	_viewer.addCoordinateSystem(0.1, "global");
}

void Viewer::showCloudPoints(const Images& images, const CameraPoses& poses,
	const cv::Mat& cameraMatrix)
{
	// Fill cloud structure
	typedef pcl::PointXYZRGB point_t;
	pcl::PointCloud<point_t>::Ptr pcl_points(new pcl::PointCloud<point_t>);

	// Per camera
#pragma omp parallel for
	for (int c = 0; c < poses.size(); c++)
	{
		Image image = images[c];

		// Per pixel
		const cv::Vec3b* rgbs;
		const float*     deps;

		cv::Vec3b rgb;
		float     dep;

		cv::Point3f point;

		for (int i = 0; i < image.dep.rows; i++)
		{
			rgbs = image.rgb.ptr<cv::Vec3b>(i);
			deps = image.dep.ptr<float>(i);
			for (int j = 0; j < image.dep.cols; j++)
			{
				rgb = rgbs[j];
				dep = deps[j];

				// Valid depth is between 40cm and 8m
				if (dep < 400 || dep > 8000) continue;

				point = backproject3D(j, i, dep, cameraMatrix);
				point_t pcl_p;
				pcl_p.x = point.x;
				pcl_p.y = point.y;
				pcl_p.z = point.z;
				pcl_p.r = rgb[2];
				pcl_p.g = rgb[1];
				pcl_p.b = rgb[0];
#pragma omp critical
				pcl_points->points.push_back(pcl_p);
			}
		}
	}

	// Show cloud
	_log("Showing %d points", pcl_points->points.size());
	vis::PointCloudColorHandlerRGBField<point_t> rgb_handler(pcl_points);
	_viewer.addPointCloud<pcl::PointXYZRGB>(pcl_points, rgb_handler);
	_log.tok();

	// Wait until closed
	while (!_viewer.wasStopped())
	{
		_viewer.spinOnce(15);
	}
}

<commit_msg>Convert point coords correctly in Viewer<commit_after>#include "opencv2/core.hpp"

#include "Viewer.hpp"

Viewer::Viewer()
:
	_log("PCL"),
	_viewer("Point Cloud")
{
	// Set viewer settings
	_viewer.setShowFPS(true);
	_viewer.setWindowBorders(false);

	_viewer.setBackgroundColor(0.1, 0.1, 0.1);
	_viewer.addCoordinateSystem(0.1, "global");
}

void Viewer::showCloudPoints(const Images& images, const CameraPoses& poses,
	const cv::Mat& cameraMatrix)
{
	// Fill cloud structure
	typedef pcl::PointXYZRGB point_t;
	pcl::PointCloud<point_t>::Ptr pcl_points(new pcl::PointCloud<point_t>);

	// Per camera
#pragma omp parallel for
	for (int c = 0; c < poses.size(); c++)
	{
		Image   image = images[c];
		cv::Mat R     = poses[c].R;
		cv::Mat t     = poses[c].t;

		// Per pixel
		const cv::Vec3b* rgbs;
		const float*     deps;

		cv::Vec3b rgb;
		float     dep;

		cv::Point3f point;
		cv::Mat     gPoint;

		for (int i = 0; i < image.dep.rows; i++)
		{
			rgbs = image.rgb.ptr<cv::Vec3b>(i);
			deps = image.dep.ptr<float>(i);
			for (int j = 0; j < image.dep.cols; j++)
			{
				rgb = rgbs[j];
				dep = deps[j];

				// Valid depth is between 40cm and 8m
				if (dep < 400 || dep > 8000) continue;

				// Calculate point pos in global coordinates
				point  = backproject3D(j, i, dep, cameraMatrix);
				gPoint = R.t() * cv::Mat(point) - t;
				point  = cv::Point3f(gPoint);

				point_t pcl_p;
				pcl_p.x = point.x;
				pcl_p.y = point.y;
				pcl_p.z = point.z;
				pcl_p.r = rgb[2];
				pcl_p.g = rgb[1];
				pcl_p.b = rgb[0];
#pragma omp critical
				pcl_points->points.push_back(pcl_p);
			}
		}
	}

	// Show cloud
	_log("Showing %d points", pcl_points->points.size());
	vis::PointCloudColorHandlerRGBField<point_t> rgb_handler(pcl_points);
	_viewer.addPointCloud<pcl::PointXYZRGB>(pcl_points, rgb_handler);
	_log.tok();

	// Wait until closed
	while (!_viewer.wasStopped())
	{
		_viewer.spinOnce(15);
	}
}

<|endoftext|>