text:
#include "mtp.h"
#include "util.h"
#include "arith_uint256.h"

extern "C" {
#include "blake2/blake2.h"
#include "blake2/blake2-impl.h"
#include "blake2/blamka-round-ref.h"
#include "core.h"
#include "ref.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
}

#include <iostream>
#include <sstream>
#include <iomanip>
#include "merkle-tree.hpp"
#include "primitives/block.h"
#include "streams.h"
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/numeric/conversion/cast.hpp>

using boost::numeric_cast;
using boost::numeric::bad_numeric_cast;
using boost::numeric::positive_overflow;
using boost::numeric::negative_overflow;

extern int validate_inputs(const argon2_context *context);
extern void clear_internal_memory(void *v, size_t n);

namespace mtp
{

namespace {

const int8_t L = MTP_L;
const unsigned T_COST = 1;
const unsigned M_COST = 1024 * 1024 * 4;
const unsigned LANES = 4;

void StoreBlock(void *output, const block *src)
{
    for (unsigned i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) {
        store64(static_cast<uint8_t*>(output)
                + (i * sizeof(src->v[i])), src->v[i]);
    }
}

int Argon2CtxMtp(argon2_context *context, argon2_type type,
        argon2_instance_t *instance)
{
    int result = validate_inputs(context);
    if (result != ARGON2_OK) {
        return result;
    }
    if ((type != Argon2_d) && (type != Argon2_i) && (type != Argon2_id)) {
        return ARGON2_INCORRECT_TYPE;
    }
    result = initialize(instance, context);
    if (result != ARGON2_OK) {
        return result;
    }
    result = fill_memory_blocks_mtp(instance, context);
    if (result != ARGON2_OK) {
        return result;
    }
    return ARGON2_OK;
}

uint32_t IndexBeta(const argon2_instance_t *instance,
        const argon2_position_t *position, uint32_t pseudo_rand,
        int same_lane)
{
    /*
     * Pass 0:
     *      This lane : all already finished segments plus already constructed
     * blocks in this segment
     *      Other lanes : all already finished segments
     * Pass 1+:
     *      This lane : (SYNC_POINTS - 1) last segments plus already constructed
     * blocks in this segment
     *      Other lanes : (SYNC_POINTS - 1) last segments
     */
    uint32_t reference_area_size;
    if (position->pass == 0) {
        /* First pass */
        if (position->slice == 0) {
            /* First slice */
            reference_area_size = position->index - 1; // all but the previous
        } else {
            if (same_lane) {
                /* The same lane => add current segment */
                reference_area_size =
                    (position->slice * instance->segment_length)
                    + position->index - 1;
            } else {
                reference_area_size =
                    (position->slice * instance->segment_length)
                    + ((position->index == 0) ? -1 : 0);
            }
        }
    } else {
        /* Second pass */
        if (same_lane) {
            reference_area_size = instance->lane_length
                - instance->segment_length + position->index - 1;
        } else {
            reference_area_size = instance->lane_length
                - instance->segment_length + ((position->index == 0) ? -1 : 0);
        }
    }

    /* 1.2.4. Mapping pseudo_rand to 0..<reference_area_size-1> and produce
     * relative position */
    uint64_t relative_position = pseudo_rand;
    relative_position = (relative_position * relative_position) >> 32;
    relative_position = reference_area_size - 1
        - ((reference_area_size * relative_position) >> 32);

    /* 1.2.5 Computing starting position */
    uint32_t start_position = 0;
    if (position->pass != 0) {
        start_position = (position->slice == (ARGON2_SYNC_POINTS - 1))
            ? 0
            : (position->slice + 1) * instance->segment_length;
    }

    /* 1.2.6. Computing absolute position */
    uint64_t absolute_position = (static_cast<uint64_t>(start_position)
            + relative_position) % static_cast<uint64_t>(instance->lane_length);
    return static_cast<uint32_t>(absolute_position);
}

void GetBlockIndex(uint32_t ij, argon2_instance_t *instance,
        uint32_t *out_ij_prev, uint32_t *out_computed_ref_block)
{
    uint32_t ij_prev = 0;
    if ((ij % instance->lane_length) == 0) {
        ij_prev = ij + instance->lane_length - 1;
    } else {
        ij_prev = ij - 1;
    }
    if ((ij % instance->lane_length) == 1) {
        ij_prev = ij - 1;
    }

    uint64_t prev_block_opening = instance->memory[ij_prev].v[0];
    uint32_t ref_lane = static_cast<uint32_t>((prev_block_opening >> 32)
            % static_cast<uint64_t>(instance->lanes));
    uint32_t pseudo_rand = static_cast<uint32_t>(prev_block_opening & 0xFFFFFFFF);
    uint32_t lane = ij / instance->lane_length;
    uint32_t slice = (ij - (lane * instance->lane_length))
        / instance->segment_length;
    uint32_t pos_index = ij - (lane * instance->lane_length)
        - (slice * instance->segment_length);
    if (slice == 0) {
        ref_lane = lane;
    }

    argon2_position_t position { 0, lane , (uint8_t)slice, pos_index };
    uint32_t ref_index = IndexBeta(instance, &position, pseudo_rand,
            ref_lane == position.lane);
    uint32_t computed_ref_block = (instance->lane_length * ref_lane) + ref_index;
    *out_ij_prev = ij_prev;
    *out_computed_ref_block = computed_ref_block;
}

/** Compute a BLAKE2B hash on a block
 *
 * \param input  [in]  Block to compute the hash on
 * \param digest [out] Computed hash
 */
void compute_blake2b(const block& input,
        uint8_t digest[MERKLE_TREE_ELEMENT_SIZE_B])
{
    block tmp_block;
    copy_block(&tmp_block, &input);
    uint8_t tmp_block_bytes[ARGON2_BLOCK_SIZE];
    StoreBlock(&tmp_block_bytes, &tmp_block);

    blake2b_state state;
    blake2b_init(&state, MERKLE_TREE_ELEMENT_SIZE_B);
    blake2b_4r_update(&state, tmp_block_bytes, ARGON2_BLOCK_SIZE);

    blake2b_4r_final(&state, digest, MERKLE_TREE_ELEMENT_SIZE_B);
    clear_internal_memory(tmp_block.v, ARGON2_BLOCK_SIZE);
    clear_internal_memory(tmp_block_bytes, ARGON2_BLOCK_SIZE);
}

struct TargetHelper
{
    bool m_negative;
    bool m_overflow;
    arith_uint256 m_target;

    TargetHelper(uint32_t target)
    {
       m_target.SetCompact(target, &m_negative, &m_overflow);
    }
};

} // unnamed namespace

namespace impl
{

bool mtp_verify(const char* input, const uint32_t target,
        const uint8_t hash_root_mtp[16], uint32_t nonce,
        const uint64_t block_mtp[MTP_L*2][128],
        const std::deque<std::vector<uint8_t>> proof_mtp[MTP_L*3],
        uint256 pow_limit,
        uint256 *mtpHashValue)
{
    MerkleTree::Buffer const root(&hash_root_mtp[0], &hash_root_mtp[16]);
    block blocks[L * 2];
    for(int i = 0; i < (L * 2); ++i) {
        std::memcpy(blocks[i].v, block_mtp[i],
                sizeof(uint64_t) * ARGON2_QWORDS_IN_BLOCK);
    }

#define TEST_OUTLEN 32
#define TEST_PWDLEN 80
#define TEST_SALTLEN 80
#define TEST_SECRETLEN 0
#define TEST_ADLEN 0

    unsigned char out[TEST_OUTLEN];
    unsigned char pwd[TEST_PWDLEN];
    std::memcpy(pwd, input, TEST_PWDLEN);
    unsigned char salt[TEST_SALTLEN];
    std::memcpy(salt, input, TEST_SALTLEN);

    argon2_context context_verify;
    context_verify.out = out;
    context_verify.outlen = TEST_OUTLEN;
    context_verify.version = ARGON2_VERSION_NUMBER;
    context_verify.pwd = pwd;
    context_verify.pwdlen = TEST_PWDLEN;
    context_verify.salt = salt;
    context_verify.saltlen = TEST_SALTLEN;
    context_verify.secret = NULL;
    context_verify.secretlen = TEST_SECRETLEN;
    context_verify.ad = NULL;
    context_verify.adlen = TEST_ADLEN;
    context_verify.t_cost = T_COST;
    context_verify.m_cost = M_COST;
    context_verify.lanes = LANES;
    context_verify.threads = LANES;
    context_verify.allocate_cbk = NULL;
    context_verify.free_cbk = NULL;
    context_verify.flags = ARGON2_DEFAULT_FLAGS;

#undef TEST_OUTLEN
#undef TEST_PWDLEN
#undef TEST_SALTLEN
#undef TEST_SECRETLEN
#undef TEST_ADLEN

    uint32_t memory_blocks = context_verify.m_cost;
    if (memory_blocks < (2 * ARGON2_SYNC_POINTS * context_verify.lanes)) {
        memory_blocks = 2 * ARGON2_SYNC_POINTS * context_verify.lanes;
    }
    uint32_t segment_length = memory_blocks / (context_verify.lanes * ARGON2_SYNC_POINTS);
    memory_blocks = segment_length * (context_verify.lanes * ARGON2_SYNC_POINTS);

    argon2_instance_t instance;
    instance.version = context_verify.version;
    instance.memory = NULL;
    instance.passes = context_verify.t_cost;
    instance.memory_blocks = context_verify.m_cost;
    instance.segment_length = segment_length;
    instance.lane_length = segment_length * ARGON2_SYNC_POINTS;
    instance.lanes = context_verify.lanes;
    instance.threads = context_verify.threads;
    instance.type = Argon2_d;
    if (instance.threads > instance.lanes) {
        instance.threads = instance.lanes;
    }

    // step 7
    uint256 y[L + 1];
    std::memset(&y[0], 0, sizeof(y));

    blake2b_state state_y0;
    blake2b_init(&state_y0, 32); // 256 bit
    blake2b_update(&state_y0, input, 80);
    blake2b_update(&state_y0, hash_root_mtp, MERKLE_TREE_ELEMENT_SIZE_B);
    blake2b_update(&state_y0, &nonce, sizeof(unsigned int));
    blake2b_final(&state_y0, &y[0], sizeof(uint256));

    // get hash_zero
    uint8_t h0[ARGON2_PREHASH_SEED_LENGTH];
    initial_hash(h0, &context_verify, instance.type);

    // step 8
    for (uint32_t j = 1; j <= L; ++j) {
        // compute ij
        std::string s = "0x" + y[j - 1].GetHex();
        boost::multiprecision::uint256_t t(s);
        uint32_t ij = numeric_cast<uint32_t>(t % M_COST);

        // retrieve x[ij-1] and x[phi(i)] from proof
        block prev_block, ref_block, t_prev_block, t_ref_block;
        std::memcpy(t_prev_block.v, block_mtp[(j * 2) - 2],
                sizeof(uint64_t) * ARGON2_QWORDS_IN_BLOCK);
        std::memcpy(t_ref_block.v, block_mtp[j*2 - 1],
                sizeof(uint64_t) * ARGON2_QWORDS_IN_BLOCK);
        copy_block(&prev_block , &t_prev_block);
        copy_block(&ref_block , &t_ref_block);
        clear_internal_memory(t_prev_block.v, ARGON2_BLOCK_SIZE);
        clear_internal_memory(t_ref_block.v, ARGON2_BLOCK_SIZE);

        //prev_index
        //compute
        uint32_t memory_blocks_2 = M_COST;
        if (memory_blocks_2 < (2 * ARGON2_SYNC_POINTS * LANES)) {
            memory_blocks_2 = 2 * ARGON2_SYNC_POINTS * LANES;
        }

        uint32_t segment_length_2 = memory_blocks_2 / (LANES * ARGON2_SYNC_POINTS);
        uint32_t lane_length = segment_length_2 * ARGON2_SYNC_POINTS;
        uint32_t ij_prev = 0;
        if ((ij % lane_length) == 0) {
            ij_prev = ij + lane_length - 1;
        } else {
            ij_prev = ij - 1;
        }
        if ((ij % lane_length) == 1) {
            ij_prev = ij - 1;
        }

        //hash[prev_index]
        uint8_t digest_prev[MERKLE_TREE_ELEMENT_SIZE_B];
        compute_blake2b(prev_block, digest_prev);
        MerkleTree::Buffer hash_prev(digest_prev,
                digest_prev + sizeof(digest_prev));
        if (!MerkleTree::checkProofOrdered(proof_mtp[(j * 3) - 2],
                    root, hash_prev, ij_prev + 1)) {
            LogPrintf("error : checkProofOrdered in x[ij_prev]\n");
            return false;
        }

        //compute ref_index
        uint64_t prev_block_opening = prev_block.v[0];
        uint32_t ref_lane = static_cast<uint32_t>((prev_block_opening >> 32) % LANES);
        uint32_t pseudo_rand = static_cast<uint32_t>(prev_block_opening & 0xFFFFFFFF);
        uint32_t lane = ij / lane_length;
        uint32_t slice = (ij - (lane * lane_length)) / segment_length_2;
        uint32_t pos_index = ij - (lane * lane_length)
            - (slice * segment_length_2);
        if (slice == 0) {
            ref_lane = lane;
        }

        argon2_instance_t instance;
        instance.segment_length = segment_length_2;
        instance.lane_length = lane_length;

        argon2_position_t position { 0, lane , (uint8_t)slice, pos_index };
        uint32_t ref_index = IndexBeta(&instance, &position, pseudo_rand,
                ref_lane == position.lane);

        uint32_t computed_ref_block = (lane_length * ref_lane) + ref_index;

        uint8_t digest_ref[MERKLE_TREE_ELEMENT_SIZE_B];
        compute_blake2b(ref_block, digest_ref);
        MerkleTree::Buffer hash_ref(digest_ref, digest_ref + sizeof(digest_ref));
        if (!MerkleTree::checkProofOrdered(proof_mtp[(j * 3) - 1],
                    root, hash_ref, computed_ref_block + 1)) {
            LogPrintf("error : checkProofOrdered in x[ij_ref]\n");
            return false;
        }

        // compute x[ij]
        block block_ij;
        fill_block_mtp(&blocks[(j * 2) - 2], &blocks[(j * 2) - 1],
                &block_ij, 0, computed_ref_block, h0);

        // verify opening
        // hash x[ij]
        uint8_t digest_ij[MERKLE_TREE_ELEMENT_SIZE_B];
        compute_blake2b(block_ij, digest_ij);
        MerkleTree::Buffer hash_ij(digest_ij, digest_ij + sizeof(digest_ij));

        if (!MerkleTree::checkProofOrdered(proof_mtp[(j * 3) - 3], root,
                    hash_ij, ij + 1)) {
            LogPrintf("error : checkProofOrdered in x[ij]\n");
            return false;
        }

        // compute y(j)
        block blockhash;
        copy_block(&blockhash, &block_ij);
        uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE];
        StoreBlock(&blockhash_bytes, &blockhash);
        blake2b_state ctx_yj;
        blake2b_init(&ctx_yj, 32);
        blake2b_update(&ctx_yj, &y[j - 1], 32);
        blake2b_update(&ctx_yj, blockhash_bytes, ARGON2_BLOCK_SIZE);
        blake2b_final(&ctx_yj, &y[j], 32);
        clear_internal_memory(block_ij.v, ARGON2_BLOCK_SIZE);
        clear_internal_memory(blockhash.v, ARGON2_BLOCK_SIZE);
        clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE);
    }

    // step 9
    bool negative;
    bool overflow;
    arith_uint256 bn_target;
    bn_target.SetCompact(target, &negative, &overflow); // diff = 1

    for (int i = 0; i < (L * 2); ++i) {
        clear_internal_memory(blocks[i].v, ARGON2_BLOCK_SIZE);
    }

    if (mtpHashValue)
        *mtpHashValue = y[L];

    if (negative || (bn_target == 0) || overflow
            || (bn_target > UintToArith256(pow_limit))
            || (UintToArith256(y[L]) > bn_target)) {
        return false;
    }
    return true;
}

namespace {

bool mtp_hash1(const char* input, uint32_t target, uint8_t hash_root_mtp[16],
        unsigned int& nonce, uint64_t block_mtp[MTP_L*2][128],
        std::deque<std::vector<uint8_t>> proof_mtp[MTP_L*3], uint256 pow_limit,
        uint256& output)
{
#define TEST_OUTLEN 32
#define TEST_PWDLEN 80
#define TEST_SALTLEN 80
#define TEST_SECRETLEN 0
#define TEST_ADLEN 0

    unsigned char out[TEST_OUTLEN];
    unsigned char pwd[TEST_PWDLEN];
    std::memcpy(pwd, input, TEST_PWDLEN);
    unsigned char salt[TEST_SALTLEN];
    std::memcpy(salt, input, TEST_SALTLEN);

    argon2_context context;
    context.out = out;
    context.outlen = TEST_OUTLEN;
    context.version = ARGON2_VERSION_NUMBER;
    context.pwd = pwd;
    context.pwdlen = TEST_PWDLEN;
    context.salt = salt;
    context.saltlen = TEST_SALTLEN;
    context.secret = NULL;
    context.secretlen = TEST_SECRETLEN;
    context.ad = NULL;
    context.adlen = TEST_ADLEN;
    context.t_cost = T_COST;
    context.m_cost = M_COST;
    context.lanes = LANES;
    context.threads = LANES;
    context.allocate_cbk = NULL;
    context.free_cbk = NULL;
    context.flags = ARGON2_DEFAULT_FLAGS;

#undef TEST_OUTLEN
#undef TEST_PWDLEN
#undef TEST_SALTLEN
#undef TEST_SECRETLEN
#undef TEST_ADLEN

    uint32_t memory_blocks = context.m_cost;
    if (memory_blocks < (2 * ARGON2_SYNC_POINTS * context.lanes)) {
        memory_blocks = 2 * ARGON2_SYNC_POINTS * context.lanes;
    }
    uint32_t segment_length = memory_blocks / (context.lanes * ARGON2_SYNC_POINTS);
    memory_blocks = segment_length * (context.lanes * ARGON2_SYNC_POINTS);

    argon2_instance_t instance;
    instance.version = context.version;
    instance.memory = NULL;
    instance.passes = context.t_cost;
    instance.memory_blocks = context.m_cost;
    instance.segment_length = segment_length;
    instance.lane_length = segment_length * ARGON2_SYNC_POINTS;
    instance.lanes = context.lanes;
    instance.threads = context.threads;
    instance.type = Argon2_d;
    if (instance.threads > instance.lanes) {
        instance.threads = instance.lanes;
    }

    // step 1
    Argon2CtxMtp(&context, Argon2_d, &instance);

    // step 2
    MerkleTree::Elements elements;
    for (long int i = 0; i < instance.memory_blocks; ++i) {
        uint8_t digest[MERKLE_TREE_ELEMENT_SIZE_B];
        compute_blake2b(instance.memory[i], digest);
        elements.emplace_back(digest, digest + sizeof(digest));
    }

    MerkleTree ordered_tree(elements, true);
    MerkleTree::Buffer root = ordered_tree.getRoot();
    std::copy(root.begin(), root.end(), hash_root_mtp);

    // step 3
    unsigned int n_nonce_internal = 0;
    TargetHelper const bn_target(target);

    // step 4
    uint256 y[L + 1];
    block blocks[L * 2];
    MerkleTree::Elements proof_blocks[L * 3];
    while (true) {
        if (n_nonce_internal == UINT_MAX) {
            // go to create a new merkle tree
            return false;
        }

        std::memset(&y[0], 0, sizeof(y));
        std::memset(&blocks[0], 0, sizeof(sizeof(block) * L * 2));

        blake2b_state state;
        blake2b_init(&state, 32); // 256 bit
        blake2b_update(&state, input, 80);
        blake2b_update(&state, hash_root_mtp, MERKLE_TREE_ELEMENT_SIZE_B);
        blake2b_update(&state, &n_nonce_internal, sizeof(unsigned int));
        blake2b_final(&state, &y[0], sizeof(uint256));

        // step 5
        bool init_blocks = false;
        for (uint32_t j = 1; j <= L; ++j) {
            std::string s = "0x" + y[j - 1].GetHex();
            boost::multiprecision::uint256_t t(s);
            uint32_t ij = numeric_cast<uint32_t>(t % M_COST);
            uint32_t except_index = numeric_cast<uint32_t>(M_COST / LANES);
            if (((ij % except_index) == 0) || ((ij % except_index) == 1)) {
                init_blocks = true;
                break;
            }

            block blockhash;
            copy_block(&blockhash, &instance.memory[ij]);
            uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE];
            StoreBlock(&blockhash_bytes, &blockhash);
            blake2b_state ctx_yj;
            blake2b_init(&ctx_yj, 32);
            blake2b_update(&ctx_yj, &y[j - 1], 32);
            blake2b_update(&ctx_yj, blockhash_bytes, ARGON2_BLOCK_SIZE);
            blake2b_final(&ctx_yj, &y[j], 32);
            clear_internal_memory(blockhash.v, ARGON2_BLOCK_SIZE);
            clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE);

            //storing blocks
            uint32_t prev_index;
            uint32_t ref_index;
            GetBlockIndex(ij, &instance, &prev_index, &ref_index);
            //previous block
            copy_block(&blocks[(j * 2) - 2], &instance.memory[prev_index]);
            //ref block
            copy_block(&blocks[(j * 2) - 1], &instance.memory[ref_index]);

            //storing proof
            //TODO : make it as function please
            //current proof
            uint8_t digest_curr[MERKLE_TREE_ELEMENT_SIZE_B];
            compute_blake2b(instance.memory[ij], digest_curr);
            MerkleTree::Buffer hash_curr(digest_curr,
                    digest_curr + sizeof(digest_curr));
            MerkleTree::Elements proof_curr = ordered_tree.getProofOrdered(
                    hash_curr, ij + 1);
            proof_blocks[(j * 3) - 3] = proof_curr;

            //prev proof
            uint8_t digest_prev[MERKLE_TREE_ELEMENT_SIZE_B];
            compute_blake2b(instance.memory[prev_index], digest_prev);
            MerkleTree::Buffer hash_prev(digest_prev,
                    digest_prev + sizeof(digest_prev));
            MerkleTree::Elements proof_prev = ordered_tree.getProofOrdered(
                    hash_prev, prev_index + 1);
            proof_blocks[(j * 3) - 2] = proof_prev;

            //ref proof
            uint8_t digest_ref[MERKLE_TREE_ELEMENT_SIZE_B];
            compute_blake2b(instance.memory[ref_index], digest_ref);
            MerkleTree::Buffer hash_ref(digest_ref,
                    digest_ref + sizeof(digest_ref));
            MerkleTree::Elements proof_ref = ordered_tree.getProofOrdered(
                    hash_ref, ref_index + 1);
            proof_blocks[(j * 3) - 1] = proof_ref;
        }

        if (init_blocks) {
            n_nonce_internal++;
            continue;
        }

        // step 6
        if (bn_target.m_negative || (bn_target.m_target == 0) || bn_target.m_overflow
                || (bn_target.m_target > UintToArith256(pow_limit))
                || (UintToArith256(y[L]) > bn_target.m_target)) {
            n_nonce_internal++;
            continue;
        }

        break;
    }

    // step 7
    std::copy(root.begin(), root.end(), hash_root_mtp);

    nonce = n_nonce_internal;
    for (int i = 0; i < L * 2; ++i) {
        std::memcpy(block_mtp[i], &blocks[i],
                sizeof(uint64_t) * ARGON2_QWORDS_IN_BLOCK);
    }
    for (int i = 0; i < L * 3; ++i) {
        proof_mtp[i] = proof_blocks[i];
    }
    std::memcpy(&output, &y[L], sizeof(uint256));

    uint8_t h0[ARGON2_PREHASH_SEED_LENGTH];
    std::memcpy(h0, instance.hash_zero,
            sizeof(uint8_t) * ARGON2_PREHASH_SEED_LENGTH);

    // get hash_zero
    uint8_t h0_computed[ARGON2_PREHASH_SEED_LENGTH];
    initial_hash(h0_computed, &context, instance.type);

    free_memory(&context, (uint8_t *)instance.memory, instance.memory_blocks, sizeof(block));
    return true;
}

} // unnamed namespace

void mtp_hash(const char* input, uint32_t target, uint8_t hash_root_mtp[16],
        unsigned int& nonce, uint64_t block_mtp[MTP_L*2][128],
        std::deque<std::vector<uint8_t>> proof_mtp[MTP_L*3], uint256 pow_limit,
        uint256& output)
{
    bool done = false;
    while (!done) {
        done = mtp_hash1(input, target, hash_root_mtp, nonce, block_mtp,
                proof_mtp, pow_limit, output);
    }
}

}

namespace
{
void serializeMtpHeader(CDataStream & stream, CBlockHeader const & header)
{
    static_assert(
                80 == sizeof(header.nVersion) + sizeof(header.hashPrevBlock)+ sizeof(header.hashMerkleRoot)
                    + sizeof(header.nTime) + sizeof(header.nBits) + sizeof(header.nVersionMTP)
                , "The header data size for MTP hashing should be 80 bytes long."
            );

    stream << header.nVersion;
    stream << header.hashPrevBlock;
    stream << header.hashMerkleRoot;
    stream << header.nTime;
    stream << header.nBits;
    stream << header.nVersionMTP;
}
}

uint256 hash(CBlockHeader & blockHeader, uint256 const & powLimit)
{
    if(!blockHeader.mtpHashData)
        blockHeader.mtpHashData = std::make_shared<CMTPHashData>();

    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
    serializeMtpHeader(ss, blockHeader);

    uint256 result;
    impl::mtp_hash(reinterpret_cast<char*>(&ss[0]), blockHeader.nBits, blockHeader.mtpHashData->hashRootMTP
            , blockHeader.nNonce, blockHeader.mtpHashData->nBlockMTP, blockHeader.mtpHashData->nProofMTP, powLimit, result);

    return result;
}

bool verify(uint32_t nonce, CBlockHeader const & blockHeader, uint256 const & powLimit, uint256 *mtpHashValue)
{
    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
    serializeMtpHeader(ss, blockHeader);

    return impl::mtp_verify(reinterpret_cast<char*>(&ss[0]), blockHeader.nBits, blockHeader.mtpHashData->hashRootMTP
            , nonce, blockHeader.mtpHashData->nBlockMTP, blockHeader.mtpHashData->nProofMTP, powLimit, mtpHashValue);
}

}


text:
> see https://aka.ms/autorest

This is the AutoRest configuration file for CustomerInsights.

---
## Getting Started
To build the SDK for CustomerInsights, simply [Install AutoRest](https://aka.ms/autorest/install) and in this folder, run:

> `autorest`

To see additional help and options, run:

> `autorest --help`
---

## Configuration

### Basic Information
These are the global settings for the CustomerInsights API.

``` yaml
openapi-type: arm
tag: package-2017-04
```

### Tag: package-2017-04

These settings apply only when `--tag=package-2017-04` is specified on the command line.

``` yaml $(tag) == 'package-2017-04'
input-file:
- Microsoft.CustomerInsights/stable/2017-04-26/customer-insights.json
```

### Tag: package-2017-01

These settings apply only when `--tag=package-2017-01` is specified on the command line.

``` yaml $(tag) == 'package-2017-01'
input-file:
- Microsoft.CustomerInsights/stable/2017-01-01/customer-insights.json
```

---
# Code Generation

## Swagger to SDK

This section describes what SDK should be generated by the automatic system.
This is not used by Autorest itself.

``` yaml $(swagger-to-sdk)
swagger-to-sdk:
  - repo: azure-sdk-for-net
  - repo: azure-sdk-for-go
  - repo: azure-sdk-for-go-track2
  - repo: azure-sdk-for-js
  - repo: azure-sdk-for-node
  - repo: azure-sdk-for-ruby
    after_scripts:
      - bundle install && rake arm:regen_all_profiles['azure_mgmt_customer_insights']
  - repo: azure-resource-manager-schemas
  - repo: azure-powershell
```

## C#

These settings apply only when `--csharp` is specified on the command line.
Please also specify `--csharp-sdks-folder=<path to "SDKs" directory of your azure-sdk-for-net clone>`.

``` yaml $(csharp)
csharp:
  azure-arm: true
  license-header: MICROSOFT_MIT_NO_VERSION
  namespace: Microsoft.Azure.Management.CustomerInsights
  output-folder: $(csharp-sdks-folder)/customer-insights/Microsoft.Azure.Management.CustomerInsights/src/Generated
  clear-output-folder: true
```

## Go

See configuration in [readme.go.md](./readme.go.md)

## Java

These settings apply only when `--java` is specified on the command line.
Please also specify `--azure-libraries-for-java-folder=<path to the root directory of your azure-libraries-for-java clone>`.

``` yaml $(java)
azure-arm: true
fluent: true
namespace: com.microsoft.azure.management.customerinsights
license-header: MICROSOFT_MIT_NO_CODEGEN
payload-flattening-threshold: 1
output-folder: $(azure-libraries-for-java-folder)/azure-mgmt-customerinsights
```

### Java multi-api

``` yaml $(java) && $(multiapi)
batch:
  - tag: package-2017-01
  - tag: package-2017-04
```

### Tag: package-2017-01 and java

These settings apply only when `--tag=package-2017-01 --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2017-01' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.customerinsights.v2017_01_01
  output-folder: $(azure-libraries-for-java-folder)/sdk/customerinsights/mgmt-v2017_01_01
regenerate-manager: true
generate-interface: true
```

### Tag: package-2017-04 and java

These settings apply only when `--tag=package-2017-04 --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2017-04' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.customerinsights.v2017_04_26
  output-folder: $(azure-libraries-for-java-folder)/sdk/customerinsights/mgmt-v2017_04_26
regenerate-manager: true
generate-interface: true
```

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Action Bar Fragment Demo</string>
    <string name="add">Add</string>
    <string name="reset">Reset</string>
    <string name="word">Word</string>
    <string name="size_template">Size: %d</string>
    <string name="icon">Icon</string>
</resources>


text:
//
// cg_syscalls.c -- this file is only included when building a dll
// cg_syscalls.asm is included instead when building a qvm
#ifdef Q3_VM
#error "Do not use in VM build"
#endif

#include "cg_local.h"

static intptr_t (QDECL *syscall)( intptr_t arg, ... ) = (intptr_t (QDECL *)( intptr_t, ...))-1;

void dllEntry( intptr_t (QDECL  *syscallptr)( intptr_t arg,... ) ) {
    syscall = syscallptr;
}

int PASSFLOAT( float x ) {
    float	floatTemp;
    floatTemp = x;
    return *(int *)&floatTemp;
}

void	trap_Print( const char *fmt ) {
    syscall( CG_PRINT, fmt );
}

void	trap_Error( const char *fmt ) {
    syscall( CG_ERROR, fmt );
    exit(CG_ERROR); //Will never occour but makes compiler happy
}

int		trap_Milliseconds( void ) {
    return syscall( CG_MILLISECONDS );
}

void	trap_Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags ) {
    syscall( CG_CVAR_REGISTER, vmCvar, varName, defaultValue, flags );
}

void	trap_Cvar_Update( vmCvar_t *vmCvar ) {
    syscall( CG_CVAR_UPDATE, vmCvar );
}

void	trap_Cvar_Set( const char *var_name, const char *value ) {
    syscall( CG_CVAR_SET, var_name, value );
}

void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) {
    syscall( CG_CVAR_VARIABLESTRINGBUFFER, var_name, buffer, bufsize );
}

int		trap_Argc( void ) {
    return syscall( CG_ARGC );
}

void	trap_Argv( int n, char *buffer, int bufferLength ) {
    syscall( CG_ARGV, n, buffer, bufferLength );
}

void	trap_Args( char *buffer, int bufferLength ) {
    syscall( CG_ARGS, buffer, bufferLength );
}

int		trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
    return syscall( CG_FS_FOPENFILE, qpath, f, mode );
}

void	trap_FS_Read( void *buffer, int len, fileHandle_t f ) {
    syscall( CG_FS_READ, buffer, len, f );
}

void	trap_FS_Write( const void *buffer, int len, fileHandle_t f ) {
    syscall( CG_FS_WRITE, buffer, len, f );
}

void	trap_FS_FCloseFile( fileHandle_t f ) {
    syscall( CG_FS_FCLOSEFILE, f );
}

int trap_FS_Seek( fileHandle_t f, long offset, int origin ) {
    return syscall( CG_FS_SEEK, f, offset, origin );
}

void	trap_SendConsoleCommand( const char *text ) {
    syscall( CG_SENDCONSOLECOMMAND, text );
}

void	trap_AddCommand( const char *cmdName ) {
    syscall( CG_ADDCOMMAND, cmdName );
}

void	trap_RemoveCommand( const char *cmdName ) {
    syscall( CG_REMOVECOMMAND, cmdName );
}

void	trap_SendClientCommand( const char *s ) {
    syscall( CG_SENDCLIENTCOMMAND, s );
}

void	trap_UpdateScreen( void ) {
    syscall( CG_UPDATESCREEN );
}

void	trap_CM_LoadMap( const char *mapname ) {
    syscall( CG_CM_LOADMAP, mapname );
}

int		trap_CM_NumInlineModels( void ) {
    return syscall( CG_CM_NUMINLINEMODELS );
}

clipHandle_t trap_CM_InlineModel( int index ) {
    return syscall( CG_CM_INLINEMODEL, index );
}

clipHandle_t trap_CM_TempBoxModel( const vec3_t mins, const vec3_t maxs ) {
    return syscall( CG_CM_TEMPBOXMODEL, mins, maxs );
}

clipHandle_t trap_CM_TempCapsuleModel( const vec3_t mins, const vec3_t maxs ) {
    return syscall( CG_CM_TEMPCAPSULEMODEL, mins, maxs );
}

int		trap_CM_PointContents( const vec3_t p, clipHandle_t model ) {
    return syscall( CG_CM_POINTCONTENTS, p, model );
}

int		trap_CM_TransformedPointContents( const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles ) {
    return syscall( CG_CM_TRANSFORMEDPOINTCONTENTS, p, model, origin, angles );
}

void	trap_CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end,
                          const vec3_t mins, const vec3_t maxs,
                          clipHandle_t model, int brushmask ) {
    syscall( CG_CM_BOXTRACE, results, start, end, mins, maxs, model, brushmask );
}

void	trap_CM_CapsuleTrace( trace_t *results, const vec3_t start, const vec3_t end,
                              const vec3_t mins, const vec3_t maxs,
                              clipHandle_t model, int brushmask ) {
    syscall( CG_CM_CAPSULETRACE, results, start, end, mins, maxs, model, brushmask );
}

void	trap_CM_TransformedBoxTrace( trace_t *results, const vec3_t start, const vec3_t end,
                                     const vec3_t mins, const vec3_t maxs,
                                     clipHandle_t model, int brushmask,
                                     const vec3_t origin, const vec3_t angles ) {
    syscall( CG_CM_TRANSFORMEDBOXTRACE, results, start, end, mins, maxs, model, brushmask, origin, angles );
}

void	trap_CM_TransformedCapsuleTrace( trace_t *results, const vec3_t start, const vec3_t end,
        const vec3_t mins, const vec3_t maxs,
        clipHandle_t model, int brushmask,
        const vec3_t origin, const vec3_t angles ) {
    syscall( CG_CM_TRANSFORMEDCAPSULETRACE, results, start, end, mins, maxs, model, brushmask, origin, angles );
}

int		trap_CM_MarkFragments( int numPoints, const vec3_t *points,
                               const vec3_t projection,
                               int maxPoints, vec3_t pointBuffer,
                               int maxFragments, markFragment_t *fragmentBuffer ) {
    return syscall( CG_CM_MARKFRAGMENTS, numPoints, points, projection, maxPoints, pointBuffer, maxFragments, fragmentBuffer );
}

void	trap_S_StartSound( vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx ) {
    syscall( CG_S_STARTSOUND, origin, entityNum, entchannel, sfx );
}

void	trap_S_StartLocalSound( sfxHandle_t sfx, int channelNum ) {
    syscall( CG_S_STARTLOCALSOUND, sfx, channelNum );
}

void	trap_S_ClearLoopingSounds( qboolean killall ) {
    syscall( CG_S_CLEARLOOPINGSOUNDS, killall );
}

void	trap_S_AddLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx ) {
    syscall( CG_S_ADDLOOPINGSOUND, entityNum, origin, velocity, sfx );
}

void	trap_S_AddRealLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx ) {
    syscall( CG_S_ADDREALLOOPINGSOUND, entityNum, origin, velocity, sfx );
}

void	trap_S_StopLoopingSound( int entityNum ) {
    syscall( CG_S_STOPLOOPINGSOUND, entityNum );
}

void	trap_S_UpdateEntityPosition( int entityNum, const vec3_t origin ) {
    syscall( CG_S_UPDATEENTITYPOSITION, entityNum, origin );
}

void	trap_S_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], int inwater ) {
    syscall( CG_S_RESPATIALIZE, entityNum, origin, axis, inwater );
}

sfxHandle_t	trap_S_RegisterSound( const char *sample, qboolean compressed ) {
    return syscall( CG_S_REGISTERSOUND, sample, compressed );
}

void	trap_S_StartBackgroundTrack( const char *intro, const char *loop ) {
    syscall( CG_S_STARTBACKGROUNDTRACK, intro, loop );
}

void	trap_R_LoadWorldMap( const char *mapname ) {
    syscall( CG_R_LOADWORLDMAP, mapname );
}

qhandle_t trap_R_RegisterModel( const char *name ) {
    return syscall( CG_R_REGISTERMODEL, name );
}

qhandle_t trap_R_RegisterSkin( const char *name ) {
    return syscall( CG_R_REGISTERSKIN, name );
}

qhandle_t trap_R_RegisterShader( const char *name ) {
    return syscall( CG_R_REGISTERSHADER, name );
}

qhandle_t trap_R_RegisterShaderNoMip( const char *name ) {
    return syscall( CG_R_REGISTERSHADERNOMIP, name );
}

void trap_R_RegisterFont(const char *fontName, int pointSize, fontInfo_t *font) {
    syscall(CG_R_REGISTERFONT, fontName, pointSize, font );
}

void	trap_R_ClearScene( void ) {
    syscall( CG_R_CLEARSCENE );
}

void	trap_R_AddRefEntityToScene( const refEntity_t *re ) {
    syscall( CG_R_ADDREFENTITYTOSCENE, re );
}

void	trap_R_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts ) {
    syscall( CG_R_ADDPOLYTOSCENE, hShader, numVerts, verts );
}

void	trap_R_AddPolysToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts, int num ) {
    syscall( CG_R_ADDPOLYSTOSCENE, hShader, numVerts, verts, num );
}

int		trap_R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir ) {
    return syscall( CG_R_LIGHTFORPOINT, point, ambientLight, directedLight, lightDir );
}

void	trap_R_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ) {
    syscall( CG_R_ADDLIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b) );
}

void	trap_R_AddAdditiveLightToScene( const vec3_t org, float intensity, float r, float g, float b ) {
    syscall( CG_R_ADDADDITIVELIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b) );
}

void	trap_R_RenderScene( const refdef_t *fd ) {
    syscall( CG_R_RENDERSCENE, fd );
}

void	trap_R_SetColor( const float *rgba ) {
    syscall( CG_R_SETCOLOR, rgba );
}

void	trap_R_DrawStretchPic( float x, float y, float w, float h,
                               float s1, float t1, float s2, float t2, qhandle_t hShader ) {
    syscall( CG_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader );
}

void	trap_R_ModelBounds( clipHandle_t model, vec3_t mins, vec3_t maxs ) {
    syscall( CG_R_MODELBOUNDS, model, mins, maxs );
}

int		trap_R_LerpTag( orientation_t *tag, clipHandle_t mod, int startFrame, int endFrame,
                        float frac, const char *tagName ) {
    return syscall( CG_R_LERPTAG, tag, mod, startFrame, endFrame, PASSFLOAT(frac), tagName );
}

void	trap_R_RemapShader( const char *oldShader, const char *newShader, const char *timeOffset ) {
    syscall( CG_R_REMAP_SHADER, oldShader, newShader, timeOffset );
}

void		trap_GetGlconfig( glconfig_t *glconfig ) {
    syscall( CG_GETGLCONFIG, glconfig );
}

void		trap_GetGameState( gameState_t *gamestate ) {
    syscall( CG_GETGAMESTATE, gamestate );
}

void		trap_GetCurrentSnapshotNumber( int *snapshotNumber, int *serverTime ) {
    syscall( CG_GETCURRENTSNAPSHOTNUMBER, snapshotNumber, serverTime );
}

qboolean	trap_GetSnapshot( int snapshotNumber, snapshot_t *snapshot ) {
    return syscall( CG_GETSNAPSHOT, snapshotNumber, snapshot );
}

qboolean	trap_GetServerCommand( int serverCommandNumber ) {
    return syscall( CG_GETSERVERCOMMAND, serverCommandNumber );
}

int			trap_GetCurrentCmdNumber( void ) {
    return syscall( CG_GETCURRENTCMDNUMBER );
}

qboolean	trap_GetUserCmd( int cmdNumber, usercmd_t *ucmd ) {
    return syscall( CG_GETUSERCMD, cmdNumber, ucmd );
}

void		trap_SetUserCmdValue( int stateValue, float sensitivityScale ) {
    syscall( CG_SETUSERCMDVALUE, stateValue, PASSFLOAT(sensitivityScale) );
}

void		testPrintInt( char *string, int i ) {
    syscall( CG_TESTPRINTINT, string, i );
}

void		testPrintFloat( char *string, float f ) {
    syscall( CG_TESTPRINTFLOAT, string, PASSFLOAT(f) );
}

int trap_MemoryRemaining( void ) {
    return syscall( CG_MEMORY_REMAINING );
}

qboolean trap_Key_IsDown( int keynum ) {
    return syscall( CG_KEY_ISDOWN, keynum );
}

int trap_Key_GetCatcher( void ) {
    return syscall( CG_KEY_GETCATCHER );
}

void trap_Key_SetCatcher( int catcher ) {
    syscall( CG_KEY_SETCATCHER, catcher );
}

int trap_Key_GetKey( const char *binding ) {
    return syscall( CG_KEY_GETKEY, binding );
}

int trap_PC_AddGlobalDefine( char *define ) {
    return syscall( CG_PC_ADD_GLOBAL_DEFINE, define );
}

int trap_PC_LoadSource( const char *filename ) {
    return syscall( CG_PC_LOAD_SOURCE, filename );
}

int trap_PC_FreeSource( int handle ) {
    return syscall( CG_PC_FREE_SOURCE, handle );
}

int trap_PC_ReadToken( int handle, pc_token_t *pc_token ) {
    return syscall( CG_PC_READ_TOKEN, handle, pc_token );
}

int trap_PC_SourceFileAndLine( int handle, char *filename, int *line ) {
    return syscall( CG_PC_SOURCE_FILE_AND_LINE, handle, filename, line );
}

void	trap_S_StopBackgroundTrack( void ) {
    syscall( CG_S_STOPBACKGROUNDTRACK );
}

int trap_RealTime(qtime_t *qtime) {
    return syscall( CG_REAL_TIME, qtime );
}

void trap_SnapVector( float *v ) {
    syscall( CG_SNAPVECTOR, v );
}

// leilei - particles!
void	trap_R_LFX_ParticleEffect( int effect, const vec3_t origin, const vec3_t velocity ) {
    syscall( CG_R_LFX_PARTICLEEFFECT, effect, origin, velocity );
}

// this returns a handle.  arg0 is the name in the format "idlogo.roq", set arg1 to NULL, alteredstates to qfalse (do not alter gamestate)
int trap_CIN_PlayCinematic( const char *arg0, int xpos, int ypos, int width, int height, int bits) {
    return syscall(CG_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits);
}

// stops playing the cinematic and ends it.  should always return FMV_EOF
// cinematics must be stopped in reverse order of when they are started
e_status trap_CIN_StopCinematic(int handle) {
    return syscall(CG_CIN_STOPCINEMATIC, handle);
}

// will run a frame of the cinematic but will not draw it.  Will return FMV_EOF if the end of the cinematic has been reached.
e_status trap_CIN_RunCinematic (int handle) {
    return syscall(CG_CIN_RUNCINEMATIC, handle);
}

// draws the current frame
void trap_CIN_DrawCinematic (int handle) {
    syscall(CG_CIN_DRAWCINEMATIC, handle);
}

// allows you to resize the animation dynamically
void trap_CIN_SetExtents (int handle, int x, int y, int w, int h) {
    syscall(CG_CIN_SETEXTENTS, handle, x, y, w, h);
}

/*
qboolean trap_loadCamera( const char *name ) {
	return syscall( CG_LOADCAMERA, name );
}

void trap_startCamera(int time) {
	syscall(CG_STARTCAMERA, time);
}

qboolean trap_getCameraInfo( int time, vec3_t *origin, vec3_t *angles) {
	return syscall( CG_GETCAMERAINFO, time, origin, angles );
}
*/

qboolean trap_GetEntityToken( char *buffer, int bufferSize ) {
    return syscall( CG_GET_ENTITY_TOKEN, buffer, bufferSize );
}

qboolean trap_R_inPVS( const vec3_t p1, const vec3_t p2 ) {
    return syscall( CG_R_INPVS, p1, p2 );
}


text:
package pl.allegro.tech.build.axion.release.domain.properties;

import pl.allegro.tech.build.axion.release.domain.scm.ScmPosition;

public class NextVersionProperties {

    @FunctionalInterface
    public interface Serializer {
        String apply(NextVersionProperties nextVersionProperties, String version);
    }

    @FunctionalInterface
    public interface Deserializer {
        String apply(NextVersionProperties nextVersionProperties, ScmPosition position, String tag);
    }

    private final String nextVersion;
    private final String suffix;
    private final String separator;
    private final String versionIncrementer;
    private final Serializer serializer;
    private final Deserializer deserializer;

    public NextVersionProperties(
        String nextVersion,
        String suffix,
        String separator,
        String versionIncrementer,
        Serializer serializer,
        Deserializer deserializer
    ) {
        this.nextVersion = nextVersion;
        this.suffix = suffix;
        this.separator = separator;
        this.versionIncrementer = versionIncrementer;
        this.serializer = serializer;
        this.deserializer = deserializer;
    }

    public final String getNextVersion() {
        return nextVersion;
    }

    public final String getSuffix() {
        return suffix;
    }

    public final String getSeparator() {
        return separator;
    }

    public final String getVersionIncrementer() {
        return versionIncrementer;
    }

    public final Serializer getSerializer() {
        return serializer;
    }

    public final Deserializer getDeserializer() {
        return deserializer;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.qihoo.apitest.MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textResult"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hello World!"/>

            <EditText
                android:id="@+id/testEdit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:digits="1234567890qwertyuiopasdfghjklzxcvbnm"
                android:hint="input"/>

            <Button
                android:id="@+id/buttonAssert"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="assertTest"/>

            <Button
                android:id="@+id/buttonService"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="serviceLaunchTest"/>

            <Button
                android:id="@+id/buttonProvider"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="providerLaunchTest"/>

            <Button
                android:id="@+id/buttonNotification"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="notificationTest"/>

            <Button
                android:id="@+id/crashTest"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="crasH Test"/>

            <Button
                android:id="@+id/MemoryTest"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Memory Test"/>

            <Button
                android:id="@+id/system_settings"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="System Settings"/>

            <Button
                android:id="@+id/enter_shortcut"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="shortcut"/>

            <Button
                android:id="@+id/enterButterKnife"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="butterKnife"/>

            <Button
                android:id="@+id/enterDagger"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="dagger"/>

            <Button
                android:id="@+id/enterActivityAnim"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="enterActivityAnim"/>

            <Button
                android:id="@+id/enterRetrofit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="retrofit"/>
        </LinearLayout>
    </ScrollView>

</RelativeLayout>


text:
/*
 * Project: Twitter Bootstrap Hover Dropdown
 * Author: Cameron Spear
 * Contributors: Mattia Larentis
 *
 * Dependencies?: Twitter Bootstrap's Dropdown plugin
 *
 * A simple plugin to enable twitter bootstrap dropdowns to active on hover and provide a nice user experience.
 *
 * No license, do what you want. I'd love credit or a shoutout, though.
 *
 * http://cameronspear.com/blog/twitter-bootstrap-dropdown-on-hover-plugin/
 */
;(function($, window, undefined) {
    // outside the scope of the jQuery plugin to
    // keep track of all dropdowns
    var $allDropdowns = $();

    // if instantlyCloseOthers is true, then it will instantly
    // shut other nav items when a new one is hovered over
    $.fn.dropdownHover = function(options) {

        // the element we really care about
        // is the dropdown-toggle's parent
        $allDropdowns = $allDropdowns.add(this.parent());

        return this.each(function() {
            var $this = $(this).parent(),
                defaults = {
                    delay: 500,
                    instantlyCloseOthers: true
                },
                data = {
                    delay: $(this).data('delay'),
                    instantlyCloseOthers: $(this).data('close-others')
                },
                options = $.extend(true, {}, defaults, options, data),
                timeout;

            $this.hover(function() {
                if(options.instantlyCloseOthers === true)
                    $allDropdowns.removeClass('open');

                window.clearTimeout(timeout);
                $(this).addClass('open');
            }, function() {
                timeout = window.setTimeout(function() {
                    $this.removeClass('open');
                }, options.delay);
            });
        });
    };

    $('[data-hover="dropdown"]').dropdownHover();
})(jQuery, this);


text:
<?php

class TasksTableSeeder extends Seeder {

	/**
	 * Auto generated seed file
	 *
	 * @return void
	 */
	public function run()
	{
		\DB::table('tasks')->delete();

	}

}


text:
[![Fruit][logo]][repo-link]

[![CI Buimd][build-image]][build-url]
[![Dependencied][dependencies-image]][dependencies-url]
[![MIT license][license-img]][license-url]
[![Gitter][gitter-img]][gitter-url]

### Introduction :

This is the postgresql adapter for the [fruit](http://npmjs.com/package/fruit) ORM, if you haven't take a look at its documentation yet, please make sure to do so.

### Installation :

```bash
  $ npm install fruit fruit-postgresql
```

### Connection options :

This is an example the options you need to pass to the fruit constructor:

```javascript
  {
      host                : 'host'
    , database            : 'db'
    , user                : 'user'
    , password            : '******'
  }
```

### Contributing

All contributions are welcome. Let's get this project to the next level.
Significant and valuable contributions will allow you to be part of [Fruit organisation](http://github.com/nodefruit).
See the [contribution guide](http://github.com/nodefruit/fruit/blob/master/CONTRIBUTING.md) for more details

### Community

If you'd like to chat and discuss this project, you can find us here:

- Mailing list: [https://groups.google.com/forum/#!forum/nodefruit](https://groups.google.com/forum/#!forum/nodefruit)
- [![Join the chat at https://gitter.im/nodefruit/fruit](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/nodefruit/fruit?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

[logo]: https://github.com/nodefruit/fruit-postgresql/raw/master/pres/fruit-and-postgres-logo.png
[repo-link]: https://github.com/nodefruit/fruit-postgresql
[build-image]: https://api.travis-ci.org/nodefruit/fruit-postgresql.svg
[build-url]: https://github.com/nodefruit/fruit-postgresql
[stability-image]: https://img.shields.io/badge/stability-experimental-orange.svg
[stability-url]: https://github.com/nodefruit/fruit-mysql
[license-img]: https://img.shields.io/badge/license-MIT-green.svg
[license-url]: https://github.com/nodefruit/fruit-postgresql/blob/master/LICENSE
[dependencies-image]:https://david-dm.org/nodefruit/fruit-postgresql.svg
[dependencies-url]:https://npmjs.com/package/fruit-postgresql
[gitter-img]: https://badges.gitter.im/Join%20Chat.svg
[gitter-url]: https://gitter.im/nodefruit/fruit?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge


text:
"""Keras data preprocessing utils for image data."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.keras.preprocessing.image import apply_transform
from tensorflow.python.keras.preprocessing.image import array_to_img
from tensorflow.python.keras.preprocessing.image import DirectoryIterator
from tensorflow.python.keras.preprocessing.image import flip_axis
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from tensorflow.python.keras.preprocessing.image import img_to_array
from tensorflow.python.keras.preprocessing.image import Iterator
from tensorflow.python.keras.preprocessing.image import load_img
from tensorflow.python.keras.preprocessing.image import NumpyArrayIterator
from tensorflow.python.keras.preprocessing.image import random_channel_shift
from tensorflow.python.keras.preprocessing.image import random_rotation
from tensorflow.python.keras.preprocessing.image import random_shear
from tensorflow.python.keras.preprocessing.image import random_shift
from tensorflow.python.keras.preprocessing.image import random_zoom

del absolute_import
del division
del print_function


text:
<?php

/*
 * This file is part of the Gush.
 *
 * (c) Luis Cordova <cordoval@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Gush\Tests\Command;

use Github\Client;
use Gush\Application;
use Gush\Tester\HttpClient\TestHttpClient;
use Gush\Tests\TestableApplication;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\CommandTester;

/**
 * @author Daniel T Leech <dantleech@gmail.com>
 */
class BaseTestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * @var TestHttpClient
     */
    protected $httpClient;

    public function setUp()
    {
        $this->httpClient = new TestHttpClient();
    }

    /**
     * @param Command $command
     * @return CommandTester
     */
    protected function getCommandTester(Command $command)
    {
        $application = new TestableApplication();
        $application->setAutoExit(false);
        $application->setGithubClient($this->buildGithubClient());
        $command->setApplication($application);

        return new CommandTester($command);
    }

    protected function buildGithubClient()
    {
        return new Client($this->httpClient);
    }
}


text:
#include "test/cpp/interop/interop_client.h"

#include <unistd.h>

#include <fstream>
#include <memory>

#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/useful.h>
#include <grpc++/channel.h>
#include <grpc++/client_context.h>
#include <grpc++/security/credentials.h>

#include "src/core/transport/stream_op.h"
#include "test/cpp/interop/client_helper.h"
#include "test/proto/test.grpc.pb.h"
#include "test/proto/empty.grpc.pb.h"
#include "test/proto/messages.grpc.pb.h"

namespace grpc {
namespace testing {

static const char* kRandomFile = "test/cpp/interop/rnd.dat";

namespace {
// The same value is defined by the Java client.
const std::vector<int> request_stream_sizes = {27182, 8, 1828, 45904};
const std::vector<int> response_stream_sizes = {31415, 9, 2653, 58979};
const int kNumResponseMessages = 2000;
const int kResponseMessageSize = 1030;
const int kReceiveDelayMilliSeconds = 20;
const int kLargeRequestSize = 271828;
const int kLargeResponseSize = 314159;

CompressionType GetInteropCompressionTypeFromCompressionAlgorithm(
    grpc_compression_algorithm algorithm) {
  switch (algorithm) {
    case GRPC_COMPRESS_NONE:
      return CompressionType::NONE;
    case GRPC_COMPRESS_GZIP:
      return CompressionType::GZIP;
    case GRPC_COMPRESS_DEFLATE:
      return CompressionType::DEFLATE;
    default:
      GPR_ASSERT(false);
  }
}
}  // namespace

InteropClient::InteropClient(std::shared_ptr<Channel> channel)
    : channel_(channel) {}

void InteropClient::AssertOkOrPrintErrorStatus(const Status& s) {
  if (s.ok()) {
    return;
  }
  gpr_log(GPR_INFO, "Error status code: %d, message: %s", s.error_code(),
          s.error_message().c_str());
  GPR_ASSERT(0);
}

void InteropClient::DoEmpty() {
  gpr_log(GPR_INFO, "Sending an empty rpc...");
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  Empty request = Empty::default_instance();
  Empty response = Empty::default_instance();
  ClientContext context;

  Status s = stub->EmptyCall(&context, request, &response);
  AssertOkOrPrintErrorStatus(s);

  gpr_log(GPR_INFO, "Empty rpc done.");
}

// Shared code to set large payload, make rpc and check response payload.
void InteropClient::PerformLargeUnary(SimpleRequest* request,
                                      SimpleResponse* response) {
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  ClientContext context;
  InteropClientContextInspector inspector(context);
  // If the request doesn't already specify the response type, default to
  // COMPRESSABLE.
  request->set_response_size(kLargeResponseSize);
  grpc::string payload(kLargeRequestSize, '\0');
  request->mutable_payload()->set_body(payload.c_str(), kLargeRequestSize);

  Status s = stub->UnaryCall(&context, *request, response);

  // Compression related checks.
  GPR_ASSERT(request->response_compression() ==
             GetInteropCompressionTypeFromCompressionAlgorithm(
                 inspector.GetCallCompressionAlgorithm()));
  if (request->response_compression() == NONE) {
    GPR_ASSERT(!(inspector.GetMessageFlags() & GRPC_WRITE_INTERNAL_COMPRESS));
  } else if (request->response_type() == PayloadType::COMPRESSABLE) {
    // requested compression and compressable response => results should always
    // be compressed.
    GPR_ASSERT(inspector.GetMessageFlags() & GRPC_WRITE_INTERNAL_COMPRESS);
  }

  AssertOkOrPrintErrorStatus(s);

  // Payload related checks.
  if (request->response_type() != PayloadType::RANDOM) {
    GPR_ASSERT(response->payload().type() == request->response_type());
  }
  switch (response->payload().type()) {
    case PayloadType::COMPRESSABLE:
      GPR_ASSERT(response->payload().body() ==
                 grpc::string(kLargeResponseSize, '\0'));
      break;
    case PayloadType::UNCOMPRESSABLE: {
      std::ifstream rnd_file(kRandomFile);
      GPR_ASSERT(rnd_file.good());
      for (int i = 0; i < kLargeResponseSize; i++) {
        GPR_ASSERT(response->payload().body()[i] == (char)rnd_file.get());
      }
    } break;
    default:
      GPR_ASSERT(false);
  }
}

void InteropClient::DoComputeEngineCreds(
    const grpc::string& default_service_account,
    const grpc::string& oauth_scope) {
  gpr_log(GPR_INFO,
          "Sending a large unary rpc with compute engine credentials ...");
  SimpleRequest request;
  SimpleResponse response;
  request.set_fill_username(true);
  request.set_fill_oauth_scope(true);
  request.set_response_type(PayloadType::COMPRESSABLE);
  PerformLargeUnary(&request, &response);
  gpr_log(GPR_INFO, "Got username %s", response.username().c_str());
  gpr_log(GPR_INFO, "Got oauth_scope %s", response.oauth_scope().c_str());
  GPR_ASSERT(!response.username().empty());
  GPR_ASSERT(response.username().c_str() == default_service_account);
  GPR_ASSERT(!response.oauth_scope().empty());
  const char* oauth_scope_str = response.oauth_scope().c_str();
  GPR_ASSERT(oauth_scope.find(oauth_scope_str) != grpc::string::npos);
  gpr_log(GPR_INFO, "Large unary with compute engine creds done.");
}

void InteropClient::DoOauth2AuthToken(const grpc::string& username,
                                      const grpc::string& oauth_scope) {
  gpr_log(GPR_INFO,
          "Sending a unary rpc with raw oauth2 access token credentials ...");
  SimpleRequest request;
  SimpleResponse response;
  request.set_fill_username(true);
  request.set_fill_oauth_scope(true);
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  ClientContext context;

  Status s = stub->UnaryCall(&context, request, &response);

  AssertOkOrPrintErrorStatus(s);
  GPR_ASSERT(!response.username().empty());
  GPR_ASSERT(!response.oauth_scope().empty());
  GPR_ASSERT(username == response.username());
  const char* oauth_scope_str = response.oauth_scope().c_str();
  GPR_ASSERT(oauth_scope.find(oauth_scope_str) != grpc::string::npos);
  gpr_log(GPR_INFO, "Unary with oauth2 access token credentials done.");
}

void InteropClient::DoPerRpcCreds(const grpc::string& json_key) {
  gpr_log(GPR_INFO, "Sending a unary rpc with per-rpc JWT access token ...");
  SimpleRequest request;
  SimpleResponse response;
  request.set_fill_username(true);
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  ClientContext context;
  std::chrono::seconds token_lifetime = std::chrono::hours(1);
  std::shared_ptr<Credentials> creds =
      ServiceAccountJWTAccessCredentials(json_key, token_lifetime.count());

  context.set_credentials(creds);

  Status s = stub->UnaryCall(&context, request, &response);

  AssertOkOrPrintErrorStatus(s);
  GPR_ASSERT(!response.username().empty());
  GPR_ASSERT(json_key.find(response.username()) != grpc::string::npos);
  gpr_log(GPR_INFO, "Unary with per-rpc JWT access token done.");
}

void InteropClient::DoJwtTokenCreds(const grpc::string& username) {
  gpr_log(GPR_INFO, "Sending a large unary rpc with JWT token credentials ...");
  SimpleRequest request;
  SimpleResponse response;
  request.set_fill_username(true);
  request.set_response_type(PayloadType::COMPRESSABLE);
  PerformLargeUnary(&request, &response);
  GPR_ASSERT(!response.username().empty());
  GPR_ASSERT(username.find(response.username()) != grpc::string::npos);
  gpr_log(GPR_INFO, "Large unary with JWT token creds done.");
}

void InteropClient::DoLargeUnary() {
  gpr_log(GPR_INFO, "Sending a large unary rpc...");
  SimpleRequest request;
  SimpleResponse response;
  request.set_response_type(PayloadType::COMPRESSABLE);
  PerformLargeUnary(&request, &response);
  gpr_log(GPR_INFO, "Large unary done.");
}

void InteropClient::DoLargeCompressedUnary() {
  const CompressionType compression_types[] = {NONE, GZIP, DEFLATE};
  const PayloadType payload_types[] = {COMPRESSABLE, UNCOMPRESSABLE, RANDOM};
  for (size_t i = 0; i < GPR_ARRAY_SIZE(payload_types); i++) {
    for (size_t j = 0; j < GPR_ARRAY_SIZE(compression_types); j++) {
      char* log_suffix;
      gpr_asprintf(&log_suffix, "(compression=%s; payload=%s)",
                   CompressionType_Name(compression_types[j]).c_str(),
                   PayloadType_Name(payload_types[i]).c_str());

      gpr_log(GPR_INFO, "Sending a large compressed unary rpc %s.", log_suffix);
      SimpleRequest request;
      SimpleResponse response;
      request.set_response_type(payload_types[i]);
      request.set_response_compression(compression_types[j]);
      PerformLargeUnary(&request, &response);
      gpr_log(GPR_INFO, "Large compressed unary done %s.", log_suffix);
      gpr_free(log_suffix);
    }
  }
}

void InteropClient::DoRequestStreaming() {
  gpr_log(GPR_INFO, "Sending request steaming rpc ...");
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  ClientContext context;
  StreamingInputCallRequest request;
  StreamingInputCallResponse response;

  std::unique_ptr<ClientWriter<StreamingInputCallRequest>> stream(
      stub->StreamingInputCall(&context, &response));

  int aggregated_payload_size = 0;
  for (unsigned int i = 0; i < request_stream_sizes.size(); ++i) {
    Payload* payload = request.mutable_payload();
    payload->set_body(grpc::string(request_stream_sizes[i], '\0'));
    GPR_ASSERT(stream->Write(request));
    aggregated_payload_size += request_stream_sizes[i];
  }
  stream->WritesDone();
  Status s = stream->Finish();

  GPR_ASSERT(response.aggregated_payload_size() == aggregated_payload_size);
  AssertOkOrPrintErrorStatus(s);
  gpr_log(GPR_INFO, "Request streaming done.");
}

void InteropClient::DoResponseStreaming() {
  gpr_log(GPR_INFO, "Receiving response steaming rpc ...");
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  ClientContext context;
  StreamingOutputCallRequest request;
  for (unsigned int i = 0; i < response_stream_sizes.size(); ++i) {
    ResponseParameters* response_parameter = request.add_response_parameters();
    response_parameter->set_size(response_stream_sizes[i]);
  }
  StreamingOutputCallResponse response;
  std::unique_ptr<ClientReader<StreamingOutputCallResponse>> stream(
      stub->StreamingOutputCall(&context, request));

  unsigned int i = 0;
  while (stream->Read(&response)) {
    GPR_ASSERT(response.payload().body() ==
               grpc::string(response_stream_sizes[i], '\0'));
    ++i;
  }
  GPR_ASSERT(response_stream_sizes.size() == i);
  Status s = stream->Finish();
  AssertOkOrPrintErrorStatus(s);
  gpr_log(GPR_INFO, "Response streaming done.");
}

void InteropClient::DoResponseCompressedStreaming() {
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  const CompressionType compression_types[] = {NONE, GZIP, DEFLATE};
  const PayloadType payload_types[] = {COMPRESSABLE, UNCOMPRESSABLE, RANDOM};
  for (size_t i = 0; i < GPR_ARRAY_SIZE(payload_types); i++) {
    for (size_t j = 0; j < GPR_ARRAY_SIZE(compression_types); j++) {
      ClientContext context;
      InteropClientContextInspector inspector(context);
      StreamingOutputCallRequest request;

      char* log_suffix;
      gpr_asprintf(&log_suffix, "(compression=%s; payload=%s)",
                   CompressionType_Name(compression_types[j]).c_str(),
                   PayloadType_Name(payload_types[i]).c_str());

      gpr_log(GPR_INFO, "Receiving response steaming rpc %s.", log_suffix);

      request.set_response_type(payload_types[i]);
      request.set_response_compression(compression_types[j]);

      for (size_t k = 0; k < response_stream_sizes.size(); ++k) {
        ResponseParameters* response_parameter =
            request.add_response_parameters();
        response_parameter->set_size(response_stream_sizes[k]);
      }
      StreamingOutputCallResponse response;

      std::unique_ptr<ClientReader<StreamingOutputCallResponse>> stream(
          stub->StreamingOutputCall(&context, request));

      size_t k = 0;
      while (stream->Read(&response)) {
        // Payload related checks.
        if (request.response_type() != PayloadType::RANDOM) {
          GPR_ASSERT(response.payload().type() == request.response_type());
        }
        switch (response.payload().type()) {
          case PayloadType::COMPRESSABLE:
            GPR_ASSERT(response.payload().body() ==
                       grpc::string(response_stream_sizes[k], '\0'));
            break;
          case PayloadType::UNCOMPRESSABLE: {
            std::ifstream rnd_file(kRandomFile);
            GPR_ASSERT(rnd_file.good());
            for (int n = 0; n < response_stream_sizes[k]; n++) {
              GPR_ASSERT(response.payload().body()[n] == (char)rnd_file.get());
            }
          } break;
          default:
            GPR_ASSERT(false);
        }

        // Compression related checks.
        GPR_ASSERT(request.response_compression() ==
                   GetInteropCompressionTypeFromCompressionAlgorithm(
                       inspector.GetCallCompressionAlgorithm()));
        if (request.response_compression() == NONE) {
          GPR_ASSERT(
              !(inspector.GetMessageFlags() & GRPC_WRITE_INTERNAL_COMPRESS));
        } else if (request.response_type() == PayloadType::COMPRESSABLE) {
          // requested compression and compressable response => results should
          // always be compressed.
          GPR_ASSERT(inspector.GetMessageFlags() &
                     GRPC_WRITE_INTERNAL_COMPRESS);
        }

        ++k;
      }

      GPR_ASSERT(response_stream_sizes.size() == k);
      Status s = stream->Finish();

      AssertOkOrPrintErrorStatus(s);
      gpr_log(GPR_INFO, "Response streaming done %s.", log_suffix);
      gpr_free(log_suffix);
    }
  }
}

void InteropClient::DoResponseStreamingWithSlowConsumer() {
  gpr_log(GPR_INFO, "Receiving response steaming rpc with slow consumer ...");
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  ClientContext context;
  StreamingOutputCallRequest request;

  for (int i = 0; i < kNumResponseMessages; ++i) {
    ResponseParameters* response_parameter = request.add_response_parameters();
    response_parameter->set_size(kResponseMessageSize);
  }
  StreamingOutputCallResponse response;
  std::unique_ptr<ClientReader<StreamingOutputCallResponse>> stream(
      stub->StreamingOutputCall(&context, request));

  int i = 0;
  while (stream->Read(&response)) {
    GPR_ASSERT(response.payload().body() ==
               grpc::string(kResponseMessageSize, '\0'));
    gpr_log(GPR_INFO, "received message %d", i);
    usleep(kReceiveDelayMilliSeconds * 1000);
    ++i;
  }
  GPR_ASSERT(kNumResponseMessages == i);
  Status s = stream->Finish();

  AssertOkOrPrintErrorStatus(s);
  gpr_log(GPR_INFO, "Response streaming done.");
}

void InteropClient::DoHalfDuplex() {
  gpr_log(GPR_INFO, "Sending half-duplex streaming rpc ...");
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  ClientContext context;
  std::unique_ptr<ClientReaderWriter<StreamingOutputCallRequest,
                                     StreamingOutputCallResponse>>
      stream(stub->HalfDuplexCall(&context));

  StreamingOutputCallRequest request;
  ResponseParameters* response_parameter = request.add_response_parameters();
  for (unsigned int i = 0; i < response_stream_sizes.size(); ++i) {
    response_parameter->set_size(response_stream_sizes[i]);
    GPR_ASSERT(stream->Write(request));
  }
  stream->WritesDone();

  unsigned int i = 0;
  StreamingOutputCallResponse response;
  while (stream->Read(&response)) {
    GPR_ASSERT(response.payload().body() ==
               grpc::string(response_stream_sizes[i], '\0'));
    ++i;
  }
  GPR_ASSERT(response_stream_sizes.size() == i);
  Status s = stream->Finish();
  AssertOkOrPrintErrorStatus(s);
  gpr_log(GPR_INFO, "Half-duplex streaming rpc done.");
}

void InteropClient::DoPingPong() {
  gpr_log(GPR_INFO, "Sending Ping Pong streaming rpc ...");
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  ClientContext context;
  std::unique_ptr<ClientReaderWriter<StreamingOutputCallRequest,
                                     StreamingOutputCallResponse>>
      stream(stub->FullDuplexCall(&context));

  StreamingOutputCallRequest request;
  request.set_response_type(PayloadType::COMPRESSABLE);
  ResponseParameters* response_parameter = request.add_response_parameters();
  Payload* payload = request.mutable_payload();
  StreamingOutputCallResponse response;
  for (unsigned int i = 0; i < request_stream_sizes.size(); ++i) {
    response_parameter->set_size(response_stream_sizes[i]);
    payload->set_body(grpc::string(request_stream_sizes[i], '\0'));
    GPR_ASSERT(stream->Write(request));
    GPR_ASSERT(stream->Read(&response));
    GPR_ASSERT(response.payload().body() ==
               grpc::string(response_stream_sizes[i], '\0'));
  }

  stream->WritesDone();
  GPR_ASSERT(!stream->Read(&response));
  Status s = stream->Finish();
  AssertOkOrPrintErrorStatus(s);
  gpr_log(GPR_INFO, "Ping pong streaming done.");
}

void InteropClient::DoCancelAfterBegin() {
  gpr_log(GPR_INFO, "Sending request steaming rpc ...");
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  ClientContext context;
  StreamingInputCallRequest request;
  StreamingInputCallResponse response;

  std::unique_ptr<ClientWriter<StreamingInputCallRequest>> stream(
      stub->StreamingInputCall(&context, &response));

  gpr_log(GPR_INFO, "Trying to cancel...");
  context.TryCancel();
  Status s = stream->Finish();
  GPR_ASSERT(s.error_code() == StatusCode::CANCELLED);
  gpr_log(GPR_INFO, "Canceling streaming done.");
}

void InteropClient::DoCancelAfterFirstResponse() {
  gpr_log(GPR_INFO, "Sending Ping Pong streaming rpc ...");
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  ClientContext context;
  std::unique_ptr<ClientReaderWriter<StreamingOutputCallRequest,
                                     StreamingOutputCallResponse>>
      stream(stub->FullDuplexCall(&context));

  StreamingOutputCallRequest request;
  request.set_response_type(PayloadType::COMPRESSABLE);
  ResponseParameters* response_parameter = request.add_response_parameters();
  response_parameter->set_size(31415);
  request.mutable_payload()->set_body(grpc::string(27182, '\0'));
  StreamingOutputCallResponse response;
  GPR_ASSERT(stream->Write(request));
  GPR_ASSERT(stream->Read(&response));
  GPR_ASSERT(response.payload().body() == grpc::string(31415, '\0'));
  gpr_log(GPR_INFO, "Trying to cancel...");
  context.TryCancel();

  Status s = stream->Finish();
  gpr_log(GPR_INFO, "Canceling pingpong streaming done.");
}

void InteropClient::DoTimeoutOnSleepingServer() {
  gpr_log(GPR_INFO, "Sending Ping Pong streaming rpc with a short deadline...");
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  ClientContext context;
  std::chrono::system_clock::time_point deadline =
      std::chrono::system_clock::now() + std::chrono::milliseconds(1);
  context.set_deadline(deadline);
  std::unique_ptr<ClientReaderWriter<StreamingOutputCallRequest,
                                     StreamingOutputCallResponse>>
      stream(stub->FullDuplexCall(&context));

  StreamingOutputCallRequest request;
  request.mutable_payload()->set_body(grpc::string(27182, '\0'));
  stream->Write(request);

  Status s = stream->Finish();
  GPR_ASSERT(s.error_code() == StatusCode::DEADLINE_EXCEEDED);
  gpr_log(GPR_INFO, "Pingpong streaming timeout done.");
}

void InteropClient::DoEmptyStream() {
  gpr_log(GPR_INFO, "Starting empty_stream.");
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  ClientContext context;
  std::unique_ptr<ClientReaderWriter<StreamingOutputCallRequest,
                                     StreamingOutputCallResponse>>
      stream(stub->FullDuplexCall(&context));
  stream->WritesDone();
  StreamingOutputCallResponse response;
  GPR_ASSERT(stream->Read(&response) == false);
  Status s = stream->Finish();
  AssertOkOrPrintErrorStatus(s);
  gpr_log(GPR_INFO, "empty_stream done.");
}

void InteropClient::DoStatusWithMessage() {
  gpr_log(GPR_INFO, "Sending RPC with a request for status code 2 and message");
  std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel_));

  ClientContext context;
  SimpleRequest request;
  SimpleResponse response;
  EchoStatus* requested_status = request.mutable_response_status();
  requested_status->set_code(grpc::StatusCode::UNKNOWN);
  grpc::string test_msg = "This is a test message";
  requested_status->set_message(test_msg);

  Status s = stub->UnaryCall(&context, request, &response);

  GPR_ASSERT(s.error_code() == grpc::StatusCode::UNKNOWN);
  GPR_ASSERT(s.error_message() == test_msg);
  gpr_log(GPR_INFO, "Done testing Status and Message");
}

}  // namespace testing
}  // namespace grpc


text:
{% extends '_skeleton.html' %}

{% block content %}

Authenticate

List Bookings

	{%block book_content%}{%endblock%}
{% endblock %}


text:
"""
testrun.py

author: erich@emfeld.com
========================

This file acts as the test server.

WARNING!
This server is not for production usage it is only intended
as a testing server. Please use gunicorn or tornado webserver.

Please refer to box.py -h for more info.

"""
from app import app
from config import SERVER_PORT

app.run(debug = True,port=SERVER_PORT)

# end of file


text:
import sys
import io
import six
import datetime

from twisted.python import log
from twisted.internet.defer import inlineCallbacks, Deferred, DeferredList
from twisted.internet.endpoints import serverFromString

from autobahn.wamp import router
from autobahn.twisted.util import sleep
from autobahn.twisted import wamp, websocket

class CaseComponent(wamp.ApplicationSession):
   """
   Application code goes here. This is an example component that calls
   a remote procedure on a WAMP peer, subscribes to a topic to receive
   events, and then stops the world after some events.
   """

   def __init__(self, config, done):
      wamp.ApplicationSession.__init__(self, config)
      self._done = done
      self.stop = False
      self._logline = 1
      self.finished = False

   def log(self, *args):
      if len(args) > 1:
         sargs = ", ".join(str(s) for s in args)
      elif len(args) == 1:
         sargs = args[0]
      else:
         sargs = "-"

      msg = u'= : {:>3} : {:<20} : {}'.format(self._logline, self.__class__.__name__, sargs)
      self._logline += 1
      print(msg)
      if self.config.log and not self.config.log.closed:
         self.config.log.write(msg + "\n")
         self.config.log.flush()
      else:
         print("log already closed")

   def finish(self):
      if not self.finished:
         self._done.callback(None)
         #self.disconnect()
         self.finished = True
      else:
         print("already finished")

class Case1_Backend(CaseComponent):

   @inlineCallbacks
   def onJoin(self, details):

      self.log("joined")

      def add2(x, y):
         self.log("add2 invoked: {}, {}".format(x, y))
         return x + y

      yield self.register(add2, 'com.mathservice.add2')
      self.log("add2 registered")

      self.finish()

class Case1_Frontend(CaseComponent):

   @inlineCallbacks
   def onJoin(self, details):

      self.log("joined")

      try:
         res = yield self.call('com.mathservice.add2', 2, 3)
      except Exception as e:
         self.log("call error: {}".format(e))
      else:
         self.log("call result: {}".format(res))

      self.finish()

class Case2_Backend(CaseComponent):

   @inlineCallbacks
   def onJoin(self, details):

      self.log("joined")

      def ping():
         self.log("ping() is invoked")
         return

      def add2(a, b):
         self.log("add2() is invoked", a, b)
         return a + b

      def stars(nick = "somebody", stars = 0):
         self.log("stars() is invoked", nick, stars)
         return u"{} starred {}x".format(nick, stars)

      def orders(product, limit = 5):
         self.log("orders() is invoked", product, limit)
         return [u"Product {}".format(i) for i in range(50)][:limit]

      def arglen(*args, **kwargs):
         self.log("arglen() is invoked", args, kwargs)
         return [len(args), len(kwargs)]

      yield self.register(ping, u'com.arguments.ping')
      yield self.register(add2, u'com.arguments.add2')
      yield self.register(stars, u'com.arguments.stars')
      yield self.register(orders, u'com.arguments.orders')
      yield self.register(arglen, u'com.arguments.arglen')

      self.log("procedures registered")

      self.finish()

from autobahn.twisted.util import sleep

class Case2_Frontend(CaseComponent):

   @inlineCallbacks
   def onJoin(self, details):

      self.log("joined")

      #yield sleep(3)

      yield self.call(u'com.arguments.ping')
      self.log("Pinged!")

      res = yield self.call(u'com.arguments.add2', 2, 3)
      self.log("Add2: {}".format(res))

      starred = yield self.call(u'com.arguments.stars')
      self.log("Starred 1: {}".format(starred))

      starred = yield self.call(u'com.arguments.stars', nick = u'Homer')
      self.log("Starred 2: {}".format(starred))

      starred = yield self.call(u'com.arguments.stars', stars = 5)
      self.log("Starred 3: {}".format(starred))

      starred = yield self.call(u'com.arguments.stars', nick = u'Homer', stars = 5)
      self.log("Starred 4: {}".format(starred))

      orders = yield self.call(u'com.arguments.orders', u'coffee')
      self.log("Orders 1: {}".format(orders))

      orders = yield self.call(u'com.arguments.orders', u'coffee', limit = 10)
      self.log("Orders 2: {}".format(orders))

      arglengths = yield self.call(u'com.arguments.arglen')
      self.log("Arglen 1: {}".format(arglengths))

      arglengths = yield self.call(u'com.arguments.arglen', 1, 2, 3)
      self.log("Arglen 1: {}".format(arglengths))

      arglengths = yield self.call(u'com.arguments.arglen', a = 1, b = 2, c = 3)
      self.log("Arglen 2: {}".format(arglengths))

      arglengths = yield self.call(u'com.arguments.arglen', 1, 2, 3, a = 1, b = 2, c = 3)
      self.log("Arglen 3: {}".format(arglengths))

      #self.leave()

      self.finish()

## test different deployment topologies
##

if __name__ == '__main__':

   import sys, argparse

   from twisted.python import log
   from twisted.internet.endpoints import serverFromString
   from twisted.internet.endpoints import clientFromString

   ## parse command line arguments
   ##
   parser = argparse.ArgumentParser()

   parser.add_argument("-d", "--debug", action = "store_true",
                       help = "Enable debug output.")

   parser.add_argument("-c", "--component", type = str, default = None,
                       help = "Start WAMP server with this application component, e.g. 'timeservice.TimeServiceBackend', or None.")

   parser.add_argument("-r", "--realm", type = str, default = "realm1",
                       help = "The WAMP realm to start the component in (if any).")

   parser.add_argument("-u", "--url", type = str, default = "ws://127.0.0.1:8080",
                       help = "WebSocket URL.")

   parser.add_argument("--server", type = str, default = "tcp:8080",
                       help = 'Twisted server endpoint descriptor, e.g. "tcp:8080" or "unix:/tmp/mywebsocket".')

   parser.add_argument("--client", type = str, default = "tcp:127.0.0.1:8080",
                       help = 'Twisted client endpoint descriptor, e.g. "tcp:127.0.0.1:8080" or "unix:/tmp/mywebsocket".')

   parser.add_argument("--transport", choices = ['websocket', 'rawsocket-json', 'rawsocket-msgpack'], default = "websocket",
                       help = 'WAMP transport type')

   args = parser.parse_args()

   ## start Twisted logging to stdout
   ##
   if args.debug:
      log.startLogging(sys.stdout)

   ## we use an Autobahn utility to install the "best" available Twisted reactor
   ##
   from autobahn.twisted.choosereactor import install_reactor
   reactor = install_reactor()
   if args.debug:
      print("Running on reactor {}".format(reactor))

   ## create a WAMP router factory
   ##
   from autobahn.wamp.router import RouterFactory
   router_factory = RouterFactory()

   ## create a WAMP router session factory
   ##
   from autobahn.twisted.wamp import RouterSessionFactory
   session_factory = RouterSessionFactory(router_factory)

   ## .. and create and add an WAMP application session to
   ## run next to the router
   ##
   from autobahn.wamp import types

   config = types.ComponentConfig(realm = args.realm,
      extra = {
         'caselog': 'case1.log'
      }
   )

   if False:
      embedded_components = [Case1_Backend]
      client_components = [Case1_Frontend]
   else:
      embedded_components = []
      #client_components = [Case2_Backend]
      #client_components = [Case1_Backend, Case1_Frontend]
      client_components = [Case2_Backend, Case2_Frontend]

   log = io.open(config.extra['caselog'], 'w')
   config.log = log
   config.components = []

   config.all_done = []

   for C in embedded_components:
      one_done = Deferred()
      config.all_done.append(one_done)
      c = C(config, one_done)
      config.components.append(c)
      session_factory.add(c)

   if args.transport == "websocket":

      ## create a WAMP-over-WebSocket transport server factory
      ##
      from autobahn.twisted.websocket import WampWebSocketServerFactory
      transport_factory = WampWebSocketServerFactory(session_factory, debug_wamp = args.debug)
      transport_factory.setProtocolOptions(failByDrop = False)

   elif args.transport in ['rawsocket-json', 'rawsocket-msgpack']:

      ## create a WAMP-over-RawSocket transport server factory
      ##
      if args.transport == 'rawsocket-msgpack':
         from autobahn.wamp.serializer import MsgPackSerializer
         serializer = MsgPackSerializer()
      elif args.transport == 'rawsocket-json':
         from autobahn.wamp.serializer import JsonSerializer
         serializer = JsonSerializer()
      else:
         raise Exception("should not arrive here")

      from autobahn.twisted.rawsocket import WampRawSocketServerFactory
      transport_factory = WampRawSocketServerFactory(session_factory, serializer, debug = args.debug)

   else:
      raise Exception("should not arrive here")

   from autobahn.twisted.websocket import WampWebSocketClientFactory, WampWebSocketClientProtocol

   ## start the server from an endpoint
   ##
   server = serverFromString(reactor, args.server)
   server.listen(transport_factory)

   clients = []
   clients_d = []
   for C in client_components:
      ## create a WAMP application session factory
      ##
      from autobahn.twisted.wamp import ApplicationSessionFactory
      session_factory = ApplicationSessionFactory(config)

      one_done = Deferred()
      config.all_done.append(one_done)

      def make_make(Klass, done):
         def make(config):
            c = Klass(config, done)
            config.components.append(c)
            return c
         return make

      ## .. and set the session class on the factory
      ##
      session_factory.session = make_make(C, one_done)

      if args.transport == "websocket":

         from autobahn.wamp.serializer import JsonSerializer

         serializers = [JsonSerializer()]

         ## create a WAMP-over-WebSocket transport client factory
         ##
         transport_factory = WampWebSocketClientFactory(session_factory, serializers = serializers, url = args.url, debug_wamp = args.debug)

         if False:
            def maker(Klass):
               class TestClientProtocol(WampWebSocketClientProtocol):
                  def onOpen(self):
                     self.txcnt = 0
                     self.rxcnt = 0
                     WampWebSocketClientProtocol.onOpen(self)

                  def sendMessage(self, bytes, isBinary):
                     self.txcnt += 1
                     print("> : {:>3} : {:<20} : {}".format(self.txcnt, Klass.__name__, bytes))
                     WampWebSocketClientProtocol.sendMessage(self, bytes, isBinary)

                  def onMessage(self, bytes, isBinary):
                     self.rxcnt += 1
                     print("< : {:>3} : {:<20} : {}".format(self.rxcnt, Klass.__name__, bytes))
                     WampWebSocketClientProtocol.onMessage(self, bytes, isBinary)
               return TestClientProtocol

            transport_factory.protocol = maker(C)
         else:
            transport_factory.protocol = WampWebSocketClientProtocol

         transport_factory.setProtocolOptions(failByDrop = False)

      elif args.transport in ['rawsocket-json', 'rawsocket-msgpack']:

         ## create a WAMP-over-RawSocket transport client factory
         ##
         if args.transport == 'rawsocket-msgpack':
            from autobahn.wamp.serializer import MsgPackSerializer
            serializer = MsgPackSerializer()
         elif args.transport == 'rawsocket-json':
            from autobahn.wamp.serializer import JsonSerializer
            serializer = JsonSerializer()
         else:
            raise Exception("should not arrive here")

         from autobahn.twisted.rawsocket import WampRawSocketClientFactory
         transport_factory = WampRawSocketClientFactory(session_factory, serializer, debug = args.debug)

      ## start the client from an endpoint
      ##
      cl = clientFromString(reactor, args.client)
      clients_d.append(cl.connect(transport_factory))

      clients.append(cl)

   d = DeferredList(config.all_done)
   #d = config.components[1]._done

   def done(res):
      log.flush()
      log.close()
      for c in config.components:
         c.leave()
      from twisted.internet import reactor
      reactor.callLater(1, reactor.stop)

   d.addCallback(done)

   ## now enter the Twisted reactor loop
   ##
   reactor.run()


text:
@interface TMOSecurity ()

+ (NSString *)secretKeyForService:(NSString *)argService;

@end

static NSString *documentPath () {
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingString:@"/com.duowan.security/"];
}

static NSString *cachePath () {
    return [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingString:@"/com.duowan.security/"];
}

@implementation TMOSecurity

+ (NSString *)secretKeyForService:(NSString *)argService {
    NSString *keychainSecretKey;
    if ((keychainSecretKey = [SSKeychain passwordForService:argService account:@"$default"]) != nil) {
        return keychainSecretKey;
    }
    else {
        return [self generateKeyForService:argService];
    }
}

+ (NSString *)generateKeyForService:(NSString *)argService {
    NSString *finalKey = @"";
    for (NSUInteger j=0; j<8; j++) {
        NSString *randomString = [NSString stringWithFormat:@"%@.%d.%d.%d.%@", argService, arc4random(), arc4random(), arc4random(), argService];
        NSInteger randomHashTime = arc4random() % 100;
        NSString *key = randomString;
        for (NSUInteger i = 0; i < randomHashTime; i++) {
            key = [key stringByMD5Hash];
        }
        finalKey = [finalKey stringByAppendingString:key];
    }
    [SSKeychain setPassword:finalKey forService:argService account:@"$default"];
    return finalKey;
}

+ (id)objectFromSecurityArea:(NSString *)argSecurityArea withIdetifier:(NSString *)argIdentifier {
    if ([argSecurityArea isEqualToString:kTMOSecurityAreaKeychain]) {
        return [SSKeychain passwordForService:@"TMOSecurityArea" account:argIdentifier];
    }
    else {
        NSData *storageData = [self dataFromSecurityArea:argSecurityArea withIdetifier:argIdentifier];
        if (storageData == nil) {
            return nil;
        }
        else {
            return [NSKeyedUnarchiver unarchiveObjectWithData:storageData];
        }
    }
}

+ (NSData *)dataFromSecurityArea:(NSString *)argSecurityArea withIdetifier:(NSString *)argIdentifier {
    NSData *encodedData;
    NSString *cacheKey = [NSString stringWithFormat:@"com.duowan.security.%@", argIdentifier];
    if ([argSecurityArea isEqualToString:kTMOSecurityAreaDocument]) {
        encodedData = [[TMOLevelDBQueue databaseWithPath:documentPath()] valueForKey:cacheKey];
    }
    else if ([argSecurityArea isEqualToString:kTMOSecurityAreaCache]) {
        encodedData = [[TMOLevelDBQueue databaseWithPath:cachePath()] valueForKey:cacheKey];
    }
    NSData *decodedData = [encodedData dataByAESDecode];
    return decodedData;
}

@end

@implementation NSObject (TMOSecurity)

- (void)saveToSecurityKeychainWithIdentifier:(NSString *)argIdentifier {
    if ([self isKindOfClass:[NSString class]]) {
        [SSKeychain setPassword:(NSString *)self forService:@"TMOSecurityArea" account:argIdentifier];
    }
    else {
        NSAssert(false, @"只支持NSString保存到KeyChain");
    }
}

- (void)saveToSecurityDocumentWithIdentifier:(NSString *)argIdentifier {
    NSString *cacheKey = [NSString stringWithFormat:@"com.duowan.security.%@", argIdentifier];
    NSData *encodedData = [self saveToSecurityData];
    [[TMOLevelDBQueue databaseWithPath:documentPath()] setObject:encodedData forKey:cacheKey];
}

- (void)saveToSecurityCacheWithIdentifier:(NSString *)argIdentifier {
    NSString *cacheKey = [NSString stringWithFormat:@"com.duowan.security.%@", argIdentifier];
    NSData *encodedData = [self saveToSecurityData];
    [[TMOLevelDBQueue databaseWithPath:cachePath()] setObject:encodedData forKey:cacheKey];
}

- (NSData *)saveToSecurityData {
    NSData *theData;
    if ([self isKindOfClass:[NSString class]] ||
        [self isKindOfClass:[UIImage class]] ||
        [self isKindOfClass:[NSDictionary class]] ||
        [self isKindOfClass:[NSArray class]] ||
        [self isKindOfClass:[NSNumber class]]) {
        NSData *preData = [NSKeyedArchiver archivedDataWithRootObject:self];
        theData = [preData dataByAESEncode];
        return theData;
    }
    else if ([self isKindOfClass:[NSData class]]) {
        theData = [(NSData *)self dataByAESEncode];
        return theData;
    }
    else {
        NSAssert(false, @"传入了不受支持的加密数据类型");
        return nil;
    }
}

@end

@implementation NSData (TMOSecurity)

- (NSData *)dataByAESEncode {
    return [self dataByAESEncodeWithService:@"defaultService"];
}

- (NSData *)dataByAESEncodeWithService:(NSString *)argService {
    return [self dataByAESEncodeWithKey:[TMOSecurity secretKeyForService:argService]];
}

- (NSData *)dataByAESEncodeWithKey:(NSString *)argKey {
    return [RNEncryptor encryptData:self withSettings:kRNCryptorAES256Settings password:argKey error:nil];
}

- (NSData *)dataByAESDecode {
    return [self dataByAESDecodeWithService:@"defaultService"];
}

- (NSData *)dataByAESDecodeWithService:(NSString *)argService {
    return [self dataByAESDecodeWithKey:[TMOSecurity secretKeyForService:argService]];
}

- (NSData *)dataByAESDecodeWithKey:(NSString *)argKey {
    return [RNDecryptor decryptData:self withPassword:argKey error:nil];
}

@end


text:
module MetaCL
  module Templates
    class PrintMatrix < Mustache
      attr_reader :size_n, :size_m, :matrix_name

      def render(matrix_name, size_n, size_m, platform)
        @size_n, @size_m, @matrix_name = size_n, size_m, matrix_name

        super IO.read("#{__dir__}/print_matrix.any.template")
      end
    end
  end
end


text:
package org.hibersap.interceptor.impl;

import javax.validation.ConstraintViolationException;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotNull;
import org.hibersap.validation.BeanValidationInterceptor;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class BeanValidationInterceptorTest {

    @Test
    public void throwsConstraintViolationExceptionWhoseMessageContainsNameOfNonValidatingClass() {
        final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        final BeanValidationInterceptor interceptor = new BeanValidationInterceptor(validatorFactory);

        assertThatThrownBy(() -> interceptor.beforeExecution(new TestObject()))
                .isInstanceOf(ConstraintViolationException.class)
                .hasMessageContaining("org.hibersap.interceptor.impl.BeanValidationInterceptorTest$InnerObject");
    }

    @SuppressWarnings("unused")
    private static class TestObject {

        @Valid
        InnerObject innerObject = new InnerObject();
    }

    @SuppressWarnings("unused")
    private static class InnerObject {

        @NotNull
        String str = null;
    }
}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit3edcec56c18f31df19f56faa5da1d5aa::getLoader();


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>IOSS: src/Ioss_TerminalColor.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

IOSS
    2.0

Classes |
Namespaces |
Enumerations |
Functions |
Variables

Ioss_TerminalColor.h File Reference

#include <cstdint>

#include <limits>

#include <ostream>

#include <sstream>

#include <string>

Go to the source code of this file.

Classes

struct  	Ioss::trmclr::Style

struct  	Ioss::trmclr::Attribute

struct  	Ioss::trmclr::Foreground

struct  	Ioss::trmclr::Background

Namespaces

  	Ioss

 	The main namespace for the Ioss library.

  	Ioss::trmclr

Enumerations

enum  	Ioss::trmclr::StyleTypes { Ioss::trmclr::FOREGROUND,
Ioss::trmclr::ATTRIBUTE,
Ioss::trmclr::BACKGROUND,
Ioss::trmclr::N_STYLE_TYPES
 }

Functions

static Style 	Ioss::trmclr::black (Ioss::trmclr::Foreground::BLACK)

static Style 	Ioss::trmclr::red (Ioss::trmclr::Foreground::RED)

static Style 	Ioss::trmclr::green (Ioss::trmclr::Foreground::GREEN)

static Style 	Ioss::trmclr::yellow (Ioss::trmclr::Foreground::YELLOW)

static Style 	Ioss::trmclr::blue (Ioss::trmclr::Foreground::BLUE)

static Style 	Ioss::trmclr::magenta (Ioss::trmclr::Foreground::MAGENTA)

static Style 	Ioss::trmclr::cyan (Ioss::trmclr::Foreground::CYAN)

static Style 	Ioss::trmclr::normal (Ioss::trmclr::Attribute::DEFAULT)

std::ostream & 	Ioss::trmclr::operator<< (std::ostream &os, const Style &style)

Variables

static const uint32_t 	Ioss::trmclr::STYLE_SHIFT = std::numeric_limits<uint32_t>::digits / N_STYLE_TYPES

src

Ioss_TerminalColor.h

Generated by

     1.8.13


text:
/* ========================================================================
   Its Only a Example, next build your script https://github.com/Harazaki/PHP-BOOTSTRAP
 * ======================================================================== */

 // Default Modal template

function modal_tmp(modal_title,modal_body,modal_footer){
var tmpl_modal = '

<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>
'+( modal_title ? modal_title : 'My Modal' )+'

 '+( modal_body ? modal_body : 'Modal Body  Here :)' )+'

 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> '+( modal_footer ? modal_footer : '' )+'

';
return tmpl_modal;
}

 //select.autosubmit

$(document).ready(function () {

	$(document).on('change', 'form select.autosubmit', function () {
		this.form.submit();
	});

});