<commit_before>// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// 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.

#ifndef ROCPRIM_DETAIL_VARIOUS_HPP_
#define ROCPRIM_DETAIL_VARIOUS_HPP_

#include <type_traits>

#include "../config.hpp"
#include "../types.hpp"
#include "../type_traits.hpp"

// TODO: Refactor when it gets crowded

BEGIN_ROCPRIM_NAMESPACE
namespace detail
{

struct empty_storage_type
{

};

template<class T>
ROCPRIM_HOST_DEVICE inline
constexpr bool is_power_of_two(const T x)
{
    static_assert(::rocprim::is_integral<T>::value, "T must be integer type");
    return (x > 0) && ((x & (x - 1)) == 0);
}

template<class T>
ROCPRIM_HOST_DEVICE inline
constexpr T next_power_of_two(const T x, const T acc = 1)
{
    static_assert(::rocprim::is_unsigned<T>::value, "T must be unsigned type");
    return acc >= x ? acc : next_power_of_two(x, 2 * acc);
}

template<class T>
ROCPRIM_HOST_DEVICE inline
constexpr auto ceiling_div(T a, T b)
    -> typename std::enable_if<::rocprim::is_integral<T>::value, T>::type
{
    return (a + b - 1) / b;
}

ROCPRIM_HOST_DEVICE inline
size_t align_size(size_t size, size_t alignment = 256)
{
    return ceiling_div(size, alignment) * alignment;
}

// Select the minimal warp size for block of size block_size, it's
// useful for blocks smaller than maximal warp size.
template<class T>
ROCPRIM_HOST_DEVICE inline
constexpr T get_min_warp_size(const T block_size, const T max_warp_size)
{
    static_assert(::rocprim::is_unsigned<T>::value, "T must be unsigned type");
    return block_size >= max_warp_size ? max_warp_size : next_power_of_two(block_size);
}

template<unsigned int WarpSize>
struct is_warpsize_shuffleable {
    static const bool value = detail::is_power_of_two(WarpSize);
};

// Selects an appropriate vector_type based on the input T and size N.
// The byte size is calculated and used to select an appropriate vector_type.
template<class T, unsigned int N>
struct match_vector_type
{
    static constexpr unsigned int size = sizeof(T) * N;
    using vector_base_type =
        typename std::conditional<
            sizeof(T) >= 4,
            int,
            typename std::conditional<
                sizeof(T) >= 2,
                short,
                char
            >::type
        >::type;

    using vector_4 = typename make_vector_type<vector_base_type, 4>::type;
    using vector_2 = typename make_vector_type<vector_base_type, 2>::type;
    using vector_1 = typename make_vector_type<vector_base_type, 1>::type;

    using type =
        typename std::conditional<
            size % sizeof(vector_4) == 0,
            vector_4,
            typename std::conditional<
                size % sizeof(vector_2) == 0,
                vector_2,
                vector_1
            >::type
        >::type;
};

// Checks if Items is odd and ensures that size of T is smaller than vector_type.
template<class T, unsigned int Items>
ROCPRIM_HOST_DEVICE
constexpr bool is_vectorizable()
{
    return (Items % 2 == 0) &&
           (sizeof(T) < sizeof(typename match_vector_type<T, Items>::type));
}

// Returns the number of LDS (local data share) banks.
ROCPRIM_HOST_DEVICE
constexpr unsigned int get_lds_banks_no()
{
    // Currently all devices supported by ROCm have 32 banks (4 bytes each)
    return 32;
}

// Finds biggest fundamental type for type T that sizeof(T) is
// a multiple of that type's size.
template<class T>
struct match_fundamental_type
{
    using type =
        typename std::conditional<
            sizeof(T)%8 == 0,
            unsigned long long,
            typename std::conditional<
                sizeof(T)%4 == 0,
                unsigned int,
                typename std::conditional<
                    sizeof(T)%2 == 0,
                    unsigned short,
                    unsigned char
                >::type
            >::type
        >::type;
};

template<class T>
ROCPRIM_DEVICE inline
auto store_volatile(T * output, T value)
    -> typename std::enable_if<std::is_fundamental<T>::value>::type
{
    *const_cast<volatile T*>(output) = value;
}

template<class T>
ROCPRIM_DEVICE inline
auto store_volatile(T * output, T value)
    -> typename std::enable_if<!std::is_fundamental<T>::value>::type
{
    using fundamental_type = typename match_fundamental_type<T>::type;
    constexpr unsigned int n = sizeof(T) / sizeof(fundamental_type);

    auto input_ptr = reinterpret_cast<volatile fundamental_type*>(&value);
    auto output_ptr = reinterpret_cast<volatile fundamental_type*>(output);

    #pragma unroll
    for(unsigned int i = 0; i < n; i++)
    {
        output_ptr[i] = input_ptr[i];
    }
}

template<class T>
ROCPRIM_DEVICE inline
auto load_volatile(T * input)
    -> typename std::enable_if<std::is_fundamental<T>::value, T>::type
{
    T retval = *const_cast<volatile T*>(input);
    return retval;
}

template<class T>
ROCPRIM_DEVICE inline
auto load_volatile(T * input)
    -> typename std::enable_if<!std::is_fundamental<T>::value, T>::type
{
    using fundamental_type = typename match_fundamental_type<T>::type;
    constexpr unsigned int n = sizeof(T) / sizeof(fundamental_type);

    T retval;
    auto output_ptr = reinterpret_cast<volatile fundamental_type*>(&retval);
    auto input_ptr = reinterpret_cast<volatile fundamental_type*>(input);

    #pragma unroll
    for(unsigned int i = 0; i < n; i++)
    {
        output_ptr[i] = input_ptr[i];
    }
    return retval;
}

#if __HCC_OR_HIP_CLANG__
ROCPRIM_DEVICE inline
void store_volatile(half * output, half value)
{
    *reinterpret_cast<volatile _Float16*>(output) = value;
}

ROCPRIM_DEVICE inline
half load_volatile(half * input)
{
    half retval = *reinterpret_cast<volatile _Float16*>(input);
    return retval;
}
#endif

// A storage-backing wrapper that allows types with non-trivial constructors to be aliased in unions
template <typename T>
struct raw_storage
{
    // Biggest memory-access word that T is a whole multiple of and is not larger than the alignment of T
    typedef typename detail::match_fundamental_type<T>::type device_word;

    // Backing storage
    device_word storage[sizeof(T) / sizeof(device_word)];

    // Alias
    ROCPRIM_HOST_DEVICE T& get()
    {
        return reinterpret_cast<T&>(*this);
    }
};

// Checks if two iterators have the same type and value
template<class Iterator1, class Iterator2>
inline
bool are_iterators_equal(Iterator1, Iterator2)
{
    return false;
}

template<class Iterator>
inline
bool are_iterators_equal(Iterator iter1, Iterator iter2)
{
    return iter1 == iter2;
}

} // end namespace detail
END_ROCPRIM_NAMESPACE

#endif // ROCPRIM_DETAIL_VARIOUS_HPP_
<commit_msg>Revert "Avoid template specialization of load_volatile and store_volatile when not using HCC or HIP-CLANG (#128)" (#131)<commit_after>// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// 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.

#ifndef ROCPRIM_DETAIL_VARIOUS_HPP_
#define ROCPRIM_DETAIL_VARIOUS_HPP_

#include <type_traits>

#include "../config.hpp"
#include "../types.hpp"
#include "../type_traits.hpp"

// TODO: Refactor when it gets crowded

BEGIN_ROCPRIM_NAMESPACE
namespace detail
{

struct empty_storage_type
{

};

template<class T>
ROCPRIM_HOST_DEVICE inline
constexpr bool is_power_of_two(const T x)
{
    static_assert(::rocprim::is_integral<T>::value, "T must be integer type");
    return (x > 0) && ((x & (x - 1)) == 0);
}

template<class T>
ROCPRIM_HOST_DEVICE inline
constexpr T next_power_of_two(const T x, const T acc = 1)
{
    static_assert(::rocprim::is_unsigned<T>::value, "T must be unsigned type");
    return acc >= x ? acc : next_power_of_two(x, 2 * acc);
}

template<class T>
ROCPRIM_HOST_DEVICE inline
constexpr auto ceiling_div(T a, T b)
    -> typename std::enable_if<::rocprim::is_integral<T>::value, T>::type
{
    return (a + b - 1) / b;
}

ROCPRIM_HOST_DEVICE inline
size_t align_size(size_t size, size_t alignment = 256)
{
    return ceiling_div(size, alignment) * alignment;
}

// Select the minimal warp size for block of size block_size, it's
// useful for blocks smaller than maximal warp size.
template<class T>
ROCPRIM_HOST_DEVICE inline
constexpr T get_min_warp_size(const T block_size, const T max_warp_size)
{
    static_assert(::rocprim::is_unsigned<T>::value, "T must be unsigned type");
    return block_size >= max_warp_size ? max_warp_size : next_power_of_two(block_size);
}

template<unsigned int WarpSize>
struct is_warpsize_shuffleable {
    static const bool value = detail::is_power_of_two(WarpSize);
};

// Selects an appropriate vector_type based on the input T and size N.
// The byte size is calculated and used to select an appropriate vector_type.
template<class T, unsigned int N>
struct match_vector_type
{
    static constexpr unsigned int size = sizeof(T) * N;
    using vector_base_type =
        typename std::conditional<
            sizeof(T) >= 4,
            int,
            typename std::conditional<
                sizeof(T) >= 2,
                short,
                char
            >::type
        >::type;

    using vector_4 = typename make_vector_type<vector_base_type, 4>::type;
    using vector_2 = typename make_vector_type<vector_base_type, 2>::type;
    using vector_1 = typename make_vector_type<vector_base_type, 1>::type;

    using type =
        typename std::conditional<
            size % sizeof(vector_4) == 0,
            vector_4,
            typename std::conditional<
                size % sizeof(vector_2) == 0,
                vector_2,
                vector_1
            >::type
        >::type;
};

// Checks if Items is odd and ensures that size of T is smaller than vector_type.
template<class T, unsigned int Items>
ROCPRIM_HOST_DEVICE
constexpr bool is_vectorizable()
{
    return (Items % 2 == 0) &&
           (sizeof(T) < sizeof(typename match_vector_type<T, Items>::type));
}

// Returns the number of LDS (local data share) banks.
ROCPRIM_HOST_DEVICE
constexpr unsigned int get_lds_banks_no()
{
    // Currently all devices supported by ROCm have 32 banks (4 bytes each)
    return 32;
}

// Finds biggest fundamental type for type T that sizeof(T) is
// a multiple of that type's size.
template<class T>
struct match_fundamental_type
{
    using type =
        typename std::conditional<
            sizeof(T)%8 == 0,
            unsigned long long,
            typename std::conditional<
                sizeof(T)%4 == 0,
                unsigned int,
                typename std::conditional<
                    sizeof(T)%2 == 0,
                    unsigned short,
                    unsigned char
                >::type
            >::type
        >::type;
};

template<class T>
ROCPRIM_DEVICE inline
auto store_volatile(T * output, T value)
    -> typename std::enable_if<std::is_fundamental<T>::value>::type
{
    *const_cast<volatile T*>(output) = value;
}

template<class T>
ROCPRIM_DEVICE inline
auto store_volatile(T * output, T value)
    -> typename std::enable_if<!std::is_fundamental<T>::value>::type
{
    using fundamental_type = typename match_fundamental_type<T>::type;
    constexpr unsigned int n = sizeof(T) / sizeof(fundamental_type);

    auto input_ptr = reinterpret_cast<volatile fundamental_type*>(&value);
    auto output_ptr = reinterpret_cast<volatile fundamental_type*>(output);

    #pragma unroll
    for(unsigned int i = 0; i < n; i++)
    {
        output_ptr[i] = input_ptr[i];
    }
}

template<class T>
ROCPRIM_DEVICE inline
auto load_volatile(T * input)
    -> typename std::enable_if<std::is_fundamental<T>::value, T>::type
{
    T retval = *const_cast<volatile T*>(input);
    return retval;
}

template<class T>
ROCPRIM_DEVICE inline
auto load_volatile(T * input)
    -> typename std::enable_if<!std::is_fundamental<T>::value, T>::type
{
    using fundamental_type = typename match_fundamental_type<T>::type;
    constexpr unsigned int n = sizeof(T) / sizeof(fundamental_type);

    T retval;
    auto output_ptr = reinterpret_cast<volatile fundamental_type*>(&retval);
    auto input_ptr = reinterpret_cast<volatile fundamental_type*>(input);

    #pragma unroll
    for(unsigned int i = 0; i < n; i++)
    {
        output_ptr[i] = input_ptr[i];
    }
    return retval;
}

// A storage-backing wrapper that allows types with non-trivial constructors to be aliased in unions
template <typename T>
struct raw_storage
{
    // Biggest memory-access word that T is a whole multiple of and is not larger than the alignment of T
    typedef typename detail::match_fundamental_type<T>::type device_word;

    // Backing storage
    device_word storage[sizeof(T) / sizeof(device_word)];

    // Alias
    ROCPRIM_HOST_DEVICE T& get()
    {
        return reinterpret_cast<T&>(*this);
    }
};

// Checks if two iterators have the same type and value
template<class Iterator1, class Iterator2>
inline
bool are_iterators_equal(Iterator1, Iterator2)
{
    return false;
}

template<class Iterator>
inline
bool are_iterators_equal(Iterator iter1, Iterator iter2)
{
    return iter1 == iter2;
}

} // end namespace detail
END_ROCPRIM_NAMESPACE

#endif // ROCPRIM_DETAIL_VARIOUS_HPP_
<|endoftext|>


<commit_before>//*****************************************************************************
// File: LaricobiusOsakensisEquations.h
//
// Class: CLaricobiusOsakensisEquations
//
//
// Description:
//				stage development rates, relative development rates
//				stage daily survival
//				Adult longevity and fecundity
//
//*****************************************************************************
// 21/07/2021	Rémi Saint-Amant    New aestivation diapause end and adult emergence from L. nigrinus
// 30/06/2021	Rémi Saint-Amant    L osakensis parameters
// 25/08/2020   Rémi Saint-Amant    Creation
//*****************************************************************************
#include "LaricobiusOsakensisEquations.h"
#include <boost/math/distributions.hpp>
#include <boost/math/distributions/logistic.hpp>
#include "ModelBase/DevRateEquation.h"
#include "ModelBase/SurvivalEquation.h"

using namespace WBSF;
using namespace LOF;
using namespace std;

namespace WBSF
{

	//*********************************************************************************************
	//fitted parameters for cumulative egg creation from egg and larvae, CEC
	//	NbVal = 30	Bias = -0.16170	MAE = 3.85438	RMSE = 5.36376	CD = 0.98070	R² = 0.98077
	//mu = 1.58011
	//s = 228.2837
	//Th1 = 2.1
	//Th2 = 20.2

	//*********************************************************************************************
	//fitted parameters for Adult Emergence from Soil AES (from L. nigrinus)
	//#NbVal = 100	Bias = 0.48893	MAE = 5.32455	RMSE = 7.49034	CD = 0.96157	R² = 0.96300
	//lam0 = 121
	//lam1 = 212
	//lam2 = -294.5
	//lam3 = 105.8
	//lam_a = 34.8
	//lam_b = 20
	//mu_ADE = 1157.8
	//s_ADE = 125.0
	//Th_ADE = -2.5

	const double CLaricobiusOsakensisEquations::CEC[NB_CEC_PARAMS] = { 1.580,228.3,-999, 2.1, 20.2 };//Weibull distribution
	const double CLaricobiusOsakensisEquations::ADE[NB_ADE_PARAMS] = { 121,212,-294.5,105.8,34.8,20 };//logistic distribution
	const double CLaricobiusOsakensisEquations::EAS[NB_EAS_PARAMS] = { 1157.8,125.0,-2.5 };//logistic distribution

	CLaricobiusOsakensisEquations::CLaricobiusOsakensisEquations(const CRandomGenerator& RG) :
		CEquationTableLookup(RG, LOF::NB_STAGES, -20, 35, 0.25)
	{

		for (size_t p = 0; p < NB_CEC_PARAMS; p++)
			m_CEC[p] = CEC[p];

		for (size_t p = 0; p < NB_ADE_PARAMS; p++)
			m_ADE[p] = ADE[p];

		for (size_t p = 0; p < NB_EAS_PARAMS; p++)
			m_EAS[p] = m_EAS[p];
	}

	//Daily development rate
	double CLaricobiusOsakensisEquations::ComputeRate(size_t s, double T)const
	{
		ASSERT(s >= 0 && s < NB_STAGES);

		static const array<CDevRateEquation::TDevRateEquation, LOF::NB_STAGES> P_EQ =
		{
			//Non-linear
			CDevRateEquation::Regniere_2012,//Egg
			CDevRateEquation::Regniere_2012,//L1
			CDevRateEquation::Regniere_2012,//L2
			CDevRateEquation::Regniere_2012,//L3
			CDevRateEquation::Regniere_2012,//L4
			CDevRateEquation::Regniere_2012,//PrePupae
			CDevRateEquation::Regniere_2012,//Pupae
			CDevRateEquation::Unknown,		//aestival diapause adult
			CDevRateEquation::LoganTb_1979	//adult longevity
		};

		static const array< vector<double>, LOF::NB_STAGES>  P_DEV =
		{ {
				//Non-linear
				{ 4.035e-02, 8.769e-02, 3, 27, 9.287e-01, 5.000e-01 },//Egg
				{ 2.027e-02, 8.478e-02, 4, 27, 3.596e-01, 5.000e-01 },//L1
				{ 2.027e-02, 8.478e-02, 4, 27, 3.596e-01, 5.000e-01 },//L2
				{ 2.027e-02, 8.478e-02, 4, 27, 3.596e-01, 5.000e-01 },//L3
				{ 2.027e-02, 8.478e-02, 4, 27, 3.596e-01, 5.000e-01 },//L4
				{ 7.032e-02, 8.388e-02, 4, 34, 50.00e+01, 1.064e+01 },//PrePupae
				{ 9.590e-03, 1.092e-01, 0, 32, 1.000e-01, 5.001e-01 },//Pupae
				{                                                   },//aestival diapause adult
				{ 2.488e-02, 1.066e-01, 4, 9.998e+01                },//adult
			} };

		//because the larval stage development rate and mortality was difficulty to estimate, we evaluate larval corrected by percent by stage
		static const double PROP_BY_STAGE[LOF::NB_STAGES] = { 1, 0.206, 0.203, 0.227, 0.364, 1, 1, 1, 1 };
		double r = max(0.0, CDevRateEquation::GetRate(P_EQ[s], P_DEV[s], T)) / PROP_BY_STAGE[s];
		_ASSERTE(!_isnan(r) && _finite(r) && r >= 0);

		return r;
	}

	//*****************************************************************************
	//CSBRelativeDevRate : compute individual relative development rate

	double CLaricobiusOsakensisEquations::GetRelativeDevRate(size_t s)const
	{
		static const double SIGMA[NB_STAGES] =
		{
			//Relative devlopement Time (individual varition): sigma
			//Non-linear
			{0.135},//Egg
			{0.184},//L1
			{0.184},//L2
			{0.184},//L3
			{0.184},//L4
			{0.201},//PrePupae
			{0.128},//Pupae
			{1.000},//aestival diapause adult
			{0.401}//adult
		};

		boost::math::lognormal_distribution<double> RDR_dist(-WBSF::Square(SIGMA[s]) / 2.0, SIGMA[s]);
		double RDR = boost::math::quantile(RDR_dist, m_randomGenerator.Randu());
		while (RDR < 0.2 || RDR>2.6)//base on individual observation
			RDR = exp(SIGMA[s] * boost::math::quantile(RDR_dist, m_randomGenerator.Randu()));

		_ASSERTE(!_isnan(RDR) && _finite(RDR));

		return RDR;
	}

	double CLaricobiusOsakensisEquations::GetCreationCDD()const
	{
		boost::math::weibull_distribution<double> egg_creation_dist(m_CEC[μ], m_CEC[ѕ]);
		double CDD = boost::math::quantile(egg_creation_dist, m_randomGenerator.Rand(0.001, 0.999));

		return CDD;
	}

	double CLaricobiusOsakensisEquations::GetAdultEmergingCDD()const
	{
		boost::math::logistic_distribution<double> emerging_dist(m_EAS[μ], m_EAS[ѕ]);
		double CDD = boost::math::quantile(emerging_dist, m_randomGenerator.Rand(0.001, 0.999));

		return CDD;
	}

	//*****************************************************************************
	//survival

	double CLaricobiusOsakensisEquations::GetDailySurvivalRate(size_t s, double T)const
	{

		static const array<CSurvivalEquation::TSurvivalEquation, LOF::NB_STAGES> S_EQ =
		{
			CSurvivalEquation::Survival_01, //egg
			CSurvivalEquation::Survival_01, //L1
			CSurvivalEquation::Survival_01, //L2
			CSurvivalEquation::Survival_01, //L3
			CSurvivalEquation::Survival_01, //L4
			CSurvivalEquation::Survival_01,	//PrePupa
			CSurvivalEquation::Survival_01,	//Pupa
			CSurvivalEquation::Unknown,		//aestival diapause adult
			CSurvivalEquation::Unknown,		// adult
		};

		static const array< vector<double>, LOF::NB_STAGES>  P_SUR =
		{ {
			{ -5.906e+00, +1.299e-01, -1.459e-03 },//egg
			{ -1.087e+00, -5.072e-01, +2.209e-02 },//L1
			{ -1.087e+00, -5.072e-01, +2.209e-02 },//L2
			{ -1.087e+00, -5.072e-01, +2.209e-02 },//L3
			{ -1.087e+00, -5.072e-01, +2.209e-02 },//L4
			{ -6.276e+00, +2.963e-01, -8.149e-03 },//PrePupa
			{ +8.134e+00, -1.635e+00, +5.088e-02 },//Pupa
			{},
			{}
		} };

		double sr = max(0.0, min(1.0, CSurvivalEquation::GetSurvival(S_EQ[s], P_SUR[s], T)));

		_ASSERTE(!_isnan(sr) && _finite(sr) && sr >= 0 && sr <= 1);
		return sr;
	}

	//*****************************************************************************
	//

	//****************************************************************************
	//

	//return fecundity [eggs]
	double CLaricobiusOsakensisEquations::GetFecondity()const
	{
		//AICc,maxLL
		//1690.46,-840.107,5
		static const double Fo = 100.4;
		static const double sigma = 0.355;

		//double Fi = m_randomGenerator.RandUnbiasedLogNormal(log(Fo), sigma);
		//while (Fi < 2 || Fi>120)
		//	Fi = m_randomGenerator.RandUnbiasedLogNormal(log(Fo), sigma);

		boost::math::lognormal_distribution<double> fecondity(log(Fo) - WBSF::Square(sigma) / 2.0, sigma);
		double Fi = boost::math::quantile(fecondity, m_randomGenerator.Rand(0.001, 0.999));

		ASSERT(!_isnan(Fi) && _finite(Fi));

		return Fi;
	}

	double CLaricobiusOsakensisEquations::GetFecondityRate(double age, double T)const
	{
		//AICc,maxLL
		//1698.68,-839.968
		static const CDevRateEquation::TDevRateEquation P_EQ = CDevRateEquation::Taylor_1981;

		static const vector<double> P_FEC = { 0.01518, 10.9, 6.535 };
		double r = max(0.0, CDevRateEquation::GetRate(P_EQ, P_FEC, T));

		_ASSERTE(!_isnan(r) && _finite(r) && r >= 0);

		return r;
	}

}
<commit_msg>Values in the publication<commit_after>//*****************************************************************************
// File: LaricobiusOsakensisEquations.h
//
// Class: CLaricobiusOsakensisEquations
//
//
// Description:
//				stage development rates, relative development rates
//				stage daily survival
//				Adult longevity and fecundity
//
//*****************************************************************************
// 21/07/2021	Rémi Saint-Amant    New aestivation diapause end and adult emergence from L. nigrinus
// 30/06/2021	Rémi Saint-Amant    L osakensis parameters
// 25/08/2020   Rémi Saint-Amant    Creation
//*****************************************************************************
#include "LaricobiusOsakensisEquations.h"
#include <boost/math/distributions.hpp>
#include <boost/math/distributions/logistic.hpp>
#include "ModelBase/DevRateEquation.h"
#include "ModelBase/SurvivalEquation.h"

using namespace WBSF;
using namespace LOF;
using namespace std;

namespace WBSF
{

	//*********************************************************************************************
	//fitted parameters for cumulative egg creation from egg and larvae, CEC
	//	NbVal = 30	Bias = -0.16170	MAE = 3.85438	RMSE = 5.36376	CD = 0.98070	R² = 0.98077
	//mu = 1.58011
	//s = 228.2837
	//Th1 = 2.1
	//Th2 = 20.2

	//*********************************************************************************************
	//fitted parameters for Adult Emergence from Soil AES (from L. nigrinus)
	//#NbVal = 100	Bias = 0.48893	MAE = 5.32455	RMSE = 7.49034	CD = 0.96157	R² = 0.96300
	//lam0 = 121
	//lam1 = 212
	//lam2 = -294.5
	//lam3 = 105.8
	//lam_a = 34.8
	//lam_b = 20
	//mu_ADE = 1157.8
	//s_ADE = 125.0
	//Th_ADE = -2.5

	const double CLaricobiusOsakensisEquations::CEC[NB_CEC_PARAMS] = { 1.580,228.3,-999, 2.1, 20.2 };//Weibull distribution
	const double CLaricobiusOsakensisEquations::ADE[NB_ADE_PARAMS] = { 121,212,-294.5,105.8,34.8,20 };//logistic distribution
	const double CLaricobiusOsakensisEquations::EAS[NB_EAS_PARAMS] = { 1157.8,125.0,-2.5 };//logistic distribution

	CLaricobiusOsakensisEquations::CLaricobiusOsakensisEquations(const CRandomGenerator& RG) :
		CEquationTableLookup(RG, LOF::NB_STAGES, -20, 35, 0.25)
	{

		for (size_t p = 0; p < NB_CEC_PARAMS; p++)
			m_CEC[p] = CEC[p];

		for (size_t p = 0; p < NB_ADE_PARAMS; p++)
			m_ADE[p] = ADE[p];

		for (size_t p = 0; p < NB_EAS_PARAMS; p++)
			m_EAS[p] = m_EAS[p];
	}

	//Daily development rate
	double CLaricobiusOsakensisEquations::ComputeRate(size_t s, double T)const
	{
		ASSERT(s >= 0 && s < NB_STAGES);

		static const array<CDevRateEquation::TDevRateEquation, LOF::NB_STAGES> P_EQ =
		{
			//Non-linear
			CDevRateEquation::Regniere_2012,//Egg
			CDevRateEquation::Regniere_2012,//L1
			CDevRateEquation::Regniere_2012,//L2
			CDevRateEquation::Regniere_2012,//L3
			CDevRateEquation::Regniere_2012,//L4
			CDevRateEquation::Regniere_2012,//PrePupae
			CDevRateEquation::Regniere_2012,//Pupae
			CDevRateEquation::Unknown,		//aestival diapause adult
			CDevRateEquation::LoganTb_1979	//adult longevity
		};

		static const array< vector<double>, LOF::NB_STAGES>  P_DEV =
		{ {
				//Non-linear
				{ 3.962e-02, 8.769e-02, 3, 27, 9.287e-01, 5.000e-01 },//Egg
				{ 1.959e-02, 8.478e-02, 4, 27, 3.596e-01, 5.000e-01 },//L1
				{ 1.959e-02, 8.478e-02, 4, 27, 3.596e-01, 5.000e-01 },//L2
				{ 1.959e-02, 8.478e-02, 4, 27, 3.596e-01, 5.000e-01 },//L3
				{ 1.959e-02, 8.478e-02, 4, 27, 3.596e-01, 5.000e-01 },//L4
				{ 7.032e-02, 8.388e-02, 4, 34, 50.00e+01, 1.064e+01 },//PrePupae
				{ 9.590e-03, 1.092e-01, 0, 32, 1.000e-01, 5.001e-01 },//Pupae
				{                                                   },//aestival diapause adult
				{ 2.488e-02, 1.066e-01, 4, 9.998e+01                },//adult
			} };

		//because the larval stage development rate and mortality was difficulty to estimate, we evaluate larval corrected by percent by stage
		static const double PROP_BY_STAGE[LOF::NB_STAGES] = { 1, 0.206, 0.203, 0.227, 0.364, 1, 1, 1, 1 };
		double r = max(0.0, CDevRateEquation::GetRate(P_EQ[s], P_DEV[s], T)) / PROP_BY_STAGE[s];
		_ASSERTE(!_isnan(r) && _finite(r) && r >= 0);

		return r;
	}

	//*****************************************************************************
	//CSBRelativeDevRate : compute individual relative development rate

	double CLaricobiusOsakensisEquations::GetRelativeDevRate(size_t s)const
	{
		static const double SIGMA[NB_STAGES] =
		{
			//Relative devlopement Time (individual varition): sigma
			//Non-linear
			{0.135},//Egg
			{0.184},//L1
			{0.184},//L2
			{0.184},//L3
			{0.184},//L4
			{0.201},//PrePupae
			{0.128},//Pupae
			{1.000},//aestival diapause adult
			{0.401}//adult
		};

		boost::math::lognormal_distribution<double> RDR_dist(-WBSF::Square(SIGMA[s]) / 2.0, SIGMA[s]);
		double RDR = boost::math::quantile(RDR_dist, m_randomGenerator.Randu());
		while (RDR < 0.2 || RDR>2.6)//base on individual observation
			RDR = exp(SIGMA[s] * boost::math::quantile(RDR_dist, m_randomGenerator.Randu()));

		_ASSERTE(!_isnan(RDR) && _finite(RDR));

		return RDR;
	}

	double CLaricobiusOsakensisEquations::GetCreationCDD()const
	{
		boost::math::weibull_distribution<double> egg_creation_dist(m_CEC[μ], m_CEC[ѕ]);
		double CDD = boost::math::quantile(egg_creation_dist, m_randomGenerator.Rand(0.001, 0.999));

		return CDD;
	}

	double CLaricobiusOsakensisEquations::GetAdultEmergingCDD()const
	{
		boost::math::logistic_distribution<double> emerging_dist(m_EAS[μ], m_EAS[ѕ]);
		double CDD = boost::math::quantile(emerging_dist, m_randomGenerator.Rand(0.001, 0.999));

		return CDD;
	}

	//*****************************************************************************
	//survival

	double CLaricobiusOsakensisEquations::GetDailySurvivalRate(size_t s, double T)const
	{

		static const array<CSurvivalEquation::TSurvivalEquation, LOF::NB_STAGES> S_EQ =
		{
			CSurvivalEquation::Survival_01, //egg
			CSurvivalEquation::Survival_01, //L1
			CSurvivalEquation::Survival_01, //L2
			CSurvivalEquation::Survival_01, //L3
			CSurvivalEquation::Survival_01, //L4
			CSurvivalEquation::Survival_01,	//PrePupa
			CSurvivalEquation::Survival_01,	//Pupa
			CSurvivalEquation::Unknown,		//aestival diapause adult
			CSurvivalEquation::Unknown,		// adult
		};

		static const array< vector<double>, LOF::NB_STAGES>  P_SUR =
		{ {
			{ -5.906e+00, +1.299e-01, -1.459e-03 },//egg
			{ -1.087e+00, -5.072e-01, +2.209e-02 },//L1
			{ -1.087e+00, -5.072e-01, +2.209e-02 },//L2
			{ -1.087e+00, -5.072e-01, +2.209e-02 },//L3
			{ -1.087e+00, -5.072e-01, +2.209e-02 },//L4
			{ -6.276e+00, +2.963e-01, -8.149e-03 },//PrePupa
			{ +8.134e+00, -1.635e+00, +5.088e-02 },//Pupa
			{},
			{}
		} };

		double sr = max(0.0, min(1.0, CSurvivalEquation::GetSurvival(S_EQ[s], P_SUR[s], T)));

		_ASSERTE(!_isnan(sr) && _finite(sr) && sr >= 0 && sr <= 1);
		return sr;
	}

	//*****************************************************************************
	//

	//****************************************************************************
	//

	//return fecundity [eggs]
	double CLaricobiusOsakensisEquations::GetFecondity()const
	{
		//AICc,maxLL
		//1690.46,-840.107,5
		static const double Fo = 100.4;
		static const double sigma = 0.355;

		boost::math::lognormal_distribution<double> fecondity(log(Fo) - WBSF::Square(sigma) / 2.0, sigma);
		double Fi = boost::math::quantile(fecondity, m_randomGenerator.Rand(0.001, 0.999));

		ASSERT(!_isnan(Fi) && _finite(Fi));

		return Fi;
	}

	double CLaricobiusOsakensisEquations::GetFecondityRate(double age, double T)const
	{
		//AICc,maxLL
		//1698.68,-839.968
		static const CDevRateEquation::TDevRateEquation P_EQ = CDevRateEquation::Taylor_1981;

		static const vector<double> P_FEC = { 0.01518, 10.9, 6.535 };
		double r = max(0.0, CDevRateEquation::GetRate(P_EQ, P_FEC, T));

		_ASSERTE(!_isnan(r) && _finite(r) && r >= 0);

		return r;
	}

}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2015 Felix Rieseberg <feriese@microsoft.com> and
// Jason Poon <jason.poon@microsoft.com>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.

#include "brightray/browser/win/notification_presenter_win.h"

#include <string>
#include <vector>

#include "base/files/file_util.h"
#include "base/md5.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/windows_version.h"
#include "brightray/browser/win/notification_presenter_win7.h"
#include "brightray/browser/win/windows_toast_notification.h"
#include "content/public/browser/desktop_notification_delegate.h"
#include "content/public/common/platform_notification_data.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"

#pragma comment(lib, "runtimeobject.lib")

namespace brightray {

namespace {

bool SaveIconToPath(const SkBitmap& bitmap, const base::FilePath& path) {
  std::vector<unsigned char> png_data;
  if (!gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &png_data))
    return false;

  char* data = reinterpret_cast<char*>(&png_data[0]);
  int size = static_cast<int>(png_data.size());
  return base::WriteFile(path, data, size) == size;
}

}  // namespace

// static
NotificationPresenter* NotificationPresenter::Create() {
  auto version = base::win::GetVersion();
  if (version < base::win::VERSION_WIN8)
    return new NotificationPresenterWin7;
  if (!WindowsToastNotification::Initialize())
    return nullptr;
  std::unique_ptr<NotificationPresenterWin> presenter(
      new NotificationPresenterWin);
  if (!presenter->Init())
    return nullptr;
  return presenter.release();
}

NotificationPresenterWin::NotificationPresenterWin() {
}

NotificationPresenterWin::~NotificationPresenterWin() {
}

bool NotificationPresenterWin::Init() {
  return temp_dir_.CreateUniqueTempDir();
}

base::string16 NotificationPresenterWin::SaveIconToFilesystem(
    const SkBitmap& icon, const GURL& origin) {
  std::string filename = base::MD5String(origin.spec()) + ".png";
  base::FilePath path = temp_dir_.GetPath().Append(base::UTF8ToUTF16(filename));
  if (base::PathExists(path))
    return path.value();
  if (SaveIconToPath(icon, path))
    return path.value();
  return base::UTF8ToUTF16(origin.spec());
}

Notification* NotificationPresenterWin::CreateNotificationObject(
    NotificationDelegate* delegate) {
  return new WindowsToastNotification(delegate, this);
}

}  // namespace brightray
<commit_msg>:wrench: Ensure correct path<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2015 Felix Rieseberg <feriese@microsoft.com> and
// Jason Poon <jason.poon@microsoft.com>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.

#include "brightray/browser/win/notification_presenter_win.h"

#include <string>
#include <vector>

#include "base/files/file_util.h"
#include "base/md5.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/win/windows_version.h"
#include "brightray/browser/win/notification_presenter_win7.h"
#include "brightray/browser/win/windows_toast_notification.h"
#include "content/public/browser/desktop_notification_delegate.h"
#include "content/public/common/platform_notification_data.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"

#pragma comment(lib, "runtimeobject.lib")

namespace brightray {

namespace {

bool SaveIconToPath(const SkBitmap& bitmap, const base::FilePath& path) {
  std::vector<unsigned char> png_data;
  if (!gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &png_data))
    return false;

  char* data = reinterpret_cast<char*>(&png_data[0]);
  int size = static_cast<int>(png_data.size());
  return base::WriteFile(path, data, size) == size;
}

}  // namespace

// static
NotificationPresenter* NotificationPresenter::Create() {
  auto version = base::win::GetVersion();
  if (version < base::win::VERSION_WIN8)
    return new NotificationPresenterWin7;
  if (!WindowsToastNotification::Initialize())
    return nullptr;
  std::unique_ptr<NotificationPresenterWin> presenter(
      new NotificationPresenterWin);
  if (!presenter->Init())
    return nullptr;
  return presenter.release();
}

NotificationPresenterWin::NotificationPresenterWin() {
}

NotificationPresenterWin::~NotificationPresenterWin() {
}

bool NotificationPresenterWin::Init() {
  return temp_dir_.CreateUniqueTempDir();
}

base::string16 NotificationPresenterWin::SaveIconToFilesystem(
    const SkBitmap& icon, const GURL& origin) {
  std::string filename;

  if (origin.is_valid()) {
    filename = base::MD5String(origin.spec()) + ".png";
  } else {
    base::TimeTicks now = base::TimeTicks::Now();
    filename = std::to_string(now.ToInternalValue()) + ".png";
  }

  base::FilePath path = temp_dir_.GetPath().Append(base::UTF8ToUTF16(filename));
  if (base::PathExists(path))
    return path.value();
  if (SaveIconToPath(icon, path))
    return path.value();
  return base::UTF8ToUTF16(origin.spec());
}

Notification* NotificationPresenterWin::CreateNotificationObject(
    NotificationDelegate* delegate) {
  return new WindowsToastNotification(delegate, this);
}

}  // namespace brightray
<|endoftext|>


<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of hdf5_handler, a data handler for the OPeNDAP data
// server.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// HDF5RequestHandler.cc

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "HDF5RequestHandler.h"

#include "h5_handler.h"

#include <BESDASResponse.h>
#include <BESDDSResponse.h>
#include <BESDataDDSResponse.h>
#include <Ancillary.h>
#include <BESInfo.h>
#include <BESResponseNames.h>
#include <BESContainer.h>
#include <BESResponseHandler.h>
#include <BESVersionInfo.h>
#include <BESServiceRegistry.h>
#include <BESUtil.h>
#include <BESDataNames.h>
#include <BESDapError.h>
#include <BESNotFoundError.h>
#include <BESInternalFatalError.h>
#include "H5Git.h"

#define HDF5_NAME "h5"

/// An external object that handles NASA EOS HDF5 files for grid generation
/// and meta data parsing.
extern H5EOS eos;

HDF5RequestHandler::HDF5RequestHandler(const string & name)
    :BESRequestHandler(name)
{
    add_handler(DAS_RESPONSE, HDF5RequestHandler::hdf5_build_das);
    add_handler(DDS_RESPONSE, HDF5RequestHandler::hdf5_build_dds);
    add_handler(DATA_RESPONSE, HDF5RequestHandler::hdf5_build_data);
    add_handler(HELP_RESPONSE, HDF5RequestHandler::hdf5_build_help);
    add_handler(VERS_RESPONSE, HDF5RequestHandler::hdf5_build_version);
}

HDF5RequestHandler::~HDF5RequestHandler()
{
}

bool HDF5RequestHandler::hdf5_build_das(BESDataHandlerInterface & dhi)
{
    string filename = dhi.container->access();
    hid_t file1 = get_fileid(filename.c_str());
    if (file1 < 0) {
        throw BESNotFoundError((string) "Could not open hdf file: "
                               + filename, __FILE__, __LINE__);
    }
    if (eos.check_eos(file1))
        eos.set_dimension_array();

    BESResponseObject *response = dhi.response_handler->get_response_object() ;
    BESDASResponse *bdas = dynamic_cast < BESDASResponse * >(response) ;
    if( !bdas )
        throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;

    try {
        bdas->set_container( dhi.container->get_symbolic_name() ) ;
        DAS *das = bdas->get_das();
        find_gloattr(file1, *das);
        depth_first(file1, "/", *das);
        Ancillary::read_ancillary_das( *das, filename ) ;

        bdas->clear_container() ;
    }
    catch(InternalErr & e) {
        BESDapError ex(e.get_error_message(), true, e.get_error_code(),
                       __FILE__, __LINE__);
        throw ex;
    }
    catch(Error & e) {
        BESDapError ex(e.get_error_message(), false, e.get_error_code(),
                       __FILE__, __LINE__);
        throw ex;
    }
    catch(...) {
        string s = "unknown exception caught building HDF5 DAS";
        BESInternalFatalError ex(s, __FILE__, __LINE__);
        throw ex;
    }

    return true;
}

bool HDF5RequestHandler::hdf5_build_dds(BESDataHandlerInterface & dhi)
{
    string filename = dhi.container->access();
    hid_t file1 = get_fileid(filename.c_str());
    if (file1 < 0) {
        throw BESNotFoundError(string("hdf5_build_dds: ")
                               + "Could not open hdf5 file: "
                               + filename, __FILE__, __LINE__);
    }
    if (eos.check_eos(file1))
        eos.set_dimension_array();

    BESResponseObject *response = dhi.response_handler->get_response_object();
    BESDDSResponse *bdds = dynamic_cast < BESDDSResponse * >(response);
    if( !bdds )
        throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;

    try {
        bdds->set_container( dhi.container->get_symbolic_name() ) ;
        DDS *dds = bdds->get_dds();

        depth_first(file1, "/", *dds, filename.c_str());

        Ancillary::read_ancillary_dds( *dds, filename ) ;

        DAS *das = new DAS ;
        BESDASResponse bdas( das ) ;
        bdas.set_container( dhi.container->get_symbolic_name() ) ;

        find_gloattr(file1, *das);
        depth_first(file1, "/", *das);

        Ancillary::read_ancillary_das( *das, filename ) ;

        dds->transfer_attributes(das);

        bdds->set_constraint( dhi ) ;

        bdds->clear_container() ;
    }
    catch(InternalErr & e) {
        BESDapError ex(e.get_error_message(), true, e.get_error_code(),
                       __FILE__, __LINE__);
        throw ex;
    }
    catch(Error & e) {
        BESDapError ex(e.get_error_message(), false, e.get_error_code(),
                       __FILE__, __LINE__);
        throw ex;
    }
    catch(...) {
        string s = "unknown exception caught building HDF5 DDS";
        BESInternalFatalError ex(s, __FILE__, __LINE__);
        throw ex;
    }

    return true;
}

bool HDF5RequestHandler::hdf5_build_data(BESDataHandlerInterface & dhi)
{
    string filename = dhi.container->access();
    hid_t file1 = get_fileid(filename.c_str());
    if (file1 < 0) {
        throw BESNotFoundError(string("hdf5_build_data: ")
                               + "Could not open hdf5 file: "
                               + filename, __FILE__, __LINE__);
    }
    if (eos.check_eos(file1))
        eos.set_dimension_array();

    BESResponseObject *response = dhi.response_handler->get_response_object();
    BESDataDDSResponse *bdds = dynamic_cast < BESDataDDSResponse * >(response);
    if( !bdds )
        throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;

    try {
        bdds->set_container( dhi.container->get_symbolic_name() ) ;
        DataDDS *dds = bdds->get_dds();

        depth_first(file1, "/", *dds, filename.c_str());

        Ancillary::read_ancillary_dds( *dds, filename ) ;

        DAS *das = new DAS ;
        BESDASResponse bdas( das ) ;
        bdas.set_container( dhi.container->get_symbolic_name() ) ;

        find_gloattr(file1, *das);
        depth_first(file1, "/", *das);

        Ancillary::read_ancillary_das( *das, filename ) ;

        dds->transfer_attributes(das);

        bdds->set_constraint( dhi ) ;

        bdds->clear_container() ;
    }
    catch(InternalErr & e) {
        BESDapError ex(e.get_error_message(), true, e.get_error_code(),
                       __FILE__, __LINE__);
        throw ex;
    }
    catch(Error & e) {
        BESDapError ex(e.get_error_message(), false, e.get_error_code(),
                       __FILE__, __LINE__);
        throw ex;
    }
    catch(...) {
        string s = "unknown exception caught building HDF5 DataDDS";
        BESInternalFatalError ex(s, __FILE__, __LINE__);
        throw ex;
    }

    return true;
}

bool HDF5RequestHandler::hdf5_build_help(BESDataHandlerInterface & dhi)
{
    BESResponseObject *response = dhi.response_handler->get_response_object();
    BESInfo *info = dynamic_cast<BESInfo *>(response);
    if( !info )
        throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;

    map<string,string> attrs ;
    attrs["name"] = PACKAGE_NAME ;
    attrs["version"] = PACKAGE_VERSION ;
    list<string> services ;
    BESServiceRegistry::TheRegistry()->services_handled( HDF5_NAME, services );
    if( services.size() > 0 )
        {
            string handles = BESUtil::implode( services, ',' ) ;
            attrs["handles"] = handles ;
        }
    info->begin_tag( "module", &attrs ) ;
    info->end_tag( "module" ) ;

    return true;
}

bool HDF5RequestHandler::hdf5_build_version(BESDataHandlerInterface & dhi)
{
    BESResponseObject *response = dhi.response_handler->get_response_object();
    BESVersionInfo *info = dynamic_cast < BESVersionInfo * >(response);
    if( !info )
        throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;

    info->add_module( PACKAGE_NAME, PACKAGE_VERSION ) ;

    return true;
}
<commit_msg>DAP Macro changes<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of hdf5_handler, a data handler for the OPeNDAP data
// server.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// HDF5RequestHandler.cc

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "HDF5RequestHandler.h"

#include "h5_handler.h"

#include <BESDASResponse.h>
#include <BESDDSResponse.h>
#include <BESDataDDSResponse.h>
#include <Ancillary.h>
#include <BESInfo.h>
#include <BESDapNames.h>
#include <BESResponseNames.h>
#include <BESContainer.h>
#include <BESResponseHandler.h>
#include <BESVersionInfo.h>
#include <BESServiceRegistry.h>
#include <BESUtil.h>
#include <BESDapError.h>
#include <BESNotFoundError.h>
#include <BESInternalFatalError.h>
#include "H5Git.h"

#define HDF5_NAME "h5"

/// An external object that handles NASA EOS HDF5 files for grid generation
/// and meta data parsing.
extern H5EOS eos;

HDF5RequestHandler::HDF5RequestHandler(const string & name)
    :BESRequestHandler(name)
{
    add_handler(DAS_RESPONSE, HDF5RequestHandler::hdf5_build_das);
    add_handler(DDS_RESPONSE, HDF5RequestHandler::hdf5_build_dds);
    add_handler(DATA_RESPONSE, HDF5RequestHandler::hdf5_build_data);
    add_handler(HELP_RESPONSE, HDF5RequestHandler::hdf5_build_help);
    add_handler(VERS_RESPONSE, HDF5RequestHandler::hdf5_build_version);
}

HDF5RequestHandler::~HDF5RequestHandler()
{
}

bool HDF5RequestHandler::hdf5_build_das(BESDataHandlerInterface & dhi)
{
    string filename = dhi.container->access();
    hid_t file1 = get_fileid(filename.c_str());
    if (file1 < 0) {
        throw BESNotFoundError((string) "Could not open hdf file: "
                               + filename, __FILE__, __LINE__);
    }
    if (eos.check_eos(file1))
        eos.set_dimension_array();

    BESResponseObject *response = dhi.response_handler->get_response_object() ;
    BESDASResponse *bdas = dynamic_cast < BESDASResponse * >(response) ;
    if( !bdas )
        throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;

    try {
        bdas->set_container( dhi.container->get_symbolic_name() ) ;
        DAS *das = bdas->get_das();
        find_gloattr(file1, *das);
        depth_first(file1, "/", *das);
        Ancillary::read_ancillary_das( *das, filename ) ;

        bdas->clear_container() ;
    }
    catch(InternalErr & e) {
        BESDapError ex(e.get_error_message(), true, e.get_error_code(),
                       __FILE__, __LINE__);
        throw ex;
    }
    catch(Error & e) {
        BESDapError ex(e.get_error_message(), false, e.get_error_code(),
                       __FILE__, __LINE__);
        throw ex;
    }
    catch(...) {
        string s = "unknown exception caught building HDF5 DAS";
        BESInternalFatalError ex(s, __FILE__, __LINE__);
        throw ex;
    }

    return true;
}

bool HDF5RequestHandler::hdf5_build_dds(BESDataHandlerInterface & dhi)
{
    string filename = dhi.container->access();
    hid_t file1 = get_fileid(filename.c_str());
    if (file1 < 0) {
        throw BESNotFoundError(string("hdf5_build_dds: ")
                               + "Could not open hdf5 file: "
                               + filename, __FILE__, __LINE__);
    }
    if (eos.check_eos(file1))
        eos.set_dimension_array();

    BESResponseObject *response = dhi.response_handler->get_response_object();
    BESDDSResponse *bdds = dynamic_cast < BESDDSResponse * >(response);
    if( !bdds )
        throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;

    try {
        bdds->set_container( dhi.container->get_symbolic_name() ) ;
        DDS *dds = bdds->get_dds();

        depth_first(file1, "/", *dds, filename.c_str());

        Ancillary::read_ancillary_dds( *dds, filename ) ;

        DAS *das = new DAS ;
        BESDASResponse bdas( das ) ;
        bdas.set_container( dhi.container->get_symbolic_name() ) ;

        find_gloattr(file1, *das);
        depth_first(file1, "/", *das);

        Ancillary::read_ancillary_das( *das, filename ) ;

        dds->transfer_attributes(das);

        bdds->set_constraint( dhi ) ;

        bdds->clear_container() ;
    }
    catch(InternalErr & e) {
        BESDapError ex(e.get_error_message(), true, e.get_error_code(),
                       __FILE__, __LINE__);
        throw ex;
    }
    catch(Error & e) {
        BESDapError ex(e.get_error_message(), false, e.get_error_code(),
                       __FILE__, __LINE__);
        throw ex;
    }
    catch(...) {
        string s = "unknown exception caught building HDF5 DDS";
        BESInternalFatalError ex(s, __FILE__, __LINE__);
        throw ex;
    }

    return true;
}

bool HDF5RequestHandler::hdf5_build_data(BESDataHandlerInterface & dhi)
{
    string filename = dhi.container->access();
    hid_t file1 = get_fileid(filename.c_str());
    if (file1 < 0) {
        throw BESNotFoundError(string("hdf5_build_data: ")
                               + "Could not open hdf5 file: "
                               + filename, __FILE__, __LINE__);
    }
    if (eos.check_eos(file1))
        eos.set_dimension_array();

    BESResponseObject *response = dhi.response_handler->get_response_object();
    BESDataDDSResponse *bdds = dynamic_cast < BESDataDDSResponse * >(response);
    if( !bdds )
        throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;

    try {
        bdds->set_container( dhi.container->get_symbolic_name() ) ;
        DataDDS *dds = bdds->get_dds();

        depth_first(file1, "/", *dds, filename.c_str());

        Ancillary::read_ancillary_dds( *dds, filename ) ;

        DAS *das = new DAS ;
        BESDASResponse bdas( das ) ;
        bdas.set_container( dhi.container->get_symbolic_name() ) ;

        find_gloattr(file1, *das);
        depth_first(file1, "/", *das);

        Ancillary::read_ancillary_das( *das, filename ) ;

        dds->transfer_attributes(das);

        bdds->set_constraint( dhi ) ;

        bdds->clear_container() ;
    }
    catch(InternalErr & e) {
        BESDapError ex(e.get_error_message(), true, e.get_error_code(),
                       __FILE__, __LINE__);
        throw ex;
    }
    catch(Error & e) {
        BESDapError ex(e.get_error_message(), false, e.get_error_code(),
                       __FILE__, __LINE__);
        throw ex;
    }
    catch(...) {
        string s = "unknown exception caught building HDF5 DataDDS";
        BESInternalFatalError ex(s, __FILE__, __LINE__);
        throw ex;
    }

    return true;
}

bool HDF5RequestHandler::hdf5_build_help(BESDataHandlerInterface & dhi)
{
    BESResponseObject *response = dhi.response_handler->get_response_object();
    BESInfo *info = dynamic_cast<BESInfo *>(response);
    if( !info )
        throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;

    map<string,string> attrs ;
    attrs["name"] = PACKAGE_NAME ;
    attrs["version"] = PACKAGE_VERSION ;
    list<string> services ;
    BESServiceRegistry::TheRegistry()->services_handled( HDF5_NAME, services );
    if( services.size() > 0 )
        {
            string handles = BESUtil::implode( services, ',' ) ;
            attrs["handles"] = handles ;
        }
    info->begin_tag( "module", &attrs ) ;
    info->end_tag( "module" ) ;

    return true;
}

bool HDF5RequestHandler::hdf5_build_version(BESDataHandlerInterface & dhi)
{
    BESResponseObject *response = dhi.response_handler->get_response_object();
    BESVersionInfo *info = dynamic_cast < BESVersionInfo * >(response);
    if( !info )
        throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;

    info->add_module( PACKAGE_NAME, PACKAGE_VERSION ) ;

    return true;
}
<|endoftext|>


<commit_before>//===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the auto-upgrade helper functions
//
//===----------------------------------------------------------------------===//

#include "llvm/Assembly/AutoUpgrade.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/SymbolTable.h"
#include <iostream>

using namespace llvm;

// Utility function for getting the correct suffix given a type
static inline const char* get_suffix(const Type* Ty) {
  switch (Ty->getTypeID()) {
    case Type::UIntTyID:    return ".i32";
    case Type::UShortTyID:  return ".i16";
    case Type::UByteTyID:   return ".i8";
    case Type::ULongTyID:   return ".i64";
    case Type::FloatTyID:   return ".f32";
    case Type::DoubleTyID:  return ".f64";
    default:                break;
  }
  return 0;
}

static inline const Type* get_type(Function* F) {
  // If there's no function, we can't get the argument type.
  if (!F)
    return 0;

  // Get the Function's name.
  const std::string& Name = F->getName();

  // Quickly eliminate it, if it's not a candidate.
  if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' || Name[2] !=
    'v' || Name[3] != 'm' || Name[4] != '.')
    return 0;

  switch (Name[5]) {
    case 'b':
      if (Name == "llvm.bswap")
        return F->getReturnType();
      break;
    case 'c':
      if (Name == "llvm.ctpop" || Name == "llvm.ctlz" || Name == "llvm.cttz")
        return F->getReturnType();
      break;
    case 'i':
      if (Name == "llvm.isunordered") {
        Function::const_arg_iterator ArgIt = F->arg_begin();
        if (ArgIt != F->arg_end())
          return ArgIt->getType();
      }
      break;
    case 's':
      if (Name == "llvm.sqrt")
        return F->getReturnType();
      break;
    default:
      break;
  }
  return 0;
}

bool llvm::IsUpgradeableIntrinsicName(const std::string& Name) {
  // Quickly eliminate it, if it's not a candidate.
  if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' || Name[2] !=
    'v' || Name[3] != 'm' || Name[4] != '.')
    return false;

  switch (Name[5]) {
    case 'b':
      if (Name == "llvm.bswap")
        return true;
      break;
    case 'c':
      if (Name == "llvm.ctpop" || Name == "llvm.ctlz" || Name == "llvm.cttz")
        return true;
      break;
    case 'i':
      if (Name == "llvm.isunordered")
        return true;
      break;
    case 's':
      if (Name == "llvm.sqrt")
        return true;
      break;
    default:
      break;
  }
  return false;
}

// UpgradeIntrinsicFunction - Convert overloaded intrinsic function names to
// their non-overloaded variants by appending the appropriate suffix based on
// the argument types.
Function* llvm::UpgradeIntrinsicFunction(Function* F) {
  // See if its one of the name's we're interested in.
  if (const Type* Ty = get_type(F)) {
    const char* suffix = get_suffix(Ty);
    if (Ty->isSigned())
      suffix = get_suffix(Ty->getUnsignedVersion());
    assert(suffix && "Intrinsic parameter type not recognized");
    const std::string& Name = F->getName();
    std::string new_name = Name + suffix;
    std::cerr << "WARNING: change " << Name << " to " << new_name << "\n";
    SymbolTable& SymTab = F->getParent()->getSymbolTable();
    if (Value* V = SymTab.lookup(F->getType(),new_name))
      if (Function* OtherF = dyn_cast<Function>(V))
        return OtherF;

    // There wasn't an existing function for the intrinsic, so now make sure the
    // signedness of the arguments is correct.
    if (Ty->isSigned()) {
      const Type* newTy = Ty->getUnsignedVersion();
      std::vector<const Type*> Params;
      Params.push_back(newTy);
      FunctionType* FT = FunctionType::get(newTy, Params,false);
      return new Function(FT, GlobalValue::ExternalLinkage, new_name,
                          F->getParent());
    }

    // The argument was the correct type (unsigned or floating), so just
    // rename the function to its correct name and return it.
    F->setName(new_name);
    return F;
  }
  return 0;
}

Instruction* llvm::UpgradeIntrinsicCall(CallInst *CI) {
  Function *F = CI->getCalledFunction();
  if (const Type* Ty = get_type(F)) {
    Function* newF = UpgradeIntrinsicFunction(F);
    std::vector<Value*> Oprnds;
    for (User::op_iterator OI = CI->op_begin(), OE = CI->op_end();
         OI != OE; ++OI)
      Oprnds.push_back(CI);
    CallInst* newCI = new CallInst(newF,Oprnds,"autoupgrade_call",CI);
    if (Ty->isSigned()) {
      const Type* newTy = Ty->getUnsignedVersion();
      newCI->setOperand(1,new CastInst(newCI->getOperand(1), newTy,
                     "autoupgrade_cast", newCI));
      CastInst* final = new CastInst(newCI, Ty, "autoupgrade_uncast",newCI);
      newCI->moveBefore(final);
      return final;
    }
    return newCI;
  }
  return 0;
}

bool llvm::UpgradeCallsToIntrinsic(Function* F) {
  if (Function* newF = UpgradeIntrinsicFunction(F)) {
    for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
         UI != UE; UI) {
      if (CallInst* CI = dyn_cast<CallInst>(*UI++)) {
        std::vector<Value*> Oprnds;
        User::op_iterator OI = CI->op_begin();
        ++OI;
        for (User::op_iterator OE = CI->op_end(); OI != OE; ++OI)
          Oprnds.push_back(*OI);
        CallInst* newCI = new CallInst(newF,Oprnds,"autoupgrade_call",CI);
        const Type* Ty = Oprnds[0]->getType();
        if (Ty->isSigned()) {
          const Type* newTy = Ty->getUnsignedVersion();
          newCI->setOperand(1,new CastInst(newCI->getOperand(1), newTy,
                         "autoupgrade_cast", newCI));
          CastInst* final = new CastInst(newCI, Ty, "autoupgrade_uncast",newCI);
          newCI->moveBefore(final);
          CI->replaceAllUsesWith(final);
        } else {
          CI->replaceAllUsesWith(newCI);
        }
        CI->eraseFromParent();
      }
    }
    if (newF != F)
      F->eraseFromParent();
    return true;
  }
  return false;
}
<commit_msg>Remove dead expression.<commit_after>//===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the auto-upgrade helper functions
//
//===----------------------------------------------------------------------===//

#include "llvm/Assembly/AutoUpgrade.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/SymbolTable.h"
#include <iostream>

using namespace llvm;

// Utility function for getting the correct suffix given a type
static inline const char* get_suffix(const Type* Ty) {
  switch (Ty->getTypeID()) {
    case Type::UIntTyID:    return ".i32";
    case Type::UShortTyID:  return ".i16";
    case Type::UByteTyID:   return ".i8";
    case Type::ULongTyID:   return ".i64";
    case Type::FloatTyID:   return ".f32";
    case Type::DoubleTyID:  return ".f64";
    default:                break;
  }
  return 0;
}

static inline const Type* get_type(Function* F) {
  // If there's no function, we can't get the argument type.
  if (!F)
    return 0;

  // Get the Function's name.
  const std::string& Name = F->getName();

  // Quickly eliminate it, if it's not a candidate.
  if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' || Name[2] !=
    'v' || Name[3] != 'm' || Name[4] != '.')
    return 0;

  switch (Name[5]) {
    case 'b':
      if (Name == "llvm.bswap")
        return F->getReturnType();
      break;
    case 'c':
      if (Name == "llvm.ctpop" || Name == "llvm.ctlz" || Name == "llvm.cttz")
        return F->getReturnType();
      break;
    case 'i':
      if (Name == "llvm.isunordered") {
        Function::const_arg_iterator ArgIt = F->arg_begin();
        if (ArgIt != F->arg_end())
          return ArgIt->getType();
      }
      break;
    case 's':
      if (Name == "llvm.sqrt")
        return F->getReturnType();
      break;
    default:
      break;
  }
  return 0;
}

bool llvm::IsUpgradeableIntrinsicName(const std::string& Name) {
  // Quickly eliminate it, if it's not a candidate.
  if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' || Name[2] !=
    'v' || Name[3] != 'm' || Name[4] != '.')
    return false;

  switch (Name[5]) {
    case 'b':
      if (Name == "llvm.bswap")
        return true;
      break;
    case 'c':
      if (Name == "llvm.ctpop" || Name == "llvm.ctlz" || Name == "llvm.cttz")
        return true;
      break;
    case 'i':
      if (Name == "llvm.isunordered")
        return true;
      break;
    case 's':
      if (Name == "llvm.sqrt")
        return true;
      break;
    default:
      break;
  }
  return false;
}

// UpgradeIntrinsicFunction - Convert overloaded intrinsic function names to
// their non-overloaded variants by appending the appropriate suffix based on
// the argument types.
Function* llvm::UpgradeIntrinsicFunction(Function* F) {
  // See if its one of the name's we're interested in.
  if (const Type* Ty = get_type(F)) {
    const char* suffix = get_suffix(Ty);
    if (Ty->isSigned())
      suffix = get_suffix(Ty->getUnsignedVersion());
    assert(suffix && "Intrinsic parameter type not recognized");
    const std::string& Name = F->getName();
    std::string new_name = Name + suffix;
    std::cerr << "WARNING: change " << Name << " to " << new_name << "\n";
    SymbolTable& SymTab = F->getParent()->getSymbolTable();
    if (Value* V = SymTab.lookup(F->getType(),new_name))
      if (Function* OtherF = dyn_cast<Function>(V))
        return OtherF;

    // There wasn't an existing function for the intrinsic, so now make sure the
    // signedness of the arguments is correct.
    if (Ty->isSigned()) {
      const Type* newTy = Ty->getUnsignedVersion();
      std::vector<const Type*> Params;
      Params.push_back(newTy);
      FunctionType* FT = FunctionType::get(newTy, Params,false);
      return new Function(FT, GlobalValue::ExternalLinkage, new_name,
                          F->getParent());
    }

    // The argument was the correct type (unsigned or floating), so just
    // rename the function to its correct name and return it.
    F->setName(new_name);
    return F;
  }
  return 0;
}

Instruction* llvm::UpgradeIntrinsicCall(CallInst *CI) {
  Function *F = CI->getCalledFunction();
  if (const Type* Ty = get_type(F)) {
    Function* newF = UpgradeIntrinsicFunction(F);
    std::vector<Value*> Oprnds;
    for (User::op_iterator OI = CI->op_begin(), OE = CI->op_end();
         OI != OE; ++OI)
      Oprnds.push_back(CI);
    CallInst* newCI = new CallInst(newF,Oprnds,"autoupgrade_call",CI);
    if (Ty->isSigned()) {
      const Type* newTy = Ty->getUnsignedVersion();
      newCI->setOperand(1,new CastInst(newCI->getOperand(1), newTy,
                     "autoupgrade_cast", newCI));
      CastInst* final = new CastInst(newCI, Ty, "autoupgrade_uncast",newCI);
      newCI->moveBefore(final);
      return final;
    }
    return newCI;
  }
  return 0;
}

bool llvm::UpgradeCallsToIntrinsic(Function* F) {
  if (Function* newF = UpgradeIntrinsicFunction(F)) {
    for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
         UI != UE; ) {
      if (CallInst* CI = dyn_cast<CallInst>(*UI++)) {
        std::vector<Value*> Oprnds;
        User::op_iterator OI = CI->op_begin();
        ++OI;
        for (User::op_iterator OE = CI->op_end(); OI != OE; ++OI)
          Oprnds.push_back(*OI);
        CallInst* newCI = new CallInst(newF,Oprnds,"autoupgrade_call",CI);
        const Type* Ty = Oprnds[0]->getType();
        if (Ty->isSigned()) {
          const Type* newTy = Ty->getUnsignedVersion();
          newCI->setOperand(1,new CastInst(newCI->getOperand(1), newTy,
                         "autoupgrade_cast", newCI));
          CastInst* final = new CastInst(newCI, Ty, "autoupgrade_uncast",newCI);
          newCI->moveBefore(final);
          CI->replaceAllUsesWith(final);
        } else {
          CI->replaceAllUsesWith(newCI);
        }
        CI->eraseFromParent();
      }
    }
    if (newF != F)
      F->eraseFromParent();
    return true;
  }
  return false;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: defaultforminspection.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 10:47:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *
 ************************************************************************/
#ifndef EXTENSIONS_SOURCE_PROPCTRLR_DEFAULTFORMINSPECTION_HXX
#define EXTENSIONS_SOURCE_PROPCTRLR_DEFAULTFORMINSPECTION_HXX

#ifndef INSPECTORMODELBASE_HXX
#include "inspectormodelbase.hxx"
#endif

/** === begin UNO includes === **/
/** === end UNO includes === **/

#include <memory>

//........................................................................
namespace pcr
{
//........................................................................

    class OPropertyInfoService;
    //====================================================================
    //= DefaultFormComponentInspectorModel
    //====================================================================
    class DefaultFormComponentInspectorModel : public ImplInspectorModel
    {
    private:
        bool                                        m_bUseFormComponentHandlers;
        bool                                        m_bConstructed;

        /// access to property meta data
        ::std::auto_ptr< OPropertyInfoService >     m_pInfoService;

    protected:
        ~DefaultFormComponentInspectorModel();

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw(::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException);

        // XObjectInspectorModel
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL getHandlerFactories() throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::inspection::PropertyCategoryDescriptor > SAL_CALL describeCategories(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Int32 SAL_CALL getPropertyOrderIndex( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::uno::RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    public:
        // XServiceInfo - static versions
        static ::rtl::OUString getImplementationName_static(  ) throw(::com::sun::star::uno::RuntimeException);
        static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_static(  ) throw(::com::sun::star::uno::RuntimeException);
        static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
                        Create(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >&);

    public:
        DefaultFormComponentInspectorModel( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext, bool _bUseFormFormComponentHandlers = true );

    protected:
        // Service constructors
        void    createDefault();
        void    createWithHelpSection( sal_Int32 _nMinHelpTextLines, sal_Int32 _nMaxHelpTextLines );
    };

//........................................................................
} // namespace pcr
//........................................................................

#endif // EXTENSIONS_SOURCE_PROPCTRLR_DEFAULTFORMINSPECTION_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.4.164); FILE MERGED 2008/04/01 12:29:48 thb 1.4.164.2: #i85898# Stripping all external header guards 2008/03/31 12:31:40 rt 1.4.164.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: defaultforminspection.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef EXTENSIONS_SOURCE_PROPCTRLR_DEFAULTFORMINSPECTION_HXX
#define EXTENSIONS_SOURCE_PROPCTRLR_DEFAULTFORMINSPECTION_HXX

#include "inspectormodelbase.hxx"

/** === begin UNO includes === **/
/** === end UNO includes === **/

#include <memory>

//........................................................................
namespace pcr
{
//........................................................................

    class OPropertyInfoService;
    //====================================================================
    //= DefaultFormComponentInspectorModel
    //====================================================================
    class DefaultFormComponentInspectorModel : public ImplInspectorModel
    {
    private:
        bool                                        m_bUseFormComponentHandlers;
        bool                                        m_bConstructed;

        /// access to property meta data
        ::std::auto_ptr< OPropertyInfoService >     m_pInfoService;

    protected:
        ~DefaultFormComponentInspectorModel();

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw(::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException);

        // XObjectInspectorModel
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL getHandlerFactories() throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::inspection::PropertyCategoryDescriptor > SAL_CALL describeCategories(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Int32 SAL_CALL getPropertyOrderIndex( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::uno::RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    public:
        // XServiceInfo - static versions
        static ::rtl::OUString getImplementationName_static(  ) throw(::com::sun::star::uno::RuntimeException);
        static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_static(  ) throw(::com::sun::star::uno::RuntimeException);
        static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
                        Create(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >&);

    public:
        DefaultFormComponentInspectorModel( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext, bool _bUseFormFormComponentHandlers = true );

    protected:
        // Service constructors
        void    createDefault();
        void    createWithHelpSection( sal_Int32 _nMinHelpTextLines, sal_Int32 _nMaxHelpTextLines );
    };

//........................................................................
} // namespace pcr
//........................................................................

#endif // EXTENSIONS_SOURCE_PROPCTRLR_DEFAULTFORMINSPECTION_HXX

<|endoftext|>


<commit_before>//
// C++ Implementation: %{MODULE}
//
// Description:
//
//
// Author: %{AUTHOR} <%{EMAIL}>, (C) %{YEAR}
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "inputprotocolbase.h"

InputProtocolBase::InputProtocolBase(QObject *parent, const char *name)
 : QObject(parent, name)
{
}

InputProtocolBase::~InputProtocolBase()
{
}

uint InputProtocolBase::state() const
{
	return m_state;
}

bool InputProtocolBase::readString( QString &message )
{
	uint len;
	QCString rawData;
	if ( !safeReadBytes( rawData, len ) )
		return false;
	message = QString::fromUtf8( rawData.data(), len );
	return true;
}

bool InputProtocolBase::okToProceed()
{
	if ( m_din )
	{
		if ( m_din->atEnd() )
		{
			m_state = NeedMore;
			qDebug( "EventProtocol::okToProceed() - Server message ended prematurely!" );
		}
		else
			return true;
	}
	return false;
}

bool InputProtocolBase::safeReadBytes( QCString & data, uint & len )
{
	// read the length of the bytes
	Q_UINT32 val;
	if ( !okToProceed() )
		return false;
	*m_din >> val;
	m_bytes += sizeof( Q_UINT32 );

	QCString temp( val );
	if ( val != 0 )
	{
		if ( !okToProceed() )
			return false;
		// if the server splits packets here we are in trouble,
		// as there is no way to see how much data was actually read
		m_din->readRawBytes( temp.data(), val );
		// the rest of the string will be filled with FF,
		// so look for that in the last position instead of \0
		if ( (Q_UINT8)( * ( temp.data() + ( temp.length() - 1 ) ) ) == 0xFF )
		{
			qDebug( "EventProtocol::safeReadBytes() - string broke, giving up" );
			m_state = NeedMore;
			return false;
		}
	}
	data = temp;
	len = val;
	m_bytes += val;
	return true;
}

#include "inputprotocolbase.moc"
<commit_msg>Fix broken string parse crash<commit_after>//
// C++ Implementation: %{MODULE}
//
// Description:
//
//
// Author: %{AUTHOR} <%{EMAIL}>, (C) %{YEAR}
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "inputprotocolbase.h"

InputProtocolBase::InputProtocolBase(QObject *parent, const char *name)
 : QObject(parent, name)
{
}

InputProtocolBase::~InputProtocolBase()
{
}

uint InputProtocolBase::state() const
{
	return m_state;
}

bool InputProtocolBase::readString( QString &message )
{
	uint len;
	QCString rawData;
	if ( !safeReadBytes( rawData, len ) )
		return false;
	message = QString::fromUtf8( rawData.data(), len );
	return true;
}

bool InputProtocolBase::okToProceed()
{
	if ( m_din )
	{
		if ( m_din->atEnd() )
		{
			m_state = NeedMore;
			qDebug( "EventProtocol::okToProceed() - Server message ended prematurely!" );
		}
		else
			return true;
	}
	return false;
}

bool InputProtocolBase::safeReadBytes( QCString & data, uint & len )
{
	// read the length of the bytes
	Q_UINT32 val;
	if ( !okToProceed() )
		return false;
	*m_din >> val;
	m_bytes += sizeof( Q_UINT32 );

	QCString temp( val );
	if ( val != 0 )
	{
		if ( !okToProceed() )
			return false;
		// if the server splits packets here we are in trouble,
		// as there is no way to see how much data was actually read
		m_din->readRawBytes( temp.data(), val );
		// the rest of the string will be filled with FF,
		// so look for that in the last position instead of \0
		// this caused a crash - guessing that temp.length() is set to the number of bytes actually read...
		// if ( (Q_UINT8)( * ( temp.data() + ( temp.length() - 1 ) ) ) == 0xFF )
		if ( temp.length() < ( val -1 ) )
		{
			qDebug( "EventProtocol::safeReadBytes() - string broke, giving up: %i, should be %i",  temp.length(), val );
			m_state = NeedMore;
			return false;
		}
	}
	data = temp;
	len = val;
	m_bytes += val;
	return true;
}

#include "inputprotocolbase.moc"
<|endoftext|>


<commit_before>/*
 * Copyright 2009 Colin Percival, 2011 ArtForz, 2012-2013 pooler
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 *
 * This file was originally written by Colin Percival as part of the Tarsnap
 * online backup system.
 */

#include "scrypt.h"
#include "util.h"
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <openssl/sha.h>

#if defined(USE_SSE2) && !defined(USE_SSE2_ALWAYS)
#ifdef _MSC_VER
// MSVC 64bit is unable to use inline asm
#include <intrin.h>
#else
// GCC Linux or i686-w64-mingw32
#include <cpuid.h>
#endif
#endif

static inline uint32_t be32dec(const void *pp)
{
	const uint8_t *p = (uint8_t const *)pp;
	return ((uint32_t)(p[3]) + ((uint32_t)(p[2]) << 8) +
	    ((uint32_t)(p[1]) << 16) + ((uint32_t)(p[0]) << 24));
}

static inline void be32enc(void *pp, uint32_t x)
{
	uint8_t *p = (uint8_t *)pp;
	p[3] = x & 0xff;
	p[2] = (x >> 8) & 0xff;
	p[1] = (x >> 16) & 0xff;
	p[0] = (x >> 24) & 0xff;
}

typedef struct HMAC_SHA256Context {
	SHA256_CTX ictx;
	SHA256_CTX octx;
} HMAC_SHA256_CTX;

/* Initialize an HMAC-SHA256 operation with the given key. */
static void
HMAC_SHA256_Init(HMAC_SHA256_CTX *ctx, const void *_K, size_t Klen)
{
	unsigned char pad[64];
	unsigned char khash[32];
	const unsigned char *K = (const unsigned char *)_K;
	size_t i;

	/* If Klen > 64, the key is really SHA256(K). */
	if (Klen > 64) {
		SHA256_Init(&ctx->ictx);
		SHA256_Update(&ctx->ictx, K, Klen);
		SHA256_Final(khash, &ctx->ictx);
		K = khash;
		Klen = 32;
	}

	/* Inner SHA256 operation is SHA256(K xor [block of 0x36] || data). */
	SHA256_Init(&ctx->ictx);
	memset(pad, 0x36, 64);
	for (i = 0; i < Klen; i++)
		pad[i] ^= K[i];
	SHA256_Update(&ctx->ictx, pad, 64);

	/* Outer SHA256 operation is SHA256(K xor [block of 0x5c] || hash). */
	SHA256_Init(&ctx->octx);
	memset(pad, 0x5c, 64);
	for (i = 0; i < Klen; i++)
		pad[i] ^= K[i];
	SHA256_Update(&ctx->octx, pad, 64);

	/* Clean the stack. */
	memset(khash, 0, 32);
}

/* Add bytes to the HMAC-SHA256 operation. */
static void
HMAC_SHA256_Update(HMAC_SHA256_CTX *ctx, const void *in, size_t len)
{
	/* Feed data to the inner SHA256 operation. */
	SHA256_Update(&ctx->ictx, in, len);
}

/* Finish an HMAC-SHA256 operation. */
static void
HMAC_SHA256_Final(unsigned char digest[32], HMAC_SHA256_CTX *ctx)
{
	unsigned char ihash[32];

	/* Finish the inner SHA256 operation. */
	SHA256_Final(ihash, &ctx->ictx);

	/* Feed the inner hash to the outer SHA256 operation. */
	SHA256_Update(&ctx->octx, ihash, 32);

	/* Finish the outer SHA256 operation. */
	SHA256_Final(digest, &ctx->octx);

	/* Clean the stack. */
	memset(ihash, 0, 32);
}

/**
 * PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, c, buf, dkLen):
 * Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and
 * write the output to buf.  The value dkLen must be at most 32 * (2^32 - 1).
 */
void
PBKDF2_SHA256(const uint8_t *passwd, size_t passwdlen, const uint8_t *salt,
    size_t saltlen, uint64_t c, uint8_t *buf, size_t dkLen)
{
	HMAC_SHA256_CTX PShctx, hctx;
	size_t i;
	uint8_t ivec[4];
	uint8_t U[32];
	uint8_t T[32];
	uint64_t j;
	int k;
	size_t clen;

	/* Compute HMAC state after processing P and S. */
	HMAC_SHA256_Init(&PShctx, passwd, passwdlen);
	HMAC_SHA256_Update(&PShctx, salt, saltlen);

	/* Iterate through the blocks. */
	for (i = 0; i * 32 < dkLen; i++) {
		/* Generate INT(i + 1). */
		be32enc(ivec, (uint32_t)(i + 1));

		/* Compute U_1 = PRF(P, S || INT(i)). */
		memcpy(&hctx, &PShctx, sizeof(HMAC_SHA256_CTX));
		HMAC_SHA256_Update(&hctx, ivec, 4);
		HMAC_SHA256_Final(U, &hctx);

		/* T_i = U_1 ... */
		memcpy(T, U, 32);

		for (j = 2; j <= c; j++) {
			/* Compute U_j. */
			HMAC_SHA256_Init(&hctx, passwd, passwdlen);
			HMAC_SHA256_Update(&hctx, U, 32);
			HMAC_SHA256_Final(U, &hctx);

			/* ... xor U_j ... */
			for (k = 0; k < 32; k++)
				T[k] ^= U[k];
		}

		/* Copy as many bytes as necessary into buf. */
		clen = dkLen - i * 32;
		if (clen > 32)
			clen = 32;
		memcpy(&buf[i * 32], T, clen);
	}

	/* Clean PShctx, since we never called _Final on it. */
	memset(&PShctx, 0, sizeof(HMAC_SHA256_CTX));
}

#define ROTL(a, b) (((a) << (b)) | ((a) >> (32 - (b))))

static inline void xor_salsa8(uint32_t B[16], const uint32_t Bx[16])
{
	uint32_t x00,x01,x02,x03,x04,x05,x06,x07,x08,x09,x10,x11,x12,x13,x14,x15;
	int i;

	x00 = (B[ 0] ^= Bx[ 0]);
	x01 = (B[ 1] ^= Bx[ 1]);
	x02 = (B[ 2] ^= Bx[ 2]);
	x03 = (B[ 3] ^= Bx[ 3]);
	x04 = (B[ 4] ^= Bx[ 4]);
	x05 = (B[ 5] ^= Bx[ 5]);
	x06 = (B[ 6] ^= Bx[ 6]);
	x07 = (B[ 7] ^= Bx[ 7]);
	x08 = (B[ 8] ^= Bx[ 8]);
	x09 = (B[ 9] ^= Bx[ 9]);
	x10 = (B[10] ^= Bx[10]);
	x11 = (B[11] ^= Bx[11]);
	x12 = (B[12] ^= Bx[12]);
	x13 = (B[13] ^= Bx[13]);
	x14 = (B[14] ^= Bx[14]);
	x15 = (B[15] ^= Bx[15]);
	for (i = 0; i < 8; i += 2) {
		/* Operate on columns. */
		x04 ^= ROTL(x00 + x12,  7);  x09 ^= ROTL(x05 + x01,  7);
		x14 ^= ROTL(x10 + x06,  7);  x03 ^= ROTL(x15 + x11,  7);

		x08 ^= ROTL(x04 + x00,  9);  x13 ^= ROTL(x09 + x05,  9);
		x02 ^= ROTL(x14 + x10,  9);  x07 ^= ROTL(x03 + x15,  9);

		x12 ^= ROTL(x08 + x04, 13);  x01 ^= ROTL(x13 + x09, 13);
		x06 ^= ROTL(x02 + x14, 13);  x11 ^= ROTL(x07 + x03, 13);

		x00 ^= ROTL(x12 + x08, 18);  x05 ^= ROTL(x01 + x13, 18);
		x10 ^= ROTL(x06 + x02, 18);  x15 ^= ROTL(x11 + x07, 18);

		/* Operate on rows. */
		x01 ^= ROTL(x00 + x03,  7);  x06 ^= ROTL(x05 + x04,  7);
		x11 ^= ROTL(x10 + x09,  7);  x12 ^= ROTL(x15 + x14,  7);

		x02 ^= ROTL(x01 + x00,  9);  x07 ^= ROTL(x06 + x05,  9);
		x08 ^= ROTL(x11 + x10,  9);  x13 ^= ROTL(x12 + x15,  9);

		x03 ^= ROTL(x02 + x01, 13);  x04 ^= ROTL(x07 + x06, 13);
		x09 ^= ROTL(x08 + x11, 13);  x14 ^= ROTL(x13 + x12, 13);

		x00 ^= ROTL(x03 + x02, 18);  x05 ^= ROTL(x04 + x07, 18);
		x10 ^= ROTL(x09 + x08, 18);  x15 ^= ROTL(x14 + x13, 18);
	}
	B[ 0] += x00;
	B[ 1] += x01;
	B[ 2] += x02;
	B[ 3] += x03;
	B[ 4] += x04;
	B[ 5] += x05;
	B[ 6] += x06;
	B[ 7] += x07;
	B[ 8] += x08;
	B[ 9] += x09;
	B[10] += x10;
	B[11] += x11;
	B[12] += x12;
	B[13] += x13;
	B[14] += x14;
	B[15] += x15;
}

void scrypt_1024_1_1_256_sp_generic(const char *input, char *output, char *scratchpad)
{
	uint8_t B[128];
	uint32_t X[32];
	uint32_t *V;
	uint32_t i, j, k;

	V = (uint32_t *)(((uintptr_t)(scratchpad) + 63) & ~ (uintptr_t)(63));

	PBKDF2_SHA256((const uint8_t *)input, 80, (const uint8_t *)input, 80, 1, B, 128);

	for (k = 0; k < 32; k++)
		X[k] = le32dec(&B[4 * k]);

	for (i = 0; i < 1024; i++) {
		memcpy(&V[i * 32], X, 128);
		xor_salsa8(&X[0], &X[16]);
		xor_salsa8(&X[16], &X[0]);
	}
	for (i = 0; i < 1024; i++) {
		j = 32 * (X[16] & 1023);
		for (k = 0; k < 32; k++)
			X[k] ^= V[j + k];
		xor_salsa8(&X[0], &X[16]);
		xor_salsa8(&X[16], &X[0]);
	}

	for (k = 0; k < 32; k++)
		le32enc(&B[4 * k], X[k]);

	PBKDF2_SHA256((const uint8_t *)input, 80, B, 128, 1, (uint8_t *)output, 32);
}

#if defined(USE_SSE2)
// By default, set to generic scrypt function. This will prevent crash in case when scrypt_detect_sse2() wasn't called
void (*scrypt_1024_1_1_256_sp_detected)(const char *input, char *output, char *scratchpad) = &scrypt_1024_1_1_256_sp_generic;

void scrypt_detect_sse2()
{
#if defined(USE_SSE2_ALWAYS)
    printf("scrypt: using scrypt-sse2 as built.\n");
#else // USE_SSE2_ALWAYS
    // 32bit x86 Linux or Windows, detect cpuid features
    unsigned int cpuid_edx=0;
#if defined(_MSC_VER)
    // MSVC
    int x86cpuid[4];
    __cpuid(x86cpuid, 1);
    cpuid_edx = (unsigned int)buffer[3];
#else // _MSC_VER
    // Linux or i686-w64-mingw32 (gcc-4.6.3)
    unsigned int eax, ebx, ecx;
    __get_cpuid(1, &eax, &ebx, &ecx, &cpuid_edx);
#endif // _MSC_VER

    if (cpuid_edx & 1<<26)
    {
        scrypt_1024_1_1_256_sp_detected = &scrypt_1024_1_1_256_sp_sse2;
        printf("scrypt: using scrypt-sse2 as detected.\n");
    }
    else
    {
        scrypt_1024_1_1_256_sp_detected = &scrypt_1024_1_1_256_sp_generic;
        printf("scrypt: using scrypt-generic, SSE2 unavailable.\n");
    }
#endif // USE_SSE2_ALWAYS
}
#endif

void scrypt_1024_1_1_256(const char *input, char *output)
{
	char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
    scrypt_1024_1_1_256_sp(input, output, scratchpad);
}
<commit_msg>Delete script.cpp<commit_after><|endoftext|>