text:
/*!
 * Copyright (c) 2015 by Contributors
 * \file mshadow_op.h
 * \brief
 * \author Bing Xu
*/
#ifndef MXNET_OPERATOR_MSHADOW_OP_H_
#define MXNET_OPERATOR_MSHADOW_OP_H_

#include <mxnet/base.h>
#include "math.h"
#include "math_functions-inl.h"
#include "special_functions-inl.h"
#include "./mxnet_op.h"

#ifdef __CUDACC__
#include <cuda_fp16.h>
#endif

namespace mxnet {
namespace op {
namespace mshadow_op {

/*!
 * \brief Use the 'MXNET_TUNABLE_MSHADOW_OP_FWD_AND_BWD' macro outside of the mshadow_op namespace
 *        See mxnet_op.h for a description of 'MXNET_TUNABLE_MSHADOW_OP_FWD_AND_BWD'
 *
 * \note An entry for the operator must also be added in operator_tune.cc, which will register it
 *       for auto-tuning and also hold its workload weight
 */
#define MSHADOW_OP_DECLARE_TUNABLE_FWD_AND_BWD(__op$) \
  } MXNET_TUNABLE_MSHADOW_OP_FWD_AND_BWD(mshadow_op::__op$) namespace mshadow_op {  // NOLINT(*)
/*!
 * \brief Use the 'MXNET_TUNABLE_MSHADOW_OP_BACKWARD' macro outside of the mshadow_op namespace
 *        See mxnet_op.h for a description of 'MXNET_TUNABLE_MSHADOW_OP_BACKWARD'
 *
 * \note An entry for the operator must also be added in operator_tune.cc, which will register it
 *       for auto-tuning and also hold its workload weight
 */
#define MSHADOW_OP_DECLARE_TUNABLE_BACKWARD(__op$) \
  }  MXNET_TUNABLE_MSHADOW_OP_BACKWARD(mshadow_op::__op$) namespace mshadow_op {  // NOLINT(*)
#ifdef __CUDA_ARCH__
__constant__ const float PI = 3.14159265358979323846;
#else
const float PI = 3.14159265358979323846;
using std::isnan;
#endif
using std::enable_if;
using std::is_unsigned;

#define MXNET_UNARY_MATH_OP(name, expr) \
  struct name { \
    template<typename DType> \
    MSHADOW_XINLINE static DType Map(DType a) { \
      return DType(expr); \
    } \
  }; \
  MSHADOW_OP_DECLARE_TUNABLE_FWD_AND_BWD(name)

#define MXNET_UNARY_MATH_OP_NC(name, expr) \
  struct name { \
    template<typename DType> \
    MSHADOW_XINLINE static DType Map(DType a) { \
      return (expr); \
    } \
  }; \
  MSHADOW_OP_DECLARE_TUNABLE_FWD_AND_BWD(name)

#define MXNET_BINARY_MATH_OP(name, expr) \
  struct name { \
    template<typename DType> \
    MSHADOW_XINLINE static DType Map(DType a, DType b) { \
      return DType(expr); \
    } \
  }; \
  MSHADOW_OP_DECLARE_TUNABLE_FWD_AND_BWD(name)

#define MXNET_BINARY_MATH_OP_NC(name, expr) \
  struct name { \
    template<typename DType> \
    MSHADOW_XINLINE static DType Map(DType a, DType b) { \
      return (expr); \
    } \
  }; \
  MSHADOW_OP_DECLARE_TUNABLE_FWD_AND_BWD(name)

#define MXNET_SIMPLE_UNARY_MATH_OP(name) MXNET_UNARY_MATH_OP(name, math::name(a))

#define MXNET_SIMPLE_BINARY_MATH_OP(name) MXNET_BINARY_MATH_OP(name, math::name(a, b))

MXNET_UNARY_MATH_OP_NC(identity, a);

MXNET_UNARY_MATH_OP(identity_grad, 1);

MXNET_BINARY_MATH_OP_NC(left, a);

MXNET_BINARY_MATH_OP_NC(right, b);

MXNET_UNARY_MATH_OP(negation, -a);

MXNET_UNARY_MATH_OP(reciprocal, 1.0f / math::id(a));

MXNET_UNARY_MATH_OP(reciprocal_grad, -1.0f / math::sqr(a));

MXNET_UNARY_MATH_OP(sigmoid, 1.0f / (1.0f + math::exp(-a)));

MXNET_UNARY_MATH_OP(sigmoid_grad, math::id(a) * (1.0f - math::id(a)));

MXNET_UNARY_MATH_OP_NC(relu, a > DType(0) ? a : DType(0));

MXNET_UNARY_MATH_OP_NC(relu_grad, a > DType(0) ? DType(1) : DType(0));

MXNET_BINARY_MATH_OP(xelu, a > DType(0) ? math::id(a) :
                     math::id(a) * math::id(b));

MXNET_BINARY_MATH_OP_NC(xelu_grad, a > DType(0) ? DType(1) : b);

MXNET_BINARY_MATH_OP(elu, a > DType(0) ? math::id(a) :
                     math::id(b) * math::expm1(a));

MXNET_BINARY_MATH_OP_NC(elu_grad, a > DType(0) ? DType(1) : DType(b + a));

MXNET_SIMPLE_UNARY_MATH_OP(tanh);

MXNET_UNARY_MATH_OP(tanh_grad, 1.0f - math::sqr(a));

/*! \brief SoftReLU, also known as softplus activation */
struct softrelu {
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a) {
    // Avoid overflow of exp for large inputs.
    // Thresholds 20.0 is chosen such that softrelu(a) = a
    // for a > 20 using floating precision
    if (a > DType(20.0f)) {
      return a;
    } else {
      return DType(math::log1p(math::exp(a)));
    }
  }
};
MSHADOW_OP_DECLARE_TUNABLE_FWD_AND_BWD(softrelu)

MXNET_UNARY_MATH_OP(softrelu_grad, -math::expm1(-a));

MXNET_SIMPLE_UNARY_MATH_OP(exp);

MXNET_SIMPLE_UNARY_MATH_OP(expm1);

MXNET_SIMPLE_UNARY_MATH_OP(log);

MXNET_UNARY_MATH_OP(log_grad, 1.0f / math::id(a));

MXNET_SIMPLE_UNARY_MATH_OP(log10);

// Constant is 1 / log(10)
struct log10_grad {
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a) {
    return DType(0.4342944819f / static_cast<float>(a));
  }
};
MSHADOW_OP_DECLARE_TUNABLE_BACKWARD(log10_grad)

template<>
MSHADOW_XINLINE double log10_grad::Map<double>(double a) {
  return 0.43429448190325182765 / a;
}

MXNET_SIMPLE_UNARY_MATH_OP(log2);

// Constant is 1 / log(2)
struct log2_grad {
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a) {
    return DType(1.442695041f / static_cast<float>(a));
  }
};
MSHADOW_OP_DECLARE_TUNABLE_BACKWARD(log2_grad)

template<>
MSHADOW_XINLINE double log2_grad::Map<double>(double a) {
  return 1.44269504088896340737 / a;
}

MXNET_SIMPLE_UNARY_MATH_OP(sin);

MXNET_UNARY_MATH_OP(sin_grad, math::cos(a));

MXNET_SIMPLE_UNARY_MATH_OP(log1p);

MXNET_UNARY_MATH_OP(log1p_grad, 1.0f / (1.0f + math::id(a)));

MXNET_SIMPLE_UNARY_MATH_OP(cos);

MXNET_UNARY_MATH_OP(cos_grad, -math::sin(a));

MXNET_SIMPLE_UNARY_MATH_OP(tan);

MXNET_UNARY_MATH_OP(tan_grad, math::sqr(a) + 1.0f);

MXNET_UNARY_MATH_OP(arcsin, math::asin(a));

MXNET_UNARY_MATH_OP(arcsin_grad, 1.0f / math::sqrt(1.0f - math::sqr(a)));

MXNET_UNARY_MATH_OP(arccos, math::acos(a));

MXNET_UNARY_MATH_OP(arccos_grad, -1.0f / math::sqrt(1.0f - math::sqr(a)));

MXNET_UNARY_MATH_OP(arctan, math::atan(a));

MXNET_UNARY_MATH_OP(arctan_grad, 1.0f / (math::sqr(a) + 1.0f));

MXNET_SIMPLE_BINARY_MATH_OP(hypot);

MXNET_BINARY_MATH_OP(hypot_grad_left, math::id(a) / math::hypot(a, b));

MXNET_BINARY_MATH_OP(hypot_grad_right, math::id(b) / math::hypot(a, b));

MXNET_UNARY_MATH_OP(degrees, 180.0f / PI * math::id(a));

MXNET_UNARY_MATH_OP(degrees_grad, 180.0f / PI);

MXNET_UNARY_MATH_OP(radians, PI / 180.0f * math::id(a));

MXNET_UNARY_MATH_OP(radians_grad, PI / 180.0f);

MXNET_SIMPLE_UNARY_MATH_OP(sinh);

MXNET_UNARY_MATH_OP(sinh_grad, math::cosh(a));

MXNET_SIMPLE_UNARY_MATH_OP(cosh);

MXNET_UNARY_MATH_OP(cosh_grad, math::sinh(a));

MXNET_UNARY_MATH_OP(arcsinh, math::asinh(a));

MXNET_UNARY_MATH_OP(arcsinh_grad, 1.0f / math::hypot(a, DType(1)));

MXNET_UNARY_MATH_OP(arccosh, math::acosh(a));

MXNET_UNARY_MATH_OP(arccosh_grad, 1.0f / math::sqrt(math::sqr(a) - 1.0f));

MXNET_UNARY_MATH_OP(arctanh, math::atanh(a));

MXNET_UNARY_MATH_OP(arctanh_grad, 1.0f / (1.0f - math::sqr(a)));

MXNET_UNARY_MATH_OP(square, math::sqr(a));

MXNET_UNARY_MATH_OP(square_grad, 2.0f * math::id(a));

/*! \brief used for generate Bernoulli mask */
MXNET_BINARY_MATH_OP_NC(threshold, a < b ? DType(1) : DType(0));

/*! \brief used for generate element of abs */
MXNET_UNARY_MATH_OP(abs, math::fabs(a)); // NOLINT(*)

/*! \brief used for generate element of sign */
struct sign {
  template<typename DType>
  MSHADOW_XINLINE static typename enable_if<!is_unsigned<DType>::value, DType>::type
  Map(DType a) {
    if (a < DType(0)) return DType(-DType(1));
    if (a > DType(0)) return DType(1);
    return DType(0);
  }
  template<typename DType>
  MSHADOW_XINLINE static typename enable_if<is_unsigned<DType>::value, DType>::type
  Map(DType a) {
    if (a > DType(0)) return DType(1);
    return DType(0);
  }
};
MSHADOW_OP_DECLARE_TUNABLE_FWD_AND_BWD(sign)

MXNET_UNARY_MATH_OP_NC(sign_grad, DType(0));

/*! \brief used for generate element of power */
MXNET_BINARY_MATH_OP(power, math::pow(a, b));

MXNET_BINARY_MATH_OP(power_grad, math::pow(a, b - DType(1)) * math::id(b));

MXNET_BINARY_MATH_OP(power_rgrad, math::pow(a, b) * math::log(a));

MXNET_BINARY_MATH_OP(rpower, math::pow(b, a));

MXNET_BINARY_MATH_OP(rpower_grad, math::id(a) * math::log(b));

/*! \brief used for generate element of maximum */
MXNET_BINARY_MATH_OP(maximum, a > b ? a : b);

/*! \brief used for generate element of minimum */
MXNET_BINARY_MATH_OP_NC(minimum, a < b ? a : b);

MXNET_BINARY_MATH_OP_NC(ge, a >= b ? DType(1) : DType(0));

MXNET_BINARY_MATH_OP_NC(gt, a > b ? DType(1) : DType(0));

MXNET_BINARY_MATH_OP_NC(lt, a < b ? DType(1) : DType(0));

MXNET_BINARY_MATH_OP_NC(le, a <= b ? DType(1) : DType(0));

MXNET_BINARY_MATH_OP_NC(eq, a == b ? DType(1) : DType(0));

MXNET_BINARY_MATH_OP_NC(ne, a != b ? DType(1) : DType(0));

MXNET_UNARY_MATH_OP(square_root, math::sqrt(a));

MXNET_UNARY_MATH_OP(square_root_grad, 0.5f / math::id(a));

MXNET_UNARY_MATH_OP(reciprocal_square_root, 1.0f / math::sqrt(a));

MXNET_UNARY_MATH_OP(reciprocal_square_root_grad, -0.5f / (math::sqrt(a) * math::id(a)));

MXNET_UNARY_MATH_OP(cube_root, math::cbrt(a));

MXNET_UNARY_MATH_OP(cube_root_grad, 1.0f / (3.0f * math::sqr(a)));

MXNET_UNARY_MATH_OP(reciprocal_cube_root, 1.0f / math::cbrt(a));

MXNET_UNARY_MATH_OP(reciprocal_cube_root_grad, -1.0f / (3.0f * math::cbrt(a) * math::id(a)));

/*! \brief used for generate element of round */
MXNET_SIMPLE_UNARY_MATH_OP(round);

/*! \brief used for generate element of ceil */
MXNET_SIMPLE_UNARY_MATH_OP(ceil);

/*! \brief used for generate element of floor */
MXNET_SIMPLE_UNARY_MATH_OP(floor);

/*! \brief used to round towards zero */
MXNET_SIMPLE_UNARY_MATH_OP(trunc);

/*! \brief used to round number to nearest integer */
struct rint {
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a) {
    auto floor = math::floor(a);
    auto ceil = math::ceil(a);
    auto af = math::id(a);
    return DType((af - floor) <= (ceil - af) ? floor : ceil);
  }
};
MSHADOW_OP_DECLARE_TUNABLE_FWD_AND_BWD(rint)

/*! \brief used to round number to integer nearest to 0 */
struct fix {
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a) {
    auto floor = math::floor(a);
    auto ceil = math::ceil(a);
    return DType((floor > 0 ? floor : -floor) < (ceil > 0 ? ceil : -ceil) ? floor : ceil);
  }
};
MSHADOW_OP_DECLARE_TUNABLE_FWD_AND_BWD(fix)

/*! \brief used for generate gradient of MAE loss*/
MXNET_BINARY_MATH_OP_NC(minus_sign, a - b > DType(0) ? DType(1) : -DType(1));

MXNET_BINARY_MATH_OP(rminus, b - a);

MXNET_BINARY_MATH_OP(div_grad, 1.0f / math::id(b));

template<>
MSHADOW_XINLINE mshadow::half::half2_t div_grad::Map<mshadow::half::half2_t>
                                               (mshadow::half::half2_t a,
                                                mshadow::half::half2_t b) {
  return mshadow::half::half2_t(1) / b;
}

MXNET_BINARY_MATH_OP(div_rgrad, -math::id(a) / math::sqr(b));

template<>
MSHADOW_XINLINE mshadow::half::half2_t div_rgrad::Map<mshadow::half::half2_t>
                                               (mshadow::half::half2_t a,
                                                mshadow::half::half2_t b) {
  return -a / (b * b);
}

MXNET_BINARY_MATH_OP(rdiv, math::id(b) / math::id(a));

MXNET_BINARY_MATH_OP(rdiv_grad, -math::id(b) / math::sqr(a));

struct mod {
  template<typename DType>
  MSHADOW_XINLINE static typename enable_if<!is_unsigned<DType>::value, DType>::type
  Map(DType a, DType b) {
    if (b == DType(0)) {
      return DType(0);
    } else if (b < DType(0)) {
      if (a < DType(0)) {
        return DType(-::fmod(-static_cast<double>(a), -static_cast<double>(b)));
      } else {
        return DType(::fmod(static_cast<double>(a), -static_cast<double>(b)) +
                     (::fmod(static_cast<double>(a), -static_cast<double>(b)) != DType(0)
                      ? b : DType(0)));
      }
    } else {
      if (a < DType(0)) {
        return DType(-::fmod(-static_cast<double>(a), static_cast<double>(b)) +
                     (::fmod(-static_cast<double>(a), static_cast<double>(b)) != DType(0)
                      ? b : DType(0)));
      } else {
        return DType(::fmod(static_cast<double>(a), static_cast<double>(b)));
      }
    }
  }
  template<typename DType>
  MSHADOW_XINLINE static typename enable_if<is_unsigned<DType>::value, DType>::type
  Map(DType a, DType b) {
    if (b == DType(0)) {
      return DType(0);
    } else {
      return DType(::fmod(static_cast<double>(a), static_cast<double>(b)));
    }
  }
};
MSHADOW_OP_DECLARE_TUNABLE_FWD_AND_BWD(mod)

template<>
MSHADOW_XINLINE mshadow::half::half2_t mod::Map<mshadow::half::half2_t>
                                               (mshadow::half::half2_t a,
                                                mshadow::half::half2_t b) {
  return a%b;
}

struct mod_grad {
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a, DType b) {
    return DType(0);
  }
};
MSHADOW_OP_DECLARE_TUNABLE_BACKWARD(mod_grad)

template<>
MSHADOW_XINLINE double mod_grad::Map<double>(double a, double b) {
  return 1.0;
}
template<>
MSHADOW_XINLINE float mod_grad::Map<float>(float a, float b) {
  return 1.0f;
}

template<>
MSHADOW_XINLINE mshadow::half::half_t mod_grad::Map<mshadow::half::half_t>
                                                   (mshadow::half::half_t a,
                                                    mshadow::half::half_t b) {
  return mshadow::half::half_t(1.0f);
}
template<>
MSHADOW_XINLINE mshadow::half::half2_t mod_grad::Map<mshadow::half::half2_t>
                                                    (mshadow::half::half2_t a,
                                                     mshadow::half::half2_t b) {
  mshadow::half::half2_t result = mshadow::half::half2_t();
#if (defined(__CUDACC__) && MSHADOW_CUDA_HALF2)
  result.half2_ = ::__float2half2_rn(1.0f);
#else
  result.half_t2[0] = mshadow::half::half_t(0.0f);
  result.half_t2[1] = mshadow::half::half_t(1.0f);
#endif
  return result;
}

struct mod_rgrad {
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a, DType b) {
    return DType(0);
  }
};
MSHADOW_OP_DECLARE_TUNABLE_BACKWARD(mod_rgrad)

template<>
MSHADOW_XINLINE double mod_rgrad::Map<double>(double a, double b) {
  return -::floor(a/b);
}
template<>
MSHADOW_XINLINE float mod_rgrad::Map<float>(float a, float b) {
  return -::floorf(a/b);
}

template<>
MSHADOW_XINLINE mshadow::half::half_t mod_rgrad::Map<mshadow::half::half_t>
                                                    (mshadow::half::half_t a,
                                                     mshadow::half::half_t b) {
  return mshadow::half::half_t(-::floorf(static_cast<float>(a/b)));
}
template<>
MSHADOW_XINLINE mshadow::half::half2_t mod_rgrad::Map<mshadow::half::half2_t>
                                                     (mshadow::half::half2_t a,
                                                      mshadow::half::half2_t b) {
#if (defined(__CUDACC__) && MSHADOW_CUDA_HALF2)
  return mshadow::half::half2_t(__hneg2(::h2floor((a/b).half2_)));
#else
  return mshadow::half::half2_t(mshadow::half::half_t(-::floorf(
                                  static_cast<float>(a.half_t2[0]/b.half_t2[0]))),
                                mshadow::half::half_t(-::floorf(
                                  static_cast<float>(a.half_t2[1]/b.half_t2[1]))));
#endif
}

struct rmod {
  template<typename DType>
  MSHADOW_XINLINE static typename enable_if<!is_unsigned<DType>::value, DType>::type
  Map(DType a, DType b) {
    if (a == DType(0)) {
      return DType(0);
    } else if (a < DType(0)) {
      if (b < DType(0)) {
        return DType(-::fmod(-static_cast<double>(b), -static_cast<double>(a)));
      } else {
        return DType(::fmod(static_cast<double>(b), -static_cast<double>(a)) +
                     (::fmod(static_cast<double>(b), -static_cast<double>(a)) != DType(0)
                      ? a : DType(0)));
      }
    } else {
      if (b < DType(0)) {
        return DType(-::fmod(-static_cast<double>(b), static_cast<double>(a)) +
                     (::fmod(-static_cast<double>(b), static_cast<double>(a)) != DType(0)
                      ? a : DType(0)));
      } else {
        return DType(::fmod(static_cast<double>(b), static_cast<double>(a)));
      }
    }
  }
  template<typename DType>
  MSHADOW_XINLINE static typename enable_if<is_unsigned<DType>::value, DType>::type
  Map(DType a, DType b) {
    if (a == DType(0)) {
      return DType(0);
    } else {
      return DType(::fmod(static_cast<double>(b), static_cast<double>(a)));
    }
  }
};
MSHADOW_OP_DECLARE_TUNABLE_FWD_AND_BWD(rmod)

template<>
MSHADOW_XINLINE mshadow::half::half2_t rmod::Map<mshadow::half::half2_t>
                                                (mshadow::half::half2_t a,
                                                 mshadow::half::half2_t b) {
  return b%a;
}

struct rmod_grad {
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a, DType b) {
    return DType(0);
  }
};
MSHADOW_OP_DECLARE_TUNABLE_BACKWARD(rmod_grad)

template<>
MSHADOW_XINLINE double rmod_grad::Map<double>(double a, double b) {
  return -::floor(b/a);
}
template<>
MSHADOW_XINLINE float rmod_grad::Map<float>(float a, float b) {
  return -::floorf(b/a);
}

template<>
MSHADOW_XINLINE mshadow::half::half_t rmod_grad::Map<mshadow::half::half_t>
                                                   (mshadow::half::half_t a,
                                                    mshadow::half::half_t b) {
  return mshadow::half::half_t(-::floorf(static_cast<float>(b/a)));
}
template<>
MSHADOW_XINLINE mshadow::half::half2_t rmod_grad::Map<mshadow::half::half2_t>
                                                     (mshadow::half::half2_t a,
                                                      mshadow::half::half2_t b) {
#if (defined(__CUDACC__) && MSHADOW_CUDA_HALF2)
  return mshadow::half::half2_t(::__hneg2(::h2floor((b/a).half2_)));
#else
  return mshadow::half::half2_t(mshadow::half::half_t(-::floorf(
                                  static_cast<float>(b.half_t2[0]/a.half_t2[0]))),
                                mshadow::half::half_t(-::floorf(
                                  static_cast<float>(b.half_t2[1]/a.half_t2[1]))));
#endif
}

struct clip {
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType x, DType bound) {
    if (x > bound) {
      return bound;
    } else if (x < -bound) {
      return -bound;
    } else {
      return x;
    }
  }
};
MSHADOW_OP_DECLARE_TUNABLE_FWD_AND_BWD(clip)

/***** gamma ******/

MXNET_UNARY_MATH_OP(gamma, math::tgamma(a));

struct gamma_grad {
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a) {
    // default implementation using floating precision
    float af(static_cast<float>(a));
    return DType(math::tgamma(af) * special_functions::cephes::psi<float>(af));
  }
};
MSHADOW_OP_DECLARE_TUNABLE_BACKWARD(gamma_grad)

template<>
MSHADOW_XINLINE double gamma_grad::Map<double>(double a) {
  return math::tgamma(a) * special_functions::cephes::psi<double>(a);
}

/***** gammaln ******/

MXNET_UNARY_MATH_OP(gammaln, math::lgamma(a));

struct gammaln_grad {
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a) {
    // default implementation using floating precision
    return DType(special_functions::cephes::psi<float>(a));
  }
};
MSHADOW_OP_DECLARE_TUNABLE_BACKWARD(gammaln_grad)

template<>
MSHADOW_XINLINE double gammaln_grad::Map<double>(double a) {
  return special_functions::cephes::psi<double>(a);
}

/* Smooth L1 Loss is a loss specific for R-CNN franchise training
 * Smooth L1 Loss function:
 * f(x) = 0.5 * (sigma * x) ^ 2,     |x| < 1 / sigma^2
 *      = |x| - 0.5 / sigma / sigma, otherwise
 * When sigma = 1, it is equivalent to the Huber loss, evaluated at
 * delta = 1.
 * smooth_l1_loss = w_out * f(w_in * x)
 * with w_in, w_out provided by input_data.
 */
struct smooth_l1_loss {
  // a is x, b is sigma
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a, DType b) {
    auto bsq = math::sqr(b);
    auto ibsq = 1.0f / bsq;
    auto af = math::id(a);
    if (af > ibsq) {
      return DType(af - 0.5f * ibsq);
    } else if (af < -ibsq) {
      return DType(-af - 0.5f * ibsq);
    } else {
      return DType(0.5f * af * af * bsq);
    }
  }
};  // struct smooth_l1_loss
MSHADOW_OP_DECLARE_TUNABLE_FWD_AND_BWD(smooth_l1_loss)

/* The derivative of smooth l1 loss is
 * f'(x) = sigma^2 * x, |x| < 1 / sigma^2
 *       = sign(x),     otherwise
 */
struct smooth_l1_gradient {
  // a is x, b is sigma2
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a, DType b) {
    auto bsq = math::sqr(b);
    auto ibsq = 1.0f / bsq;
    auto af = math::id(a);
    if (af > ibsq) {
      return DType(1);
    } else if (af < -ibsq) {
      return DType(-1);
    } else {
      return DType(bsq * af);
    }
  }
};  // struct smooth_l1_derivative
MSHADOW_OP_DECLARE_TUNABLE_BACKWARD(smooth_l1_gradient)

/*! \brief product reducer */
struct product {
  /*! \brief do reduction into dst */
  template<typename DType>
  MSHADOW_XINLINE static void Reduce(volatile DType& dst, volatile DType src) { // NOLINT(*)
    dst *= src;
  }
  /*! \brief do reduction into dst */
  template<typename DType>
  MSHADOW_XINLINE static void Reduce(volatile DType& dst, volatile DType src, volatile DType& none) { // NOLINT(*)
    Reduce(dst, src);
  }
  /*!
  *\brief calculate gradient of redres with respect to redsrc,
  * redres: reduced result, redsrc: one of reduction element
  */
  template<typename DType>
  MSHADOW_XINLINE static DType PartialGrad(DType redres, DType redsrc) {
    return redres / redsrc;
  }
  /*!
  *\brief set the initial value during reduction
  */
  template<typename DType>
  MSHADOW_XINLINE static void SetInitValue(DType &initv) { // NOLINT(*)
    initv = 1;
  }
  /*!
  *\brief set the initial value during reduction
  */
  template<typename DType>
  MSHADOW_XINLINE static void SetInitValue(DType &initv, DType &none) { // NOLINT(*)
    SetInitValue(initv);
  }
};

namespace isnan_typed {
  template<typename DType>
  MSHADOW_XINLINE bool IsNan(volatile DType val) {
    return false;
  }
  template<>
  MSHADOW_XINLINE bool IsNan(volatile float val) {
    return isnan(val);
  }
  template<>
  MSHADOW_XINLINE bool IsNan(volatile double val) {
    return isnan(val);
  }
  template<>
  MSHADOW_XINLINE bool IsNan(volatile long double val) {
    return isnan(val);
  }

  template<>
  MSHADOW_XINLINE bool IsNan(volatile mshadow::half::half_t val) {
    return (val.half_ & 0x7fff) > 0x7c00;
  }
};  // namespace isnan_typed

/*! \brief sum reducer that ignores NaN values in the input */
struct nansum {
  /*! \brief do reduction into dst */
  template<typename DType>
  MSHADOW_XINLINE static void Reduce(volatile DType& dst, volatile DType src) { // NOLINT(*)
    if (isnan_typed::IsNan(src)) return;
    dst += src;
  }
  /*! \brief do reduction into dst */
  template<typename DType>
  MSHADOW_XINLINE static void Reduce(volatile DType& dst, volatile DType src, volatile DType& residual) { // NOLINT(*)
    if (isnan_typed::IsNan(src)) return;
    DType y = src - residual;
    DType t = dst + y;
    residual = (t - dst) - y;
    dst = t;
  }
  /*!
  *\brief set the initial value during reduction
  */
  template<typename DType>
  MSHADOW_XINLINE static void SetInitValue(DType & initv) { // NOLINT(*)
      initv = 0;
  }
  /*!
   *\brief set the initial value during reduction
   */
  template<typename DType>
  MSHADOW_XINLINE static void SetInitValue(DType &initv, DType &residual) { // NOLINT(*)
    SetInitValue(initv);
    residual = 0;
  }
};

struct nansum_grad {
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a, DType b) {
    return isnan_typed::IsNan(a) ? DType(0) : DType(1);
  }
};
MSHADOW_OP_DECLARE_TUNABLE_BACKWARD(nansum_grad)

/*! \brief product reducer that ignores NaN values in the input */
struct nanprod {
  /*! \brief do reduction into dst */
  template<typename DType>
  MSHADOW_XINLINE static void Reduce(volatile DType& dst, volatile DType src) { // NOLINT(*)
    if (isnan_typed::IsNan(src)) return;
    dst *= src;
  }
  /*! \brief do reduction into dst */
  template<typename DType>
  MSHADOW_XINLINE static void Reduce(volatile DType& dst, volatile DType src, volatile DType& none) { // NOLINT(*)
    Reduce(dst, src);
  }
  /*!
  *\brief set the initial value during reduction
  */
  template<typename DType>
  MSHADOW_XINLINE static void SetInitValue(DType & initv) { // NOLINT(*)
    initv = 1;
  }
  /*!
  *\brief set the initial value during reduction
  */
  template<typename DType>
  MSHADOW_XINLINE static void SetInitValue(DType &initv, DType &none) { // NOLINT(*)
    SetInitValue(initv);
  }
};

struct nanprod_grad {
  template<typename DType>
  MSHADOW_XINLINE static DType Map(DType a, DType b) {
    return isnan_typed::IsNan(a) ? DType(0) : b / a;

  }
};

/*! \brief nbit quantize function, calc grad using straight-through estimator(STE) */
struct quantize {
    template<typename DType>
    MSHADOW_XINLINE static DType Map(DType a, real_t b) {
      return DType( roundf( DType(real_t(powf(2.0f, b)- 1.0f) * a) ) / DType( powf(2.0f, b)- 1.0f) );
    }
};

struct quantize_grad {
    template<typename DType>
    MSHADOW_XINLINE static DType Map(DType a) {
      return DType(DType(1.0f));
    }
};

/*! \brief deterministic binary sign function, calc grad using STE */
struct det_sign {
    template<typename DType>
    MSHADOW_XINLINE static DType Map(DType a) {
      if (a < 0.0f) return DType(-DType(1.0f));
      if (a > 0.0f) return DType(DType(1.0f));
      return DType(DType(1.0f));
    }
};

struct det_sign_grad {
    template<typename DType>
    MSHADOW_XINLINE static DType Map(DType a) {
      return DType(fabsf(float(a)) <= DType(0.5f) ? DType(1.0f) : DType(0.0f));
    }
};

MSHADOW_OP_DECLARE_TUNABLE_BACKWARD(nanprod_grad)

}  // namespace mshadow_op
}  // namespace op
}  // namespace mxnet
#endif  // MXNET_OPERATOR_MSHADOW_OP_H_


text:
// mi issue: https://github.com/microsoft/TypeScript/issues/39569
// continúa en: https://github.com/microsoft/TypeScript/issues/27808

export class DigitoVerificador<Num extends bigint|number>{
    constructor(private cast:(numbreString:string|number)=>Num, private multiplicadores:Num[], private divisor:Num, private desplazamiento?:Num){
    }
    obtenerDigito(numero:Num):Num|null{
        var digitos=numero.toString().split('');
        var i=0;
        var sumador:Num = this.cast(0);
        while(digitos.length){
            var digito = this.cast(digitos.pop()||0);
            var multiplicador = this.multiplicadores[i];
            // @ts-expect-error No debería ser error. https://github.com/microsoft/TypeScript/issues/39569
            var producto:Num = digito * multiplicador;
            // @ts-expect-error No debería ser error. https://github.com/microsoft/TypeScript/issues/39569
            sumador = sumador + producto;
            i++;
        }
        if(this.desplazamiento){
            // @ts-expect-error No debería ser error. https://github.com/microsoft/TypeScript/issues/39569
            sumador = sumador + this.desplazamiento;
        }
        // @ts-expect-error No debería ser error. https://github.com/microsoft/TypeScript/issues/39569
        var verificador:Num = sumador % this.divisor;
        if(!verificador) return this.cast(0);
        if(this.divisor-verificador>9) return null;
        // @ts-expect-error No debería ser error. https://github.com/microsoft/TypeScript/issues/39569
        return this.divisor-verificador;
    }
}

redpajama_set_name: RedPajamaGithub


text:
from datetime import datetime

from sqlalchemy import Column, Integer, String, ForeignKey, Boolean, Date, Table, Enum
from sqlalchemy.orm import validates, relationship

from db_handler import Base
from password import Password

class User(Base):
    __tablename__ = 'users'
    email = Column(String(120), unique=True, primary_key=True)
    password = Column(Password)
    admin = Column(Boolean)

    # Or specify a cost factor other than the default 12
    # password = Column(Password(rounds=10))

    @validates('password')
    def _validate_password(self, key, password):
        self.validated = getattr(type(self), key).type.validator(password)
        return self.validated

    def is_active(self):
        return True

    def get_id(self):
        return self.email

    def is_authenticated(self):
        return self.validated

    def is_admin(self):
        return self.admin

    def is_anonymous(self):
        return False

    def __init__(self, email=None, admin=False):
        self.email = email
        self.admin = admin
        self.validated = False

    def __repr__(self):
        return '<User {}>'.format(self.email)

round_questions = Table(
    'associations', Base.metadata,
    Column('round_id', Integer, ForeignKey('rounds.id')),
    Column('question_id', Integer, ForeignKey('questions.id'))
)

class Round(Base):
    __tablename__ = 'rounds'
    id = Column(Integer, primary_key=True)
    running = Column(Boolean)
    created_at = Column(Date)
    questions = relationship("Question", secondary=round_questions)

    def __init__(self, running=True, created_at=datetime.now()):
        self.running = running
        self.created_at = created_at

    def __repr__(self):
        return "<Round - Created at: {} Running: {}>".format(self.created_at,
                self.running)

class Participation(Base):
    __tablename__ = 'participations'
    id = Column(Integer, primary_key=True)
    round_id = Column(Integer, ForeignKey('rounds.id'))
    cur_round = relationship("Round", foreign_keys=[round_id])
    description_id = Column(Integer, ForeignKey('descriptions.id'))
    description = relationship("Description", foreign_keys=[description_id])
    other_description_id = Column(Integer, ForeignKey('descriptions.id'))
    other_description = relationship("Description", foreign_keys=[other_description_id])
    eligible = Column(Boolean)

    def __init__(self, cur_round=None, description=None, other_description=None, eligible=False):
        self.cur_round = cur_round
        self.description = description
        self.other_description = other_description
        self.eligible = eligible

    def __repr__(self):
        return "<Participation {}: Round: {} Eligible: {}>".format(self.id, self.round_id, self.eligible)

class Description(Base):
    __tablename__ = 'descriptions'
    id = Column('id', Integer, primary_key=True)
    user_id = Column(String(120), ForeignKey('users.email'))
    user = relationship("User", foreign_keys=[user_id])
    answers = []

    def __init__(self, user=None, questions=None):
        if questions is None:
            questions = []
        self.user = user
        self.questions = questions

class Question(Base):
    __tablename__ = 'questions'
    id = Column('id', Integer, primary_key=True)
    text = Column(String(512))
    q_type = Column('type', Enum('text', 'image', 'sound'))

    def __init__(self, text=None, q_type='text'):
        self.text = text
        self.q_type = q_type

class Answer(Base):
    __tablename__ = 'answers'
    id = Column('id', Integer, primary_key=True)
    description_id = Column(Integer, ForeignKey('descriptions.id'))
    description = relationship("Description", foreign_keys=[description_id])
    question_id = Column(Integer, ForeignKey('questions.id'))
    question = relationship("Question", foreign_keys=[question_id])
    text = Column(String(256))

    def __init__(self, description=None, question=None, text=None):
        self.description = description
        self.question = question
        self.text = text


text:
.class Lnet/clickdev/music/ui/fragments/ArtistDetailFragment$5;
.super Ljava/lang/Object;
.source "ArtistDetailFragment.java"

# interfaces
.implements Lnet/clickdev/music/widgets/IPopupMenuCallback$IListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lnet/clickdev/music/ui/fragments/ArtistDetailFragment;->setupSongList()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lnet/clickdev/music/ui/fragments/ArtistDetailFragment;

# direct methods
.method constructor <init>(Lnet/clickdev/music/ui/fragments/ArtistDetailFragment;)V
    .locals 0

    .prologue
    .line 171
    iput-object p1, p0, Lnet/clickdev/music/ui/fragments/ArtistDetailFragment$5;->this$0:Lnet/clickdev/music/ui/fragments/ArtistDetailFragment;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onPopupMenuClicked(Landroid/view/View;I)V
    .locals 1
    .param p1, "v"    # Landroid/view/View;
    .param p2, "position"    # I

    .prologue
    .line 174
    iget-object v0, p0, Lnet/clickdev/music/ui/fragments/ArtistDetailFragment$5;->this$0:Lnet/clickdev/music/ui/fragments/ArtistDetailFragment;

    # getter for: Lnet/clickdev/music/ui/fragments/ArtistDetailFragment;->mSongPopupMenuHelper:Lnet/clickdev/music/utils/PopupMenuHelper;
    invoke-static {v0}, Lnet/clickdev/music/ui/fragments/ArtistDetailFragment;->access$500(Lnet/clickdev/music/ui/fragments/ArtistDetailFragment;)Lnet/clickdev/music/utils/PopupMenuHelper;

    move-result-object v0

    invoke-virtual {v0, p1, p2}, Lnet/clickdev/music/utils/PopupMenuHelper;->showPopupMenu(Landroid/view/View;I)V

    .line 175
    return-void
.end method


text:
layout: page
title: "JavaScript fgetss function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/fgetss:803
- /functions/view/fgetss
- /functions/view/803
- /functions/fgetss:803
- /functions/803
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's fgetss

{% codeblock filesystem/fgetss.js lang:js https://raw.github.com/kvz/phpjs/master/functions/filesystem/fgetss.js raw on github %}
function fgetss (handle, length, allowable_tags) {
  // http://kevin.vanzonneveld.net
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // -    depends on: strip_tags
  // *     example 1: fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
  // *     example 1: fgetss(handle, 4096, 'a');
  // *     returns 1: ''

  var start = 0,
    fullline = '';

  if (!this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer || length !== undefined && !length) {
    return false;
  }

  start = this.php_js.resourceDataPointer[handle.id];

  if (start === undefined || !this.php_js.resourceData[handle.id][start]) {
    return false; // Resource was already closed or already reached the end of the file
  }

  fullline = this.php_js.resourceData[handle.id].slice(start, this.php_js.resourceData[handle.id].indexOf('\n', start) + 1);
  if (fullline === '') {
    fullline = this.php_js.resourceData[handle.id].slice(start); // Get to rest of the file
  }

  length = (length === undefined || fullline.length < length) ? fullline.length : Math.floor(length / 2) || 1; // two bytes per character (or surrogate), but ensure at least one

  this.php_js.resourceDataPointer[handle.id] += length - 1;
  return this.strip_tags(this.php_js.resourceData[handle.id].substr(start, length), allowable_tags);
}
{% endcodeblock %}

 - [view on github](https://github.com/kvz/phpjs/blob/master/functions/filesystem/fgetss.js)
 - [edit on github](https://github.com/kvz/phpjs/edit/master/functions/filesystem/fgetss.js)

### Example 1
This code
{% codeblock lang:js example %}
fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
fgetss(handle, 4096, 'a');
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
''
{% endcodeblock %}

### Other PHP functions in the filesystem extension
{% render_partial _includes/custom/filesystem.html %}


text:
module Skippr
  class Unit < Api

  end
end


text:
type PrivateTest<'a, I> = (Box<Parser<Input = I, Output = char> + 'a>,
                           Box<Parser<Input = I, Output = char> + 'a>);

pub type PublicTest<'a, I, O> = Result<Vec<MyLongType>,
                                       Box<Parser<Input = I, Output = char> + 'a>,
                                       Box<Parser<Input = I, Output = char> + 'a>>;

pub type LongGenericListTest<'a,
                             'b,
                             'c,
                             'd,
                             LONGPARAMETERNAME,
                             LONGPARAMETERNAME,
                             LONGPARAMETERNAME,
                             A,
                             B,
                             C> = Option<Vec<MyType>>;

pub type Exactly100CharsTest<'a, 'b, 'c, 'd, LONGPARAMETERNAME, LONGPARAMETERNAME, A, B> = Vec<i32>;

pub type Exactly101CharsTest<'a, 'b, 'c, 'd, LONGPARAMETERNAME, LONGPARAMETERNAME, A, B> =
    Vec<Test>;

pub type Exactly100CharsToEqualTest<'a, 'b, 'c, 'd, LONGPARAMETERNAME, LONGPARAMETERNAME, A, B, C> =
    Vec<i32>;

pub type GenericsFitButNotEqualTest<'a,
                                    'b,
                                    'c,
                                    'd,
                                    LONGPARAMETERNAME,
                                    LONGPARAMETERNAME,
                                    A1,
                                    B,
                                    C> = Vec<i32>;

pub type CommentTest<// Lifetime
                     'a, // Type
                     T> = ();

pub type WithWhereClause<LONGPARAMETERNAME, T>
    where T: Clone,
          LONGPARAMETERNAME: Clone + Eq + OtherTrait = Option<T>;

pub type Exactly100CharstoEqualWhereTest<T, U, PARAMET> where T: Clone + Ord + Eq + SomeOtherTrait =
    Option<T>;

pub type Exactly101CharstoEqualWhereTest<T, U, PARAMETE>
    where T: Clone + Ord + Eq + SomeOtherTrait = Option<T>;

type RegisterPlugin = unsafe fn(pt: *const c_char,
                                plugin: *mut c_void,
                                data: *mut CallbackData);


text:
#ifndef LIBCAER_DEVICES_DVXPLORER_HPP_
#define LIBCAER_DEVICES_DVXPLORER_HPP_

#include "../events/imu6.hpp"
#include "../events/polarity.hpp"
#include "../events/special.hpp"

#include <libcaer/devices/dvxplorer.h>

#include "usb.hpp"

namespace libcaer {
namespace devices {

class dvXplorer : public usb {
public:
	dvXplorer(uint16_t deviceID) : usb(deviceID, CAER_DEVICE_DVXPLORER) {
	}

	dvXplorer(uint16_t deviceID, uint8_t busNumberRestrict, uint8_t devAddressRestrict,
		const std::string &serialNumberRestrict) :
		usb(deviceID, CAER_DEVICE_DVXPLORER, busNumberRestrict, devAddressRestrict, serialNumberRestrict) {
	}

	struct caer_dvx_info infoGet() const noexcept {
		return (caerDVXplorerInfoGet(handle.get()));
	}

	std::string toString() const noexcept override {
		return (infoGet().deviceString);
	}
};
} // namespace devices
} // namespace libcaer

#endif /* LIBCAER_DEVICES_DVXPLORER_HPP_ */


text:
import winston from 'winston'

export function init(app) {
    winston.configure({
        transports: [
            new (winston.transports.Console)({
                prettyPrint: true,
                colorize: true,
                json: false
            })
        ],
        levels: winston.config.syslog.levels,
        format: winston.format.simple()
    })
    winston.addColors(winston.config.syslog.colors)
    // app.use(expressWinston.logger({
    //     transports: [
    //         new winston.transports.Console({
    //             json: false,
    //             colorize: true
    //         })
    //     ],
    //     format: winston.format.simple(),
    //     meta: true, // optional: control whether you want to log the meta data about the request (default to true)
    //     msg: "HTTP {{req.method}} {{req.url}}", // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
    //     expressFormat: true, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors with colorize set to true
    //     colorize: false, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
    //     ignoreRoute: function (req, res) { return false; } // optional: allows to skip some log messages based on request and/or response
    // }));
}


text:
import java.io.Serializable;

// "Change type arguments to <Serializable & Comparable<? extends Serializable & Comparable<?>>>" "true"
class Generic<E> {
  Generic(E arg, E arg1) {
  }
}

class Tester {
  void method() {
    new Generic<Serializable>("hi", 1);
  }
}


text:
<?php

$lang['server']           = 'Your PostgreSQL server';
$lang['port']             = 'Your PostgreSQL server\'s port';
$lang['user']             = 'PostgreSQL user name';
$lang['password']         = 'Password for above user';
$lang['database']         = 'Database to use';
$lang['debug']            = 'Display additional debug information';
$lang['forwardClearPass'] = 'Pass user passwords as cleartext to the SQL statements below, instead of using the passcrypt option';
$lang['checkPass']        = 'SQL statement for checking passwords';
$lang['getUserInfo']      = 'SQL statement for retrieving user information';
$lang['getGroups']        = 'SQL statement for retrieving a user\'s group memberships';
$lang['getUsers']         = 'SQL statement to list all users';
$lang['FilterLogin']      = 'SQL clause for filtering users by login name';
$lang['FilterName']       = 'SQL clause for filtering users by full name';
$lang['FilterEmail']      = 'SQL clause for filtering users by email address';
$lang['FilterGroup']      = 'SQL clause for filtering users by group membership';
$lang['SortOrder']        = 'SQL clause to sort users';
$lang['addUser']          = 'SQL statement to add a new user';
$lang['addGroup']         = 'SQL statement to add a new group';
$lang['addUserGroup']     = 'SQL statement to add a user to an existing group';
$lang['delGroup']         = 'SQL statement to remove a group';
$lang['getUserID']        = 'SQL statement to get the primary key of a user';
$lang['delUser']          = 'SQL statement to delete a user';
$lang['delUserRefs']      = 'SQL statement to remove a user from all groups';
$lang['updateUser']       = 'SQL statement to update a user profile';
$lang['UpdateLogin']      = 'Update clause for updating the user\'s login name';
$lang['UpdatePass']       = 'Update clause for updating the user\'s password';
$lang['UpdateEmail']      = 'Update clause for updating the user\'s email address';
$lang['UpdateName']       = 'Update clause for updating the user\'s full name';
$lang['UpdateTarget']     = 'Limit clause to identify the user when updating';
$lang['delUserGroup']     = 'SQL statement to remove a user from a given group';
$lang['getGroupID']       = 'SQL statement to get the primary key of a given group';


text:
import { Model } from 'mongoose';
import { Character } from '../models/characters';
import { NextFunction, Request, Response } from "express";
import helpers = require('../modules/helpers');
import {MainController} from './main';
const GeneralSkills = require('../../dataSeeds/generalSkills.json');
const WarriorSkills = require('../../dataSeeds/warriorSkills.json');
const MageSkills = require('../../dataSeeds/mageSkills.json');

class Characters extends MainController {

    constructor (Model){
        super(Model);
    }

    public get (req: Request, res: Response, cb?: Function){
        super.get(req, res, cb ? cb : ()=>{});
    }

    public getByUser (req:Request, res:Response) {
        console.log('GET BY USER', req.params.uid)
        Character.find({user : req.params.uid}).sort('-birthDate').limit(1).exec((err, characters)=>{
            if(err){
                return res.status(500).send({err : err});
            }
            res.send(characters[0])
        })
    }

    public delete (req: Request, res: Response, cb?: Function){
        super.delete(req, res, cb ? cb : ()=>{});

    }

    public upsert (req: Request, res: Response, cb?: Function){
        let body = req.body;
        console.log(body)
        if(!req.params.id){
            body.abilities = [];
            body.abilities = body.abilities.concat(GeneralSkills);

            switch(body.class){
                case 'mage' :
                    body.abilities = body.abilities.concat(MageSkills);
                    break;
                case 'warrior' :
                    body.abilities = body.abilities.concat(WarriorSkills);
                    break;
                default :
                    null
                    break;
            }
        }

        super.upsert(req, res, body, (data)=>{

        });

    }

}

export = new Characters(Character);


text:
balloon_learning_environment.metrics.statistics_instance
=========================================================

.. currentmodule:: balloon_learning_environment.metrics.statistics_instance

.. autoclass:: balloon_learning_environment.metrics.statistics_instance.StatisticsInstance
   :members:


text:
ACCEPTED

#### According to
Euro+Med Plantbase

#### Published in
Sp. pl. 2:883. 1753

#### Original name
null

### Remarks
null


text:
package org.atlasapi.query.v4.schedule;

import org.atlasapi.schedule.ChannelSchedule;

interface ScheduleMerger {
    ChannelSchedule merge(ChannelSchedule original, ChannelSchedule override);
}


text:
package Paws::Health::AffectedEntity;
  use Moose;
  has AwsAccountId => (is => 'ro', isa => 'Str', request_name => 'awsAccountId', traits => ['NameInRequest']);
  has EntityArn => (is => 'ro', isa => 'Str', request_name => 'entityArn', traits => ['NameInRequest']);
  has EntityValue => (is => 'ro', isa => 'Str', request_name => 'entityValue', traits => ['NameInRequest']);
  has EventArn => (is => 'ro', isa => 'Str', request_name => 'eventArn', traits => ['NameInRequest']);
  has LastUpdatedTime => (is => 'ro', isa => 'Str', request_name => 'lastUpdatedTime', traits => ['NameInRequest']);
  has StatusCode => (is => 'ro', isa => 'Str', request_name => 'statusCode', traits => ['NameInRequest']);
  has Tags => (is => 'ro', isa => 'Paws::Health::TagSet', request_name => 'tags', traits => ['NameInRequest']);
1;

### main pod documentation begin ###

=head1 NAME

Paws::Health::AffectedEntity

=head1 USAGE

This class represents one of two things:

=head3 Arguments in a call to a service

Use the attributes of this class as arguments to methods. You shouldn't make instances of this class.
Each attribute should be used as a named argument in the calls that expect this type of object.

As an example, if Att1 is expected to be a Paws::Health::AffectedEntity object:

  $service_obj->Method(Att1 => { AwsAccountId => $value, ..., Tags => $value  });

=head3 Results returned from an API call

Use accessors for each attribute. If Att1 is expected to be an Paws::Health::AffectedEntity object:

  $result = $service_obj->Method(...);
  $result->Att1->AwsAccountId

=head1 DESCRIPTION

Information about an entity that is affected by a Health event.

=head1 ATTRIBUTES

=head2 AwsAccountId => Str

  The 12-digit AWS account number that contains the affected entity.

=head2 EntityArn => Str

  The unique identifier for the entity. Format:
C<arn:aws:health:I<entity-region>:I<aws-account>:entity/I<entity-id> >.
Example:
C<arn:aws:health:us-east-1:111222333444:entity/AVh5GGT7ul1arKr1sE1K>

=head2 EntityValue => Str

  The ID of the affected entity.

=head2 EventArn => Str

  The unique identifier for the event. Format:
C<arn:aws:health:I<event-region>::event/I<EVENT_TYPE_PLUS_ID> >.
Example: C<arn:aws:health:us-east-1::event/AWS_EC2_MAINTENANCE_5331>

=head2 LastUpdatedTime => Str

  The most recent time that the entity was updated.

=head2 StatusCode => Str

  The most recent status of the entity affected by the event. The
possible values are C<IMPAIRED>, C<UNIMPAIRED>, and C<UNKNOWN>.

=head2 Tags => L<Paws::Health::TagSet>

  A map of entity tags attached to the affected entity.

=head1 SEE ALSO

This class forms part of L<Paws>, describing an object used in L<Paws::Health>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
/**
 * OrganizationSettingsDetail.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package com.sforce.soap._2006._04.metadata;

public class OrganizationSettingsDetail  implements java.io.Serializable {
    private java.lang.String settingName;

    private boolean settingValue;

    public OrganizationSettingsDetail() {
    }

    public OrganizationSettingsDetail(
           java.lang.String settingName,
           boolean settingValue) {
           this.settingName = settingName;
           this.settingValue = settingValue;
    }

    /**
     * Gets the settingName value for this OrganizationSettingsDetail.
     *
     * @return settingName
     */
    public java.lang.String getSettingName() {
        return settingName;
    }

    /**
     * Sets the settingName value for this OrganizationSettingsDetail.
     *
     * @param settingName
     */
    public void setSettingName(java.lang.String settingName) {
        this.settingName = settingName;
    }

    /**
     * Gets the settingValue value for this OrganizationSettingsDetail.
     *
     * @return settingValue
     */
    public boolean isSettingValue() {
        return settingValue;
    }

    /**
     * Sets the settingValue value for this OrganizationSettingsDetail.
     *
     * @param settingValue
     */
    public void setSettingValue(boolean settingValue) {
        this.settingValue = settingValue;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof OrganizationSettingsDetail)) return false;
        OrganizationSettingsDetail other = (OrganizationSettingsDetail) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.settingName==null && other.getSettingName()==null) ||
             (this.settingName!=null &&
              this.settingName.equals(other.getSettingName()))) &&
            this.settingValue == other.isSettingValue();
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getSettingName() != null) {
            _hashCode += getSettingName().hashCode();
        }
        _hashCode += (isSettingValue() ? Boolean.TRUE : Boolean.FALSE).hashCode();
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(OrganizationSettingsDetail.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "OrganizationSettingsDetail"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("settingName");
        elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "settingName"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("settingValue");
        elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "settingValue"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">

  <title>CodePen - A Pen by  Jaime Estrada</title>

  <title>Jaime's Stage 0 Notes</title>

Intro to Programming Stage 0

Basics of Web

Computers that send requests to servers to access web pages.
The server finds the HTML associated with the web page based
on the request and sends it back to the originator.
The user's browser will then interpretthe web page
and display on the computer. This video explains the
interaction.

World Wide Web (www) and HTML (Hypertext Markup Language>

World Wide Web uses HTML to connect the webpages. HTML is the
heart of the web, its text content, markup (how it looks), references to documents
(images and videos), and links to other web pages.

Tags

Tags are used to create the HTML code. Depending on the tag, you will
have opening and/or closing tags, some tags we have used so far in module 0 are bold, emphasis, anchor, and linkable tags consisting
both of websites or images.


text:
package com.teamclay.MagnticTech.Item;

import com.teamclay.MagnticTech.MagneticTech;

import net.minecraft.item.ItemSword;
import net.minecraftforge.common.util.EnumHelper;

public class ItemSeptumMagnetSword extends ItemSword{
	public static ToolMaterial material = EnumHelper.addToolMaterial("SeptumMagnet", 2, 200, 2.0F, 2.0F, 14);
	public ItemSeptumMagnetSword(){
		super(material);
		this.setMaxDamage(200);
		this.setUnlocalizedName("septum_magnet_sword");
		this.setTextureName("magnetictech:septum_magnet_iron_sword");
		this.setMaxStackSize(1);
		this.setCreativeTab(MagneticTech.MT_BASE);
	}
}


text:
import socket
import logging

from django.core import cache
from django.core.exceptions import ImproperlyConfigured

from ipware.utils import is_valid_ipv4

from cached_httpbl.conf import settings

HTTPBL_THREAT_SEARCHENGINE = 0
HTTPBL_THREAT_SUSPICIOUS = 1
HTTPBL_THREAT_HARVESTER = 2
HTTPBL_THREAT_SPAMMER = 4

if settings.CACHED_HTTPBL_USE_LOGGING:
    logger = logging.getLogger(__name__)

class CachedHTTPBL(object):
    def __init__(self, **kwargs):
        """
        Instantiate the CachedHTTPBL object.

        :param kwargs: optional parameters
        :return:
        """

        api_key = kwargs.get('api_key', None)
        api_host = kwargs.get('api_host', None)
        api_timeout = kwargs.get('api_timeout', None)
        use_cache = kwargs.get('use_cache', None)
        cache_backend = kwargs.get('cache_backend', None)
        cache_timeout = kwargs.get('cache_timeout', None)

        # per instance cache
        no_api_key = True
        if hasattr(settings, 'CACHED_HTTPBL_API_KEY'):
            self._api_key = api_key if api_key else settings.CACHED_HTTPBL_API_KEY
            if self._api_key is not None:
                no_api_key = False
        if no_api_key:
            raise ImproperlyConfigured(
                'You should add httpBL API key to your settings. '
                'Please register on http://projecthoneypot.org to get one.'
            )
        self._last_result = None
        self._api_host = api_host if api_host else settings.CACHED_HTTPBL_API_HOST
        self._api_timeout = api_timeout if api_timeout else settings.CACHED_HTTPBL_API_TIMEOUT
        self._use_cache = use_cache if use_cache else settings.CACHED_HTTPBL_USE_CACHE
        self._cache_backend = cache_backend if cache_backend else settings.CACHED_HTTPBL_CACHE_BACKEND
        self._cache_timeout = cache_timeout if cache_timeout else settings.CACHED_HTTPBL_CACHE_TIMEOUT
        self._cache_version = 1

        if self._use_cache and self._cache_backend is None:
            self._cache_backend = 'default'

        if self._use_cache:
            try:
                self._cache = cache.caches[self._cache_backend]
                try:
                    self._cache_version = int(self._cache.get('cached_httpbl_{0}_version'.format(self._api_key)))
                except TypeError:
                    self._cache.set('cached_httpbl_{0}_version'.format(self._api_key), str(1))
            except cache.InvalidCacheBackendError:
                raise ImproperlyConfigured('You should provide valid cache backend!')

    def _make_cache_key(self, ip):
        return 'cached_httpbl_{0}_ip:{1}'.format(self._api_key, ip)

    def _request_httpbl(self, ip):
        query = '.'.join([self._api_key] + ip.split('.')[::-1] + [self._api_host])

        try:
            try:
                socket.setdefaulttimeout(self._api_timeout)
                response = socket.gethostbyname(query)
            except socket.gaierror:
                # error is raised for good ip
                return 0, 0, 0, 0
        except socket.timeout:
            return -1, -1, -1, -1

        error, age, threat, type = [int(x) for x in response.split('.')]

        return error, age, threat, type

    def check_ip(self, ip):
        """
        Check IP trough the httpBL API

        :param ip: ipv4 ip address
        :return: httpBL results or None if any error is occurred
        """

        self._last_result = None

        if is_valid_ipv4(ip):
            key = None
            if self._use_cache:
                key = self._make_cache_key(ip)
                self._last_result = self._cache.get(key, version=self._cache_version)

            if self._last_result is None:
                # request httpBL API
                error, age, threat, type = self._request_httpbl(ip)
                if error == 127 or error == 0:
                    self._last_result = {
                        'error': error,
                        'age': age,
                        'threat': threat,
                        'type': type
                    }
                    if self._use_cache:
                        self._cache.set(key, self._last_result, timeout=self._api_timeout, version=self._cache_version)
            if self._last_result is not None and settings.CACHED_HTTPBL_USE_LOGGING:
                logger.info(
                    'httpBL check ip: {0}; '
                    'httpBL result: error: {1}, age: {2}, threat: {3}, type: {4}'.format(ip,
                                                                                self._last_result['error'],
                                                                                self._last_result['age'],
                                                                                self._last_result['threat'],
                                                                                self._last_result['type']
                                                                                )
                )

        return self._last_result

    def is_threat(self, result=None, harmless_age=None, threat_score=None, threat_type=None):
        """
        Check if IP is a threat

        :param result: httpBL results; if None, then results from last check_ip() used (optional)
        :param harmless_age: harmless age for check if httpBL age is older (optional)
        :param threat_score: threat score for check if httpBL threat is lower (optional)
        :param threat_type:  threat type, if not equal httpBL score type, then return False (optional)
        :return: True or False
        """

        harmless_age = harmless_age if harmless_age is not None else settings.CACHED_HTTPBL_HARMLESS_AGE
        threat_score = threat_score if threat_score is not None else settings.CACHED_HTTPBL_THREAT_SCORE
        threat_type = threat_type if threat_type is not None else -1
        result = result if result is not None else self._last_result
        threat = False
        if result is not None:
            if result['age'] < harmless_age and result['threat'] > threat_score:
                threat = True
            if threat_type > -1:
                if result['type'] & threat_type:
                    threat = True
                else:
                    threat = False
        return threat

    def is_suspicious(self, result=None):
        """
        Check if IP is suspicious

        :param result: httpBL results; if None, then results from last check_ip() used (optional)
        :return: True or False
        """

        result = result if result is not None else self._last_result
        suspicious = False
        if result is not None:
            suspicious = True if result['type'] > 0 else False
        return suspicious

    def invalidate_ip(self, ip):
        """
        Invalidate httpBL cache for IP address

        :param ip: ipv4 IP address
        """

        if self._use_cache:
            key = self._make_cache_key(ip)
            self._cache.delete(key, version=self._cache_version)

    def invalidate_cache(self):
        """
        Invalidate httpBL cache
        """

        if self._use_cache:
            self._cache_version += 1
            self._cache.increment('cached_httpbl_{0}_version'.format(self._api_key))


text:
package org.linqs.psl.model.rule.arithmetic.expression;

import org.linqs.psl.model.atom.QueryAtom;
import org.linqs.psl.model.rule.arithmetic.expression.coefficient.Coefficient;
import org.linqs.psl.model.rule.arithmetic.expression.coefficient.ConstantNumber;
import org.linqs.psl.model.term.ConstantType;
import org.linqs.psl.model.term.Variable;
import org.linqs.psl.reasoner.function.FunctionComparator;
import org.linqs.psl.test.PSLBaseTest;
import org.linqs.psl.test.TestModel;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;

public class ArithmeticRuleExpressionTest extends PSLBaseTest {
    @Test
    public void testHash() {
        TestModel.ModelInformation model = TestModel.getModel();

        List<Coefficient> coefficients;
        List<SummationAtomOrAtom> atoms;

        // 1.0: Nice(A) + Nice(B) >= 1 ^2
        coefficients = Arrays.asList(
            (Coefficient)(new ConstantNumber(1)),
            (Coefficient)(new ConstantNumber(1))
        );

        atoms = Arrays.asList(
            (SummationAtomOrAtom)(new QueryAtom(model.predicates.get("Nice"), new Variable("A"))),
            (SummationAtomOrAtom)(new QueryAtom(model.predicates.get("Nice"), new Variable("B")))
        );

        ArithmeticRuleExpression expression1 = new ArithmeticRuleExpression(coefficients, atoms, FunctionComparator.GTE, new ConstantNumber(1));
        ArithmeticRuleExpression expression2 = new ArithmeticRuleExpression(coefficients, atoms, FunctionComparator.GTE, new ConstantNumber(1));

        assertEquals(expression1.hashCode(), expression2.hashCode());
        assertEquals(expression1, expression2);
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="NaosDeploymentMessageBusJsonSerializationConfiguration.cs" company="Naos Project">
//    Copyright (c) Naos Project 2019. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Naos.Deployment.MessageBus.Handler
{
    using System;
    using System.Collections.Generic;
    using Naos.Deployment.Tracking;
    using OBeautifulCode.Representation.System;
    using OBeautifulCode.Serialization;
    using OBeautifulCode.Serialization.Json;
    using static System.FormattableString;

    /// <summary>
    /// MessageBus serialization configuration.
    /// </summary>
    public class NaosDeploymentMessageBusJsonSerializationConfiguration : JsonSerializationConfigurationBase
    {
        /// <inheritdoc />
        public override UnregisteredTypeEncounteredStrategy UnregisteredTypeEncounteredStrategy => UnregisteredTypeEncounteredStrategy.Attempt;

        /// <inheritdoc />
        protected override IReadOnlyCollection<JsonSerializationConfigurationType> DependentJsonSerializationConfigurationTypes =>
            new[]
            {
                typeof(NaosDeploymentTrackingJsonSerializationConfiguration).ToJsonSerializationConfigurationType(),
            };

        /// <inheritdoc />
        protected override IReadOnlyCollection<TypeToRegisterForJson> TypesToRegisterForJson => new[]
                                                                                {
                                                                                typeof(DeploymentMessageHandlerSettings)
                                                                                .ToTypeToRegisterForJson(),
                                                                                };

        /// <summary>
        /// Gets the default serializer representation.
        /// </summary>
        /// <value>The default serializer representation.</value>
        public static SerializerRepresentation NaosDeploymentMessageBusJsonSerializerRepresentation
            => new SerializerRepresentation(
                SerializationKind.Json,
                typeof(NaosDeploymentMessageBusJsonSerializationConfiguration).ToRepresentation());
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="Date-Revision-yyyymmdd" content="20141125" />
    <meta http-equiv="Content-Language" content="en" />
    <title>TrAP Transport WebSocket by Netty - Project Dependencies</title>
    <link rel="stylesheet" href="./css/apache-maven-fluido-1.3.0.min.css" />
    <link rel="stylesheet" href="./css/site.css" />
    <link rel="stylesheet" href="./css/print.css" media="print" />

TrAP Transport WebSocket by Netty

Last Published: 2014-11-25

|

Version: 1.3

|

        Trap

/

        TrAP Transports

/

        WebSocket Transport Parent

/

        TrAP Transport WebSocket by Netty

/

Project Dependencies

Trap 1.3

        Introduction

        Java Quickstart

        JavaScript Quickstart

        Channels

        Configuration

Language Specific Documentation

        Java

        JavaScript

Project Documentation

        Project Information

        About

        Plugin Management

        Distribution Management

        Dependency Information

        Dependency Convergence

        Source Repository

        Mailing Lists

        Issue Tracking

        Continuous Integration

        Project Plugins

        Project License

        Dependency Management

        Project Team

        Project Summary

            Dependencies

        Project Reports

                            <form id="search-form" action="http://www.google.com/search" method="get" >

  <input value="ericssonresearch.github.io/trap/transports/websocket/websocket-netty/" name="sitesearch" type="hidden"/>
  <input class="search-query" name="q" id="query" type="text" />
</form>

Project Dependencies

compile

The following is a list of compile dependencies for this project. These dependencies are required to compile and run the application:

GroupId
ArtifactId
Version
Type
License

com.ericsson.research.trap
trap-core
1.3
jar
BSD 3-clause

io.netty
netty
3.5.2.Final
jar
Apache License, Version 2.0

test

The following is a list of test dependencies for this project. These dependencies are only required to compile and run unit tests for the application:

GroupId
ArtifactId
Version
Type
License

junit
junit
4.10
jar
Common Public License Version 1.0

org.slf4j
slf4j-jdk14
1.7.5
jar
MIT License

Project Transitive Dependencies

The following is a list of transitive dependencies for this project. Transitive dependencies are the dependencies of the project dependencies.

compile

The following is a list of compile dependencies for this project. These dependencies are required to compile and run the application:

GroupId
ArtifactId
Version
Type
License

com.ericsson.research.trap
trap-api
1.3
jar
BSD 3-clause

com.ericsson.research.trap
trap-utils-15
1.3
jar
BSD 3-clause

com.ericsson.research.trap
trap-utils-api
1.3
jar
BSD 3-clause

org.slf4j
slf4j-api
1.7.5
jar
MIT License

test

The following is a list of test dependencies for this project. These dependencies are only required to compile and run unit tests for the application:

GroupId
ArtifactId
Version
Type
License

org.hamcrest
hamcrest-core
1.1
jar
BSD style

Project Dependency Graph

Dependency Tree

com.ericsson.research.trap.transports:websocket-netty:jar:1.3

TrAP Transport WebSocket by Netty

Description: Container project for Trap's transport implementations.

URL: http://ericssonresearch.github.io/trap/transports/websocket/websocket-netty/

Project License: BSD 3-clause

com.ericsson.research.trap:trap-core:jar:1.3 (compile)

TrAP Core

Description: Core Trap implementations, with abstract classes for transports. This project provides the base functionality of Trap, but serves no purpose without at least one transport project.

URL: http://ericssonresearch.github.io/trap/trap-core/

Project License: BSD 3-clause

com.ericsson.research.trap:trap-api:jar:1.3 (compile)

TrAP API

Description: API for Trap. Contains all API methods but no implementation.

URL: http://ericssonresearch.github.io/trap/trap-api/

Project License: BSD 3-clause

com.ericsson.research.trap:trap-utils-api:jar:1.3 (compile)

TrAP Utils API

Description: Parent pom for the Transport Abstraction Package. This defines all properties for the children.

The Transport Abstraction Package, or trap, provides an overlaying socket api that can be used across multiple underlying transports, while supporting reconnects, wifi/cellular handover, compression and multiplexing.

URL: http://ericssonresearch.github.io/trap/trap-utils-api/

Project License: BSD 3-clause

com.ericsson.research.trap:trap-utils-15:jar:1.3 (compile)

TrAP Utils JDK 1.5

Description: Parent pom for the Transport Abstraction Package. This defines all properties for the children.

The Transport Abstraction Package, or trap, provides an overlaying socket api that can be used across multiple underlying transports, while supporting reconnects, wifi/cellular handover, compression and multiplexing.

URL: http://ericssonresearch.github.io/trap/trap-utils-15/

Project License: BSD 3-clause

org.slf4j:slf4j-api:jar:1.7.5 (compile)

SLF4J API Module

Description: The slf4j API

URL: http://www.slf4j.org

Project License: MIT License

junit:junit:jar:4.10 (test)

JUnit

Description: JUnit is a regression testing framework written by Erich Gamma and Kent Beck.
        It is used by the developer who implements unit tests in Java.

URL: http://junit.org

Project License: Common Public License Version 1.0

org.hamcrest:hamcrest-core:jar:1.1 (test)

Hamcrest Core

Description: There is currently no description associated with this project.

Project License: BSD style

org.slf4j:slf4j-jdk14:jar:1.7.5 (test)

SLF4J JDK14 Binding

Description: SLF4J JDK14 Binding

URL: http://www.slf4j.org

Project License: MIT License

io.netty:netty:jar:3.5.2.Final (compile)

The Netty Project

Description: The Netty project is an effort to provide an asynchronous event-driven
    network application framework and tools for rapid development of
    maintainable high performance and high scalability protocol servers and
    clients.  In other words, Netty is a NIO client server framework which
    enables quick and easy development of network applications such as protocol
    servers and clients. It greatly simplifies and streamlines network
    programming such as TCP and UDP socket server.

URL: http://netty.io/

Project License: Apache License, Version 2.0

Licenses

BSD 3-clause: TrAP API, TrAP Core, TrAP Transport WebSocket by Netty, TrAP Utils API, TrAP Utils JDK 1.5

BSD style: Hamcrest Core

MIT License: SLF4J API Module, SLF4J JDK14 Binding

Apache License, Version 2.0: The Netty Project

Common Public License Version 1.0: JUnit

Dependency File Details

Filename
Size
Entries
Classes
Packages
JDK Rev
Debug

trap-api/target/classes
-
0
0
0
-
release

trap-core/target/classes
-
0
0
0
-
release

trap-utils-15/target/classes
-
0
0
0
-
release

trap-utils-api/target/classes
-
0
0
0
-
release

netty-3.5.2.Final.jar
1.07 MB
801
733
41
1.5
debug

junit-4.10.jar
247.23 kB
290
252
31
1.5
debug

hamcrest-core-1.1.jar
74.85 kB
54
21
3
1.5
debug

slf4j-api-1.7.5.jar
25.47 kB
34
23
3
1.5
debug

slf4j-jdk14-1.7.5.jar
7.71 kB
15
5
1
1.5
debug

Total
Size
Entries
Classes
Packages
JDK Rev
Debug

9
1.42 MB
1,194
1,034
79
1.5
5

compile: 6
compile: 1.09 MB
compile: 835
compile: 756
compile: 44
-
compile: 2

test: 3
test: 329.79 kB
test: 359
test: 278
test: 35
-
test: 3

Dependency Repository Locations

Repo ID
URL
Release
Snapshot

warp-releases
http://cf.ericsson.net/nexus/content/repositories/warp-releases/
Yes
Yes

central
http://repo.maven.apache.org/maven2
Yes
-

trap-snapshots
https://oss.sonatype.com/content/repositories/snapshots
-
Yes

sonatype-nexus-snapshots
https://oss.sonatype.org/content/repositories/snapshots
-
Yes

Repository locations for each of the Dependencies.

Artifact
airbourne-warp-releases
central
airbourne-trap-snapshots
sonatype-nexus-snapshots

com.ericsson.research.trap:trap-api:jar:1.3
-

-
-

com.ericsson.research.trap:trap-core:jar:1.3
-

-
-

com.ericsson.research.trap:trap-utils-15:jar:1.3
-

-
-

com.ericsson.research.trap:trap-utils-api:jar:1.3
-

-
-

io.netty:netty:jar:3.5.2.Final
-

-
-

junit:junit:jar:4.10
-

-
-

org.hamcrest:hamcrest-core:jar:1.1
-

-
-

org.slf4j:slf4j-api:jar:1.7.5
-

-
-

org.slf4j:slf4j-jdk14:jar:1.7.5
-

-
-

Total
airbourne-warp-releases
central
airbourne-trap-snapshots
sonatype-nexus-snapshots

9 (compile: 6, test: 3)
0
9
0
0

Copyright ©                    2014
                        Ericsson AB.
            All Rights Reserved.


text:
from kivy.app import runTouchApp
from kivy.uix.gridlayout import GridLayout
from kivy.properties import StringProperty
from kivy.lang import Builder
from kivy.utils import get_hex_from_color, get_random_color
import timeit
import re
import random
from functools import partial

def layout_perf(label, repeat):
    if repeat:
        repeat = int(repeat)
    else:
        return 'None'
    return str(timeit.Timer(label._label.render).repeat(1, repeat))

def layout_real_perf(label, repeat):
    if repeat:
        repeat = int(repeat)
    else:
        return 'None'
    old_text = label._label.texture
    label._label.texture = label._label.texture_1px
    res = str(timeit.Timer(partial(label._label.render, True)).repeat(1,
                                                                      repeat))
    label._label.texture = old_text
    return res

kv = '''
#:import tlp visual_test_label.layout_perf
#:import tlrp visual_test_label.layout_real_perf

<TSliderButton@ToggleButton>:
    size_hint: None, None
    size: 100, 50
    group: 'slider'
    on_press: self.parent.slider.name = self.text if self.state =='down' else\
    'dummy'

<TSpinner@Spinner>:
    size_hint: None, None
    size: 100, 50
    name: ''
    on_text: setattr(self.parent.label, self.name, self.text)

<TBoolButton@ToggleButton>:
    size_hint: None, None
    size: 100, 50
    on_state: setattr(self.parent.label, self.text, self.state == 'down')

<TLabel@Label>:
    size_hint: None, None
    size: 100, 50

<LabelTest>:
    cols: 1
    spacing: 10
    padding: 20
    TabbedPanel:
        do_default_tab: False
        tab_width: self.width / 11 * 3
        TabbedPanelItem:
            text: 'Label'
            BoxLayout:
                ScrollView:
                    id: scrollview
                    Label:
                        size_hint: None, None
                        size: self.texture_size
                        id: label
                        text: record.text
                        dummy: 0
                        canvas:
                            Color:
                                rgba: 0, 1, 0, 0.5
                            Rectangle:
                                pos: self.pos
                                size: self.width, self.padding_y
                            Rectangle:
                                pos: self.x, self.y + self.height -\
                                self.padding_y
                                size: self.width, self.padding_y
                            Color:
                                rgba: 0, 0, 1, 0.5
                            Rectangle:
                                pos: self.pos
                                size: self.padding_x, self.height
                            Rectangle:
                                pos: self.x + self.width - self.padding_x,\
                                self.y
                                size: self.padding_x, self.height
                Splitter:
                    sizable_from: 'left'
                    TextInput:
                        id: record
                        text: label.text
                        text: root.text
        TabbedPanelItem:
            text: 'Test performance'
            BoxLayout:
                orientation: 'vertical'
                Label:
                    text: 'Test timeit performance with current label settings'
                BoxLayout:
                    size_hint_y: None
                    height: 40
                    padding: [20, 0]
                    Label:
                        text: 'Repeat count: '
                    TextInput:
                        id: repeat
                        text: '1000'
                    Button:
                        text: 'Go (render - layout)'
                        on_press: results.text = tlp(label, repeat.text)
                    Button:
                        text: 'Go (render_real)'
                        on_press: results.text = tlrp(label, repeat.text)
                Label:
                    id: results
                    text: 'Results:'

    StackLayout:
        id: slider_ctrl
        size_hint_y: None
        height: self.minimum_height
        slider: slider
        label: label
        TLabel:
            text: 'halign: '
        TSpinner:
            name: 'halign'
            values: ['left', 'center', 'right', 'justify']
            text: 'left'
        TLabel:
            text: 'valign: '
        TSpinner:
            name: 'valign'
            values: ['top', 'middle', 'center', 'bottom']
            text: 'bottom'
        TBoolButton:
            text: 'markup'
        TBoolButton:
            text: 'shorten'
        TextInput:
            size_hint: None, None
            size: 100, 50
            hint_text: 'split_str'
            on_text_validate: label.split_str = self.text
            multiline: False
        TLabel:
            text: 'shorten_from: '
        TSpinner:
            name: 'shorten_from'
            values: ['left', 'center', 'right']
            text: 'right'
        TBoolButton:
            text: 'strip'
            state: 'down'
        ToggleButton:
            size_hint: None, None
            size: 100, 50
            text: 'random size'
            on_state: label.text = root.sized_text if self.state == 'down'\
            else root.text
        TLabel:
            text: 'Slider control:'
        TSliderButton:
            text: 'font_size'
        TSliderButton:
            text: 'line_height'
        TSliderButton:
            text: 'max_lines'
        TSliderButton:
            text: 'padding_x'
        TSliderButton:
            text: 'padding_y'
        TextInput:
            size_hint: None, None
            size: 100, 50
            hint_text: 'text_size[0]'
            on_text_validate: label.text_size = (int(self.text) if self.text\
            else None), label.text_size[1]
            multiline: False
        TextInput:
            size_hint: None, None
            size: 100, 50
            hint_text: 'text_size[1]'
            on_text_validate: label.text_size = label.text_size[0],\
            (int(self.text) if self.text else None)
            multiline: False
        TLabel:
            text: '<-- w/ validate'
    Label:
        size_hint_y: None
        height: 40
        color: [0, 1, 0, 1]
        text_size: self.size
        text: 'scrollview size: {}, label size: {}, text_size: {}, '\
        'texture_size: {}, padding: {}'.format(scrollview.size, label.size,\
        label.text_size, label.texture_size, label.padding)

    BoxLayout:
        size_hint_y: None
        height: 40
        Slider:
            id: slider
            range: -10, 200
            value: 15
            name: 'dummy'
            on_value: setattr(label, self.name, self.value)
        Label:
            size_hint_x: None
            width: 50
            text: str(int(slider.value))

'''

text = '''
Because it would spare your Majesty all fear of future \
annoyance. If the lady loves her husband, she does not love your \
Majesty. If she does not love your Majesty, there is no reason \
why she should interfere with your Majesty's plan.

"It is true. And yet--Well! I wish she had been of my own \
station! What a queen she would have made!" He relapsed into a \
moody silence, which was not broken until we drew up in \
Serpentine Avenue.

The door of Briony Lodge was open, and an elderly woman stood \
upon the steps. She watched us with a sardonic eye as we stepped \
from the brougham.

Mr. Sherlock Holmes, I believe?" said she.

I am Mr. Holmes," answered my companion, looking at her with a \
questioning and rather startled gaze.

Indeed! My mistress told me that you were likely to call. She \
left this morning with her husband by the 5:15 train from Charing \
Cross for the Continent."

"What!" Sherlock Holmes staggered back, white with chagrin and \
surprise. "Do you mean that she has left England?"

Never to return.

"And the papers?" asked the King hoarsely. "All is lost."
'''

words = re.split('( +|\\n+)', text)

def annotate(pre, post, callable, words):
    state = False
    i = random.randint(0, 4)
    while i < len(words):
        if ' ' in words[i] or '\n' in words[i]:  # skip spaces
            i += 1
            continue
        if not state:
            words[i] = pre.format(callable(), words[i])
        else:
            words[i] = post.format(words[i])
        state = not state
        i += random.randint(1, 7)

annotate('[size={0}]{1}', '{0}[/size]', partial(random.randint, 8, 24), words)
annotate('[b]{1}', '{0}[/b]', str, words)
annotate('[i]{1}', '{0}[/i]', str, words)
annotate('[color={0}]{1}', '{0}[/color]',
         lambda: get_hex_from_color(get_random_color()), words)
annotated_text = ''.join(words)

class LabelTest(GridLayout):

    text = StringProperty(text)
    sized_text = StringProperty(annotated_text)

if __name__ in ('__main__', ):
    Builder.load_string(kv)
    runTouchApp(LabelTest())


text: docker build -t jdutch .


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Phytologia 10:439, t. 11, fig. 9, 10. 1964

#### Original name
null

### Remarks
null


text:
import os
from typing import Iterable

from mitmproxy import exceptions
from mitmproxy import flow
from mitmproxy import flowfilter
from mitmproxy import http
from mitmproxy import tcp
from mitmproxy import websocket
from mitmproxy.contrib import tnetstring
from mitmproxy import io_compat

FLOW_TYPES = dict(
    http=http.HTTPFlow,
    websocket=websocket.WebSocketFlow,
    tcp=tcp.TCPFlow,
)

class FlowWriter:
    def __init__(self, fo):
        self.fo = fo

    def add(self, flow):
        d = flow.get_state()
        tnetstring.dump(d, self.fo)

class FlowReader:
    def __init__(self, fo):
        self.fo = fo

    def stream(self) -> Iterable[flow.Flow]:
        """
            Yields Flow objects from the dump.
        """
        try:
            while True:
                data = tnetstring.load(self.fo)
                try:
                    data = io_compat.migrate_flow(data)
                except ValueError as e:
                    raise exceptions.FlowReadException(str(e))
                if data["type"] not in FLOW_TYPES:
                    raise exceptions.FlowReadException("Unknown flow type: {}".format(data["type"]))
                yield FLOW_TYPES[data["type"]].from_state(data)
        except ValueError as e:
            if str(e) == "not a tnetstring: empty file":
                return  # Error is due to EOF
            raise exceptions.FlowReadException("Invalid data format.")

class FilteredFlowWriter:
    def __init__(self, fo, flt):
        self.fo = fo
        self.flt = flt

    def add(self, f: flow.Flow):
        if self.flt and not flowfilter.match(self.flt, f):
            return
        d = f.get_state()
        tnetstring.dump(d, self.fo)

def read_flows_from_paths(paths):
    """
    Given a list of filepaths, read all flows and return a list of them.
    From a performance perspective, streaming would be advisable -
    however, if there's an error with one of the files, we want it to be raised immediately.

    Raises:
        FlowReadException, if any error occurs.
    """
    try:
        flows = []
        for path in paths:
            path = os.path.expanduser(path)
            with open(path, "rb") as f:
                flows.extend(FlowReader(f).stream())
    except IOError as e:
        raise exceptions.FlowReadException(e.strerror)
    return flows


text:
class SessionsController < ApplicationController

  def new
  end

  def create
  end

  def destroy
  end
end


text:
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %} 무비덕 {% endblock %}</title>
  <meta charset="utf-8">
  <meta property="og:title" content="무비덕" />

  <meta name="description" content="Movie the Movie">
  <meta property="og:description" content="Movie the Movie">

  <meta property="og:image" content="https://d17f28g3dsa4vh.cloudfront.net/img/home-design.png" />

<link rel="icon" type="image/vnd.microsoft.icon" href="/asset/favicon.ico" />

<meta property="og:type" content="website" />
<meta property="fb:admins" content="" />

<meta name="google-site-verification" content="" />
<meta name="author" content="carpedm20">
<link rel="author" href="./humans.txt" />

<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" />
<link rel="stylesheet" href="/asset/colorbox.css" />
<link rel="stylesheet" href="/asset/popup_login.css" />

<link rel="stylesheet" href="/asset/style.css" />
<link rel="stylesheet" href="/asset/loginform.css" />

{% if messages %}

    {% for message in messages %}

        {{ message }}

    {% endfor %}

{% endif %}

MovieDuk

Movie

Watch!

Random

FreeTalk

    {% if request.session.DukUser %}

Social

Profile

Sign Out

    {% else %}

        Sign In/Up

      {% include "account/popup_login.html" %}
    {% endif %}

        <input name="searchBox" type="text" class="search-input ui-autocomplete-input" placeholder="제목,배우,감독 검색" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">

          <input type="submit" value="검색">

{% block content%}
{% endblock content %}


text:
module.exports = ['$scope', '$location', function ($scope, $location) {
    'use strict';

    //*** Functions *****************

    $scope.matchesPath = function (path) {
        return $location.$$path === path;
    };

    //*** Listeners *****************

    //todo
}];


text:
package com.eaglesakura.lib.android.game.io.fs;

import com.eaglesakura.lib.android.game.io.IFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * ファイルシステムを扱ったシステム
 *
 * @author TAKESHI YAMASHITA
 */
public class FSFile implements IFile {
    File file;

    public FSFile(File file) {
        this.file = file;
    }

    @Override
    public boolean isDirectory() {
        return file.isDirectory();
    }

    @Override
    public boolean isFile() {
        return file.isFile();
    }

    @Override
    public String getName() {
        return file.getName();
    }

    @Override
    public boolean exists() {
        return file.exists();
    }

    @Override
    public long length() {
        return file.length();
    }

    @Override
    public List<IFile> list() {
        List<IFile> result = new ArrayList<IFile>();
        File[] files = file.listFiles();
        if (files != null) {
            for (File sub : files) {
                result.add(new FSFile(sub));
            }
        }
        return result;
    }

    @Override
    public InputStream openReadable() throws IOException {
        return new FileInputStream(file);
    }

    @Override
    public OutputStream openWritable() throws IOException {
        return new FileOutputStream(file);
    }

}


text:
package com.sedsoftware.xyzreader.data.local;

import android.content.ContentValues;
import android.database.Cursor;
import com.sedsoftware.xyzreader.data.model.Article;

class ArticlesDatabase {

  abstract static class Table {

    static final String TABLE_NAME = "articles";

    static final String COLUMN_ID = "_id";
    static final String COLUMN_SERVER_ID = "server_id";
    static final String COLUMN_TITLE = "title";
    static final String COLUMN_AUTHOR = "author";
    static final String COLUMN_BODY = "body";
    static final String COLUMN_THUMB_URL = "thumb_url";
    static final String COLUMN_PHOTO_URL = "photo_url";
    static final String COLUMN_ASPECT_RATIO = "aspect_ratio";
    static final String COLUMN_PUBLISHED_DATE = "published_date";

    static final String CREATE =
        "CREATE TABLE " + TABLE_NAME + " ("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_SERVER_ID + " INTEGER,"
            + COLUMN_TITLE + " TEXT NOT NULL,"
            + COLUMN_AUTHOR + " TEXT NOT NULL,"
            + COLUMN_BODY + " TEXT NOT NULL,"
            + COLUMN_THUMB_URL + " TEXT NOT NULL,"
            + COLUMN_PHOTO_URL + " TEXT NOT NULL,"
            + COLUMN_ASPECT_RATIO + " REAL NOT NULL DEFAULT 1.5,"
            + COLUMN_PUBLISHED_DATE + " TEXT NOT NULL"
            + ")";
  }

  static ContentValues toContentValues(Article article) {

    ContentValues cv = new ContentValues();

    cv.put(Table.COLUMN_SERVER_ID, article.id());
    cv.put(Table.COLUMN_TITLE, article.title());
    cv.put(Table.COLUMN_AUTHOR, article.author());
    cv.put(Table.COLUMN_BODY, article.body());
    cv.put(Table.COLUMN_THUMB_URL, article.thumb());
    cv.put(Table.COLUMN_PHOTO_URL, article.photo());
    cv.put(Table.COLUMN_ASPECT_RATIO, article.aspect_ratio());
    cv.put(Table.COLUMN_PUBLISHED_DATE, article.published_date());

    return cv;
  }

  static Article parseCursor(Cursor cursor) {

    int articleId = cursor.getInt(cursor.getColumnIndexOrThrow(Table.COLUMN_SERVER_ID));
    String articleTitle = cursor.getString(cursor.getColumnIndexOrThrow(Table.COLUMN_TITLE));
    String articleAuthor = cursor.getString(cursor.getColumnIndexOrThrow(Table.COLUMN_AUTHOR));
    String articleBody = cursor.getString(cursor.getColumnIndexOrThrow(Table.COLUMN_BODY));
    String articleThumb = cursor.getString(cursor.getColumnIndexOrThrow(Table.COLUMN_THUMB_URL));
    String articlePhoto = cursor.getString(cursor.getColumnIndexOrThrow(Table.COLUMN_PHOTO_URL));
    double articleRatio = cursor.getDouble(cursor.getColumnIndexOrThrow(Table.COLUMN_ASPECT_RATIO));
    String articleDate = cursor.getString(cursor.getColumnIndexOrThrow(Table.COLUMN_PUBLISHED_DATE));

    return Article.builder()
        .id(articleId)
        .title(articleTitle)
        .author(articleAuthor)
        .body(articleBody)
        .thumb(articleThumb)
        .photo(articlePhoto)
        .aspect_ratio(articleRatio)
        .published_date(articleDate)
        .build();
  }
}


text:
require_relative 'git_hub_api'

module GitHubApi
  class Repo
    attr_accessor :fq_repo_name, :milestones, :labels, :client

    def initialize(octokit_repo, organization)
      @fq_repo_name   = organization.fq_repo_name
      @client = organization.client
      load_milestones
      load_valid_labels
    end

    def notifications
      @notifications = begin
        octokit_notifications = GitHubApi.execute(@client, :repository_notifications, @fq_repo_name, "all" => false)
        octokit_notifications.collect do |octokit_notification|
          Notification.new(octokit_notification, self)
        end
      end
    end

    def valid_label?(label_text)
      @labels.include?(label_text)
    end

    def valid_milestone?(milestone)
      milestones.include?(milestone)
    end

    private

    def load_valid_labels
      @labels     = Set.new
      repo_labels = GitHubApi.execute(@client, :labels, @fq_repo_name)
      repo_labels.each do |label|
        @labels.add(label.name)
      end
    end

    def load_milestones
      @milestones = Hash.new
      octokit_milestones = GitHubApi.execute(@client, :list_milestones, @fq_repo_name)
      octokit_milestones.each do |octokit_milestone|
        milestone = Milestone.new(octokit_milestone, self)
        @milestones[milestone.title] = milestone.number
      end
    end
  end
end


text:
namespace task_management {

namespace {

base::string16 AdjustTitle(const content::SiteInstance* site_instance) {
  DCHECK(site_instance);
  int message_id = site_instance->GetBrowserContext()->IsOffTheRecord() ?
      IDS_TASK_MANAGER_SUBFRAME_INCOGNITO_PREFIX :
      IDS_TASK_MANAGER_SUBFRAME_PREFIX;

  return l10n_util::GetStringFUTF16(message_id, base::UTF8ToUTF16(
      site_instance->GetSiteURL().spec()));
}

}  // namespace

SubframeTask::SubframeTask(content::RenderFrameHost* render_frame_host,
                           content::WebContents* web_contents)
    : RendererTask(AdjustTitle(render_frame_host->GetSiteInstance()),
                   nullptr,
                   web_contents,
                   render_frame_host->GetProcess()) {
  // Note that we didn't get the RenderProcessHost from the WebContents, but
  // rather from the RenderFrameHost. Out-of-process iframes reside on
  // different processes than that of their main frame.
}

SubframeTask::~SubframeTask() {
}

void SubframeTask::UpdateTitle() {
  // This will be called when the title changes on the WebContents's main frame,
  // but this Task represents other frames, so we don't care.
}

void SubframeTask::UpdateFavicon() {
  // This will be called when the favicon changes on the WebContents's main
  // frame, but this Task represents other frames, so we don't care.
}

}  // namespace task_management