text:
//
//  File: %t-binary.c
//  Summary: "BINARY! datatype"
//  Section: datatypes
//  Project: "Rebol 3 Interpreter and Run-time (Ren-C branch)"
//  Homepage: https://github.com/metaeducation/ren-c/
//
//=////////////////////////////////////////////////////////////////////////=//
//
// Copyright 2012 REBOL Technologies
// Copyright 2012-2017 Rebol Open Source Contributors
// REBOL is a trademark of REBOL Technologies
//
// See README.md and CREDITS.md for more information.
//
// 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.
//
//=////////////////////////////////////////////////////////////////////////=//
//

#include "sys-core.h"
#include "sys-int-funcs.h"

#include "datatypes/sys-money.h"

//
//  CT_Binary: C
//
REBINT CT_Binary(const REBCEL *a, const REBCEL *b, REBINT mode)
{
    assert(CELL_KIND(a) == REB_BINARY);
    assert(CELL_KIND(b) == REB_BINARY);

    REBINT num = Compare_Binary_Vals(a, b);

    if (mode >= 0) return (num == 0) ? 1 : 0;
    if (mode == -1) return (num >= 0) ? 1 : 0;
    return (num > 0) ? 1 : 0;
}

/***********************************************************************
**
**  Local Utility Functions
**
***********************************************************************/

static void reverse_binary(REBVAL *v, REBLEN len)
{
    REBYTE *bp = VAL_BIN_AT(v);

    REBLEN n = 0;
    REBLEN m = len - 1;
    for (; n < len / 2; n++, m--) {
        REBYTE b = bp[n];
        bp[n] = bp[m];
        bp[m] = b;
    }
}

//
//  find_binary: C
//
REBLEN find_binary(
    REBLEN *size,  // match size (if TAG! pattern, not VAL_LEN_AT(pattern))
    REBSER *bin,
    REBLEN index,
    REBLEN end,
    const RELVAL *pattern,
    REBLEN flags,
    REBINT skip
) {
    assert(end >= index);

    REBLEN start;
    if (skip < 0)
        start = 0;
    else
        start = index;

    if (ANY_STRING(pattern)) {
        if (skip != 1)
            fail ("String search in BINARY! only supports /SKIP 1 for now.");

        REBSTR *formed = nullptr;

        REBYTE *bp2;
        REBLEN len2;
        if (not IS_TEXT(pattern)) { // !!! for TAG!, but what about FILE! etc?
            formed = Copy_Form_Value(pattern, 0);
            len2 = STR_LEN(formed);
            bp2 = STR_HEAD(formed);
            *size = STR_SIZE(formed);
        }
        else {
            len2 = VAL_LEN_AT(pattern);
            bp2 = VAL_STRING_AT(pattern);
            *size = VAL_SIZE_LIMIT_AT(NULL, pattern, len2);
        }

        if (*size > end - index)  // series not long enough for pattern
            return NOT_FOUND;

        REBLEN result = Find_Str_In_Bin(
            bin,
            start,
            bp2,
            len2,
            *size,
            flags & (AM_FIND_MATCH | AM_FIND_CASE)
        );

        if (formed)
            Free_Unmanaged_Series(SER(formed));

        return result;
    }
    else if (IS_BINARY(pattern)) {
        if (skip != 1)
            fail ("Search for BINARY! in BINARY! only supports /SKIP 1 ATM");

        *size = VAL_LEN_AT(pattern);
        return Find_Bin_In_Bin(
            bin,
            start,
            VAL_BIN_AT(pattern),
            *size,
            flags & AM_FIND_MATCH
        );
    }
    else if (IS_CHAR(pattern)) {
        //
        // Technically speaking the upper and lowercase sizes of a character
        // may not be the same.  It's okay here since we only do cased.
        //
        // https://stackoverflow.com/q/14792841/
        //
        *size = VAL_CHAR_ENCODED_SIZE(pattern);
        return Find_Char_In_Bin(
            VAL_CHAR(pattern),
            bin,
            start,
            index,
            end,
            skip,
            flags & (AM_FIND_CASE | AM_FIND_MATCH)
        );
    }
    else if (IS_INTEGER(pattern)) {  // specific byte value, never apply case
        if (VAL_INT64(pattern) < 0 or VAL_INT64(pattern) > 255)
            fail (Error_Out_Of_Range(KNOWN(pattern)));

        *size = 1;

        REBYTE byte = cast(REBYTE, VAL_INT64(pattern));

        return Find_Bin_In_Bin(
            bin,
            start,
            &byte,
            *size,
            flags & AM_FIND_MATCH
        );
    }
    else if (IS_BITSET(pattern)) {
        *size = 1;

        return Find_Bin_Bitset(
            bin,
            start,
            index,
            end,
            skip,
            VAL_BITSET(pattern),
            flags & AM_FIND_MATCH  // no AM_FIND_CASE
        );
    }
    else
        fail ("Unsupported pattern type passed to find_binary()");
}

static REBSER *Make_Binary_BE64(const REBVAL *arg)
{
    REBSER *ser = Make_Binary(8);

    REBYTE *bp = BIN_HEAD(ser);

    REBI64 i;
    REBDEC d;
    const REBYTE *cp;
    if (IS_INTEGER(arg)) {
        assert(sizeof(REBI64) == 8);
        i = VAL_INT64(arg);
        cp = cast(const REBYTE*, &i);
    }
    else {
        assert(sizeof(REBDEC) == 8);
        d = VAL_DECIMAL(arg);
        cp = cast(const REBYTE*, &d);
    }

#ifdef ENDIAN_LITTLE
    REBLEN n;
    for (n = 0; n < 8; ++n)
        bp[n] = cp[7 - n];
#elif defined(ENDIAN_BIG)
    REBLEN n;
    for (n = 0; n < 8; ++n)
        bp[n] = cp[n];
#else
    #error "Unsupported CPU endian"
#endif

    TERM_BIN_LEN(ser, 8);
    return ser;
}

// Common behaviors for:
//
//     MAKE BINARY! ...
//     TO BINARY! ...
//
// !!! MAKE and TO were not historically very clearly differentiated in
// Rebol, and so often they would "just do the same thing".  Ren-C ultimately
// will seek to limit the synonyms/polymorphism, e.g. MAKE or TO BINARY! of a
// BINARY! acting as COPY, in favor of having the user call COPY explicilty.
//
// Note also the existence of AS and storing strings as UTF-8 should reduce
// copying, e.g. `as binary! some-string` will be cheaper than TO or MAKE.
//
static REBSER *MAKE_TO_Binary_Common(const REBVAL *arg)
{
    switch (VAL_TYPE(arg)) {
    case REB_BINARY:
        return Copy_Bytes(VAL_BIN_AT(arg), VAL_LEN_AT(arg));

    case REB_TEXT:
    case REB_FILE:
    case REB_EMAIL:
    case REB_URL:
    case REB_TAG: {  // !!! What should REB_ISSUE do?
        REBSIZ offset = VAL_OFFSET_FOR_INDEX(arg, VAL_INDEX(arg));

        REBSIZ size = VAL_SIZE_LIMIT_AT(NULL, arg, UNKNOWN);

        REBSER *bin = Make_Binary(size);
        memcpy(BIN_HEAD(bin), BIN_AT(VAL_SERIES(arg), offset), size);
        TERM_BIN_LEN(bin, size);
        return bin; }

    case REB_BLOCK:
        Join_Binary_In_Byte_Buf(arg, -1);
        return Copy_Sequence_Core(BYTE_BUF, SERIES_FLAGS_NONE);

    case REB_TUPLE:
        return Copy_Bytes(VAL_TUPLE(arg), VAL_TUPLE_LEN(arg));

    case REB_CHAR: {
        REBSER *bin = Make_Binary(6);
        TERM_SEQUENCE_LEN(bin, Encode_UTF8_Char(BIN_HEAD(bin), VAL_CHAR(arg)));
        return bin;
    }

    case REB_BITSET:
        return Copy_Bytes(VAL_BIN_HEAD(arg), VAL_LEN_HEAD(arg));

    case REB_MONEY: {
        REBSER *bin = Make_Binary(12);
        deci_to_binary(BIN_HEAD(bin), VAL_MONEY_AMOUNT(arg));
        TERM_SEQUENCE_LEN(bin, 12);
        return bin; }

    default:
        fail (Error_Bad_Make(REB_BINARY, arg));
    }
}

//
//  MAKE_Binary: C
//
// See also: MAKE_String, which is similar.
//
REB_R MAKE_Binary(
    REBVAL *out,
    enum Reb_Kind kind,
    const REBVAL *opt_parent,
    const REBVAL *def
){
    assert(kind == REB_BINARY);

    if (opt_parent)
        fail (Error_Bad_Make_Parent(kind, opt_parent));

    if (IS_INTEGER(def)) {
        //
        // !!! R3-Alpha tolerated decimal, e.g. `make string! 3.14`, which
        // is semantically nebulous (round up, down?) and generally bad.
        //
        return Init_Binary(out, Make_Binary(Int32s(def, 0)));
    }

    if (IS_BLOCK(def)) {
        //
        // The construction syntax for making binaries preloaded with an
        // offset into the data is #[binary [#{0001} 2]].
        //
        // !!! R3-Alpha make definitions didn't have to be a single value
        // (they are for compatibility between construction syntax and MAKE
        // in Ren-C).  So the positional syntax was #[binary! #{0001} 2]...
        // while #[binary [#{0001} 2]] would join the pieces together in order
        // to produce #{000102}.  That behavior is not available in Ren-C.

        if (VAL_ARRAY_LEN_AT(def) != 2)
            goto bad_make;

        RELVAL *first = VAL_ARRAY_AT(def);
        if (not IS_BINARY(first))
            goto bad_make;

        RELVAL *index = VAL_ARRAY_AT(def) + 1;
        if (not IS_INTEGER(index))
            goto bad_make;

        REBINT i = Int32(index) - 1 + VAL_INDEX(first);
        if (i < 0 or i > cast(REBINT, VAL_LEN_AT(first)))
            goto bad_make;

        return Init_Any_Series_At(out, REB_BINARY, VAL_SERIES(first), i);
    }

    return Init_Any_Series(out, REB_BINARY, MAKE_TO_Binary_Common(def));

bad_make:
    fail (Error_Bad_Make(REB_BINARY, def));
}

//
//  TO_Binary: C
//
REB_R TO_Binary(REBVAL *out, enum Reb_Kind kind, const REBVAL *arg)
{
    assert(kind == REB_BINARY);
    UNUSED(kind);

    if (IS_INTEGER(arg) or IS_DECIMAL(arg))
        return Init_Any_Series(out, REB_BINARY, Make_Binary_BE64(arg));

    return Init_Any_Series(out, REB_BINARY, MAKE_TO_Binary_Common(arg));
}

enum COMPARE_CHR_FLAGS {
    CC_FLAG_CASE = 1 << 0, // Case sensitive sort
    CC_FLAG_REVERSE = 1 << 1 // Reverse sort order
};

//
//  Compare_Byte: C
//
// This function is called by qsort_r, on behalf of the string sort
// function.  The `thunk` is an argument passed through from the caller
// and given to us by the sort routine, which tells us about the string
// and the kind of sort that was requested.
//
static int Compare_Byte(void *thunk, const void *v1, const void *v2)
{
    REBFLGS * const flags = cast(REBFLGS*, thunk);

    REBYTE b1 = *cast(const REBYTE*, v1);
    REBYTE b2 = *cast(const REBYTE*, v2);

    if (*flags & CC_FLAG_REVERSE)
        return b2 - b1;
    else
        return b1 - b2;
}

//
//  Sort_Binary: C
//
static void Sort_Binary(
    REBVAL *binary,
    REBVAL *skipv,
    REBVAL *compv,
    REBVAL *part,
    bool rev
){
    assert(IS_BINARY(binary));

    if (not IS_BLANK(compv))
        fail (Error_Bad_Refine_Raw(compv));  // !!! R3-Alpha didn't support

    REBFLGS thunk = 0;

    REBLEN len = Part_Len_May_Modify_Index(binary, part);  // length of sort
    if (len <= 1)
        return;

    REBLEN skip;
    if (IS_BLANK(skipv))
        skip = 1;
    else {
        skip = Get_Num_From_Arg(skipv);
        if (skip <= 0 or (len % skip != 0) or skip > len)
            fail (skipv);
    }

    REBSIZ size = 1;
    if (skip > 1) {
        len /= skip;
        size *= skip;
    }

    if (rev)
        thunk |= CC_FLAG_REVERSE;

    reb_qsort_r(
        VAL_RAW_DATA_AT(binary),
        len,
        size,
        &thunk,
        Compare_Byte
    );
}

//
//  PD_Binary: C
//
REB_R PD_Binary(
    REBPVS *pvs,
    const REBVAL *picker,
    const REBVAL *opt_setval
){
    REBSER *ser = VAL_SERIES(pvs->out);

    // Note: There was some more careful management of overflow here in the
    // PICK and POKE actions, before unification.  But otherwise the code
    // was less thorough.  Consider integrating this bit, though it seems
    // that a more codebase-wide review should be given to the issue.
    //
    /*
        REBINT len = Get_Num_From_Arg(arg);
        if (
            REB_I32_SUB_OF(len, 1, &len)
            || REB_I32_ADD_OF(index, len, &index)
            || index < 0 || index >= tail
        ){
            fail (Error_Out_Of_Range(arg));
        }
    */

    if (not opt_setval) { // PICK-ing
        if (IS_INTEGER(picker)) {
            REBINT n = Int32(picker) + VAL_INDEX(pvs->out) - 1;
            if (n < 0 or cast(REBLEN, n) >= SER_LEN(ser))
                return nullptr;

            Init_Integer(pvs->out, *BIN_AT(ser, n));
            return pvs->out;
        }

        return R_UNHANDLED;
    }

    // Otherwise, POKE-ing

    FAIL_IF_READ_ONLY(pvs->out);

    if (not IS_INTEGER(picker))
        return R_UNHANDLED;

    REBINT n = Int32(picker) + VAL_INDEX(pvs->out) - 1;
    if (n < 0 or cast(REBLEN, n) >= SER_LEN(ser))
        fail (Error_Out_Of_Range(picker));

    REBINT c;
    if (IS_CHAR(opt_setval)) {
        c = VAL_CHAR(opt_setval);
        if (c > cast(REBI64, MAX_UNI))
            return R_UNHANDLED;
    }
    else if (IS_INTEGER(opt_setval)) {
        c = Int32(opt_setval);
        if (c > cast(REBI64, MAX_UNI) or c < 0)
            return R_UNHANDLED;
    }
    else if (ANY_BINSTR(opt_setval)) {
        REBLEN i = VAL_INDEX(opt_setval);
        if (i >= VAL_LEN_HEAD(opt_setval))
            fail (opt_setval);

        c = GET_CHAR_AT(VAL_STRING(opt_setval), i);
    }
    else
        return R_UNHANDLED;

    if (c > 0xff)
        fail (Error_Out_Of_Range(opt_setval));

    BIN_HEAD(ser)[n] = cast(REBYTE, c);
    return R_INVISIBLE;
}

//
//  MF_Binary: C
//
void MF_Binary(REB_MOLD *mo, const REBCEL *v, bool form)
{
    UNUSED(form);

    if (GET_MOLD_FLAG(mo, MOLD_FLAG_ALL) and VAL_INDEX(v) != 0)
        Pre_Mold(mo, v); // #[binary!

    REBLEN len = VAL_LEN_AT(v);

    switch (Get_System_Int(SYS_OPTIONS, OPTIONS_BINARY_BASE, 16)) {
      default:
      case 16: {
        Append_Ascii(mo->series, "#{"); // default, so #{...} not #16{...}

        const bool brk = (len > 32);
        Form_Base16(mo, VAL_BIN_AT(v), len, brk);
        break; }

      case 64: {
        Append_Ascii(mo->series, "64#{");

        const bool brk = (len > 64);
        Form_Base64(mo, VAL_BIN_AT(v), len, brk);
        break; }

      case 2: {
        Append_Ascii(mo->series, "2#{");

        const bool brk = (len > 8);
        Form_Base2(mo, VAL_BIN_AT(v), len, brk);
        break; }
    }

    Append_Codepoint(mo->series, '}');

    if (GET_MOLD_FLAG(mo, MOLD_FLAG_ALL) and VAL_INDEX(v) != 0)
        Post_Mold(mo, v);
}

//
//  REBTYPE: C
//
REBTYPE(Binary)
{
    REBVAL *v = D_ARG(1);
    assert(IS_BINARY(v));

    // Common setup code for all actions:
    //
    REBINT index = cast(REBINT, VAL_INDEX(v));
    REBINT tail = cast(REBINT, VAL_LEN_HEAD(v));

    REBSYM sym = VAL_WORD_SYM(verb);
    switch (sym) {

        // Note: INTERSECT, UNION, DIFFERENCE handled later in the switch
        //
      case SYM_REFLECT:
      case SYM_SKIP:
      case SYM_AT:
      case SYM_REMOVE:
        return Series_Common_Action_Maybe_Unhandled(frame_, verb);

    //-- Modification:
      case SYM_APPEND:
      case SYM_INSERT:
      case SYM_CHANGE: {
        INCLUDE_PARAMS_OF_INSERT;  // compatible frame with APPEND, CHANGE
        UNUSED(PAR(series));  // covered by `v`

        FAIL_IF_READ_ONLY(v);

        if (REF(only)) {
            // !!! Doesn't pay attention...all binary appends are /ONLY
        }

        REBLEN len; // length of target
        if (VAL_WORD_SYM(verb) == SYM_CHANGE)
            len = Part_Len_May_Modify_Index(v, ARG(part));
        else
            len = Part_Limit_Append_Insert(ARG(part));

        REBFLGS flags = 0;
        if (REF(part))
            flags |= AM_PART;
        if (REF(line))
            flags |= AM_LINE;

        VAL_INDEX(v) = Modify_String_Or_Binary(
            v,
            VAL_WORD_CANON(verb),
            ARG(value),
            flags,
            len,
            REF(dup) ? Int32(ARG(dup)) : 1
        );
        RETURN (v); }

    //-- Search:
      case SYM_SELECT:
      case SYM_FIND: {
        INCLUDE_PARAMS_OF_FIND;
        UNUSED(PAR(series));  // covered by `v`

        UNUSED(REF(reverse));  // Deprecated https://forum.rebol.info/t/1126
        UNUSED(REF(last));  // ...a HIJACK in %mezz-legacy errors if used

        REBVAL *pattern = ARG(pattern);

        // !!! R3-Alpha FIND/MATCH historically implied /TAIL.  Should it?
        //
        REBFLGS flags = (
            (REF(only) ? AM_FIND_ONLY : 0)
            | (REF(match) ? AM_FIND_MATCH : 0)
            | (REF(case) ? AM_FIND_CASE : 0)
        );

        flags |= AM_FIND_CASE;

        if (REF(part))
            tail = Part_Tail_May_Modify_Index(v, ARG(part));

        REBLEN skip;
        if (REF(skip))
            skip = Part_Len_May_Modify_Index(v, ARG(part));
        else
            skip = 1;

        REBLEN len;
        REBLEN ret = find_binary(
            &len, VAL_SERIES(v), index, tail, pattern, flags, skip
        );

        if (ret >= cast(REBLEN, tail))
            return nullptr;

        if (sym == SYM_FIND) {
            if (REF(tail) or REF(match))
                ret += len;
            return Init_Any_Series_At(D_OUT, REB_BINARY, VAL_SERIES(v), ret);
        }

        ret++;
        if (ret >= cast(REBLEN, tail))
            return nullptr;

        return Init_Integer(D_OUT, *BIN_AT(VAL_SERIES(v), ret)); }

      case SYM_TAKE_P: {
        INCLUDE_PARAMS_OF_TAKE_P;

        FAIL_IF_READ_ONLY(v);

        UNUSED(PAR(series));

        if (REF(deep))
            fail (Error_Bad_Refines_Raw());

        REBINT len;
        if (REF(part)) {
            len = Part_Len_May_Modify_Index(v, ARG(part));
            if (len == 0)
                return Init_Any_Series(D_OUT, VAL_TYPE(v), Make_Binary(0));
        } else
            len = 1;

        // Note that /PART can change index

        if (REF(last)) {
            if (tail - len < 0) {
                VAL_INDEX(v) = 0;
                len = tail;
            }
            else
                VAL_INDEX(v) = cast(REBLEN, tail - len);
        }

        if (cast(REBINT, VAL_INDEX(v)) >= tail) {
            if (not REF(part))
                return Init_Blank(D_OUT);

            return Init_Any_Series(D_OUT, VAL_TYPE(v), Make_Binary(0));
        }

        REBSER *ser = VAL_SERIES(v);
        index = VAL_INDEX(v);

        // if no /PART, just return value, else return string
        //
        if (not REF(part)) {
            Init_Integer(D_OUT, *VAL_BIN_AT(v));
        }
        else {
            Init_Binary(
                D_OUT,
                Copy_Sequence_At_Len(VAL_SERIES(v), VAL_INDEX(v), len)
            );
        }
        Remove_Series_Units(ser, VAL_INDEX(v), len);
        return D_OUT; }

      case SYM_CLEAR: {
        REBSER *ser = VAL_SERIES(v);
        FAIL_IF_READ_ONLY(v);

        if (index >= tail)
            RETURN (v); // clearing after available data has no effect

        // !!! R3-Alpha would take this opportunity to make it so that if the
        // series is now empty, it reclaims the "bias" (unused capacity at
        // the head of the series).  One of many behaviors worth reviewing.
        //
        if (index == 0 and IS_SER_DYNAMIC(ser))
            Unbias_Series(ser, false);

        TERM_SEQUENCE_LEN(ser, cast(REBLEN, index));
        RETURN (v); }

    //-- Creation:

      case SYM_COPY: {
        INCLUDE_PARAMS_OF_COPY;

        UNUSED(PAR(value));

        if (REF(deep) or REF(types))
            fail (Error_Bad_Refines_Raw());

        REBINT len = Part_Len_May_Modify_Index(v, ARG(part));

        return Init_Any_Series(
            D_OUT,
            REB_BINARY,
            Copy_Sequence_At_Len(VAL_SERIES(v), VAL_INDEX(v), len)
        ); }

    //-- Bitwise:

      case SYM_INTERSECT:
      case SYM_UNION:
      case SYM_DIFFERENCE: {
        REBVAL *arg = D_ARG(2);

        if (VAL_INDEX(v) > VAL_LEN_HEAD(v))
            VAL_INDEX(v) = VAL_LEN_HEAD(v);

        if (VAL_INDEX(arg) > VAL_LEN_HEAD(arg))
            VAL_INDEX(arg) = VAL_LEN_HEAD(arg);

        return Init_Any_Series(
            D_OUT,
            REB_BINARY,
            Xandor_Binary(verb, v, arg)
        ); }

      case SYM_COMPLEMENT: {
        return Init_Any_Series(
            D_OUT,
            REB_BINARY,
            Complement_Binary(v)
        ); }

    // Arithmetic operations are allowed on BINARY!, because it's too limiting
    // to not allow `#{4B} + 1` => `#{4C}`.  Allowing the operations requires
    // a default semantic of binaries as unsigned arithmetic, since one
    // does not want `#{FF} + 1` to be #{FE}.  It uses a big endian
    // interpretation, so `#{00FF} + 1` is #{0100}
    //
    // Since Rebol is a language with mutable semantics by default, `add x y`
    // will mutate x by default (if X is not an immediate type).  `+` is an
    // enfixing of `add-of` which copies the first argument before adding.
    //
    // To try and maximize usefulness, the semantic chosen is that any
    // arithmetic that would go beyond the bounds of the length is considered
    // an overflow.  Hence the size of the result binary will equal the size
    // of the original binary.  This means that `#{0100} - 1` is #{00FF},
    // not #{FF}.
    //
    // !!! The code below is extremely slow and crude--using an odometer-style
    // loop to do the math.  What's being done here is effectively "bigint"
    // math, and it might be that it would share code with whatever big
    // integer implementation was used; e.g. integers which exceeded the size
    // of the platform REBI64 would use BINARY! under the hood.

      case SYM_SUBTRACT:
      case SYM_ADD: {
        FAIL_IF_READ_ONLY(v);
        REBVAL *arg = D_ARG(2);

        REBINT amount;
        if (IS_INTEGER(arg))
            amount = VAL_INT32(arg);
        else if (IS_BINARY(arg))
            fail (arg); // should work
        else
            fail (arg); // what about other types?

        if (sym == SYM_SUBTRACT)
            amount = -amount;

        if (amount == 0) // adding or subtracting 0 works, even #{} + 0
            RETURN (v);

        if (VAL_LEN_AT(v) == 0) // add/subtract to #{} otherwise
            fail (Error_Overflow_Raw());

        while (amount != 0) {
            REBLEN wheel = VAL_LEN_HEAD(v) - 1;
            while (true) {
                REBYTE *b = VAL_BIN_AT_HEAD(v, wheel);
                if (amount > 0) {
                    if (*b == 255) {
                        if (wheel == VAL_INDEX(v))
                            fail (Error_Overflow_Raw());

                        *b = 0;
                        --wheel;
                        continue;
                    }
                    ++(*b);
                    --amount;
                    break;
                }
                else {
                    if (*b == 0) {
                        if (wheel == VAL_INDEX(v))
                            fail (Error_Overflow_Raw());

                        *b = 255;
                        --wheel;
                        continue;
                    }
                    --(*b);
                    ++amount;
                    break;
                }
            }
        }
        RETURN (v); }

    //-- Special actions:

      case SYM_SWAP: {
        FAIL_IF_READ_ONLY(v);

        REBVAL *arg = D_ARG(2);

        if (VAL_TYPE(v) != VAL_TYPE(arg))
            fail (Error_Not_Same_Type_Raw());

        FAIL_IF_READ_ONLY(arg);

        if (index < tail and VAL_INDEX(arg) < VAL_LEN_HEAD(arg)) {
            REBYTE temp = *VAL_BIN_AT(v);
            *VAL_BIN_AT(v) = *VAL_BIN_AT(arg);
            *VAL_BIN_AT(arg) = temp;
        }
        RETURN (v); }

      case SYM_REVERSE: {
        INCLUDE_PARAMS_OF_REVERSE;
        UNUSED(ARG(series));

        FAIL_IF_READ_ONLY(v);

        REBINT len = Part_Len_May_Modify_Index(v, ARG(part));
        if (len > 0)
            reverse_binary(v, len);
        RETURN (v); }

      case SYM_SORT: {
        INCLUDE_PARAMS_OF_SORT;

        FAIL_IF_READ_ONLY(v);

        UNUSED(PAR(series));

        if (REF(all))
            fail (Error_Bad_Refine_Raw(ARG(all)));

        if (REF(case)) {
            // Ignored...all BINARY! sorts are case-sensitive.
        }

        Sort_Binary(
            v,
            ARG(skip),  // blank! if not /SKIP
            ARG(compare),  // (blank! if not /COMPARE)
            ARG(part),   // (blank! if not /PART)
            REF(reverse)
        );
        RETURN (v); }

      case SYM_RANDOM: {
        INCLUDE_PARAMS_OF_RANDOM;

        UNUSED(PAR(value));

        if (REF(seed)) { // binary contents are the seed
            Set_Random(Compute_CRC24(VAL_BIN_AT(v), VAL_LEN_AT(v)));
            return Init_Void(D_OUT);
        }

        FAIL_IF_READ_ONLY(v);

        if (REF(only)) {
            if (index >= tail)
                return Init_Blank(D_OUT);

            index += cast(REBLEN, Random_Int(REF(secure))) % (tail - index);
            return Init_Integer(D_OUT, *VAL_BIN_AT_HEAD(v, index)); // PICK
        }

        Shuffle_String(v, REF(secure));
        RETURN (v); }

      default:
        break;
    }

    return R_UNHANDLED;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using NUnit.Framework;

namespace MongoDB.Migrations.Tests
{
    [TestFixture]
    public class IntegrationTests : DatabaseTestsBase
    {
        private const string CUSTOMERS_COLLECTION = "customers";
        private MongoCollection<Customer> _customersCollection;

        private class CustomerOld
        {
            public string Name { get; set; }
        }

        [Migration(typeof (MigrationTo_0_5))]
        [Migration(typeof (MigrationTo_1_0))]
        private class Customer
        {
            public ObjectId Id { get; set; }
            public string Title { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }

        private class MigrationTo_0_5 : IMigration<Customer>
        {
            public Version To
            {
                get { return new Version(0, 5); }
            }

            public void Upgrade(Customer obj, IDictionary<string, object> extraElements)
            {
                var fullName = (string) extraElements["Name"];
                obj.LastName = fullName.Split().Last();
                obj.FirstName = fullName.Substring(0, fullName.Length - obj.LastName.Length).Trim();
                extraElements.Remove("Name");
            }
        }

        private class MigrationTo_1_0 : IMigration<Customer>
        {
            public Version To
            {
                get { return new Version(1, 0); }
            }

            public void Upgrade(Customer obj, IDictionary<string, object> extraElements)
            {
                obj.Title = obj.FirstName.Split().Count() > 1 ? obj.FirstName.Split().First() : null;
                obj.FirstName = obj.FirstName.Substring((obj.Title ?? "").Length).Trim();
            }
        }

        [SetUp]
        public void SetUp()
        {
            BsonSerializer.RegisterSerializationProvider(new MigrationSerializationProvider());

            SetUpDatabase();
            _customersCollection = GetDatabaseCollection<Customer>(CUSTOMERS_COLLECTION);
        }

        [Test]
        public void TestMigrations()
        {
            _customersCollection.Insert(new CustomerOld {Name = "Miss Chanandler Bong"});

            var customer = _customersCollection.AsQueryable().First();
            _customersCollection.Save(customer);

            customer = _customersCollection.AsQueryable().First();
            Assert.That(customer.Title, Is.EqualTo("Miss"));
            Assert.That(customer.FirstName, Is.EqualTo("Chanandler"));
            Assert.That(customer.LastName, Is.EqualTo("Bong"));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 *
 */
namespace Mvc5\Response\Emitter;

use Mvc5\Response\Emitter;

use function passthru;

class PassThru
    implements Emitter
{
    /**
     * @var string
     */
    protected $command;

    /**
     * @param string $command
     */
    function __construct(string $command)
    {
        $this->command = $command;
    }

    /**
     *
     */
    function emit() : void
    {
        passthru($this->command);
    }
}


text:
// qualifiedname.go
package utils

import (
	"github.com/stretchr/testify/assert"
	"testing"
)

func TestLicenseLocalValidation(t *testing.T) {
	assert.False(t, LicenseLocalValidation("---"))
	assert.True(t, LicenseLocalValidation("Apache-2.0"))
	assert.True(t, LicenseLocalValidation("0BSD"))
	assert.True(t, LicenseLocalValidation("0bsd"))
	assert.True(t, LicenseLocalValidation("MIT"))
	assert.True(t, LicenseLocalValidation("MIT-feh"))
	assert.True(t, LicenseLocalValidation("BSD-3-Clause-LBNL"))
	assert.False(t, LicenseLocalValidation("GPL-3.0+"))
	assert.False(t, LicenseLocalValidation("Zimbra-1.3"))
	assert.False(t, LicenseLocalValidation("xpp"))
}

func TestLicenseRemoteValidation(t *testing.T) {
	assert.False(t, LicenseRemoteValidation("---"))
	assert.True(t, LicenseRemoteValidation("Apache-2.0"))
	assert.True(t, LicenseRemoteValidation("0BSD"))
	assert.True(t, LicenseRemoteValidation("0bsd"))
	assert.True(t, LicenseRemoteValidation("MIT"))
	assert.True(t, LicenseRemoteValidation("MIT-feh"))
	assert.True(t, LicenseRemoteValidation("BSD-3-Clause-LBNL"))
	assert.True(t, LicenseRemoteValidation("GPL-3.0+"))
	assert.True(t, LicenseRemoteValidation("Zimbra-1.3"))
	assert.True(t, LicenseRemoteValidation("xpp"))
}

func TestCheckLicense(t *testing.T) {
	assert.False(t, CheckLicense("---"))
	assert.True(t, CheckLicense("Apache-2.0"))
	assert.True(t, CheckLicense("0BSD"))
	assert.True(t, CheckLicense("0bsd"))
	assert.True(t, CheckLicense("MIT"))
	assert.True(t, CheckLicense("MIT-feh"))
	assert.True(t, CheckLicense("BSD-3-Clause-LBNL"))
	assert.True(t, CheckLicense("GPL-3.0+"))
	assert.True(t, CheckLicense("Zimbra-1.3"))
	assert.True(t, CheckLicense("xpp"))
}


text:
import glossDecorator, { Gloss, findGlossEntities } from './Gloss';
export { Gloss, findGlossEntities };
export default glossDecorator;


text:
package org.smslib.message;

import java.io.Serializable;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;
import org.smslib.helper.Common;
import org.smslib.message.OutboundMessage.SentStatus;

public abstract class AbstractMessage implements Serializable
{
	public enum Encoding
	{
		Enc7("7"), Enc8("8"), EncUcs2("U"), EncCustom("C");
		private final String shortString;

		private Encoding(String shortString)
		{
			this.shortString = shortString;
		}

		public String toShortString()
		{
			return this.shortString;
		}

		public static Encoding getEncodingFromShortString(String shortString)
		{
			if (shortString.equalsIgnoreCase("7")) return Enc7;
			else if (shortString.equalsIgnoreCase("8")) return Enc8;
			else if (shortString.equalsIgnoreCase("U")) return EncUcs2;
			else if (shortString.equalsIgnoreCase("C")) return EncCustom;
			else return null;
		}
	}

	public enum DcsClass
	{
		None, Flash, Me, Sim, Te
	}

	public enum Type
	{
		Inbound, Outbound, StatusReport
	}

	private static final long serialVersionUID = 1L;

	Date creationDate = new Date();

	String id = UUID.randomUUID().toString();

	MsIsdn originatorAddress = new MsIsdn();

	MsIsdn recipientAddress = new MsIsdn();

	Payload payload = new Payload("");

	Type type = Type.Inbound;

	Encoding encoding = Encoding.Enc7;

	DcsClass dcsClass = DcsClass.Sim;

	String gatewayId = "";

	int sourcePort = -1;

	int destinationPort = -1;

	Date sentDate = null;

	public AbstractMessage()
	{
	}

	public AbstractMessage(AbstractMessage m)
	{
		this.creationDate = m.getCreationDate();
		this.originatorAddress = new MsIsdn(m.getOriginatorAddress());
		this.recipientAddress = new MsIsdn(m.getRecipientAddress());
		this.payload = new Payload(m.getPayload());
		this.type = m.getType();
		this.encoding = m.getEncoding();
		this.dcsClass = m.getDcsClass();
		this.gatewayId = m.getGatewayId();
		this.sourcePort = m.getSourcePort();
		this.destinationPort = m.getDestinationPort();
		this.sentDate = m.getSentDate();
	}

	public AbstractMessage(Type type, MsIsdn originatorAddress, MsIsdn recipientAddress, Payload payload)
	{
		setType(type);
		setOriginatorAddress(originatorAddress);
		setRecipientAddress(recipientAddress);
		setPayload(payload);
	}

	public String getId()
	{
		return this.id;
	}

	public void setId(String id)
	{
		this.id = id;
	}

	public Date getCreationDate()
	{
		return this.creationDate;
	}

	public MsIsdn getOriginatorAddress()
	{
		return this.originatorAddress;
	}

	public void setOriginatorAddress(MsIsdn originator)
	{
		this.originatorAddress = originator;
	}

	public MsIsdn getRecipientAddress()
	{
		return this.recipientAddress;
	}

	public void setRecipientAddress(MsIsdn recipient)
	{
		this.recipientAddress = recipient;
	}

	public Payload getPayload()
	{
		return this.payload;
	}

	public void setPayload(Payload payload)
	{
		this.payload = payload;
	}

	public Type getType()
	{
		return this.type;
	}

	public void setType(Type type)
	{
		this.type = type;
	}

	public Encoding getEncoding()
	{
		return this.encoding;
	}

	public void setEncoding(Encoding encoding)
	{
		this.encoding = encoding;
	}

	public DcsClass getDcsClass()
	{
		return this.dcsClass;
	}

	public void setDcsClass(DcsClass dcsClass)
	{
		this.dcsClass = dcsClass;
	}

	public String getGatewayId()
	{
		return this.gatewayId;
	}

	public void setGatewayId(String gatewayId)
	{
		this.gatewayId = gatewayId;
	}

	public int getSourcePort()
	{
		return this.sourcePort;
	}

	public void setSourcePort(int sourcePort)
	{
		this.sourcePort = sourcePort;
	}

	public int getDestinationPort()
	{
		return this.destinationPort;
	}

	public void setDestinationPort(int destinationPort)
	{
		this.destinationPort = destinationPort;
	}

	public Date getSentDate()
	{
		return (this.sentDate != null ? (Date) this.sentDate.clone() : null);
	}

	public void setSentDate(Date sentDate)
	{
		this.sentDate = new Date(sentDate.getTime());
	}

	public abstract String getSignature();

	public abstract String toShortString();

	public String hashSignature(String s)
	{
		try
		{
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(s.getBytes(), 0, s.length());
			BigInteger i = new BigInteger(1, md.digest());
			return String.format("%1$032x", i);
		}
		catch (NoSuchAlgorithmException e)
		{
			throw new RuntimeException(e);
		}
	}

	@Override
	public String toString()
	{
		StringBuffer b = new StringBuffer(1024);
		b.append("%n== MESSAGE START ======================================================================%n");
		b.append(String.format("CLASS: %s%n", this.getClass().toString()));
		b.append(String.format("Message ID: %s%n", getId()));
		b.append(String.format("Message Signature: %s%n", getSignature()));
		b.append(String.format("Via Gateway: %s%n", getGatewayId() == null ? "N/A" : getGatewayId()));
		b.append(String.format("Creation Date: %s%n", getCreationDate()));
		b.append(String.format("Type: %s%n", getType()));
		b.append(String.format("Encoding: %s%n", getEncoding()));
		b.append(String.format("DCS Class: %s%n", getDcsClass()));
		b.append(String.format("Source Port: %s%n", getSourcePort()));
		b.append(String.format("Destination Port: %s%n", getDestinationPort()));
		b.append(String.format("Originator Address: %s%n", getOriginatorAddress()));
		b.append(String.format("Recipient Address: %s%n", getRecipientAddress()));
		if (getPayload() != null)
		{
			b.append(String.format("Payload Type: %s%n", getPayload().getType()));
			b.append(String.format("Text payload: %s%n", (getPayload().getText() == null ? "null" : getPayload().getText())));
			b.append(String.format("Binary payload: %s%n", (getPayload().getBytes() == null ? "null" : Common.bytesToString(getPayload().getBytes()))));
		}
		if (this instanceof InboundMessage)
		{
			b.append(String.format("Sent Date: %s%n", getSentDate()));
			b.append(String.format("Memory Storage Location: %s%n", ((InboundMessage) this).getMemLocation()));
			b.append(String.format("Memory Index: %d%n", ((InboundMessage) this).getMemIndex()));
			b.append(String.format("Memory MP Index: %s%n", ((InboundMessage) this).getMpMemIndex()));
		}
		if (this instanceof InboundEncryptedMessage)
		{
			try
			{
				b.append(String.format("Decrypted binary payload: %s%n", Common.bytesToString(((InboundEncryptedMessage) this).getDecryptedData())));
			}
			catch (Exception e)
			{
				b.append(String.format("Cannot decrypt, due to %s.", e.getMessage()));
			}
		}
		if (this instanceof OutboundMessage)
		{
			b.append(String.format("Sent Date: %s%n", (((OutboundMessage) this).getSentStatus() == SentStatus.Sent ? getSentDate() : "N/A")));
			String ids = "";
			for (String opId : ((OutboundMessage) this).getOperatorMessageIds())
			{
				ids += (ids.length() == 0 ? opId : "," + opId);
			}
			b.append(String.format("Operator Message IDs: %s%n", ids));
			b.append(String.format("Status: %s%n", ((OutboundMessage) this).getSentStatus().toString()));
			b.append(String.format("Credits used: %f%n", ((OutboundMessage) this).getCreditsUsed()));
			b.append(String.format("Failure: %s%n", ((OutboundMessage) this).getFailureCause().toString()));
			b.append(String.format("Operator Failure Code: %s%n", ((OutboundMessage) this).getOperatorFailureCode()));
			b.append(String.format("Request Delivery Reports: %b%n", ((OutboundMessage) this).getRequestDeliveryReport()));
		}
		if (this instanceof DeliveryReportMessage)
		{
			b.append(String.format("Original Operator Message Id: %s%n", ((DeliveryReportMessage) this).getOriginalOperatorMessageId()));
			b.append(String.format("Delivery Date: %s%n", ((DeliveryReportMessage) this).getOriginalReceivedDate()));
			b.append(String.format("Delivery Status: %s%n", ((DeliveryReportMessage) this).getDeliveryStatus()));
		}
		b.append("== MESSAGE END ========================================================================%n");
		return b.toString();
	}
}


text:
define({
  "_widgetLabel": "Filter",
  "toggleTip": "Klik for at vise/skjule filterindstillingerne",
  "toggleOn": "Tryk på til/fra-knappen for at aktivere det aktuelle filter",
  "toggleOff": "Tryk på til/fra-knappen for at deaktivere det aktuelle filter",
  "filterActions": "Filterhandlinger",
  "resetAll": "Nulstil alle inputværdier",
  "turnOffAll": "Slå alle filtre fra",
  "createCustomFilter": "Opret brugerdefineret filter",
  "customFilter": "Brugerdefineret filter",
  "toggleCustomFilter": "Slå filteret til eller fra",
  "toggleCustomFilters": "Slå alle filtre til og fra"
});


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**pricing_tiers** | [**\ArtikCloud\ArtikCloud\Model\DevicePricingTier[]**](DevicePricingTier.md) | Pricing Tiers list | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
namespace Aliyun.OSS
{
    /// <summary>
    /// The result class of operation to complete a multipart upload.
    /// </summary>
    public class CompleteMultipartUploadResult : PutObjectResult
    {
        /// <summary>
        /// Bucket name getter/setter
        /// </summary>
        public string BucketName { get; internal set; }

        /// <summary>
        /// Object key's getter/setter.
        /// </summary>
        public string Key { get; internal set; }

        /// <summary>
        /// The new object' URL
        /// </summary>
        public string Location { get; internal set; }

        internal CompleteMultipartUploadResult()
        { }
    }
}


text:
/// QAS Pro Web integration code
/// (c) Experian, www.edq.com
namespace Experian.Qas.Prowebintegration
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using Experian.Qas.Proweb;

    /// <summary>
    /// Scenario "Address Capture on the Web" - flattened picklists
    /// Search on the input lines and display a picklist of results, then take them to the final address page,
    /// or refinement page if required. Will skip past this page if there's only one match.
    /// This page is based on FlatBasePage, which provides functionality common to the scenario
    /// </summary>
    public partial class FlatSearch : FlatBasePage
    {
        // Name of field in private data form
        protected const string FIELD_MUST_REFINE = "MustRefine";
        // Member
        protected Picklist m_Picklist = null;

        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (!IsPostBack)
            {
                DoSearch();
            }
            // Else leave it to the event handlers (Next, Back)
        }

        /** Search operations **/

        /// <summary>
        /// Perform search using DataID and InputLines
        /// </summary>
        private void DoSearch()
        {
            Constants.Routes eRoute = Constants.Routes.Undefined;

            // If the picklist moniker is not present then we haven't been here before, and can auto-skip forwards
         bool bAutoSkip = (GetPicklistMoniker() == null);

            try
            {
                IAddressLookup searchService = QAS.GetSearchService();
                searchService.CurrentEngine.EngineType = Engine.EngineTypes.Singleline;
                searchService.CurrentEngine.Flatten = true;

                if (bAutoSkip)
                {
                    m_Picklist = searchService.Search(GetDataID(), GetInputLine(), GetPromptSet(), GetLayout()).Picklist;

                    while ( m_Picklist.IsAutoStepinSafe )
                    {
                        m_Picklist = searchService.StepIn(m_Picklist.PicklistItems[0].Moniker, GetLayout());
                    }

                    SetPicklistMoniker(m_Picklist.Moniker);
                }
                else
                {
                    // Recreate picklist from moniker
                    m_Picklist = searchService.StepIn(GetPicklistMoniker(), GetLayout());
                }

                // Handle 'failure' cases
                if (m_Picklist.IsTimeout)
                {
                    eRoute = Constants.Routes.Timeout;
                }
                else if (m_Picklist.IsMaxMatches)
                {
                    eRoute = Constants.Routes.TooManyMatches;
                }
                else if (m_Picklist.PicklistItems == null || m_Picklist.Total == 0)
                {
                    eRoute = Constants.Routes.NoMatches;
                }
            }
            catch (Exception x)
            {
                GoErrorPage(x);
            }

            if (!eRoute.Equals(Constants.Routes.Undefined))
            {
                GoErrorPage(eRoute);
            }
            else if (bAutoSkip)
            {
                if (m_Picklist.IsAutoFormatSafe || m_Picklist.IsAutoFormatPastClose)
                {
                    // Auto-step past picklist to format page
                    GoFormatPage(m_Picklist.PicklistItems[0].Moniker);
                }
                else if (m_Picklist.PicklistItems.Count == 1 && MustRefine(m_Picklist.PicklistItems[0]))
                {
                    // Auto-step past picklist to refinement page
                    GoRefinementPage(m_Picklist.PicklistItems[0].Moniker);
                }
            }
            // Else let page render the picklist itself
        }

        /// <summary>
        /// Helper function: must the picklist item be refined (extra text entered)
        /// </summary>
        protected bool MustRefine(PicklistItem item)
        {
            return (item.IsIncompleteAddress
                || item.IsUnresolvableRange
                || item.IsPhantomPrimaryPoint);
        }

        /** Page events **/

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {

        }
        #endregion

        /// <summary>
        /// 'Back' button clicked: return to the search terms Input page
        /// </summary>
        protected void ButtonBack_ServerClick(object sender, System.EventArgs e)
        {
            GoInputPage();
        }

        /// <summary>
        /// 'Next' button clicked: go forward to the refinement page if required, or format address page
        /// </summary>
        protected void ButtonNext_ServerClick(object sender, System.EventArgs e)
        {
            // Pick up hidden field, set by client JavaScript when they selected an item
            bool bMustRefine = !Request[FIELD_MUST_REFINE].Equals("");
            if (bMustRefine)
            {
                GoRefinementPage(GetMoniker());
            }
            else
            {
                GoFormatPage(null);					// Moniker already set on page
            }
        }
    }
}


text:
const test = require("tape");
const path = require("path");
const load = require("load-json-file");
const write = require("write-json-file");
const directionalMean = require("./index").default;

test("turf-directional-mean", (t) => {
  const outGpsJsonPath1 = path.join(
    __dirname,
    "test",
    "out",
    "bus_route_gps1.json"
  );
  const outGpsJsonPath2 = path.join(
    __dirname,
    "test",
    "out",
    "bus_route_gps2.json"
  );
  const outUtmJsonPath1 = path.join(
    __dirname,
    "test",
    "out",
    "bus_route_utm1.json"
  );
  const outUtmJsonPath2 = path.join(
    __dirname,
    "test",
    "out",
    "bus_route_utm2.json"
  );

  const utmFilepath = path.join(__dirname, "test", "in", "bus_route_utm.json");
  const utmGeojson = load.sync(utmFilepath);

  const gpsFilepath = path.join(__dirname, "test", "in", "bus_route_gps.json");
  const gpsGeojson = load.sync(gpsFilepath);

  // utm
  let utmResult1 = directionalMean(utmGeojson, {
    planar: true,
    segment: false,
  });
  t.deepEqual(utmResult1, load.sync(outUtmJsonPath1), "utm");
  // utm segment
  let utmResult2 = directionalMean(utmGeojson, {
    planar: true,
    segment: true,
  });
  t.deepEqual(utmResult2, load.sync(outUtmJsonPath2), "utm segment");

  // gps
  let gpsResult1 = directionalMean(gpsGeojson, {
    planar: false,
  });
  t.deepEqual(gpsResult1, load.sync(outGpsJsonPath1), "gps");
  // gps segment
  let gpsResult2 = directionalMean(gpsGeojson, {
    planar: false,
    segment: true,
  });
  t.deepEqual(gpsResult2, load.sync(outGpsJsonPath2), "gps segment");

  if (process.env.REGEN) {
    write.sync(outGpsJsonPath1, gpsResult1);
    write.sync(outGpsJsonPath2, gpsResult2);
    write.sync(outUtmJsonPath1, utmResult1);
    write.sync(outUtmJsonPath2, utmResult2);
  }

  t.end();
});


text:
{% extends "base.html" %}
{% comment %}

Copyright (c) 2017, Evan Moritz.

botw-tracker is an open source software project released under the MIT License.
See the accompanying LICENSE file for terms.

{% endcomment %}
{% load static %}
{% load questentry_extras %}

{% block head %}
<link rel="stylesheet" href="{% static 'user/css/profile.css' %}">

{% endblock %}

{% block content %}

Profile: {{ object.user.username }}

{% for quest_type, quest_description in view.get_quest_types %}
{{ quest_description }}
{% endfor %}

{% for quest_type, quest_description in view.get_quest_types %}

{{ quest_description }}

Active

        {% if user.is_authenticated and view.get_user_id == user.id %}
            {% include 'user/questentry_list_owner.html' with list=object.questentry_set|in_category:quest_type|completion_status:False %}
        {% else %}
            {% include 'user/questentry_list_anon.html' with list=object.questentry_set|in_category:quest_type|completion_status:False %}
        {% endif %}

Completed

        {% if user.is_authenticated and view.get_user_id == user.id %}
            {% include 'user/questentry_list_owner.html' with list=object.questentry_set|in_category:quest_type|completion_status:True %}
        {% else %}
            {% include 'user/questentry_list_anon.html' with list=object.questentry_set|in_category:quest_type|completion_status:True %}
        {% endif %}
        {% if user.is_authenticated and view.get_user_id == user.id %}

Undiscovered

+

                {% for quest in view.get_undiscovered_quests|in_category:quest_type %}
                    {% include 'user/quest_detail.html' %}
                {% endfor %}

        {% endif %}

{% endfor %}

{% endblock %}


text:
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="@android:color/darker_gray" />
    <stroke
        android:width="4dp"
        android:color="@android:color/white" />
</shape>


text:
import static org.junit.Assert.*;

import java.util.TreeMap;

import org.junit.Test;

public class HashTreeComparatorTest {
	Node n1 = new Node(1L);
	Node n2 = new Node(2L);
	Node n3 = new Node(3L);
	Node n4 = new Node(4L);
	Node n5 = new Node(5L);
	@Test
	public void test() {
		TreeMapComparator comp = new TreeMapComparator();
		TreeMap<Long, Node> hashTree1 = new TreeMap<Long, Node>();
		TreeMap<Long, Node> hashTree2 = new TreeMap<Long, Node>();

		hashTree1.put(4L, n1);
		hashTree1.put(2L, n2);
		//hashTree1.put(3L, n3);
		//hashTree2.put(1L, n4);
		hashTree2.put(2L, n4);
		hashTree2.put(7L, n5);

		//System.out.println("whas?" + ((Long) 1L).compareTo((Long) 4L));
		System.out.println(comp.compare(hashTree1, hashTree2));

	}

}


text:
package monix.execution.misc

import monix.execution.Callback
import monix.execution.atomic.PaddingStrategy.NoPadding
import monix.execution.atomic.{AtomicAny, PaddingStrategy}

import scala.annotation.tailrec
import scala.collection.immutable.Queue
import scala.concurrent.{Future, Promise}

/** Asynchronous mutable location, that is either empty or contains
  * a value of type `A`.
  *
  * It has 2 fundamental atomic operations:
  *
  *  - [[put]] which fills the var if empty, or blocks
  *    (asynchronously) otherwise until the var is empty again
  *
  *  - [[take]] which empties the var if full, returning the contained
  *    value, or blocks (asynchronously) otherwise until there is
  *    a value to pull
  *
  * The `AsyncVar` is appropriate for building synchronization
  * primitives and performing simple inter-thread communications.
  * If it helps, it's similar with a `BlockingQueue(capacity = 1)`,
  * except that it doesn't block any threads, all waiting being
  * callback-based.
  *
  * Given its asynchronous, non-blocking nature, it can be used on
  * top of Javascript as well.
  *
  * Inspired by `Control.Concurrent.MVar` from Haskell.
  */
final class AsyncVar[A] private (_ref: AtomicAny[AsyncVar.State[A]]) {
  import AsyncVar._
  private[this] val stateRef: AtomicAny[State[A]] = _ref

  private def this(ps: PaddingStrategy) =
    this(AtomicAny.withPadding(AsyncVar.State.empty[A], ps))
  private def this(initial: A, ps: PaddingStrategy) =
    this(AtomicAny.withPadding(AsyncVar.State(initial), ps))

  /** Fills the `AsyncVar` if it is empty, or blocks (asynchronously)
    * if the `AsyncVar` is full, until the given value is next in
    * line to be consumed on [[take]].
    *
    * This operation is atomic.
    *
    * @see [[unsafePut]] for the raw, unsafe version that can work
    *     with plain callbacks.
    *
    * @return a future that will complete when the `put` operation
    *         succeeds in filling the `AsyncVar`, with the given
    *         value being next in line to be consumed
    */
  def put(a: A): Future[Unit] = {
    val p = Promise[Unit]()
    if (unsafePut(a, Callback.fromPromise(p))) Future.successful(())
    else p.future
  }

  /** Fills the `AsyncVar` if it is empty, or blocks (asynchronously)
    * if the `AsyncVar` is full, until the given value is next in
    * line to be consumed on [[take]] (or [[unsafeTake]]).
    *
    * This operation is atomic.
    *
    * @see [[put]] for the safe future-enabled version.
    *
    * @param a is the value to store
    * @param await is a callback that, only in case of asynchronous blocking,
    *        will get called when the blocking is over and the operation
    *        succeeded
    *
    * @return `true` if the operation succeeded already, with no
    *        blocking necessary, or `false` if the operation
    *        is blocked because the var is already full
    */
  @tailrec def unsafePut(a: A, await: Callback[Nothing, Unit]): Boolean = {
    if (a == null) throw new NullPointerException("null not supported in AsyncVar/MVar")
    val current: State[A] = stateRef.get

    current match {
      case _: Empty[_] =>
        if (stateRef.compareAndSet(current, WaitForTake(a, Queue.empty))) true
        else unsafePut(a, await) // retry

      case WaitForTake(value, queue) =>
        val update = WaitForTake(value, queue.enqueue(a -> await))
        if (stateRef.compareAndSet(current, update)) false
        else unsafePut(a, await) // retry

      case current @ WaitForPut(first, queue) =>
        if (stateRef.compareAndSet(current, current.dequeue)) { first.onSuccess(a); true }
        else unsafePut(a, await) // retry
    }
  }

  /** Empties the var if full, returning the contained value,
    * or blocks (asynchronously) until a value is available.
    *
    * This operation is atomic.
    *
    * @see [[unsafeTake]] for the raw, unsafe version that can work
    *     with plain callbacks.
    */
  def take: Future[A] = {
    val p = Promise[A]()
    unsafeTake(Callback.fromPromise(p)) match {
      case null => p.future
      case a => Future.successful(a)
    }
  }

  /** Empties the var if full, returning the contained value,
    * or blocks (asynchronously) until a value is available.
    *
    * This operation is atomic.
    *
    * @see [[take]] for the safe future-enabled version.
    *
    * @param await is a callback that, only in case of asynchronous blocking,
    *        will get called sometime in the future with a value
    *
    * @return a value of type `A` if the operation succeeded already,
    *         with no blocking necessary, or `null` if async blocking
    *         is in progress (in which case the `await` callback
    *         gets called with the result)
    */
  @tailrec def unsafeTake(await: Callback[Nothing, A]): A = {
    @inline def nil = null.asInstanceOf[A]

    val current: State[A] = stateRef.get
    current match {
      case _: Empty[_] =>
        if (stateRef.compareAndSet(current, WaitForPut(await, Queue.empty))) nil
        else unsafeTake(await) // retry

      case WaitForTake(value, queue) =>
        if (queue.isEmpty) {
          if (stateRef.compareAndSet(current, State.empty)) value
          else unsafeTake(await)
        }
        else {
          val ((ax, notify), xs) = queue.dequeue
          if (stateRef.compareAndSet(current, WaitForTake(ax, xs))) {
            notify.onSuccess(()) // notification
            value
          } else {
            unsafeTake(await) // retry
          }
        }

      case WaitForPut(first, queue) =>
        if (stateRef.compareAndSet(current, WaitForPut(first, queue.enqueue(await)))) nil
        else unsafeTake(await)
    }
  }

  /** Tries reading the current value, or blocks (asynchronously)
    * otherwise, until there is a value available, at which point
    * the operation resorts to a `take` followed by a `put`.
    *
    * This `read` operation is equivalent to:
    * {{{
    *   for (a <- v.take; _ <- v.put(a)) yield a
    * }}}
    *
    * This operation is not atomic. Being equivalent with a `take`
    * followed by a `put`, in order to ensure that no race conditions
    * happen, additional synchronization is necessary.
    * See [[AsyncSemaphore]] for a possible solution.
    *
    * @see [[unsafeRead]] for the raw, unsafe version that can work
    *     with plain callbacks.
    *
    * @return a future that might already be completed in case the
    *         result is available immediately
    */
  def read: Future[A] = {
    val p = Promise[A]()
    unsafeRead(Callback.fromPromise(p)) match {
      case null => p.future
      case a => Future.successful(a)
    }
  }

  /** Tries reading the current value, or blocks (asynchronously)
    * otherwise, until there is a value available, at which point
    * the operation resorts to a `take` followed by a `put`.
    *
    * This `read` operation is equivalent to:
    * {{{
    *   for (a <- v.take; _ <- v.put(a)) yield a
    * }}}
    *
    * This operation is not atomic. Being equivalent with a `take`
    * followed by a `put`, in order to ensure that no race conditions
    * happen, additional synchronization is necessary.
    * See [[AsyncSemaphore]] for a possible solution.
    *
    * @see [[read]] for the safe future-enabled version.
    *
    * @param await is a callback that, only in case of asynchronous blocking,
    *        will get called sometime in the future with a value
    *
    * @return a value of type `A` if the operation succeeded already,
    *         with no blocking necessary, or `null` if async blocking
    *         is in progress (in which case the `await` callback
    *         gets called with the result)
    */
  def unsafeRead(await: Callback[Nothing, A]): A = {
    // To be used with unsafePut
    def awaitPut(a: A): Callback[Nothing, Unit] = new Callback[Nothing, Unit] {
      def onError(e: Nothing): Unit = ()
      def onSuccess(value: Unit): Unit =
        await.onSuccess(a)
    }
    // To be used with unsafeTake
    def awaitTake: Callback[Nothing, A] = new Callback[Nothing, A] {
      def onError(e: Nothing): Unit = ()
      def onSuccess(value: A): Unit = {
        // Execution could be synchronous
        if (unsafePut(value, awaitPut(value)))
          await.onSuccess(value)
      }
    }

    (stateRef.get : State[A]) match {
      case WaitForTake(value, _) => value // Fast-path
      case _ =>
        // Doing the equivalent of:
        // for (a <- take; _ <- put(a)) yield a
        unsafeTake(awaitTake) match {
          case null =>
            // Async execution
            null.asInstanceOf[A]
          case value =>
            if (unsafePut(value, awaitPut(value))) value
            else null.asInstanceOf[A] // Async execution
        }
    }
  }
}

object AsyncVar {
  /** Builds an [[AsyncVar]] instance with an `initial` value. */
  def apply[A](initial: A): AsyncVar[A] =
    new AsyncVar[A](initial, NoPadding)

  /** Returns an empty [[AsyncVar]] instance. */
  def empty[A]: AsyncVar[A] =
    new AsyncVar[A](NoPadding)

  /** Builds an [[AsyncVar]] instance with an `initial` value and a given
    * [[monix.execution.atomic.PaddingStrategy PaddingStrategy]]
    * (for avoiding the false sharing problem).
    */
  def withPadding[A](initial: A, ps: PaddingStrategy): AsyncVar[A] =
    new AsyncVar[A](initial, ps)

  /** Builds an empty [[AsyncVar]] instance with a given
    * [[monix.execution.atomic.PaddingStrategy PaddingStrategy]]
    * (for avoiding the false sharing problem).
    */
  def withPadding[A](ps: PaddingStrategy): AsyncVar[A] =
    new AsyncVar[A](ps)

  /** ADT modelling the internal state of [[AsyncVar]]. */
  private sealed trait State[A]

  /** Private [[State]] builders.*/
  private object State {
    private[this] val ref = Empty()
    def apply[A](a: A): State[A] = WaitForTake(a, Queue.empty)
    /** `Empty` state, reusing the same instance. */
    def empty[A]: State[A] = ref.asInstanceOf[State[A]]
  }

  /** `AsyncVar` state signaling an empty location.
    *
    * Evolves into [[WaitForPut]] or [[WaitForTake]],
    * depending on which operation happens first.
    */
  private final case class Empty[A]() extends State[A]

  /** `AsyncVar` state signaling it has `take` callbacks
    * registered and we are waiting for one or multiple
    * `put` operations.
    *
    * @param first is the first request waiting in line
    * @param queue are the rest of the requests waiting in line,
    *        if more than one `take` requests were registered
    */
  private final case class WaitForPut[A](first: Callback[Nothing, A], queue: Queue[Callback[Nothing, A]])
    extends State[A] {

    def dequeue: State[A] =
      if (queue.isEmpty) State.empty[A] else {
        val (x, xs) = queue.dequeue
        WaitForPut(x, xs)
      }
  }

  /** `AsyncVar` state signaling it has one or more values enqueued,
    * to be signaled on the next `take`.
    *
    * @param value is the first value to signal
    * @param queue are the rest of the `put` requests, along with the
    *        callbacks that need to be called whenever the corresponding
    *        value is first in line (i.e. when the corresponding `put`
    *        is unblocked from the user's point of view)
    */
  private final case class WaitForTake[A](value: A, queue: Queue[(A, Callback[Nothing, Unit])])
    extends State[A]
}


text:
.. _zend.navigation.view.helper.sitemap:

View Helper - Sitemap
=====================

The Sitemap helper is used for generating *XML* sitemaps, as defined by the `Sitemaps XML format`_. Read more about
`Sitemaps on Wikipedia`_.

By default, the sitemap helper uses :ref:`sitemap validators <zend.validator.sitemap>` to validate each element
that is rendered. This can be disabled by calling *$helper->setUseSitemapValidators(false)*.

.. note::

   If you disable sitemap validators, the custom properties (see table) are not validated at all.

The sitemap helper also supports `Sitemap XSD Schema`_ validation of the generated sitemap. This is disabled by
default, since it will require a request to the Schema file. It can be enabled with
*$helper->setUseSchemaValidation(true)*.

.. _zend.navigation.view.helper.sitemap.elements:

.. table:: Sitemap XML elements

   +----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
   |Element   |Description                                                                                |
   +==========+======================================================================================================================================================================================================================================================================================================================================================================================================+
   |loc       |Absolute URL to page. An absolute URL will be generated by the helper.                                                                                |
   +----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
   |lastmod   |The date of last modification of the file, in W3C Datetime format. This time portion can be omitted if desired, and only use YYYY-MM-DD. The helper will try to retrieve the lastmod value from the page's custom property lastmod if it is set in the page. If the value is not a valid date, it is ignored.                                                                                |
   +----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
   |changefreq|How frequently the page is likely to change. This value provides general information to search engines and may not correlate exactly to how often they crawl the page. Valid values are: alwayshourlydailyweeklymonthlyyearlynever The helper will try to retrieve the changefreq value from the page's custom property changefreq if it is set in the page. If the value is not valid, it is ignored.|
   +----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
   |priority  |The priority of this URL relative to other URLs on your site. Valid values range from 0.0 to 1.0. The helper will try to retrieve the priority value from the page's custom property priority if it is set in the page. If the value is not valid, it is ignored.                                                                                |
   +----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

Methods in the sitemap helper:

- *{get|set}FormatOutput()* gets/sets a flag indicating whether *XML* output should be formatted. This corresponds
  to the *formatOutput* property of the native ``DOMDocument`` class. Read more at `PHP: DOMDocument - Manual`_.
  Default is ``FALSE``.

- *{get|set}UseXmlDeclaration()* gets/sets a flag indicating whether the *XML* declaration should be included when
  rendering. Default is ``TRUE``.

- *{get|set}UseSitemapValidators()* gets/sets a flag indicating whether sitemap validators should be used when
  generating the DOM sitemap. Default is ``TRUE``.

- *{get|set}UseSchemaValidation()* gets/sets a flag indicating whether the helper should use *XML* Schema
  validation when generating the DOM sitemap. Default is ``FALSE``. If ``TRUE``.

- *{get|set}ServerUrl()* gets/sets server *URL* that will be prepended to non-absolute *URL*\ s in the ``url()``
  method. If no server *URL* is specified, it will be determined by the helper.

- ``url()`` is used to generate absolute *URL*\ s to pages.

- ``getDomSitemap()`` generates a DOMDocument from a given container.

.. _zend.navigation.view.helper.sitemap.example:

.. rubric:: Rendering an XML sitemap

This example shows how to render an *XML* sitemap based on the setup we did further up.

.. code-block:: php
   :linenos:

   // In a view script or layout:

   // format output
   $this->navigation()
         ->sitemap()
         ->setFormatOutput(true); // default is false

   // other possible methods:
   // ->setUseXmlDeclaration(false); // default is true
   // ->setServerUrl('http://my.otherhost.com');
   // default is to detect automatically

   // print sitemap
   echo $this->navigation()->sitemap();

Notice how pages that are invisible or pages with *ACL* roles incompatible with the view helper are filtered out:

.. code-block:: xml
   :linenos:

   <?xml version="1.0" encoding="UTF-8"?>
   <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
     <url>
       <loc>http://www.example.com/</loc>
     </url>
     <url>
       <loc>http://www.example.com/products</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/server</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/server/faq</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/server/editions</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/server/requirements</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/studio</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/studio/customers</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/studio/support</loc>
     </url>
     <url>
       <loc>http://www.example.com/company/about</loc>
     </url>
     <url>
       <loc>http://www.example.com/company/about/investors</loc>
     </url>
     <url>
       <loc>http://www.example.com/company/news</loc>
     </url>
     <url>
       <loc>http://www.example.com/company/news/press</loc>
     </url>
     <url>
       <loc>http://www.example.com/archive</loc>
     </url>
     <url>
       <loc>http://www.example.com/community</loc>
     </url>
     <url>
       <loc>http://www.example.com/community/account</loc>
     </url>
     <url>
       <loc>http://forums.example.com/</loc>
     </url>
   </urlset>

Render the sitemap using no *ACL* role (should filter out /community/account):

.. code-block:: php
   :linenos:

   echo $this->navigation()
             ->sitemap()
             ->setFormatOutput(true)
             ->setRole();

.. code-block:: xml
   :linenos:

   <?xml version="1.0" encoding="UTF-8"?>
   <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
     <url>
       <loc>http://www.example.com/</loc>
     </url>
     <url>
       <loc>http://www.example.com/products</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/server</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/server/faq</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/server/editions</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/server/requirements</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/studio</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/studio/customers</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/studio/support</loc>
     </url>
     <url>
       <loc>http://www.example.com/company/about</loc>
     </url>
     <url>
       <loc>http://www.example.com/company/about/investors</loc>
     </url>
     <url>
       <loc>http://www.example.com/company/news</loc>
     </url>
     <url>
       <loc>http://www.example.com/company/news/press</loc>
     </url>
     <url>
       <loc>http://www.example.com/archive</loc>
     </url>
     <url>
       <loc>http://www.example.com/community</loc>
     </url>
     <url>
       <loc>http://forums.example.com/</loc>
     </url>
   </urlset>

Render the sitemap using a maximum depth of 1.

.. code-block:: php
   :linenos:

   echo $this->navigation()
             ->sitemap()
             ->setFormatOutput(true)
             ->setMaxDepth(1);

.. code-block:: xml
   :linenos:

   <?xml version="1.0" encoding="UTF-8"?>
   <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
     <url>
       <loc>http://www.example.com/</loc>
     </url>
     <url>
       <loc>http://www.example.com/products</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/server</loc>
     </url>
     <url>
       <loc>http://www.example.com/products/studio</loc>
     </url>
     <url>
       <loc>http://www.example.com/company/about</loc>
     </url>
     <url>
       <loc>http://www.example.com/company/about/investors</loc>
     </url>
     <url>
       <loc>http://www.example.com/company/news</loc>
     </url>
     <url>
       <loc>http://www.example.com/community</loc>
     </url>
     <url>
       <loc>http://www.example.com/community/account</loc>
     </url>
     <url>
       <loc>http://forums.example.com/</loc>
     </url>
   </urlset>

.. note::

   **UTF-8 encoding used by default**

   By default, Zend Framework uses *UTF-8* as its default encoding, and, specific to this case, ``Zend\View`` does
   as well. So if you want to use another encoding with ``Sitemap``, you will have do three things:
      1. Create a custom renderer and implement a ``getEncoding()`` method;
      2. Create a custom rendering strategy that will return an instance of your custom renderer;
      3. Attach the custom strategy in the ``ViewEvent``;

   See the :ref:`example from **headStile** documentation <zend.view.helpers.initial.headstyle.encoding.example>`
   to see how you can achieve this.

.. _`Sitemaps XML format`: http://www.sitemaps.org/protocol.php
.. _`Sitemaps on Wikipedia`: http://en.wikipedia.org/wiki/Sitemaps
.. _`Sitemap XSD Schema`: http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
.. _`PHP: DOMDocument - Manual`: http://php.net/domdocument


text:
%% TestingBehavior class:  class for unit testing Behavior
classdef TestingBehavior < Behavior

    properties
    end
    methods
         function obj = TestingBehavior(prefix, animal, behaviorStatus)
            import uk.ac.imperial.pipe.runner.*;
            obj = obj@Behavior(prefix, animal, behaviorStatus);

         end
         function behaviorStatus = getStandaloneStatus(obj)
            behaviorStatus = TestingBehaviorStatusStandalone('', []);
         end
         function behaviorStatus = getIncludeStatus(obj)
            behaviorStatus = TestingBehaviorStatusInclude('', []);
         end

         function buildStatus(obj, behaviorStatus)
            if (isempty(behaviorStatus))
                obj.behaviorStatus = obj.getStandaloneStatus();
            else
                obj.behaviorStatus = behaviorStatus;
            end

         end
         function getSystemsFromAnimal(obj)
            obj.cortex = obj.animal.cortex;
            obj.motorCortex = obj.animal.motorCortex;
            obj.subCortex = obj.animal.subCortex;
         end
         function buildRunner(obj)
            obj.runner = obj.behaviorStatus.buildRunner();
         end
         function execute(obj)
             obj.behaviorStatus.execute();
         end
        function buildStandardSemantics(obj)
            obj.buildRunner();
            obj.listenPlaces();
        end
        function listenPlaces(obj)
            obj.behaviorStatus.listenPlaces();
        end
        function buildThreadedStandardSemantics(obj)
            obj.behaviorStatus.buildThreadedStandardSemantics();
        end
        function run(obj)
            obj.behaviorStatus.run();
        end
        function acknowledge(obj, place)
           obj.runner.acknowledge(place);
        end
        function resetRandomSeed(obj, reset)
            obj.resetSeed = reset;
        end
        function placeReport = getPlaceReport(obj, index)
           placeReport = obj.runner.getPlaceReport(index);
        end
    end

end


text:
<!--
  ~ Copyright (c) 2014. Pokevian Ltd.
  ~
  ~ 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.
  -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <WebView
            android:id="@+id/web_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <ProgressBar
            android:id="@+id/progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"/>
    </FrameLayout>

</LinearLayout>


text:
'use strict';

const vars = require('js.shared').vars;
const utils = require('js.shared').utils;

const constants = require('./const.js');

exports.error = error;
exports.checkStringNotEmpty = checkStringNotEmpty;
exports.boolValue = boolValue;
exports.getUserName = getUserName;
exports.getObjectId = getObjectId;
exports.parseQuery = parseQuery;

/**
 * Check that given string is not empty
 * @param {string} s the string to check
 * @returns {boolean} true if the given string is define and is not null and has length
 */
function checkStringNotEmpty(s) {
    return (s && typeof s === 'string' && s.trim().length > 0);
}

/**
 * Send an error to the HTTP response
 * @param res   response
 * @param http  HTTP code (400, 401, 403, 409, 500, etc)
 * @param error extended code to be sent as {error:code}
 * @param message error message to be sent as {message:string}
 */
function error(res, http, error, message) {
    if (typeof http === 'undefined') {
        http = 500;
    }
    res
        .status(http)
        .send({
            error: error || http,
            message: message || constants.errorMessage(error)
        });
}

/**
 * Calculate boolean value
 * @param {string|number|boolean} s
 * @return {*}
 */
function boolValue(s) {
    if (s && typeof s === 'boolean') {
        return s;
    }
    if (s) {
        if (typeof s === 'number') {
            return s > 0;
        }
        if (typeof s === 'string') {
            return s.match(/true|yes|1|on/i);
        }
    }
    return false;
}

/**
 * Calculate full user name to be used in emails
 * @param {Object} user user info
 * @returns {string} - user name composed from first and last name or user's login
 */
function getUserName(user) {
    let name = user.Login;
    if (user.FirstName || user.LastName) {
        if (user.FirstName) {
            name = user.FirstName;
            if (user.LastName) {
                name += ' ' + user.LastName;
            }
        } else {
            name = user.LastName;
        }

    }
    return name;
}

/**
 * Extract object (User/Metapublication/Figure) ID from request
 * @param {Object} req
 * @param {Object} res
 * @returns {string} ID
 */
function getObjectId(req, res) {
    let id = vars.get(req, 'ID');
    if (!id) {
        throw {
            http: httpStatus.BAD_REQUEST,
            error: constants.ERROR_BADPARAMETERS,
            message : 'No ID provided'
        };
    }
    return id;
}

/**
 * Parse out search query from input parameters
 * @param {Object[]} tables - list of table descriptors to evaluate query parameters against
 * @param {Object<string, string>} params - input request parameters
 * @returns {CommonResponse} parsed query {Query} in data
 */
function parseQuery(tables, params) {
    /*jshint maxstatements:100 */
    /*jshint maxcomplexity:100 */
    let _query = {
        from: 0,
        size: constants.DEFAULT_PAGE_SIZE,
        sortDirection: constants.SORT_DIRECTION_ASCENDING,
        query: '',
        filters: []
    };

    if (!params) {
        return {data: _query};
    }
    // pagination
    if (utils.isset(params.from)) {
        let i = parseInt(params.from);
        if (!isNaN(i) && i > 0) {
            _query.from = i;
        }
    }
    if (utils.isset(params.size)) {
        let i = parseInt(params.size);
        if (!isNaN(i) && i > 0) {
            _query.size = i;
        }
    }

    // sorting
    // first, assume that sort order can be passed as
    // sort=column:order
    let _sortField = null;
    let _sortDirection = null;
    if (utils.isset(params.sort)) {
        let _re = new RegExp('^([^:]+):(' +
            constants.SORT_DIRECTION_ASCENDING + '|' +
            constants.SORT_DIRECTION_DESCENDING + ')$', 'i');
        let _m = String(params.sort).match(_re);
        if (_m) {
            _sortField = _m[1];
            _sortDirection = _m[2].toUpperCase();
        } else {
            _sortField = String(params.sort);
        }
    }
    if (!_sortField) {
        // just in case: have an ability to set sort field name
        // separately via sortField or sor_field parameter
        let _s = params.sortField || params['sort_field'];
        if (utils.isset(_s)) {
            _sortField = String(_s);
        }
    }
    if (_sortField) {
        _query.sortField = _sortField;
    }

    if (!_sortDirection) {
        let _s = params.sortDirection || params['sort_dir'] || params['dir'];
        if (utils.isset(_s)) {
            _s = String(_s);
            let _re = new RegExp('^' +
                constants.SORT_DIRECTION_ASCENDING + '|' +
                constants.SORT_DIRECTION_DESCENDING + '$', 'i');
            if (_s.match(_re)) {
                _sortDirection = _s.toUpperCase();
            }
        }
    }
    if (_sortDirection) {
        _query.sortDirection = _sortDirection;
    }

    // add main query
    if (utils.isset(params.query)) {
        _query.query = params.query;
    }

    // add filters
    if (tables) {
        tables.forEach((table) => {
            table.columns.forEach((column) => {
                let _f = table.name + '.' + column.name;
                let _lf = _f.toLowerCase();
                Object.keys(params).forEach((k) => {
                    if (k.toLowerCase() === _lf) {
                        if (typeof params[k] !== 'undefined') {
                            _query.filters.push({name: _f, value: params[k]});
                        }
                    }
                });
            });
        });
    }
    return {data: _query};
}


text:
import six.moves.cPickle as pickle
from collections import OrderedDict
import sys, time, os
import numpy as np
import gzip
import theano
from theano import config
theano.config.compute_test_value = 'warn'
from theano.printing import pydotprint
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from utils.optimizer import adam,rmsprop
from utils.misc import saveHDF5
from __init__ import BaseModel

class MLP(BaseModel, object):
    def __init__(self, params, paramFile=None, reloadFile=None):
        super(MLP,self).__init__(params, paramFile=paramFile, reloadFile=reloadFile)
    def _createParams(self):
        """
                    _createParams: create parameters necessary for the model
        """
        npWeights = OrderedDict()
        if 'dim_hidden' not in self.params:
            self.params['dim_hidden']= dim_hidden
        DIM_HIDDEN = self.params['dim_hidden']
        #Weights in recognition network model
        for layer in range(self.params['nlayers']):
            dim_input     = DIM_HIDDEN
            dim_output    = DIM_HIDDEN
            if layer==0:
                dim_input     = self.params['dim_observations']
            if self.params['nonlinearity']=='maxout':
                dim_output= DIM_HIDDEN*self.params['maxout_stride']
            npWeights['layer_'+str(layer)+'_W'] = self._getWeight((dim_input, dim_output))
            npWeights['layer_'+str(layer)+'_b'] = self._getWeight((dim_output, ),scheme='zero')
        npWeights['layer_out_W'] = self._getWeight((dim_input,self.params['nclasses']))
        npWeights['layer_out_b'] = self._getWeight((self.params['nclasses'], ),scheme='zero')
        return npWeights

    def _fakeData(self):
        """
                                Compile all the fake data
        """
        X = np.random.rand(2, self.params['dim_observations']).astype(config.floatX)
        m1=X>0.5
        m0=X<=0.5
        X[m0]=0
        X[m1]=1
        Y = np.random.randint(low=0,high=2,size=2).astype('int32')#.astype(config.floatX)
        #Y = np.random.multinomial(n=1,pvals=[0.5,0.5],size=2).astype(config.floatX)
        return X, Y

    def _buildClassifier(self, X, dropout_prob=0., normlayer=None, evaluation=False):
        """
                                Build classifier
        """
        #Dropout
        self._p(('Classifier with dropout :%.4f')%(dropout_prob))
        inp = self._dropout(X,dropout_prob)
        #Hidden layers
        for layer in range(self.params['nlayers']):
            W = self.tWeights['layer_'+str(layer)+'_W']
            b = self.tWeights['layer_'+str(layer)+'_b']
            if normlayer is None:
                inp = self._LinearNL(W,b,inp)
            elif normlayer=='batchnorm':
                inp = self._BNlayer(W,b,inp,evaluation=evaluation)
            elif normlayer=='layernorm':
                inp = self._LayerNorm(W,b,inp)
            else:
                try:
                    errmsg = "unknown normalization layer type: %s" % normlayer
                except:
                    errmsg = "unknown normalization layer type"
                assert False, errmsg

        #Output layer
        inp = self._LinearNL(self.tWeights['layer_out_W'],self.tWeights['layer_out_b'],inp,onlyLinear=True)
        probs = T.nnet.softmax(inp)

        return probs

    def _buildModel(self):
        """
                        ******BUILD MLP GRAPH******
        """
        #Inputs to graph
        X   = T.matrix('X',   dtype=config.floatX)
        Y   = T.ivector('Y')#,   dtype=config.floatX)
        X.tag.test_value, Y.tag.test_value  = self._fakeData()
        self.updates_ack = True
        #Learning Rates and annealing objective function
        #Add them to npWeights/tWeights to be tracked [do not have a prefix _W or _b so wont be diff.]
        self._addWeights('lr', np.asarray(self.params['lr'],dtype=config.floatX),borrow=False)
        self._addWeights('update_ctr', np.asarray(1.,dtype=config.floatX),borrow=False)

        lr  = self.tWeights['lr']
        iteration_t    = self.tWeights['update_ctr']

        lr_update = [(lr,T.switch(lr/1.0005<1e-4,lr,lr/1.0005))]

        #Build training graph
        probs_t = self._buildClassifier(X,self.params['input_dropout'],self.params['normlayer'],evaluation=False)
        probs_e = self._buildClassifier(X,0.,self.params['normlayer'],evaluation=True)

        #Cost function to minimize
        crossentropy_train = T.nnet.categorical_crossentropy(probs_t,Y).sum()
        crossentropy_eval = T.nnet.categorical_crossentropy(probs_e,Y).sum()

        #Accuracy
        ncorrect_train = T.eq(T.argmax(probs_t,axis=1),Y).sum()
        ncorrect_eval = T.eq(T.argmax(probs_e,axis=1),Y).sum()

        #Optimizer with specification for regularizer
        model_params         = self._getModelParams()
        optimizer_up, norm_list  = self._setupOptimizer(crossentropy_train, model_params,lr = lr,
                                                        reg_type =self.params['reg_type'],
                                                        reg_spec =self.params['reg_spec'],
                                                        reg_value= self.params['reg_value'],
                                                       grad_norm = self.params['grad_norm'],
                                                       divide_grad = T.cast(X.shape[0],config.floatX))

        #self.updates is container for all updates (e.g. see _BNlayer in __init__.py)
        self.updates += optimizer_up

        #Build theano functions
        fxn_inputs = [X,Y]

        #Importance sampled estimate
        self.train      = theano.function(fxn_inputs, [crossentropy_train, ncorrect_train],
                                              updates = self.updates, name = 'Train')
        self.debug      = theano.function(fxn_inputs, [crossentropy_train,norm_list[0],
                                                       norm_list[1],norm_list[2],ncorrect_train],
                                              updates = self.updates, name = 'Train+Debug')
        self.evaluate   = theano.function(fxn_inputs, [crossentropy_eval, ncorrect_eval], name = 'Evaluate')
        self.decay_lr   = theano.function([],lr.sum(),name = 'Update LR',updates=lr_update)

    def sampleDataset(self, dataset):
        p = np.random.uniform(low=0,high=1,size=dataset.shape)
        return (dataset >= p).astype(config.floatX)

    def evaluateClassifier(self, dataset, batch_size):
        """
                         Evaluate neg log likelihood and accuracy
        """
        N = dataset['X'].shape[0]
        crossentropy = 0
        ncorrect = 0
        for bnum, st_idx in enumerate(range(0,N,batch_size)):
            end_idx = min(st_idx+batch_size,N)
            X = self.sampleDataset(dataset['X'][st_idx:end_idx].astype(config.floatX))
            Y = dataset['Y'][st_idx:end_idx].astype('int32')
            batch_crossentropy, batch_ncorrect = self.evaluate(X=X,Y=Y)
            crossentropy += batch_crossentropy
            ncorrect += batch_ncorrect
        crossentropy /= float(N)
        accuracy = ncorrect/float(N)
        return crossentropy, accuracy

    def learn(self, dataset, epoch_start=0, epoch_end=1000, batch_size=200, shuffle=True,
              savefile = None, savefreq = None, evalfreq = 1, dataset_eval=None):
        assert len(dataset['X'].shape)==2,'Expecting 2D dataset matrix'
        assert dataset['X'].shape[1]==self.params['dim_observations'],'dim observations incorrect'
        assert dataset['X'].shape[0]==dataset['Y'].shape[0],'len X and Y do not match'
        assert shuffle==True,'Shuffle should be true, especially when using batchnorm'
        N = dataset['X'].shape[0]
        idxlist = range(N)
        train_crossentropy,train_accuracy,valid_crossentropy,valid_accuracy,current_lr = [],[],[],[],self.params['lr']
        #Training epochs
        for epoch in range(epoch_start, epoch_end+1):
            start_time = time.time()
            crossentropy, ncorrect, grad_norm, param_norm = 0, 0, [], []

            #Update learning rate
            #current_lr = self.decay_lr()

            if shuffle:
                np.random.shuffle(idxlist)

            #Go through dataset
            for bnum,st_idx in enumerate(range(0,N,batch_size)):
                end_idx = min(st_idx+batch_size, N)
                X       = self.sampleDataset(dataset['X'][idxlist[st_idx:end_idx]].astype(config.floatX))
                Y       = dataset['Y'][idxlist[st_idx:end_idx]].astype('int32')
                Nbatch  = X.shape[0]

                #Forward/Backward pass
                batch_crossentropy, batch_ncorrect = self.train(X=X, Y=Y)

                crossentropy  += batch_crossentropy
                ncorrect += batch_ncorrect

            crossentropy /= float(N)
            accuracy = ncorrect/float(N)
            train_crossentropy.append((epoch,crossentropy))
            train_accuracy.append((epoch,accuracy))
            end_time   = time.time()
            self._p(('Ep (%d) Train CE_NLL: %.4f, Train Accuracy: %0.4f [Took %.4f seconds]')%(epoch, crossentropy, accuracy, (end_time-start_time)))

            if evalfreq is not None and epoch%evalfreq==0:
                if dataset_eval is not None:
                    v_crossentropy, v_accuracy = self.evaluateClassifier(dataset_eval, batch_size=batch_size)
                    valid_crossentropy.append((epoch,v_crossentropy))
                    valid_accuracy.append((epoch,v_accuracy))
                    self._p(('Ep (%d): Valid CE_NLL: %.4f, Valid Accuracy: %.4f')%(epoch, v_crossentropy, v_accuracy))

            if savefreq is not None and epoch%savefreq==0:
                self._p(('Saving at epoch %d'%epoch))
                self._saveModel(fname=savefile+'EP'+str(epoch))
                intermediate = {}
                intermediate['train_crossentropy'] = np.array(train_crossentropy)
                intermediate['train_accuracy'] = np.array(train_accuracy)
                intermediate['valid_crossentropy'] = np.array(valid_crossentropy)
                intermediate['valid_accuracy'] = np.array(valid_accuracy)
                saveHDF5(savefile+'EP'+str(epoch)+'-stats.h5', intermediate)
        ret_map = {}
        ret_map['train_crossentropy'] = np.array(train_crossentropy)
        ret_map['train_accuracy'] = np.array(train_accuracy)
        ret_map['valid_crossentropy'] = np.array(valid_crossentropy)
        ret_map['valid_accuracy'] = np.array(valid_accuracy)
        return ret_map


text:
package com.arena.sso.oidc.consumer;

import javax.servlet.http.HttpServletRequest;

public interface OAuthConsumer {

    /**
     * Handles login request and return url for redirection to identity provider.
     * @param request HttpServletRequest
     * @return return url for redirection to identity provider.
     * @throws OAuthConsumerException in case of any problem occurs during processing
     */
    String handleLoginRequest(HttpServletRequest request) throws OAuthConsumerException;

    /**
     * Handles response coming from identity provider, and return authentication token.
     * @param request request coming from identity provider.
     * @return  user identity.
     * @throws OAuthConsumerException in case of any problem occurs during processing
     */
    UserData handleAuthenticationRequest(HttpServletRequest request) throws OAuthConsumerException;

}


text:
package storage

import (
	"fmt"
	"github.com/lastbackend/lastbackend/internal/pkg/storage/bbolt"
	"github.com/lastbackend/lastbackend/internal/pkg/storage/mock"
	"github.com/lastbackend/lastbackend/internal/pkg/storage/types"
)

const (
	MockDriver  = "mock"
	BboltDriver = "bbolt"
)

const (
	NamespaceKind  types.Kind = "namespace"
	ServiceKind    types.Kind = "service"
	DeploymentKind types.Kind = "deployment"
	ClusterKind    types.Kind = "cluster"
	PodKind        types.Kind = "pod"
	IngressKind    types.Kind = "ingress"
	ExporterKind   types.Kind = "exporter"
	SystemKind     types.Kind = "system"
	NodeKind       types.Kind = "node"
	RouteKind      types.Kind = "route"
	VolumeKind     types.Kind = "volume"
	TriggerKind    types.Kind = "trigger"
	SecretKind     types.Kind = "secret"
	EndpointKind   types.Kind = "endpoint"
	UtilsKind      types.Kind = "utils"
	ManifestKind   types.Kind = "manifest"
	NetworkKind    types.Kind = "network"
	SubnetKind     types.Kind = "subnet"
	TaskKind       types.Kind = "task"
	JobKind        types.Kind = "job"
	TestKind       types.Kind = "test"
)

type IStorage interface {
	List(collection string, listOutPtr interface{}) error
	Get(collection, key string, outPtr interface{}) error
	Set(collection, key string, obj interface{}) error
	Put(collection, key string, obj interface{}) error
	Del(collection, key string) error
	Close() error
}

type BboltConfig bbolt.Options

func Get(driver string, opts interface{}) (IStorage, error) {

	if driver != MockDriver && opts == nil {
		return nil, fmt.Errorf("options can not be is nil")
	}

	switch driver {
	case MockDriver:
		return mock.New()
	case BboltDriver:
		fallthrough
	default:
		o := opts.(BboltConfig)
		return bbolt.New(bbolt.Options(o))
	}
}

func GetOpts() *types.Opts {
	return new(types.Opts)
}

func NewWatcher() chan *types.WatcherEvent {
	return make(chan *types.WatcherEvent)
}


text:
Article 1122
----
On est censé avoir stipulé pour soi et pour ses héritiers et ayants cause, à
moins que le contraire ne soit exprimé ou ne résulte de la nature de la
convention.


text:
#include <pololu/orangutan.h>

/*
 * svp-one-servo: for the Orangutan SVP.
 *
 * This example uses the OrangutanServos functions to control one servo.
 * The servo pulse signal is sent on pin PD5, which is hardwired to the
 * input of the demux.  The servo signal is available on demux output 0.
 * This example uses the OrangutanPushbuttons functions to take input
 * from the user, and the OrangutanLCD functions to display feedback on
 * the LCD.
 *
 * http://www.pololu.com/docs/0J20
 * http://www.pololu.com
 * http://forum.pololu.com
 */

int main()
{
	const unsigned char demuxPins[] = {};
	servos_start(demuxPins, sizeof(demuxPins));

	set_servo_target(0, 1300);	// Make the servo go to a neutral position.

	clear(); // Clear the LCD.

	while(1) // Loop forever.
	{
		// When the user presses the top button, execute a pre-programmed
		// sequence of servo movements.
		if (button_is_pressed(TOP_BUTTON))
		{
			// Set the servo speed to 150.  This means that the pulse width
			// will change by at most 15 microseconds every 20 ms.  So it will
			// take 1.33 seconds to go from a pulse width of 1000 us to 2000 us.
			set_servo_speed(0, 150);

			// Slowly move the servo to position 1800.
			set_servo_target(0, 1800);
			delay_ms(700);

			// Disable the speed limit
			set_servo_speed(0, 0);

			// Make the servo move back to position 1300 as fast as possible.
			set_servo_target(0, 1300);
		}

		if (button_is_pressed(BOTTOM_BUTTON))
		{
			// While the user holds down the bottom button, move the servo
			// slowly towards position 1800.
			set_servo_speed(0, 60);
			set_servo_target(0, 1800);
			wait_for_button_release(BOTTOM_BUTTON);

			// When the user releases the bottom button, print its current
			// position (in microseconds) and then move it back quickly.
			clear();
			print_long(get_servo_position(0));
			print_from_program_space(PSTR(" \xE4s"));
			set_servo_speed(0, 0);
			set_servo_target(0, 1300);
		}
	}
}

// Local Variables: **
// mode: C **
// c-basic-offset: 4 **
// tab-width: 4 **
// indent-tabs-mode: t **
// end: **