text:
namespace clang {
namespace tooling {

TEST_F(ReplacementTest, CanDeleteAllText) {
  FileID ID = Context.createInMemoryFile("input.cpp", "text");
  SourceLocation Location = Context.getLocation(ID, 1, 1);
  Replacement Replace(createReplacement(Location, 4, ""));
  EXPECT_TRUE(Replace.apply(Context.Rewrite));
  EXPECT_EQ("", Context.getRewrittenText(ID));
}

TEST_F(ReplacementTest, CanDeleteAllTextInTextWithNewlines) {
  FileID ID = Context.createInMemoryFile("input.cpp", "line1\nline2\nline3");
  SourceLocation Location = Context.getLocation(ID, 1, 1);
  Replacement Replace(createReplacement(Location, 17, ""));
  EXPECT_TRUE(Replace.apply(Context.Rewrite));
  EXPECT_EQ("", Context.getRewrittenText(ID));
}

TEST_F(ReplacementTest, CanAddText) {
  FileID ID = Context.createInMemoryFile("input.cpp", "");
  SourceLocation Location = Context.getLocation(ID, 1, 1);
  Replacement Replace(createReplacement(Location, 0, "result"));
  EXPECT_TRUE(Replace.apply(Context.Rewrite));
  EXPECT_EQ("result", Context.getRewrittenText(ID));
}

TEST_F(ReplacementTest, CanReplaceTextAtPosition) {
  FileID ID = Context.createInMemoryFile("input.cpp",
                                         "line1\nline2\nline3\nline4");
  SourceLocation Location = Context.getLocation(ID, 2, 3);
  Replacement Replace(createReplacement(Location, 12, "x"));
  EXPECT_TRUE(Replace.apply(Context.Rewrite));
  EXPECT_EQ("line1\nlixne4", Context.getRewrittenText(ID));
}

TEST_F(ReplacementTest, CanReplaceTextAtPositionMultipleTimes) {
  FileID ID = Context.createInMemoryFile("input.cpp",
                                         "line1\nline2\nline3\nline4");
  SourceLocation Location1 = Context.getLocation(ID, 2, 3);
  Replacement Replace1(createReplacement(Location1, 12, "x\ny\n"));
  EXPECT_TRUE(Replace1.apply(Context.Rewrite));
  EXPECT_EQ("line1\nlix\ny\nne4", Context.getRewrittenText(ID));

  // Since the original source has not been modified, the (4, 4) points to the
  // 'e' in the original content.
  SourceLocation Location2 = Context.getLocation(ID, 4, 4);
  Replacement Replace2(createReplacement(Location2, 1, "f"));
  EXPECT_TRUE(Replace2.apply(Context.Rewrite));
  EXPECT_EQ("line1\nlix\ny\nnf4", Context.getRewrittenText(ID));
}

TEST_F(ReplacementTest, ApplyFailsForNonExistentLocation) {
  Replacement Replace("nonexistent-file.cpp", 0, 1, "");
  EXPECT_FALSE(Replace.apply(Context.Rewrite));
}

TEST_F(ReplacementTest, CanRetrivePath) {
  Replacement Replace("/path/to/file.cpp", 0, 1, "");
  EXPECT_EQ("/path/to/file.cpp", Replace.getFilePath());
}

TEST_F(ReplacementTest, ReturnsInvalidPath) {
  Replacement Replace1(Context.Sources, SourceLocation(), 0, "");
  EXPECT_TRUE(Replace1.getFilePath().empty());

  Replacement Replace2;
  EXPECT_TRUE(Replace2.getFilePath().empty());
}

// Checks that an llvm::Error instance contains a ReplacementError with expected
// error code, expected new replacement, and expected existing replacement.
static bool checkReplacementError(
    llvm::Error&& Error, replacement_error ExpectedErr,
    llvm::Optional<Replacement> ExpectedExisting,
    llvm::Optional<Replacement> ExpectedNew) {
  if (!Error) {
    llvm::errs() << "Error is a success.";
    return false;
  }
  std::string ErrorMessage;
  llvm::raw_string_ostream OS(ErrorMessage);
  llvm::handleAllErrors(std::move(Error), [&](const ReplacementError &RE) {
    llvm::errs() << "Handling error...\n";
    if (ExpectedErr != RE.get())
      OS << "Unexpected error code: " << int(RE.get()) << "\n";
    if (ExpectedExisting != RE.getExistingReplacement()) {
      OS << "Expected Existing != Actual Existing.\n";
      if (ExpectedExisting.hasValue())
        OS << "Expected existing replacement: " << ExpectedExisting->toString()
           << "\n";
      if (RE.getExistingReplacement().hasValue())
        OS << "Actual existing replacement: "
           << RE.getExistingReplacement()->toString() << "\n";
    }
    if (ExpectedNew != RE.getNewReplacement()) {
      OS << "Expected New != Actual New.\n";
      if (ExpectedNew.hasValue())
        OS << "Expected new replacement: " << ExpectedNew->toString() << "\n";
      if (RE.getNewReplacement().hasValue())
        OS << "Actual new replacement: " << RE.getNewReplacement()->toString()
           << "\n";
    }
  });
  OS.flush();
  if (ErrorMessage.empty()) return true;
  llvm::errs() << ErrorMessage;
  return false;
}

TEST_F(ReplacementTest, FailAddReplacements) {
  Replacements Replaces;
  Replacement Deletion("x.cc", 0, 10, "3");
  auto Err = Replaces.add(Deletion);
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  Replacement OverlappingReplacement("x.cc", 0, 2, "a");
  Err = Replaces.add(OverlappingReplacement);
  EXPECT_TRUE(checkReplacementError(std::move(Err),
                                    replacement_error::overlap_conflict,
                                    Deletion, OverlappingReplacement));

  Replacement ContainedReplacement("x.cc", 2, 2, "a");
  Err = Replaces.add(Replacement(ContainedReplacement));
  EXPECT_TRUE(checkReplacementError(std::move(Err),
                                    replacement_error::overlap_conflict,
                                    Deletion, ContainedReplacement));

  Replacement WrongPathReplacement("y.cc", 20, 2, "");
  Err = Replaces.add(WrongPathReplacement);
  EXPECT_TRUE(checkReplacementError(std::move(Err),
                                    replacement_error::wrong_file_path,
                                    Deletion, WrongPathReplacement));

  EXPECT_EQ(1u, Replaces.size());
  EXPECT_EQ(Deletion, *Replaces.begin());
}

TEST_F(ReplacementTest, DeletionInReplacements) {
  Replacements Replaces;
  Replacement R("x.cc", 0, 10, "3");
  auto Err = Replaces.add(R);
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Err = Replaces.add(Replacement("x.cc", 0, 2, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Err = Replaces.add(Replacement("x.cc", 2, 2, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  EXPECT_EQ(1u, Replaces.size());
  EXPECT_EQ(R, *Replaces.begin());
}

TEST_F(ReplacementTest, OverlappingReplacements) {
  Replacements Replaces;
  auto Err = Replaces.add(Replacement("x.cc", 0, 3, "345"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Err = Replaces.add(Replacement("x.cc", 2, 3, "543"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  EXPECT_EQ(1u, Replaces.size());
  EXPECT_EQ(Replacement("x.cc", 0, 5, "34543"), *Replaces.begin());

  Err = Replaces.add(Replacement("x.cc", 2, 1, "5"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  EXPECT_EQ(1u, Replaces.size());
  EXPECT_EQ(Replacement("x.cc", 0, 5, "34543"), *Replaces.begin());
}

TEST_F(ReplacementTest, AddAdjacentInsertionAndReplacement) {
  Replacements Replaces;
  // Test adding an insertion at the offset of an existing replacement.
  auto Err = Replaces.add(Replacement("x.cc", 10, 3, "replace"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Err = Replaces.add(Replacement("x.cc", 10, 0, "insert"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  EXPECT_EQ(Replaces.size(), 2u);

  Replaces.clear();
  // Test overlap with an existing insertion.
  Err = Replaces.add(Replacement("x.cc", 10, 0, "insert"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Err = Replaces.add(Replacement("x.cc", 10, 3, "replace"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  EXPECT_EQ(Replaces.size(), 2u);
}

TEST_F(ReplacementTest, MergeNewDeletions) {
  Replacements Replaces;
  Replacement ContainingReplacement("x.cc", 0, 10, "");
  auto Err = Replaces.add(ContainingReplacement);
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  Err = Replaces.add(Replacement("x.cc", 5, 3, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  Err = Replaces.add(Replacement("x.cc", 0, 10, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  Err = Replaces.add(Replacement("x.cc", 5, 5, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  EXPECT_EQ(1u, Replaces.size());
  EXPECT_EQ(*Replaces.begin(), ContainingReplacement);
}

TEST_F(ReplacementTest, MergeOverlappingButNotAdjacentReplacement) {
  Replacements Replaces;
  auto Err = Replaces.add(Replacement("x.cc", 0, 2, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  Err = Replaces.add(Replacement("x.cc", 5, 5, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  Replacement After = Replacement("x.cc", 10, 5, "");
  Err = Replaces.add(After);
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  Replacement ContainingReplacement("x.cc", 0, 10, "");
  Err = Replaces.add(ContainingReplacement);
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  EXPECT_EQ(2u, Replaces.size());
  EXPECT_EQ(*Replaces.begin(), ContainingReplacement);
  EXPECT_EQ(*(++Replaces.begin()), After);
}

TEST_F(ReplacementTest, InsertionBeforeMergedDeletions) {
  Replacements Replaces;

  Replacement Insertion("x.cc", 0, 0, "123");
  auto Err = Replaces.add(Insertion);
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  Err = Replaces.add(Replacement("x.cc", 5, 5, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  Replacement Deletion("x.cc", 0, 10, "");
  Err = Replaces.add(Deletion);
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  EXPECT_EQ(2u, Replaces.size());
  EXPECT_EQ(*Replaces.begin(), Insertion);
  EXPECT_EQ(*(++Replaces.begin()), Deletion);
}

TEST_F(ReplacementTest, MergeOverlappingDeletions) {
  Replacements Replaces;
  auto Err = Replaces.add(Replacement("x.cc", 0, 2, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  Err = Replaces.add(Replacement("x.cc", 0, 5, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  EXPECT_EQ(1u, Replaces.size());
  EXPECT_EQ(Replacement("x.cc", 0, 5, ""), *Replaces.begin());

  Err = Replaces.add(Replacement("x.cc", 1, 5, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  EXPECT_EQ(1u, Replaces.size());
  EXPECT_EQ(Replacement("x.cc", 0, 6, ""), *Replaces.begin());
}

TEST_F(ReplacementTest, FailedMergeExistingDeletions) {
  Replacements Replaces;
  Replacement First("x.cc", 0, 2, "");
  auto Err = Replaces.add(First);
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  Replacement Second("x.cc", 5, 5, "");
  Err = Replaces.add(Second);
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  Err = Replaces.add(Replacement("x.cc", 1, 10, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  EXPECT_EQ(1u, Replaces.size());
  EXPECT_EQ(Replacement("x.cc", 0, 11, ""), *Replaces.begin());
}

TEST_F(ReplacementTest, FailAddRegression) {
  Replacements Replaces;
  // Create two replacements, where the second one is an insertion of the empty
  // string exactly at the end of the first one.
  auto Err = Replaces.add(Replacement("x.cc", 0, 10, "1"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Err = Replaces.add(Replacement("x.cc", 10, 0, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  // Make sure we find the overlap with the first entry when inserting a
  // replacement that ends exactly at the seam of the existing replacements.
  Replacement OverlappingReplacement("x.cc", 5, 5, "fail");
  Err = Replaces.add(OverlappingReplacement);
  EXPECT_TRUE(checkReplacementError(std::move(Err),
                                    replacement_error::overlap_conflict,
                                    *Replaces.begin(), OverlappingReplacement));

  Err = Replaces.add(Replacement("x.cc", 10, 0, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
}

TEST_F(ReplacementTest, InsertAtOffsetOfReplacement) {
  Replacements Replaces;
  auto Err = Replaces.add(Replacement("x.cc", 10, 2, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Err = Replaces.add(Replacement("x.cc", 10, 0, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  EXPECT_EQ(Replaces.size(), 2u);

  Replaces.clear();
  Err = Replaces.add(Replacement("x.cc", 10, 0, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Err = Replaces.add(Replacement("x.cc", 10, 2, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  EXPECT_EQ(Replaces.size(), 2u);
}

TEST_F(ReplacementTest, AddInsertAtOtherInsertWhenOderIndependent) {
  Replacements Replaces;
  auto Err = Replaces.add(Replacement("x.cc", 10, 0, "a"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Replacement ConflictInsertion("x.cc", 10, 0, "b");
  Err = Replaces.add(ConflictInsertion);
  EXPECT_TRUE(checkReplacementError(std::move(Err),
                                    replacement_error::insert_conflict,
                                    *Replaces.begin(), ConflictInsertion));

  Replaces.clear();
  Err = Replaces.add(Replacement("x.cc", 10, 0, "a"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Err = Replaces.add(Replacement("x.cc", 10, 0, "aa"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  EXPECT_EQ(1u, Replaces.size());
  EXPECT_EQ(Replacement("x.cc", 10, 0, "aaa"), *Replaces.begin());

  Replaces.clear();
  Err = Replaces.add(Replacement("x.cc", 10, 0, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Err = Replaces.add(Replacement("x.cc", 10, 3, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Err = Replaces.add(Replacement("x.cc", 10, 0, ""));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  EXPECT_EQ(2u, Replaces.size());
  EXPECT_EQ(Replacement("x.cc", 10, 0, ""), *Replaces.begin());
  EXPECT_EQ(Replacement("x.cc", 10, 3, ""), *std::next(Replaces.begin()));
}

TEST_F(ReplacementTest, InsertBetweenAdjacentReplacements) {
  Replacements Replaces;
  auto Err = Replaces.add(Replacement("x.cc", 10, 5, "a"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Err = Replaces.add(Replacement("x.cc", 8, 2, "a"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
  Err = Replaces.add(Replacement("x.cc", 10, 0, "b"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));
}

TEST_F(ReplacementTest, CanApplyReplacements) {
  FileID ID = Context.createInMemoryFile("input.cpp",
                                         "line1\nline2\nline3\nline4");
  Replacements Replaces =
      toReplacements({Replacement(Context.Sources,
                                  Context.getLocation(ID, 2, 1), 5, "replaced"),
                      Replacement(Context.Sources,
                                  Context.getLocation(ID, 3, 1), 5, "other")});
  EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
  EXPECT_EQ("line1\nreplaced\nother\nline4", Context.getRewrittenText(ID));
}

// Verifies that replacement/deletion is applied before insertion at the same
// offset.
TEST_F(ReplacementTest, InsertAndDelete) {
  FileID ID = Context.createInMemoryFile("input.cpp",
                                         "line1\nline2\nline3\nline4");
  Replacements Replaces = toReplacements(
      {Replacement(Context.Sources, Context.getLocation(ID, 2, 1), 6, ""),
       Replacement(Context.Sources, Context.getLocation(ID, 2, 1), 0,
                   "other\n")});
  EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
  EXPECT_EQ("line1\nother\nline3\nline4", Context.getRewrittenText(ID));
}

TEST_F(ReplacementTest, AdjacentReplacements) {
  FileID ID = Context.createInMemoryFile("input.cpp",
                                         "ab");
  Replacements Replaces = toReplacements(
      {Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 1, "x"),
       Replacement(Context.Sources, Context.getLocation(ID, 1, 2), 1, "y")});
  EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
  EXPECT_EQ("xy", Context.getRewrittenText(ID));
}

TEST_F(ReplacementTest, AddDuplicateReplacements) {
  FileID ID = Context.createInMemoryFile("input.cpp",
                                         "line1\nline2\nline3\nline4");
  auto Replaces = toReplacements({Replacement(
      Context.Sources, Context.getLocation(ID, 2, 1), 5, "replaced")});

  auto Err = Replaces.add(Replacement(
      Context.Sources, Context.getLocation(ID, 2, 1), 5, "replaced"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  Err = Replaces.add(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
                                 5, "replaced"));
  EXPECT_TRUE(!Err);
  llvm::consumeError(std::move(Err));

  EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
  EXPECT_EQ("line1\nreplaced\nline3\nline4", Context.getRewrittenText(ID));
}

TEST_F(ReplacementTest, FailOrderDependentReplacements) {
  FileID ID = Context.createInMemoryFile("input.cpp",
                                         "line1\nline2\nline3\nline4");
  auto Replaces = toReplacements({Replacement(
      Context.Sources, Context.getLocation(ID, 2, 1), 5, "other")});

  Replacement ConflictReplacement(Context.Sources,
                                  Context.getLocation(ID, 2, 1), 5, "rehto");
  auto Err = Replaces.add(ConflictReplacement);
  EXPECT_TRUE(checkReplacementError(std::move(Err),
                                    replacement_error::overlap_conflict,
                                    *Replaces.begin(), ConflictReplacement));

  EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
  EXPECT_EQ("line1\nother\nline3\nline4", Context.getRewrittenText(ID));
}

TEST_F(ReplacementTest, InvalidSourceLocationFailsApplyAll) {
  Replacements Replaces =
      toReplacements({Replacement(Context.Sources, SourceLocation(), 5, "2")});

  EXPECT_FALSE(applyAllReplacements(Replaces, Context.Rewrite));
}

TEST_F(ReplacementTest, MultipleFilesReplaceAndFormat) {
  // Column limit is 20.
  std::string Code1 = "Long *a =\n"
                      "    new Long();\n"
                      "long x = 1;";
  std::string Expected1 = "auto a = new Long();\n"
                          "long x =\n"
                          "    12345678901;";
  std::string Code2 = "int x = 123;\n"
                      "int y = 0;";
  std::string Expected2 = "int x =\n"
                          "    1234567890123;\n"
                          "int y = 10;";
  StringRef File1 = "format_1.cpp";
  StringRef File2 = "format_2.cpp";
  FileID ID1 = Context.createInMemoryFile(File1, Code1);
  FileID ID2 = Context.createInMemoryFile(File2, Code2);

  // Scrambled the order of replacements.
  std::map<std::string, Replacements> FileToReplaces;
  FileToReplaces[File1] = toReplacements(
      {tooling::Replacement(Context.Sources, Context.getLocation(ID1, 1, 1), 6,
                            "auto "),
       tooling::Replacement(Context.Sources, Context.getLocation(ID1, 3, 10), 1,
                            "12345678901")});
  FileToReplaces[File2] = toReplacements(
      {tooling::Replacement(Context.Sources, Context.getLocation(ID2, 1, 12), 0,
                            "4567890123"),
       tooling::Replacement(Context.Sources, Context.getLocation(ID2, 2, 9), 1,
                            "10")});
  EXPECT_TRUE(
      formatAndApplyAllReplacements(FileToReplaces, Context.Rewrite,
                                    "{BasedOnStyle: LLVM, ColumnLimit: 20}"));
  EXPECT_EQ(Expected1, Context.getRewrittenText(ID1));
  EXPECT_EQ(Expected2, Context.getRewrittenText(ID2));
}

TEST(ShiftedCodePositionTest, FindsNewCodePosition) {
  Replacements Replaces =
      toReplacements({Replacement("", 0, 1, ""), Replacement("", 4, 3, " ")});
  // Assume ' int   i;' is turned into 'int i;' and cursor is located at '|'.
  EXPECT_EQ(0u, Replaces.getShiftedCodePosition(0)); // |int   i;
  EXPECT_EQ(0u, Replaces.getShiftedCodePosition(1)); //  |nt   i;
  EXPECT_EQ(1u, Replaces.getShiftedCodePosition(2)); //  i|t   i;
  EXPECT_EQ(2u, Replaces.getShiftedCodePosition(3)); //  in|   i;
  EXPECT_EQ(3u, Replaces.getShiftedCodePosition(4)); //  int|  i;
  EXPECT_EQ(3u, Replaces.getShiftedCodePosition(5)); //  int | i;
  EXPECT_EQ(3u, Replaces.getShiftedCodePosition(6)); //  int  |i;
  EXPECT_EQ(4u, Replaces.getShiftedCodePosition(7)); //  int   |;
  EXPECT_EQ(5u, Replaces.getShiftedCodePosition(8)); //  int   i|
}

TEST(ShiftedCodePositionTest, FindsNewCodePositionWithInserts) {
  Replacements Replaces = toReplacements({Replacement("", 4, 0, "\"\n\"")});
  // Assume '"12345678"' is turned into '"1234"\n"5678"'.
  EXPECT_EQ(3u, Replaces.getShiftedCodePosition(3)); // "123|5678"
  EXPECT_EQ(7u, Replaces.getShiftedCodePosition(4)); // "1234|678"
  EXPECT_EQ(8u, Replaces.getShiftedCodePosition(5)); // "12345|78"
}

TEST(ShiftedCodePositionTest, FindsNewCodePositionInReplacedText) {
  // Replace the first four characters with "abcd".
  auto Replaces = toReplacements({Replacement("", 0, 4, "abcd")});
  for (unsigned i = 0; i < 3; ++i)
    EXPECT_EQ(i, Replaces.getShiftedCodePosition(i));
}

TEST(ShiftedCodePositionTest, NoReplacementText) {
  Replacements Replaces = toReplacements({Replacement("", 0, 42, "")});
  EXPECT_EQ(0u, Replaces.getShiftedCodePosition(0));
  EXPECT_EQ(0u, Replaces.getShiftedCodePosition(39));
  EXPECT_EQ(3u, Replaces.getShiftedCodePosition(45));
  EXPECT_EQ(0u, Replaces.getShiftedCodePosition(42));
}

class FlushRewrittenFilesTest : public ::testing::Test {
public:
   FlushRewrittenFilesTest() {}

   ~FlushRewrittenFilesTest() override {
    for (llvm::StringMap<std::string>::iterator I = TemporaryFiles.begin(),
                                                E = TemporaryFiles.end();
         I != E; ++I) {
      llvm::StringRef Name = I->second;
      std::error_code EC = llvm::sys::fs::remove(Name);
      (void)EC;
      assert(!EC);
    }
  }

  FileID createFile(llvm::StringRef Name, llvm::StringRef Content) {
    SmallString<1024> Path;
    int FD;
    std::error_code EC = llvm::sys::fs::createTemporaryFile(Name, "", FD, Path);
    assert(!EC);
    (void)EC;

    llvm::raw_fd_ostream OutStream(FD, true);
    OutStream << Content;
    OutStream.close();
    const FileEntry *File = Context.Files.getFile(Path);
    assert(File != nullptr);

    StringRef Found =
        TemporaryFiles.insert(std::make_pair(Name, Path.str())).first->second;
    assert(Found == Path);
    (void)Found;
    return Context.Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
  }

  std::string getFileContentFromDisk(llvm::StringRef Name) {
    std::string Path = TemporaryFiles.lookup(Name);
    assert(!Path.empty());
    // We need to read directly from the FileManager without relaying through
    // a FileEntry, as otherwise we'd read through an already opened file
    // descriptor, which might not see the changes made.
    // FIXME: Figure out whether there is a way to get the SourceManger to
    // reopen the file.
    auto FileBuffer = Context.Files.getBufferForFile(Path);
    return (*FileBuffer)->getBuffer();
  }

  llvm::StringMap<std::string> TemporaryFiles;
  RewriterTestContext Context;
};

TEST_F(FlushRewrittenFilesTest, StoresChangesOnDisk) {
  FileID ID = createFile("input.cpp", "line1\nline2\nline3\nline4");
  Replacements Replaces = toReplacements({Replacement(
      Context.Sources, Context.getLocation(ID, 2, 1), 5, "replaced")});
  EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
  EXPECT_FALSE(Context.Rewrite.overwriteChangedFiles());
  EXPECT_EQ("line1\nreplaced\nline3\nline4",
            getFileContentFromDisk("input.cpp"));
}

namespace {
template <typename T>
class TestVisitor : public clang::RecursiveASTVisitor<T> {
public:
  bool runOver(StringRef Code) {
    return runToolOnCode(new TestAction(this), Code);
  }

protected:
  clang::SourceManager *SM;
  clang::ASTContext *Context;

private:
  class FindConsumer : public clang::ASTConsumer {
  public:
    FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}

    void HandleTranslationUnit(clang::ASTContext &Context) override {
      Visitor->TraverseDecl(Context.getTranslationUnitDecl());
    }

  private:
    TestVisitor *Visitor;
  };

  class TestAction : public clang::ASTFrontendAction {
  public:
    TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}

    std::unique_ptr<clang::ASTConsumer>
    CreateASTConsumer(clang::CompilerInstance &compiler,
                      llvm::StringRef dummy) override {
      Visitor->SM = &compiler.getSourceManager();
      Visitor->Context = &compiler.getASTContext();
      /// TestConsumer will be deleted by the framework calling us.
      return llvm::make_unique<FindConsumer>(Visitor);
    }

  private:
    TestVisitor *Visitor;
  };
};
} // end namespace

void expectReplacementAt(const Replacement &Replace,
                         StringRef File, unsigned Offset, unsigned Length) {
  ASSERT_TRUE(Replace.isApplicable());
  EXPECT_EQ(File, Replace.getFilePath());
  EXPECT_EQ(Offset, Replace.getOffset());
  EXPECT_EQ(Length, Replace.getLength());
}

class ClassDeclXVisitor : public TestVisitor<ClassDeclXVisitor> {
public:
  bool VisitCXXRecordDecl(CXXRecordDecl *Record) {
    if (Record->getName() == "X") {
      Replace = Replacement(*SM, Record, "");
    }
    return true;
  }
  Replacement Replace;
};

TEST(Replacement, CanBeConstructedFromNode) {
  ClassDeclXVisitor ClassDeclX;
  EXPECT_TRUE(ClassDeclX.runOver("     class X;"));
  expectReplacementAt(ClassDeclX.Replace, "input.cc", 5, 7);
}

TEST(Replacement, ReplacesAtSpellingLocation) {
  ClassDeclXVisitor ClassDeclX;
  EXPECT_TRUE(ClassDeclX.runOver("#define A(Y) Y\nA(class X);"));
  expectReplacementAt(ClassDeclX.Replace, "input.cc", 17, 7);
}

class CallToFVisitor : public TestVisitor<CallToFVisitor> {
public:
  bool VisitCallExpr(CallExpr *Call) {
    if (Call->getDirectCallee()->getName() == "F") {
      Replace = Replacement(*SM, Call, "");
    }
    return true;
  }
  Replacement Replace;
};

TEST(Replacement, FunctionCall) {
  CallToFVisitor CallToF;
  EXPECT_TRUE(CallToF.runOver("void F(); void G() { F(); }"));
  expectReplacementAt(CallToF.Replace, "input.cc", 21, 3);
}

TEST(Replacement, TemplatedFunctionCall) {
  CallToFVisitor CallToF;
  EXPECT_TRUE(CallToF.runOver(
        "template <typename T> void F(); void G() { F<int>(); }"));
  expectReplacementAt(CallToF.Replace, "input.cc", 43, 8);
}

class NestedNameSpecifierAVisitor
    : public TestVisitor<NestedNameSpecifierAVisitor> {
public:
  bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLoc) {
    if (NNSLoc.getNestedNameSpecifier()) {
      if (const NamespaceDecl* NS = NNSLoc.getNestedNameSpecifier()->getAsNamespace()) {
        if (NS->getName() == "a") {
          Replace = Replacement(*SM, &NNSLoc, "", Context->getLangOpts());
        }
      }
    }
    return TestVisitor<NestedNameSpecifierAVisitor>::TraverseNestedNameSpecifierLoc(
        NNSLoc);
  }
  Replacement Replace;
};

TEST(Replacement, ColonColon) {
  NestedNameSpecifierAVisitor VisitNNSA;
  EXPECT_TRUE(VisitNNSA.runOver("namespace a { void f() { ::a::f(); } }"));
  expectReplacementAt(VisitNNSA.Replace, "input.cc", 25, 5);
}

TEST(Range, overlaps) {
  EXPECT_TRUE(Range(10, 10).overlapsWith(Range(0, 11)));
  EXPECT_TRUE(Range(0, 11).overlapsWith(Range(10, 10)));
  EXPECT_FALSE(Range(10, 10).overlapsWith(Range(0, 10)));
  EXPECT_FALSE(Range(0, 10).overlapsWith(Range(10, 10)));
  EXPECT_TRUE(Range(0, 10).overlapsWith(Range(2, 6)));
  EXPECT_TRUE(Range(2, 6).overlapsWith(Range(0, 10)));
}

TEST(Range, contains) {
  EXPECT_TRUE(Range(0, 10).contains(Range(0, 10)));
  EXPECT_TRUE(Range(0, 10).contains(Range(2, 6)));
  EXPECT_FALSE(Range(2, 6).contains(Range(0, 10)));
  EXPECT_FALSE(Range(0, 10).contains(Range(0, 11)));
}

TEST(Range, CalculateRangesOfReplacements) {
  // Before: aaaabbbbbbz
  // After : bbbbbbzzzzzzoooooooooooooooo
  Replacements Replaces = toReplacements(
      {Replacement("foo", 0, 4, ""), Replacement("foo", 10, 1, "zzzzzz"),
       Replacement("foo", 11, 0, "oooooooooooooooo")});

  std::vector<Range> Ranges = Replaces.getAffectedRanges();

  EXPECT_EQ(2ul, Ranges.size());
  EXPECT_TRUE(Ranges[0].getOffset() == 0);
  EXPECT_TRUE(Ranges[0].getLength() == 0);
  EXPECT_TRUE(Ranges[1].getOffset() == 6);
  EXPECT_TRUE(Ranges[1].getLength() == 22);
}

TEST(Range, CalculateRangesOfInsertionAroundReplacement) {
  Replacements Replaces = toReplacements(
      {Replacement("foo", 0, 2, ""), Replacement("foo", 0, 0, "ba")});

  std::vector<Range> Ranges = Replaces.getAffectedRanges();

  EXPECT_EQ(1ul, Ranges.size());
  EXPECT_EQ(0u, Ranges[0].getOffset());
  EXPECT_EQ(2u, Ranges[0].getLength());
}

TEST(Range, RangesAfterEmptyReplacements) {
  std::vector<Range> Ranges = {Range(5, 6), Range(10, 5)};
  Replacements Replaces;
  std::vector<Range> Expected = {Range(5, 10)};
  EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
}

TEST(Range, RangesAfterReplacements) {
  std::vector<Range> Ranges = {Range(5, 2), Range(10, 5)};
  Replacements Replaces = toReplacements({Replacement("foo", 0, 2, "1234")});
  std::vector<Range> Expected = {Range(0, 4), Range(7, 2), Range(12, 5)};
  EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
}

TEST(Range, RangesBeforeReplacements) {
  std::vector<Range> Ranges = {Range(5, 2), Range(10, 5)};
  Replacements Replaces = toReplacements({Replacement("foo", 20, 2, "1234")});
  std::vector<Range> Expected = {Range(5, 2), Range(10, 5), Range(20, 4)};
  EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
}

TEST(Range, NotAffectedByReplacements) {
  std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(10, 5)};
  Replacements Replaces = toReplacements({Replacement("foo", 3, 2, "12"),
                                          Replacement("foo", 12, 2, "12"),
                                          Replacement("foo", 20, 5, "")});
  std::vector<Range> Expected = {Range(0, 2), Range(3, 4), Range(10, 5),
                                 Range(20, 0)};
  EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
}

TEST(Range, RangesWithNonOverlappingReplacements) {
  std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(10, 5)};
  Replacements Replaces = toReplacements({Replacement("foo", 3, 1, ""),
                                          Replacement("foo", 6, 1, "123"),
                                          Replacement("foo", 20, 2, "12345")});
  std::vector<Range> Expected = {Range(0, 2), Range(3, 0), Range(4, 4),
                                 Range(11, 5), Range(21, 5)};
  EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
}

TEST(Range, RangesWithOverlappingReplacements) {
  std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(15, 5),
                               Range(30, 5)};
  Replacements Replaces = toReplacements(
      {Replacement("foo", 1, 3, ""), Replacement("foo", 6, 1, "123"),
       Replacement("foo", 13, 3, "1"), Replacement("foo", 25, 15, "")});
  std::vector<Range> Expected = {Range(0, 1), Range(2, 4), Range(12, 5),
                                 Range(22, 0)};
  EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
}

TEST(Range, MergeIntoOneRange) {
  std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(15, 5)};
  Replacements Replaces =
      toReplacements({Replacement("foo", 1, 15, "1234567890")});
  std::vector<Range> Expected = {Range(0, 15)};
  EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
}

TEST(Range, ReplacementsStartingAtRangeOffsets) {
  std::vector<Range> Ranges = {Range(0, 2), Range(5, 5), Range(15, 5)};
  Replacements Replaces = toReplacements(
      {Replacement("foo", 0, 2, "12"), Replacement("foo", 5, 1, "123"),
       Replacement("foo", 7, 4, "12345"), Replacement("foo", 15, 10, "12")});
  std::vector<Range> Expected = {Range(0, 2), Range(5, 9), Range(18, 2)};
  EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
}

TEST(Range, ReplacementsEndingAtRangeEnds) {
  std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(15, 5)};
  Replacements Replaces = toReplacements(
      {Replacement("foo", 6, 1, "123"), Replacement("foo", 17, 3, "12")});
  std::vector<Range> Expected = {Range(0, 2), Range(5, 4), Range(17, 4)};
  EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
}

TEST(Range, AjacentReplacements) {
  std::vector<Range> Ranges = {Range(0, 0), Range(15, 5)};
  Replacements Replaces = toReplacements(
      {Replacement("foo", 1, 2, "123"), Replacement("foo", 12, 3, "1234")});
  std::vector<Range> Expected = {Range(0, 0), Range(1, 3), Range(13, 9)};
  EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
}

TEST(Range, MergeRangesAfterReplacements) {
  std::vector<Range> Ranges = {Range(8, 0), Range(5, 2), Range(9, 0), Range(0, 1)};
  Replacements Replaces = toReplacements({Replacement("foo", 1, 3, ""),
                                          Replacement("foo", 7, 0, "12"),
                                          Replacement("foo", 9, 2, "")});
  std::vector<Range> Expected = {Range(0, 1), Range(2, 4), Range(7, 0),
                                 Range(8, 0)};
  EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
}

TEST(Range, ConflictingRangesBeforeReplacements) {
  std::vector<Range> Ranges = {Range(8, 3), Range(5, 4), Range(9, 1)};
  Replacements Replaces = toReplacements({Replacement("foo", 1, 3, "")});
  std::vector<Range> Expected = {Range(1, 0), Range(2, 6)};
  EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
}

class MergeReplacementsTest : public ::testing::Test {
protected:
  void mergeAndTestRewrite(StringRef Code, StringRef Intermediate,
                           StringRef Result, const Replacements &First,
                           const Replacements &Second) {
    // These are mainly to verify the test itself and make it easier to read.
    auto AfterFirst = applyAllReplacements(Code, First);
    EXPECT_TRUE(static_cast<bool>(AfterFirst));
    auto InSequenceRewrite = applyAllReplacements(*AfterFirst, Second);
    EXPECT_TRUE(static_cast<bool>(InSequenceRewrite));
    EXPECT_EQ(Intermediate, *AfterFirst);
    EXPECT_EQ(Result, *InSequenceRewrite);

    tooling::Replacements Merged = First.merge(Second);
    auto MergedRewrite = applyAllReplacements(Code, Merged);
    EXPECT_TRUE(static_cast<bool>(MergedRewrite));
    EXPECT_EQ(*InSequenceRewrite, *MergedRewrite);
    if (*InSequenceRewrite != *MergedRewrite)
      for (tooling::Replacement M : Merged)
        llvm::errs() << M.getOffset() << " " << M.getLength() << " "
                     << M.getReplacementText() << "\n";
  }
  void mergeAndTestRewrite(StringRef Code, const Replacements &First,
                           const Replacements &Second) {
    auto AfterFirst = applyAllReplacements(Code, First);
    EXPECT_TRUE(static_cast<bool>(AfterFirst));
    auto InSequenceRewrite = applyAllReplacements(*AfterFirst, Second);
    tooling::Replacements Merged = First.merge(Second);
    auto MergedRewrite = applyAllReplacements(Code, Merged);
    EXPECT_TRUE(static_cast<bool>(MergedRewrite));
    EXPECT_EQ(*InSequenceRewrite, *MergedRewrite);
    if (*InSequenceRewrite != *MergedRewrite)
      for (tooling::Replacement M : Merged)
        llvm::errs() << M.getOffset() << " " << M.getLength() << " "
                     << M.getReplacementText() << "\n";
  }
};

TEST_F(MergeReplacementsTest, Offsets) {
  mergeAndTestRewrite("aaa", "aabab", "cacabab",
                      toReplacements({{"", 2, 0, "b"}, {"", 3, 0, "b"}}),
                      toReplacements({{"", 0, 0, "c"}, {"", 1, 0, "c"}}));
  mergeAndTestRewrite("aaa", "babaa", "babacac",
                      toReplacements({{"", 0, 0, "b"}, {"", 1, 0, "b"}}),
                      toReplacements({{"", 4, 0, "c"}, {"", 5, 0, "c"}}));
  mergeAndTestRewrite("aaaa", "aaa", "aac", toReplacements({{"", 1, 1, ""}}),
                      toReplacements({{"", 2, 1, "c"}}));

  mergeAndTestRewrite("aa", "bbabba", "bbabcba",
                      toReplacements({{"", 0, 0, "bb"}, {"", 1, 0, "bb"}}),
                      toReplacements({{"", 4, 0, "c"}}));
}

TEST_F(MergeReplacementsTest, Concatenations) {
  // Basic concatenations. It is important to merge these into a single
  // replacement to ensure the correct order.
  {
    auto First = toReplacements({{"", 0, 0, "a"}});
    auto Second = toReplacements({{"", 1, 0, "b"}});
    EXPECT_EQ(toReplacements({{"", 0, 0, "ab"}}), First.merge(Second));
  }
  {
    auto First = toReplacements({{"", 0, 0, "a"}});
    auto Second = toReplacements({{"", 0, 0, "b"}});
    EXPECT_EQ(toReplacements({{"", 0, 0, "ba"}}), First.merge(Second));
  }
  mergeAndTestRewrite("", "a", "ab", toReplacements({{"", 0, 0, "a"}}),
                      toReplacements({{"", 1, 0, "b"}}));
  mergeAndTestRewrite("", "a", "ba", toReplacements({{"", 0, 0, "a"}}),
                      toReplacements({{"", 0, 0, "b"}}));
}

TEST_F(MergeReplacementsTest, NotChangingLengths) {
  mergeAndTestRewrite("aaaa", "abba", "acca",
                      toReplacements({{"", 1, 2, "bb"}}),
                      toReplacements({{"", 1, 2, "cc"}}));
  mergeAndTestRewrite("aaaa", "abba", "abcc",
                      toReplacements({{"", 1, 2, "bb"}}),
                      toReplacements({{"", 2, 2, "cc"}}));
  mergeAndTestRewrite("aaaa", "abba", "ccba",
                      toReplacements({{"", 1, 2, "bb"}}),
                      toReplacements({{"", 0, 2, "cc"}}));
  mergeAndTestRewrite("aaaaaa", "abbdda", "abccda",
                      toReplacements({{"", 1, 2, "bb"}, {"", 3, 2, "dd"}}),
                      toReplacements({{"", 2, 2, "cc"}}));
}

TEST_F(MergeReplacementsTest, OverlappingRanges) {
  mergeAndTestRewrite("aaa", "bbd", "bcbcd",
                      toReplacements({{"", 0, 1, "bb"}, {"", 1, 2, "d"}}),
                      toReplacements({{"", 1, 0, "c"}, {"", 2, 0, "c"}}));

  mergeAndTestRewrite("aaaa", "aabbaa", "acccca",
                      toReplacements({{"", 2, 0, "bb"}}),
                      toReplacements({{"", 1, 4, "cccc"}}));
  mergeAndTestRewrite("aaaa", "aababa", "acccca",
                      toReplacements({{"", 2, 0, "b"}, {"", 3, 0, "b"}}),
                      toReplacements({{"", 1, 4, "cccc"}}));
  mergeAndTestRewrite("aaaaaa", "abbbba", "abba",
                      toReplacements({{"", 1, 4, "bbbb"}}),
                      toReplacements({{"", 2, 2, ""}}));
  mergeAndTestRewrite("aaaa", "aa", "cc",
                      toReplacements({{"", 1, 1, ""}, {"", 2, 1, ""}}),
                      toReplacements({{"", 0, 2, "cc"}}));
  mergeAndTestRewrite("aa", "abbba", "abcbcba",
                      toReplacements({{"", 1, 0, "bbb"}}),
                      toReplacements({{"", 2, 0, "c"}, {"", 3, 0, "c"}}));

  mergeAndTestRewrite(
      "aaa", "abbab", "ccdd",
      toReplacements({{"", 0, 1, ""}, {"", 2, 0, "bb"}, {"", 3, 0, "b"}}),
      toReplacements({{"", 0, 2, "cc"}, {"", 2, 3, "dd"}}));
  mergeAndTestRewrite(
      "aa", "babbab", "ccdd",
      toReplacements({{"", 0, 0, "b"}, {"", 1, 0, "bb"}, {"", 2, 0, "b"}}),
      toReplacements({{"", 0, 3, "cc"}, {"", 3, 3, "dd"}}));
}

TEST(DeduplicateByFileTest, PathsWithDots) {
  std::map<std::string, Replacements> FileToReplaces;
  llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> VFS(
      new vfs::InMemoryFileSystem());
  FileManager FileMgr(FileSystemOptions(), VFS);
#if !defined(LLVM_ON_WIN32)
  StringRef Path1 = "a/b/.././c.h";
  StringRef Path2 = "a/c.h";
#else
  StringRef Path1 = "a\\b\\..\\.\\c.h";
  StringRef Path2 = "a\\c.h";
#endif
  EXPECT_TRUE(VFS->addFile(Path1, 0, llvm::MemoryBuffer::getMemBuffer("")));
  EXPECT_TRUE(VFS->addFile(Path2, 0, llvm::MemoryBuffer::getMemBuffer("")));
  FileToReplaces[Path1] = Replacements();
  FileToReplaces[Path2] = Replacements();
  FileToReplaces = groupReplacementsByFile(FileMgr, FileToReplaces);
  EXPECT_EQ(1u, FileToReplaces.size());
  EXPECT_EQ(Path1, FileToReplaces.begin()->first);
}

TEST(DeduplicateByFileTest, PathWithDotSlash) {
  std::map<std::string, Replacements> FileToReplaces;
  llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> VFS(
      new vfs::InMemoryFileSystem());
  FileManager FileMgr(FileSystemOptions(), VFS);
#if !defined(LLVM_ON_WIN32)
  StringRef Path1 = "./a/b/c.h";
  StringRef Path2 = "a/b/c.h";
#else
  StringRef Path1 = ".\\a\\b\\c.h";
  StringRef Path2 = "a\\b\\c.h";
#endif
  EXPECT_TRUE(VFS->addFile(Path1, 0, llvm::MemoryBuffer::getMemBuffer("")));
  EXPECT_TRUE(VFS->addFile(Path2, 0, llvm::MemoryBuffer::getMemBuffer("")));
  FileToReplaces[Path1] = Replacements();
  FileToReplaces[Path2] = Replacements();
  FileToReplaces = groupReplacementsByFile(FileMgr, FileToReplaces);
  EXPECT_EQ(1u, FileToReplaces.size());
  EXPECT_EQ(Path1, FileToReplaces.begin()->first);
}

TEST(DeduplicateByFileTest, NonExistingFilePath) {
  std::map<std::string, Replacements> FileToReplaces;
  llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> VFS(
      new vfs::InMemoryFileSystem());
  FileManager FileMgr(FileSystemOptions(), VFS);
#if !defined(LLVM_ON_WIN32)
  StringRef Path1 = "./a/b/c.h";
  StringRef Path2 = "a/b/c.h";
#else
  StringRef Path1 = ".\\a\\b\\c.h";
  StringRef Path2 = "a\\b\\c.h";
#endif
  FileToReplaces[Path1] = Replacements();
  FileToReplaces[Path2] = Replacements();
  FileToReplaces = groupReplacementsByFile(FileMgr, FileToReplaces);
  EXPECT_TRUE(FileToReplaces.empty());
}

} // end namespace tooling
} // end namespace clang


text:
package org.machine.engine.communication.services

import akka.actor.{Actor, ActorLogging, Props}
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.unmarshalling.Unmarshal

import com.typesafe.scalalogging.{LazyLogging}
import scala.collection.mutable.ArrayBuffer
import spray.json._

import org.machine.engine.Engine
import org.machine.engine.authentication.PasswordTools
import org.machine.engine.graph.Neo4JHelper
import org.machine.engine.graph.nodes.Credential
import org.machine.engine.graph.commands.GraphCommandOptions

trait LoginUserServiceJsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val loginRequestFormat = jsonFormat2(LoginRequest)
  implicit val loginResponseFormat = jsonFormat2(LoginResponse)
  implicit val userLoginResponseFormat = jsonFormat1(UserLoginResponse)
}

case class LoginRequest(userName: String, password: String)
case class LoginResponse(status: Int, userId: String)
case class UserLoginResponse(userId: String)

object LoginUserServiceActor {
  def props(): Props = {
    Props(classOf[LoginUserServiceActor])
  }
}

class LoginUserServiceActor extends Actor with ActorLogging{
  import Neo4JHelper._
  import PasswordTools._;
  def receive = {
    case request: LoginRequest => {
      sender() ! attemptLoginUser(request)
    }
  }

  private def attemptLoginUser(request: LoginRequest):LoginResponse = {
    val credential = findPassword(request)
    var response:LoginResponse = LoginResponse(401, null);
    credential.foreach(cred => {
      val saltHash = base64ToHash(cred.passwordSalt)
      val providedPwdHash:Array[Byte] = generateHash(request.password, saltHash, cred.hashIterationCount)
      val originalPwdHash = base64ToHash(cred.passwordHash)
      val passwordMatch = compare(originalPwdHash, providedPwdHash)
      if (passwordMatch){
        response = LoginResponse(200, cred.userId)
      }
    })
    return response
  }

  private def findPassword(request: LoginRequest): Option[Credential] = {
    val findPasswordQuery = """
    | match (u:user)-[:authenticates_with]->(c:credential)
    | where u.user_name = {userName}
    | return u.mid as userId,
    |   c.mid as mid,
    |   c.password_hash as passwordHash,
    |   c.password_salt as passwordSalt,
    |   c.hash_iteration_count as hashIterationCount,
    |   c.creation_time as creationTime,
    |   c.last_modified_time as lastModifiedTime
    """.stripMargin
    val params = GraphCommandOptions().addOption("userName", request.userName)
    val credentials = query[Credential](Engine.getInstance.database,
      findPasswordQuery,
      params.toJavaMap,
      credentialsMapper)
    return if (credentials.isEmpty) None else Some(credentials.head)
  }

  private def credentialsMapper(results: ArrayBuffer[Credential],
    record: java.util.Map[java.lang.String, Object]):Unit = {
      val userId: String = record.get("userId").toString()
      val id:String = record.get("mid").toString()
      val passwordHash:String = record.get("passwordHash").toString()
      val passwordSalt:String = record.get("passwordSalt").toString()
      val hashIterationCount:Int = record.get("hashIterationCount").asInstanceOf[Int]
      val creationTime:Long = record.get("creationTime").asInstanceOf[Long]
      val lastModifiedTime:Long = record.get("lastModifiedTime").asInstanceOf[Long]
      results += new Credential(userId, id, passwordHash, passwordSalt, hashIterationCount, creationTime, lastModifiedTime)
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.agilos.zendesk_jira_plugin.testframework;

public class ProjectRoles {

}


text:
jQueryTouchPlugin
=================

jQuery TouchPlugin

usage

1. link jQuery
2. link vinytouch.js

============================================
short touch

$(Selector).touch(function(){console.log("hello");},"pressed style css class name");

============================================

long touch

$(Selector).longtouch(function(){console.log("hello");},"pressed style css class name");

*. When you are pressing button , CallBack continously invoke

  if you want to control invoke time , you have to use option like below

$(Selector).longtouch(function(){console.log("hello");},"pressed style css class name",{time:200});

============================================

this library tested in Android 4.0+ , iOS 4.0 + , Chrome , Safari (dont support IE , I made for Mobile Web or Mobile WebApp)

=============================================

example)

$(".btn").touch(function(){console.log("touched!!");},"btn_presss");

$(".btn_long").longtouch(function(){console.log("long touched Callback!!");},"btn_presss");

$(".btn_long_3000").longtouch(function(){console.log("long touched Callback!! -3000ms");},"btn_presss",{time:3000});


text:
package org.estatio.module.capex.dom.invoice;

import java.math.BigDecimal;

import org.junit.Before;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class IncomingInvoice_Validator_validateForAmounts_Test {

    String invoiceAtPath;

    IncomingInvoice invoice;
    IncomingInvoiceItem item;

    IncomingInvoice.Validator validator;

    @Before
    public void setUp() throws Exception {
        validator = new IncomingInvoice.Validator();

        invoice = new IncomingInvoice() {
            @Override public String getAtPath() {
                return invoiceAtPath;
            }
        };
        item = new IncomingInvoiceItem(){
            @Override void invalidateApproval() {
            }
        };
    }

    @Test
    public void when_gross_amount_not_set_validation_is_skipped() throws Exception {

        // given
        invoice.setNetAmount(bd("100.00"));
        invoice.setGrossAmount(null);

        // when
        final String result = validator.validateForAmounts(invoice).getResult();

        // then
        assertThat(result).isNull();
    }

    @Test
    public void when_net_amount_not_set_validation_is_skipped() throws Exception {

        // given
        invoice.setGrossAmount(bd("100.00"));
        invoice.setNetAmount(null);

        // when
        final String result = validator.validateForAmounts(invoice).getResult();

        // then
        assertThat(result).isNull();
    }

    @Test
    public void net_amount_does_not_match() throws Exception {

        // given
        invoice.setNetAmount(bd("100.00"));
        invoice.setGrossAmount(BigDecimal.ZERO);

        // when
        final String result = validator.validateForAmounts(invoice).getResult();

        // then
        assertThat(result).isEqualTo("total amount on items equal to amount on the invoice required");

    }

    @Test
    public void gross_amount_does_not_match() throws Exception {

        // given
        invoice.setNetAmount(BigDecimal.ZERO);
        invoice.setGrossAmount(bd("100.00"));

        // when
        final String result = validator.validateForAmounts(invoice).getResult();

        // then
        assertThat(result).isEqualTo("total amount on items equal to amount on the invoice required");
    }

    @Test
    public void when_has_items_and_amounts_do_match() throws Exception {

        // and given
        invoice.setNetAmount(bd("90.00"));
        invoice.setGrossAmount(bd("100.00"));
        assertThat(invoice.getVatAmount()).isEqualTo(bd("10.00"));

        item.setNetAmount(bd("90.00"));
        item.setGrossAmount(bd("100.00"));
        item.setVatAmount(bd("10.00"));
        invoice.getItems().add(item);

        // when
        final String result = validator.validateForAmounts(invoice).getResult();

        // then
        assertThat(result).isNull();
    }

    @Test
    public void vat_amount_does_not_match() throws Exception {

        // given
        invoice.setNetAmount(bd("90.00"));
        invoice.setGrossAmount(bd("100.00"));
        assertThat(invoice.getVatAmount()).isEqualTo(bd("10.00"));

        item.setNetAmount(bd("90.00"));
        item.setGrossAmount(bd("100.00"));
        item.setVatAmount(bd("11.00")); // should be 10.00
        invoice.getItems().add(item);

        // when
        final String result = validator.validateForAmounts(invoice).getResult();

        // then
        assertThat(result).isEqualTo("total amount on items equal to amount on the invoice required");
    }

    @Test
    public void when_italian_then_no_check() throws Exception {

        // given
        invoice.setNetAmount(bd("90.00"));
        invoice.setGrossAmount(bd("100.00"));
        assertThat(invoice.getVatAmount()).isEqualTo(bd("10.00"));

        item.setNetAmount(bd("90.00"));
        item.setGrossAmount(bd("100.00"));
        item.setVatAmount(bd("11.00")); // should be 10.00
        invoice.getItems().add(item);

        // and also
        invoiceAtPath = "/ITA";

        // when
        final String result = validator.validateForAmounts(invoice).getResult();

        // then
        assertThat(result).isNull();
    }

    @Test
    public void when_all_zero_no_items_and_amounts_do_match() throws Exception {

        // given
        invoice.setGrossAmount(BigDecimal.ZERO);
        invoice.setNetAmount(BigDecimal.ZERO);

        // when
        final String result = validator.validateForAmounts(invoice).getResult();

        // then
        assertThat(result).isNull();
    }

    private static BigDecimal bd(final String val) {
        return new BigDecimal(val);
    }

}


text:
package edu.uci.isr.xarch.types;

import org.w3c.dom.*;

import edu.uci.isr.xarch.*;

import java.util.*;

/**
 * DOM-Based implementation of the IPrescribedInterfaceInstance interface.
 *
 * @author Automatically generated by xArch apigen.
 */
public class PrescribedInterfaceInstanceImpl extends edu.uci.isr.xarch.instance.InterfaceInstanceImpl implements
IPrescribedInterfaceInstance, edu.uci.isr.xarch.instance.IInterfaceInstance, DOMBased{

	public static final String XSD_TYPE_NSURI = TypesConstants.NS_URI;
	public static final String XSD_TYPE_NAME = "PrescribedInterfaceInstance";

	/** Tag name for structures in this object. */
	public static final String STRUCTURE_ELT_NAME = "structure";

	private static SequenceOrder seqOrderAppend = new SequenceOrder(
		new QName[]{
			new QName(TypesConstants.NS_URI, STRUCTURE_ELT_NAME)
		}
	);

	public PrescribedInterfaceInstanceImpl(Element elt){
		super(elt);
	}

	protected static SequenceOrder getSequenceOrder(){
		return new SequenceOrder(edu.uci.isr.xarch.instance.InterfaceInstanceImpl.getSequenceOrder(), seqOrderAppend);
	}

	public IXArchElement cloneElement(int depth){
		synchronized(DOMUtils.getDOMLock(elt)){
			Document doc = elt.getOwnerDocument();
			if(depth == 0){
				Element cloneElt = (Element)elt.cloneNode(false);
				cloneElt = (Element)doc.importNode(cloneElt, true);
				PrescribedInterfaceInstanceImpl cloneImpl = new PrescribedInterfaceInstanceImpl(cloneElt);
				cloneImpl.setXArch(getXArch());
				return cloneImpl;
			}
			else if(depth == 1){
				Element cloneElt = (Element)elt.cloneNode(false);
				cloneElt = (Element)doc.importNode(cloneElt, true);
				PrescribedInterfaceInstanceImpl cloneImpl = new PrescribedInterfaceInstanceImpl(cloneElt);
				cloneImpl.setXArch(getXArch());

				NodeList nl = elt.getChildNodes();
				int size = nl.getLength();
				for(int i = 0; i < size; i++){
					Node n = nl.item(i);
					Node cloneNode = (Node)n.cloneNode(false);
					cloneNode = doc.importNode(cloneNode, true);
					cloneElt.appendChild(cloneNode);
				}
				return cloneImpl;
			}
			else /* depth = infinity */{
				Element cloneElt = (Element)elt.cloneNode(true);
				cloneElt = (Element)doc.importNode(cloneElt, true);
				PrescribedInterfaceInstanceImpl cloneImpl = new PrescribedInterfaceInstanceImpl(cloneElt);
				cloneImpl.setXArch(getXArch());
				return cloneImpl;
			}
		}
	}

	/**
	 * For internal use only.
	 */
	private static Object makeDerivedWrapper(Element elt, String baseTypeName){
		synchronized(DOMUtils.getDOMLock(elt)){
			QName typeName = XArchUtils.getXSIType(elt);
			if(typeName == null){
				return null;
			}
			else{
				if(!DOMUtils.hasXSIType(elt, "http://www.ics.uci.edu/pub/arch/xArch/types.xsd", baseTypeName)){
					try{
						String packageTitle = XArchUtils.getPackageTitle(typeName.getNamespaceURI());
						String packageName = XArchUtils.getPackageName(packageTitle);
						String implName = XArchUtils.getImplName(packageName, typeName.getName());
						Class c = Class.forName(implName);
						java.lang.reflect.Constructor con = c.getConstructor(new Class[]{Element.class});
						Object o = con.newInstance(new Object[]{elt});
						return o;
					}
					catch(Exception e){
						//Lots of bad things could happen, but this
						//is OK, because this is best-effort anyway.
					}
				}
				return null;
			}
		}
	}

	public XArchTypeMetadata getTypeMetadata(){
		return IPrescribedInterfaceInstance.TYPE_METADATA;
	}

	public XArchInstanceMetadata getInstanceMetadata(){
		return new XArchInstanceMetadata(XArchUtils.getPackageTitle(elt.getNamespaceURI()));
	}

	public void setStructure(edu.uci.isr.xarch.instance.IXMLLink value){
		if(!(value instanceof DOMBased)){
			throw new IllegalArgumentException("Cannot handle non-DOM-based xArch entities.");
		}
		{
			edu.uci.isr.xarch.instance.IXMLLink oldElt = getStructure();
			DOMUtils.removeChildren(elt, TypesConstants.NS_URI, STRUCTURE_ELT_NAME);

			IXArch context = getXArch();
			if(context != null){
				context.fireXArchEvent(
					new XArchEvent(this,
					XArchEvent.CLEAR_EVENT,
					XArchEvent.ELEMENT_CHANGED,
					"structure", oldElt,
					XArchUtils.getDefaultXArchImplementation().isContainedIn(xArch, this), true)
				);
			}
		}
		Element newChildElt = (Element)(((DOMBased)value).getDOMNode());
		newChildElt = DOMUtils.cloneAndRename(newChildElt, TypesConstants.NS_URI, STRUCTURE_ELT_NAME);
		((DOMBased)value).setDOMNode(newChildElt);

		synchronized(DOMUtils.getDOMLock(elt)){
			elt.appendChild(newChildElt);
			DOMUtils.order(elt, getSequenceOrder());
		}

		IXArch context = getXArch();
		if(context != null){
			context.fireXArchEvent(
				new XArchEvent(this,
				XArchEvent.SET_EVENT,
				XArchEvent.ELEMENT_CHANGED,
				"structure", value,
				XArchUtils.getDefaultXArchImplementation().isContainedIn(xArch, this))
			);
		}
	}

	public void clearStructure(){
		edu.uci.isr.xarch.instance.IXMLLink oldElt = getStructure();
		DOMUtils.removeChildren(elt, TypesConstants.NS_URI, STRUCTURE_ELT_NAME);

		IXArch context = getXArch();
		if(context != null){
			context.fireXArchEvent(
				new XArchEvent(this,
				XArchEvent.CLEAR_EVENT,
				XArchEvent.ELEMENT_CHANGED,
				"structure", oldElt,
				XArchUtils.getDefaultXArchImplementation().isContainedIn(xArch, this))
			);
		}
	}

	public edu.uci.isr.xarch.instance.IXMLLink getStructure(){
		NodeList nl = DOMUtils.getChildren(elt, TypesConstants.NS_URI, STRUCTURE_ELT_NAME);
		if(nl.getLength() == 0){
			return null;
		}
		else{
			Element el = (Element)nl.item(0);
			IXArch de = getXArch();
			if(de != null){
				IXArchElement cachedXArchElt = de.getWrapper(el);
				if(cachedXArchElt != null){
					return (edu.uci.isr.xarch.instance.IXMLLink)cachedXArchElt;
				}
			}

			Object o = makeDerivedWrapper(el, "XMLLink");
			if(o != null){
				try{
					((edu.uci.isr.xarch.IXArchElement)o).setXArch(getXArch());
					if(de != null){
						de.cacheWrapper(el, ((edu.uci.isr.xarch.IXArchElement)o));
					}
					return (edu.uci.isr.xarch.instance.IXMLLink)o;
				}
				catch(Exception e){}
			}
			edu.uci.isr.xarch.instance.XMLLinkImpl eltImpl = new edu.uci.isr.xarch.instance.XMLLinkImpl(el);
			eltImpl.setXArch(getXArch());
			if(de != null){
				de.cacheWrapper(el, ((edu.uci.isr.xarch.IXArchElement)eltImpl));
			}
			return eltImpl;
		}
	}

	public boolean hasStructure(edu.uci.isr.xarch.instance.IXMLLink value){
		edu.uci.isr.xarch.instance.IXMLLink thisValue = getStructure();
		edu.uci.isr.xarch.instance.IXMLLink thatValue = value;

		if((thisValue == null) && (thatValue == null)){
			return true;
		}
		else if((thisValue == null) && (thatValue != null)){
			return false;
		}
		else if((thisValue != null) && (thatValue == null)){
			return false;
		}
		return thisValue.isEquivalent(thatValue);
	}

	public boolean isEquivalent(IPrescribedInterfaceInstance c){
		return
			super.isEquivalent(c) &&
			hasStructure(c.getStructure()) ;
	}

}


text:
name: Xamarin.iOS - WatchKit Catalog
description: "This sample is for use with the Xamarin watchOS 3 preview that was release along with our iOS 10 support (watchOS)"
page_type: sample
languages:
- csharp
products:
- xamarin
extensions:
    tags:
    - watchos
urlFragment: watchos-watchkitcatalog
---
# WatchKit Catalog (watchOS 3)

## Xamarin watchOS 3 Preview

This sample is for use with the Xamarin watchOS 3 preview that was release along with our [iOS 10 support](https://devblogs.microsoft.com/xamarin/let-the-ios10-ing-begin/).

1. Right-click the **WatchApp3** project and select **Set as startup project**.
2. The simulator list should change to display 38mm and 42mm watch options.
3. With a *watch simulator* selected, start debugging.

![Apple Watch screen](Screenshots/watchOS3-sml.png) ![Apple Watch screen](Screenshots/watchCatalog3-sml.png)

^ Screenshots are shown with the iOS Simulator running inside [Bezel].

![WatchKit Catalog (watchOS 3) application screenshot](Screenshots/0.png "WatchKit Catalog (watchOS 3) application screenshot")

## Using WatchKit Interface Elements

WatchKit Catalog is an exploration of the UI elements available in the WatchKit framework.
Throughout the sample, you'll find tips and configurations that will help guide the development of your watchOS app.

### WatchKit Controls

WatchKit Catalog demonstrates how to configure and customize the following controls:

- WKInterfaceController
- WKInterfaceDevice
- WKInterfaceGroup
- WKInterfaceImage
- WKInterfaceLabel
- WKInterfaceMap
- WKInterfaceMovie and WKInterfaceInlineMovie
- WKInterfaceSeparator
- WKInterfaceSlider
- WKInterfaceSwitch
- WKInterfaceTable
- WKInterfaceTimer
- WKUserNotificationInterfaceController
- IWKCrownDelegate and CrownSequencer
- Gesture Recognizers

### Tips

- ButtonDetailController has two examples of how to hide and show UI elements at runtime. First, tapping on button "1" will toggle the hidden property of button "2." When hiding the button, the layout will change to make use of the newly available space. When showing it again, the layout will change to make room for it. The second example is by setting the alpha property of button "2" to 0.0 or 1.0. Tapping on button "3" will toggle this and while button "2" may look invisible, the space it takes up does not change and no layout changes will occur.

- WKInterfaceDevice's screenBounds property is used in ImageDetailController to decide which image resource to load at runtime, depending on the wearer having a 38mm or 42mm Apple Watch. This can be more easily accomplished with images in an Asset Catalog.

- In the storyboard scene for GroupDetailController, note the use of nested groups to achieve more sophisticated layouts of images and labels. This is highly encouraged and will be necessary to achieve specific designs.

- TableDetailController has an example of inserting more rows into a table after the initial set of rows have been added to a table.

- ControllerDetailController shows how to present a modal controller, as well as how to present a controller that does not match the navigation style of your root controller. In this case, the app has a hierarchical navigation style. Using the presentation of a modal controller though, we are able to present a page-based set of controllers.

- ControllerDetailController can present a modal controller. The "Dismiss" text of the modal controller is set in the Title field in the Attributes Inspector of the scene for PageController.

- TextInputController presents the text input controller with a set of suggestions. The result is sent to the parent iOS application and a confirmation message is sent back to the WatchKit app extension.

## Build/Runtime Requirements

- Xcode 8.0 (or newer)
- Xamarin Studio 6.10 or newer
- Xamarin.iOS 10

## License

Xamarin port changes are released under the MIT license

*Watch screenshots use [Bezel] courtesy of [infinitapps] :)*

[Bezel]:http://infinitapps.com/bezel/
[infinitapps]:http://infinitapps.com/


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

package org.chromium.native_test;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Process;
import android.system.Os;

import org.chromium.base.Log;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.test.util.UrlUtils;
import org.chromium.build.gtest_apk.NativeTestIntent;
import org.chromium.test.reporter.TestStatusReporter;

import java.io.File;

/**
 *  Helper to run tests inside Activity or NativeActivity.
 */
@JNINamespace("testing::android")
public class NativeTest {
    private static final String TAG = "NativeTest";

    private String mCommandLineFilePath;
    private StringBuilder mCommandLineFlags = new StringBuilder();
    private TestStatusReporter mReporter;
    private boolean mRunInSubThread;
    private String mStdoutFilePath;

    private static class ReportingUncaughtExceptionHandler
            implements Thread.UncaughtExceptionHandler {

        private TestStatusReporter mReporter;
        private Thread.UncaughtExceptionHandler mWrappedHandler;

        public ReportingUncaughtExceptionHandler(TestStatusReporter reporter,
                Thread.UncaughtExceptionHandler wrappedHandler) {
            mReporter = reporter;
            mWrappedHandler = wrappedHandler;
        }

        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            mReporter.uncaughtException(Process.myPid(), ex);
            if (mWrappedHandler != null) mWrappedHandler.uncaughtException(thread, ex);
        }
    }

    public void preCreate(Activity activity) {
        String coverageDeviceFile =
                activity.getIntent().getStringExtra(NativeTestIntent.EXTRA_COVERAGE_DEVICE_FILE);
        if (coverageDeviceFile != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                Os.setenv("LLVM_PROFILE_FILE", coverageDeviceFile, true);
            } catch (Exception e) {
                Log.w(TAG, "failed to set LLVM_PROFILE_FILE", e);
            }
        }
        // To use Os.setenv, need to check Android API level, because
        // it requires API level 21 and Kitkat(API 19) doesn't match.
        // See crbug.com/1042122.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // Set TMPDIR to make perfetto_unittests not to use /data/local/tmp
            // as temporary directory.
            try {
                Os.setenv(
                        "TMPDIR", activity.getApplicationContext().getCacheDir().getPath(), false);
            } catch (Exception e) {
                // Need to use Exception for Android Kitkat, because
                // Kitkat doesn't know ErrnoException is an exception class.
                // When dalvikvm(Kitkat) verifies preCreate method, it finds
                // that unknown method:Os.setenv is used without any exception
                // class. So dalvikvm rejects preCreate method and also rejects
                // NativeClass. All native tests will crash.
                // The verification is executed before running preCreate.
                // The above Build.VERSION check doesn't work to avoid
                // the crash.
                Log.w(TAG, "failed to set TMPDIR", e);
            }
        }
    }

    public void postCreate(Activity activity) {
        parseArgumentsFromIntent(activity, activity.getIntent());
        mReporter = new TestStatusReporter(activity);
        mReporter.testRunStarted(Process.myPid());
        Thread.setDefaultUncaughtExceptionHandler(
                new ReportingUncaughtExceptionHandler(mReporter,
                        Thread.getDefaultUncaughtExceptionHandler()));
    }

    private void parseArgumentsFromIntent(Activity activity, Intent intent) {
        Log.i(TAG, "Extras:");
        Bundle extras = intent.getExtras();
        if (extras != null) {
            for (String s : extras.keySet()) {
                Log.i(TAG, "  %s", s);
            }
        }

        mCommandLineFilePath = intent.getStringExtra(NativeTestIntent.EXTRA_COMMAND_LINE_FILE);
        if (mCommandLineFilePath == null) {
            mCommandLineFilePath = "";
        } else {
            File commandLineFile = new File(mCommandLineFilePath);
            if (!commandLineFile.isAbsolute()) {
                mCommandLineFilePath = Environment.getExternalStorageDirectory() + "/"
                        + mCommandLineFilePath;
            }
            Log.i(TAG, "command line file path: %s", mCommandLineFilePath);
        }

        String commandLineFlags = intent.getStringExtra(NativeTestIntent.EXTRA_COMMAND_LINE_FLAGS);
        if (commandLineFlags != null) mCommandLineFlags.append(commandLineFlags);

        mRunInSubThread = intent.hasExtra(NativeTestIntent.EXTRA_RUN_IN_SUB_THREAD);

        String gtestFilter = intent.getStringExtra(NativeTestIntent.EXTRA_GTEST_FILTER);
        if (gtestFilter != null) {
            appendCommandLineFlags("--gtest_filter=" + gtestFilter);
        }

        mStdoutFilePath = intent.getStringExtra(NativeTestIntent.EXTRA_STDOUT_FILE);
    }

    public void appendCommandLineFlags(String flags) {
        mCommandLineFlags.append(" ").append(flags);
    }

    public void postStart(final Activity activity, boolean forceRunInSubThread) {
        final Runnable runTestsTask = new Runnable() {
            @Override
            public void run() {
                runTests(activity);
            }
        };

        if (mRunInSubThread || forceRunInSubThread) {
            // Post a task that posts a task that creates a new thread and runs tests on it.

            // On L and M, the system posts a task to the main thread that prints to stdout
            // from android::Layout (https://goo.gl/vZA38p). Chaining the subthread creation
            // through multiple tasks executed on the main thread ensures that this task
            // runs before we start running tests s.t. its output doesn't interfere with
            // the test output. See crbug.com/678146 for additional context.

            final Handler handler = new Handler();
            final Runnable startTestThreadTask = new Runnable() {
                @Override
                public void run() {
                    new Thread(runTestsTask).start();
                }
            };
            final Runnable postTestStarterTask = new Runnable() {
                @Override
                public void run() {
                    handler.post(startTestThreadTask);
                }
            };
            handler.post(postTestStarterTask);
        } else {
            // Post a task to run the tests. This allows us to not block
            // onCreate and still run tests on the main thread.
            new Handler().post(runTestsTask);
        }
    }

    private void runTests(Activity activity) {
        nativeRunTests(mCommandLineFlags.toString(), mCommandLineFilePath, mStdoutFilePath,
                activity.getApplicationContext(), UrlUtils.getIsolatedTestRoot());
        activity.finish();
        mReporter.testRunFinished(Process.myPid());
    }

    // Signal a failure of the native test loader to python scripts
    // which run tests.  For example, we look for
    // RUNNER_FAILED build/android/test_package.py.
    private void nativeTestFailed() {
        Log.e(TAG, "[ RUNNER_FAILED ] could not load native library");
    }

    private native void nativeRunTests(String commandLineFlags, String commandLineFilePath,
            String stdoutFilePath, Context appContext, String testDataDir);
}


text:
package edu.northwestern.bioinformatics.studycalendar.domain.delta;

import edu.northwestern.bioinformatics.studycalendar.StudyCalendarError;
import edu.northwestern.bioinformatics.studycalendar.domain.DeepComparable;
import edu.northwestern.bioinformatics.studycalendar.domain.TransientCloneable;
import edu.northwestern.bioinformatics.studycalendar.domain.tools.Differences;
import gov.nih.nci.cabig.ctms.domain.AbstractMutableDomainObject;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;

/**
 * @author Rhett Sutphin
 */

@Entity
@Table(name = "deltas")
@GenericGenerator(name="id-generator", strategy = "native",
    parameters = {
        @Parameter(name="sequence", value="seq_deltas_id")
    }
)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="node_type", discriminatorType = DiscriminatorType.STRING)
public abstract class Delta<T extends Changeable>
    extends AbstractMutableDomainObject
    implements Cloneable, TransientCloneable<Delta<T>>, DeepComparable<Delta<T>>
{
    private List<Change> changes;
    private T node;
    private Revision revision;
    private boolean memoryOnly;

    protected Delta() {
        changes = new ArrayList<Change>();
    }

    protected Delta(T node) {
        this();
        this.node = node;
    }

    ////// FACTORY

    @SuppressWarnings({ "unchecked" })
    public static <T extends Changeable> Delta<T> createDeltaFor(T node, Change... changes) {
        Delta<T> delta = DeltaNodeType.valueForNodeClass(node.getClass()).deltaInstance(node);
        delta.addChanges(changes);
        return delta;
    }

    ////// LOGIC

    public Delta<T> addChange(Change change) {
        changes.add(change);
        change.setDelta(this);
        return this;
    }

    public Delta<T> addChanges(Change... newChanges) {
        for (Change c : newChanges) {
            addChange(c);
        }
        return this;
    }

    public Delta<T> removeChange(Change change, Date updateTime) {
        int removedIndex = getChangesInternal().indexOf(change);
        if (getChangesInternal().remove(change)) {
            for (ListIterator<Change> it = getChanges().listIterator(); it.hasNext();) {
                Change sib = it.next();
                int sibOriginalIdx = it.previousIndex();
                if (removedIndex <= sibOriginalIdx) sibOriginalIdx++;
                sib.siblingDeleted(this, change, removedIndex, sibOriginalIdx, updateTime);
            }
            change.setDelta(null);
        }
        return this;
    }

    @Transient
    public List<Change> getChanges() {
        return Collections.unmodifiableList(getChangesInternal());
    }

    @Transient
    public String getBriefDescription() {
        return String.format("delta for %s %s", getNodeTypeDescription(), getNode().getGridId());
    }

    @Transient
    public DeltaNodeType getNodeType() {
        return DeltaNodeType.valueForDeltaClass(getClass());
    }

    @Transient
    public String getNodeTypeDescription() {
        return getNodeType().getNodeTypeName();
    }

    ////// IMPLEMENTATION OF TransientCloneable

    @Transient
    public boolean isMemoryOnly() {
        return memoryOnly;
    }

    public void setMemoryOnly(boolean memoryOnly) {
        this.memoryOnly = memoryOnly;
        for (Change change : getChanges()) {
            change.setMemoryOnly(memoryOnly);
        }
    }

    public Delta<T> transientClone() {
        Delta<T> clone = clone();
        clone.setMemoryOnly(true);
        return clone;
    }

    ////// BEAN PROPERTIES

    @Transient // here only -- mapped in subclasses
    public T getNode() {
        return node;
    }

    public void setNode(T node) {
        this.node = node;
    }

    @OneToMany
    @JoinColumn(name = "delta_id", nullable = false)
    @OrderBy // order by ID for testing consistency // TODO: explicit ordering
    @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
    protected List<Change> getChangesInternal() {
        return changes;
    }

    protected void setChangesInternal(List<Change> changes) {
        this.changes = changes;
    }

    @ManyToOne(targetEntity = Amendment.class) // temporary, of course
    @JoinColumn(name = "amendment_id", insertable = false, updatable = false)
    public Revision getRevision() {
        return revision;
    }

    public void setRevision(Revision revision) {
        this.revision = revision;
    }

    ////// OBJECT METHODS

    @Override
    public String toString() {
        return  new StringBuilder(getClass().getSimpleName())
            .append("[node=").append(getNode()).append(']').toString();
    }

    @Override
    @SuppressWarnings({ "unchecked" })
    public Delta<T> clone() {
        try {
            Delta<T> clone = (Delta<T>) super.clone();
            clone.setRevision(null);
            clone.setChangesInternal(new ArrayList<Change>(getChangesInternal().size()));
            for (Change change : getChangesInternal()) {
                clone.addChange(change.clone());
            }
            return clone;
        } catch (CloneNotSupportedException e) {
            throw new StudyCalendarError("Clone is supported", e);
        }
    }

    public Differences deepEquals(Delta<T> that) {
        Differences differences =  new Differences();

        if (getNode() != null && that.getNode() != null) {
            if (getNode().getGridId() != null ? !getNode().getGridId().equals(that.getNode().getGridId())
                    : that.getNode().getGridId() != null) {
                differences.addMessage("for different node");
            }
        }

        for (int i = 0; i < Math.max(that.getChanges().size(), getChanges().size()); i++) {
            Change left =  getOrNull(this.getChanges(), i);
            Change right = getOrNull(that.getChanges(), i);
            if (left == null) {
                differences.recurseDifferences(right.getNaturalKey(), null, right);
            } else if (right == null) {
                differences.recurseDifferences(left.getNaturalKey(), left, null);
            } else if (left.getNaturalKey().equals(right.getNaturalKey())) {
                differences.recurseDifferences(left.getNaturalKey(), left, right);
            } else {
                differences.addMessage(
                    "%s replaced by %s", left.getNaturalKey(), right.getNaturalKey());
            }
        }

        return differences;
    }

    private <T> T getOrNull(List<T> l, int i) {
        return i < l.size() ? l.get(i) : null;
    }

    //Object Methods

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Delta)) return false;

        Delta delta = (Delta) o;
        if (node != null ? !node.equals(delta.getNode()) : delta.getNode() != null) return false;
        return true;
    }

    @Override
    public int hashCode() {
        int result = node != null ? node.hashCode() : 0;
        return result;
    }
}


text:
This tutorial demonstrates the use of Hibernate's "unmanaged native" configuration in your OSGi container.  In this
configuration, the client bundle is in charge of manually creating the Hibernate SessionFactory, instead of using JPA.

This tutorial also demonstrates how to register custom impls of Hibernate ORM extension points, registered through the
use of OSGi Blueprint (blueprint.xml).

## Running the Tutorial

To run the tutorial, use the following commands in the Karaf console:

- feature:repo-add mvn:org.hibernate/hibernate-osgi/[VERSION]/xml/karaf
- feature:install hibernate-orm
- feature:repo-add file:/[PATH]/hibernate-demos/hibernate-orm/osgi/unmanaged-native/features.xml
- feature:install hibernate-osgi-unmanaged-native


text:
package se.unlogic.standardutils.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public interface Elementable extends XMLable {

	public Element toXML(Document doc);
}


text:
package northwind.model;

public class UserRole {
    private long id;
    private long userId;
    private long roleId;

    private User user;
    private Role role;

	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public long getUserId() {
		return userId;
	}
	public void setUserId(long userId) {
		this.userId = userId;
	}
	public long getRoleId() {
		return roleId;
	}
	public void setRoleId(long roleId) {
		this.roleId = roleId;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public Role getRole() {
		return role;
	}
	public void setRole(Role role) {
		this.role = role;
	}

}


text:
class Ksync < Formula
  desc "Sync files between your local system and a kubernetes cluster"
  homepage "https://ksync.github.io/ksync/"
  url "https://github.com/ksync/ksync.git",
      tag:      "0.4.6",
      revision: "bfb445b179a0405ab4a01b999010010406f425b7"
  license "Apache-2.0"
  head "https://github.com/ksync/ksync.git"

  bottle do
    rebuild 1
    sha256 cellar: :any_skip_relocation, arm64_big_sur: "b8fdaafce04e89be790f15be07240b0ce0baabd5550ce6f625b6177d9fafecd1"
    sha256 cellar: :any_skip_relocation, big_sur:       "e68abf337654f51128a835f8d3c124df880a37a26f2773b0aa09fce74c67d63a"
    sha256 cellar: :any_skip_relocation, catalina:      "68409c1188fc629bb181765961ee9ff645b941400edcea9939d8d7189e7db5dc"
    sha256 cellar: :any_skip_relocation, mojave:        "a4d52a2a59f8b6308ea858f051e8971145b9964c32564a832408e05f6582c23e"
  end

  depends_on "go" => :build

  def install
    # Remove this when upstream provide working go.sum files
    # (i.e. it builds without errors)
    # https://github.com/ksync/ksync/issues/504
    system "go", "mod", "tidy"

    project = "github.com/ksync/ksync"
    ldflags = %W[
      -w
      -X #{project}/pkg/ksync.GitCommit=#{Utils.git_short_head}
      -X #{project}/pkg/ksync.GitTag=#{version}
      -X #{project}/pkg/ksync.BuildDate=#{Utils.safe_popen_read("date", "+%Y%m%dT%H%M%S").chomp}
      -X #{project}/pkg/ksync.VersionString=Homebrew
      -X #{project}/pkg/ksync.GoVersion=go#{Formula["go"].version}
    ]
    system "go", "build", "-ldflags", ldflags.join(" "), *std_go_args, "#{project}/cmd/ksync"
  end

  test do
    # Basic build test. Potential for more sophisticated tests in the future
    # Initialize the local client and see if it completes successfully
    expected = "level=fatal"
    assert_match expected.to_s, shell_output("#{bin}/ksync init --local --log-level debug", 1)
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.robolectric.fakes Class Hierarchy (robolectric-parent 3.1 API)</title>
<meta name="date" content="2016-06-06">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.robolectric.fakes

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.robolectric.fakes.BaseCursor (implements android.database.Cursor)

org.robolectric.fakes.RoboCursor

android.content.IntentSender (implements android.os.Parcelable)

org.robolectric.fakes.RoboIntentSender

org.robolectric.fakes.RoboAttributeSet (implements android.util.AttributeSet)

org.robolectric.fakes.RoboMenu (implements android.view.Menu)

org.robolectric.fakes.RoboSubMenu (implements android.view.SubMenu)

org.robolectric.fakes.RoboMenuItem (implements android.view.MenuItem)

org.robolectric.fakes.RoboSharedPreferences (implements android.content.SharedPreferences)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016. All rights reserved.


text:
<?php
namespace Chamilo\Core\Repository\Menu;

use Chamilo\Configuration\Configuration;
use Chamilo\Configuration\Storage\DataClass\Registration;
use Chamilo\Core\Repository\Common\Import\ImportTypeSelector;
use Chamilo\Core\Repository\Filter\FilterData;
use Chamilo\Core\Repository\Manager;
use Chamilo\Core\Repository\Workspace\PersonalWorkspace;
use Chamilo\Core\Repository\Workspace\Service\RightsService;
use Chamilo\Libraries\Architecture\ClassnameUtilities;
use Chamilo\Libraries\Format\Structure\ActionBar\Button;
use Chamilo\Libraries\Format\Structure\ActionBar\ButtonGroup;
use Chamilo\Libraries\Format\Structure\ActionBar\ButtonToolBar;
use Chamilo\Libraries\Format\Structure\ActionBar\Renderer\ButtonToolBarRenderer;
use Chamilo\Libraries\Format\Structure\Glyph\BootstrapGlyph;
use Chamilo\Libraries\Format\Tabs\DynamicTabsRenderer;
use Chamilo\Libraries\Platform\Translation;
use Chamilo\Libraries\Utilities\Utilities;

/**
 *
 * @package Chamilo\Core\Repository\Menu
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 * @author Magali Gillard <magali.gillard@ehb.be>
 * @author Eduard Vossen <eduard.vossen@ehb.be>
 */
class RepositoryMenu
{

    /**
     *
     * @var \Chamilo\Core\Repository\Manager
     */
    private $repositoryManager;

    /**
     *
     * @param \Chamilo\Core\Repository\Manager $repositoryManager
     */
    public function __construct(Manager $repositoryManager)
    {
        $this->repositoryManager = $repositoryManager;
    }

    /**
     *
     * @return \Chamilo\Core\Repository\Manager
     */
    public function getRepositoryManager()
    {
        return $this->repositoryManager;
    }

    /**
     *
     * @param \Chamilo\Core\Repository\Manager $repositoryManager
     */
    public function setRepositoryManager(Manager $repositoryManager)
    {
        $this->repositoryManager = $repositoryManager;
    }

    /**
     *
     * @return string
     */
    public function render()
    {
        $repositoryManager = $this->getRepositoryManager();
        $buttonToolBar = new ButtonToolBar();
        $buttonToolBar->addClass('btn-action-toolbar-vertical');

        $rightsService = RightsService::getInstance();
        $canAddContentObjects = $rightsService->canAddContentObjects(
            $repositoryManager->get_user(),
            $repositoryManager->getWorkspace());

        if ($canAddContentObjects)
        {
            $buttonGroup = new ButtonGroup(array(), array('btn-group-vertical'));

            $buttonGroup->addButton(
                new Button(
                    Translation::get('Create', null, Utilities::COMMON_LIBRARIES),
                    new BootstrapGlyph('plus'),
                    $repositoryManager->get_url(
                        array(
                            \Chamilo\Core\Repository\Manager::PARAM_ACTION => \Chamilo\Core\Repository\Manager::ACTION_CREATE_CONTENT_OBJECTS)),
                    Button::DISPLAY_ICON_AND_LABEL,
                    false,
                    'btn-primary'));

            $importParameters = $repositoryManager->get_parameters();
            $importParameters[Manager::PARAM_ACTION] = Manager::ACTION_IMPORT_CONTENT_OBJECTS;

            $importTypeSelector = new ImportTypeSelector($importParameters, $this->getImportTypes());
            $buttonGroup->addButton($importTypeSelector->getTypeSelectorDropdownButton());

            if (! $repositoryManager->getWorkspace() instanceof PersonalWorkspace)
            {
                $buttonGroup->addButton(
                    new Button(
                        Translation::get('AddExisting'),
                        new BootstrapGlyph('hdd'),
                        $repositoryManager->get_url(
                            array(

                                \Chamilo\Core\Repository\Manager::PARAM_ACTION => \Chamilo\Core\Repository\Manager::ACTION_WORKSPACE,
                                \Chamilo\Core\Repository\Workspace\Manager::PARAM_ACTION => \Chamilo\Core\Repository\Workspace\Manager::ACTION_PUBLISH,
                                FilterData::FILTER_CATEGORY => FilterData::getInstance(
                                    $repositoryManager->getWorkspace())->get_category())),
                        Button::DISPLAY_ICON_AND_LABEL));
            }

            $buttonToolBar->addButtonGroup($buttonGroup);
        }

        $buttonGroup = new ButtonGroup(array(), array('btn-group-vertical'));

        if ($repositoryManager->getWorkspace() instanceof PersonalWorkspace)
        {
            $buttonGroup->addButton(
                new Button(
                    Translation::get('MyPublications'),
                    new BootstrapGlyph('list'),
                    $repositoryManager->get_url(
                        array(
                            \Chamilo\Core\Repository\Manager::PARAM_ACTION => \Chamilo\Core\Repository\Manager::ACTION_PUBLICATION),
                        array(\Chamilo\Core\Repository\Publication\Manager::PARAM_ACTION))));
        }

        if ($repositoryManager->getWorkspace() instanceof PersonalWorkspace)
        {
            $buttonGroup->addButton(
                new Button(
                    Translation::get('Quota'),
                    new BootstrapGlyph('stats'),
                    $repositoryManager->get_url(
                        array(
                            \Chamilo\Core\Repository\Manager::PARAM_ACTION => \Chamilo\Core\Repository\Manager::ACTION_QUOTA,
                            \Chamilo\Core\Repository\Manager::PARAM_CATEGORY_ID => null,
                            \Chamilo\Core\Repository\Quota\Manager::PARAM_ACTION => null,
                            DynamicTabsRenderer::PARAM_SELECTED_TAB => null))));

            $buttonGroup->addButton(
                new Button(
                    Translation::get('ViewDoubles'),
                    new BootstrapGlyph('duplicate'),
                    $repositoryManager->get_url(
                        array(
                            \Chamilo\Core\Repository\Manager::PARAM_ACTION => \Chamilo\Core\Repository\Manager::ACTION_VIEW_DOUBLES))));

            $buttonGroup->addButton(
                new Button(
                    Translation::get('RecycleBin'),
                    new BootstrapGlyph('trash'),
                    $repositoryManager->get_recycle_bin_url()));
        }

        $buttonToolBar->addButtonGroup($buttonGroup);
        $buttonToolBarRenderer = new ButtonToolBarRenderer($buttonToolBar);

        return $buttonToolBarRenderer->render();
    }

    /**
     *
     * @return string[]
     */
    public function getImportTypes()
    {
        $registrations = Configuration::getInstance()->get_registrations_by_type(
            'Chamilo\Core\Repository\ContentObject');

        $types = array();

        foreach ($registrations as $registration)
        {
            $namespace = $registration[Registration::PROPERTY_CONTEXT];
            $packageName = ClassnameUtilities::getInstance()->getPackageNameFromNamespace($namespace);
            $types[] = $namespace . '\Storage\DataClass\\' . $packageName;
        }

        return $types;
    }
}


text:
require 'spec_helper'
require_relative '../../../lib/judopay/core_ext/string'

describe String do
  it 'should convert an underscored string to camel case' do
    expect('judo_pay'.camel_case).to eq('judoPay')
  end

  it 'should convert an camel case string to underscored format' do
    expect('JudoPay'.underscore).to eq('judo_pay')
  end

  it 'should uncapitalize a word' do
    expect('JudoPay'.uncapitalize).to eq('judoPay')
  end
end


text:
'use strict'

angular.module('remonit')

.run(['$rootScope', 'node', function($rootScope, node) {
  if (!node) return

  var process = require('child_process')
  var scope = $rootScope
  var sandboxes = scope.tasks = {}
  var consoles = scope.consoles = {}

  scope.$watch('monitors', function(monitors) {
    addConsoles(monitors)
    addRunningMonitors(monitors)
    removeStoppedMoinitors(monitors)
  }, true)

  function addConsoles(monitors) {
    _.each(monitors, function(monitor) {
      var id = monitor._id
      var existed = id in consoles
      if (!existed) consoles[id] = new Console(scope)
    })
  }

  function addRunningMonitors(monitors) {
    _.each(monitors, function(monitor) {
      var id = monitor._id
      var existed = id in sandboxes

      if (monitor.enabled && !existed) {
        consoles[id].clear()
        sandboxes[id] = new Sandbox(consoles[id])
        .inject('require', require)
        .inject('$return', function(obj) {
          if (_.contains(scope.constants.reservedNames, monitor.name)) return
          if (scope.stats && !_.isEqual(scope.stats[monitor.name], obj)) {
            scope.stats[monitor.name] = obj
            Stats.$save(scope.stats, monitor.name)
          }
        })
        .inject('$exec', getExec(monitor, consoles[id]))
        .run(monitor.code, monitor.frequency * 1000)
      }
    })
  }

  function removeStoppedMoinitors(monitors) {
    _.each(sandboxes, function(sandbox, id) {
      var existed = _.find(monitors, function(monitor) {
        return monitor._id === id && monitor.enabled
      })

      if (!existed) {
        sandbox.stop()
        delete sandboxes[id]
      }
    })
  }

  function cbWrapper(fn, console) {
    return function() {
      try {
        return(fn.apply(this, arguments))
      } catch(e) {
        console.error(e)
      }
    }
  }

  function getExec(monitor, console) {
    if (monitor.location === '<local>') {
      return function(command, callback) {
        process.exec(command, cbWrapper(callback, console))
      }
    } else {
      return function(command, callback) {
        var conn = scope.connections[monitor.location]
        if (conn) conn.exec(command, cbWrapper(callback, console))
      }
    }
  }
}])


text:
package org.zapylaev.game.truetennis.core.screen.menu;

import com.badlogic.gdx.scenes.scene2d.ui.Table;
import org.zapylaev.game.truetennis.core.TrueTennisMain;

public class OptionsMenu extends MenuScreen {
    public OptionsMenu(TrueTennisMain game) {
        super(game);
    }

    @Override
    public void show() {
        super.show();
        Table table = new Table(mSkin);
        table.setFillParent(true);

        mStage.addActor(table);
    }
}


text:
package core

import _root_.core.node.{ NodeDirectoryService, NodeRegistrationService }
import search.SearchService
import util.{ OrganizationConfigurationResourceHolder, OrganizationConfigurationHandler }
import services._
import models.{ CommonsServiceConfiguration, BaseXConfiguration, OrganizationConfiguration, HubUser }
import play.api.{ Logger, Play }
import play.api.Play.current
import storage.BaseXStorage

/**
 * Global Services used by the Hub, initialized at startup time (see ConfigurationPlugin)
 *
 * TODO find a cleaner way to initialize this object or pass it around
 *
 * @author Manuel Bernhardt <bernhardt.manuel@gmail.com>
 */

object HubServices {

  val log = Logger("CultureHub")

  // ~~~ service locators for organization-bound services
  lazy val authenticationServiceLocator = new DomainServiceLocator[AuthenticationService] {
    def byDomain(implicit configuration: OrganizationConfiguration): AuthenticationService = baseServices.getResource(configuration)
  }
  lazy val registrationServiceLocator = new DomainServiceLocator[RegistrationService] {
    def byDomain(implicit configuration: OrganizationConfiguration): RegistrationService = baseServices.getResource(configuration)
  }
  lazy val userProfileServiceLocator = new DomainServiceLocator[UserProfileService] {
    def byDomain(implicit configuration: OrganizationConfiguration): UserProfileService = baseServices.getResource(configuration)
  }
  lazy val organizationServiceLocator = new DomainServiceLocator[OrganizationService] {
    def byDomain(implicit configuration: OrganizationConfiguration): OrganizationService = baseServices.getResource(configuration)
  }
  lazy val directoryServiceLocator = new DomainServiceLocator[DirectoryService] {
    def byDomain(implicit configuration: OrganizationConfiguration): DirectoryService = baseServices.getResource(configuration)
  }
  lazy val nodeRegistrationServiceLocator = new DomainServiceLocator[NodeRegistrationService] {
    def byDomain(implicit configuration: OrganizationConfiguration): NodeRegistrationService = baseServices.getResource(configuration)
  }
  lazy val nodeDirectoryServiceLocator = new DomainServiceLocator[NodeDirectoryService] {
    def byDomain(implicit configuration: OrganizationConfiguration): NodeDirectoryService = baseServices.getResource(configuration)
  }
  lazy val searchServiceLocator = new DomainServiceLocator[SearchService] {
    def byDomain(implicit configuration: OrganizationConfiguration): SearchService = CultureHubPlugin.getServices(classOf[SearchService]).head
  }
  lazy val indexingServiceLocator = new DomainServiceLocator[IndexingService] {
    def byDomain(implicit configuration: OrganizationConfiguration): IndexingService = CultureHubPlugin.getServices(classOf[IndexingService]).head
  }

  type CommonServiceType = AuthenticationService with RegistrationService with UserProfileService with OrganizationService with DirectoryService with NodeRegistrationService with NodeDirectoryService

  def basexStorages = basexStoragesHolder
  def baseServices = baseServicesHolder

  private var basexStoragesHolder: OrganizationConfigurationResourceHolder[BaseXConfiguration, BaseXStorage] = null
  private var baseServicesHolder: OrganizationConfigurationResourceHolder[(String, CommonsServiceConfiguration), CommonServiceType] = null

  def init() {

    basexStoragesHolder = new OrganizationConfigurationResourceHolder[BaseXConfiguration, BaseXStorage]("basexStorages") {

      protected def resourceConfiguration(configuration: OrganizationConfiguration): BaseXConfiguration = configuration.baseXConfiguration

      protected def onAdd(resourceConfiguration: BaseXConfiguration): Option[BaseXStorage] = {
        try {
          Some(new BaseXStorage(resourceConfiguration))
        } catch {
          case t: Throwable =>
            log.error(s"Could not initialize BaseXStorage for host ${resourceConfiguration.host}", t)
            None
        }
      }

      protected def onRemove(removed: BaseXStorage) {
        // TODO we may need to call stop() on the storage, check documentation
      }
    }

    baseServicesHolder = new OrganizationConfigurationResourceHolder[(String, CommonsServiceConfiguration), CommonServiceType]("baseServices") {

      protected def resourceConfiguration(configuration: OrganizationConfiguration): (String, CommonsServiceConfiguration) = (configuration.orgId, configuration.commonsService)

      protected def onAdd(resourceConfiguration: (String, CommonsServiceConfiguration)): Option[CommonServiceType] = {

        var services: CommonServiceType = null

        resourceConfiguration._2.commonsHost match {

          case host if (!host.isEmpty) =>
            val node = resourceConfiguration._2.nodeName
            val orgId = resourceConfiguration._1
            val apiToken = resourceConfiguration._2.apiToken
            services = new CommonsServices(host, orgId, apiToken, node)
            Some(services)

          case host if (host.isEmpty) && !Play.isProd => {
            // in development mode, load all hubUsers as basis for the remote ones
            val users = HubUser.all.flatMap {
              users =>
                users.findAll.map {
                  u =>
                    {
                      MemoryUser(
                        u.userName,
                        u.firstName,
                        u.lastName,
                        u.email,
                        "secret",
                        u.userProfile,
                        true
                      )
                    }
                }
            }.map(u => (u.userName -> u)).toMap

            val memoryServices = new MemoryServices
            users.foreach {
              u => memoryServices.users += u
            }

            // add example organizations
            OrganizationConfigurationHandler.getAllCurrentConfigurations.foreach {
              implicit configuration =>
                val org = MemoryOrganization(orgId = configuration.orgId, name = Map("en" -> configuration.orgId.capitalize), admins = List("bob"))
                memoryServices.organizations += (configuration.orgId -> org)

                // now ensure that bob is member everywhere
                HubUser.dao.addToOrganization("bob", configuration.orgId)
            }

            services = memoryServices
            Some(services)
          }

          case _ =>
            throw new RuntimeException("The remote services are not configured. You need to specify 'services.commons.host' and 'services.commons.apiToken")
            None
        }
      }

      protected def onRemove(removed: CommonServiceType) {
        basexStoragesHolder = null
        baseServicesHolder = null
      }

    }

    OrganizationConfigurationHandler.registerResourceHolder(basexStorages)
    OrganizationConfigurationHandler.registerResourceHolder(baseServices)
  }

}