text:
namespace lslboost {
namespace container {
namespace container_detail {

template<class size_type>
struct hdr_offset_holder_t
{
   hdr_offset_holder_t(size_type offset = 0)
      : hdr_offset(offset)
   {}
   size_type hdr_offset;
};

template<class VoidPointer, class SizeType>
struct adaptive_pool_types
{
   typedef VoidPointer void_pointer;
   typedef typename bi::make_set_base_hook
      < bi::void_pointer<void_pointer>
      , bi::optimize_size<true>
      , bi::constant_time_size<false>
      , bi::link_mode<bi::normal_link> >::type multiset_hook_t;

   typedef hdr_offset_holder_t<SizeType> hdr_offset_holder;

   struct block_info_t
      :
         public hdr_offset_holder,
         public multiset_hook_t
   {
      typedef typename node_slist<void_pointer>::node_slist_t free_nodes_t;
      //An intrusive list of free node from this block
      free_nodes_t free_nodes;
      friend bool operator <(const block_info_t &l, const block_info_t &r)
      {
//      {  return l.free_nodes.size() < r.free_nodes.size();   }
         //Let's order blocks first by free nodes and then by address
         //so that highest address fully free blocks are deallocated.
         //This improves returning memory to the OS (trimming).
         const bool is_less  = l.free_nodes.size() < r.free_nodes.size();
         const bool is_equal = l.free_nodes.size() == r.free_nodes.size();
         return is_less || (is_equal && (&l < &r));
      }

      friend bool operator ==(const block_info_t &l, const block_info_t &r)
      {  return &l == &r;  }
   };
   typedef typename bi::make_multiset
      <block_info_t, bi::base_hook<multiset_hook_t> >::type  block_multiset_t;
};

template<class size_type>
inline size_type calculate_alignment
   ( size_type overhead_percent, size_type real_node_size
   , size_type hdr_size, size_type hdr_offset_size, size_type payload_per_allocation)
{
   //to-do: handle real_node_size != node_size
   const size_type divisor  = overhead_percent*real_node_size;
   const size_type dividend = hdr_offset_size*100;
   size_type elements_per_subblock = (dividend - 1)/divisor + 1;
   size_type candidate_power_of_2 =
      upper_power_of_2(elements_per_subblock*real_node_size + hdr_offset_size);
   bool overhead_satisfied = false;
   //Now calculate the wors-case overhead for a subblock
   const size_type max_subblock_overhead  = hdr_size + payload_per_allocation;
   while(!overhead_satisfied){
      elements_per_subblock = (candidate_power_of_2 - max_subblock_overhead)/real_node_size;
      const size_type overhead_size = candidate_power_of_2 - elements_per_subblock*real_node_size;
      if(overhead_size*100/candidate_power_of_2 < overhead_percent){
         overhead_satisfied = true;
      }
      else{
         candidate_power_of_2 <<= 1;
      }
   }
   return candidate_power_of_2;
}

template<class size_type>
inline void calculate_num_subblocks
   (size_type alignment, size_type real_node_size, size_type elements_per_block
   , size_type &num_subblocks, size_type &real_num_node, size_type overhead_percent
   , size_type hdr_size, size_type hdr_offset_size, size_type payload_per_allocation)
{
   size_type elements_per_subblock = (alignment - hdr_offset_size)/real_node_size;
   size_type possible_num_subblock = (elements_per_block - 1)/elements_per_subblock + 1;
   size_type hdr_subblock_elements = (alignment - hdr_size - payload_per_allocation)/real_node_size;
   while(((possible_num_subblock-1)*elements_per_subblock + hdr_subblock_elements) < elements_per_block){
      ++possible_num_subblock;
   }
   elements_per_subblock = (alignment - hdr_offset_size)/real_node_size;
   bool overhead_satisfied = false;
   while(!overhead_satisfied){
      const size_type total_data = (elements_per_subblock*(possible_num_subblock-1) + hdr_subblock_elements)*real_node_size;
      const size_type total_size = alignment*possible_num_subblock;
      if((total_size - total_data)*100/total_size < overhead_percent){
         overhead_satisfied = true;
      }
      else{
         ++possible_num_subblock;
      }
   }
   num_subblocks = possible_num_subblock;
   real_num_node = (possible_num_subblock-1)*elements_per_subblock + hdr_subblock_elements;
}

template<class SegmentManagerBase, bool AlignOnly = false>
class private_adaptive_node_pool_impl
{
   //Non-copyable
   private_adaptive_node_pool_impl();
   private_adaptive_node_pool_impl(const private_adaptive_node_pool_impl &);
   private_adaptive_node_pool_impl &operator=(const private_adaptive_node_pool_impl &);
   typedef private_adaptive_node_pool_impl this_type;

   typedef typename SegmentManagerBase::void_pointer void_pointer;
   static const typename SegmentManagerBase::
      size_type PayloadPerAllocation = SegmentManagerBase::PayloadPerAllocation;
   typedef bool_<AlignOnly>            IsAlignOnly;
   typedef true_                       AlignOnlyTrue;
   typedef false_                      AlignOnlyFalse;

   public:
   typedef typename node_slist<void_pointer>::node_t node_t;
   typedef typename node_slist<void_pointer>::node_slist_t free_nodes_t;
   typedef typename SegmentManagerBase::multiallocation_chain     multiallocation_chain;
   typedef typename SegmentManagerBase::size_type                 size_type;

   private:
   typedef typename adaptive_pool_types<void_pointer, size_type>::block_info_t      block_info_t;
   typedef typename adaptive_pool_types<void_pointer, size_type>::block_multiset_t  block_multiset_t;
   typedef typename block_multiset_t::iterator                                      block_iterator;
   typedef typename adaptive_pool_types<void_pointer, size_type>::hdr_offset_holder hdr_offset_holder;

   static const size_type MaxAlign = alignment_of<node_t>::value;
   static const size_type HdrSize  = ((sizeof(block_info_t)-1)/MaxAlign+1)*MaxAlign;
   static const size_type HdrOffsetSize = ((sizeof(hdr_offset_holder)-1)/MaxAlign+1)*MaxAlign;

   public:
   //!Segment manager typedef
   typedef SegmentManagerBase                 segment_manager_base_type;

   //!Constructor from a segment manager. Never throws
   private_adaptive_node_pool_impl
      ( segment_manager_base_type *segment_mngr_base
      , size_type node_size
      , size_type nodes_per_block
      , size_type max_free_blocks
      , unsigned char overhead_percent
      )
   :  m_max_free_blocks(max_free_blocks)
   ,  m_real_node_size(lcm(node_size, size_type(alignment_of<node_t>::value)))
      //Round the size to a power of two value.
      //This is the total memory size (including payload) that we want to
      //allocate from the general-purpose allocator
   ,  m_real_block_alignment
         (AlignOnly ?
            upper_power_of_2(HdrSize + m_real_node_size*nodes_per_block) :
            calculate_alignment( (size_type)overhead_percent, m_real_node_size
                               , HdrSize, HdrOffsetSize, PayloadPerAllocation))
      //This is the real number of nodes per block
   ,  m_num_subblocks(0)
   ,  m_real_num_node(AlignOnly ? (m_real_block_alignment - PayloadPerAllocation - HdrSize)/m_real_node_size : 0)
      //General purpose allocator
   ,  mp_segment_mngr_base(segment_mngr_base)
   ,  m_block_multiset()
   ,  m_totally_free_blocks(0)
   {
      if(!AlignOnly){
         calculate_num_subblocks
            ( m_real_block_alignment
            , m_real_node_size
            , nodes_per_block
            , m_num_subblocks
            , m_real_num_node
            , (size_type)overhead_percent
            , HdrSize
            , HdrOffsetSize
            , PayloadPerAllocation);
      }
   }

   //!Destructor. Deallocates all allocated blocks. Never throws
   ~private_adaptive_node_pool_impl()
   {  priv_clear();  }

   size_type get_real_num_node() const
   {  return m_real_num_node; }

   //!Returns the segment manager. Never throws
   segment_manager_base_type* get_segment_manager_base()const
   {  return container_detail::to_raw_pointer(mp_segment_mngr_base);  }

   //!Allocates array of count elements. Can throw
   void *allocate_node()
   {
      priv_invariants();
      //If there are no free nodes we allocate a new block
      if (m_block_multiset.empty()){
         priv_alloc_block(1);
      }
      //We take the first free node the multiset can't be empty
      return priv_take_first_node();
   }

   //!Deallocates an array pointed by ptr. Never throws
   void deallocate_node(void *pElem)
   {
      multiallocation_chain chain;
      chain.push_front(void_pointer(pElem));
      this->priv_reinsert_nodes_in_block(chain, 1);
      //Update free block count<
      if(m_totally_free_blocks > m_max_free_blocks){
         this->priv_deallocate_free_blocks(m_max_free_blocks);
      }
      priv_invariants();
   }

   //!Allocates n nodes.
   //!Can throw
   multiallocation_chain allocate_nodes(const size_type n)
   {
      multiallocation_chain chain;
      size_type i = 0;
      try{
         priv_invariants();
         while(i != n){
            //If there are no free nodes we allocate all needed blocks
            if (m_block_multiset.empty()){
               priv_alloc_block(((n - i) - 1)/m_real_num_node + 1);
            }
            free_nodes_t &free_nodes = m_block_multiset.begin()->free_nodes;
            const size_type free_nodes_count_before = free_nodes.size();
            if(free_nodes_count_before == m_real_num_node){
               --m_totally_free_blocks;
            }
            const size_type num_elems = ((n-i) < free_nodes_count_before) ? (n-i) : free_nodes_count_before;
            for(size_type j = 0; j != num_elems; ++j){
               void *new_node = &free_nodes.front();
               free_nodes.pop_front();
               chain.push_back(new_node);
            }

            if(free_nodes.empty()){
               m_block_multiset.erase(m_block_multiset.begin());
            }
            i += num_elems;
         }
      }
      catch(...){
         this->deallocate_nodes(lslboost::move(chain));
         throw;
      }
      priv_invariants();
      return lslboost::move(chain);
   }

   //!Deallocates a linked list of nodes. Never throws
   void deallocate_nodes(multiallocation_chain nodes)
   {
      this->priv_reinsert_nodes_in_block(nodes, nodes.size());
      if(m_totally_free_blocks > m_max_free_blocks){
         this->priv_deallocate_free_blocks(m_max_free_blocks);
      }
   }

   void deallocate_free_blocks()
   {  this->priv_deallocate_free_blocks(0);   }

   size_type num_free_nodes()
   {
      typedef typename block_multiset_t::const_iterator citerator;
      size_type count = 0;
      citerator it (m_block_multiset.begin()), itend(m_block_multiset.end());
      for(; it != itend; ++it){
         count += it->free_nodes.size();
      }
      return count;
   }

   void swap(private_adaptive_node_pool_impl &other)
   {
      BOOST_ASSERT(m_max_free_blocks == other.m_max_free_blocks);
      BOOST_ASSERT(m_real_node_size == other.m_real_node_size);
      BOOST_ASSERT(m_real_block_alignment == other.m_real_block_alignment);
      BOOST_ASSERT(m_real_num_node == other.m_real_num_node);
      std::swap(mp_segment_mngr_base, other.mp_segment_mngr_base);
      std::swap(m_totally_free_blocks, other.m_totally_free_blocks);
      m_block_multiset.swap(other.m_block_multiset);
   }

   //Deprecated, use deallocate_free_blocks
   void deallocate_free_chunks()
   {  this->priv_deallocate_free_blocks(0);   }

   private:
   void priv_deallocate_free_blocks(size_type max_free_blocks)
   {
      priv_invariants();
      //Now check if we've reached the free nodes limit
      //and check if we have free blocks. If so, deallocate as much
      //as we can to stay below the limit
      for( block_iterator itend = m_block_multiset.end()
         ; m_totally_free_blocks > max_free_blocks
         ; --m_totally_free_blocks
         ){
         BOOST_ASSERT(!m_block_multiset.empty());
         block_iterator it = itend;
         --it;
         BOOST_ASSERT(it->free_nodes.size() == m_real_num_node);
         m_block_multiset.erase_and_dispose(it, block_destroyer(this));
      }
   }

   void priv_reinsert_nodes_in_block(multiallocation_chain &chain, size_type n)
   {
      block_iterator block_it(m_block_multiset.end());
      while(n--){
         void *pElem = container_detail::to_raw_pointer(chain.front());
         chain.pop_front();
         priv_invariants();
         block_info_t *block_info = this->priv_block_from_node(pElem);
         BOOST_ASSERT(block_info->free_nodes.size() < m_real_num_node);
         //We put the node at the beginning of the free node list
         node_t * to_deallocate = static_cast<node_t*>(pElem);
         block_info->free_nodes.push_front(*to_deallocate);

         block_iterator this_block(block_multiset_t::s_iterator_to(*block_info));
         block_iterator next_block(this_block);
         ++next_block;

         //Cache the free nodes from the block
         size_type this_block_free_nodes = this_block->free_nodes.size();

         if(this_block_free_nodes == 1){
            m_block_multiset.insert(m_block_multiset.begin(), *block_info);
         }
         else{
            block_iterator next_block(this_block);
            ++next_block;
            if(next_block != block_it){
               size_type next_free_nodes = next_block->free_nodes.size();
               if(this_block_free_nodes > next_free_nodes){
                  //Now move the block to the new position
                  m_block_multiset.erase(this_block);
                  m_block_multiset.insert(*block_info);
               }
            }
         }
         //Update free block count
         if(this_block_free_nodes == m_real_num_node){
            ++m_totally_free_blocks;
         }
         priv_invariants();
      }
   }

   node_t *priv_take_first_node()
   {
      BOOST_ASSERT(m_block_multiset.begin() != m_block_multiset.end());
      //We take the first free node the multiset can't be empty
      free_nodes_t &free_nodes = m_block_multiset.begin()->free_nodes;
      node_t *first_node = &free_nodes.front();
      const size_type free_nodes_count = free_nodes.size();
      BOOST_ASSERT(0 != free_nodes_count);
      free_nodes.pop_front();
      if(free_nodes_count == 1){
         m_block_multiset.erase(m_block_multiset.begin());
      }
      else if(free_nodes_count == m_real_num_node){
         --m_totally_free_blocks;
      }
      priv_invariants();
      return first_node;
   }

   class block_destroyer;
   friend class block_destroyer;

   class block_destroyer
   {
      public:
      block_destroyer(const this_type *impl)
         :  mp_impl(impl)
      {}

      void operator()(typename block_multiset_t::pointer to_deallocate)
      {  return this->do_destroy(to_deallocate, IsAlignOnly()); }

      private:
      void do_destroy(typename block_multiset_t::pointer to_deallocate, AlignOnlyTrue)
      {
         size_type free_nodes = to_deallocate->free_nodes.size();
         (void)free_nodes;
         BOOST_ASSERT(free_nodes == mp_impl->m_real_num_node);
         mp_impl->mp_segment_mngr_base->deallocate(to_deallocate);
      }

      void do_destroy(typename block_multiset_t::pointer to_deallocate, AlignOnlyFalse)
      {
         size_type free_nodes = to_deallocate->free_nodes.size();
         (void)free_nodes;
         BOOST_ASSERT(free_nodes == mp_impl->m_real_num_node);
         BOOST_ASSERT(0 == to_deallocate->hdr_offset);
         hdr_offset_holder *hdr_off_holder = mp_impl->priv_first_subblock_from_block(container_detail::to_raw_pointer(to_deallocate));
         mp_impl->mp_segment_mngr_base->deallocate(hdr_off_holder);
      }

      const this_type *mp_impl;
   };

   //This macro will activate invariant checking. Slow, but helpful for debugging the code.
   //#define BOOST_CONTAINER_ADAPTIVE_NODE_POOL_CHECK_INVARIANTS
   void priv_invariants()
   #ifdef BOOST_CONTAINER_ADAPTIVE_NODE_POOL_CHECK_INVARIANTS
   #undef BOOST_CONTAINER_ADAPTIVE_NODE_POOL_CHECK_INVARIANTS
   {
      //We iterate through the block tree to free the memory
      block_iterator it(m_block_multiset.begin()),
                     itend(m_block_multiset.end()), to_deallocate;
      if(it != itend){
         for(++it; it != itend; ++it){
            block_iterator prev(it);
            --prev;
            size_type sp = prev->free_nodes.size(),
                        si = it->free_nodes.size();
            BOOST_ASSERT(sp <= si);
            (void)sp;   (void)si;
         }
      }
      //Check that the total free nodes are correct
      it    = m_block_multiset.begin();
      itend = m_block_multiset.end();
      size_type total_free_nodes = 0;
      for(; it != itend; ++it){
         total_free_nodes += it->free_nodes.size();
      }
      BOOST_ASSERT(total_free_nodes >= m_totally_free_blocks*m_real_num_node);

      //Check that the total totally free blocks are correct
      it    = m_block_multiset.begin();
      itend = m_block_multiset.end();
      total_free = 0;
      for(; it != itend; ++it){
         total_free += it->free_nodes.size() == m_real_num_node;
      }
      BOOST_ASSERT(total_free >= m_totally_free_blocks);

      if(!AlignOnly){
         //Check that header offsets are correct
         it = m_block_multiset.begin();
         for(; it != itend; ++it){
            hdr_offset_holder *hdr_off_holder = priv_first_subblock_from_block(&*it);
            for(size_type i = 0, max = m_num_subblocks; i < max; ++i){
               BOOST_ASSERT(hdr_off_holder->hdr_offset == size_type(reinterpret_cast<char*>(&*it)- reinterpret_cast<char*>(hdr_off_holder)));
               BOOST_ASSERT(0 == ((size_type)hdr_off_holder & (m_real_block_alignment - 1)));
               BOOST_ASSERT(0 == (hdr_off_holder->hdr_offset & (m_real_block_alignment - 1)));
               hdr_off_holder = reinterpret_cast<hdr_offset_holder *>(reinterpret_cast<char*>(hdr_off_holder) + m_real_block_alignment);
            }
         }
      }
   }
   #else
   {} //empty
   #endif

   //!Deallocates all used memory. Never throws
   void priv_clear()
   {
      #ifndef NDEBUG
      block_iterator it    = m_block_multiset.begin();
      block_iterator itend = m_block_multiset.end();
      size_type num_free_nodes = 0;
      for(; it != itend; ++it){
         //Check for memory leak
         BOOST_ASSERT(it->free_nodes.size() == m_real_num_node);
         ++num_free_nodes;
      }
      BOOST_ASSERT(num_free_nodes == m_totally_free_blocks);
      #endif
      //Check for memory leaks
      priv_invariants();
      m_block_multiset.clear_and_dispose(block_destroyer(this));
      m_totally_free_blocks = 0;
   }

   block_info_t *priv_block_from_node(void *node, AlignOnlyFalse) const
   {
      hdr_offset_holder *hdr_off_holder =
         reinterpret_cast<hdr_offset_holder*>((std::size_t)node & size_type(~(m_real_block_alignment - 1)));
      BOOST_ASSERT(0 == ((std::size_t)hdr_off_holder & (m_real_block_alignment - 1)));
      BOOST_ASSERT(0 == (hdr_off_holder->hdr_offset & (m_real_block_alignment - 1)));
      block_info_t *block = reinterpret_cast<block_info_t *>
         (reinterpret_cast<char*>(hdr_off_holder) + hdr_off_holder->hdr_offset);
      BOOST_ASSERT(block->hdr_offset == 0);
      return block;
   }

   block_info_t *priv_block_from_node(void *node, AlignOnlyTrue) const
   {
      return (block_info_t *)((std::size_t)node & std::size_t(~(m_real_block_alignment - 1)));
   }

   block_info_t *priv_block_from_node(void *node) const
   {  return priv_block_from_node(node, IsAlignOnly());   }

   hdr_offset_holder *priv_first_subblock_from_block(block_info_t *block) const
   {
      hdr_offset_holder *hdr_off_holder = reinterpret_cast<hdr_offset_holder*>
            (reinterpret_cast<char*>(block) - (m_num_subblocks-1)*m_real_block_alignment);
      BOOST_ASSERT(hdr_off_holder->hdr_offset == size_type(reinterpret_cast<char*>(block) - reinterpret_cast<char*>(hdr_off_holder)));
     BOOST_ASSERT(0 == ((std::size_t)hdr_off_holder & (m_real_block_alignment - 1)));
      BOOST_ASSERT(0 == (hdr_off_holder->hdr_offset & (m_real_block_alignment - 1)));
      return hdr_off_holder;
   }

   //!Allocates a several blocks of nodes. Can throw
   void priv_alloc_block(size_type n, AlignOnlyTrue)
   {
      size_type real_block_size = m_real_block_alignment - PayloadPerAllocation;
      for(size_type i = 0; i != n; ++i){
         //We allocate a new NodeBlock and put it the last
         //element of the tree
         char *mem_address = static_cast<char*>
            (mp_segment_mngr_base->allocate_aligned(real_block_size, m_real_block_alignment));
         if(!mem_address)   throw std::bad_alloc();
         ++m_totally_free_blocks;
         block_info_t *c_info = new(mem_address)block_info_t();
         m_block_multiset.insert(m_block_multiset.end(), *c_info);

         mem_address += HdrSize;
         //We initialize all Nodes in Node Block to insert
         //them in the free Node list
         typename free_nodes_t::iterator prev_insert_pos = c_info->free_nodes.before_begin();
         for(size_type i = 0; i < m_real_num_node; ++i){
            prev_insert_pos = c_info->free_nodes.insert_after(prev_insert_pos, *(node_t*)mem_address);
            mem_address   += m_real_node_size;
         }
      }
   }

   void priv_alloc_block(size_type n, AlignOnlyFalse)
   {
      size_type real_block_size = m_real_block_alignment*m_num_subblocks - PayloadPerAllocation;
      size_type elements_per_subblock = (m_real_block_alignment - HdrOffsetSize)/m_real_node_size;
      size_type hdr_subblock_elements = (m_real_block_alignment - HdrSize - PayloadPerAllocation)/m_real_node_size;

      for(size_type i = 0; i != n; ++i){
         //We allocate a new NodeBlock and put it the last
         //element of the tree
         char *mem_address = static_cast<char*>
            (mp_segment_mngr_base->allocate_aligned(real_block_size, m_real_block_alignment));
         if(!mem_address)   throw std::bad_alloc();
         ++m_totally_free_blocks;

         //First initialize header information on the last subblock
         char *hdr_addr = mem_address + m_real_block_alignment*(m_num_subblocks-1);
         block_info_t *c_info = new(hdr_addr)block_info_t();
         //Some structural checks
         BOOST_ASSERT(static_cast<void*>(&static_cast<hdr_offset_holder*>(c_info)->hdr_offset) ==
                static_cast<void*>(c_info));
         typename free_nodes_t::iterator prev_insert_pos = c_info->free_nodes.before_begin();
         for( size_type subblock = 0, maxsubblock = m_num_subblocks - 1
            ; subblock < maxsubblock
            ; ++subblock, mem_address += m_real_block_alignment){
            //Initialize header offset mark
            new(mem_address) hdr_offset_holder(size_type(hdr_addr - mem_address));
            char *pNode = mem_address + HdrOffsetSize;
            for(size_type i = 0; i < elements_per_subblock; ++i){
               prev_insert_pos = c_info->free_nodes.insert_after(prev_insert_pos, *new (pNode) node_t);
               pNode   += m_real_node_size;
            }
         }
         {
            char *pNode = hdr_addr + HdrSize;
            //We initialize all Nodes in Node Block to insert
            //them in the free Node list
            for(size_type i = 0; i < hdr_subblock_elements; ++i){
               prev_insert_pos = c_info->free_nodes.insert_after(prev_insert_pos, *new (pNode) node_t);
               pNode   += m_real_node_size;
            }
         }
         //Insert the block after the free node list is full
         m_block_multiset.insert(m_block_multiset.end(), *c_info);
      }
   }

   //!Allocates a block of nodes. Can throw std::bad_alloc
   void priv_alloc_block(size_type n)
   {  return priv_alloc_block(n, IsAlignOnly());   }

   private:
   typedef typename lslboost::intrusive::pointer_traits
      <void_pointer>::template rebind_pointer<segment_manager_base_type>::type   segment_mngr_base_ptr_t;
   const size_type m_max_free_blocks;
   const size_type m_real_node_size;
   //Round the size to a power of two value.
   //This is the total memory size (including payload) that we want to
   //allocate from the general-purpose allocator
   const size_type m_real_block_alignment;
   size_type m_num_subblocks;
   //This is the real number of nodes per block
   //const
   size_type m_real_num_node;
   segment_mngr_base_ptr_t                mp_segment_mngr_base;   //Segment manager
   block_multiset_t                       m_block_multiset;       //Intrusive block list
   size_type                            m_totally_free_blocks;  //Free blocks
};

}  //namespace container_detail {
}  //namespace container {
}  //namespace lslboost {

#include <lslboost/container/detail/config_end.hpp>

#endif   //#ifndef BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_IMPL_HPP


text:
The beersong
In this puzzle, write code to print out the entire "99 bottles of beer on the wall" song.
For those who do not know the song, the lyrics follow this form:

The beersong
In this puzzle, write code to print out the entire "99 bottles of beer on the wall" song.
For those who do not know the song, the lyrics follow this form:

    X bottles of beer on the wall, X bottles of beer.
    Take one down, pass it around, X-1 bottles of beer on the wall.

    X-1 bottles of beer on the wall, X bottles of beer.
    ...

last two paragraph is different. It should be:

    1 bottle of beer on the wall, 1 bottle of beer.
    Take one down and pass it around, no more bottles of beer on the wall.
    No more bottles of beer on the wall, no more bottles of beer.
    Go to the store and buy some more, 99 bottles of beer on the wall.

redpajama_set_name: RedPajamaGithub


text:
package com.example.bakes.login_menu;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.util.ArrayList;

import warofages.gamebackend.DisplaysChanges;
import warofages.gamebackend.UIbackend;

public class UI extends AppCompatActivity implements DisplaysChanges {
    boolean movedToOtherIntent = false;

    private UIbackend uiBackend;
    private final int BASE_TOWN_ICON = 10000;
    private int numTownIcons = 0;

    //The number of squares in the map. Used so often that I save the value in here
    private int mapSize;
    //size of the map tiles image
    private int tileSize = 100;
    //username
    String username = "";
    //if click on town with friendly unit and 0, open town menu.
    // if 1, currently using popup. if 2, moving unit.
    int unitVtown;
    //town menu
    PopupWindow townMenu;
    //popul showing whose turn it is
    PopupWindow endMenu;
    //text in endMenu
    TextView endText;
    //scrollview. class wide so inactive player can use it.
    ScrollView scroller;
    boolean gameOn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        username = getIntent().getStringExtra("username");
        boolean spectator = getIntent().hasExtra("spectator");

        //initialize gameOn
        gameOn = true;

        //initialize scroller
        scroller = (ScrollView) findViewById(R.id.scroll);

        unitVtown = -1;

        makeTownMenu();
        makeEndMenu();

        uiBackend = new UIbackend(getApplicationContext(), username, spectator, this);
    }

    public int getTileSize(){
        return tileSize;
    }

    //shows whose turn it is
    private void makeEndMenu(){
        endMenu = new PopupWindow(this);
        LinearLayout popLayout = new LinearLayout(this);
        endText = new TextView(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        endText.setText(R.string.EndTextDefault);
        endText.setTextColor(Color.BLACK);
        popLayout.addView(endText, layoutParams);
        endMenu.setContentView(popLayout);
        endMenu.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        endMenu.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        //I didn't like how ugly the black box is
        endMenu.setBackgroundDrawable(new ColorDrawable(Color.GRAY));
//        endMenu.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        endMenu.getBackground().setAlpha(127); // 50% opaque
    }

    //initialize townMenu window
    private void makeTownMenu(){
        townMenu = new PopupWindow(this);
        GridLayout popLayout = new GridLayout(this);

        ImageView image;
        ViewGroup.LayoutParams layoutParams = new LinearLayout.LayoutParams(125, 125);
        ArrayList<Integer> icons = findTownMenuIDs();

        for(int i = 0; i < icons.size(); i++){
            if(i % 5 == 0){
                LinearLayout row = new LinearLayout(this);
                popLayout.addView(row);
            }
            image = new ImageView(this);
            image.setImageResource(icons.get(i));
            image.setId(BASE_TOWN_ICON + i);
            image.setOnClickListener(townMenuListener);
            popLayout.addView(image, layoutParams);
            numTownIcons++;
        }
        townMenu.setContentView(popLayout);
        //The menu didn't show up on mobile devices (worked on emulator though). fixed by http://stackoverflow.com/a/39363218
        townMenu.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        townMenu.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        townMenu.getBackground().setAlpha(102); //40% opaque
    }

    private ArrayList<Integer> findTownMenuIDs(){
        ArrayList<Integer> unitIDs = new ArrayList<>();
        Field[] fields = R.drawable.class.getFields();
        for(Field field : fields){
            if(field.getName().startsWith("unit") && field.getName().endsWith("friendly")){
                try {
                    unitIDs.add(field.getInt(null));
                }
                catch(IllegalAccessException e){
                    Log.d("findTownMenuIDs", e.getLocalizedMessage());
                }
            }
        }
        return unitIDs;
    }

    //Create table of any size(must be square)
    private void createTerrainButtons(){
        //Creates an initial row
        LinearLayout mapLayout = (LinearLayout) findViewById(R.id.gameLayout);

        //Creates an initial column
        LinearLayout column = new LinearLayout(this);
        column.setOrientation(LinearLayout.VERTICAL);
        mapLayout.addView(column);

        //set images to all columns. create new columns as needed
        for(int id = 0, rowLength = 0; id < mapSize; id++, rowLength++){
            //if column is filled, begin new column and set parameters for it
            if(rowLength == Math.sqrt(mapSize)){
                //Creates a new row for both grids
                column = new LinearLayout(this);
                //we move every second column down a bit
                if((id / rowLength) % 2 == 1)
                    adjustColumnParams(column, rowLength, false);
                else
                    adjustColumnParams(column, rowLength, true);

                //Adds column to the matrix
                mapLayout.addView(column);
                rowLength = 0;
            }

            //creates image and adds it to terrain. HexagonMaskView has default size of 100x100
            HexagonMaskView image = new HexagonMaskView(this);
            image.setId(id);
            column.addView(image);

            //he had a separate method just for this, which is odd since it always adds the same image
            image.setOnClickListener(gameClickListener);
        }
    }

    /* Should not be called on first column
     * first column doesn't need special parameters besides being set to vertical.
     * evenIndex: true if index 0,2,4... false if its odd
     */
    private void adjustColumnParams(LinearLayout column, int rowLength, boolean evenIndex){
        //set orientation just in case it hasn't been done at creation
        column.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams params;
        if(evenIndex) {
            params = new LinearLayout.LayoutParams(tileSize, rowLength * tileSize);
            params.setMargins(-tileSize/4, 0,0,0);
        }
        else {
            params = new LinearLayout.LayoutParams(tileSize, rowLength * tileSize + tileSize / 2);
            params.setMargins(-tileSize/4, (int)(Math.sqrt(3.0)/2 * tileSize / 2), 0, -(int)(Math.sqrt(3.0)/2 * tileSize / 2));
        }
        column.setLayoutParams(params);
    }

    private void loadSingleTerrainToButton(int tID, int mapID){
        String picName = "";
        switch (tID) {
            case 1:
                picName = "tile_desert";
                break;
            case 2:
                picName = "tile_forest";
                break;
            case 3:
                picName = "tile_meadow";
                break;
            case 4:
                picName = "tile_mountain";
                break;
            case 5:
                picName = "tile_town_friendly";
                break;
            case 6:
                picName = "tile_town_hostile";
                break;
            case 7:
                picName = "tile_town_neutral";
                break;
            case 8:
                picName = "tile_water";
                break;
            case 9:
                picName = "tile_impassible";
                break;
        }
        //gets and sets reference for picture ID. "p12" would indicate something went wrong
        int resID = getResources().getIdentifier(picName.equals("") ? "p12" : picName, "drawable", getPackageName());
        HexagonMaskView image = getImage(mapID);
        Drawable oldForeground = image.getForeground();

        image.setImageResource(resID);
        image.setForeground(oldForeground);
    }

    //load given terrain at given id
    public void loadTerrainToButtons(){
        for(int id = 0; id < mapSize; id++) {
            int terrainTypeID = uiBackend.getTerrainAtLocation(id);
            //gets imageview object at given id
            loadSingleTerrainToButton(terrainTypeID, id);
        }
    }

    HexagonMaskView getImage(int mapID){
        int mapRoot = (int)Math.sqrt(mapSize);
        int x = mapID / mapRoot;
        int y = mapID % mapRoot;
        LinearLayout layout = (LinearLayout)findViewById(R.id.gameLayout);
        layout = (LinearLayout)layout.getChildAt(x);
        return (HexagonMaskView)layout.getChildAt(y);
    }

    public void bottomBarListener(View v){
        try {
            switch (v.getId()) {
                case R.id.endTurn:
                    uiBackend.endTurn();
                    return;
                case R.id.zoomIn:
                    if (tileSize < 500) {
                        tileSize += 100;
                        resize();
                    }
                    break;
                case R.id.zoomOut:
                    if (tileSize > 100) {
                        tileSize -= 100;
                        resize();
                    }
                    break;
            }
        }
        catch(Exception e){
            Log.d("bottomBar", e.getLocalizedMessage());
        }
    }

    private void resize (){
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(tileSize, tileSize);
        for (int id = 0; id < mapSize; id++) {
            HexagonMaskView image = getImage(id);
            image.setLayoutParams(params);
        }
        //loop through all columns after the first and adjust their parameters
        LinearLayout rootLayout = (LinearLayout) findViewById(R.id.gameLayout);
        LinearLayout column;
        //number of columns = number of rows, since I only make square maps, so I can use count as rowLength
        int count = rootLayout.getChildCount();

        for (int i = 1; i < count; i++) {
            column = (LinearLayout)rootLayout.getChildAt(i);
            if(i % 2 == 1)
                adjustColumnParams(column, count, false);
            else
                adjustColumnParams(column, count, true);
        }
    }

    //processes clicks when the town menu is open
    View.OnClickListener townMenuListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //clicked on one of the add unit buttons
            int id = v.getId();
            if (id >= BASE_TOWN_ICON && v.getId() < BASE_TOWN_ICON+numTownIcons) {
                int unitIDtoAdd = v.getId() - BASE_TOWN_ICON + 1;
                uiBackend.recruitFromTownMenu(unitIDtoAdd);
            }
            /*  if user didn't click on move or unit icons, they must have pressed the map or
             *  something, in which case this listener shouldn't have been notified so this shouldn't happen
             */
            else
                uiBackend.resetMapIdManipulated();
            //close menu regardless of the user's choice
            townMenu.dismiss();
        }
    };

    //processes clicks
    View.OnClickListener gameClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v){
            uiBackend.helpWithMapClicks(v.getId());
        }
    };

    public void displayTownMenu(){
        ScrollView scroll = (ScrollView) findViewById(R.id.scroll);
        townMenu.showAtLocation(scroll, Gravity.TOP, 0, 500);
    }

    public void dismissTownMenu(){
        townMenu.dismiss();
    }

    public void displayForeground(int mapID, int unitID, boolean friendly, boolean selected){
        int drawableID;
        switch(unitID){
            case 0:
                if(selected)
                    drawableID = R.drawable.selected_tile;
                else
                    drawableID = -1;
                break;
            case 1: //archer
                if(friendly && selected)
                    drawableID = R.drawable.unit_1_archer_friendly_selected;
                else if(friendly)
                    drawableID = R.drawable.unit_1_archer_friendly;
                else if(selected)
                    drawableID = R.drawable.unit_1_archer_hostile_selected;
                else
                    drawableID = R.drawable.unit_1_archer_hostile;
                break;
            case 2: //cavalry
                if(friendly && selected)
                    drawableID = R.drawable.unit_2_cavalry_friendly_selected;
                else if(friendly)
                    drawableID = R.drawable.unit_2_cavalry_friendly;
                else if(selected)
                    drawableID = R.drawable.unit_2_cavalry_hostile_selected;
                else
                    drawableID = R.drawable.unit_2_cavalry_hostile;
                break;
            case 3: //swordsman
                if(friendly && selected)
                    drawableID = R.drawable.unit_3_sword_friendly_selected;
                else if(friendly)
                    drawableID = R.drawable.unit_3_sword_friendly;
                else if(selected)
                    drawableID = R.drawable.unit_3_sword_hostile_selected;
                else
                    drawableID = R.drawable.unit_3_sword_hostile;
                break;
            case 4: //spearman
                if(friendly && selected)
                    drawableID = R.drawable.unit_4_spear_friendly_selected;
                else if(friendly)
                    drawableID = R.drawable.unit_4_spear_friendly;
                else if(selected)
                    drawableID = R.drawable.unit_4_spear_hostile_selected;
                else
                    drawableID = R.drawable.unit_4_spear_hostile;
                break;
            case 5: //general
                if(friendly && selected)
                    drawableID = R.drawable.unit_5_general_friendly_selected;
                else if(friendly)
                    drawableID = R.drawable.unit_5_general_friendly;
                else if(selected)
                    drawableID = R.drawable.unit_5_general_hostile_selected;
                else
                    drawableID = R.drawable.unit_5_general_hostile;
                break;
            default:
                return;
        }
        HexagonMaskView image = getImage(mapID);
        if(drawableID != -1)
            image.setForeground(getDrawable(drawableID));
        else
            image.setForeground(null);
    }

    @Override
    public void onBackPressed(){
        uiBackend.ensurePollKilled();
        movedToOtherIntent = true;
        Intent intent = new Intent(getApplicationContext(), com.example.bakes.login_menu.Menu.class);
        intent.putExtra("username", username);
        intent.putExtra("message", "leftGame");
        startActivity(intent);
        finish();
    }

    @Override
    public void onDestroy(){
        endMenu.dismiss();
        if(isFinishing() && !movedToOtherIntent) {
            Intent forceLogout = new Intent(this, com.example.bakes.login_menu.LogoutBackgroundService.class);
            forceLogout.putExtra("username", username);
            startService(forceLogout);
        }
        else{
            Log.d("destroying", "was not finishing");
        }
        super.onDestroy();
    }

    public void setInfoBar(String text){
        TextView info = (TextView) findViewById(R.id.infoBar);
        info.setText(text);
    }

    public void clearMap(){
        for(int x = 0; x < mapSize; x++){
            clearImage(x);
        }
    }
    private void clearImage(int mapID){
        if(getImage(mapID).getForeground() != null)
            getImage(mapID).setForeground(null);
    }

    public void makeToast(String text){
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    public void setEndText(String text){
        endText.setText(text);
        endMenu.showAtLocation(scroller, Gravity.BOTTOM, 0, 400);
    }

    public void dismissEndText(){
        if(endMenu.isShowing())
            endMenu.dismiss();
    }

    public void displayTerrain(int mapSize){
        this.mapSize = mapSize;
        createTerrainButtons();
        loadTerrainToButtons();
    }
    public void changeTownOwnership(int newTerrainID, int mapID){
        loadSingleTerrainToButton(newTerrainID, mapID);
    }
}


text:
package com.socialize.google.gson;

import java.lang.reflect.Type;

/**
 * Context for serialization that is passed to a custom serializer during invocation of its
 * {@link JsonSerializer#serialize(Object, Type, JsonSerializationContext)} method.
 *
 * @author Inderjeet Singh
 * @author Joel Leitch
 */
public interface JsonSerializationContext {

  /**
   * Invokes default serialization on the specified object.
   *
   * @param src the object that needs to be serialized.
   * @return a tree of {@link JsonElement}s corresponding to the serialized form of {@code src}.
   */
  public JsonElement serialize(Object src);

  /**
   * Invokes default serialization on the specified object passing the specific type information.
   * It should never be invoked on the element received as a parameter of the
   * {@link JsonSerializer#serialize(Object, Type, JsonSerializationContext)} method. Doing
   * so will result in an infinite loop since Gson will in-turn call the custom serializer again.
   *
   * @param src the object that needs to be serialized.
   * @param typeOfSrc the actual genericized type of src object.
   * @return a tree of {@link JsonElement}s corresponding to the serialized form of {@code src}.
   */
  public JsonElement serialize(Object src, Type typeOfSrc);
}


text:
function callback_readWS(hObject,~,varargin)
% READSLA - opens YCweather workspace *.mat file.
%__________________________________________________________________________
% USAGE: readWS(hObject,eventdata,varargin)
%
% INPUT:
%   hObject = current object (not used)
%   eventdata = reserved for future use (MATLAB required)
%   varargin{1} = if it is empty then the program prompts the user
%               = filename - opens the desired filename
%
% PROGRAM OUTLINE:
% 1 - DETERMINE THE FILE TO OPEN
% 2 - ACTIVIATE THE NECESSARY SETTINGS
% SUBFUNCTION: readWS
% SUBFUNCTION: set_times
% SUBFUNCTION: build_plot
% SUBFUNCTION: set_window_position
% SUFUNCTION: verifyposition
%__________________________________________________________________________
try
% 1 - DETERMINE THE FILE TO OPEN
    % 1.1 - Utilize the user defined filename
    if ~isempty(varargin);
        filename = varargin{1};

    % 1.2 - Determine the workspace filename
    else
        % 1.2.1 - Use that last used directory, otherwise the saved folder
        GUI = guidata(hObject);
        if ~isfield(GUI,'currentdir');
            if ~exist(GUI.settings.paths.saved,'dir');
                mkdir(GUI.settings.paths.saved);
            end
            GUI.currentdir = GUI.settings.paths.saved;
        end

        % 1.2.2 - Prompt the user for the file
        [file,pth] = uigetfile([GUI.currentdir,'*.mat'],'Open file...');
        if file == 0; return; end
        filename = [pth,file];
        GUI.currentdir = pth;
    end

    % 1.3 - Open the saved *.mat file
        GUIold = guidata(hObject);
        GUI = load(filename,'-mat');
        GUI = comparewithdefault(GUI);
        GUI.main = findobj('Tag','YCweather');

    % 1.4 - Maintain the current handles
        if ~isempty(GUIold);
            p = {'primary','secondary','varwindow','preferences',...
            'logview','imageview'};
            for i = 1:length(p);
                if ishandle( GUIold.(p{i}));
                    GUI.(p{i}) = GUIold.(p{i});
        end,end,end

    % 1.5 - Update the open recent option and current directory
        guidata(hObject,GUI);
        callback_recent(hObject,[],filename);

% 2 - ACTIVIATE THE NECESSARY SETTINGS
    applyWS(GUI.main,GUIold,filename);

catch
    mes = ['An error occured reading the *.mat file (callback_readWS)',...
            ', see errorlog.txt.'];
    errorlog(mes);
end

%--------------------------------------------------------------------------
% SUBFUNCTION: applyWS
function applyWS(hObject,GUIold,filename)
% applyWS applies the open *.mat file containing the YCweather data
% structure
%__________________________________________________________________________
% USAGE: applyWS(hObject)
%
% INPUT: hObject = Handle of object in program control window
%        GUIold  = Data structure currently in use
%__________________________________________________________________________

% 1 - SET SEASON AND PROGRAM CONTROL POSITION
    GUI = guidata(hObject);
    h = guihandles(hObject);

    % 1.1 - Initilize folder list
        % 1.1.1 - Extract existing folders from database directory,
        % eliminating the '.' and '..' directories
            yr = struct2cell(dir(GUI.settings.paths.database));
            yr = yr(1,:); yr(strmatch('.',yr)) = [];

        % 1.1.2 - Initilizes the folder list
            if isempty(yr);
                warndlg('No weather stations located.','!! WARNING !!');
                return;
            else
                set(h.season,'String',yr);
            end

    % 1.2 - Attempt to match folder with input from *.mat file
        val = strmatch(GUI.season,yr,'exact');
        if isempty(val); val = length(yr); end
        set(h.season,'Value',val);

% 2 -UPDATE STATION PANEL AND CHECK WINDOW POSITION
    % 2.1 - Update data structures and get handles
        % 2.1.1 - Define a tigger to load the season data, trig == 1 causes
        % the data to be open, "getselected" gathers all available station
        % buttons, which are then all deselected.
            trig = 1;
            use = getselected(hObject,'all');
            for i = 1:length(use); set(h.(use{i}),'Value',0); end

        % 2.1.2 - First compare the current database folder and season, if
        % they are the same the data does not need to be reloaded.
        % However, if "use = []" then the program is opening for the first
        % time and thus the data needs to be loaded
        if ~isempty(GUIold);
            Dold = GUIold.settings.paths.database; Sold = GUIold.season;
            D = GUI.settings.paths.database; S = GUI.season;
            if strcmp(Dold,D) && strcmp(Sold,S); trig = 0; end
            if isempty(use); trig = 1; end
        end

        if trig == 1; callback_season(hObject,1); end
        h = guihandles(hObject);

    % 2.2 - Reposition the windows
        p = {'main','varwindow','preferences'};
        for i = 1:length(p);
            if ishandle(GUI.(p{i}));
                 set_window_position(GUI.(p{i}),...
                        GUI.settings.position.(p{i}));
        end,end

% 3 - SET START/END TIMES
    % 3.1 - Force default.mat to always use current time
        [~,f] = fileparts(filename);
        if strcmpi(f,'default'); GUI.settings.pref.timetype = 1; end

    % 3.2 - Prompt user for type of time, if selected
        if GUI.settings.pref.timetype == 3;
            mes = ['Would you like to use the current time',...
                    'or the absolute time?'];
            q = questdlg(mes,'Type of time?','Current','Stored','Current');
            switch q
                case 'Current'; GUI.settings.pref.timetype = 1;
                otherwise; GUI.settings.pref.timetype = 2;
            end
        end

    % 3.3 - Build time string if the current time is desired
        if GUI.settings.pref.timetype == 1;
            use = getselected(hObject,'all');
            if isempty(use); t = now; end;

            for i = 1:length(use);
                d = get(h.(use{i}),'UserData');
                t(i) = max(d.Time);
            end
            os = GUI.settings.pref.timeoffset;
            GUI.time = [floor(max(t)-os/24),max(t)];
        end

    % 3.4 - Insert the times into the GUI
        set_times(h,GUI.time(1),'strt');
        set_times(h,GUI.time(2),'end');

    % 3.5 - Insert the time into GUI data
        callback_settime(hObject,1);

% 4 - SET THE STATION BUTTONS
    btn = GUI.settings.stations;
    for i = 1:length(btn);
        if isfield(h,btn{i});
            set(h.(btn{i}),'Value',1);
            fcn = get(h.(btn{i}),'callback');
            feval(fcn,h.(btn{i}),[]);
        end
    end

% 5 - READ/PLOT GRAPHS
    if isfield(GUI,'plot') && ~isempty(GUI.plot)...
                                        && ~isempty(GUI.plot(1).data)
        callback_varmenu(hObject,1);
        set_window_position(GUI.varwindow,GUI.settings.position.varwindow);
        pause(1);
        for i = 1:length(GUI.plot);
            build_plot(hObject,GUI.plot(i).data,GUI.plot(i).position);
        end
    end

%--------------------------------------------------------------------------
% SUBFUNCTION: set_times
function set_times(h,time,label)
% SET_TIMES sets the time popupmenus

% 1 - Read input time string
    t = datevec(time);

% 2 - Set month, day, hour, minute
    m = h.([label,'month']); set(m,'Value',t(2));
    set(h.([label,'day']),'Value',t(3));
    set(h.([label,'hr']),'Value',t(4)+1);
    set(h.([label,'min']),'Value',t(5)+1);

% 3 - Set the year
    y = h.([label,'year']);
    str = get(y,'String');
    set(y,'Value',strmatch(num2str(t(1)),str));

%--------------------------------------------------------------------------
% SUBFUNCTION: build_plot
function build_plot(h,tag,pos)
% BUILD_PLOT constructs graphs of selected variables

% 1 - Get handles and variable menu tags
    GUI = guidata(h);
    vh  = guihandles(GUI.varwindow);

% 2 - Select the desired variable buttons/listboxes
    k = 1;
    while k <= length(tag);
        switch get(vh.(tag{k}),'Style');
            case 'radiobutton'
                set(vh.(tag{k}),'Value',1);
                callback_click(vh.(tag{k}),1);k = k + 1;
            case 'listbox';
                val = tag{k+1};
                set(vh.(tag{k}),'Value',val);
                callback_click(vh.(tag{k}),1);k = k + 2;
    end,end

% 3 - Plot the data and reposition window
    callback_plotdata(h,1);
    set(gcf,'Position',pos);

% 4 - Deselect the variable buttons/listboxs
k = 1;
while k <= length(tag);
    switch get(vh.(tag{k}),'Style');
        case 'radiobutton'
            set(vh.(tag{k}),'Value',0);
            callback_click(vh.(tag{k}),1); k = k + 1;
        case 'listbox';
            val = tag{k+1};
            set(vh.(tag{k}),'Value',1);
            callback_click(vh.(tag{k}),1); k = k + 2;
end,end

%--------------------------------------------------------------------------
% SUBFUNCTION: set_window_position
function set_window_position(handle,P)
% SET_WINDOW_POSITION - set the window positions

% Proceed if the window exists
if ishandle(handle);
    set(handle,'units','normalized');
    loc = get(handle,'position');
    loc(1) = P(1); loc(2) = P(2);
    set(handle,'position',loc);
    %movegui(handle,'onscreen');
end

%--------------------------------------------------------------------------
function GUI = comparewithdefault(GUI)
%COMPAREWITHDEFAULT compares the GUI loaded with the default, adds missing

DEF = create_defaultWS;

% Check primary fields
    GUI = checkfields(GUI,DEF);
    GUI.sidebar = checkfields(GUI.sidebar,DEF.sidebar);

% Check settings
    GUI.settings = checkfields(GUI.settings,DEF.settings);
    GUI.settings.pref = checkfields(GUI.settings.pref,DEF.settings.pref);
    GUI.settings.position = checkfields(GUI.settings.position,...
        DEF.settings.position);

%--------------------------------------------------------------------------
function S1 = checkfields(S1,S2)
% CHECKFIELDS inserts missing fields from S1 based on S2
fn = fieldnames(S2);
for i = 1:length(fn);
    if ~isfield(S1,fn{i});
        S1.(fn{i}) = S2.(fn{i});
    end
end


text:
 /*
  *   LOCATION:    see http://www.boost.org for most recent version.
  *   FILE         static_mutex_test.cpp
  *   VERSION      see <boost/version.hpp>
  *   DESCRIPTION: test program for boost::static_mutex.
  */

#include <iostream>
#include <boost/regex/pending/static_mutex.hpp>
#include <boost/thread/thread.hpp>
#include <boost/timer.hpp>

//
// we cannot use the regular Boost.Test in here: it is not thread safe
// and calls to BOOST_TEST will eventually crash on some compilers
// (Borland certainly) due to race conditions inside the Boost.Test lib.
//
#define BOOST_TEST(pred) if(!(pred)) failed_test(__FILE__, __LINE__, BOOST_STRINGIZE(pred));

int total_failures = 0;
void failed_test(const char* file, int line, const char* pred)
{
   static boost::static_mutex mut = BOOST_STATIC_MUTEX_INIT ;
   boost::static_mutex::scoped_lock guard(mut);
   ++total_failures;
   std::cout << "Failed test in \"" << file << "\" at line " << line << ": " << pred << std::endl;
}

void print_cycles(int c)
{
   static boost::static_mutex mut = BOOST_STATIC_MUTEX_INIT ;
   boost::static_mutex::scoped_lock guard(mut);
   std::cout << "Thread exited after " << c << " cycles." << std::endl;
}

bool sufficient_time()
{
   // return true if enough time has passed since the tests began:
   static boost::static_mutex mut = BOOST_STATIC_MUTEX_INIT ;
   boost::static_mutex::scoped_lock guard(mut);
   static boost::timer t;
   // is 10 seconds enough?
   return t.elapsed() >= 10.0;
}

// define three trivial test proceedures:
bool t1()
{
   static boost::static_mutex mut = BOOST_STATIC_MUTEX_INIT ;
   static int has_lock = 0;
   static int data = 10000;

   boost::static_mutex::scoped_lock guard(mut);
   BOOST_TEST(++has_lock == 1);
   BOOST_TEST(guard.locked());
   BOOST_TEST(guard);
   bool result = (--data > 0) ? true : false;
   BOOST_TEST(--has_lock == 0);
   return result;
}

bool t2()
{
   static boost::static_mutex mut = BOOST_STATIC_MUTEX_INIT ;
   static int has_lock = 0;
   static int data = 10000;

   boost::static_mutex::scoped_lock guard(mut, false);
   BOOST_TEST(0 == guard.locked());
   BOOST_TEST(!guard);
   guard.lock();
   BOOST_TEST(++has_lock == 1);
   BOOST_TEST(guard.locked());
   BOOST_TEST(guard);
   bool result = (--data > 0) ? true : false;
   BOOST_TEST(--has_lock == 0);
   guard.unlock();
   BOOST_TEST(0 == guard.locked());
   BOOST_TEST(!guard);
   return result;
}

bool t3()
{
   static boost::static_mutex mut = BOOST_STATIC_MUTEX_INIT ;
   static int has_lock = 0;
   static int data = 10000;

   boost::static_mutex::scoped_lock guard(mut);
   BOOST_TEST(++has_lock == 1);
   BOOST_TEST(guard.locked());
   BOOST_TEST(guard);
   bool result = (--data > 0) ? true : false;
   BOOST_TEST(--has_lock == 0);
   return result;
}

// define their thread procs:
void thread1_proc()
{
   int cycles = 0;
   while(!sufficient_time())
   {
      t1();
      t2();
      ++cycles;
   }
   print_cycles(cycles);
}

void thread2_proc()
{
   int cycles = 0;
   while(!sufficient_time())
   {
      t2();
      t3();
      ++cycles;
   }
   print_cycles(cycles);
}

void thread3_proc()
{
   int cycles = 0;
   while(!sufficient_time())
   {
      t1();
      t3();
      ++cycles;
   }
   print_cycles(cycles);
}

// make sure that at least one of our test proceedures
// is called during program startup:
struct startup1
{
   startup1()
   {
      t1();
   }
   ~startup1()
   {
      t1();
   }
};

startup1 up1;

int main()
{
   (void)up1;

   std::list<boost::shared_ptr<boost::thread> > threads;
   for(int i = 0; i < 2; ++i)
   {
      try{
         threads.push_back(boost::shared_ptr<boost::thread>(new boost::thread(&thread1_proc)));
      }
      catch(const std::exception& e)
      {
         std::cerr << "<note>Thread creation failed with message: " << e.what() << "</note>" << std::endl;
      }
   }
   for(int i = 0; i < 2; ++i)
   {
      try{
         threads.push_back(boost::shared_ptr<boost::thread>(new boost::thread(&thread2_proc)));
      }
      catch(const std::exception& e)
      {
         std::cerr << "<note>Thread creation failed with message: " << e.what() << "</note>" << std::endl;
      }
   }
   for(int i = 0; i < 2; ++i)
   {
      try{
         threads.push_back(boost::shared_ptr<boost::thread>(new boost::thread(&thread3_proc)));
      }
      catch(const std::exception& e)
      {
         std::cerr << "<note>Thread creation failed with message: " << e.what() << "</note>" << std::endl;
      }
   }

   std::list<boost::shared_ptr<boost::thread> >::const_iterator a(threads.begin()), b(threads.end());
   while(a != b)
   {
      (*a)->join();
      ++a;
   }

   return total_failures;
}


text:
package org.elasticsearch.xpack.ml.integration;

import org.elasticsearch.xpack.core.ml.job.config.AnalysisConfig;
import org.elasticsearch.xpack.core.ml.job.config.DataDescription;
import org.elasticsearch.xpack.core.ml.job.config.Detector;
import org.elasticsearch.xpack.core.ml.job.config.Job;
import org.junit.After;

import java.util.Collections;

import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.is;

public class ReopenJobResetsFinishedTimeIT extends MlNativeAutodetectIntegTestCase {

    @After
    public void cleanUpTest() {
        cleanUp();
    }

    public void test() {
        final String jobId = "reset-finished-time-test";
        Job.Builder job = createJob(jobId);

        registerJob(job);
        putJob(job);
        openJob(job.getId());

        assertThat(getSingleJob(jobId).getFinishedTime(), is(nullValue()));

        closeJob(jobId);
        assertThat(getSingleJob(jobId).getFinishedTime(), is(notNullValue()));

        openJob(jobId);
        assertThat(getSingleJob(jobId).getFinishedTime(), is(nullValue()));
    }

    private Job getSingleJob(String jobId) {
        return getJob(jobId).get(0);
    }

    private Job.Builder createJob(String id) {
        DataDescription.Builder dataDescription = new DataDescription.Builder();
        dataDescription.setFormat(DataDescription.DataFormat.XCONTENT);
        dataDescription.setTimeFormat(DataDescription.EPOCH_MS);

        Detector.Builder d = new Detector.Builder("count", null);
        AnalysisConfig.Builder analysisConfig = new AnalysisConfig.Builder(Collections.singletonList(d.build()));

        Job.Builder builder = new Job.Builder();
        builder.setId(id);
        builder.setAnalysisConfig(analysisConfig);
        builder.setDataDescription(dataDescription);
        return builder;
    }
}


text:
Contributions and issues are most welcome! All issues and pull requests are
handled through GitHub on the
[ambitioninc repository](https://github.com/ambitioninc/django-activatable-model/issues).
Also, please check for any existing issues before filing a new one. If you have
a great idea but it involves big changes, please file a ticket before making a
pull request! We want to make sure you don't spend your time coding something
that might not fit the scope of the project.

## Running the tests

To get the source source code and run the unit tests, run:
```bash
git clone git://github.com/ambitioninc/django-activatable-model.git
cd django-activatable-model
virtualenv env
. env/bin/activate
python setup.py install
coverage run setup.py test
coverage report --fail-under=100
```

While 100% code coverage does not make a library bug-free, it significantly
reduces the number of easily caught bugs! Please make sure coverage is at 100%
before submitting a pull request!

## Code Quality

For code quality, please run flake8:
```bash
pip install flake8
flake8 .
```

## Code Styling
Please arrange imports with the following style

```python
# Standard library imports
import os

# Third party package imports
from mock import patch
from django.conf import settings

# Local package imports
from activatable_model.version import __version__
```

Please follow
[Google's python style](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html)
guide wherever possible.

## Release Checklist

Before a new release, please go through the following checklist:

* Bump version in activatable_model/version.py
* Add a release note at the bottom of the [README.md](README.md)
* Git tag the version
* Upload to pypi:
```bash
pip install wheel
python setup.py sdist bdist_wheel upload
```

## Vulnerability Reporting

For any security issues, please do NOT file an issue or pull request on GitHub!
Please contact [security@ambition.com](mailto:security@ambition.com) with the
GPG key provided on [Ambition's website](http://ambition.com/security/).


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Repo Widget</title>
<link type="text/css" rel="stylesheet" href="../css/github_repo_widget_2.css"/>


text:
<?php

namespace Umulmrum\Holiday\Provider\Germany;

use Umulmrum\Holiday\Constant\HolidayName;
use Umulmrum\Holiday\Constant\HolidayType;
use Umulmrum\Holiday\Model\Holiday;
use Umulmrum\Holiday\Model\HolidayList;
use Umulmrum\Holiday\Provider\Religion\ChristianHolidaysTrait;

class Bavaria extends Germany
{
    use ChristianHolidaysTrait;

    /**
     * {@inheritdoc}
     */
    public function calculateHolidaysForYear(int $year): HolidayList
    {
        $holidays = parent::calculateHolidaysForYear($year);

        $holidays->add($this->getEpiphany($year, HolidayType::DAY_OFF));
        $holidays->add($this->getCorpusChristi($year, HolidayType::DAY_OFF));
        $holidays->add($this->getAllSaintsDay($year, HolidayType::DAY_OFF));
        $holidays->add(Holiday::create(HolidayName::AUGSBURGER_FRIEDENSFEST, "{$year}-08-08", HolidayType::DAY_OFF | HolidayType::PARTIAL_ONLY));
        if ($year < 1969) {
            $holidays->add($this->getSaintJosephsDay($year, HolidayType::DAY_OFF));
        }
        $holidays->add($this->getAssumptionDay($year, HolidayType::DAY_OFF | HolidayType::PARTIAL_ONLY));

        return $holidays;
    }
}


text:
using System.Collections.Generic;
using BEPUutilities;
using System;
using BEPUphysics.CollisionShapes;
using Voxalia.Shared.Files;
using BEPUphysics.CollisionShapes.ConvexShapes;
using FreneticScript;

namespace Voxalia.Shared
{
    /// <summary>
    /// Handles abstract 3D models. Can be purposed for both collision systems and rendering.
    /// </summary>
    public class ModelHandler
    {
        /// <summary>
        /// Loads a model from .VMD (Voxalia Model Data) input.
        /// </summary>
        public Model3D LoadModel(byte[] data)
        {
            if (data.Length < 3 || data[0] != 'V' || data[1] != 'M' || data[2] != 'D')
            {
                throw new Exception("Model3D: Invalid header bits.");
            }
            byte[] dat_filt = new byte[data.Length - "VMD001".Length];
            Array.ConstrainedCopy(data, "VMD001".Length, dat_filt, 0, dat_filt.Length);
            dat_filt = FileHandler.UnGZip(dat_filt);
            DataStream ds = new DataStream(dat_filt);
            DataReader dr = new DataReader(ds);
            Model3D mod = new Model3D();
            mod.MatrixA = ReadMat(dr);
            int meshCount = dr.ReadInt();
            mod.Meshes = new List<Model3DMesh>(meshCount);
            for (int m = 0; m < meshCount; m++)
            {
                Model3DMesh mesh = new Model3DMesh();
                mod.Meshes.Add(mesh);
                mesh.Name = dr.ReadFullString();
                int vertexCount = dr.ReadInt();
                mesh.Vertices = new List<Vector3>(vertexCount);
                for (int v = 0; v < vertexCount; v++)
                {
                    double f1 = dr.ReadFloat();
                    double f2 = dr.ReadFloat();
                    double f3 = dr.ReadFloat();
                    mesh.Vertices.Add(new Vector3(f1, f2, f3));
                }
                int indiceCount = dr.ReadInt() * 3;
                mesh.Indices = new List<int>(indiceCount);
                for (int i = 0; i < indiceCount; i++)
                {
                    mesh.Indices.Add(dr.ReadInt());
                }
                int tcCount = dr.ReadInt();
                mesh.TexCoords = new List<Vector2>(tcCount);
                for (int t = 0; t < tcCount; t++)
                {
                    double f1 = dr.ReadFloat();
                    double f2 = dr.ReadFloat();
                    mesh.TexCoords.Add(new Vector2(f1, f2));
                }
                int normCount = dr.ReadInt();
                mesh.Normals = new List<Vector3>(normCount);
                for (int n = 0; n < normCount; n++)
                {
                    double f1 = dr.ReadFloat();
                    double f2 = dr.ReadFloat();
                    double f3 = dr.ReadFloat();
                    mesh.Normals.Add(new Vector3(f1, f2, f3));
                }
                int boneCount = dr.ReadInt();
                mesh.Bones = new List<Model3DBone>(boneCount);
                for (int b = 0; b < boneCount; b++)
                {
                    Model3DBone bone = new Model3DBone();
                    mesh.Bones.Add(bone);
                    bone.Name = dr.ReadFullString();
                    int weights = dr.ReadInt();
                    bone.IDs = new List<int>(weights);
                    bone.Weights = new List<double>(weights);
                    for (int w = 0; w < weights; w++)
                    {
                        bone.IDs.Add(dr.ReadInt());
                        bone.Weights.Add(dr.ReadFloat());
                    }
                    bone.MatrixA = ReadMat(dr);
                }
            }
            mod.RootNode = ReadSingleNode(null, dr);
            return mod;
        }

        public Model3DNode ReadSingleNode(Model3DNode root, DataReader dr)
        {
            Model3DNode n = new Model3DNode();
            n.Parent = root;
            n.Name = dr.ReadFullString();
            n.MatrixA = ReadMat(dr);
            int cCount = dr.ReadInt();
            n.Children = new List<Model3DNode>(cCount);
            for (int i = 0; i < cCount; i++)
            {
                n.Children.Add(ReadSingleNode(n, dr));
            }
            return n;
        }

        public Matrix ReadMat(DataReader reader)
        {
            double a1 = reader.ReadFloat();
            double a2 = reader.ReadFloat();
            double a3 = reader.ReadFloat();
            double a4 = reader.ReadFloat();
            double b1 = reader.ReadFloat();
            double b2 = reader.ReadFloat();
            double b3 = reader.ReadFloat();
            double b4 = reader.ReadFloat();
            double c1 = reader.ReadFloat();
            double c2 = reader.ReadFloat();
            double c3 = reader.ReadFloat();
            double c4 = reader.ReadFloat();
            double d1 = reader.ReadFloat();
            double d2 = reader.ReadFloat();
            double d3 = reader.ReadFloat();
            double d4 = reader.ReadFloat();
            return new Matrix(a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4);
            //return new Matrix(a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3, a4, b4, c4, d4);
        }

        public List<Vector3> GetVertices(Model3D input)
        {
            List<Vector3> vertices = new List<Vector3>(input.Meshes.Count * 100);
            foreach (Model3DMesh mesh in input.Meshes)
            {
                for (int i = 0; i < mesh.Vertices.Count; i++)
                {
                    vertices.Add(mesh.Vertices[i]);
                }
            }
            return vertices;
        }

        public List<Vector3> GetCollisionVertices(Model3D input)
        {
            List<Vector3> vertices = new List<Vector3>(input.Meshes.Count * 100);
            bool colOnly = false;
            foreach (Model3DMesh mesh in input.Meshes)
            {
                if (mesh.Name.ToLowerFast().Contains("collision"))
                {
                    colOnly = true;
                    break;
                }
            }
            foreach (Model3DMesh mesh in input.Meshes)
            {
                if ((!colOnly || mesh.Name.ToLowerFast().Contains("collision")) && !mesh.Name.ToLowerFast().Contains("nocollide"))
                {
                    for (int i = 0; i < mesh.Indices.Count; i ++)
                    {
                        vertices.Add(mesh.Vertices[mesh.Indices[i]]);
                    }
                }
            }
            return vertices;
        }

        public MobileMeshShape MeshToBepu(Model3D input, out int verts)
        {
            List<Vector3> vertices = GetCollisionVertices(input);
            List<int> indices = new List<int>(vertices.Count);
            for (int i = 0; i < vertices.Count; i++)
            {
                indices.Add(indices.Count);
            }
            verts = vertices.Count;
            return new MobileMeshShape(vertices.ToArray(), indices.ToArray(), AffineTransform.Identity, MobileMeshSolidity.DoubleSided);
        }

        public ConvexHullShape MeshToBepuConvex(Model3D input, out int verts)
        {
            List<Vector3> vertices = GetCollisionVertices(input);
            ConvexHullHelper.RemoveRedundantPoints(vertices);
            verts = vertices.Count;
            return new ConvexHullShape(vertices);
        }
    }
}


text:
#include <aws/elasticmapreduce/model/ClusterStateChangeReason.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace EMR
{
namespace Model
{

ClusterStateChangeReason::ClusterStateChangeReason() :
    m_code(ClusterStateChangeReasonCode::NOT_SET),
    m_codeHasBeenSet(false),
    m_messageHasBeenSet(false)
{
}

ClusterStateChangeReason::ClusterStateChangeReason(JsonView jsonValue) :
    m_code(ClusterStateChangeReasonCode::NOT_SET),
    m_codeHasBeenSet(false),
    m_messageHasBeenSet(false)
{
  *this = jsonValue;
}

ClusterStateChangeReason& ClusterStateChangeReason::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("Code"))
  {
    m_code = ClusterStateChangeReasonCodeMapper::GetClusterStateChangeReasonCodeForName(jsonValue.GetString("Code"));

    m_codeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Message"))
  {
    m_message = jsonValue.GetString("Message");

    m_messageHasBeenSet = true;
  }

  return *this;
}

JsonValue ClusterStateChangeReason::Jsonize() const
{
  JsonValue payload;

  if(m_codeHasBeenSet)
  {
   payload.WithString("Code", ClusterStateChangeReasonCodeMapper::GetNameForClusterStateChangeReasonCode(m_code));
  }

  if(m_messageHasBeenSet)
  {
   payload.WithString("Message", m_message);

  }

  return payload;
}

} // namespace Model
} // namespace EMR
} // namespace Aws


text:
using System;
/*Problem 15.* Bits Exchange

Write a program that exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given 32-bit unsigned integer.*/

namespace BitsExchange
{
    class BitsExchange
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter integer number");
            uint number = uint.Parse(Console.ReadLine());
            Console.WriteLine("The binary representation is:" + Convert.ToString(number, 2).PadLeft(32, '0'));
            uint mask = 7u;
            uint bits345 = number & (mask << 3);
            uint bits242526 = number & (mask << 24);
            bits345 = bits345 << 21;
            bits242526 = bits242526 >> 21;
            number = number & ~(mask << 3);
            number = number & ~(mask << 24);
            number = number | bits345;
            number = number | bits242526;
            Console.WriteLine("The binary result is: " + Convert.ToString(number, 2).PadLeft(32, '0') + "\n" + number);
        }
    }
}


text:
FROM node:0.10.35
# https://registry.hub.docker.com/_/node/

WORKDIR /

RUN npm install cheerio@0.17.0

ADD gdochtml2tex.js /gdochtml2tex.js

ENTRYPOINT ["/usr/local/bin/node"]
CMD ["gdochtml2tex.js"]


text:
<?php

namespace SlmQueueAmq\Controller;

use SlmQueue\Controller\AbstractWorkerController;

/**
 * This controller allow to execute jobs using the command line
 */
class AmqWorkerController extends AbstractWorkerController
{
}


text:
#include "Vao/OgreNULLBufferInterface.h"
#include "Vao/OgreNULLVaoManager.h"
#include "Vao/OgreNULLStagingBuffer.h"

namespace Ogre
{
    NULLBufferInterface::NULLBufferInterface( size_t vboPoolIdx ) :
        mVboPoolIdx( vboPoolIdx ),
        mMappedPtr( 0 ),
        mNullDataPtr( 0 )
    {
    }
    //-----------------------------------------------------------------------------------
    NULLBufferInterface::~NULLBufferInterface()
    {
        if( mNullDataPtr )
        {
            OGRE_FREE_SIMD( mNullDataPtr, MEMCATEGORY_RENDERSYS );
            mNullDataPtr = 0;
        }
    }
    //-----------------------------------------------------------------------------------
    void NULLBufferInterface::_firstUpload( const void *data, size_t elementStart, size_t elementCount )
    {
        //In OpenGL; immutable buffers are a charade. They're mostly there to satisfy D3D11's needs.
        //However we emulate the behavior and trying to upload to an immutable buffer will result
        //in an exception or an assert, thus we temporarily change the type.
        BufferType originalBufferType = mBuffer->mBufferType;
        if( mBuffer->mBufferType == BT_IMMUTABLE )
            mBuffer->mBufferType = BT_DEFAULT;

        upload( data, elementStart, elementCount );

        mBuffer->mBufferType = originalBufferType;
    }
    //-----------------------------------------------------------------------------------
    void* RESTRICT_ALIAS_RETURN NULLBufferInterface::map( size_t elementStart, size_t elementCount,
                                                          MappingState prevMappingState,
                                                          bool bAdvanceFrame )
    {
        size_t bytesPerElement = mBuffer->mBytesPerElement;

        NULLVaoManager *vaoManager = static_cast<NULLVaoManager*>( mBuffer->mVaoManager );
        bool canPersistentMap = vaoManager->supportsArbBufferStorage();

        size_t dynamicCurrentFrame = advanceFrame( bAdvanceFrame );

        if( prevMappingState == MS_UNMAPPED || !canPersistentMap )
        {
            //Non-persistent buffers just map the small region they'll need.
            size_t offset = mBuffer->mInternalBufferStart + elementStart +
                            mBuffer->_getInternalNumElements() * dynamicCurrentFrame;
            size_t length = elementCount;

            if( mBuffer->mBufferType >= BT_DYNAMIC_PERSISTENT && canPersistentMap )
            {
                //Persistent buffers map the *whole* assigned buffer,
                //we later care for the offsets and lengths
                offset = mBuffer->mInternalBufferStart;
                length = mBuffer->_getInternalNumElements() * vaoManager->getDynamicBufferMultiplier();
            }

            mMappedPtr = mNullDataPtr + offset * bytesPerElement;
        }

        //For regular maps, mLastMappingStart is 0. So that we can later flush correctly.
        mBuffer->mLastMappingStart = 0;
        mBuffer->mLastMappingCount = elementCount;

        char *retVal = (char*)mMappedPtr;

        if( mBuffer->mBufferType >= BT_DYNAMIC_PERSISTENT && canPersistentMap )
        {
            //For persistent maps, we've mapped the whole 3x size of the buffer. mLastMappingStart
            //points to the right offset so that we can later flush correctly.
            size_t lastMappingStart = elementStart +
                    mBuffer->_getInternalNumElements() * dynamicCurrentFrame;
            mBuffer->mLastMappingStart = lastMappingStart;
            retVal += lastMappingStart * bytesPerElement;
        }

        return retVal;
    }
    //-----------------------------------------------------------------------------------
    void NULLBufferInterface::unmap( UnmapOptions unmapOption,
                                        size_t flushStartElem, size_t flushSizeElem )
    {
        assert( flushStartElem <= mBuffer->mLastMappingCount &&
                "Flush starts after the end of the mapped region!" );
        assert( flushStartElem + flushSizeElem <= mBuffer->mLastMappingCount &&
                "Flush region out of bounds!" );

        bool canPersistentMap = static_cast<NULLVaoManager*>( mBuffer->mVaoManager )->
                                                                supportsArbBufferStorage();

        if( mBuffer->mBufferType <= BT_DYNAMIC_PERSISTENT ||
            unmapOption == UO_UNMAP_ALL || !canPersistentMap )
        {
            if( !flushSizeElem )
                flushSizeElem = mBuffer->mLastMappingCount - flushStartElem;

            if( unmapOption == UO_UNMAP_ALL || !canPersistentMap ||
                mBuffer->mBufferType == BT_DYNAMIC_DEFAULT )
            {
                mMappedPtr = 0;
            }
        }
    }
    //-----------------------------------------------------------------------------------
    void NULLBufferInterface::advanceFrame(void)
    {
        advanceFrame( true );
    }
    //-----------------------------------------------------------------------------------
    size_t NULLBufferInterface::advanceFrame( bool bAdvanceFrame )
    {
        NULLVaoManager *vaoManager = static_cast<NULLVaoManager*>( mBuffer->mVaoManager );
        size_t dynamicCurrentFrame = mBuffer->mFinalBufferStart - mBuffer->mInternalBufferStart;
        dynamicCurrentFrame /= mBuffer->_getInternalNumElements();

        dynamicCurrentFrame = (dynamicCurrentFrame + 1) % vaoManager->getDynamicBufferMultiplier();

        if( bAdvanceFrame )
        {
            mBuffer->mFinalBufferStart = mBuffer->mInternalBufferStart +
                                            dynamicCurrentFrame * mBuffer->_getInternalNumElements();
        }

        return dynamicCurrentFrame;
    }
    //-----------------------------------------------------------------------------------
    void NULLBufferInterface::regressFrame(void)
    {
        NULLVaoManager *vaoManager = static_cast<NULLVaoManager*>( mBuffer->mVaoManager );
        size_t dynamicCurrentFrame = mBuffer->mFinalBufferStart - mBuffer->mInternalBufferStart;
        dynamicCurrentFrame /= mBuffer->_getInternalNumElements();

        dynamicCurrentFrame = (dynamicCurrentFrame + vaoManager->getDynamicBufferMultiplier() - 1) %
                                vaoManager->getDynamicBufferMultiplier();

        mBuffer->mFinalBufferStart = mBuffer->mInternalBufferStart +
                                        dynamicCurrentFrame * mBuffer->_getInternalNumElements();
    }
    //-----------------------------------------------------------------------------------
    void NULLBufferInterface::_notifyBuffer( BufferPacked *buffer )
    {
        BufferInterface::_notifyBuffer( buffer );

        mNullDataPtr = reinterpret_cast<uint8*>( OGRE_MALLOC_SIMD( mBuffer->getTotalSizeBytes(),
                                                                    MEMCATEGORY_RENDERSYS ) );
    }
}


text:
AUTHFAILURE = 'AuthFailure'

# 操作失败。
FAILEDOPERATION = 'FailedOperation'

# 目标数据不存在。
FAILEDOPERATION_DATANOTFOUND = 'FailedOperation.DataNotFound'

# 重复数据。
FAILEDOPERATION_DUPLICATEDATA = 'FailedOperation.DuplicateData'

# 内部错误。
INTERNALERROR = 'InternalError'

# 参数错误。
INVALIDPARAMETER = 'InvalidParameter'

# 无效的资源ID,用于资源不存在或已过期。
INVALIDPARAMETER_RESOURCEID = 'InvalidParameter.ResourceId'

# 参数取值错误。
INVALIDPARAMETERVALUE = 'InvalidParameterValue'

# 超过配额限制。
LIMITEXCEEDED = 'LimitExceeded'

# 缺少参数错误。
MISSINGPARAMETER = 'MissingParameter'

# 操作被拒绝。
OPERATIONDENIED = 'OperationDenied'

# 请求的次数超过了频率限制。
REQUESTLIMITEXCEEDED = 'RequestLimitExceeded'

# 资源被占用。
RESOURCEINUSE = 'ResourceInUse'

# 资源不足。
RESOURCEINSUFFICIENT = 'ResourceInsufficient'

# 资源不存在。
RESOURCENOTFOUND = 'ResourceNotFound'

# 资源不可用。
RESOURCEUNAVAILABLE = 'ResourceUnavailable'

# 资源售罄。
RESOURCESSOLDOUT = 'ResourcesSoldOut'

# 未授权操作。
UNAUTHORIZEDOPERATION = 'UnauthorizedOperation'

# 无操作权限。
UNAUTHORIZEDOPERATION_NOPERMISSION = 'UnauthorizedOperation.NoPermission'

# 未知参数错误。
UNKNOWNPARAMETER = 'UnknownParameter'

# 操作不支持。
UNSUPPORTEDOPERATION = 'UnsupportedOperation'


text:
package service

import (
	"context"
	"testing"

	"go-common/app/interface/main/mcn/model/mcnmodel"

	"github.com/smartystreets/goconvey/convey"
)

func TestServiceGetUpAccountInfo(t *testing.T) {
	convey.Convey("GetUpAccountInfo", t, func(ctx convey.C) {
		var (
			c   = context.Background()
			arg = &mcnmodel.McnGetAccountReq{}
		)
		ctx.Convey("When everything goes positive", func(ctx convey.C) {
			result, err := s.GetUpAccountInfo(c, arg)
			ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
				ctx.So(err, convey.ShouldBeNil)
				ctx.So(result, convey.ShouldNotBeNil)
			})
		})
	})
}


text:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#ifdef _WIN32
	#include <windows.h>
	#include <winsock.h>
#else
   #ifndef hp10
	#include <sysent.h>
   #endif
   #include <signal.h>
   #include <arpa/inet.h>
   #include <netinet/tcp.h>
   #include <netdb.h>
   #include <sys/socket.h>
   #include <netinet/in.h>
   #include <unistd.h>
   #include <sys/types.h>
   #include <sys/wait.h>
   #ifdef sun4
      #include <poll.h>
      #include <time.h>
      #include <sys/time.h>
   #endif
   #ifdef irix6
      #include <sys/poll.h>
   #endif
   #ifdef hp700
      #include <sys/poll.h>
      #include <time.h>
      extern "C" int select(int, int*, int*, int*, const struct timeval*);
   #endif
   #define closesocket(sock) close(sock)
#endif

#include "lib.h"
#include "editor_api.h"
#include "connect_mgr.h"

#include "nameServCalls.h"
#include "CommProto.h"
#include "startproc.h"
#include "debug.h"

extern CConnectionDescriptor Connection;
#define EDITOR_NAME "Editor:Emacs"
#define INTEGRATOR_NAME "EmacsIntegrator"

//  ----------------------------------------------------------------------------------
//  These are the static routines used in io.
//  ----------------------------------------------------------------------------------

static int sendToServer( SOCKET s, char* msg ) {
	_DBG(fprintf(log_fd,"Sending message to the server: %s\n",msg));
	return sendReply( s, msg)*strlen(msg);
}

static char* getSelectionFile(void) {
	char msg[MAXLISPEXPR];
	static char file[MAXLISPEXPR];
	int ret = -1, msz;
	if(Connection.m_IntegratorSocket >= 0 ) {
		sprintf (msg, "(roverserv-get-current-file)");
		if( sendToServer(Connection.m_IntegratorSocket, msg) != SOCKET_ERROR ) {
			msz = getDataFromServer(Connection.m_IntegratorSocket, msg, MAXLISPEXPR, EditorDataHdr);
			if( msz ) {
				strncpy( file, msg, MAXLISPEXPR);
				file[MAXLISPEXPR-1] = 0;
			}
		}
	}
	_DBG(fprintf(log_fd,"Returning current selected file %s\n", file); );
    return file;
}

static int getSelectionLine(void) {
	char msg[MAXLISPEXPR];
	int ret = -1, msz;
	if( Connection.m_IntegratorSocket >= 0 ) {
		sprintf (msg, "(roverserv-get-current-line)");
		if( sendToServer(Connection.m_IntegratorSocket, msg) != SOCKET_ERROR ) {
			msz = getDataFromServer(Connection.m_IntegratorSocket, msg, MAXLISPEXPR, EditorDataHdr);
			if( msz ) ret = atoi(msg);
		}
	}
	_DBG(fprintf(log_fd,"Get cursor position (line number) ret = %d\n", ret); );
	return ret;
}

static int getSelectionLineOffset(void) {
	char msg[MAXLISPEXPR];
	int ret = -1, msz;
	if( Connection.m_IntegratorSocket >= 0 ) {
		sprintf (msg, "(roverserv-get-current-column)");
		if( sendToServer(Connection.m_IntegratorSocket, msg) != SOCKET_ERROR ) {
			msz = getDataFromServer(Connection.m_IntegratorSocket, msg, MAXLISPEXPR, EditorDataHdr);
			if( msz ) ret = atoi(msg);
		}
	}
	_DBG(fprintf(log_fd,"Get cursor position (within line) ret = %d\n", ret); );
	return ret;
}

// This is the rountine to receive data from the emacs "server".
// Format of data from emacs server is (ERROR|OK)/NUMBYTESDATA:DATA
// Data is extracted and returned to calling function.
static int getFromServer(SOCKET s, char *msg, int msize ) {
	_DBG(fprintf(log_fd,"Reading string from the server..."));
	char* cmdServer = getString(s);
	if(cmdServer == NULL) {
		_DBG(fprintf(log_fd,"No reply!!!\n"));
		return 0;
	} else
		strcpy(msg,cmdServer+2);
	_DBG(fprintf(log_fd,"Reply is %s\n",msg));
	return strlen(msg);
}

//  -----------------------------------------------------------------------------
//  All Externally Published Rountines
//  -----------------------------------------------------------------------------
void ConstructServicePrefix(char prefix[1024]) {
	char*	userName;
	char*	dnStart;
	// determine the current host name
	gethostname(prefix,1024);
	// this part of code just removes domain name suffix from the hostname
	if((dnStart = strchr(prefix,'.'))>0)
		prefix[dnStart-prefix] = 0;
	// constructing service prefix
	strcat(prefix,":");
	userName = getenv("USER");
#ifdef _WIN32
	if(userName == NULL) {
		char	userString[1024];
		DWORD	nUserSize = 1024;
		if(GetUserName(userString,&nUserSize)==TRUE)
			userName = userString;
	}
#endif
	if(userName!=NULL) {
		strcat(prefix,userName);
		strcat(prefix,":");
	}
}

char *GetIntegratorName(void) {
static char integratorName[1024];
	ConstructServicePrefix(integratorName);
	strcat(integratorName,INTEGRATOR_NAME);
	return integratorName;
}

char *GetEditorName(void) {
static char	editorName[1024];
	ConstructServicePrefix(editorName);
	strcat(editorName,EDITOR_NAME);
	return editorName;
}

// Launch emacs.  Sources roverserv.el and starts server exec.
// Emacs and this server talk via a pipe.  This is required because emacs
// Must spawn anything it wants to talk to.  We want the browser to pre-exist emacs
// so this inbetween in necessary.
#ifdef _WIN32
int LaunchIntegrator(void) {
	char intname[1024];
	char msg[1024];
	HKEY someKey;

	#define EMACS_PATH_LEN 1024l

	char some_dir[EMACS_PATH_LEN];
	char some_path[EMACS_PATH_LEN];
	char tmp_path[EMACS_PATH_LEN];
	DWORD some_dir_len = sizeof(some_dir);
	DWORD paramType = REG_EXPAND_SZ;

	_DBG(fprintf(log_fd,"Starting Integrator... \n"));

	// getting emacs path (if it's properly installed)
	// this is directory for emacs
	some_path[0]=0;
	LONG res = RegOpenKeyEx(HKEY_LOCAL_MACHINE,"Software\\GNU\\Emacs",0,KEY_READ,&someKey);
	if(res == ERROR_SUCCESS) {
		res = RegQueryValueEx( someKey, "emacs_dir", NULL, &paramType, (BYTE *)some_dir, &some_dir_len);
		if(res == ERROR_SUCCESS) {
			// this is directory for emacs - it must be something like this "%emacs_dir%/bin"
			some_dir_len = sizeof(some_path);
			res = RegQueryValueEx( someKey, "EMACSPATH", NULL, &paramType, (BYTE *)some_path, &some_dir_len);
			if(res!=ERROR_SUCCESS)	{
				some_path[0]=0;
				some_dir[0]=0;
			}
		}
	}
	// constructing emacs path
	if(some_path[0] == '%') {
		for(unsigned i=1;i<strlen(some_path) && some_path[i]!='%';i++)
			tmp_path[i-1]=some_path[i];
		if( i != strlen(some_path) ) {
			tmp_path[i-1] = 0;
			i++;
		}
		if(strcmp(tmp_path,"emacs_dir")==0) {
			strcat(some_dir,some_path+i);
		} else {
			strcpy(some_dir,some_path);
		}
	} else {
		strcat(some_dir,some_path);
	}
	// adding emacs path to the launch parameter
	if(strlen(some_dir)>0) {
		strcpy(tmp_path,"\"");
		strcat(tmp_path,some_dir);
		strcat(tmp_path,"\\emacs.exe\"");
	} else {
		strcpy(tmp_path,"emacs.exe");
	}
	// we convert our path string to short file name because emacs doesn't understand spaces
	// in file names
	strcpy(intname,tmp_path);
	strcat(intname," -l ");

    // getting DIScover directory
	char* envPath = getenv("PSETHOME");
	if(envPath)
		strcpy(some_dir,envPath);
	else
		strcpy(some_dir,"");

	strcpy(tmp_path,"\"");
	strcat(tmp_path,some_dir);
	strcat(tmp_path,"\\bin\\roverserv.el\"");
	// we convert our path string to short file name because emacs doesn't understand spaces
	// in file names
	strcat(intname,tmp_path);

	// we convert our path string to short file name because emacs doesn't understand spaces
	// in file names
	strcpy(some_path,some_dir);
	if(some_path[strlen(some_path)-1]=='\\' || some_path[strlen(some_path)-1]=='/')
		some_path[strlen(some_path)-1]=0;

	for(int i=strlen(intname); i; i--) if(intname[i]=='/') intname[i]='\\';
	for(i=strlen(some_path); i; i--) if(some_path[i]=='/') some_path[i]='\\';

	DWORD retCode;
	if((retCode = start_new_process(intname,START_NO_WAIT,OPEN_WINDOW))==-1) {
		wsprintf (msg,"%s - return code %d\n", intname, retCode);
		_DBG(fprintf(log_fd,"Error while launching integrator server. Command is %s\n",intname));
		return 0;
	}
	_DBG(fprintf(log_fd,"Integrator started. Command is %s\n",intname));
	return 1;
}
#else
int LaunchIntegrator(void) {
	char emacsCmd[1024];
	char msg[1024];

	_DBG(fprintf(log_fd,"Starting Integrator... \n"));

    // getting DIScover directory
	char* envPath = getenv("PSETHOME");
	if(envPath) {
		strcpy(emacsCmd,"\"");
		strcat(emacsCmd,envPath);
		strcat(emacsCmd,"/bin/emacs\" -l ");
		strcat(emacsCmd,"\"");
		strcat(emacsCmd,envPath);
		strcat(emacsCmd,"/bin/");
	} else
		strcpy(emacsCmd,"emacs -l \"");
	strcat(emacsCmd,"roverserv.el\"");

	DWORD retCode;
	if((retCode = start_new_process(emacsCmd,START_NO_WAIT,OPEN_WINDOW))==-1) {
		sprintf (msg,"%s - return code %d\n",emacsCmd, retCode);
		_DBG(fprintf(log_fd,"Error while launching integrator server. Command is %s\n",emacsCmd));
		return 0;
	}
	_DBG(fprintf(log_fd,"Integrator started. Command is %s\n",emacsCmd));
	return 1;
}
#endif

static char * trim( char * sep ) {
	while ( sep && *sep ) {
		if( *sep == ' ' || *sep == '\n' || *sep == '\r' )
			sep++;
		else
			break;
	}
	return sep;
}

// Used by driver to get incoming data from server.
int getDataFromServer(SOCKET s, char *msg, int msize, char * hdr ) {
	return getFromServer(s, msg, msize );
}

int MakeSelectionOnLine(char* file, int line, int lineoffset,int length) {
	char msg[MAXLISPEXPR];
	int ret = 0, msz;
	if( Connection.m_IntegratorSocket >= 0 ) {
		if( strlen(file) + 50 < MAXLISPEXPR ) {
			sprintf (msg, "(roverserv-select-region \"%s\" %d %d %d)", file, line, lineoffset, length );
			if( sendToServer(Connection.m_IntegratorSocket, msg) != SOCKET_ERROR ) {
				msz = getDataFromServer(Connection.m_IntegratorSocket, msg, MAXLISPEXPR, EditorDataHdr);
				if( msz >0 && !strncmp(msg, EMACSOK, strlen(EMACSOK) ) ) ret = 1;
			}
		}
	}
   _DBG(fprintf(log_fd,"Make selection: File:%s Line:%d Column:%d Length:%d.\n",file,line,lineoffset,length););
   return ret;
}

int ShowMessage(char* messag) {
	char msg[MAXLISPEXPR];
	int msz, ret = -1;
	if(messag && strlen(messag) && Connection.m_IntegratorSocket >= 0 ) {
		sprintf (msg, "info\t\"%s\"", messag);
		if( sendToServer(Connection.m_IntegratorSocket, msg) != SOCKET_ERROR ) {
			msz = getDataFromServer(Connection.m_IntegratorSocket, msg, MAXLISPEXPR, EditorDataHdr);
			if( msz > 0 ) ret = atoi(msg);
		}
	}
	_DBG(fprintf(log_fd,"Print message in status bar %s\n", messag););
	return ret;
}

struct selection {
	int line_offset;
	int column_offset;
	char *file;
} GSel = { -1, -1, NULL };

int FreezeSelection(void) {
  _DBG(fprintf(log_fd,"Freeze selection.\n"));
  GSel.file = getSelectionFile();
  GSel.line_offset = getSelectionLine();
  GSel.column_offset = getSelectionLineOffset();
  return 1;
}

char* GetSelectionFile(void) {
    return GSel.file;
}

int GetSelectionLine(void) {
	return GSel.line_offset;
}

int GetSelectionLineOffset(void) {
	return GSel.column_offset;
}

int OpenFileOnLine(char* file, int line) {
	char msg[MAXLISPEXPR];
	int ret = 1, msz;
	if( Connection.m_IntegratorSocket >= 0 ) {
		// roverserv-edit-files-quickly responses immeadiatedly without waiting
		// for errors, user interaction, etc.
		if( strlen(file) + 50 < MAXLISPEXPR ) {
			sprintf(msg, "open\t\"%s\"\t%d", file, line);
			if(sendToServer(Connection.m_IntegratorSocket, msg) != SOCKET_ERROR ) {
				msz = getDataFromServer(Connection.m_IntegratorSocket, msg, MAXLISPEXPR, EditorDataHdr);
				if( msz > 0 && !strncmp(msg, EMACSOK, strlen(EMACSOK) ) ) ret = 0;
			}
		}
	}
	_DBG(fprintf(log_fd,"Open file %s at line %d. ret = %d\n",file,line, ret); );
	return ret;
}

void decrementRefCount(SOCKET sock) {
	// do nothing - there is no such command
	return;
}

// returns maximum length of command
int getCommandLength(void) {
	return 1024;
}


text:
/**
 * @file
 * @brief
 *
 * @author Thomas Escher
 */

#ifndef CACHE_DATA_ACCESS_H
#define CACHE_DATA_ACCESS_H

#include "slam6d/data_types.h"

#include <boost/interprocess/sync/interprocess_upgradable_mutex.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>

// hide the boost namespace and shorten others
namespace
{
  namespace ip = boost::interprocess;
}

/**
 * @brief Access object for data in a CacheObject.
 *
 * This object functions as a reading lock on the data in a CacheObject. While any of these objects exists with a lock on a CacheObject it is guaranteed the CacheManager won't remove it from memory when flushing the cache.
 * It is derived from the DataPointer class, which already represents application-specific access operators for this data, and builds the locking functionality on top of it.
 * A CacheDataAccess is returned by the accessing function in a CacheObject as a temporary and is constructed by these means (&&-ctor). Size and data pointer will be copied and the reading lock will also be obtained. When all CacheDataAccess instances for a given CacheObject are destroyed (fell out of scope) all read locks are gone and the CacheManager is able to remove its contained data from memory.
 */
class CacheDataAccess : public DataPointer {
  class Lock : public PrivateImplementation {
  public:
    Lock(ip::interprocess_upgradable_mutex& mutex);
    // on destruction, the lock has to be released, which comes from m_lock destruction
    virtual ~Lock() {}
  private:
    ip::sharable_lock<ip::interprocess_upgradable_mutex> m_lock;
  };
public:
  //  CacheDataAccess& operator=(const CacheDataAccess&) = delete;
  //  CacheDataAccess(const CacheDataAccess&) = delete;

  //! Aquires a lock on the mutex and takes assigned data
  CacheDataAccess(ip::interprocess_upgradable_mutex& mutex, unsigned int& size, unsigned char* data);

  CacheDataAccess(CacheDataAccess&& other) : DataPointer(other) {}

  //! Non-locking version
  //CacheDataAccess(unsigned int& size, unsigned char* data);

  //! Transfers the lock to this instance and also takes assigned data
  //CacheDataAccess(const CacheDataAccess& other);
};

#endif //CACHE_DATA_ACCESS_H


text:
<ion-view>
    <ion-nav-title>

{{"Rifiuto"|translate}}

{{nome|translate}}

    </ion-nav-title>

    <ion-nav-buttons side="left">
        <button ng-click="back()" class="row button button-icon ion-ios7-arrow-back">

        </button>
    </ion-nav-buttons>

    <ion-tabs class="tabs-balanced tabs-top tabs-100r">
        <ion-tab title="{{'PUNTI DI RACCOLTA'|translate}}">
            <ion-view>
                <ion-content class="expandable-list-items" scroll="false">

                                        {{item.tipologiaPuntoRaccolta|translate}}

                                        {{item.tipologiaRaccolta|translate}}

                                        {{item.infoRaccolta|translate}}

                                        {{punto.dettaglioIndirizzo || punto.indirizzo}}

                                {{'empty_elem'|translate}}

                </ion-content>
            </ion-view>
        </ion-tab>
    </ion-tabs>
</ion-view>


text:
(function(doc) {
  'use strict';

  let buttons = doc.querySelectorAll('.pt-button-navigation')
  let allButtons = Array.from(buttons)
  allButtons.map( (item, index) => {
    item.addEventListener('click', function() {search(index)})
    item.addEventListener('touchstart', function() {search(index)})
  })

  let cleanButton = doc.querySelector('.pt-button-white')
  function cleanBtnFunction() {
    Array.from(doc.querySelectorAll('.pt-menu-items')).map( item => item.classList.remove('hide'));
  }
  cleanButton.addEventListener('click', cleanBtnFunction )
  cleanButton.addEventListener('touchstart', cleanBtnFunction )

  function search(arrayIndex) {
    let bars = doc.querySelectorAll('.pt-menu-items')
    let searchBars = Array.from(bars)

    searchBars.map( (item ) => {
      item.classList.remove('hide')
      item.classList.contains(`${arrayIndex}`) ?
        '' :
        item.classList.toggle('hide')
      }
    )
  }

})(document);