text:
// Copyright 2021 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 "ash/quick_pair/keyed_service/quick_pair_mediator.h"

#include <memory>

#include "ash/constants/ash_pref_names.h"
#include "ash/quick_pair/common/account_key_failure.h"
#include "ash/quick_pair/common/device.h"
#include "ash/quick_pair/common/mock_quick_pair_browser_delegate.h"
#include "ash/quick_pair/common/pair_failure.h"
#include "ash/quick_pair/common/protocol.h"
#include "ash/quick_pair/fast_pair_handshake/fake_fast_pair_handshake.h"
#include "ash/quick_pair/fast_pair_handshake/fast_pair_data_encryptor.h"
#include "ash/quick_pair/fast_pair_handshake/fast_pair_gatt_service_client.h"
#include "ash/quick_pair/fast_pair_handshake/fast_pair_handshake_lookup.h"
#include "ash/quick_pair/feature_status_tracker/fake_feature_status_tracker.h"
#include "ash/quick_pair/feature_status_tracker/mock_quick_pair_feature_status_tracker.h"
#include "ash/quick_pair/feature_status_tracker/quick_pair_feature_status_tracker.h"
#include "ash/quick_pair/keyed_service/fast_pair_bluetooth_config_delegate.h"
#include "ash/quick_pair/message_stream/fake_message_stream_lookup.h"
#include "ash/quick_pair/message_stream/message_stream_lookup.h"
#include "ash/quick_pair/pairing/fake_retroactive_pairing_detector.h"
#include "ash/quick_pair/pairing/mock_pairer_broker.h"
#include "ash/quick_pair/pairing/pairer_broker.h"
#include "ash/quick_pair/pairing/retroactive_pairing_detector.h"
#include "ash/quick_pair/repository/mock_fast_pair_repository.h"
#include "ash/quick_pair/scanning/mock_scanner_broker.h"
#include "ash/quick_pair/scanning/scanner_broker.h"
#include "ash/quick_pair/ui/mock_ui_broker.h"
#include "ash/quick_pair/ui/ui_broker.h"
#include "ash/services/quick_pair/quick_pair_process_manager_impl.h"
#include "ash/test/ash_test_base.h"
#include "ash/test/ash_test_helper.h"
#include "base/memory/scoped_refptr.h"
#include "chromeos/services/bluetooth_config/fake_discovery_session_manager.h"
#include "chromeos/services/bluetooth_config/public/mojom/cros_bluetooth_config.mojom.h"
#include "components/prefs/pref_registry.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/testing_pref_service.h"
#include "device/bluetooth/bluetooth_adapter.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/test/mock_bluetooth_adapter.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

namespace {

using testing::Return;

constexpr char kTestMetadataId[] = "test_metadata_id";
constexpr char kTestAddress[] = "test_address";

}  // namespace

namespace ash {
namespace quick_pair {

class MediatorTest : public AshTestBase {
 public:
  void SetUp() override {
    AshTestBase::SetUp();
    adapter_ =
        base::MakeRefCounted<testing::NiceMock<device::MockBluetoothAdapter>>();
    ON_CALL(*adapter_, IsPresent()).WillByDefault(testing::Return(true));
    ON_CALL(*adapter_, GetLowEnergyScanSessionHardwareOffloadingStatus())
        .WillByDefault(testing::Return(
            device::BluetoothAdapter::
                LowEnergyScanSessionHardwareOffloadingStatus::kSupported));
    device::BluetoothAdapterFactory::SetAdapterForTesting(adapter_);

    std::unique_ptr<FeatureStatusTracker> tracker =
        std::make_unique<FakeFeatureStatusTracker>();
    feature_status_tracker_ =
        static_cast<FakeFeatureStatusTracker*>(tracker.get());

    std::unique_ptr<ScannerBroker> scanner_broker =
        std::make_unique<MockScannerBroker>();
    mock_scanner_broker_ =
        static_cast<MockScannerBroker*>(scanner_broker.get());

    std::unique_ptr<RetroactivePairingDetector> retroactive_pairing_detector =
        std::make_unique<FakeRetroactivePairingDetector>();
    fake_retroactive_pairing_detector_ =
        static_cast<FakeRetroactivePairingDetector*>(
            retroactive_pairing_detector.get());

    std::unique_ptr<PairerBroker> pairer_broker =
        std::make_unique<MockPairerBroker>();
    mock_pairer_broker_ = static_cast<MockPairerBroker*>(pairer_broker.get());

    std::unique_ptr<UIBroker> ui_broker = std::make_unique<MockUIBroker>();
    mock_ui_broker_ = static_cast<MockUIBroker*>(ui_broker.get());

    std::unique_ptr<FastPairRepository> fast_pair_repository =
        std::make_unique<MockFastPairRepository>();
    mock_fast_pair_repository_ =
        static_cast<MockFastPairRepository*>(fast_pair_repository.get());

    browser_delegate_ = std::make_unique<MockQuickPairBrowserDelegate>();
    ON_CALL(*browser_delegate_, GetActivePrefService())
        .WillByDefault(testing::Return(&pref_service_));
    pref_service_.registry()->RegisterBooleanPref(ash::prefs::kFastPairEnabled,
                                                  /*default_value=*/true);

    FastPairHandshakeLookup::SetCreateFunctionForTesting(base::BindRepeating(
        &MediatorTest::CreateHandshake, base::Unretained(this)));

    mediator_ = std::make_unique<Mediator>(
        std::move(tracker), std::move(scanner_broker),
        std::move(retroactive_pairing_detector),
        std::make_unique<FakeMessageStreamLookup>(), std::move(pairer_broker),
        std::move(ui_broker), std::move(fast_pair_repository),
        std::make_unique<QuickPairProcessManagerImpl>());

    device_ = base::MakeRefCounted<Device>(kTestMetadataId, kTestAddress,
                                           Protocol::kFastPairInitial);
    base::RunLoop().RunUntilIdle();
  }

  void SetHasAtLeastOneDiscoverySessionChanged(
      bool has_at_least_one_discovery_session) {
    fake_discovery_session_manager()->SetIsDiscoverySessionActive(
        /*has_at_least_one_discovery_session = */
        has_at_least_one_discovery_session);
    base::RunLoop().RunUntilIdle();
  }

  std::unique_ptr<FastPairHandshake> CreateHandshake(
      scoped_refptr<Device> device,
      FastPairHandshake::OnCompleteCallback callback) {
    auto fake = std::make_unique<FakeFastPairHandshake>(
        adapter_, std::move(device), std::move(callback));
    return fake;
  }

 protected:
  chromeos::bluetooth_config::FakeDiscoverySessionManager*
  fake_discovery_session_manager() {
    return ash_test_helper()
        ->bluetooth_config_test_helper()
        ->fake_discovery_session_manager();
  }

  scoped_refptr<Device> device_;
  scoped_refptr<testing::NiceMock<device::MockBluetoothAdapter>> adapter_;
  FakeFeatureStatusTracker* feature_status_tracker_;
  MockScannerBroker* mock_scanner_broker_;
  FakeRetroactivePairingDetector* fake_retroactive_pairing_detector_;
  MockPairerBroker* mock_pairer_broker_;
  MockUIBroker* mock_ui_broker_;
  MockFastPairRepository* mock_fast_pair_repository_;
  std::unique_ptr<MockQuickPairBrowserDelegate> browser_delegate_;
  TestingPrefServiceSimple pref_service_;
  std::unique_ptr<Mediator> mediator_;
};

TEST_F(MediatorTest, TogglesScanningWhenFastPairEnabledChanges) {
  EXPECT_CALL(*mock_scanner_broker_, StartScanning);
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  feature_status_tracker_->SetIsFastPairEnabled(false);
  EXPECT_CALL(*mock_scanner_broker_, StartScanning);
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  feature_status_tracker_->SetIsFastPairEnabled(false);

  // When one or more discovery sessions, are active, don't toggle
  // scanning when fast pair enabled changes.
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  SetHasAtLeastOneDiscoverySessionChanged(true);
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  feature_status_tracker_->SetIsFastPairEnabled(false);
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  feature_status_tracker_->SetIsFastPairEnabled(false);
}

TEST_F(MediatorTest, TogglesScanningWhenHasAtLeastOneDiscoverySessionChanges) {
  EXPECT_CALL(*mock_scanner_broker_, StartScanning);
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  SetHasAtLeastOneDiscoverySessionChanged(true);
  EXPECT_CALL(*mock_scanner_broker_, StartScanning);
  SetHasAtLeastOneDiscoverySessionChanged(false);
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  SetHasAtLeastOneDiscoverySessionChanged(true);

  // When fast pair is disabled, don't toggle scanning when "we have at
  // least one discovery session" changes.
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  feature_status_tracker_->SetIsFastPairEnabled(false);
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  SetHasAtLeastOneDiscoverySessionChanged(false);
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  SetHasAtLeastOneDiscoverySessionChanged(true);
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  SetHasAtLeastOneDiscoverySessionChanged(false);
}

TEST_F(MediatorTest, DismissesHandshakesWhenFastPairEnabledChanges) {
  // Start with fast pair enabled and one handshake in progress.
  feature_status_tracker_->SetIsFastPairEnabled(true);
  FastPairHandshakeLookup::GetInstance()->Create(adapter_, device_,
                                                 base::DoNothing());
  EXPECT_TRUE(FastPairHandshakeLookup::GetInstance()->Get(device_));

  // If Fast Pair becomes disabled, stop scanning, clear existing
  // handshakes, and dismiss notifications.
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  EXPECT_CALL(*mock_ui_broker_, RemoveNotifications);
  feature_status_tracker_->SetIsFastPairEnabled(false);
  EXPECT_FALSE(FastPairHandshakeLookup::GetInstance()->Get(device_));

  // If Fast Pair becomes enabled, resume scanning.
  EXPECT_CALL(*mock_scanner_broker_, StartScanning);
  feature_status_tracker_->SetIsFastPairEnabled(true);
}

TEST_F(MediatorTest, DoesntDismissHandshakesWhenFastPairEnabledChangesMidPair) {
  // Start with fast pair enabled and one handshake in progress.
  feature_status_tracker_->SetIsFastPairEnabled(true);
  FastPairHandshakeLookup::GetInstance()->Create(adapter_, device_,
                                                 base::DoNothing());
  EXPECT_TRUE(FastPairHandshakeLookup::GetInstance()->Get(device_));

  // If Fast Pair becomes disabled while we are mid pair, stop
  // scanning but do not clear existing handshakes.
  EXPECT_CALL(*mock_scanner_broker_, StopScanning);
  EXPECT_CALL(*mock_pairer_broker_, IsPairing).WillOnce(Return(true));
  feature_status_tracker_->SetIsFastPairEnabled(false);
  EXPECT_TRUE(FastPairHandshakeLookup::GetInstance()->Get(device_));
}

TEST_F(MediatorTest, InvokesShowDiscoveryWhenDeviceFound) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowDiscovery);
  mock_scanner_broker_->NotifyDeviceFound(device_);
}

TEST_F(MediatorTest, InvokesShowPairingOnAppropriateAction) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairing);
  mock_ui_broker_->NotifyDiscoveryAction(device_,
                                         DiscoveryAction::kPairToDevice);
}

TEST_F(MediatorTest, InvokesShowPairing_V1) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  auto device = base::MakeRefCounted<Device>(kTestMetadataId, kTestAddress,
                                             Protocol::kFastPairInitial);
  device_->SetAdditionalData(Device::AdditionalDataType::kFastPairVersion, {1});
  EXPECT_CALL(*mock_ui_broker_, ShowPairing).Times(0);
  mock_ui_broker_->NotifyDiscoveryAction(device_,
                                         DiscoveryAction::kPairToDevice);
}

TEST_F(MediatorTest, InvokesShowPairing_InvalidV1Data) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  auto device = base::MakeRefCounted<Device>(kTestMetadataId, kTestAddress,
                                             Protocol::kFastPairInitial);
  device_->SetAdditionalData(Device::AdditionalDataType::kFastPairVersion,
                             {1, 2});
  EXPECT_CALL(*mock_ui_broker_, ShowPairing);
  mock_ui_broker_->NotifyDiscoveryAction(device_,
                                         DiscoveryAction::kPairToDevice);
}

TEST_F(MediatorTest, DoesNotInvokeShowPairing_DismissedByUser) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairing).Times(0);
  mock_ui_broker_->NotifyDiscoveryAction(device_,
                                         DiscoveryAction::kDismissedByUser);
}

TEST_F(MediatorTest, DoesNotInvokeShowPairing_Dismissed) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairing).Times(0);
  mock_ui_broker_->NotifyDiscoveryAction(device_, DiscoveryAction::kDismissed);
}

TEST_F(MediatorTest, DoesNotInvokeShowPairing_LearnMore) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairing).Times(0);
  mock_ui_broker_->NotifyDiscoveryAction(device_, DiscoveryAction::kLearnMore);
}

TEST_F(MediatorTest, NotifyPairFailure_KeyBasedPairingCharacteristicDiscovery) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kKeyBasedPairingCharacteristicDiscovery);
}

TEST_F(MediatorTest, NotifyPairFailure_CreateGattConnection) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(device_,
                                         PairFailure::kCreateGattConnection);
}

TEST_F(MediatorTest, NotifyPairFailure_GattServiceDiscovery) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(device_,
                                         PairFailure::kGattServiceDiscovery);
}

TEST_F(MediatorTest, NotifyPairFailure_GattServiceDiscoveryTimeout) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kGattServiceDiscoveryTimeout);
}

TEST_F(MediatorTest, NotifyPairFailure_DataEncryptorRetrieval) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(device_,
                                         PairFailure::kDataEncryptorRetrieval);
}

TEST_F(MediatorTest, NotifyPairFailure_PasskeyCharacteristicDiscovery) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kPasskeyCharacteristicDiscovery);
}

TEST_F(MediatorTest, NotifyPairFailure_AccountKeyCharacteristicDiscovery) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kAccountKeyCharacteristicDiscovery);
}

TEST_F(MediatorTest,
       NotifyPairFailure_KeyBasedPairingCharacteristicNotifySession) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kKeyBasedPairingCharacteristicNotifySession);
}

TEST_F(MediatorTest, NotifyPairFailure_PasskeyCharacteristicNotifySession) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kPasskeyCharacteristicNotifySession);
}

TEST_F(MediatorTest,
       NotifyPairFailure_KeyBasedPairingCharacteristicNotifySessionTimeout) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kKeyBasedPairingCharacteristicNotifySessionTimeout);
}

TEST_F(MediatorTest,
       NotifyPairFailure_PasskeyCharacteristicNotifySessionTimeout) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kPasskeyCharacteristicNotifySessionTimeout);
}

TEST_F(MediatorTest, NotifyPairFailure_KeyBasedPairingCharacteristicWrite) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kKeyBasedPairingCharacteristicWrite);
}

TEST_F(MediatorTest, NotifyPairFailure_PasskeyPairingCharacteristicWrite) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kPasskeyPairingCharacteristicWrite);
}

TEST_F(MediatorTest, NotifyPairFailure_KeyBasedPairingResponseTimeout) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kKeyBasedPairingResponseTimeout);
}

TEST_F(MediatorTest, NotifyPairFailure_PasskeyResponseTimeout) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(device_,
                                         PairFailure::kPasskeyResponseTimeout);
}

TEST_F(MediatorTest, NotifyPairFailure_KeybasedPairingResponseDecryptFailure) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kKeybasedPairingResponseDecryptFailure);
}

TEST_F(MediatorTest, NotifyPairFailure_IncorrectKeyBasedPairingResponseType) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kIncorrectKeyBasedPairingResponseType);
}

TEST_F(MediatorTest, NotifyPairFailure_PasskeyDecryptFailure) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(device_,
                                         PairFailure::kPasskeyDecryptFailure);
}

TEST_F(MediatorTest, NotifyPairFailure_IncorrectPasskeyResponseType) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(
      device_, PairFailure::kIncorrectPasskeyResponseType);
}

TEST_F(MediatorTest, NotifyPairFailure_PasskeyMismatch) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(device_,
                                         PairFailure::kPasskeyMismatch);
}

TEST_F(MediatorTest, NotifyPairFailure_PairingDeviceLost) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(device_,
                                         PairFailure::kPairingDeviceLost);
}

TEST_F(MediatorTest, NotifyPairFailure_PairingConnect) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(device_, PairFailure::kPairingConnect);
}

TEST_F(MediatorTest, NotifyPairFailure_AddressConnect) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed);
  mock_pairer_broker_->NotifyPairFailure(device_, PairFailure::kAddressConnect);
}

TEST_F(MediatorTest, InvokesShowAssociateAccount) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowAssociateAccount);
  fake_retroactive_pairing_detector_->NotifyRetroactivePairFound(device_);
}

TEST_F(MediatorTest, RemoveNotificationOnPaired) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, RemoveNotifications);
  mock_pairer_broker_->NotifyDevicePaired(device_);
}

TEST_F(MediatorTest, RemoveNotificationOnDeviceLost) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, RemoveNotifications);
  mock_scanner_broker_->NotifyDeviceLost(device_);
}

TEST_F(
    MediatorTest,
    NoNotificationOnAccountKeyWriteFailure_AccountKeyCharacteristicDiscovery) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed).Times(0);
  mock_pairer_broker_->NotifyAccountKeyWrite(
      device_, AccountKeyFailure::kAccountKeyCharacteristicDiscovery);
}

TEST_F(MediatorTest,
       NoNotificationOnAccountKeyWriteFailure_kAccountKeyCharacteristicWrite) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_ui_broker_, ShowPairingFailed).Times(0);
  mock_pairer_broker_->NotifyAccountKeyWrite(
      device_, AccountKeyFailure::kAccountKeyCharacteristicDiscovery);
}

TEST_F(MediatorTest, AssociateAccountKeyAction_AssociateAccount) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_pairer_broker_, PairDevice);
  mock_ui_broker_->NotifyAssociateAccountAction(
      device_, AssociateAccountAction::kAssoicateAccount);
}

TEST_F(MediatorTest, AssociateAccountKeyAction_LearnMore) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_pairer_broker_, PairDevice).Times(0);
  mock_ui_broker_->NotifyAssociateAccountAction(
      device_, AssociateAccountAction::kLearnMore);
}

TEST_F(MediatorTest, AssociateAccountKeyAction_DismissedByUser) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_pairer_broker_, PairDevice).Times(0);
  mock_ui_broker_->NotifyAssociateAccountAction(
      device_, AssociateAccountAction::kDismissedByUser);
}

TEST_F(MediatorTest, AssociateAccountKeyAction_Dismissed) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_pairer_broker_, PairDevice).Times(0);
  mock_ui_broker_->NotifyAssociateAccountAction(
      device_, AssociateAccountAction::kDismissed);
}

TEST_F(MediatorTest, CompanionAppAction_DownloadApp) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_pairer_broker_, PairDevice).Times(0);
  mock_ui_broker_->NotifyCompanionAppAction(
      device_, CompanionAppAction::kDownloadAndLaunchApp);
}

TEST_F(MediatorTest, CompanionAppAction_LaunchApp) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_pairer_broker_, PairDevice).Times(0);
  mock_ui_broker_->NotifyCompanionAppAction(device_,
                                            CompanionAppAction::kLaunchApp);
}

TEST_F(MediatorTest, CompanionAppAction_DismissedByUser) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_pairer_broker_, PairDevice).Times(0);
  mock_ui_broker_->NotifyCompanionAppAction(
      device_, CompanionAppAction::kDismissedByUser);
}

TEST_F(MediatorTest, CompanionAppAction_Dismissed) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_pairer_broker_, PairDevice).Times(0);
  mock_ui_broker_->NotifyCompanionAppAction(device_,
                                            CompanionAppAction::kDismissed);
}

TEST_F(MediatorTest, PairingFailedAction_NavigateToSettings) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_pairer_broker_, PairDevice).Times(0);
  mock_ui_broker_->NotifyPairingFailedAction(
      device_, PairingFailedAction::kNavigateToSettings);
}

TEST_F(MediatorTest, PairingFailedAction_DismissedByUser) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_pairer_broker_, PairDevice).Times(0);
  mock_ui_broker_->NotifyPairingFailedAction(
      device_, PairingFailedAction::kDismissedByUser);
}

TEST_F(MediatorTest, PairingFailedAction_Dismissed) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  EXPECT_CALL(*mock_pairer_broker_, PairDevice).Times(0);
  mock_ui_broker_->NotifyPairingFailedAction(device_,
                                             PairingFailedAction::kDismissed);
}

TEST_F(MediatorTest, FastPairBluetoothConfigDelegate) {
  feature_status_tracker_->SetIsFastPairEnabled(true);
  chromeos::bluetooth_config::FastPairDelegate* delegate =
      mediator_->GetFastPairDelegate();
  delegate->SetDeviceNameManager(nullptr);
  EXPECT_TRUE(delegate);
  EXPECT_EQ(delegate->GetDeviceImageInfo(kTestMetadataId), absl::nullopt);
}

}  // namespace quick_pair
}  // namespace ash


text:
#ifndef IPF_COMPONENT_H
#define IPF_COMPONENT_H

typedef struct
{
    uint32_t mBase;
    uint32_t mIndex;
}ipf_state_t;

ComponentPtr
ipf_get_new_component(DagCardPtr card, uint32_t index);

#endif // IPF_COMPONENT_H

redpajama_set_name: RedPajamaGithub


text:
package com.mauriciotogneri.tensiontunnel.shapes;

import android.opengl.GLES20;

public class Rectangle extends Shape
{
    public Rectangle(float x, float y, float width, float height, int color)
    {
        super(GLES20.GL_TRIANGLE_STRIP, color, 0, 0, new float[] {x, y + height, //
                x, y, //
                x + width, y + height, //
                x + width, y});
    }

    public Rectangle(float width, float height, int color)
    {
        this(0, 0, width, height, color);
    }
}


text:
using HttpServer;
using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace WebServer
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        Server Server;

        public MainPage()
        {
            InitializeComponent();
        }

        // Example of a Background Task, not tested
        private async void RegisterBtn_Click(object sender, RoutedEventArgs e)
        {
            string myTaskName = "First Task";

            // check if task is already registered
            foreach (var cur in BackgroundTaskRegistration.AllTasks)
            {
                if (cur.Value.Name == myTaskName)
                {
                    Log("Task already registered", "Caution");
                    return;
                }
            }

            // Windows Phone app must call this to use trigger types (see MSDN)
            await BackgroundExecutionManager.RequestAccessAsync();

            // register a new task
            BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder { Name = "First Task", TaskEntryPoint = "WebServerTask.BackgroundTask" };

            taskBuilder.SetTrigger(new TimeTrigger(15, true));
            //taskBuilder.SetTrigger(new SystemTrigger(SystemTriggerType.TimeZoneChange, false));

            BackgroundTaskRegistration myFirstTask = taskBuilder.Register();

            await (new MessageDialog("Task registered")).ShowAsync();
        }

        private async void btnPickerImage_Click(object sender, RoutedEventArgs e)
        {
            StartServer();

            // var myPictures = await StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
            var picker = new FileOpenPicker();
            picker.ViewMode = PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".png");

            StorageFile file = await picker.PickSingleFileAsync();
            if (file != null)
            {
                // Application now has read/write access to the picked file
                Log("Picked photo: " + file.Path, "Success");
                Server.File = file;
            }
            else
            {
                Log("Operation cancelled.", "Error");
            }
        }

        private async void btnPickerVideo_Click(object sender, RoutedEventArgs e)
        {
            StartServer();

            FileOpenPicker picker = new FileOpenPicker();
            picker.ViewMode = PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
            picker.FileTypeFilter.Clear();
            picker.FileTypeFilter.Add(".mp4");
            picker.FileTypeFilter.Add(".wmv");
            StorageFile file = await picker.PickSingleFileAsync();
            if (file != null)
            {
                // Application now has read/write access to the picked file
                Log("Picked video: " + file.Path, "Success");
                Server.File = file;
            }
            else
            {
                Log("Operation cancelled.", "Error");
            }
        }

        private async void btnPickerSite_Click(object sender, RoutedEventArgs e)
        {
            StartServer();

            FileOpenPicker picker = new FileOpenPicker();
            picker.ViewMode = PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = PickerLocationId.Desktop;
            picker.FileTypeFilter.Clear();
            picker.FileTypeFilter.Add(".html");
            StorageFile file = await picker.PickSingleFileAsync();
            if (file != null)
            {
                // Application now has read/write access to the picked file
                Log("Picked site: " + file.Path, "Success");
                Server.File = file;
            }
            else
            {
                Log("Operation cancelled.", "Error");
            }
        }

        private async void Log(string message, string title)
        {
            await new MessageDialog(message, title).ShowAsync();
        }

        private void StartServer()
        {
            Server = new Server(8080);
            Server.StartServer();
        }
    }
}


text:
package org.apache.lucene.facet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.facet.DrillSideways.DrillSidewaysResult;
import org.apache.lucene.facet.sortedset.DefaultSortedSetDocValuesReaderState;
import org.apache.lucene.facet.sortedset.SortedSetDocValuesFacetField;
import org.apache.lucene.facet.sortedset.SortedSetDocValuesReaderState;
import org.apache.lucene.facet.taxonomy.TaxonomyReader;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.FilteredQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.SimpleCollector;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BitDocIdSet;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.InPlaceMergeSorter;
import org.apache.lucene.util.InfoStream;
import org.apache.lucene.util.TestUtil;

public class TestDrillSideways extends FacetTestCase {

  public void testBasic() throws Exception {
    Directory dir = newDirectory();
    Directory taxoDir = newDirectory();

    // Writes facet ords to a separate directory from the
    // main index:
    DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);

    FacetsConfig config = new FacetsConfig();
    config.setHierarchical("Publish Date", true);

    RandomIndexWriter writer = new RandomIndexWriter(random(), dir);

    Document doc = new Document();
    doc.add(new FacetField("Author", "Bob"));
    doc.add(new FacetField("Publish Date", "2010", "10", "15"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("Author", "Lisa"));
    doc.add(new FacetField("Publish Date", "2010", "10", "20"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("Author", "Lisa"));
    doc.add(new FacetField("Publish Date", "2012", "1", "1"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("Author", "Susan"));
    doc.add(new FacetField("Publish Date", "2012", "1", "7"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("Author", "Frank"));
    doc.add(new FacetField("Publish Date", "1999", "5", "5"));
    writer.addDocument(config.build(taxoWriter, doc));

    // NRT open
    IndexSearcher searcher = newSearcher(writer.getReader());

    //System.out.println("searcher=" + searcher);

    // NRT open
    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);

    DrillSideways ds = new DrillSideways(searcher, config, taxoReader);

    //  case: drill-down on a single field; in this
    // case the drill-sideways + drill-down counts ==
    // drill-down of just the query:
    DrillDownQuery ddq = new DrillDownQuery(config);
    ddq.add("Author", "Lisa");
    DrillSidewaysResult r = ds.search(null, ddq, 10);
    assertEquals(2, r.hits.totalHits);
    // Publish Date is only drill-down, and Lisa published
    // one in 2012 and one in 2010:
    assertEquals("dim=Publish Date path=[] value=2 childCount=2\n  2010 (1)\n  2012 (1)\n", r.facets.getTopChildren(10, "Publish Date").toString());

    // Author is drill-sideways + drill-down: Lisa
    // (drill-down) published twice, and Frank/Susan/Bob
    // published once:
    assertEquals("dim=Author path=[] value=5 childCount=4\n  Lisa (2)\n  Bob (1)\n  Susan (1)\n  Frank (1)\n", r.facets.getTopChildren(10, "Author").toString());

    // Same simple case, but no baseQuery (pure browse):
    // drill-down on a single field; in this case the
    // drill-sideways + drill-down counts == drill-down of
    // just the query:
    ddq = new DrillDownQuery(config);
    ddq.add("Author", "Lisa");
    r = ds.search(null, ddq, 10);

    assertEquals(2, r.hits.totalHits);
    // Publish Date is only drill-down, and Lisa published
    // one in 2012 and one in 2010:
    assertEquals("dim=Publish Date path=[] value=2 childCount=2\n  2010 (1)\n  2012 (1)\n", r.facets.getTopChildren(10, "Publish Date").toString());

    // Author is drill-sideways + drill-down: Lisa
    // (drill-down) published twice, and Frank/Susan/Bob
    // published once:
    assertEquals("dim=Author path=[] value=5 childCount=4\n  Lisa (2)\n  Bob (1)\n  Susan (1)\n  Frank (1)\n", r.facets.getTopChildren(10, "Author").toString());

    // Another simple case: drill-down on single fields
    // but OR of two values
    ddq = new DrillDownQuery(config);
    ddq.add("Author", "Lisa");
    ddq.add("Author", "Bob");
    r = ds.search(null, ddq, 10);
    assertEquals(3, r.hits.totalHits);
    // Publish Date is only drill-down: Lisa and Bob
    // (drill-down) published twice in 2010 and once in 2012:
    assertEquals("dim=Publish Date path=[] value=3 childCount=2\n  2010 (2)\n  2012 (1)\n", r.facets.getTopChildren(10, "Publish Date").toString());
    // Author is drill-sideways + drill-down: Lisa
    // (drill-down) published twice, and Frank/Susan/Bob
    // published once:
    assertEquals("dim=Author path=[] value=5 childCount=4\n  Lisa (2)\n  Bob (1)\n  Susan (1)\n  Frank (1)\n", r.facets.getTopChildren(10, "Author").toString());

    assertTrue(r.facets instanceof MultiFacets);
    List<FacetResult> allResults = r.facets.getAllDims(10);
    assertEquals(2, allResults.size());
    assertEquals("dim=Author path=[] value=5 childCount=4\n  Lisa (2)\n  Bob (1)\n  Susan (1)\n  Frank (1)\n", allResults.get(0).toString());
    assertEquals("dim=Publish Date path=[] value=3 childCount=2\n  2010 (2)\n  2012 (1)\n", allResults.get(1).toString());

    // More interesting case: drill-down on two fields
    ddq = new DrillDownQuery(config);
    ddq.add("Author", "Lisa");
    ddq.add("Publish Date", "2010");
    r = ds.search(null, ddq, 10);
    assertEquals(1, r.hits.totalHits);
    // Publish Date is drill-sideways + drill-down: Lisa
    // (drill-down) published once in 2010 and once in 2012:
    assertEquals("dim=Publish Date path=[] value=2 childCount=2\n  2010 (1)\n  2012 (1)\n", r.facets.getTopChildren(10, "Publish Date").toString());
    // Author is drill-sideways + drill-down:
    // only Lisa & Bob published (once each) in 2010:
    assertEquals("dim=Author path=[] value=2 childCount=2\n  Bob (1)\n  Lisa (1)\n", r.facets.getTopChildren(10, "Author").toString());

    // Even more interesting case: drill down on two fields,
    // but one of them is OR
    ddq = new DrillDownQuery(config);

    // Drill down on Lisa or Bob:
    ddq.add("Author", "Lisa");
    ddq.add("Publish Date", "2010");
    ddq.add("Author", "Bob");
    r = ds.search(null, ddq, 10);
    assertEquals(2, r.hits.totalHits);
    // Publish Date is both drill-sideways + drill-down:
    // Lisa or Bob published twice in 2010 and once in 2012:
    assertEquals("dim=Publish Date path=[] value=3 childCount=2\n  2010 (2)\n  2012 (1)\n", r.facets.getTopChildren(10, "Publish Date").toString());
    // Author is drill-sideways + drill-down:
    // only Lisa & Bob published (once each) in 2010:
    assertEquals("dim=Author path=[] value=2 childCount=2\n  Bob (1)\n  Lisa (1)\n", r.facets.getTopChildren(10, "Author").toString());

    // Test drilling down on invalid field:
    ddq = new DrillDownQuery(config);
    ddq.add("Foobar", "Baz");
    r = ds.search(null, ddq, 10);
    assertEquals(0, r.hits.totalHits);
    assertNull(r.facets.getTopChildren(10, "Publish Date"));
    assertNull(r.facets.getTopChildren(10, "Foobar"));

    // Test drilling down on valid term or'd with invalid term:
    ddq = new DrillDownQuery(config);
    ddq.add("Author", "Lisa");
    ddq.add("Author", "Tom");
    r = ds.search(null, ddq, 10);
    assertEquals(2, r.hits.totalHits);
    // Publish Date is only drill-down, and Lisa published
    // one in 2012 and one in 2010:
    assertEquals("dim=Publish Date path=[] value=2 childCount=2\n  2010 (1)\n  2012 (1)\n", r.facets.getTopChildren(10, "Publish Date").toString());
    // Author is drill-sideways + drill-down: Lisa
    // (drill-down) published twice, and Frank/Susan/Bob
    // published once:
    assertEquals("dim=Author path=[] value=5 childCount=4\n  Lisa (2)\n  Bob (1)\n  Susan (1)\n  Frank (1)\n", r.facets.getTopChildren(10, "Author").toString());

    // LUCENE-4915: test drilling down on a dimension but
    // NOT facet counting it:
    ddq = new DrillDownQuery(config);
    ddq.add("Author", "Lisa");
    ddq.add("Author", "Tom");
    r = ds.search(null, ddq, 10);
    assertEquals(2, r.hits.totalHits);
    // Publish Date is only drill-down, and Lisa published
    // one in 2012 and one in 2010:
    assertEquals("dim=Publish Date path=[] value=2 childCount=2\n  2010 (1)\n  2012 (1)\n", r.facets.getTopChildren(10, "Publish Date").toString());

    // Test main query gets null scorer:
    ddq = new DrillDownQuery(config, new TermQuery(new Term("foobar", "baz")));
    ddq.add("Author", "Lisa");
    r = ds.search(null, ddq, 10);

    assertEquals(0, r.hits.totalHits);
    assertNull(r.facets.getTopChildren(10, "Publish Date"));
    assertNull(r.facets.getTopChildren(10, "Author"));
    writer.close();
    IOUtils.close(searcher.getIndexReader(), taxoReader, taxoWriter, dir, taxoDir);
  }

  public void testSometimesInvalidDrillDown() throws Exception {
    Directory dir = newDirectory();
    Directory taxoDir = newDirectory();
    RandomIndexWriter writer = new RandomIndexWriter(random(), dir);

    // Writes facet ords to a separate directory from the
    // main index:
    DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);

    FacetsConfig config = new FacetsConfig();
    config.setHierarchical("Publish Date", true);

    Document doc = new Document();
    doc.add(new FacetField("Author", "Bob"));
    doc.add(new FacetField("Publish Date", "2010", "10", "15"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("Author", "Lisa"));
    doc.add(new FacetField("Publish Date", "2010", "10", "20"));
    writer.addDocument(config.build(taxoWriter, doc));

    writer.commit();

    // 2nd segment has no Author:
    doc = new Document();
    doc.add(new FacetField("Foobar", "Lisa"));
    doc.add(new FacetField("Publish Date", "2012", "1", "1"));
    writer.addDocument(config.build(taxoWriter, doc));

    // NRT open
    IndexSearcher searcher = newSearcher(writer.getReader());

    //System.out.println("searcher=" + searcher);

    // NRT open
    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);

    DrillDownQuery ddq = new DrillDownQuery(config);
    ddq.add("Author", "Lisa");
    DrillSidewaysResult r = new DrillSideways(searcher, config, taxoReader).search(null, ddq, 10);

    assertEquals(1, r.hits.totalHits);
    // Publish Date is only drill-down, and Lisa published
    // one in 2012 and one in 2010:
    assertEquals("dim=Publish Date path=[] value=1 childCount=1\n  2010 (1)\n", r.facets.getTopChildren(10, "Publish Date").toString());
    // Author is drill-sideways + drill-down: Lisa
    // (drill-down) published once, and Bob
    // published once:
    assertEquals("dim=Author path=[] value=2 childCount=2\n  Bob (1)\n  Lisa (1)\n", r.facets.getTopChildren(10, "Author").toString());

    writer.close();
    IOUtils.close(searcher.getIndexReader(), taxoReader, taxoWriter, dir, taxoDir);
  }

  public void testMultipleRequestsPerDim() throws Exception {
    Directory dir = newDirectory();
    Directory taxoDir = newDirectory();
    RandomIndexWriter writer = new RandomIndexWriter(random(), dir);

    // Writes facet ords to a separate directory from the
    // main index:
    DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);

    FacetsConfig config = new FacetsConfig();
    config.setHierarchical("dim", true);

    Document doc = new Document();
    doc.add(new FacetField("dim", "a", "x"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("dim", "a", "y"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("dim", "a", "z"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("dim", "b"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("dim", "c"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("dim", "d"));
    writer.addDocument(config.build(taxoWriter, doc));

    // NRT open
    IndexSearcher searcher = newSearcher(writer.getReader());

    //System.out.println("searcher=" + searcher);

    // NRT open
    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);

    DrillDownQuery ddq = new DrillDownQuery(config);
    ddq.add("dim", "a");
    DrillSidewaysResult r = new DrillSideways(searcher, config, taxoReader).search(null, ddq, 10);

    assertEquals(3, r.hits.totalHits);
    assertEquals("dim=dim path=[] value=6 childCount=4\n  a (3)\n  b (1)\n  c (1)\n  d (1)\n", r.facets.getTopChildren(10, "dim").toString());
    assertEquals("dim=dim path=[a] value=3 childCount=3\n  x (1)\n  y (1)\n  z (1)\n", r.facets.getTopChildren(10, "dim", "a").toString());

    writer.close();
    IOUtils.close(searcher.getIndexReader(), taxoReader, taxoWriter, dir, taxoDir);
  }

  private static class Doc implements Comparable<Doc> {
    String id;
    String contentToken;

    public Doc() {}

    // -1 if the doc is missing this dim, else the index
    // -into the values for this dim:
    int[] dims;

    // 2nd value per dim for the doc (so we test
    // multi-valued fields):
    int[] dims2;
    boolean deleted;

    @Override
    public int compareTo(Doc other) {
      return id.compareTo(other.id);
    }
  }

  private double aChance, bChance, cChance;

  private String randomContentToken(boolean isQuery) {
    double d = random().nextDouble();
    if (isQuery) {
      if (d < 0.33) {
        return "a";
      } else if (d < 0.66) {
        return "b";
      } else {
        return "c";
      }
    } else {
      if (d <= aChance) {
        return "a";
      } else if (d < aChance + bChance) {
        return "b";
      } else {
        return "c";
      }
    }
  }

  public void testRandom() throws Exception {

    while (aChance == 0.0) {
      aChance = random().nextDouble();
    }
    while (bChance == 0.0) {
      bChance = random().nextDouble();
    }
    while (cChance == 0.0) {
      cChance = random().nextDouble();
    }
    //aChance = .01;
    //bChance = 0.5;
    //cChance = 1.0;
    double sum = aChance + bChance + cChance;
    aChance /= sum;
    bChance /= sum;
    cChance /= sum;

    int numDims = TestUtil.nextInt(random(), 2, 5);
    //int numDims = 3;
    int numDocs = atLeast(3000);
    //int numDocs = 20;
    if (VERBOSE) {
      System.out.println("numDims=" + numDims + " numDocs=" + numDocs + " aChance=" + aChance + " bChance=" + bChance + " cChance=" + cChance);
    }
    String[][] dimValues = new String[numDims][];
    int valueCount = 2;

    for(int dim=0;dim<numDims;dim++) {
      Set<String> values = new HashSet<>();
      while (values.size() < valueCount) {
        String s = TestUtil.randomRealisticUnicodeString(random());
        //String s = _TestUtil.randomString(random());
        if (s.length() > 0) {
          values.add(s);
        }
      }
      dimValues[dim] = values.toArray(new String[values.size()]);
      valueCount *= 2;
    }

    List<Doc> docs = new ArrayList<>();
    for(int i=0;i<numDocs;i++) {
      Doc doc = new Doc();
      doc.id = ""+i;
      doc.contentToken = randomContentToken(false);
      doc.dims = new int[numDims];
      doc.dims2 = new int[numDims];
      for(int dim=0;dim<numDims;dim++) {
        if (random().nextInt(5) == 3) {
          // This doc is missing this dim:
          doc.dims[dim] = -1;
        } else if (dimValues[dim].length <= 4) {
          int dimUpto = 0;
          doc.dims[dim] = dimValues[dim].length-1;
          while (dimUpto < dimValues[dim].length) {
            if (random().nextBoolean()) {
              doc.dims[dim] = dimUpto;
              break;
            }
            dimUpto++;
          }
        } else {
          doc.dims[dim] = random().nextInt(dimValues[dim].length);
        }

        if (random().nextInt(5) == 3) {
          // 2nd value:
          doc.dims2[dim] = random().nextInt(dimValues[dim].length);
        } else {
          doc.dims2[dim] = -1;
        }
      }
      docs.add(doc);
    }

    Directory d = newDirectory();
    Directory td = newDirectory();

    IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random()));
    iwc.setInfoStream(InfoStream.NO_OUTPUT);
    RandomIndexWriter w = new RandomIndexWriter(random(), d, iwc);
    DirectoryTaxonomyWriter tw = new DirectoryTaxonomyWriter(td, IndexWriterConfig.OpenMode.CREATE);
    FacetsConfig config = new FacetsConfig();
    for(int i=0;i<numDims;i++) {
      config.setMultiValued("dim"+i, true);
    }

    boolean doUseDV = random().nextBoolean();

    for(Doc rawDoc : docs) {
      Document doc = new Document();
      doc.add(newStringField("id", rawDoc.id, Field.Store.YES));
      doc.add(new SortedDocValuesField("id", new BytesRef(rawDoc.id)));
      doc.add(newStringField("content", rawDoc.contentToken, Field.Store.NO));

      if (VERBOSE) {
        System.out.println("  doc id=" + rawDoc.id + " token=" + rawDoc.contentToken);
      }
      for(int dim=0;dim<numDims;dim++) {
        int dimValue = rawDoc.dims[dim];
        if (dimValue != -1) {
          if (doUseDV) {
            doc.add(new SortedSetDocValuesFacetField("dim" + dim, dimValues[dim][dimValue]));
          } else {
            doc.add(new FacetField("dim" + dim, dimValues[dim][dimValue]));
          }
          doc.add(new StringField("dim" + dim, dimValues[dim][dimValue], Field.Store.YES));
          if (VERBOSE) {
            System.out.println("    dim" + dim + "=" + new BytesRef(dimValues[dim][dimValue]));
          }
        }
        int dimValue2 = rawDoc.dims2[dim];
        if (dimValue2 != -1) {
          if (doUseDV) {
            doc.add(new SortedSetDocValuesFacetField("dim" + dim, dimValues[dim][dimValue2]));
          } else {
            doc.add(new FacetField("dim" + dim, dimValues[dim][dimValue2]));
          }
          doc.add(new StringField("dim" + dim, dimValues[dim][dimValue2], Field.Store.YES));
          if (VERBOSE) {
            System.out.println("      dim" + dim + "=" + new BytesRef(dimValues[dim][dimValue2]));
          }
        }
      }

      w.addDocument(config.build(tw, doc));
    }

    if (random().nextBoolean()) {
      // Randomly delete a few docs:
      int numDel = TestUtil.nextInt(random(), 1, (int) (numDocs * 0.05));
      if (VERBOSE) {
        System.out.println("delete " + numDel);
      }
      int delCount = 0;
      while (delCount < numDel) {
        Doc doc = docs.get(random().nextInt(docs.size()));
        if (!doc.deleted) {
          if (VERBOSE) {
            System.out.println("  delete id=" + doc.id);
          }
          doc.deleted = true;
          w.deleteDocuments(new Term("id", doc.id));
          delCount++;
        }
      }
    }

    if (random().nextBoolean()) {
      if (VERBOSE) {
        System.out.println("TEST: forceMerge(1)...");
      }
      w.forceMerge(1);
    }
    IndexReader r = w.getReader();

    final SortedSetDocValuesReaderState sortedSetDVState;
    IndexSearcher s = newSearcher(r);

    if (doUseDV) {
      sortedSetDVState = new DefaultSortedSetDocValuesReaderState(s.getIndexReader());
    } else {
      sortedSetDVState = null;
    }

    if (VERBOSE) {
      System.out.println("r.numDocs() = " + r.numDocs());
    }

    // NRT open
    TaxonomyReader tr = new DirectoryTaxonomyReader(tw);

    int numIters = atLeast(10);

    for(int iter=0;iter<numIters;iter++) {

      String contentToken = random().nextInt(30) == 17 ? null : randomContentToken(true);
      int numDrillDown = TestUtil.nextInt(random(), 1, Math.min(4, numDims));
      if (VERBOSE) {
        System.out.println("\nTEST: iter=" + iter + " baseQuery=" + contentToken + " numDrillDown=" + numDrillDown + " useSortedSetDV=" + doUseDV);
      }

      String[][] drillDowns = new String[numDims][];

      int count = 0;
      boolean anyMultiValuedDrillDowns = false;
      while (count < numDrillDown) {
        int dim = random().nextInt(numDims);
        if (drillDowns[dim] == null) {
          if (random().nextBoolean()) {
            // Drill down on one value:
            drillDowns[dim] = new String[] {dimValues[dim][random().nextInt(dimValues[dim].length)]};
          } else {
            int orCount = TestUtil.nextInt(random(), 1, Math.min(5, dimValues[dim].length));
            drillDowns[dim] = new String[orCount];
            anyMultiValuedDrillDowns |= orCount > 1;
            for(int i=0;i<orCount;i++) {
              while (true) {
                String value = dimValues[dim][random().nextInt(dimValues[dim].length)];
                for(int j=0;j<i;j++) {
                  if (value.equals(drillDowns[dim][j])) {
                    value = null;
                    break;
                  }
                }
                if (value != null) {
                  drillDowns[dim][i] = value;
                  break;
                }
              }
            }
          }
          if (VERBOSE) {
            BytesRef[] values = new BytesRef[drillDowns[dim].length];
            for(int i=0;i<values.length;i++) {
              values[i] = new BytesRef(drillDowns[dim][i]);
            }
            System.out.println("  dim" + dim + "=" + Arrays.toString(values));
          }
          count++;
        }
      }

      Query baseQuery;
      if (contentToken == null) {
        baseQuery = new MatchAllDocsQuery();
      } else {
        baseQuery = new TermQuery(new Term("content", contentToken));
      }

      DrillDownQuery ddq = new DrillDownQuery(config, baseQuery);

      for(int dim=0;dim<numDims;dim++) {
        if (drillDowns[dim] != null) {
          for(String value : drillDowns[dim]) {
            ddq.add("dim" + dim, value);
          }
        }
      }

      Filter filter;
      if (random().nextInt(7) == 6) {
        if (VERBOSE) {
          System.out.println("  only-even filter");
        }
        filter = new Filter() {
            @Override
            public DocIdSet getDocIdSet(LeafReaderContext context, Bits acceptDocs) throws IOException {
              int maxDoc = context.reader().maxDoc();
              final FixedBitSet bits = new FixedBitSet(maxDoc);
              for(int docID=0;docID < maxDoc;docID++) {
                // Keeps only the even ids:
                if ((acceptDocs == null || acceptDocs.get(docID)) && (Integer.parseInt(context.reader().document(docID).get("id")) & 1) == 0) {
                  bits.set(docID);
                }
              }
              return new BitDocIdSet(bits);
            }
            @Override
            public String toString(String field) {
              return "drillSidewaysTestFilter";
            }
          };
      } else {
        filter = null;
      }

      // Verify docs are always collected in order.  If we
      // had an AssertingScorer it could catch it when
      // Weight.scoresDocsOutOfOrder lies!:
      new DrillSideways(s, config, tr).search(ddq,
                           new SimpleCollector() {
                             int lastDocID;

                             @Override
                             public void collect(int doc) {
                               assert doc > lastDocID;
                               lastDocID = doc;
                             }

                             @Override
                             protected void doSetNextReader(LeafReaderContext context) throws IOException {
                               lastDocID = -1;
                             }

                            @Override
                            public boolean needsScores() {
                              return false;
                            }
                           });

      // Also separately verify that DS respects the
      // scoreSubDocsAtOnce method, to ensure that all
      // subScorers are on the same docID:
      if (!anyMultiValuedDrillDowns) {
        // Can only do this test when there are no OR'd
        // drill-down values, because in that case it's
        // easily possible for one of the DD terms to be on
        // a future docID:
        new DrillSideways(s, config, tr) {
          @Override
          protected boolean scoreSubDocsAtOnce() {
            return true;
          }
        }.search(ddq, new AssertingSubDocsAtOnceCollector());
      }

      TestFacetResult expected = slowDrillSidewaysSearch(s, docs, contentToken, drillDowns, dimValues, filter);

      Sort sort = new Sort(new SortField("id", SortField.Type.STRING));
      DrillSideways ds;
      if (doUseDV) {
        ds = new DrillSideways(s, config, sortedSetDVState);
      } else {
        ds = new DrillSideways(s, config, tr) {
            @Override
            protected Facets buildFacetsResult(FacetsCollector drillDowns, FacetsCollector[] drillSideways, String[] drillSidewaysDims) throws IOException {
              Map<String,Facets> drillSidewaysFacets = new HashMap<>();
              Facets drillDownFacets = getTaxonomyFacetCounts(taxoReader, config, drillDowns);
              if (drillSideways != null) {
                for(int i=0;i<drillSideways.length;i++) {
                  drillSidewaysFacets.put(drillSidewaysDims[i],
                                          getTaxonomyFacetCounts(taxoReader, config, drillSideways[i]));
                }
              }

              if (drillSidewaysFacets.isEmpty()) {
                return drillDownFacets;
              } else {
                return new MultiFacets(drillSidewaysFacets, drillDownFacets);
              }

            }
          };
      }

      // Retrieve all facets:
      DrillSidewaysResult actual = ds.search(ddq, filter, null, numDocs, sort, true, true);

      TopDocs hits = s.search(baseQuery, numDocs);
      Map<String,Float> scores = new HashMap<>();
      for(ScoreDoc sd : hits.scoreDocs) {
        scores.put(s.doc(sd.doc).get("id"), sd.score);
      }
      if (VERBOSE) {
        System.out.println("  verify all facets");
      }
      verifyEquals(dimValues, s, expected, actual, scores, doUseDV);

      // Make sure drill down doesn't change score:
      Query q = ddq;
      if (filter != null) {
        q = new FilteredQuery(q, filter);
      }
      TopDocs ddqHits = s.search(q, numDocs);
      assertEquals(expected.hits.size(), ddqHits.totalHits);
      for(int i=0;i<expected.hits.size();i++) {
        // Score should be IDENTICAL:
        assertEquals(scores.get(expected.hits.get(i).id), ddqHits.scoreDocs[i].score, 0.0f);
      }
    }

    w.close();
    IOUtils.close(r, tr, tw, d, td);
  }

  private static class Counters {
    int[][] counts;

    public Counters(String[][] dimValues) {
      counts = new int[dimValues.length][];
      for(int dim=0;dim<dimValues.length;dim++) {
        counts[dim] = new int[dimValues[dim].length];
      }
    }

    public void inc(int[] dims, int[] dims2) {
      inc(dims, dims2, -1);
    }

    public void inc(int[] dims, int[] dims2, int onlyDim) {
      assert dims.length == counts.length;
      assert dims2.length == counts.length;
      for(int dim=0;dim<dims.length;dim++) {
        if (onlyDim == -1 || dim == onlyDim) {
          if (dims[dim] != -1) {
            counts[dim][dims[dim]]++;
          }
          if (dims2[dim] != -1 && dims2[dim] != dims[dim]) {
            counts[dim][dims2[dim]]++;
          }
        }
      }
    }
  }

  private static class TestFacetResult {
    List<Doc> hits;
    int[][] counts;
    int[] uniqueCounts;
    public TestFacetResult() {}
  }

  private int[] getTopNOrds(final int[] counts, final String[] values, int topN) {
    final int[] ids = new int[counts.length];
    for(int i=0;i<ids.length;i++) {
      ids[i] = i;
    }

    // Naive (on purpose, to reduce bug in tester/gold):
    // sort all ids, then return top N slice:
    new InPlaceMergeSorter() {

      @Override
      protected void swap(int i, int j) {
        int id = ids[i];
        ids[i] = ids[j];
        ids[j] = id;
      }

      @Override
      protected int compare(int i, int j) {
        int counti = counts[ids[i]];
        int countj = counts[ids[j]];
        // Sort by count descending...
        if (counti > countj) {
          return -1;
        } else if (counti < countj) {
          return 1;
        } else {
          // ... then by label ascending:
          return new BytesRef(values[ids[i]]).compareTo(new BytesRef(values[ids[j]]));
        }
      }

    }.sort(0, ids.length);

    if (topN > ids.length) {
      topN = ids.length;
    }

    int numSet = topN;
    for(int i=0;i<topN;i++) {
      if (counts[ids[i]] == 0) {
        numSet = i;
        break;
      }
    }

    int[] topNIDs = new int[numSet];
    System.arraycopy(ids, 0, topNIDs, 0, topNIDs.length);
    return topNIDs;
  }

  private TestFacetResult slowDrillSidewaysSearch(IndexSearcher s, List<Doc> docs,
                                                        String contentToken, String[][] drillDowns,
                                                        String[][] dimValues, Filter onlyEven) throws Exception {
    int numDims = dimValues.length;

    List<Doc> hits = new ArrayList<>();
    Counters drillDownCounts = new Counters(dimValues);
    Counters[] drillSidewaysCounts = new Counters[dimValues.length];
    for(int dim=0;dim<numDims;dim++) {
      drillSidewaysCounts[dim] = new Counters(dimValues);
    }

    if (VERBOSE) {
      System.out.println("  compute expected");
    }

    nextDoc: for(Doc doc : docs) {
      if (doc.deleted) {
        continue;
      }
      if (onlyEven != null & (Integer.parseInt(doc.id) & 1) != 0) {
        continue;
      }
      if (contentToken == null || doc.contentToken.equals(contentToken)) {
        int failDim = -1;
        for(int dim=0;dim<numDims;dim++) {
          if (drillDowns[dim] != null) {
            String docValue = doc.dims[dim] == -1 ? null : dimValues[dim][doc.dims[dim]];
            String docValue2 = doc.dims2[dim] == -1 ? null : dimValues[dim][doc.dims2[dim]];
            boolean matches = false;
            for(String value : drillDowns[dim]) {
              if (value.equals(docValue) || value.equals(docValue2)) {
                matches = true;
                break;
              }
            }
            if (!matches) {
              if (failDim == -1) {
                // Doc could be a near-miss, if no other dim fails
                failDim = dim;
              } else {
                // Doc isn't a hit nor a near-miss
                continue nextDoc;
              }
            }
          }
        }

        if (failDim == -1) {
          if (VERBOSE) {
            System.out.println("    exp: id=" + doc.id + " is a hit");
          }
          // Hit:
          hits.add(doc);
          drillDownCounts.inc(doc.dims, doc.dims2);
          for(int dim=0;dim<dimValues.length;dim++) {
            drillSidewaysCounts[dim].inc(doc.dims, doc.dims2);
          }
        } else {
          if (VERBOSE) {
            System.out.println("    exp: id=" + doc.id + " is a near-miss on dim=" + failDim);
          }
          drillSidewaysCounts[failDim].inc(doc.dims, doc.dims2, failDim);
        }
      }
    }

    Map<String,Integer> idToDocID = new HashMap<>();
    for(int i=0;i<s.getIndexReader().maxDoc();i++) {
      idToDocID.put(s.doc(i).get("id"), i);
    }

    Collections.sort(hits);

    TestFacetResult res = new TestFacetResult();
    res.hits = hits;
    res.counts = new int[numDims][];
    res.uniqueCounts = new int[numDims];
    for (int dim = 0; dim < numDims; dim++) {
      if (drillDowns[dim] != null) {
        res.counts[dim] = drillSidewaysCounts[dim].counts[dim];
      } else {
        res.counts[dim] = drillDownCounts.counts[dim];
      }
      int uniqueCount = 0;
      for (int j = 0; j < res.counts[dim].length; j++) {
        if (res.counts[dim][j] != 0) {
          uniqueCount++;
        }
      }
      res.uniqueCounts[dim] = uniqueCount;
    }

    return res;
  }

  void verifyEquals(String[][] dimValues, IndexSearcher s, TestFacetResult expected,
                    DrillSidewaysResult actual, Map<String,Float> scores, boolean isSortedSetDV) throws Exception {
    if (VERBOSE) {
      System.out.println("  verify totHits=" + expected.hits.size());
    }
    assertEquals(expected.hits.size(), actual.hits.totalHits);
    assertEquals(expected.hits.size(), actual.hits.scoreDocs.length);
    for(int i=0;i<expected.hits.size();i++) {
      if (VERBOSE) {
        System.out.println("    hit " + i + " expected=" + expected.hits.get(i).id);
      }
      assertEquals(expected.hits.get(i).id,
                   s.doc(actual.hits.scoreDocs[i].doc).get("id"));
      // Score should be IDENTICAL:
      assertEquals(scores.get(expected.hits.get(i).id), actual.hits.scoreDocs[i].score, 0.0f);
    }

    for(int dim=0;dim<expected.counts.length;dim++) {
      int topN = random().nextBoolean() ? dimValues[dim].length : TestUtil.nextInt(random(), 1, dimValues[dim].length);
      FacetResult fr = actual.facets.getTopChildren(topN, "dim"+dim);
      if (VERBOSE) {
        System.out.println("    dim" + dim + " topN=" + topN + " (vs " + dimValues[dim].length + " unique values)");
        System.out.println("      actual");
      }

      int idx = 0;
      Map<String,Integer> actualValues = new HashMap<>();

      if (fr != null) {
        for(LabelAndValue labelValue : fr.labelValues) {
          actualValues.put(labelValue.label, labelValue.value.intValue());
          if (VERBOSE) {
            System.out.println("        " + idx + ": " + new BytesRef(labelValue.label) + ": " + labelValue.value);
            idx++;
          }
        }
        assertEquals("dim=" + dim, expected.uniqueCounts[dim], fr.childCount);
      }

      if (topN < dimValues[dim].length) {
        int[] topNIDs = getTopNOrds(expected.counts[dim], dimValues[dim], topN);
        if (VERBOSE) {
          idx = 0;
          System.out.println("      expected (sorted)");
          for(int i=0;i<topNIDs.length;i++) {
            int expectedOrd = topNIDs[i];
            String value = dimValues[dim][expectedOrd];
            System.out.println("        " + idx + ": " + new BytesRef(value) + ": " + expected.counts[dim][expectedOrd]);
            idx++;
          }
        }
        if (VERBOSE) {
          System.out.println("      topN=" + topN + " expectedTopN=" + topNIDs.length);
        }

        if (fr != null) {
          assertEquals(topNIDs.length, fr.labelValues.length);
        } else {
          assertEquals(0, topNIDs.length);
        }
        for(int i=0;i<topNIDs.length;i++) {
          int expectedOrd = topNIDs[i];
          assertEquals(expected.counts[dim][expectedOrd], fr.labelValues[i].value.intValue());
          if (isSortedSetDV) {
            // Tie-break facet labels are only in unicode
            // order with SortedSetDVFacets:
            assertEquals("value @ idx=" + i, dimValues[dim][expectedOrd], fr.labelValues[i].label);
          }
        }
      } else {

        if (VERBOSE) {
          idx = 0;
          System.out.println("      expected (unsorted)");
          for(int i=0;i<dimValues[dim].length;i++) {
            String value = dimValues[dim][i];
            if (expected.counts[dim][i] != 0) {
              System.out.println("        " + idx + ": " + new BytesRef(value) + ": " + expected.counts[dim][i]);
              idx++;
            }
          }
        }

        int setCount = 0;
        for(int i=0;i<dimValues[dim].length;i++) {
          String value = dimValues[dim][i];
          if (expected.counts[dim][i] != 0) {
            assertTrue(actualValues.containsKey(value));
            assertEquals(expected.counts[dim][i], actualValues.get(value).intValue());
            setCount++;
          } else {
            assertFalse(actualValues.containsKey(value));
          }
        }
        assertEquals(setCount, actualValues.size());
      }
    }
  }

  public void testEmptyIndex() throws Exception {
    // LUCENE-5045: make sure DrillSideways works with an empty index
    Directory dir = newDirectory();
    Directory taxoDir = newDirectory();
    RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
    DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
    IndexSearcher searcher = newSearcher(writer.getReader());
    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);

    // Count "Author"
    FacetsConfig config = new FacetsConfig();
    DrillSideways ds = new DrillSideways(searcher, config, taxoReader);
    DrillDownQuery ddq = new DrillDownQuery(config);
    ddq.add("Author", "Lisa");

    DrillSidewaysResult r = ds.search(ddq, 10); // this used to fail on IllegalArgEx
    assertEquals(0, r.hits.totalHits);

    r = ds.search(ddq, null, null, 10, new Sort(new SortField("foo", SortField.Type.INT)), false, false); // this used to fail on IllegalArgEx
    assertEquals(0, r.hits.totalHits);

    writer.close();
    IOUtils.close(taxoWriter, searcher.getIndexReader(), taxoReader, dir, taxoDir);
  }

  public void testScorer() throws Exception {
    // LUCENE-6001 some scorers, eg ReqExlScorer, can hit NPE if cost is called after nextDoc
    Directory dir = newDirectory();
    Directory taxoDir = newDirectory();

    // Writes facet ords to a separate directory from the
    // main index:
    DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);

    FacetsConfig config = new FacetsConfig();

    RandomIndexWriter writer = new RandomIndexWriter(random(), dir);

    Document doc = new Document();
    doc.add(newTextField("field", "foo bar", Field.Store.NO));
    doc.add(new FacetField("Author", "Bob"));
    doc.add(new FacetField("dim", "a"));
    writer.addDocument(config.build(taxoWriter, doc));

    // NRT open
    IndexSearcher searcher = newSearcher(writer.getReader());

    // NRT open
    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);

    DrillSideways ds = new DrillSideways(searcher, config, taxoReader);

    BooleanQuery.Builder bq = new BooleanQuery.Builder();
    bq.setDisableCoord(true);
    bq.add(new TermQuery(new Term("field", "foo")), BooleanClause.Occur.MUST);
    bq.add(new TermQuery(new Term("field", "bar")), BooleanClause.Occur.MUST_NOT);
    DrillDownQuery ddq = new DrillDownQuery(config, bq.build());
    ddq.add("field", "foo");
    ddq.add("author", bq.build());
    ddq.add("dim", bq.build());
    DrillSidewaysResult r = ds.search(null, ddq, 10);
    assertEquals(0, r.hits.totalHits);

    writer.close();
    IOUtils.close(searcher.getIndexReader(), taxoReader, taxoWriter, dir, taxoDir);
  }
}


text:
from django.conf import settings
import djclick as click

from il.models import Agency, Stop
from tsdata.dataset_facts import compute_dataset_facts

@click.command()
def command():
    facts = compute_dataset_facts(Agency, Stop, settings.IL_KEY)
    for fact in facts:
        click.echo(fact)


text:
package com.ning.jetty.base.modules;

import com.google.inject.Binder;
import com.google.inject.Module;

public class HelloModule implements Module
{
    public void configure(final Binder binder)
    {
        binder.bind(HelloResource.class);
    }
}


text:
require_relative 'spec_helper'

describe "create_ipa task" do

	describe "invalid config handling" do
		context "missing previous tasks" do
			context "xcode_build" do
				let(:runner) { mock_runner vc.enable_create_ipa! }
				specify { expect { runner.run_tasks! }.to raise_error }
			end
		end
	end

	describe "ipa creation" do
		let!(:existing_ipa_exists) { (Dir["#{runner.config.build_dir}/*"].reject{ |f| !f.include? ".ipa" }.count > 0) }
		let(:runner) { mock_runner vc.enable_xcode_build!.enable_create_ipa! }
		before { runner.run_tasks! }
		specify { existing_ipa_exists.should be_false }
		specify { Dir["#{runner.config.build_dir}/*"].reject{ |f| !f.include? ".ipa" }.count.should == 1 }
	end

	describe "task completion" do
		let(:runner) { mock_runner vc.enable_xcode_build!.enable_create_ipa! }
		before { runner.run_tasks! }
		specify { runner.tasks[:completed].include?(:create_ipa).should be_true }
		specify { runner.outputs[:create_ipa].should_not be_nil }
	end

end


text:
<?php
/**
 * pagination.php
 */

/**
 * Pagination generates the page counter according to the number of elements to display
 *
 * @package Helpers
 * @author Johan Dufau <johan.dufau@creatiwity.net>
 * @version 0.3-01-04-2010
 */
class Pagination {

	/**
	 *
	 * @var int Total pages number
	 */
	private $n;
	/**
	 *
	 * @var int Total elements number
	 */
	private $total;
	/**
	 *
	 * @var int Maximum number of elements on a page
	 */
	private $limit;
	/**
	 *
	 * @var int Current page
	 */
	private $currentPage;
	/**
	 *
	 * @var string URL pattern for the current page
	 */
	private $urlPattern;

	/**
	 * Setup Pagination
	 *
	 * @param type  $total          Total elements number
	 * @param type  $limit          Maximum number of elements on a page
	 * @param int   $currentPage    Page Current page
	 * @param type  $urlPattern     URL model for the current page
	 */
	public function __construct($total, $limit, $currentPage, $urlPattern) {
		$this->total = $total <= 0 ? 1 : $total;
		$this->limit = $limit;
		$this->urlPattern = $urlPattern;

		// Computes the number of pages (rule for inexact value : trunc(n)+1)
		$this->n = ceil($this->total / $this->limit);

		if ($currentPage <= 0 || $currentPage > $this->n) {
			$currentPage = 1;
		}
		$this->currentPage = $currentPage;
	}

	/**
	 * Returns the HTML code corresponding to the current page page-selector
	 *
	 * @return string HTML code of the page selector
	 */
	public function getHTML() {
		// CSS adding
		$tpl = WSystem::getTemplate();

		// Beginning of the display-chain
		$output = "

";

		$firstDone = false;
		$lastDone = false;
		for ($i = 1; $i <= $this->n; $i++) {
			if ($i == $this->currentPage) {
				$output .= sprintf('
%d (current)
 ', $i);
			}
			// We are around the current page : we display it
			else if (abs($this->currentPage - $i) <= 5) {
				$output .= sprintf('
urlPattern).'">%d
 ', $i, $i);
			}
			// Displaying something before forgetting useless pages
			else {
				// Before the current page
				if (!$firstDone && $i < $this->currentPage) {
					$firstDone = true;
					$output .= sprintf(
						'
First

«
 ',
						sprintf(urldecode($this->urlPattern), 1), sprintf(urldecode($this->urlPattern), $this->currentPage-1)
					);
				}
				// After the current page
				else if (!$lastDone && $i > $this->currentPage) {
					$lastDone = true;
					$output .= sprintf(
						'
»

Last
',
						sprintf(urldecode($this->urlPattern), $this->currentPage+1), sprintf(urldecode($this->urlPattern), $this->n)
					);
				}
				// After interesting cases : stop
				else if ($i > $this->currentPage) {
					break;
				}
			}
		}

		$output .= '

';
		return $output;
	}

	/**
	 * Returns the HTML code corresponding to the current page page-selector
	 *
	 * @see Pagination::getHTML()
	 * @return string HTML code of the page selector
	 */
	public function __toString() {
		return $this->getHTML();
	}
}

?>


text:
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Geometry;

namespace ArcGISSilverlightSDK
{
    public partial class ToolkitAttachmentEditor : UserControl
    {
        private static ESRI.ArcGIS.Client.Projection.WebMercator _mercator =
            new ESRI.ArcGIS.Client.Projection.WebMercator();

        public ToolkitAttachmentEditor()
        {
            InitializeComponent();

            ESRI.ArcGIS.Client.Geometry.Envelope initialExtent =
                    new ESRI.ArcGIS.Client.Geometry.Envelope(
                _mercator.FromGeographic(
                    new ESRI.ArcGIS.Client.Geometry.MapPoint(-122.4306073721, 37.7666097907)) as MapPoint,
                _mercator.FromGeographic(
                    new ESRI.ArcGIS.Client.Geometry.MapPoint(-122.4230971868, 37.77197420877)) as MapPoint);

            initialExtent.SpatialReference = new SpatialReference(102100);

            MyMap.Extent = initialExtent;
        }

        private void FeatureLayer_MouseLeftButtonUp(object sender, GraphicMouseButtonEventArgs e)
        {
            FeatureLayer featureLayer = sender as FeatureLayer;

            foreach (Graphic g in featureLayer.Graphics)
              if (g.Selected)
                g.UnSelect();

            e.Graphic.Select();
            MyAttachmentEditor.GraphicSource = e.Graphic;
        }

        private void MyAttachmentEditor_UploadFailed(object sender, ESRI.ArcGIS.Client.Toolkit.AttachmentEditor.UploadFailedEventArgs e)
        {
            MessageBox.Show(e.Result.Message);
        }
    }
}


text:
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test') {
  module.exports = require('./configureStore.production')
} else {
  module.exports = require('./configureStore.development')
}


text:
require "smarterfed/version"

module Smarterfed
  # Your code goes here...
end


text:
package io.fluo.commoncrawl.data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import io.fluo.api.data.Bytes;
import io.fluo.api.data.Column;
import io.fluo.api.data.RowColumn;
import io.fluo.commoncrawl.core.Constants;
import io.fluo.commoncrawl.core.DataConfig;
import io.fluo.commoncrawl.core.DataUtil;
import io.fluo.commoncrawl.data.spark.IndexEnv;
import io.fluo.commoncrawl.data.spark.IndexUtil;
import io.fluo.commoncrawl.data.util.LinkUtil;
import io.fluo.mapreduce.FluoEntryInputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.function.PairFlatMapFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Tuple2;

public class Reindex {

  private static final Logger log = LoggerFactory.getLogger(Reindex.class);

  private static IndexEnv env;

  static class RowColumnComparator implements Comparator<RowColumn>, Serializable {
    final static RowColumnComparator INSTANCE = new RowColumnComparator();

    @Override
    public int compare(RowColumn o1, RowColumn o2) {
      int result;
      result = o1.getRow().toString().compareTo(o2.getRow().toString());
      if (result == 0) {
        Column c1 = o1.getColumn();
        Column c2 = o2.getColumn();
        result = c1.getFamily().toString().compareTo(c2.getFamily().toString());
        if (result == 0) {
          result = c1.getQualifier().toString().compareTo(c2.getQualifier().toString());
          if (result == 0) {
            result = c1.getVisibility().toString().compareTo(c2.getVisibility().toString());
          }
        }
      }
      return result;
    }
  }

  public static void main(String[] args) throws Exception {

    if (args.length != 1) {
      log.error("Usage: Reindex <dataConfigPath>");
      System.exit(1);
    }
    DataConfig dataConfig = DataConfig.load(args[0]);

    try {
      SparkConf sparkConf = new SparkConf().setAppName("CC-Reindex");
      env = new IndexEnv(dataConfig, sparkConf);
      env.initAccumuloIndexTable();
      env.makeHdfsTempDirs();
    } catch (Exception e) {
      log.error("Env setup failed due to exception", e);
      System.exit(-1);
    }

    Job job = Job.getInstance(env.getSparkCtx().hadoopConfiguration());
    FluoEntryInputFormat.configure(job, env.getFluoConfig());

    JavaPairRDD<RowColumn, Bytes> fluoData =
        env.getSparkCtx().newAPIHadoopRDD(job.getConfiguration(), FluoEntryInputFormat.class,
            RowColumn.class, Bytes.class);

    JavaPairRDD<RowColumn, Bytes> indexData =
        fluoData
            .flatMapToPair(new PairFlatMapFunction<Tuple2<RowColumn, Bytes>, RowColumn, Bytes>() {
              @Override
              public Iterable<Tuple2<RowColumn, Bytes>> call(Tuple2<RowColumn, Bytes> kvTuple)
                  throws Exception {

                List<Tuple2<RowColumn, Bytes>> retval = new ArrayList<>();
                retval.add(kvTuple);
                RowColumn rc = kvTuple._1();
                String row = rc.getRow().toString();
                String cf = rc.getColumn().getFamily().toString();
                String cq = rc.getColumn().getQualifier().toString();
                Bytes v = kvTuple._2();
                if (row.startsWith("p:") && cf.equals(Constants.PAGE)
                    && (cq.equals(Constants.INCOUNT) || cq.equals(Constants.SCORE))) {
                  String pageUri = row.substring(2);
                  Long num = Long.parseLong(v.toString());
                  Column rankCol =
                      new Column(Constants.RANK, String.format("%s:%s",
                          IndexUtil.revEncodeLong(num), pageUri));
                  if (cq.equals(Constants.SCORE)) {
                    String domain = "d:" + LinkUtil.getReverseTopPrivate(DataUtil.toUrl(pageUri));
                    retval.add(new Tuple2<>(new RowColumn(domain, rankCol), v));
                  }
                  retval.add(new Tuple2<>(new RowColumn("t:" + cq, rankCol), v));
                }
                return retval;
              }
            });

    JavaPairRDD<RowColumn, Bytes> sortedIndexes = indexData.sortByKey(RowColumnComparator.INSTANCE);

    env.saveRowColBytesToAccumulo(sortedIndexes);

  }
}


text:
/**
 * JSONRPC.Client plugins need to extend this class.
 */
module.exports =
class ClientPluginBase
{
	/**
	 * Gives a chance to modify the client request object before sending it out.
	 *
	 * Normally, this allows extending the protocol.
	 *
	 * @param {JSONRPC.OutgoingRequest} outgoingRequest
	 */
	async beforeJSONEncode(outgoingRequest)
	{
		// outgoingRequest.requestObject is available here.

		// outgoingRequest.headers and outgoingRequest.enpointURL may be modified here.
		// outgoingRequest.requestBody may be set to a non-NULL value to replace JSON.stringy() (and thus replace serialization).
	}

	/**
	 * Gives a chance to encrypt, sign or log RAW outgoing requests.
	 *
	 * @param {JSONRPC.OutgoingRequest} outgoingRequest
	 */
	async afterJSONEncode(outgoingRequest)
	{
		// outgoingRequest.requestBody is available here.

		// outgoingRequest.headers and outgoingRequest.enpointURL may be modified here.
	}

	/**
	 * If a plugin chooses to actually make the call here,
	 * it must set the result in the outgoingRequest.callResult property.
	 *
	 * @param {JSONRPC.OutgoingRequest} outgoingRequest
	 *
	 * @returns {Promise.<null>}
	 */
	async makeRequest(outgoingRequest)
	{
		// outgoingRequest.callResult may be written here.
	}

	/**
	 * @param {JSONRPC.OutgoingRequest} outgoingRequest
	 */
	async beforeJSONDecode(outgoingRequest)
	{
		// outgoingRequest.responseBody is available here.
		// outgoingRequest.responseObject may be set to a non-NULL value to replace JSON.parse() (and thus replace serialization).
	}

	/**
	 * @param {JSONRPC.OutgoingRequest} outgoingRequest
	 */
	async afterJSONDecode(outgoingRequest)
	{
		// outgoingRequest.responseObject is available here.
	}

	/**
	 * Should be used to log exceptions or replace exceptions with other exceptions.
	 *
	 * This is only called if outgoingRequest.callResult is a subclass of Error or an instance of Error.
	 *
	 * @param {JSONRPC.OutgoingRequest} outgoingRequest
	 */
	async exceptionCatch(outgoingRequest)
	{
		// outgoingRequest.callResult is available here, and it is a subclass of Error.
	}
};


text:
package gw.fs;

import gw.lang.UnstableAPI;

@UnstableAPI
public class IFileUtil {

  public static String getExtension(IFile file) {
    int lastDot = file.getName().lastIndexOf(".");
    if (lastDot >= 0) {
      return file.getName().substring(lastDot + 1);
    }
    else {
      return "";
    }
  }

  public static String getExtension(String fileName) {
    int lastDot = fileName.lastIndexOf(".");
    if (lastDot >= 0) {
      return fileName.substring(lastDot + 1);
    }
    else {
      return "";
    }
  }

  public static String getBaseName(IFile file) {
    return getBaseName( file.getName() );
  }

  public static String getBaseName(String fileName) {
    int lastDot = fileName.lastIndexOf(".");
    if (lastDot >= 0) {
      return fileName.substring(0, lastDot);
    }
    else {
      return "";
    }
  }
}