text:
//===--- DiagnosticConsumerTests.cpp --------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/AST/DiagnosticConsumer.h"
#include "swift/Basic/Located.h"
#include "swift/Basic/SourceManager.h"
#include "gtest/gtest.h"

using namespace swift;

namespace {
  using ExpectedDiagnostic = Located<StringRef>;

  class ExpectationDiagnosticConsumer: public DiagnosticConsumer {
    ExpectationDiagnosticConsumer *previous;
    SmallVector<ExpectedDiagnostic, 4> expected;
    bool hasFinished = false;

  public:
    ExpectationDiagnosticConsumer(ExpectationDiagnosticConsumer *previous,
                                  ArrayRef<ExpectedDiagnostic> expected)
      : previous(previous), expected(expected.begin(), expected.end()) {}

    ~ExpectationDiagnosticConsumer() override {
      EXPECT_TRUE(hasFinished);
      EXPECT_TRUE(expected.empty());
    }

    void handleDiagnostic(SourceManager &SM,
                          const DiagnosticInfo &Info) override {
      ASSERT_FALSE(expected.empty());
      EXPECT_EQ(Located<StringRef>(Info.FormatString, Info.Loc), expected.front());
      expected.erase(expected.begin());
    }

    bool finishProcessing() override {
      EXPECT_FALSE(hasFinished);
      if (previous)
        EXPECT_TRUE(previous->hasFinished);
      hasFinished = true;
      return false;
    }
  };

  DiagnosticInfo testDiagnosticInfo(SourceLoc Loc, const char *Message,
                                    DiagnosticKind Kind) {
    return DiagnosticInfo(DiagID(0), Loc, Kind, Message, /*args*/ {},
                          /*category*/ StringRef(),
                          /*indirectBuffer*/ SourceLoc(), /*childInfo*/ {},
                          /*ranges*/ {}, /*fixIts*/ {}, /*isChild*/ false);
  }

} // end anonymous namespace

TEST(FileSpecificDiagnosticConsumer, SubconsumersFinishInOrder) {
  SourceManager sourceMgr;
  (void)sourceMgr.addMemBufferCopy("abcde", "A");
  (void)sourceMgr.addMemBufferCopy("vwxyz", "B");

  auto consumerA = std::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, None);
  auto consumerUnaffiliated = std::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), None);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("", std::move(consumerUnaffiliated));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->finishProcessing();
}

TEST(FileSpecificDiagnosticConsumer, InvalidLocDiagsGoToEveryConsumer) {
  SourceManager sourceMgr;
  (void)sourceMgr.addMemBufferCopy("abcde", "A");
  (void)sourceMgr.addMemBufferCopy("vwxyz", "B");

  ExpectedDiagnostic expected[] = { Located<StringRef>("dummy", SourceLoc()) };
  auto consumerA = std::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expected);
  auto consumerUnaffiliated = std::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expected);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("", std::move(consumerUnaffiliated));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->handleDiagnostic(
      sourceMgr,
      testDiagnosticInfo(SourceLoc(), "dummy", DiagnosticKind::Error));
  topConsumer->finishProcessing();
}

TEST(FileSpecificDiagnosticConsumer, ErrorsWithLocationsGoToExpectedConsumers) {
  SourceManager sourceMgr;
  //                                             01234
  unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
  unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");

  SourceLoc frontOfA = sourceMgr.getLocForOffset(bufferA, 0);
  SourceLoc middleOfA = sourceMgr.getLocForOffset(bufferA, 2);
  SourceLoc backOfA = sourceMgr.getLocForOffset(bufferA, 4);

  SourceLoc frontOfB = sourceMgr.getLocForOffset(bufferB, 0);
  SourceLoc middleOfB = sourceMgr.getLocForOffset(bufferB, 2);
  SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4);

  ExpectedDiagnostic expectedA[] = {
    {"front", frontOfA},
    {"middle", middleOfA},
    {"back", backOfA},
  };
  ExpectedDiagnostic expectedB[] = {
    {"front", frontOfB},
    {"middle", middleOfB},
    {"back", backOfB}
  };

  auto consumerA = std::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expectedA);
  auto consumerB = std::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expectedB);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("B", std::move(consumerB));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfA, "front", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfB, "front", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr,
      testDiagnosticInfo(middleOfA, "middle", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr,
      testDiagnosticInfo(middleOfB, "middle", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfA, "back", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfB, "back", DiagnosticKind::Error));
  topConsumer->finishProcessing();
}

TEST(FileSpecificDiagnosticConsumer,
     ErrorsInUnaffiliatedFilesGoToEveryConsumer) {
  SourceManager sourceMgr;
  //                                             01234
  unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
  unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");

  SourceLoc frontOfA = sourceMgr.getLocForOffset(bufferA, 0);
  SourceLoc middleOfA = sourceMgr.getLocForOffset(bufferA, 2);
  SourceLoc backOfA = sourceMgr.getLocForOffset(bufferA, 4);

  SourceLoc frontOfB = sourceMgr.getLocForOffset(bufferB, 0);
  SourceLoc middleOfB = sourceMgr.getLocForOffset(bufferB, 2);
  SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4);

  ExpectedDiagnostic expectedA[] = {
    {"front", frontOfA},
    {"front", frontOfB},
    {"middle", middleOfA},
    {"middle", middleOfB},
    {"back", backOfA},
    {"back", backOfB}
  };
  ExpectedDiagnostic expectedUnaffiliated[] = {
    {"front", frontOfB},
    {"middle", middleOfB},
    {"back", backOfB}
  };

  auto consumerA = std::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expectedA);
  auto consumerUnaffiliated = std::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expectedUnaffiliated);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("", std::move(consumerUnaffiliated));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfA, "front", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfB, "front", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr,
      testDiagnosticInfo(middleOfA, "middle", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr,
      testDiagnosticInfo(middleOfB, "middle", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfA, "back", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfB, "back", DiagnosticKind::Error));
  topConsumer->finishProcessing();
}

TEST(FileSpecificDiagnosticConsumer, WarningsAndRemarksAreTreatedLikeErrors) {
  SourceManager sourceMgr;
  //                                             01234
  unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
  unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");

  SourceLoc frontOfA = sourceMgr.getLocForBufferStart(bufferA);
  SourceLoc frontOfB = sourceMgr.getLocForBufferStart(bufferB);

  ExpectedDiagnostic expectedA[] = {
    {"warning", frontOfA},
    {"warning", frontOfB},
    {"remark", frontOfA},
    {"remark", frontOfB},
  };
  ExpectedDiagnostic expectedUnaffiliated[] = {
    {"warning", frontOfB},
    {"remark", frontOfB},
  };

  auto consumerA = std::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expectedA);
  auto consumerUnaffiliated = std::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expectedUnaffiliated);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("", std::move(consumerUnaffiliated));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->handleDiagnostic(
      sourceMgr,
      testDiagnosticInfo(frontOfA, "warning", DiagnosticKind::Warning));
  topConsumer->handleDiagnostic(
      sourceMgr,
      testDiagnosticInfo(frontOfB, "warning", DiagnosticKind::Warning));
  topConsumer->handleDiagnostic(
      sourceMgr,
      testDiagnosticInfo(frontOfA, "remark", DiagnosticKind::Remark));
  topConsumer->handleDiagnostic(
      sourceMgr,
      testDiagnosticInfo(frontOfB, "remark", DiagnosticKind::Remark));
  topConsumer->finishProcessing();
}

TEST(FileSpecificDiagnosticConsumer, NotesAreAttachedToErrors) {
  SourceManager sourceMgr;
  //                                             01234
  unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
  unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");

  SourceLoc frontOfA = sourceMgr.getLocForOffset(bufferA, 0);
  SourceLoc middleOfA = sourceMgr.getLocForOffset(bufferA, 2);
  SourceLoc backOfA = sourceMgr.getLocForOffset(bufferA, 4);

  SourceLoc frontOfB = sourceMgr.getLocForOffset(bufferB, 0);
  SourceLoc middleOfB = sourceMgr.getLocForOffset(bufferB, 2);
  SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4);

  ExpectedDiagnostic expectedA[] = {
    {"error", frontOfA},
    {"note", middleOfA},
    {"note", backOfA},
    {"error", frontOfB},
    {"note", middleOfB},
    {"note", backOfB},
    {"error", frontOfA},
    {"note", middleOfA},
    {"note", backOfA},
  };
  ExpectedDiagnostic expectedUnaffiliated[] = {
    {"error", frontOfB},
    {"note", middleOfB},
    {"note", backOfB},
  };

  auto consumerA = std::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expectedA);
  auto consumerUnaffiliated = std::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expectedUnaffiliated);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("", std::move(consumerUnaffiliated));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfA, "error", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(middleOfA, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfA, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfB, "error", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(middleOfB, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfB, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfA, "error", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(middleOfA, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfA, "note", DiagnosticKind::Note));
  topConsumer->finishProcessing();
}

TEST(FileSpecificDiagnosticConsumer, NotesAreAttachedToWarningsAndRemarks) {
  SourceManager sourceMgr;
  //                                             01234
  unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
  unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");

  SourceLoc frontOfA = sourceMgr.getLocForOffset(bufferA, 0);
  SourceLoc middleOfA = sourceMgr.getLocForOffset(bufferA, 2);
  SourceLoc backOfA = sourceMgr.getLocForOffset(bufferA, 4);

  SourceLoc frontOfB = sourceMgr.getLocForOffset(bufferB, 0);
  SourceLoc middleOfB = sourceMgr.getLocForOffset(bufferB, 2);
  SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4);

  ExpectedDiagnostic expectedA[] = {
    {"warning", frontOfA},
    {"note", middleOfA},
    {"note", backOfA},
    {"warning", frontOfB},
    {"note", middleOfB},
    {"note", backOfB},
    {"remark", frontOfA},
    {"note", middleOfA},
    {"note", backOfA},
  };
  ExpectedDiagnostic expectedUnaffiliated[] = {
    {"warning", frontOfB},
    {"note", middleOfB},
    {"note", backOfB},
  };

  auto consumerA = std::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expectedA);
  auto consumerUnaffiliated = std::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expectedUnaffiliated);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("", std::move(consumerUnaffiliated));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->handleDiagnostic(
      sourceMgr,
      testDiagnosticInfo(frontOfA, "warning", DiagnosticKind::Warning));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(middleOfA, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfA, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr,
      testDiagnosticInfo(frontOfB, "warning", DiagnosticKind::Warning));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(middleOfB, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfB, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr,
      testDiagnosticInfo(frontOfA, "remark", DiagnosticKind::Remark));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(middleOfA, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfA, "note", DiagnosticKind::Note));
  topConsumer->finishProcessing();
}

TEST(FileSpecificDiagnosticConsumer, NotesAreAttachedToErrorsEvenAcrossFiles) {
  SourceManager sourceMgr;
  //                                             01234
  unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
  unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");

  SourceLoc frontOfA = sourceMgr.getLocForOffset(bufferA, 0);
  SourceLoc middleOfA = sourceMgr.getLocForOffset(bufferA, 2);
  SourceLoc backOfA = sourceMgr.getLocForOffset(bufferA, 4);

  SourceLoc frontOfB = sourceMgr.getLocForOffset(bufferB, 0);
  SourceLoc middleOfB = sourceMgr.getLocForOffset(bufferB, 2);
  SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4);

  ExpectedDiagnostic expectedA[] = {
    {"error", frontOfA},
    {"note", middleOfB},
    {"note", backOfA},
    {"error", frontOfA},
    {"note", middleOfB},
    {"note", backOfA},
  };
  ExpectedDiagnostic expectedB[] = {
    {"error", frontOfB},
    {"note", middleOfA},
    {"note", backOfB},
  };

  auto consumerA = std::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expectedA);
  auto consumerB = std::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expectedB);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("B", std::move(consumerB));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfA, "error", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(middleOfB, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfA, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfB, "error", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(middleOfA, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfB, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfA, "error", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(middleOfB, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfA, "note", DiagnosticKind::Note));
  topConsumer->finishProcessing();
}

TEST(FileSpecificDiagnosticConsumer,
     NotesAreAttachedToErrorsEvenAcrossFilesWithUnaffiliatedConsumer) {
  SourceManager sourceMgr;
  //                                             01234
  unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
  unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");

  SourceLoc frontOfA = sourceMgr.getLocForOffset(bufferA, 0);
  SourceLoc middleOfA = sourceMgr.getLocForOffset(bufferA, 2);
  SourceLoc backOfA = sourceMgr.getLocForOffset(bufferA, 4);

  SourceLoc frontOfB = sourceMgr.getLocForOffset(bufferB, 0);
  SourceLoc middleOfB = sourceMgr.getLocForOffset(bufferB, 2);
  SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4);

  ExpectedDiagnostic expectedA[] = {
    {"error", frontOfA},
    {"note", middleOfB},
    {"note", backOfA},
    {"error", frontOfB},
    {"note", middleOfA},
    {"note", backOfB},
    {"error", frontOfA},
    {"note", middleOfB},
    {"note", backOfA},
  };
  ExpectedDiagnostic expectedUnaffiliated[] = {
    {"error", frontOfB},
    {"note", middleOfA},
    {"note", backOfB},
  };

  auto consumerA = std::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expectedA);
  auto consumerUnaffiliated = std::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expectedUnaffiliated);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("", std::move(consumerUnaffiliated));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfA, "error", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(middleOfB, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfA, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfB, "error", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(middleOfA, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfB, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfA, "error", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(middleOfB, "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(backOfA, "note", DiagnosticKind::Note));
  topConsumer->finishProcessing();
}

TEST(FileSpecificDiagnosticConsumer,
     NotesWithInvalidLocsAreStillAttachedToErrors) {
  SourceManager sourceMgr;
  //                                             01234
  unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
  unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");

  SourceLoc frontOfA = sourceMgr.getLocForBufferStart(bufferA);
  SourceLoc frontOfB = sourceMgr.getLocForBufferStart(bufferB);

  ExpectedDiagnostic expectedA[] = {
    {"error", frontOfA},
    {"note", SourceLoc()},
    {"error", frontOfB},
    {"note", SourceLoc()},
    {"error", frontOfA},
    {"note", SourceLoc()},
  };
  ExpectedDiagnostic expectedUnaffiliated[] = {
    {"error", frontOfB},
    {"note", SourceLoc()},
  };

  auto consumerA = std::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expectedA);
  auto consumerUnaffiliated = std::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expectedUnaffiliated);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("", std::move(consumerUnaffiliated));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfA, "error", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(SourceLoc(), "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfB, "error", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(SourceLoc(), "note", DiagnosticKind::Note));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(frontOfA, "error", DiagnosticKind::Error));
  topConsumer->handleDiagnostic(
      sourceMgr, testDiagnosticInfo(SourceLoc(), "note", DiagnosticKind::Note));
  topConsumer->finishProcessing();
}


text:
<?php
/**
 * Message translations.
 *
 * This file is automatically generated by 'yiic message' command.
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 *
 * NOTE, this file must be saved in UTF-8 encoding.
 *
 * @version $Id: $
 */
return array (
  'Congratulations!' => 'Συγχαρητήρια!',
  'Install Rights' => 'Εγκατάσταση Δικαιωμάτων',
  'Installation failed.' => 'Η εγκατάσταση απέτυχε.',
  'No' => 'Όχι',
  'Notice: All your existing data will be lost.' => 'Παρατήρηση:Όλα τα υπάρχοντα δεδομένα σας θα χαθούν.',
  'Please confirm if you wish to reinstall.' => 'Παρακαλούμε επιβεβαιώστε ότι επιθυμείτε να επαναλάβετε την εγκατάσταση.',
  'Rights has been installed succesfully.' => 'Τα Δικαιώματα εγκαταστάθηκαν με επιτυχία.',
  'Rights is already installed!' => 'Τα Δικαιώματα είναι ήδη εγκατεστημένα.',
  'Yes' => 'Ναι',
  'You can start by generating your authorization items' => 'Αρχίστε δημιουργώντας τα αντικείμενα εξουσιοδότησης.',
  'You must be logged in to install Rights.' => 'Πρέπει να είστε συνεδεμένος στην ιστοσελίδα  για να εγκαταστήσετε τα Δικαιώματα.',
  'here' => 'εδώ',
);

redpajama_set_name: RedPajamaGithub


text:
package org.innovateuk.ifs.assessment.builder;

import org.innovateuk.ifs.assessment.resource.AssessmentSubmissionsResource;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

import static org.innovateuk.ifs.assessment.builder.AssessmentSubmissionsResourceBuilder.newAssessmentSubmissionsResource;
import static org.junit.Assert.assertEquals;

public class AssessmentSubmissionsResourceBuilderTest {

    @Test
    public void buildOne() throws Exception {
        List<Long> assessmentIds = Arrays.asList(10L, 50L, 100L);

        AssessmentSubmissionsResource resource = newAssessmentSubmissionsResource()
                .withAssessmentIds(assessmentIds)
                .build();

        assertEquals(resource.getAssessmentIds(), assessmentIds);
    }

    @Test
    public void buildMany() throws Exception {
        List<Long> expectedAssessmentIds1 = Arrays.asList(10L, 50L, 100L);
        List<Long> expectedAssessmentIds2 = Arrays.asList(20L, 100L, 200L, 250L);

        List<AssessmentSubmissionsResource> resources = newAssessmentSubmissionsResource()
                .withAssessmentIds(expectedAssessmentIds1, expectedAssessmentIds2)
                .build(3);

        AssessmentSubmissionsResource resource1 = resources.get(0);
        assertEquals(resource1.getAssessmentIds(), expectedAssessmentIds1);

        AssessmentSubmissionsResource resource2 = resources.get(1);
        assertEquals(resource2.getAssessmentIds(), expectedAssessmentIds2);
    }
}


text:
Docker is not just for running and deploying applications, it's great for development too. Using Docker for development provides consistent, clean development environment. Each build can be in a fresh environment without any dependencies on your development workstation or clashes/contamination with your workstation. All developers can use the same OS, same system libraries, same language runtime, no matter what host OS they are using (even Windows). The development environment is the exact same as the production environment. You only need Docker to develop; you don't need to install a bunch of language environments, libraries and tools on your machine.

A Docker conatiner recipe for the Oncoscape development environment is located at https://github.com/FredHutch/Oncoscape-dev-environment

To use the Oncoscape development container use 'git' to clone the Oncoscape development container repository to your Docker enabled development system, build a container image and then run it. Here are the commands required to create a container image tagged "oncodev" (you can name it something else if you would like):

```bash
git clone https://github.com/FredHutch/Oncoscape-dev-environment.git
cd Oncoscape-dev-environment
docker build -t oncodev .
```
The build process will take several minutes to complete. When the build is finished, there will be a new container image registered with your Docker engine named "oncodev" (or whatever you named it). Check to see that the new image was registered with the following command:

```bash
docker images
```
The above command will list the images registered with your docker engine and will look similar to the following:

```
REPOSITORY      TAG         IMAGE ID        CREATED         VIRTUAL SIZE
oncodev         latest      31ee6c745277    2 minutes ago    751.8 MB
```

Now that we have an image registered, you are ready to start making development environment containers. To use the development environment, create and run a container from the image you built and registered. Here is an example (assuming you named your image 'oncodev'):

```bash
docker run -ti -p 80:80 --name myoncodev01 --hostname myoncodev01 oncodev
```
Paramater Description:
  - '--name myoncodev01' flag tags this container (choose whatever name you like).
  - '--hostname myoncodev01' sets the hostname inside the container to match the container instance name. The bash prompt inside the container will include the provided hostname to make it clear what environment you are currently in.
  - '-p 80:80' flag tells docker that you want to bind TCP port 80 inside your container to TCP port 80 on your Docker-Machine VM (or directly to the host on Linux). You can bind as many ports as you need by using multiple '-p' arguments. The port you bind to outside the container doesn't have to match the port inside the container. For example '-p 8080:80' will map TCP port 8080 outside the container to TCP port 80 inside the container.

After you execute the above command you'll be dropped to a bash shell inside this new container. You are now root in an isolated Linux environment that has everything that you need to build and run Oncoscape. The container is empty so you'll need to clone the Oncoscape repo (git is included in the container) and install/build/configure/run as you like. You can create new branches, edit code (vim, emacs and nano are provided), commit and push to github right from inside the container.

***NOTE:*** Windows users only. While the "Docker Quick Start Terminal" is fine for managing, starting, and stopping containers, you'll want to use either the standard command prompt (cmd.exe) or Powershell consoles for interactive work such editing files inside the container. Note that when using 'vi' in a container via cmd.exe or Powershell consoles, the arrow keys do not work and you'll need to use the traditional 'hjkl' keys to move the cursor: 'h'=left, 'j'=down, 'k'=up, 'l'=right.

Setup the environment variables required by docker for the shell of your choice as shown below:

***Classic command prompt (cmd.exe)***
```
FOR /f "tokens=*" %i IN ('docker-machine.exe env --shell=cmd default') DO %i
```
***Powershell***
```
docker-machine.exe env --shell=powershell default | Invoke-Expression
```

After you build and run Oncoscape in a container you'll likely want to point your browser at it. If you are running docker on Linux, you simply point your browser at either http://localhost or http://servername if it's running on a remote server. If you are running Docker on Mac OS X or Windows you first have to determine the IP address of the Docker Machine VM. To do so you'll need to run the following command:

```bash
docker-machine ip default
```

The output of the above command will be a private IP address that you can only reach from your development workstation. After you have this IP address simply point you browser at it with the desired port; "http://192.168.99.100:80" for example.

#### Stopping and starting your containers

To stop your development container, simply exit the bash shell with the "exit" command. This will stop the container and drop you back on your workstation's command line. You can see all of your containers running and stopped with the following command:

```bash
docker ps -a
```
The output of the above command will look similar to the following:

```
CONTAINER ID   IMAGE      COMMAND   CREATED             STATUS                 NAMES
3bb2bc400dd3   oncodev    "bash"    19 minutes ago      Exited 7 seconds ago   myoncodev01
```

If you want to start your container again and enter it, simply run the following commands replacing "myoncodev01" with the name of your container:

```bash
docker start myoncodev01
docker attach myoncodev01
```
This will drop you back into an instance of bash running inside your container.

You're not limited to a single container, you can have as many different Oncoscape development environments on your system as you need.

#### Accessing data outside of your container

In the examples above we cloned the Oncocape repository inside of the container. If you'd rather clone it to your workstation directly and access it from inside your container you can use the Docker 'volumes' feature. For example let's say you have cloned the Oncoscape repo to /Users/myuser/Oncoscape and want to fire up a container and access this external data from inside your container. To accomplish this you'll need to use the '-v' flag when creating a new container and tell it what folder on your workstation you want to be mounted inside the container. Here is an example:

```bash
docker run -ti -p 80:80 -v /Users/myuser/Oncoscape:/opt/Oncoscape --name myoncodev02 --hostname myoncodev02 oncodev
```

After running the above command, you should see that the '/User/myuser/Oncoscape' folder on your development workstation is now mounted read/write to '/opt/Oncoscape' inside this new container. You can change to this directory and use git just like you do on your workstation. It's worth noting that any modifications to this directory or files it contains inside the container, is directly modifying the files outside of your container. This approach can save you a lot of time and disk space by not having to clone the repo inside each container, but if you need true isolation between each conatiner, this might not be the right approach.

***NOTE:*** Windows users can't specify the local folder they want mounted in the traditional *'C:/xyz'* format. You'll need to use the *'/c/xzy'* format. For example *"-v /c/Users/myuser/Oncoscape:/opt/Oncoscape"* will mount 'C:\Users\myuser\Oncoscape' on your workstation to *'/opt/Oncoscape'* inside the container.

#### Cleaning up unneeded containers and images

To delete a container you don't need any longer, it must first be stopped if it's currently running then use the following command replacing "myoncodev03" with the name of the container you wish to delete:

```
docker rm myoncodev03
```

To delete the oncodev image that you built, first there must be no containers running or stopped that are based off of it. When there are no containers created from the oncodev image remaining you can delete this image with the following command replacing "oncodev" with name of the image you created:

```
docker rmi oncodev
```

You can see which containers are on you workstation with the "docker ps -a" command and which images are on your workstation with the "docker images" command.


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

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

User's Guide
Reference Manual
Release Notes
PDF
Top
orber
User's Guide
Version 3.8.1

Expand All
Contract All
Chapters

The Orber Application

              Top of chapter

Content Overview

Brief Description of the User's Guide

Introduction to Orber

              Top of chapter

Overview

The Orber Application

              Top of chapter

ORB Kernel and IIOP

The Object Request Broker (ORB)

Internet Inter-Object Protocol (IIOP)

Interface Repository

              Top of chapter

Interface Repository(IFR)

Installing Orber

              Top of chapter

Installation Process

Configuration

Firewall Configuration

Interface Configuration

OMG IDL to Erlang Mapping

              Top of chapter

OMG IDL to Erlang Mapping - Overview

OMG IDL Mapping Elements

Getting Started

Basic OMG IDL Types

Template OMG IDL Types and Complex Declarators

Constructed OMG IDL Types

Scoped Names and Generated Files

Typecode, Identity and Name Access Functions

References to Constants

References to Objects Defined in OMG IDL

Exceptions

Access to Attributes

Invocations of Operations

Implementing the DB Application

Reserved Compiler Names and Keywords

Type Code Representation

CosNaming Service

              Top of chapter

Overview of the CosNaming Service

The Basic Use-cases of the Naming Service

Interoperable Naming Service

How to use security in Orber

              Top of chapter

Security in Orber

Orber Stubs/Skeletons

              Top of chapter

Orber Stubs and Skeletons Description

CORBA System and User Defined Exceptions

              Top of chapter

System Exceptions

User Defined Exceptions

Throwing Exceptions

Catching Exceptions

Orber Interceptors

              Top of chapter

Using Interceptors

Interceptor Example

OrberWeb

              Top of chapter

Using OrberWeb

Starting OrberWeb

Debugging

              Top of chapter

Tools and FAQ

12 OrberWeb

12.1
        Using OrberWeb

OrberWeb is intended to make things easier when developing and
      testing applications using Orber. The user is able to interact
      with Orber via a GUI by using a web browser.

OrberWeb requires that the application WebTool is available and
      started on at least one node; if so OrberWeb can usually be used to
      to access Orber nodes supporting the Interoperable Naming
      Service. How to start OrberWeb is described in
      Starting OrberWeb

The OrberWeb GUI consists of a Menu Frame and a
      Data Frames.

The Menu Frame

The menu frame consists of:

Node List - which node to access.

Configuration - see how Orber on the current node is configured.

Name Service - browse the NameService and add/remove a Context/Object.

IFR Types - see which types are registered in IFR.

Create Object - create a new object and, possibly, store it in the NameService.

        Figure
        12.1:

        The Menu Frame.

Which nodes we can access is determined by what is returned when invoking [node()|nodes()].
        If you cannot see a desired node in the list, you have to call net_adm:ping(Node).
        But this requires that the node is started with the distribution switched on
        (e.g. erl -sname myNode); this also goes for the node OrberWeb is running on.

The Configuration Data Frame

When accessing the Configuration page OrberWeb presents a table containing the
        configuration settings for the target node.

        Figure
        12.2:

        Configuration Settings.

It is also possible to change those configuration parameters which can be changed when Orber
        is already started. The Key-Value pairs is given as a list of tuples, e.g.,
        [{orber_debug_level, 5}, {iiop_timeout, 60}, {giop_version, {1,2}}]. If one tries to update a parameter
        which may not be changed an error message will be displayed.

The IFR Data Frame

All types registered in the IFR (Interface Repository) which have an associated IFR-id
        can be viewed via the IFR Data Frame. This gives the user an easy way to confirm that
        all necessary IDL-specifications have been properly registered. All available types are
        listed when choosing IFR Types in the menu frame:

        Figure
        12.3:

        Select Type.

After selecting a type all definitions of that particular type will be displayed. If no such
        bindings exists the table will be empty.

Since Orber adds definitions to the IFR when it is installed (e.g. CosNaming), not only
        types defined by the user will show up in the table. In the figure below you find the
        the NameService exceptions listed.

        Figure
        12.4:

        List Registered Exceptions.

The NameService Data Frame

The NameService main purpose is to make possible to bind object references, which
        can client applications can resolve and invoke operations on. Initially, the NameService
        is empty. The most common scenario, is that user applications create Contexts and add objects
        in the NameService. OrberWeb allows the user to do the very same thing.

When referencing an object or context you must use stringified NameComponents.
        For more information see the Interoperable Naming Service.
        In the following example we will use the string org/erlang/TheObjectName, where
        org and erlang will be contexts and TheObjectName
        the name the object will be bound to.

Since the NameService is empty in the beginning, the only thing we can do is creating
        a new context. Simply write org in the input field and press New Context.
        If OrberWeb was able to create the context or not, is shown in the completion message.
        If successful, just press the Go Back button. Now, a link named org should
        be listed in the table. In the right column the context type is displayed. Contexts are
        associated with ncontext and objects with nobject.

        Figure
        12.5:

        Add a New Context.

To create the next level context (i.e. erlang), simply follow the link and repeat the procedure.
        If done correctly, a table containing the same data as the following figure should be the result
        if you follow the erlang link. Note, that the path is displayed in the yellow
        field.

If a context does not contain any sub-contexts or object bindings, it is possible to
        delete the context. If these requirements are met, a Delete Context button will appear.
        A completion status message will be displayed after deleting the context.

        Figure
        12.6:

        Delete Context.

Now it is possible to bind an object using the complete name string. To find out how this is
        done using OrberWeb see Object Creation.
        For now, we will just assume that an object have been created and bound as TheObjectName.

        Figure
        12.7:

        Object Stored in the NameService.

If you follow the TheObjectName link, data about the bound object will be
        presented. Note, depending on which type of object it is, the information given differs.
        It would, for example, not be possible to display a Pid for all types of objects since
        it might reside on a Java-ORB. In the figure below a CosNotification FilterFactory have
        been bound under the name org/erlang/TheObjectName.

        Figure
        12.8:

        Object Data.

OrberWeb also makes it possible to remove a binding and dispose the associated object.
        Pressing Unbind the binding will be removed but the object will still exist.
        But, if the Unbind and Dispose button is pressed, the binding will be removed
        and the object terminated.

The Object Creation Data Frame

This part makes it possible to create a new object and, if wanted, store it the
        NameService.

        Figure
        12.9:

        Create a New Object.

Module - simply type the name of the module of the object type
         you want to create. If the module begins with a capital letter, we normally must
         write 'Module_Interface'. But, when using OrberWeb, you shall NOT.
         Since we cannot create linked objects this is not an option.

Arguments - the supplied arguments must be written as a single Erlang term.
         That is, as a list or tuple containing other Erlang terms. The arguments will be
         passed to the init function of the object. It is, however, not possible
         to use Erlang records. If OrberWeb is not able to parse the arguments, an error message
         will be displayed. If left empty, an empty list will be passed.

Options - the options can be the ones listed under
        Module_Interface in Orber's Reference manual.
         Hence, they are not further described here. But, as an example, in the figure above
         we started the object as globally registered. If no options supplied the object
         will be started as default.

Name String - if left empty the object will not be registered in the
         NameService. Hence, it is important that you can access the object in another way,
         otherwise a zombie process is created. In the previous section we used the name string
        org/erlang/TheObjectName. If we choose the same name here, the listed contexts
         (i.e. org and erlang) must be created before we can create
         and bind the object to TheObjectName. If this requirement is not met, OrberWeb
         cannot bind the object. Hence, the object will be terminated and an error message
         displayed.

Operation to use - which option choosed will determine the behavior of OrberWeb.
         If you choose bind and a binding already exists an error message will be
         displayed and the newly started object terminated. But if you choose rebind
         any existing binding will over-written.

12.2
        Starting OrberWeb

You may choose to start OrberWeb on node, on which Orber is running or not. But
      the Erlang distribution must be started (e.g. by using -sname aNodeName). Now, all
      you have to do is to invoke:

erl> webtool:start().
WebTool is available at http://localhost:8888/
Or  http://127.0.0.1:8888/

Type one of the URL:s in your web-browser. If you want to access the WebTool application
      from different machine, just replace localhost with its name. For more information,
      see the WebTool documentation.

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


text:
S3 - Encrypt All Objects
========================

Will scan all keys in the bucket for unencrypted keys and by default
remediate them such that they are encrypted.

.. code-block:: yaml

   policies:
     - name: s3-key-encryption
       resource: s3
       actions:
         - encrypt-keys

Options
  ``crypto`` for determining the crypto mechanism, this can either be ``AWS:KMS`` or ``AES256`` (default)
  ``report-only`` generate reports of unencrypted keys in a bucket, but do not remediate them.


text:
import { Service } from "../../service";
import { endpoints } from "./endpoints";

/**
 * HTTP interface definition for basemaps service.
 */
export class WebSDKService extends Service {

    constructor () {
        super(endpoints);
    }

    parse(response: Response) {
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SQLite;
using ItcastCater.Model;

namespace ItcastCater.DAL
{
    public class CategoryInfoDLL
    {
        public CategoryInfo GetCategoryInfoById(int id)
        {
            string sql = "select * from CategoryInfo where DelFlag=0 and CatId=" + id;
            CategoryInfo ct = null;
            DataTable dt = SqliteHelper.ExecuteTable(sql);
            if (dt.Rows.Count > 0)
            {
                ct = RowToCategoryInfo(dt.Rows[0]);
            }
            return ct;
        }

        public List<CategoryInfo> GetCategoryInfoByDelFlag(int delFlag)
        {
            string sql = "select CatId,CatName,CatNum,Remark from CategoryInfo where DelFlag=" + delFlag;
            DataTable dt = SqliteHelper.ExecuteTable(sql);
            List<CategoryInfo> list = new List<CategoryInfo>();
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    list.Add(RowToCategoryInfo(dr));
                }
            }
            return list;
        }

        private CategoryInfo RowToCategoryInfo(DataRow dr)
        {
            CategoryInfo ct = new CategoryInfo();
            //if(tp==1)
            //{
            ct.CatId = Convert.ToInt32(dr["CatId"]);
            //}

            ct.CatName = dr["CatName"].ToString();
            ct.CatNum = Convert.ToInt32(dr["CatNum"]);
            ct.Remark = dr["Remark"].ToString();
            return ct;
        }

        public int AddCategoryInfo(CategoryInfo ct)
        {
            string sql = "insert into CategoryInfo (CatName,CatNum,Remark,DelFlag,SubTime,SubBy) values(@CatName,@CatNum,@Remark,@DelFlag,@SubTime,@SubBy)";
            return AddAndUpdateCategoryInfo(sql, 1, ct);
        }

        public int UpdateCategoryInfo(CategoryInfo ct)
        {
            string sql = "update CategoryInfo set CatName=@CatName,CatNum=@CatNum,Remark=@Remark where CatId=@CatId";
            return AddAndUpdateCategoryInfo(sql, 2, ct);
        }

        private int AddAndUpdateCategoryInfo(string sql, int temp, CategoryInfo ct)
        {
            SQLiteParameter[] ps ={
                                     new SQLiteParameter("@CatName",ct.CatName),
                                     new SQLiteParameter("@CatNum",ct.CatNum),
                                     new SQLiteParameter("@Remark",ct.Remark)
                                 };
            List<SQLiteParameter> list = new List<SQLiteParameter>();
            list.AddRange(ps);
            if(temp == 1)
            {
                //Insert
                list.Add(new SQLiteParameter("@DelFlag", ct.DelFlag));
                list.Add(new SQLiteParameter("@SubTime", ct.SubTime));
                list.Add(new SQLiteParameter("@SubBy", ct.SubBy));
            }
            else if(temp == 2)
            {
                //Update
                list.Add(new SQLiteParameter("@CatId", ct.CatId));
            }
            return SqliteHelper.ExecuteNonQuery(sql, list.ToArray());
        }

        /// <summary>
        /// 根据商品类别的id删除该类别
        /// </summary>
        /// <param name="catId"></param>
        /// <returns></returns>
        public int SoftDeleteCategoryInfoByCatId(int catId)
        {
            string sql = "update CategoryInfo set DelFlag=1 where CatId=" + catId;
            return SqliteHelper.ExecuteNonQuery(sql);
        }
    }
}


text:
package resources

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/codestarconnections"
	"github.com/rebuy-de/aws-nuke/v2/pkg/types"
)

type CodeStarConnection struct {
	svc              *codestarconnections.CodeStarConnections
	connectionARN    *string
	connectionName   *string
	providerType     *string
}

func init() {
	register("CodeStarConnection", ListCodeStarConnections)
}

func ListCodeStarConnections(sess *session.Session) ([]Resource, error) {
	svc := codestarconnections.New(sess)
	resources := []Resource{}

	params := &codestarconnections.ListConnectionsInput{
		MaxResults: aws.Int64(100),
	}

	for {
		output, err := svc.ListConnections(params)
		if err != nil {
			return nil, err
		}

		for _, connection := range output.Connections {
			resources = append(resources, &CodeStarConnection{
				svc:              svc,
				connectionARN:    connection.ConnectionArn,
				connectionName:   connection.ConnectionName,
				providerType:     connection.ProviderType,
			})
		}

		if output.NextToken == nil {
			break
		}

		params.NextToken = output.NextToken
	}

	return resources, nil
}

func (f *CodeStarConnection) Remove() error {

	_, err := f.svc.DeleteConnection(&codestarconnections.DeleteConnectionInput{
		ConnectionArn: f.connectionARN,
	})

	return err
}

func (f *CodeStarConnection) Properties() types.Properties {
	properties := types.NewProperties()
	properties.
		Set("Name", f.connectionName).
		Set("ProviderType", f.providerType)
	return properties
}

func (f *CodeStarConnection) String() string {
	return *f.connectionName
}


text:
Let's walk through the process of adding a new String-typed setting:

1. Add a new setting to [BenchmarkSettings.swift](https://github.com/tensorflow/swift-models/blob/main/SwiftModelsBenchmarksCore/BenchmarkSettings.swift):

    a. Add a new setting type:

    ```swift

    public struct MySetting: BenchmarkSetting {
      var value: String
      init(_ value: String) {
        self.value = value
      }
    }
    ```

    b. Add a default (if appropriate) to the `defaultSettings` in the same file:

    ```swift
    public let defaultSettings: [BenchmarkSetting] = [
      ...
      MySetting("...") // default value goes here
      ...
    ]
    ```

    c. Add a convenience getter to the `BenchmarkSettings` extension:

    ```swift
      var mySetting: String? {
        return self[MySetting.self]?.value
      }
    ```

    If your setting has a default you can unwrap the optional and return non-optional result:

    ```swift
      var mySetting: String {
        if let value = self[MySetting.self]?.value {
          return value
        } else {
          fatalError("MySetting setting must have a default.")
        }
      }
    ```

4. Add a new benchmark flag to [BenchmarkArguments.swift](https://github.com/tensorflow/swift-models/blob/main/SwiftModelsBenchmarksCore/BenchmarkArguments.swift):

    a. Add a flag property:

    ```swift
    @Option(help: "Useful description of MySetting here.")
    var mySettingFlagName: String?
    ```

    b. Validate your flag value in `BenchmarkArguments.validate()` function if necessary.

    c. Convert command-line flag to a setting in `BenchmarkArgument.settings` computed property:

    ```swift
      if let value = mySettingFlagName {
        settings.append(MySetting(value))
      }
    ```


text:
import {Component,OnInit} from '@angular/core';
import {Car} from '../domain/car';
import {CarService} from '../service/carservice';

@Component({
    templateUrl: 'showcase/demo/datatable/datatablecolresizedemo.html'
})
export class DataTableColResizeDemo implements OnInit {

    cars: Car[];

    constructor(private carService: CarService) { }

    ngOnInit() {
        this.carService.getCarsSmall().then(cars => this.cars = cars);
    }
}


text:
'use strict';

import { coalesce } from 'vs/base/common/arrays';
import { onUnexpectedExternalError } from 'vs/base/common/errors';
import { TPromise } from 'vs/base/common/winjs.base';
import { ITextModel } from 'vs/editor/common/model';
import { registerDefaultLanguageCommand } from 'vs/editor/browser/editorExtensions';
import { Hover, HoverProviderRegistry } from 'vs/editor/common/modes';
import { asWinJsPromise } from 'vs/base/common/async';
import { Position } from 'vs/editor/common/core/position';

export function getHover(model: ITextModel, position: Position): TPromise<Hover[]> {

	const supports = HoverProviderRegistry.ordered(model);
	const values: Hover[] = [];

	const promises = supports.map((support, idx) => {
		return asWinJsPromise((token) => {
			return support.provideHover(model, position, token);
		}).then((result) => {
			if (result) {
				let hasRange = (typeof result.range !== 'undefined');
				let hasHtmlContent = typeof result.contents !== 'undefined' && result.contents && result.contents.length > 0;
				if (hasRange && hasHtmlContent) {
					values[idx] = result;
				}
			}
		}, err => {
			onUnexpectedExternalError(err);
		});
	});

	return TPromise.join(promises).then(() => coalesce(values));
}

registerDefaultLanguageCommand('_executeHoverProvider', getHover);


text:
define(['aura_base'], function(base) {

  'use strict';

  var core = {}; // Mediator object
  var channels = {}; // Loaded modules and their callbacks
  var emitQueue = [];
  var isWidgetLoading = false;
  var WIDGETS_PATH = '../../../widgets'; // Path to widgets

  // Load in the base library, such as Zepto or jQuery. the following are
  // required for Aura to run:
  //
  // * base.data.deferred
  // * base.data.when
  // * base.data.dom.find
  (function() {
    if (typeof base === undefined) {
      throw new Error('Base library is required');
    }

    if (!base.data) {
      throw new Error('Base library must include the data property');
    }

    if (!base.data.deferred) {
      throw new Error('Base library must include data.deferred');
    }

    if (!base.data.when) {
      throw new Error('Base library must include data.when');
    }

    if (!base.dom) {
      throw new Error('Base library must include the dom property');
    }

    if (!base.dom.find) {
      throw new Error('Base library must include dom.find');
    }

    core = base;

  }());

  // The bind method is used for callbacks.
  //
  // * (bind)[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind]
  // * (You don't need to use $.proxy)[http://www.aaron-powell.com/javascript/you-dont-need-jquery-proxy]
  if (!Function.prototype.bind) {
    Function.prototype.bind = function(oThis) {
      if (typeof this !== "function") {
        // closest thing possible to the ECMAScript 5 internal IsCallable function
        throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
      }

      var aArgs = Array.prototype.slice.call(arguments, 1);
      var fToBind = this;
      var FNOP = function() {};
      var FBound = function() {
          return fToBind.apply(this instanceof FNOP && oThis ? this : oThis,
          aArgs.concat(Array.prototype.slice.call(arguments)));
        };

      FNOP.prototype = this.prototype;
      FBound.prototype = new FNOP();

      return FBound;
    };
  }

  // Returns true if an object is an array, false if it is not.
  //
  // * (isArray)[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray]
  if (!Array.isArray) {
    Array.isArray = function(vArg) {
      return Object.prototype.toString.call(vArg) === "[object Array]";
    };
  }

  // Decamelize a string and add a delimeter before any
  // previously capitalized letters
  function decamelize(camelCase, delimiter) {
    delimiter = (delimiter === undefined) ? '_' : delimiter;
    return camelCase.replace(/([A-Z])/g, delimiter + '$1').toLowerCase();
  }

  // Is a given variable an object? (via zepto)
  function isObject(obj) {
    return obj instanceof Object;
  }

  // Get the widgets path
  core.getWidgetsPath = function() {
    return WIDGETS_PATH;
  };

  // Subscribe to an event
  //
  // * **param:** {string} channel Event name
  // * **param:** {string} subscriber Subscriber name
  // * **param:** {function} callback Module callback
  // * **param:** {object} context Context in which to execute the module
  core.on = function(channel, subscriber, callback, context) {
    if (channel === undefined || callback === undefined || context === undefined) {
      throw new Error('Channel, callback, and context must be defined');
    }
    if (typeof channel !== 'string') {
      throw new Error('Channel must be a string');
    }
    if (typeof subscriber !== 'string') {
      throw new Error('Subscriber must be a string');
    }
    if (typeof callback !== 'function') {
      throw new Error('Callback must be a function');
    }

    channels[channel] = (!channels[channel]) ? [] : channels[channel];

    if(channel === '*'){
      for (var key in channels) {
        if (channels.hasOwnProperty(key)) {
            channels[key].push({
               subscriber: subscriber,
               callback: callback.bind(context)
            });
        }
      }
    }else{
      channels[channel].push({
        subscriber: subscriber,
        callback: callback.bind(context)
        // callback: this.util.method(callback, context)
      });
    }

  };

  core.getEmitQueueLength = function() {
    return emitQueue.length;
  };

  // Publish an event, passing arguments to subscribers. Will
  // call start if the channel is not already registered.
  //
  // * **param:** {string} channel Event name
  core.emit = function(channel) {
    if (channel === undefined) {
      throw new Error('Channel must be defined');
    }
    if (typeof channel !== 'string') {
      throw new Error('Channel must be a string');
    }
    if (isWidgetLoading) { // Catch emit event!
      emitQueue.push(arguments);
      return false;
    }

    var i, l;
    var args = [].slice.call(arguments, 1);
    if (!channels[channel]) {
      return false;
    }
    for (i = 0; i < channels[channel].length; i++) {

      // if the callback has been nulled by core.stop, remove this subscriber
      if (channels[channel][i].callback == null) {
        channels[channel].splice(i, 1);

        // since we are removing the subscriber at this index, set the iterator
        // back, so we try this index again
        i--;

      // otherwise proceed normally: try the callback and iterate
      } else {
        try {
          channels[channel][i].callback.apply(this, args);
        }
        catch (e) {
          console.error(e.message);
        }
      }
    }

    return true;
  };

  // Empty the list with all stored emit events.
  core.emptyEmitQueue = function() {
    var args, i, len;
    isWidgetLoading = false;

    for (i = 0, len = emitQueue.length; i < len; i++) {
      core.emit.apply(this, emitQueue[i]);
    }

    // _.each(emitQueue, function(args) {
    //  core.emit.apply(this, args);
    // });

    emitQueue = [];
  };

  // Automatically load a widget and initialize it. File name of the
  // widget will be derived from the channel, decamelized and underscore
  // delimited by default.
  //
  // * **param:** {Object/Array} an array with objects or single object containing channel and options
  core.start = function(list) {
    var args = [].slice.call(arguments, 1);

    // Allow pair channel & options as params
    if (typeof list === 'string' && args[0] !== undefined) {
      list = [{
        channel : list,
        options : args[0]
      }];
    }

    // Allow a single object as param
    if (isObject(list) && !Array.isArray(list)) {
      list = [list];
    }

    if (!Array.isArray(list)) {
      throw new Error('Channel must be defined as an array');
    }

    var i = 0;
    var l = list.length;
    var promises = [];

    function load(file, options) {
      var dfd = core.data.deferred();
      var widgetsPath = core.getWidgetsPath();
      var requireConfig = require.s.contexts._.config;

      if (requireConfig.paths && requireConfig.paths.hasOwnProperty('widgets')) {
        widgetsPath = requireConfig.paths.widgets;
      }

      require([widgetsPath + '/' + file + '/main'], function(main) {
        try {
          main(options);
        } catch (e) {
          console.error(e);
        }
        dfd.resolve();
      }, function(err) {
        if (err.requireType === 'timeout') {
          console.warn('Could not load module ' + err.requireModules);
        } else {
          // If a timeout hasn't occurred and there was another module
          // related error, unload the module then throw an error
          var failedId = err.requireModules && err.requireModules[0];
          require.undef(failedId);
          throw err;
        }
        dfd.reject();
      });

      return dfd.promise();
    }

    isWidgetLoading = true;

    for (; i < l; i++) {
      var widget = list[i];
      var file = decamelize(widget.channel);

      promises.push(load(file, widget.options || {}));
    }

    core.data.when.apply($, promises).done(core.emptyEmitQueue);
  };

  // Unload a widget (collection of modules) by passing in a named reference
  // to the channel/widget. This will both locate and reset the internal
  // state of the modules in require.js and empty the widgets DOM element
  //
  // * **param:** {string} channel Event name
  // * **param:** {string} el Element name (Optional)
  core.stop = function(channel, el) {
    var file = decamelize(channel);

    for (var ch in channels) {
      if (channels.hasOwnProperty(ch)) {
        for (var i = 0, l = channels[ch].length; i < l; i++) {
          if (channels[ch][i].subscriber === channel) {

            // If core.stop is being called as a callback to core.emit,
            // removing the subscriber at this point can cause an error with
            // emit's iterator going longer than the changed array length.
            // Set the callback to null and have core.emit check this.
            channels[ch][i].callback = null;
          }
        }
      }
    }
    // Remove all modules under a widget path (e.g widgets/todos)
    core.unload('widgets/' + file);

    // Remove widget descendents, unbinding any event handlers
    // attached to children within the widget.
    if(el) {
      core.dom.find(el).children().remove();
    }
  };

  // Undefine/unload a module, resetting the internal state of it in require.js
  // to act like it wasn't loaded. By default require won't cleanup any markup
  // associated with this
  //
  // The interesting challenge with .stop() is that in order to correctly clean-up
  // one would need to maintain a custom track of dependencies loaded for each
  // possible channel, including that channels DOM elements per dependency.
  //
  // This issue with this is shared dependencies. E.g, say one loaded up a module
  // containing jQuery, others also use jQuery and then the module was unloaded.
  // This would cause jQuery to also be unloaded if the entire tree was being done
  // so.
  //
  // A simpler solution is to just remove those modules that fall under the
  // widget path as we know those dependencies (e.g models, views etc) should only
  // belong to one part of the codebase and shouldn't be depended on by others.
  //
  // * **param:** {string} channel Event name
  core.unload = function(channel) {
    var key;
    var contextMap = require.s.contexts._.defined;

    for (key in contextMap) {
      if (contextMap.hasOwnProperty(key) && key.indexOf(channel) !== -1) {
        require.undef(key);
      }
    }
  };

  core.getChannels = function() {
    return channels;
  };

  return core;

});


text:
<Mapper>
  <fileName>UserMapper</fileName>
  <suffix>xml</suffix>
  <namespace>org.qxp.mapper</namespace>
  <insertList>
    <org.qxp.ctrl.mybatis.xml.po.Insert>
      <id>addUser1</id>
      <flushCache>true1</flushCache>
      <sql>insert into user(1)</sql>
    </org.qxp.ctrl.mybatis.xml.po.Insert>
    <org.qxp.ctrl.mybatis.xml.po.Insert>
      <id>addUser2</id>
      <flushCache>true2</flushCache>
      <sql>insert into user(2)</sql>
    </org.qxp.ctrl.mybatis.xml.po.Insert>
    <org.qxp.ctrl.mybatis.xml.po.Insert>
      <id>addUser3</id>
      <flushCache>true3</flushCache>
      <sql>insert into user(3)</sql>
    </org.qxp.ctrl.mybatis.xml.po.Insert>
  </insertList>
  <updateList>
    <org.qxp.ctrl.mybatis.xml.po.Update>
      <id>addUser1</id>
      <flushCache>true1</flushCache>
      <sql>insert into user(1)</sql>
    </org.qxp.ctrl.mybatis.xml.po.Update>
    <org.qxp.ctrl.mybatis.xml.po.Update>
      <id>addUser2</id>
      <flushCache>true2</flushCache>
      <sql>insert into user(2)</sql>
    </org.qxp.ctrl.mybatis.xml.po.Update>
    <org.qxp.ctrl.mybatis.xml.po.Update>
      <id>addUser3</id>
      <flushCache>true3</flushCache>
      <sql>insert into user(3)</sql>
    </org.qxp.ctrl.mybatis.xml.po.Update>
  </updateList>
  <selectList>
    <org.qxp.ctrl.mybatis.xml.po.Select>
      <id>findUser1</id>
      <resultType>java.lang.Integer1</resultType>
      <flushCache>true1</flushCache>
      <sql>select * from tb_user1</sql>
    </org.qxp.ctrl.mybatis.xml.po.Select>
    <org.qxp.ctrl.mybatis.xml.po.Select>
      <id>findUser2</id>
      <resultType>java.lang.Integer2</resultType>
      <flushCache>true2</flushCache>
      <sql>select * from tb_user2</sql>
    </org.qxp.ctrl.mybatis.xml.po.Select>
    <org.qxp.ctrl.mybatis.xml.po.Select>
      <id>findUser3</id>
      <resultType>java.lang.Integer3</resultType>
      <flushCache>true3</flushCache>
      <sql>select * from tb_user3</sql>
    </org.qxp.ctrl.mybatis.xml.po.Select>
  </selectList>
</Mapper>


text:
package org.apache.hadoop.hive.common.io;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

/**
 * Used for identifying the related object of the buffer stored in cache.
 * Comes in 3 flavours to optimize for minimal memory overhead:
 * - TableCacheTag for tables without partitions: DB/table level
 * - SinglePartitionCacheTag for tables with 1 partition level: DB/table/1st_partition
 * - MultiPartitionCacheTag for tables with >1 partition levels:
 *     DB/table/1st_partition/.../nth_partition .
 */
public abstract class CacheTag implements Comparable<CacheTag> {

  private static final String ENCODING = "UTF-8";

  /**
   * Prepended by DB name and '.' .
   */
  protected final String tableName;

  private CacheTag(String tableName) {
    this.tableName = tableName.intern();
  }

  public String getTableName() {
    return tableName;
  }

  @Override
  public int compareTo(CacheTag o) {
    if (o == null) {
      return 1;
    }
    return tableName.compareTo(o.tableName);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == null || !(obj instanceof CacheTag)) {
      return false;
    } else {
      return this.compareTo((CacheTag) obj) == 0;
    }
  }

  @Override
  public int hashCode() {
    int res = tableName.hashCode();
    return res;
  }

  public static final CacheTag build(String tableName) {
    if (StringUtils.isEmpty(tableName)) {
      throw new IllegalArgumentException();
    }
    return new TableCacheTag(tableName);
  }

  public static final CacheTag build(String tableName, LinkedHashMap<String, String> partDescMap) {
    if (StringUtils.isEmpty(tableName) || partDescMap == null || partDescMap.isEmpty()) {
      throw new IllegalArgumentException();
    }

    String[] partDescs = new String[partDescMap.size()];
    int i = 0;

    for (Map.Entry<String, String> entry : partDescMap.entrySet()) {
      partDescs[i++] = encodePartDesc(entry.getKey(), entry.getValue());
    }

    if (partDescs.length == 1) {
      return new SinglePartitionCacheTag(tableName, partDescs[0]);
    } else {
      // In this case it must be >1
      return new MultiPartitionCacheTag(tableName, partDescs);
    }
  }

  /**
   * Constructs a (fake) parent CacheTag instance by walking back in the hierarchy i.e. stepping
   * from inner to outer partition levels, then producing a CacheTag for the table and finally
   * the DB.
   */
  public static final CacheTag createParentCacheTag(CacheTag tag) {
    if (tag == null) {
      throw new IllegalArgumentException();
    }

    if (tag instanceof MultiPartitionCacheTag) {
      MultiPartitionCacheTag multiPartitionCacheTag = (MultiPartitionCacheTag) tag;
      if (multiPartitionCacheTag.partitionDesc.length > 2) {
        String[] subList = new String[multiPartitionCacheTag.partitionDesc.length - 1];
        for (int i = 0; i < subList.length; ++i) {
          subList[i] = multiPartitionCacheTag.partitionDesc[i];
        }
        return new MultiPartitionCacheTag(multiPartitionCacheTag.tableName, subList);
      } else {
        return new SinglePartitionCacheTag(multiPartitionCacheTag.tableName,
            multiPartitionCacheTag.partitionDesc[0]);
      }
    }

    if (tag instanceof SinglePartitionCacheTag) {
      return new TableCacheTag(tag.tableName);
    } else {
      // DB level
      int ix = tag.tableName.indexOf(".");
      if (ix <= 0) {
        return null;
      }
      return new TableCacheTag(tag.tableName.substring(0, ix));
    }

  }

  /**
   * CacheTag for tables without partitions.
   */
  public static final class TableCacheTag extends CacheTag {

    private TableCacheTag(String tableName) {
      super(tableName);
    }

    @Override
    public int compareTo(CacheTag o) {
      if (o == null) {
        return 1;
      }
      if (o instanceof SinglePartitionCacheTag || o instanceof MultiPartitionCacheTag) {
        return -1;
      } else {
        return super.compareTo(o);
      }
    }

  }

  /**
   * CacheTag for tables with partitions.
   */
  public abstract static class PartitionCacheTag extends CacheTag {

    private PartitionCacheTag(String tableName) {
      super(tableName);
    }

    /**
     * Returns a pretty printed String version of the partitionDesc in the format of p1=v1/p2=v2...
     * @return the pretty printed String
     */
    public abstract String partitionDescToString();

    /**
     * Returns a map of partition keys and values built from the information of this CacheTag.
     * @return the map
     */
    public abstract LinkedHashMap<String, String> getPartitionDescMap();

  }

  /**
   * CacheTag for tables with exactly one partition level.
   */
  public static final class SinglePartitionCacheTag extends PartitionCacheTag {

    private final String partitionDesc;

    private SinglePartitionCacheTag(String tableName, String partitionDesc) {
      super(tableName);
      if (StringUtils.isEmpty(partitionDesc)) {
        throw new IllegalArgumentException();
      }
      this.partitionDesc = partitionDesc.intern();
    }

    @Override
    public String partitionDescToString() {
      return String.join("=", CacheTag.decodePartDesc(partitionDesc));
    }

    @Override
    public LinkedHashMap<String, String> getPartitionDescMap() {
      LinkedHashMap<String, String> result = new LinkedHashMap<>();
      String[] partition = CacheTag.decodePartDesc(partitionDesc);
      result.put(partition[0], partition[1]);
      return result;
    }

    @Override
    public int compareTo(CacheTag o) {
      if (o == null) {
        return 1;
      }
      if (o instanceof TableCacheTag) {
        return 1;
      } else if (o instanceof MultiPartitionCacheTag) {
        return -1;
      }
      SinglePartitionCacheTag other = (SinglePartitionCacheTag) o;
      int tableNameDiff = super.compareTo(other);
      if (tableNameDiff != 0) {
        return tableNameDiff;
      } else {
        return partitionDesc.compareTo(other.partitionDesc);
      }
    }

    @Override
    public int hashCode() {
      return super.hashCode() + partitionDesc.hashCode();
    }
  }

  /**
   * CacheTag for tables with more than one partition level.
   */
  public static final class MultiPartitionCacheTag extends PartitionCacheTag {

    private final String[] partitionDesc;

    private MultiPartitionCacheTag(String tableName, String[] partitionDesc) {
      super(tableName);
      if (partitionDesc != null && partitionDesc.length > 1) {
        for (int i = 0; i < partitionDesc.length; ++i) {
          partitionDesc[i] = partitionDesc[i].intern();
        }
        this.partitionDesc = partitionDesc;
      } else {
        throw new IllegalArgumentException();
      }
    }

    @Override
    public int compareTo(CacheTag o) {
      if (o == null) {
        return 1;
      }
      if (o instanceof TableCacheTag || o instanceof SinglePartitionCacheTag) {
        return 1;
      }
      MultiPartitionCacheTag other = (MultiPartitionCacheTag) o;
      int tableNameDiff = super.compareTo(other);
      if (tableNameDiff != 0) {
        return tableNameDiff;
      } else {
        int sizeDiff = partitionDesc.length - other.partitionDesc.length;
        if (sizeDiff != 0) {
          return sizeDiff;
        } else {
          for (int i = 0; i < partitionDesc.length; ++i) {
            int partDiff = partitionDesc[i].compareTo(other.partitionDesc[i]);
            if (partDiff != 0) {
              return partDiff;
            }
          }
          return 0;
        }
      }
    }

    @Override
    public int hashCode() {
      int res = super.hashCode();
      for (String p : partitionDesc) {
        res += p.hashCode();
      }
      return res;
    }

    @Override
    public String partitionDescToString() {
      StringBuilder sb = new StringBuilder();
      for (String partDesc : partitionDesc) {
        String[] partition = CacheTag.decodePartDesc(partDesc);
        sb.append(partition[0]).append('=').append(partition[1]);
        sb.append('/');
      }
      sb.deleteCharAt(sb.length() - 1);
      return sb.toString();
    }

    @Override
    public LinkedHashMap<String, String> getPartitionDescMap() {
      LinkedHashMap<String, String> result = new LinkedHashMap<>();
      for (String partDesc : partitionDesc) {
        String[] partition = CacheTag.decodePartDesc(partDesc);
        result.put(partition[0], partition[1]);
      }
      return result;
    }
  }

  /**
   * Combines partition key and value Strings into one by encoding each and concating with '=' .
   * @param partKey
   * @param partVal
   * @return
   */
  private static String encodePartDesc(String partKey, String partVal) {
    try {
      StringBuilder sb = new StringBuilder();
      sb.append(
          URLEncoder.encode(partKey, ENCODING))
          .append('=')
          .append(URLEncoder.encode(partVal, ENCODING));
      return sb.toString();
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * Splits and decodes an a partition desc String encoded by encodePartDesc().
   * @param partDesc
   * @return
   */
  private static String[] decodePartDesc(String partDesc) {
    try {
      String[] encodedPartDesc = partDesc.split("=");
      assert encodedPartDesc.length == 2;
      return new String[] {
          URLDecoder.decode(encodedPartDesc[0], ENCODING),
          URLDecoder.decode(encodedPartDesc[1], ENCODING)};
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }

}


text:
macro(ament_libraries_deduplicate VAR)
  ament_libraries_pack_build_configuration(_packed ${ARGN})
  set(_unique "")
  foreach(_lib ${_packed})
    # remove existing value if it exists
    list(REMOVE_ITEM _unique ${_lib})
    # append value to the end
    list(APPEND _unique ${_lib})
  endforeach()
  ament_libraries_unpack_build_configuration(${VAR} ${_unique})
endmacro()


text:
package org.apereo.cas.web.support.config;

import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.web.support.AbstractInMemoryThrottledSubmissionHandlerInterceptorAdapter;
import org.apereo.cas.web.support.AbstractThrottledSubmissionHandlerInterceptorAdapter;
import org.apereo.cas.web.support.InMemoryThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapter;
import org.apereo.cas.web.support.InMemoryThrottledSubmissionByIpAddressHandlerInterceptorAdapter;
import org.apereo.cas.web.support.InMemoryThrottledSubmissionCleaner;
import org.apereo.cas.web.support.ThrottledSubmissionHandlerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * This is {@link CasThrottlingConfiguration}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
@Configuration("casThrottlingConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class CasThrottlingConfiguration {

    @Autowired
    private CasConfigurationProperties casProperties;

    @RefreshScope
    @ConditionalOnMissingBean(name = "authenticationThrottle")
    @Bean(name = {"defaultAuthenticationThrottle", "authenticationThrottle"})
    public ThrottledSubmissionHandlerInterceptor defaultAuthenticationThrottle() {

        if (casProperties.getAuthn().getThrottle().getFailure().getThreshold() > 0
                && casProperties.getAuthn().getThrottle().getFailure().getRangeSeconds() > 0) {
            if (StringUtils.isNotBlank(casProperties.getAuthn().getThrottle().getUsernameParameter())) {
                return inMemoryIpAddressUsernameThrottle();
            }
            return inMemoryIpAddressThrottle();
        }
        return neverThrottle();
    }

    @Bean
    public Runnable throttleSubmissionCleaner(@Qualifier("authenticationThrottle")
                                              final ThrottledSubmissionHandlerInterceptor adapter) {
        return new InMemoryThrottledSubmissionCleaner(adapter);
    }

    private ThrottledSubmissionHandlerInterceptor inMemoryIpAddressUsernameThrottle() {
        return configureInMemoryInterceptorAdaptor(
                new InMemoryThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapter());
    }

    private ThrottledSubmissionHandlerInterceptor inMemoryIpAddressThrottle() {
        return configureInMemoryInterceptorAdaptor(
                new InMemoryThrottledSubmissionByIpAddressHandlerInterceptorAdapter());
    }

    private static ThrottledSubmissionHandlerInterceptor neverThrottle() {
        return new ThrottledSubmissionHandlerInterceptor() {
        };
    }

    private AbstractThrottledSubmissionHandlerInterceptorAdapter
    configureThrottleHandlerInterceptorAdaptor(final AbstractThrottledSubmissionHandlerInterceptorAdapter interceptorAdapter) {
        interceptorAdapter.setUsernameParameter(casProperties.getAuthn().getThrottle().getUsernameParameter());
        interceptorAdapter.setFailureThreshold(casProperties.getAuthn().getThrottle().getFailure().getThreshold());
        interceptorAdapter.setFailureRangeInSeconds(casProperties.getAuthn().getThrottle().getFailure().getRangeSeconds());
        return interceptorAdapter;
    }

    private ThrottledSubmissionHandlerInterceptor
    configureInMemoryInterceptorAdaptor(final AbstractInMemoryThrottledSubmissionHandlerInterceptorAdapter interceptorAdapter) {
        return configureThrottleHandlerInterceptorAdaptor(interceptorAdapter);
    }

}


text:
package net.imagej.ops.special.chain;

import net.imagej.ops.special.inplace.BinaryInplaceOnlyOp;
import net.imagej.ops.special.inplace.BinaryInplaceOp;

/**
 * Base class for {@link BinaryInplaceOnlyOp}s that delegate to
 * {@link BinaryInplaceOp}s with all matching types (inputs same as output).
 *
 * @author Curtis Rueden
 * @param <A> type of inputs and output (for both the op and its worker)
 * @see BIOViaBI
 */
public abstract class BIOViaBISame<A> extends BIOViaBI<A, A, A> {
	// NB: No implementation needed.
}


text:
title: Projekte
menu:
  main:
    weight: 40
    name: Projekte
---

{{< headline-icon icon="icon-documents.svg" color="blue" >}}

{{< headline-brackets-h1 color="red"  >}}
Unsere Projekte
{{< /headline-brackets-h1  >}}

{{< hero-block-center  >}}
In unseren Labs entstehen Projekte, die aufzeigen, welchen Mehrwert Offene Daten und Freie und Offene Software für unsere Gesellschaft bieten und wie diese Open Government begünstigen.
{{< /hero-block-center  >}}

{{< paragraph-center  >}}
In unseren prototypischen Anwendungen werden die Offenen Daten z. B. durch Visualisierungen für alle Menschen zugänglich gemacht. So sind komplexe Informationen leichter zu verstehen. Die Projekte orientieren sich an den jeweiligen lokalen Bedarfen. Gleichzeitig sind sie darauf ausgerichtet, Synergien zwischen kommunalen Verwaltungen deutschlandweit zu schaffen.
{{< /paragraph-center  >}}


text:
package org.jivesoftware.openfire.plugin.gojara.sessions;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.jivesoftware.openfire.plugin.gojara.database.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This is the central point for doing anything Gojara GatewaySession related. We keep track of Users connected to
 * Transports, stats about these and provide some methods for Presentation in JSP Pages.
 *
 * @author axel.frederik.brand
 */
public class TransportSessionManager {
	private static TransportSessionManager myself;
	private DatabaseManager db;
	private GojaraAdminManager adminManager;
	private Map<String, Map<String, Long>> transportSessions = new ConcurrentHashMap<String, Map<String, Long>>(16, 0.75f, 1);
	private static final Logger Log = LoggerFactory.getLogger(TransportSessionManager.class);

	private TransportSessionManager() {
		db = DatabaseManager.getInstance();
		adminManager = GojaraAdminManager.getInstance();
		Log.info(" Created TransportSessionManager");
	}

	public static synchronized TransportSessionManager getInstance() {
		if (myself == null) {
			myself = new TransportSessionManager();
		}
		return myself;
	}

	/**
	 * adds a subdomain to watched transports
	 *
	 * @param subdomain
	 */
	public void addTransport(String subdomain) {
		transportSessions.put(subdomain, new ConcurrentHashMap<String, Long>(64, 0.75f, 1));
		Log.debug("Added key to transportSessionMap: " + subdomain);
	}

	/**
	 * removes subdomain from watched transports
	 *
	 * @param subdomain
	 */
	public void removeTransport(String subdomain) {
		transportSessions.remove(subdomain);
		Log.debug("Removed " + subdomain + "from TransportSessionMap ");

	}

	public boolean isTransportActive(String subdomain) {
		return transportSessions.containsKey(subdomain) ? true : false;
	}

	/**
	 * register is seperate to connect because a user may register to transport but not connect to it, e.g. with wrong credentials.
	 * we still want to keep track of those registrations so we know they happened and we can reset them
	 *
	 * @param transport
	 * @param user
	 */
	public void registerUserTo(String transport, String user) {
		db.insertOrUpdateSession(transport, user, 0);
	}

	/**
	 * Add the session of user that connected to gateway and update or create timestamp for session
	 *
	 * @param transport
	 * @param user
	 * @return
	 */
	public boolean connectUserTo(String transport, String user) {
		//dont update if user is already present, else lots of away to online changes might be spammed
		if (transportSessions.get(transport) != null && transportSessions.get(transport).get(user) == null) {
			long millis = System.currentTimeMillis();
			transportSessions.get(transport).put(user, millis);
			db.insertOrUpdateSession(transport, user, millis);
			return true;
		}
		return false;
	}

	public boolean disconnectUserFrom(String transport, String user) {
//		Log.debug("Trying to remove User " + JID.nodeprep(user) + " from Session for Transport " + transport);
		if (isUserConnectedTo(transport, user)) {
			transportSessions.get(transport).remove(user);
			return true;
		}
		return false;
	}

	public boolean isUserConnectedTo(String transport, String user) {
		return transportSessions.get(transport).containsKey(user);
	}

	/**
	 *
	 * Removes registration from our database.
	 *
	 * @param transport
	 * @param user
	 * @return String that describes what happened.
	 */
	public void removeRegistrationOfUserFromDB(String transport, String user) {
		db.removeSessionEntry(transport, user);
	}
	/**
	 * Initializes Sessions through adminmanager, ofc needs to be called at a point where there are Transports registered in
	 * transportSessions
	 */
	public void initializeSessions() {
		Log.info("Initializing Sessions.");
		for (String transport : transportSessions.keySet()) {
			adminManager.getOnlineUsersOf(transport);
		}
	}

	/**
	 * @return Set of currently active Gateways
	 */
	public final Set<String>getActiveGateways() {
		return transportSessions.keySet();
	}

	public final Map<String, Map<String, Long>> getSessions() {
		return transportSessions;
	}

	/**
	 * Puts all Sessions into an ArrayList of GatewaySession Objects, and sorts it according to specified sorting
	 * attributes.
	 *
	 * @param sortby
	 *            username, transport or LoginTime
	 * @param sortorder
	 *            ASC or DESC
	 * @return Sorted/Unsorted ArrayList of GatewaySession Objects
	 */
	public ArrayList<GatewaySession> getSessionsSorted(String sortby, String sortorder) {
		ArrayList<GatewaySession> result = new ArrayList<GatewaySession>(getNumberOfActiveSessions());
		for (Map.Entry<String, Map<String,Long>> gateway : transportSessions.entrySet()) {
			for (Map.Entry<String, Long> entry : gateway.getValue().entrySet()) {
				Timestamp stamp = new Timestamp(entry.getValue());
				Date date = new Date(stamp.getTime());
				result.add(new GatewaySession(entry.getKey(), gateway.getKey(), date));
			}
		}

		if (sortby.equals("username")) {
			Collections.sort(result, new SortUserName());
		} else if (sortby.equals("transport")) {
			Collections.sort(result, new SortTransport());
		} else if (sortby.equals("loginTime")) {
			Collections.sort(result, new SortLastActivity());
		}
		if (sortorder.equals("DESC")) {
			Collections.reverse(result);
		}
		return result;
	}

	/**
	 * @return count of recognized active Sessions
	 */
	public int getNumberOfActiveSessions() {
		int result = 0;
		for (Map.Entry<String, Map<String,Long>> gateway : transportSessions.entrySet()) {
			result += gateway.getValue().size();
		}
		return result;
	}

	/**
	 * Returns number of active Sessions for specified transport or 0 if not valid transport.
	 * @param transport
	 * @return
	 */
	public int getNumberOfActiveSessionsFor(String transport) {
		if (transportSessions.containsKey(transport))
			return transportSessions.get(transport).size();
		return 0;
	}

	/**
	 * Searches for Sessions with given Username and returns them as ArrList
	 *
	 * @param username
	 * @return
	 */
	public ArrayList<GatewaySession> getConnectionsFor(String username) {
		ArrayList<GatewaySession> userconnections = new ArrayList<GatewaySession>();
		for (Map.Entry<String, Map<String, Long>> transport : transportSessions.entrySet()) {
			if (transport.getValue().containsKey(username)) {
				Timestamp stamp = new Timestamp(transport.getValue().get(username));
				Date date = new Date(stamp.getTime());
				userconnections.add(new GatewaySession(username, transport.getKey(), date));
			}
		}
		return userconnections;
	}

	/**
	 * Returns Registrations associated with Username
	 *
	 * @param username
	 * @return ArrayList of SessionEntries
	 */
	public ArrayList<SessionEntry> getRegistrationsFor(String username) {
		return db.getSessionEntriesFor(username);
	}

	/**
	 * Get all registrations sorted by attribute and order. Validation for correctness of attributes is done in DB
	 * Manager, returns default sorting: username ASC when not valid
	 */
	public ArrayList<SessionEntry> getAllRegistrations(String orderAttr, String order) {
		return db.getAllSessionEntries(orderAttr, order);
	}

	public int getNumberOfRegistrations() {
		return db.getNumberOfRegistrations();
	}

	public int getNumberOfRegistrationsForTransport(String transport) {
		if (transportSessions.containsKey(transport)) {
			return db.getNumberOfRegistrationsForTransport(transport);
		}
		return 0;
	}
}