text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <cstdlib>
#include <cerrno>
#include <ctime>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <typeinfo>
#include <limits>
#include <algorithm>
#include <sstream>
#include <complex>
#include <deque>
#include <queue>

#define min(A,B) please_protect_your_min_with_parentheses
#define max(A,B) please_protect_your_max_with_parentheses

#define FORBIDDEN_IDENTIFIER (this_identifier_is_forbidden_to_avoid_clashes) this_identifier_is_forbidden_to_avoid_clashes
// B0 is defined in POSIX header termios.h
#define B0 FORBIDDEN_IDENTIFIER

// the following file is automatically generated by cmake
#include "split_test_helper.h"

#ifdef NDEBUG
#undef NDEBUG
#endif

// bounds integer values for AltiVec
#ifdef __ALTIVEC__
#define EIGEN_MAKING_DOCS
#endif

#ifndef EIGEN_TEST_FUNC
#error EIGEN_TEST_FUNC must be defined
#endif

#define DEFAULT_REPEAT 10

#ifdef __ICC
// disable warning #279: controlling expression is constant
#pragma warning disable 279
#endif

namespace Eigen
{
  static std::vector<std::string> g_test_stack;
  static int g_repeat;
  static unsigned int g_seed;
  static bool g_has_set_repeat, g_has_set_seed;
}

#define EI_PP_MAKE_STRING2(S) #S
#define EI_PP_MAKE_STRING(S) EI_PP_MAKE_STRING2(S)

#define EIGEN_DEFAULT_IO_FORMAT IOFormat(4, 0, "  ", "\n", "", "", "", "")

#ifndef EIGEN_NO_ASSERTION_CHECKING

  namespace Eigen
  {
    static const bool should_raise_an_assert = false;

    // Used to avoid to raise two exceptions at a time in which
    // case the exception is not properly caught.
    // This may happen when a second exceptions is triggered in a destructor.
    static bool no_more_assert = false;
    static bool report_on_cerr_on_assert_failure = true;

    struct eigen_assert_exception
    {
      eigen_assert_exception(void) {}
      ~eigen_assert_exception() { Eigen::no_more_assert = false; }
    };
  }
  // If EIGEN_DEBUG_ASSERTS is defined and if no assertion is triggered while
  // one should have been, then the list of excecuted assertions is printed out.
  //
  // EIGEN_DEBUG_ASSERTS is not enabled by default as it
  // significantly increases the compilation time
  // and might even introduce side effects that would hide
  // some memory errors.
  #ifdef EIGEN_DEBUG_ASSERTS

    namespace Eigen
    {
      namespace internal
      {
        static bool push_assert = false;
      }
      static std::vector<std::string> eigen_assert_list;
    }
    #define eigen_assert(a)                       \
      if( (!(a)) && (!no_more_assert) )     \
      { \
        if(report_on_cerr_on_assert_failure) \
          std::cerr <<  #a << " " __FILE__ << "(" << __LINE__ << ")\n"; \
        Eigen::no_more_assert = true;       \
        throw Eigen::eigen_assert_exception(); \
      }                                     \
      else if (Eigen::internal::push_assert)       \
      {                                     \
        eigen_assert_list.push_back(std::string(EI_PP_MAKE_STRING(__FILE__) " (" EI_PP_MAKE_STRING(__LINE__) ") : " #a) ); \
      }

    #define VERIFY_RAISES_ASSERT(a)                                                   \
      {                                                                               \
        Eigen::no_more_assert = false;                                                \
        Eigen::eigen_assert_list.clear();                                                \
        Eigen::internal::push_assert = true;                                                 \
        Eigen::report_on_cerr_on_assert_failure = false;                              \
        try {                                                                         \
          a;                                                                          \
          std::cerr << "One of the following asserts should have been triggered:\n";  \
          for (uint ai=0 ; ai<eigen_assert_list.size() ; ++ai)                           \
            std::cerr << "  " << eigen_assert_list[ai] << "\n";                          \
          VERIFY(Eigen::should_raise_an_assert && # a);                               \
        } catch (Eigen::eigen_assert_exception) {                                        \
          Eigen::internal::push_assert = false; VERIFY(true);                                \
        }                                                                             \
        Eigen::report_on_cerr_on_assert_failure = true;                               \
        Eigen::internal::push_assert = false;                                                \
      }

  #else // EIGEN_DEBUG_ASSERTS
    // see bug 89. The copy_bool here is working around a bug in gcc <= 4.3
    #define eigen_assert(a) \
      if( (!Eigen::internal::copy_bool(a)) && (!no_more_assert) )\
      {                                       \
        Eigen::no_more_assert = true;         \
        if(report_on_cerr_on_assert_failure)  \
          eigen_plain_assert(a);              \
        else                                  \
          throw Eigen::eigen_assert_exception(); \
      }
    #define VERIFY_RAISES_ASSERT(a) {                             \
        Eigen::no_more_assert = false;                            \
        Eigen::report_on_cerr_on_assert_failure = false;          \
        try {                                                     \
          a;                                                      \
          VERIFY(Eigen::should_raise_an_assert && # a);           \
        }                                                         \
        catch (Eigen::eigen_assert_exception&) { VERIFY(true); }     \
        Eigen::report_on_cerr_on_assert_failure = true;           \
      }

  #endif // EIGEN_DEBUG_ASSERTS

  #define EIGEN_USE_CUSTOM_ASSERT

#else // EIGEN_NO_ASSERTION_CHECKING

  #define VERIFY_RAISES_ASSERT(a) {}

#endif // EIGEN_NO_ASSERTION_CHECKING

#define EIGEN_INTERNAL_DEBUGGING
#include <Eigen/QR> // required for createRandomPIMatrixOfRank

static void verify_impl(bool condition, const char *testname, const char *file, int line, const char *condition_as_string)
{
  if (!condition)
  {
    std::cerr << "Test " << testname << " failed in " << file << " (" << line << ")" \
      << std::endl << "    " << condition_as_string << std::endl << std::endl; \
    abort();
  }
}

#define VERIFY(a) ::verify_impl(a, g_test_stack.back().c_str(), __FILE__, __LINE__, EI_PP_MAKE_STRING(a))

#define VERIFY_IS_EQUAL(a, b) VERIFY(test_is_equal(a, b))
#define VERIFY_IS_APPROX(a, b) VERIFY(test_isApprox(a, b))
#define VERIFY_IS_NOT_APPROX(a, b) VERIFY(!test_isApprox(a, b))
#define VERIFY_IS_MUCH_SMALLER_THAN(a, b) VERIFY(test_isMuchSmallerThan(a, b))
#define VERIFY_IS_NOT_MUCH_SMALLER_THAN(a, b) VERIFY(!test_isMuchSmallerThan(a, b))
#define VERIFY_IS_APPROX_OR_LESS_THAN(a, b) VERIFY(test_isApproxOrLessThan(a, b))
#define VERIFY_IS_NOT_APPROX_OR_LESS_THAN(a, b) VERIFY(!test_isApproxOrLessThan(a, b))

#define VERIFY_IS_UNITARY(a) VERIFY(test_isUnitary(a))

#define CALL_SUBTEST(FUNC) do { \
    g_test_stack.push_back(EI_PP_MAKE_STRING(FUNC)); \
    FUNC; \
    g_test_stack.pop_back(); \
  } while (0)

namespace Eigen {

template<typename T> inline typename NumTraits<T>::Real test_precision() { return NumTraits<T>::dummy_precision(); }
template<> inline float test_precision<float>() { return 1e-3f; }
template<> inline double test_precision<double>() { return 1e-6; }
template<> inline float test_precision<std::complex<float> >() { return test_precision<float>(); }
template<> inline double test_precision<std::complex<double> >() { return test_precision<double>(); }
template<> inline long double test_precision<long double>() { return 1e-6; }

inline bool test_isApprox(const int& a, const int& b)
{ return internal::isApprox(a, b, test_precision<int>()); }
inline bool test_isMuchSmallerThan(const int& a, const int& b)
{ return internal::isMuchSmallerThan(a, b, test_precision<int>()); }
inline bool test_isApproxOrLessThan(const int& a, const int& b)
{ return internal::isApproxOrLessThan(a, b, test_precision<int>()); }

inline bool test_isApprox(const float& a, const float& b)
{ return internal::isApprox(a, b, test_precision<float>()); }
inline bool test_isMuchSmallerThan(const float& a, const float& b)
{ return internal::isMuchSmallerThan(a, b, test_precision<float>()); }
inline bool test_isApproxOrLessThan(const float& a, const float& b)
{ return internal::isApproxOrLessThan(a, b, test_precision<float>()); }
inline bool test_isApprox(const double& a, const double& b)
{ return internal::isApprox(a, b, test_precision<double>()); }

inline bool test_isMuchSmallerThan(const double& a, const double& b)
{ return internal::isMuchSmallerThan(a, b, test_precision<double>()); }
inline bool test_isApproxOrLessThan(const double& a, const double& b)
{ return internal::isApproxOrLessThan(a, b, test_precision<double>()); }

inline bool test_isApprox(const std::complex<float>& a, const std::complex<float>& b)
{ return internal::isApprox(a, b, test_precision<std::complex<float> >()); }
inline bool test_isMuchSmallerThan(const std::complex<float>& a, const std::complex<float>& b)
{ return internal::isMuchSmallerThan(a, b, test_precision<std::complex<float> >()); }

inline bool test_isApprox(const std::complex<double>& a, const std::complex<double>& b)
{ return internal::isApprox(a, b, test_precision<std::complex<double> >()); }
inline bool test_isMuchSmallerThan(const std::complex<double>& a, const std::complex<double>& b)
{ return internal::isMuchSmallerThan(a, b, test_precision<std::complex<double> >()); }

inline bool test_isApprox(const long double& a, const long double& b)
{
    bool ret = internal::isApprox(a, b, test_precision<long double>());
    if (!ret) std::cerr
        << std::endl << "    actual   = " << a
        << std::endl << "    expected = " << b << std::endl << std::endl;
    return ret;
}

inline bool test_isMuchSmallerThan(const long double& a, const long double& b)
{ return internal::isMuchSmallerThan(a, b, test_precision<long double>()); }
inline bool test_isApproxOrLessThan(const long double& a, const long double& b)
{ return internal::isApproxOrLessThan(a, b, test_precision<long double>()); }

template<typename Type1, typename Type2>
inline bool test_isApprox(const Type1& a, const Type2& b)
{
  return a.isApprox(b, test_precision<typename Type1::Scalar>());
}

// The idea behind this function is to compare the two scalars a and b where
// the scalar ref is a hint about the expected order of magnitude of a and b.
// Therefore, if for some reason a and b are very small compared to ref,
// we won't issue a false negative.
// This test could be: abs(a-b) <= eps * ref
// However, it seems that simply comparing a+ref and b+ref is more sensitive to true error.
template<typename Scalar,typename ScalarRef>
inline bool test_isApproxWithRef(const Scalar& a, const Scalar& b, const ScalarRef& ref)
{
  return test_isApprox(a+ref, b+ref);
}

template<typename Derived1, typename Derived2>
inline bool test_isMuchSmallerThan(const MatrixBase<Derived1>& m1,
                                   const MatrixBase<Derived2>& m2)
{
  return m1.isMuchSmallerThan(m2, test_precision<typename internal::traits<Derived1>::Scalar>());
}

template<typename Derived>
inline bool test_isMuchSmallerThan(const MatrixBase<Derived>& m,
                                   const typename NumTraits<typename internal::traits<Derived>::Scalar>::Real& s)
{
  return m.isMuchSmallerThan(s, test_precision<typename internal::traits<Derived>::Scalar>());
}

template<typename Derived>
inline bool test_isUnitary(const MatrixBase<Derived>& m)
{
  return m.isUnitary(test_precision<typename internal::traits<Derived>::Scalar>());
}

template<typename T, typename U>
bool test_is_equal(const T& actual, const U& expected)
{
    if (actual==expected)
        return true;
    // false:
    std::cerr
        << std::endl << "    actual   = " << actual
        << std::endl << "    expected = " << expected << std::endl << std::endl;
    return false;
}

/** Creates a random Partial Isometry matrix of given rank.
  *
  * A partial isometry is a matrix all of whose singular values are either 0 or 1.
  * This is very useful to test rank-revealing algorithms.
  */
template<typename MatrixType>
void createRandomPIMatrixOfRank(typename MatrixType::Index desired_rank, typename MatrixType::Index rows, typename MatrixType::Index cols, MatrixType& m)
{
  typedef typename internal::traits<MatrixType>::Index Index;
  typedef typename internal::traits<MatrixType>::Scalar Scalar;
  enum { Rows = MatrixType::RowsAtCompileTime, Cols = MatrixType::ColsAtCompileTime };

  typedef Matrix<Scalar, Dynamic, 1> VectorType;
  typedef Matrix<Scalar, Rows, Rows> MatrixAType;
  typedef Matrix<Scalar, Cols, Cols> MatrixBType;

  if(desired_rank == 0)
  {
    m.setZero(rows,cols);
    return;
  }

  if(desired_rank == 1)
  {
    // here we normalize the vectors to get a partial isometry
    m = VectorType::Random(rows).normalized() * VectorType::Random(cols).normalized().transpose();
    return;
  }

  MatrixAType a = MatrixAType::Random(rows,rows);
  MatrixType d = MatrixType::Identity(rows,cols);
  MatrixBType  b = MatrixBType::Random(cols,cols);

  // set the diagonal such that only desired_rank non-zero entries reamain
  const Index diag_size = (std::min)(d.rows(),d.cols());
  if(diag_size != desired_rank)
    d.diagonal().segment(desired_rank, diag_size-desired_rank) = VectorType::Zero(diag_size-desired_rank);

  HouseholderQR<MatrixAType> qra(a);
  HouseholderQR<MatrixBType> qrb(b);
  m = qra.householderQ() * d * qrb.householderQ();
}

template<typename PermutationVectorType>
void randomPermutationVector(PermutationVectorType& v, typename PermutationVectorType::Index size)
{
  typedef typename PermutationVectorType::Index Index;
  typedef typename PermutationVectorType::Scalar Scalar;
  v.resize(size);
  for(Index i = 0; i < size; ++i) v(i) = Scalar(i);
  if(size == 1) return;
  for(Index n = 0; n < 3 * size; ++n)
  {
    Index i = internal::random<Index>(0, size-1);
    Index j;
    do j = internal::random<Index>(0, size-1); while(j==i);
    std::swap(v(i), v(j));
  }
}

} // end namespace Eigen

template<typename T> struct GetDifferentType;

template<> struct GetDifferentType<float> { typedef double type; };
template<> struct GetDifferentType<double> { typedef float type; };
template<typename T> struct GetDifferentType<std::complex<T> >
{ typedef std::complex<typename GetDifferentType<T>::type> type; };

template<typename T> std::string type_name() { return "other"; }
template<> std::string type_name<float>() { return "float"; }
template<> std::string type_name<double>() { return "double"; }
template<> std::string type_name<int>() { return "int"; }
template<> std::string type_name<std::complex<float> >() { return "complex<float>"; }
template<> std::string type_name<std::complex<double> >() { return "complex<double>"; }
template<> std::string type_name<std::complex<int> >() { return "complex<int>"; }

// forward declaration of the main test function
void EIGEN_CAT(test_,EIGEN_TEST_FUNC)();

using namespace Eigen;

void set_repeat_from_string(const char *str)
{
  errno = 0;
  g_repeat = int(strtoul(str, 0, 10));
  if(errno || g_repeat <= 0)
  {
    std::cout << "Invalid repeat value " << str << std::endl;
    exit(EXIT_FAILURE);
  }
  g_has_set_repeat = true;
}

void set_seed_from_string(const char *str)
{
  errno = 0;
  g_seed = strtoul(str, 0, 10);
  if(errno || g_seed == 0)
  {
    std::cout << "Invalid seed value " << str << std::endl;
    exit(EXIT_FAILURE);
  }
  g_has_set_seed = true;
}

int main(int argc, char *argv[])
{
    g_has_set_repeat = false;
    g_has_set_seed = false;
    bool need_help = false;

    for(int i = 1; i < argc; i++)
    {
      if(argv[i][0] == 'r')
      {
        if(g_has_set_repeat)
        {
          std::cout << "Argument " << argv[i] << " conflicting with a former argument" << std::endl;
          return 1;
        }
        set_repeat_from_string(argv[i]+1);
      }
      else if(argv[i][0] == 's')
      {
        if(g_has_set_seed)
        {
          std::cout << "Argument " << argv[i] << " conflicting with a former argument" << std::endl;
          return 1;
        }
         set_seed_from_string(argv[i]+1);
      }
      else
      {
        need_help = true;
      }
    }

    if(need_help)
    {
      std::cout << "This test application takes the following optional arguments:" << std::endl;
      std::cout << "  rN     Repeat each test N times (default: " << DEFAULT_REPEAT << ")" << std::endl;
      std::cout << "  sN     Use N as seed for random numbers (default: based on current time)" << std::endl;
      std::cout << std::endl;
      std::cout << "If defined, the environment variables EIGEN_REPEAT and EIGEN_SEED" << std::endl;
      std::cout << "will be used as default values for these parameters." << std::endl;
      return 1;
    }

    char *env_EIGEN_REPEAT = getenv("EIGEN_REPEAT");
    if(!g_has_set_repeat && env_EIGEN_REPEAT)
      set_repeat_from_string(env_EIGEN_REPEAT);
    char *env_EIGEN_SEED = getenv("EIGEN_SEED");
    if(!g_has_set_seed && env_EIGEN_SEED)
      set_seed_from_string(env_EIGEN_SEED);

    if(!g_has_set_seed) g_seed = (unsigned int) time(NULL);
    if(!g_has_set_repeat) g_repeat = DEFAULT_REPEAT;

    std::cout << "Initializing random number generator with seed " << g_seed << std::endl;
    srand(g_seed);
    std::cout << "Repeating each test " << g_repeat << " times" << std::endl;

    Eigen::g_test_stack.push_back(EI_PP_MAKE_STRING(EIGEN_TEST_FUNC));

    EIGEN_CAT(test_,EIGEN_TEST_FUNC)();
    return 0;
}


text:
<?php declare(strict_types=1);

namespace PhpParser\Node\Expr;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\FunctionLike;

class Closure extends Expr implements FunctionLike
{
    /** @var bool Whether the closure is static */
    public $static;
    /** @var bool Whether to return by reference */
    public $byRef;
    /** @var Node\Param[] Parameters */
    public $params;
    /** @var ClosureUse[] use()s */
    public $uses;
    /** @var null|Node\Identifier|Node\Name|Node\NullableType Return type */
    public $returnType;
    /** @var Node\Stmt[] Statements */
    public $stmts;

    /**
     * Constructs a lambda function node.
     *
     * @param array $subNodes   Array of the following optional subnodes:
     *                          'static'     => false  : Whether the closure is static
     *                          'byRef'      => false  : Whether to return by reference
     *                          'params'     => array(): Parameters
     *                          'uses'       => array(): use()s
     *                          'returnType' => null   : Return type
     *                          'stmts'      => array(): Statements
     * @param array $attributes Additional attributes
     */
    public function __construct(array $subNodes = [], array $attributes = []) {
        parent::__construct($attributes);
        $this->static = $subNodes['static'] ?? false;
        $this->byRef = $subNodes['byRef'] ?? false;
        $this->params = $subNodes['params'] ?? [];
        $this->uses = $subNodes['uses'] ?? [];
        $returnType = $subNodes['returnType'] ?? null;
        $this->returnType = \is_string($returnType) ? new Node\Identifier($returnType) : $returnType;
        $this->stmts = $subNodes['stmts'] ?? [];
    }

    public function getSubNodeNames() : array {
        return ['static', 'byRef', 'params', 'uses', 'returnType', 'stmts'];
    }

    public function returnsByRef() : bool {
        return $this->byRef;
    }

    public function getParams() : array {
        return $this->params;
    }

    public function getReturnType() {
        return $this->returnType;
    }

    /** @return Node\Stmt[] */
    public function getStmts() : array {
        return $this->stmts;
    }

    function getType() : string {
        return 'Expr_Closure';
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface NSRegularExpression (RFExtendedAPI)

+ (NSRegularExpression *)regexFromString:(NSString *)regexString;
+ (NSString *)stringByReplacingRegex:(NSString *)regexString withTemplate:(NSString *)template inString:(NSString *)sourceString;
+ (void)replaceRegex:(NSString *)regexString withTemplate:(NSString *)template inString:(NSMutableString *)sourceString;
+ (NSUInteger)numberOfMatchesToRegex:(NSString *)regexString inString:(NSString *)sourceString;

@end


text:
class OpenUriAdapter < HTTPBaseAdapter
  def send_get_request
    open(parse_uri)
  end

  def expected_response_body
    " (not available yet)"
  end

  def self.should_log_headers?
    false
  end

  def logs_data?
    false
  end
end


text:
  Xirocourt est
       un village
       localisé dans le département de Meurthe-et-Moselle en Lorraine. On dénombrait 449 habitants en 2008.

À coté de Xirocourt sont positionnées géographiquement les villes de
Tantonville à 4 km, 623 habitants,
Vaudigny à 2 km, 46 habitants,
Germonville située à 3 km, 83 habitants,
Praye localisée à 4 km, 241 habitants,
Battexey située à 4 km, 29 habitants,
Affracourt à 3 km, 98 habitants,
 entre autres. De plus, Xirocourt est située à seulement 29 km de Nancy.

Le nombre d'habitations, à Xirocourt, était réparti en 2011 en quatorze appartements et 208 maisons soit
 un marché relativement équilibré.

Si vous pensez emmenager à Xirocourt, vous pourrez facilement trouver une maison à acheter.

La ville propose quelques  équipements, elle propose entre autres une boucle de randonnée.


text:
#ifndef PERIODIC_H_
#define PERIODIC_H_

/*--------------------------------------------------------------------------------------
 * Purpose: Initialize the periodic events settings.
 * Input: none
 * Output: returns 0 on success, 1 on failure
 * He Yan @ July 22, 2008
 * -------------------------------------------------------------------------------------*/
int
initPeriodicSettings();

/*--------------------------------------------------------------------------------------
 * Purpose: Read the periodic events settings from the config file.
 * Input: none
 * Output: returns 0 on success, 1 on failure
 * He Yan @ July 22, 2008
 * -------------------------------------------------------------------------------------*/
int
readPeriodicSettings();

/*--------------------------------------------------------------------------------------
 * Purpose: Save the periodic events settings to the config file.
 * Input:  none
 * Output: returns 0 on success, 1 on failure.
 * He Yan @ July 22, 2008
 * -------------------------------------------------------------------------------------*/
int
savePeriodicSettings();

/*--------------------------------------------------------------------------------------
 * Purpose: launch periodic route refresh and status message threads, called by main.c
 * Input:  none
 * Output: none
 * He Yan @ July 22, 2008
 * -------------------------------------------------------------------------------------*/
void LaunchPeriodicThreads();

/*--------------------------------------------------------------------------------------
 * Purpose: Set the interval of route refresh
 * Input:	the interval
 * Output:
 * He Yan @ Sep 22, 2008
 * -------------------------------------------------------------------------------------*/
void
setPeriodicRouteRefreshInterval( int interval );

/*--------------------------------------------------------------------------------------
 * Purpose: get the interval of route refresh
 * Input:
 * Output: the interva
 * He Yan @ Sep 22, 2008
 * -------------------------------------------------------------------------------------*/
int
getPeriodicRouteRefreshInterval();

/*--------------------------------------------------------------------------------------
 * Purpose: Set the interval of sending status message
 * Input:	the interval
 * Output:
 * He Yan @ Sep 22, 2008
 * -------------------------------------------------------------------------------------*/
void
setPeriodicStatusMessageInterval( int interval );

/*--------------------------------------------------------------------------------------
 * Purpose: Get the interval of sending status message
 * Input:
 * Output: the interval
 * He Yan @ Sep 22, 2008
 * -------------------------------------------------------------------------------------*/
int
getPeriodicStatusMessageInterval();

/*--------------------------------------------------------------------------------------
 * Purpose: enable route refresh from peers
 * Input: the transfer type
 * Output:
 * Kevin Burnett @ June 18, 2009
 * -------------------------------------------------------------------------------------*/
void
enablePeriodicRouteRefresh();

/*--------------------------------------------------------------------------------------
 * Purpose: disables route refresh from peers
 * Input: the transfer type
 * Output:
 * Kevin Burnett @ June 18, 2009
 * -------------------------------------------------------------------------------------*/
void
disablePeriodicRouteRefresh();

/*--------------------------------------------------------------------------------------
 * Purpose: Get the transfer type
 * Input:
 * Output: the type
 * Kevin Burnett @ June 18, 2009
 * -------------------------------------------------------------------------------------*/
int
getPeriodicRouteRefreshEnableStatus();

/*--------------------------------------------------------------------------------------
 * Purpose: get the last action time of the Periodic thread
 * Input:
 * Output: last action time
 * Mikhail Strizhov @ Jun 25, 2009
 * -------------------------------------------------------------------------------------*/
time_t
getPeriodicRouteRefreshThreadLastActionTime();

/*--------------------------------------------------------------------------------------
 * Purpose: get the last action time of the Periodic thread
 * Input:
 * Output: last action time
 * Mikhail Strizhov @ Jun 25, 2009
 * -------------------------------------------------------------------------------------*/
time_t
getPeriodicStatusMessageThreadLastActionTime();

/*--------------------------------------------------------------------------------------
 * Purpose: Intialize the shutdown process for the periodic module
 * Input:  none
 * Output: none
 * Kevin Burnett @ July 10, 2009
 * -------------------------------------------------------------------------------------*/
void signalPeriodicShutdown();

/*--------------------------------------------------------------------------------------
 * Purpose: wait on all periodic pieces to finish closing before returning
 * Input:  none
 * Output: none
 * Kevin Burnett @ July 10, 2009
 * -------------------------------------------------------------------------------------*/
void waitForPeriodicShutdown();

#endif /*PERIODIC_H_*/


text:
package com.guidewire.editor.devtools.dependencies;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import gw.lang.reflect.module.IModule;
import gw.plugin.ij.actions.TypeSystemAwareAction;
import gw.plugin.ij.compiler.FileDependencyCache;
import gw.plugin.ij.compiler.FileDependencyInfo;
import gw.plugin.ij.compiler.GosuCompilerMonitor;
import gw.plugin.ij.util.GosuModuleUtil;

import java.util.Collection;

public class DumpDependencyInfo extends TypeSystemAwareAction {
  private void print(String title, Collection<VirtualFile> files) {
    System.out.println(String.format("  %s (%d):", title, files.size()));
    if (files.isEmpty()) {
      System.out.println("    None");
    } else {
      for (VirtualFile f : files) {
        System.out.println("    " + f);
      }
    }
  }

  private void printDK(String title, Collection<String> strings) {
    System.out.println(String.format("  %s (%d):", title, strings.size()));
    if (strings.isEmpty()) {
      System.out.println("    None");
    } else {
      for (String f : strings) {
        System.out.println("    " + f);
      }
    }
  }

  @Override
  public void actionPerformed(AnActionEvent e) {
    final Project project = e.getProject();
    final FileDependencyCache cache = GosuCompilerMonitor.getInstance(project).getDependencyCache();
    for (VirtualFile file : e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY)) {
      final IModule module = GosuModuleUtil.findModuleForFile(file, project);
      final FileDependencyInfo info = cache.get(file);
      if (info != null) {
        System.out.println(String.format("Cache for '%s' [%d] - %dms", file, info.getFingerprint(), info.getCompileTime()));
        print("Dependencies", cache.getDependencies(file));
        print("Dependents", cache.getDependentsOn(file));
        printDK("DisplayKeys", cache.get(file).getDisplayKeys());
        System.out.println();
      } else {
        System.out.println(String.format("No cache entry for '%s'", file));
      }
    }
  }
}


text:
package org.apache.sysds.runtime.instructions.spark;

import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.function.PairFlatMapFunction;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.broadcast.Broadcast;
import org.apache.spark.storage.StorageLevel;
import org.apache.sysds.lops.PMapMult;
import org.apache.sysds.runtime.DMLRuntimeException;
import org.apache.sysds.runtime.controlprogram.context.ExecutionContext;
import org.apache.sysds.runtime.controlprogram.context.SparkExecutionContext;
import org.apache.sysds.runtime.instructions.InstructionUtils;
import org.apache.sysds.runtime.instructions.cp.CPOperand;
import org.apache.sysds.runtime.instructions.spark.data.PartitionedBlock;
import org.apache.sysds.runtime.instructions.spark.functions.IsBlockInRange;
import org.apache.sysds.runtime.instructions.spark.utils.RDDAggregateUtils;
import org.apache.sysds.runtime.matrix.data.MatrixBlock;
import org.apache.sysds.runtime.matrix.data.MatrixIndexes;
import org.apache.sysds.runtime.matrix.data.OperationsOnMatrixValues;
import org.apache.sysds.runtime.matrix.operators.AggregateBinaryOperator;
import org.apache.sysds.runtime.matrix.operators.Operator;
import org.apache.sysds.runtime.meta.DataCharacteristics;
import scala.Tuple2;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * This pmapmm matrix multiplication instruction is still experimental
 * not integrated in automatic operator selection yet.
 *
 */
public class PMapmmSPInstruction extends BinarySPInstruction {
	private static final int NUM_ROWBLOCKS = 4;

	private PMapmmSPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand out, String opcode, String istr) {
		super(SPType.PMAPMM, op, in1, in2, out, opcode, istr);
	}

	public static PMapmmSPInstruction parseInstruction( String str ) {
		String parts[] = InstructionUtils.getInstructionPartsWithValueType(str);
		String opcode = parts[0];

		if ( opcode.equalsIgnoreCase(PMapMult.OPCODE)) {
			CPOperand in1 = new CPOperand(parts[1]);
			CPOperand in2 = new CPOperand(parts[2]);
			CPOperand out = new CPOperand(parts[3]);
			AggregateBinaryOperator aggbin = InstructionUtils.getMatMultOperator(1);
			return new PMapmmSPInstruction(aggbin, in1, in2, out, opcode, str);
		}
		else {
			throw new DMLRuntimeException("PMapmmSPInstruction.parseInstruction():: Unknown opcode " + opcode);
		}
	}

	@Override
	public void processInstruction(ExecutionContext ec) {
		SparkExecutionContext sec = (SparkExecutionContext)ec;

		//get inputs
		JavaPairRDD<MatrixIndexes,MatrixBlock> in1 = sec.getBinaryMatrixBlockRDDHandleForVariable( input1.getName() );
		JavaPairRDD<MatrixIndexes,MatrixBlock> in2 = sec.getBinaryMatrixBlockRDDHandleForVariable( input2.getName() );
		DataCharacteristics mc1 = sec.getDataCharacteristics(input1.getName());

		// This avoids errors such as java.lang.UnsupportedOperationException: Cannot change storage level of an RDD after it was already assigned a level
		// Ideally, we should ensure that we donot redundantly call persist on the same RDD.
		StorageLevel pmapmmStorageLevel = StorageLevel.MEMORY_AND_DISK();

		//cache right hand side because accessed many times
		in2 = in2.repartition(sec.getSparkContext().defaultParallelism())
				 .persist(pmapmmStorageLevel);

		JavaPairRDD<MatrixIndexes,MatrixBlock> out = null;
		for( int i=0; i<mc1.getRows(); i+=NUM_ROWBLOCKS*mc1.getBlocksize() )
		{
			//create broadcast for rdd partition
			JavaPairRDD<MatrixIndexes,MatrixBlock> rdd = in1
					.filter(new IsBlockInRange(i+1, i+NUM_ROWBLOCKS*mc1.getBlocksize(), 1, mc1.getCols(), mc1))
					.mapToPair(new PMapMMRebaseBlocksFunction(i/mc1.getBlocksize()));

			int rlen = (int)Math.min(mc1.getRows()-i, NUM_ROWBLOCKS*mc1.getBlocksize());
			PartitionedBlock<MatrixBlock> pmb = SparkExecutionContext.toPartitionedMatrixBlock(rdd, rlen, (int)mc1.getCols(), mc1.getBlocksize(), -1L);
			Broadcast<PartitionedBlock<MatrixBlock>> bpmb = sec.getSparkContext().broadcast(pmb);

			//matrix multiplication
			JavaPairRDD<MatrixIndexes,MatrixBlock> rdd2 = in2
					.flatMapToPair(new PMapMMFunction(bpmb, i/mc1.getBlocksize()));
			rdd2 = RDDAggregateUtils.sumByKeyStable(rdd2, false);
			rdd2.persist(pmapmmStorageLevel)
			    .count();
			bpmb.unpersist(false);

			if( out == null )
				out = rdd2;
			else
				out = out.union(rdd2);
		}

		//cache final result
		out = out.persist(pmapmmStorageLevel);
		out.count();

		//put output RDD handle into symbol table
		sec.setRDDHandleForVariable(output.getName(), out);
		sec.addLineageRDD(output.getName(), input1.getName());
		sec.addLineageRDD(output.getName(), input2.getName());

		//update output statistics if not inferred
		updateBinaryMMOutputDataCharacteristics(sec, true);
	}

	private static class PMapMMRebaseBlocksFunction implements PairFunction<Tuple2<MatrixIndexes, MatrixBlock>, MatrixIndexes, MatrixBlock>
	{
		private static final long serialVersionUID = 98051757210704132L;

		private int _offset = -1;

		public PMapMMRebaseBlocksFunction(int offset){
			_offset = offset;
		}

		@Override
		public Tuple2<MatrixIndexes, MatrixBlock> call( Tuple2<MatrixIndexes, MatrixBlock> arg0 )
			throws Exception
		{
			long rix = arg0._1().getRowIndex()-_offset;
			MatrixIndexes ixout = new MatrixIndexes(rix, arg0._1().getColumnIndex());
			return new Tuple2<>(ixout, arg0._2());
		}
	}

	private static class PMapMMFunction implements PairFlatMapFunction<Tuple2<MatrixIndexes, MatrixBlock>, MatrixIndexes, MatrixBlock>
	{
		private static final long serialVersionUID = -4520080421816885321L;

		private AggregateBinaryOperator _op = null;
		private Broadcast<PartitionedBlock<MatrixBlock>> _pbc = null;
		private long _offset = -1;

		public PMapMMFunction( Broadcast<PartitionedBlock<MatrixBlock>> binput, long offset ) {
			_pbc = binput;
			_offset = offset;
			_op = InstructionUtils.getMatMultOperator(1);
		}

		@Override
		public Iterator<Tuple2<MatrixIndexes, MatrixBlock>> call(Tuple2<MatrixIndexes, MatrixBlock> arg0)
			throws Exception
		{
			PartitionedBlock<MatrixBlock> pm = _pbc.value();

			MatrixIndexes ixIn = arg0._1();
			MatrixBlock blkIn = arg0._2();

			MatrixIndexes ixOut = new MatrixIndexes();
			MatrixBlock blkOut = new MatrixBlock();

			ArrayList<Tuple2<MatrixIndexes, MatrixBlock>> ret = new ArrayList<>();

			//get the right hand side matrix
			for( int i=1; i<=pm.getNumRowBlocks(); i++ ) {
				MatrixBlock left = pm.getBlock(i, (int)ixIn.getRowIndex());

				//execute matrix-vector mult
				OperationsOnMatrixValues.matMult(new MatrixIndexes(i,ixIn.getRowIndex()),
					left, ixIn, blkIn, ixOut, blkOut, _op);

				//output new tuple
				ixOut.setIndexes(_offset+i, ixOut.getColumnIndex());
				ret.add(new Tuple2<>(ixOut, blkOut));
			}

			return ret.iterator();
		}
	}
}


text:
title: Adding Snippets to Your Sublime Text Installation
localeTitle: Добавление фрагментов к вашей строжайшей текстовой установке
---
Если вы являетесь пользователем возвышенного текста (я надеюсь, что вы это делаете, он пинает задницу. Вы можете получить его [здесь](https://www.sublimetext.com/) ), тогда вы, возможно, уже заметили некоторые возможности завершения табуляции. Например, когда вы открываете тег html, такой как `<p>` , он автоматически закрывает тег сразу после ввода `/` . Вы можете получить аналогичную функциональность для фрагментов кода, которые вы в конечном итоге переписываете снова и снова, и это удивительно просто!

Вот пример, который активируется после ввода `div` и затем вкладки:

![alt text](//discourse-user-assets.s3.amazonaws.com/original/2X/5/59a4d233d2dcb17b76a9c36ca30c5bb07a35d00b.png)

## Шаг 1.

Нажмите « `Tools > New Snippet...` на панели навигации. Это откроет файл скелетного фрагмента, который будет выглядеть следующим образом:

![alt text](//discourse-user-assets.s3.amazonaws.com/original/2X/a/a56106fbf754f7e641342d1ebdbc3f5bed582263.png)

## Шаг 2.

Вы добавите фрагмент, заменив текст `Hello, ${1:this} is a ${2:snippet}.`

В случае фрагмента `div` это так же просто, как размещение следующего текста в области фрагмента:
```
<!-- $1 -->
 <div class= "$1">

 </div>
 <!-- $1 -->
```

Оператор `$` ссылается на переменные, которые будут введены после того, как вы наберете `div` и затем вкладку. На самом деле у вас может быть любое их количество!

## Шаг 3.

Сохраните файл. Вы можете `.sublime-snippet` ему любое имя файла, но расширение **должно** быть `.sublime-snippet` . Помните, вы можете иметь только один фрагмент файла! Мне нравится давать им описательные имена, такие как `html-div.sublime-snippet` .

И вот оно! Вы можете стать настолько креативными, насколько хотите.


text:
require 'spec_helper'

describe CloudsAndDragons do
  it 'has a version number' do
    expect(CloudsAndDragons::VERSION).not_to be nil
  end

  it 'does something useful' do
    expect(false).to eq(true)
  end
end


text:
define(['./system'], function (system) {
	var parseMarkupCore;

	if ($.parseHTML) {
		parseMarkupCore = function(html) {
			return $.parseHTML(html);
		};
	} else {
		parseMarkupCore = function(html) {
			return $(html).get();
		};
	}

	return {
		viewExtension: '.html',
		viewPlugin: 'text',
		isViewUrl: function (url) {
			return url.indexOf(this.viewExtension, url.length - this.viewExtension.length) !== -1;
		},
		convertViewUrlToViewId: function (url) {
			return url.substring(0, url.length - this.viewExtension.length);
		},
		convertViewIdToRequirePath: function (viewId) {
			return this.viewPlugin + '!' + viewId + this.viewExtension;
		},
		parseMarkup: function (markup) {
			var allElements = parseMarkupCore(markup);
			if (allElements.length === 1) {
				return allElements[0];
			}

			var withoutCommentsOrEmptyText = [];

			for (var i = 0; i < allElements.length; i++) {
				var current = allElements[i];
				if (current.nodeType !== 8) {
					if (current.nodeType === 3) {
						var result = /\S/.test(current.nodeValue);
						if (!result) {
							continue;
						}
					}

					withoutCommentsOrEmptyText.push(current);
				}
			}

			if (withoutCommentsOrEmptyText.length > 1) {
				return $(withoutCommentsOrEmptyText).wrapAll('

').parent().get(0);
			}

			return withoutCommentsOrEmptyText[0];
		},
		createView: function(viewId) {
			var that = this;
			var requirePath = this.convertViewIdToRequirePath(viewId);

			return system.defer(function(dfd) {
				system.acquire(requirePath).then(function(markup) {
					var element = that.parseMarkup(markup);
					element.setAttribute('data-view', viewId);
					dfd.resolve(element);
				});
			}).promise();
		}
	};
});


text:
// Author: Marcin Hoppe <marcin.hoppe (at) gmail.com>

using System;

namespace MarcinHoppe.EightQueens
{
    class Program
    {
        static void Main(string[] args)
        {
            var problem = new EightQueensProblem();
            problem.Solve();
            problem.PrintSolution();
        }
    }
}


text:
package com.namics.commons.random.test;

/**
 * GenericChild.
 *
 * @author aschaefer, Namics AG
 * @since 09.07.15 09:27
 */
public class GenericGrandDaughter extends GenericDaughter<GenericGrandDaughter> {
}


text:
package adapter

import (
	"net/http"
	"testing"

	_ "knative.dev/pkg/metrics/testing"

	"knative.dev/pkg/metrics/metricskey"
	"knative.dev/pkg/metrics/metricstest"
)

func TestStatsReporter(t *testing.T) {
	args := &ReportArgs{
		EventType:   "dev.knative.event",
		EventSource: "unit-test",
	}

	r, err := NewStatsReporter("testobject", "testns", "testresourcegroup")
	if err != nil {
		t.Fatalf("Error creating reporter: %v", err)
	}

	wantTags := map[string]string{
		metricskey.LabelNamespaceName:     "testns",
		metricskey.LabelEventType:         "dev.knative.event",
		metricskey.LabelEventSource:       "unit-test",
		metricskey.LabelName:              "testobject",
		metricskey.LabelResourceGroup:     "testresourcegroup",
		metricskey.LabelResponseCode:      "202",
		metricskey.LabelResponseCodeClass: "2xx",
	}

	// test ReportEventCount
	expectSuccess(t, func() error {
		return r.ReportEventCount(args, http.StatusAccepted)
	})
	expectSuccess(t, func() error {
		return r.ReportEventCount(args, http.StatusAccepted)
	})
	metricstest.CheckCountData(t, "event_count", wantTags, 2)
}

func expectSuccess(t *testing.T, f func() error) {
	t.Helper()
	if err := f(); err != nil {
		t.Errorf("Reporter expected success but got error: %v", err)
	}
}


text:
require 'spec_helper'

describe Gitlab::Diff::SuggestionDiff do
  describe '#diff_lines' do
    let(:from_content) do
      <<-BLOB.strip_heredoc
         "tags": ["devel", "development", "nightly"],
         "desktop-file-name-prefix": "(Development) ",
         "finish-args": "foo",
      BLOB
    end

    let(:to_content) do
      <<-BLOB.strip_heredoc
         "buildsystem": "meson",
         "builddir": true,
         "name": "nautilus",
         "bar": "bar",
      BLOB
    end

    let(:suggestion) do
      instance_double(Suggestion, from_line: 12,
                                  from_content: from_content,
                                  to_content: to_content)
    end

    subject { described_class.new(suggestion).diff_lines }

    let(:expected_diff_lines) do
      [
        { old_pos: 12, new_pos: 12, type: "match", text: "@@ -12 +12" },
        { old_pos: 12, new_pos: 12, type: "old", text: "-\"tags\": [\"devel\", \"development\", \"nightly\"]," },
        { old_pos: 13, new_pos: 12, type: "old", text: "-\"desktop-file-name-prefix\": \"(Development) \"," },
        { old_pos: 14, new_pos: 12, type: "old", text: "-\"finish-args\": \"foo\"," },
        { old_pos: 15, new_pos: 12, type: "new", text: "+\"buildsystem\": \"meson\"," },
        { old_pos: 15, new_pos: 13, type: "new", text: "+\"builddir\": true," },
        { old_pos: 15, new_pos: 14, type: "new", text: "+\"name\": \"nautilus\"," },
        { old_pos: 15, new_pos: 15, type: "new", text: "+\"bar\": \"bar\"," }
      ]
    end

    it 'returns diff lines with correct line numbers' do
      diff_lines = subject

      expect(diff_lines).to all(be_a(Gitlab::Diff::Line))

      expected_diff_lines.each_with_index do |expected_line, index|
        expect(diff_lines[index].to_hash).to include(expected_line)
      end
    end
  end
end


text:
using System;
using System.Threading;
using Microsoft.Isam.Esent.Interop;

namespace DvachBrowser3.Storage.Esent
{
    /// <summary>
    /// Транзакция таблицы.
    /// </summary>
    internal struct TableTransaction : IDisposable
    {
        /// <summary>
        /// Экземпляр.
        /// </summary>
        public IEsentInstance Instance;

        /// <summary>
        /// Сессия.
        /// </summary>
        public Session Session;

        /// <summary>
        /// Идентификатор базы.
        /// </summary>
        public JET_DBID Dbid;

        /// <summary>
        /// Транзакция.
        /// </summary>
        public Transaction Transaction;

        /// <summary>
        /// Таблица.
        /// </summary>
        public Table Table;

        /// <summary>
        /// Контекст выполнения.
        /// </summary>
        public IThreadExecutionContext ExecutionContext;

        /// <summary>
        /// Выполняет определяемые приложением задачи, связанные с удалением, высвобождением или сбросом неуправляемых ресурсов.
        /// </summary>
        public async void Dispose()
        {
            try
            {
                var r = this;
                await ExecutionContext.Execute(() =>
                {
                    r.Table.Dispose();
                    r.Transaction.Dispose();
                    r.Session.Dispose();
                    r.Instance.Dispose();
                });
            }
            finally
            {
                ExecutionContext.Dispose();
            }
        }
    }
}


text:
#ifndef ownServerApi_INCLUDED
#define ownServerApi_INCLUDED

#ifdef __cplusplus
extern "C" {
#endif

#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */
#include "simplehttp.h"

void postWeather(float temperature, float pressure, char const * uuid);

#ifdef __cplusplus
}
#endif
#endif


text:
namespace google {
namespace cloud {
namespace spanner_admin_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

class InstanceAdminConnectionImpl
    : public spanner_admin::InstanceAdminConnection {
 public:
  ~InstanceAdminConnectionImpl() override = default;

  InstanceAdminConnectionImpl(
      std::unique_ptr<google::cloud::BackgroundThreads> background,
      std::shared_ptr<spanner_admin_internal::InstanceAdminStub> stub,
      Options options);

  Options options() override { return options_; }

  StreamRange<google::spanner::admin::instance::v1::InstanceConfig>
  ListInstanceConfigs(
      google::spanner::admin::instance::v1::ListInstanceConfigsRequest request)
      override;

  StatusOr<google::spanner::admin::instance::v1::InstanceConfig>
  GetInstanceConfig(
      google::spanner::admin::instance::v1::GetInstanceConfigRequest const&
          request) override;

  future<StatusOr<google::spanner::admin::instance::v1::InstanceConfig>>
  CreateInstanceConfig(
      google::spanner::admin::instance::v1::CreateInstanceConfigRequest const&
          request) override;

  future<StatusOr<google::spanner::admin::instance::v1::InstanceConfig>>
  UpdateInstanceConfig(
      google::spanner::admin::instance::v1::UpdateInstanceConfigRequest const&
          request) override;

  Status DeleteInstanceConfig(
      google::spanner::admin::instance::v1::DeleteInstanceConfigRequest const&
          request) override;

  StreamRange<google::longrunning::Operation> ListInstanceConfigOperations(
      google::spanner::admin::instance::v1::ListInstanceConfigOperationsRequest
          request) override;

  StreamRange<google::spanner::admin::instance::v1::Instance> ListInstances(
      google::spanner::admin::instance::v1::ListInstancesRequest request)
      override;

  StatusOr<google::spanner::admin::instance::v1::Instance> GetInstance(
      google::spanner::admin::instance::v1::GetInstanceRequest const& request)
      override;

  future<StatusOr<google::spanner::admin::instance::v1::Instance>>
  CreateInstance(
      google::spanner::admin::instance::v1::CreateInstanceRequest const&
          request) override;

  future<StatusOr<google::spanner::admin::instance::v1::Instance>>
  UpdateInstance(
      google::spanner::admin::instance::v1::UpdateInstanceRequest const&
          request) override;

  Status DeleteInstance(
      google::spanner::admin::instance::v1::DeleteInstanceRequest const&
          request) override;

  StatusOr<google::iam::v1::Policy> SetIamPolicy(
      google::iam::v1::SetIamPolicyRequest const& request) override;

  StatusOr<google::iam::v1::Policy> GetIamPolicy(
      google::iam::v1::GetIamPolicyRequest const& request) override;

  StatusOr<google::iam::v1::TestIamPermissionsResponse> TestIamPermissions(
      google::iam::v1::TestIamPermissionsRequest const& request) override;

 private:
  std::unique_ptr<spanner_admin::InstanceAdminRetryPolicy> retry_policy() {
    auto const& options = internal::CurrentOptions();
    if (options.has<spanner_admin::InstanceAdminRetryPolicyOption>()) {
      return options.get<spanner_admin::InstanceAdminRetryPolicyOption>()
          ->clone();
    }
    return options_.get<spanner_admin::InstanceAdminRetryPolicyOption>()
        ->clone();
  }

  std::unique_ptr<BackoffPolicy> backoff_policy() {
    auto const& options = internal::CurrentOptions();
    if (options.has<spanner_admin::InstanceAdminBackoffPolicyOption>()) {
      return options.get<spanner_admin::InstanceAdminBackoffPolicyOption>()
          ->clone();
    }
    return options_.get<spanner_admin::InstanceAdminBackoffPolicyOption>()
        ->clone();
  }

  std::unique_ptr<spanner_admin::InstanceAdminConnectionIdempotencyPolicy>
  idempotency_policy() {
    auto const& options = internal::CurrentOptions();
    if (options.has<
            spanner_admin::InstanceAdminConnectionIdempotencyPolicyOption>()) {
      return options
          .get<spanner_admin::InstanceAdminConnectionIdempotencyPolicyOption>()
          ->clone();
    }
    return options_
        .get<spanner_admin::InstanceAdminConnectionIdempotencyPolicyOption>()
        ->clone();
  }

  std::unique_ptr<PollingPolicy> polling_policy() {
    auto const& options = internal::CurrentOptions();
    if (options.has<spanner_admin::InstanceAdminPollingPolicyOption>()) {
      return options.get<spanner_admin::InstanceAdminPollingPolicyOption>()
          ->clone();
    }
    return options_.get<spanner_admin::InstanceAdminPollingPolicyOption>()
        ->clone();
  }

  std::unique_ptr<google::cloud::BackgroundThreads> background_;
  std::shared_ptr<spanner_admin_internal::InstanceAdminStub> stub_;
  Options options_;
};

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
namespace gcpcxxV1 = GOOGLE_CLOUD_CPP_NS;  // NOLINT(misc-unused-alias-decls)
}  // namespace spanner_admin_internal
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_INTERNAL_INSTANCE_ADMIN_CONNECTION_IMPL_H


text:
package main

import (
	"compress/gzip"
	"context"
	"fmt"
	"io"
	"log"
	"math"
	"math/rand"
	"mime"
	"os"
	"path"
	"path/filepath"
	"sort"
	"strings"
	"sync"
	"time"

	"google.golang.org/cloud/storage"
)

// Plugin defines the GCS plugin parameters.
type Plugin struct {
	AuthKey string

	// Indicates the files ACL's to apply
	ACL []string

	// Copies the files from the specified directory.
	Source string

	// Destination to copy files to, including bucket name
	Target string

	// Exclude files matching this pattern.
	Ignore string

	Gzip         []string
	CacheControl string
	Metadata     map[string]string

	// bucket is the GCS target bucket
	bucket *storage.BucketHandle

	// google cloud storage client
	// client *storage.Client

	// logging functions
	printf func(string, ...interface{})
	fatalf func(string, ...interface{})

	// program exit code
	ecodeMu sync.Mutex // guards ecode
	ecode   int

	// sleep is overwritten during tests
	sleep func(time.Duration)
}

func (p *Plugin) Exec(client *storage.Client) error {
	// init some values
	sort.Strings(p.Gzip) // need for matchGzip
	rand.Seed(time.Now().UnixNano())
	p.sleep = time.Sleep
	p.printf = log.Printf
	p.fatalf = log.Fatalf

	// extract bucket name from the target path
	tgt := strings.SplitN(p.Target, "/", 2)
	bname := tgt[0]
	if len(tgt) == 1 {
		p.Target = ""
	} else {
		p.Target = tgt[1]
	}
	p.bucket = client.Bucket(strings.Trim(bname, "/"))

	// create a list of files to upload
	if !strings.HasPrefix(p.Source, "/") {
		pwd, err := os.Getwd()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		p.printf("source path relative to %s", pwd)
		p.Source = filepath.Join(pwd, p.Source)
	}
	src, err := p.walkFiles()
	if err != nil {
		p.fatalf("local files: %v", err)
	}

	// result contains upload result of a single file
	type result struct {
		name string
		err  error
	}

	// upload all files in a goroutine, maxConcurrent at a time
	buf := make(chan struct{}, maxConcurrent)
	res := make(chan *result, len(src))
	for _, f := range src {
		buf <- struct{}{} // alloc one slot
		go func(f string) {
			rel, err := filepath.Rel(p.Source, f)
			if err != nil {
				res <- &result{f, err}
				return
			}
			err = p.retryUpload(path.Join(p.Target, rel), f, 5)
			res <- &result{rel, err}
			<-buf // free up
		}(f)
	}

	// wait for all files to be uploaded or stop at first error
	for _ = range src {
		r := <-res
		if r.err != nil {
			p.fatalf("%s: %v", r.name, r.err)
		}
		p.printf(r.name)
	}

	return nil
}

// errorf sets exit code to a non-zero value and outputs using printf.
func (p *Plugin) errorf(format string, args ...interface{}) {
	p.ecodeMu.Lock()
	p.ecode = 1
	p.ecodeMu.Unlock()
	p.printf(format, args...)
}

// retryUpload calls uploadFile until the latter returns nil
// or the number of invocations reaches n.
// It blocks for a duration of seconds exponential to the iteration between the calls.
func (p *Plugin) retryUpload(dst, file string, n int) error {
	var err error
	for i := 0; i <= n; i++ {
		if i > 0 {
			t := time.Duration((math.Pow(2, float64(i)) + rand.Float64()) * float64(time.Second))
			p.sleep(t)
		}
		if err = p.uploadFile(dst, file); err == nil {
			break
		}
	}
	return err
}

// uploadFile uploads the file to dst using global bucket.
// To get a more robust upload use retryUpload instead.
func (p *Plugin) uploadFile(dst, file string) error {
	r, gz, err := p.gzipper(file)
	if err != nil {
		return err
	}
	defer r.Close()
	rel, err := filepath.Rel(p.Source, file)
	if err != nil {
		return err
	}
	name := path.Join(p.Target, rel)
	w := p.bucket.Object(name).NewWriter(context.Background())
	w.CacheControl = p.CacheControl
	w.Metadata = p.Metadata
	for _, s := range p.ACL {
		a := strings.SplitN(s, ":", 2)
		if len(a) != 2 {
			return fmt.Errorf("%s: invalid ACL %q", name, s)
		}
		w.ACL = append(w.ACL, storage.ACLRule{
			Entity: storage.ACLEntity(a[0]),
			Role:   storage.ACLRole(a[1]),
		})
	}
	w.ContentType = mime.TypeByExtension(filepath.Ext(file))
	if w.ContentType == "" {
		w.ContentType = "application/octet-stream"
	}
	if gz {
		w.ContentEncoding = "gzip"
	}
	if _, err := io.Copy(w, r); err != nil {
		return err
	}
	return w.Close()
}

// gzipper returns a stream of file and a boolean indicating
// whether the stream is gzip-compressed.
//
// The stream is compressed if p.Gzip contains file extension.
func (p *Plugin) gzipper(file string) (io.ReadCloser, bool, error) {
	r, err := os.Open(file)
	if err != nil || !p.matchGzip(file) {
		return r, false, err
	}
	pr, pw := io.Pipe()
	w := gzip.NewWriter(pw)
	go func() {
		_, err := io.Copy(w, r)
		if err != nil {
			p.errorf("%s: io.Copy: %v", file, err)
		}
		if err := w.Close(); err != nil {
			p.errorf("%s: gzip: %v", file, err)
		}
		if err := pw.Close(); err != nil {
			p.errorf("%s: pipe: %v", file, err)
		}
		r.Close()
	}()
	return pr, true, nil
}

// matchGzip reports whether the file should be gzip-compressed during upload.
// Compressed files should be uploaded with "gzip" content-encoding.
func (p *Plugin) matchGzip(file string) bool {
	ext := filepath.Ext(file)
	if ext == "" {
		return false
	}
	ext = ext[1:]
	i := sort.SearchStrings(p.Gzip, ext)

	retVal := i < len(p.Gzip) && p.Gzip[i] == ext
	return retVal
}

// walkFiles creates a complete set of files to upload
// by walking p.Source recursively.
//
// It excludes files matching vargs.Ignore pattern.
// The ignore pattern is matched using filepath.Match against a partial
// file name, relative to vargs.Source.
func (p *Plugin) walkFiles() ([]string, error) {
	var items []string
	err := filepath.Walk(p.Source, func(path string, fi os.FileInfo, err error) error {
		if err != nil || fi.IsDir() {
			return err
		}
		rel, err := filepath.Rel(p.Source, path)
		if err != nil {
			return err
		}
		var ignore bool
		if p.Ignore != "" {
			ignore, err = filepath.Match(p.Ignore, rel)
		}
		if err != nil || ignore {
			return err
		}
		items = append(items, path)
		return nil
	})
	return items, err
}


text:
require 'whois/record/parser/base'
require 'whois/record/scanners/whois.smallregistry.net.rb'

module Whois
  class Record
    class Parser

      # Parser for the whois.smallregistry.net server.
      #
      # @author Mathieu Arnold <m@absolight.fr>
      #
      class WhoisSmallregistryNet < Base
        include Scanners::Nodable

        property_supported :disclaimer do
          node("field:disclaimer") do |str|
            str.scan(/# (.+)\n/).flatten.map do |str|
              token = str.strip
              token.gsub!(/\s+/, " ")
            end.join(" ").gsub!(/(\s{2})/, "\n")
          end
        end

        property_supported :domain do
          node("name")
        end

        property_not_supported :domain_id

        property_supported :status do
          if node?("status:available")
            :available
          else
            case node("status")
            when "ACTIVE"
              :registered
            else
              Whois.bug!(ParserError, "Unknown status `#{node("field:status")}'.")
            end
          end
        end

        property_supported :available? do
          status == :available
        end

        property_supported :registered? do
          !available?
        end

        property_supported :created_on do
          node("created") { |str| Time.parse(str) }
        end

        property_supported :updated_on do
          node("updated") { |str| Time.parse(str) }
        end

        property_supported :expires_on do
          node("expired") { |str| Time.parse(str) }
        end

        property_supported :registrar do
          node("registrar") do |hash|
            v1, v2, v3, v4 = hash.values_at('nil', 'name', 'name', 'web')
            Registrar.new(
                :id           => v1,
                :name         => v2,
                :organization => v3,
                :url          => v4
            )
          end
        end

        property_supported :registrant_contacts do
          build_contact("registrant", Whois::Record::Contact::TYPE_REGISTRANT)
        end

        property_supported :admin_contacts do
          build_contact("administrative_contact", Whois::Record::Contact::TYPE_ADMIN)
        end

        property_supported :technical_contacts do
          build_contact("technical_contact", Whois::Record::Contact::TYPE_TECHNICAL)
        end

        property_supported :nameservers do
          Array.wrap(node("name_servers")).map do |hash|
            Record::Nameserver.new(:name => hash)
          end
        end

        # Initializes a new {Scanners::WhoisSmallregistryNet} instance
        # passing the {#content_for_scanner}
        # and calls +parse+ on it.
        #
        # @return [Hash]
        def parse
          Scanners::WhoisSmallregistryNet.new(content_for_scanner).parse
        end

      private

        def build_contact(element, type)
          node(element) do |hash|
            Record::Contact.new(
              :type         => type,
              :id           => hash['nic-handle'],
              :name         => hash['name'],
              :organization => hash['company'],
              :address      => hash['address'],
              :phone        => hash['phone'],
              :fax          => hash['fax'],
              :email        => hash['mobile'],
              :updated_on   => Time.parse(hash['updated'])
            )
          end
        end

      end
    end
  end
end


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;

namespace FileHelpers
{
    /// <summary>
    /// Enable reading a string as a stream
    /// </summary>
    [Serializable]
    internal sealed class InternalStringReader : TextReader
    {
        /// <summary>
        /// String we are analysing
        /// </summary>
        private string mS;

        /// <summary>
        /// Create a stream based on the string
        /// </summary>
        /// <param name="s"></param>
        public InternalStringReader(string s)
        {
            if (s == null)
                throw new ArgumentNullException("s");
            this.mS = s;
            this.Length = s.Length;
        }

        /// <summary>
        /// Length of the stream
        /// </summary>
        internal int Length { get; private set; }

        /// <summary>
        /// Position within the stream
        /// </summary>
        internal int Position { get; private set; }

        /// <summary>
        /// Close the stream
        /// </summary>
        public override void Close()
        {
            this.Dispose(true);
        }

        /// <summary>
        /// Close the stream and release resources
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            this.mS = null;
            this.Position = 0;
            this.Length = 0;
            base.Dispose(disposing);
        }

        /// <summary>
        /// Peek at the next byte along in the stream
        /// </summary>
        /// <returns>Next character as an integer</returns>
        public override int Peek()
        {
            if (this.mS == null)
                throw new ObjectDisposedException(null, "The Reader is Closed");
            if (this.Position == this.Length)
                return -1;
            return this.mS[this.Position];
        }

        /// <summary>
        /// Read the next byte along in the string
        /// </summary>
        /// <returns>next character as an integer</returns>
        public override int Read()
        {
            if (this.mS == null)
                throw new ObjectDisposedException(null, "The Reader is Closed");
            if (this.Position == this.Length)
                return -1;
            return this.mS[this.Position = this.Position + 1];
        }

        /// <summary>
        /// Replaces text into the buffer at index for count characters
        /// </summary>
        /// <param name="buffer">
        /// An array of Unicode characters to which characters in this instance
        /// are copied.
        /// </param>
        /// <param name="index">
        /// The index in destination at which the copy operation begins.
        /// </param>
        /// <param name="count">
        /// The number of characters in this instance to copy to destination.
        /// </param>
        /// <returns>number of characters actually copied</returns>
        public override int Read([In, Out] char[] buffer, int index, int count)
        {
            if (buffer == null)
                throw new ArgumentNullException("buffer");
            if (index < 0)
                throw new ArgumentOutOfRangeException("index");
            if (count < 0)
                throw new ArgumentOutOfRangeException("count");
            if ((buffer.Length - index) < count)
                throw new ArgumentException("offset");
            if (this.mS == null)
                throw new ObjectDisposedException(null, "The Reader is Closed");
            int num = this.Length - this.Position;
            if (num > 0) {
                if (num > count)
                    num = count;
                this.mS.CopyTo(this.Position, buffer, index, num);
                this.Position = this.Position + num;
            }
            return num;
        }

        /// <summary>
        /// Read a line from the buffer
        /// </summary>
        /// <returns>Line without line end</returns>
        public override string ReadLine()
        {
            if (this.mS == null)
                throw new ObjectDisposedException(null, "The Reader is Closed");
            int num = this.Position;
            while (num < this.Length) {
                char ch = this.mS[num];
                switch (ch) {
                    case '\r':
                    case '\n':
                    {
                        string str = this.mS.Substring(this.Position, num - this.Position);
                        this.Position = num + 1;
                        if (((ch == '\r') && (this.Position < this.Length)) &&
                            (this.mS[this.Position] == '\n'))
                            this.Position = this.Position + 1;
                        return str;
                    }
                }
                num++;
            }
            if (num > this.Position) {
                string str2 = this.mS.Substring(this.Position, num - this.Position);
                this.Position = num;
                return str2;
            }
            return null;
        }

        /// <summary>
        /// Read the buffer to the end
        /// </summary>
        /// <returns>String containing all remaining text</returns>
        public override string ReadToEnd()
        {
            string str;
            if (this.mS == null)
                throw new ObjectDisposedException(null, "The Reader is Closed");
            if (this.Position == 0)
                str = this.mS;
            else
                str = this.mS.Substring(this.Position, this.Length - this.Position);
            this.Position = this.Length;
            return str;
        }
    }
}


text:
package com.github.angelndevil2.loadt.listener;

import com.github.angelndevil2.loadt.common.ISample;

/**
 * @author k, Created on 16. 2. 15.
 */
public interface IResultViewer extends IResultListener {

    void view();

    /**
     *
     * @return save interval in millis
     */
    long getViewInterval();

    /**
     * check {@link com.github.angelndevil2.loadt.common.ViewOptions} and view or not
     *
     */
    void viewOrNot(final ISample sample);
}


text:
namespace Rs317.Sharp
{
	public sealed class Wall
	{
		public int z;

		public int x;
		public int y;
		public int orientation;
		public int orientation2;
		public Animable primary;
		public Animable secondary;
		public int uid;
		public byte objConf;

		public Wall()
		{
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing
		infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<context:annotation-config/>
	<context:component-scan base-package="gemlite.core.webapp,gemlite.shell" />
	<mvc:annotation-driven />
	<!-- Handles HTTP GET requests for /resources/** by efficiently serving
		up static resources in the ${webappRoot}/resources directory -->
	<mvc:resources mapping="/resources/**" location="/resources/" />
	<mvc:resources mapping="/js/**" location="/js/" />
	<mvc:resources mapping="/css/**" location="/css/" />
	<mvc:resources mapping="/assets/**" location="/assets/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources
		in the /WEB-INF/views directory -->

	<bean
		class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
		<property name="order" value="1" />
		<property name="viewResolvers">
			<list>
				<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
				<bean
					class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
					<property name="cache" value="true" />
					<property name="prefix" value="" />
					<property name="suffix" value=".xhtml" />
					<property name="contentType">
						<value>text/html;charset=UTF-8</value>
					</property>
					<property name="exposeSpringMacroHelpers" value="true"/>
					<property name="requestContextAttribute" value="rc"/>
					<property name="dateToolAttribute" value="dateTool"/>
                    <property name="numberToolAttribute" value="numberTool"/>
				</bean>
				<bean
					class="org.springframework.web.servlet.view.InternalResourceViewResolver">
					<property name="prefix" value="/" />
					<property name="suffix" value=".jsp" />
					<property name="viewClass"
						value="org.springframework.web.servlet.view.JstlView" />
				</bean>
			</list>
		</property>
		<property name="defaultViews">
			<list>
				<bean id="jsonView"
					class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
			</list>
		</property>
	</bean>

	<bean id="velocityConfigurer"
		class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
		<property name="resourceLoaderPath" value="/WEB-INF/templates/" />
		<property name="velocityProperties">
			<props>
				<prop key="input.encoding">utf-8</prop>
				<prop key="output.encoding">utf-8</prop>
			</props>
		</property>
	</bean>

	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="utf-8" />
		<property name="maxUploadSize" value="10000000" />
	</bean>
</beans>


text:
package ru.abelov.sql.io;

import org.quartz.Job;
import org.quartz.JobExecutionContext;

/**
 * Class ParsingVacanciesFromSqlRuJob.
 * Implementation of org.quartz.Job to start parsing vacancies from sql.ru.
 */
public class ParsingVacanciesFromSqlRuJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        InternetSiteTemplateObjectsCollector.parseVacanciesFromSqlRu();
    }
}


text:
<!-- Start actions/PlayerActionCreators.js -->

# [PlayerActionCreators.js](PlayerActionCreators.js)

## placed($el)

after the player is mounted into the DOM

### Params:

* **Object** *$el* jquery player element

## died($el)

after the player died

### Params:

* **Object** *$el* jquery player element

<!-- End actions/PlayerActionCreators.js -->


text:
var url = require('css-url-regex');
var map = require('map-obj');
var isColor = require('./is-color');
var isLength = require('./is-length');
var normalizeColor = require('./normalize-color');

var ATTACHMENT = /^(fixed|local|scroll)$/;
var BOX = /^(border-box|padding-box|content-box)$/;
var IMAGE = new RegExp('^(none|' + url().source + ')$', 'i');
var REPEAT_SINGLE = /^(repeat-x|repeat-y)$/i;
var REPEAT_DOUBLE = /^(repeat|space|round|no-repeat)$/i;
var POSITION_HORIZONTAL = /^(left|center|right)$/;
var POSITION_VERTICAL = /^(top|center|bottom)$/;
var SIZE_SINGLE = /^(cover|contain)$/;
var KEYWORD = /^(inherit|initial)$/i;

var normalizeUrl = function(value) {
	return value.replace(url(), function(match) {
		return match
			.replace(/^url\(\s+/, 'url(')
			.replace(/\s+\)$/, ')');
	});
};

module.exports = function(value) {
	var result = {};
	var values = normalizeUrl(normalizeColor(value))
		.replace(/\//, ' / ')
		.split(/\s+/);

	var first = values[0];

	if(values.length === 1 && KEYWORD.test(first)) {
		return {
			'background-attachment': first,
			'background-clip': first,
			'background-image': first,
			'background-repeat': first,
			'background-color': first,
			'background-position': first,
			'background-size': first
		};
	}

	for(var i = 0; i < values.length; i++) {
		var v = values[i];

		if(ATTACHMENT.test(v)) {
			if(result.attachment) return;
			result.attachment = v;
		} else if(BOX.test(v)) {
			if(result.clip) return;
			result.clip = v;
		} else if(IMAGE.test(v)) {
			if(result.image) return;
			result.image = v;
		} else if(REPEAT_SINGLE.test(v)) {
			if(result.repeat) return;
			result.repeat = v;
		} else if(REPEAT_DOUBLE.test(v)) {
			if(result.repeat) return;

			var n = values[i + 1];

			if(n && REPEAT_DOUBLE.test(n)) {
				v += ' ' + n;
				i++;
			}

			result.repeat = v;
		} else if(isColor(v)) {
			if(result.color) return;
			result.color = v;
		} else if(POSITION_HORIZONTAL.test(v) || POSITION_VERTICAL.test(v) || isLength(v)) {
			if(result.position) return;

			var n = values[i + 1];
			var isHorizontal = POSITION_HORIZONTAL.test(v) || isLength(v);
			var isVertical = POSITION_VERTICAL.test(n) || isLength(n);

			if(isHorizontal && isVertical) {
				result.position = v + ' ' + n;
				i++;
			} else {
				result.position = v;
			}

			v = values[i + 1];

			if(v === '/') {
				i += 2;
				v = values[i];

				if(SIZE_SINGLE.test(v)) {
					result.size = v;
				} else if(v === 'auto' || isLength(v)) {
					n = values[i + 1];

					if(n === 'auto' || isLength(n)) {
						v += ' ' + n;
						i++;
					}

					result.size = v;
				} else {
					return;
				}
			}
		} else {
			return;
		}
	}

	return map(result, function(key, value) {
		return ['background-' + key, value];
	});
};


text:
package tableview;

import java.util.ArrayList;
import java.util.List;

import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.foundation.NSData;
import org.robovm.apple.foundation.NSIndexPath;
import org.robovm.apple.foundation.NSURL;
import org.robovm.apple.uikit.NSIndexPathExtensions;
import org.robovm.apple.uikit.UIImage;
import org.robovm.apple.uikit.UIImageView;
import org.robovm.apple.uikit.UILabel;
import org.robovm.apple.uikit.UITableView;
import org.robovm.apple.uikit.UITableViewCell;
import org.robovm.apple.uikit.UITableViewController;
import org.robovm.objc.ObjCClass;
import org.robovm.rt.bro.annotation.MachineSizedFloat;

public class GenderListTableViewController extends UITableViewController {

	private static final String CELL_IDENTIFIER = "AddressbookCell";

	private List<String> gender;

	private List<String> getGender() {
		if (gender == null) {
			gender = new ArrayList<String>();
			gender.add("female");
			gender.add("male");
		}
		return gender;
	}

	public GenderListTableViewController() {
		super();
		this.setTitle("Address Book");
		//this.setEditing(true, true);
	}

	public @MachineSizedFloat double getRowHeight(UITableView tableView, NSIndexPath indexPath){
    	return 90;
    }

	@Override
	protected void dispose(boolean finalizing) {
		super.dispose(finalizing);
	}

	@Override
	public void viewDidLoad() {
		super.viewDidLoad();
		this.getTableView().registerReusableCellClass(ObjCClass.getByType(UITableViewCell.class), CELL_IDENTIFIER);
	}

	@Override
	public long getNumberOfRowsInSection(UITableView tableView, long section) {
		return getGender().size();
	}

	@Override
	public boolean canEditRow(UITableView tableView, NSIndexPath indexPath){
		//this.setEditing(true, true);
		//this.commitRowEditingStyle(tableView, UITableViewCellEditingStyle.Delete, indexPath);
		return Boolean.TRUE;
	}

	@Override
	public UITableViewCell getRowCell(UITableView tableView, NSIndexPath indexPath) {

		UITableViewCell cell = (UITableViewCell) tableView.dequeueReusableCell(CELL_IDENTIFIER);
		int row = (int) NSIndexPathExtensions.getRow(indexPath);

		String text = getGender().get(row);

		if (text.equals("male"))
        {
			NSURL url = new NSURL("http://icons.iconarchive.com/icons/iconshock/trendy-guys/64/andrew-icon.png");
			setContentOfCell(cell, text, url);
		}
		if (text.equals("female"))
        {
			NSURL url = new NSURL("http://icons.iconarchive.com/icons/iloveicons.ru/browser-girl/64/browser-girl-firefox-icon.png");
			setContentOfCell(cell, text, url);
		}
		return cell;
	}

	@Override
	public void didSelectRow(UITableView tableView, NSIndexPath indexPath) {
		int row = (int) NSIndexPathExtensions.getRow(indexPath);
        String text = getGender().get(row);

		if (text.equals("female"))
        {
			FemaleGenderTableViewController femaleGenderTableViewController = new FemaleGenderTableViewController();
			willSelectCell(femaleGenderTableViewController, "female") ;
		}
		if (text.equals("male"))
        {
			MaleGenderTableViewController maleGenderTableViewlController = new MaleGenderTableViewController();
			willSelectCell(maleGenderTableViewlController, "male") ;
        }
	}

	public void willSelectCell(UITableViewController controller, String detail) {
		getNavigationController().addStrongRef(controller);
		getNavigationController().setHidesBottomBarWhenPushed(false);
		getNavigationController().pushViewController(controller, true);
	}

	public void setContentOfCell(UITableViewCell cell, String txt, NSURL url) {
		UIImageView img = new UIImageView(new CGRect(25, 5, 80, 80));
    	NSData data = (NSData) NSData.read(url);
		img.setImage(new UIImage(data));
		cell.getContentView().addSubview(img);

		UILabel label = new UILabel(new CGRect(120, 30, cell.getContentView()
				.getFrame().getWidth(), 20));
		label.setText(txt);
		cell.getContentView().addSubview(label);
	}
}


text:
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 */
#include "tomcrypt_private.h"

/**
  @file crypt_hash_is_valid.c
  Determine if hash is valid, Tom St Denis
*/

/*
   Test if a hash index is valid
   @param idx   The index of the hash to search for
   @return CRYPT_OK if valid
*/
int hash_is_valid(int idx)
{
   LTC_MUTEX_LOCK(&ltc_hash_mutex);
   if (idx < 0 || idx >= TAB_SIZE || hash_descriptor[idx].name == NULL) {
      LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
      return CRYPT_INVALID_HASH;
   }
   LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
   return CRYPT_OK;
}

/* ref:         HEAD -> develop */
/* git commit:  9c0d7085234bd6baba2ab8fd9eee62254599341c */
/* commit time: 2018-10-15 10:51:17 +0200 */


text:
// Package randomforest defines the gradient boosted trees model.
package randomforest

import (
	"context"
	"fmt"
	"path/filepath"

	dataspec_pb "github.com/google/yggdrasil-decision-forests/yggdrasil_decision_forests/port/go/dataset/proto"
	model_pb "github.com/google/yggdrasil-decision-forests/yggdrasil_decision_forests/port/go/model/proto"
	rf_pb "github.com/google/yggdrasil-decision-forests/yggdrasil_decision_forests/port/go/model/randomforest/proto"
	dt "github.com/google/yggdrasil-decision-forests/yggdrasil_decision_forests/port/go/model/decisiontree"
	"github.com/google/yggdrasil-decision-forests/yggdrasil_decision_forests/port/go/model"

	// External dependencies, pls keep in this position in file.
	"google.golang.org/protobuf/proto"
	"github.com/google/yggdrasil-decision-forests/yggdrasil_decision_forests/port/go/utils/file"
	// End of external dependencies.//
	//
)

// ModelKey is the unique identifier of the model for serizalization.
const ModelKey = "RANDOM_FOREST"

// Filename containing the GBT header.
const headerFilename = "random_forest_header.pb"

// Model is a Gradient Boosted Trees model.
type Model struct {
	header   *model_pb.AbstractModel
	dataspec *dataspec_pb.DataSpecification
	RfHeader *rf_pb.Header
	Forest   *dt.Forest
}

func init() {
	// Register the constructor (loader) for GBTs.
	model.RegisteredBuilders[ModelKey] = Create
}

// Create creates a GBT model.
func Create(header *model_pb.AbstractModel, dataspec *dataspec_pb.DataSpecification) model.Implementation {
	return &Model{header: header, dataspec: dataspec, RfHeader: nil}
}

// Name of the model.
func (me *Model) Name() string {
	return ModelKey
}

// Header of the model.
func (me *Model) Header() *model_pb.AbstractModel {
	return me.header
}

// Dataspec of the model.
func (me *Model) Dataspec() *dataspec_pb.DataSpecification {
	return me.dataspec
}

// LoadSpecific loads a model from disk.
func (me *Model) LoadSpecific(modelPath string, prefix string) error {

	// Load the RF specialized header.
	serializedGbtHeader, err := file.ReadFile(context.Background(),
		filepath.Join(modelPath, prefix+headerFilename))
	if err != nil {
		return err
	}
	me.RfHeader = &rf_pb.Header{}
	if err := proto.Unmarshal(serializedGbtHeader, me.RfHeader); err != nil {
		return err
	}

	// Load the forest structure.
	me.Forest, err = dt.LoadForest(
		filepath.Join(modelPath, prefix+dt.DefaultNodeFilename),
		int(me.RfHeader.GetNumNodeShards()),
		me.RfHeader.GetNodeFormat(),
		int(me.RfHeader.GetNumTrees()))
	if err != nil {
		return err
	}

	if len(me.Forest.Trees) != int(me.RfHeader.GetNumTrees()) {
		return fmt.Errorf("Don't number of trees in the model")
	}
	return nil
}


text:
void print_description( char *description ) {
   if( description == NULL ) return;
   printf( "\tdescription: %s\n", description );
}

void print_inet_addr( struct sockaddr_in *inet_addr ) {

   char *ip = inet_ntoa( inet_addr->sin_addr );

   if( ip == NULL ) {
      perror( "inet_ntoa" );
      return;
   }

   printf( "\t%s", ip );
}

void print_inet6_addr( struct sockaddr_in6 *inet_addr ) {

   char *addr = (char *)&inet_addr->sin6_addr;
   char *ip = malloc( INET6_ADDRSTRLEN * sizeof(char) );

   if( ip == NULL ) {
      perror( "malloc" );
      return;
   }

   // this feels like a terrible hack
   ip = (char *)inet_ntop( AF_INET6, addr, ip, INET6_ADDRSTRLEN );

   if( ip == NULL ) {
      perror( "inet_ntop" );
      return;
   }

   printf( "\t%s", ip );
   free( ip );
}

void print_link_addr( struct sockaddr *addr ) {

   char *mac = ether_ntoa( (struct ether_addr *)addr );

   if( mac == NULL ) {
      perror( "ether_ntoa" );
      return;
   }

   printf( "\t%s", mac );
}

//void print_link_addr( void *link_addr ) {
//   printf( "\nMAC: unimplemented\n" );
//}

void print_current_address( struct sockaddr *address, char *label ) {

   if( address == NULL ) return;

   sa_family_t family = address->sa_family;

   switch( family ) {

   case AF_UNSPEC:
   case AF_INET:
      print_inet_addr( (struct sockaddr_in *)address );
      printf( "(IP %s)", label );
      break;

   case AF_INET6:
      print_inet6_addr( (struct sockaddr_in6 *)address );
      printf( "(IPv6 %s)", label );
      break;

   case AF_CUSTOM1:
      print_link_addr( address );
      printf( "(MAC %s)", label );
      break;

   default:
      printf( "\t(unrecognized address family %d)", family );
   }
}

void print_remaining_addresses( pcap_addr_t *address ) {

   if( address == NULL ) return;

   print_current_address( address->addr,      "unicast"     );
   print_current_address( address->broadaddr, "broadcast"   );
   print_current_address( address->netmask,   "netmask"     );
   print_current_address( address->dstaddr,   "destination" );
   printf( "\n" );
   print_remaining_addresses( address->next );
}

void print_flags( int flags ) {

   if( flags == 0 ) return;
   printf( "\tflags:" );
   if( flags & PCAP_IF_LOOPBACK ) printf( " LOOPBACK" );

// These are not defined until 1.6.0, and I'm using an old version
//   if( flags & PCAP_IF_UP )       printf( " UP" );
//   if( flags & PCAP_IF_RUNNING )  printf( " RUNNING" );

   printf( "\n" );
}

void print_remaining_devices( pcap_if_t *dev_p ) {

   if( dev_p == NULL ) return;

   printf( "name: %s\n", dev_p->name );

   print_description(         dev_p->description );
   print_remaining_addresses( dev_p->addresses   );
   print_flags(               dev_p->flags       );
   print_remaining_devices(   dev_p->next        );
}

int main( int argc, char **argv ) {

   char errbuf[PCAP_ERRBUF_SIZE];

   pcap_if_t *dev_p;

   int ret = pcap_findalldevs( &dev_p, errbuf );

   if( ret == -1 || ret != 0 ) {
      printf( "ERROR: %s - aborting\n", errbuf );
      exit( EXIT_FAILURE );
   }

   print_remaining_devices( dev_p );

   pcap_freealldevs( dev_p );

   exit( EXIT_SUCCESS );
}


text:
require File.expand_path('../../../../spec_helper', __FILE__)
require File.expand_path('../../fixtures/common', __FILE__)

describe "Logger#info?" do
  before :each do
    @path = tmp("test_log.log")
    @log_file = File.open(@path, "w+")
    @logger = Logger.new(@path)
  end

  after :each do
    @logger.close
    @log_file.close unless @log_file.closed?
    rm_r @path
  end

  it "returns true if severity level allows info messages" do
    @logger.level = Logger::INFO
    @logger.info?.should == true
  end

  it "returns false if severity level does not allow info messages" do
    @logger.level = Logger::FATAL
    @logger.info?.should == false
  end
end

describe "Logger#info" do
  before :each do
    @path = tmp("test_log.log")
    @log_file = File.open(@path, "w+")
    @logger = Logger.new(@path)
  end

  after :each do
    @logger.close
    @log_file.close unless @log_file.closed?
    rm_r @path
  end

  it "logs a INFO message" do
    @logger.info("test")
    @log_file.rewind
    LoggerSpecs.strip_date(@log_file.readlines.first).should == "INFO -- : test\n"
  end

  it "accepts an application name with a block" do
    @logger.info("MyApp") { "Test message" }
    @log_file.rewind
    LoggerSpecs.strip_date(@log_file.readlines.first).should == "INFO -- MyApp: Test message\n"
  end

end


text:
module Virtus

  # Include this Module for Value Object semantics
  #
  # The idea is that instances should be immutable and compared based on state
  #   (rather than identity, as is typically the case)
  #
  # @example
  #   class GeoLocation
  #     include Virtus::ValueObject
  #     attribute :latitude,  Float
  #     attribute :longitude, Float
  #   end
  #
  #   location = GeoLocation.new(:latitude => 10, :longitude => 100)
  #   same_location = GeoLocation.new(:latitude => 10, :longitude => 100)
  #   location == same_location       #=> true
  #   hash = { location => :foo }
  #   hash[same_location]             #=> :foo
  module ValueObject

    # Callback to configure including Class as a Value Object
    #
    # Including Class will include Virtus and have additional
    #   value object semantics defined in this module
    #
    # @return [Undefined]
    #
    # TODO: stacking modules is getting painful
    #   time for Facets' module_inheritance, ActiveSupport::Concern or the like
    #
    # @api private
    def self.included(base)
      Virtus.warn "Virtus::ValueObject is deprecated and will be removed in 1.0.0 #{caller.first}"

      base.instance_eval do
        include Virtus
        include InstanceMethods
        extend ClassMethods
        extend AllowedWriterMethods
        private :attributes=
      end
    end

    private_class_method :included

    module InstanceMethods

      # ValueObjects are immutable and can't be cloned
      #
      # They always represent the same value
      #
      # @example
      #
      #   value_object.clone === value_object # => true
      #
      # @return [self]
      #
      # @api public
      def clone
        self
      end
      alias dup clone

      # Create a new ValueObject by combining the passed attribute hash with
      # the instances attributes.
      #
      # @example
      #
      #   number = PhoneNumber.new(kind: "mobile", number: "123-456-78-90")
      #   number.with(number: "987-654-32-10")
      #   # => #<PhoneNumber kind="mobile" number="987-654-32-10">
      #
      # @return [Object]
      #
      # @api public
      def with(attribute_updates)
        self.class.new(attribute_set.get(self).merge(attribute_updates))
      end

    end

    module AllowedWriterMethods
      # The list of writer methods that can be mass-assigned to in #attributes=
      #
      # @return [Set]
      #
      # @api private
      def allowed_writer_methods
        @allowed_writer_methods ||=
          begin
            allowed_writer_methods = super
            allowed_writer_methods += attribute_set.map{|attr| "#{attr.name}="}
            allowed_writer_methods.to_set.freeze
          end
      end
    end

    module ClassMethods

      # Define an attribute on the receiver
      #
      # The Attribute will have private writer methods (eg., immutable instances)
      #   and be used in equality/equivalence comparisons
      #
      # @example
      #   class GeoLocation
      #     include Virtus::ValueObject
      #
      #     attribute :latitude,  Float
      #     attribute :longitude, Float
      #   end
      #
      # @see Virtus::ClassMethods.attribute
      #
      # @return [self]
      #
      # @api public
      def attribute(name, type, options = {})
        equalizer << name
        super name, type, options.merge(:writer => :private)
      end

      # Define and include a module that provides Value Object semantics
      #
      # Included module will have #inspect, #eql?, #== and #hash
      # methods whose definition is based on the _keys_ argument
      #
      # @example
      #   virtus_class.equalizer
      #
      # @return [Equalizer]
      #   An Equalizer module which defines #inspect, #eql?, #== and #hash
      #   for instances of this class
      #
      # @api public
      def equalizer
        @equalizer ||=
          begin
            equalizer = Virtus::Equalizer.new(name || inspect)
            include equalizer
            equalizer
          end
      end

    end # module ClassMethods

  end # module ValueObject

end # module Virtus


text:
Package.describe({
  name: "override-constraints",
  version: "1.5.3",
  summary: "Test package for @x.y.z! style package version constraints",
  documentation: null,
});

Package.onUse(function(api) {
  api.use("ecmascript");
  api.mainModule("override-constraints.js");
});


text:
package ox.softeng.projector.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Projections {
	Projection[] value();
}


text:
'use strict';

var randomBytes = require('mz/crypto').randomBytes;

module.exports = function trace (app, options) {
  /* istanbul ignore next */
  options = options || {};

  require('koa-trace')(app);

  /* istanbul ignore else */
  if (app.env !== 'production') {
    app.debug();
  }

  return function * (next) {
    this.id = yield randomBytes(10);

    var that = this;
    var req = this.req;
    var res = this.res;

    // request start
    this.trace('time.start');

    // request end
    req.once('end', this.trace.bind(this, 'time.end'));

    // response headers
    var writeHead = res.writeHead;
    res.writeHead = function () {
      that.trace('time.headers');
      return writeHead.apply(this, arguments);
    };

    // response finish
    res.once('finish', this.trace.bind(this, 'time.finish'));

    yield* next;
  };
};


text:
layout: post
title: MozJPEG Fuzzing
published: true
---

This blog post details the steps I took to set up AFL fuzzer to target [MozJPEG](https://github.com/mozilla/mozjpeg). I did this using the base image that was set up in the post on [fuzzing XPDF](/xpdf-fuzzing/). This post is written to document how to fuzz something like an image parser.

## Install prerequisites

These are required in addition to anything inherited from the previous blog post.

    sudo apt-get install nasm autoreconf libtool

## Prepare MozJPEG

    cd ~/Downloads
    wget "https://github.com/mozilla/mozjpeg/releases/download/v3.1/mozjpeg-3.1-release-source.tar.gz"
    tar -xf mozjpeg-3.1-release-source.tar.gz
    cd mozjpeg
    # Running `autoreconf` is required to avoid some errors.
    autoreconf -f -i
    # Instrument MozJPEG using AFL
    CC=~/bin/afl/afl-gcc ./configure --disable-shared
    make clean all AFL_HARDEN=1

## Prepare ramdisk

This code is used to set up a ramdisk, which should hopefully speed up reads and writes.

    cat << EOF > ~/bin/set-up-ramdisk.sh
    #!/bin/bash
    if grep -qs '/tmp/afl-ramdisk' /proc/mounts; then
        sudo umount /tmp/afl-ramdisk
        rm -rf /tmp/afl-ramdisk
    fi
    sudo mkdir /tmp/afl-ramdisk && sudo chmod 777 /tmp/afl-ramdisk
    sudo mount -t tmpfs -o size=1G tmpfs /tmp/afl-ramdisk
    cp -R ~/Downloads/mozjpeg /tmp/afl-ramdisk
    cp -R ~/bin/afl /tmp/afl-ramdisk
    cp -R ~/bin/afl/testcases/images/jpeg/ /tmp/afl-ramdisk/samples
    EOF
    chmod +x ~/bin/set-up-ramdisk.sh
    sudo -E env "PATH=$PATH" set-up-ramdisk.sh

## Prepare AFL

This is required in order to run AFL.

    sudo su
    echo core >/proc/sys/kernel/core_pattern
    exit

## Start fuzzing

Kick off the fuzzer.

    cd /tmp/afl-ramdisk
    export PATH="$PATH:/tmp/afl-ramdisk/afl"
    sudo chown $(whoami):$(whoami) -R afl/ samples/ mozjpeg/
    mkdir cjpeg_out
    afl-launch -m="2G" -i samples -o afl_out -n 4 mozjpeg/cjpeg -quality 70 \
        -outfile cjpeg_out/afl-image.jpg @@

For some options, check out [this post](http://calendar.perfplanet.com/2014/mozjpeg-3-0/). Of note, some options that are available are:

- The `-quality` option accepts fractional numbers (necessary if you want to make a fair benchmark) and two numbers separated by commas to set quality of brightness and color separately, e.g. -quality 60,70.
- `-sample 1x1` enables full-resolution color (e.g. red lines won't be smudged as badly), but it makes files larger.
- `-quant-table 2` (mentioned earlier) makes images softer and reduces posterization in low qualities.
- `-notrellis` makes images sharper, but increases file size.
- `-outfile` defines path where result is (over)written to.
And the last argument is the source image. It can be a PNG, a very high-quality JPEG or Targa.

The status of the fuzzer can be checked with `afl-whatsup`:

    watch afl-whatsup -s pdf-out

Performance is decent, hovering around 1500 execs/second:

![ramdisk-performance](https://s3-us-west-1.amazonaws.com/blog.carterjones.info/mozjpeg-fuzzing/ramdisk-performance.PNG)


text:
package net.minidev.ovh.api.cloud.stack;

/**
 * Stack
 */
public class OvhStack {
	/**
	 * Instructions to start the stack
	 *
	 * canBeNull && readOnly
	 */
	public OvhInstructionGuide[] instructions;

	/**
	 * GIT repository
	 *
	 * canBeNull && readOnly
	 */
	public String gitRepository;

	/**
	 * Stack release tag
	 *
	 * canBeNull && readOnly
	 */
	public String release;

	/**
	 * Stack last commit
	 *
	 * canBeNull && readOnly
	 */
	public String commit;

	/**
	 * Stack name
	 *
	 * canBeNull && readOnly
	 */
	public String name;

	/**
	 * Stack description
	 *
	 * canBeNull && readOnly
	 */
	public String description;

	/**
	 * Stack uuid
	 *
	 * canBeNull && readOnly
	 */
	public String uuid;
}


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>com.github.shynixn.astraledit.business.metrics (AstralEdit 1.1.0 API)</title>
<meta name="date" content="2017-10-07">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

com.github.shynixn.astraledit.business.metrics

Classes

Metrics

Metrics.AdvancedBarChart

Metrics.AdvancedPie

Metrics.CustomChart

Metrics.DrilldownPie

Metrics.MultiLineChart

Metrics.SimpleBarChart

Metrics.SimplePie

Metrics.SingleLineChart