text:
namespace base {
namespace internal {

template <typename T>
constexpr bool CheckedAddImpl(T x, T y, T* result) {
  static_assert(std::is_integral<T>::value, "Type must be integral");
  // Since the value of x+y is undefined if we have a signed type, we compute
  // it using the unsigned type of the same size.
  using UnsignedDst = typename std::make_unsigned<T>::type;
  using SignedDst = typename std::make_signed<T>::type;
  const UnsignedDst ux = static_cast<UnsignedDst>(x);
  const UnsignedDst uy = static_cast<UnsignedDst>(y);
  const UnsignedDst uresult = static_cast<UnsignedDst>(ux + uy);
  // Addition is valid if the sign of (x + y) is equal to either that of x or
  // that of y.
  if (std::is_signed<T>::value
          ? static_cast<SignedDst>((uresult ^ ux) & (uresult ^ uy)) < 0
          : uresult < uy)  // Unsigned is either valid or underflow.
    return false;
  *result = static_cast<T>(uresult);
  return true;
}

template <typename T, typename U, class Enable = void>
struct CheckedAddOp {};

template <typename T, typename U>
struct CheckedAddOp<T,
                    U,
                    typename std::enable_if<std::is_integral<T>::value &&
                                            std::is_integral<U>::value>::type> {
  using result_type = typename MaxExponentPromotion<T, U>::type;
  template <typename V>
  static constexpr bool Do(T x, U y, V* result) {
    // TODO(jschuh) Make this "constexpr if" once we're C++17.
    if (CheckedAddFastOp<T, U>::is_supported)
      return CheckedAddFastOp<T, U>::Do(x, y, result);

    // Double the underlying type up to a full machine word.
    using FastPromotion = typename FastIntegerArithmeticPromotion<T, U>::type;
    using Promotion =
        typename std::conditional<(IntegerBitsPlusSign<FastPromotion>::value >
                                   IntegerBitsPlusSign<intptr_t>::value),
                                  typename BigEnoughPromotion<T, U>::type,
                                  FastPromotion>::type;
    // Fail if either operand is out of range for the promoted type.
    // TODO(jschuh): This could be made to work for a broader range of values.
    if (BASE_NUMERICS_UNLIKELY(!IsValueInRangeForNumericType<Promotion>(x) ||
                               !IsValueInRangeForNumericType<Promotion>(y))) {
      return false;
    }

    Promotion presult = {};
    bool is_valid = true;
    if (IsIntegerArithmeticSafe<Promotion, T, U>::value) {
      presult = static_cast<Promotion>(x) + static_cast<Promotion>(y);
    } else {
      is_valid = CheckedAddImpl(static_cast<Promotion>(x),
                                static_cast<Promotion>(y), &presult);
    }
    if (!is_valid || !IsValueInRangeForNumericType<V>(presult))
      return false;
    *result = static_cast<V>(presult);
    return true;
  }
};

template <typename T>
constexpr bool CheckedSubImpl(T x, T y, T* result) {
  static_assert(std::is_integral<T>::value, "Type must be integral");
  // Since the value of x+y is undefined if we have a signed type, we compute
  // it using the unsigned type of the same size.
  using UnsignedDst = typename std::make_unsigned<T>::type;
  using SignedDst = typename std::make_signed<T>::type;
  const UnsignedDst ux = static_cast<UnsignedDst>(x);
  const UnsignedDst uy = static_cast<UnsignedDst>(y);
  const UnsignedDst uresult = static_cast<UnsignedDst>(ux - uy);
  // Subtraction is valid if either x and y have same sign, or (x-y) and x have
  // the same sign.
  if (std::is_signed<T>::value
          ? static_cast<SignedDst>((uresult ^ ux) & (ux ^ uy)) < 0
          : x < y)
    return false;
  *result = static_cast<T>(uresult);
  return true;
}

template <typename T, typename U, class Enable = void>
struct CheckedSubOp {};

template <typename T, typename U>
struct CheckedSubOp<T,
                    U,
                    typename std::enable_if<std::is_integral<T>::value &&
                                            std::is_integral<U>::value>::type> {
  using result_type = typename MaxExponentPromotion<T, U>::type;
  template <typename V>
  static constexpr bool Do(T x, U y, V* result) {
    // TODO(jschuh) Make this "constexpr if" once we're C++17.
    if (CheckedSubFastOp<T, U>::is_supported)
      return CheckedSubFastOp<T, U>::Do(x, y, result);

    // Double the underlying type up to a full machine word.
    using FastPromotion = typename FastIntegerArithmeticPromotion<T, U>::type;
    using Promotion =
        typename std::conditional<(IntegerBitsPlusSign<FastPromotion>::value >
                                   IntegerBitsPlusSign<intptr_t>::value),
                                  typename BigEnoughPromotion<T, U>::type,
                                  FastPromotion>::type;
    // Fail if either operand is out of range for the promoted type.
    // TODO(jschuh): This could be made to work for a broader range of values.
    if (BASE_NUMERICS_UNLIKELY(!IsValueInRangeForNumericType<Promotion>(x) ||
                               !IsValueInRangeForNumericType<Promotion>(y))) {
      return false;
    }

    Promotion presult = {};
    bool is_valid = true;
    if (IsIntegerArithmeticSafe<Promotion, T, U>::value) {
      presult = static_cast<Promotion>(x) - static_cast<Promotion>(y);
    } else {
      is_valid = CheckedSubImpl(static_cast<Promotion>(x),
                                static_cast<Promotion>(y), &presult);
    }
    if (!is_valid || !IsValueInRangeForNumericType<V>(presult))
      return false;
    *result = static_cast<V>(presult);
    return true;
  }
};

template <typename T>
constexpr bool CheckedMulImpl(T x, T y, T* result) {
  static_assert(std::is_integral<T>::value, "Type must be integral");
  // Since the value of x*y is potentially undefined if we have a signed type,
  // we compute it using the unsigned type of the same size.
  using UnsignedDst = typename std::make_unsigned<T>::type;
  using SignedDst = typename std::make_signed<T>::type;
  const UnsignedDst ux = SafeUnsignedAbs(x);
  const UnsignedDst uy = SafeUnsignedAbs(y);
  const UnsignedDst uresult = static_cast<UnsignedDst>(ux * uy);
  const bool is_negative =
      std::is_signed<T>::value && static_cast<SignedDst>(x ^ y) < 0;
  // We have a fast out for unsigned identity or zero on the second operand.
  // After that it's an unsigned overflow check on the absolute value, with
  // a +1 bound for a negative result.
  if (uy > UnsignedDst(!std::is_signed<T>::value || is_negative) &&
      ux > (std::numeric_limits<T>::max() + UnsignedDst(is_negative)) / uy)
    return false;
  *result = is_negative ? 0 - uresult : uresult;
  return true;
}

template <typename T, typename U, class Enable = void>
struct CheckedMulOp {};

template <typename T, typename U>
struct CheckedMulOp<T,
                    U,
                    typename std::enable_if<std::is_integral<T>::value &&
                                            std::is_integral<U>::value>::type> {
  using result_type = typename MaxExponentPromotion<T, U>::type;
  template <typename V>
  static constexpr bool Do(T x, U y, V* result) {
    // TODO(jschuh) Make this "constexpr if" once we're C++17.
    if (CheckedMulFastOp<T, U>::is_supported)
      return CheckedMulFastOp<T, U>::Do(x, y, result);

    using Promotion = typename FastIntegerArithmeticPromotion<T, U>::type;
    // Verify the destination type can hold the result (always true for 0).
    if (BASE_NUMERICS_UNLIKELY((!IsValueInRangeForNumericType<Promotion>(x) ||
                                !IsValueInRangeForNumericType<Promotion>(y)) &&
                               x && y)) {
      return false;
    }

    Promotion presult = {};
    bool is_valid = true;
    if (CheckedMulFastOp<Promotion, Promotion>::is_supported) {
      // The fast op may be available with the promoted type.
      is_valid = CheckedMulFastOp<Promotion, Promotion>::Do(x, y, &presult);
    } else if (IsIntegerArithmeticSafe<Promotion, T, U>::value) {
      presult = static_cast<Promotion>(x) * static_cast<Promotion>(y);
    } else {
      is_valid = CheckedMulImpl(static_cast<Promotion>(x),
                                static_cast<Promotion>(y), &presult);
    }
    if (!is_valid || !IsValueInRangeForNumericType<V>(presult))
      return false;
    *result = static_cast<V>(presult);
    return true;
  }
};

// Division just requires a check for a zero denominator or an invalid negation
// on signed min/-1.
template <typename T, typename U, class Enable = void>
struct CheckedDivOp {};

template <typename T, typename U>
struct CheckedDivOp<T,
                    U,
                    typename std::enable_if<std::is_integral<T>::value &&
                                            std::is_integral<U>::value>::type> {
  using result_type = typename MaxExponentPromotion<T, U>::type;
  template <typename V>
  static constexpr bool Do(T x, U y, V* result) {
    if (BASE_NUMERICS_UNLIKELY(!y))
      return false;

    // The overflow check can be compiled away if we don't have the exact
    // combination of types needed to trigger this case.
    using Promotion = typename BigEnoughPromotion<T, U>::type;
    if (BASE_NUMERICS_UNLIKELY(
            (std::is_signed<T>::value && std::is_signed<U>::value &&
             IsTypeInRangeForNumericType<T, Promotion>::value &&
             static_cast<Promotion>(x) ==
                 std::numeric_limits<Promotion>::lowest() &&
             y == static_cast<U>(-1)))) {
      return false;
    }

    // This branch always compiles away if the above branch wasn't removed.
    if (BASE_NUMERICS_UNLIKELY((!IsValueInRangeForNumericType<Promotion>(x) ||
                                !IsValueInRangeForNumericType<Promotion>(y)) &&
                               x)) {
      return false;
    }

    const Promotion presult = Promotion(x) / Promotion(y);
    if (!IsValueInRangeForNumericType<V>(presult))
      return false;
    *result = static_cast<V>(presult);
    return true;
  }
};

template <typename T, typename U, class Enable = void>
struct CheckedModOp {};

template <typename T, typename U>
struct CheckedModOp<T,
                    U,
                    typename std::enable_if<std::is_integral<T>::value &&
                                            std::is_integral<U>::value>::type> {
  using result_type = typename MaxExponentPromotion<T, U>::type;
  template <typename V>
  static constexpr bool Do(T x, U y, V* result) {
    if (BASE_NUMERICS_UNLIKELY(!y))
      return false;

    using Promotion = typename BigEnoughPromotion<T, U>::type;
    if (BASE_NUMERICS_UNLIKELY(
            (std::is_signed<T>::value && std::is_signed<U>::value &&
             IsTypeInRangeForNumericType<T, Promotion>::value &&
             static_cast<Promotion>(x) ==
                 std::numeric_limits<Promotion>::lowest() &&
             y == static_cast<U>(-1)))) {
      *result = 0;
      return true;
    }

    const Promotion presult =
        static_cast<Promotion>(x) % static_cast<Promotion>(y);
    if (!IsValueInRangeForNumericType<V>(presult))
      return false;
    *result = static_cast<Promotion>(presult);
    return true;
  }
};

template <typename T, typename U, class Enable = void>
struct CheckedLshOp {};

// Left shift. Shifts less than 0 or greater than or equal to the number
// of bits in the promoted type are undefined. Shifts of negative values
// are undefined. Otherwise it is defined when the result fits.
template <typename T, typename U>
struct CheckedLshOp<T,
                    U,
                    typename std::enable_if<std::is_integral<T>::value &&
                                            std::is_integral<U>::value>::type> {
  using result_type = T;
  template <typename V>
  static constexpr bool Do(T x, U shift, V* result) {
    // Disallow negative numbers and verify the shift is in bounds.
    if (BASE_NUMERICS_LIKELY(!IsValueNegative(x) &&
                             as_unsigned(shift) <
                                 as_unsigned(std::numeric_limits<T>::digits))) {
      // Shift as unsigned to avoid undefined behavior.
      *result = static_cast<V>(as_unsigned(x) << shift);
      // If the shift can be reversed, we know it was valid.
      return *result >> shift == x;
    }

    // Handle the legal corner-case of a full-width signed shift of zero.
    if (!std::is_signed<T>::value || x ||
        as_unsigned(shift) != as_unsigned(std::numeric_limits<T>::digits))
      return false;
    *result = 0;
    return true;
  }
};

template <typename T, typename U, class Enable = void>
struct CheckedRshOp {};

// Right shift. Shifts less than 0 or greater than or equal to the number
// of bits in the promoted type are undefined. Otherwise, it is always defined,
// but a right shift of a negative value is implementation-dependent.
template <typename T, typename U>
struct CheckedRshOp<T,
                    U,
                    typename std::enable_if<std::is_integral<T>::value &&
                                            std::is_integral<U>::value>::type> {
  using result_type = T;
  template <typename V>
  static bool Do(T x, U shift, V* result) {
    // Use sign conversion to push negative values out of range.
    if (BASE_NUMERICS_UNLIKELY(as_unsigned(shift) >=
                               IntegerBitsPlusSign<T>::value)) {
      return false;
    }

    const T tmp = x >> shift;
    if (!IsValueInRangeForNumericType<V>(tmp))
      return false;
    *result = static_cast<V>(tmp);
    return true;
  }
};

template <typename T, typename U, class Enable = void>
struct CheckedAndOp {};

// For simplicity we support only unsigned integer results.
template <typename T, typename U>
struct CheckedAndOp<T,
                    U,
                    typename std::enable_if<std::is_integral<T>::value &&
                                            std::is_integral<U>::value>::type> {
  using result_type = typename std::make_unsigned<
      typename MaxExponentPromotion<T, U>::type>::type;
  template <typename V>
  static constexpr bool Do(T x, U y, V* result) {
    const result_type tmp =
        static_cast<result_type>(x) & static_cast<result_type>(y);
    if (!IsValueInRangeForNumericType<V>(tmp))
      return false;
    *result = static_cast<V>(tmp);
    return true;
  }
};

template <typename T, typename U, class Enable = void>
struct CheckedOrOp {};

// For simplicity we support only unsigned integers.
template <typename T, typename U>
struct CheckedOrOp<T,
                   U,
                   typename std::enable_if<std::is_integral<T>::value &&
                                           std::is_integral<U>::value>::type> {
  using result_type = typename std::make_unsigned<
      typename MaxExponentPromotion<T, U>::type>::type;
  template <typename V>
  static constexpr bool Do(T x, U y, V* result) {
    const result_type tmp =
        static_cast<result_type>(x) | static_cast<result_type>(y);
    if (!IsValueInRangeForNumericType<V>(tmp))
      return false;
    *result = static_cast<V>(tmp);
    return true;
  }
};

template <typename T, typename U, class Enable = void>
struct CheckedXorOp {};

// For simplicity we support only unsigned integers.
template <typename T, typename U>
struct CheckedXorOp<T,
                    U,
                    typename std::enable_if<std::is_integral<T>::value &&
                                            std::is_integral<U>::value>::type> {
  using result_type = typename std::make_unsigned<
      typename MaxExponentPromotion<T, U>::type>::type;
  template <typename V>
  static constexpr bool Do(T x, U y, V* result) {
    const result_type tmp =
        static_cast<result_type>(x) ^ static_cast<result_type>(y);
    if (!IsValueInRangeForNumericType<V>(tmp))
      return false;
    *result = static_cast<V>(tmp);
    return true;
  }
};

// Max doesn't really need to be implemented this way because it can't fail,
// but it makes the code much cleaner to use the MathOp wrappers.
template <typename T, typename U, class Enable = void>
struct CheckedMaxOp {};

template <typename T, typename U>
struct CheckedMaxOp<
    T,
    U,
    typename std::enable_if<std::is_arithmetic<T>::value &&
                            std::is_arithmetic<U>::value>::type> {
  using result_type = typename MaxExponentPromotion<T, U>::type;
  template <typename V>
  static constexpr bool Do(T x, U y, V* result) {
    const result_type tmp = IsGreater<T, U>::Test(x, y)
                                ? static_cast<result_type>(x)
                                : static_cast<result_type>(y);
    if (!IsValueInRangeForNumericType<V>(tmp))
      return false;
    *result = static_cast<V>(tmp);
    return true;
  }
};

// Min doesn't really need to be implemented this way because it can't fail,
// but it makes the code much cleaner to use the MathOp wrappers.
template <typename T, typename U, class Enable = void>
struct CheckedMinOp {};

template <typename T, typename U>
struct CheckedMinOp<
    T,
    U,
    typename std::enable_if<std::is_arithmetic<T>::value &&
                            std::is_arithmetic<U>::value>::type> {
  using result_type = typename LowestValuePromotion<T, U>::type;
  template <typename V>
  static constexpr bool Do(T x, U y, V* result) {
    const result_type tmp = IsLess<T, U>::Test(x, y)
                                ? static_cast<result_type>(x)
                                : static_cast<result_type>(y);
    if (!IsValueInRangeForNumericType<V>(tmp))
      return false;
    *result = static_cast<V>(tmp);
    return true;
  }
};

// This is just boilerplate that wraps the standard floating point arithmetic.
// A macro isn't the nicest solution, but it beats rewriting these repeatedly.
#define BASE_FLOAT_ARITHMETIC_OPS(NAME, OP)                              \
  template <typename T, typename U>                                      \
  struct Checked##NAME##Op<                                              \
      T, U,                                                              \
      typename std::enable_if<std::is_floating_point<T>::value ||        \
                              std::is_floating_point<U>::value>::type> { \
    using result_type = typename MaxExponentPromotion<T, U>::type;       \
    template <typename V>                                                \
    static constexpr bool Do(T x, U y, V* result) {                      \
      using Promotion = typename MaxExponentPromotion<T, U>::type;       \
      const Promotion presult = x OP y;                                  \
      if (!IsValueInRangeForNumericType<V>(presult))                     \
        return false;                                                    \
      *result = static_cast<V>(presult);                                 \
      return true;                                                       \
    }                                                                    \
  };

BASE_FLOAT_ARITHMETIC_OPS(Add, +)
BASE_FLOAT_ARITHMETIC_OPS(Sub, -)
BASE_FLOAT_ARITHMETIC_OPS(Mul, *)
BASE_FLOAT_ARITHMETIC_OPS(Div, /)

#undef BASE_FLOAT_ARITHMETIC_OPS

// Floats carry around their validity state with them, but integers do not. So,
// we wrap the underlying value in a specialization in order to hide that detail
// and expose an interface via accessors.
enum NumericRepresentation {
  NUMERIC_INTEGER,
  NUMERIC_FLOATING,
  NUMERIC_UNKNOWN
};

template <typename NumericType>
struct GetNumericRepresentation {
  static const NumericRepresentation value =
      std::is_integral<NumericType>::value
          ? NUMERIC_INTEGER
          : (std::is_floating_point<NumericType>::value ? NUMERIC_FLOATING
                                                        : NUMERIC_UNKNOWN);
};

template <typename T,
          NumericRepresentation type = GetNumericRepresentation<T>::value>
class CheckedNumericState {};

// Integrals require quite a bit of additional housekeeping to manage state.
template <typename T>
class CheckedNumericState<T, NUMERIC_INTEGER> {
 public:
  template <typename Src = int>
  constexpr explicit CheckedNumericState(Src value = 0, bool is_valid = true)
      : is_valid_(is_valid && IsValueInRangeForNumericType<T>(value)),
        value_(WellDefinedConversionOrZero(value, is_valid_)) {
    static_assert(std::is_arithmetic<Src>::value, "Argument must be numeric.");
  }

  template <typename Src>
  constexpr CheckedNumericState(const CheckedNumericState<Src>& rhs)
      : CheckedNumericState(rhs.value(), rhs.is_valid()) {}

  constexpr bool is_valid() const { return is_valid_; }

  constexpr T value() const { return value_; }

 private:
  // Ensures that a type conversion does not trigger undefined behavior.
  template <typename Src>
  static constexpr T WellDefinedConversionOrZero(Src value, bool is_valid) {
    using SrcType = typename internal::UnderlyingType<Src>::type;
    return (std::is_integral<SrcType>::value || is_valid)
               ? static_cast<T>(value)
               : 0;
  }

  // is_valid_ precedes value_ because member intializers in the constructors
  // are evaluated in field order, and is_valid_ must be read when initializing
  // value_.
  bool is_valid_;
  T value_;
};

// Floating points maintain their own validity, but need translation wrappers.
template <typename T>
class CheckedNumericState<T, NUMERIC_FLOATING> {
 public:
  template <typename Src = double>
  constexpr explicit CheckedNumericState(Src value = 0.0, bool is_valid = true)
      : value_(WellDefinedConversionOrNaN(
            value,
            is_valid && IsValueInRangeForNumericType<T>(value))) {}

  template <typename Src>
  constexpr CheckedNumericState(const CheckedNumericState<Src>& rhs)
      : CheckedNumericState(rhs.value(), rhs.is_valid()) {}

  constexpr bool is_valid() const {
    // Written this way because std::isfinite is not reliably constexpr.
    return MustTreatAsConstexpr(value_)
               ? value_ <= std::numeric_limits<T>::max() &&
                     value_ >= std::numeric_limits<T>::lowest()
               : std::isfinite(value_);
  }

  constexpr T value() const { return value_; }

 private:
  // Ensures that a type conversion does not trigger undefined behavior.
  template <typename Src>
  static constexpr T WellDefinedConversionOrNaN(Src value, bool is_valid) {
    using SrcType = typename internal::UnderlyingType<Src>::type;
    return (StaticDstRangeRelationToSrcRange<T, SrcType>::value ==
                NUMERIC_RANGE_CONTAINED ||
            is_valid)
               ? static_cast<T>(value)
               : std::numeric_limits<T>::quiet_NaN();
  }

  T value_;
};

}  // namespace internal
}  // namespace base

#endif  // BASE_NUMERICS_CHECKED_MATH_IMPL_H_


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../otp_doc.css" type="text/css">
<title>Erlang -- Records</title>

User's Guide
PDF
Top
Programming Examples
User's Guide
Version 7.3

Expand All
Contract All
Chapters

Records

              Top of chapter

Records and Tuples

Defining a Record

Creating a Record

Accessing a Record Field

Updating a Record

Type Testing

Pattern Matching

Nested Records

A Longer Example

Funs

              Top of chapter

map

foreach

Syntax of Funs

Variable Bindings Within a Fun

Funs and Module Lists

Funs Returning Funs

List Comprehensions

              Top of chapter

Simple Examples

Quick Sort

Permutations

Pythagorean Triplets

Simplifications With List Comprehensions

Variable Bindings in List Comprehensions

Bit Syntax

              Top of chapter

Introduction

Lexical Note

Segments

Defaults

Constructing Binaries and Bitstrings

Matching Binaries

Appending to a Binary

1 Records

1.1
        Records and Tuples

The main advantage of using records rather than tuples is that
      fields in a record are accessed by name, whereas fields in a
      tuple are accessed by position. To illustrate these differences,
      suppose that you want to represent a person with the tuple
      {Name, Address, Phone}.

To write functions that manipulate this data, remember the following:

The Name field is the first element of the tuple.

The Address field is the second element.

The Phone field is the third element.

For example, to extract data from a variable P
      that contains such a tuple, you can write the following code
      and then use pattern matching to extract the relevant fields:

Name = element(1, P),
Address = element(2, P),
...

Such code is difficult to read and understand, and errors
      occur if the numbering of the elements in the tuple is wrong.
      If the data representation of the fields is changed, by re-ordering,
      adding, or removing fields, all references to
      the person tuple must be checked and possibly modified.

Records allow references to the fields by name, instead of by
      position. In the following example, a record instead of a tuple
      is used to store the data:

-record(person, {name, phone, address}).

This enables references to the fields of the record by name.
    For example, if P is a variable whose value is a
      person record, the following code access
      the name and address fields of the records:

Name = P#person.name,
Address = P#person.address,
...

Internally, records are represented using tagged tuples:

{person, Name, Phone, Address}

1.2
        Defining a Record

This following definition of a person is used in several
      examples in this section. Three fields are included, name,
      phone, and address. The default values for
      name and phone is "" and [], respectively.
      The default value for address is the atom
      undefined, since no default value is supplied for this
      field:

-record(person, {name = "", phone = [], address}).

The record must be defined in the shell to enable
      use of the record syntax in the examples:

> rd(person, {name = "", phone = [], address}).
person

This is because record definitions are only available
      at compile time, not at runtime. For details on records
      in the shell, see the
      shell(3)
      manual page in stdlib.

1.3
        Creating a Record

A new person record is created as follows:

> #person{phone=[0,8,2,3,4,3,1,2], name="Robert"}.
#person{name = "Robert",phone = [0,8,2,3,4,3,1,2],address = undefined}

As the address field was omitted, its default value
      is used.

From Erlang 5.1/OTP R8B, a value to all
      fields in a record can be set with the special field _.
      _ means "all fields not explicitly specified".

Example:

> #person{name = "Jakob", _ = '_'}.
#person{name = "Jakob",phone = '_',address = '_'}

It is primarily intended to be used in ets:match/2 and
      mnesia:match_object/3, to set record fields to the atom
      '_'. (This is a wildcard in ets:match/2.)

1.4
        Accessing a Record Field

The following example shows how to access a record field:

> P = #person{name = "Joe", phone = [0,8,2,3,4,3,1,2]}.
#person{name = "Joe",phone = [0,8,2,3,4,3,1,2],address = undefined}
> P#person.name.
"Joe"

1.5
        Updating a Record

The following example shows how to update a record:

> P1 = #person{name="Joe", phone=[1,2,3], address="A street"}.
#person{name = "Joe",phone = [1,2,3],address = "A street"}
> P2 = P1#person{name="Robert"}.
#person{name = "Robert",phone = [1,2,3],address = "A street"}

1.6
        Type Testing

The following example shows that the guard succeeds if
      P is record of type person:

foo(P) when is_record(P, person) -> a_person;
foo(_) -> not_a_person.

1.7
        Pattern Matching

Matching can be used in combination with records, as shown in
      the following example:

> P3 = #person{name="Joe", phone=[0,0,7], address="A street"}.
#person{name = "Joe",phone = [0,0,7],address = "A street"}
> #person{name = Name} = P3, Name.
"Joe"

The following function takes a list of person records
      and searches for the phone number of a person with a particular
      name:

find_phone([#person{name=Name, phone=Phone} | _], Name) ->
    {found,  Phone};
find_phone([_| T], Name) ->
    find_phone(T, Name);
find_phone([], Name) ->
    not_found.

The fields referred to in the pattern can be given in any order.

1.8
        Nested Records

The value of a field in a record can be an instance of a
      record. Retrieval of nested data can be done stepwise, or in a
      single step, as shown in the following example:

-record(name, {first = "Robert", last = "Ericsson"}).
-record(person, {name = #name{}, phone}).

demo() ->
  P = #person{name= #name{first="Robert",last="Virding"}, phone=123},
  First = (P#person.name)#name.first.

Here, demo() evaluates to "Robert".

1.9
        A Longer Example

Comments are embedded in the following example:

%% File: person.hrl

%%-----------------------------------------------------------
%% Data Type: person
%% where:
%%    name:  A string (default is undefined).
%%    age:   An integer (default is undefined).
%%    phone: A list of integers (default is []).
%%    dict:  A dictionary containing various information
%%           about the person.
%%           A {Key, Value} list (default is the empty list).
%%------------------------------------------------------------
-record(person, {name, age, phone = [], dict = []}).

-module(person).
-include("person.hrl").
-compile(export_all). % For test purposes only.

%% This creates an instance of a person.
%%   Note: The phone number is not supplied so the
%%         default value [] will be used.

make_hacker_without_phone(Name, Age) ->
   #person{name = Name, age = Age,
           dict = [{computer_knowledge, excellent},
                   {drinks, coke}]}.

%% This demonstrates matching in arguments

print(#person{name = Name, age = Age,
              phone = Phone, dict = Dict}) ->
  io:format("Name: ~s, Age: ~w, Phone: ~w ~n"
            "Dictionary: ~w.~n", [Name, Age, Phone, Dict]).

%% Demonstrates type testing, selector, updating.

birthday(P) when record(P, person) ->
   P#person{age = P#person.age + 1}.

register_two_hackers() ->
   Hacker1 = make_hacker_without_phone("Joe", 29),
   OldHacker = birthday(Hacker1),
   % The central_register_server should have
   % an interface function for this.
   central_register_server ! {register_person, Hacker1},
   central_register_server ! {register_person,
             OldHacker#person{name = "Robert",
                              phone = [0,8,3,2,4,5,3,1]}}.

Copyright © 2003-2016 Ericsson AB. All Rights Reserved.

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'

import CloseSvg from '../svgs/close.svg'

export const MoNav = ({ isOpenMobile, children, close }) => (

    Menu
    {children}
    <button
      onClick={close}
      className='mo-nav__close'
    >
      <CloseSvg />
    </button>

)

MoNav.propTypes = {
  isOpenMobile: PropTypes.bool,
  children: PropTypes.node,
  close: PropTypes.func
}


text:
package June.week5;

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

/**
 * Created by Alex_Xie on 29/06/2017.
 Given a digit string, return all possible letter combinations that the number could represent.
 A mapping of digit to letters (just like on the telephone buttons) is given below.

 Input:Digit string "23"
 Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
 Note:
 Although the above answer is in lexicographical order, your answer could be in any order you want.

 https://leetcode.com/problems/letter-combinations-of-a-phone-number/#/description
 */
public class LetterCombinations {
    private static final String[] KEYS = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<>();
        if (digits == null || digits.length() == 0) {
            return result;
        }

        combination("", digits, 0, result);

        return result;
    }

    private void combination(String prefix, String digits, int offset, List<String> result) {
        if (offset >= digits.length()) {
            result.add(prefix);
            return;
        }

        String letters = KEYS[digits.charAt(offset) - '0'];
        for (int i = 0; i < letters.length(); i++) {
            char letter = letters.charAt(i);
            combination(prefix + letter, digits, offset + 1, result);
        }
    }

/**
 public List<String> letterCombinations(String digits) {
 List<String> res = new ArrayList<>();
 if (digits == null || digits.length() == 0) return res;
 StringBuilder sb = new StringBuilder();
 combine(res, digits, sb, 0);
 return res;
 }

 private void combine(List<String> res, String digits, StringBuilder sb, int posn) {
 if (posn == digits.length()) {
 res.add(sb.toString());
 return;
 }
 String letters = KEYS[digits.charAt(posn) - '0'];
 for (int i = 0; i < letters.length(); i++) {
 int sbLen = sb.length();
 combine(res, digits, sb.append(letters.charAt(i)), posn+1);
 sb.setLength(sbLen);
 }
 }

* */

}


text:
weekly_roundup: true
date: "2013-11-22 15:38:00 UTC"
published: true
title: "Dev News for Friday"
authors:
  - "Grant Speelman"
tags:
  - Rails
  - Agile
  - Lean
---

## A controversial opinion - [Murray](/people#murray-steele)

Flying in face of the dogma spouted by the so-called "XP" and "Agile" throught-leaders, [Pat Maddox](http://patmaddox.com/) bravely provides a convincing blog post about [why *not* to pair](http://patmaddox.com/2013/11/21/why-not-to-pair/).

## useful for integrating accessibility testing - Tom Russell

released by our friends at Nature Publishing Group: http://pa11y.org/

## bridge between campfire and your IRC client - Tom Russell

https://github.com/zerowidth/camper_van

A bridge between campfire and your IRC client, if you hate all the GUI clients available :)

## Noduino - Andy M

[http://semu.github.io/noduino/](http://semu.github.io/noduino/)

I've finally looked at buying myself an arduino this week for some interactive stuff around my house, but I would rather not deal with the learning curve invovled in getting something basic up and running. Noduino offers a node framework for accessing basic Arduino controls from familiar web interfaces.

## Ruby 2.1.0-preview1 released - Andy M

[https://www.ruby-lang.org/en/news/2013/09/23/ruby-2-1-0-preview1-is-released/](https://www.ruby-lang.org/en/news/2013/09/23/ruby-2-1-0-preview1-is-released/)

Ruby 2.1.0-preview1 has been released this week. Beware of following vulnerability though! [https://www.ruby-lang.org/en/news/2013/11/22/heap-overflow-in-floating-point-parsing-cve-2013-4164/](https://www.ruby-lang.org/en/news/2013/11/22/heap-overflow-in-floating-point-parsing-cve-2013-4164/)

## Hacking your home with Ruby - Andy M

[http://www.youtube.com/watch?v=BeyTsdkItg4](http://www.youtube.com/watch?v=BeyTsdkItg4)

Following on from my other post here is some more cool stuff around hacking the home with Ruby. As you may have guessed, I just moved house. Let's see how tech we can make it!


text:
/*
Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.26
Mocha integration test from: microformats-v1/geo/abbrpattern
The test was built on Wed May 25 2016 10:23:15 GMT+0100 (BST)
*/

assert = chai.assert;

describe('geo', function() {
   var htmlFragment = "<meta charset=\"utf-8\">\n
\n N 37° 24.491,  \n W 122° 08.313\n
";
   var expected = {"items":[{"type":["h-geo"],"properties":{"latitude":["37.408183"],"longitude":["-122.13855"]}}],"rels":{},"rel-urls":{}};

   it('abbrpattern', function(){
       var doc, dom, node, options, parser, found;
       dom = new DOMParser();
       doc = dom.parseFromString( htmlFragment, 'text/html' );
       options ={
       		'document': doc,
       		'node': doc,
       		'baseUrl': 'http://example.com',
       		'dateFormat': 'html5'
       };
       found = Microformats.get( options );
       assert.deepEqual(found, expected);
   });
});


text:
package com.tikinou.schedulesdirect.core.commands.lineup;

import com.tikinou.schedulesdirect.core.HttpMethod;

/**
 * @author Sebastien Astie
 */
public abstract class AbstractAddLineupCommand extends AbstractLineupManagementCommand {
    public AbstractAddLineupCommand() {
        super(HttpMethod.PUT);
    }
}


text: body{color:red}a{color:blue}body{color:red}p{color:green}


text:
<?php

declare(strict_types=1);

namespace ColissimoPostage\StructType;

use InvalidArgumentException;
use WsdlToPhp\PackageBase\AbstractStructBase;

/**
 * This class stands for GetListMailBoxPickingDatesResponseType StructType
 * @subpackage Structs
 * @author WsdlToPhp <contact@wsdltophp.com>
 */
class GetListMailBoxPickingDatesResponseType extends BaseResponse
{
    /**
     * The mailBoxPickingDateMaxHour
     * Meta information extracted from the WSDL
     * - minOccurs: 0
     * @var string|null
     */
    protected ?string $mailBoxPickingDateMaxHour = null;
    /**
     * The mailBoxPickingDates
     * Meta information extracted from the WSDL
     * - maxOccurs: unbounded
     * - minOccurs: 0
     * - nillable: true
     * @var string[]
     */
    protected ?array $mailBoxPickingDates = null;
    /**
     * The validityTime
     * Meta information extracted from the WSDL
     * - minOccurs: 0
     * @var string|null
     */
    protected ?string $validityTime = null;
    /**
     * Constructor method for GetListMailBoxPickingDatesResponseType
     * @uses GetListMailBoxPickingDatesResponseType::setMailBoxPickingDateMaxHour()
     * @uses GetListMailBoxPickingDatesResponseType::setMailBoxPickingDates()
     * @uses GetListMailBoxPickingDatesResponseType::setValidityTime()
     * @param string $mailBoxPickingDateMaxHour
     * @param string[] $mailBoxPickingDates
     * @param string $validityTime
     */
    public function __construct(?string $mailBoxPickingDateMaxHour = null, ?array $mailBoxPickingDates = null, ?string $validityTime = null)
    {
        $this
            ->setMailBoxPickingDateMaxHour($mailBoxPickingDateMaxHour)
            ->setMailBoxPickingDates($mailBoxPickingDates)
            ->setValidityTime($validityTime);
    }
    /**
     * Get mailBoxPickingDateMaxHour value
     * @return string|null
     */
    public function getMailBoxPickingDateMaxHour(): ?string
    {
        return $this->mailBoxPickingDateMaxHour;
    }
    /**
     * Set mailBoxPickingDateMaxHour value
     * @param string $mailBoxPickingDateMaxHour
     * @return \ColissimoPostage\StructType\GetListMailBoxPickingDatesResponseType
     */
    public function setMailBoxPickingDateMaxHour(?string $mailBoxPickingDateMaxHour = null): self
    {
        // validation for constraint: string
        if (!is_null($mailBoxPickingDateMaxHour) && !is_string($mailBoxPickingDateMaxHour)) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($mailBoxPickingDateMaxHour, true), gettype($mailBoxPickingDateMaxHour)), __LINE__);
        }
        $this->mailBoxPickingDateMaxHour = $mailBoxPickingDateMaxHour;

        return $this;
    }
    /**
     * Get mailBoxPickingDates value
     * An additional test has been added (isset) before returning the property value as
     * this property may have been unset before, due to the fact that this property is
     * removable from the request (nillable=true+minOccurs=0)
     * @return string[]
     */
    public function getMailBoxPickingDates(): ?array
    {
        return isset($this->mailBoxPickingDates) ? $this->mailBoxPickingDates : null;
    }
    /**
     * This method is responsible for validating the values passed to the setMailBoxPickingDates method
     * This method is willingly generated in order to preserve the one-line inline validation within the setMailBoxPickingDates method
     * @param array $values
     * @return string A non-empty message if the values does not match the validation rules
     */
    public static function validateMailBoxPickingDatesForArrayConstraintsFromSetMailBoxPickingDates(?array $values = []): string
    {
        if (!is_array($values)) {
            return '';
        }
        $message = '';
        $invalidValues = [];
        foreach ($values as $getListMailBoxPickingDatesResponseTypeMailBoxPickingDatesItem) {
            // validation for constraint: itemType
            if (!is_string($getListMailBoxPickingDatesResponseTypeMailBoxPickingDatesItem)) {
                $invalidValues[] = is_object($getListMailBoxPickingDatesResponseTypeMailBoxPickingDatesItem) ? get_class($getListMailBoxPickingDatesResponseTypeMailBoxPickingDatesItem) : sprintf('%s(%s)', gettype($getListMailBoxPickingDatesResponseTypeMailBoxPickingDatesItem), var_export($getListMailBoxPickingDatesResponseTypeMailBoxPickingDatesItem, true));
            }
        }
        if (!empty($invalidValues)) {
            $message = sprintf('The mailBoxPickingDates property can only contain items of type string, %s given', is_object($invalidValues) ? get_class($invalidValues) : (is_array($invalidValues) ? implode(', ', $invalidValues) : gettype($invalidValues)));
        }
        unset($invalidValues);

        return $message;
    }
    /**
     * Set mailBoxPickingDates value
     * This property is removable from request (nillable=true+minOccurs=0), therefore
     * if the value assigned to this property is null, it is removed from this object
     * @throws InvalidArgumentException
     * @param string[] $mailBoxPickingDates
     * @return \ColissimoPostage\StructType\GetListMailBoxPickingDatesResponseType
     */
    public function setMailBoxPickingDates(?array $mailBoxPickingDates = null): self
    {
        // validation for constraint: array
        if ('' !== ($mailBoxPickingDatesArrayErrorMessage = self::validateMailBoxPickingDatesForArrayConstraintsFromSetMailBoxPickingDates($mailBoxPickingDates))) {
            throw new InvalidArgumentException($mailBoxPickingDatesArrayErrorMessage, __LINE__);
        }
        if (is_null($mailBoxPickingDates) || (is_array($mailBoxPickingDates) && empty($mailBoxPickingDates))) {
            unset($this->mailBoxPickingDates);
        } else {
            $this->mailBoxPickingDates = $mailBoxPickingDates;
        }

        return $this;
    }
    /**
     * Add item to mailBoxPickingDates value
     * @throws InvalidArgumentException
     * @param string $item
     * @return \ColissimoPostage\StructType\GetListMailBoxPickingDatesResponseType
     */
    public function addToMailBoxPickingDates(string $item): self
    {
        // validation for constraint: itemType
        if (!is_string($item)) {
            throw new InvalidArgumentException(sprintf('The mailBoxPickingDates property can only contain items of type string, %s given', is_object($item) ? get_class($item) : (is_array($item) ? implode(', ', $item) : gettype($item))), __LINE__);
        }
        $this->mailBoxPickingDates[] = $item;

        return $this;
    }
    /**
     * Get validityTime value
     * @return string|null
     */
    public function getValidityTime(): ?string
    {
        return $this->validityTime;
    }
    /**
     * Set validityTime value
     * @param string $validityTime
     * @return \ColissimoPostage\StructType\GetListMailBoxPickingDatesResponseType
     */
    public function setValidityTime(?string $validityTime = null): self
    {
        // validation for constraint: string
        if (!is_null($validityTime) && !is_string($validityTime)) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($validityTime, true), gettype($validityTime)), __LINE__);
        }
        $this->validityTime = $validityTime;

        return $this;
    }
}


text:
package vortex.scripts;

import cern.colt.matrix.impl.DenseDoubleMatrix2D;
import cern.colt.matrix.linalg.Algebra;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Calendar;
import sandbox.clustering.Dataset;
import util.Correlation;
import util.MatrixOp;
import vortex.util.Config;
import vortex.util.ConnectionManager;

/**
 *
 * @author Nikolay
 */
public class CorrelMtxForZach {
    static String[] dsNames = new String[]{
        "Cy",
        "Hu",
        "Rh"};

    public static void main(String[] args) throws SQLException, IOException {
        do {

            if (Config.getDefaultDatabaseHost() == null) {
                ConnectionManager.showDlgSelectDatabaseHost();
            }
            if (Config.getDefaultDatabaseHost() == null) {
                System.exit(0);
            }
            ConnectionManager.setDatabaseHost(Config.getDefaultDatabaseHost());

        } while (ConnectionManager.getDatabaseHost() == null);

        for (int i = 0; i < dsNames.length; i++) {
            String dsName = dsNames[i];
            Dataset ds = ConnectionManager.getStorageEngine().loadDataset(dsName);
             double[][] vec = Algebra.DEFAULT.transpose(new DenseDoubleMatrix2D(getVectors(ds))).toArray();
             DenseDoubleMatrix2D corr = new DenseDoubleMatrix2D(vec.length, vec.length);

             long time = Calendar.getInstance().getTimeInMillis();
             System.out.println();
             for (int j = 0; j < vec.length; j++) {
                 for (int k = j; k < vec.length; k++) {
                     if(k==j){
                         corr.set(j, k, 1);
                         continue;
                     }
                     double c = Correlation.getUncenteredCorrelation(vec[j], vec[k]);
                     corr.set(j, k, c);
                     corr.set(k, j, c);
                 }
            }
             System.out.println(Calendar.getInstance().getTimeInMillis()-time);
             System.out.println(ds.getName());
             System.out.println(Arrays.toString(ds.getFeatureNamesCombined()));
             System.out.println(corr);
        }
    }

    public static double[][] getVectors(Dataset ds){
    double[][] res = new double[ds.getDatapoints().length][];
        for (int i = 0; i < res.length; i++) {
           res[i]= MatrixOp.concat(ds.getDatapoints()[i].getVector(), ds.getDatapoints()[i].getSideVector());
        }
        return res;
    }

}


text:
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import {stateName as chromeStateName} from 'chrome/state';
import {breadcrumbsConfig} from 'common/components/breadcrumbs/service';
import {stateName as workloadsStateName} from 'workloads/state';

import {stateUrl} from './../state';
import {ReplicaSetListController} from './controller';

/**
 * I18n object that defines strings for translation used in this file.
 */
const i18n = {
  /** @type {string} @desc Label 'Replica Sets' that appears as a breadcrumbs on the action bar. */
  MSG_BREADCRUMBS_REPLICA_SETS_LABEL: goog.getMsg('Replica Sets'),
};

/**
 * Config state object for the Replica Set list view.
 *
 * @type {!ui.router.StateConfig}
 */
export const config = {
  url: stateUrl,
  parent: chromeStateName,
  resolve: {
    'replicaSetList': resolveReplicaSetList,
  },
  data: {
    [breadcrumbsConfig]: {
      'label': i18n.MSG_BREADCRUMBS_REPLICA_SETS_LABEL,
      'parent': workloadsStateName,
    },
  },
  views: {
    '': {
      controller: ReplicaSetListController,
      controllerAs: '$ctrl',
      templateUrl: 'replicaset/list/list.html',
    },
  },
};

/**
 * @param {!angular.$resource} $resource
 * @return {!angular.Resource}
 * @ngInject
 */
export function replicaSetListResource($resource) {
  return $resource('api/v1/replicaset/:namespace');
}

/**
 * @param {!angular.Resource} kdReplicaSetListResource
 * @param {!./../../chrome/state.StateParams} $stateParams
 * @param {!./../../common/pagination/service.PaginationService} kdPaginationService
 * @return {!angular.$q.Promise}
 * @ngInject
 */
export function resolveReplicaSetList(kdReplicaSetListResource, $stateParams, kdPaginationService) {
  let query = kdPaginationService.getDefaultResourceQuery($stateParams.namespace);
  return kdReplicaSetListResource.get(query).$promise;
}


text:
Return the Cortex XSOAR server version.

## Script Data
---

| **Name** | **Description** |
| --- | --- |
| Script Type | python3 |
| Cortex XSOAR Version | 5.0.0 |

## Inputs
---
There are no inputs for this script.

## Outputs
---

| **Path** | **Description** | **Type** |
| --- | --- | --- |
| DemistoVersion.version | The version of the Cortex XSOAR server. | string |
| DemistoVersion.buildNumber | The build number of the Cortex XSOAR server. | string |


text:
<#
.SYNOPSIS
    Enables Dynatrace .NET agent.
.DESCRIPTION
    Checks if Dynatrace .NET agent is already configured.
    If yes it rewrites it's configuration.
    If there's already 3rd party .NET profiler configured, Dynatrace .NET agent installation is skipped.
.PARAMETER DTHOME
    "root" directory of the Dynatrace agent's. Agent DLL's are referenced relative from this directory <DTHOME>\agent\lib\dtagent.dll
.PARAMETER AgentName
    Agent's name as shown in Dynatrace
.PARAMETER CollectorIP
    <HostnameOrIP>[:Port]
.PARAMETER Use64Bit
    Boolean value to force usage of 64-bit agent
.PARAMETER ProcessEngine
    JSON string array of processes to whitelist. Optionally supports process arguments. e.g. "w3wp.exe -ap \"<ProcessEngine>\""
.NOTE
    NOTE: If NO processes are whitelisted, agent instruments ALL .NET processes when they are started!
#>
[CmdletBinding()]
param(
	#[Parameter(Mandatory=$True)]
	#[string]$ProcesseEngineName,

	[Parameter(Mandatory=$True)]
	[string]$DTHOME,

    [Switch]$Use64Bit,

    [Parameter(Mandatory=$True)]
    [string] $CollectorIP,

	[Parameter(Mandatory=$True)]
	[string]$AgentName,

	[Parameter(Mandatory=$True)]
    [string] $ProcessEngine  ### check on process engine name  [ "PT001.exe -ap \"myDotNet\"" ]'

)

Write-Host "-----------------------------------------------------------------" -ForegroundColor green
Write-Host "--              Dynatrace LLC                                  --" -ForegroundColor green
Write-Host "--              Hao-lin Liang                             --" -ForegroundColor green
Write-Host "-----------------------------------------------------------------" -ForegroundColor green

Write-Host "Set-ExecutionPolicy..."
# Set-ExecutionPolicy Unrestricted
Set-ExecutionPolicy "RemoteSigned" -Scope Process -Confirm:$false
Set-ExecutionPolicy "RemoteSigned" -Scope CurrentUser -Confirm:$false
Write-Host "Ready to run the script if no error." -ForegroundColor green

Write-Host "Collector IP is $CollectorIP"

Write-Host "Install dir is $DTHOME"

$processEngineString = '[ "w3wp.exe -ap ' + '\"' +$ProcessEngine+'\"" ]'

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

Write-Host = "Execution Path of the script is : " $scriptPath

$FilePath = $scriptPath + '\InstallDotNetAgent.ps1'

#.\InstallDotNetAgent.ps1 $DTHOME '$AgentName' '$CollectorIP' -Use64Bit '[ "w3wp.exe -ap \"$ProcessEngine\""]'

& FilePath $DTHOME $AgentName $CollectorIP -Use64Bit $processEngineString

iisreset


text:
DyConf [![Build Status](https://travis-ci.org/gow/dyconf.svg?branch=master)](https://travis-ci.org/gow/dyconf) [![Coverage Status](https://coveralls.io/repos/gow/dyconf/badge.svg?branch=master&service=github)](https://coveralls.io/github/gow/dyconf?branch=master)  [![GoDoc](https://godoc.org/github.com/gow/dyconf?status.svg)](https://godoc.org/github.com/gow/dyconf)
====

A dynamic configuration tool written in go.
Will add more details here.


text:
require 'spec_helper'

describe "sys_db", type: :feature, dbscope: :example do
  let(:index_path) { sys_db_colls_path }

  it "without auth" do
    login_ss_user
    visit index_path
    expect(status_code).to eq 403
  end

  context "with auth" do
    before { login_sys_user }

    it "#index" do
      visit index_path
      expect(status_code).to eq 200
      expect(current_path).not_to eq sns_login_path
    end
  end
end


text:
package com.link_intersystems.swing;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashSet;
import java.util.Set;

import javax.swing.Action;

public class ListModelSelectionMediator<E> {

	private SelectionModel<? extends E> selectionModel;

	private class ListModelSelectionListener implements PropertyChangeListener {

		@SuppressWarnings("unchecked")
		@Override
		public void propertyChange(PropertyChangeEvent evt) {
			if (ListModelSelection.PROP_SELECTION.equals(evt.getPropertyName())) {
				SelectionModel<E> source = (SelectionModel<E>) evt.getSource();
				ListModelSelectionMediator.this
						.handleListModelSelectionUpdate(source);
			}
		}

	}

	private ListModelSelectionListener listModelSelectionListener = new ListModelSelectionListener();
	private Set<Action> disabledOnEmptySelection = new HashSet<Action>();

	public ListModelSelectionMediator() {
	}

	public void setSelectionModel(SelectionModel<? extends E> selectionModel) {
		if (this.selectionModel != null) {
			this.selectionModel
					.removePropertyChangeListener(listModelSelectionListener);
		}
		this.selectionModel = selectionModel;
		if (this.selectionModel != null) {
			this.selectionModel
					.addPropertyChangeListener(listModelSelectionListener);
		}

	}

	public void addDisabledActionOnEmptySelection(Action action) {
		disabledOnEmptySelection.add(action);
		if (selectionModel != null) {
			handleListModelSelectionUpdate(selectionModel);
		}
	}

	private void handleListModelSelectionUpdate(
			SelectionModel<? extends E> selectionModel) {

		for (Action action : disabledOnEmptySelection) {
			action.setEnabled(!selectionModel.isEmpty());
		}
	}
}


text:
/**
 * Autogenerated by Thrift Compiler (0.9.1)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.curator.generated;

import java.util.Map;
import java.util.HashMap;
import org.apache.thrift.TEnum;

public enum ZooKeeperExceptionType implements org.apache.thrift.TEnum {
  SYSTEMERROR(0),
  RUNTIMEINCONSISTENCY(1),
  DATAINCONSISTENCY(2),
  CONNECTIONLOSS(3),
  MARSHALLINGERROR(4),
  UNIMPLEMENTED(5),
  OPERATIONTIMEOUT(6),
  BADARGUMENTS(7),
  APIERROR(8),
  NOAUTH(9),
  NOCHILDRENFOREPHEMERALS(10),
  INVALIDACL(11),
  AUTHFAILED(12),
  SESSIONEXPIRED(13),
  INVALIDCALLBACK(14),
  SESSIONMOVED(15),
  NOTREADONLY(16);

  private final int value;

  private ZooKeeperExceptionType(int value) {
    this.value = value;
  }

  /**
   * Get the integer value of this enum value, as defined in the Thrift IDL.
   */
  public int getValue() {
    return value;
  }

  /**
   * Find a the enum type by its integer value, as defined in the Thrift IDL.
   * @return null if the value is not found.
   */
  public static ZooKeeperExceptionType findByValue(int value) {
    switch (value) {
      case 0:
        return SYSTEMERROR;
      case 1:
        return RUNTIMEINCONSISTENCY;
      case 2:
        return DATAINCONSISTENCY;
      case 3:
        return CONNECTIONLOSS;
      case 4:
        return MARSHALLINGERROR;
      case 5:
        return UNIMPLEMENTED;
      case 6:
        return OPERATIONTIMEOUT;
      case 7:
        return BADARGUMENTS;
      case 8:
        return APIERROR;
      case 9:
        return NOAUTH;
      case 10:
        return NOCHILDRENFOREPHEMERALS;
      case 11:
        return INVALIDACL;
      case 12:
        return AUTHFAILED;
      case 13:
        return SESSIONEXPIRED;
      case 14:
        return INVALIDCALLBACK;
      case 15:
        return SESSIONMOVED;
      case 16:
        return NOTREADONLY;
      default:
        return null;
    }
  }
}


text:
package challenge18

import (
	"bytes"

	"github.com/stripedpajamas/cryptopals/set1/challenge7"
)

func IncrementCounter(target []byte, endian string) []byte {
	var i int
	if endian == "little" {
		// little endian
		for i = 0; i < len(target) && target[i] == 255; i++ {
			target[i] = 0
		}
	} else if endian == "big" {
		// big endian
		for i = len(target) - 1; i >= 0 && target[i] == 255; i-- {
			target[i] = 0
		}
	}
	if ^i != 0 {
		target[i]++
	}

	return target
}

func CTR(input, key, nonce []byte) []byte {
	// this CTR implementation is for 16 byte blocks
	// ala cryptopals challenges

	inputLen := len(input)
	output := make([]byte, inputLen)

	counter := []byte{0, 0, 0, 0, 0, 0, 0, 0}

	var keystream, inputBuff bytes.Buffer

	// initialize buffers
	inputBuff.Write(input)
	keystream.Write(challenge7.ECBEncrypter(append(nonce, counter...), key))

	for i := 0; i < inputLen; i++ {
		in, err := inputBuff.ReadByte()
		if err != nil {
			panic(err)
		}
		// if we run out of keystream, refill
		if keystream.Len() == 0 {
			// we increment counter during refill because the keystream is always 16 bytes
			// which means when we run out it's because we're at the next "block"
			counter = IncrementCounter(counter, "little")
			keystream.Write(challenge7.ECBEncrypter(append(nonce, counter...), key))
		}
		ks, err := keystream.ReadByte()
		if err != nil {
			panic(err)
		}

		// output is input byte xored with keystream byte
		output[i] = in ^ ks
	}

	return output
}


text:
package org.elasticsearch.search.sort.xnumeric;

import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.search.FieldComparator;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.FieldCache.Floats;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.plain.xnumeric.xfloat.XFloatIndexFieldData;
import org.elasticsearch.index.fielddata.plain.xnumeric.xfloat.MultiXFloatValues;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.search.sort.SortParser;

import java.io.IOException;
import java.util.BitSet;

public class XFloatSortParser implements SortParser {

    @Override
    public String[] names() {
        return new String[] { "_xfloat" };
    }

    @Override
    public SortField parse(XContentParser parser, SearchContext context) throws Exception {
        String fieldName = null;
        boolean reverse = false;
        final BitSet bitSet = new BitSet();

        XContentParser.Token token;
        String currentName = parser.currentName();
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentName = parser.currentName();
            } else if (token == XContentParser.Token.START_ARRAY) {
                while (!parser.nextToken().equals(XContentParser.Token.END_ARRAY)) {
                    if (parser.currentToken() == XContentParser.Token.VALUE_NUMBER) {
                        bitSet.set(parser.intValue());
                    }
                }
                fieldName = currentName;
            } else if (token.isValue()) {
                if ("reverse".equals(currentName)) {
                    reverse = parser.booleanValue();
                } else if ("order".equals(currentName)) {
                    reverse = "desc".equals(parser.text());
                } else {
                    fieldName = currentName;
                }
            }
        }

        FieldMapper<?> mapper = context.smartNameFieldMapper(fieldName);
        if (mapper == null) {
            throw new ElasticsearchIllegalArgumentException("failed to find mapper for [" + fieldName + "] for geo distance based sort");
        }

        final XFloatIndexFieldData fieldData = context.fieldData().getForField(mapper);

        IndexFieldData.XFieldComparatorSource comparatorSource = new IndexFieldData.XFieldComparatorSource() {

            @Override
            public SortField.Type reducedType() {
                return SortField.Type.FLOAT;
            }

            @Override
            public FieldComparator<?> newComparator(String fieldname, int numHits, int sortPos, boolean reversed) throws IOException {
                return new FieldComparator.FloatComparator(numHits, null, null, null) {

                    @Override
                    protected Floats getFloatValues(AtomicReaderContext context, String field) throws IOException {
                        final MultiXFloatValues floatSetValues = fieldData.load(context).getValues();
                        final BitSet flags = bitSet;
                        return new Floats() {

                            @Override
                            public float get(int docID) {
                                floatSetValues.setDocument(docID);
                                return floatSetValues.valueAt(0).value(flags);
                            }
                        };
                    }
                };
            }

        };

        return new SortField(fieldName, comparatorSource, reverse);
    }
}


text:
import odml.tools.xmlparser as xml
import odml.tools.jsonparser as json

parsers = ["xml", "json"]

def load(filename, backend="xml"):
    if backend in parsers:
        if backend == "xml":
            return xml.load(filename)
        elif backend == "json":
            return json.JSONReader().fromFile(open(filename))
    else:
        raise ValueError("No such parser")

def save(obj, filename, backend="xml"):
    if backend in parsers:
        if backend == "xml":
            xml.XMLWriter(obj).write_file(filename)
        elif backend == "json":
            json.JSONWriter(obj).write_file(filename)
    else:
        raise ValueError("No such parser")

def display(obj, backend="xml"):
    if backend in parsers:
        if backend == "xml":
            print(str(xml.XMLWriter(obj)))
        elif backend == "json":
            print(str(json.JSONWriter(obj)))
    else:
        raise ValueError("No such parser")


text:
#pragma once
#include <aws/devicefarm/DeviceFarm_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/devicefarm/model/DevicePoolType.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/devicefarm/model/Rule.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace DeviceFarm
{
namespace Model
{

  /**
   *
Represents a collection of device types.

See Also:
   AWS
   * API Reference

   */
  class AWS_DEVICEFARM_API DevicePool
  {
  public:
    DevicePool();
    DevicePool(const Aws::Utils::Json::JsonValue& jsonValue);
    DevicePool& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The device pool's ARN.

     */
    inline const Aws::String& GetArn() const{ return m_arn; }

    /**
     *
The device pool's ARN.

     */
    inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; }

    /**
     *
The device pool's ARN.

     */
    inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); }

    /**
     *
The device pool's ARN.

     */
    inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); }

    /**
     *
The device pool's ARN.

     */
    inline DevicePool& WithArn(const Aws::String& value) { SetArn(value); return *this;}

    /**
     *
The device pool's ARN.

     */
    inline DevicePool& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}

    /**
     *
The device pool's ARN.

     */
    inline DevicePool& WithArn(const char* value) { SetArn(value); return *this;}

    /**
     *
The device pool's name.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
The device pool's name.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
The device pool's name.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
The device pool's name.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
The device pool's name.

     */
    inline DevicePool& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
The device pool's name.

     */
    inline DevicePool& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
The device pool's name.

     */
    inline DevicePool& WithName(const char* value) { SetName(value); return *this;}

    /**
     *
The device pool's description.

     */
    inline const Aws::String& GetDescription() const{ return m_description; }

    /**
     *
The device pool's description.

     */
    inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }

    /**
     *
The device pool's description.

     */
    inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }

    /**
     *
The device pool's description.

     */
    inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }

    /**
     *
The device pool's description.

     */
    inline DevicePool& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}

    /**
     *
The device pool's description.

     */
    inline DevicePool& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}

    /**
     *
The device pool's description.

     */
    inline DevicePool& WithDescription(const char* value) { SetDescription(value); return *this;}

    /**
     *
The device pool's type.

Allowed values include:

     *
CURATED: A device pool that is created and managed by AWS Device Farm.

     *

PRIVATE: A device pool that is created and managed by the device
     * pool developer.

     */
    inline const DevicePoolType& GetType() const{ return m_type; }

    /**
     *
The device pool's type.

Allowed values include:

     *
CURATED: A device pool that is created and managed by AWS Device Farm.

     *

PRIVATE: A device pool that is created and managed by the device
     * pool developer.

     */
    inline void SetType(const DevicePoolType& value) { m_typeHasBeenSet = true; m_type = value; }

    /**
     *
The device pool's type.

Allowed values include:

     *
CURATED: A device pool that is created and managed by AWS Device Farm.

     *

PRIVATE: A device pool that is created and managed by the device
     * pool developer.

     */
    inline void SetType(DevicePoolType&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }

    /**
     *
The device pool's type.

Allowed values include:

     *
CURATED: A device pool that is created and managed by AWS Device Farm.

     *

PRIVATE: A device pool that is created and managed by the device
     * pool developer.

     */
    inline DevicePool& WithType(const DevicePoolType& value) { SetType(value); return *this;}

    /**
     *
The device pool's type.

Allowed values include:

     *
CURATED: A device pool that is created and managed by AWS Device Farm.

     *

PRIVATE: A device pool that is created and managed by the device
     * pool developer.

     */
    inline DevicePool& WithType(DevicePoolType&& value) { SetType(std::move(value)); return *this;}

    /**
     *
Information about the device pool's rules.

     */
    inline const Aws::Vector<Rule>& GetRules() const{ return m_rules; }

    /**
     *
Information about the device pool's rules.

     */
    inline void SetRules(const Aws::Vector<Rule>& value) { m_rulesHasBeenSet = true; m_rules = value; }

    /**
     *
Information about the device pool's rules.

     */
    inline void SetRules(Aws::Vector<Rule>&& value) { m_rulesHasBeenSet = true; m_rules = std::move(value); }

    /**
     *
Information about the device pool's rules.

     */
    inline DevicePool& WithRules(const Aws::Vector<Rule>& value) { SetRules(value); return *this;}

    /**
     *
Information about the device pool's rules.

     */
    inline DevicePool& WithRules(Aws::Vector<Rule>&& value) { SetRules(std::move(value)); return *this;}

    /**
     *
Information about the device pool's rules.

     */
    inline DevicePool& AddRules(const Rule& value) { m_rulesHasBeenSet = true; m_rules.push_back(value); return *this; }

    /**
     *
Information about the device pool's rules.

     */
    inline DevicePool& AddRules(Rule&& value) { m_rulesHasBeenSet = true; m_rules.push_back(std::move(value)); return *this; }

  private:
    Aws::String m_arn;
    bool m_arnHasBeenSet;
    Aws::String m_name;
    bool m_nameHasBeenSet;
    Aws::String m_description;
    bool m_descriptionHasBeenSet;
    DevicePoolType m_type;
    bool m_typeHasBeenSet;
    Aws::Vector<Rule> m_rules;
    bool m_rulesHasBeenSet;
  };

} // namespace Model
} // namespace DeviceFarm
} // namespace Aws


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @constructor
 * @param {!WebInspector.CSSStyleDeclaration} ownerStyle
 * @param {number} index
 * @param {string} name
 * @param {string} value
 * @param {boolean} important
 * @param {boolean} disabled
 * @param {boolean} parsedOk
 * @param {boolean} implicit
 * @param {?string=} text
 * @param {!CSSAgent.SourceRange=} range
 */
WebInspector.CSSProperty = function(ownerStyle, index, name, value, important, disabled, parsedOk, implicit, text, range)
{
    this.ownerStyle = ownerStyle;
    this.index = index;
    this.name = name;
    this.value = value;
    this.important = important;
    this.disabled = disabled;
    this.parsedOk = parsedOk;
    this.implicit = implicit; // A longhand, implicitly set by missing values of shorthand.
    this.text = text;
    this.range = range ? WebInspector.TextRange.fromObject(range) : null;
    this._active = true;
    this._nameRange = null;
    this._valueRange = null;
}

/**
 * @param {!WebInspector.CSSStyleDeclaration} ownerStyle
 * @param {number} index
 * @param {!CSSAgent.CSSProperty} payload
 * @return {!WebInspector.CSSProperty}
 */
WebInspector.CSSProperty.parsePayload = function(ownerStyle, index, payload)
{
    // The following default field values are used in the payload:
    // important: false
    // parsedOk: true
    // implicit: false
    // disabled: false
    var result = new WebInspector.CSSProperty(
        ownerStyle, index, payload.name, payload.value, payload.important || false, payload.disabled || false, ("parsedOk" in payload) ? !!payload.parsedOk : true, !!payload.implicit, payload.text, payload.range);
    return result;
}

WebInspector.CSSProperty.prototype = {
    _ensureRanges: function()
    {
        if (this._nameRange && this._valueRange)
            return;
        var range = this.range;
        var text = this.text ? new WebInspector.Text(this.text) : null;
        if (!range || !text)
            return;

        var nameIndex = text.value().indexOf(this.name);
        var valueIndex = text.value().lastIndexOf(this.value);
        if (nameIndex === -1 || valueIndex === -1 || nameIndex > valueIndex)
            return;

        var nameSourceRange = new WebInspector.SourceRange(nameIndex, this.name.length);
        var valueSourceRange = new WebInspector.SourceRange(valueIndex, this.value.length);

        this._nameRange = rebase(text.toTextRange(nameSourceRange), range.startLine, range.startColumn);
        this._valueRange = rebase(text.toTextRange(valueSourceRange), range.startLine, range.startColumn);

        /**
         * @param {!WebInspector.TextRange} oneLineRange
         * @param {number} lineOffset
         * @param {number} columnOffset
         * @return {!WebInspector.TextRange}
         */
        function rebase(oneLineRange, lineOffset, columnOffset)
        {
            if (oneLineRange.startLine === 0) {
                oneLineRange.startColumn += columnOffset;
                oneLineRange.endColumn += columnOffset;
            }
            oneLineRange.startLine += lineOffset;
            oneLineRange.endLine += lineOffset;
            return oneLineRange;
        }
    },

    /**
     * @return {?WebInspector.TextRange}
     */
    nameRange: function()
    {
        this._ensureRanges();
        return this._nameRange;
    },

    /**
     * @return {?WebInspector.TextRange}
     */
    valueRange: function()
    {
        this._ensureRanges();
        return this._valueRange;
    },

    /**
     * @param {!WebInspector.CSSModel.Edit} edit
     */
    rebase: function(edit)
    {
        if (this.ownerStyle.styleSheetId !== edit.styleSheetId)
            return;
        if (this.range)
            this.range = this.range.rebaseAfterTextEdit(edit.oldRange, edit.newRange);
    },

    /**
     * @param {boolean} active
     */
    _setActive: function(active)
    {
        this._active = active;
    },

    get propertyText()
    {
        if (this.text !== undefined)
            return this.text;

        if (this.name === "")
            return "";
        return this.name + ": " + this.value + (this.important ? " !important" : "") + ";";
    },

    /**
     * @return {boolean}
     */
    activeInStyle: function()
    {
        return this._active;
    },

    /**
     * @param {string} propertyText
     * @param {boolean} majorChange
     * @param {boolean} overwrite
     * @return {!Promise.<boolean>}
     */
    setText: function(propertyText, majorChange, overwrite)
    {
        if (!this.ownerStyle)
            return Promise.reject(new Error("No ownerStyle for property"));

        if (!this.ownerStyle.styleSheetId)
            return Promise.reject(new Error("No owner style id"));

        if (!this.range || !this.ownerStyle.range)
            return Promise.reject(new Error("Style not editable"));

        if (majorChange)
            WebInspector.userMetrics.actionTaken(WebInspector.UserMetrics.Action.StyleRuleEdited);

        if (overwrite && propertyText === this.propertyText) {
            if (majorChange)
                this.ownerStyle.cssModel().domModel().markUndoableState();
            return Promise.resolve(true);
        }

        var range = this.range.relativeTo(this.ownerStyle.range.startLine, this.ownerStyle.range.startColumn);
        var indentation = this.ownerStyle.cssText ? this._detectIndentation(this.ownerStyle.cssText) : WebInspector.moduleSetting("textEditorIndent").get();
        var endIndentation = this.ownerStyle.cssText ? indentation.substring(0, this.ownerStyle.range.endColumn) : "";
        var text = new WebInspector.Text(this.ownerStyle.cssText || "");
        var newStyleText = text.replaceRange(range, String.sprintf(";%s;", propertyText));

        return self.runtime.instancePromise(WebInspector.TokenizerFactory)
            .then(this._formatStyle.bind(this, newStyleText, indentation, endIndentation))
            .then(setStyleText.bind(this));

        /**
         * @param {string} styleText
         * @this {WebInspector.CSSProperty}
         * @return {!Promise.<boolean>}
         */
        function setStyleText(styleText)
        {
            return this.ownerStyle.setText(styleText, majorChange);
        }
    },

    /**
     * @param {string} styleText
     * @param {string} indentation
     * @param {string} endIndentation
     * @param {!WebInspector.TokenizerFactory} tokenizerFactory
     * @return {string}
     */
    _formatStyle: function(styleText, indentation, endIndentation, tokenizerFactory)
    {
        if (indentation)
            indentation = "\n" + indentation;
        var result = "";
        var propertyText;
        var insideProperty = false;
        var tokenize = tokenizerFactory.createTokenizer("text/css");

        tokenize("*{" + styleText + "}", processToken);
        if (insideProperty)
            result += propertyText;
        result = result.substring(2, result.length - 1).trimRight();
        return result + (indentation ? "\n" + endIndentation : "");

        /**
         * @param {string} token
         * @param {?string} tokenType
         * @param {number} column
         * @param {number} newColumn
         */
        function processToken(token, tokenType, column, newColumn)
        {
            if (!insideProperty) {
                var disabledProperty = tokenType && tokenType.includes("css-comment") && isDisabledProperty(token);
                var isPropertyStart = tokenType && (tokenType.includes("css-string") || tokenType.includes("css-meta") || tokenType.includes("css-property") || tokenType.includes("css-variable-2"));
                if (disabledProperty) {
                    result = result.trimRight() + indentation + token;
                } else if (isPropertyStart) {
                    insideProperty = true;
                    propertyText = token;
                } else if (token !== ";") {
                    result += token;
                }
                return;
            }

            if (token === "}" || token === ";") {
                result = result.trimRight() + indentation + propertyText.trim() + ";";
                insideProperty = false;
                if (token === "}")
                    result += "}";
            } else {
                propertyText += token;
            }
        }

        /**
         * @param {string} text
         * @return {boolean}
         */
        function isDisabledProperty(text)
        {
            var colon = text.indexOf(":");
            if (colon === -1)
                return false;
            var propertyName = text.substring(2, colon).trim();
            return WebInspector.CSSMetadata.isCSSPropertyName(propertyName);
        }
    },

    /**
     * @param {string} text
     * @return {string}
     */
    _detectIndentation: function(text)
    {
        var lines = text.split("\n");
        if (lines.length < 2)
            return "";
        return WebInspector.TextUtils.lineIndent(lines[1]);
    },

    /**
     * @param {string} newValue
     * @param {boolean} majorChange
     * @param {boolean} overwrite
     * @param {function(boolean)=} userCallback
     */
    setValue: function(newValue, majorChange, overwrite, userCallback)
    {
        var text = this.name + ": " + newValue + (this.important ? " !important" : "") + ";";
        this.setText(text, majorChange, overwrite).then(userCallback);
    },

    /**
     * @param {boolean} disabled
     * @return {!Promise.<boolean>}
     */
    setDisabled: function(disabled)
    {
        if (!this.ownerStyle)
            return Promise.resolve(false);
        if (disabled === this.disabled)
            return Promise.resolve(true);
        var propertyText = this.text.trim();
        var text = disabled ? "/* " + propertyText + " */" : this.text.substring(2, propertyText.length - 2).trim();
        return this.setText(text, true, true);
    }
}


text:
/**
 * Common types used for collecting the information about {@link com.linecorp.armeria.common.Request}s and
 * {@link com.linecorp.armeria.common.Response}s.
 *
 *
Starting points

 *

 *
{@link com.linecorp.armeria.common.logging.RequestLog}

 *
{@link com.linecorp.armeria.common.logging.RequestLogBuilder}

 *

 */
package com.linecorp.armeria.common.logging;


text:
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using EPiServer.Reference.Commerce.Shared.Models;
using System.ComponentModel.DataAnnotations;

namespace EPiServer.Reference.Commerce.Site.Features.Global.ResetPassword.Pages
{
    [ContentType(DisplayName = "Reset password e-mail", GUID = "6c939f47-b8bb-44a8-bc10-371b54d609b4", Description = "The page which allows you to reset password via e-mail.", AvailableInEditMode = true)]
    [ImageUrl("~/styles/images/page_type.png")]
    public class ResetPasswordMailPage : MailBasePage
    {
        [CultureSpecific]
        [Display(
            Name = "Main body",
            Description = "The main body will be shown in the main content area of the page, using the XHTML-editor you can insert for example text, images and tables.",
            GroupName = SystemTabNames.Content,
            Order = 1)]
        public virtual XhtmlString MailBody { get; set; }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.s4game.oa.common.mapper.SupplementManageMapper">
  <resultMap id="BaseResultMap" type="com.s4game.oa.common.entity.SupplementManage">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="year" jdbcType="SMALLINT" property="year" />
    <result column="month" jdbcType="SMALLINT" property="month" />
    <result column="type" jdbcType="TINYINT" property="type" />
    <result column="investment_amount" jdbcType="DECIMAL" property="investmentAmount" />
    <result column="composite_amount" jdbcType="DECIMAL" property="compositeAmount" />
    <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
    <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
  </resultMap>
  <sql id="Base_Column_List">
    id, year, month, type, investment_amount, composite_amount, create_time, update_time
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from oa_supplement_manage
    where id = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    delete from oa_supplement_manage
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="com.s4game.oa.common.entity.SupplementManage">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into oa_supplement_manage (year, month, type,
      investment_amount, composite_amount, create_time,
      update_time)
    values (#{year,jdbcType=SMALLINT}, #{month,jdbcType=SMALLINT}, #{type,jdbcType=TINYINT},
      #{investmentAmount,jdbcType=DECIMAL}, #{compositeAmount,jdbcType=DECIMAL}, #{createTime,jdbcType=TIMESTAMP},
      #{updateTime,jdbcType=TIMESTAMP})
  </insert>
  <insert id="insertSelective" parameterType="com.s4game.oa.common.entity.SupplementManage">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into oa_supplement_manage
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="year != null">
        year,
      </if>
      <if test="month != null">
        month,
      </if>
      <if test="type != null">
        type,
      </if>
      <if test="investmentAmount != null">
        investment_amount,
      </if>
      <if test="compositeAmount != null">
        composite_amount,
      </if>
      <if test="createTime != null">
        create_time,
      </if>
      <if test="updateTime != null">
        update_time,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="year != null">
        #{year,jdbcType=SMALLINT},
      </if>
      <if test="month != null">
        #{month,jdbcType=SMALLINT},
      </if>
      <if test="type != null">
        #{type,jdbcType=TINYINT},
      </if>
      <if test="investmentAmount != null">
        #{investmentAmount,jdbcType=DECIMAL},
      </if>
      <if test="compositeAmount != null">
        #{compositeAmount,jdbcType=DECIMAL},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null">
        #{updateTime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.s4game.oa.common.entity.SupplementManage">
    update oa_supplement_manage
    <set>
      <if test="year != null">
        year = #{year,jdbcType=SMALLINT},
      </if>
      <if test="month != null">
        month = #{month,jdbcType=SMALLINT},
      </if>
      <if test="type != null">
        type = #{type,jdbcType=TINYINT},
      </if>
      <if test="investmentAmount != null">
        investment_amount = #{investmentAmount,jdbcType=DECIMAL},
      </if>
      <if test="compositeAmount != null">
        composite_amount = #{compositeAmount,jdbcType=DECIMAL},
      </if>
      <if test="createTime != null">
        create_time = #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null">
        update_time = #{updateTime,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.s4game.oa.common.entity.SupplementManage">
    update oa_supplement_manage
    set year = #{year,jdbcType=SMALLINT},
      month = #{month,jdbcType=SMALLINT},
      type = #{type,jdbcType=TINYINT},
      investment_amount = #{investmentAmount,jdbcType=DECIMAL},
      composite_amount = #{compositeAmount,jdbcType=DECIMAL},
      create_time = #{createTime,jdbcType=TIMESTAMP},
      update_time = #{updateTime,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=BIGINT}
  </update>

  <select id="selectAll" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from oa_supplement_manage

    <where>
    	<if test="months != null">
    		and month in
    		<foreach collection="months" index="index" item="item" open="(" separator="," close=")">
		    	#{item}
		    </foreach>
    	</if>
    </where>
  </select>

  <select id="selectReport" resultMap="BaseResultMap">
    select type, sum(investment_amount) as investment_amount, sum(composite_amount) as composite_amount

    from oa_supplement_manage

    <where>
    	<if test="year != null">
    		and `year` = #{year}
    	</if>
    	<if test="month != null">
    		and month = #{month}
    	</if>
    </where>
    group by type

  </select>

</mapper>


text:
/* crypto/pem/pem_err.c */
/* ====================================================================
 * Copyright (c) 1999-2016 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    openssl-core@OpenSSL.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */

/*
 * NOTE: this file was auto generated by the mkerr.pl script: any changes
 * made to it will be overwritten when the script next updates this file,
 * only reason strings will be preserved.
 */

#include <stdio.h>
#include <openssl/err.h>
#include <openssl/pem.h>

/* BEGIN ERROR CODES */
#ifndef OPENSSL_NO_ERR

# define ERR_FUNC(func) ERR_PACK(ERR_LIB_PEM,func,0)
# define ERR_REASON(reason) ERR_PACK(ERR_LIB_PEM,0,reason)

static ERR_STRING_DATA PEM_str_functs[] = {
    {ERR_FUNC(PEM_F_B2I_DSS), "B2I_DSS"},
    {ERR_FUNC(PEM_F_B2I_PVK_BIO), "b2i_PVK_bio"},
    {ERR_FUNC(PEM_F_B2I_RSA), "B2I_RSA"},
    {ERR_FUNC(PEM_F_CHECK_BITLEN_DSA), "CHECK_BITLEN_DSA"},
    {ERR_FUNC(PEM_F_CHECK_BITLEN_RSA), "CHECK_BITLEN_RSA"},
    {ERR_FUNC(PEM_F_D2I_PKCS8PRIVATEKEY_BIO), "d2i_PKCS8PrivateKey_bio"},
    {ERR_FUNC(PEM_F_D2I_PKCS8PRIVATEKEY_FP), "d2i_PKCS8PrivateKey_fp"},
    {ERR_FUNC(PEM_F_DO_B2I), "DO_B2I"},
    {ERR_FUNC(PEM_F_DO_B2I_BIO), "DO_B2I_BIO"},
    {ERR_FUNC(PEM_F_DO_BLOB_HEADER), "DO_BLOB_HEADER"},
    {ERR_FUNC(PEM_F_DO_PK8PKEY), "DO_PK8PKEY"},
    {ERR_FUNC(PEM_F_DO_PK8PKEY_FP), "DO_PK8PKEY_FP"},
    {ERR_FUNC(PEM_F_DO_PVK_BODY), "DO_PVK_BODY"},
    {ERR_FUNC(PEM_F_DO_PVK_HEADER), "DO_PVK_HEADER"},
    {ERR_FUNC(PEM_F_I2B_PVK), "I2B_PVK"},
    {ERR_FUNC(PEM_F_I2B_PVK_BIO), "i2b_PVK_bio"},
    {ERR_FUNC(PEM_F_LOAD_IV), "LOAD_IV"},
    {ERR_FUNC(PEM_F_PEM_ASN1_READ), "PEM_ASN1_read"},
    {ERR_FUNC(PEM_F_PEM_ASN1_READ_BIO), "PEM_ASN1_read_bio"},
    {ERR_FUNC(PEM_F_PEM_ASN1_WRITE), "PEM_ASN1_write"},
    {ERR_FUNC(PEM_F_PEM_ASN1_WRITE_BIO), "PEM_ASN1_write_bio"},
    {ERR_FUNC(PEM_F_PEM_DEF_CALLBACK), "PEM_def_callback"},
    {ERR_FUNC(PEM_F_PEM_DO_HEADER), "PEM_do_header"},
    {ERR_FUNC(PEM_F_PEM_F_PEM_WRITE_PKCS8PRIVATEKEY),
     "PEM_F_PEM_WRITE_PKCS8PRIVATEKEY"},
    {ERR_FUNC(PEM_F_PEM_GET_EVP_CIPHER_INFO), "PEM_get_EVP_CIPHER_INFO"},
    {ERR_FUNC(PEM_F_PEM_PK8PKEY), "PEM_PK8PKEY"},
    {ERR_FUNC(PEM_F_PEM_READ), "PEM_read"},
    {ERR_FUNC(PEM_F_PEM_READ_BIO), "PEM_read_bio"},
    {ERR_FUNC(PEM_F_PEM_READ_BIO_PARAMETERS), "PEM_read_bio_Parameters"},
    {ERR_FUNC(PEM_F_PEM_READ_BIO_PRIVATEKEY), "PEM_READ_BIO_PRIVATEKEY"},
    {ERR_FUNC(PEM_F_PEM_READ_PRIVATEKEY), "PEM_READ_PRIVATEKEY"},
    {ERR_FUNC(PEM_F_PEM_SEALFINAL), "PEM_SealFinal"},
    {ERR_FUNC(PEM_F_PEM_SEALINIT), "PEM_SealInit"},
    {ERR_FUNC(PEM_F_PEM_SIGNFINAL), "PEM_SignFinal"},
    {ERR_FUNC(PEM_F_PEM_WRITE), "PEM_write"},
    {ERR_FUNC(PEM_F_PEM_WRITE_BIO), "PEM_write_bio"},
    {ERR_FUNC(PEM_F_PEM_WRITE_PRIVATEKEY), "PEM_WRITE_PRIVATEKEY"},
    {ERR_FUNC(PEM_F_PEM_X509_INFO_READ), "PEM_X509_INFO_read"},
    {ERR_FUNC(PEM_F_PEM_X509_INFO_READ_BIO), "PEM_X509_INFO_read_bio"},
    {ERR_FUNC(PEM_F_PEM_X509_INFO_WRITE_BIO), "PEM_X509_INFO_write_bio"},
    {0, NULL}
};

static ERR_STRING_DATA PEM_str_reasons[] = {
    {ERR_REASON(PEM_R_BAD_BASE64_DECODE), "bad base64 decode"},
    {ERR_REASON(PEM_R_BAD_DECRYPT), "bad decrypt"},
    {ERR_REASON(PEM_R_BAD_END_LINE), "bad end line"},
    {ERR_REASON(PEM_R_BAD_IV_CHARS), "bad iv chars"},
    {ERR_REASON(PEM_R_BAD_MAGIC_NUMBER), "bad magic number"},
    {ERR_REASON(PEM_R_BAD_PASSWORD_READ), "bad password read"},
    {ERR_REASON(PEM_R_BAD_VERSION_NUMBER), "bad version number"},
    {ERR_REASON(PEM_R_BIO_WRITE_FAILURE), "bio write failure"},
    {ERR_REASON(PEM_R_CIPHER_IS_NULL), "cipher is null"},
    {ERR_REASON(PEM_R_ERROR_CONVERTING_PRIVATE_KEY),
     "error converting private key"},
    {ERR_REASON(PEM_R_EXPECTING_PRIVATE_KEY_BLOB),
     "expecting private key blob"},
    {ERR_REASON(PEM_R_EXPECTING_PUBLIC_KEY_BLOB),
     "expecting public key blob"},
    {ERR_REASON(PEM_R_HEADER_TOO_LONG), "header too long"},
    {ERR_REASON(PEM_R_INCONSISTENT_HEADER), "inconsistent header"},
    {ERR_REASON(PEM_R_KEYBLOB_HEADER_PARSE_ERROR),
     "keyblob header parse error"},
    {ERR_REASON(PEM_R_KEYBLOB_TOO_SHORT), "keyblob too short"},
    {ERR_REASON(PEM_R_NOT_DEK_INFO), "not dek info"},
    {ERR_REASON(PEM_R_NOT_ENCRYPTED), "not encrypted"},
    {ERR_REASON(PEM_R_NOT_PROC_TYPE), "not proc type"},
    {ERR_REASON(PEM_R_NO_START_LINE), "no start line"},
    {ERR_REASON(PEM_R_PROBLEMS_GETTING_PASSWORD),
     "problems getting password"},
    {ERR_REASON(PEM_R_PUBLIC_KEY_NO_RSA), "public key no rsa"},
    {ERR_REASON(PEM_R_PVK_DATA_TOO_SHORT), "pvk data too short"},
    {ERR_REASON(PEM_R_PVK_TOO_SHORT), "pvk too short"},
    {ERR_REASON(PEM_R_READ_KEY), "read key"},
    {ERR_REASON(PEM_R_SHORT_HEADER), "short header"},
    {ERR_REASON(PEM_R_UNSUPPORTED_CIPHER), "unsupported cipher"},
    {ERR_REASON(PEM_R_UNSUPPORTED_ENCRYPTION), "unsupported encryption"},
    {ERR_REASON(PEM_R_UNSUPPORTED_KEY_COMPONENTS),
     "unsupported key components"},
    {0, NULL}
};

#endif

void ERR_load_PEM_strings(void)
{
#ifndef OPENSSL_NO_ERR

    if (ERR_func_error_string(PEM_str_functs[0].error) == NULL) {
        ERR_load_strings(0, PEM_str_functs);
        ERR_load_strings(0, PEM_str_reasons);
    }
#endif
}


text:
layout: post
title: There's a Nintendo Wii-U Sized Hole In My Firewall
date: 2015-08-10 22:43:07 -08:00
type: post
published: true
status: publish
permalink: /2015/08/10/theres-a-nintendo-wii-u-sized-hole-in-my-firewall/
categories: []
tags: []
author:
  login: phoneboy
  email: dwelch@phoneboy.com
  display_name: Dameon Welch-Abernathy
---
In order to allow your Nintendo Wii-U to participate in multiplayer online games, you have to configure your router/firewall/whatever in [one of three ways per Nintendo](http://en-americas-support.nintendo.com/app/answers/detail/a_id/13214/p/431):

* Enable Universal Plug-n-Play (uPNP) on your router, which is [widely known to be insecure](https://community.rapid7.com/community/infosec/blog/2013/01/29/security-flaws-in-universal-plug-and-play-unplug-dont-play).
* Assign your Wii-U a static IP and use DMZ mode, which is opening your firewall to everyone on the Internet.
* Assign your Wii-U a static IP and forward all UDP ports (1-65535) to your Wii-U. Note that mapping a couple of ports isn't unusual, but when you're mapping this many ports, is basically the same thing as DMZ mode, thus not any better.

None of these options are acceptable from a security point of view. Granted, I am reasonably security savvy and can mitigate the unnecessary risks involved with such a configuration. However, most consumers cannot and will not understand the risk they are undertaking.

[While I'm not exactly fond of a CyberUL](http://blog.erratasec.com/2015/06/cyberul-is-dumb-idea.html), if there was such a thing, this kind of configuration would clearly be non-compliant.

Of course, neither [Microsoft](http://support.xbox.com/en-US/xbox-360/networking/nat-error-solution) or [Sony](https://support.us.playstation.com/app/answers/detail/a_id/241/kw/nat) are much better, as they push the DMZ and uPNP as primary solutions first, but at least they offer solutions that don't require forwarding **all** ports like Nintendo does.

It's the kind of thing I'm surprised I haven't heard other security professionals rant about, honestly. It's certainly going to make me think twice about buying **any** product from Nintendo in the future.

**Edited to add on 10 Aug 2015**: Links to why uPNP is bad as well as explanations on why the other options Nintendo offers aren't much better.