<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreOverlayContainer.h"
#include "OgreException.h"
#include "OgreOverlayManager.h"
#include "OgreOverlay.h"

namespace Ogre {

    //---------------------------------------------------------------------
    OverlayContainer::OverlayContainer(const String& name)
        : OverlayElement(name),
        mChildrenProcessEvents(true)
    {
    }
    //---------------------------------------------------------------------
    OverlayContainer::~OverlayContainer()
    {
        // remove from parent overlay if root
        if (mOverlay && !mParent)
        {
            mOverlay->remove2D(this);
        }

        for (const auto& p : mChildren)
        {
            p.second->_notifyParent(0, 0);
        }
    }
    //---------------------------------------------------------------------
    void OverlayContainer::addChild(OverlayElement* elem)
    {
        if (elem->isContainer())
        {
            addChildImpl(static_cast<OverlayContainer*>(elem));
        }
        else
        {
            addChildImpl(elem);
        }

    }
    //---------------------------------------------------------------------
    void OverlayContainer::addChildImpl(OverlayElement* elem)
    {
        String name = elem->getName();
        ChildMap::iterator i = mChildren.find(name);
        if (i != mChildren.end())
        {
            OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, "Child with name " + name +
                " already defined.", "OverlayContainer::addChild");
        }

        mChildren.emplace(name, elem);
        // tell child about parent & Z-order
        elem->_notifyParent(this, mOverlay);
        elem->_notifyZOrder(Math::uint16Cast(mZOrder + 1));
        elem->_notifyWorldTransforms(mXForm);
    }
    //---------------------------------------------------------------------
    void OverlayContainer::addChildImpl(OverlayContainer* cont)
    {
        // Add to main map first
        // This will pick up duplicates
        OverlayElement* pElem = cont;
        addChildImpl(pElem);

        /*
        cont->_notifyParent(this, mOverlay);
        cont->_notifyZOrder(mZOrder + 1);
        cont->_notifyWorldTransforms(mXForm);

        // tell children of new container the current overlay
        ChildIterator it = cont->getChildIterator();
        while (it.hasMoreElements())
        {
            // Give children Z-order 1 higher than this
            GuiElement* pElemChild = it.getNext();
            pElemChild->_notifyParent(cont, mOverlay);
            pElemChild->_notifyZOrder(cont->getZOrder() + 1);
            pElemChild->_notifyWorldTransforms(mXForm);
        }
        */

        // Now add to specific map too
        mChildContainers.emplace(cont->getName(), cont);

    }
    //---------------------------------------------------------------------
    void OverlayContainer::removeChild(const String& name)
    {
        ChildMap::iterator i = mChildren.find(name);
        if (i == mChildren.end())
        {
            OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child with name " + name +
                " not found.", "OverlayContainer::removeChild");
        }

        OverlayElement* element = i->second;
        mChildren.erase(i);

        // Remove from container list (if found)
        ChildContainerMap::iterator j = mChildContainers.find(name);
        if (j != mChildContainers.end())
            mChildContainers.erase(j);

        element->_setParent(0);
    }
    //---------------------------------------------------------------------
    void OverlayContainer::_addChild(OverlayElement* elem)
    {
        if (elem->isContainer())
        {
            addChildImpl(static_cast<OverlayContainer*>(elem));
        }
        else
        {
            addChildImpl(elem);
        }
    }
    //---------------------------------------------------------------------
    void OverlayContainer::_removeChild(const String& name)
    {
        ChildMap::iterator i = mChildren.find(name);
        if (i == mChildren.end())
        {
            OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child with name " + name +
                " not found.", "OverlayContainer::removeChild");
        }

        OverlayElement* element = i->second;
        mChildren.erase(i);

        // Remove from container list (if found)
        ChildContainerMap::iterator j = mChildContainers.find(name);
        if (j != mChildContainers.end())
            mChildContainers.erase(j);

        element->_setParent(0);
    }
    //---------------------------------------------------------------------
    OverlayElement* OverlayContainer::getChild(const String& name)
    {
        ChildMap::iterator i = mChildren.find(name);
        if (i == mChildren.end())
        {
            OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child with name " + name +
                " not found.", "OverlayContainer::getChild");
        }

        return i->second;
    }
    //---------------------------------------------------------------------
    OverlayContainer::ChildIterator OverlayContainer::getChildIterator(void)
    {
        return ChildIterator(mChildren.begin(), mChildren.end());
    }
    //---------------------------------------------------------------------
    OverlayContainer::ChildContainerIterator OverlayContainer::getChildContainerIterator(void)
    {
        return ChildContainerIterator(mChildContainers.begin(), mChildContainers.end());
    }
    //---------------------------------------------------------------------
    void OverlayContainer::initialise(void)
    {
        ChildContainerMap::iterator coni;
        for (coni =  mChildContainers.begin(); coni != mChildContainers.end(); ++coni)
        {
            coni->second->initialise();
        }
        ChildMap::iterator ci;
        for (ci =  mChildren.begin(); ci != mChildren.end(); ++ci)
        {
            ci->second->initialise();
        }
    }
    //---------------------------------------------------------------------
    void OverlayContainer::_positionsOutOfDate(void)
    {
        OverlayElement::_positionsOutOfDate();

        for (const auto& p : mChildren)
        {
            p.second->_positionsOutOfDate();
        }
    }

    //---------------------------------------------------------------------
    void OverlayContainer::_update(void)
    {
        // call superclass
        OverlayElement::_update();

        // Update children
        for (const auto& p : mChildren)
        {
            p.second->_update();
        }
    }
    //---------------------------------------------------------------------
    ushort OverlayContainer::_notifyZOrder(ushort newZOrder)
    {
        OverlayElement::_notifyZOrder(newZOrder);
        // One for us
        newZOrder++;

        // Update children
        for (const auto& p : mChildren)
        {
            // Children "consume" Z-order values, so keep track of them
            newZOrder = p.second->_notifyZOrder(newZOrder);
        }

        return newZOrder;
    }
    //---------------------------------------------------------------------
    void OverlayContainer::_notifyWorldTransforms(const Matrix4& xform)
    {
        OverlayElement::_notifyWorldTransforms(xform);

        // Update children
        for (const auto& p : mChildren)
        {
            p.second->_notifyWorldTransforms(xform);
        }
    }
    //---------------------------------------------------------------------
    void OverlayContainer::_notifyViewport()
    {
        OverlayElement::_notifyViewport();

        // Update children
        for (const auto& p : mChildren)
        {
            p.second->_notifyViewport();
        }
    }
    //---------------------------------------------------------------------
    void OverlayContainer::_notifyParent(OverlayContainer* parent, Overlay* overlay)
    {
        OverlayElement::_notifyParent(parent, overlay);

        // Update children
        for (const auto& p : mChildren)
        {
            // Notify the children of the overlay
            p.second->_notifyParent(this, overlay);
        }
    }

    //---------------------------------------------------------------------
    void OverlayContainer::_updateRenderQueue(RenderQueue* queue)
    {
        if (mVisible)
        {

            OverlayElement::_updateRenderQueue(queue);

            // Also add children
            for (const auto& p : mChildren)
            {
                // Give children Z-order 1 higher than this
                p.second->_updateRenderQueue(queue);
            }
        }

    }

    OverlayElement* OverlayContainer::findElementAt(Real x, Real y)         // relative to parent
    {

        OverlayElement* ret = NULL;

        int currZ = -1;

        if (mVisible)
        {
            ret = OverlayElement::findElementAt(x,y);   //default to the current container if no others are found
            if (ret && mChildrenProcessEvents)
            {
                for (const auto& p : mChildren)
                {
                    OverlayElement* currentOverlayElement = p.second;
                    if (currentOverlayElement->isVisible() && currentOverlayElement->isEnabled())
                    {
                        int z = currentOverlayElement->getZOrder();
                        if (z > currZ)
                        {
                            OverlayElement* elementFound = currentOverlayElement->findElementAt(x ,y );
                            if (elementFound)
                            {
                                currZ = z;
                                ret = elementFound;
                            }
                        }
                    }
                }
            }
        }
        return ret;
    }

    void OverlayContainer::copyFromTemplate(OverlayElement* templateOverlay)
    {
        OverlayElement::copyFromTemplate(templateOverlay);

            if (templateOverlay->isContainer() && isContainer())
            {
             for (const auto& p : static_cast<OverlayContainer*>(templateOverlay)->getChildren())
             {
                 OverlayElement* oldChildElement = p.second;
                 if (oldChildElement->isCloneable())
                 {
                     OverlayElement* newChildElement =
                         OverlayManager::getSingleton().createOverlayElement(
                            oldChildElement->getTypeName(),
                            mName+"/"+oldChildElement->getName());
                     newChildElement->copyFromTemplate(oldChildElement);
                     addChild(static_cast<OverlayContainer*>(newChildElement));
                 }
             }
        }
    }

    OverlayElement* OverlayContainer::clone(const String& instanceName)
    {
        OverlayContainer *newContainer;

        newContainer = static_cast<OverlayContainer*>(OverlayElement::clone(instanceName));

        for (const auto& p : mChildren)
        {
            OverlayElement* oldChildElement = p.second;
            if (oldChildElement->isCloneable())
            {
                OverlayElement* newChildElement = oldChildElement->clone(instanceName);
                newContainer->_addChild(newChildElement);
            }
        }

        return newContainer;
    }

}

<commit_msg>Overlay: OverlayContainer - drop wrong cast<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreOverlayContainer.h"
#include "OgreException.h"
#include "OgreOverlayManager.h"
#include "OgreOverlay.h"

namespace Ogre {

    //---------------------------------------------------------------------
    OverlayContainer::OverlayContainer(const String& name)
        : OverlayElement(name),
        mChildrenProcessEvents(true)
    {
    }
    //---------------------------------------------------------------------
    OverlayContainer::~OverlayContainer()
    {
        // remove from parent overlay if root
        if (mOverlay && !mParent)
        {
            mOverlay->remove2D(this);
        }

        for (const auto& p : mChildren)
        {
            p.second->_notifyParent(0, 0);
        }
    }
    //---------------------------------------------------------------------
    void OverlayContainer::addChild(OverlayElement* elem)
    {
        if (elem->isContainer())
        {
            addChildImpl(static_cast<OverlayContainer*>(elem));
        }
        else
        {
            addChildImpl(elem);
        }

    }
    //---------------------------------------------------------------------
    void OverlayContainer::addChildImpl(OverlayElement* elem)
    {
        String name = elem->getName();
        ChildMap::iterator i = mChildren.find(name);
        if (i != mChildren.end())
        {
            OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, "Child with name " + name +
                " already defined.", "OverlayContainer::addChild");
        }

        mChildren.emplace(name, elem);
        // tell child about parent & Z-order
        elem->_notifyParent(this, mOverlay);
        elem->_notifyZOrder(Math::uint16Cast(mZOrder + 1));
        elem->_notifyWorldTransforms(mXForm);
    }
    //---------------------------------------------------------------------
    void OverlayContainer::addChildImpl(OverlayContainer* cont)
    {
        // Add to main map first
        // This will pick up duplicates
        OverlayElement* pElem = cont;
        addChildImpl(pElem);

        /*
        cont->_notifyParent(this, mOverlay);
        cont->_notifyZOrder(mZOrder + 1);
        cont->_notifyWorldTransforms(mXForm);

        // tell children of new container the current overlay
        ChildIterator it = cont->getChildIterator();
        while (it.hasMoreElements())
        {
            // Give children Z-order 1 higher than this
            GuiElement* pElemChild = it.getNext();
            pElemChild->_notifyParent(cont, mOverlay);
            pElemChild->_notifyZOrder(cont->getZOrder() + 1);
            pElemChild->_notifyWorldTransforms(mXForm);
        }
        */

        // Now add to specific map too
        mChildContainers.emplace(cont->getName(), cont);

    }
    //---------------------------------------------------------------------
    void OverlayContainer::removeChild(const String& name)
    {
        ChildMap::iterator i = mChildren.find(name);
        if (i == mChildren.end())
        {
            OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child with name " + name +
                " not found.", "OverlayContainer::removeChild");
        }

        OverlayElement* element = i->second;
        mChildren.erase(i);

        // Remove from container list (if found)
        ChildContainerMap::iterator j = mChildContainers.find(name);
        if (j != mChildContainers.end())
            mChildContainers.erase(j);

        element->_setParent(0);
    }
    //---------------------------------------------------------------------
    void OverlayContainer::_addChild(OverlayElement* elem)
    {
        if (elem->isContainer())
        {
            addChildImpl(static_cast<OverlayContainer*>(elem));
        }
        else
        {
            addChildImpl(elem);
        }
    }
    //---------------------------------------------------------------------
    void OverlayContainer::_removeChild(const String& name)
    {
        ChildMap::iterator i = mChildren.find(name);
        if (i == mChildren.end())
        {
            OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child with name " + name +
                " not found.", "OverlayContainer::removeChild");
        }

        OverlayElement* element = i->second;
        mChildren.erase(i);

        // Remove from container list (if found)
        ChildContainerMap::iterator j = mChildContainers.find(name);
        if (j != mChildContainers.end())
            mChildContainers.erase(j);

        element->_setParent(0);
    }
    //---------------------------------------------------------------------
    OverlayElement* OverlayContainer::getChild(const String& name)
    {
        ChildMap::iterator i = mChildren.find(name);
        if (i == mChildren.end())
        {
            OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child with name " + name +
                " not found.", "OverlayContainer::getChild");
        }

        return i->second;
    }
    //---------------------------------------------------------------------
    OverlayContainer::ChildIterator OverlayContainer::getChildIterator(void)
    {
        return ChildIterator(mChildren.begin(), mChildren.end());
    }
    //---------------------------------------------------------------------
    OverlayContainer::ChildContainerIterator OverlayContainer::getChildContainerIterator(void)
    {
        return ChildContainerIterator(mChildContainers.begin(), mChildContainers.end());
    }
    //---------------------------------------------------------------------
    void OverlayContainer::initialise(void)
    {
        ChildContainerMap::iterator coni;
        for (coni =  mChildContainers.begin(); coni != mChildContainers.end(); ++coni)
        {
            coni->second->initialise();
        }
        ChildMap::iterator ci;
        for (ci =  mChildren.begin(); ci != mChildren.end(); ++ci)
        {
            ci->second->initialise();
        }
    }
    //---------------------------------------------------------------------
    void OverlayContainer::_positionsOutOfDate(void)
    {
        OverlayElement::_positionsOutOfDate();

        for (const auto& p : mChildren)
        {
            p.second->_positionsOutOfDate();
        }
    }

    //---------------------------------------------------------------------
    void OverlayContainer::_update(void)
    {
        // call superclass
        OverlayElement::_update();

        // Update children
        for (const auto& p : mChildren)
        {
            p.second->_update();
        }
    }
    //---------------------------------------------------------------------
    ushort OverlayContainer::_notifyZOrder(ushort newZOrder)
    {
        OverlayElement::_notifyZOrder(newZOrder);
        // One for us
        newZOrder++;

        // Update children
        for (const auto& p : mChildren)
        {
            // Children "consume" Z-order values, so keep track of them
            newZOrder = p.second->_notifyZOrder(newZOrder);
        }

        return newZOrder;
    }
    //---------------------------------------------------------------------
    void OverlayContainer::_notifyWorldTransforms(const Matrix4& xform)
    {
        OverlayElement::_notifyWorldTransforms(xform);

        // Update children
        for (const auto& p : mChildren)
        {
            p.second->_notifyWorldTransforms(xform);
        }
    }
    //---------------------------------------------------------------------
    void OverlayContainer::_notifyViewport()
    {
        OverlayElement::_notifyViewport();

        // Update children
        for (const auto& p : mChildren)
        {
            p.second->_notifyViewport();
        }
    }
    //---------------------------------------------------------------------
    void OverlayContainer::_notifyParent(OverlayContainer* parent, Overlay* overlay)
    {
        OverlayElement::_notifyParent(parent, overlay);

        // Update children
        for (const auto& p : mChildren)
        {
            // Notify the children of the overlay
            p.second->_notifyParent(this, overlay);
        }
    }

    //---------------------------------------------------------------------
    void OverlayContainer::_updateRenderQueue(RenderQueue* queue)
    {
        if (mVisible)
        {

            OverlayElement::_updateRenderQueue(queue);

            // Also add children
            for (const auto& p : mChildren)
            {
                // Give children Z-order 1 higher than this
                p.second->_updateRenderQueue(queue);
            }
        }

    }

    OverlayElement* OverlayContainer::findElementAt(Real x, Real y)         // relative to parent
    {

        OverlayElement* ret = NULL;

        int currZ = -1;

        if (mVisible)
        {
            ret = OverlayElement::findElementAt(x,y);   //default to the current container if no others are found
            if (ret && mChildrenProcessEvents)
            {
                for (const auto& p : mChildren)
                {
                    OverlayElement* currentOverlayElement = p.second;
                    if (currentOverlayElement->isVisible() && currentOverlayElement->isEnabled())
                    {
                        int z = currentOverlayElement->getZOrder();
                        if (z > currZ)
                        {
                            OverlayElement* elementFound = currentOverlayElement->findElementAt(x ,y );
                            if (elementFound)
                            {
                                currZ = z;
                                ret = elementFound;
                            }
                        }
                    }
                }
            }
        }
        return ret;
    }

    void OverlayContainer::copyFromTemplate(OverlayElement* templateOverlay)
    {
        OverlayElement::copyFromTemplate(templateOverlay);

            if (templateOverlay->isContainer() && isContainer())
            {
             for (const auto& p : static_cast<OverlayContainer*>(templateOverlay)->getChildren())
             {
                 OverlayElement* oldChildElement = p.second;
                 if (oldChildElement->isCloneable())
                 {
                     OverlayElement* newChildElement =
                         OverlayManager::getSingleton().createOverlayElement(
                            oldChildElement->getTypeName(),
                            mName+"/"+oldChildElement->getName());
                     newChildElement->copyFromTemplate(oldChildElement);
                     addChild(newChildElement);
                 }
             }
        }
    }

    OverlayElement* OverlayContainer::clone(const String& instanceName)
    {
        OverlayContainer *newContainer;

        newContainer = static_cast<OverlayContainer*>(OverlayElement::clone(instanceName));

        for (const auto& p : mChildren)
        {
            OverlayElement* oldChildElement = p.second;
            if (oldChildElement->isCloneable())
            {
                OverlayElement* newChildElement = oldChildElement->clone(instanceName);
                newContainer->_addChild(newChildElement);
            }
        }

        return newContainer;
    }

}

<|endoftext|>


<commit_before>#include <iostream>
#include <stan/services/util/mcmc_writer.hpp>
#include <gtest/gtest.h>
#include <test/unit/services/instrumented_callbacks.hpp>
#include <test/test-models/good/services/test_lp.hpp>
#include <stan/callbacks/logger.hpp>
#include <stan/callbacks/writer.hpp>
#include <stan/io/empty_var_context.hpp>
#include <stan/services/util/create_rng.hpp>

namespace test {
// mock_throwing_model_in_write_array throws exception in the write_array()
// method
class throwing_model : public stan::model::model_base_crtp<throwing_model> {
 private:
  int pos__;

 public:
  ~throwing_model() {}

  std::string model_name() const final { return "throwing_model"; }

  std::vector<std::string> model_compile_info() const {
    std::vector<std::string> stanc_info;
    stanc_info.push_back("stanc_version = stanc3 e010e06c");
    stanc_info.push_back("stancflags = ");
    return stanc_info;
  }

  throwing_model(stan::io::var_context& context__,
                 unsigned int random_seed__ = 0,
                 std::ostream* pstream__ = nullptr)
      : model_base_crtp(0) {}

  template <bool propto__, bool jacobian__, typename T__>
  inline T__ log_prob(std::vector<T__>& params_r__,
                      std::vector<int>& params_i__,
                      std::ostream* pstream__ = nullptr) const {
    return 0.0;
  }  // log_prob()

  template <typename RNG>
  void write_array(RNG& base_rng__, std::vector<double>& params_r__,
                   std::vector<int>& params_i__, std::vector<double>& vars__,
                   bool include_tparams__ = true, bool include_gqs__ = true,
                   std::ostream* pstream__ = 0) const {
    vars__.resize(0);
    for (size_t i = 0; i < params_r__.size() - 2; ++i)
      vars__.push_back(params_r__[i]);
    throw std::domain_error("throwing within write_array");
  }

  inline void transform_inits(const stan::io::var_context& context__,
                              std::vector<int>& params_i__,
                              std::vector<double>& vars__,
                              std::ostream* pstream__) const final {

  }  // transform_inits()

  inline void get_param_names(std::vector<std::string>& names__) const {
    names__.clear();
    names__.emplace_back("y");
    names__.emplace_back("z");
    names__.emplace_back("xgq");
  }  // get_param_names()

  inline void get_dims(std::vector<std::vector<size_t>>& dimss__) const final {
    dimss__.clear();
    dimss__.emplace_back(std::vector<size_t>{static_cast<size_t>(2)});

    dimss__.emplace_back(std::vector<size_t>{static_cast<size_t>(2)});

    dimss__.emplace_back(std::vector<size_t>{});

  }  // get_dims()

  inline void constrained_param_names(std::vector<std::string>& param_names__,
                                      bool emit_transformed_parameters__ = true,
                                      bool emit_generated_quantities__
                                      = true) const final {
    for (int sym1__ = 1; sym1__ <= 2; ++sym1__) {
      {
        param_names__.emplace_back(std::string() + "y" + '.'
                                   + std::to_string(sym1__));
      }
    }
    if (emit_transformed_parameters__) {
      for (int sym1__ = 1; sym1__ <= 2; ++sym1__) {
        {
          param_names__.emplace_back(std::string() + "z" + '.'
                                     + std::to_string(sym1__));
        }
      }
    }

    if (emit_generated_quantities__) {
      param_names__.emplace_back(std::string() + "xgq");
    }

  }  // constrained_param_names()

  inline void unconstrained_param_names(std::vector<std::string>& param_names__,
                                        bool emit_transformed_parameters__
                                        = true,
                                        bool emit_generated_quantities__
                                        = true) const final {
    for (int sym1__ = 1; sym1__ <= 2; ++sym1__) {
      {
        param_names__.emplace_back(std::string() + "y" + '.'
                                   + std::to_string(sym1__));
      }
    }
    if (emit_transformed_parameters__) {
      for (int sym1__ = 1; sym1__ <= 2; ++sym1__) {
        {
          param_names__.emplace_back(std::string() + "z" + '.'
                                     + std::to_string(sym1__));
        }
      }
    }

    if (emit_generated_quantities__) {
      param_names__.emplace_back(std::string() + "xgq");
    }

  }  // unconstrained_param_names()

  inline std::string get_constrained_sizedtypes() const {
    return "";
  }  // get_constrained_sizedtypes()

  inline std::string get_unconstrained_sizedtypes() const {
    return "";
  }  // get_unconstrained_sizedtypes()

  // Begin method overload boilerplate
  template <typename RNG>
  void write_array(RNG& base_rng,
                   Eigen::Matrix<double, Eigen::Dynamic, 1>& params_r,
                   Eigen::Matrix<double, Eigen::Dynamic, 1>& vars,
                   bool include_tparams = true, bool include_gqs = true,
                   std::ostream* pstream = 0) const {
    throw std::domain_error("throwing within write_array");
  }

  template <bool propto__, bool jacobian__, typename T_>
  inline T_ log_prob(Eigen::Matrix<T_, Eigen::Dynamic, 1>& params_r,
                     std::ostream* pstream = nullptr) const {
    return 0.0;
  }

  inline void transform_inits(
      const stan::io::var_context& context,
      Eigen::Matrix<double, Eigen::Dynamic, 1>& params_r,
      std::ostream* pstream__ = nullptr) const {}
};
}  // namespace test

class ServicesUtil : public ::testing::Test {
 public:
  ServicesUtil()
      : mcmc_writer(sample_writer, diagnostic_writer, logger),
        model(context, 0, &model_log),
        throwing_model(context, 0, &model_log) {}

  stan::test::unit::instrumented_writer sample_writer, diagnostic_writer;
  stan::test::unit::instrumented_logger logger;
  stan::services::util::mcmc_writer mcmc_writer;
  std::stringstream model_log;
  stan::io::empty_var_context context;
  stan_model model;
  test::throwing_model throwing_model;
};

TEST_F(ServicesUtil, constructor) {
  EXPECT_EQ(0, sample_writer.call_count());
  EXPECT_EQ(0, diagnostic_writer.call_count());
  EXPECT_EQ(0, logger.call_count());
}

class mock_sampler : public stan::mcmc::base_mcmc {
 public:
  int n_transition;
  int n_get_sampler_param_names;
  int n_get_sampler_params;
  int n_write_sampler_state;
  int n_get_sampler_diagnostic_names;
  int n_get_sampler_diagnostics;

  mock_sampler() { reset(); }

  void reset() {
    n_transition = 0;
    n_get_sampler_param_names = 0;
    n_get_sampler_params = 0;
    n_write_sampler_state = 0;
    n_get_sampler_diagnostic_names = 0;
    n_get_sampler_diagnostics = 0;
  }

  stan::mcmc::sample transition(stan::mcmc::sample& init_sample,
                                stan::callbacks::logger& logger) {
    ++n_transition;
    stan::mcmc::sample result(init_sample);
    return result;
  }

  void get_sampler_param_names(std::vector<std::string>& names) {
    ++n_get_sampler_param_names;
  }

  void get_sampler_params(std::vector<double>& values) {
    ++n_get_sampler_params;
  }

  void write_sampler_state(stan::callbacks::writer& writer) {
    ++n_write_sampler_state;
  }

  void get_sampler_diagnostic_names(std::vector<std::string>& model_names,
                                    std::vector<std::string>& names) {
    ++n_get_sampler_diagnostic_names;
  }

  void get_sampler_diagnostics(std::vector<double>& values) {
    ++n_get_sampler_diagnostics;
  }
};

TEST_F(ServicesUtil, write_sample_names) {
  Eigen::VectorXd x = Eigen::VectorXd::Zero(2);
  stan::mcmc::sample sample(x, 1, 2);
  mock_sampler sampler;

  mcmc_writer.write_sample_names(sample, sampler, model);
  EXPECT_EQ(1, sample_writer.call_count());
  EXPECT_EQ(1, sample_writer.call_count("vector_string"));
  EXPECT_EQ(0, diagnostic_writer.call_count());
  EXPECT_EQ(0, logger.call_count());

  EXPECT_EQ(2, mcmc_writer.num_sample_params_);
  EXPECT_EQ(0, mcmc_writer.num_sampler_params_);
  EXPECT_EQ(5, mcmc_writer.num_model_params_);
}

TEST_F(ServicesUtil, write_sample_params) {
  boost::ecuyer1988 rng = stan::services::util::create_rng(0, 1);
  Eigen::VectorXd x = Eigen::VectorXd::Zero(2);
  stan::mcmc::sample sample(x, 1, 2);
  mock_sampler sampler;

  mcmc_writer.write_sample_params(rng, sample, sampler, model);
  EXPECT_EQ(1, sample_writer.call_count());
  EXPECT_EQ(1, sample_writer.call_count("vector_double"));
  EXPECT_EQ(0, diagnostic_writer.call_count());
  EXPECT_EQ(0, logger.call_count());
}

TEST_F(ServicesUtil, write_adapt_finish) {
  mock_sampler sampler;

  mcmc_writer.write_adapt_finish(sampler);
  EXPECT_EQ(1, sample_writer.call_count());
  EXPECT_EQ(1, sample_writer.call_count("string"));
  EXPECT_EQ(0, diagnostic_writer.call_count());
  EXPECT_EQ(0, logger.call_count());
}

TEST_F(ServicesUtil, write_diagnostic_names) {
  Eigen::VectorXd x = Eigen::VectorXd::Zero(2);
  stan::mcmc::sample sample(x, 1, 2);
  mock_sampler sampler;

  mcmc_writer.write_diagnostic_names(sample, sampler, model);
  EXPECT_EQ(0, sample_writer.call_count());
  EXPECT_EQ(1, diagnostic_writer.call_count());
  EXPECT_EQ(1, diagnostic_writer.call_count("vector_string"));
  EXPECT_EQ(0, logger.call_count());
}

TEST_F(ServicesUtil, write_diagnostic_params) {
  Eigen::VectorXd x = Eigen::VectorXd::Zero(2);
  stan::mcmc::sample sample(x, 1, 2);
  mock_sampler sampler;

  mcmc_writer.write_diagnostic_params(sample, sampler);
  EXPECT_EQ(0, sample_writer.call_count());
  EXPECT_EQ(1, diagnostic_writer.call_count());
  EXPECT_EQ(1, diagnostic_writer.call_count("vector_double"));
  EXPECT_EQ(0, logger.call_count());
}

TEST_F(ServicesUtil, internal_write_timing) {
  stan::test::unit::instrumented_writer writer;
  mcmc_writer.write_timing(0, 0, writer);
  EXPECT_EQ(5, writer.call_count());
  EXPECT_EQ(3, writer.call_count("string"));
  EXPECT_EQ(2, writer.call_count("empty"));
}

TEST_F(ServicesUtil, write_timing) {
  mcmc_writer.write_timing(0, 0);
  EXPECT_EQ(5, sample_writer.call_count());
  EXPECT_EQ(3, sample_writer.call_count("string"));
  EXPECT_EQ(2, sample_writer.call_count("empty"));
  EXPECT_EQ(5, diagnostic_writer.call_count());
  EXPECT_EQ(3, diagnostic_writer.call_count("string"));
  EXPECT_EQ(2, diagnostic_writer.call_count("empty"));
  EXPECT_EQ(5, logger.call_count());
  EXPECT_EQ(5, logger.call_count_info());
}

TEST_F(ServicesUtil, throwing_model__write_sample_parameters) {
  boost::ecuyer1988 rng = stan::services::util::create_rng(0, 1);
  Eigen::VectorXd x = Eigen::VectorXd::Zero(2);
  stan::mcmc::sample sample(x, 1, 2);
  mock_sampler sampler;

  mcmc_writer.write_sample_names(sample, sampler, throwing_model);
  ASSERT_EQ(5, mcmc_writer.num_model_params_);

  mcmc_writer.write_sample_params(rng, sample, sampler, throwing_model);
  EXPECT_EQ(2, sample_writer.call_count());
  EXPECT_EQ(1, sample_writer.call_count("vector_double"));
  EXPECT_EQ(0, diagnostic_writer.call_count());
  EXPECT_EQ(1, logger.call_count());

  std::vector<std::vector<double>> values
      = sample_writer.vector_double_values();
  ASSERT_EQ(1, values.size());
  ASSERT_EQ(mcmc_writer.num_sample_params_ + mcmc_writer.num_sampler_params_
                + mcmc_writer.num_model_params_,
            values[0].size());

  for (size_t i = 0;
       i < mcmc_writer.num_sample_params_ + mcmc_writer.num_sampler_params_;
       ++i) {
    EXPECT_FALSE(std::isnan(values[0][i]));
  }

  for (size_t i
       = mcmc_writer.num_sample_params_ + mcmc_writer.num_sampler_params_;
       i < values[0].size(); ++i) {
    EXPECT_TRUE(std::isnan(values[0][i]));
  }
}
<commit_msg>remove unnecessary functions from test<commit_after>#include <iostream>
#include <stan/services/util/mcmc_writer.hpp>
#include <gtest/gtest.h>
#include <test/unit/services/instrumented_callbacks.hpp>
#include <test/test-models/good/services/test_lp.hpp>
#include <stan/callbacks/logger.hpp>
#include <stan/callbacks/writer.hpp>
#include <stan/io/empty_var_context.hpp>
#include <stan/services/util/create_rng.hpp>

namespace test {
// mock_throwing_model_in_write_array throws exception in the write_array()
// method
class throwing_model : public stan::model::model_base_crtp<throwing_model> {
 private:
  int pos__;

 public:
  ~throwing_model() {}

  std::string model_name() const final { return "throwing_model"; }

  std::vector<std::string> model_compile_info() const {
    std::vector<std::string> stanc_info;
    stanc_info.push_back("stanc_version = stanc3 e010e06c");
    stanc_info.push_back("stancflags = ");
    return stanc_info;
  }

  throwing_model(stan::io::var_context& context__,
                 unsigned int random_seed__ = 0,
                 std::ostream* pstream__ = nullptr)
      : model_base_crtp(0) {}

  template <bool propto__, bool jacobian__, typename T__>
  inline T__ log_prob(std::vector<T__>& params_r__,
                      std::vector<int>& params_i__,
                      std::ostream* pstream__ = nullptr) const {
    return 0.0;
  }  // log_prob()

  template <typename RNG>
  void write_array(RNG& base_rng__, std::vector<double>& params_r__,
                   std::vector<int>& params_i__, std::vector<double>& vars__,
                   bool include_tparams__ = true, bool include_gqs__ = true,
                   std::ostream* pstream__ = 0) const {
    vars__.resize(0);
    for (size_t i = 0; i < params_r__.size() - 2; ++i)
      vars__.push_back(params_r__[i]);
    throw std::domain_error("throwing within write_array");
  }

  inline void transform_inits(const stan::io::var_context& context__,
                              std::vector<int>& params_i__,
                              std::vector<double>& vars__,
                              std::ostream* pstream__) const final {

  }  // transform_inits()

  inline void get_param_names(std::vector<std::string>& names__) const {
    names__.clear();
    names__.emplace_back("y");
    names__.emplace_back("z");
    names__.emplace_back("xgq");
  }  // get_param_names()

  inline void get_dims(std::vector<std::vector<size_t>>& dimss__) const final {
    dimss__.clear();
    dimss__.emplace_back(std::vector<size_t>{static_cast<size_t>(2)});

    dimss__.emplace_back(std::vector<size_t>{static_cast<size_t>(2)});

    dimss__.emplace_back(std::vector<size_t>{});

  }  // get_dims()

  inline void constrained_param_names(std::vector<std::string>& param_names__,
                                      bool emit_transformed_parameters__ = true,
                                      bool emit_generated_quantities__
                                      = true) const final {
    for (int sym1__ = 1; sym1__ <= 2; ++sym1__) {
      {
        param_names__.emplace_back(std::string() + "y" + '.'
                                   + std::to_string(sym1__));
      }
    }
    if (emit_transformed_parameters__) {
      for (int sym1__ = 1; sym1__ <= 2; ++sym1__) {
        {
          param_names__.emplace_back(std::string() + "z" + '.'
                                     + std::to_string(sym1__));
        }
      }
    }

    if (emit_generated_quantities__) {
      param_names__.emplace_back(std::string() + "xgq");
    }

  }  // constrained_param_names()

  inline void unconstrained_param_names(std::vector<std::string>& param_names__,
                                        bool emit_transformed_parameters__
                                        = true,
                                        bool emit_generated_quantities__
                                        = true) const final {
    for (int sym1__ = 1; sym1__ <= 2; ++sym1__) {
      {
        param_names__.emplace_back(std::string() + "y" + '.'
                                   + std::to_string(sym1__));
      }
    }
    if (emit_transformed_parameters__) {
      for (int sym1__ = 1; sym1__ <= 2; ++sym1__) {
        {
          param_names__.emplace_back(std::string() + "z" + '.'
                                     + std::to_string(sym1__));
        }
      }
    }

    if (emit_generated_quantities__) {
      param_names__.emplace_back(std::string() + "xgq");
    }

  }  // unconstrained_param_names()

  // Begin method overload boilerplate
  template <typename RNG>
  void write_array(RNG& base_rng,
                   Eigen::Matrix<double, Eigen::Dynamic, 1>& params_r,
                   Eigen::Matrix<double, Eigen::Dynamic, 1>& vars,
                   bool include_tparams = true, bool include_gqs = true,
                   std::ostream* pstream = 0) const {
    throw std::domain_error("throwing within write_array");
  }

  template <bool propto__, bool jacobian__, typename T_>
  inline T_ log_prob(Eigen::Matrix<T_, Eigen::Dynamic, 1>& params_r,
                     std::ostream* pstream = nullptr) const {
    return 0.0;
  }

  inline void transform_inits(
      const stan::io::var_context& context,
      Eigen::Matrix<double, Eigen::Dynamic, 1>& params_r,
      std::ostream* pstream__ = nullptr) const {}
};
}  // namespace test

class ServicesUtil : public ::testing::Test {
 public:
  ServicesUtil()
      : mcmc_writer(sample_writer, diagnostic_writer, logger),
        model(context, 0, &model_log),
        throwing_model(context, 0, &model_log) {}

  stan::test::unit::instrumented_writer sample_writer, diagnostic_writer;
  stan::test::unit::instrumented_logger logger;
  stan::services::util::mcmc_writer mcmc_writer;
  std::stringstream model_log;
  stan::io::empty_var_context context;
  stan_model model;
  test::throwing_model throwing_model;
};

TEST_F(ServicesUtil, constructor) {
  EXPECT_EQ(0, sample_writer.call_count());
  EXPECT_EQ(0, diagnostic_writer.call_count());
  EXPECT_EQ(0, logger.call_count());
}

class mock_sampler : public stan::mcmc::base_mcmc {
 public:
  int n_transition;
  int n_get_sampler_param_names;
  int n_get_sampler_params;
  int n_write_sampler_state;
  int n_get_sampler_diagnostic_names;
  int n_get_sampler_diagnostics;

  mock_sampler() { reset(); }

  void reset() {
    n_transition = 0;
    n_get_sampler_param_names = 0;
    n_get_sampler_params = 0;
    n_write_sampler_state = 0;
    n_get_sampler_diagnostic_names = 0;
    n_get_sampler_diagnostics = 0;
  }

  stan::mcmc::sample transition(stan::mcmc::sample& init_sample,
                                stan::callbacks::logger& logger) {
    ++n_transition;
    stan::mcmc::sample result(init_sample);
    return result;
  }

  void get_sampler_param_names(std::vector<std::string>& names) {
    ++n_get_sampler_param_names;
  }

  void get_sampler_params(std::vector<double>& values) {
    ++n_get_sampler_params;
  }

  void write_sampler_state(stan::callbacks::writer& writer) {
    ++n_write_sampler_state;
  }

  void get_sampler_diagnostic_names(std::vector<std::string>& model_names,
                                    std::vector<std::string>& names) {
    ++n_get_sampler_diagnostic_names;
  }

  void get_sampler_diagnostics(std::vector<double>& values) {
    ++n_get_sampler_diagnostics;
  }
};

TEST_F(ServicesUtil, write_sample_names) {
  Eigen::VectorXd x = Eigen::VectorXd::Zero(2);
  stan::mcmc::sample sample(x, 1, 2);
  mock_sampler sampler;

  mcmc_writer.write_sample_names(sample, sampler, model);
  EXPECT_EQ(1, sample_writer.call_count());
  EXPECT_EQ(1, sample_writer.call_count("vector_string"));
  EXPECT_EQ(0, diagnostic_writer.call_count());
  EXPECT_EQ(0, logger.call_count());

  EXPECT_EQ(2, mcmc_writer.num_sample_params_);
  EXPECT_EQ(0, mcmc_writer.num_sampler_params_);
  EXPECT_EQ(5, mcmc_writer.num_model_params_);
}

TEST_F(ServicesUtil, write_sample_params) {
  boost::ecuyer1988 rng = stan::services::util::create_rng(0, 1);
  Eigen::VectorXd x = Eigen::VectorXd::Zero(2);
  stan::mcmc::sample sample(x, 1, 2);
  mock_sampler sampler;

  mcmc_writer.write_sample_params(rng, sample, sampler, model);
  EXPECT_EQ(1, sample_writer.call_count());
  EXPECT_EQ(1, sample_writer.call_count("vector_double"));
  EXPECT_EQ(0, diagnostic_writer.call_count());
  EXPECT_EQ(0, logger.call_count());
}

TEST_F(ServicesUtil, write_adapt_finish) {
  mock_sampler sampler;

  mcmc_writer.write_adapt_finish(sampler);
  EXPECT_EQ(1, sample_writer.call_count());
  EXPECT_EQ(1, sample_writer.call_count("string"));
  EXPECT_EQ(0, diagnostic_writer.call_count());
  EXPECT_EQ(0, logger.call_count());
}

TEST_F(ServicesUtil, write_diagnostic_names) {
  Eigen::VectorXd x = Eigen::VectorXd::Zero(2);
  stan::mcmc::sample sample(x, 1, 2);
  mock_sampler sampler;

  mcmc_writer.write_diagnostic_names(sample, sampler, model);
  EXPECT_EQ(0, sample_writer.call_count());
  EXPECT_EQ(1, diagnostic_writer.call_count());
  EXPECT_EQ(1, diagnostic_writer.call_count("vector_string"));
  EXPECT_EQ(0, logger.call_count());
}

TEST_F(ServicesUtil, write_diagnostic_params) {
  Eigen::VectorXd x = Eigen::VectorXd::Zero(2);
  stan::mcmc::sample sample(x, 1, 2);
  mock_sampler sampler;

  mcmc_writer.write_diagnostic_params(sample, sampler);
  EXPECT_EQ(0, sample_writer.call_count());
  EXPECT_EQ(1, diagnostic_writer.call_count());
  EXPECT_EQ(1, diagnostic_writer.call_count("vector_double"));
  EXPECT_EQ(0, logger.call_count());
}

TEST_F(ServicesUtil, internal_write_timing) {
  stan::test::unit::instrumented_writer writer;
  mcmc_writer.write_timing(0, 0, writer);
  EXPECT_EQ(5, writer.call_count());
  EXPECT_EQ(3, writer.call_count("string"));
  EXPECT_EQ(2, writer.call_count("empty"));
}

TEST_F(ServicesUtil, write_timing) {
  mcmc_writer.write_timing(0, 0);
  EXPECT_EQ(5, sample_writer.call_count());
  EXPECT_EQ(3, sample_writer.call_count("string"));
  EXPECT_EQ(2, sample_writer.call_count("empty"));
  EXPECT_EQ(5, diagnostic_writer.call_count());
  EXPECT_EQ(3, diagnostic_writer.call_count("string"));
  EXPECT_EQ(2, diagnostic_writer.call_count("empty"));
  EXPECT_EQ(5, logger.call_count());
  EXPECT_EQ(5, logger.call_count_info());
}

TEST_F(ServicesUtil, throwing_model__write_sample_parameters) {
  boost::ecuyer1988 rng = stan::services::util::create_rng(0, 1);
  Eigen::VectorXd x = Eigen::VectorXd::Zero(2);
  stan::mcmc::sample sample(x, 1, 2);
  mock_sampler sampler;

  mcmc_writer.write_sample_names(sample, sampler, throwing_model);
  ASSERT_EQ(5, mcmc_writer.num_model_params_);

  mcmc_writer.write_sample_params(rng, sample, sampler, throwing_model);
  EXPECT_EQ(2, sample_writer.call_count());
  EXPECT_EQ(1, sample_writer.call_count("vector_double"));
  EXPECT_EQ(0, diagnostic_writer.call_count());
  EXPECT_EQ(1, logger.call_count());

  std::vector<std::vector<double>> values
      = sample_writer.vector_double_values();
  ASSERT_EQ(1, values.size());
  ASSERT_EQ(mcmc_writer.num_sample_params_ + mcmc_writer.num_sampler_params_
                + mcmc_writer.num_model_params_,
            values[0].size());

  for (size_t i = 0;
       i < mcmc_writer.num_sample_params_ + mcmc_writer.num_sampler_params_;
       ++i) {
    EXPECT_FALSE(std::isnan(values[0][i]));
  }

  for (size_t i
       = mcmc_writer.num_sample_params_ + mcmc_writer.num_sampler_params_;
       i < values[0].size(); ++i) {
    EXPECT_TRUE(std::isnan(values[0][i]));
  }
}
<|endoftext|>


<commit_before>// h5wrap.cpp

#include "h5wrap.h"

/*
 *  Index into an hdf5 array.
 */

template <typename T>
T h5wrap::get_array_index(H5::DataSet * ds, int n, H5::DataType dt)
{
    H5::DataSpace array_space = (*ds).getSpace();

    hsize_t count  [1] = {1};
    hsize_t offset [1] = {n};

    //Handle negative indices
    if (n < 0)
        offset[0] = offset[0] + array_space.getSimpleExtentNpoints();

    //If still out of range we have a problem
    if (offset[0] < 0 || array_space.getSimpleExtentNpoints() <= offset[0])
        throw h5wrap::HDF5BoundsError();

    array_space.selectHyperslab(H5S_SELECT_SET, count, offset);

    //Set memmory hyperspace
    hsize_t dimsm[1] = {1};
    H5::DataSpace memspace(1, dimsm);

    hsize_t count_out  [1] = {1};
    hsize_t offset_out [1] = {0};

    memspace.selectHyperslab(H5S_SELECT_SET, count_out, offset_out);

    T data_out [1];
    (*ds).read(data_out, dt, memspace, array_space);

    return data_out[0];
};

template int h5wrap::get_array_index(H5::DataSet *, int, H5::DataType);
template double h5wrap::get_array_index(H5::DataSet *, int, H5::DataType);

/*
 *  Convert hdf5 array to C++ set.
 */

template <typename T>
std::set<T> h5wrap::h5_array_to_cpp_set(H5::H5File * h5_file, std::string data_path, H5::DataType dt)
{
    // Init
    std::set<T> cpp_set = std::set<T>();
    hsize_t arr_len[1];

    H5::DataSet h5_arr = (*h5_file).openDataSet(data_path);

    // Initilize to dataspace, to find the indices we are looping over
    H5::DataSpace arr_space = h5_arr.getSpace();
    int arr_dim = arr_space.getSimpleExtentDims(arr_len, NULL);

    // Allocate memory buffer
    T * mem_arr = new T [arr_len[0]];

    // Read in data from file to memory
    h5_arr.read(mem_arr, dt);

    // Load new values into the set
    cpp_set.insert(&mem_arr[0], &mem_arr[arr_len[0]]);

    // Close out data set
    h5_arr.close();

    // Return set
    return cpp_set;
};

template std::set<int> h5wrap::h5_array_to_cpp_set(H5::H5File *, std::string, H5::DataType);
template std::set<double> h5wrap::h5_array_to_cpp_set(H5::H5File *, std::string, H5::DataType);

/*
 *  Convert hdf5 array to C++ vector.
 */

template <typename T>
std::vector<T> h5wrap::h5_array_to_cpp_vector_1d(H5::H5File * h5_file, std::string data_path, H5::DataType dt)
{
    // Init
    hsize_t arr_dims [1];
    H5::DataSet h5_arr = (*h5_file).openDataSet(data_path);

    // Initilize to dataspace, to find the indices we are looping over
    H5::DataSpace arr_space = h5_arr.getSpace();
    int arr_ndims = arr_space.getSimpleExtentDims(arr_dims, NULL);

    // Allocate memory buffer
    T mem_arr [arr_dims[0]];

    // Read in data from file to memory
    h5_arr.read(mem_arr, dt);

    // Initialize vector
    std::vector<T> cpp_vec;

    // Load new values into the vector
    cpp_vec.assign(mem_arr, mem_arr+arr_dims[0]);

    // Close out data set
    h5_arr.close();

    // Return vector of vectors
    return cpp_vec;
};

template std::vector<int> h5wrap::h5_array_to_cpp_vector_1d(H5::H5File *, std::string, H5::DataType);
template std::vector<double> h5wrap::h5_array_to_cpp_vector_1d(H5::H5File *, std::string, H5::DataType);

/*
 *  Convert hdf5 array to C++ vector of vectors.
 */

template <typename T>
std::vector< std::vector<T> > h5wrap::h5_array_to_cpp_vector_2d(H5::H5File * h5_file, std::string data_path, H5::DataType dt)
{
    // Init
    hsize_t arr_dims [2];
    H5::DataSet h5_arr = (*h5_file).openDataSet(data_path);

    // Initilize to dataspace, to find the indices we are looping over
    H5::DataSpace arr_space = h5_arr.getSpace();
    int arr_ndims = arr_space.getSimpleExtentDims(arr_dims, NULL);

    // Allocate memory buffer
    T mem_arr [arr_dims[0] * arr_dims[1]];

    // Read in data from file to memory
    // Have to read in as 1D array to get HDF5 and new keyword
    // to play nice with each other
    h5_arr.read(mem_arr, dt);

    // Initialize vector of vectors
    std::vector< std::vector<T> > cpp_vec (arr_dims[0], std::vector<T>(arr_dims[1]));

    // Load new values into the vector of vectors, using some indexing tricks
    for(int i = 0; i < arr_dims[0]; i++)
    {
        cpp_vec[i].assign(mem_arr+(i*arr_dims[1]), mem_arr+((i+1)*arr_dims[1]));
    };

    // Close out data set
    h5_arr.close();

    // Return vector of vectors
    return cpp_vec;
};

template std::vector< std::vector<int> > h5wrap::h5_array_to_cpp_vector_2d(H5::H5File *, std::string, H5::DataType);
template std::vector< std::vector<double> > h5wrap::h5_array_to_cpp_vector_2d(H5::H5File *, std::string, H5::DataType);

/*
 *  Convert hdf5 array to C++ vector of vectors of vectors.
 */

template <typename T>
std::vector< std::vector< std::vector<T> > > h5wrap::h5_array_to_cpp_vector_3d(H5::H5File * h5_file, std::string data_path, H5::DataType dt)
{
    // Init
    hsize_t arr_dims [3];
    H5::DataSet h5_arr = (*h5_file).openDataSet(data_path);

    // Initilize to dataspace, to find the indices we are looping over
    H5::DataSpace arr_space = h5_arr.getSpace();
    int arr_ndims = arr_space.getSimpleExtentDims(arr_dims, NULL);

    // Allocate memory buffer
    T mem_arr [arr_dims[0] * arr_dims[1] * arr_dims[2]];

    // Read in data from file to memory
    // Have to read in as 1D array to get HDF5 and new keyword
    // to play nice with each other
    h5_arr.read(mem_arr, dt);

    // Initialize vector of vectors of vectors
    std::vector< std::vector< std::vector<T> > > cpp_vec (arr_dims[0], std::vector< std::vector<T> >(arr_dims[1], std::vector<T>(arr_dims[2])));

    // Load new values into the vector of vectors of vectors, using some indexing tricks
    for(int i = 0; i < arr_dims[0]; i++)
    {
        for(int j = 0; j < arr_dims[j]; j++)
        {
            cpp_vec[i][j].assign(mem_arr+((i*arr_dims[1]*arr_dims[2]) + (j*arr_dims[2])), mem_arr+((i*arr_dims[1]*arr_dims[2]) + ((j+1)*arr_dims[2])));
        };
    };

    // Close out data set
    h5_arr.close();

    // Return vector of vectors
    return cpp_vec;
};

template std::vector< std::vector< std::vector<int> > > h5wrap::h5_array_to_cpp_vector_3d(H5::H5File * h5_file, std::string data_path, H5::DataType dt);
template std::vector< std::vector< std::vector<double> > > h5wrap::h5_array_to_cpp_vector_3d(H5::H5File * h5_file, std::string data_path, H5::DataType dt);

/*
 * Classes
 */

/*
 * HomogenousTypeTable
 */

template <typename T>
h5wrap::HomogenousTypeTable<T>::HomogenousTypeTable()
{
};

template <typename T>
h5wrap::HomogenousTypeTable<T>::HomogenousTypeTable(H5::H5File * h5_file, std::string data_path, H5::DataType dt)
{
    // Init
    H5::DataSet h5_set = (*h5_file).openDataSet(data_path);
    H5::DataSpace h5_space = h5_set.getSpace();
    H5::CompType h5_type = H5::CompType(h5_set);

    // set path
    path = data_path;

    // set shape
    shape[0] = h5_space.getSimpleExtentNpoints();
    shape[1] = h5_type.getNmembers();

    // set cols
    std::string * cols_buf = new std::string [shape[1]];
    for(int n = 0; n < shape[1]; n++)
    {
        cols_buf[n] = h5_type.getMemberName(n);
    };
    cols.assign(cols_buf, cols_buf+shape[1]);

    // set data
    H5::CompType col_type;
    T * col_buf;

    data.clear();
    for(int n = 0; n < shape[1]; n++)
    {
        // Make a compound data type of just this column
        col_type = H5::CompType(sizeof(T));
        col_type.insertMember(cols[n], 0, dt);

        // allocate space to read in this column
        col_buf = new T [shape[0]];

        // Read in this column
        h5_set.read(col_buf, col_type);

        // save this column as a vector in out data map
        data[cols[n]] = std::vector<T>(col_buf, col_buf+shape[0]);
    };

};

template <typename T>
std::vector<T> h5wrap::HomogenousTypeTable<T>::operator[](std::string col_name)
{
    return data[col_name];
};

template <typename T>
std::map<std::string, T> h5wrap::HomogenousTypeTable<T>::operator[](int m)
{
    // init row
    std::map<std::string, T> row = std::map<std::string, T>();

    // fill row values
    for(int n = 0; n < shape[1]; n++)
    {
        row[cols[n]] = data[cols[n]][m];
    };

    // return row map
    return row;
};

template class h5wrap::HomogenousTypeTable<int>;
template class h5wrap::HomogenousTypeTable<double>;
<commit_msg>Added sigma_s_gh<commit_after>// h5wrap.cpp

#include "h5wrap.h"

/*
 *  Index into an hdf5 array.
 */

template <typename T>
T h5wrap::get_array_index(H5::DataSet * ds, int n, H5::DataType dt)
{
    H5::DataSpace array_space = (*ds).getSpace();

    hsize_t count  [1] = {1};
    hsize_t offset [1] = {n};

    //Handle negative indices
    if (n < 0)
        offset[0] = offset[0] + array_space.getSimpleExtentNpoints();

    //If still out of range we have a problem
    if (offset[0] < 0 || array_space.getSimpleExtentNpoints() <= offset[0])
        throw h5wrap::HDF5BoundsError();

    array_space.selectHyperslab(H5S_SELECT_SET, count, offset);

    //Set memmory hyperspace
    hsize_t dimsm[1] = {1};
    H5::DataSpace memspace(1, dimsm);

    hsize_t count_out  [1] = {1};
    hsize_t offset_out [1] = {0};

    memspace.selectHyperslab(H5S_SELECT_SET, count_out, offset_out);

    T data_out [1];
    (*ds).read(data_out, dt, memspace, array_space);

    return data_out[0];
};

template int h5wrap::get_array_index(H5::DataSet *, int, H5::DataType);
template double h5wrap::get_array_index(H5::DataSet *, int, H5::DataType);

/*
 *  Convert hdf5 array to C++ set.
 */

template <typename T>
std::set<T> h5wrap::h5_array_to_cpp_set(H5::H5File * h5_file, std::string data_path, H5::DataType dt)
{
    // Init
    std::set<T> cpp_set = std::set<T>();
    hsize_t arr_len[1];

    H5::DataSet h5_arr = (*h5_file).openDataSet(data_path);

    // Initilize to dataspace, to find the indices we are looping over
    H5::DataSpace arr_space = h5_arr.getSpace();
    int arr_dim = arr_space.getSimpleExtentDims(arr_len, NULL);

    // Allocate memory buffer
    T * mem_arr = new T [arr_len[0]];

    // Read in data from file to memory
    h5_arr.read(mem_arr, dt);

    // Load new values into the set
    cpp_set.insert(&mem_arr[0], &mem_arr[arr_len[0]]);

    // Close out data set
    h5_arr.close();

    // Return set
    return cpp_set;
};

template std::set<int> h5wrap::h5_array_to_cpp_set(H5::H5File *, std::string, H5::DataType);
template std::set<double> h5wrap::h5_array_to_cpp_set(H5::H5File *, std::string, H5::DataType);

/*
 *  Convert hdf5 array to C++ vector.
 */

template <typename T>
std::vector<T> h5wrap::h5_array_to_cpp_vector_1d(H5::H5File * h5_file, std::string data_path, H5::DataType dt)
{
    // Init
    hsize_t arr_dims [1];
    H5::DataSet h5_arr = (*h5_file).openDataSet(data_path);

    // Initilize to dataspace, to find the indices we are looping over
    H5::DataSpace arr_space = h5_arr.getSpace();
    int arr_ndims = arr_space.getSimpleExtentDims(arr_dims, NULL);

    // Allocate memory buffer
    T mem_arr [arr_dims[0]];

    // Read in data from file to memory
    h5_arr.read(mem_arr, dt);

    // Initialize vector
    std::vector<T> cpp_vec;

    // Load new values into the vector
    cpp_vec.assign(mem_arr, mem_arr+arr_dims[0]);

    // Close out data set
    h5_arr.close();

    // Return vector of vectors
    return cpp_vec;
};

template std::vector<int> h5wrap::h5_array_to_cpp_vector_1d(H5::H5File *, std::string, H5::DataType);
template std::vector<double> h5wrap::h5_array_to_cpp_vector_1d(H5::H5File *, std::string, H5::DataType);

/*
 *  Convert hdf5 array to C++ vector of vectors.
 */

template <typename T>
std::vector< std::vector<T> > h5wrap::h5_array_to_cpp_vector_2d(H5::H5File * h5_file, std::string data_path, H5::DataType dt)
{
    // Init
    hsize_t arr_dims [2];
    H5::DataSet h5_arr = (*h5_file).openDataSet(data_path);

    // Initilize to dataspace, to find the indices we are looping over
    H5::DataSpace arr_space = h5_arr.getSpace();
    int arr_ndims = arr_space.getSimpleExtentDims(arr_dims, NULL);

    // Allocate memory buffer
    T mem_arr [arr_dims[0] * arr_dims[1]];

    // Read in data from file to memory
    // Have to read in as 1D array to get HDF5 and new keyword
    // to play nice with each other
    h5_arr.read(mem_arr, dt);

    // Initialize vector of vectors
    std::vector< std::vector<T> > cpp_vec (arr_dims[0], std::vector<T>(arr_dims[1]));

    // Load new values into the vector of vectors, using some indexing tricks
    for(int i = 0; i < arr_dims[0]; i++)
    {
        cpp_vec[i].assign(mem_arr+(i*arr_dims[1]), mem_arr+((i+1)*arr_dims[1]));
    };

    // Close out data set
    h5_arr.close();

    // Return vector of vectors
    return cpp_vec;
};

template std::vector< std::vector<int> > h5wrap::h5_array_to_cpp_vector_2d(H5::H5File *, std::string, H5::DataType);
template std::vector< std::vector<double> > h5wrap::h5_array_to_cpp_vector_2d(H5::H5File *, std::string, H5::DataType);

/*
 *  Convert hdf5 array to C++ vector of vectors of vectors.
 */

template <typename T>
std::vector< std::vector< std::vector<T> > > h5wrap::h5_array_to_cpp_vector_3d(H5::H5File * h5_file, std::string data_path, H5::DataType dt)
{
    // Init
    hsize_t arr_dims [3];
    H5::DataSet h5_arr = (*h5_file).openDataSet(data_path);

    // Initilize to dataspace, to find the indices we are looping over
    H5::DataSpace arr_space = h5_arr.getSpace();
    int arr_ndims = arr_space.getSimpleExtentDims(arr_dims, NULL);

    // Allocate memory buffer
    T mem_arr [arr_dims[0] * arr_dims[1] * arr_dims[2]];

    // Read in data from file to memory
    // Have to read in as 1D array to get HDF5 and new keyword
    // to play nice with each other
    h5_arr.read(mem_arr, dt);

    // Initialize vector of vectors of vectors
    std::vector< std::vector< std::vector<T> > > cpp_vec (arr_dims[0], std::vector< std::vector<T> >(arr_dims[1], std::vector<T>(arr_dims[2])));

    // Load new values into the vector of vectors of vectors, using some indexing tricks
    for(int i = 0; i < arr_dims[0]; i++)
    {
        for(int j = 0; j < arr_dims[1]; j++)
        {
            cpp_vec[i][j].assign(mem_arr+((i*arr_dims[1]*arr_dims[2]) + (j*arr_dims[2])), mem_arr+((i*arr_dims[1]*arr_dims[2]) + ((j+1)*arr_dims[2])));
        };
    };

    // Close out data set
    h5_arr.close();

    // Return vector of vectors
    return cpp_vec;
};

template std::vector< std::vector< std::vector<int> > > h5wrap::h5_array_to_cpp_vector_3d(H5::H5File * h5_file, std::string data_path, H5::DataType dt);
template std::vector< std::vector< std::vector<double> > > h5wrap::h5_array_to_cpp_vector_3d(H5::H5File * h5_file, std::string data_path, H5::DataType dt);

/*
 * Classes
 */

/*
 * HomogenousTypeTable
 */

template <typename T>
h5wrap::HomogenousTypeTable<T>::HomogenousTypeTable()
{
};

template <typename T>
h5wrap::HomogenousTypeTable<T>::HomogenousTypeTable(H5::H5File * h5_file, std::string data_path, H5::DataType dt)
{
    // Init
    H5::DataSet h5_set = (*h5_file).openDataSet(data_path);
    H5::DataSpace h5_space = h5_set.getSpace();
    H5::CompType h5_type = H5::CompType(h5_set);

    // set path
    path = data_path;

    // set shape
    shape[0] = h5_space.getSimpleExtentNpoints();
    shape[1] = h5_type.getNmembers();

    // set cols
    std::string * cols_buf = new std::string [shape[1]];
    for(int n = 0; n < shape[1]; n++)
    {
        cols_buf[n] = h5_type.getMemberName(n);
    };
    cols.assign(cols_buf, cols_buf+shape[1]);

    // set data
    H5::CompType col_type;
    T * col_buf;

    data.clear();
    for(int n = 0; n < shape[1]; n++)
    {
        // Make a compound data type of just this column
        col_type = H5::CompType(sizeof(T));
        col_type.insertMember(cols[n], 0, dt);

        // allocate space to read in this column
        col_buf = new T [shape[0]];

        // Read in this column
        h5_set.read(col_buf, col_type);

        // save this column as a vector in out data map
        data[cols[n]] = std::vector<T>(col_buf, col_buf+shape[0]);
    };

};

template <typename T>
std::vector<T> h5wrap::HomogenousTypeTable<T>::operator[](std::string col_name)
{
    return data[col_name];
};

template <typename T>
std::map<std::string, T> h5wrap::HomogenousTypeTable<T>::operator[](int m)
{
    // init row
    std::map<std::string, T> row = std::map<std::string, T>();

    // fill row values
    for(int n = 0; n < shape[1]; n++)
    {
        row[cols[n]] = data[cols[n]][m];
    };

    // return row map
    return row;
};

template class h5wrap::HomogenousTypeTable<int>;
template class h5wrap::HomogenousTypeTable<double>;
<|endoftext|>


<commit_before>#include <cprel/cprel.hh>

namespace MPG { namespace CPRel {
/*
 * Value selection classes
 *
 */

// Select smallest value
    class ValMin : public Gecode::ValSelBase<CPRel::CPRelView,int> {
    public:
      ValMin(void) {}
      ValMin(Gecode::Space& home, const Gecode::ValBranchOptions& vbo)
	: Gecode::ValSelBase<CPRel::CPRelView,int>(home,vbo) {}
      int val(Gecode::Space&, View x) const {
	return x.min();
      }
      ModEvent tell(Gecode::Space& home, unsigned int a, CPRel::CPRelView x, int n) {
	return (a == 0) ? x.lq(home,n) : x.gq(home,n+1);
      }
};
  }

  /*
   * Branching post function
   *
   */
  // Branch by selecting the first unassigned variable, assigning its
  // smallest value first
  void branch(Gecode::Home home, const CPRelVarArgs& x) {
    using namespace CPRel;
    if (home.failed()) return;
    Gecode::ViewArray<CPRel::CPRelView> y(home,x);
    Gecode::ViewSelNone<CPRel::CPRelView> sn; ValMin vm;
    Gecode::ViewValBrancher<
      Gecode::ViewSelNone<CPRel::CPRelView>,ValMin>::post(home,y,sn,vm);
  }
}

// Register a disposer for variable implementations
Gecode::VarImpDisposer<MPG::CPRel::CPRelVarImp> d;
<commit_msg>Forgot to commit in the last<commit_after>#include <cprel/cprel.hh>

namespace MPG { namespace CPRel {
/*
 * Value selection classes
 *
 */

// Select smallest value
    class ValMin : public Gecode::ValSelBase<CPRel::CPRelView,int> {
    public:
      ValMin(void) {}
      ValMin(Gecode::Space& home, const Gecode::ValBranchOptions& vbo)
	: Gecode::ValSelBase<CPRel::CPRelView,int>(home,vbo) {}
      int val(Gecode::Space&, View x) const {
	return x.min();
      }
      ModEvent tell(Gecode::Space& home, unsigned int a, CPRel::CPRelView x, int n) {
	return (a == 0) ? x.lq(home,n) : x.gq(home,n+1);
      }
    };
  }

  /*
   * Branching post function
   *
   */
  // Branch by selecting the first unassigned variable, assigning its
  // smallest value first
  void branch(Gecode::Home home, const CPRelVarArgs& x) {
    using namespace CPRel;
    if (home.failed()) return;
    Gecode::ViewArray<CPRel::CPRelView> y(home,x);
    Gecode::ViewSelNone<CPRel::CPRelView> sn; ValMin vm;
    Gecode::ViewValBrancher<
      Gecode::ViewSelNone<CPRel::CPRelView>,ValMin>::post(home,y,sn,vm);
  }
}

// Register a disposer for variable implementations
Gecode::VarImpDisposer<MPG::CPRel::CPRelVarImp> d;
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <seastar/core/shared_ptr.hh>

#include "tuples.hh"
#include "types/list.hh"

namespace cql3 {

lw_shared_ptr<column_specification>
tuples::component_spec_of(const column_specification& column, size_t component) {
    return make_lw_shared<column_specification>(
            column.ks_name,
            column.cf_name,
            ::make_shared<column_identifier>(format("{}[{:d}]", column.name, component), true),
            static_pointer_cast<const tuple_type_impl>(column.type->underlying_type())->type(component));
}

shared_ptr<term>
tuples::literal::prepare(database& db, const sstring& keyspace, lw_shared_ptr<column_specification> receiver) const {
    validate_assignable_to(db, keyspace, *receiver);
    std::vector<shared_ptr<term>> values;
    bool all_terminal = true;
    for (size_t i = 0; i < _elements.size(); ++i) {
        auto&& value = _elements[i]->prepare(db, keyspace, component_spec_of(*receiver, i));
        if (dynamic_pointer_cast<non_terminal>(value)) {
            all_terminal = false;
        }
        values.push_back(std::move(value));
    }
    delayed_value value(static_pointer_cast<const tuple_type_impl>(receiver->type), values);
    if (all_terminal) {
        return value.bind(query_options::DEFAULT);
    } else {
        return make_shared<delayed_value>(std::move(value));
    }
}

shared_ptr<term>
tuples::literal::prepare(database& db, const sstring& keyspace, const std::vector<lw_shared_ptr<column_specification>>& receivers) const {
    if (_elements.size() != receivers.size()) {
        throw exceptions::invalid_request_exception(format("Expected {:d} elements in value tuple, but got {:d}: {}", receivers.size(), _elements.size(), *this));
    }

    std::vector<shared_ptr<term>> values;
    std::vector<data_type> types;
    bool all_terminal = true;
    for (size_t i = 0; i < _elements.size(); ++i) {
        auto&& t = _elements[i]->prepare(db, keyspace, receivers[i]);
        if (dynamic_pointer_cast<non_terminal>(t)) {
            all_terminal = false;
        }
        values.push_back(t);
        types.push_back(receivers[i]->type);
    }
    delayed_value value(tuple_type_impl::get_instance(std::move(types)), std::move(values));
    if (all_terminal) {
        return value.bind(query_options::DEFAULT);
    } else {
        return make_shared<delayed_value>(std::move(value));
    }
}

tuples::in_value
tuples::in_value::from_serialized(const fragmented_temporary_buffer::view& value_view, const list_type_impl& type, const query_options& options) {
    try {
        // Collections have this small hack that validate cannot be called on a serialized object,
        // but the deserialization does the validation (so we're fine).
      return with_linearized(value_view, [&] (bytes_view value) {
        auto l = value_cast<list_type_impl::native_type>(type.deserialize(value, options.get_cql_serialization_format()));
        auto ttype = dynamic_pointer_cast<const tuple_type_impl>(type.get_elements_type());
        assert(ttype);

        std::vector<std::vector<bytes_opt>> elements;
        elements.reserve(l.size());
        for (auto&& e : l) {
            elements.emplace_back(to_bytes_opt_vec(ttype->split(ttype->decompose(e))));
        }
        return tuples::in_value(elements);
      });
    } catch (marshal_exception& e) {
        throw exceptions::invalid_request_exception(e.what());
    }
}

lw_shared_ptr<column_specification>
tuples::in_raw::make_in_receiver(const std::vector<lw_shared_ptr<column_specification>>& receivers) {
    std::vector<data_type> types;
    types.reserve(receivers.size());
    sstring in_name = "in(";
    for (auto&& receiver : receivers) {
        in_name += receiver->name->text();
        if (receiver != receivers.back()) {
            in_name += ",";
        }

        if (receiver->type->is_collection() && receiver->type->is_multi_cell()) {
            throw exceptions::invalid_request_exception("Non-frozen collection columns do not support IN relations");
        }

        types.emplace_back(receiver->type);
    }
    in_name += ")";

    auto identifier = ::make_shared<column_identifier>(in_name, true);
    auto type = tuple_type_impl::get_instance(types);
    return make_lw_shared<column_specification>(receivers.front()->ks_name, receivers.front()->cf_name, identifier, list_type_impl::get_instance(type, false));
}

tuples::in_marker::in_marker(int32_t bind_index, lw_shared_ptr<column_specification> receiver)
    : abstract_marker(bind_index, std::move(receiver))
{
    assert(dynamic_pointer_cast<const list_type_impl>(_receiver->type));
}

shared_ptr<terminal> tuples::in_marker::bind(const query_options& options) {
    const auto& value = options.get_value_at(_bind_index);
    if (value.is_null()) {
        return nullptr;
    } else if (value.is_unset_value()) {
        throw exceptions::invalid_request_exception(format("Invalid unset value for tuple {}", _receiver->name->text()));
    } else {
        auto& type = static_cast<const list_type_impl&>(*_receiver->type);
        auto& elem_type = static_cast<const tuple_type_impl&>(*type.get_elements_type());
        try {
            with_linearized(*value, [&] (bytes_view v) {
                type.validate(v, options.get_cql_serialization_format());
                auto l = value_cast<list_type_impl::native_type>(type.deserialize(v, options.get_cql_serialization_format()));

                for (auto&& element : l) {
                    elem_type.validate(elem_type.decompose(element), options.get_cql_serialization_format());
                }
            });
        } catch (marshal_exception& e) {
            throw exceptions::invalid_request_exception(e.what());
        }
        return make_shared<tuples::in_value>(tuples::in_value::from_serialized(*value, type, options));
    }
}

}
<commit_msg>cql3: tuples: don't linearize in in_value::from_serialized<commit_after>/*
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <seastar/core/shared_ptr.hh>

#include "tuples.hh"
#include "types/list.hh"

namespace cql3 {

lw_shared_ptr<column_specification>
tuples::component_spec_of(const column_specification& column, size_t component) {
    return make_lw_shared<column_specification>(
            column.ks_name,
            column.cf_name,
            ::make_shared<column_identifier>(format("{}[{:d}]", column.name, component), true),
            static_pointer_cast<const tuple_type_impl>(column.type->underlying_type())->type(component));
}

shared_ptr<term>
tuples::literal::prepare(database& db, const sstring& keyspace, lw_shared_ptr<column_specification> receiver) const {
    validate_assignable_to(db, keyspace, *receiver);
    std::vector<shared_ptr<term>> values;
    bool all_terminal = true;
    for (size_t i = 0; i < _elements.size(); ++i) {
        auto&& value = _elements[i]->prepare(db, keyspace, component_spec_of(*receiver, i));
        if (dynamic_pointer_cast<non_terminal>(value)) {
            all_terminal = false;
        }
        values.push_back(std::move(value));
    }
    delayed_value value(static_pointer_cast<const tuple_type_impl>(receiver->type), values);
    if (all_terminal) {
        return value.bind(query_options::DEFAULT);
    } else {
        return make_shared<delayed_value>(std::move(value));
    }
}

shared_ptr<term>
tuples::literal::prepare(database& db, const sstring& keyspace, const std::vector<lw_shared_ptr<column_specification>>& receivers) const {
    if (_elements.size() != receivers.size()) {
        throw exceptions::invalid_request_exception(format("Expected {:d} elements in value tuple, but got {:d}: {}", receivers.size(), _elements.size(), *this));
    }

    std::vector<shared_ptr<term>> values;
    std::vector<data_type> types;
    bool all_terminal = true;
    for (size_t i = 0; i < _elements.size(); ++i) {
        auto&& t = _elements[i]->prepare(db, keyspace, receivers[i]);
        if (dynamic_pointer_cast<non_terminal>(t)) {
            all_terminal = false;
        }
        values.push_back(t);
        types.push_back(receivers[i]->type);
    }
    delayed_value value(tuple_type_impl::get_instance(std::move(types)), std::move(values));
    if (all_terminal) {
        return value.bind(query_options::DEFAULT);
    } else {
        return make_shared<delayed_value>(std::move(value));
    }
}

tuples::in_value
tuples::in_value::from_serialized(const fragmented_temporary_buffer::view& value_view, const list_type_impl& type, const query_options& options) {
    try {
        // Collections have this small hack that validate cannot be called on a serialized object,
        // but the deserialization does the validation (so we're fine).
        auto l = value_cast<list_type_impl::native_type>(type.deserialize(value_view, options.get_cql_serialization_format()));
        auto ttype = dynamic_pointer_cast<const tuple_type_impl>(type.get_elements_type());
        assert(ttype);

        std::vector<std::vector<bytes_opt>> elements;
        elements.reserve(l.size());
        for (auto&& e : l) {
            elements.emplace_back(to_bytes_opt_vec(ttype->split(ttype->decompose(e))));
        }
        return tuples::in_value(elements);
    } catch (marshal_exception& e) {
        throw exceptions::invalid_request_exception(e.what());
    }
}

lw_shared_ptr<column_specification>
tuples::in_raw::make_in_receiver(const std::vector<lw_shared_ptr<column_specification>>& receivers) {
    std::vector<data_type> types;
    types.reserve(receivers.size());
    sstring in_name = "in(";
    for (auto&& receiver : receivers) {
        in_name += receiver->name->text();
        if (receiver != receivers.back()) {
            in_name += ",";
        }

        if (receiver->type->is_collection() && receiver->type->is_multi_cell()) {
            throw exceptions::invalid_request_exception("Non-frozen collection columns do not support IN relations");
        }

        types.emplace_back(receiver->type);
    }
    in_name += ")";

    auto identifier = ::make_shared<column_identifier>(in_name, true);
    auto type = tuple_type_impl::get_instance(types);
    return make_lw_shared<column_specification>(receivers.front()->ks_name, receivers.front()->cf_name, identifier, list_type_impl::get_instance(type, false));
}

tuples::in_marker::in_marker(int32_t bind_index, lw_shared_ptr<column_specification> receiver)
    : abstract_marker(bind_index, std::move(receiver))
{
    assert(dynamic_pointer_cast<const list_type_impl>(_receiver->type));
}

shared_ptr<terminal> tuples::in_marker::bind(const query_options& options) {
    const auto& value = options.get_value_at(_bind_index);
    if (value.is_null()) {
        return nullptr;
    } else if (value.is_unset_value()) {
        throw exceptions::invalid_request_exception(format("Invalid unset value for tuple {}", _receiver->name->text()));
    } else {
        auto& type = static_cast<const list_type_impl&>(*_receiver->type);
        auto& elem_type = static_cast<const tuple_type_impl&>(*type.get_elements_type());
        try {
            with_linearized(*value, [&] (bytes_view v) {
                type.validate(v, options.get_cql_serialization_format());
                auto l = value_cast<list_type_impl::native_type>(type.deserialize(v, options.get_cql_serialization_format()));

                for (auto&& element : l) {
                    elem_type.validate(elem_type.decompose(element), options.get_cql_serialization_format());
                }
            });
        } catch (marshal_exception& e) {
            throw exceptions::invalid_request_exception(e.what());
        }
        return make_shared<tuples::in_value>(tuples::in_value::from_serialized(*value, type, options));
    }
}

}
<|endoftext|>


<commit_before>/*
Copyright (c) 2014-2019 AscEmu Team <http://www.ascemu.org>
This file is released under the MIT license. See README-MIT for more information.
*/

#include "StdAfx.h"
#include "Management/GameEvent.h"
#include "Chat/ChatHandler.hpp"

//.event list
bool ChatHandler::HandleEventListEvents(const char* /*args*/, WorldSession* m_session)
{
    SystemMessage(m_session, "--- Current Active Events ---");
    auto eventList = sGameEventMgr.mGameEvents;
    for (auto gameEventPair : eventList)
    {
        auto gameEvent = gameEventPair.second;
        if (gameEvent->GetState() == GAMEEVENT_ACTIVE)
        {
            SystemMessage(m_session, "%u - %s", gameEvent->event_id, gameEvent->description.c_str());
        }
        else if (gameEvent->GetState() == GAMEEVENT_ACTIVE_FORCED)
        {
            SystemMessage(m_session, "[Force Activated] %u - %s", gameEvent->event_id, gameEvent->description.c_str());
        }
    }
    SystemMessage(m_session, "--- End List ---");
    return true;
}

//.event start
bool ChatHandler::HandleEventStartEvent(const char* args, WorldSession* m_session)
{
    uint32 eventid = atoi(args);
    if (eventid == 0)
    {
        SystemMessage(m_session, "Invalid argument: %s", args);
        return false;
    }

    for (auto eventPair : sGameEventMgr.mGameEvents)
    {
        auto gameEvent = eventPair.second;
        if (gameEvent->event_id == eventid)
        {
            SystemMessage(m_session, "Force starting event %u (%s)", gameEvent->event_id, gameEvent->description.c_str());
            gameEvent->StartEvent(true);
            return true;
        }
    }

    SystemMessage(m_session, "Game event with ID %u not found", eventid);
    return false;
}

//.event stop
bool ChatHandler::HandleEventStopEvent(const char* args, WorldSession* m_session)
{
    uint32 eventid = atoi(args);
    if (eventid == 0)
    {
        SystemMessage(m_session, "Invalid argument: %s", args);
        return false;
    }

    for (auto eventPair : sGameEventMgr.mGameEvents)
    {
        auto gameEvent = eventPair.second;
        if (gameEvent->event_id == eventid)
        {
            SystemMessage(m_session, "Force stopping event %u (%s)", gameEvent->event_id, gameEvent->description.c_str());
            gameEvent->StopEvent(true);
            return true;
        }
    }

    SystemMessage(m_session, "Game event with ID %u not found", eventid);
    return false;
}

//.event reset
bool ChatHandler::HandleEventResetEvent(const char* args, WorldSession* m_session)
{
    uint32 eventid = atoi(args);
    if (eventid == 0)
    {
        SystemMessage(m_session, "Invalid argument: %s", args);
        return false;
    }

    for (auto eventPair : sGameEventMgr.mGameEvents)
    {
        auto gameEvent = eventPair.second;
        if (gameEvent->event_id == eventid)
        {
            SystemMessage(m_session, "Clearing flags for event %u (%s)", gameEvent->event_id, gameEvent->description.c_str());
            if (gameEvent->GetState() == GAMEEVENT_ACTIVE_FORCED)
                gameEvent->SetState(GAMEEVENT_ACTIVE);
            else
                gameEvent->SetState(GAMEEVENT_INACTIVE);
            return true;
        }
    }

    SystemMessage(m_session, "Game event with ID %u not found", eventid);
    return false;
}

//.event reload
bool ChatHandler::HandleEventReloadAllEvents(const char* /*args*/, WorldSession* m_session)
{
    SystemMessage(m_session, "Beginning reload of all game events");
    auto start = time(0);

    // Stop all events, then clear storage
    for (auto eventPair : sGameEventMgr.mGameEvents)
    {
        auto gameEvent = eventPair.second;
        gameEvent->StopEvent();
        delete gameEvent;
    }

    // Clear game events
    sGameEventMgr.mGameEvents.clear();

    // Reload events from DB
    sGameEventMgr.LoadFromDB();

    SystemMessage(m_session, "Reloaded all game events in %u ms", time(0)-start);
    return true;
}
<commit_msg>Resolved CID 351818 (Invalid type in argument to printf format specifier)<commit_after>/*
Copyright (c) 2014-2019 AscEmu Team <http://www.ascemu.org>
This file is released under the MIT license. See README-MIT for more information.
*/

#include "StdAfx.h"
#include "Management/GameEvent.h"
#include "Chat/ChatHandler.hpp"

//.event list
bool ChatHandler::HandleEventListEvents(const char* /*args*/, WorldSession* m_session)
{
    SystemMessage(m_session, "--- Current Active Events ---");
    auto eventList = sGameEventMgr.mGameEvents;
    for (auto gameEventPair : eventList)
    {
        auto gameEvent = gameEventPair.second;
        if (gameEvent->GetState() == GAMEEVENT_ACTIVE)
        {
            SystemMessage(m_session, "%u - %s", gameEvent->event_id, gameEvent->description.c_str());
        }
        else if (gameEvent->GetState() == GAMEEVENT_ACTIVE_FORCED)
        {
            SystemMessage(m_session, "[Force Activated] %u - %s", gameEvent->event_id, gameEvent->description.c_str());
        }
    }
    SystemMessage(m_session, "--- End List ---");
    return true;
}

//.event start
bool ChatHandler::HandleEventStartEvent(const char* args, WorldSession* m_session)
{
    uint32 eventid = atoi(args);
    if (eventid == 0)
    {
        SystemMessage(m_session, "Invalid argument: %s", args);
        return false;
    }

    for (auto eventPair : sGameEventMgr.mGameEvents)
    {
        auto gameEvent = eventPair.second;
        if (gameEvent->event_id == eventid)
        {
            SystemMessage(m_session, "Force starting event %u (%s)", gameEvent->event_id, gameEvent->description.c_str());
            gameEvent->StartEvent(true);
            return true;
        }
    }

    SystemMessage(m_session, "Game event with ID %u not found", eventid);
    return false;
}

//.event stop
bool ChatHandler::HandleEventStopEvent(const char* args, WorldSession* m_session)
{
    uint32 eventid = atoi(args);
    if (eventid == 0)
    {
        SystemMessage(m_session, "Invalid argument: %s", args);
        return false;
    }

    for (auto eventPair : sGameEventMgr.mGameEvents)
    {
        auto gameEvent = eventPair.second;
        if (gameEvent->event_id == eventid)
        {
            SystemMessage(m_session, "Force stopping event %u (%s)", gameEvent->event_id, gameEvent->description.c_str());
            gameEvent->StopEvent(true);
            return true;
        }
    }

    SystemMessage(m_session, "Game event with ID %u not found", eventid);
    return false;
}

//.event reset
bool ChatHandler::HandleEventResetEvent(const char* args, WorldSession* m_session)
{
    uint32 eventid = atoi(args);
    if (eventid == 0)
    {
        SystemMessage(m_session, "Invalid argument: %s", args);
        return false;
    }

    for (auto eventPair : sGameEventMgr.mGameEvents)
    {
        auto gameEvent = eventPair.second;
        if (gameEvent->event_id == eventid)
        {
            SystemMessage(m_session, "Clearing flags for event %u (%s)", gameEvent->event_id, gameEvent->description.c_str());
            if (gameEvent->GetState() == GAMEEVENT_ACTIVE_FORCED)
                gameEvent->SetState(GAMEEVENT_ACTIVE);
            else
                gameEvent->SetState(GAMEEVENT_INACTIVE);
            return true;
        }
    }

    SystemMessage(m_session, "Game event with ID %u not found", eventid);
    return false;
}

//.event reload
bool ChatHandler::HandleEventReloadAllEvents(const char* /*args*/, WorldSession* m_session)
{
    SystemMessage(m_session, "Beginning reload of all game events");
    auto startTime = Util::TimeNow();

    // Stop all events, then clear storage
    for (auto eventPair : sGameEventMgr.mGameEvents)
    {
        auto gameEvent = eventPair.second;
        gameEvent->StopEvent();
        delete gameEvent;
    }

    // Clear game events
    sGameEventMgr.mGameEvents.clear();

    // Reload events from DB
    sGameEventMgr.LoadFromDB();

    SystemMessage(m_session, "Reloaded all game events in %u ms", Util::GetTimeDifferenceToNow(startTime));
    return true;
}
<|endoftext|>