<commit_before>/*************************************************************************
 *
 * Copyright 2016 Realm Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 **************************************************************************/

#include "test_all.hpp"

int main(int argc, char* argv[])
{
    return test_all(argc, argv);
}
<commit_msg>Make realm-tests switch to test directory upon start<commit_after>/*************************************************************************
 *
 * Copyright 2016 Realm Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 **************************************************************************/

#include "test_all.hpp"
#ifdef _MSC_VER
#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
#else
#include <unistd.h>
#include <libgen.h>
#endif

int main(int argc, char* argv[])
{
#ifdef _MSC_VER
    char path[MAX_PATH];
    if (GetModuleFileNameA(NULL, path, sizeof(path)) == 0) {
        fprintf(stderr, "Failed to retrieve path to exectuable.\n");
        return 1;
    }
    PathRemoveFileSpecA(path);
    SetCurrentDirectoryA(path);
#else
    char executable[PATH_MAX];
    realpath(argv[0], executable);
    const char* directory = dirname(executable);
    chdir(directory);
#endif

    return test_all(argc, argv);
}
<|endoftext|>


<commit_before>#ifndef VIENNAGRID_METAINFO_HPP
#define VIENNAGRID_METAINFO_HPP

/* =======================================================================
   Copyright (c) 2011-2012, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at
                 Josef Weinbub                    weinbub@iue.tuwien.ac.at

   (A list of additional contributors can be found in the PDF manual)

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

namespace viennagrid
{

    namespace metainfo
    {

        struct random_access_tag {};
        struct associative_access_tag {};

        namespace result_of
        {

            template<typename container_type>
            struct associative_container_value_type
            {
                typedef typename container_type::value_type type;
            };

            template<typename key_type, typename value_type, typename compare, typename allocator>
            struct associative_container_value_type< std::map<key_type, value_type, compare, allocator> >
            {
                typedef value_type type;
            };

            template<typename container_type>
            struct associative_container_access_tag
            {
                typedef random_access_tag type;
            };

            template<typename key_type, typename value_type, typename compare, typename allocator>
            struct associative_container_access_tag< std::map<key_type, value_type, compare, allocator> >
            {
                typedef associative_access_tag type;
            };

        }

        template<typename geometric_container_type, typename element_type>
        typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element, random_access_tag )
        {
            return container[ element.id().get() ];
        }

        template<typename geometric_container_type, typename element_type>
        typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element, associative_access_tag )
        {
            typename geometric_container_type::iterator it = container.find( element.id() );
            return it->second;
        }

        template<typename geometric_container_type, typename element_type>
        typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element )
        {
            return look_up(container, element, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
        }

        template<typename geometric_container_type, typename element_type>
        void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info, random_access_tag )
        {
            if (container.size() >= element.id().get() )
                container.resize( element.id().get()+1 );

            container[ element.id().get() ] = info;
        }

        template<typename geometric_container_type, typename element_type>
        void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info, associative_access_tag )
        {
            container.insert(
                std::make_pair( element.id(), info )
            );
        }

        template<typename geometric_container_type, typename element_type>
        void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info )
        {
            set(container, element, info, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
        }
    }
}

namespace viennagrid
{
    namespace result_of
    {
        template<typename container_collection_type, typename element_type, typename metainfo_type>
        struct info_container;

        template<typename container_typemap, typename element_type, typename metainfo_type>
        struct info_container< viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type >
        {
            typedef typename viennagrid::storage::result_of::container_of< viennagrid::storage::collection_t<container_typemap>, viennameta::static_pair<element_type, metainfo_type> >::type type;
        };
    }

    template< typename element_type, typename metainfo_type, typename container_typemap >
    typename result_of::info_container< viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type>::type & get_info( viennagrid::storage::collection_t<container_typemap> & container_collection )
    {
        return viennagrid::storage::collection::get< viennameta::static_pair<element_type, metainfo_type> >(container_collection);
    }

    template< typename element_type, typename metainfo_type, typename container_typemap >
    const typename result_of::info_container<viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type>::type & get_info( const viennagrid::storage::collection_t<container_typemap> & container_collection )
    {
        return viennagrid::storage::collection::get< viennameta::static_pair<element_type, metainfo_type> >(container_collection);
    }

    template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
    typename metainfo::result_of::associative_container_value_type<
        typename result_of::info_container<
            viennagrid::storage::collection_t<metainfo_container_typemap>,
            element_type,
            metainfo_type
        >::type
    >::type & look_up(
            viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
            const element_type & element
        )
    {
        return metainfo::look_up( get_info<element_type, metainfo_type>(metainfo_collection), element );
    }

    template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
    void set(
            viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
             const element_type & element,
             const typename metainfo::result_of::associative_container_value_type<
                typename result_of::info_container<
                    viennagrid::storage::collection_t<metainfo_container_typemap>,
                    element_type,
                    metainfo_type
                >::type
            >::type & meta_info )
    {
        metainfo::set( get_info<element_type, metainfo_type>(metainfo_collection), element, meta_info );
    }

    namespace metainfo
    {

        template<typename element_type, typename cur_typemap>
        struct for_each_element_helper;

        template<typename element_type, typename cur_element_type, typename cur_metainfo_type, typename container_type, typename tail>
        struct for_each_element_helper<
            element_type,
            viennameta::typelist_t<
                viennameta::static_pair<
                    viennameta::static_pair<
                        cur_element_type,
                        cur_metainfo_type
                    >,
                    container_type
                >,
            tail>
        >
        {
            template<typename metainfo_container_typemap, typename functor_type>
            static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
            {
                for_each_element_helper<element_type, tail>::exec(collection, functor);
            }
        };

        template<typename element_type, typename cur_metainfo_type, typename container_type, typename tail>
        struct for_each_element_helper<
            element_type,
            viennameta::typelist_t<
                viennameta::static_pair<
                    viennameta::static_pair<
                        element_type,
                        cur_metainfo_type
                    >,
                    container_type
                >,
            tail>
        >
        {
            template<typename metainfo_container_typemap, typename functor_type>
            static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
            {
                functor( get_info<element_type, cur_metainfo_type>(collection) );
                //get_info<element_type, cur_metainfo_type>(collection).resize( size );
                for_each_element_helper<element_type, tail>::exec(collection, functor);
            }
        };

        template<typename element_type>
        struct for_each_element_helper<
            element_type,
            viennameta::null_type
        >
        {
            template<typename metainfo_container_typemap, typename functor_type>
            static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
            {}
        };

        class resize_functor
        {
        public:
            resize_functor(std::size_t size_) : size(size_) {}

            template<typename container_type>
            void operator() ( container_type & container )
            {
                container.resize(size);
            }

        private:
            std::size_t size;
        };

        template<typename element_type, typename metainfo_container_typemap>
        void resize_container( storage::collection_t<metainfo_container_typemap> & collection, std::size_t size )
        {
            for_each_element_helper<element_type, metainfo_container_typemap>::exec(collection, resize_functor(size) );
        }

        class increment_size_functor
        {
        public:
            increment_size_functor() {}

            template<typename container_type>
            void operator() ( container_type & container )
            {
                container.resize( container.size()+1 );
            }
        };

        template<typename element_type, typename metainfo_container_typemap>
        void increment_size( storage::collection_t<metainfo_container_typemap> & collection )
        {
            for_each_element_helper<element_type, metainfo_container_typemap>::exec(collection, increment_size_functor() );
        }

    }

    namespace result_of
    {
        template<typename pair_type, typename container_config, typename topologic_domain_config>
        struct metainfo_container;

        template<typename element_type, typename metainfo_type, typename container_config, typename topologic_domain_config>
        struct metainfo_container< viennameta::static_pair<element_type, metainfo_type>, container_config, topologic_domain_config >
        {
            typedef typename viennameta::typemap::result_of::find<container_config, viennameta::static_pair<element_type, metainfo_type> >::type search_result;
            typedef typename viennameta::typemap::result_of::find<container_config, viennagrid::storage::default_tag>::type default_container;

            typedef typename viennameta::_if<
                !viennameta::_equal<search_result, viennameta::not_found>::value,
                search_result,
                default_container
            >::type container_tag_pair;

            //typedef typename viennagrid::storage::result_of::container_from_tag<value_type, typename container_tag_pair::second>::type type;
            typedef typename viennagrid::storage::result_of::container<metainfo_type, typename container_tag_pair::second>::type type;
        };

        template<typename element_list, typename container_config, typename topologic_domain_config>
        struct metainfo_container_typemap;

        template<typename container_config, typename topologic_domain_config>
        struct metainfo_container_typemap<viennameta::null_type, container_config, topologic_domain_config>
        {
            typedef viennameta::null_type type;
        };

        template<typename element_tag, typename metainfo_type, typename tail, typename container_config, typename topologic_domain_config>
        struct metainfo_container_typemap<viennameta::typelist_t< viennameta::static_pair<element_tag, metainfo_type>, tail>, container_config, topologic_domain_config>
        {
            typedef typename viennagrid::result_of::element<topologic_domain_config, element_tag>::type element_type;

            typedef viennameta::typelist_t<
                typename viennameta::static_pair<
                        viennameta::static_pair<element_type, metainfo_type>,
                        typename metainfo_container< viennameta::static_pair<element_type, metainfo_type>, container_config, topologic_domain_config>::type
                    >,
                typename metainfo_container_typemap<tail, container_config, topologic_domain_config>::type
            > type;
        };
    }

}

#endif
<commit_msg>added const version of look_up<commit_after>#ifndef VIENNAGRID_METAINFO_HPP
#define VIENNAGRID_METAINFO_HPP

/* =======================================================================
   Copyright (c) 2011-2012, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at
                 Josef Weinbub                    weinbub@iue.tuwien.ac.at

   (A list of additional contributors can be found in the PDF manual)

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

namespace viennagrid
{

    namespace metainfo
    {

        struct random_access_tag {};
        struct associative_access_tag {};

        namespace result_of
        {

            template<typename container_type>
            struct associative_container_value_type
            {
                typedef typename container_type::value_type type;
            };

            template<typename key_type, typename value_type, typename compare, typename allocator>
            struct associative_container_value_type< std::map<key_type, value_type, compare, allocator> >
            {
                typedef value_type type;
            };

            template<typename container_type>
            struct associative_container_access_tag
            {
                typedef random_access_tag type;
            };

            template<typename key_type, typename value_type, typename compare, typename allocator>
            struct associative_container_access_tag< std::map<key_type, value_type, compare, allocator> >
            {
                typedef associative_access_tag type;
            };

        }

        template<typename geometric_container_type, typename element_type>
        typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element, random_access_tag )
        {
            return container[ element.id().get() ];
        }

        template<typename geometric_container_type, typename element_type>
        typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element, associative_access_tag )
        {
            typename geometric_container_type::iterator it = container.find( element.id() );
            return it->second;
        }

        template<typename geometric_container_type, typename element_type>
        typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element )
        {
            return look_up(container, element, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
        }

        template<typename geometric_container_type, typename element_type>
        const typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( const geometric_container_type & container, const element_type & element, random_access_tag )
        {
            return container[ element.id().get() ];
        }

        template<typename geometric_container_type, typename element_type>
        const typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( const geometric_container_type & container, const element_type & element, associative_access_tag )
        {
            typename geometric_container_type::iterator it = container.find( element.id() );
            return it->second;
        }

        template<typename geometric_container_type, typename element_type>
        const typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( const geometric_container_type & container, const element_type & element )
        {
            return look_up(container, element, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
        }

        template<typename geometric_container_type, typename element_type>
        void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info, random_access_tag )
        {
            if (container.size() >= element.id().get() )
                container.resize( element.id().get()+1 );

            container[ element.id().get() ] = info;
        }

        template<typename geometric_container_type, typename element_type>
        void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info, associative_access_tag )
        {
            container.insert(
                std::make_pair( element.id(), info )
            );
        }

        template<typename geometric_container_type, typename element_type>
        void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info )
        {
            set(container, element, info, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
        }
    }
}

namespace viennagrid
{
    namespace result_of
    {
        template<typename container_collection_type, typename element_type, typename metainfo_type>
        struct info_container;

        template<typename container_typemap, typename element_type, typename metainfo_type>
        struct info_container< viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type >
        {
            typedef typename viennagrid::storage::result_of::container_of< viennagrid::storage::collection_t<container_typemap>, viennameta::static_pair<element_type, metainfo_type> >::type type;
        };
    }

    template< typename element_type, typename metainfo_type, typename container_typemap >
    typename result_of::info_container< viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type>::type & get_info( viennagrid::storage::collection_t<container_typemap> & container_collection )
    {
        return viennagrid::storage::collection::get< viennameta::static_pair<element_type, metainfo_type> >(container_collection);
    }

    template< typename element_type, typename metainfo_type, typename container_typemap >
    const typename result_of::info_container<viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type>::type & get_info( const viennagrid::storage::collection_t<container_typemap> & container_collection )
    {
        return viennagrid::storage::collection::get< viennameta::static_pair<element_type, metainfo_type> >(container_collection);
    }

    template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
    typename metainfo::result_of::associative_container_value_type<
        typename result_of::info_container<
            viennagrid::storage::collection_t<metainfo_container_typemap>,
            element_type,
            metainfo_type
        >::type
    >::type & look_up(
            viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
            const element_type & element
        )
    {
        return metainfo::look_up( get_info<element_type, metainfo_type>(metainfo_collection), element );
    }

    template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
    const typename metainfo::result_of::associative_container_value_type<
        typename result_of::info_container<
            viennagrid::storage::collection_t<metainfo_container_typemap>,
            element_type,
            metainfo_type
        >::type
    >::type & look_up(
            const viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
            const element_type & element
        )
    {
        return metainfo::look_up( get_info<element_type, metainfo_type>(metainfo_collection), element );
    }

    template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
    void set(
            viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
             const element_type & element,
             const typename metainfo::result_of::associative_container_value_type<
                typename result_of::info_container<
                    viennagrid::storage::collection_t<metainfo_container_typemap>,
                    element_type,
                    metainfo_type
                >::type
            >::type & meta_info )
    {
        metainfo::set( get_info<element_type, metainfo_type>(metainfo_collection), element, meta_info );
    }

    namespace metainfo
    {

        template<typename element_type, typename cur_typemap>
        struct for_each_element_helper;

        template<typename element_type, typename cur_element_type, typename cur_metainfo_type, typename container_type, typename tail>
        struct for_each_element_helper<
            element_type,
            viennameta::typelist_t<
                viennameta::static_pair<
                    viennameta::static_pair<
                        cur_element_type,
                        cur_metainfo_type
                    >,
                    container_type
                >,
            tail>
        >
        {
            template<typename metainfo_container_typemap, typename functor_type>
            static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
            {
                for_each_element_helper<element_type, tail>::exec(collection, functor);
            }
        };

        template<typename element_type, typename cur_metainfo_type, typename container_type, typename tail>
        struct for_each_element_helper<
            element_type,
            viennameta::typelist_t<
                viennameta::static_pair<
                    viennameta::static_pair<
                        element_type,
                        cur_metainfo_type
                    >,
                    container_type
                >,
            tail>
        >
        {
            template<typename metainfo_container_typemap, typename functor_type>
            static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
            {
                functor( get_info<element_type, cur_metainfo_type>(collection) );
                //get_info<element_type, cur_metainfo_type>(collection).resize( size );
                for_each_element_helper<element_type, tail>::exec(collection, functor);
            }
        };

        template<typename element_type>
        struct for_each_element_helper<
            element_type,
            viennameta::null_type
        >
        {
            template<typename metainfo_container_typemap, typename functor_type>
            static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
            {}
        };

        class resize_functor
        {
        public:
            resize_functor(std::size_t size_) : size(size_) {}

            template<typename container_type>
            void operator() ( container_type & container )
            {
                container.resize(size);
            }

        private:
            std::size_t size;
        };

        template<typename element_type, typename metainfo_container_typemap>
        void resize_container( storage::collection_t<metainfo_container_typemap> & collection, std::size_t size )
        {
            for_each_element_helper<element_type, metainfo_container_typemap>::exec(collection, resize_functor(size) );
        }

        class increment_size_functor
        {
        public:
            increment_size_functor() {}

            template<typename container_type>
            void operator() ( container_type & container )
            {
                container.resize( container.size()+1 );
            }
        };

        template<typename element_type, typename metainfo_container_typemap>
        void increment_size( storage::collection_t<metainfo_container_typemap> & collection )
        {
            for_each_element_helper<element_type, metainfo_container_typemap>::exec(collection, increment_size_functor() );
        }

    }

    namespace result_of
    {
        template<typename pair_type, typename container_config, typename topologic_domain_config>
        struct metainfo_container;

        template<typename element_type, typename metainfo_type, typename container_config, typename topologic_domain_config>
        struct metainfo_container< viennameta::static_pair<element_type, metainfo_type>, container_config, topologic_domain_config >
        {
            typedef typename viennameta::typemap::result_of::find<container_config, viennameta::static_pair<element_type, metainfo_type> >::type search_result;
            typedef typename viennameta::typemap::result_of::find<container_config, viennagrid::storage::default_tag>::type default_container;

            typedef typename viennameta::_if<
                !viennameta::_equal<search_result, viennameta::not_found>::value,
                search_result,
                default_container
            >::type container_tag_pair;

            //typedef typename viennagrid::storage::result_of::container_from_tag<value_type, typename container_tag_pair::second>::type type;
            typedef typename viennagrid::storage::result_of::container<metainfo_type, typename container_tag_pair::second>::type type;
        };

        template<typename element_list, typename container_config, typename topologic_domain_config>
        struct metainfo_container_typemap;

        template<typename container_config, typename topologic_domain_config>
        struct metainfo_container_typemap<viennameta::null_type, container_config, topologic_domain_config>
        {
            typedef viennameta::null_type type;
        };

        template<typename element_tag, typename metainfo_type, typename tail, typename container_config, typename topologic_domain_config>
        struct metainfo_container_typemap<viennameta::typelist_t< viennameta::static_pair<element_tag, metainfo_type>, tail>, container_config, topologic_domain_config>
        {
            typedef typename viennagrid::result_of::element<topologic_domain_config, element_tag>::type element_type;

            typedef viennameta::typelist_t<
                typename viennameta::static_pair<
                        viennameta::static_pair<element_type, metainfo_type>,
                        typename metainfo_container< viennameta::static_pair<element_type, metainfo_type>, container_config, topologic_domain_config>::type
                    >,
                typename metainfo_container_typemap<tail, container_config, topologic_domain_config>::type
            > type;
        };
    }

}

#endif
<|endoftext|>


<commit_before>/**
 * \file RLSFilter.cpp
 */

#include "RLSFilter.h"

#include <cstdint>
#include <cstring>
#include <stdexcept>

namespace ATK
{
  template<typename DataType_>
  RLSFilter<DataType_>::RLSFilter(int64_t size)
  :Parent(1, 1), global_size(size), P(PType::Identity(size, size)), w(wType::Zero(size, 1)), memory(.99), learning(false)
  {
    input_delay = size;
  }

  template<typename DataType_>
  RLSFilter<DataType_>::~RLSFilter()
  {

  }

  template<typename DataType_>
  void RLSFilter<DataType_>::set_size(int64_t size)
  {
    if(size < 0)
    {
      throw std::out_of_range("Size must be positive");
    }

    P = PType::Identity(size, size) / size;
    w = wType(size, 1);
    input_delay = size+1;
    this->global_size = size;
  }

  template<typename DataType_>
  int64_t RLSFilter<DataType_>::get_size() const
  {
    return global_size;
  }

  template<typename DataType_>
  void RLSFilter<DataType_>::set_memory(DataType_ memory)
  {
    if(memory > 1)
    {
      throw std::out_of_range("Memory must be less than 1");
    }
    if(memory <= 0)
    {
      throw std::out_of_range("Memory must be strictly positive");
    }

    this->memory = memory;
  }

  template<typename DataType_>
  DataType_ RLSFilter<DataType_>::get_memory() const
  {
    return memory;
  }

  template<typename DataType_>
  void RLSFilter<DataType_>::set_learning(bool learning)
  {
    this->learning = learning;
  }

  template<typename DataType_>
  bool RLSFilter<DataType_>::get_learning() const
  {
    return learning;
  }

  template<typename DataType_>
  void RLSFilter<DataType_>::process_impl(int64_t size)
  {
    const DataType* ATK_RESTRICT input = converted_inputs[0];
    DataType* ATK_RESTRICT output = outputs[0];

    for(int64_t i = 0; i < size; ++i)
    {
      xType x(input - global_size + i, global_size, 1);

      // compute next sample
      output[i] = w.transpose() * x.reverse();

      if(learning)
      {
        //update w and P
        learn(x, input[i], output[i]);
      }
    }
  }

  template<typename DataType_>
  void RLSFilter<DataType_>::learn(const xType& x, DataType_ target, DataType_ actual)
  {
    auto alpha = target - actual;
    auto xreverse = x.reverse();

    wType g = (P * xreverse) / (memory + xreverse.transpose() * P * xreverse);
    PType pupdate = (g * (xreverse.transpose() * P));
    P = (P - (pupdate+pupdate.transpose())/2) / memory;
    w = w + alpha * g;
  }

  template<typename DataType_>
  void RLSFilter<DataType_>::set_P(const Eigen::Matrix<DataType_, Eigen::Dynamic, Eigen::Dynamic>& P)
  {
    assert(P.rows() == P.cols());
    assert(P.rows() == size);
    this->P = P;
  }

  template<typename DataType_>
  Eigen::Matrix<DataType_, Eigen::Dynamic, Eigen::Dynamic> RLSFilter<DataType_>::get_P() const
  {
    return P;
  }

  template<typename DataType_>
  void RLSFilter<DataType_>::set_w(const Eigen::Matrix<DataType_, Eigen::Dynamic, 1>& w)
  {
    assert(w.rows() == size);
    this->w = w;
  }

  template<typename DataType_>
  Eigen::Matrix<DataType_, Eigen::Dynamic, 1> RLSFilter<DataType_>::get_w() const
  {
    return w;
  }

  template class RLSFilter<float>;
  template class RLSFilter<double>;
}
<commit_msg>Fixed init to match size reinit<commit_after>/**
 * \file RLSFilter.cpp
 */

#include "RLSFilter.h"

#include <cstdint>
#include <cstring>
#include <stdexcept>

namespace ATK
{
  template<typename DataType_>
  RLSFilter<DataType_>::RLSFilter(int64_t size)
  :Parent(1, 1), global_size(size), P(PType::Identity(size, size)/size), w(wType::Zero(size, 1)), memory(.99), learning(false)
  {
    input_delay = size;
  }

  template<typename DataType_>
  RLSFilter<DataType_>::~RLSFilter()
  {
  }

  template<typename DataType_>
  void RLSFilter<DataType_>::set_size(int64_t size)
  {
    if(size < 0)
    {
      throw std::out_of_range("Size must be positive");
    }

    P = PType::Identity(size, size) / size;
    w = wType(size, 1);
    input_delay = size+1;
    this->global_size = size;
  }

  template<typename DataType_>
  int64_t RLSFilter<DataType_>::get_size() const
  {
    return global_size;
  }

  template<typename DataType_>
  void RLSFilter<DataType_>::set_memory(DataType_ memory)
  {
    if(memory > 1)
    {
      throw std::out_of_range("Memory must be less than 1");
    }
    if(memory <= 0)
    {
      throw std::out_of_range("Memory must be strictly positive");
    }

    this->memory = memory;
  }

  template<typename DataType_>
  DataType_ RLSFilter<DataType_>::get_memory() const
  {
    return memory;
  }

  template<typename DataType_>
  void RLSFilter<DataType_>::set_learning(bool learning)
  {
    this->learning = learning;
  }

  template<typename DataType_>
  bool RLSFilter<DataType_>::get_learning() const
  {
    return learning;
  }

  template<typename DataType_>
  void RLSFilter<DataType_>::process_impl(int64_t size)
  {
    const DataType* ATK_RESTRICT input = converted_inputs[0];
    DataType* ATK_RESTRICT output = outputs[0];

    for(int64_t i = 0; i < size; ++i)
    {
      xType x(input - global_size + i, global_size, 1);

      // compute next sample
      output[i] = w.transpose() * x.reverse();

      if(learning)
      {
        //update w and P
        learn(x, input[i], output[i]);
      }
    }
  }

  template<typename DataType_>
  void RLSFilter<DataType_>::learn(const xType& x, DataType_ target, DataType_ actual)
  {
    auto alpha = target - actual;
    auto xreverse = x.reverse();

    wType g = (P * xreverse) / (memory + xreverse.transpose() * P * xreverse);
    PType pupdate = (g * (xreverse.transpose() * P));
    P = (P - (pupdate+pupdate.transpose())/2) / memory;
    w = w + alpha * g;
  }

  template<typename DataType_>
  void RLSFilter<DataType_>::set_P(const Eigen::Matrix<DataType_, Eigen::Dynamic, Eigen::Dynamic>& P)
  {
    assert(P.rows() == P.cols());
    assert(P.rows() == size);
    this->P = P;
  }

  template<typename DataType_>
  Eigen::Matrix<DataType_, Eigen::Dynamic, Eigen::Dynamic> RLSFilter<DataType_>::get_P() const
  {
    return P;
  }

  template<typename DataType_>
  void RLSFilter<DataType_>::set_w(const Eigen::Matrix<DataType_, Eigen::Dynamic, 1>& w)
  {
    assert(w.rows() == size);
    this->w = w;
  }

  template<typename DataType_>
  Eigen::Matrix<DataType_, Eigen::Dynamic, 1> RLSFilter<DataType_>::get_w() const
  {
    return w;
  }

  template class RLSFilter<float>;
  template class RLSFilter<double>;
}
<|endoftext|>


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

  Program:   Monteverdi
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

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

#include "mvdI18nMainWindow.h"

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QtGui>

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)
#include "otbSystem.h"

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdBackgroundTask.h"
#include "mvdImageImporter.h"
#include "mvdOverviewBuilder.h"
#include "mvdVectorImageModel.h"
#include "mvdAboutDialog.h"
#include "mvdI18nApplication.h"
#include "mvdImportImagesDialog.h"
#include "mvdTaskProgressDialog.h"

namespace mvd
{

/*
  TRANSLATOR mvd::I18nMainWindow

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

namespace
{
} // end of anonymous namespace.

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */
/*****************************************************************************/

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */
/*****************************************************************************/
I18nMainWindow
::I18nMainWindow( QWidget* p, Qt::WindowFlags flags ) :
  QMainWindow( p, flags )
{
}

/*****************************************************************************/
I18nMainWindow
::~I18nMainWindow()
{
}

/*****************************************************************************/
void
I18nMainWindow
::Initialize()
{
  /*
  // Default setup.
  setObjectName( "mvd::I18nMainWindow" );
  setWindowTitle( PROJECT_NAME );
  */

  virtual_SetupUI();

  // Connect Appllication and MainWindow when selected model is about
  // to change.
  QObject::connect(
    I18nApplication::Instance(),
    SIGNAL( AboutToChangeModel( const AbstractModel* ) ),
    this,
    SLOT( OnAboutToChangeModel( const AbstractModel* ) )
  );

  // Connect Application and MainWindow when selected model has been
  // changed.
  QObject::connect(
    I18nApplication::Instance(),
    SIGNAL( ModelChanged( AbstractModel* ) ),
    this,
    SLOT( OnModelChanged( AbstractModel* ) )
  );

  virtual_ConnectUI();

  virtual_InitializeUI();
}

/*****************************************************************************/
QDockWidget*
I18nMainWindow
::AddWidgetToDock( QWidget* widget,
                   const QString& dockName,
                   const QString& dockTitle,
                   Qt::DockWidgetArea dockArea,
                   DockLayoutFlags flags )
{
  // New dock.
  QDockWidget* dockWidget = new QDockWidget( dockTitle, this );

  // You can use findChild( dockName ) to get dock-widget.
  dockWidget->setObjectName( dockName );
  dockWidget->setWidget( widget );

  // Features.
  dockWidget->setFloating( flags.testFlag( DOCK_LAYOUT_FLOATING ) );
  dockWidget->setFeatures(
    QDockWidget::DockWidgetMovable |
    QDockWidget::DockWidgetFloatable |
    QDockWidget::DockWidgetClosable
  );

  // dockWidget->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );

  // dockWidget->adjustSize();

  // Add dock.
  addDockWidget( dockArea, dockWidget );

  //
  return dockWidget;
}

/*****************************************************************************/
VectorImageModel *
I18nMainWindow
::ImportImage( const QString& filename,
               int widthVal,
               int heightVal )
{
  return
    QObjectCast< VectorImageModel * >(
      Import(
        // New dataset-importer worker.
        // It will be auto-deleted by background-task.
        new ImageImporter(
          filename,
          widthVal, heightVal
        )
      ),
      "QObject is not a VectorImageModel."
    );
}

/*****************************************************************************/
bool
I18nMainWindow
::BuildGDALOverviews( const QStringList & filenames )
{
  ImportImagesDialog * importDialog = new ImportImagesDialog( filenames, this );

  if( importDialog->GetEffectiveCount()<1 )
    return true;

  int result = importDialog->exec();

  if( result== QDialog::Rejected )
    return false;

  if( result==QDialog::Accepted )
    {
    // AbstractWorker will be automatically deleted by BackgroundTask in
    // ::Import().
    OverviewBuilder * builder =
      new OverviewBuilder(
	importDialog->GetGDALOverviewsBuilders()
      );

    delete importDialog;
    importDialog = NULL;

    Import( builder );
    }

  return true;
}

/*****************************************************************************/
QObject *
I18nMainWindow
::Import( AbstractWorker * importer )
{
  assert( importer );

  //
  // Background task.

  // New background-task running worker.
  // Will be self auto-deleted when worker has finished.
  BackgroundTask* task = new BackgroundTask( importer, false, this );

  //
  // Progress dialog.
  TaskProgressDialog progress(
    task,
    this,
    Qt::CustomizeWindowHint | Qt::WindowTitleHint
  );

  progress.setWindowModality( Qt::WindowModal );
  progress.setAutoReset( false );
  progress.setAutoClose( false );
  progress.setCancelButton( NULL );
  progress.setMinimumDuration( 0 );

  //
  // Result.
  int button = progress.Exec();

  // MANTIS-921 (synchronize deletion of BackgroungTask).
  task->wait();
  delete task;
  task = NULL;

  // MANTIS-921 (then, process result).
  if( button!=QDialog::Accepted )
    {
    assert( progress.GetObject()==NULL );

    return NULL;
    }

  // qDebug() << "object:" << progress.GetObject< DatasetModel >();

  // assert( progress.GetObject()!=NULL );

  return progress.GetObject();
}

/*****************************************************************************/
void
I18nMainWindow
::closeEvent( QCloseEvent * e )
{
  QMainWindow::closeEvent( e );
}

/*****************************************************************************/
void
I18nMainWindow
::virtual_InitializeUI()
{
  // Change to NULL model to force emitting GUI signals when GUI is
  // instantiated. So, GUI will be initialized and controller-widgets
  // disabled.
  I18nApplication::Instance()->SetModel( NULL );
}

/*****************************************************************************/
void
I18nMainWindow
::SaveLayout( int version ) const
{
  // qDebug() << this << "::SaveLayout()";

  assert( I18nCoreApplication::Instance()!=NULL );

  QString name( objectName() );

  I18nCoreApplication::Instance()
    ->StoreSettingsKey( name + "Geometry", saveGeometry() );

  I18nCoreApplication::Instance()
    ->StoreSettingsKey( name + "State", saveState( version ) );
}

/*****************************************************************************/
bool
I18nMainWindow
::RestoreLayout( int version )
{
  // qDebug() << this << "::RestoreLayout()";

  I18nCoreApplication * application = I18nCoreApplication::Instance();
  assert( application!=NULL );

  QString name( objectName() );
  assert( !name.isEmpty() );

  if( !restoreGeometry(
	application->RetrieveSettingsKey( name + "Geometry" ).toByteArray() ) )
    return false;

  return
    restoreState(
      application->RetrieveSettingsKey( name + "State" ).toByteArray(),
      version
    );
}

/*****************************************************************************/
/* SLOTS                                                                     */
/*****************************************************************************/
void
I18nMainWindow
::on_action_Quit_triggered()
{
  close();
}

/*****************************************************************************/
void
I18nMainWindow
::on_action_About_triggered()
{
  AboutDialog aboutDialog( this );

  aboutDialog.exec();
}

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

} // end namespace 'mvd'
<commit_msg>BUG: Mantis-1338: ImportImageDialog was not deleted<commit_after>/*=========================================================================

  Program:   Monteverdi
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

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

#include "mvdI18nMainWindow.h"

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QtGui>

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)
#include "otbSystem.h"

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdBackgroundTask.h"
#include "mvdImageImporter.h"
#include "mvdOverviewBuilder.h"
#include "mvdVectorImageModel.h"
#include "mvdAboutDialog.h"
#include "mvdI18nApplication.h"
#include "mvdImportImagesDialog.h"
#include "mvdTaskProgressDialog.h"

namespace mvd
{

/*
  TRANSLATOR mvd::I18nMainWindow

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

namespace
{
} // end of anonymous namespace.

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */
/*****************************************************************************/

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */
/*****************************************************************************/
I18nMainWindow
::I18nMainWindow( QWidget* p, Qt::WindowFlags flags ) :
  QMainWindow( p, flags )
{
}

/*****************************************************************************/
I18nMainWindow
::~I18nMainWindow()
{
}

/*****************************************************************************/
void
I18nMainWindow
::Initialize()
{
  /*
  // Default setup.
  setObjectName( "mvd::I18nMainWindow" );
  setWindowTitle( PROJECT_NAME );
  */

  virtual_SetupUI();

  // Connect Appllication and MainWindow when selected model is about
  // to change.
  QObject::connect(
    I18nApplication::Instance(),
    SIGNAL( AboutToChangeModel( const AbstractModel* ) ),
    this,
    SLOT( OnAboutToChangeModel( const AbstractModel* ) )
  );

  // Connect Application and MainWindow when selected model has been
  // changed.
  QObject::connect(
    I18nApplication::Instance(),
    SIGNAL( ModelChanged( AbstractModel* ) ),
    this,
    SLOT( OnModelChanged( AbstractModel* ) )
  );

  virtual_ConnectUI();

  virtual_InitializeUI();
}

/*****************************************************************************/
QDockWidget*
I18nMainWindow
::AddWidgetToDock( QWidget* widget,
                   const QString& dockName,
                   const QString& dockTitle,
                   Qt::DockWidgetArea dockArea,
                   DockLayoutFlags flags )
{
  // New dock.
  QDockWidget* dockWidget = new QDockWidget( dockTitle, this );

  // You can use findChild( dockName ) to get dock-widget.
  dockWidget->setObjectName( dockName );
  dockWidget->setWidget( widget );

  // Features.
  dockWidget->setFloating( flags.testFlag( DOCK_LAYOUT_FLOATING ) );
  dockWidget->setFeatures(
    QDockWidget::DockWidgetMovable |
    QDockWidget::DockWidgetFloatable |
    QDockWidget::DockWidgetClosable
  );

  // dockWidget->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );

  // dockWidget->adjustSize();

  // Add dock.
  addDockWidget( dockArea, dockWidget );

  //
  return dockWidget;
}

/*****************************************************************************/
VectorImageModel *
I18nMainWindow
::ImportImage( const QString& filename,
               int widthVal,
               int heightVal )
{
  return
    QObjectCast< VectorImageModel * >(
      Import(
        // New dataset-importer worker.
        // It will be auto-deleted by background-task.
        new ImageImporter(
          filename,
          widthVal, heightVal
        )
      ),
      "QObject is not a VectorImageModel."
    );
}

/*****************************************************************************/
bool
I18nMainWindow
::BuildGDALOverviews( const QStringList & filenames )
{
  ImportImagesDialog * importDialog = new ImportImagesDialog( filenames, this );
  // The import dialog should be deleted before leaving this function

  if( importDialog->GetEffectiveCount()<1 )
    {
    delete importDialog;
    importDialog = NULL;
    return true;
    }

  int result = importDialog->exec();

  if( result== QDialog::Rejected )
    {
    delete importDialog;
    importDialog = NULL;
    return false;
    }

  if( result==QDialog::Accepted )
    {
    // AbstractWorker will be automatically deleted by BackgroundTask in
    // ::Import().
    OverviewBuilder * builder =
      new OverviewBuilder(
	importDialog->GetGDALOverviewsBuilders()
      );

    delete importDialog;
    importDialog = NULL;

    Import( builder );
    }

  if (importDialog)
    {
    delete importDialog;
    importDialog = NULL;
    }
  return true;
}

/*****************************************************************************/
QObject *
I18nMainWindow
::Import( AbstractWorker * importer )
{
  assert( importer );

  //
  // Background task.

  // New background-task running worker.
  // Will be self auto-deleted when worker has finished.
  BackgroundTask* task = new BackgroundTask( importer, false, this );

  //
  // Progress dialog.
  TaskProgressDialog progress(
    task,
    this,
    Qt::CustomizeWindowHint | Qt::WindowTitleHint
  );

  progress.setWindowModality( Qt::WindowModal );
  progress.setAutoReset( false );
  progress.setAutoClose( false );
  progress.setCancelButton( NULL );
  progress.setMinimumDuration( 0 );

  //
  // Result.
  int button = progress.Exec();

  // MANTIS-921 (synchronize deletion of BackgroungTask).
  task->wait();
  delete task;
  task = NULL;

  // MANTIS-921 (then, process result).
  if( button!=QDialog::Accepted )
    {
    assert( progress.GetObject()==NULL );

    return NULL;
    }

  // qDebug() << "object:" << progress.GetObject< DatasetModel >();

  // assert( progress.GetObject()!=NULL );

  return progress.GetObject();
}

/*****************************************************************************/
void
I18nMainWindow
::closeEvent( QCloseEvent * e )
{
  QMainWindow::closeEvent( e );
}

/*****************************************************************************/
void
I18nMainWindow
::virtual_InitializeUI()
{
  // Change to NULL model to force emitting GUI signals when GUI is
  // instantiated. So, GUI will be initialized and controller-widgets
  // disabled.
  I18nApplication::Instance()->SetModel( NULL );
}

/*****************************************************************************/
void
I18nMainWindow
::SaveLayout( int version ) const
{
  // qDebug() << this << "::SaveLayout()";

  assert( I18nCoreApplication::Instance()!=NULL );

  QString name( objectName() );

  I18nCoreApplication::Instance()
    ->StoreSettingsKey( name + "Geometry", saveGeometry() );

  I18nCoreApplication::Instance()
    ->StoreSettingsKey( name + "State", saveState( version ) );
}

/*****************************************************************************/
bool
I18nMainWindow
::RestoreLayout( int version )
{
  // qDebug() << this << "::RestoreLayout()";

  I18nCoreApplication * application = I18nCoreApplication::Instance();
  assert( application!=NULL );

  QString name( objectName() );
  assert( !name.isEmpty() );

  if( !restoreGeometry(
	application->RetrieveSettingsKey( name + "Geometry" ).toByteArray() ) )
    return false;

  return
    restoreState(
      application->RetrieveSettingsKey( name + "State" ).toByteArray(),
      version
    );
}

/*****************************************************************************/
/* SLOTS                                                                     */
/*****************************************************************************/
void
I18nMainWindow
::on_action_Quit_triggered()
{
  close();
}

/*****************************************************************************/
void
I18nMainWindow
::on_action_About_triggered()
{
  AboutDialog aboutDialog( this );

  aboutDialog.exec();
}

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

} // end namespace 'mvd'
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/utils/stopreg/p9_stop_data_struct.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file   p9_stop_data_struct.H
/// @brief  describes data structures internal to STOP API.
///
// *HWP HW Owner    :  Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner    :  Prem Shanker Jha <premjha2@in.ibm.com>
// *HWP Team        :  PM
// *HWP Level       :  2
// *HWP Consumed by :  HB:HYP
#ifndef __STOP_DATA_STRUCT_
#define __STOP_DATA_STRUCT_

#ifndef  _AIX
    #include <endian.h>
#endif

#include "p9_hcd_memmap_base.H"

#ifdef __FAPI_2_
    #include <fapi2.H>
#endif

#ifdef __cplusplus
extern "C" {
namespace stopImageSection
{
#endif

enum
{
    MAX_SPR_RESTORE_INST = 0x08,
    SIZE_PER_SPR_RESTORE_INST = ((4 * sizeof(uint8_t)) / sizeof(uint32_t)),
};

typedef struct
{
    uint32_t scomEntryHeader;
    uint32_t scomEntryAddress;
    uint64_t scomEntryData;
} ScomEntry_t;

/**
 * @brief models a CPU register restoration area in STOP section of homer image.
 */
typedef struct
{
    uint8_t threadArea[CORE_RESTORE_THREAD_AREA_SIZE];
    uint8_t coreArea[CORE_RESTORE_CORE_AREA_SIZE];
} SprRestoreArea_t;

/**
 * @brief   models homer image of a chip.
 * @note    sections not relevant for CPU register restoration have been
 * abstracted using field 'reserve'.
 */
typedef struct
{
    uint8_t occ_host_sgpe_area[ TWO_MB ];  // CPU restore area starts at an offset of 2MB from chip HOMER
    uint8_t interrruptHandler[SELF_RESTORE_INT_SIZE];
    uint8_t threadLauncher[THREAD_LAUNCHER_SIZE];
    SprRestoreArea_t coreThreadRestore[MAX_CORES_PER_CHIP][MAX_THREADS_PER_CORE];
    uint8_t reserve[(ONE_KB * ONE_KB) - SELF_RESTORE_SIZE_TOTAL];
} HomerSection_t;

/**
 * @brief models cache subsection in STOP section of a given homer image.
 * @note    given the start of cache subsection associated with a given core,
 *          the structure below represents what a cache subsection would look
 *          like. Based on known start address, quick traversing can be done
 *          within the cache subsection.
 */
typedef struct
{
    ScomEntry_t  nonCacheArea[MAX_EQ_SCOM_ENTRIES];
    ScomEntry_t  l2CacheArea[MAX_L2_SCOM_ENTRIES];
    ScomEntry_t  l3CacheArea[MAX_L3_SCOM_ENTRIES];
} StopCacheSection_t;

/**
 * @brief summarizes attributes associated with a SPR register.
 */
typedef struct
{
    uint32_t sprId;
    bool isThreadScope;
} StopSprReg_t;

enum
{
    SIZE_SCOM_ENTRY = sizeof( ScomEntry_t ),
    SCOM_ENTRY_START = 0xDEADDEAD,
};

#ifdef __FAPI_2_
    #define MY_ERR( _fmt_, _args_...)  FAPI_ERR(_fmt_, ##_args_)
    #define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)
#else
    #define MY_ERR( _fmt_, _args_...)
    #define MY_INF(_fmt_, _args_...)
#endif

#define CORE_ID_SCOM_START(io_image,\
                           i_chipletId) \
((ScomEntry_t*)(((uint8_t*)(io_image)) + CORE_SCOM_RESTORE_HOMER_OFFSET +\
                ((i_chipletId - CORE_CHIPLET_ID_MIN) * \
                 CORE_SCOM_RESTORE_SIZE_PER_CORE)));

#define CACHE_SECTN_START(io_image,\
                          i_chipletId) \
((StopCacheSection_t *)(((uint8_t *)(io_image)) + QUAD_SCOM_RESTORE_HOMER_OFFSET +\
                        ((i_chipletId - CACHE_CHIPLET_ID_MIN) * \
                         QUAD_SCOM_RESTORE_SIZE_PER_QUAD)));
#ifdef __cplusplus
}  // extern "C"

} //namespace stopImageSection ends
#endif //__cplusplus

#endif
<commit_msg>Fixes required to build P9 STOP API with skiboot<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/utils/stopreg/p9_stop_data_struct.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file   p9_stop_data_struct.H
/// @brief  describes data structures internal to STOP API.
///
// *HWP HW Owner    :  Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner    :  Prem Shanker Jha <premjha2@in.ibm.com>
// *HWP Team        :  PM
// *HWP Level       :  2
// *HWP Consumed by :  HB:HYP
#ifndef __STOP_DATA_STRUCT_
#define __STOP_DATA_STRUCT_

#ifndef  _AIX
    #include <endian.h>
#endif

#include "p9_hcd_memmap_base.H"

#ifdef __SKIBOOT__
    #include <skiboot.h>
#endif

#ifdef __FAPI_2_
    #include <fapi2.H>
#endif

#ifdef __cplusplus
extern "C" {
namespace stopImageSection
{
#endif

enum
{
    MAX_SPR_RESTORE_INST = 0x08,
    SIZE_PER_SPR_RESTORE_INST = ((4 * sizeof(uint8_t)) / sizeof(uint32_t)),
};

typedef struct
{
    uint32_t scomEntryHeader;
    uint32_t scomEntryAddress;
    uint64_t scomEntryData;
} ScomEntry_t;

/**
 * @brief models a CPU register restoration area in STOP section of homer image.
 */
typedef struct
{
    uint8_t threadArea[CORE_RESTORE_THREAD_AREA_SIZE];
    uint8_t coreArea[CORE_RESTORE_CORE_AREA_SIZE];
} SprRestoreArea_t;

/**
 * @brief   models homer image of a chip.
 * @note    sections not relevant for CPU register restoration have been
 * abstracted using field 'reserve'.
 */
typedef struct
{
    uint8_t occ_host_sgpe_area[ TWO_MB ];  // CPU restore area starts at an offset of 2MB from chip HOMER
    uint8_t interrruptHandler[SELF_RESTORE_INT_SIZE];
    uint8_t threadLauncher[THREAD_LAUNCHER_SIZE];
    SprRestoreArea_t coreThreadRestore[MAX_CORES_PER_CHIP][MAX_THREADS_PER_CORE];
    uint8_t reserve[(ONE_KB * ONE_KB) - SELF_RESTORE_SIZE_TOTAL];
} HomerSection_t;

/**
 * @brief models cache subsection in STOP section of a given homer image.
 * @note    given the start of cache subsection associated with a given core,
 *          the structure below represents what a cache subsection would look
 *          like. Based on known start address, quick traversing can be done
 *          within the cache subsection.
 */
typedef struct
{
    ScomEntry_t  nonCacheArea[MAX_EQ_SCOM_ENTRIES];
    ScomEntry_t  l2CacheArea[MAX_L2_SCOM_ENTRIES];
    ScomEntry_t  l3CacheArea[MAX_L3_SCOM_ENTRIES];
} StopCacheSection_t;

/**
 * @brief summarizes attributes associated with a SPR register.
 */
typedef struct
{
    uint32_t sprId;
    bool isThreadScope;
} StopSprReg_t;

enum
{
    SIZE_SCOM_ENTRY = sizeof( ScomEntry_t ),
    SCOM_ENTRY_START = 0xDEADDEAD,
};

#ifdef __FAPI_2_
    #define MY_ERR( _fmt_, _args_...)  FAPI_ERR(_fmt_, ##_args_)
    #define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)
#else
    #define MY_ERR( _fmt_, _args_...)
    #define MY_INF(_fmt_, _args_...)
#endif

#define CORE_ID_SCOM_START(io_image,\
                           i_chipletId) \
((ScomEntry_t*)(((uint8_t*)(io_image)) + CORE_SCOM_RESTORE_HOMER_OFFSET +\
                ((i_chipletId - CORE_CHIPLET_ID_MIN) * \
                 CORE_SCOM_RESTORE_SIZE_PER_CORE)));

#define CACHE_SECTN_START(io_image,\
                          i_chipletId) \
((StopCacheSection_t *)(((uint8_t *)(io_image)) + QUAD_SCOM_RESTORE_HOMER_OFFSET +\
                        ((i_chipletId - CACHE_CHIPLET_ID_MIN) * \
                         QUAD_SCOM_RESTORE_SIZE_PER_QUAD)));
#ifdef __cplusplus
}  // extern "C"

} //namespace stopImageSection ends
#endif //__cplusplus

#endif
<|endoftext|>


<commit_before>#include "ksp_plugin/journal.hpp"

#include <fstream>
#include <list>
#include <string>
#include <type_traits>

#include "base/array.hpp"
#include "base/get_line.hpp"
#include "base/hexadecimal.hpp"
#include "base/map_util.hpp"
#include "glog/logging.h"

namespace principia {
namespace ksp_plugin {

using base::Bytes;
using base::FindOrDie;
using base::GetLine;
using base::HexadecimalDecode;
using base::HexadecimalEncode;
using base::UniqueBytes;

namespace {

int const kBufferSize = 100;

template<typename T,
         typename = typename std::enable_if<std::is_pointer<T>::value>::type>
T Find(PointerMap const& pointer_map, std::uint64_t const address) {
    return reinterpret_cast<T>(FindOrDie(pointer_map, address));
}

template<typename T>
void Insert(not_null<PointerMap*> const pointer_map,
            std::uint64_t const address,
            T* const pointer) {
  auto inserted = pointer_map->emplace(address, pointer);
  CHECK(inserted.second) << address;
}

template<typename T>
std::uint64_t SerializePointer(T* t) {
  return reinterpret_cast<std::uint64_t>(t);
}

serialization::XYZ SerializeXYZ(XYZ const& xyz) {
  serialization::XYZ m;
  m.set_x(xyz.x);
  m.set_y(xyz.y);
  m.set_z(xyz.z);
  return m;
}

serialization::QP SerializeQP(QP const& qp) {
  serialization::QP m;
  *m.mutable_p() = SerializeXYZ(qp.p);
  *m.mutable_q() = SerializeXYZ(qp.q);
  return m;
}

}  // namespace

void SetBufferedLogging::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_max_severity(in.max_severity);
}

void SetBufferedLogging::Run(Message const& message,
                             not_null<PointerMap*> const pointer_map) {
  principia__SetBufferedLogging(message.in().max_severity());
}

void GetBufferedLogging::Fill(Return const& result,
                              not_null<Message*> const message) {
  message->mutable_return_()->set_max_severity(result);
}

void GetBufferedLogging::Run(Message const& message,
                             not_null<PointerMap*> const pointer_map) {
  CHECK_EQ(message.return_().max_severity(), principia__GetBufferedLogging());
}

void SetBufferDuration::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_seconds(in.seconds);
}

void SetBufferDuration::Run(Message const& message,
                            not_null<PointerMap*> const pointer_map) {
  principia__SetBufferDuration(message.in().seconds());
}

void GetBufferDuration::Fill(Return const& result,
                             not_null<Message*> const message) {
  message->mutable_return_()->set_seconds(result);
}

void GetBufferDuration::Run(Message const& message,
                            not_null<PointerMap*> const pointer_map) {
  CHECK_EQ(message.return_().seconds(), principia__GetBufferDuration());
}

void SetSuppressedLogging::Fill(In const& in,
                                not_null<Message*> const message) {
  message->mutable_in()->set_min_severity(in.min_severity);
}

void SetSuppressedLogging::Run(Message const& message,
                               not_null<PointerMap*> const pointer_map) {
  principia__SetSuppressedLogging(message.in().min_severity());
}

void GetSuppressedLogging::Fill(Return const& result,
                                not_null<Message*> const message) {
  message->mutable_return_()->set_min_severity(result);
}

void GetSuppressedLogging::Run(Message const& message,
                               not_null<PointerMap*> const pointer_map) {
  CHECK_EQ(message.return_().min_severity(), principia__GetSuppressedLogging());
}

void SetVerboseLogging::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_level(in.level);
}

void SetVerboseLogging::Run(Message const& message,
                            not_null<PointerMap*> const pointer_map) {
  principia__SetVerboseLogging(message.in().level());
}

void GetVerboseLogging::Fill(Return const& result,
                             not_null<Message*> const message) {
  message->mutable_return_()->set_level(result);
}

void GetVerboseLogging::Run(Message const& message,
                            not_null<PointerMap*> const pointer_map) {
  CHECK_EQ(message.return_().level(), principia__GetVerboseLogging());
}

void SetStderrLogging::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_min_severity(in.min_severity);
}

void SetStderrLogging::Run(Message const& message,
                           not_null<PointerMap*> const pointer_map) {
  principia__SetStderrLogging(message.in().min_severity());
}

void GetStderrLogging::Fill(Return const& result,
                            not_null<Message*> const message) {
  message->mutable_return_()->set_min_severity(result);
}

void GetStderrLogging::Run(Message const& message,
                           not_null<PointerMap*> const pointer_map) {
  CHECK_EQ(message.return_().min_severity(), principia__GetStderrLogging());
}

void LogInfo::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_message(in.message);
}

void LogInfo::Run(Message const& message,
                  not_null<PointerMap*> const pointer_map) {
  principia__LogInfo(message.in().message().c_str());
}

void LogWarning::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_message(in.message);
}

void LogWarning::Run(Message const& message,
                     not_null<PointerMap*> const pointer_map) {
  principia__LogWarning(message.in().message().c_str());
}

void LogError::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_message(in.message);
}

void LogError::Run(Message const& message,
                   not_null<PointerMap*> const pointer_map) {
  principia__LogError(message.in().message().c_str());
}

void LogFatal::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_message(in.message);
}

void LogFatal::Run(Message const& message,
                   not_null<PointerMap*> const pointer_map) {
  principia__LogFatal(message.in().message().c_str());
}

void NewPlugin::Fill(In const& in, not_null<Message*> const message) {
  auto* mutable_in = message->mutable_in();
  mutable_in->set_initial_time(in.initial_time);
  mutable_in->set_planetarium_rotation_in_degrees(
      in.planetarium_rotation_in_degrees);
}

void NewPlugin::Fill(Return const& result, not_null<Message*> const message) {
  message->mutable_return_()->set_plugin(SerializePointer(result));
}

void NewPlugin::Run(Message const& message,
                    not_null<PointerMap*> const pointer_map) {
  auto* plugin = principia__NewPlugin(
                     message.in().initial_time(),
                     message.in().planetarium_rotation_in_degrees());
  Insert(pointer_map, message.return_().plugin(), plugin);
}

void DeletePlugin::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_plugin(SerializePointer(in.plugin));
}

void DeletePlugin::Fill(Out const& out, not_null<Message*> const message) {
  message->mutable_out()->set_plugin(SerializePointer(*out.plugin));
}

void DeletePlugin::Run(Message const& message,
                       not_null<PointerMap*> const pointer_map) {
  auto* plugin = Find<Plugin const*>(*pointer_map, message.in().plugin());
  principia__DeletePlugin(&plugin);
  // TODO(phl): should we do something with out() here?
}

void DirectlyInsertCelestial::Fill(In const& in,
                                   not_null<Message*> const message) {
  Message::In* m = message->mutable_in();
  m->set_plugin(SerializePointer(in.plugin));
  m->set_celestial_index(in.celestial_index);
  if (in.parent_index != nullptr) {
    m->set_parent_index(*in.parent_index);
  }
  m->set_gravitational_parameter(in.gravitational_parameter);
  if (in.axis_right_ascension != nullptr) {
    m->set_axis_right_ascension(in.axis_right_ascension);
  }
  if (in.axis_declination != nullptr) {
    m->set_axis_declination(in.axis_declination);
  }
  if (in.j2 != nullptr) {
    m->set_j2(in.j2);
  }
  if (in.reference_radius != nullptr) {
    m->set_reference_radius(in.reference_radius);
  }
  m->set_x(in.x);
  m->set_y(in.y);
  m->set_z(in.z);
  m->set_vx(in.vx);
  m->set_vy(in.vy);
  m->set_vz(in.vz);
}

void InsertCelestial::Fill(In const& in, not_null<Message*> const message) {
  Message::In* m = message->mutable_in();
  m->set_plugin(SerializePointer(in.plugin));
  m->set_celestial_index(in.celestial_index);
  m->set_gravitational_parameter(in.gravitational_parameter);
  m->set_parent_index(in.parent_index);
  *m->mutable_from_parent() = SerializeQP(in.from_parent);
}

Journal::Journal(std::experimental::filesystem::path const& path)
    : stream_(path, std::ios::out) {}

Journal::~Journal() {
  stream_.close();
}

void Journal::Write(serialization::Method const& method) {
  UniqueBytes bytes(method.ByteSize());
  method.SerializeToArray(bytes.data.get(), static_cast<int>(bytes.size));

  std::int64_t const hexadecimal_size = (bytes.size << 1) + 2;
  UniqueBytes hexadecimal(hexadecimal_size);
  HexadecimalEncode({bytes.data.get(), bytes.size}, hexadecimal.get());
  hexadecimal.data.get()[hexadecimal_size - 2] = '\n';
  hexadecimal.data.get()[hexadecimal_size - 1] = '\0';
  stream_ << hexadecimal.data.get();
  stream_.flush();
}

void Journal::Activate(base::not_null<Journal*> const journal) {
  CHECK(active_ == nullptr);
  active_ = journal;
}

void Journal::Deactivate() {
  CHECK(active_ != nullptr);
  delete active_;
  active_ = nullptr;
}

Player::Player(std::experimental::filesystem::path const& path)
    : stream_(path, std::ios::in) {}

bool Player::Play() {
  std::unique_ptr<serialization::Method> method = Read();
  if (method == nullptr) {
    return false;
  }

  bool ran = false;
  ran |= RunIfAppropriate<DeletePlugin>(*method);
  ran |= RunIfAppropriate<NewPlugin>(*method);
  CHECK(ran);

  return true;
}

std::unique_ptr<serialization::Method> Player::Read() {
  std::string const line = GetLine(&stream_);
  if (line.empty()) {
    return nullptr;
  }

  uint8_t const* const hexadecimal =
      reinterpret_cast<uint8_t const*>(line.c_str());
  int const hexadecimal_size = strlen(line.c_str());
  UniqueBytes bytes(hexadecimal_size >> 1);
  HexadecimalDecode({hexadecimal, hexadecimal_size},
                    {bytes.data.get(), bytes.size});
  auto method = std::make_unique<serialization::Method>();
  CHECK(method->ParseFromArray(bytes.data.get(),
                               static_cast<int>(bytes.size)));

  return method;
}

Journal* Journal::active_ = nullptr;

}  // namespace ksp_plugin
}  // namespace principia
<commit_msg>Empty definitions.<commit_after>#include "ksp_plugin/journal.hpp"

#include <fstream>
#include <list>
#include <string>
#include <type_traits>

#include "base/array.hpp"
#include "base/get_line.hpp"
#include "base/hexadecimal.hpp"
#include "base/map_util.hpp"
#include "glog/logging.h"

namespace principia {
namespace ksp_plugin {

using base::Bytes;
using base::FindOrDie;
using base::GetLine;
using base::HexadecimalDecode;
using base::HexadecimalEncode;
using base::UniqueBytes;

namespace {

int const kBufferSize = 100;

template<typename T,
         typename = typename std::enable_if<std::is_pointer<T>::value>::type>
T Find(PointerMap const& pointer_map, std::uint64_t const address) {
    return reinterpret_cast<T>(FindOrDie(pointer_map, address));
}

template<typename T>
void Insert(not_null<PointerMap*> const pointer_map,
            std::uint64_t const address,
            T* const pointer) {
  auto inserted = pointer_map->emplace(address, pointer);
  CHECK(inserted.second) << address;
}

template<typename T>
std::uint64_t SerializePointer(T* t) {
  return reinterpret_cast<std::uint64_t>(t);
}

serialization::XYZ SerializeXYZ(XYZ const& xyz) {
  serialization::XYZ m;
  m.set_x(xyz.x);
  m.set_y(xyz.y);
  m.set_z(xyz.z);
  return m;
}

serialization::QP SerializeQP(QP const& qp) {
  serialization::QP m;
  *m.mutable_p() = SerializeXYZ(qp.p);
  *m.mutable_q() = SerializeXYZ(qp.q);
  return m;
}

}  // namespace

void SetBufferedLogging::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_max_severity(in.max_severity);
}

void SetBufferedLogging::Run(Message const& message,
                             not_null<PointerMap*> const pointer_map) {
  principia__SetBufferedLogging(message.in().max_severity());
}

void GetBufferedLogging::Fill(Return const& result,
                              not_null<Message*> const message) {
  message->mutable_return_()->set_max_severity(result);
}

void GetBufferedLogging::Run(Message const& message,
                             not_null<PointerMap*> const pointer_map) {
  CHECK_EQ(message.return_().max_severity(), principia__GetBufferedLogging());
}

void SetBufferDuration::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_seconds(in.seconds);
}

void SetBufferDuration::Run(Message const& message,
                            not_null<PointerMap*> const pointer_map) {
  principia__SetBufferDuration(message.in().seconds());
}

void GetBufferDuration::Fill(Return const& result,
                             not_null<Message*> const message) {
  message->mutable_return_()->set_seconds(result);
}

void GetBufferDuration::Run(Message const& message,
                            not_null<PointerMap*> const pointer_map) {
  CHECK_EQ(message.return_().seconds(), principia__GetBufferDuration());
}

void SetSuppressedLogging::Fill(In const& in,
                                not_null<Message*> const message) {
  message->mutable_in()->set_min_severity(in.min_severity);
}

void SetSuppressedLogging::Run(Message const& message,
                               not_null<PointerMap*> const pointer_map) {
  principia__SetSuppressedLogging(message.in().min_severity());
}

void GetSuppressedLogging::Fill(Return const& result,
                                not_null<Message*> const message) {
  message->mutable_return_()->set_min_severity(result);
}

void GetSuppressedLogging::Run(Message const& message,
                               not_null<PointerMap*> const pointer_map) {
  CHECK_EQ(message.return_().min_severity(), principia__GetSuppressedLogging());
}

void SetVerboseLogging::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_level(in.level);
}

void SetVerboseLogging::Run(Message const& message,
                            not_null<PointerMap*> const pointer_map) {
  principia__SetVerboseLogging(message.in().level());
}

void GetVerboseLogging::Fill(Return const& result,
                             not_null<Message*> const message) {
  message->mutable_return_()->set_level(result);
}

void GetVerboseLogging::Run(Message const& message,
                            not_null<PointerMap*> const pointer_map) {
  CHECK_EQ(message.return_().level(), principia__GetVerboseLogging());
}

void SetStderrLogging::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_min_severity(in.min_severity);
}

void SetStderrLogging::Run(Message const& message,
                           not_null<PointerMap*> const pointer_map) {
  principia__SetStderrLogging(message.in().min_severity());
}

void GetStderrLogging::Fill(Return const& result,
                            not_null<Message*> const message) {
  message->mutable_return_()->set_min_severity(result);
}

void GetStderrLogging::Run(Message const& message,
                           not_null<PointerMap*> const pointer_map) {
  CHECK_EQ(message.return_().min_severity(), principia__GetStderrLogging());
}

void LogInfo::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_message(in.message);
}

void LogInfo::Run(Message const& message,
                  not_null<PointerMap*> const pointer_map) {
  principia__LogInfo(message.in().message().c_str());
}

void LogWarning::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_message(in.message);
}

void LogWarning::Run(Message const& message,
                     not_null<PointerMap*> const pointer_map) {
  principia__LogWarning(message.in().message().c_str());
}

void LogError::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_message(in.message);
}

void LogError::Run(Message const& message,
                   not_null<PointerMap*> const pointer_map) {
  principia__LogError(message.in().message().c_str());
}

void LogFatal::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_message(in.message);
}

void LogFatal::Run(Message const& message,
                   not_null<PointerMap*> const pointer_map) {
  principia__LogFatal(message.in().message().c_str());
}

void NewPlugin::Fill(In const& in, not_null<Message*> const message) {
  auto* mutable_in = message->mutable_in();
  mutable_in->set_initial_time(in.initial_time);
  mutable_in->set_planetarium_rotation_in_degrees(
      in.planetarium_rotation_in_degrees);
}

void NewPlugin::Fill(Return const& result, not_null<Message*> const message) {
  message->mutable_return_()->set_plugin(SerializePointer(result));
}

void NewPlugin::Run(Message const& message,
                    not_null<PointerMap*> const pointer_map) {
  auto* plugin = principia__NewPlugin(
                     message.in().initial_time(),
                     message.in().planetarium_rotation_in_degrees());
  Insert(pointer_map, message.return_().plugin(), plugin);
}

void DeletePlugin::Fill(In const& in, not_null<Message*> const message) {
  message->mutable_in()->set_plugin(SerializePointer(in.plugin));
}

void DeletePlugin::Fill(Out const& out, not_null<Message*> const message) {
  message->mutable_out()->set_plugin(SerializePointer(*out.plugin));
}

void DeletePlugin::Run(Message const& message,
                       not_null<PointerMap*> const pointer_map) {
  auto* plugin = Find<Plugin const*>(*pointer_map, message.in().plugin());
  principia__DeletePlugin(&plugin);
  // TODO(phl): should we do something with out() here?
}

void DirectlyInsertCelestial::Fill(In const& in,
                                   not_null<Message*> const message) {
  Message::In* m = message->mutable_in();
  m->set_plugin(SerializePointer(in.plugin));
  m->set_celestial_index(in.celestial_index);
  if (in.parent_index != nullptr) {
    m->set_parent_index(*in.parent_index);
  }
  m->set_gravitational_parameter(in.gravitational_parameter);
  if (in.axis_right_ascension != nullptr) {
    m->set_axis_right_ascension(in.axis_right_ascension);
  }
  if (in.axis_declination != nullptr) {
    m->set_axis_declination(in.axis_declination);
  }
  if (in.j2 != nullptr) {
    m->set_j2(in.j2);
  }
  if (in.reference_radius != nullptr) {
    m->set_reference_radius(in.reference_radius);
  }
  m->set_x(in.x);
  m->set_y(in.y);
  m->set_z(in.z);
  m->set_vx(in.vx);
  m->set_vy(in.vy);
  m->set_vz(in.vz);
}

void DirectlyInsertCelestial::Run(Message const& message,
                                  not_null<PointerMap*> const pointer_map) {}

void InsertCelestial::Fill(In const& in, not_null<Message*> const message) {
  Message::In* m = message->mutable_in();
  m->set_plugin(SerializePointer(in.plugin));
  m->set_celestial_index(in.celestial_index);
  m->set_gravitational_parameter(in.gravitational_parameter);
  m->set_parent_index(in.parent_index);
  *m->mutable_from_parent() = SerializeQP(in.from_parent);
}

void InsertCelestial::Run(Message const& message,
                          not_null<PointerMap*> const pointer_map) {}

void InsertSun::Fill(In const& in, not_null<Message*> const message) {}

void InsertSun::Run(Message const& message,
                    not_null<PointerMap*> const pointer_map) {}

void UpdateCelestialHierarchy::Fill(In const& in,
                                    not_null<Message*> const message) {}

void UpdateCelestialHierarchy::Run(Message const& message,
                                   not_null<PointerMap*> const pointer_map) {}

void EndInitialization::Fill(In const& in, not_null<Message*> const message) {}

void EndInitialization::Run(Message const& message,
                            not_null<PointerMap*> const pointer_map) {}

void InsertOrKeepVessel::Fill(In const& in, not_null<Message*> const message) {}

void InsertOrKeepVessel::Fill(Return const& result,
                              not_null<Message*> const message) {}

void InsertOrKeepVessel::Run(Message const& message,
                             not_null<PointerMap*> const pointer_map) {}

void SetVesselStateOffset::Fill(In const& in,
                                not_null<Message*> const message) {}

void SetVesselStateOffset::Run(Message const& message,
                               not_null<PointerMap*> const pointer_map) {}

void AdvanceTime::Fill(In const& in, not_null<Message*> const message) {}

void AdvanceTime::Run(Message const& message,
                      not_null<PointerMap*> const pointer_map) {}

void ForgetAllHistoriesBefore::Fill(In const& in,
                                    not_null<Message*> const message) {}

void ForgetAllHistoriesBefore::Run(Message const& message,
                                   not_null<PointerMap*> const pointer_map) {}

Journal::Journal(std::experimental::filesystem::path const& path)
    : stream_(path, std::ios::out) {}

Journal::~Journal() {
  stream_.close();
}

void Journal::Write(serialization::Method const& method) {
  UniqueBytes bytes(method.ByteSize());
  method.SerializeToArray(bytes.data.get(), static_cast<int>(bytes.size));

  std::int64_t const hexadecimal_size = (bytes.size << 1) + 2;
  UniqueBytes hexadecimal(hexadecimal_size);
  HexadecimalEncode({bytes.data.get(), bytes.size}, hexadecimal.get());
  hexadecimal.data.get()[hexadecimal_size - 2] = '\n';
  hexadecimal.data.get()[hexadecimal_size - 1] = '\0';
  stream_ << hexadecimal.data.get();
  stream_.flush();
}

void Journal::Activate(base::not_null<Journal*> const journal) {
  CHECK(active_ == nullptr);
  active_ = journal;
}

void Journal::Deactivate() {
  CHECK(active_ != nullptr);
  delete active_;
  active_ = nullptr;
}

Player::Player(std::experimental::filesystem::path const& path)
    : stream_(path, std::ios::in) {}

bool Player::Play() {
  std::unique_ptr<serialization::Method> method = Read();
  if (method == nullptr) {
    return false;
  }

  bool ran = false;
  ran |= RunIfAppropriate<DeletePlugin>(*method);
  ran |= RunIfAppropriate<NewPlugin>(*method);
  CHECK(ran);

  return true;
}

std::unique_ptr<serialization::Method> Player::Read() {
  std::string const line = GetLine(&stream_);
  if (line.empty()) {
    return nullptr;
  }

  uint8_t const* const hexadecimal =
      reinterpret_cast<uint8_t const*>(line.c_str());
  int const hexadecimal_size = strlen(line.c_str());
  UniqueBytes bytes(hexadecimal_size >> 1);
  HexadecimalDecode({hexadecimal, hexadecimal_size},
                    {bytes.data.get(), bytes.size});
  auto method = std::make_unique<serialization::Method>();
  CHECK(method->ParseFromArray(bytes.data.get(),
                               static_cast<int>(bytes.size)));

  return method;
}

Journal* Journal::active_ = nullptr;

}  // namespace ksp_plugin
}  // namespace principia
<|endoftext|>


<commit_before>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/

#include "SampleSlide.h"

#include "SkCanvas.h"
#include "SkCommonFlags.h"
#include "SkKey.h"
#include "SkOSFile.h"
#include "SkStream.h"

using namespace sk_app;

SampleSlide::SampleSlide(const SkViewFactory* factory)
    : fViewFactory(factory)
    , fClick(nullptr) {
    SkView* view = (*factory)();
    SampleCode::RequestTitle(view, &fName);
    view->unref();
}

SampleSlide::~SampleSlide() { delete fClick; }

void SampleSlide::draw(SkCanvas* canvas) {
    SkASSERT(fView);
    fView->draw(canvas);
}

void SampleSlide::load(SkScalar winWidth, SkScalar winHeight) {
    fView.reset((*fViewFactory)());
    fView->setVisibleP(true);
    fView->setClipToBounds(false);
    fView->setSize(winWidth, winHeight);
}

void SampleSlide::unload() {
    fView.reset();
}

bool SampleSlide::onChar(SkUnichar c) {
    if (!fView) {
        return false;
    }
    SkEvent evt(gCharEvtName);
    evt.setFast32(c);
    return fView->doQuery(&evt);
}

bool SampleSlide::onMouse(SkScalar x, SkScalar y, Window::InputState state,
                          uint32_t modifiers) {
    // map to SkView modifiers
    unsigned modifierKeys = 0;
    modifierKeys |= (state & Window::kShift_ModifierKey) ? kShift_SkModifierKey : 0;
    modifierKeys |= (state & Window::kControl_ModifierKey) ? kControl_SkModifierKey : 0;
    modifierKeys |= (state & Window::kOption_ModifierKey) ? kOption_SkModifierKey : 0;
    modifierKeys |= (state & Window::kCommand_ModifierKey) ? kCommand_SkModifierKey : 0;

    bool handled = false;
    switch (state) {
        case Window::kDown_InputState: {
            delete fClick;
            fClick = fView->findClickHandler(SkIntToScalar(x), SkIntToScalar(y), modifierKeys);
            if (fClick) {
                SkView::DoClickDown(fClick, x, y, modifierKeys);
                handled = true;
            }
            break;
        }
        case Window::kMove_InputState: {
            if (fClick) {
                SkView::DoClickMoved(fClick, x, y, modifierKeys);
                handled = true;
            }
            break;
        }
        case Window::kUp_InputState: {
            if (fClick) {
                SkView::DoClickUp(fClick, x, y, modifierKeys);
                delete fClick;
                fClick = nullptr;
                handled = true;
            }
            break;
        }
    }

    return handled;
}
<commit_msg>Fix sample modifier keys for mouse events<commit_after>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/

#include "SampleSlide.h"

#include "SkCanvas.h"
#include "SkCommonFlags.h"
#include "SkKey.h"
#include "SkOSFile.h"
#include "SkStream.h"

using namespace sk_app;

SampleSlide::SampleSlide(const SkViewFactory* factory)
    : fViewFactory(factory)
    , fClick(nullptr) {
    SkView* view = (*factory)();
    SampleCode::RequestTitle(view, &fName);
    view->unref();
}

SampleSlide::~SampleSlide() { delete fClick; }

void SampleSlide::draw(SkCanvas* canvas) {
    SkASSERT(fView);
    fView->draw(canvas);
}

void SampleSlide::load(SkScalar winWidth, SkScalar winHeight) {
    fView.reset((*fViewFactory)());
    fView->setVisibleP(true);
    fView->setClipToBounds(false);
    fView->setSize(winWidth, winHeight);
}

void SampleSlide::unload() {
    fView.reset();
}

bool SampleSlide::onChar(SkUnichar c) {
    if (!fView) {
        return false;
    }
    SkEvent evt(gCharEvtName);
    evt.setFast32(c);
    return fView->doQuery(&evt);
}

bool SampleSlide::onMouse(SkScalar x, SkScalar y, Window::InputState state,
                          uint32_t modifiers) {
    // map to SkView modifiers
    unsigned modifierKeys = 0;
    modifierKeys |= (modifiers & Window::kShift_ModifierKey) ? kShift_SkModifierKey : 0;
    modifierKeys |= (modifiers & Window::kControl_ModifierKey) ? kControl_SkModifierKey : 0;
    modifierKeys |= (modifiers & Window::kOption_ModifierKey) ? kOption_SkModifierKey : 0;
    modifierKeys |= (modifiers & Window::kCommand_ModifierKey) ? kCommand_SkModifierKey : 0;

    bool handled = false;
    switch (state) {
        case Window::kDown_InputState: {
            delete fClick;
            fClick = fView->findClickHandler(SkIntToScalar(x), SkIntToScalar(y), modifierKeys);
            if (fClick) {
                SkView::DoClickDown(fClick, x, y, modifierKeys);
                handled = true;
            }
            break;
        }
        case Window::kMove_InputState: {
            if (fClick) {
                SkView::DoClickMoved(fClick, x, y, modifierKeys);
                handled = true;
            }
            break;
        }
        case Window::kUp_InputState: {
            if (fClick) {
                SkView::DoClickUp(fClick, x, y, modifierKeys);
                delete fClick;
                fClick = nullptr;
                handled = true;
            }
            break;
        }
    }

    return handled;
}
<|endoftext|>