<commit_before>/******************************************************************************
 * @file     prngcl_ranecu.cl
 * @author   Vadim Demchik <vadimdi@yahoo.com>
 * @version  1.0
 *
 * @brief    [PRNGCL library]
 *           contains implementation, description and initialization procedures of
 *           RANECU pseudo-random number generator
 *
 *
 * @section  CREDITS
 *
 *   F. James,
 *   "A review of pseudorandom number generators",
 *   Computer Physics Communications, 60 (1990), 329--344.
 *
 *   Pierre L'Ecuyer,
 *   "Efficient and Portable Combined Random Number Generators",
 *   Communications of the ACM, 31, 6 (1988), 742--751.
 *
 *
 * @section  LICENSE
 *
 * Copyright (c) 2013, Vadim Demchik
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *
 *    Redistributions in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the documentation
 *      and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *****************************************************************************/

#include "hgpu_prng.h"

#define HGPU_PRNG_RANECU_m      (2147483648.0)                 // 2^31
#define HGPU_PRNG_RANECU_min    1
#define HGPU_PRNG_RANECU_max    2147483647                     // 2^31-1
#define HGPU_PRNG_RANECU_min_FP (1.0)
#define HGPU_PRNG_RANECU_max_FP (2147483647.0/2147483648.0)
#define HGPU_PRNG_RANECU_k      (4.656612873077392578125E-10) // 1/2^31

#define HGPU_PRNG_RANECU_twom31	(2147483648.0)

#define HGPU_PRNG_RANECU_icons1  2147483563
#define HGPU_PRNG_RANECU_icons2  2147483399
#define HGPU_PRNG_RANECU_icons3  2147483562

#define HGPU_PRNG_RANECU_init_1  2147483563
#define HGPU_PRNG_RANECU_init_2  2147483398

#define HGPU_PRNG_RANECU_seedP11 53668
#define HGPU_PRNG_RANECU_seedP12 12211
#define HGPU_PRNG_RANECU_seedP13 40014

#define HGPU_PRNG_RANECU_seedP21 52774
#define HGPU_PRNG_RANECU_seedP22 3791
#define HGPU_PRNG_RANECU_seedP23 40692

    typedef struct {
                 int  jseed1;
                 int  jseed2;
    } HGPU_PRNG_RANECU_state_t;

            static void   HGPU_PRNG_RANECU_initialize(void* PRNG_state, unsigned int PRNG_randseries);
    static unsigned int   HGPU_PRNG_RANECU_produce_one_uint_CPU(void* PRNG_state);
          static double   HGPU_PRNG_RANECU_produce_one_double_CPU(void* PRNG_state);
            static void   HGPU_PRNG_RANECU_init_GPU(HGPU_GPU_context* context,void* PRNG_state,HGPU_PRNG_parameters* PRNG_parameters);
            static void   HGPU_PRNG_RANECU_parameters_set(void* PRNG_state,HGPU_parameter** parameters);

static void
HGPU_PRNG_RANECU_initialize(void* PRNG_state, unsigned int PRNG_randseries){
    HGPU_PRNG_RANECU_state_t* state = (HGPU_PRNG_RANECU_state_t*) PRNG_state;
    HGPU_PRNG_srand(PRNG_randseries);

    state->jseed1 = HGPU_PRNG_rand32bit() % HGPU_PRNG_RANECU_init_1;
    state->jseed2 = HGPU_PRNG_rand32bit() % HGPU_PRNG_RANECU_init_2;
}

static unsigned int
HGPU_PRNG_RANECU_produce_one_uint_CPU(void* PRNG_state){
    HGPU_PRNG_RANECU_state_t* state = (HGPU_PRNG_RANECU_state_t*) PRNG_state;
    int k;
    //
    k = state->jseed1 / HGPU_PRNG_RANECU_seedP11;
        state->jseed1 = HGPU_PRNG_RANECU_seedP13 * (state->jseed1 - k * HGPU_PRNG_RANECU_seedP11) - k * HGPU_PRNG_RANECU_seedP12;
        if (state->jseed1 < 0) state->jseed1 += HGPU_PRNG_RANECU_icons1;

    k = state->jseed2 / HGPU_PRNG_RANECU_seedP21;
        state->jseed2 = HGPU_PRNG_RANECU_seedP23 * (state->jseed2 - k * HGPU_PRNG_RANECU_seedP21) - k * HGPU_PRNG_RANECU_seedP22;
        if (state->jseed2 < 0) state->jseed2 += HGPU_PRNG_RANECU_icons2;

    int z = state->jseed1 - state->jseed2;
    if (z < 1) z += HGPU_PRNG_RANECU_icons3;

	return z;
}

static double
HGPU_PRNG_RANECU_produce_one_double_CPU(void* PRNG_state){
    double y = (double) HGPU_PRNG_RANECU_produce_one_uint_CPU(PRNG_state);
	return (y / HGPU_PRNG_RANECU_twom31);
}

static void
HGPU_PRNG_RANECU_init_GPU(HGPU_GPU_context* context,void* PRNG_state,HGPU_PRNG_parameters* PRNG_parameters){
    HGPU_PRNG_RANECU_state_t* state = (HGPU_PRNG_RANECU_state_t*) PRNG_state;

    size_t seed_table_size         = HGPU_GPU_context_buffer_size_align(context,PRNG_parameters->instances * 2);
    size_t randoms_size            = HGPU_GPU_context_buffer_size_align(context,PRNG_parameters->instances * PRNG_parameters->samples);
    cl_uint4* PRNG_seed_table_uint4= (cl_uint4*)  calloc(seed_table_size,sizeof(cl_uint4));
    cl_float4*  PRNG_randoms        = NULL;
    cl_double4* PRNG_randoms_double = NULL;
    if (PRNG_parameters->precision==HGPU_precision_double)
        PRNG_randoms_double = (cl_double4*) calloc(randoms_size,sizeof(cl_double4));
    else
        PRNG_randoms        = (cl_float4*)  calloc(randoms_size,sizeof(cl_float4));
    if ((!PRNG_seed_table_uint4) || ((!PRNG_randoms_double) && (!PRNG_randoms)))
        HGPU_error_message(HGPU_ERROR_NO_MEMORY,"could not allocate memory for randoms");

    for (unsigned int i=0; i<(seed_table_size>>1); i++) {
        PRNG_seed_table_uint4[i].s[0] = HGPU_PRNG_rand32bit() % HGPU_PRNG_RANECU_init_1;
        PRNG_seed_table_uint4[i].s[1] = HGPU_PRNG_rand32bit() % HGPU_PRNG_RANECU_init_1;
        PRNG_seed_table_uint4[i].s[2] = HGPU_PRNG_rand32bit() % HGPU_PRNG_RANECU_init_1;
        PRNG_seed_table_uint4[i].s[3] = HGPU_PRNG_rand32bit() % HGPU_PRNG_RANECU_init_1;
    }

    for (unsigned int i=(seed_table_size>>1); i<seed_table_size; i++) {
        PRNG_seed_table_uint4[i].s[0] = HGPU_PRNG_rand32bit() % HGPU_PRNG_RANECU_init_2;
        PRNG_seed_table_uint4[i].s[1] = HGPU_PRNG_rand32bit() % HGPU_PRNG_RANECU_init_2;
        PRNG_seed_table_uint4[i].s[2] = HGPU_PRNG_rand32bit() % HGPU_PRNG_RANECU_init_2;
        PRNG_seed_table_uint4[i].s[3] = HGPU_PRNG_rand32bit() % HGPU_PRNG_RANECU_init_2;
    }

    PRNG_seed_table_uint4[0].s[0] = state->jseed1;    // setup first thread as CPU
    PRNG_seed_table_uint4[PRNG_parameters->instances].s[0] = state->jseed2;

    unsigned int seed_table_id = 0;
    unsigned int randoms_id = 0;

    seed_table_id = HGPU_GPU_context_buffer_init(context,PRNG_seed_table_uint4,HGPU_GPU_buffer_type_io,seed_table_size,sizeof(cl_uint4));
    HGPU_GPU_context_buffer_set_name(context,seed_table_id,(char*) "(RANECU) PRNG_seed_table");

    if (PRNG_parameters->precision==HGPU_precision_double)
        randoms_id = HGPU_GPU_context_buffer_init(context,PRNG_randoms_double,HGPU_GPU_buffer_type_io,randoms_size,sizeof(cl_double4));
    else
        randoms_id = HGPU_GPU_context_buffer_init(context,PRNG_randoms,HGPU_GPU_buffer_type_io,randoms_size,sizeof(cl_float4));
    HGPU_GPU_context_buffer_set_name(context,randoms_id,(char*) "(RANECU) PRNG_randoms");

    PRNG_parameters->id_buffer_input_seeds = HGPU_GPU_MAX_BUFFERS;
    PRNG_parameters->id_buffer_seeds       = seed_table_id;
    PRNG_parameters->id_buffer_randoms     = randoms_id;
}

static void
HGPU_PRNG_RANECU_parameters_set(void* PRNG_state,HGPU_parameter** parameters){
    if ((!parameters) || (!PRNG_state)) return;
    HGPU_PRNG_RANECU_state_t* state = (HGPU_PRNG_RANECU_state_t*) PRNG_state;
    HGPU_parameter* parameter = HGPU_parameters_get_by_name(parameters,(char*) HGPU_PARAMETER_PRNG_SEED1);
    if (parameter) (*state).jseed1 = parameter->value_integer;

    parameter = HGPU_parameters_get_by_name(parameters,(char*) HGPU_PARAMETER_PRNG_SEED2);
    if (parameter) (*state).jseed2 = parameter->value_integer;

}

static const HGPU_PRNG_description
HGPU_PRNG_RANECU_description = {
        "RANECU",                                     // name
        31,                                           // bitness
        HGPU_PRNG_output_type_uint,                   // PRNG GPU output type
        HGPU_PRNG_RANECU_min,                         // PRNG_min_uint_value
        HGPU_PRNG_RANECU_max,                         // PRNG_max_uint_value
        HGPU_PRNG_RANECU_min_FP,                      // PRNG_min_double_value
        HGPU_PRNG_RANECU_max_FP,                      // PRNG_max_double_value
        HGPU_PRNG_RANECU_k,                           // PRNG_k_value
        sizeof(HGPU_PRNG_RANECU_state_t),             // size of PRNG state
        &HGPU_PRNG_RANECU_initialize,                 // PRNG initialization
        &HGPU_PRNG_RANECU_parameters_set,             // PRNG additional parameters initialization
        &HGPU_PRNG_RANECU_produce_one_uint_CPU,       // PRNG production one unsigned integer
        &HGPU_PRNG_RANECU_produce_one_double_CPU,     // PRNG production one double
        //
        &HGPU_PRNG_RANECU_init_GPU,                   // PRNG init for GPU procedure
        NULL,                                         // PRNG additional compilation options
        "random/prngcl_ranecu.cl",                    // PRNG source codes
        NULL,                                         // PRNG init kernel
        "ranecu"                                      // PRNG production kernel
};

const HGPU_PRNG_description*  HGPU_PRNG_RANECU = &HGPU_PRNG_RANECU_description;
<commit_msg>Delete prngcl_ranecu.cpp<commit_after><|endoftext|>


<commit_before>/*
	This file is part of the MinSG library.
	Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "WriterMinSG.h"
#include "../SceneDescription.h"
#include <Util/IO/FileName.h>
#include <Util/IO/FileUtils.h>
#include <Util/Macros.h>
#include <algorithm>
#include <memory>
#include <string>

namespace MinSG{
namespace SceneManagement{

using namespace Util;

//! (internal)
static void convertDescriptionToXML(std::ostream & out,const DescriptionMap & d,uint32_t indention/*=0*/){
	const std::string type = d.getString(Consts::TYPE);

	for(uint32_t i=0;i<indention;++i)
		out << "\t";
	out << "<"<<type;

	// insert attributes
	std::vector<std::pair<std::string,std::string>> attributes; // used for sorting by the attributes' key
	for(const auto & mapEntry : d) {
		const std::string key=mapEntry.first.toString();
		if(key.empty() || (key.at(0)=='_' && key.at(key.size()-1)=='_')) // skip description meta keys like  _DATA_, _CHILDREN_, ...
				continue;
		attributes.emplace_back(key,mapEntry.second->toString());
	}
	std::sort(attributes.begin(),attributes.end());
	for(const auto & a : attributes)
		out << " "<<a.first<<"=\""<<StringUtils::replaceAll(a.second,  "\"",""")<<"\"";

	const DescriptionArray * children = dynamic_cast<DescriptionArray *>(d.getValue(Consts::CHILDREN));
	const GenericAttribute * dataBlock = d.getValue(Consts::DATA_BLOCK);
	if( dataBlock || (children && !children->empty()) ) {
		out<<">\n";
		if(children) {
			for(const auto & child : *children) {
				DescriptionMap * m=dynamic_cast<DescriptionMap *>(child.get());
				if(m)
					convertDescriptionToXML(out,*m,indention+1);
			}
		}
		if(dataBlock){
			for(uint32_t i=0;i<indention;++i)
				out << "\t";
			out<<dataBlock->toString()<<"\n";
		}
		for(uint32_t i=0;i<indention;++i)
			out << "\t";
		out << "</"<<type<<">\n";
	}else{
		out << "/>\n";
	}
}

//! (static)
bool WriterMinSG::save(std::ostream & out, const DescriptionMap & sceneDescription) {
	if(!out.good()) {
		WARN("Invalid stream.");
		return false;
	}
	out << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
	convertDescriptionToXML(out, sceneDescription, 0);
	return true;
}

}
}
<commit_msg>WriterMinSG: Support attribute values covering multiple lines.<commit_after>/*
	This file is part of the MinSG library.
	Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "WriterMinSG.h"
#include "../SceneDescription.h"
#include <Util/IO/FileName.h>
#include <Util/IO/FileUtils.h>
#include <Util/Macros.h>
#include <algorithm>
#include <memory>
#include <string>

namespace MinSG{
namespace SceneManagement{

using namespace Util;

//! (internal)
static void convertDescriptionToXML(std::ostream & out,const DescriptionMap & d,uint32_t indention/*=0*/){
	const std::string type = d.getString(Consts::TYPE);

	for(uint32_t i=0;i<indention;++i)
		out << "\t";
	out << "<"<<type;

	// insert attributes
	std::vector<std::pair<std::string,std::string>> attributes; // used for sorting by the attributes' key
	for(const auto & mapEntry : d) {
		const std::string key=mapEntry.first.toString();
		if(key.empty() || (key.at(0)=='_' && key.at(key.size()-1)=='_')) // skip description meta keys like  _DATA_, _CHILDREN_, ...
				continue;
		attributes.emplace_back(key,mapEntry.second->toString());
	}
	std::sort(attributes.begin(),attributes.end());

	static const std::deque<std::pair<const std::string,std::string>> findReplace={
		{	"\"",	"""	},
		{ 	"'", 	"'" 	},
		{	"<",	"<"		},
		{	">",	">"		},
		{	"&",	"&"		},
		{	"\n",	"
"		},
		{	"\t",	"	"		}
	};

	for(const auto & a : attributes)
		out << " "<<a.first<<"=\""<<StringUtils::replaceMultiple(a.second, findReplace,-1)<<"\"";

	const DescriptionArray * children = dynamic_cast<DescriptionArray *>(d.getValue(Consts::CHILDREN));
	const GenericAttribute * dataBlock = d.getValue(Consts::DATA_BLOCK);
	if( dataBlock || (children && !children->empty()) ) {
		out<<">\n";
		if(children) {
			for(const auto & child : *children) {
				DescriptionMap * m=dynamic_cast<DescriptionMap *>(child.get());
				if(m)
					convertDescriptionToXML(out,*m,indention+1);
			}
		}
		if(dataBlock){
			for(uint32_t i=0;i<indention;++i)
				out << "\t";
			out<<dataBlock->toString()<<"\n";
		}
		for(uint32_t i=0;i<indention;++i)
			out << "\t";
		out << "</"<<type<<">\n";
	}else{
		out << "/>\n";
	}
}

//! (static)
bool WriterMinSG::save(std::ostream & out, const DescriptionMap & sceneDescription) {
	if(!out.good()) {
		WARN("Invalid stream.");
		return false;
	}
	out << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
	convertDescriptionToXML(out, sceneDescription, 0);
	return true;
}

}
}
<|endoftext|>


<commit_before>#ifndef JARNGREIPR_CLEMENTI_GO
#define JARNGREIPR_CLEMENTI_GO
#include "Model.hpp"
#include "CarbonAlpha.hpp"
#include <vector>

namespace jarngreipr
{

template<typename traitsT>
class ClementiGo : public Model<traitsT>
{
  public:

    typedef Model<traitsT> base_type;
    typedef typename base_type::real_type            real_type;
    typedef typename base_type::coordinate_type      coordinate_type;
    typedef typename base_type::bead_type            bead_type;
    typedef typename base_type::bead_container_type  bead_container_type;
    typedef typename base_type::chain_type           chain_type;
    typedef typename base_type::chain_container_type chain_container_type;
    typedef std::vector<std::size_t>                 index_list_type;
    typedef std::vector<index_list_type>             exception_list_type;
    template<std::size_t N>
    using interaction_type = typename base_type::interaction_type<N>;

  public:

    ClementiGo() = default;
    ClementiGo(const chain_container_type& chain)
    {
        this->make(chain);
    }
    ~ClementiGo() = default;

    void make(const chain_container_type& chain) override;

    interaction_type<2>&       bond()       {return bond_length_;}
    interaction_type<2> const& bond() const {return bond_length_;}

    interaction_type<2>&       contact()       {return go_contact_;}
    interaction_type<2> const& contact() const {return go_contact_;}

    interaction_type<3>&       angle()       {return bond_angle_;}
    interaction_type<3> const& angle() const {return bond_angle_;}

    interaction_type<4>&       dihedral()       {return dihedral_angle_;}
    interaction_type<4> const& dihedral() const {return dihedral_angle_;}

    exception_list_type &      exception()       {return exception_;}
    exception_list_type const& exception() const {return exception_;}

  private:

    interaction_type<2> bond_length_;
    interaction_type<2> go_contact_;
    interaction_type<3> bond_angle_;
    interaction_type<4> dihedral_angle_;
    exception_list_type exception_; // !< for EXV exception
};

template<typename traitsT>
void ClementiGo<traitsT>::make(const chain_container_type& chain)
{
    ;// TODO
    return;
}

}//jarngreipr
#endif /* JARNGREIPR_CLEMENTI_GO */
<commit_msg>add clementi-go<commit_after>#ifndef JARNGREIPR_CLEMENTI_GO
#define JARNGREIPR_CLEMENTI_GO
#include "Model.hpp"
#include "CarbonAlpha.hpp"
#include <jarngreipr/geometry/distance.hpp>
#include <jarngreipr/geometry/angle.hpp>
#include <jarngreipr/geometry/dihedral.hpp>
#include <iterator>
#include <vector>

namespace jarngreipr
{

template<typename traitsT>
class ClementiGo : public Model<traitsT>
{
  public:

    typedef Model<traitsT> base_type;
    typedef typename base_type::real_type            real_type;
    typedef typename base_type::coordinate_type      coordinate_type;
    typedef typename base_type::bead_type            bead_type;
    typedef typename base_type::bead_container_type  bead_container_type;
    typedef typename base_type::chain_type           chain_type;
    typedef typename base_type::chain_container_type chain_container_type;
    typedef std::vector<std::size_t>                 index_list_type;
    typedef std::vector<index_list_type>             exception_list_type;
    template<std::size_t N>
    using interaction_type = typename base_type::interaction_type<N>;

  public:

    ClementiGo(): contact_threshold_(6.5){}
    explicit ClementiGo(const real_type th): contact_threshold_(th){}
    ~ClementiGo() = default;

    void make(const chain_container_type& chain) override;

    real_type& contact_threshold()       {return contact_threshold_;}
    real_type  contact_threshold() const {return contact_threshold_;}

    interaction_type<2>&       bond()            {return bond_length_;}
    interaction_type<2> const& bond()      const {return bond_length_;}
    interaction_type<2>&       contact()         {return go_contact_;}
    interaction_type<2> const& contact()   const {return go_contact_;}
    interaction_type<3>&       angle()           {return bond_angle_;}
    interaction_type<3> const& angle()     const {return bond_angle_;}
    interaction_type<4>&       dihedral()        {return dihedral_angle_;}
    interaction_type<4> const& dihedral()  const {return dihedral_angle_;}
    exception_list_type &      exception()       {return exception_;}
    exception_list_type const& exception() const {return exception_;}

  private:

    real_type contact_threshold_;

    std::vector<interaction_type<2>> bond_length_;
    std::vector<interaction_type<2>> go_contact_;
    std::vector<interaction_type<3>> bond_angle_;
    std::vector<interaction_type<4>> dihedral_angle_;
    exception_list_type exception_; // !< for EXV exception
};

template<typename traitsT>
void ClementiGo<traitsT>::make(const chain_container_type& chains)
{
    const real_type threshold2 = contact_threshold_ * contact_threshold_;

    for(auto chain = chains.cbegin(); chain != chains.cend(); ++chain)
    {
        const std::size_t cg_begin = this->beads_.size();
        // make cg-beads
        for(auto iter = chain->cbegin(); iter != chain->cend(); ++iter)
            this->beads_.emplace_back(*iter);

        { // ditect go-contact
        std::size_t i = cg_begin;
        exception_.resize(this->beads.size());
        for(auto iter = chain->cbegin(); iter != chain->cend()-3; ++iter)
        {
             std::size_t j = i+3;
             for(auto jter = iter + 3; jter != chain->cend(); ++jter)
             {
                if(min_distance_sq(*iter, *jter) < threshold2)
                {
                    const auto dist = distance(this->beads_.at(i).position(),
                                               this->beads_.at(j).position());
                    this->go_contact_.emplace_back({{i, j}}, dist);
                    this->exception_.at(i).push_back(j);
                    this->exception_.at(j).push_back(i);
                }
                ++j;
             }
             ++i;
        }
        } // go-contact

        {// bond, angle, dihd
        for(std::size_t i=cg_begin; i<beads_.size(); ++i)
        {
            this->exception_.at(i).reserve(8);
            this->exception_.at(i).push_back(i);

            if(i+1 < beads_.size()) // bond
            {
                bond_length_.emplace_back({{i, i+1}}, distance(
                        this->beads_.at(i).position(),
                        this->beads_.at(i+1).position()));
                for(std::size_t j=i; j<=i+1; ++j)
                for(std::size_t k=i; k<=i+1; ++k)
                    if(j != k) this->exception_.at(j).push_back(k);
            }

            if(i+2 < beads_.size()) // angle
            {
                bond_angle_.emplace_back({{i, i+1, i+2}}, angle(
                        this->beads_.at(i).position(),
                        this->beads_.at(i+1).position(),
                        this->beads_.at(i+2).position()));
                for(std::size_t j=i; j<=i+2; ++j)
                for(std::size_t k=i; k<=i+2; ++k)
                    if(j != k) this->exception_.at(j).push_back(k);
            }

            if(i+3 < beads_.size()) // dihd
            {
                dihedral_angle_.emplace_back({{i, i+1, i+2, i+3}},
                        dihedral(this->beads_.at(i  ).position(),
                                 this->beads_.at(i+1).position(),
                                 this->beads_.at(i+2).position(),
                                 this->beads_.at(i+3).position()));
                for(std::size_t j=i; j<=i+3; ++j)
                for(std::size_t k=i; k<=i+3; ++k)
                    if(j != k) this->exception_.at(j).push_back(k);
            }
        }
        }// bond, angle, dihd
    }

    // inter-chain go-contact assuming(num of residue == num of Ca)
    std::size_t i_begin = 0;
    std::size_t j_begin = 0;
    for(auto iter = chains.cbegin(); iter != chains.cend()-1; ++iter)
    {
        j_begin = i_begin + iter->size();
        for(auto jter = iter+1; jter != chains.cend(); ++jter)
        {
            std::size_t i = i_begin;
            std::size_t j = j_begin;
            for(auto lhs = iter->cbegin(); lhs != iter->cend(); ++lhs)
            {// PDBResidue
                for(auto rhs = iter->cbegin(); rhs != iter->cend(); ++rhs)
                {
                    if(min_distance_sq(*lhs, *rhs) < threshold2)
                    {
                        const auto dist = distance(this->beads_.at(i).position(),
                                                   this->beads_.at(j).position());
                        this->go_contact_.emplace_back({{i, j}}, dist);
                        this->exception_.at(i).push_back(j);
                        this->exception_.at(j).push_back(i);
                    }
                    ++j;
                }
                ++i;
            }
            j_begin += jter->size();
        }
        i_begin += iter->size();
    }

    return;
}

}//jarngreipr
#endif /* JARNGREIPR_CLEMENTI_GO */
<|endoftext|>


<commit_before><commit_msg>CFishCloud: Initialize x230_whichModel on construction<commit_after><|endoftext|>


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

/* $Id$ */

//-------------------------------------------------------------------------
//     Event handler for ESD input
//     Author: Andreas Morsch, CERN
//-------------------------------------------------------------------------

#include <TTree.h>
#include <TChain.h>
#include <TFile.h>
#include <TArchiveFile.h>
#include <TObjArray.h>
#include <TSystem.h>
#include <TString.h>
#include <TObjString.h>
#include <TProcessID.h>
#include <TMap.h>

#include "AliESDInputHandler.h"
#include "AliESDEvent.h"
#include "AliESDfriend.h"
#include "AliVCuts.h"
#include "AliESD.h"
#include "AliRunTag.h"
#include "AliEventTag.h"
#include "AliLog.h"

ClassImp(AliESDInputHandler)

static Option_t *gESDDataType = "ESD";

//______________________________________________________________________________
AliESDInputHandler::AliESDInputHandler() :
  AliInputEventHandler(),
  fEvent(0x0),
  fFriend(0x0),
  fAnalysisType(0),
  fNEvents(0),
  fHLTEvent(0x0),
  fHLTTree(0x0),
  fUseHLT(kFALSE),
  fTagCutSumm(0x0),
  fUseTags(kFALSE),
  fChainT(0),
  fTreeT(0),
  fRunTag(0)
{
  // default constructor
}

//______________________________________________________________________________
AliESDInputHandler::~AliESDInputHandler()
{
  //  destructor
  //  delete fEvent;
}

//______________________________________________________________________________
AliESDInputHandler::AliESDInputHandler(const char* name, const char* title):
    AliInputEventHandler(name, title), fEvent(0x0), fFriend(0x0), fAnalysisType(0),
    fNEvents(0),  fHLTEvent(0x0), fHLTTree(0x0), fUseHLT(kFALSE), fTagCutSumm(0x0), fUseTags(kFALSE), fChainT(0), fTreeT(0), fRunTag(0)
{
    // Constructor
}

Bool_t AliESDInputHandler::Init(TTree* tree,  Option_t* opt)
{
    // Initialisation necessary for each new tree
    fAnalysisType = opt;
    fTree         = tree;

    if (!fTree) return kFALSE;
    fTree->GetEntry(0);

    // Get pointer to ESD event
    SwitchOffBranches();
    SwitchOnBranches();

    if (!fEvent) fEvent = new AliESDEvent();
    fEvent->ReadFromTree(fTree);
    fNEvents = fTree->GetEntries();
    if (fTree->GetBranch("ESDfriend.")) {
	fTree->SetBranchAddress("ESDfriend.", &fFriend);
    }

    return kTRUE;
}

Bool_t AliESDInputHandler::BeginEvent(Long64_t entry)
{

    // Copy from old to new format if necessary
  AliESD* old = ((AliESDEvent*) fEvent)->GetAliESDOld();
  if (old) {
	((AliESDEvent*)fEvent)->CopyFromOldESD();
	old->Reset();
  }

  if (fHLTTree) {
      fHLTTree->GetEntry(entry);
  }

  fNewEvent = kTRUE;
  //
  // Event selection
  //
  if (fEventCuts)
    fIsSelected = fEventCuts->IsSelected((AliESDEvent*)fEvent);
  //
  // Friends
  ((AliESDEvent*)fEvent)->SetESDfriend(fFriend);

  return kTRUE;
}

Bool_t  AliESDInputHandler::FinishEvent()
{
    // Finish the event
    if(fEvent)fEvent->Reset();
    return kTRUE;
}

Bool_t AliESDInputHandler::Notify(const char* path)
{
    // Notify a directory change
    AliInfo(Form("Directory change %s \n", path));
    //
    if (fUseHLT) {
	// Get HLTesdTree from current file
	TTree* cTree = fTree;
	if (fTree->GetTree()) cTree = fTree->GetTree();
	TFile* cFile = cTree->GetCurrentFile();
	cFile->GetObject("HLTesdTree", fHLTTree);

	if (fHLTTree) {
	  if (!fHLTEvent) fHLTEvent = new AliESDEvent();
	  fHLTEvent->ReadFromTree(fHLTTree);
	}
    }

    if (!fUseTags) return (kTRUE);

    Bool_t zip = kFALSE;

    TString fileName(path);
    if(fileName.Contains("#AliESDs.root")){
	zip = kTRUE;
    }
    else if (fileName.Contains("AliESDs.root")){
	fileName.ReplaceAll("AliESDs.root", "");
    }
    else if(fileName.Contains("#AliAOD.root")){
	zip = kTRUE;
    }
    else if(fileName.Contains("AliAOD.root")){
	fileName.ReplaceAll("AliAOD.root", "");
    }
    else if(fileName.Contains("#galice.root")){
	// For running with galice and kinematics alone...
	zip = kTRUE;
    }
    else if(fileName.Contains("galice.root")){
	// For running with galice and kinematics alone...
	fileName.ReplaceAll("galice.root", "");
    }

    TString pathName("./");
    if (fileName.Length() != 0) {
	pathName = fileName;
    }

    printf("AliESDInputHandler::Notify() Path: %s\n", pathName.Data());

    if (fRunTag) {
	fRunTag->Clear();
    } else {
	fRunTag = new AliRunTag();
    }

    delete fTreeT; fTreeT = 0;

    if (fChainT) {
	delete fChainT;
	fChainT = 0;
    }

    if (!fChainT) {
	fChainT = new TChain("T");
    }

    const char* tagPattern = "ESD.tag.root";
    const char* name = 0x0;
    TString tagFilename;
    if (zip) {
	TFile* file = fTree->GetCurrentFile();
	TArchiveFile* arch = file->GetArchive();
	TObjArray* arr = arch->GetMembers();
	TIter next(arr);

	while ((file = (TFile*) next())) {
	    name = file->GetName();
	    if (strstr(name,tagPattern)) {
		tagFilename = pathName.Data();
		tagFilename += "#";
		tagFilename += name;
		fChainT->Add(tagFilename);
		AliInfo(Form("Adding %s to tag chain \n", tagFilename.Data()));
	    }//pattern check
	} // archive file loop
    } else {
	void * dirp = gSystem->OpenDirectory(pathName.Data());
	while((name = gSystem->GetDirEntry(dirp))) {
	    if (strstr(name,tagPattern)) {
		tagFilename = pathName.Data();
		tagFilename += "/";
		tagFilename += name;
		fChainT->Add(tagFilename);
		AliInfo(Form("Adding %s to tag chain \n", tagFilename.Data()));
	    }//pattern check
	}//directory loop
    }
    fChainT->SetBranchAddress("AliTAG",&fRunTag);
    fChainT->GetEntry(0);
    return kTRUE;
}

Option_t *AliESDInputHandler::GetDataType() const
{
// Returns handled data type.
   return gESDDataType;
}

Int_t AliESDInputHandler::GetNEventAcceptedInFile()
{
  // Get number of events in file accepted by the tag cuts
  // return -1 if no info is available
  if (!fTagCutSumm) {
    TList *luo = fTree->GetUserInfo();
    if (!luo) {
      AliInfo(Form("No user info in input tree - no tag cut summary\n"));
      return -1;
    }
    for (int iluo=0; iluo<luo->GetEntries(); iluo++) {
      fTagCutSumm = dynamic_cast<TMap *>(luo->At(iluo));
      if (fTagCutSumm) break;
    }
    if (!fTagCutSumm) {
      AliInfo(Form("No tag summary map in input tree\n"));
      return -1;
    }
  }

  TObjString *ostr = 0;
  if (fTagCutSumm->FindObject(fTree->GetCurrentFile()->GetName()))
    ostr = (TObjString *) fTagCutSumm->GetValue(fTree->GetCurrentFile()->GetName());
  else {
    AliInfo(Form("No tag cut summary for file %s\n", fTree->GetCurrentFile()->GetName()));
    return -1;
  }
  char *iTagInfo;
  iTagInfo = strdup(ostr->GetString().Data());

  Int_t iAcc = atoi(strtok(iTagInfo, ","));

  AliInfo(Form("Got %i accepted events for file %s", iAcc,  fTree->GetCurrentFile()->GetName()));

  free(iTagInfo);

  return iAcc;
}
Int_t AliESDInputHandler::GetNEventRejectedInFile()
{
  // Get number of events in file rejected by the tag cuts
  // return -1 if no info is available
  if (!fTagCutSumm) {
    TList *luo = fTree->GetUserInfo();
    if (!luo) {
      AliInfo(Form("No user info in input tree - no tag cut summary\n"));
      return -1;
    }
    for (int iluo=0; iluo<luo->GetEntries(); iluo++) {
      fTagCutSumm = dynamic_cast<TMap *>(luo->At(iluo));
      if (fTagCutSumm) break;
    }
    if (!fTagCutSumm) {
      AliInfo(Form("No tag summary map in input tree\n"));
      return -1;
    }
  }

  TObjString *ostr = 0;
  if (fTagCutSumm->FindObject(fTree->GetCurrentFile()->GetName()))
    ostr = (TObjString *) fTagCutSumm->GetValue(fTree->GetCurrentFile()->GetName());
  else {
    AliInfo(Form("No tag cut summary for file %s\n", fTree->GetCurrentFile()->GetName()));
    return -1;
  }
  char *iTagInfo;
  iTagInfo = strdup(ostr->GetString().Data());

  strtok(iTagInfo, ",");
  Int_t iRej = atoi(strtok(NULL, ","));

  AliInfo(Form("Got %i accepted events for file %s", iRej,  fTree->GetCurrentFile()->GetName()));

  free(iTagInfo);

  return iRej;
}
Bool_t AliESDInputHandler::GetCutSummaryForChain(Int_t *aTotal, Int_t *aAccepted, Int_t *aRejected)
{
  // Get number of events in the full chain
  // Count accepted and rejected events
  // return kFALSE if no info is available
  if (!fTagCutSumm) {
    TList *luo = fTree->GetUserInfo();
    if (!luo) {
      AliInfo(Form("No user info in input tree - no tag cut summary\n"));
      return kFALSE;
    }
    for (int iluo=0; iluo<luo->GetEntries(); iluo++) {
      fTagCutSumm = dynamic_cast<TMap *>(luo->At(iluo));
      if (fTagCutSumm) break;
    }
    if (!fTagCutSumm) {
      AliInfo(Form("No tag summary map in input tree\n"));
      return kFALSE;
    }
  }

  TMapIter *tIter = new TMapIter(fTagCutSumm);

  Int_t iTotList=0, iAccList=0, iRejList=0;

  TObject *cobj;
  while ((cobj = tIter->Next())) {
    TObjString *kstr = (TObjString *) cobj;
    TObjString *vstr = (TObjString *) fTagCutSumm->GetValue(kstr->GetString().Data());
    //    printf("Got object value %s %s\n", kstr->GetString().Data(), vstr->GetString().Data());
    char *iTagInfo;
    iTagInfo = strdup(vstr->GetString().Data());

    Int_t iAcc = atoi(strtok(iTagInfo, ","));
    Int_t iRej = atoi(strtok(NULL, ","));

    iAccList += iAcc;
    iRejList += iRej;
    iTotList += (iAcc+iRej);
  }

  *aTotal = iTotList;
  *aAccepted = iAccList;
  *aRejected = iRejList;

  return kTRUE;
}

Int_t AliESDInputHandler::GetNFilesEmpty()
{
  // Count number of files in which all events were de-selected
  // For such files Notify() will NOT be called
  // return -1 if no info is available
  if (!fTagCutSumm) {
    TList *luo = fTree->GetUserInfo();
    if (!luo) {
      AliInfo(Form("No user info in input tree - no tag cut summary\n"));
      return -1;
    }
    for (int iluo=0; iluo<luo->GetEntries(); iluo++) {
      fTagCutSumm = dynamic_cast<TMap *>(luo->At(iluo));
      if (fTagCutSumm) break;
    }
    if (!fTagCutSumm) {
      AliInfo(Form("No tag summary map in input tree\n"));
      return -1;
    }
  }

  TMapIter *tIter = new TMapIter(fTagCutSumm);

  Int_t iFilesEmpty = 0;

  TObject *cobj;
  while ((cobj = tIter->Next())) {
    TObjString *kstr = (TObjString *) cobj;
    TObjString *vstr = (TObjString *) fTagCutSumm->GetValue(kstr->GetString().Data());
    //    printf("Got object value %s %s\n", kstr->GetString().Data(), vstr->GetString().Data());
    char *iTagInfo;
    iTagInfo = strdup(vstr->GetString().Data());

    Int_t iAcc = atoi(strtok(iTagInfo, ","));
    Int_t iRej = atoi(strtok(NULL, ","));

    if ((iAcc == 0) && ((iRej+iAcc)>0))
      iFilesEmpty++;
  }

  return iFilesEmpty;

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

/* $Id$ */

//-------------------------------------------------------------------------
//     Event handler for ESD input
//     Author: Andreas Morsch, CERN
//-------------------------------------------------------------------------

#include <TTree.h>
#include <TChain.h>
#include <TFile.h>
#include <TArchiveFile.h>
#include <TObjArray.h>
#include <TSystem.h>
#include <TString.h>
#include <TObjString.h>
#include <TProcessID.h>
#include <TMap.h>

#include "AliESDInputHandler.h"
#include "AliESDEvent.h"
#include "AliESDfriend.h"
#include "AliVCuts.h"
#include "AliESD.h"
#include "AliRunTag.h"
#include "AliEventTag.h"
#include "AliLog.h"

ClassImp(AliESDInputHandler)

static Option_t *gESDDataType = "ESD";

//______________________________________________________________________________
AliESDInputHandler::AliESDInputHandler() :
  AliInputEventHandler(),
  fEvent(0x0),
  fFriend(0x0),
  fAnalysisType(0),
  fNEvents(0),
  fHLTEvent(0x0),
  fHLTTree(0x0),
  fUseHLT(kFALSE),
  fTagCutSumm(0x0),
  fUseTags(kFALSE),
  fChainT(0),
  fTreeT(0),
  fRunTag(0)
{
  // default constructor
}

//______________________________________________________________________________
AliESDInputHandler::~AliESDInputHandler()
{
  //  destructor
  //  delete fEvent;
}

//______________________________________________________________________________
AliESDInputHandler::AliESDInputHandler(const char* name, const char* title):
    AliInputEventHandler(name, title), fEvent(0x0), fFriend(0x0), fAnalysisType(0),
    fNEvents(0),  fHLTEvent(0x0), fHLTTree(0x0), fUseHLT(kFALSE), fTagCutSumm(0x0), fUseTags(kFALSE), fChainT(0), fTreeT(0), fRunTag(0)
{
    // Constructor
}

Bool_t AliESDInputHandler::Init(TTree* tree,  Option_t* opt)
{
    // Initialisation necessary for each new tree
    fAnalysisType = opt;
    fTree         = tree;

    if (!fTree) return kFALSE;
    fTree->GetEntry(0);

    // Get pointer to ESD event
    SwitchOffBranches();
    SwitchOnBranches();

    if (!fEvent) fEvent = new AliESDEvent();
    fEvent->ReadFromTree(fTree);
    fNEvents = fTree->GetEntries();
    fFriend = (AliESDfriend*)(fEvent->FindListObject("AliESDfriend"));
    return kTRUE;
}

Bool_t AliESDInputHandler::BeginEvent(Long64_t entry)
{

    // Copy from old to new format if necessary
  AliESD* old = ((AliESDEvent*) fEvent)->GetAliESDOld();
  if (old) {
	((AliESDEvent*)fEvent)->CopyFromOldESD();
	old->Reset();
  }

  if (fHLTTree) {
      fHLTTree->GetEntry(entry);
  }

  fNewEvent = kTRUE;
  //
  // Event selection
  //
  if (fEventCuts)
    fIsSelected = fEventCuts->IsSelected((AliESDEvent*)fEvent);
  //
  // Friends
  ((AliESDEvent*)fEvent)->SetESDfriend(fFriend);

  return kTRUE;
}

Bool_t  AliESDInputHandler::FinishEvent()
{
    // Finish the event
    if(fEvent)fEvent->Reset();
    return kTRUE;
}

Bool_t AliESDInputHandler::Notify(const char* path)
{
    // Notify a directory change
    AliInfo(Form("Directory change %s \n", path));
    //
    if (fUseHLT) {
	// Get HLTesdTree from current file
	TTree* cTree = fTree;
	if (fTree->GetTree()) cTree = fTree->GetTree();
	TFile* cFile = cTree->GetCurrentFile();
	cFile->GetObject("HLTesdTree", fHLTTree);

	if (fHLTTree) {
	  if (!fHLTEvent) fHLTEvent = new AliESDEvent();
	  fHLTEvent->ReadFromTree(fHLTTree);
	}
    }

    if (!fUseTags) return (kTRUE);

    Bool_t zip = kFALSE;

    TString fileName(path);
    if(fileName.Contains("#AliESDs.root")){
	zip = kTRUE;
    }
    else if (fileName.Contains("AliESDs.root")){
	fileName.ReplaceAll("AliESDs.root", "");
    }
    else if(fileName.Contains("#AliAOD.root")){
	zip = kTRUE;
    }
    else if(fileName.Contains("AliAOD.root")){
	fileName.ReplaceAll("AliAOD.root", "");
    }
    else if(fileName.Contains("#galice.root")){
	// For running with galice and kinematics alone...
	zip = kTRUE;
    }
    else if(fileName.Contains("galice.root")){
	// For running with galice and kinematics alone...
	fileName.ReplaceAll("galice.root", "");
    }

    TString pathName("./");
    if (fileName.Length() != 0) {
	pathName = fileName;
    }

    printf("AliESDInputHandler::Notify() Path: %s\n", pathName.Data());

    if (fRunTag) {
	fRunTag->Clear();
    } else {
	fRunTag = new AliRunTag();
    }

    delete fTreeT; fTreeT = 0;

    if (fChainT) {
	delete fChainT;
	fChainT = 0;
    }

    if (!fChainT) {
	fChainT = new TChain("T");
    }

    const char* tagPattern = "ESD.tag.root";
    const char* name = 0x0;
    TString tagFilename;
    if (zip) {
	TFile* file = fTree->GetCurrentFile();
	TArchiveFile* arch = file->GetArchive();
	TObjArray* arr = arch->GetMembers();
	TIter next(arr);

	while ((file = (TFile*) next())) {
	    name = file->GetName();
	    if (strstr(name,tagPattern)) {
		tagFilename = pathName.Data();
		tagFilename += "#";
		tagFilename += name;
		fChainT->Add(tagFilename);
		AliInfo(Form("Adding %s to tag chain \n", tagFilename.Data()));
	    }//pattern check
	} // archive file loop
    } else {
	void * dirp = gSystem->OpenDirectory(pathName.Data());
	while((name = gSystem->GetDirEntry(dirp))) {
	    if (strstr(name,tagPattern)) {
		tagFilename = pathName.Data();
		tagFilename += "/";
		tagFilename += name;
		fChainT->Add(tagFilename);
		AliInfo(Form("Adding %s to tag chain \n", tagFilename.Data()));
	    }//pattern check
	}//directory loop
    }
    fChainT->SetBranchAddress("AliTAG",&fRunTag);
    fChainT->GetEntry(0);
    return kTRUE;
}

Option_t *AliESDInputHandler::GetDataType() const
{
// Returns handled data type.
   return gESDDataType;
}

Int_t AliESDInputHandler::GetNEventAcceptedInFile()
{
  // Get number of events in file accepted by the tag cuts
  // return -1 if no info is available
  if (!fTagCutSumm) {
    TList *luo = fTree->GetUserInfo();
    if (!luo) {
      AliInfo(Form("No user info in input tree - no tag cut summary\n"));
      return -1;
    }
    for (int iluo=0; iluo<luo->GetEntries(); iluo++) {
      fTagCutSumm = dynamic_cast<TMap *>(luo->At(iluo));
      if (fTagCutSumm) break;
    }
    if (!fTagCutSumm) {
      AliInfo(Form("No tag summary map in input tree\n"));
      return -1;
    }
  }

  TObjString *ostr = 0;
  if (fTagCutSumm->FindObject(fTree->GetCurrentFile()->GetName()))
    ostr = (TObjString *) fTagCutSumm->GetValue(fTree->GetCurrentFile()->GetName());
  else {
    AliInfo(Form("No tag cut summary for file %s\n", fTree->GetCurrentFile()->GetName()));
    return -1;
  }
  char *iTagInfo;
  iTagInfo = strdup(ostr->GetString().Data());

  Int_t iAcc = atoi(strtok(iTagInfo, ","));

  AliInfo(Form("Got %i accepted events for file %s", iAcc,  fTree->GetCurrentFile()->GetName()));

  free(iTagInfo);

  return iAcc;
}
Int_t AliESDInputHandler::GetNEventRejectedInFile()
{
  // Get number of events in file rejected by the tag cuts
  // return -1 if no info is available
  if (!fTagCutSumm) {
    TList *luo = fTree->GetUserInfo();
    if (!luo) {
      AliInfo(Form("No user info in input tree - no tag cut summary\n"));
      return -1;
    }
    for (int iluo=0; iluo<luo->GetEntries(); iluo++) {
      fTagCutSumm = dynamic_cast<TMap *>(luo->At(iluo));
      if (fTagCutSumm) break;
    }
    if (!fTagCutSumm) {
      AliInfo(Form("No tag summary map in input tree\n"));
      return -1;
    }
  }

  TObjString *ostr = 0;
  if (fTagCutSumm->FindObject(fTree->GetCurrentFile()->GetName()))
    ostr = (TObjString *) fTagCutSumm->GetValue(fTree->GetCurrentFile()->GetName());
  else {
    AliInfo(Form("No tag cut summary for file %s\n", fTree->GetCurrentFile()->GetName()));
    return -1;
  }
  char *iTagInfo;
  iTagInfo = strdup(ostr->GetString().Data());

  strtok(iTagInfo, ",");
  Int_t iRej = atoi(strtok(NULL, ","));

  AliInfo(Form("Got %i accepted events for file %s", iRej,  fTree->GetCurrentFile()->GetName()));

  free(iTagInfo);

  return iRej;
}
Bool_t AliESDInputHandler::GetCutSummaryForChain(Int_t *aTotal, Int_t *aAccepted, Int_t *aRejected)
{
  // Get number of events in the full chain
  // Count accepted and rejected events
  // return kFALSE if no info is available
  if (!fTagCutSumm) {
    TList *luo = fTree->GetUserInfo();
    if (!luo) {
      AliInfo(Form("No user info in input tree - no tag cut summary\n"));
      return kFALSE;
    }
    for (int iluo=0; iluo<luo->GetEntries(); iluo++) {
      fTagCutSumm = dynamic_cast<TMap *>(luo->At(iluo));
      if (fTagCutSumm) break;
    }
    if (!fTagCutSumm) {
      AliInfo(Form("No tag summary map in input tree\n"));
      return kFALSE;
    }
  }

  TMapIter *tIter = new TMapIter(fTagCutSumm);

  Int_t iTotList=0, iAccList=0, iRejList=0;

  TObject *cobj;
  while ((cobj = tIter->Next())) {
    TObjString *kstr = (TObjString *) cobj;
    TObjString *vstr = (TObjString *) fTagCutSumm->GetValue(kstr->GetString().Data());
    //    printf("Got object value %s %s\n", kstr->GetString().Data(), vstr->GetString().Data());
    char *iTagInfo;
    iTagInfo = strdup(vstr->GetString().Data());

    Int_t iAcc = atoi(strtok(iTagInfo, ","));
    Int_t iRej = atoi(strtok(NULL, ","));

    iAccList += iAcc;
    iRejList += iRej;
    iTotList += (iAcc+iRej);
  }

  *aTotal = iTotList;
  *aAccepted = iAccList;
  *aRejected = iRejList;

  return kTRUE;
}

Int_t AliESDInputHandler::GetNFilesEmpty()
{
  // Count number of files in which all events were de-selected
  // For such files Notify() will NOT be called
  // return -1 if no info is available
  if (!fTagCutSumm) {
    TList *luo = fTree->GetUserInfo();
    if (!luo) {
      AliInfo(Form("No user info in input tree - no tag cut summary\n"));
      return -1;
    }
    for (int iluo=0; iluo<luo->GetEntries(); iluo++) {
      fTagCutSumm = dynamic_cast<TMap *>(luo->At(iluo));
      if (fTagCutSumm) break;
    }
    if (!fTagCutSumm) {
      AliInfo(Form("No tag summary map in input tree\n"));
      return -1;
    }
  }

  TMapIter *tIter = new TMapIter(fTagCutSumm);

  Int_t iFilesEmpty = 0;

  TObject *cobj;
  while ((cobj = tIter->Next())) {
    TObjString *kstr = (TObjString *) cobj;
    TObjString *vstr = (TObjString *) fTagCutSumm->GetValue(kstr->GetString().Data());
    //    printf("Got object value %s %s\n", kstr->GetString().Data(), vstr->GetString().Data());
    char *iTagInfo;
    iTagInfo = strdup(vstr->GetString().Data());

    Int_t iAcc = atoi(strtok(iTagInfo, ","));
    Int_t iRej = atoi(strtok(NULL, ","));

    if ((iAcc == 0) && ((iRej+iAcc)>0))
      iFilesEmpty++;
  }

  return iFilesEmpty;

}
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/

#include "precomp.hpp"

using namespace std;

const int draw_shift_bits = 4;
const int draw_multiplier = 1 << draw_shift_bits;

namespace cv
{

/*
 * Functions to draw keypoints and matches.
 */
static inline void _drawKeypoint( Mat& img, const KeyPoint& p, const Scalar& color, int flags )
{
    CV_Assert( !img.empty() );
    Point center( cvRound(p.pt.x * draw_multiplier), cvRound(p.pt.y * draw_multiplier) );

    if( flags & DrawMatchesFlags::DRAW_RICH_KEYPOINTS )
    {
        int radius = cvRound(p.size/2 * draw_multiplier); // KeyPoint::size is a diameter

        // draw the circles around keypoints with the keypoints size
        circle( img, center, radius, color, 1, CV_AA, draw_shift_bits );

        // draw orientation of the keypoint, if it is applicable
        if( p.angle != -1 )
        {
            float srcAngleRad = p.angle*(float)CV_PI/180.f;
            Point orient( cvRound( cos(srcAngleRad)*radius ),
                          cvRound(-sin(srcAngleRad)*radius ) // "-" to invert orientation of axis y
                        );
            line( img, center, center+orient, color, 1, CV_AA, draw_shift_bits );
        }
#if 0
        else
        {
            // draw center with R=1
            int radius = 1 * draw_multiplier;
            circle( img, center, radius, color, 1, CV_AA, draw_shift_bits );
        }
#endif
    }
    else
    {
        // draw center with R=3
        int radius = 3 * draw_multiplier;
        circle( img, center, radius, color, 1, CV_AA, draw_shift_bits );
    }
}

void drawKeypoints( const Mat& image, const vector<KeyPoint>& keypoints, Mat& outImage,
                    const Scalar& _color, int flags )
{
    if( !(flags & DrawMatchesFlags::DRAW_OVER_OUTIMG) )
    {
        if( image.type() == CV_8UC3 )
        {
            image.copyTo( outImage );
        }
        else if( image.type() == CV_8UC1 )
        {
            cvtColor( image, outImage, CV_GRAY2BGR );
        }
        else
        {
            CV_Error( CV_StsBadArg, "Incorrect type of input image.\n" );
        }
    }

    RNG& rng=theRNG();
    bool isRandColor = _color == Scalar::all(-1);

    CV_Assert( !outImage.empty() );
    vector<KeyPoint>::const_iterator it = keypoints.begin(),
                                     end = keypoints.end();
    for( ; it != end; ++it )
    {
        Scalar color = isRandColor ? Scalar(rng(256), rng(256), rng(256)) : _color;
        _drawKeypoint( outImage, *it, color, flags );
    }
}

static void _prepareImgAndDrawKeypoints( const Mat& img1, const vector<KeyPoint>& keypoints1,
                                         const Mat& img2, const vector<KeyPoint>& keypoints2,
                                         Mat& outImg, Mat& outImg1, Mat& outImg2,
                                         const Scalar& singlePointColor, int flags )
{
    Size size( img1.cols + img2.cols, MAX(img1.rows, img2.rows) );
    if( flags & DrawMatchesFlags::DRAW_OVER_OUTIMG )
    {
        if( size.width > outImg.cols || size.height > outImg.rows )
            CV_Error( CV_StsBadSize, "outImg has size less than need to draw img1 and img2 together" );
        outImg1 = outImg( Rect(0, 0, img1.cols, img1.rows) );
        outImg2 = outImg( Rect(img1.cols, 0, img2.cols, img2.rows) );
    }
    else
    {
        outImg.create( size, CV_MAKETYPE(img1.depth(), 3) );
        outImg = Scalar::all(0);
        outImg1 = outImg( Rect(0, 0, img1.cols, img1.rows) );
        outImg2 = outImg( Rect(img1.cols, 0, img2.cols, img2.rows) );

        if( img1.type() == CV_8U )
            cvtColor( img1, outImg1, CV_GRAY2BGR );
        else
            img1.copyTo( outImg1 );

        if( img2.type() == CV_8U )
            cvtColor( img2, outImg2, CV_GRAY2BGR );
        else
            img2.copyTo( outImg2 );
    }

    // draw keypoints
    if( !(flags & DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS) )
    {
        Mat _outImg1 = outImg( Rect(0, 0, img1.cols, img1.rows) );
        drawKeypoints( _outImg1, keypoints1, _outImg1, singlePointColor, flags + DrawMatchesFlags::DRAW_OVER_OUTIMG );

        Mat _outImg2 = outImg( Rect(img1.cols, 0, img2.cols, img2.rows) );
        drawKeypoints( _outImg2, keypoints2, _outImg2, singlePointColor, flags + DrawMatchesFlags::DRAW_OVER_OUTIMG );
    }
}

static inline void _drawMatch( Mat& outImg, Mat& outImg1, Mat& outImg2 ,
                          const KeyPoint& kp1, const KeyPoint& kp2, const Scalar& matchColor, int flags )
{
    RNG& rng = theRNG();
    bool isRandMatchColor = matchColor == Scalar::all(-1);
    Scalar color = isRandMatchColor ? Scalar( rng(256), rng(256), rng(256) ) : matchColor;

    _drawKeypoint( outImg1, kp1, color, flags );
    _drawKeypoint( outImg2, kp2, color, flags );

    Point2f pt1 = kp1.pt,
            pt2 = kp2.pt,
            dpt2 = Point2f( std::min(pt2.x+outImg1.cols, float(outImg.cols-1)), pt2.y );

    line( outImg,
          Point(cvRound(pt1.x*draw_multiplier), cvRound(pt1.y*draw_multiplier)),
          Point(cvRound(dpt2.x*draw_multiplier), cvRound(dpt2.y*draw_multiplier)),
          color, 1, CV_AA, draw_shift_bits );
}

void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1,
                  const Mat& img2, const vector<KeyPoint>& keypoints2,
                  const vector<DMatch>& matches1to2, Mat& outImg,
                  const Scalar& matchColor, const Scalar& singlePointColor,
                  const vector<char>& matchesMask, int flags )
{
    if( !matchesMask.empty() && matchesMask.size() != matches1to2.size() )
        CV_Error( CV_StsBadSize, "matchesMask must have the same size as matches1to2" );

    Mat outImg1, outImg2;
    _prepareImgAndDrawKeypoints( img1, keypoints1, img2, keypoints2,
                                 outImg, outImg1, outImg2, singlePointColor, flags );

    // draw matches
    for( size_t m = 0; m < matches1to2.size(); m++ )
    {
        int i1 = matches1to2[m].queryIdx;
        int i2 = matches1to2[m].trainIdx;
        if( matchesMask.empty() || matchesMask[m] )
        {
            const KeyPoint &kp1 = keypoints1[i1], &kp2 = keypoints2[i2];
            _drawMatch( outImg, outImg1, outImg2, kp1, kp2, matchColor, flags );
        }
    }
}

void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1,
                  const Mat& img2, const vector<KeyPoint>& keypoints2,
                  const vector<vector<DMatch> >& matches1to2, Mat& outImg,
                  const Scalar& matchColor, const Scalar& singlePointColor,
                  const vector<vector<char> >& matchesMask, int flags )
{
    if( !matchesMask.empty() && matchesMask.size() != matches1to2.size() )
        CV_Error( CV_StsBadSize, "matchesMask must have the same size as matches1to2" );

    Mat outImg1, outImg2;
    _prepareImgAndDrawKeypoints( img1, keypoints1, img2, keypoints2,
                                 outImg, outImg1, outImg2, singlePointColor, flags );

    // draw matches
    for( size_t i = 0; i < matches1to2.size(); i++ )
    {
        for( size_t j = 0; j < matches1to2[i].size(); j++ )
        {
            int i1 = matches1to2[i][j].queryIdx;
            int i2 = matches1to2[i][j].trainIdx;
            if( matchesMask.empty() || matchesMask[i][j] )
            {
                const KeyPoint &kp1 = keypoints1[i1], &kp2 = keypoints2[i2];
                _drawMatch( outImg, outImg1, outImg2, kp1, kp2, matchColor, flags );
            }
        }
    }
}
}
<commit_msg>removed y-axis inversion in drawKeypoints (FeatureDetector has to do this)<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/

#include "precomp.hpp"

using namespace std;

const int draw_shift_bits = 4;
const int draw_multiplier = 1 << draw_shift_bits;

namespace cv
{

/*
 * Functions to draw keypoints and matches.
 */
static inline void _drawKeypoint( Mat& img, const KeyPoint& p, const Scalar& color, int flags )
{
    CV_Assert( !img.empty() );
    Point center( cvRound(p.pt.x * draw_multiplier), cvRound(p.pt.y * draw_multiplier) );

    if( flags & DrawMatchesFlags::DRAW_RICH_KEYPOINTS )
    {
        int radius = cvRound(p.size/2 * draw_multiplier); // KeyPoint::size is a diameter

        // draw the circles around keypoints with the keypoints size
        circle( img, center, radius, color, 1, CV_AA, draw_shift_bits );

        // draw orientation of the keypoint, if it is applicable
        if( p.angle != -1 )
        {
            float srcAngleRad = p.angle*(float)CV_PI/180.f;
            Point orient( cvRound(cos(srcAngleRad)*radius ),
                          cvRound(sin(srcAngleRad)*radius )
                        );
            line( img, center, center+orient, color, 1, CV_AA, draw_shift_bits );
        }
#if 0
        else
        {
            // draw center with R=1
            int radius = 1 * draw_multiplier;
            circle( img, center, radius, color, 1, CV_AA, draw_shift_bits );
        }
#endif
    }
    else
    {
        // draw center with R=3
        int radius = 3 * draw_multiplier;
        circle( img, center, radius, color, 1, CV_AA, draw_shift_bits );
    }
}

void drawKeypoints( const Mat& image, const vector<KeyPoint>& keypoints, Mat& outImage,
                    const Scalar& _color, int flags )
{
    if( !(flags & DrawMatchesFlags::DRAW_OVER_OUTIMG) )
    {
        if( image.type() == CV_8UC3 )
        {
            image.copyTo( outImage );
        }
        else if( image.type() == CV_8UC1 )
        {
            cvtColor( image, outImage, CV_GRAY2BGR );
        }
        else
        {
            CV_Error( CV_StsBadArg, "Incorrect type of input image.\n" );
        }
    }

    RNG& rng=theRNG();
    bool isRandColor = _color == Scalar::all(-1);

    CV_Assert( !outImage.empty() );
    vector<KeyPoint>::const_iterator it = keypoints.begin(),
                                     end = keypoints.end();
    for( ; it != end; ++it )
    {
        Scalar color = isRandColor ? Scalar(rng(256), rng(256), rng(256)) : _color;
        _drawKeypoint( outImage, *it, color, flags );
    }
}

static void _prepareImgAndDrawKeypoints( const Mat& img1, const vector<KeyPoint>& keypoints1,
                                         const Mat& img2, const vector<KeyPoint>& keypoints2,
                                         Mat& outImg, Mat& outImg1, Mat& outImg2,
                                         const Scalar& singlePointColor, int flags )
{
    Size size( img1.cols + img2.cols, MAX(img1.rows, img2.rows) );
    if( flags & DrawMatchesFlags::DRAW_OVER_OUTIMG )
    {
        if( size.width > outImg.cols || size.height > outImg.rows )
            CV_Error( CV_StsBadSize, "outImg has size less than need to draw img1 and img2 together" );
        outImg1 = outImg( Rect(0, 0, img1.cols, img1.rows) );
        outImg2 = outImg( Rect(img1.cols, 0, img2.cols, img2.rows) );
    }
    else
    {
        outImg.create( size, CV_MAKETYPE(img1.depth(), 3) );
        outImg = Scalar::all(0);
        outImg1 = outImg( Rect(0, 0, img1.cols, img1.rows) );
        outImg2 = outImg( Rect(img1.cols, 0, img2.cols, img2.rows) );

        if( img1.type() == CV_8U )
            cvtColor( img1, outImg1, CV_GRAY2BGR );
        else
            img1.copyTo( outImg1 );

        if( img2.type() == CV_8U )
            cvtColor( img2, outImg2, CV_GRAY2BGR );
        else
            img2.copyTo( outImg2 );
    }

    // draw keypoints
    if( !(flags & DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS) )
    {
        Mat _outImg1 = outImg( Rect(0, 0, img1.cols, img1.rows) );
        drawKeypoints( _outImg1, keypoints1, _outImg1, singlePointColor, flags + DrawMatchesFlags::DRAW_OVER_OUTIMG );

        Mat _outImg2 = outImg( Rect(img1.cols, 0, img2.cols, img2.rows) );
        drawKeypoints( _outImg2, keypoints2, _outImg2, singlePointColor, flags + DrawMatchesFlags::DRAW_OVER_OUTIMG );
    }
}

static inline void _drawMatch( Mat& outImg, Mat& outImg1, Mat& outImg2 ,
                          const KeyPoint& kp1, const KeyPoint& kp2, const Scalar& matchColor, int flags )
{
    RNG& rng = theRNG();
    bool isRandMatchColor = matchColor == Scalar::all(-1);
    Scalar color = isRandMatchColor ? Scalar( rng(256), rng(256), rng(256) ) : matchColor;

    _drawKeypoint( outImg1, kp1, color, flags );
    _drawKeypoint( outImg2, kp2, color, flags );

    Point2f pt1 = kp1.pt,
            pt2 = kp2.pt,
            dpt2 = Point2f( std::min(pt2.x+outImg1.cols, float(outImg.cols-1)), pt2.y );

    line( outImg,
          Point(cvRound(pt1.x*draw_multiplier), cvRound(pt1.y*draw_multiplier)),
          Point(cvRound(dpt2.x*draw_multiplier), cvRound(dpt2.y*draw_multiplier)),
          color, 1, CV_AA, draw_shift_bits );
}

void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1,
                  const Mat& img2, const vector<KeyPoint>& keypoints2,
                  const vector<DMatch>& matches1to2, Mat& outImg,
                  const Scalar& matchColor, const Scalar& singlePointColor,
                  const vector<char>& matchesMask, int flags )
{
    if( !matchesMask.empty() && matchesMask.size() != matches1to2.size() )
        CV_Error( CV_StsBadSize, "matchesMask must have the same size as matches1to2" );

    Mat outImg1, outImg2;
    _prepareImgAndDrawKeypoints( img1, keypoints1, img2, keypoints2,
                                 outImg, outImg1, outImg2, singlePointColor, flags );

    // draw matches
    for( size_t m = 0; m < matches1to2.size(); m++ )
    {
        int i1 = matches1to2[m].queryIdx;
        int i2 = matches1to2[m].trainIdx;
        if( matchesMask.empty() || matchesMask[m] )
        {
            const KeyPoint &kp1 = keypoints1[i1], &kp2 = keypoints2[i2];
            _drawMatch( outImg, outImg1, outImg2, kp1, kp2, matchColor, flags );
        }
    }
}

void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1,
                  const Mat& img2, const vector<KeyPoint>& keypoints2,
                  const vector<vector<DMatch> >& matches1to2, Mat& outImg,
                  const Scalar& matchColor, const Scalar& singlePointColor,
                  const vector<vector<char> >& matchesMask, int flags )
{
    if( !matchesMask.empty() && matchesMask.size() != matches1to2.size() )
        CV_Error( CV_StsBadSize, "matchesMask must have the same size as matches1to2" );

    Mat outImg1, outImg2;
    _prepareImgAndDrawKeypoints( img1, keypoints1, img2, keypoints2,
                                 outImg, outImg1, outImg2, singlePointColor, flags );

    // draw matches
    for( size_t i = 0; i < matches1to2.size(); i++ )
    {
        for( size_t j = 0; j < matches1to2[i].size(); j++ )
        {
            int i1 = matches1to2[i][j].queryIdx;
            int i2 = matches1to2[i][j].trainIdx;
            if( matchesMask.empty() || matchesMask[i][j] )
            {
                const KeyPoint &kp1 = keypoints1[i1], &kp2 = keypoints2[i2];
                _drawMatch( outImg, outImg1, outImg2, kp1, kp2, matchColor, flags );
            }
        }
    }
}
}
<|endoftext|>


<commit_before>#include "mbed_events.h"
#include "mbed.h"
#include "rtos.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include <cstdlib>
#include <cmath>

using namespace utest::v1;

// Test delay
#ifndef TEST_EVENTS_TIMING_TIME
#define TEST_EVENTS_TIMING_TIME 20000
#endif

#ifndef TEST_EVENTS_TIMING_MEAN
#define TEST_EVENTS_TIMING_MEAN 25
#endif

#ifndef M_PI
#define M_PI 3.14159265358979323846264338327950288
#endif

// Random number generation to skew timing values
float gauss(float mu, float sigma) {
    float x = (float)rand() / ((float)RAND_MAX+1);
    float y = (float)rand() / ((float)RAND_MAX+1);
    float x2pi = x*2.0*M_PI;
    float g2rad = sqrt(-2.0 * log(1.0-y));
    float z = cos(x2pi) * g2rad;
    return mu + z*sigma;
}

float chisq(float sigma) {
    return pow(gauss(0, sqrt(sigma)), 2);
}

Timer timer;
DigitalOut led(LED1);

equeue_sema_t sema;

// Timer timing test
void timer_timing_test() {
    timer.reset();
    timer.start();
    int prev = timer.read_us();

    while (prev < TEST_EVENTS_TIMING_TIME*1000) {
        int next = timer.read_us();
        if (next < prev) {
            printf("backwards drift %d -> %d (%08x -> %08x)\r\n",
                prev, next, prev, next);
        }
        TEST_ASSERT(next >= prev);
        prev = next;
    }
}

// equeue tick timing test
void tick_timing_test() {
    unsigned start = equeue_tick();
    int prev = 0;

    while (prev < TEST_EVENTS_TIMING_TIME) {
        int next = equeue_tick() - start;
        if (next < prev) {
            printf("backwards drift %d -> %d (%08x -> %08x)\r\n",
                prev, next, prev, next);
        }
        TEST_ASSERT(next >= prev);
        prev = next;
    }
}

// equeue semaphore timing test
void semaphore_timing_test() {
    srand(0);
    timer.reset();
    timer.start();

    int err = equeue_sema_create(&sema);
    TEST_ASSERT_EQUAL(0, err);

    while (timer.read_ms() < TEST_EVENTS_TIMING_TIME) {
        int delay = chisq(TEST_EVENTS_TIMING_MEAN);

        int start = timer.read_us();
        equeue_sema_wait(&sema, delay);
        int taken = timer.read_us() - start;

        printf("delay %dms => error %dus\r\n", delay, abs(1000*delay - taken));
        TEST_ASSERT_INT_WITHIN(5000, taken, delay * 1000);

        led = !led;
    }

    equeue_sema_destroy(&sema);
}

// Test setup
utest::v1::status_t test_setup(const size_t number_of_cases) {
    GREENTEA_SETUP((number_of_cases+1)*TEST_EVENTS_TIMING_TIME, "default_auto");
    return verbose_test_setup_handler(number_of_cases);
}

const Case cases[] = {
    Case("Testing accuracy of timer", timer_timing_test),
    Case("Testing accuracy of equeue tick", tick_timing_test),
    Case("Testing accuracy of equeue semaphore", semaphore_timing_test),
};

Specification specification(test_setup, cases);

int main() {
    return !Harness::run(specification);
}

<commit_msg>Fixed timeout units in events timing test<commit_after>#include "mbed_events.h"
#include "mbed.h"
#include "rtos.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include <cstdlib>
#include <cmath>

using namespace utest::v1;

// Test delay
#ifndef TEST_EVENTS_TIMING_TIME
#define TEST_EVENTS_TIMING_TIME 20000
#endif

#ifndef TEST_EVENTS_TIMING_MEAN
#define TEST_EVENTS_TIMING_MEAN 25
#endif

#ifndef M_PI
#define M_PI 3.14159265358979323846264338327950288
#endif

// Random number generation to skew timing values
float gauss(float mu, float sigma) {
    float x = (float)rand() / ((float)RAND_MAX+1);
    float y = (float)rand() / ((float)RAND_MAX+1);
    float x2pi = x*2.0*M_PI;
    float g2rad = sqrt(-2.0 * log(1.0-y));
    float z = cos(x2pi) * g2rad;
    return mu + z*sigma;
}

float chisq(float sigma) {
    return pow(gauss(0, sqrt(sigma)), 2);
}

Timer timer;
DigitalOut led(LED1);

equeue_sema_t sema;

// Timer timing test
void timer_timing_test() {
    timer.reset();
    timer.start();
    int prev = timer.read_us();

    while (prev < TEST_EVENTS_TIMING_TIME*1000) {
        int next = timer.read_us();
        if (next < prev) {
            printf("backwards drift %d -> %d (%08x -> %08x)\r\n",
                prev, next, prev, next);
        }
        TEST_ASSERT(next >= prev);
        prev = next;
    }
}

// equeue tick timing test
void tick_timing_test() {
    unsigned start = equeue_tick();
    int prev = 0;

    while (prev < TEST_EVENTS_TIMING_TIME) {
        int next = equeue_tick() - start;
        if (next < prev) {
            printf("backwards drift %d -> %d (%08x -> %08x)\r\n",
                prev, next, prev, next);
        }
        TEST_ASSERT(next >= prev);
        prev = next;
    }
}

// equeue semaphore timing test
void semaphore_timing_test() {
    srand(0);
    timer.reset();
    timer.start();

    int err = equeue_sema_create(&sema);
    TEST_ASSERT_EQUAL(0, err);

    while (timer.read_ms() < TEST_EVENTS_TIMING_TIME) {
        int delay = chisq(TEST_EVENTS_TIMING_MEAN);

        int start = timer.read_us();
        equeue_sema_wait(&sema, delay);
        int taken = timer.read_us() - start;

        printf("delay %dms => error %dus\r\n", delay, abs(1000*delay - taken));
        TEST_ASSERT_INT_WITHIN(5000, taken, delay * 1000);

        led = !led;
    }

    equeue_sema_destroy(&sema);
}

// Test setup
utest::v1::status_t test_setup(const size_t number_of_cases) {
    GREENTEA_SETUP((number_of_cases+1)*TEST_EVENTS_TIMING_TIME/1000, "default_auto");
    return verbose_test_setup_handler(number_of_cases);
}

const Case cases[] = {
    Case("Testing accuracy of timer", timer_timing_test),
    Case("Testing accuracy of equeue tick", tick_timing_test),
    Case("Testing accuracy of equeue semaphore", semaphore_timing_test),
};

Specification specification(test_setup, cases);

int main() {
    return !Harness::run(specification);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: editsrc.cxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: sab $ $Date: 2002-03-21 06:32:37 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#include "scitems.hxx"
#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD
#include <svx/unofored.hxx>

#include "editsrc.hxx"
#include "textuno.hxx"
#include "editutil.hxx"
#include "docsh.hxx"
#include "docfunc.hxx"
#include "hints.hxx"
#include "patattr.hxx"
#include "unoguard.hxx"
#ifndef _SC_ACCESSIBLETEXT_HXX
#include "AccessibleText.hxx"
#endif

//------------------------------------------------------------------------

TYPEINIT1( ScHeaderFooterChangedHint, SfxHint );

ScHeaderFooterChangedHint::ScHeaderFooterChangedHint(USHORT nP) :
    nPart( nP )
{
}

ScHeaderFooterChangedHint::~ScHeaderFooterChangedHint()
{
}

//------------------------------------------------------------------------

ScSharedHeaderFooterEditSource::ScSharedHeaderFooterEditSource( ScHeaderFooterTextData* pData ) :
    pTextData( pData )
{
    //  pTextData is held by the ScHeaderFooterTextObj.
    //  Text range and cursor keep a reference to their parent text, so the text object is
    //  always alive and the TextData is valid as long as there are children.
}

ScSharedHeaderFooterEditSource::~ScSharedHeaderFooterEditSource()
{
}

SvxEditSource* ScSharedHeaderFooterEditSource::Clone() const
{
    return new ScSharedHeaderFooterEditSource( pTextData );
}

SvxTextForwarder* ScSharedHeaderFooterEditSource::GetTextForwarder()
{
    return pTextData->GetTextForwarder();
}

void ScSharedHeaderFooterEditSource::UpdateData()
{
    pTextData->UpdateData();
}

ScEditEngineDefaulter* ScSharedHeaderFooterEditSource::GetEditEngine()
{
    return pTextData->GetEditEngine();
}

//------------------------------------------------------------------------

//  each ScHeaderFooterEditSource object has its own ScHeaderFooterTextData

ScHeaderFooterEditSource::ScHeaderFooterEditSource( ScHeaderFooterContentObj* pContent,
                                                    USHORT nP ) :
    ScSharedHeaderFooterEditSource( new ScHeaderFooterTextData( *pContent, nP ) )
{
}

ScHeaderFooterEditSource::ScHeaderFooterEditSource( ScHeaderFooterContentObj& rContent,
                                                    USHORT nP ) :
    ScSharedHeaderFooterEditSource( new ScHeaderFooterTextData( rContent, nP ) )
{
}

ScHeaderFooterEditSource::~ScHeaderFooterEditSource()
{
    delete GetTextData();   // not accessed in ScSharedHeaderFooterEditSource dtor
}

SvxEditSource* ScHeaderFooterEditSource::Clone() const
{
    const ScHeaderFooterTextData* pData = GetTextData();
    return new ScHeaderFooterEditSource( pData->GetContentObj(), pData->GetPart() );
}

//------------------------------------------------------------------------

ScSharedCellEditSource::ScSharedCellEditSource( ScCellTextData* pData ) :
    pCellTextData( pData )
{
    //  pCellTextData is part of the ScCellTextObj.
    //  Text range and cursor keep a reference to their parent text, so the text object is
    //  always alive and the CellTextData is valid as long as there are children.
}

ScSharedCellEditSource::~ScSharedCellEditSource()
{
}

SvxEditSource* ScSharedCellEditSource::Clone() const
{
    return new ScSharedCellEditSource( pCellTextData );
}

SvxTextForwarder* ScSharedCellEditSource::GetTextForwarder()
{
    return pCellTextData->GetTextForwarder();
}

void ScSharedCellEditSource::UpdateData()
{
    pCellTextData->UpdateData();
}

void ScSharedCellEditSource::SetDoUpdateData(sal_Bool bValue)
{
    pCellTextData->SetDoUpdate(bValue);
}

sal_Bool ScSharedCellEditSource::IsDirty() const
{
    return pCellTextData->IsDirty();
}

ScEditEngineDefaulter* ScSharedCellEditSource::GetEditEngine()
{
    return pCellTextData->GetEditEngine();
}

//------------------------------------------------------------------------

//  each ScCellEditSource object has its own ScCellTextData

ScCellEditSource::ScCellEditSource( ScDocShell* pDocSh, const ScAddress& rP ) :
    ScSharedCellEditSource( new ScCellTextData( pDocSh, rP ) )
{
}

ScCellEditSource::~ScCellEditSource()
{
    delete GetCellTextData();   // not accessed in ScSharedCellEditSource dtor
}

SvxEditSource* ScCellEditSource::Clone() const
{
    const ScCellTextData* pData = GetCellTextData();
    return new ScCellEditSource( pData->GetDocShell(), pData->GetCellPos() );
}

//------------------------------------------------------------------------

ScAnnotationEditSource::ScAnnotationEditSource(ScDocShell* pDocSh, const ScAddress& rP) :
    pDocShell( pDocSh ),
    aCellPos( rP ),
    pEditEngine( NULL ),
    pForwarder( NULL ),
    bDataValid( FALSE )
{
    if (pDocShell)
        pDocShell->GetDocument()->AddUnoObject(*this);
}

ScAnnotationEditSource::~ScAnnotationEditSource()
{
    ScUnoGuard aGuard;      //  needed for EditEngine dtor

    if (pDocShell)
        pDocShell->GetDocument()->RemoveUnoObject(*this);

    delete pForwarder;
    delete pEditEngine;
}

SvxEditSource* ScAnnotationEditSource::Clone() const
{
    return new ScAnnotationEditSource( pDocShell, aCellPos );
}

SvxTextForwarder* ScAnnotationEditSource::GetTextForwarder()
{
    if (!pEditEngine)
    {
        // Notizen haben keine Felder
        if ( pDocShell )
            pEditEngine = new ScEditEngineDefaulter(
                pDocShell->GetDocument()->GetEnginePool(), FALSE );
        else
        {
            SfxItemPool* pEnginePool = EditEngine::CreatePool();
            pEnginePool->FreezeIdRanges();
            pEditEngine = new ScEditEngineDefaulter( pEnginePool, TRUE );
        }
        pForwarder = new SvxEditEngineForwarder(*pEditEngine);
    }

    if (bDataValid)
        return pForwarder;

    if ( pDocShell )
    {
        ScPostIt aNote;
        ScDocument* pDoc = pDocShell->GetDocument();
        pDoc->GetNote( aCellPos.Col(), aCellPos.Row(), aCellPos.Tab(), aNote );

        pEditEngine->SetText( aNote.GetText() );        // incl. Umbrueche
    }

    bDataValid = TRUE;
    return pForwarder;
}

void ScAnnotationEditSource::UpdateData()
{
    if ( pDocShell && pEditEngine )
    {
        String aNewText = pEditEngine->GetText( LINEEND_LF );   // im SetNoteText passiert ConvertLineEnd
        ScDocFunc aFunc(*pDocShell);
        aFunc.SetNoteText( aCellPos, aNewText, TRUE );

        // bDataValid wird bei SetDocumentModified zurueckgesetzt
    }
}

void ScAnnotationEditSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    if ( rHint.ISA( ScUpdateRefHint ) )
    {
        const ScUpdateRefHint& rRef = (const ScUpdateRefHint&)rHint;

        //! Ref-Update
    }
    else if ( rHint.ISA( SfxSimpleHint ) )
    {
        ULONG nId = ((const SfxSimpleHint&)rHint).GetId();
        if ( nId == SFX_HINT_DYING )
        {
            pDocShell = NULL;                       // ungueltig geworden

            DELETEZ( pForwarder );
            DELETEZ( pEditEngine );     // EditEngine uses document's pool
        }
        else if ( nId == SFX_HINT_DATACHANGED )
            bDataValid = FALSE;                     // Text muss neu geholt werden
    }
}

//------------------------------------------------------------------------

ScSimpleEditSource::ScSimpleEditSource( SvxTextForwarder* pForw ) :
    pForwarder( pForw )
{
    //  The same forwarder (and EditEngine) is shared by all children of the same Text object.
    //  Text range and cursor keep a reference to their parent text, so the text object is
    //  always alive and the forwarder is valid as long as there are children.
}

ScSimpleEditSource::~ScSimpleEditSource()
{
}

SvxEditSource* ScSimpleEditSource::Clone() const
{
    return new ScSimpleEditSource( pForwarder );
}

SvxTextForwarder* ScSimpleEditSource::GetTextForwarder()
{
    return pForwarder;
}

void ScSimpleEditSource::UpdateData()
{
    //  nothing
}

//------------------------------------------------------------------------

ScAccessibilityEditSource::ScAccessibilityEditSource( ::std::auto_ptr < ScAccessibleTextData > pAccessibleCellTextData )
    : mpAccessibleTextData(pAccessibleCellTextData)
{
}

ScAccessibilityEditSource::~ScAccessibilityEditSource()
{
}

SvxEditSource* ScAccessibilityEditSource::Clone() const
{
    return new ScAccessibilityEditSource(::std::auto_ptr < ScAccessibleTextData > (mpAccessibleTextData->Clone()));
}

SvxTextForwarder* ScAccessibilityEditSource::GetTextForwarder()
{
    return mpAccessibleTextData->GetTextForwarder();
}

SvxViewForwarder* ScAccessibilityEditSource::GetViewForwarder()
{
    return mpAccessibleTextData->GetViewForwarder();
}

SvxEditViewForwarder* ScAccessibilityEditSource::GetEditViewForwarder( sal_Bool bCreate )
{
    return mpAccessibleTextData->GetEditViewForwarder(bCreate);
}

void ScAccessibilityEditSource::UpdateData()
{
    mpAccessibleTextData->UpdateData();
}

SfxBroadcaster& ScAccessibilityEditSource::GetBroadcaster() const
{
    return mpAccessibleTextData->GetBroadcaster();
}

void ScAccessibilityEditSource::SetDoUpdateData(sal_Bool bValue)
{
    mpAccessibleTextData->SetDoUpdate(bValue);
}

sal_Bool ScAccessibilityEditSource::IsDirty() const
{
    return mpAccessibleTextData->IsDirty();
}

<commit_msg>INTEGRATION: CWS dr12 (1.18.280); FILE MERGED 2004/02/24 10:15:48 jmarmion 1.18.280.1: #i21255# text formatting for cell notes<commit_after>/*************************************************************************
 *
 *  $RCSfile: editsrc.cxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: hr $ $Date: 2004-09-08 13:57:23 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#include "scitems.hxx"
#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD
#include <svx/unofored.hxx>

#include "editsrc.hxx"
#include "textuno.hxx"
#include "editutil.hxx"
#include "docsh.hxx"
#include "docfunc.hxx"
#include "hints.hxx"
#include "patattr.hxx"
#include "unoguard.hxx"
#ifndef _SC_ACCESSIBLETEXT_HXX
#include "AccessibleText.hxx"
#endif

//------------------------------------------------------------------------

TYPEINIT1( ScHeaderFooterChangedHint, SfxHint );

ScHeaderFooterChangedHint::ScHeaderFooterChangedHint(USHORT nP) :
    nPart( nP )
{
}

ScHeaderFooterChangedHint::~ScHeaderFooterChangedHint()
{
}

//------------------------------------------------------------------------

ScSharedHeaderFooterEditSource::ScSharedHeaderFooterEditSource( ScHeaderFooterTextData* pData ) :
    pTextData( pData )
{
    //  pTextData is held by the ScHeaderFooterTextObj.
    //  Text range and cursor keep a reference to their parent text, so the text object is
    //  always alive and the TextData is valid as long as there are children.
}

ScSharedHeaderFooterEditSource::~ScSharedHeaderFooterEditSource()
{
}

SvxEditSource* ScSharedHeaderFooterEditSource::Clone() const
{
    return new ScSharedHeaderFooterEditSource( pTextData );
}

SvxTextForwarder* ScSharedHeaderFooterEditSource::GetTextForwarder()
{
    return pTextData->GetTextForwarder();
}

void ScSharedHeaderFooterEditSource::UpdateData()
{
    pTextData->UpdateData();
}

ScEditEngineDefaulter* ScSharedHeaderFooterEditSource::GetEditEngine()
{
    return pTextData->GetEditEngine();
}

//------------------------------------------------------------------------

//  each ScHeaderFooterEditSource object has its own ScHeaderFooterTextData

ScHeaderFooterEditSource::ScHeaderFooterEditSource( ScHeaderFooterContentObj* pContent,
                                                    USHORT nP ) :
    ScSharedHeaderFooterEditSource( new ScHeaderFooterTextData( *pContent, nP ) )
{
}

ScHeaderFooterEditSource::ScHeaderFooterEditSource( ScHeaderFooterContentObj& rContent,
                                                    USHORT nP ) :
    ScSharedHeaderFooterEditSource( new ScHeaderFooterTextData( rContent, nP ) )
{
}

ScHeaderFooterEditSource::~ScHeaderFooterEditSource()
{
    delete GetTextData();   // not accessed in ScSharedHeaderFooterEditSource dtor
}

SvxEditSource* ScHeaderFooterEditSource::Clone() const
{
    const ScHeaderFooterTextData* pData = GetTextData();
    return new ScHeaderFooterEditSource( pData->GetContentObj(), pData->GetPart() );
}

//------------------------------------------------------------------------

ScSharedCellEditSource::ScSharedCellEditSource( ScCellTextData* pData ) :
    pCellTextData( pData )
{
    //  pCellTextData is part of the ScCellTextObj.
    //  Text range and cursor keep a reference to their parent text, so the text object is
    //  always alive and the CellTextData is valid as long as there are children.
}

ScSharedCellEditSource::~ScSharedCellEditSource()
{
}

SvxEditSource* ScSharedCellEditSource::Clone() const
{
    return new ScSharedCellEditSource( pCellTextData );
}

SvxTextForwarder* ScSharedCellEditSource::GetTextForwarder()
{
    return pCellTextData->GetTextForwarder();
}

void ScSharedCellEditSource::UpdateData()
{
    pCellTextData->UpdateData();
}

void ScSharedCellEditSource::SetDoUpdateData(sal_Bool bValue)
{
    pCellTextData->SetDoUpdate(bValue);
}

sal_Bool ScSharedCellEditSource::IsDirty() const
{
    return pCellTextData->IsDirty();
}

ScEditEngineDefaulter* ScSharedCellEditSource::GetEditEngine()
{
    return pCellTextData->GetEditEngine();
}

//------------------------------------------------------------------------

//  each ScCellEditSource object has its own ScCellTextData

ScCellEditSource::ScCellEditSource( ScDocShell* pDocSh, const ScAddress& rP ) :
    ScSharedCellEditSource( new ScCellTextData( pDocSh, rP ) )
{
}

ScCellEditSource::~ScCellEditSource()
{
    delete GetCellTextData();   // not accessed in ScSharedCellEditSource dtor
}

SvxEditSource* ScCellEditSource::Clone() const
{
    const ScCellTextData* pData = GetCellTextData();
    return new ScCellEditSource( pData->GetDocShell(), pData->GetCellPos() );
}

//------------------------------------------------------------------------

ScAnnotationEditSource::ScAnnotationEditSource(ScDocShell* pDocSh, const ScAddress& rP) :
    pDocShell( pDocSh ),
    aCellPos( rP ),
    pEditEngine( NULL ),
    pForwarder( NULL ),
    bDataValid( FALSE )
{
    if (pDocShell)
        pDocShell->GetDocument()->AddUnoObject(*this);
}

ScAnnotationEditSource::~ScAnnotationEditSource()
{
    ScUnoGuard aGuard;      //  needed for EditEngine dtor

    if (pDocShell)
        pDocShell->GetDocument()->RemoveUnoObject(*this);

    delete pForwarder;
    delete pEditEngine;
}

SvxEditSource* ScAnnotationEditSource::Clone() const
{
    return new ScAnnotationEditSource( pDocShell, aCellPos );
}

SvxTextForwarder* ScAnnotationEditSource::GetTextForwarder()
{
    if (!pEditEngine)
    {
        // Notizen haben keine Felder
        if ( pDocShell )
            pEditEngine = new ScEditEngineDefaulter(
                pDocShell->GetDocument()->GetEnginePool(), FALSE );
        else
        {
            SfxItemPool* pEnginePool = EditEngine::CreatePool();
            pEnginePool->FreezeIdRanges();
            pEditEngine = new ScEditEngineDefaulter( pEnginePool, TRUE );
        }
        pForwarder = new SvxEditEngineForwarder(*pEditEngine);
    }

    if (bDataValid)
        return pForwarder;

    if ( pDocShell )
    {
        ScDocument* pDoc = pDocShell->GetDocument();
        ScPostIt aNote(pDoc);
        pDoc->GetNote( aCellPos.Col(), aCellPos.Row(), aCellPos.Tab(), aNote );

        pEditEngine->SetText( aNote.GetText() );        // incl. Umbrueche
    }

    bDataValid = TRUE;
    return pForwarder;
}

void ScAnnotationEditSource::UpdateData()
{
    if ( pDocShell && pEditEngine )
    {
        String aNewText = pEditEngine->GetText( LINEEND_LF );   // im SetNoteText passiert ConvertLineEnd
        ScDocFunc aFunc(*pDocShell);
        aFunc.SetNoteText( aCellPos, aNewText, TRUE );

        // bDataValid wird bei SetDocumentModified zurueckgesetzt
    }
}

void ScAnnotationEditSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    if ( rHint.ISA( ScUpdateRefHint ) )
    {
        const ScUpdateRefHint& rRef = (const ScUpdateRefHint&)rHint;

        //! Ref-Update
    }
    else if ( rHint.ISA( SfxSimpleHint ) )
    {
        ULONG nId = ((const SfxSimpleHint&)rHint).GetId();
        if ( nId == SFX_HINT_DYING )
        {
            pDocShell = NULL;                       // ungueltig geworden

            DELETEZ( pForwarder );
            DELETEZ( pEditEngine );     // EditEngine uses document's pool
        }
        else if ( nId == SFX_HINT_DATACHANGED )
            bDataValid = FALSE;                     // Text muss neu geholt werden
    }
}

//------------------------------------------------------------------------

ScSimpleEditSource::ScSimpleEditSource( SvxTextForwarder* pForw ) :
    pForwarder( pForw )
{
    //  The same forwarder (and EditEngine) is shared by all children of the same Text object.
    //  Text range and cursor keep a reference to their parent text, so the text object is
    //  always alive and the forwarder is valid as long as there are children.
}

ScSimpleEditSource::~ScSimpleEditSource()
{
}

SvxEditSource* ScSimpleEditSource::Clone() const
{
    return new ScSimpleEditSource( pForwarder );
}

SvxTextForwarder* ScSimpleEditSource::GetTextForwarder()
{
    return pForwarder;
}

void ScSimpleEditSource::UpdateData()
{
    //  nothing
}

//------------------------------------------------------------------------

ScAccessibilityEditSource::ScAccessibilityEditSource( ::std::auto_ptr < ScAccessibleTextData > pAccessibleCellTextData )
    : mpAccessibleTextData(pAccessibleCellTextData)
{
}

ScAccessibilityEditSource::~ScAccessibilityEditSource()
{
}

SvxEditSource* ScAccessibilityEditSource::Clone() const
{
    return new ScAccessibilityEditSource(::std::auto_ptr < ScAccessibleTextData > (mpAccessibleTextData->Clone()));
}

SvxTextForwarder* ScAccessibilityEditSource::GetTextForwarder()
{
    return mpAccessibleTextData->GetTextForwarder();
}

SvxViewForwarder* ScAccessibilityEditSource::GetViewForwarder()
{
    return mpAccessibleTextData->GetViewForwarder();
}

SvxEditViewForwarder* ScAccessibilityEditSource::GetEditViewForwarder( sal_Bool bCreate )
{
    return mpAccessibleTextData->GetEditViewForwarder(bCreate);
}

void ScAccessibilityEditSource::UpdateData()
{
    mpAccessibleTextData->UpdateData();
}

SfxBroadcaster& ScAccessibilityEditSource::GetBroadcaster() const
{
    return mpAccessibleTextData->GetBroadcaster();
}

void ScAccessibilityEditSource::SetDoUpdateData(sal_Bool bValue)
{
    mpAccessibleTextData->SetDoUpdate(bValue);
}

sal_Bool ScAccessibilityEditSource::IsDirty() const
{
    return mpAccessibleTextData->IsDirty();
}

<|endoftext|>