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

#include "services/network/trust_tokens/trust_token_request_issuance_helper.h"

#include <memory>

#include "base/callback.h"
#include "base/test/task_environment.h"
#include "net/base/load_flags.h"
#include "net/base/request_priority.h"
#include "net/http/http_response_headers.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_test_util.h"
#include "services/network/public/mojom/trust_tokens.mojom.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "services/network/trust_tokens/proto/public.pb.h"
#include "services/network/trust_tokens/test/trust_token_test_util.h"
#include "services/network/trust_tokens/trust_token_http_headers.h"
#include "services/network/trust_tokens/trust_token_key_commitment_getter.h"
#include "services/network/trust_tokens/trust_token_parameterization.h"
#include "services/network/trust_tokens/trust_token_store.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/origin.h"

namespace network {

namespace {

using ::testing::_;
using ::testing::ByMove;
using ::testing::ElementsAre;
using ::testing::Property;
using ::testing::Return;
using ::testing::ReturnNull;

using TrustTokenRequestIssuanceHelperTest = TrustTokenRequestHelperTest;
using UnblindedTokens =
    TrustTokenRequestIssuanceHelper::Cryptographer::UnblindedTokens;

// FixedKeyCommitmentGetter returns the provided commitment result when
// |Get| is called by the tested code.
class FixedKeyCommitmentGetter : public TrustTokenKeyCommitmentGetter {
 public:
  FixedKeyCommitmentGetter() = default;
  explicit FixedKeyCommitmentGetter(
      const url::Origin& issuer,
      mojom::TrustTokenKeyCommitmentResultPtr result)
      : issuer_(issuer), result_(std::move(result)) {}

  void Get(const url::Origin& origin,
           base::OnceCallback<void(mojom::TrustTokenKeyCommitmentResultPtr)>
               on_done) const override {
    EXPECT_EQ(origin, issuer_);
    std::move(on_done).Run(result_.Clone());
  }

 private:
  url::Origin issuer_;
  mojom::TrustTokenKeyCommitmentResultPtr result_;
};

base::NoDestructor<FixedKeyCommitmentGetter> g_fixed_key_commitment_getter{};

// MockCryptographer mocks out the cryptographic operations underlying Trust
// Tokens issuance.
class MockCryptographer
    : public TrustTokenRequestIssuanceHelper::Cryptographer {
 public:
  MOCK_METHOD1(Initialize, bool(int issuer_configured_batch_size));
  MOCK_METHOD1(AddKey, bool(base::StringPiece key));
  MOCK_METHOD1(BeginIssuance, base::Optional<std::string>(size_t num_tokens));
  MOCK_METHOD1(
      ConfirmIssuance,
      std::unique_ptr<UnblindedTokens>(base::StringPiece response_header));
};

}  // namespace

// Check that issuance fails if it would result in too many issuers being
// configured for the issuance top-level origin.
TEST_F(TrustTokenRequestIssuanceHelperTest, RejectsIfTooManyIssuers) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  auto issuer = *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));
  auto toplevel =
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/"));

  // Associate the toplevel with the cap's worth of issuers different from
  // |issuer|. (The cap is guaranteed to be quite small because of privacy
  // requirements of the Trust Tokens protocol.)
  for (int i = 0; i < kTrustTokenPerToplevelMaxNumberOfAssociatedIssuers; ++i) {
    ASSERT_TRUE(store->SetAssociation(
        *SuitableTrustTokenOrigin::Create(
            GURL(base::StringPrintf("https://issuer%d.com/", i))),
        toplevel));
  }

  TrustTokenRequestIssuanceHelper helper(toplevel, store.get(),
                                         g_fixed_key_commitment_getter.get(),
                                         std::make_unique<MockCryptographer>());

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(issuer);
  EXPECT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kResourceExhausted);
}

// Check that issuance fails if the number of tokens stored for the issuer is
// already at capacity.
TEST_F(TrustTokenRequestIssuanceHelperTest, RejectsIfAtCapacity) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  auto issuer = *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));

  // Fill up the store with tokens; issuance should fail the tokens for |issuer|
  // are at capacity.
  store->AddTokens(issuer,
                   std::vector<std::string>(kTrustTokenPerIssuerTokenCapacity),
                   /*issuing_key=*/"");

  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), g_fixed_key_commitment_getter.get(),
      std::make_unique<MockCryptographer>());

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(issuer);
  EXPECT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kResourceExhausted);
}

// Check that issuance fails if its key commitment request fails.
TEST_F(TrustTokenRequestIssuanceHelperTest, RejectsIfKeyCommitmentFails) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  SuitableTrustTokenOrigin issuer =
      *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));

  // Have the key commitment getter return nullptr, denoting that the key
  // commitment fetch failed.
  auto getter = std::make_unique<FixedKeyCommitmentGetter>(issuer, nullptr);
  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), getter.get(), std::make_unique<MockCryptographer>());

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(
      *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/")));

  EXPECT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kFailedPrecondition);
}

// Reject if initializing the cryptography delegate fails.
TEST_F(TrustTokenRequestIssuanceHelperTest,
       RejectsIfInitializingCryptographerFails) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  SuitableTrustTokenOrigin issuer =
      *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));

  auto key_commitment_result = mojom::TrustTokenKeyCommitmentResult::New();
  key_commitment_result->keys.push_back(
      mojom::TrustTokenVerificationKey::New());
  key_commitment_result->batch_size =
      static_cast<int>(kMaximumTrustTokenIssuanceBatchSize);
  auto getter = std::make_unique<FixedKeyCommitmentGetter>(
      issuer, std::move(key_commitment_result));

  auto cryptographer = std::make_unique<MockCryptographer>();
  EXPECT_CALL(*cryptographer, Initialize(_)).WillOnce(Return(false));

  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), getter.get(), std::move(cryptographer));

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(issuer);

  EXPECT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kInternalError);
}

// Reject if one of the keys in the commitment is malformed.
TEST_F(TrustTokenRequestIssuanceHelperTest, RejectsIfAddingKeyFails) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  SuitableTrustTokenOrigin issuer =
      *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));

  auto key_commitment_result = mojom::TrustTokenKeyCommitmentResult::New();
  key_commitment_result->keys.push_back(
      mojom::TrustTokenVerificationKey::New());
  key_commitment_result->batch_size =
      static_cast<int>(kMaximumTrustTokenIssuanceBatchSize);
  auto getter = std::make_unique<FixedKeyCommitmentGetter>(
      issuer, std::move(key_commitment_result));

  auto cryptographer = std::make_unique<MockCryptographer>();
  EXPECT_CALL(*cryptographer, Initialize(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, AddKey(_)).WillOnce(Return(false));

  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), getter.get(), std::move(cryptographer));

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(issuer);

  EXPECT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kFailedPrecondition);
}

// Reject if there's an error getting blinded, unsigned tokens from BoringSSL.
TEST_F(TrustTokenRequestIssuanceHelperTest,
       RejectsIfGettingBlindedTokensFails) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  SuitableTrustTokenOrigin issuer =
      *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));

  auto key_commitment_result = mojom::TrustTokenKeyCommitmentResult::New();
  key_commitment_result->keys.push_back(
      mojom::TrustTokenVerificationKey::New());
  key_commitment_result->batch_size =
      static_cast<int>(kMaximumTrustTokenIssuanceBatchSize);
  auto getter = std::make_unique<FixedKeyCommitmentGetter>(
      issuer, std::move(key_commitment_result));

  auto cryptographer = std::make_unique<MockCryptographer>();
  EXPECT_CALL(*cryptographer, Initialize(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, AddKey(_)).WillOnce(Return(true));
  // Return nullopt, denoting an error, when the issuance helper requests
  // blinded, unsigned tokens.
  EXPECT_CALL(*cryptographer, BeginIssuance(_)).WillOnce(Return(base::nullopt));

  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), getter.get(), std::move(cryptographer));

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(issuer);

  // This is an internal error because creating blinded tokens is a
  // cryptographic operation not dependent on the inputs provided by the client
  // or the protocol state.
  EXPECT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kInternalError);
}

// Check that the issuance helper sets the Sec-Trust-Token header on the
// outgoing request.
TEST_F(TrustTokenRequestIssuanceHelperTest, SetsRequestHeader) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  SuitableTrustTokenOrigin issuer =
      *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));

  auto key_commitment_result = mojom::TrustTokenKeyCommitmentResult::New();
  key_commitment_result->keys.push_back(
      mojom::TrustTokenVerificationKey::New());
  key_commitment_result->batch_size =
      static_cast<int>(kMaximumTrustTokenIssuanceBatchSize);
  auto getter = std::make_unique<FixedKeyCommitmentGetter>(
      issuer, std::move(key_commitment_result));

  // The result of providing blinded, unsigned tokens should be the exact value
  // of the Sec-Trust-Token header attached to the request.
  auto cryptographer = std::make_unique<MockCryptographer>();
  EXPECT_CALL(*cryptographer, Initialize(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, AddKey(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, BeginIssuance(_))
      .WillOnce(
          Return(std::string("this string contains some blinded tokens")));

  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), getter.get(), std::move(cryptographer));

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(issuer);

  ASSERT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kOk);

  std::string attached_header;
  EXPECT_TRUE(request->extra_request_headers().GetHeader(
      kTrustTokensSecTrustTokenHeader, &attached_header));
  EXPECT_EQ(attached_header, "this string contains some blinded tokens");
}

// Check that the issuance helper sets the LOAD_BYPASS_CACHE flag on the
// outgoing request.
TEST_F(TrustTokenRequestIssuanceHelperTest, SetsLoadFlag) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  SuitableTrustTokenOrigin issuer =
      *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));

  auto key_commitment_result = mojom::TrustTokenKeyCommitmentResult::New();
  key_commitment_result->keys.push_back(
      mojom::TrustTokenVerificationKey::New());
  key_commitment_result->batch_size =
      static_cast<int>(kMaximumTrustTokenIssuanceBatchSize);
  auto getter = std::make_unique<FixedKeyCommitmentGetter>(
      issuer, std::move(key_commitment_result));

  // The result of providing blinded, unsigned tokens should be the exact value
  // of the Sec-Trust-Token header attached to the request.
  auto cryptographer = std::make_unique<MockCryptographer>();
  EXPECT_CALL(*cryptographer, Initialize(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, AddKey(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, BeginIssuance(_))
      .WillOnce(
          Return(std::string("this string contains some blinded tokens")));

  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), getter.get(), std::move(cryptographer));

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(issuer);

  ASSERT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kOk);
  EXPECT_TRUE(request->load_flags() & net::LOAD_BYPASS_CACHE);
}

// Check that the issuance helper rejects responses lacking the Sec-Trust-Token
// response header.
TEST_F(TrustTokenRequestIssuanceHelperTest, RejectsIfResponseOmitsHeader) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  SuitableTrustTokenOrigin issuer =
      *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));

  auto key_commitment_result = mojom::TrustTokenKeyCommitmentResult::New();
  key_commitment_result->keys.push_back(
      mojom::TrustTokenVerificationKey::New());
  key_commitment_result->batch_size =
      static_cast<int>(kMaximumTrustTokenIssuanceBatchSize);
  auto getter = std::make_unique<FixedKeyCommitmentGetter>(
      issuer, std::move(key_commitment_result));

  auto cryptographer = std::make_unique<MockCryptographer>();
  EXPECT_CALL(*cryptographer, Initialize(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, AddKey(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, BeginIssuance(_))
      .WillOnce(
          Return(std::string("this string contains some blinded tokens")));

  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), getter.get(), std::move(cryptographer));

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(issuer);

  ASSERT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kOk);

  auto response_head = mojom::URLResponseHead::New();
  response_head->headers =
      net::HttpResponseHeaders::TryToCreate("HTTP/1.1 200 OK\r\n");
  EXPECT_EQ(ExecuteFinalizeAndWaitForResult(&helper, response_head.get()),
            mojom::TrustTokenOperationStatus::kBadResponse);
}

// Check that the issuance helper handles an issuance response rejected by the
// underlying cryptographic library.
TEST_F(TrustTokenRequestIssuanceHelperTest, RejectsIfResponseIsUnusable) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  SuitableTrustTokenOrigin issuer =
      *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));

  auto key_commitment_result = mojom::TrustTokenKeyCommitmentResult::New();
  key_commitment_result->keys.push_back(
      mojom::TrustTokenVerificationKey::New());
  key_commitment_result->batch_size =
      static_cast<int>(kMaximumTrustTokenIssuanceBatchSize);
  auto getter = std::make_unique<FixedKeyCommitmentGetter>(
      issuer, std::move(key_commitment_result));

  auto cryptographer = std::make_unique<MockCryptographer>();
  EXPECT_CALL(*cryptographer, Initialize(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, AddKey(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, BeginIssuance(_))
      .WillOnce(
          Return(std::string("this string contains some blinded tokens")));
  // Fail the "confirm issuance" step of validating the server's response
  // within the underlying cryptographic library.
  EXPECT_CALL(*cryptographer, ConfirmIssuance(_)).WillOnce(ReturnNull());

  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), getter.get(), std::move(cryptographer));

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(issuer);

  ASSERT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kOk);

  auto response_head = mojom::URLResponseHead::New();
  response_head->headers =
      net::HttpResponseHeaders::TryToCreate("HTTP/1.1 200 OK\r\n");
  response_head->headers->SetHeader(
      kTrustTokensSecTrustTokenHeader,
      "response from issuer (this value will be ignored, since "
      "Cryptographer::ConfirmResponse is mocked out)");
  EXPECT_EQ(ExecuteFinalizeAndWaitForResult(&helper, response_head.get()),
            mojom::TrustTokenOperationStatus::kBadResponse);

  // Verify that Finalize correctly stripped the response header.
  EXPECT_FALSE(
      response_head->headers->HasHeader(kTrustTokensSecTrustTokenHeader));
}

// Check that, when preconditions are met and the underlying cryptographic steps
// successfully complete, the begin/finalize methods succeed.
TEST_F(TrustTokenRequestIssuanceHelperTest, Success) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  SuitableTrustTokenOrigin issuer =
      *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));

  auto key_commitment_result = mojom::TrustTokenKeyCommitmentResult::New();
  key_commitment_result->keys.push_back(
      mojom::TrustTokenVerificationKey::New());
  key_commitment_result->batch_size =
      static_cast<int>(kMaximumTrustTokenIssuanceBatchSize);
  auto getter = std::make_unique<FixedKeyCommitmentGetter>(
      issuer, std::move(key_commitment_result));

  auto cryptographer = std::make_unique<MockCryptographer>();
  EXPECT_CALL(*cryptographer, Initialize(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, AddKey(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, BeginIssuance(_))
      .WillOnce(
          Return(std::string("this string contains some blinded tokens")));
  EXPECT_CALL(*cryptographer, ConfirmIssuance(_))
      .WillOnce(Return(ByMove(std::make_unique<UnblindedTokens>())));

  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), getter.get(), std::move(cryptographer));

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(issuer);

  ASSERT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kOk);

  auto response_head = mojom::URLResponseHead::New();
  response_head->headers =
      net::HttpResponseHeaders::TryToCreate("HTTP/1.1 200 OK\r\n");
  response_head->headers->SetHeader(
      kTrustTokensSecTrustTokenHeader,
      "response from issuer (this value will be ignored, since "
      "Cryptographer::ConfirmResponse is mocked out)");
  EXPECT_EQ(ExecuteFinalizeAndWaitForResult(&helper, response_head.get()),
            mojom::TrustTokenOperationStatus::kOk);

  // Verify that Finalize correctly stripped the response header.
  EXPECT_FALSE(
      response_head->headers->HasHeader(kTrustTokensSecTrustTokenHeader));
}

// Check that a successful Begin call associates the issuer with the issuance
// toplevel origin.
TEST_F(TrustTokenRequestIssuanceHelperTest, AssociatesIssuerWithToplevel) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  SuitableTrustTokenOrigin issuer =
      *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));

  auto key_commitment_result = mojom::TrustTokenKeyCommitmentResult::New();
  key_commitment_result->keys.push_back(
      mojom::TrustTokenVerificationKey::New());
  key_commitment_result->batch_size =
      static_cast<int>(kMaximumTrustTokenIssuanceBatchSize);
  auto getter = std::make_unique<FixedKeyCommitmentGetter>(
      issuer, std::move(key_commitment_result));

  auto cryptographer = std::make_unique<MockCryptographer>();
  EXPECT_CALL(*cryptographer, Initialize(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, AddKey(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, BeginIssuance(_))
      .WillOnce(
          Return(std::string("this string contains some blinded tokens")));

  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), getter.get(), std::move(cryptographer));

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(issuer);

  ASSERT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kOk);

  // After the operation has successfully begun, the issuer and the toplevel
  // should be associated.
  EXPECT_TRUE(store->IsAssociated(issuer, *SuitableTrustTokenOrigin::Create(
                                              GURL("https://toplevel.com/"))));
}

// Check that a successful end-to-end Begin/Finalize flow stores the obtained
// trust tokens in the trust token store.
TEST_F(TrustTokenRequestIssuanceHelperTest, StoresObtainedTokens) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  SuitableTrustTokenOrigin issuer =
      *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));

  auto key_commitment_result = mojom::TrustTokenKeyCommitmentResult::New();
  key_commitment_result->keys.push_back(
      mojom::TrustTokenVerificationKey::New("key", /*expiry=*/base::Time()));
  key_commitment_result->batch_size =
      static_cast<int>(kMaximumTrustTokenIssuanceBatchSize);
  auto getter = std::make_unique<FixedKeyCommitmentGetter>(
      issuer, std::move(key_commitment_result));

  // Have the Trust Tokens issuance conclude by the underlying cryptographic
  // library returning one signed, unblinded token associated with the same
  // returned from the key commitment.
  auto unblinded_tokens = std::make_unique<UnblindedTokens>();
  unblinded_tokens->body_of_verifying_key = "key";
  unblinded_tokens->tokens.push_back("a signed, unblinded token");

  auto cryptographer = std::make_unique<MockCryptographer>();
  EXPECT_CALL(*cryptographer, Initialize(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, AddKey(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, BeginIssuance(_))
      .WillOnce(
          Return(std::string("this string contains some blinded tokens")));
  EXPECT_CALL(*cryptographer, ConfirmIssuance(_))
      .WillOnce(Return(ByMove(std::move((unblinded_tokens)))));

  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), getter.get(), std::move(cryptographer));

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(issuer);

  ASSERT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kOk);

  auto response_head = mojom::URLResponseHead::New();
  response_head->headers =
      net::HttpResponseHeaders::TryToCreate("HTTP/1.1 200 OK\r\n");
  response_head->headers->SetHeader(
      kTrustTokensSecTrustTokenHeader,
      "response from issuer (this value will be ignored, since "
      "Cryptographer::ConfirmResponse is mocked out)");
  EXPECT_EQ(ExecuteFinalizeAndWaitForResult(&helper, response_head.get()),
            mojom::TrustTokenOperationStatus::kOk);

  // After the operation has successfully finished, the trust tokens parsed from
  // the server response should be in the store.
  auto match_all_keys =
      base::BindRepeating([](const std::string&) { return true; });
  EXPECT_THAT(
      store->RetrieveMatchingTokens(issuer, std::move(match_all_keys)),
      ElementsAre(Property(&TrustToken::body, "a signed, unblinded token")));
}

TEST_F(TrustTokenRequestIssuanceHelperTest, RejectsUnsuitableInsecureIssuer) {
  auto store = TrustTokenStore::CreateForTesting();
  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), g_fixed_key_commitment_getter.get(),
      std::make_unique<MockCryptographer>());

  auto request = MakeURLRequest("http://insecure-issuer.com/");

  EXPECT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kInvalidArgument);
}

TEST_F(TrustTokenRequestIssuanceHelperTest,
       RejectsUnsuitableNonHttpNonHttpsIssuer) {
  auto store = TrustTokenStore::CreateForTesting();
  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), g_fixed_key_commitment_getter.get(),
      std::make_unique<MockCryptographer>());

  auto request = MakeURLRequest("file:///non-https-issuer.txt");

  EXPECT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kInvalidArgument);
}

TEST_F(TrustTokenRequestIssuanceHelperTest, RespectsMaximumBatchsize) {
  std::unique_ptr<TrustTokenStore> store = TrustTokenStore::CreateForTesting();

  SuitableTrustTokenOrigin issuer =
      *SuitableTrustTokenOrigin::Create(GURL("https://issuer.com/"));

  auto key_commitment_result = mojom::TrustTokenKeyCommitmentResult::New();
  key_commitment_result->keys.push_back(
      mojom::TrustTokenVerificationKey::New("key", /*expiry=*/base::Time()));
  key_commitment_result->batch_size =
      static_cast<int>(kMaximumTrustTokenIssuanceBatchSize + 1);
  auto getter = std::make_unique<FixedKeyCommitmentGetter>(
      issuer, std::move(key_commitment_result));

  auto cryptographer = std::make_unique<MockCryptographer>();
  EXPECT_CALL(*cryptographer, Initialize(_)).WillOnce(Return(true));
  EXPECT_CALL(*cryptographer, AddKey(_)).WillOnce(Return(true));

  // The batch size should be clamped to the configured maximum.
  EXPECT_CALL(*cryptographer,
              BeginIssuance(kMaximumTrustTokenIssuanceBatchSize))
      .WillOnce(
          Return(std::string("this string contains some blinded tokens")));

  TrustTokenRequestIssuanceHelper helper(
      *SuitableTrustTokenOrigin::Create(GURL("https://toplevel.com/")),
      store.get(), getter.get(), std::move(cryptographer));

  auto request = MakeURLRequest("https://issuer.com/");
  request->set_initiator(issuer);

  ASSERT_EQ(ExecuteBeginOperationAndWaitForResult(&helper, request.get()),
            mojom::TrustTokenOperationStatus::kOk);
}

}  // namespace network


text:
package com.adaptris.core.management.config;

import javax.management.MalformedObjectNameException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.adaptris.core.CoreException;
import com.adaptris.core.management.AdapterConfigManager;
import com.adaptris.core.management.BootstrapProperties;
import com.adaptris.core.runtime.AdapterRegistry;
import com.adaptris.core.runtime.AdapterRegistryMBean;

/**
 * Basic implemetation of {@link AdapterConfigManager}, which sets the BootstrapProperties.
 *
 * @author gcsiki
 *
 */
abstract class ConfigManagerImpl implements AdapterConfigManager {

  protected transient Logger log = LoggerFactory.getLogger(getClass());

  protected BootstrapProperties bootstrapProperties;
  private transient AdapterRegistryMBean adapterRegistry;

  @Override
  public void configure(BootstrapProperties bootstrapProperties) throws Exception {
    this.bootstrapProperties = bootstrapProperties;
  }

  public synchronized AdapterRegistryMBean getAdapterRegistry() throws MalformedObjectNameException, CoreException {
    if (adapterRegistry == null) {
      adapterRegistry = AdapterRegistry.findInstance(bootstrapProperties);
    }
    return adapterRegistry;
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright 2017 Jiaheng Ge

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <com.ge.protein.ui.widget.CurvedFrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal|bottom"
                android:layout_marginBottom="@dimen/login_sunegg_margin_bottom"
                android:layout_marginTop="@dimen/login_sunegg_margin_top"
                android:src="@drawable/ic_sunegg" />
        </FrameLayout>
    </com.ge.protein.ui.widget.CurvedFrameLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="@dimen/login_title_margin_top"
        android:text="@string/login_pre_title"
        android:textAppearance="@style/ProteinTextAppearance.Medium.XXL.Primary" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginTop="8dp"
        android:lineSpacingMultiplier="@dimen/line_spacing_multiplier"
        android:text="@string/protein_desc"
        android:textAppearance="@style/ProteinTextAppearance.Regular.M.Secondary" />

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="@dimen/login_button_margin_top"
        android:layout_marginBottom="@dimen/login_button_margin_bottom"
        android:drawableLeft="@drawable/ic_dribbble"
        android:drawablePadding="8dp"
        android:padding="16dp"
        android:text="@string/login_pre_button"
        android:textAllCaps="false"
        android:textColor="@color/protein_white"
        app:backgroundTint="@color/dribbble_brand_color"/>

</LinearLayout>


text:
set -ex

#############
# VARIABLES #
#############

CEPH_RELEASES=(luminous mimic)

#############
# FUNCTIONS #
#############

function install_docker {
  sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --force-yes docker.io
  sudo systemctl start docker
  sudo systemctl status docker
  sudo chgrp "$(whoami)" /var/run/docker.sock
}

function build_ceph_imgs {
  echo "Build Ceph container image(s)"
  for ceph_release in "${CEPH_RELEASES[@]}"; do
    make DAEMON_BASE_TAG=daemon-base:"$RELEASE"-"${ceph_release}"-centos-7-aarch64 DAEMON_TAG=daemon:"$RELEASE"-"${ceph_release}"-centos-7-aarch64 RELEASE="$RELEASE" FLAVORS="${ceph_release},centos-arm64,7" BASEOS_REPO=centos build
  done
  docker images
}

function push_ceph_imgs {
  echo "Push Ceph container image(s) to the Docker Hub registry"
  for ceph_release in "${CEPH_RELEASES[@]}"; do
    make DAEMON_BASE_TAG=daemon-base:"$RELEASE"-"${ceph_release}"-centos-7-aarch64 DAEMON_TAG=daemon:"$RELEASE"-"${ceph_release}"-centos-7-aarch64 RELEASE="$RELEASE" FLAVORS="${ceph_release},centos-arm64,7" BASEOS_REPO=centos push
  done
}

function build_and_push_latest_bis {
  return
}

function push_ceph_imgs_latests {
  return
}

function create_registry_manifest {
  return
}

function wait_for_arm_images {
  return
}

########
# MAIN #
########

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# shellcheck source=./
# shellcheck disable=SC1091
source "$SCRIPT_DIR"/build-push-ceph-container-imgs.sh


text:
package com.nicholasgot.citypulse.androidapp.common;

public class DefaultValues {

	// CTBAV
	//public static final String WEB_SOCKET_SERVER_IP = "192.168.100.30";

	// NUIG
	// public static final String WEB_SOCKET_SERVER_IP = "140.203.155.76";

	// SURREY
	public static final String WEB_SOCKET_SERVER_IP = "131.227.92.55";

//	public static final String REASONING_REQUEST_WEB_SOCKET_END_POINT = "ws://"
//			+ "SERVER_IP" + ":" + "8005"
//			+ "/websockets/reasoning_request";

	public static final String REASONING_REQUEST_WEB_SOCKET_END_POINT = "ws://"
			+ "SERVER_IP" + ":" + "8018" // For Stockholm GDI
			+ "/websockets/reasoning_request";

	public static final String CONTEXTUAL_EVENTS_REQUEST_WEB_SOCKET_END_POINT = "ws://"
			+ "SERVER_IP"
			+ ":"
			+ "8005"
			+ "/websockets/contextual_events_request";

	public static final String TRAFFIC_STATUS_REQUEST_WEB_SOCKET_END_POINT = "ws://"
			+ "SERVER_IP"
			+ ":"
			+ "8002"
			+ "/";

	public static final int TRAVEL_PLANNER_CONSTRAINTS_REQUEST_CODE = 999;

	public static final int PARKING_PLACE_PLANNER_CONSTRAINTS_REQUEST_CODE = 888;

	public static final String CAR_TRANSPORTATION_TYPE = "CAR";

	public static final String WALK_TRANSPORTATION_TYPE = "WALK";

	public static final String BICYCLE_TRANSPORTATION_TYPE = "BICYCLE";

	public static final Integer NOTIFICATION_SERVICE_PERIOD = 10000;

	public static final String CLOSE_ACTIVITY_MESSAGE = "close activity message";

	public static final String EVENT_ALERT_MESSAGE = "event alert message";

	public static final String ERROR_MESSAGE = "error message";

	public static final String EVENT_ALERT_MESSAGE_PAYLOAD = "event alert message payload";

	public static final String ERROR_MESSAGE_PAYLOAD = "error message payload";

	public static final String COMMMAND_BUNDLE = "command bundle";

	public static final String COMMAND_GO_TO_PARKING_RECOMANDATION = "go to parking recomandation";

	public static final String COMMAND_GO_TO_TRAVEL_RECOMANDATION = "go to TRAVEL recomandation";

	public static String getEndPointForIP(String endPointBase,String IP){

		return endPointBase.replace("SERVER_IP", IP);
	}

}


text:
import { renderListOfColors } from './utils.js'

export const usageInstructions =`
  usage: ths <query> [-j|-h|-c|-l]

    options:

        -j|--json            output results as JSON
        -h|--help            show this help
        -c|--color <color>   change color of output -- <color> can be one of ${renderListOfColors()}
        -l|--limit <n>       limit results to <n>`

export const LIST_OF_COLORS = ['black', 'red', 'green','yellow', 'blue', 'magenta', 'cyan', 'white', 'gray']


text:
<?php

declare(strict_types=1);

namespace WeCodeMore\WpStarter\Util;

use Composer\Util\Filesystem as ComposerFilesystem;
use Composer\Util\Platform;

/**
 * Wrapper for Composer Filesystem with custom functionalities.
 */
class Filesystem
{
    /**
     * @var ComposerFilesystem
     */
    private $filesystem;

    /**
     * @param ComposerFilesystem $filesystem
     */
    public function __construct(ComposerFilesystem $filesystem)
    {
        $this->filesystem = $filesystem;
    }

    /**
     * Save some textual content to a file in given path.
     *
     * @param string $content
     * @param string $targetPath
     * @return bool
     */
    public function writeContent(string $content, string $targetPath): bool
    {
        try {
            $parent = dirname($this->filesystem->normalizePath($targetPath));

            if (!$this->createDir($parent)) {
                return false;
            }

            $exists = file_exists($targetPath);
            if ($exists && !is_file($targetPath)) {
                return false;
            }

            $currentContent = $exists ? file_get_contents($targetPath) : null;
            if ($currentContent === $content) {
                return true;
            }

            return file_put_contents($targetPath, $content) !== false;
        } catch (\Throwable $exception) {
            return false;
        }
    }

    /**
     * @param string $content
     * @param string $targetPath
     * @return bool
     *
     * @deprecated
     */
    public function save(string $content, string $targetPath): bool
    {
        return $this->writeContent($content, $targetPath);
    }

    /**
     * Move a single file from a source to a destination.
     *
     * @param string $sourcePath
     * @param string $targetPath
     * @return bool
     */
    public function moveFile(string $sourcePath, string $targetPath): bool
    {
        return $this->copyOrMoveFile($sourcePath, $targetPath, false);
    }

    /**
     * Copy a single file from a source to a destination.
     *
     * @param string $sourcePath
     * @param string $targetPath
     * @return bool
     */
    public function copyFile(string $sourcePath, string $targetPath): bool
    {
        return $this->copyOrMoveFile($sourcePath, $targetPath, true);
    }

    /**
     * Recursively copy all files from a directory to another.
     *
     * @param string $sourcePath
     * @param string $targetPath
     * @return bool
     */
    public function moveDir(string $sourcePath, string $targetPath): bool
    {
        return $this->copyOrMoveDir($sourcePath, $targetPath, false);
    }

    /**
     * Recursively copy all files from a directory to another.
     *
     * @param string $sourcePath
     * @param string $targetPath
     * @return bool
     */
    public function copyDir(string $sourcePath, string $targetPath): bool
    {
        return $this->copyOrMoveDir($sourcePath, $targetPath, true);
    }

    /**
     * Symlink implementation which uses junction on dirs on Windows.
     *
     * @param string $targetPath
     * @param string $linkPath
     * @return bool
     */
    public function symlink(string $targetPath, string $linkPath): bool
    {
        try {
            if (!file_exists($targetPath)) {
                return false;
            }

            if (file_exists($linkPath) || $this->isLink($linkPath)) {
                $this->filesystem->unlink($linkPath);
            }

            $isWindows = Platform::isWindows();
            $directories = is_dir($targetPath);

            if ($isWindows && $directories) {
                $this->filesystem->junction($targetPath, $linkPath);

                return $this->filesystem->isJunction($linkPath);
            }

            $absolute = $this->filesystem->isAbsolutePath($targetPath)
                && $this->filesystem->isAbsolutePath($linkPath);

            // Attempt relative symlink, but not on Windows
            if ($absolute && !$isWindows) {
                return $this->filesystem->relativeSymlink($targetPath, $linkPath);
            }

            return @symlink($targetPath, $linkPath);
        } catch (\Throwable $exception) {
            return false;
        }
    }

    /**
     * Create a directory recursively, derived from wp_makedir_p.
     *
     * @param string $targetPath
     * @return bool
     */
    public function createDir(string $targetPath): bool
    {
        try {
            $targetPath = $this->filesystem->normalizePath($targetPath);

            if (file_exists($targetPath)) {
                return @is_dir($targetPath);
            }

            $parentDir = dirname($targetPath);
            while ('.' !== $parentDir && !is_dir($parentDir)) {
                $parentDir = dirname($parentDir);
            }

            $stat = @stat($parentDir);
            $permissions = $stat ? ((int)$stat['mode']) & 0007777 : 0755;

            if (!@mkdir($targetPath, $permissions, true) && !is_dir($targetPath)) {
                return false;
            }

            if ($permissions !== ($permissions & ~umask())) {
                $nameParts = explode('/', substr($targetPath, strlen($parentDir) + 1) ?: '');
                for ($i = 1, $count = count($nameParts); $i <= $count; $i++) {
                    $dirname = $parentDir . '/' . implode('/', array_slice($nameParts, 0, $i));
                    @chmod($dirname, $permissions);
                }
            }

            return true;
        } catch (\Throwable $throwable) {
            return false;
        }
    }

    /**
     * Remove a directory only if "real".
     *
     * @param string $directory
     * @return bool
     */
    public function removeRealDir(string $directory): bool
    {
        try {
            if ($this->isLink($directory)) {
                return false;
            }

            if (is_dir($directory)) {
                return $this->filesystem->removeDirectory($directory);
            }

            return !file_exists($directory);
        } catch (\Throwable $throwable) {
            return false;
        }
    }

    /**
     * @param string $path
     * @return bool
     */
    public function isLink(string $path): bool
    {
        return $this->filesystem->isSymlinkedDirectory($path)
            || $this->filesystem->isJunction($path)
            || is_link($path);
    }

    /**
     * @param string $sourcePath
     * @param string $targetPath
     * @param bool $copy
     * @return bool
     */
    private function copyOrMoveFile(string $sourcePath, string $targetPath, bool $copy): bool
    {
        try {
            $sourcePath = realpath($sourcePath);
            if (!$sourcePath || !is_file($sourcePath)) {
                return false;
            }

            $targetPath = $this->filesystem->normalizePath($targetPath);
            if (!$this->createDir(dirname($targetPath))) {
                return false;
            }

            file_exists($targetPath) and $this->filesystem->unlink($targetPath);

            $copy
                ? copy($sourcePath, $targetPath)
                : $this->filesystem->rename($sourcePath, $targetPath);

            return file_exists($targetPath);
        } catch (\Throwable $throwable) {
            return false;
        }
    }

    /**
     * @param string $sourcePath
     * @param string $targetPath
     * @param bool $copy
     * @return bool
     */
    private function copyOrMoveDir(string $sourcePath, string $targetPath, bool $copy): bool
    {
        try {
            $sourcePath = realpath($sourcePath);
            if (!$sourcePath || !is_dir($sourcePath)) {
                return false;
            }

            $targetPath = $this->filesystem->normalizePath($targetPath);
            $exists = file_exists($targetPath);
            if ($exists && !is_dir($targetPath)) {
                return false;
            }

            if (!$exists && !$this->createDir($targetPath)) {
                return false;
            }

            $copy
                ? $this->filesystem->copy($sourcePath, $targetPath)
                : $this->filesystem->copyThenRemove($sourcePath, $targetPath);

            if (!is_dir($targetPath)) {
                return false;
            }

            return $copy || !file_exists($sourcePath);
        } catch (\Throwable $exception) {
            return false;
        }
    }
}


text:
var knex = require('knex');
var config = require('./knexfile.js');

var ENV = process.env.ENVIRONMENT || 'development';
var db = config[ENV];

module.exports = db;


text:
/* $This file is distributed under the terms of the license in LICENSE$ */

package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.BaseEditElementVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditElementVTwo;
public class FieldVTwo {

//    public enum OptionsType {
//        LITERALS,
//        HARDCODED_LITERALS,
//        STRINGS_VIA_DATATYPE_PROPERTY,
//        INDIVIDUALS_VIA_OBJECT_PROPERTY,
//        INDIVIDUALS_VIA_VCLASS,
//        CHILD_VCLASSES,
//        CHILD_VCLASSES_WITH_PARENT,
//        VCLASSGROUP,
//        FILE,
//        UNDEFINED,
//        DATETIME,
//        DATE,
//        TIME
//    };

    public static String RDF_XML_LITERAL_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral";

    private String name;

    /**
     * List of basic validators.  See BaiscValidation.
     */
    private List <String> validators = new ArrayList<String>();

    /** Object to get options from. */
    private FieldOptions fieldOptions;

    /**
     * Used for holding the expected/required datatype of the predicate when the predicate is a datatype propertyl.
     * this can be a explicit URI or a qname.
     * example:
     *  "this is the literal"^^<http://someuri.com/v1.2#type23>
     *  or
     *  "this is the literal"^^someprefix:type23
     */
    private String rangeDatatypeUri;

    /**
     * Used for holding the language of the literal when the predicate is a datatype property.
     * This is the lang of the literal.  lang strings must be: [a-z]+(-[a-z0-9]+)*
     */
    private String rangeLang;

    /**
     * Property for special edit element.
     */
    private EditElementVTwo editElement=null;;

    /* *********************** Constructors ************************** */

    public FieldVTwo() {}

    //private static String[] parameterNames = {"editElement","newResource","validators","optionsType","predicateUri","objectClassUri","rangeDatatypeUri","rangeLang","literalOptions","assertions"};
    //static{  Arrays.sort(parameterNames); }

    /* ****************** Getters and Setters ******************************* */

    public FieldVTwo setEditElement(EditElementVTwo editElement){
        this.editElement = editElement;

        if( editElement instanceof BaseEditElementVTwo)
            ((BaseEditElementVTwo) editElement).setField(this);

        return this;
    }

    public String getName(){
        return name;
    }

    public List <String> getValidators() {
        return validators;
    }
    public FieldVTwo setValidators(List <String> v) {
        validators = v;
        return this;
    }

    public FieldVTwo setOptions( FieldOptions fopts){
        this.fieldOptions = fopts;
        return this;
    }

    public FieldOptions getFieldOptions(){
        return this.fieldOptions;
    }

    public String getRangeDatatypeUri() {
        return rangeDatatypeUri;
    }
    public FieldVTwo setRangeDatatypeUri(String r) {
        if( rangeLang != null && rangeLang.trim().length() > 0 )
            throw new IllegalArgumentException("A Field object may not have both rangeDatatypeUri and rangeLanguage set");

        rangeDatatypeUri = r;
        return this;
    }

    public String getRangeLang() {
        return rangeLang;
    }

    public FieldVTwo setRangeLang(String rangeLang) {
        if( rangeDatatypeUri != null && rangeDatatypeUri.trim().length() > 0)
            throw new IllegalArgumentException("A Field object may not have both rangeDatatypeUri and rangeLanguage set");

        this.rangeLang = rangeLang;
        return this;
    }

    public EditElementVTwo getEditElement(){
        return editElement;
    }

    public FieldVTwo setName(String name){
        this.name = name;
        return this;
    }

    @Override
    public String toString(){
        return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
    }

    //Check that two fields are the same
    //Not sure how to compare EditElement and FieldOptions
    public boolean isEqualTo(FieldVTwo inputField) {
    	//Name required
    	boolean nameEqual = this.name.equals(inputField.getName());
    	//Validators initialized so can check
    	boolean validatorsEqual = this.validators.equals(inputField.getValidators());
    	//other fields optional and may be null
    	boolean rangeDatatypeEqual = ((this.rangeDatatypeUri == null && inputField.getRangeDatatypeUri() == null) ||
    								(this.rangeDatatypeUri != null && inputField.getRangeDatatypeUri() != null
    								&& this.rangeDatatypeUri.equals(inputField.getRangeDatatypeUri())));
    	boolean rangeLangEqual = ((this.rangeLang == null && inputField.getRangeLang() == null) ||
				(this.rangeLang != null && inputField.getRangeLang() != null
				&& this.rangeLang.equals(inputField.getRangeLang())));

    	return (nameEqual &&
    			validatorsEqual &&
    			rangeDatatypeEqual &&
    			rangeLangEqual);

    }
}


text:
package Utilities.networking;

import java.rmi.server.UnicastRemoteObject;
import java.rmi.registry.*;
import java.rmi.*;

/**
 * @author ChordFPG Team
 * @version 1.0
 */
public class ProxyBinder extends UnicastRemoteObject implements ProxyBinderInt {

    public ProxyBinder() throws RemoteException {
    }

    public void remoteBind(String prefix, Remote omg) throws RemoteException, AlreadyBoundException {
        Registry rmiHandle = LocateRegistry.getRegistry();
        rmiHandle.bind(prefix, omg);

    }

    public void remoteUnbind(String prefix) throws RemoteException, NotBoundException {
        Registry rmiHandle = LocateRegistry.getRegistry();
        rmiHandle.unbind(prefix);
    }
}


text:
/*
 * app.header.js
 * Header feature module
*/

/*jslint         browser : true, continue : true,
  devel  : true, indent  : 2,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : true,
  regexp : true, sloppy  : true, vars     : false,
  white  : true, camelcase: false
*/

/*global $, app, Handlebars */

app.header = (function () {
  'use strict';

  //---------------- BEGIN MODULE SCOPE VARIABLES --------------
  var
    configMap = {
      main_html           : Handlebars.compile($('#app-header-template').html()),
      auth_buttons_html   : Handlebars.compile($('#app-authentication-buttons-template').html())
    },
    stateMap  = { $container : null },
    jqueryMap = {},

    signOutBtnClick,
    showAuthButtons,

    setJqueryMap,
    configModule,
    initModule;
  //----------------- END MODULE SCOPE VARIABLES ---------------

  //------------------- BEGIN UTILITY METHODS ------------------

  //-------------------- END UTILITY METHODS -------------------

  //--------------------- BEGIN DOM METHODS --------------------
  // Begin DOM method /setJqueryMap/
  setJqueryMap = function () {
    var $container = stateMap.$append_target.find('#app-header');
    jqueryMap = {
      $container              : $container,
      $authButtons            : $container.find('#app-authentication-buttons')
    };
  };
  // End DOM method /setJqueryMap/
  //---------------------- END DOM METHODS ---------------------

  //------------------- BEGIN EVENT HANDLERS -------------------

  signOutBtnClick = function(){
    jqueryMap.$container.on('click', '#sign-out', function(){
      app.model.user.sign_out();
      $.gevent.publish( 'app-user-signed-out', [ ] );
    });
  };

  showAuthButtons = function( event, authStatus ){
    jqueryMap.$authButtons.empty();
    if(authStatus === 'signed-in'){
      jqueryMap.$authButtons.append(
        configMap.auth_buttons_html({
          userSignedIn  : true,
          userPhoto     : app.model.user.get_photo(),
          displayName   : app.model.user.get_display_name(),
          firstName     : app.model.user.get_first_name()
        })
      );
    }
    if(authStatus === 'signed-out'){
      jqueryMap.$authButtons.append(
        configMap.auth_buttons_html({
          userSignedIn : false
        })
      );
    }
    setJqueryMap();
  };

  //-------------------- END EVENT HANDLERS --------------------

  //------------------- BEGIN PUBLIC METHODS -------------------
  // Begin public method /configModule/
  // Purpose    : Adjust configuration of allowed keys
  // Arguments  : A map of settable keys and values
  //   * color_name - color to use
  // Settings   :
  //   * configMap.settable_map declares allowed keys
  // Returns    : true
  // Throws     : none
  //
  configModule = function ( input_map ) {
    app.butil.setConfigMap({
      input_map    : input_map,
      settable_map : configMap.settable_map,
      config_map   : configMap
    });
    return true;
  };
  // End public method /configModule/

  // Begin public method /initModule/
  // Purpose    : Initializes module
  // Arguments  :
  //  * $container the jquery element used by this feature
  // Returns    : true
  // Throws     : none
  //
  initModule = function ( $append_target ) {
    stateMap.$append_target = $append_target;
    $append_target.append( configMap.main_html() );
    setJqueryMap();
    signOutBtnClick();
    $.gevent.subscribe( jqueryMap.$container, 'app-authentication-status',    showAuthButtons );
    return true;
  };
  // End public method /initModule/

  // return public methods
  return {
    configModule : configModule,
    initModule   : initModule
  };
  //------------------- END PUBLIC METHODS ---------------------
}());


text:
package org.jitsi.impl.neomedia.notify;

import java.beans.*;
import java.util.*;
import java.util.concurrent.*;

import javax.media.*;

import org.jitsi.impl.neomedia.*;
import org.jitsi.impl.neomedia.device.*;
import org.jitsi.service.audionotifier.*;

/**
 * The implementation of <tt>AudioNotifierService</tt>.
 *
 * @author Yana Stamcheva
 * @author Lyubomir Marinov
 */
public class AudioNotifierServiceImpl
    implements AudioNotifierService,
               PropertyChangeListener
{
    /**
     * The cache of <tt>SCAudioClip</tt> instances which we may reuse. The reuse
     * is complex because a <tt>SCAudioClip</tt> may be used by a single user at
     * a time.
     */
    private Map<AudioKey, SCAudioClip> audios;

    /**
     * The <tt>Object</tt> which synchronizes the access to {@link #audios}.
     */
    private final Object audiosSyncRoot = new Object();

    /**
     * The <tt>DeviceConfiguration</tt> which provides information about the
     * notify and playback devices on which this instance plays
     * <tt>SCAudioClip</tt>s.
     */
    private final DeviceConfiguration deviceConfiguration;

    /**
     * The indicator which determined whether <tt>SCAudioClip</tt>s are to be
     * played by this instance.
     */
    private boolean mute;

    /**
     * Initializes a new <tt>AudioNotifierServiceImpl</tt> instance.
     */
    public AudioNotifierServiceImpl()
    {
        this.deviceConfiguration
            = NeomediaServiceUtils
                .getMediaServiceImpl()
                    .getDeviceConfiguration();

        this.deviceConfiguration.addPropertyChangeListener(this);
    }

    /**
     * Checks whether the playback and notification configuration share the same
     * device.
     *
     * @return are audio out and notifications using the same device.
     */
    public boolean audioOutAndNotificationsShareSameDevice()
    {
        AudioSystem audioSystem = getDeviceConfiguration().getAudioSystem();
        CaptureDeviceInfo notify
            = audioSystem.getSelectedDevice(AudioSystem.DataFlow.NOTIFY);
        CaptureDeviceInfo playback
            = audioSystem.getSelectedDevice(AudioSystem.DataFlow.PLAYBACK);

        if (notify == null)
            return (playback == null);
        else
        {
            if (playback == null)
                return false;
            else
                return notify.getLocator().equals(playback.getLocator());
        }
    }

    /**
     * Creates an SCAudioClip from the given URI and adds it to the list of
     * available audio-s. Uses notification device if any.
     *
     * @param uri the path where the audio file could be found
     * @return a newly created <tt>SCAudioClip</tt> from <tt>uri</tt>
     */
    public SCAudioClip createAudio(String uri)
    {
        return createAudio(uri, false);
    }

    /**
     * Creates an SCAudioClip from the given URI and adds it to the list of
     * available audio-s.
     *
     * @param uri the path where the audio file could be found
     * @param playback use or not the playback device.
     * @return a newly created <tt>SCAudioClip</tt> from <tt>uri</tt>
     */
    public SCAudioClip createAudio(String uri, boolean playback)
    {
        SCAudioClip audio;

        synchronized (audiosSyncRoot)
        {
            final AudioKey key = new AudioKey(uri, playback);

            /*
             * While we want to reuse the SCAudioClip instances, they may be
             * used by a single user at a time. That's why we'll forget about
             * them while they are in use and we'll reclaim them when they are
             * no longer in use.
             */
            audio = (audios == null) ? null : audios.remove(key);

            if (audio == null)
            {
                try
                {
                    AudioSystem audioSystem
                        = getDeviceConfiguration().getAudioSystem();

                    if (audioSystem == null)
                    {
                        audio = new JavaSoundClipImpl(uri, this);
                    }
                    else if (NoneAudioSystem.LOCATOR_PROTOCOL.equalsIgnoreCase(
                            audioSystem.getLocatorProtocol()))
                    {
                        audio = null;
                    }
                    else
                    {
                        audio
                            = new AudioSystemClipImpl(
                                    uri,
                                    this,
                                    audioSystem,
                                    playback);
                    }
                }
                catch (Throwable t)
                {
                    if (t instanceof ThreadDeath)
                        throw (ThreadDeath) t;
                    else
                    {
                        /*
                         * Could not initialize a new SCAudioClip instance to be
                         * played.
                         */
                        return null;
                    }
                }
            }

            /*
             * Make sure that the SCAudioClip will be reclaimed for reuse when
             * it is no longer in use.
             */
            if (audio != null)
            {
                if (audios == null)
                    audios = new HashMap<AudioKey, SCAudioClip>();

                /*
                 * We have to return in the Map which was active at the time the
                 * SCAudioClip was initialized because it may have become
                 * invalid if the playback or notify audio device changed.
                 */
                final Map<AudioKey, SCAudioClip> finalAudios = audios;
                final SCAudioClip finalAudio = audio;

                audio
                    = new SCAudioClip()
                    {
                        /**
                         * Evaluates a specific <tt>loopCondition</tt> as
                         * defined by
                         * {@link SCAudioClip#play(int,Callable)}.
                         *
                         * @param loopCondition the
                         * <tt>Callable<Boolean></tt> which represents the
                         * <tt>loopCondition</tt> to be evaluated
                         * @return {@link Boolean#FALSE} if
                         * <tt>loopCondition</tt> is <tt>null</tt>; otherwise,
                         * the value returned by invoking
                         * {@link Callable#call()} on the specified
                         * <tt>loopCondition</tt>
                         * @throws Exception if the specified
                         * <tt>loopCondition</tt> throws an <tt>Exception</tt>
                         */
                        private Boolean evaluateLoopCondition(
                                Callable<Boolean> loopCondition)
                            throws Exception
                        {
                            /*
                             * SCAudioClip.play(int,Callable<Boolean>) is
                             * documented to play the SCAudioClip once only if
                             * the loopCondition is null. The same will be
                             * accomplished by returning Boolean.FALSE.
                             */
                            return
                                (loopCondition == null)
                                    ? Boolean.FALSE
                                    : loopCondition.call();
                        }

                        /**
                         * {@inheritDoc}
                         *
                         * Returns the wrapped <tt>SCAudioClip</tt> into the
                         * cache from it has earlier been retrieved in order to
                         * allow its reuse.
                         */
                        @Override
                        protected void finalize()
                            throws Throwable
                        {
                            try
                            {
                                synchronized (audios)
                                {
                                    finalAudios.put(key, finalAudio);
                                }
                            }
                            finally
                            {
                                super.finalize();
                            }
                        }

                        public void play()
                        {
                            /*
                             * SCAudioClip.play() is documented to behave as if
                             * loopInterval is negative and/or loopCondition is
                             * null. We have to take care that this instance
                             * does not get garbage collected until the
                             * finalAudio finishes playing so we will delegate
                             * to this instance's implementation of
                             * SCAudioClip.play(int,Callable<Boolean>) instead
                             * of to the finalAudio's.
                             */
                            play(-1, null);
                        }

                        public void play(
                                int loopInterval,
                                final Callable<Boolean> finalLoopCondition)
                        {
                            /*
                             * We have to make sure that this instance does not
                             * get garbage collected before the finalAudio
                             * finishes playing. The argument loopCondition of
                             * the method
                             * SCAudioClip.play(int,Callable<Boolean>) will
                             * live/be referenced during that time so we will
                             * use it to hold on to this instance.
                             */
                            Callable<Boolean> loopCondition
                                = new Callable<Boolean>()
                                {
                                    public Boolean call()
                                        throws Exception
                                    {
                                        return
                                            evaluateLoopCondition(
                                                    finalLoopCondition);
                                    }
                                };

                            finalAudio.play(loopInterval, loopCondition);
                        }

                        public void stop()
                        {
                            finalAudio.stop();
                        }

                        /**
                         * Determines whether this audio is started i.e. a
                         * <tt>play</tt> method was invoked and no subsequent
                         * <tt>stop</tt> has been invoked yet.
                         *
                         * @return <tt>true</tt> if this audio is started;
                         * otherwise, <tt>false</tt>
                         */
                        public boolean isStarted()
                        {
                            return finalAudio.isStarted();
                        }
                    };
            }
        }

        return audio;
    }

    /**
     * The device configuration.
     *
     * @return the deviceConfiguration
     */
    public DeviceConfiguration getDeviceConfiguration()
    {
        return deviceConfiguration;
    }

    /**
     * Returns <tt>true</tt> if the sound is currently disabled; <tt>false</tt>,
     * otherwise.
     *
     * @return <tt>true</tt> if the sound is currently disabled; <tt>false</tt>,
     * otherwise
     */
    public boolean isMute()
    {
        return mute;
    }

    /**
     * Listens for changes in notify device.
     *
     * @param ev the event that notify device has changed.
     */
    public void propertyChange(PropertyChangeEvent ev)
    {
        String propertyName = ev.getPropertyName();

        if (DeviceConfiguration.AUDIO_NOTIFY_DEVICE.equals(propertyName)
                || DeviceConfiguration.AUDIO_PLAYBACK_DEVICE.equals(
                        propertyName))
        {
            synchronized (audiosSyncRoot)
            {
                /*
                 * Make sure that the currently referenced SCAudioClips will not
                 * be reclaimed.
                 */
                audios = null;
            }
        }
    }

    /**
     * Enables or disables the sound in the application. If <tt>false</tt>, we
     * try to restore all looping sounds if any.
     *
     * @param mute when <tt>true</tt> disables the sound; otherwise, enables the
     * sound.
     */
    public void setMute(boolean mute)
    {
        // TODO Auto-generated method stub
        this.mute = mute;
    }

    /**
     * Implements the key of {@link AudioNotifierServiceImpl#audios}. Combines
     * the <tt>uri</tt> of the <tt>SCAudioClip</tt> with the indicator which
     * determines whether the <tt>SCAudioClip</tt> in question uses the playback
     * or the notify audio device.
     */
    private static class AudioKey
    {
        /**
         * Is it playback?
         */
        private final boolean playback;

        /**
         * The uri.
         */
        final String uri;

        /**
         * Initializes a new <tt>AudioKey</tt> instance.
         *
         * @param uri
         * @param playback
         */
        private AudioKey(String uri, boolean playback)
        {
            this.uri = uri;
            this.playback = playback;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean equals(Object o)
        {
            if (o == this)
                return true;
            if (o == null)
                return false;

            AudioKey that = (AudioKey) o;

            return
                (playback == that.playback)
                    && ((uri == null)
                            ? (that.uri == null)
                            : uri.equals(that.uri));
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public int hashCode()
        {
            return ((uri == null) ? 0 : uri.hashCode()) + (playback ? 1 : 0);
        }
    }
}


text:
import unittest
from mock import MagicMock
import json
import requests
import responses
import checkmate

class TestReservations(unittest.TestCase):
    def setUp(self):
        cm = checkmate.CheckMate(api_key='12345',
                                 api_base='http://partners.checkmate.dev')
        self.reservations_client = cm.reservations
        self.list_response = {
            'reservations': [
                {
                    'id': 121,
                    'confirmation_number': '12345'
                },
                {
                    'id': 122,
                    'confirmation_number': '12346'
                }
            ],
            'page': 1,
            'total': 2,
            'total_pages': 1,
            'links': []
        }
        self.reservation_response = {
            'id': 123,
            'confirmation_number': '12347'
        }
        self.create_params = {
            'external_id': '22234',
            'confirmation_number': 'testing12234',
            'first_name': 'John',
            'last_name': 'Doe',
            'email': 'john@example.com',
            'start_on': '2014-12-20',
            'end_on': '2014-12-24',
            'property': {
                'name': 'Hotel Checkmate',
                'address': {
                    'street': '123 Main St',
                    'city': 'Brooklyn',
                    'region': 'NY',
                    'postal_code': '11201',
                    'country_code': 'US'
                }
            }
        }

    @responses.activate
    def test_list(self):
        url = 'http://partners.checkmate.dev/reservations'
        responses.add(responses.GET, url,
                      body=json.dumps(self.list_response), status=200,
                      content_type='application/json')

        reservations = self.reservations_client.list()
        self.assertTrue('reservations' in reservations)
        self.assertTrue(reservations.reservations[0].id == 121)

    @responses.activate
    def test_list_unauthorized(self):
        url = 'http://partners.checkmate.dev/reservations'
        responses.add(responses.GET, url, status=401)
        self.assertRaises(requests.HTTPError, self.reservations_client.list)

    @responses.activate
    def test_list_error(self):
        url = 'http://partners.checkmate.dev/reservations'
        responses.add(responses.GET, url, status=500)
        self.assertRaises(requests.HTTPError, self.reservations_client.list)

    def test_list_url(self):
        self.reservations_client.client.request = MagicMock(name='request')
        mocked_request = self.reservations_client.client.request
        self.reservations_client.list()
        mocked_request.assert_called_once_with('GET', '/reservations', {})

    def test_list_url_with_property_id(self):
        self.reservations_client.client.request = MagicMock(name='request')
        mocked_request = self.reservations_client.client.request
        self.reservations_client.list({'property_id': 2})
        mocked_request.assert_called_once_with('GET',
                                               '/properties/2/reservations',
                                               {'property_id': 2})

    @responses.activate
    def test_create(self):
        url = 'http://partners.checkmate.dev/reservations'
        responses.add(responses.POST, url,
                      body=json.dumps(self.reservation_response), status=201,
                      content_type='application/json')
        reservation = self.reservations_client.create(self.create_params)
        self.assertEqual(reservation.id, self.reservation_response['id'])

    def test_create_url(self):
        self.reservations_client.client.request = MagicMock(name='request')
        mocked_request = self.reservations_client.client.request
        self.reservations_client.create(self.create_params)
        mocked_request.assert_called_once_with('POST',
                                               '/reservations',
                                               self.create_params)

    def test_create_url_with_property_id(self):
        self.reservations_client.client.request = MagicMock(name='request')
        mocked_request = self.reservations_client.client.request
        params = self.create_params.copy()
        del(params['property'])
        params['property_id'] = 123
        self.reservations_client.create(params)
        mocked_request.assert_called_once_with('POST',
                                               '/properties/123/reservations',
                                               params)

    @responses.activate
    def test_show(self):
        url = 'http://partners.checkmate.dev/reservations/123'
        responses.add(responses.GET, url,
                      body=json.dumps(self.reservation_response), status=200,
                      content_type='application/json')
        reservation = self.reservations_client.show(123)
        self.assertEqual(reservation.id, self.reservation_response['id'])

    @responses.activate
    def test_update(self):
        url = 'http://partners.checkmate.dev/reservations/123'
        responses.add(responses.PUT, url,
                      body=json.dumps(self.reservation_response), status=200,
                      content_type='application/json')
        update_params = {'loyalty_number': '123456789qwerty'}
        reservation = self.reservations_client.update(123, update_params)
        self.assertEqual(reservation.id, self.reservation_response['id'])

    @responses.activate
    def test_destroy(self):
        url = 'http://partners.checkmate.dev/reservations/123'
        responses.add(responses.DELETE, url,
                      status=204,
                      content_type='application/json')
        response = self.reservations_client.destroy(123)
        self.assertEqual(response, {})

    @responses.activate
    def test_bulk_create(self):
        url = 'http://partners.checkmate.dev/reservations/bulk_create'
        bulk_create_response = [self.reservation_response.copy(),
                                self.reservation_response.copy()]
        responses.add(responses.POST, url,
                      body=json.dumps(bulk_create_response),
                      status=200,
                      content_type='application/json')
        create_params = [self.create_params.copy(), self.create_params.copy()]

        response = self.reservations_client.bulk_create(create_params)
        self.assertEqual(response, bulk_create_response)

    def test_bulk_create_params(self):
        self.reservations_client.client.request = MagicMock(name='request')
        mocked_request = self.reservations_client.client.request
        self.reservations_client.bulk_create([])
        mocked_request.assert_called_once_with('POST',
                                               '/reservations/bulk_create',
                                               {'reservations': []})

    def test_bulk_create_params_with_callback(self):
        cb = "http://example.com/callback"
        self.reservations_client.client.request = MagicMock(name='request')
        mocked_request = self.reservations_client.client.request
        self.reservations_client.bulk_create([], cb)
        mocked_request.assert_called_once_with('POST',
                                               '/reservations/bulk_create',
                                               {
                                                   'reservations': [],
                                                   'webhook': cb
                                               })


text:
class NotificationWidget;

class NotificationManager : public QObject
{
    Q_OBJECT
public:
    explicit NotificationManager();
    ~NotificationManager();

    void showNotification(NotificationWidget * const widget);

    uint maxWidgets() const;
    void setMaxWidgets(const uint &maxWidgets);

    QSize widgetSize() const;
    void setWidgetSize(const QSize &widgetSize);

    QEasingCurve curve() const;
    void setCurve(const QEasingCurve &curve);

private slots:
    void removeWidget();
    void updateWidgetsPosition();

private:
    uint m_maxWidgets;
    QList<NotificationWidget*> *m_widgets;
    int m_zoom;
    QSize m_widgetSize; // the size of shown widgets
    QPoint m_position;  // position on the desktop where the first widget will appear
    int m_offset;       // offset on Oy axis for a new widget position
    QEasingCurve m_curve;
};

#endif // NOTIFICATIONMANAGER_H


text:
var Promise = require('bluebird');
var request = Promise.promisify(require('request'));
var cheerio = require('cheerio');
var moment = require('moment');
var uuid = require('node-uuid');
var config = require('./util/helpers').config;
var dbPouch = require('./connections/pouchDb');
var getUrl = require('./util/helpers').getUrl;
var log = require('./util/logger');

module.exports = function(message,from,cb){
	var myUrl = getUrl(message);
	var optInRegExp = new RegExp("( "+config.irc.optin+"|"+config.irc.optin+" )");
	if ((myUrl != null) && (from != config.irc.nick) && (optInRegExp.test(message))) {
		var title = '';
		var p1 = request(myUrl).then(function(content){
			$ = cheerio.load(content[0].body);
			title = $('title').text();
			return {
				"_id":uuid.v1(),
				"message": message,
				"timestamp": moment().format(),
				"channel": config.irc.channel,
				"server": config.irc.server+":"+config.irc.port,
				"nick": from,
				"urlSite": myUrl,
				"title": title
			};
		});
		var p2 = dbPouch.search({
			query: myUrl,
			fields: ['urlSite']
		});
		Promise.all([p1,p2]).then(function(datas){
			if (datas[1].rows.length != 0) throw "URL already exists in current database";
			else return dbPouch.put(datas[0]);
		}).then(function(){
			typeof cb === "function" && cb(null,{url:myUrl,title:title});
		}).catch(function(err){
			typeof cb === "function" && cb(err,null);
		});
	}
};


text:
package org.diorite.cfg.simple.serialization;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DelegateDeserialization
{
    Class<? extends ConfigurationSerializable> value();
}


text:
package com.amazonaws.services.marketplaceentitlement.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * The GetEntitlementsRequest contains results from the GetEntitlements operation.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetEntitlementsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The set of entitlements found through the GetEntitlements operation. If the result contains an empty set of
     * entitlements, NextToken might still be present and should be used.
     *

     */
    private java.util.List<Entitlement> entitlements;
    /**
     *

     * For paginated results, use NextToken in subsequent calls to GetEntitlements. If the result contains an empty set
     * of entitlements, NextToken might still be present and should be used.
     *

     */
    private String nextToken;

    /**
     *

     * The set of entitlements found through the GetEntitlements operation. If the result contains an empty set of
     * entitlements, NextToken might still be present and should be used.
     *

     *
     * @return The set of entitlements found through the GetEntitlements operation. If the result contains an empty set
     *         of entitlements, NextToken might still be present and should be used.
     */

    public java.util.List<Entitlement> getEntitlements() {
        return entitlements;
    }

    /**
     *

     * The set of entitlements found through the GetEntitlements operation. If the result contains an empty set of
     * entitlements, NextToken might still be present and should be used.
     *

     *
     * @param entitlements
     *        The set of entitlements found through the GetEntitlements operation. If the result contains an empty set
     *        of entitlements, NextToken might still be present and should be used.
     */

    public void setEntitlements(java.util.Collection<Entitlement> entitlements) {
        if (entitlements == null) {
            this.entitlements = null;
            return;
        }

        this.entitlements = new java.util.ArrayList<Entitlement>(entitlements);
    }

    /**
     *

     * The set of entitlements found through the GetEntitlements operation. If the result contains an empty set of
     * entitlements, NextToken might still be present and should be used.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setEntitlements(java.util.Collection)} or {@link #withEntitlements(java.util.Collection)} if you want to
     * override the existing values.
     *

     *
     * @param entitlements
     *        The set of entitlements found through the GetEntitlements operation. If the result contains an empty set
     *        of entitlements, NextToken might still be present and should be used.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetEntitlementsResult withEntitlements(Entitlement... entitlements) {
        if (this.entitlements == null) {
            setEntitlements(new java.util.ArrayList<Entitlement>(entitlements.length));
        }
        for (Entitlement ele : entitlements) {
            this.entitlements.add(ele);
        }
        return this;
    }

    /**
     *

     * The set of entitlements found through the GetEntitlements operation. If the result contains an empty set of
     * entitlements, NextToken might still be present and should be used.
     *

     *
     * @param entitlements
     *        The set of entitlements found through the GetEntitlements operation. If the result contains an empty set
     *        of entitlements, NextToken might still be present and should be used.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetEntitlementsResult withEntitlements(java.util.Collection<Entitlement> entitlements) {
        setEntitlements(entitlements);
        return this;
    }

    /**
     *

     * For paginated results, use NextToken in subsequent calls to GetEntitlements. If the result contains an empty set
     * of entitlements, NextToken might still be present and should be used.
     *

     *
     * @param nextToken
     *        For paginated results, use NextToken in subsequent calls to GetEntitlements. If the result contains an
     *        empty set of entitlements, NextToken might still be present and should be used.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * For paginated results, use NextToken in subsequent calls to GetEntitlements. If the result contains an empty set
     * of entitlements, NextToken might still be present and should be used.
     *

     *
     * @return For paginated results, use NextToken in subsequent calls to GetEntitlements. If the result contains an
     *         empty set of entitlements, NextToken might still be present and should be used.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * For paginated results, use NextToken in subsequent calls to GetEntitlements. If the result contains an empty set
     * of entitlements, NextToken might still be present and should be used.
     *

     *
     * @param nextToken
     *        For paginated results, use NextToken in subsequent calls to GetEntitlements. If the result contains an
     *        empty set of entitlements, NextToken might still be present and should be used.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetEntitlementsResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getEntitlements() != null)
            sb.append("Entitlements: ").append(getEntitlements()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetEntitlementsResult == false)
            return false;
        GetEntitlementsResult other = (GetEntitlementsResult) obj;
        if (other.getEntitlements() == null ^ this.getEntitlements() == null)
            return false;
        if (other.getEntitlements() != null && other.getEntitlements().equals(this.getEntitlements()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getEntitlements() == null) ? 0 : getEntitlements().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public GetEntitlementsResult clone() {
        try {
            return (GetEntitlementsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="net.coding.program.project.detail.file.LocalProjectFileActivity"
    tools:showIn="@layout/activity_local_project_file">

</RelativeLayout>


text:
.searchBox h1 {
    font-size: 34px;
    font-weight: 700;
    letter-spacing: 2;
}

.searchBoxCard {
    -webkit-transition: all 0.3s ease-in;
    -moz-transition: all 0.3s ease-in;
    -ms-transition: all 0.3s ease-in;
    -o-transition: all 0.3s ease-in;
    transition: all 0.3s ease-in;
}

.rojakLogo {
    composes: bg-white from "../../assets/css/colors.css";
    width: 200px;
    height: 200px;
}

.rojakDescription {
    composes: bg-white from "../../assets/css/colors.css";
}

.learnMoreButton {
    composes: bg-transparent from "../../assets/css/colors.css";
    color: rgb(51, 51, 51);
    border: 2px solid rgb(51, 51, 51);
    border-radius: 0;
}

.description {
    margin: 25px 0;
    padding: 25px 0;
    border-top: solid 1px #ccc;
}

.description > p ~ p {
    margin-top: 20px;
}

.searchCategories {
    margin: 15px auto 0px;
}

.searchCategories div {
    display: inline-block;
    margin-left: 10px;
    margin-right: 10px;
    border-bottom: dotted 1px #ccc;
    cursor: pointer;
}

.searchCategories div:hover {
    text-decoration: none;
    border-bottom: solid 1px black;
}


text:
<?php

namespace Front\FrontBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class MusicTypeFrontFilterType extends AbstractType
{
     /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'entity', array(
                    'class' => 'FrontFrontBundle:MusicType',
                    'property' => 'title',
                    'multiple' => true,
                    'expanded' => true,
                    'by_reference' => true,
                ))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Front\FrontBundle\Entity\MusicType'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'ffmtff';
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <link rel="icon" type="image/png" href="img/crowdlendrr_logo.png">

    <title>WeiLend - A Decentralized Open-Source P2P Lending Platform</title>

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

    <link href="css/landing-page.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

WeiLend

                        Discover

                        Start

                        About

                        Contact

Search Loan

                    	<input type="text" id="loan_id" class="form-control" aria-describedby="sizing-addon1" style="width: 200px; margin-right: 10px;" placeholder="Loan #ID">
                        Search

Recent

Open Source: Radio Potdast

43%
funded

5
backers

E13,299
pledged

10
days to Go

Save Our Park

63%
funded

100
backers

E23,299
pledged

15
days to Go

Jerry's Ice Cream Shop Loan

www.jerrysmission.com

45
Backers

E16,500
pledged of E20,000

13
Days to Go

                                <input type="hidden" id="loan_id">
                                <input type="number" id="donate_amount" class="form-control" aria-describedby="sizing-addon1" style="width: 200px;" placeholder="Amount (e.g. 10 Ether)">

                             Payout to Beneficiary
                             Donate to Loan

Get Your Project Funded

                	Start A Loan

                            Discover

⋅

                            Start

⋅

                            About

⋅

                            Contact

Copyright © WeiLend 2015. All Rights Reserved


text:
.VideoDisabledMessage {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgb(0 0 0 / 30%);
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 4;
}

.VideoDisabledMessage-text {
  margin-right: 15px;
}


text:
// SPDX-License-Identifier: Apache-2.0

#include "QRErrorCorrectionLevel.h"

#include <cassert>

namespace ZXing::QRCode {

const char* ToString(ErrorCorrectionLevel l)
{
	assert(l != ErrorCorrectionLevel::Invalid);
	static const char* const LEVEL_STR[] = {"L", "M", "Q", "H", nullptr};
	return LEVEL_STR[static_cast<int>(l)];
}

ErrorCorrectionLevel ECLevelFromString(const char* str)
{
	switch (str[0]) {
	case 'L': return ErrorCorrectionLevel::Low;
	case 'M': return ErrorCorrectionLevel::Medium;
	case 'Q': return ErrorCorrectionLevel::Quality;
	case 'H': return ErrorCorrectionLevel::High;
	default:  return ErrorCorrectionLevel::Invalid;
	}
}

ErrorCorrectionLevel ECLevelFromBits(int bits, const bool isMicro)
{
	if (isMicro) {
		constexpr ErrorCorrectionLevel LEVEL_FOR_BITS[] = {
			ErrorCorrectionLevel::Low,    ErrorCorrectionLevel::Low, ErrorCorrectionLevel::Medium, ErrorCorrectionLevel::Low,
			ErrorCorrectionLevel::Medium, ErrorCorrectionLevel::Low, ErrorCorrectionLevel::Medium, ErrorCorrectionLevel::Quality};
		return LEVEL_FOR_BITS[bits & 0x07];
	}
	constexpr ErrorCorrectionLevel LEVEL_FOR_BITS[] = {ErrorCorrectionLevel::Medium, ErrorCorrectionLevel::Low,
													   ErrorCorrectionLevel::High, ErrorCorrectionLevel::Quality};
	return LEVEL_FOR_BITS[bits & 0x3];
}

int BitsFromECLevel(ErrorCorrectionLevel l)
{
	assert(l != ErrorCorrectionLevel::Invalid);
	static const int BITS[] = {1, 0, 3, 2, -1};
	return BITS[(int)l];
}

} // namespace ZXing::QRCode


text:
@class DVTSDK, DVTSourceExpression, DVTSourceLanguageService, NSString;

@protocol DVTSourceExpressionSource <NSObject, DVTInvalidation>
@property(readonly, nonatomic) DVTSourceExpression *mouseOverExpression;
@property(readonly, nonatomic) struct CGRect currentSelectionFrame;
@property(readonly) DVTSourceExpression *contextMenuExpression;
@property(readonly, nonatomic) DVTSourceExpression *selectedExpression;
- (struct CGRect)expressionFrameForExpression:(DVTSourceExpression *)arg1;

@optional
@property(readonly) DVTSDK *sdk;
@property(readonly, nonatomic) DVTSourceLanguageService *languageService;
@property(readonly, nonatomic) NSString *selectedText;
@property(readonly) DVTSourceExpression *quickHelpExpression;
@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpikeShared;

namespace Spike1
{
    public class ThingManager : ICanFindNearByThings
    {
        private static ThingManager instance = new ThingManager();

        public static ThingManager Instance
        {
            get { return instance; }
        }

        public virtual List<Thing> FindThingsNear(Thing thing)
        {
            throw new NotImplementedException();
        }
    }

    public class GrueBehavior : Behavior
    {
        private ThingManager thingManager;

        public GrueBehavior(ThingManager thingManager)
        {
            this.thingManager = thingManager;
        }

        public void Hunt()
        {
            var potentialTargets = thingManager.FindThingsNear(this.Parent);
        }
    }
}