text:
namespace {

using std::string;

// REFERENCE IMPLEMENTATIONS

// Get the largest power of two smaller than i.
int DownToPowerOfTwo(int i) {
  CHECK_GE(i, 2);
  // Find the smallest power of two greater than or equal to i.
  int split = 1;
  do {
    split <<= 1;
  } while (split < i);

  // Get the largest power of two smaller than i.
  return split >> 1;
}

// Reference implementation of Merkle hash, for cross-checking.
string ReferenceMerkleTreeHash(string inputs[], int input_size,
                               TreeHasher* treehasher) {
  if (!input_size)
    return treehasher->HashEmpty();
  if (input_size == 1)
    return treehasher->HashLeaf(inputs[0]);

  const int split = DownToPowerOfTwo(input_size);

  return treehasher->HashChildren(
      ReferenceMerkleTreeHash(&inputs[0], split, treehasher),
      ReferenceMerkleTreeHash(&inputs[split], input_size - split, treehasher));
}

// Reference implementation of Merkle paths. Path from leaf to root,
// excluding the leaf and root themselves.
std::vector<string> ReferenceMerklePath(string inputs[], int input_size,
                                        int leaf, TreeHasher* treehasher) {
  std::vector<string> path;
  if (leaf > input_size || leaf == 0)
    return path;

  if (input_size == 1)
    return path;

  const int split = DownToPowerOfTwo(input_size);

  std::vector<string> subpath;
  if (leaf <= split) {
    subpath = ReferenceMerklePath(&inputs[0], split, leaf, treehasher);
    path.insert(path.end(), subpath.begin(), subpath.end());
    path.push_back(ReferenceMerkleTreeHash(&inputs[split], input_size - split,
                                           treehasher));
  } else {
    subpath = ReferenceMerklePath(&inputs[split], input_size - split,
                                  leaf - split, treehasher);
    path.insert(path.end(), subpath.begin(), subpath.end());
    path.push_back(ReferenceMerkleTreeHash(&inputs[0], split, treehasher));
  }

  return path;
}

// Reference implementation of snapshot consistency.
// Call with have_root1 = true.
std::vector<string> ReferenceSnapshotConsistency(string inputs[],
                                                 int snapshot2, int snapshot1,
                                                 TreeHasher* treehasher,
                                                 bool have_root1) {
  std::vector<string> proof;
  if (snapshot1 == 0 || snapshot1 > snapshot2)
    return proof;
  if (snapshot1 == snapshot2) {
    // Consistency proof for two equal subtrees is empty.
    if (!have_root1)
      // Record the hash of this subtree unless it's the root for which
      // the proof was originally requested. (This happens when the snapshot1
      // tree is balanced.)
      proof.push_back(ReferenceMerkleTreeHash(inputs, snapshot1, treehasher));
    return proof;
  }

  // 0 < snapshot1 < snapshot2
  const int split = DownToPowerOfTwo(snapshot2);

  std::vector<string> subproof;
  if (snapshot1 <= split) {
    // Root of snapshot1 is in the left subtree of snapshot2.
    // Prove that the left subtrees are consistent.
    subproof = ReferenceSnapshotConsistency(inputs, split, snapshot1,
                                            treehasher, have_root1);
    proof.insert(proof.end(), subproof.begin(), subproof.end());
    // Record the hash of the right subtree (only present in snapshot2).
    proof.push_back(ReferenceMerkleTreeHash(&inputs[split], snapshot2 - split,
                                            treehasher));
  } else {
    // Snapshot1 root is at the same level as snapshot2 root.
    // Prove that the right subtrees are consistent. The right subtree
    // doesn't contain the root of snapshot1, so set have_root1 = false.
    subproof =
        ReferenceSnapshotConsistency(&inputs[split], snapshot2 - split,
                                     snapshot1 - split, treehasher, false);
    proof.insert(proof.end(), subproof.begin(), subproof.end());
    // Record the hash of the left subtree (equal in both trees).
    proof.push_back(ReferenceMerkleTreeHash(&inputs[0], split, treehasher));
  }
  return proof;
}

class MerkleTreeTest : public ::testing::Test {
 protected:
  TreeHasher tree_hasher_;
  std::vector<string> data_;
  MerkleTreeTest() : tree_hasher_(new Sha256Hasher()) {
    for (int i = 0; i < 256; ++i)
      data_.push_back(string(1, i));
  }
};

class MerkleTreeFuzzTest : public MerkleTreeTest {
 protected:
  MerkleTreeFuzzTest() : MerkleTreeTest() {
  }
  void SetUp() {
    srand(time(NULL));
  }
};

class CompactMerkleTreeTest : public MerkleTreeTest {};

class CompactMerkleTreeFuzzTest : public MerkleTreeFuzzTest {
 protected:
  string RandomLeaf(size_t len) {
    string r;
    for (size_t i = 0; i < len; ++i) {
      r += uint8_t(rand() % 0xff);
    }
    return r;
  }
};

// FUZZ TESTS AGAINST REFERENCE IMPLEMENTATIONS

// Make random root queries and check against the reference hash.
TEST_F(MerkleTreeFuzzTest, RootFuzz) {
  for (size_t tree_size = 1; tree_size <= data_.size(); ++tree_size) {
    MerkleTree tree(new Sha256Hasher());
    for (size_t j = 0; j < tree_size; ++j)
      tree.AddLeaf(data_[j]);
    // Since the tree is evaluated lazily, the order of queries is significant.
    // Generate a random sequence of 8 queries for each tree.
    for (size_t j = 0; j < 8; ++j) {
      // A snapshot in the range 0...tree_size.
      const size_t snapshot = rand() % (tree_size + 1);
      EXPECT_EQ(tree.RootAtSnapshot(snapshot),
                ReferenceMerkleTreeHash(data_.data(), snapshot,
                                        &tree_hasher_));
    }
  }
}

TEST_F(CompactMerkleTreeTest, RootFuzz) {
  for (size_t tree_size = 1; tree_size <= data_.size(); ++tree_size) {
    CompactMerkleTree tree(new Sha256Hasher());
    for (size_t j = 0; j < tree_size; ++j) {
      tree.AddLeaf(data_[j]);
      // Since the tree is evaluated lazily, the tree state is significant
      // when querying the root hash. Flip a coin and decide whether to
      // query now or later.
      if (rand() & 1) {
        EXPECT_EQ(tree.CurrentRoot(),
                  ReferenceMerkleTreeHash(data_.data(), j + 1, &tree_hasher_));
      }
    }
  }
}

// Make random path queries and check against the reference implementation.
TEST_F(MerkleTreeFuzzTest, PathFuzz) {
  for (size_t tree_size = 1; tree_size <= data_.size(); ++tree_size) {
    MerkleTree tree(new Sha256Hasher());
    for (size_t j = 0; j < tree_size; ++j)
      tree.AddLeaf(data_[j]);

    // Since the tree is evaluated lazily, the order of queries is significant.
    // Generate a random sequence of 8 queries for each tree.
    for (size_t j = 0; j < 8; ++j) {
      // A snapshot in the range 0... length.
      const size_t snapshot = rand() % (tree_size + 1);
      // A leaf in the range 0... snapshot.
      const size_t leaf = rand() % (snapshot + 1);
      EXPECT_EQ(tree.PathToRootAtSnapshot(leaf, snapshot),
                ReferenceMerklePath(data_.data(), snapshot, leaf,
                                    &tree_hasher_));
    }
  }
}

// Make random proof queries and check against the reference implementation.
TEST_F(MerkleTreeFuzzTest, ConsistencyFuzz) {
  for (size_t tree_size = 1; tree_size <= data_.size(); ++tree_size) {
    MerkleTree tree(new Sha256Hasher());
    for (size_t j = 0; j < tree_size; ++j)
      tree.AddLeaf(data_[j]);

    // Since the tree is evaluated lazily, the order of queries is significant.
    // Generate a random sequence of 8 queries for each tree.
    for (size_t j = 0; j < 8; ++j) {
      // A snapshot in the range 0... length.
      const size_t snapshot2 = rand() % (tree_size + 1);
      // A snapshot in the range 0... snapshot.
      const size_t snapshot1 = rand() % (snapshot2 + 1);
      EXPECT_EQ(tree.SnapshotConsistency(snapshot1, snapshot2),
                ReferenceSnapshotConsistency(data_.data(), snapshot2,
                                             snapshot1, &tree_hasher_, true));
    }
  }
}

// KNOWN ANSWER TESTS

typedef struct {
  const char* str;
  int length_bytes;
} TestVector;

// A slightly shorter notation for constructing binary blobs from test vectors.
#define S(t) util::BinaryString(string(t.str, 2 * t.length_bytes))
// The reverse
#define H(t) util::HexString(t)

// The hash of an empty tree is the hash of the empty string.
// (see SerialHasherTest and http://csrc.nist.gov/groups/STM/cavp/)
const TestVector kSHA256EmptyTreeHash = {
    "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", 32};

// Inputs to the reference tree, which has eight leaves.
const TestVector kInputs[8] = {
    {"", 0},
    {"00", 1},
    {"10", 1},
    {"2021", 2},
    {"3031", 2},
    {"40414243", 4},
    {"5051525354555657", 8},
    {"606162636465666768696a6b6c6d6e6f", 16},
};

// Level counts for number of leaves in [1, 8]
const size_t kLevelCounts[8] = {1, 2, 3, 3, 4, 4, 4, 4};

// Incremental roots from building the reference tree from inputs leaf-by-leaf.
// Generated from ReferenceMerkleTreeHash.
const TestVector kSHA256Roots[8] = {
    {"6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d", 32},
    {"fac54203e7cc696cf0dfcb42c92a1d9dbaf70ad9e621f4bd8d98662f00e3c125", 32},
    {"aeb6bcfe274b70a14fb067a5e5578264db0fa9b51af5e0ba159158f329e06e77", 32},
    {"d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7", 32},
    {"4e3bbb1f7b478dcfe71fb631631519a3bca12c9aefca1612bfce4c13a86264d4", 32},
    {"76e67dadbcdf1e10e1b74ddc608abd2f98dfb16fbce75277b5232a127f2087ef", 32},
    {"ddb89be403809e325750d3d263cd78929c2942b7942a34b77e122c9594a74c8c", 32},
    {"5dc9da79a70659a9ad559cb701ded9a2ab9d823aad2f4960cfe370eff4604328", 32}};

TEST_F(MerkleTreeTest, RootTestVectors) {
  // The first tree: add nodes one by one.
  MerkleTree tree1(new Sha256Hasher());
  EXPECT_EQ(tree1.LeafCount(), 0U);
  EXPECT_EQ(tree1.LevelCount(), 0U);
  EXPECT_STREQ(H(tree1.CurrentRoot()).c_str(), kSHA256EmptyTreeHash.str);
  for (size_t i = 0; i < 8; ++i) {
    tree1.AddLeaf(S(kInputs[i]));
    EXPECT_EQ(tree1.LeafCount(), i + 1);
    EXPECT_EQ(tree1.LevelCount(), kLevelCounts[i]);
    EXPECT_STREQ(H(tree1.CurrentRoot()).c_str(), kSHA256Roots[i].str);
    EXPECT_STREQ(H(tree1.RootAtSnapshot(0)).c_str(), kSHA256EmptyTreeHash.str);
    for (size_t j = 0; j <= i; ++j) {
      EXPECT_STREQ(H(tree1.RootAtSnapshot(j + 1)).c_str(),
                   kSHA256Roots[j].str);
    }

    for (size_t j = i + 1; j < 8; ++j) {
      EXPECT_EQ(tree1.RootAtSnapshot(j + 1), string());
    }
  }

  // The second tree: add all nodes at once.
  MerkleTree tree2(new Sha256Hasher());
  for (int i = 0; i < 8; ++i) {
    tree2.AddLeaf(S(kInputs[i]));
  }
  EXPECT_EQ(tree2.LeafCount(), 8U);
  EXPECT_EQ(tree2.LevelCount(), kLevelCounts[7]);
  EXPECT_STREQ(H(tree2.CurrentRoot()).c_str(), kSHA256Roots[7].str);

  // The third tree: add nodes in two chunks.
  MerkleTree tree3(new Sha256Hasher());
  // Add three nodes.
  for (int i = 0; i < 3; ++i) {
    tree3.AddLeaf(S(kInputs[i]));
  }
  EXPECT_EQ(tree3.LeafCount(), 3U);
  EXPECT_EQ(tree3.LevelCount(), kLevelCounts[2]);
  EXPECT_STREQ(H(tree3.CurrentRoot()).c_str(), kSHA256Roots[2].str);
  // Add the remaining nodes.
  for (int i = 3; i < 8; ++i) {
    tree3.AddLeaf(S(kInputs[i]));
  }
  EXPECT_EQ(tree3.LeafCount(), 8U);
  EXPECT_EQ(tree3.LevelCount(), kLevelCounts[7]);
  EXPECT_STREQ(H(tree3.CurrentRoot()).c_str(), kSHA256Roots[7].str);
}

TEST_F(CompactMerkleTreeTest, RootTestVectors) {
  // The first tree: add nodes one by one.
  CompactMerkleTree tree1(new Sha256Hasher());
  EXPECT_EQ(tree1.LeafCount(), 0U);
  EXPECT_EQ(tree1.LevelCount(), 0U);
  EXPECT_STREQ(H(tree1.CurrentRoot()).c_str(), kSHA256EmptyTreeHash.str);
  for (size_t i = 0; i < 8; ++i) {
    tree1.AddLeaf(S(kInputs[i]));
    EXPECT_EQ(tree1.LeafCount(), i + 1);
    EXPECT_EQ(tree1.LevelCount(), kLevelCounts[i]);
    EXPECT_STREQ(H(tree1.CurrentRoot()).c_str(), kSHA256Roots[i].str);
  }

  // The second tree: add all nodes at once.
  CompactMerkleTree tree2(new Sha256Hasher());
  for (int i = 0; i < 8; ++i) {
    tree2.AddLeaf(S(kInputs[i]));
  }
  EXPECT_EQ(tree2.LeafCount(), 8U);
  EXPECT_EQ(tree2.LevelCount(), kLevelCounts[7]);
  EXPECT_STREQ(H(tree2.CurrentRoot()).c_str(), kSHA256Roots[7].str);

  // The third tree: add nodes in two chunks.
  CompactMerkleTree tree3(new Sha256Hasher());
  // Add three nodes.
  for (int i = 0; i < 3; ++i) {
    tree3.AddLeaf(S(kInputs[i]));
  }
  EXPECT_EQ(tree3.LeafCount(), 3U);
  EXPECT_EQ(tree3.LevelCount(), kLevelCounts[2]);
  EXPECT_STREQ(H(tree3.CurrentRoot()).c_str(), kSHA256Roots[2].str);
  // Add the remaining nodes.
  for (int i = 3; i < 8; ++i) {
    tree3.AddLeaf(S(kInputs[i]));
  }
  EXPECT_EQ(tree3.LeafCount(), 8U);
  EXPECT_EQ(tree3.LevelCount(), kLevelCounts[7]);
  EXPECT_STREQ(H(tree3.CurrentRoot()).c_str(), kSHA256Roots[7].str);
}

TEST_F(CompactMerkleTreeTest, TestCopyCtorWithRootTestVectors) {
  MerkleTree tree1(new Sha256Hasher());
  CompactMerkleTree refctree1(new Sha256Hasher());
  EXPECT_EQ(tree1.LeafCount(), 0U);
  EXPECT_EQ(tree1.LevelCount(), 0U);
  EXPECT_STREQ(H(tree1.CurrentRoot()).c_str(), kSHA256EmptyTreeHash.str);
  for (size_t i = 0; i < 8; ++i) {
    tree1.AddLeaf(S(kInputs[i]));
    refctree1.AddLeaf(S(kInputs[i]));
  }
  EXPECT_EQ(tree1.LeafCount(), 8U);
  EXPECT_EQ(tree1.LevelCount(), kLevelCounts[7]);
  EXPECT_STREQ(H(tree1.CurrentRoot()).c_str(), kSHA256Roots[7].str);

  CompactMerkleTree ctree1(tree1, new Sha256Hasher());
  EXPECT_EQ(tree1.LeafCount(), ctree1.LeafCount());
  EXPECT_EQ(tree1.LevelCount(), ctree1.LevelCount());
  EXPECT_EQ(tree1.CurrentRoot(), ctree1.CurrentRoot());
}

TEST_F(CompactMerkleTreeTest, TestCopyCtorThenAddLeafWithRootTestVectors) {
  MerkleTree tree(new Sha256Hasher());
  EXPECT_EQ(tree.LeafCount(), 0U);
  EXPECT_EQ(tree.LevelCount(), 0U);
  EXPECT_STREQ(H(tree.CurrentRoot()).c_str(), kSHA256EmptyTreeHash.str);
  for (size_t i = 0; i < 5; ++i) {
    tree.AddLeaf(S(kInputs[i]));
  }
  EXPECT_EQ(tree.LeafCount(), 5U);
  EXPECT_EQ(tree.LevelCount(), kLevelCounts[4]);
  EXPECT_STREQ(H(tree.CurrentRoot()).c_str(), kSHA256Roots[4].str);
  CompactMerkleTree ctree(tree, new Sha256Hasher());
  EXPECT_EQ(tree.LeafCount(), ctree.LeafCount());
  EXPECT_EQ(tree.LevelCount(), ctree.LevelCount());
  EXPECT_EQ(tree.CurrentRoot(), ctree.CurrentRoot());

  // Add the remaining nodes.
  for (int i = 5; i < 6; ++i) {
    tree.AddLeaf(S(kInputs[i]));
    ctree.AddLeaf(S(kInputs[i]));
  }
  EXPECT_EQ(tree.LeafCount(), 6U);
  EXPECT_EQ(tree.LevelCount(), kLevelCounts[5]);
  EXPECT_STREQ(H(tree.CurrentRoot()).c_str(), kSHA256Roots[5].str);
  EXPECT_EQ(tree.LeafCount(), ctree.LeafCount());
  EXPECT_EQ(tree.LevelCount(), ctree.LevelCount());
  EXPECT_EQ(tree.CurrentRoot(), ctree.CurrentRoot());
}

TEST_F(CompactMerkleTreeFuzzTest, CopyCtorForLargerTreesThenAppend) {
  for (size_t tree_size = 1; tree_size <= 512; ++tree_size) {
    // Build a tree of |tree_size| from random leaves
    MerkleTree tree(new Sha256Hasher());
    for (size_t i = 0; i < tree_size; ++i) {
      const string l(RandomLeaf(256));
      tree.AddLeaf(l);
    }
    EXPECT_EQ(tree.LeafCount(), tree_size);
    // Now build a CompactMerkleTree using |tree| as the model
    CompactMerkleTree ctree(tree, new Sha256Hasher());
    // And check that the public interface concurs
    EXPECT_EQ(tree.LeafCount(), ctree.LeafCount());
    EXPECT_EQ(tree.LevelCount(), ctree.LevelCount());
    EXPECT_EQ(tree.CurrentRoot(), ctree.CurrentRoot());
    // Now add a bunch more nodes and check that the compact tree
    // doesn't diverge from the reference tree:
    for (size_t i = 0; i < 256; ++i) {
      const string l(RandomLeaf(256));
      tree.AddLeaf(l);
      ctree.AddLeaf(l);
      EXPECT_EQ(tree.LeafCount(), ctree.LeafCount());
      EXPECT_EQ(tree.LevelCount(), ctree.LevelCount());
      EXPECT_EQ(tree.CurrentRoot(), ctree.CurrentRoot());
    }
  }
}

// Some paths for the reference tree.
typedef struct {
  int leaf;
  int snapshot;
  int path_length;
  TestVector path[3];
} PathTestVector;

// Generated from ReferenceMerklePath.
const PathTestVector kSHA256Paths[6] = {
    {0, 0, 0, {{"", 0}, {"", 0}, {"", 0}}},
    {1, 1, 0, {{"", 0}, {"", 0}, {"", 0}}},
    {1,
     8,
     3,
     {{"96a296d224f285c67bee93c30f8a309157f0daa35dc5b87e410b78630a09cfc7", 32},
      {"5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e", 32},
      {"6b47aaf29ee3c2af9af889bc1fb9254dabd31177f16232dd6aab035ca39bf6e4",
       32}}},
    {6,
     8,
     3,
     {{"bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b", 32},
      {"ca854ea128ed050b41b35ffc1b87b8eb2bde461e9e3b5596ece6b9d5975a0ae0", 32},
      {"d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7",
       32}}},
    {3,
     3,
     1,
     {{"fac54203e7cc696cf0dfcb42c92a1d9dbaf70ad9e621f4bd8d98662f00e3c125", 32},
      {"", 0},
      {"", 0}}},
    {2,
     5,
     3,
     {{"6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d", 32},
      {"5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e", 32},
      {"bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b",
       32}}}};

TEST_F(MerkleTreeTest, PathTestVectors) {
  // First tree: build in one go.
  MerkleTree tree1(new Sha256Hasher());
  for (int i = 0; i < 8; ++i) {
    tree1.AddLeaf(S(kInputs[i]));
  }
  EXPECT_EQ(tree1.LeafCount(), 8U);
  EXPECT_STREQ(H(tree1.CurrentRoot()).c_str(), kSHA256Roots[7].str);

  EXPECT_TRUE(tree1.PathToCurrentRoot(9).empty());
  for (int i = 0; i < 6; ++i) {
    std::vector<string> path =
        tree1.PathToRootAtSnapshot(kSHA256Paths[i].leaf,
                                   kSHA256Paths[i].snapshot);
    std::vector<string> kat_path;
    for (int j = 0; j < kSHA256Paths[i].path_length; ++j)
      kat_path.push_back(S(kSHA256Paths[i].path[j]));
    EXPECT_EQ(path, kat_path);
  }

  // Second tree: build incrementally.
  MerkleTree tree2(new Sha256Hasher());
  EXPECT_EQ(tree2.PathToCurrentRoot(0), tree1.PathToRootAtSnapshot(0, 0));
  EXPECT_TRUE(tree2.PathToCurrentRoot(1).empty());
  for (int i = 0; i < 8; ++i) {
    tree2.AddLeaf(S(kInputs[i]));
    for (int j = 0; j <= i + 1; ++j) {
      EXPECT_EQ(tree1.PathToRootAtSnapshot(j, i + 1),
                tree2.PathToCurrentRoot(j));
    }
    for (int j = i + 2; j <= 9; ++j)
      EXPECT_TRUE(tree1.PathToRootAtSnapshot(j, i + 1).empty());
  }
}

typedef struct {
  int snapshot1;
  int snapshot2;
  int proof_length;
  TestVector proof[3];
} ProofTestVector;

// Generated from ReferenceSnapshotConsistency.
const ProofTestVector kSHA256Proofs[4] = {
    {1, 1, 0, {{"", 0}, {"", 0}, {"", 0}}},
    {1,
     8,
     3,
     {{"96a296d224f285c67bee93c30f8a309157f0daa35dc5b87e410b78630a09cfc7", 32},
      {"5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e", 32},
      {"6b47aaf29ee3c2af9af889bc1fb9254dabd31177f16232dd6aab035ca39bf6e4",
       32}}},
    {6,
     8,
     3,
     {{"0ebc5d3437fbe2db158b9f126a1d118e308181031d0a949f8dededebc558ef6a", 32},
      {"ca854ea128ed050b41b35ffc1b87b8eb2bde461e9e3b5596ece6b9d5975a0ae0", 32},
      {"d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7",
       32}}},
    {2,
     5,
     2,
     {{"5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e", 32},
      {"bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b", 32},
      {"", 0}}}};

TEST_F(MerkleTreeTest, ConsistencyTestVectors) {
  MerkleTree tree1(new Sha256Hasher());
  for (int i = 0; i < 8; ++i) {
    tree1.AddLeaf(S(kInputs[i]));
  }
  EXPECT_EQ(tree1.LeafCount(), 8U);
  EXPECT_STREQ(H(tree1.CurrentRoot()).c_str(), kSHA256Roots[7].str);

  for (int i = 0; i < 4; ++i) {
    std::vector<string> proof =
        tree1.SnapshotConsistency(kSHA256Proofs[i].snapshot1,
                                  kSHA256Proofs[i].snapshot2);
    std::vector<string> kat_proof;
    for (int j = 0; j < kSHA256Proofs[i].proof_length; ++j)
      kat_proof.push_back(S(kSHA256Proofs[i].proof[j]));
    EXPECT_EQ(proof, kat_proof);
  }
}

TEST_F(MerkleTreeTest, AddLeafHash) {
  const char* kHashValue = "0123456789abcdef0123456789abcdef";
  MerkleTree tree(new Sha256Hasher());
  size_t index = tree.AddLeafHash(kHashValue);
  EXPECT_EQ(1U, index);
  EXPECT_EQ(kHashValue, tree.LeafHash(index));
}

TEST_F(CompactMerkleTreeTest, TestCloneEmptyTreeProducesWorkingTree) {
  MerkleTree tree(new Sha256Hasher);
  CompactMerkleTree compact(tree, new Sha256Hasher);
  EXPECT_STREQ(H(compact.CurrentRoot()).c_str(), kSHA256EmptyTreeHash.str);
}

// VERIFICATION TESTS

class MerkleVerifierTest : public MerkleTreeTest {
 protected:
  MerkleVerifier verifier_;
  MerkleVerifierTest() : MerkleTreeTest(), verifier_(new Sha256Hasher()) {
  }

  void VerifierCheck(int leaf, int tree_size, const std::vector<string>& path,
                     const string& root, const string& data) {
    // Verify the original path.
    EXPECT_EQ(H(verifier_.RootFromPath(leaf, tree_size, path, data)), H(root));
    EXPECT_TRUE(verifier_.VerifyPath(leaf, tree_size, path, root, data));

    // Wrong leaf index.
    EXPECT_FALSE(verifier_.VerifyPath(leaf - 1, tree_size, path, root, data));
    EXPECT_FALSE(verifier_.VerifyPath(leaf + 1, tree_size, path, root, data));
    EXPECT_FALSE(verifier_.VerifyPath(leaf ^ 2, tree_size, path, root, data));

    // Wrong tree height.
    EXPECT_FALSE(verifier_.VerifyPath(leaf, tree_size * 2, path, root, data));
    EXPECT_FALSE(verifier_.VerifyPath(leaf, tree_size / 2, path, root, data));

    // Wrong leaf.
    const char wrong_leaf[] = "WrongLeaf";
    EXPECT_FALSE(verifier_.VerifyPath(leaf, tree_size, path, root,
                                      string(wrong_leaf, 9)));

    // Wrong root.
    EXPECT_FALSE(verifier_.VerifyPath(leaf, tree_size, path,
                                      S(kSHA256EmptyTreeHash), data));

    // Wrong paths.
    std::vector<string> wrong_path;

    // Modify a single element on the path.
    for (size_t j = 0; j < path.size(); ++j) {
      wrong_path = path;
      wrong_path[j] = S(kSHA256EmptyTreeHash);
      EXPECT_FALSE(
          verifier_.VerifyPath(leaf, tree_size, wrong_path, root, data));
    }

    // Add garbage at the end of the path.
    wrong_path = path;
    wrong_path.push_back(string());
    EXPECT_FALSE(
        verifier_.VerifyPath(leaf, tree_size, wrong_path, root, data));
    wrong_path.pop_back();

    wrong_path.push_back(root);
    EXPECT_FALSE(
        verifier_.VerifyPath(leaf, tree_size, wrong_path, root, data));
    wrong_path.pop_back();

    // Remove a node from the end.
    if (!wrong_path.empty()) {
      wrong_path.pop_back();
      EXPECT_FALSE(
          verifier_.VerifyPath(leaf, tree_size, wrong_path, root, data));
    }

    // Add garbage in the beginning of the path.
    wrong_path.clear();
    wrong_path.push_back(string());
    wrong_path.insert(wrong_path.end(), path.begin(), path.end());
    EXPECT_FALSE(
        verifier_.VerifyPath(leaf, tree_size, wrong_path, root, data));

    wrong_path[0] = root;
    EXPECT_FALSE(
        verifier_.VerifyPath(leaf, tree_size, wrong_path, root, data));
  }

  void VerifierConsistencyCheck(int snapshot1, int snapshot2,
                                const string& root1, const string& root2,
                                const std::vector<string>& proof) {
    // Verify the original consistency proof.
    EXPECT_TRUE(verifier_.VerifyConsistency(snapshot1, snapshot2, root1, root2,
                                            proof));

    if (proof.empty())
      // For simplicity test only non-trivial proofs that have root1 != root2
      // snapshot1 != 0 and snapshot1 != snapshot2.
      return;

    // Wrong snapshot index.
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1 - 1, snapshot2, root1,
                                             root2, proof));
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1 + 1, snapshot2, root1,
                                             root2, proof));
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1 ^ 2, snapshot2, root1,
                                             root2, proof));

    // Wrong tree height.
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1, snapshot2 * 2, root1,
                                             root2, proof));
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1, snapshot2 / 2, root1,
                                             root2, proof));

    // Wrong root.
    const char wrong_root[] = "WrongRoot";
    const string bwrong_root(wrong_root, 9);
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1, snapshot2, root1,
                                             bwrong_root, proof));
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1, snapshot2, bwrong_root,
                                             root2, proof));
    // Swap roots.
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1, snapshot2, root2,
                                             root1, proof));

    // Wrong proofs.
    std::vector<string> wrong_proof;
    // Empty proof.
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1, snapshot2, root1,
                                             root2, wrong_proof));

    // Modify a single element in the proof.
    for (size_t j = 0; j < proof.size(); ++j) {
      wrong_proof = proof;
      wrong_proof[j] = S(kSHA256EmptyTreeHash);
      EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1, snapshot2, root1,
                                               root2, wrong_proof));
    }

    // Add garbage at the end of the proof.
    wrong_proof = proof;
    wrong_proof.push_back(string());
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1, snapshot2, root1,
                                             root2, wrong_proof));
    wrong_proof.pop_back();

    wrong_proof.push_back(proof.back());
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1, snapshot2, root1,
                                             root2, wrong_proof));
    wrong_proof.pop_back();

    // Remove a node from the end.
    wrong_proof.pop_back();
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1, snapshot2, root1,
                                             root2, wrong_proof));

    // Add garbage in the beginning of the proof.
    wrong_proof.clear();
    wrong_proof.push_back(string());
    wrong_proof.insert(wrong_proof.end(), proof.begin(), proof.end());
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1, snapshot2, root1,
                                             root2, wrong_proof));

    wrong_proof[0] = proof[0];
    EXPECT_FALSE(verifier_.VerifyConsistency(snapshot1, snapshot2, root1,
                                             root2, wrong_proof));
  }
};

TEST_F(MerkleVerifierTest, VerifyPath) {
  std::vector<string> path;
  // Various invalid paths.
  EXPECT_FALSE(verifier_.VerifyPath(0, 0, path, string(), string()));
  EXPECT_FALSE(verifier_.VerifyPath(0, 1, path, string(), string()));
  EXPECT_FALSE(verifier_.VerifyPath(1, 0, path, string(), string()));
  EXPECT_FALSE(verifier_.VerifyPath(2, 1, path, string(), string()));

  EXPECT_FALSE(
      verifier_.VerifyPath(0, 0, path, S(kSHA256EmptyTreeHash), string()));
  EXPECT_FALSE(
      verifier_.VerifyPath(0, 1, path, S(kSHA256EmptyTreeHash), string()));
  EXPECT_FALSE(
      verifier_.VerifyPath(1, 0, path, S(kSHA256EmptyTreeHash), string()));
  EXPECT_FALSE(
      verifier_.VerifyPath(2, 1, path, S(kSHA256EmptyTreeHash), string()));

  // Known good paths.
  // i = 0 is an invalid path.
  for (int i = 1; i < 6; ++i) {
    // Construct the path.
    path.clear();
    for (int j = 0; j < kSHA256Paths[i].path_length; ++j)
      path.push_back(S(kSHA256Paths[i].path[j]));
    VerifierCheck(kSHA256Paths[i].leaf, kSHA256Paths[i].snapshot, path,
                  S(kSHA256Roots[kSHA256Paths[i].snapshot - 1]),
                  S(kInputs[kSHA256Paths[i].leaf - 1]));
  }

  // More tests with reference path generator.
  string root;
  for (size_t tree_size = 1; tree_size <= data_.size() / 2; ++tree_size) {
    // Repeat for each leaf in range.
    for (size_t leaf = 1; leaf <= tree_size; ++leaf) {
      path = ReferenceMerklePath(data_.data(), tree_size, leaf, &tree_hasher_);
      root = ReferenceMerkleTreeHash(data_.data(), tree_size, &tree_hasher_);
      VerifierCheck(leaf, tree_size, path, root, data_[leaf - 1]);
    }
  }
}

TEST_F(MerkleVerifierTest, VerifyConsistencyProof) {
  std::vector<string> proof;
  string root1, root2;
  // Snapshots that are always consistent.
  EXPECT_TRUE(verifier_.VerifyConsistency(0, 0, root1, root2, proof));
  EXPECT_TRUE(verifier_.VerifyConsistency(0, 1, root1, root2, proof));
  EXPECT_TRUE(verifier_.VerifyConsistency(1, 1, root1, root2, proof));

  // Invalid consistency proofs.
  // Time travel to the past.
  EXPECT_FALSE(verifier_.VerifyConsistency(1, 0, root1, root2, proof));
  EXPECT_FALSE(verifier_.VerifyConsistency(2, 1, root1, root2, proof));
  // Empty proof.
  EXPECT_FALSE(verifier_.VerifyConsistency(1, 2, root1, root2, proof));

  root1 = S(kSHA256EmptyTreeHash);
  // Roots don't match.
  EXPECT_FALSE(verifier_.VerifyConsistency(0, 0, root1, root2, proof));
  EXPECT_FALSE(verifier_.VerifyConsistency(1, 1, root1, root2, proof));
  // Roots match but the proof is not empty.
  root2 = S(kSHA256EmptyTreeHash);
  proof.push_back(S(kSHA256EmptyTreeHash));
  EXPECT_FALSE(verifier_.VerifyConsistency(0, 0, root1, root2, proof));
  EXPECT_FALSE(verifier_.VerifyConsistency(0, 1, root1, root2, proof));
  EXPECT_FALSE(verifier_.VerifyConsistency(1, 1, root1, root2, proof));

  // Known good proofs.
  for (int i = 0; i < 4; ++i) {
    proof.clear();
    for (int j = 0; j < kSHA256Proofs[i].proof_length; ++j)
      proof.push_back(S(kSHA256Proofs[i].proof[j]));
    const int snapshot1 = kSHA256Proofs[i].snapshot1;
    const int snapshot2 = kSHA256Proofs[i].snapshot2;
    VerifierConsistencyCheck(snapshot1, snapshot2,
                             S(kSHA256Roots[snapshot1 - 1]),
                             S(kSHA256Roots[snapshot2 - 1]), proof);
  }

  // More tests with reference proof generator.
  for (size_t tree_size = 1; tree_size <= data_.size() / 2; ++tree_size) {
    root2 = ReferenceMerkleTreeHash(data_.data(), tree_size, &tree_hasher_);
    // Repeat for each snapshot in range.
    for (size_t snapshot = 1; snapshot <= tree_size; ++snapshot) {
      proof = ReferenceSnapshotConsistency(data_.data(), tree_size, snapshot,
                                           &tree_hasher_, true);
      root1 = ReferenceMerkleTreeHash(data_.data(), snapshot, &tree_hasher_);
      VerifierConsistencyCheck(snapshot, tree_size, root1, root2, proof);
    }
  }
}

#undef S
#undef H

}  // namespace

int main(int argc, char** argv) {
  cert_trans::test::InitTesting(argv[0], &argc, &argv, true);
  return RUN_ALL_TESTS();
}


text:
package com.gs.fw.common.freyaxml.generator;

import java.util.concurrent.atomic.AtomicInteger;

public class AwaitingThreadExecutor
{

    private AutoShutdownThreadExecutor executor;
    private AtomicInteger todo = new AtomicInteger();

    public AwaitingThreadExecutor(int maxThreads, String name)
    {
        executor = new AutoShutdownThreadExecutor(maxThreads, name);
    }

    public void submit(Runnable task)
    {
        executor.submit(new CountingRunnable(task));
    }

    public void shutdown()
    {
        executor.shutdown();
    }

    public void setExceptionHandler(AutoShutdownThreadExecutor.ExceptionHandler exceptionHandler)
    {
        executor.setExceptionHandler(exceptionHandler);
    }

    public void waitUntilDone()
    {
        synchronized (todo)
        {
            while(todo.get() != 0 && !executor.isAborted())
            {
                try
                {
                    todo.wait(1000);
                }
                catch (InterruptedException e)
                {
                    //ignore
                }
            }
        }
    }

    private class CountingRunnable implements Runnable
    {
        private Runnable target;

        private CountingRunnable(Runnable target)
        {
            this.target = target;
            todo.incrementAndGet();
        }

        public void run()
        {
            try
            {
                target.run();
            }
            finally
            {
                int remaining = todo.decrementAndGet();
                if (remaining == 0)
                {
                    synchronized (todo)
                    {
                        todo.notify();
                    }
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package uk.ac.cam.caret.sakai.rwiki.tool;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.time.cover.TimeService;

import uk.ac.cam.caret.sakai.rwiki.service.exception.PermissionException;
import uk.ac.cam.caret.sakai.rwiki.service.exception.ReadPermissionException;
import uk.ac.cam.caret.sakai.rwiki.tool.bean.ResourceLoaderBean;
import uk.ac.cam.caret.sakai.rwiki.tool.bean.ViewBean;
import uk.ac.cam.caret.sakai.rwiki.tool.bean.helper.ResourceLoaderHelperBean;
import uk.ac.cam.caret.sakai.rwiki.tool.command.Dispatcher;
import uk.ac.cam.caret.sakai.rwiki.utils.UserDisplayHelper;

/**
 * @author ieb
 */
public class VelocityInlineDispatcher implements Dispatcher
{
	private static final String MACROS = "/WEB-INF/vm/macros.vm";

	private VelocityEngine vengine;

	private String inlineMacros;

	private String basePath;

	private VelocityUtilBean utilBean = new VelocityUtilBean();

	public void init(ServletContext context) throws ServletException
	{
		inlineMacros = MACROS;
		try
		{
			vengine = new VelocityEngine();

			vengine.setApplicationAttribute(ServletContext.class.getName(), context);

			Properties p = new Properties();
			p.load(this.getClass().getResourceAsStream("rwikivelocity.config"));
			vengine.init(p);
			vengine.getTemplate(inlineMacros);

		}
		catch (Exception ex)
		{
			throw new ServletException(ex);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see uk.ac.cam.caret.sakai.rwiki.tool.command.Dispatcher#dispatch(java.lang.String,
	 *      javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	public void dispatch(String path, HttpServletRequest request,
			HttpServletResponse response) throws ServletException
	{
		VelocityContext vcontext = new VelocityContext();

		// EventCartridge ec = new EventCartridge();
		// ec.addEventHandler(new ExcludeEscapeHtmlReference());
		// ec.attachToContext(vcontext);

		vcontext.put("session", request.getSession());
		vcontext.put("request", request);
		vcontext.put("requestScope", RequestScopeSuperBean.getFromRequest(request));
		vcontext.put("util", utilBean);
		try
		{
			String filePath = path + ".vm";
			response.setContentType("text/html");
			response.setCharacterEncoding("UTF-8");
			vengine.mergeTemplate(filePath, vcontext, response.getWriter());
		}
		catch (MethodInvocationException e)
		{
			Throwable cause = e.getWrappedThrowable();
			if (cause instanceof PermissionException)
			{
				try
				{
					String filePath = "/WEB-INF/vm/permission.vm";
					response.setContentType("text/html");
					response.setCharacterEncoding("UTF-8");
					vengine.mergeTemplate(filePath, vcontext, response.getWriter());
				}
				catch (Exception ex)
				{
					throw new ServletException(ex);
				}
			}
			else
			{
				throw new ServletException(e);

			}

		}
		catch (Exception e)
		{
			throw new ServletException(e);
		}
	}

	public class VelocityUtilBean
	{

		public String escapeHtml(String val)
		{
			return FormattedText.escapeHtml(val, false);
		}

		public String formatDisplayName(String name)
		{
			if (name == null)
			{
				return "unknown";
			}
			return UserDisplayHelper.formatDisplayName(name, null);
		}

		public String formatDateTime(Date date, HttpServletRequest request)
		{
			if (date == null)
			{
				return "unkown-date";
			}
			ResourceLoader rl = new ResourceLoader();
			DateFormat formatter = DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.LONG, rl.getLocale() );
			formatter.setTimeZone(TimeService.getLocalTimeZone());
			return formatter.format(date);
		}

		public ViewBean newViewBean(RequestScopeSuperBean rssb)
		{
			ViewBean vb = new ViewBean();
			vb.setLocalSpace(rssb.getCurrentLocalSpace());
			return vb;
		}

	}

}


text:
<!DOCTYPE html >

          <meta http-equiv="X-UA-Compatible" content="IE=edge" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
          <title>Spark NLP 4.2.2 ScalaDoc  - com.johnsnowlabs.nlp.Router</title>
          <meta name="description" content="Spark NLP 4.2.2 ScalaDoc - com.johnsnowlabs.nlp.Router" />
          <meta name="keywords" content="Spark NLP 4.2.2 ScalaDoc com.johnsnowlabs.nlp.Router" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../lib/index.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

        Spark NLP 4.2.2 ScalaDoc
        < Back

            <input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" />
            
            

Packages

        

        package

        root

Definition Classes

root

        

        package

        com

Definition Classes

root

        

        package

        johnsnowlabs

Definition Classes

com

        

        package

        nlp

Definition Classes

johnsnowlabs

        

        package

        annotators

Definition Classes

nlp

        

        package

        eval

Definition Classes

nlp

        

        package

        jsl

Definition Classes

nlp

        

        package

        param

Definition Classes

nlp

        

        package

        pretrained

Definition Classes

nlp

        

        package

        training

Definition Classes

nlp

                        AnnotationMerger

                        Doc2ChunkInternal

                        FeaturesAssembler

                        Router

o

com.johnsnowlabs.nlp

Router

        

            Companion class Router

        object

        Router extends ParamsAndFeaturesReadable[Router] with Serializable

            Linear Supertypes

Serializable, Serializable, ParamsAndFeaturesReadable[Router], DefaultParamsReadable[Router], MLReadable[Router], AnyRef, Any

          

            <input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" />

          

            Ordering

Alphabetic

By Inheritance

                  Inherited

Router

Serializable

Serializable

ParamsAndFeaturesReadable

DefaultParamsReadable

MLReadable

AnyRef

Any

Hide All

Show All

              Visibility

Public

All

Value Members

        

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        def

        addReader(reader: (Router, String, SparkSession) ⇒ Unit): Unit

Definition Classes

ParamsAndFeaturesReadable

        

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        

        def

        clone(): AnyRef

Attributes

protected[lang]

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

                @native()

        

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        def

        finalize(): Unit

Attributes

protected[lang]

Definition Classes

AnyRef

Annotations

                @throws(

      classOf[java.lang.Throwable]
    )

        

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

Annotations

                @native()

        

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

Annotations

                @native()

        

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        

        def

        load(path: String): Router

Definition Classes

MLReadable

Annotations

                @Since(

      "1.6.0"
    )

        

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        final
        def

        notify(): Unit

Definition Classes

AnyRef

Annotations

                @native()

        

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

Annotations

                @native()

        

        def

        read: MLReader[Router]

Definition Classes

ParamsAndFeaturesReadable → DefaultParamsReadable → MLReadable

        

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        

        def

        toString(): String

Definition Classes

AnyRef → Any

        

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

                @native()

Inherited from Serializable

Inherited from Serializable

Inherited from ParamsAndFeaturesReadable[Router]

Inherited from DefaultParamsReadable[Router]

Inherited from MLReadable[Router]

Inherited from AnyRef

Inherited from Any

Ungrouped


text:
lcgshuffle
===
[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![Dependencies][dependencies-image]][dependencies-url]

> A linear congruential pseudorandom number generator whose output is shuffled per the Bays-Durham algorithm (lcgshuffle).

## *NB. NOT READY FOR USE*

## Installation

``` bash
$ npm install compute-lcgshuffle
```

For use in the browser, use [browserify](https://github.com/substack/node-browserify).

## Usage

To use the module,

``` javascript
var lcgshuffle = require( 'compute-lcgshuffle' );
```

#### foo( arr )

What does this function do?

## Examples

``` javascript
var foo = require( 'compute-lcgshuffle' );
```

To run the example code from the top-level application directory,

``` bash
$ node ./examples/index.js
```

## Notes

This module performs a Bays-Durham shuffle on the output from compute-lcg, a linear congruential generator.  This additional step considerably strengthens the "randomness quality" of lcg's output.

### Bays-Durham Shuffle Description

Suppose, for example, you have a (in this contrived example, terrible) random number generator exampleRand() that outputs 5, 10, 15, ..., and you want to shuffle its output in accord with the Bays-Durham algorithm.

1. Make a table T of size K, let us say, for example, 6.  (The table will change, so we will number the successive versions of the table as T0, T1, ... ).

2. Initialize T with K successive calls to exampleRand() =>

	T0 = [5,10,15,20,25,30]

3. Call exampleRand() to obtain the next random number R0 =>

	R0 = 35

4. Generate an index j0 into T0 from R0 by: (R0 + 1) mod K =>

	j0 = (35 + 1) mod 6 = 0

5. Get the next shuffled output from T0[j0], so our first shuffled output number X0 is:

	X0 = T0[j0] => T0[0] => 5

6. Now replace T0[j] with R0. => T0[0] = 35 =>

	T1 = [35,10,25,20,25,30]

7. Repeat steps 2-5 for X1, X2, etc.

For example, to get X1:

* R1 = exampleRand() => 40

* j1 = (40 + 1) mod 6 => 5

* X1 = T1[5] => 30

* Set T1[5] to R2 => T1[5] = 40 =>

	T2 = [35,10,25,20,25,40]

## References

1. Bays, Carter, & Durham, S.D., "Improving a Poor Random Number Generator", 2 *ACM Transactions on Mathematical Software* pp 59-64 (1976) (hereinafter Bays & Durham).

2. Bays & Durham p 59; Thomas N. Herzog and Graham Lord, *Applications of Monte Carlo Methods to Finance and Insurance* p19 (2002) (portions available [online] (http://books.google.com/books)).

3. W. Press, et al., *Numerical Recipes in C*, pp 280-81 (2d ed. 1992).

## Tests

### Unit

Unit tests use the [Mocha](http://mochajs.org/) test framework with [Chai](http://chaijs.com) assertions. To run the tests, execute the following command in the top-level application directory:

``` bash
$ make test
```

All new feature development should have corresponding unit tests to validate correct functionality.

### Test Coverage

This repository uses [Istanbul](https://github.com/gotwarlost/istanbul) as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory:

``` bash
$ make test-cov
```

Istanbul creates a `./reports/coverage` directory. To access an HTML version of the report,

``` bash
$ make view-cov
```

## License

[MIT license](http://opensource.org/licenses/MIT).

---
## Copyright

Copyright © 2015. rgizz.

[npm-image]: http://img.shields.io/npm/v/compute-lcgshuffle.svg
[npm-url]: https://npmjs.org/package/compute-lcgshuffle

[travis-image]: http://img.shields.io/travis/compute-io/lcgshuffle/master.svg
[travis-url]: https://travis-ci.org/compute-io/lcgshuffle

[coveralls-image]: https://img.shields.io/coveralls/compute-io/lcgshuffle/master.svg
[coveralls-url]: https://coveralls.io/r/compute-io/lcgshuffle?branch=master

[dependencies-image]: http://img.shields.io/david/compute-io/lcgshuffle.svg
[dependencies-url]: https://david-dm.org/compute-io/lcgshuffle

[dev-dependencies-image]: http://img.shields.io/david/dev/compute-io/lcgshuffle.svg
[dev-dependencies-url]: https://david-dm.org/dev/compute-io/lcgshuffle

[github-issues-image]: http://img.shields.io/github/issues/compute-io/lcgshuffle.svg
[github-issues-url]: https://github.com/compute-io/lcgshuffle/issues


text:
import * as au from "../aurelia";
import { deprecated } from "aurelia-framework";

@au.customElement("md-card")
@au.autoinject
export class MdCard {
	constructor(private element: Element) { }

	@au.ato.bindable.booleanMd({ defaultBindingMode: au.bindingMode.oneTime })
	horizontal: boolean;

	@au.ato.bindable.stringMd({ defaultBindingMode: au.bindingMode.oneTime })
	image: string = null;

	@au.ato.bindable.booleanMd({ defaultBindingMode: au.bindingMode.oneTime })
	reveal: boolean;

	@au.ato.bindable.booleanMd({ defaultBindingMode: au.bindingMode.oneTime })
	action: boolean;

	@au.ato.bindable.booleanMd({ defaultBindingMode: au.bindingMode.oneTime })
	stickyAction: boolean;

	@au.ato.bindable.stringMd({ defaultBindingMode: au.bindingMode.oneWay })
	size: string = "";

	@au.ato.bindable.stringMd({ defaultBindingMode: au.bindingMode.oneTime })
	title: string;
	@deprecated({ error: false, message: "Please use md-title instead." })
	titleChanged() {
		this.mdTitle = this.title;
	}

	@au.ato.bindable.stringMd({ defaultBindingMode: au.bindingMode.oneTime })
	mdTitle: string;

	@au.ato.bindable.stringMd({ defaultBindingMode: au.bindingMode.oneTime })
	mdClass: string;
}


text:
package com.cadalys.heroku.stereotype.service.controller;

import com.cadalys.heroku.stereotype.service.ArchiveService;
import com.cadalys.heroku.archive.ArchiveTableNames;
import com.cadalys.heroku.archive.ArchiveObjects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ArchiveController {

    @Autowired
    private ArchiveService archiveService;

    /**
     * Api call to archive specified objects
     *
     * @param objects
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/archive")
    public ResponseEntity<String> archiveObjects(@RequestBody ArchiveObjects objects) {
        archiveService.checkObjects(objects);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * Api call to delete triggers of specified objects
     *
     * @param objects
     * @return
     */
    @RequestMapping(method = RequestMethod.DELETE, value = "/archive")
    public ResponseEntity<String> deleteTrigger(@RequestBody ArchiveTableNames objects) {
        archiveService.deleteObjectsTrigger(objects);
        return new ResponseEntity<>(HttpStatus.OK);
    }

}


text:
<?php
class HtmlHelper{

	const DEFAULT_IMAGE_WIDTH = 16;
	const DEFAULT_IMAGE_HEIGHT = 16;

	public static function image($source, $alt = null, $width = self::DEFAULT_IMAGE_WIDTH, $height = self::DEFAULT_IMAGE_HEIGHT){
		return "";
	}

	public static function link($content, $link, $title = null, $confirm = false){
		$link = " {$content} ";
		return $link;
	}

	public static function resizeWithPHPThumb($phpThumbDir, $image, $width, $height, $alt, $title = '', $zc = 1){
		return "";
	}
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>AdminLTE 2 | Widgets</title>
    <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>

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

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

    <link href="http://code.ionicframework.com/ionicons/2.0.0/css/ionicons.min.css" rel="stylesheet" type="text/css" />

    <link href="../dist/css/AdminLTE.min.css" rel="stylesheet" type="text/css" />

    <link href="../dist/css/skins/_all-skins.min.css" rel="stylesheet" type="text/css" />

        AdminLTE

            Toggle navigation

                  4

You have 4 messages

                            Support Team
                             5 mins

Why not buy a new awesome theme?

                            AdminLTE Design Team
                             2 hours

Why not buy a new awesome theme?

                            Developers
                             Today

Why not buy a new awesome theme?

                            Sales Department
                             Yesterday

Why not buy a new awesome theme?

                            Reviewers
                             2 days

Why not buy a new awesome theme?

See All Messages

                  10

You have 10 notifications

                           5 new members joined today

                           Very long description here that may not fit into the page and may cause design problems

                           5 new members joined

                           25 sales made

                           You changed your username

View all

                  9

You have 9 tasks

                            Design some buttons
                            20%

                              20% Complete

                            Create a nice theme
                            40%

                              40% Complete

                            Some task I need to do
                            60%

                              60% Complete

                            Make beautiful transitions
                            80%

                              80% Complete

                    View all tasks

                  Alexander Pierce

                      Alexander Pierce - Web Developer
                      Member since Nov. 2012

                      Followers

                      Sales

                      Friends

                      Profile

                      Sign out

Alexander Pierce

               Online

          <form action="#" method="get" class="sidebar-form">

              <input type="text" name="q" class="form-control" placeholder="Search..."/>

                <button type='submit' name='seach' id='search-btn' class="btn btn-flat"></button>

          </form>

MAIN NAVIGATION

                 Dashboard

 Dashboard v1

 Dashboard v2

                Layout Options
                4

 Top Navigation

 Boxed

 Fixed

 Collapsed Sidebar

                 Widgets new

                Charts

 Morris

 Flot

 Inline charts

                UI Elements

 General

 Icons

 Buttons

 Sliders

 Timeline

 Modals

                 Forms

 General Elements

 Advanced Elements

 Editors

                 Tables

 Simple tables

 Data tables

                 Calendar
                3

                 Mailbox
                12

                 Examples

 Invoice

 Login

 Register

 Lockscreen

 404 Error

 500 Error

 Blank Page

                 Multilevel

 Level One

                   Level One

 Level Two

                       Level Two

 Level Three

 Level Three

 Level One

 Documentation

LABELS

 Important

 Warning

 Information

            Widgets
            Preview page

 Home

Widgets

            AdminLTE Small Boxes
            Small boxes are used for viewing statistics. To create a small box use the class .small-box and mix & match using the bg-* classes.

                    150

                    New Orders

                  More info

                    53%

                    Bounce Rate

                  More info

                    44

                    User Registrations

                  More info

                    65

                    Unique Visitors

                  More info

                    230

                    Sales

                  More info

                    80%

                    Conversion Rate

                  More info

                    14

                    Notifications

                  More info

                    160

                    Products

                  More info

            AdminLTE Boxes
            We use the base class .box to create widgets simply.

Default Box (button tooltip)

                    <button class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse"></button>
                    <button class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove"></button>

                  Box class: .box

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

                  .box-footer

Primary Box (header tooltip)

                    <button class="btn btn-primary btn-xs" data-widget="collapse"></button>
                    <button class="btn btn-primary btn-xs" data-widget="remove"></button>

                  Box class: .box.box-primary

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

                  .box-footer

Info Box

Label

                  Box class: .box.box-info

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

                  .box-footer

Danger Box (Loading state)

                    <button class="btn btn-danger btn-sm" data-widget="collapse"></button>
                    <button class="btn btn-danger btn-sm" data-widget="remove"></button>

                  Box class: .box.box-danger

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Success Box (toggle buttons)

                      <button type="button" class="btn btn-success btn-xs active" data-toggle="on">Left</button>
                      <button type="button" class="btn btn-success btn-xs" data-toggle="off">Right</button>

                  Box class: .box.box-success

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Warning Box

«

1

2

»

                  Box class: .box.box-warning

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

            AdminLTE Solid Boxes
            We use the base class .box and .box-solid to create solid boxes that look like this.

Default Solid Box

                    <button class="btn btn-default btn-sm" data-widget="collapse"></button>
                    <button class="btn btn-default btn-sm" data-widget="remove"></button>

                  Box class: .box.box-solid

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Primary Solid Box

                    <button class="btn btn-primary btn-sm" data-widget="collapse"></button>
                    <button class="btn btn-primary btn-sm" data-widget="remove"></button>

                  Box class: .box.box-solid.box-primary

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Info Solid Box

                    <button class="btn btn-info btn-sm" data-widget="collapse"></button>
                    <button class="btn btn-info btn-sm" data-widget="remove"></button>

                  Box class: .box.box-solid.box-info

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Danger Solid Box

                    <button class="btn btn-danger btn-sm" data-widget="collapse"></button>
                    <button class="btn btn-danger btn-sm" data-widget="remove"></button>

                  Box class: .box.box-solid.box-danger

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Success Solid Box

                    <button class="btn btn-success btn-sm" data-widget="collapse"></button>
                    <button class="btn btn-success btn-sm" data-widget="remove"></button>

                  Box class: .box.box-solid.box-success

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Warning Solid Box

                    <button class="btn btn-warning btn-sm" data-widget="collapse"></button>
                    <button class="btn btn-warning btn-sm" data-widget="remove"></button>

                  Box class: .box.box-solid.box-warning

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

            AdminLTE Tiles
            To create a tile we create a solid box and a .bg-* class ( * being the name of the color) to the box.

Navy Tile

                  Box class: .box.box-solid.bg-navy

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Primary Tile

                  Box class: .box.box-solid.bg-light-blue

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Info Tile

                  Box class: .box.box-solid.bg-aqua

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Danger Tile

                  Box class: .box.box-solid.bg-red

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Success Tile

                  Box class: .box.box-solid.bg-green

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Warning Tile

                  Box class: .box.box-solid.bg-yellow

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Purple Tile

                  Box class: .box.box-solid.bg-purple

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Blue Tile

                  Box class: .box.box-solid.bg-blue

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

Maroon Tile

                  Box class: .box.box-solid.bg-maroon

                    amber, microbrewery abbey hydrometer, brewpub ale lauter tun saccharification oxidized barrel.
                    berliner weisse wort chiller adjunct hydrometer alcohol aau!
                    sour/acidic sour/acidic chocolate malt ipa ipa hydrometer.

          Version 2.0

        Copyright © 2014-2015 Almsaeed Studio. All rights reserved.


text:
import * as React from 'react';

import { AspectRatioProps } from '../AspectRatio';
import { BoxProps } from '../Box';

type HtmlAttributes = Omit<React.ImgHTMLAttributes<HTMLImageElement>, keyof Props>;

export type ImageProvider = 'shopify' | undefined;

interface Props extends BoxProps {
  /** The alt text that describes the image */
  alt?: string;
  /** The native HTML `width` attribute to the passed to the `img` */
  htmlWidth?: string | number;
  /**  The native HTML `height` attribute to the passed to the `img` */
  htmlHeight?: string | number;
  /** Defines loading strategy */
  loading?: 'eager' | 'lazy';
  /** Set an aspect ratio for the image */
  aspectRatio?: AspectRatioProps['ratio'];
  /** Handy for use with the aspectRatio option */
  objectFit?: 'contain' | 'cover' | 'fill' | 'scale-down' | 'none';
  /** Handy for use with the aspectRatio option */
  objectPosition?:
    | 'left'
    | 'right'
    | 'bottom'
    | 'top'
    | 'left-top'
    | 'left-bottom'
    | 'right-top'
    | 'right-bottom'
    | 'center';
  /** The classname for  AspectRatio container wrapper */
  containerClassName?: string;
  /** The image sources, pass in an array to display the second image on hover */
  hoverSrc?: string;
  /* Decides how the `width` or `height` prop is handled */
  provider?: ImageProvider;
}

export interface ImageProps extends HtmlAttributes, Props {}


text:
using System;
using PactNet.Mocks.MockHttpService.Mappers;
using PactNet.Mocks.MockHttpService.Models;
using Xunit;

namespace PactNet.Tests.Mocks.MockHttpService.Mappers
{
    public class HttpVerbMapperTests
    {
        private IHttpVerbMapper GetSubject()
        {
            return new HttpVerbMapper();
        }

        [Fact]
        public void Convert_WithValueThatDoesNotHaveAMap_ThrowsArgumentException()
        {
            var mapper = GetSubject();

            Assert.Throws<ArgumentException>(() => mapper.Convert("blah"));
        }

        [Fact]
        public void Convert_WithGetString_ReturnsHttpVerbGet()
        {
            var mapper = GetSubject();

            var result = mapper.Convert("GET");

            Assert.Equal(HttpVerb.Get, result);
        }

        [Fact]
        public void Convert_WithPostString_ReturnsHttpVerbPost()
        {
            var mapper = GetSubject();

            var result = mapper.Convert("POST");

            Assert.Equal(HttpVerb.Post, result);
        }

        [Fact]
        public void Convert_WithPutString_ReturnsHttpVerbPut()
        {
            var mapper = GetSubject();

            var result = mapper.Convert("PUT");

            Assert.Equal(HttpVerb.Put, result);
        }

        [Fact]
        public void Convert_WithDeleteString_ReturnsHttpVerbDelete()
        {
            var mapper = GetSubject();

            var result = mapper.Convert("DELETE");

            Assert.Equal(HttpVerb.Delete, result);
        }

        [Fact]
        public void Convert_WithHeadString_ReturnsHttpVerbHead()
        {
            var mapper = GetSubject();

            var result = mapper.Convert("HEAD");

            Assert.Equal(HttpVerb.Head, result);
        }

        [Fact]
        public void Convert_WithPatchString_ReturnsHttpVerbPatch()
        {
            var mapper = GetSubject();

            var result = mapper.Convert("PATCH");

            Assert.Equal(HttpVerb.Patch, result);
        }
    }
}


text:
<?php
namespace Workflow\Execution;

use Workflow\Entity\Instance;
use Workflow\Entity\Place;

/**
 * Kontrak untuk instance manager (Eksekusi workflow).
 *
 * @author zakyalvan
 */
interface ExecutionServiceInterface {
	/**
	 * Apakah workflow dapat distart atau tidak.
	 *
	 * @param Workflow $workflow
	 * @return boolean
	 */
	public function canStartWorkflow(Workflow $workflow, array $datas);

	/**
	 * Start instance workflow baru.
	 *
	 * @param Workflow $workflow
	 * @param array $datas
	 * @throws WorkflowManager
	 * @return Instance
	 */
	public function startWorkflow(Workflow $workflow, array $datas);

	/**
	 * Manage work item, didelegasiin ke object dari kelas {@link WorkitemManager}.
	 *
	 * @param Workitem $workitem
	 * @return WorkitemManager
	 */
	public function manageWorkitem(Workitem $workitem);

	/**
	 * Apakah instance sudah complete atau belum.
	 *
	 * @param Instance $instance
	 */
	public function isCompletedInstance(Instance $instance);

	/**
	 * Retrieve di place mana saja token untuk instance yang bersangkutan nyangkut.
	 *
	 * @return array Place
	 */
	public function getInstanceState(Instance $instance);
}


text:
describe('emp3.api.Ellipse', function () {
  it('extends emp3.api.Feature', function() {
    var ellipse = new emp3.api.Ellipse();
    ellipse.should.be.an.instanceof(emp3.api.Feature);
  });

  describe('constructor', function () {
    var defaultEllipse;
    var defaultPosition;
    beforeEach(function() {
      defaultEllipse = new cmapi.IGeoEllipse();
      defaultPosition = new cmapi.IGeoPosition();
    });

    it('handles no parameters', function () {
      var ellipse = new emp3.api.Ellipse();
      ellipse.should.exist;
      ellipse.should.have.property('semiMajor', defaultEllipse.semiMajor);
      ellipse.should.have.property('semiMinor', defaultEllipse.semiMinor);
      expect(ellipse.position).to.have.property('latitude', defaultPosition.latitude);
      expect(ellipse.position).to.have.property('longitude', defaultPosition.longitude);
      expect(ellipse.position).to.have.property('altitude', defaultPosition.altitude);
    });

    it('handles null', function () {
      var ellipse = new emp3.api.Ellipse(null);
      ellipse.should.exist;
      ellipse.should.have.property('semiMajor', defaultEllipse.semiMajor);
      ellipse.should.have.property('semiMinor', defaultEllipse.semiMinor);
      expect(ellipse.position).to.have.property('latitude', defaultPosition.latitude);
      expect(ellipse.position).to.have.property('longitude', defaultPosition.longitude);
      expect(ellipse.position).to.have.property('altitude', defaultPosition.altitude);
    });

    it('handles undefined', function () {
      var ellipse = new emp3.api.Ellipse(undefined);
      ellipse.should.exist;
      ellipse.should.have.property('semiMajor', defaultEllipse.semiMajor);
      ellipse.should.have.property('semiMinor', defaultEllipse.semiMinor);
      expect(ellipse.position).to.have.property('latitude', defaultPosition.latitude);
      expect(ellipse.position).to.have.property('longitude', defaultPosition.longitude);
      expect(ellipse.position).to.have.property('altitude', defaultPosition.altitude);
    });

    it('handles arrays', function () {
      var ellipse = new emp3.api.Ellipse(['arrays', 'of', 'things']);
      ellipse.should.exist;
      ellipse.should.have.property('semiMajor', defaultEllipse.semiMajor);
      ellipse.should.have.property('semiMinor', defaultEllipse.semiMinor);
      expect(ellipse.position).to.have.property('latitude', defaultPosition.latitude);
      expect(ellipse.position).to.have.property('longitude', defaultPosition.longitude);
      expect(ellipse.position).to.have.property('altitude', defaultPosition.altitude);
    });

    it('handles strings', function () {
      var ellipse = new emp3.api.Ellipse('strings');
      ellipse.should.exist;
      ellipse.should.have.property('semiMajor', defaultEllipse.semiMajor);
      ellipse.should.have.property('semiMinor', defaultEllipse.semiMinor);
      expect(ellipse.position).to.have.property('latitude', defaultPosition.latitude);
      expect(ellipse.position).to.have.property('longitude', defaultPosition.longitude);
      expect(ellipse.position).to.have.property('altitude', defaultPosition.altitude);
    });

    it('handles numbers', function () {
      var ellipse = new emp3.api.Ellipse(42);
      ellipse.should.exist;
      ellipse.should.have.property('semiMajor', defaultEllipse.semiMajor);
      ellipse.should.have.property('semiMinor', defaultEllipse.semiMinor);
      expect(ellipse.position).to.have.property('latitude', defaultPosition.latitude);
      expect(ellipse.position).to.have.property('longitude', defaultPosition.longitude);
      expect(ellipse.position).to.have.property('altitude', defaultPosition.altitude);
    });

    it('handles missing arguments', function () {
      var args = {
        semiMajor: 1
      };
      var ellipse = new emp3.api.Ellipse(args);
      ellipse.should.exist;
      ellipse.should.have.property('semiMajor', args.semiMajor);
      ellipse.should.have.property('semiMinor', defaultEllipse.semiMinor);
      expect(ellipse.position).to.have.property('latitude', defaultPosition.latitude);
      expect(ellipse.position).to.have.property('longitude', defaultPosition.longitude);
      expect(ellipse.position).to.have.property('altitude', defaultPosition.altitude);

      args = {
        position: null
      };
      ellipse = new emp3.api.Ellipse({args: null});
      ellipse.should.exist;
      ellipse.should.have.property('semiMajor', defaultEllipse.semiMajor);
      ellipse.should.have.property('semiMinor', defaultEllipse.semiMinor);
      expect(ellipse.position).to.have.property('latitude', defaultPosition.latitude);
      expect(ellipse.position).to.have.property('longitude', defaultPosition.longitude);
      expect(ellipse.position).to.have.property('altitude', defaultPosition.altitude);

      args = {
        position: {latitude: 50.2, altitude: 89.3},
        semiMinor: 156
      };
      ellipse = new emp3.api.Ellipse(args);
      ellipse.should.have.property('semiMajor', defaultEllipse.semiMajor);
      ellipse.should.have.property('semiMinor', args.semiMinor);
      expect(ellipse.position).to.have.property('latitude', args.position.latitude);
      expect(ellipse.position).to.have.property('longitude', defaultPosition.longitude);
      expect(ellipse.position).to.have.property('altitude', args.position.altitude);
    });

    it('handles corrupt arguments', function () {
      var ellipse;
      var args;

      args = {position: undefined};
      ellipse = new emp3.api.Ellipse(args);
      ellipse.should.have.property('semiMajor', defaultEllipse.semiMajor);
      ellipse.should.have.property('semiMinor', defaultEllipse.semiMinor);
      expect(ellipse.position).to.have.property('latitude', defaultPosition.latitude);
      expect(ellipse.position).to.have.property('longitude', defaultPosition.longitude);
      expect(ellipse.position).to.have.property('altitude', defaultPosition.altitude);

      args = {
        semiMajor: '13',
        semiMinor: null
      };
      ellipse = new emp3.api.Ellipse(args);
      ellipse.should.have.property('semiMajor', defaultEllipse.semiMajor);
      ellipse.should.have.property('semiMinor', defaultEllipse.semiMinor);
      expect(ellipse.position).to.have.property('latitude', defaultPosition.latitude);
      expect(ellipse.position).to.have.property('longitude', defaultPosition.longitude);
      expect(ellipse.position).to.have.property('altitude', defaultPosition.altitude);

      args = {
        semiMajor: undefined,
        semiMinor: 'cow'
      };
      ellipse = new emp3.api.Ellipse(args);
      ellipse.should.have.property('semiMajor', defaultEllipse.semiMajor);
      ellipse.should.have.property('semiMinor', defaultEllipse.semiMinor);
      expect(ellipse.position).to.have.property('latitude', defaultPosition.latitude);
      expect(ellipse.position).to.have.property('longitude', defaultPosition.longitude);
      expect(ellipse.position).to.have.property('altitude', defaultPosition.altitude);

      args = {
        semiMajor: null,
        semiMinor: null
      };
      ellipse = new emp3.api.Ellipse(args);
      ellipse.should.have.property('semiMajor', defaultEllipse.semiMajor);
      ellipse.should.have.property('semiMinor', defaultEllipse.semiMinor);
      expect(ellipse.position).to.have.property('latitude', defaultPosition.latitude);
      expect(ellipse.position).to.have.property('longitude', defaultPosition.longitude);
      expect(ellipse.position).to.have.property('altitude', defaultPosition.altitude);
    });

    it('handles valid parameters', function () {
      var ellipse;
      var args;

      args = {
        position: {
          latitude: -71,
          longitude: 52.3
        },
        azimuth: 15.9,
        semiMajor: 87,
        semiMinor: 46.8
      };
      ellipse = new emp3.api.Ellipse(args);
      ellipse.should.exist;
      ellipse.should.have.property('semiMajor', args.semiMajor);
      ellipse.should.have.property('semiMinor', args.semiMinor);
      ellipse.should.have.property('azimuth', args.azimuth);
      expect(ellipse.position).to.have.property('latitude', args.position.latitude);
      expect(ellipse.position).to.have.property('longitude', args.position.longitude);
      expect(ellipse.position).to.have.property('altitude', args.position.altitude);
    });

    it('handles IGeoEllipse');
  });

  describe('featureType', function() {
    it('is GEO_ELLIPSE', function() {
      var ellipse = new emp3.api.Ellipse();
      ellipse.featureType.should.equal(emp3.api.enums.FeatureTypeEnum.GEO_ELLIPSE);
    });
  });
});


text:
<!DOCTYPE html>

<meta charset="UTF-8">

local/index should be loaded, local/a should be alert.

global/index should not be loaded, an error should be throwed because use global require in factory.

./assertrelativeid/local/index should not be required, an error should be throwed.


text:
<?php
namespace MOC\MarkIV\Core\Error\Handler\Source\Type;

use MOC\MarkIV\Core\Error\Handler\Source\Template\Shutdown as ShutdownTemplate;

/**
 * Class Shutdown
 *
 * @package MOC\MarkIV\Core\Error\Handler\Source\Type
 */
class Shutdown extends Generic
{

    /**
     * @return void
     */
    public function registerType()
    {

        register_shutdown_function(
            create_function( '',
                '\MOC\MarkIV\Api::groupCore()->unitError()->apiHandler()->apiType()->buildShutdown()->setData( "Shutdown", "","-1","","" );'
            )
        );
    }

    /**
     * @param string $Title
     * @param string $Message
     * @param string $Code
     * @param string $File
     * @param string $Line
     * @param string $Trace
     * @param string $Information
     *
     * @return void
     */
    public function setData( $Title, $Message, $Code, $File, $Line, $Trace = '', $Information = '' )
    {

        if (( $Error = error_get_last() ) !== null && $Error['type'] === E_ERROR) {
            if (empty( $Trace ) || strlen( $Trace ) < 10) {
                $Trace = $this->getTrace();
            }
            print new ShutdownTemplate( 'Shutdown', $Error['message'], $Error['type'], $Error['file'], $Error['line'],
                $Trace, 'Fatal - Execution has been stopped!' );
        }
    }

}


text:
package remoteexec

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"strings"
	"time"

	"github.com/hashicorp/terraform/communicator"
	"github.com/hashicorp/terraform/communicator/remote"
	"github.com/hashicorp/terraform/helper/schema"
	"github.com/hashicorp/terraform/terraform"
	"github.com/mitchellh/go-linereader"
)

// maxBackoffDealy is the maximum delay between retry attempts
var maxBackoffDelay = 10 * time.Second
var initialBackoffDelay = time.Second

func Provisioner() terraform.ResourceProvisioner {
	return &schema.Provisioner{
		Schema: map[string]*schema.Schema{
			"inline": {
				Type:          schema.TypeList,
				Elem:          &schema.Schema{Type: schema.TypeString},
				PromoteSingle: true,
				Optional:      true,
				ConflictsWith: []string{"script", "scripts"},
			},

			"script": {
				Type:          schema.TypeString,
				Optional:      true,
				ConflictsWith: []string{"inline", "scripts"},
			},

			"scripts": {
				Type:          schema.TypeList,
				Elem:          &schema.Schema{Type: schema.TypeString},
				Optional:      true,
				ConflictsWith: []string{"script", "inline"},
			},
		},

		ApplyFunc: applyFn,
	}
}

// Apply executes the remote exec provisioner
func applyFn(ctx context.Context) error {
	connState := ctx.Value(schema.ProvRawStateKey).(*terraform.InstanceState)
	data := ctx.Value(schema.ProvConfigDataKey).(*schema.ResourceData)
	o := ctx.Value(schema.ProvOutputKey).(terraform.UIOutput)

	// Get a new communicator
	comm, err := communicator.New(connState)
	if err != nil {
		return err
	}

	// Collect the scripts
	scripts, err := collectScripts(data)
	if err != nil {
		return err
	}
	for _, s := range scripts {
		defer s.Close()
	}

	// Copy and execute each script
	if err := runScripts(ctx, o, comm, scripts); err != nil {
		return err
	}

	return nil
}

// generateScripts takes the configuration and creates a script from each inline config
func generateScripts(d *schema.ResourceData) ([]string, error) {
	var lines []string
	for _, l := range d.Get("inline").([]interface{}) {
		line, ok := l.(string)
		if !ok {
			return nil, fmt.Errorf("Error parsing %v as a string", l)
		}
		lines = append(lines, line)
	}
	lines = append(lines, "")

	return []string{strings.Join(lines, "\n")}, nil
}

// collectScripts is used to collect all the scripts we need
// to execute in preparation for copying them.
func collectScripts(d *schema.ResourceData) ([]io.ReadCloser, error) {
	// Check if inline
	if _, ok := d.GetOk("inline"); ok {
		scripts, err := generateScripts(d)
		if err != nil {
			return nil, err
		}

		var r []io.ReadCloser
		for _, script := range scripts {
			r = append(r, ioutil.NopCloser(bytes.NewReader([]byte(script))))
		}

		return r, nil
	}

	// Collect scripts
	var scripts []string
	if script, ok := d.GetOk("script"); ok {
		scr, ok := script.(string)
		if !ok {
			return nil, fmt.Errorf("Error parsing script %v as string", script)
		}
		scripts = append(scripts, scr)
	}

	if scriptList, ok := d.GetOk("scripts"); ok {
		for _, script := range scriptList.([]interface{}) {
			scr, ok := script.(string)
			if !ok {
				return nil, fmt.Errorf("Error parsing script %v as string", script)
			}
			scripts = append(scripts, scr)
		}
	}

	// Open all the scripts
	var fhs []io.ReadCloser
	for _, s := range scripts {
		fh, err := os.Open(s)
		if err != nil {
			for _, fh := range fhs {
				fh.Close()
			}
			return nil, fmt.Errorf("Failed to open script '%s': %v", s, err)
		}
		fhs = append(fhs, fh)
	}

	// Done, return the file handles
	return fhs, nil
}

// runScripts is used to copy and execute a set of scripts
func runScripts(
	ctx context.Context,
	o terraform.UIOutput,
	comm communicator.Communicator,
	scripts []io.ReadCloser) error {

	retryCtx, cancel := context.WithTimeout(ctx, comm.Timeout())
	defer cancel()

	// Wait and retry until we establish the connection
	err := communicator.Retry(retryCtx, func() error {
		return comm.Connect(o)
	})
	if err != nil {
		return err
	}

	// Wait for the context to end and then disconnect
	go func() {
		<-ctx.Done()
		comm.Disconnect()
	}()

	for _, script := range scripts {
		var cmd *remote.Cmd

		outR, outW := io.Pipe()
		errR, errW := io.Pipe()
		defer outW.Close()
		defer errW.Close()

		go copyOutput(o, outR)
		go copyOutput(o, errR)

		remotePath := comm.ScriptPath()

		if err := comm.UploadScript(remotePath, script); err != nil {
			return fmt.Errorf("Failed to upload script: %v", err)
		}

		cmd = &remote.Cmd{
			Command: remotePath,
			Stdout:  outW,
			Stderr:  errW,
		}
		if err := comm.Start(cmd); err != nil {
			return fmt.Errorf("Error starting script: %v", err)
		}
		cmd.Wait()

		if err := cmd.Err(); err != nil {
			return fmt.Errorf("Remote command exited with error: %s", err)
		}

		if cmd.ExitStatus() != 0 {
			err = fmt.Errorf("Script exited with non-zero exit status: %d", cmd.ExitStatus())
		}

		// Upload a blank follow up file in the same path to prevent residual
		// script contents from remaining on remote machine
		empty := bytes.NewReader([]byte(""))
		if err := comm.Upload(remotePath, empty); err != nil {
			// This feature is best-effort.
			log.Printf("[WARN] Failed to upload empty follow up script: %v", err)
		}
	}

	return nil
}

func copyOutput(
	o terraform.UIOutput, r io.Reader) {
	lr := linereader.New(r)
	for line := range lr.Ch {
		o.Output(line)
	}
}


text:
<!DOCTYPE html><html>
    <head>
        <meta name="go-import" content="npf.io/gorram git https://github.com/natefinch/gorram">
        <meta name="go-source" content="npf.io/gorram https://github.com/natefinch/gorram https://github.com/natefinch/gorram/tree/master{/dir} https://github.com/natefinch/gorram/blob/master{/dir}/{file}#L{line}">
        <title>https://npf.io/gorram/</title>
        <link rel="canonical" href="https://npf.io/gorram/"/>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <meta http-equiv="refresh" content="0; url=https://npf.io/gorram/" />
    </head>
</html>


text:
import unittest
import os
import sys
if os.environ.get('USELIB') != '1':
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from pyleri import (
    KeywordError,
    create_grammar,
    Keyword,
    Token,
    Choice,
)  # nopep8

class TestKeyword(unittest.TestCase):

    def test_keyword(self):
        k_hi = Keyword('hi')
        grammar = create_grammar(k_hi)

        self.assertFalse(k_hi.ign_case)
        self.assertTrue(grammar.parse('hi').is_valid)
        self.assertTrue(grammar.parse(' hi ').is_valid)
        self.assertFalse(grammar.parse('Hi').is_valid)
        self.assertFalse(grammar.parse('hello').is_valid)
        self.assertEqual(
            'error at position 0, expecting: hi',
            str(grammar.parse('hello')))
        self.assertEqual(
            'parsed successfully',
            str(grammar.parse('hi')))

    def test_keyword_ign_case(self):
        k_hi = Keyword('hi', ign_case=True)
        grammar = create_grammar(k_hi)

        self.assertTrue(k_hi.ign_case)
        self.assertTrue(grammar.parse('hi').is_valid)
        self.assertTrue(grammar.parse('Hi').is_valid)
        self.assertFalse(grammar.parse('hello').is_valid)
        self.assertEqual(
            'error at position 2, expecting: end_of_statement',
            str(grammar.parse('Hi Iris')))

    def test_keyword_alt_regkw(self):
        grammar = create_grammar(Choice(Keyword('hi'), Token('HI')), r'[a-z]+')
        self.assertTrue(grammar.parse('hi').is_valid)
        self.assertTrue(grammar.parse('HI').is_valid)
        self.assertFalse(grammar.parse('').is_valid)
        self.assertFalse(grammar.parse('Hi').is_valid)

if __name__ == '__main__':
    unittest.main()