text:
// Debugging mode support code -*- C++ -*-

// Copyright (C) 2003-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.

// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://www.gnu.org/licenses/>.

#include <debug/debug.h>
#include <debug/safe_sequence.h>
#include <debug/safe_unordered_container.h>
#include <debug/safe_iterator.h>
#include <debug/safe_local_iterator.h>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <functional>

using namespace std;

namespace
{
  /** Returns different instances of __mutex depending on the passed address
   *  in order to limit contention without breaking current library binary
   *  compatibility. */
  __gnu_cxx::__mutex&
  get_safe_base_mutex(void* __address)
  {
    const size_t mask = 0xf;
    static __gnu_cxx::__mutex safe_base_mutex[mask + 1];
    const size_t index = _Hash_impl::hash(__address) & mask;
    return safe_base_mutex[index];
  }

  void
  swap_its(__gnu_debug::_Safe_sequence_base& __lhs,
	   __gnu_debug::_Safe_iterator_base*& __lhs_its,
	   __gnu_debug::_Safe_sequence_base& __rhs,
	   __gnu_debug::_Safe_iterator_base*& __rhs_its)
  {
    swap(__lhs_its, __rhs_its);
    __gnu_debug::_Safe_iterator_base* __iter;
    for (__iter = __rhs_its; __iter; __iter = __iter->_M_next)
      __iter->_M_sequence = &__rhs;
    for (__iter = __lhs_its; __iter; __iter = __iter->_M_next)
      __iter->_M_sequence = &__lhs;
  }

  void
  swap_seq(__gnu_debug::_Safe_sequence_base& __lhs,
	   __gnu_debug::_Safe_sequence_base& __rhs)
  {
    swap(__lhs._M_version, __rhs._M_version);
    swap_its(__lhs, __lhs._M_iterators,
	     __rhs, __rhs._M_iterators);
    swap_its(__lhs, __lhs._M_const_iterators,
	     __rhs, __rhs._M_const_iterators);
  }

  void
  swap_ucont(__gnu_debug::_Safe_unordered_container_base& __lhs,
	    __gnu_debug::_Safe_unordered_container_base& __rhs)
  {
    swap_seq(__lhs, __rhs);
    swap_its(__lhs, __lhs._M_local_iterators,
	     __rhs, __rhs._M_local_iterators);
    swap_its(__lhs, __lhs._M_const_local_iterators,
	     __rhs, __rhs._M_const_local_iterators);
  }

  void
  detach_all(__gnu_debug::_Safe_iterator_base* __iter)
  {
    for (; __iter;)
      {
	__gnu_debug::_Safe_iterator_base* __old = __iter;
	__iter = __iter->_M_next;
	__old->_M_reset();
      }
  }
} // anonymous namespace

namespace __gnu_debug
{
  const char* _S_debug_messages[] =
  {
    // General Checks
    "function requires a valid iterator range [%1.name;, %2.name;)",
    "attempt to insert into container with a singular iterator",
    "attempt to insert into container with an iterator"
    " from a different container",
    "attempt to erase from container with a %2.state; iterator",
    "attempt to erase from container with an iterator"
    " from a different container",
    "attempt to subscript container with out-of-bounds index %2;,"
    " but container only holds %3; elements",
    "attempt to access an element in an empty container",
    "elements in iterator range [%1.name;, %2.name;)"
    " are not partitioned by the value %3;",
    "elements in iterator range [%1.name;, %2.name;)"
    " are not partitioned by the predicate %3; and value %4;",
    "elements in iterator range [%1.name;, %2.name;) are not sorted",
    "elements in iterator range [%1.name;, %2.name;)"
    " are not sorted according to the predicate %3;",
    "elements in iterator range [%1.name;, %2.name;) do not form a heap",
    "elements in iterator range [%1.name;, %2.name;)"
    " do not form a heap with respect to the predicate %3;",
    // std::bitset checks
    "attempt to write through a singular bitset reference",
    "attempt to read from a singular bitset reference",
    "attempt to flip a singular bitset reference",
    // std::list checks
    "attempt to splice a list into itself",
    "attempt to splice lists with unequal allocators",
    "attempt to splice elements referenced by a %1.state; iterator",
    "attempt to splice an iterator from a different container",
    "splice destination %1.name;"
    " occurs within source range [%2.name;, %3.name;)",
    // iterator checks
    "attempt to initialize an iterator that will immediately become singular",
    "attempt to copy-construct an iterator from a singular iterator",
    "attempt to construct a constant iterator"
    " from a singular mutable iterator",
    "attempt to copy from a singular iterator",
    "attempt to dereference a %1.state; iterator",
    "attempt to increment a %1.state; iterator",
    "attempt to decrement a %1.state; iterator",
    "attempt to subscript a %1.state; iterator %2; step from"
    " its current position, which falls outside its dereferenceable range",
    "attempt to advance a %1.state; iterator %2; steps,"
    " which falls outside its valid range",
    "attempt to retreat a %1.state; iterator %2; steps,"
    " which falls outside its valid range",
    "attempt to compare a %1.state; iterator to a %2.state; iterator",
    "attempt to compare iterators from different sequences",
    "attempt to order a %1.state; iterator to a %2.state; iterator",
    "attempt to order iterators from different sequences",
    "attempt to compute the difference between a %1.state;"
    " iterator to a %2.state; iterator",
    "attempt to compute the different between two iterators"
    " from different sequences",
    // istream_iterator
    "attempt to dereference an end-of-stream istream_iterator",
    "attempt to increment an end-of-stream istream_iterator",
    // ostream_iterator
    "attempt to output via an ostream_iterator with no associated stream",
    // istreambuf_iterator
    "attempt to dereference an end-of-stream istreambuf_iterator"
    " (this is a GNU extension)",
    "attempt to increment an end-of-stream istreambuf_iterator",
    // std::forward_list
    "attempt to insert into container after an end iterator",
    "attempt to erase from container after a %2.state; iterator not followed"
    " by a dereferenceable one",
    "function requires a valid iterator range (%2.name;, %3.name;)"
    ", \"%2.name;\" shall be before and not equal to \"%3.name;\"",
    // std::unordered_container::local_iterator
    "attempt to compare local iterators from different unordered container"
    " buckets",
    "function requires a non-empty iterator range [%1.name;, %2.name;)",
    "attempt to self move assign",
    "attempt to access container with out-of-bounds bucket index %2;,"
    " container only holds %3; buckets",
    "load factor shall be positive",
    "allocators must be equal"
  };

  void
  _Safe_sequence_base::
  _M_detach_all()
  {
    __gnu_cxx::__scoped_lock sentry(_M_get_mutex());
    detach_all(_M_iterators);
    _M_iterators = 0;

    detach_all(_M_const_iterators);
    _M_const_iterators = 0;
  }

  void
  _Safe_sequence_base::
  _M_detach_singular()
  {
    __gnu_cxx::__scoped_lock sentry(_M_get_mutex());
    for (_Safe_iterator_base* __iter = _M_iterators; __iter;)
      {
	_Safe_iterator_base* __old = __iter;
	__iter = __iter->_M_next;
	if (__old->_M_singular())
	  __old->_M_detach_single();
      }

    for (_Safe_iterator_base* __iter2 = _M_const_iterators; __iter2;)
      {
	_Safe_iterator_base* __old = __iter2;
	__iter2 = __iter2->_M_next;
	if (__old->_M_singular())
	  __old->_M_detach_single();
      }
  }

  void
  _Safe_sequence_base::
  _M_revalidate_singular()
  {
    __gnu_cxx::__scoped_lock sentry(_M_get_mutex());
    for (_Safe_iterator_base* __iter = _M_iterators; __iter;
	 __iter = __iter->_M_next)
      __iter->_M_version = _M_version;

    for (_Safe_iterator_base* __iter2 = _M_const_iterators; __iter2;
	 __iter2 = __iter2->_M_next)
      __iter2->_M_version = _M_version;
  }

  void
  _Safe_sequence_base::
  _M_swap(_Safe_sequence_base& __x)
  {
    // We need to lock both sequences to swap
    using namespace __gnu_cxx;
    __mutex *__this_mutex = &_M_get_mutex();
    __mutex *__x_mutex = &__x._M_get_mutex();
    if (__this_mutex == __x_mutex)
      {
	__scoped_lock __lock(*__this_mutex);
	swap_seq(*this, __x);
      }
    else
      {
	__scoped_lock __l1(__this_mutex < __x_mutex
			     ? *__this_mutex : *__x_mutex);
	__scoped_lock __l2(__this_mutex < __x_mutex
			     ? *__x_mutex : *__this_mutex);
	swap_seq(*this, __x);
      }
  }

  __gnu_cxx::__mutex&
  _Safe_sequence_base::
  _M_get_mutex() throw ()
  { return get_safe_base_mutex(this); }

  void
  _Safe_sequence_base::
  _M_attach(_Safe_iterator_base* __it, bool __constant)
  {
    __gnu_cxx::__scoped_lock sentry(_M_get_mutex());
    _M_attach_single(__it, __constant);
  }

  void
  _Safe_sequence_base::
  _M_attach_single(_Safe_iterator_base* __it, bool __constant) throw ()
  {
    _Safe_iterator_base*& __its =
      __constant ? _M_const_iterators : _M_iterators;
    __it->_M_next = __its;
    if (__it->_M_next)
      __it->_M_next->_M_prior = __it;
    __its = __it;
  }

  void
  _Safe_sequence_base::
  _M_detach(_Safe_iterator_base* __it)
  {
    // Remove __it from this sequence's list
    __gnu_cxx::__scoped_lock sentry(_M_get_mutex());
    _M_detach_single(__it);
  }

  void
  _Safe_sequence_base::
  _M_detach_single(_Safe_iterator_base* __it) throw ()
  {
    // Remove __it from this sequence's list
    __it->_M_unlink();
    if (_M_const_iterators == __it)
      _M_const_iterators = __it->_M_next;
    if (_M_iterators == __it)
      _M_iterators = __it->_M_next;
  }

  void
  _Safe_iterator_base::
  _M_attach(_Safe_sequence_base* __seq, bool __constant)
  {
    _M_detach();

    // Attach to the new sequence (if there is one)
    if (__seq)
      {
	_M_sequence = __seq;
	_M_version = _M_sequence->_M_version;
	_M_sequence->_M_attach(this, __constant);
      }
  }

  void
  _Safe_iterator_base::
  _M_attach_single(_Safe_sequence_base* __seq, bool __constant) throw ()
  {
    _M_detach_single();

    // Attach to the new sequence (if there is one)
    if (__seq)
      {
	_M_sequence = __seq;
	_M_version = _M_sequence->_M_version;
	_M_sequence->_M_attach_single(this, __constant);
      }
  }

  void
  _Safe_iterator_base::
  _M_detach()
  {
    if (_M_sequence)
      _M_sequence->_M_detach(this);

    _M_reset();
  }

  void
  _Safe_iterator_base::
  _M_detach_single() throw ()
  {
    if (_M_sequence)
      _M_sequence->_M_detach_single(this);

    _M_reset();
  }

  void
  _Safe_iterator_base::
  _M_reset() throw ()
  {
    _M_sequence = 0;
    _M_version = 0;
    _M_prior = 0;
    _M_next = 0;
  }

  bool
  _Safe_iterator_base::
  _M_singular() const throw ()
  { return !_M_sequence || _M_version != _M_sequence->_M_version; }

  bool
  _Safe_iterator_base::
  _M_can_compare(const _Safe_iterator_base& __x) const throw ()
  {
    return (!_M_singular()
	    && !__x._M_singular() && _M_sequence == __x._M_sequence);
  }

  __gnu_cxx::__mutex&
  _Safe_iterator_base::
  _M_get_mutex() throw ()
  { return get_safe_base_mutex(_M_sequence); }

  _Safe_unordered_container_base*
  _Safe_local_iterator_base::
  _M_get_container() const _GLIBCXX_NOEXCEPT
  { return static_cast<_Safe_unordered_container_base*>(_M_sequence); }

  void
  _Safe_local_iterator_base::
  _M_attach(_Safe_sequence_base* __cont, bool __constant)
  {
    _M_detach();

    // Attach to the new container (if there is one)
    if (__cont)
      {
	_M_sequence = __cont;
	_M_version = _M_sequence->_M_version;
	_M_get_container()->_M_attach_local(this, __constant);
      }
  }

  void
  _Safe_local_iterator_base::
  _M_attach_single(_Safe_sequence_base* __cont, bool __constant) throw ()
  {
    _M_detach_single();

    // Attach to the new container (if there is one)
    if (__cont)
      {
	_M_sequence = __cont;
	_M_version = _M_sequence->_M_version;
	_M_get_container()->_M_attach_local_single(this, __constant);
      }
  }

  void
  _Safe_local_iterator_base::
  _M_detach()
  {
    if (_M_sequence)
      _M_get_container()->_M_detach_local(this);

    _M_reset();
  }

  void
  _Safe_local_iterator_base::
  _M_detach_single() throw ()
  {
    if (_M_sequence)
      _M_get_container()->_M_detach_local_single(this);

    _M_reset();
  }

  void
  _Safe_unordered_container_base::
  _M_detach_all()
  {
    __gnu_cxx::__scoped_lock sentry(_M_get_mutex());
    detach_all(_M_iterators);
    _M_iterators = 0;

    detach_all(_M_const_iterators);
    _M_const_iterators = 0;

    detach_all(_M_local_iterators);
    _M_local_iterators = 0;

    detach_all(_M_const_local_iterators);
    _M_const_local_iterators = 0;
  }

  void
  _Safe_unordered_container_base::
  _M_swap(_Safe_unordered_container_base& __x)
  {
    // We need to lock both containers to swap
    using namespace __gnu_cxx;
    __mutex *__this_mutex = &_M_get_mutex();
    __mutex *__x_mutex = &__x._M_get_mutex();
    if (__this_mutex == __x_mutex)
      {
	__scoped_lock __lock(*__this_mutex);
	swap_ucont(*this, __x);
      }
    else
      {
	__scoped_lock __l1(__this_mutex < __x_mutex
			     ? *__this_mutex : *__x_mutex);
	__scoped_lock __l2(__this_mutex < __x_mutex
			     ? *__x_mutex : *__this_mutex);
	swap_ucont(*this, __x);
      }
  }

  void
  _Safe_unordered_container_base::
  _M_attach_local(_Safe_iterator_base* __it, bool __constant)
  {
    __gnu_cxx::__scoped_lock sentry(_M_get_mutex());
    _M_attach_local_single(__it, __constant);
  }

  void
  _Safe_unordered_container_base::
  _M_attach_local_single(_Safe_iterator_base* __it, bool __constant) throw ()
  {
    _Safe_iterator_base*& __its =
      __constant ? _M_const_local_iterators : _M_local_iterators;
    __it->_M_next = __its;
    if (__it->_M_next)
      __it->_M_next->_M_prior = __it;
    __its = __it;
  }

  void
  _Safe_unordered_container_base::
  _M_detach_local(_Safe_iterator_base* __it)
  {
    // Remove __it from this container's list
    __gnu_cxx::__scoped_lock sentry(_M_get_mutex());
    _M_detach_local_single(__it);
  }

  void
  _Safe_unordered_container_base::
  _M_detach_local_single(_Safe_iterator_base* __it) throw ()
  {
    // Remove __it from this container's list
    __it->_M_unlink();
    if (_M_const_local_iterators == __it)
      _M_const_local_iterators = __it->_M_next;
    if (_M_local_iterators == __it)
      _M_local_iterators = __it->_M_next;
  }

  void
  _Error_formatter::_Parameter::
  _M_print_field(const _Error_formatter* __formatter, const char* __name) const
  {
    assert(this->_M_kind != _Parameter::__unused_param);
    const int __bufsize = 64;
    char __buf[__bufsize];

    if (_M_kind == __iterator)
      {
	if (strcmp(__name, "name") == 0)
	  {
	    assert(_M_variant._M_iterator._M_name);
	    __formatter->_M_print_word(_M_variant._M_iterator._M_name);
	  }
	else if (strcmp(__name, "address") == 0)
	  {
	    __formatter->_M_format_word(__buf, __bufsize, "%p",
					_M_variant._M_iterator._M_address);
	    __formatter->_M_print_word(__buf);
	  }
	else if (strcmp(__name, "type") == 0)
	  {
	    if (!_M_variant._M_iterator._M_type)
	      __formatter->_M_print_word("<unknown type>");
	    else
	      // TBD: demangle!
	      __formatter->_M_print_word(_M_variant._M_iterator.
					 _M_type->name());
	  }
	else if (strcmp(__name, "constness") == 0)
	  {
	    static const char* __constness_names[__last_constness] =
	      {
		"<unknown>",
		"constant",
		"mutable"
	      };
	    __formatter->_M_print_word(__constness_names[_M_variant.
							 _M_iterator.
							 _M_constness]);
	  }
	else if (strcmp(__name, "state") == 0)
	  {
	    static const char* __state_names[__last_state] =
	      {
		"<unknown>",
		"singular",
		"dereferenceable (start-of-sequence)",
		"dereferenceable",
		"past-the-end",
		"before-begin"
	      };
	    __formatter->_M_print_word(__state_names[_M_variant.
						     _M_iterator._M_state]);
	  }
	else if (strcmp(__name, "sequence") == 0)
	  {
	    assert(_M_variant._M_iterator._M_sequence);
	    __formatter->_M_format_word(__buf, __bufsize, "%p",
					_M_variant._M_iterator._M_sequence);
	    __formatter->_M_print_word(__buf);
	  }
	else if (strcmp(__name, "seq_type") == 0)
	  {
	    if (!_M_variant._M_iterator._M_seq_type)
	      __formatter->_M_print_word("<unknown seq_type>");
	    else
	      // TBD: demangle!
	      __formatter->_M_print_word(_M_variant._M_iterator.
					 _M_seq_type->name());
	  }
	else
	  assert(false);
      }
    else if (_M_kind == __sequence)
      {
	if (strcmp(__name, "name") == 0)
	  {
	    assert(_M_variant._M_sequence._M_name);
	    __formatter->_M_print_word(_M_variant._M_sequence._M_name);
	  }
	else if (strcmp(__name, "address") == 0)
	  {
	    assert(_M_variant._M_sequence._M_address);
	    __formatter->_M_format_word(__buf, __bufsize, "%p",
					_M_variant._M_sequence._M_address);
	    __formatter->_M_print_word(__buf);
	  }
	else if (strcmp(__name, "type") == 0)
	  {
	    if (!_M_variant._M_sequence._M_type)
	      __formatter->_M_print_word("<unknown type>");
	    else
	      // TBD: demangle!
	      __formatter->_M_print_word(_M_variant._M_sequence.
					 _M_type->name());
	  }
	else
	  assert(false);
      }
    else if (_M_kind == __integer)
      {
	if (strcmp(__name, "name") == 0)
	  {
	    assert(_M_variant._M_integer._M_name);
	    __formatter->_M_print_word(_M_variant._M_integer._M_name);
	  }
	else
	assert(false);
      }
    else if (_M_kind == __string)
      {
	if (strcmp(__name, "name") == 0)
	  {
	    assert(_M_variant._M_string._M_name);
	    __formatter->_M_print_word(_M_variant._M_string._M_name);
	  }
	else
	  assert(false);
      }
    else
      {
	assert(false);
      }
  }

  void
  _Error_formatter::_Parameter::
  _M_print_description(const _Error_formatter* __formatter) const
  {
    const int __bufsize = 128;
    char __buf[__bufsize];

    if (_M_kind == __iterator)
      {
	__formatter->_M_print_word("iterator ");
	if (_M_variant._M_iterator._M_name)
	  {
	    __formatter->_M_format_word(__buf, __bufsize, "\"%s\" ",
					_M_variant._M_iterator._M_name);
	    __formatter->_M_print_word(__buf);
	  }

	__formatter->_M_format_word(__buf, __bufsize, "@ 0x%p {\n",
				    _M_variant._M_iterator._M_address);
	__formatter->_M_print_word(__buf);
	if (_M_variant._M_iterator._M_type)
	  {
	    __formatter->_M_print_word("type = ");
	    _M_print_field(__formatter, "type");

	    if (_M_variant._M_iterator._M_constness != __unknown_constness)
	      {
		__formatter->_M_print_word(" (");
		_M_print_field(__formatter, "constness");
		__formatter->_M_print_word(" iterator)");
	      }
	    __formatter->_M_print_word(";\n");
	  }

	if (_M_variant._M_iterator._M_state != __unknown_state)
	  {
	    __formatter->_M_print_word("  state = ");
	    _M_print_field(__formatter, "state");
	    __formatter->_M_print_word(";\n");
	  }

	if (_M_variant._M_iterator._M_sequence)
	  {
	    __formatter->_M_print_word("  references sequence ");
	    if (_M_variant._M_iterator._M_seq_type)
	      {
		__formatter->_M_print_word("with type `");
		_M_print_field(__formatter, "seq_type");
		__formatter->_M_print_word("' ");
	      }

	    __formatter->_M_format_word(__buf, __bufsize, "@ 0x%p\n",
					_M_variant._M_sequence._M_address);
	    __formatter->_M_print_word(__buf);
	  }
	__formatter->_M_print_word("}\n");
      }
    else if (_M_kind == __sequence)
      {
	__formatter->_M_print_word("sequence ");
	if (_M_variant._M_sequence._M_name)
	  {
	    __formatter->_M_format_word(__buf, __bufsize, "\"%s\" ",
					_M_variant._M_sequence._M_name);
	    __formatter->_M_print_word(__buf);
	  }

	__formatter->_M_format_word(__buf, __bufsize, "@ 0x%p {\n",
				    _M_variant._M_sequence._M_address);
	__formatter->_M_print_word(__buf);

	if (_M_variant._M_sequence._M_type)
	  {
	    __formatter->_M_print_word("  type = ");
	    _M_print_field(__formatter, "type");
	    __formatter->_M_print_word(";\n");
	  }
	__formatter->_M_print_word("}\n");
      }
  }

  const _Error_formatter&
  _Error_formatter::_M_message(_Debug_msg_id __id) const throw ()
  { return this->_M_message(_S_debug_messages[__id]); }

  void
  _Error_formatter::_M_error() const
  {
    const int __bufsize = 128;
    char __buf[__bufsize];

    // Emit file & line number information
    _M_column = 1;
    _M_wordwrap = false;
    if (_M_file)
      {
	_M_format_word(__buf, __bufsize, "%s:", _M_file);
	_M_print_word(__buf);
	_M_column += strlen(__buf);
      }

    if (_M_line > 0)
      {
	_M_format_word(__buf, __bufsize, "%u:", _M_line);
	_M_print_word(__buf);
	_M_column += strlen(__buf);
      }

    if (_M_max_length)
      _M_wordwrap = true;
    _M_print_word("error: ");

    // Print the error message
    assert(_M_text);
    _M_print_string(_M_text);
    _M_print_word(".\n");

    // Emit descriptions of the objects involved in the operation
    _M_wordwrap = false;
    bool __has_noninteger_parameters = false;
    for (unsigned int __i = 0; __i < _M_num_parameters; ++__i)
      {
	if (_M_parameters[__i]._M_kind == _Parameter::__iterator
	    || _M_parameters[__i]._M_kind == _Parameter::__sequence)
	  {
	    if (!__has_noninteger_parameters)
	      {
		_M_first_line = true;
		_M_print_word("\nObjects involved in the operation:\n");
		__has_noninteger_parameters = true;
	      }
	    _M_parameters[__i]._M_print_description(this);
	  }
      }

    abort();
  }

  template<typename _Tp>
    void
    _Error_formatter::_M_format_word(char* __buf,
				     int __n __attribute__ ((__unused__)),
				     const char* __fmt, _Tp __s) const throw ()
    {
#ifdef _GLIBCXX_USE_C99
      std::snprintf(__buf, __n, __fmt, __s);
#else
      std::sprintf(__buf, __fmt, __s);
#endif
    }

  void
  _Error_formatter::_M_print_word(const char* __word) const
  {
    if (!_M_wordwrap)
      {
	fprintf(stderr, "%s", __word);
	return;
      }

    size_t __length = strlen(__word);
    if (__length == 0)
      return;

    if ((_M_column + __length < _M_max_length)
	|| (__length >= _M_max_length && _M_column == 1))
      {
	// If this isn't the first line, indent
	if (_M_column == 1 && !_M_first_line)
	  {
	    char __spacing[_M_indent + 1];
	    for (int i = 0; i < _M_indent; ++i)
	      __spacing[i] = ' ';
	    __spacing[_M_indent] = '\0';
	    fprintf(stderr, "%s", __spacing);
	    _M_column += _M_indent;
	  }

	fprintf(stderr, "%s", __word);
	_M_column += __length;

	if (__word[__length - 1] == '\n')
	  {
	    _M_first_line = false;
	    _M_column = 1;
	  }
      }
    else
      {
	_M_column = 1;
	_M_print_word("\n");
	_M_print_word(__word);
      }
  }

  void
  _Error_formatter::
  _M_print_string(const char* __string) const
  {
    const char* __start = __string;
    const char* __finish = __start;
    const int __bufsize = 128;
    char __buf[__bufsize];

    while (*__start)
      {
	if (*__start != '%')
	  {
	    // [__start, __finish) denotes the next word
	    __finish = __start;
	    while (isalnum(*__finish))
	      ++__finish;
	    if (__start == __finish)
	      ++__finish;
	    if (isspace(*__finish))
	      ++__finish;

	    const ptrdiff_t __len = __finish - __start;
	    assert(__len < __bufsize);
	    memcpy(__buf, __start, __len);
	    __buf[__len] = '\0';
	    _M_print_word(__buf);
	    __start = __finish;

	    // Skip extra whitespace
	    while (*__start == ' ')
	      ++__start;

	    continue;
	  }

	++__start;
	assert(*__start);
	if (*__start == '%')
	  {
	    _M_print_word("%");
	    ++__start;
	    continue;
	  }

	// Get the parameter number
	assert(*__start >= '1' && *__start <= '9');
	size_t __param = *__start - '0';
	--__param;
	assert(__param < _M_num_parameters);

	// '.' separates the parameter number from the field
	// name, if there is one.
	++__start;
	if (*__start != '.')
	  {
	    assert(*__start == ';');
	    ++__start;
	    __buf[0] = '\0';
	    if (_M_parameters[__param]._M_kind == _Parameter::__integer)
	      {
		_M_format_word(__buf, __bufsize, "%ld",
			       _M_parameters[__param]._M_variant._M_integer._M_value);
		_M_print_word(__buf);
	      }
	    else if (_M_parameters[__param]._M_kind == _Parameter::__string)
	      _M_print_string(_M_parameters[__param]._M_variant._M_string._M_value);
	    continue;
	  }

	// Extract the field name we want
	enum { __max_field_len = 16 };
	char __field[__max_field_len];
	int __field_idx = 0;
	++__start;
	while (*__start != ';')
	  {
	    assert(*__start);
	    assert(__field_idx < __max_field_len-1);
	    __field[__field_idx++] = *__start++;
	  }
	++__start;
	__field[__field_idx] = 0;

	_M_parameters[__param]._M_print_field(this, __field);
      }
  }

  void
  _Error_formatter::_M_get_max_length() const throw ()
  {
    const char* __nptr = std::getenv("GLIBCXX_DEBUG_MESSAGE_LENGTH");
    if (__nptr)
      {
	char* __endptr;
	const unsigned long __ret = std::strtoul(__nptr, &__endptr, 0);
	if (*__nptr != '\0' && *__endptr == '\0')
	  _M_max_length = __ret;
      }
  }

  // Instantiations.
  template
    void
    _Error_formatter::_M_format_word(char*, int, const char*,
				     const void*) const;

  template
    void
    _Error_formatter::_M_format_word(char*, int, const char*, long) const;

  template
    void
    _Error_formatter::_M_format_word(char*, int, const char*,
				     std::size_t) const;

  template
    void
    _Error_formatter::_M_format_word(char*, int, const char*,
				     const char*) const;
} // namespace __gnu_debug


text:
class Webmail::RolesController < ApplicationController
  include Webmail::BaseFilter
  include Sns::CrudFilter

  model Webmail::Role

  prepend_view_path "app/views/ss/roles"

  before_action :set_items
  before_action :set_item, only: [:show, :edit, :update, :delete, :destroy]

  private

  def set_crumbs
    @crumbs << [t("mongoid.models.webmail/role"), { action: :index } ]
  end

  def fix_params
    { cur_user: @cur_user }
  end

  def set_items
    @items = @model.all.allow(:read, @cur_user)
  end

  def set_item
    @item = @items.find(params[:id])
  end

  public

  def index
    raise "403" unless @model.allowed?(:read, @cur_user)

    @items = @items.order_by(name: 1, id: 1).
      page(params[:page]).per(50)
  end

  def download
    csv = @model.unscoped.order_by(name: 1, id: 1).to_csv
    send_data csv.encode("SJIS", invalid: :replace, undef: :replace), filename: "webmail_roles_#{Time.zone.now.to_i}.csv"
  end

  def import
    @item = @model.new
    return if request.get?

    file = params.require(:item).permit(:in_file)[:in_file]
    if file.blank?
      @item.errors.add :base, :invalid_csv
      return
    end

    mime = SS::MimeType.find(file.original_filename, file.content_type)
    if mime != "text/comma-separated-values" || !Webmail::RoleImportJob.valid_csv?(file)
      @item.errors.add :base, :invalid_csv
      return
    end

    temp_file = SS::TempFile.new
    temp_file.in_file = file
    temp_file.save!

    Webmail::RoleImportJob.bind(user_id: @cur_user).perform_now(temp_file.id)
    redirect_to({ action: :index }, { notice: t("ss.notice.saved") })
  end
end

redpajama_set_name: RedPajamaGithub


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="app_bar_height">200dp</dimen>
    <dimen name="fab_margin">16dp</dimen>
    <dimen name="text_margin">16dp</dimen>
    <dimen name="drawer_logo_margin">10dp</dimen>
</resources>


text:
#ifndef loopfilter_h
#define loopfilter_h

#include "vpx_ports/mem.h"
#include "vpx_config.h"
#include "vpx_rtcd.h"

#define MAX_LOOP_FILTER             63
/* fraction of total macroblock rows to be used in fast filter level picking */
/* has to be > 2 */
#define PARTIAL_FRAME_FRACTION      8

typedef enum
{
    NORMAL_LOOPFILTER = 0,
    SIMPLE_LOOPFILTER = 1
} LOOPFILTERTYPE;

#if ARCH_ARM
#define SIMD_WIDTH 1
#else
#define SIMD_WIDTH 16
#endif

/* Need to align this structure so when it is declared and
 * passed it can be loaded into vector registers.
 */
typedef struct
{
    DECLARE_ALIGNED(SIMD_WIDTH, unsigned char, mblim[MAX_LOOP_FILTER + 1][SIMD_WIDTH]);
    DECLARE_ALIGNED(SIMD_WIDTH, unsigned char, blim[MAX_LOOP_FILTER + 1][SIMD_WIDTH]);
    DECLARE_ALIGNED(SIMD_WIDTH, unsigned char, lim[MAX_LOOP_FILTER + 1][SIMD_WIDTH]);
    DECLARE_ALIGNED(SIMD_WIDTH, unsigned char, hev_thr[4][SIMD_WIDTH]);
    unsigned char lvl[4][4][4];
    unsigned char hev_thr_lut[2][MAX_LOOP_FILTER + 1];
    unsigned char mode_lf_lut[10];
} loop_filter_info_n __attribute__ ((aligned(SIMD_WIDTH)));

typedef struct loop_filter_info
{
    const unsigned char * mblim;
    const unsigned char * blim;
    const unsigned char * lim;
    const unsigned char * hev_thr;
} loop_filter_info;

typedef void loop_filter_uvfunction
(
    unsigned char *u,   /* source pointer */
    int p,              /* pitch */
    const unsigned char *blimit,
    const unsigned char *limit,
    const unsigned char *thresh,
    unsigned char *v
);

/* assorted loopfilter functions which get used elsewhere */
struct VP8Common;
struct macroblockd;

void vp8_loop_filter_init(struct VP8Common *cm);

void vp8_loop_filter_frame_init(struct VP8Common *cm,
                                struct macroblockd *mbd,
                                int default_filt_lvl);

void vp8_loop_filter_frame(struct VP8Common *cm, struct macroblockd *mbd);

void vp8_loop_filter_partial_frame(struct VP8Common *cm,
                                   struct macroblockd *mbd,
                                   int default_filt_lvl);

void vp8_loop_filter_frame_yonly(struct VP8Common *cm,
                                 struct macroblockd *mbd,
                                 int default_filt_lvl);

void vp8_loop_filter_update_sharpness(loop_filter_info_n *lfi,
                                      int sharpness_lvl);

#endif


text:
package com.ugurcan.springtraining;

import org.springframework.stereotype.Component;

@Component
public class RESTFortuneService implements FortuneService{

	@Override
	public String getFortune() {
		return "REST Fortune Service";
	}

}


text:
ITexture* CTNERenderTargets::CreateScopeTexture( IMaterialSystem* pMaterialSystem )
{
        return pMaterialSystem->CreateNamedRenderTargetTextureEx2(
                "dev/_rt_Scope",
                1024, 1024, RT_SIZE_OFFSCREEN,
                pMaterialSystem->GetBackBufferFormat(),
                MATERIAL_RT_DEPTH_SHARED,
                TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT,
                CREATERENDERTARGETFLAGS_HDR );
}
//-----------------------------------------------------------------------------
// Purpose: Called by the engine in material system init and shutdown.
//                      Clients should override this in their inherited version, but the base
//                      is to init all standard render targets for use.
// Input  : pMaterialSystem - the engine's material system (our singleton is not yet inited at the time this is called)
//                      pHardwareConfig - the user hardware config, useful for conditional render target setup
//-----------------------------------------------------------------------------
void CTNERenderTargets::InitClientRenderTargets( IMaterialSystem* pMaterialSystem, IMaterialSystemHardwareConfig* pHardwareConfig )
{
        m_ScopeTexture.Init( CreateScopeTexture( pMaterialSystem ) );

        // Water effects & camera from the base class (standard HL2 targets)
        BaseClass::InitClientRenderTargets( pMaterialSystem, pHardwareConfig );
}
//-----------------------------------------------------------------------------
// Purpose: Shut down each CTextureReference we created in InitClientRenderTargets.
//                      Called by the engine in material system shutdown.
// Input  :  -
//-----------------------------------------------------------------------------
void CTNERenderTargets::ShutdownClientRenderTargets()
{
        m_ScopeTexture.Shutdown();

        // Clean up standard HL2 RTs (camera and water)
        BaseClass::ShutdownClientRenderTargets();
}

//add the interface!
static CTNERenderTargets g_TNERenderTargets;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CTNERenderTargets, IClientRenderTargets, CLIENTRENDERTARGETS_INTERFACE_VERSION, g_TNERenderTargets  );
CTNERenderTargets* TNERenderTargets = &g_TNERenderTargets;


text:
package cn.gyyx.framework.mybatis;

import cn.gyyx.framework.mybatis.entity.GlobalConfiguration;
import cn.gyyx.framework.mybatis.toolkit.IOUtils;
import org.apache.ibatis.exceptions.ExceptionFactory;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;

public class MybatisSessionFactoryBuilder extends SqlSessionFactoryBuilder {

    private GlobalConfiguration globalConfig = GlobalConfiguration.defaults();

    @Override
    public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
        try {
            MybatisXMLConfigBuilder parser = new MybatisXMLConfigBuilder(reader, environment, properties);
            GlobalConfiguration.setGlobalConfig(parser.getConfiguration(), this.globalConfig);
            return build(parser.parse());
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("Error building SqlSession.", e);
        } finally {
            ErrorContext.instance().reset();
            IOUtils.closeQuietly(reader);
        }
    }

    @Override
    public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
        try {
            MybatisXMLConfigBuilder parser = new MybatisXMLConfigBuilder(inputStream, environment, properties);
            GlobalConfiguration.setGlobalConfig(parser.getConfiguration(), this.globalConfig);
            return build(parser.parse());
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("Error building SqlSession.", e);
        } finally {
            ErrorContext.instance().reset();
            IOUtils.closeQuietly(inputStream);
        }
    }

    // TODO 注入全局配置
    public void setGlobalConfig(GlobalConfiguration globalConfig) {
        this.globalConfig = globalConfig;
    }

}


text:
package org.apache.nifi.web.security.jwt.converter;

import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.PlainJWT;
import org.apache.nifi.admin.service.IdpUserGroupService;
import org.apache.nifi.authorization.AccessPolicyProvider;
import org.apache.nifi.authorization.Group;
import org.apache.nifi.authorization.ManagedAuthorizer;
import org.apache.nifi.authorization.UserAndGroups;
import org.apache.nifi.authorization.UserGroupProvider;
import org.apache.nifi.authorization.user.NiFiUser;
import org.apache.nifi.authorization.user.NiFiUserDetails;
import org.apache.nifi.idp.IdpUserGroup;
import org.apache.nifi.util.NiFiProperties;
import org.apache.nifi.util.StringUtils;
import org.apache.nifi.web.security.token.NiFiAuthenticationToken;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.oauth2.jwt.Jwt;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class StandardJwtAuthenticationConverterTest {
    private static final String USERNAME = "NiFi";

    private static final String AUTHORIZER_GROUP = "AuthorizerGroup";

    private static final String PROVIDER_GROUP = "ProviderGroup";

    private static final String TYPE_FIELD = "typ";

    private static final String JWT_TYPE = "JWT";

    @Mock
    private ManagedAuthorizer authorizer;

    @Mock
    private AccessPolicyProvider accessPolicyProvider;

    @Mock
    private UserGroupProvider userGroupProvider;

    @Mock
    private UserAndGroups userAndGroups;

    @Mock
    private IdpUserGroupService idpUserGroupService;

    private StandardJwtAuthenticationConverter converter;

    @Before
    public void setConverter() {
        final Map<String, String> properties = new HashMap<>();
        final NiFiProperties niFiProperties = NiFiProperties.createBasicNiFiProperties(StringUtils.EMPTY, properties);
        converter = new StandardJwtAuthenticationConverter(authorizer, idpUserGroupService, niFiProperties);

        when(authorizer.getAccessPolicyProvider()).thenReturn(accessPolicyProvider);
        when(accessPolicyProvider.getUserGroupProvider()).thenReturn(userGroupProvider);
        when(userGroupProvider.getUserAndGroups(eq(USERNAME))).thenReturn(userAndGroups);

        final Group group = new Group.Builder().name(AUTHORIZER_GROUP).identifier(AUTHORIZER_GROUP).build();
        when(userAndGroups.getGroups()).thenReturn(Collections.singleton(group));

        final IdpUserGroup idpUserGroup = new IdpUserGroup();
        idpUserGroup.setGroupName(PROVIDER_GROUP);
        when(idpUserGroupService.getUserGroups(eq(USERNAME))).thenReturn(Collections.singletonList(idpUserGroup));
    }

    @Test
    public void testConvert() {
        final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                .subject(USERNAME)
                .build();
        final String token = new PlainJWT(claimsSet).serialize();
        final Jwt jwt = Jwt.withTokenValue(token)
                .header(TYPE_FIELD, JWT_TYPE)
                .subject(USERNAME)
                .build();

        final NiFiAuthenticationToken authenticationToken = converter.convert(jwt);
        assertNotNull(authenticationToken);
        assertEquals(USERNAME, authenticationToken.toString());

        final NiFiUserDetails details = (NiFiUserDetails) authenticationToken.getDetails();
        final NiFiUser user = details.getNiFiUser();

        final Set<String> expectedGroups = Collections.singleton(AUTHORIZER_GROUP);
        assertEquals(expectedGroups, user.getGroups());

        final Set<String> expectedProviderGroups = Collections.singleton(PROVIDER_GROUP);
        assertEquals(expectedProviderGroups, user.getIdentityProviderGroups());
    }
}


text:
<?php

namespace WarGaming\Api\Method;

/**
 * Pager method
 *
 * @author Vitaliy Zhuk <zhuk2205@gmail.com>
 */
interface PagerMethodInterface extends MethodInterface
{
    /**
     * Set limit
     *
     * @param int $limit
     */
    public function setLimit($limit);

    /**
     * Get limit
     *
     * @return int
     */
    public function getLimit();

    /**
     * Set page
     *
     * @param int $page
     */
    public function setPage($page);

    /**
     * Get page
     *
     * @return int
     */
    public function getPage();
}


text:
<?php
namespace Neos\Flow\Security\Cryptography;

/**
 * A password hashing strategy interface
 *
 */
interface PasswordHashingStrategyInterface
{
    /**
     * Hash a password for storage
     *
     * @param string $password Cleartext password that will be hashed
     * @param string $staticSalt Optional static salt that will not be stored in the hashed password
     * @return string The hashed password with dynamic salt (if used)
     */
    public function hashPassword($password, $staticSalt = null);

    /**
     * Validate a hashed password against a cleartext password
     *
     * @param string $password
     * @param string $hashedPasswordAndSalt Hashed password with dynamic salt (if used)
     * @param string $staticSalt Optional static salt that will not be stored in the hashed password
     * @return boolean TRUE if the given cleartext password matched the hashed password
     */
    public function validatePassword($password, $hashedPasswordAndSalt, $staticSalt = null);
}


text:
set(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
  "C:/Users/Jeremy/Desktop/RemoteComputer/Client/src/client.cpp" "C:/Users/Jeremy/Desktop/RemoteComputer/Client/build/CMakeFiles/Client.dir/src/client.cpp.obj"
  "C:/Users/Jeremy/Desktop/RemoteComputer/Client/src/command.cpp" "C:/Users/Jeremy/Desktop/RemoteComputer/Client/build/CMakeFiles/Client.dir/src/command.cpp.obj"
  "C:/Users/Jeremy/Desktop/RemoteComputer/Client/src/main.cpp" "C:/Users/Jeremy/Desktop/RemoteComputer/Client/build/CMakeFiles/Client.dir/src/main.cpp.obj"
  )
set(CMAKE_CXX_COMPILER_ID "MSVC")

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  )

# The include file search paths:
set(CMAKE_C_TARGET_INCLUDE_PATH
  "C:/Devel/cpp/libs/boost_1_57_0"
  )
set(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
set(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
set(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})


text:
package pl.czak.retronix.android;

import android.app.Activity;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import pl.czak.retronix.Game;
import pl.czak.retronix.engine.Backend;
import pl.czak.retronix.engine.Event;
import pl.czak.retronix.engine.Sound;
import pl.czak.retronix.engine.State;
import pl.czak.retronix.states.WelcomeState;

public class MainActivity extends Activity implements Backend {
    private Game game;
    private Thread gameThread;
    private Screen screen;
    private SoundBank soundBank;

    private GestureDetectorCompat detector;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        screen = new Screen(this);
        setContentView(screen);

        detector = new GestureDetectorCompat(this, new GestureListener());

        soundBank = new SoundBank(this);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        game = new Game(this);
        game.pushState(new WelcomeState(game));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        soundBank.release();
    }

    @Override
    protected void onResume() {
        super.onResume();
        game.resume();
        gameThread = new Thread(new MainLoop());
        gameThread.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        game.pause();
        try {
            gameThread.join();
        } catch (InterruptedException ignored) { }
    }

    @Override
    public void playSound(Sound sound) {
        soundBank.play(sound);
    }

    @Override
    public void draw(State state) {
        screen.draw(state);
    }

    @Override
    public boolean isTouchEnabled() {
        Configuration config = getResources().getConfiguration();
        return config.touchscreen == Configuration.TOUCHSCREEN_FINGER;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_UP:
                game.addEvent(Event.UP);
                return true;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                game.addEvent(Event.DOWN);
                return true;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                game.addEvent(Event.LEFT);
                return true;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                game.addEvent(Event.RIGHT);
                return true;
            case KeyEvent.KEYCODE_DPAD_CENTER:
            case KeyEvent.KEYCODE_ENTER:
                game.addEvent(Event.SELECT);
                return true;
            case KeyEvent.KEYCODE_BACK:
                game.addEvent(Event.BACK);
                return true;
            default:
                return false;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        detector.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    class GestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            // Calculate tap location in game pixels
            int x = (int) (e.getX() / screen.getWidth() * 320);
            int y = (int) (e.getY() / screen.getHeight() * 180);
            game.addEvent(new Event(Event.Type.CLICK, x, y));
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            // Stolen from http://stackoverflow.com/a/26387629/379822
            float x1 = e1.getX();
            float y1 = e1.getY();

            float x2 = e2.getX();
            float y2 = e2.getY();

            double angle = getAngle(x1, y1, x2, y2);

            if (angle >= 45 && angle < 135) {
                game.addEvent(Event.UP);
            } else if (angle >= 0 && angle < 45 || angle >= 315 && angle < 360) {
                game.addEvent(Event.RIGHT);
            } else if (angle >= 225 && angle < 315) {
                game.addEvent(Event.DOWN);
            } else {
                game.addEvent(Event.LEFT);
            }

            return true;
        }

        private double getAngle(float x1, float y1, float x2, float y2) {
            double rad = Math.atan2(y1-y2, x2-x1) + Math.PI;
            return (rad * 180/Math.PI + 180) % 360;
        }
    }

    private class MainLoop implements Runnable {
        @Override
        public void run() {
            while (game.isRunning()) {
                long start = System.currentTimeMillis();

                game.handleEvent();
                game.update();
                game.draw();

                long duration = System.currentTimeMillis() - start;

                try {
                    Thread.sleep(Math.max(0, 50 - duration));
                } catch (InterruptedException ignored) {}
            }

            if (game.isDone()) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                });
            }
        }
    }
}


text:
class CServerTools : public IServerTools
{
public:
	// Inherited from IServerTools
	virtual IServerEntity *GetIServerEntity( IClientEntity *pClientEntity );
	virtual bool GetPlayerPosition( Vector &org, QAngle &ang, IClientEntity *pClientPlayer = NULL );
	virtual bool SnapPlayerToPosition( const Vector &org, const QAngle &ang, IClientEntity *pClientPlayer = NULL );
	virtual int GetPlayerFOV( IClientEntity *pClientPlayer = NULL );
	virtual bool SetPlayerFOV( int fov, IClientEntity *pClientPlayer = NULL );
	virtual bool IsInNoClipMode( IClientEntity *pClientPlayer = NULL );
	virtual CBaseEntity *FirstEntity( void );
	virtual CBaseEntity *NextEntity( CBaseEntity *pEntity );
	virtual CBaseEntity *FindEntityByHammerID( int iHammerID );
	virtual bool GetKeyValue( CBaseEntity *pEntity, const char *szField, char *szValue, int iMaxLen );
	virtual bool SetKeyValue( CBaseEntity *pEntity, const char *szField, const char *szValue );
	virtual bool SetKeyValue( CBaseEntity *pEntity, const char *szField, float flValue );
	virtual bool SetKeyValue( CBaseEntity *pEntity, const char *szField, const Vector &vecValue );
	virtual CBaseEntity *CreateEntityByName( const char *szClassName );
	virtual void DispatchSpawn( CBaseEntity *pEntity );
	virtual void ReloadParticleDefintions( const char *pFileName, const void *pBufData, int nLen );
	virtual void AddOriginToPVS( const Vector &org );
	virtual void MoveEngineViewTo( const Vector &vPos, const QAngle &vAngles );
	virtual bool DestroyEntityByHammerId( int iHammerID );
	virtual CBaseEntity *GetBaseEntityByEntIndex( int iEntIndex );
	virtual void RemoveEntity( CBaseEntity *pEntity );
	virtual void RemoveEntityImmediate( CBaseEntity *pEntity );
	virtual IEntityFactoryDictionary *GetEntityFactoryDictionary( void );
	virtual void SetMoveType( CBaseEntity *pEntity, int val );
	virtual void SetMoveType( CBaseEntity *pEntity, int val, int moveCollide );
	virtual void ResetSequence( CBaseAnimating *pEntity, int nSequence );
	virtual void ResetSequenceInfo( CBaseAnimating *pEntity );
	virtual void ClearMultiDamage( void );
	virtual void ApplyMultiDamage( void );
	virtual void AddMultiDamage( const CTakeDamageInfo &pTakeDamageInfo, CBaseEntity *pEntity );
	virtual void RadiusDamage( const CTakeDamageInfo &info, const Vector &vecSrc, float flRadius, int iClassIgnore, CBaseEntity *pEntityIgnore );
	virtual ITempEntsSystem *GetTempEntsSystem( void );
};

//-----------------------------------------------------------------------------
// Singleton
//-----------------------------------------------------------------------------
static CServerTools g_ServerTools;

// VSERVERTOOLS_INTERFACE_VERSION_1 is compatible with the latest since we're only adding things to the end, so expose that as well.
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CServerTools, IServerTools001, VSERVERTOOLS_INTERFACE_VERSION_1, g_ServerTools );
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CServerTools, IServerTools, VSERVERTOOLS_INTERFACE_VERSION, g_ServerTools );

// When bumping the version to this interface, check that our assumption is still valid and expose the older version in the same way
COMPILE_TIME_ASSERT( VSERVERTOOLS_INTERFACE_VERSION_INT == 2 );

IServerEntity *CServerTools::GetIServerEntity( IClientEntity *pClientEntity )
{
	if ( pClientEntity == NULL )
		return NULL;

	CBaseHandle ehandle = pClientEntity->GetRefEHandle();
	if ( ehandle.GetEntryIndex() >= MAX_EDICTS )
		return NULL; // the first MAX_EDICTS entities are networked, the rest are client or server only

#if 0
	// this fails, since the server entities have extra bits in their serial numbers,
	// since 20 bits are reserved for serial numbers, except for networked entities, which are restricted to 10

	// Brian believes that everything should just restrict itself to 10 to make things simpler,
	// so if/when he changes NUM_SERIAL_NUM_BITS to 10, we can switch back to this simpler code

	IServerNetworkable *pNet = gEntList.GetServerNetworkable( ehandle );
	if ( pNet == NULL )
		return NULL;

	CBaseEntity *pServerEnt = pNet->GetBaseEntity();
	return pServerEnt;
#else
	IHandleEntity *pEnt = gEntList.LookupEntityByNetworkIndex( ehandle.GetEntryIndex() );
	if ( pEnt == NULL )
		return NULL;

	CBaseHandle h = gEntList.GetNetworkableHandle( ehandle.GetEntryIndex() );
	const int mask = ( 1 << NUM_NETWORKED_EHANDLE_SERIAL_NUMBER_BITS ) - 1;
	if ( !h.IsValid() || ( ( h.GetSerialNumber() & mask ) != ( ehandle.GetSerialNumber() & mask ) ) )
		return NULL;

	IServerUnknown *pUnk = static_cast< IServerUnknown* >( pEnt );
	return pUnk->GetBaseEntity();
#endif
}

bool CServerTools::GetPlayerPosition( Vector &org, QAngle &ang, IClientEntity *pClientPlayer )
{
	IServerEntity *pServerPlayer = GetIServerEntity( pClientPlayer );
	CBasePlayer *pPlayer = pServerPlayer ? ( CBasePlayer* )pServerPlayer : UTIL_GetLocalPlayer();
	if ( pPlayer == NULL )
		return false;

	org = pPlayer->EyePosition();
	ang = pPlayer->EyeAngles();
	return true;
}

bool CServerTools::SnapPlayerToPosition( const Vector &org, const QAngle &ang, IClientEntity *pClientPlayer )
{
	IServerEntity *pServerPlayer = GetIServerEntity( pClientPlayer );
	CBasePlayer *pPlayer = pServerPlayer ? ( CBasePlayer* )pServerPlayer : UTIL_GetLocalPlayer();
	if ( pPlayer == NULL )
		return false;

	pPlayer->SetAbsOrigin( org - pPlayer->GetViewOffset() );
	pPlayer->SnapEyeAngles( ang );

	// Disengage from hierarchy
	pPlayer->SetParent( NULL );

	return true;
}

int CServerTools::GetPlayerFOV( IClientEntity *pClientPlayer )
{
	IServerEntity *pServerPlayer = GetIServerEntity( pClientPlayer );
	CBasePlayer *pPlayer = pServerPlayer ? ( CBasePlayer* )pServerPlayer : UTIL_GetLocalPlayer();
	if ( pPlayer == NULL )
		return 0;

	return pPlayer->GetFOV();
}

bool CServerTools::SetPlayerFOV( int fov, IClientEntity *pClientPlayer )
{
	IServerEntity *pServerPlayer = GetIServerEntity( pClientPlayer );
	CBasePlayer *pPlayer = pServerPlayer ? ( CBasePlayer* )pServerPlayer : UTIL_GetLocalPlayer();
	if ( pPlayer == NULL )
		return false;

	pPlayer->SetDefaultFOV( fov );
	CBaseEntity *pFOVOwner = pPlayer->GetFOVOwner();
	return pPlayer->SetFOV( pFOVOwner ? pFOVOwner : pPlayer, fov );
}

bool CServerTools::IsInNoClipMode( IClientEntity *pClientPlayer )
{
	IServerEntity *pServerPlayer = GetIServerEntity( pClientPlayer );
	CBasePlayer *pPlayer = pServerPlayer ? ( CBasePlayer* )pServerPlayer : UTIL_GetLocalPlayer();
	if ( pPlayer == NULL )
		return true;

	return pPlayer->GetMoveType() == MOVETYPE_NOCLIP;
}

CBaseEntity *CServerTools::FirstEntity( void )
{
	return gEntList.FirstEnt();
}

CBaseEntity *CServerTools::NextEntity( CBaseEntity *pEntity )
{
	CBaseEntity *pEnt;

	if ( pEntity == NULL )
	{
		pEnt = gEntList.FirstEnt();
	}
	else
	{
		pEnt = gEntList.NextEnt( (CBaseEntity *)pEntity );
	}
	return pEnt;
}

CBaseEntity *CServerTools::FindEntityByHammerID( int iHammerID )
{
	CBaseEntity *pEntity = gEntList.FirstEnt();

	while (pEntity)
	{
		if (pEntity->m_iHammerID == iHammerID)
			return pEntity;
		pEntity = gEntList.NextEnt( pEntity );
	}
	return NULL;
}

bool CServerTools::GetKeyValue( CBaseEntity *pEntity, const char *szField, char *szValue, int iMaxLen )
{
	return pEntity->GetKeyValue( szField, szValue, iMaxLen );
}

bool CServerTools::SetKeyValue( CBaseEntity *pEntity, const char *szField, const char *szValue )
{
	return pEntity->KeyValue( szField, szValue );
}

bool CServerTools::SetKeyValue( CBaseEntity *pEntity, const char *szField, float flValue )
{
	return pEntity->KeyValue( szField, flValue );
}

bool CServerTools::SetKeyValue( CBaseEntity *pEntity, const char *szField, const Vector &vecValue )
{
	return pEntity->KeyValue( szField, vecValue );
}

//-----------------------------------------------------------------------------
// entity spawning
//-----------------------------------------------------------------------------
CBaseEntity *CServerTools::CreateEntityByName( const char *szClassName )
{
	return ::CreateEntityByName( szClassName );
}

void CServerTools::DispatchSpawn( CBaseEntity *pEntity )
{
	::DispatchSpawn( pEntity );
}

//-----------------------------------------------------------------------------
// Reload particle definitions
//-----------------------------------------------------------------------------
void CServerTools::ReloadParticleDefintions( const char *pFileName, const void *pBufData, int nLen )
{
	// FIXME: Use file name to determine if we care about this data
	CUtlBuffer buf( pBufData, nLen, CUtlBuffer::READ_ONLY );
	g_pParticleSystemMgr->ReadParticleConfigFile( buf, true );
}

void CServerTools::AddOriginToPVS( const Vector &org )
{
	engine->AddOriginToPVS( org );
}

void CServerTools::MoveEngineViewTo( const Vector &vPos, const QAngle &vAngles )
{
	CBasePlayer *pPlayer = UTIL_GetListenServerHost();
	if ( !pPlayer )
		return;

	extern void EnableNoClip( CBasePlayer *pPlayer );
	EnableNoClip( pPlayer );

	Vector zOffset = pPlayer->EyePosition() - pPlayer->GetAbsOrigin();

	pPlayer->SetAbsOrigin( vPos - zOffset );
	pPlayer->SnapEyeAngles( vAngles );
}

bool CServerTools::DestroyEntityByHammerId( int iHammerID )
{
	CBaseEntity *pEntity = (CBaseEntity*)FindEntityByHammerID( iHammerID );
	if ( !pEntity )
		return false;

	UTIL_Remove( pEntity );
	return true;
}

void CServerTools::RemoveEntity( CBaseEntity *pEntity )
{
	UTIL_Remove( pEntity );
}

void CServerTools::RemoveEntityImmediate( CBaseEntity *pEntity )
{
	UTIL_RemoveImmediate( pEntity );
}

CBaseEntity *CServerTools::GetBaseEntityByEntIndex( int iEntIndex )
{
	edict_t *pEdict = INDEXENT( iEntIndex );
	if ( pEdict )
		return CBaseEntity::Instance( pEdict );
	else
		return NULL;
}

IEntityFactoryDictionary *CServerTools::GetEntityFactoryDictionary( void )
{
	return ::EntityFactoryDictionary();
}

void CServerTools::SetMoveType( CBaseEntity *pEntity, int val )
{
	pEntity->SetMoveType( (MoveType_t)val );
}

void CServerTools::SetMoveType( CBaseEntity *pEntity, int val, int moveCollide )
{
	pEntity->SetMoveType( (MoveType_t)val, (MoveCollide_t)moveCollide );
}

void CServerTools::ResetSequence( CBaseAnimating *pEntity, int nSequence )
{
	pEntity->ResetSequence( nSequence );
}

void CServerTools::ResetSequenceInfo( CBaseAnimating *pEntity )
{
	pEntity->ResetSequenceInfo();
}

void CServerTools::ClearMultiDamage( void )
{
	::ClearMultiDamage();
}

void CServerTools::ApplyMultiDamage( void )
{
	::ApplyMultiDamage();
}

void CServerTools::AddMultiDamage( const CTakeDamageInfo &pTakeDamageInfo, CBaseEntity *pEntity )
{
	::AddMultiDamage( pTakeDamageInfo, pEntity );
}

void CServerTools::RadiusDamage( const CTakeDamageInfo &info, const Vector &vecSrc, float flRadius, int iClassIgnore, CBaseEntity *pEntityIgnore )
{
	::RadiusDamage( info, vecSrc, flRadius, iClassIgnore, pEntityIgnore );
}

ITempEntsSystem *CServerTools::GetTempEntsSystem( void )
{
	return (ITempEntsSystem *)te;
}

// Interface from engine to tools for manipulating entities
class CServerChoreoTools : public IServerChoreoTools
{
public:
	// Iterates through ALL entities (separate list for client vs. server)
	virtual EntitySearchResult	NextChoreoEntity( EntitySearchResult currentEnt )
	{
		CBaseEntity *ent = reinterpret_cast< CBaseEntity* >( currentEnt );
		ent = gEntList.FindEntityByClassname( ent, "logic_choreographed_scene" );
		return reinterpret_cast< EntitySearchResult >( ent );
	}

	virtual const char			*GetSceneFile( EntitySearchResult sr )
	{
		CBaseEntity *ent = reinterpret_cast< CBaseEntity* >( sr );
		if ( !sr )
			return "";

		if ( Q_stricmp( ent->GetClassname(), "logic_choreographed_scene" ) )
			return "";

		return GetSceneFilename( ent );
	}

	// For interactive editing
	virtual int	GetEntIndex( EntitySearchResult sr )
	{
		CBaseEntity *ent = reinterpret_cast< CBaseEntity* >( sr );
		if ( !ent )
			return -1;

		return ent->entindex();
	}

	virtual void ReloadSceneFromDisk( int entindex )
	{
		CBaseEntity *ent = CBaseEntity::Instance( entindex );
		if ( !ent )
			return;

		::ReloadSceneFromDisk( ent );
	}
};

static CServerChoreoTools g_ServerChoreoTools;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CServerChoreoTools, IServerChoreoTools, VSERVERCHOREOTOOLS_INTERFACE_VERSION, g_ServerChoreoTools );

//------------------------------------------------------------------------------
// Applies keyvalues to the entity by hammer ID.
//------------------------------------------------------------------------------
void CC_Ent_Keyvalue( const CCommand &args )
{
	// Must have an odd number of arguments.
	if ( ( args.ArgC() < 4 ) || ( args.ArgC() & 1 ) )
	{
		Msg( "Format: ent_keyvalue <entity id> \"key1\" \"value1\" \"key2\" \"value2\" ... \"keyN\" \"valueN\"\n" );
		return;
	}

	int nID = atoi( args[1] );

	CBaseEntity *pEnt = g_ServerTools.FindEntityByHammerID( nID );
	if ( !pEnt )
	{
		Msg( "Entity ID %d not found.\n", nID );
		return;
	}

	int nArg = 2;
	while ( nArg < args.ArgC() )
	{
		const char *pszKey = args[ nArg ];
		const char *pszValue = args[ nArg + 1 ];
		nArg += 2;

		g_ServerTools.SetKeyValue( pEnt, pszKey, pszValue );
	}
}

static ConCommand ent_keyvalue("ent_keyvalue", CC_Ent_Keyvalue, "Applies the comma delimited key=value pairs to the entity with the given Hammer ID.\n\tFormat: ent_keyvalue <entity id> <key1> <value1> <key2> <value2> ... <keyN> <valueN>\n", FCVAR_CHEAT);