text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('browser', '0019_resource_show_in_browser'),
    ]

    operations = [
        migrations.CreateModel(
            name='REvent',
            fields=[
                ('resource_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='browser.Resource')),
                ('date_time', models.DateTimeField()),
                ('location', models.TextField(blank=True)),
            ],
            options={
                'verbose_name': 'Event',
            },
            bases=('browser.resource',),
        ),
        migrations.AlterModelOptions(
            name='rlibrary',
            options={'verbose_name': 'Library Item'},
        ),
        migrations.AlterModelOptions(
            name='ronline',
            options={'verbose_name': 'Online item'},
        ),
        migrations.AlterModelOptions(
            name='rservice',
            options={'verbose_name': 'Service'},
        ),
        migrations.AlterField(
            model_name='borower',
            name='status',
            field=models.CharField(default=b'0', max_length=1, choices=[(b'0', b'Available'), (b'1', b'Reserved'), (b'2', b'Checked Out')]),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='sdisorder',
            name='aspergers',
            field=models.BooleanField(default=False, verbose_name=b'Asperger Syndrome'),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='sdisorder',
            name='cdd',
            field=models.BooleanField(default=False, verbose_name=b'Cognitive Development Disorder'),
            preserve_default=True,
        ),
    ]


text:
<?php

namespace Cola\Tests;

use Cola\MString;
use Cola\Set;

class MStringTest extends \PHPUnit_Framework_TestCase{

	public function testCodeUnit(){
		$str = new MString('一二三四五');
		$this->assertEquals(19968, $str[0]->codeUnit());
	}

	/**
	 * @expectedException \InvalidArgumentException
	 */
	public function testInvalidConstructor(){
		$str = new MString(1);
	}

	public function testImmutibility(){
		$str1 = new MString('一二三四五');
		$str2 = $str1->trim();
		$this->assertNotSame($str1, $str2);
	}

	public function testClone(){

		$str1 = new MString('一二三四五');
		$str2 = clone $str1;

		$this->assertSame(\strval($str1), \strval($str2));
		$this->assertNotSame($str1, $str2);

	}

	public function testCompare(){

		$str1 = new MString('一二三四五');
		$str2 = new MString('一二三四五');

		$this->assertEquals(0, $str1->compareTo($str2));

		$str2 = $str2->substring(0, 4);
		$this->assertEquals(1, $str1->compareTo($str2));

		$str1 = $str1->substring(0, 1);
		$this->assertEquals(-1, $str1->compareTo($str2));

	}

	public function testConcat(){
		$str = new MString('一二三四五');
		$this->assertEquals('一二三四五abcd', $str->concat('a', 'bc', 'd'));
	}

	public function testContains(){

		$str = new MString('一二三四五');

		$this->assertTrue($str->contains(new MString('四')));
		$this->assertTrue($str->contains(new MString('一二')));
		$this->assertTrue($str->contains(new MString('五')));
		$this->assertTrue($str->contains(new MString('一二三四五')));

		$this->assertFalse($str->contains(new MString('a')));
		$this->assertFalse($str->contains(new MString('0')));

	}

	public function testConvertEncoding(){

		$str = new MString('一二三四五');
		$str = $str->convertEncoding('ASCII');

		$this->assertEquals('?????', \strval($str));

	}

	public function testEndsWith(){

		$str = new MString('一二三四五');

		$this->assertTrue($str->endsWith(new MString('五')));
		$this->assertTrue($str->endsWith(new MString('二三四五')));
		$this->assertTrue($str->endsWith(new MString('一二三四五')));

		$this->assertFalse($str->endsWith(new MString('四')));
		$this->assertFalse($str->endsWith(new MString('一')));
		$this->assertFalse($str->endsWith(new MString('一二三四')));
		$this->assertFalse($str->endsWith(new MString('abc')));

	}

	/**
	 * @expectedException \InvalidArgumentException
	 */
	public function testInvalidEndsWith1(){
		$str = new MString('一二三四五');
		$this->assertTrue($str->endsWith(new MString('')));
	}

	/**
	 * @expectedException \InvalidArgumentException
	 */
	public function testInvalidEndsWith2(){
		$str = new MString('一二三四五');
		$this->assertFalse($str->endsWith(new MString('一二三四五一二三四五')));
	}

	public function testCodeUnitToCharacter(){
		$str = MString::fromCodeUnit(19968);
		$this->assertEquals('一', \strval($str));
	}

	public function testFromMString(){
		$str = MString::fromString('一二三四五');
		$this->assertEquals('一二三四五', \strval($str));
	}

	public function testEncodingSet(){

		$str = new MString('一二三四五');
		$this->assertEquals(MString::ENCODING, $str->getEncoding());

		$str = $str->convertEncoding('ASCII');
		$this->assertEquals('ASCII', $str->getEncoding());

	}

	public function testIterator(){

		$str = new MString('一二三四五');
		$out = '';

		foreach($str as $char){
			$out .= $char;
		}

		$this->assertEquals('一二三四五', $out);

	}

	public function testIndexOf(){

		$str = new MString('一二三四五');

		$this->assertEquals(0, $str->indexOf(new MString('一')));
		$this->assertEquals(4, $str->indexOf(new MString('五')));

		$this->assertEquals(MString::NO_INDEX, $str->indexOf(new MString('a')));

	}

	public function testInsert(){

		$str = new MString('一二三四五');

		$str2 = $str->insert(0, new MString('abc'));
		$this->assertEquals('abc一二三四五', \strval($str2));

		$str3 = $str->insert(4, new MString('abc'));
		$this->assertEquals('一二三四abc五', \strval($str3));

		$this->assertNotEquals(\strval($str), \strval($str3));

	}

	/**
	 * @expectedException \OutOfRangeException
	 */
	public function testInvalidInsert(){
		$str = new MString('一二三四五');
		$str->insert(5, new MString('abc'));
	}

	public function testInvoke(){

		$str = new MString('一二三四五');

		$this->assertEquals('TEST: 一二三四五', $str('TEST: %s'));
		$this->assertNotEquals('一二三四五', $str('12345, %s'));

	}

	public function testNullOrEmpty(){

		$str = new MString('一二三四五');
		$this->assertFalse($str->isNullOrEmpty());

		$str = new MString('');
		$this->assertTrue($str->isNullOrEmpty());

		$str = new MString('     ');
		$this->assertFalse($str->isNullOrEmpty());

	}

	public function testIsNullOrWhitespac(){

		$str = new MString('一二三四五');
		$this->assertFalse($str->isNullOrWhitespace());

		$str = new MString('');
		$this->assertTrue($str->isNullOrWhitespace());

		$str = new MString('     ');
		$this->assertTrue($str->isNullOrWhitespace());

	}

	public function testJoin(){

		$arr = array(
			'red',
			'green',
			'blue'
		);

		$str = MString::join($arr, new MString('一二三四五'));

		$expected = 'red一二三四五green一二三四五blue';

		$this->assertEquals($expected, \strval($str));

	}

	public function testJson(){

		$str = new MString('一二三四五');
		$expected = '"\u4e00\u4e8c\u4e09\u56db\u4e94"';
		$this->assertEquals($expected, \json_encode($str));

	}

	public function testLastIndexOf(){

		$str = new MString('一二三四一');

		$this->assertEquals(4, $str->lastIndexOf(new MString('一')));
		$this->assertEquals(1, $str->lastIndexOf(new MString('二')));

		$this->assertEquals(MString::NO_INDEX, $str->lastIndexOf(new MString('abc')));

	}

	public function testLcfirst(){

		$str = new MString('Ça me plaît');

		$this->assertEquals('ça me plaît', \strval($str->lcfirst()));
		$this->assertNotEquals('Ça me plaît', \strval($str->lcfirst()));

	}

	public function testLength(){

		$str = new MString('一二三四五');
		$this->assertEquals(5, $str->length());

		$str = new MString('');
		$this->assertEquals(0, $str->length());

		$str = new MString('一二三四五');
		$this->assertNotEquals(100, $str->length());

	}

	public function testOffsetExists(){

		$str = new MString('一二三四五');

		$this->assertTrue(isset($str[0]));
		$this->assertTrue(isset($str[4]));

		$this->assertFalse(isset($str[5]));

	}

	/**
	 * @expectedException \OutOfBoundsException
	 */
	public function testOffsetGet(){

		$str = new MString('一二三四五');

		$this->assertEquals(new MString('一'), $str[0]);
		$this->assertEquals(new MString('五'), $str[4]);

		$str[5];

	}

	public function testPadLeft(){

		$str = new MString('一二三四五');

		$str2 = $str->padLeft(5, new MString('a'));
		$this->assertEquals('aaaaa一二三四五', \strval($str2));

	}

	public function testPadRight(){

		$str = new MString('一二三四五');

		$str2 = $str->padRight(5, new MString('a'));
		$this->assertEquals('一二三四五aaaaa', \strval($str2));

	}

	public function testReplace(){

		$str = new MString('一二三四五');

		$str2 = $str->replace(new MString('一'), new MString('a'));
		$this->assertEquals('a二三四五', \strval($str2));

	}

	public function testRepeat(){

		$str = new MString('一二三四五');

		$this->assertEquals('一二三四五一二三四五一二三四五', \strval($str->repeat(3)));

	}

	public function testSubstring(){

		$str = new MString('一二三四五');

		$this->assertEquals('二三四', \strval($str->substring(1, 3)));

	}

	public function testSerialize(){

		$str = new MString('一二三四五');
		$ser = \serialize($str);

		$str2 = \unserialize($ser);
		$this->assertEquals(\strval($str), \strval($str2));

	}

	public function testShuffle(){

		$str = new MString('一二三四五一二三四五一二三四五一二三四五一二三四五');

		$this->assertNotEquals(\strval($str), \strval($str->shuffle()));

	}

	public function testSplit(){

		$str = new MString('一二三四五');

		$set = $str->split();
		$this->assertCount(5, $set);

	}

	public function testStartsWith(){

		$str = new MString('一二三四五');

		$this->assertTrue($str->startsWith(new MString('一二三')));

	}

	public function testCharArray(){

		$str = new MString('一二三四五');

		$this->assertEquals(\strval($str), \implode('', $str->toCharArray()));

	}

	public function testToLower(){

		$str = new MString('ABCDEFG');

		$this->assertEquals('abcdefg', \strval($str->toLower()));

	}

	public function testToUpper(){

		$str = new MString('abcdefg');

		$this->assertEquals('ABCDEFG', \strval($str->toUpper()));

	}

	public function testTrim(){

		$str = new MString('   一二三四五   ');

		$this->assertEquals('一二三四五', \strval($str->trim()));

	}

	public function testTrimEnd(){

		$str = new MString('一二三四五   ');

		$this->assertEquals('一二三四五', \strval($str->trimEnd()));

	}

	public function testTrimStart(){

		$str = new MString('   一二三四五');

		$this->assertEquals('一二三四五', \strval($str->trimStart()));

	}

	public function testUcfirst(){

		$str = new MString('ça me plaît');

		$this->assertEquals('Ça me plaît', \strval($str->ucfirst()));
		$this->assertNotEquals('ça me plaît', \strval($str->ucfirst()));

	}

}

redpajama_set_name: RedPajamaGithub


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

#include "chrome/browser/ash/policy/core/device_cloud_policy_manager_ash.h"

#include <stdint.h>

#include <algorithm>
#include <memory>
#include <utility>

#include "ash/constants/ash_switches.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "chrome/browser/ash/ownership/owner_settings_service_ash.h"
#include "chrome/browser/ash/ownership/owner_settings_service_ash_factory.h"
#include "chrome/browser/ash/policy/core/device_cloud_policy_client_factory_ash.h"
#include "chrome/browser/ash/policy/core/device_cloud_policy_store_ash.h"
#include "chrome/browser/ash/policy/enrollment/device_cloud_policy_initializer.h"
#include "chrome/browser/ash/policy/enrollment/enrollment_config.h"
#include "chrome/browser/ash/policy/enrollment/enrollment_handler.h"
#include "chrome/browser/ash/policy/enrollment/enrollment_requisition_manager.h"
#include "chrome/browser/ash/policy/enrollment/enrollment_status.h"
#include "chrome/browser/ash/settings/device_settings_test_helper.h"
#include "chrome/browser/device_identity/device_oauth2_token_service.h"
#include "chrome/browser/device_identity/device_oauth2_token_service_factory.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chromeos/ash/components/attestation/fake_certificate.h"
#include "chromeos/ash/components/attestation/mock_attestation_flow.h"
#include "chromeos/ash/components/cryptohome/system_salt_getter.h"
#include "chromeos/ash/components/dbus/dbus_thread_manager.h"
#include "chromeos/ash/components/dbus/session_manager/fake_session_manager_client.h"
#include "chromeos/ash/components/dbus/userdataauth/fake_cryptohome_misc_client.h"
#include "chromeos/ash/components/dbus/userdataauth/fake_install_attributes_client.h"
#include "chromeos/ash/components/install_attributes/install_attributes.h"
#include "chromeos/system/fake_statistics_provider.h"
#include "chromeos/system/statistics_provider.h"
#include "components/policy/core/common/cloud/cloud_policy_client.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "components/policy/core/common/cloud/cloud_policy_core.h"
#include "components/policy/core/common/cloud/dm_auth.h"
#include "components/policy/core/common/cloud/mock_cloud_external_data_manager.h"
#include "components/policy/core/common/cloud/mock_device_management_service.h"
#include "components/policy/core/common/cloud/mock_signing_service.h"
#include "components/policy/core/common/cloud/test/policy_builder.h"
#include "components/policy/core/common/external_data_fetcher.h"
#include "components/policy/core/common/policy_types.h"
#include "components/policy/core/common/schema_registry.h"
#include "components/policy/policy_constants.h"
#include "components/policy/proto/chrome_device_policy.pb.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/testing_pref_service.h"
#include "components/session_manager/core/session_manager.h"
#include "content/public/test/test_utils.h"
#include "google_apis/gaia/gaia_oauth_client.h"
#include "google_apis/gaia/gaia_urls.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "services/network/test/test_url_loader_factory.h"
#include "services/network/test/test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace policy {
namespace {

using ::testing::_;
using ::testing::AnyNumber;
using ::testing::AtMost;
using ::testing::DoAll;
using ::testing::Invoke;
using ::testing::Mock;
using ::testing::SaveArg;
using ::testing::StrictMock;
using ::testing::WithArgs;
namespace em = ::enterprise_management;

MATCHER_P(HasJobType, job_type, "matches job type") {
  return arg.GetConfigurationForTesting()->GetType() == job_type;
}

void CopyLockResult(base::RunLoop* loop,
                    ash::InstallAttributes::LockResult* out,
                    ash::InstallAttributes::LockResult result) {
  *out = result;
  loop->Quit();
}

void CertCallbackSuccess(
    ash::attestation::AttestationFlow::CertificateCallback callback,
    std::string certificate) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::BindOnce(std::move(callback), ash::attestation::ATTESTATION_SUCCESS,
                     std::move(certificate)));
}

void CertCallbackSuccessWithValidCertificate(
    ash::attestation::AttestationFlow::CertificateCallback callback) {
  std::string certificate;
  ash::attestation::GetFakeCertificatePEM(base::Days(10), &certificate);
  CertCallbackSuccess(std::move(callback), std::move(certificate));
}

void CertCallbackSuccessWithExpiredCertificate(
    ash::attestation::AttestationFlow::CertificateCallback callback) {
  std::string certificate;
  ash::attestation::GetFakeCertificatePEM(base::Days(-1), &certificate);
  CertCallbackSuccess(std::move(callback), std::move(certificate));
}

class FakeSigningServiceProvider final
    : public EnrollmentHandler::SigningServiceProvider {
 public:
  explicit FakeSigningServiceProvider(bool success) : success_(success) {}

  std::unique_ptr<SigningService> CreateSigningService() const override {
    auto service = std::make_unique<FakeSigningService>();
    service->set_success(success_);
    return service;
  }

 private:
  bool success_;
};

class TestingDeviceCloudPolicyManagerAsh : public DeviceCloudPolicyManagerAsh {
 public:
  TestingDeviceCloudPolicyManagerAsh(
      std::unique_ptr<DeviceCloudPolicyStoreAsh> store,
      std::unique_ptr<CloudExternalDataManager> external_data_manager,
      const scoped_refptr<base::SequencedTaskRunner>& task_runner,
      ServerBackedStateKeysBroker* state_keys_broker)
      : DeviceCloudPolicyManagerAsh(std::move(store),
                                    std::move(external_data_manager),
                                    task_runner,
                                    state_keys_broker) {
    set_component_policy_disabled_for_testing(true);
  }

  ~TestingDeviceCloudPolicyManagerAsh() override {}

  ManagedSessionService* GetManagedSessionService() {
    return managed_session_service_.get();
  }

  ash::reporting::LoginLogoutReporter* GetLoginLogoutReporter() {
    return login_logout_reporter_.get();
  }

  reporting::UserAddedRemovedReporter* GetUserAddedRemovedReporter() {
    return user_added_removed_reporter_.get();
  }
};

class DeviceCloudPolicyManagerAshTest
    : public ash::DeviceSettingsTestBase,
      public ash::SessionManagerClient::Observer {
 public:
  DeviceCloudPolicyManagerAshTest(const DeviceCloudPolicyManagerAshTest&) =
      delete;
  DeviceCloudPolicyManagerAshTest& operator=(
      const DeviceCloudPolicyManagerAshTest&) = delete;

 protected:
  DeviceCloudPolicyManagerAshTest()
      : state_keys_broker_(&session_manager_client_), store_(nullptr) {
    fake_statistics_provider_.SetMachineStatistic(
        chromeos::system::kSerialNumberKeyForTest, "test_sn");
    fake_statistics_provider_.SetMachineStatistic(
        chromeos::system::kHardwareClassKey, "test_hw");
    session_manager_client_.AddObserver(this);
  }

  ~DeviceCloudPolicyManagerAshTest() override {
    session_manager_client_.RemoveObserver(this);
    chromeos::system::StatisticsProvider::SetTestProvider(nullptr);
  }

  virtual bool ShouldRegisterWithCert() const { return false; }

  void SetUp() override {
    DeviceSettingsTestBase::SetUp();

    device_management_service_.ScheduleInitialization(0);
    base::RunLoop().RunUntilIdle();

    if (set_empty_system_salt_) {
      ash::FakeCryptohomeMiscClient::Get()->set_system_salt(
          std::vector<uint8_t>());
    }

    ash::InstallAttributesClient::InitializeFake();
    install_attributes_ = std::make_unique<ash::InstallAttributes>(
        ash::FakeInstallAttributesClient::Get());
    store_ = new DeviceCloudPolicyStoreAsh(device_settings_service_.get(),
                                           install_attributes_.get(),
                                           base::ThreadTaskRunnerHandle::Get());
    auto external_data_manager =
        std::make_unique<MockCloudExternalDataManager>();
    external_data_manager_ = external_data_manager.get();
    manager_ = std::make_unique<TestingDeviceCloudPolicyManagerAsh>(
        base::WrapUnique(store_), std::move(external_data_manager),
        base::ThreadTaskRunnerHandle::Get(), &state_keys_broker_);

    RegisterLocalState(local_state_.registry());
    manager_->Init(&schema_registry_);
    manager_->SetSigninProfileSchemaRegistry(&schema_registry_);

    // SharedURLLoaderFactory and LocalState singletons have to be set since
    // they are accessed by EnrollmentHandler and StartupUtils.
    TestingBrowserProcess::GetGlobal()->SetSharedURLLoaderFactory(
        test_url_loader_factory_.GetSafeWeakWrapper());
    TestingBrowserProcess::GetGlobal()->SetLocalState(&local_state_);

    // SystemSaltGetter is used in DeviceOAuth2TokenService.
    chromeos::SystemSaltGetter::Initialize();
    DeviceOAuth2TokenServiceFactory::Initialize(
        test_url_loader_factory_.GetSafeWeakWrapper(), &local_state_);

    url_fetcher_response_code_ = net::HTTP_OK;
    url_fetcher_response_string_ =
        "{\"access_token\":\"accessToken4Test\","
        "\"expires_in\":1234,"
        "\"refresh_token\":\"refreshToken4Test\"}";

    AllowUninterestingRemoteCommandFetches();
  }

  void TearDown() override {
    if (initializer_)
      initializer_->Shutdown();
    ShutdownManager();
    manager_.reset();
    install_attributes_.reset();

    DeviceOAuth2TokenServiceFactory::Shutdown();
    chromeos::SystemSaltGetter::Shutdown();
    ash::InstallAttributesClient::Shutdown();
    TestingBrowserProcess::GetGlobal()->SetLocalState(nullptr);

    DeviceSettingsTestBase::TearDown();
  }

  void LockDevice() {
    base::RunLoop loop;
    ash::InstallAttributes::LockResult result;
    install_attributes_->LockDevice(
        DEVICE_MODE_ENTERPRISE, PolicyBuilder::kFakeDomain,
        std::string(),  // realm
        PolicyBuilder::kFakeDeviceId,
        base::BindOnce(&CopyLockResult, &loop, &result));
    loop.Run();
    ASSERT_EQ(ash::InstallAttributes::LOCK_SUCCESS, result);
  }

  void AddStateKeys() {
    std::vector<std::string> state_keys;
    state_keys.push_back("1");
    state_keys.push_back("2");
    state_keys.push_back("3");
    session_manager_client_.set_server_backed_state_keys(state_keys);
  }

  void ConnectManager(bool expectExternalDataManagerConnectCall = true) {
    if (expectExternalDataManagerConnectCall) {
      EXPECT_CALL(*external_data_manager_, Connect(_));
    }
    AddStateKeys();
    InitDeviceCloudPolicyInitializer();
  }

  void InitDeviceCloudPolicyInitializer() {
    manager_->Initialize(&local_state_);
    EnrollmentRequisitionManager::Initialize();
    initializer_ = std::make_unique<DeviceCloudPolicyInitializer>(
        &device_management_service_, install_attributes_.get(),
        &state_keys_broker_, store_, manager_.get(),
        &fake_statistics_provider_);
    initializer_->SetSystemURLLoaderFactoryForTesting(
        test_url_loader_factory_.GetSafeWeakWrapper());
    initializer_->Init();
    base::RunLoop().RunUntilIdle();
    Mock::VerifyAndClearExpectations(external_data_manager_);
  }

  void ShutdownManager() {
    EXPECT_CALL(*external_data_manager_, Disconnect());
    manager_->Shutdown();
    Mock::VerifyAndClearExpectations(external_data_manager_);
  }

  void VerifyPolicyPopulated() {
    const auto* actual_policy =
        manager_->policies()
            .Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))
            .Get(key::kDeviceMetricsReportingEnabled);
    EXPECT_TRUE(!!actual_policy);
    PolicyMap::Entry expected_policy(POLICY_LEVEL_MANDATORY,
                                     POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD,
                                     base::Value(false), nullptr);
    EXPECT_TRUE(actual_policy->Equals(expected_policy));
  }

  // Should be called after EXPECT_CALL(..., StartJob(_)) so "any" case does
  // not override this one.
  void AllowUninterestingRemoteCommandFetches() {
    // We are not interested in remote command fetches that the client initiates
    // automatically. Make them fail and ignore them otherwise.
    EXPECT_CALL(
        job_creation_handler_,
        OnJobCreation(HasJobType(
            DeviceManagementService::JobConfiguration::TYPE_REMOTE_COMMANDS)))
        .Times(AnyNumber())
        .WillRepeatedly(device_management_service_.SendJobResponseAsync(
            net::OK, DeviceManagementService::kServiceUnavailable,
            em::DeviceManagementResponse()));
  }

  // SessionManagerClient::Observer:
  void OwnerKeySet(bool success) override {
    // Called when the owner key is set in SessionManagerClient. Make it
    // immediately available to |owner_key_util_| since code that "loads" the
    // key will load it through that instance.
    EXPECT_TRUE(success);
    owner_key_util_->SetPublicKeyFromPrivateKey(
        *device_policy_->GetNewSigningKey());
  }

  std::unique_ptr<ash::InstallAttributes> install_attributes_;

  net::HttpStatusCode url_fetcher_response_code_;
  std::string url_fetcher_response_string_;
  TestingPrefServiceSimple local_state_;
  StrictMock<MockJobCreationHandler> job_creation_handler_;
  FakeDeviceManagementService device_management_service_{
      &job_creation_handler_};
  chromeos::system::ScopedFakeStatisticsProvider fake_statistics_provider_;
  bool set_empty_system_salt_ = false;
  ServerBackedStateKeysBroker state_keys_broker_;
  StrictMock<ash::attestation::MockAttestationFlow> mock_attestation_flow_;

  DeviceCloudPolicyStoreAsh* store_;
  SchemaRegistry schema_registry_;
  MockCloudExternalDataManager* external_data_manager_;
  std::unique_ptr<TestingDeviceCloudPolicyManagerAsh> manager_;
  std::unique_ptr<DeviceCloudPolicyInitializer> initializer_;
  network::TestURLLoaderFactory test_url_loader_factory_;

 private:
  // This property is required to instantiate the session manager, a singleton
  // which is used by the device status collector.
  session_manager::SessionManager session_manager_;
};

TEST_F(DeviceCloudPolicyManagerAshTest, FreshDevice) {
  owner_key_util_->Clear();
  FlushDeviceSettings();
  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));

  manager_->Initialize(&local_state_);

  PolicyBundle bundle;
  EXPECT_TRUE(manager_->policies().Equals(bundle));
}

TEST_F(DeviceCloudPolicyManagerAshTest, EnrolledDevice) {
  LockDevice();
  FlushDeviceSettings();
  EXPECT_EQ(CloudPolicyStore::STATUS_OK, store_->status());
  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
  VerifyPolicyPopulated();

  // Trigger a policy refresh - this triggers a policy update.
  DeviceManagementService::JobForTesting policy_job;
  DeviceManagementService::JobConfiguration::JobType job_type;
  EXPECT_CALL(job_creation_handler_, OnJobCreation)
      .WillOnce(DoAll(device_management_service_.CaptureJobType(&job_type),
                      SaveArg<0>(&policy_job)));
  AllowUninterestingRemoteCommandFetches();
  ConnectManager();
  Mock::VerifyAndClearExpectations(&device_management_service_);
  ASSERT_TRUE(policy_job.IsActive());
  ASSERT_EQ(DeviceManagementService::JobConfiguration::TYPE_POLICY_FETCH,
            job_type);
  // Should create a status uploader for reporting on enrolled devices.
  EXPECT_TRUE(manager_->GetStatusUploader());
  EXPECT_TRUE(manager_->GetManagedSessionService());
  EXPECT_TRUE(manager_->GetLoginLogoutReporter());
  EXPECT_TRUE(manager_->GetUserAddedRemovedReporter());
  VerifyPolicyPopulated();

  ShutdownManager();
  VerifyPolicyPopulated();

  EXPECT_EQ(store_->policy()->service_account_identity(),
            PolicyBuilder::kFakeServiceAccountIdentity);
}

TEST_F(DeviceCloudPolicyManagerAshTest, UnmanagedDevice) {
  device_policy_->policy_data().set_state(em::PolicyData::UNMANAGED);
  device_policy_->Build();
  session_manager_client_.set_device_policy(device_policy_->GetBlob());

  LockDevice();
  FlushDeviceSettings();
  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
  EXPECT_FALSE(store_->is_managed());

  // Policy settings should be ignored for UNMANAGED devices.
  PolicyBundle bundle;
  EXPECT_TRUE(manager_->policies().Equals(bundle));

  // Trigger a policy refresh.
  DeviceManagementService::JobForTesting policy_job;
  DeviceManagementService::JobConfiguration::JobType job_type;
  EXPECT_CALL(job_creation_handler_, OnJobCreation)
      .WillOnce(DoAll(device_management_service_.CaptureJobType(&job_type),
                      SaveArg<0>(&policy_job)));
  AllowUninterestingRemoteCommandFetches();
  ConnectManager();
  Mock::VerifyAndClearExpectations(&device_management_service_);
  ASSERT_TRUE(policy_job.IsActive());
  ASSERT_EQ(DeviceManagementService::JobConfiguration::TYPE_POLICY_FETCH,
            job_type);
  // Should create a status provider for reporting on enrolled devices, even
  // those that aren't managed.
  EXPECT_TRUE(manager_->GetStatusUploader());
  EXPECT_TRUE(manager_->GetManagedSessionService());
  EXPECT_TRUE(manager_->GetLoginLogoutReporter());
  EXPECT_TRUE(manager_->GetUserAddedRemovedReporter());

  // Switch back to ACTIVE, service the policy fetch and let it propagate.
  device_policy_->policy_data().set_state(em::PolicyData::ACTIVE);
  device_policy_->Build();
  session_manager_client_.set_device_policy(device_policy_->GetBlob());
  em::DeviceManagementResponse policy_fetch_response;
  policy_fetch_response.mutable_policy_response()->add_responses()->CopyFrom(
      device_policy_->policy());
  device_management_service_.SendJobResponseNow(
      &policy_job, net::OK, DeviceManagementService::kSuccess,
      policy_fetch_response);
  EXPECT_FALSE(policy_job.IsActive());
  FlushDeviceSettings();

  // Policy state should now be active and the policy map should be populated.
  EXPECT_TRUE(store_->is_managed());
  VerifyPolicyPopulated();
}

TEST_F(DeviceCloudPolicyManagerAshTest, ConsumerDevice) {
  FlushDeviceSettings();
  EXPECT_EQ(CloudPolicyStore::STATUS_BAD_STATE, store_->status());
  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));

  PolicyBundle bundle;
  EXPECT_TRUE(manager_->policies().Equals(bundle));

  ConnectManager(false);
  EXPECT_TRUE(manager_->policies().Equals(bundle));
  // Should not create a status provider for reporting on consumer devices.
  EXPECT_FALSE(manager_->GetStatusUploader());
  EXPECT_FALSE(manager_->GetManagedSessionService());
  EXPECT_FALSE(manager_->GetLoginLogoutReporter());
  EXPECT_FALSE(manager_->GetUserAddedRemovedReporter());

  ShutdownManager();
  EXPECT_TRUE(manager_->policies().Equals(bundle));
}

TEST_F(DeviceCloudPolicyManagerAshTest, EnrolledDeviceNoStateKeysGenerated) {
  LockDevice();
  FlushDeviceSettings();
  EXPECT_EQ(CloudPolicyStore::STATUS_OK, store_->status());
  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
  VerifyPolicyPopulated();

  EXPECT_CALL(job_creation_handler_, OnJobCreation).Times(0);
  AllowUninterestingRemoteCommandFetches();

  EXPECT_FALSE(manager_->GetManagedSessionService());
  EXPECT_FALSE(manager_->GetLoginLogoutReporter());
  EXPECT_FALSE(manager_->GetUserAddedRemovedReporter());

  InitDeviceCloudPolicyInitializer();

  // Status uploader for reporting on enrolled devices is only created on
  // connect call.
  EXPECT_FALSE(manager_->GetStatusUploader());
  // Managed session service and reporters are created when notified by
  // |DeviceCloudPolicyInitializer| that the policy store is ready.
  EXPECT_TRUE(manager_->GetManagedSessionService());
  EXPECT_TRUE(manager_->GetLoginLogoutReporter());
  EXPECT_TRUE(manager_->GetUserAddedRemovedReporter());

  ShutdownManager();

  EXPECT_EQ(store_->policy()->service_account_identity(),
            PolicyBuilder::kFakeServiceAccountIdentity);
}

class DeviceCloudPolicyManagerAshObserverTest
    : public DeviceCloudPolicyManagerAshTest,
      public DeviceCloudPolicyManagerAsh::Observer {
 protected:
  DeviceCloudPolicyManagerAshObserverTest() {}

  void SetUp() override {
    DeviceCloudPolicyManagerAshTest::SetUp();
    manager_->AddDeviceCloudPolicyManagerObserver(this);
  }

  void TearDown() override {
    manager_->RemoveDeviceCloudPolicyManagerObserver(this);
    DeviceCloudPolicyManagerAshTest::TearDown();
  }

  // DeviceCloudPolicyManagerAsh::Observer:
  MOCK_METHOD0(OnDeviceCloudPolicyManagerConnected, void());
  MOCK_METHOD0(OnDeviceCloudPolicyManagerDisconnected, void());
  MOCK_METHOD0(OnDeviceCloudPolicyManagerGotRegistry, void());
};

TEST_F(DeviceCloudPolicyManagerAshObserverTest, ConnectAndDisconnect) {
  LockDevice();
  FlushDeviceSettings();
  EXPECT_FALSE(manager_->IsConnected());

  // Connect the manager.
  DeviceManagementService::JobForTesting policy_job;
  EXPECT_CALL(job_creation_handler_, OnJobCreation)
      .WillOnce(SaveArg<0>(&policy_job));
  AllowUninterestingRemoteCommandFetches();
  EXPECT_CALL(*this, OnDeviceCloudPolicyManagerConnected());
  ConnectManager();
  Mock::VerifyAndClearExpectations(&device_management_service_);
  Mock::VerifyAndClearExpectations(this);
  EXPECT_TRUE(manager_->IsConnected());

  // Disconnect the manager.
  EXPECT_CALL(*this, OnDeviceCloudPolicyManagerDisconnected());
  manager_->Disconnect();
  EXPECT_FALSE(manager_->IsConnected());
}

TEST_F(DeviceCloudPolicyManagerAshObserverTest, GetSchemaRegistry) {
  EXPECT_CALL(*this, OnDeviceCloudPolicyManagerGotRegistry()).Times(1);

  manager_->Shutdown();
  manager_->Init(&schema_registry_);

  EXPECT_FALSE(manager_->HasSchemaRegistry());

  manager_->SetSigninProfileSchemaRegistry(&schema_registry_);

  EXPECT_TRUE(manager_->HasSchemaRegistry());
}

class DeviceCloudPolicyManagerAshEnrollmentTest
    : public DeviceCloudPolicyManagerAshTest,
      public testing::WithParamInterface<bool> {
 public:
  DeviceCloudPolicyManagerAshEnrollmentTest(
      const DeviceCloudPolicyManagerAshEnrollmentTest&) = delete;
  DeviceCloudPolicyManagerAshEnrollmentTest& operator=(
      const DeviceCloudPolicyManagerAshEnrollmentTest&) = delete;

  void Done(EnrollmentStatus status) {
    enrollment_handler_.reset();
    ConnectManager(false);
    status_ = status;
    done_ = true;
  }

  MOCK_METHOD1(OnUnregistered, void(bool));

 protected:
  DeviceCloudPolicyManagerAshEnrollmentTest()
      : register_status_(DM_STATUS_SUCCESS),
        policy_fetch_status_(DM_STATUS_SUCCESS),
        robot_auth_fetch_status_(DM_STATUS_SUCCESS),
        status_(EnrollmentStatus::ForStatus(EnrollmentStatus::SUCCESS)),
        expect_robot_auth_fetch_failure_(false),
        done_(false) {}

  void SetUp() override {
    DeviceCloudPolicyManagerAshTest::SetUp();

    // Set up test data.
    device_policy_->SetDefaultNewSigningKey();
    device_policy_->policy_data().set_timestamp(
        base::Time::NowFromSystemTime().ToJavaTime());
    device_policy_->Build();

    register_response_.mutable_register_response()->set_device_management_token(
        PolicyBuilder::kFakeToken);
    register_response_.mutable_register_response()->set_enrollment_type(
        em::DeviceRegisterResponse::ENTERPRISE);
    policy_fetch_response_.mutable_policy_response()->add_responses()->CopyFrom(
        device_policy_->policy());
    robot_auth_fetch_response_.mutable_service_api_access_response()
        ->set_auth_code("auth_code_for_test");

    // Initialize the manager.
    FlushDeviceSettings();
    EXPECT_EQ(CloudPolicyStore::STATUS_BAD_STATE, store_->status());
    EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));

    PolicyBundle bundle;
    EXPECT_TRUE(manager_->policies().Equals(bundle));

    if (ShouldRegisterWithCert()) {
      // TODO(crbug.com/1298989): This expectation tests implementation details
      // of EnrollmentHandler which is not the scope of this tests. Remove it
      // once EnrollmentHandler has its own unit tests.
      EXPECT_CALL(
          mock_attestation_flow_,
          GetCertificate(
              ash::attestation::PROFILE_ENTERPRISE_ENROLLMENT_CERTIFICATE, _, _,
              /*force_new_key=*/false, _, _))
          .Times(1)
          .WillOnce(
              WithArgs<5>(Invoke(CertCallbackSuccessWithExpiredCertificate)));
      EXPECT_CALL(
          mock_attestation_flow_,
          GetCertificate(
              ash::attestation::PROFILE_ENTERPRISE_ENROLLMENT_CERTIFICATE, _, _,
              /*force_new_key=*/true, _, _))
          .Times(1)
          .WillOnce(
              WithArgs<5>(Invoke(CertCallbackSuccessWithValidCertificate)));
    }
    AddStateKeys();
  }

  void ExpectFailedEnrollment(EnrollmentStatus::Status status) {
    EXPECT_EQ(status, status_.status());
    EXPECT_FALSE(store_->is_managed());
    PolicyBundle empty_bundle;
    EXPECT_TRUE(manager_->policies().Equals(empty_bundle));
  }

  void ExpectSuccessfulEnrollment() {
    EXPECT_EQ(EnrollmentStatus::SUCCESS, status_.status());
    ASSERT_TRUE(manager_->core()->client());
    EXPECT_TRUE(manager_->core()->client()->is_registered());
    EXPECT_EQ(DEVICE_MODE_ENTERPRISE, install_attributes_->GetMode());
    EXPECT_TRUE(store_->has_policy());
    EXPECT_TRUE(store_->is_managed());
    VerifyPolicyPopulated();
  }

  void RunTest() {
    const bool with_cert = ShouldRegisterWithCert();
    // Trigger enrollment.
    DeviceManagementService::JobForTesting register_job;
    DeviceManagementService::JobConfiguration::JobType register_job_type;
    EXPECT_CALL(job_creation_handler_, OnJobCreation)
        .Times(AtMost(1))
        .WillOnce(
            DoAll(device_management_service_.CaptureJobType(&register_job_type),
                  device_management_service_.CaptureQueryParams(&query_params_),
                  device_management_service_.CaptureRequest(&register_request_),
                  SaveArg<0>(&register_job)));
    AllowUninterestingRemoteCommandFetches();

    ash::OwnerSettingsServiceAsh* owner_settings_service =
        ash::OwnerSettingsServiceAshFactory::GetForBrowserContext(
            profile_.get());
    ASSERT_TRUE(owner_settings_service);

    EnrollmentConfig enrollment_config;
    enrollment_config.auth_mechanism =
        EnrollmentConfig::AUTH_MECHANISM_BEST_AVAILABLE;
    enrollment_config.mode = with_cert ? EnrollmentConfig::MODE_ATTESTATION
                                       : EnrollmentConfig::MODE_MANUAL;
    DMAuth auth =
        with_cert ? DMAuth::NoAuth() : DMAuth::FromOAuthToken("auth token");

    auto client = CreateDeviceCloudPolicyClientAsh(
        &fake_statistics_provider_, &device_management_service_,
        test_url_loader_factory_.GetSafeWeakWrapper(),
        CloudPolicyClient::DeviceDMTokenCallback());

    enrollment_handler_ = std::make_unique<EnrollmentHandler>(
        store_, install_attributes_.get(), &state_keys_broker_,
        &mock_attestation_flow_, std::move(client),
        base::ThreadTaskRunnerHandle::Get(),
        /*ad_join_delegate=*/nullptr, enrollment_config,
        policy::LicenseType::kEnterprise, std::move(auth),
        install_attributes_->GetDeviceId(),
        EnrollmentRequisitionManager::GetDeviceRequisition(),
        EnrollmentRequisitionManager::GetSubOrganization(),

        base::BindOnce(&DeviceCloudPolicyManagerAshEnrollmentTest::Done,
                       base::Unretained(this)));
    enrollment_handler_->SetSigningServiceProviderForTesting(
        std::make_unique<FakeSigningServiceProvider>(/*success=*/true));
    enrollment_handler_->StartEnrollment();
    base::RunLoop().RunUntilIdle();
    Mock::VerifyAndClearExpectations(&device_management_service_);

    if (done_)
      return;

    // Process registration.
    ASSERT_TRUE(register_job.IsActive());
    ASSERT_EQ(
        with_cert
            ? DeviceManagementService::JobConfiguration::
                  TYPE_CERT_BASED_REGISTRATION
            : DeviceManagementService::JobConfiguration::TYPE_REGISTRATION,
        register_job_type);
    DeviceManagementService::JobForTesting fetch_job;
    DeviceManagementService::JobConfiguration::JobType fetch_job_type;
    EXPECT_CALL(job_creation_handler_, OnJobCreation)
        .Times(AtMost(1))
        .WillOnce(
            DoAll(device_management_service_.CaptureJobType(&fetch_job_type),
                  SaveArg<0>(&fetch_job)));
    AllowUninterestingRemoteCommandFetches();
    device_management_service_.SendJobResponseNow(
        &register_job,
        register_status_ == DM_STATUS_SUCCESS ? net::OK : net::ERR_FAILED,
        DeviceManagementService::kSuccess, register_response_);
    EXPECT_FALSE(register_job.IsActive());
    Mock::VerifyAndClearExpectations(&device_management_service_);

    if (done_)
      return;

    // Process policy fetch.
    ASSERT_TRUE(fetch_job.IsActive());
    ASSERT_EQ(DeviceManagementService::JobConfiguration::TYPE_POLICY_FETCH,
              fetch_job_type);
    device_management_service_.SendJobResponseNow(
        &fetch_job,
        policy_fetch_status_ == DM_STATUS_SUCCESS ? net::OK : net::ERR_FAILED,
        DeviceManagementService::kSuccess, policy_fetch_response_);
    EXPECT_FALSE(fetch_job.IsActive());

    if (done_)
      return;

    // Process verification.
    DeviceManagementService::JobForTesting robot_auth_fetch_job;
    DeviceManagementService::JobConfiguration::JobType robot_job_type;
    EXPECT_CALL(job_creation_handler_, OnJobCreation)
        .Times(AtMost(1))
        .WillOnce(
            DoAll(device_management_service_.CaptureJobType(&robot_job_type),
                  SaveArg<0>(&robot_auth_fetch_job)));
    AllowUninterestingRemoteCommandFetches();
    base::RunLoop().RunUntilIdle();
    Mock::VerifyAndClearExpectations(&device_management_service_);

    if (done_)
      return;

    // Process robot auth token fetch.
    ASSERT_TRUE(robot_auth_fetch_job.IsActive());
    ASSERT_EQ(
        DeviceManagementService::JobConfiguration::TYPE_API_AUTH_CODE_FETCH,
        robot_job_type);
    device_management_service_.SendJobResponseNow(
        &robot_auth_fetch_job,
        robot_auth_fetch_status_ == DM_STATUS_SUCCESS ? net::OK
                                                      : net::ERR_FAILED,
        DeviceManagementService::kSuccess, robot_auth_fetch_response_);
    EXPECT_FALSE(robot_auth_fetch_job.IsActive());
    Mock::VerifyAndClearExpectations(&device_management_service_);

    if (done_)
      return;

    // Set expectations for the second policy refresh that happens after the
    // enrollment completes.
    DeviceManagementService::JobForTesting component_fetch_job;
    DeviceManagementService::JobConfiguration::JobType component_job_type;
    EXPECT_CALL(job_creation_handler_, OnJobCreation)
        .Times(AtMost(1))
        .WillOnce(DoAll(
            device_management_service_.CaptureJobType(&component_job_type),
            SaveArg<0>(&component_fetch_job)));
    AllowUninterestingRemoteCommandFetches();

    // Process robot refresh token fetch if the auth code fetch succeeded.
    // DeviceCloudPolicyInitializer holds an EnrollmentHandler which
    // holds a GaiaOAuthClient that fetches the refresh token during enrollment.
    // We return a successful OAuth response via a TestURLLoaderFactory to
    // trigger the happy path for these classes so that enrollment can continue.
    if (robot_auth_fetch_status_ == DM_STATUS_SUCCESS) {
      if (!expect_robot_auth_fetch_failure_) {
        EXPECT_CALL(*external_data_manager_, Connect(_));
      }
      test_url_loader_factory_.SimulateResponseForPendingRequest(
          GaiaUrls::GetInstance()->oauth2_token_url(),
          network::URLLoaderCompletionStatus(net::OK),
          network::CreateURLResponseHead(url_fetcher_response_code_),
          url_fetcher_response_string_);
      content::RunAllTasksUntilIdle();
      Mock::VerifyAndClearExpectations(external_data_manager_);
    }

    // Process robot refresh token store and policy store.
    base::RunLoop().RunUntilIdle();

    if (!done_ || status_.status() == EnrollmentStatus::SUCCESS) {
      // Verify the state only if the task is not yet failed.
      // Note that, if the flow is not yet |done_| here, assume that it is
      // in the "succeeding" flow, so verify here, too.
      DeviceOAuth2TokenService* token_service =
          DeviceOAuth2TokenServiceFactory::Get();

      // For the refresh token for the robot account to be visible, the robot
      // account ID must not be empty.
      token_service->set_robot_account_id_for_testing(CoreAccountId("dummy"));

      EXPECT_TRUE(token_service->RefreshTokenIsAvailable());
      EXPECT_EQ(device_policy_->GetBlob(),
                session_manager_client_.device_policy());
    }
    if (done_)
      return;

    // Policy load.

    // Reloading device settings will call StartJob() a few times but the test
    // simply ignores those calls.
    EXPECT_CALL(job_creation_handler_, OnJobCreation)
        .WillRepeatedly(device_management_service_.SendJobOKAsync(
            em::DeviceManagementResponse()));
    AllowUninterestingRemoteCommandFetches();

    ReloadDeviceSettings();

    // Respond to the second policy refresh.
    if (component_fetch_job.IsActive()) {
      ASSERT_EQ(DeviceManagementService::JobConfiguration::TYPE_POLICY_FETCH,
                component_job_type);
      device_management_service_.SendJobResponseNow(
          &robot_auth_fetch_job,
          policy_fetch_status_ == DM_STATUS_SUCCESS ? net::OK : net::ERR_FAILED,
          DeviceManagementService::kSuccess, policy_fetch_response_);
      EXPECT_FALSE(robot_auth_fetch_job.IsActive());
    }
    Mock::VerifyAndClearExpectations(&device_management_service_);
  }

  bool ShouldRegisterWithCert() const override { return GetParam(); }

  const std::unique_ptr<em::DeviceRegisterRequest> GetDeviceRegisterRequest() {
    auto req = std::make_unique<em::DeviceRegisterRequest>();
    if (ShouldRegisterWithCert()) {
      em::CertificateBasedDeviceRegistrationData data;
      const em::SignedData& signed_request =
          register_request_.certificate_based_register_request()
              .signed_request();
      EXPECT_TRUE(data.ParseFromString(signed_request.data().substr(
          0,
          signed_request.data().size() - signed_request.extra_data_bytes())));
      EXPECT_EQ(em::CertificateBasedDeviceRegistrationData::
                    ENTERPRISE_ENROLLMENT_CERTIFICATE,
                data.certificate_type());
      req->CopyFrom(data.device_register_request());
    } else {
      req->CopyFrom(register_request_.register_request());
    }
    return req;
  }

  DeviceManagementStatus register_status_;
  em::DeviceManagementResponse register_response_;

  DeviceManagementStatus policy_fetch_status_;
  em::DeviceManagementResponse policy_fetch_response_;

  DeviceManagementStatus robot_auth_fetch_status_;
  em::DeviceManagementResponse robot_auth_fetch_response_;

  em::DeviceManagementRequest register_request_;
  DeviceManagementService::JobConfiguration::ParameterMap query_params_;
  EnrollmentStatus status_;

  std::unique_ptr<EnrollmentHandler> enrollment_handler_;

  // Set to true if the robot auth fetch is expected to fail.
  bool expect_robot_auth_fetch_failure_;

  bool done_;
};

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest, Success) {
  RunTest();
  ExpectSuccessfulEnrollment();
}

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest, Reenrollment) {
  LockDevice();
  RunTest();
  ExpectSuccessfulEnrollment();
  EXPECT_TRUE(GetDeviceRegisterRequest()->reregister());
  EXPECT_EQ(PolicyBuilder::kFakeDeviceId,
            query_params_[dm_protocol::kParamDeviceID]);
}

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest, RegistrationFailed) {
  register_status_ = DM_STATUS_REQUEST_FAILED;
  expect_robot_auth_fetch_failure_ = true;
  RunTest();
  ExpectFailedEnrollment(EnrollmentStatus::REGISTRATION_FAILED);
  EXPECT_EQ(DM_STATUS_REQUEST_FAILED, status_.client_status());
}

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest, RobotAuthCodeFetchFailed) {
  robot_auth_fetch_status_ = DM_STATUS_REQUEST_FAILED;
  RunTest();
  ExpectFailedEnrollment(EnrollmentStatus::ROBOT_AUTH_FETCH_FAILED);
}

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest,
       RobotRefreshTokenFetchResponseCodeFailed) {
  url_fetcher_response_code_ = net::HTTP_BAD_REQUEST;
  expect_robot_auth_fetch_failure_ = true;
  RunTest();
  ExpectFailedEnrollment(EnrollmentStatus::ROBOT_REFRESH_FETCH_FAILED);
}

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest,
       RobotRefreshTokenFetchResponseStringFailed) {
  url_fetcher_response_string_ = "invalid response json";
  expect_robot_auth_fetch_failure_ = true;
  RunTest();
  ExpectFailedEnrollment(EnrollmentStatus::ROBOT_REFRESH_FETCH_FAILED);
}

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest,
       RobotRefreshEncryptionFailed) {
  // The encryption lib is a noop for tests, but empty results from encryption
  // is an error, so we simulate an encryption error by returning an empty
  // refresh token.
  url_fetcher_response_string_ =
      "{\"access_token\":\"accessToken4Test\","
      "\"expires_in\":1234,"
      "\"refresh_token\":\"\"}";
  expect_robot_auth_fetch_failure_ = true;
  RunTest();
  ExpectFailedEnrollment(EnrollmentStatus::ROBOT_REFRESH_STORE_FAILED);
}

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest, PolicyFetchFailed) {
  policy_fetch_status_ = DM_STATUS_REQUEST_FAILED;
  RunTest();
  ExpectFailedEnrollment(EnrollmentStatus::POLICY_FETCH_FAILED);
  EXPECT_EQ(DM_STATUS_REQUEST_FAILED, status_.client_status());
}

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest, ValidationFailed) {
  device_policy_->policy().set_policy_data_signature("bad");
  policy_fetch_response_.clear_policy_response();
  policy_fetch_response_.mutable_policy_response()->add_responses()->CopyFrom(
      device_policy_->policy());
  RunTest();
  ExpectFailedEnrollment(EnrollmentStatus::VALIDATION_FAILED);
  EXPECT_EQ(CloudPolicyValidatorBase::VALIDATION_BAD_INITIAL_SIGNATURE,
            status_.validation_status());
}

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest, StoreError) {
  session_manager_client_.ForceStorePolicyFailure(true);
  expect_robot_auth_fetch_failure_ = true;
  RunTest();
  ExpectFailedEnrollment(EnrollmentStatus::STORE_ERROR);
  EXPECT_EQ(CloudPolicyStore::STATUS_STORE_ERROR, status_.store_status());
}

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest, LoadError) {
  session_manager_client_.ForceRetrievePolicyLoadError(true);
  expect_robot_auth_fetch_failure_ = true;
  RunTest();
  ExpectFailedEnrollment(EnrollmentStatus::STORE_ERROR);
  EXPECT_EQ(CloudPolicyStore::STATUS_LOAD_ERROR, status_.store_status());
}

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest, UnregisterSucceeds) {
  // Enroll first.
  RunTest();
  ExpectSuccessfulEnrollment();

  // Set up mock objects for the upcoming unregistration job.
  em::DeviceManagementResponse response;
  response.mutable_unregister_response();
  DeviceManagementService::JobConfiguration::JobType job_type;
  EXPECT_CALL(job_creation_handler_, OnJobCreation)
      .WillOnce(DoAll(device_management_service_.CaptureJobType(&job_type),
                      device_management_service_.SendJobOKAsync(response)));
  AllowUninterestingRemoteCommandFetches();
  EXPECT_CALL(*this, OnUnregistered(true));

  // Start unregistering.
  manager_->Unregister(
      base::BindOnce(&DeviceCloudPolicyManagerAshEnrollmentTest::OnUnregistered,
                     base::Unretained(this)));

  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(DeviceManagementService::JobConfiguration::TYPE_UNREGISTRATION,
            job_type);
}

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest, UnregisterFails) {
  // Enroll first.
  RunTest();
  ExpectSuccessfulEnrollment();

  // Set up mock objects for the upcoming unregistration job.
  DeviceManagementService::JobConfiguration::JobType job_type;
  EXPECT_CALL(job_creation_handler_, OnJobCreation)
      .WillOnce(DoAll(device_management_service_.CaptureJobType(&job_type),
                      device_management_service_.SendJobResponseAsync(
                          net::ERR_FAILED, DeviceManagementService::kSuccess)));
  AllowUninterestingRemoteCommandFetches();
  EXPECT_CALL(*this, OnUnregistered(false));

  // Start unregistering.
  manager_->Unregister(
      base::BindOnce(&DeviceCloudPolicyManagerAshEnrollmentTest::OnUnregistered,
                     base::Unretained(this)));

  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(DeviceManagementService::JobConfiguration::TYPE_UNREGISTRATION,
            job_type);
}

TEST_P(DeviceCloudPolicyManagerAshEnrollmentTest, DisableMachineCertReq) {
  // Simulate the flag --disable-machine-cert-request being provided to Chrome.
  base::CommandLine::ForCurrentProcess()->AppendSwitch(
      ash::switches::kDisableMachineCertRequest);

  // Set expectation that a request for a machine cert is never made.
  EXPECT_CALL(mock_attestation_flow_,
              GetCertificate(ash::attestation::AttestationCertificateProfile::
                                 PROFILE_ENTERPRISE_MACHINE_CERTIFICATE,
                             _, _, _, _, _))
      .Times(0);

  RunTest();
  ExpectSuccessfulEnrollment();
}

// A subclass that runs with a blank system salt.
class DeviceCloudPolicyManagerAshEnrollmentBlankSystemSaltTest
    : public DeviceCloudPolicyManagerAshEnrollmentTest {
 protected:
  DeviceCloudPolicyManagerAshEnrollmentBlankSystemSaltTest() {
    set_empty_system_salt_ = true;
  }
};

TEST_P(DeviceCloudPolicyManagerAshEnrollmentBlankSystemSaltTest,
       RobotRefreshSaveFailed) {
  // Without the system salt, the robot token can't be stored.
  expect_robot_auth_fetch_failure_ = true;
  RunTest();
  ExpectFailedEnrollment(EnrollmentStatus::ROBOT_REFRESH_STORE_FAILED);
}

INSTANTIATE_TEST_SUITE_P(Cert,
                         DeviceCloudPolicyManagerAshEnrollmentTest,
                         ::testing::Values(false, true));

INSTANTIATE_TEST_SUITE_P(
    Cert,
    DeviceCloudPolicyManagerAshEnrollmentBlankSystemSaltTest,
    ::testing::Values(false, true));

}  // namespace
}  // namespace policy


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class WeaponPickup : MonoBehaviour
{

    public List<GameObject> weaponsList = new List<GameObject>();

    public int weaponNum;

    public GameObject weaponObj;

    // Use this for initialization
    void Start()
    {
        //weaponObj = weaponsList[weaponNum];

        weaponObj = Instantiate(weaponsList[weaponNum], transform.position, Quaternion.identity) as GameObject;

    }

    // Update is called once per frame
    void Update()
    {

    }

    // If the player is inside the gun trigger area, they can pick it up
    void OnTriggerStay2D(Collider2D col)
    {
        if (col.gameObject.tag == "Player")
        {
            if (Input.GetKeyDown(KeyCode.C))
            {

                col.gameObject.GetComponent<PlayerCombat>().pickedUpWeaponObj = weaponObj;
                col.gameObject.GetComponent<PlayerCombat>().hasWeapon = true;
               // col.gameObject.GetComponent<PlayerCombat>().canHit = false;

                weaponObj.transform.parent = col.gameObject.transform;
                weaponObj.GetComponent<SpriteRenderer>().sortingOrder = 2;

                switch (weaponObj.tag)
                {
                    case "Gun":
                        weaponObj.GetComponent<Pistol>().canUse = true;
                        break;
                    case "BaseBall Bat":
                        weaponObj.GetComponent<BaseBallBat>().canUse = true;

                        break;
                    default:
                        print("Error");
                        break;
                }

                Destroy(gameObject);
            }
        }

    }
}


text:
CPDF_TilingPattern::CPDF_TilingPattern(CPDF_Document* pDoc,
                                       CPDF_Object* pPatternObj,
                                       const CFX_Matrix& parentMatrix)
    : CPDF_Pattern(pDoc, pPatternObj, parentMatrix) {
  ASSERT(document());
  m_bColored = pattern_obj()->GetDict()->GetIntegerFor("PaintType") == 1;
  SetPatternToFormMatrix();
}

CPDF_TilingPattern::~CPDF_TilingPattern() = default;

CPDF_TilingPattern* CPDF_TilingPattern::AsTilingPattern() {
  return this;
}

std::unique_ptr<CPDF_Form> CPDF_TilingPattern::Load(CPDF_PageObject* pPageObj) {
  const CPDF_Dictionary* pDict = pattern_obj()->GetDict();
  m_bColored = pDict->GetIntegerFor("PaintType") == 1;
  m_XStep = static_cast<float>(fabs(pDict->GetNumberFor("XStep")));
  m_YStep = static_cast<float>(fabs(pDict->GetNumberFor("YStep")));

  CPDF_Stream* pStream = pattern_obj()->AsStream();
  if (!pStream)
    return nullptr;

  const CFX_Matrix& matrix = parent_matrix();
  auto form = pdfium::MakeUnique<CPDF_Form>(document(), nullptr, pStream);

  CPDF_AllStates allStates;
  allStates.m_ColorState.Emplace();
  allStates.m_GraphState.Emplace();
  allStates.m_TextState.Emplace();
  allStates.m_GeneralState = pPageObj->m_GeneralState;
  form->ParseContent(&allStates, &matrix, nullptr);
  m_BBox = pDict->GetRectFor("BBox");
  return form;
}


text:
class Foo
  def create
    redirect_to foo_path, notice: 'Successfully created.'
  end
end


text:
<?php

namespace Unisharp\Taggable\Traits;

use Illuminate\Support\Str;
use InvalidArgumentException;

trait IndependentTag
{
    public function parent()
    {
        return $this->hasOne(get_class($this), 'id', 'parent_id');
    }

    public function subs()
    {
        return $this->hasMany(get_class($this), 'parent_id', 'id');
    }
    public function hasSubs()
    {
        return $this->subs->count() > 0;
    }

    public function hasParent()
    {
        if ($this->parent_id === 0 || is_null($this->parent)) {
            return false;
        } else {
            return true;
        }
    }

    public function addParent($parent)
    {
        $class = get_class($this);
        if (gettype($parent) == 'int') {
            $this->parent_id = $parent;
            $this->save();
        } elseif (gettype($parent) == 'string') {
            $tag = $class::firstOrCreate(['name' => $parent]);
            $tag->name = $parent;
            $tag->save();
        } elseif ($parent instanceof $class) {
            $this->parent_id = $parent->id;
            $this->save();
        } else {
            throw new InvalidArgumentException("only accept int, string or" . get_class($this) . " object");
        }
    }

    public function entities()
    {
        $entity_model = $this->entity_model ?: substr(get_class(), 0, count(get_class()) - strlen('Tag') - 1);
        $entity_reflection = new \ReflectionClass($entity_model);
        $intermediate_table = $this->intermediate_table ?: Str::snake($entity_reflection->getShortName()) . '_tag_map';
        $entity_column = Str::snake($entity_reflection->getShortName());
        return $this->belongsToMany($entity_model, $intermediate_table,'tag_id',  $entity_column . '_id');
    }
}


text:
<!DOCTYPE HTML>

<title>DateTime</title>
<meta name="date" content="2016-05-18">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Library

Object

Prev Object

Next Object

Frames

No Frames

http://www.opentravel.org/OTM/Common/v0

SimpleType DateTime

http://www.opentravel.org/OTM/Common/v0:DateTime

Description

XSD DateTime allows either a time-zone specification or allows the time-zone to be omitted.
When omitted, times are "local". XSD DateTime with either a "Z" or a "+/-hh:mm" value are UTC. Time is the time "in the indicated time zone". When a element or attribute has xsd:dateTime type, the data in a message can be either local or UTC and software can easily determine which it is.

Overview

Library

Object

Prev Object

Next Object

Frames

No Frames


text:
Working with django database
================================================================================

.. testcode::
   :hide:

    >>> class Attributable:
    ...     def __init__(self, adict):
    ...         self.mydict = adict
    ...
    ...     def __getattr__(self, field):
    ...         return self.mydict[field]
    ...
    >>> class Objects:
    ...     def __init__(self):
    ...         self.objs = None
    ...
    ...     def bulk_create(self, objs, batch_size):
    ...         self.objs = objs
    ...         self.batch_size = batch_size
    ...
    ...     def all(self):
    ...         return [Attributable(o) for o in self.objs]
    ...
    >>> class Field:
    ...     def __init__(self, name):
    ...         self.attname = name
    ...
    >>> class Meta:
    ...     instance = 0
    ...     def __init__(self):
    ...         self.model_name = "Sheet%d" % Meta.instance
    ...         self.concrete_fields = []
    ...         Meta.instance = Meta.instance + 1
    ...
    ...     def update(self, data):
    ...         for f in data:
    ...             self.concrete_fields.append(Field(f))

This section shows the way to to write and read from django database. Becuase it
is "heavy"" to include a django site here to show you. A mocked django model is
used here to demonstate it::

    >>> class FakeDjangoModel:
    ...     def __init__(self):
    ...         self.objects = Objects()
    ...         self._meta = Meta()
    ...
    ...     def __call__(self, **keywords):
    ...         return keywords

.. note::
   You can visit
   `django-excel documentation <http://django-excel.readthedocs.org/en/latest/>`_
   if you would prefer a real django model to be used in tutorial.

Write data to a django model
--------------------------------------------------------------------------------

Let's suppose we have a django model:

    >>> from pyexcel_io import save_data
    >>> from pyexcel_io.constants import DB_DJANGO, DEFAULT_SHEET_NAME
    >>> from pyexcel_io.database.common import DjangoModelImporter, DjangoModelImportAdapter
    >>> from pyexcel_io.database.common import DjangoModelExporter, DjangoModelExportAdapter
    >>> model = FakeDjangoModel()

Suppose you have these data::

    >>> data  = [
    ...     ["X", "Y", "Z"],
    ...     [1, 2, 3],
    ...     [4, 5, 6]
    ... ]
    >>> importer = DjangoModelImporter()
    >>> adapter = DjangoModelImportAdapter(model)
    >>> adapter.column_names = data[0]
    >>> importer.append(adapter)
    >>> save_data(importer, {adapter.get_name(): data[1:]}, file_type=DB_DJANGO)
    >>> import pprint
    >>> pprint.pprint(model.objects.objs)
    [{'X': 1, 'Y': 2, 'Z': 3}, {'X': 4, 'Y': 5, 'Z': 6}]

Read data from a django model
--------------------------------------------------------------------------------

.. testcode::
   :hide:

   >>> model._meta.update(["X", "Y", "Z"])

Continue from previous example, you can read this back::

   >>> from pyexcel_io import get_data
   >>> exporter = DjangoModelExporter()
   >>> adapter = DjangoModelExportAdapter(model)
   >>> exporter.append(adapter)
   >>> data = get_data(exporter, file_type=DB_DJANGO)
   >>> data
   OrderedDict([('Sheet0', [['X', 'Y', 'Z'], [1, 2, 3], [4, 5, 6]])])

Read a sub set of the columns:

   >>> exporter = DjangoModelExporter()
   >>> adapter = DjangoModelExportAdapter(model, ['X'])
   >>> exporter.append(adapter)
   >>> data = get_data(exporter, file_type=DB_DJANGO)
   >>> data
   OrderedDict([('Sheet0', [['X'], [1], [4]])])

Write data into multiple models
--------------------------------------------------------------------------------

Suppose you have the following data to be stored in the database:

    >>> data = {
    ...     "Sheet1": [['X', 'Y', 'Z'], [1, 4, 7], [2, 5, 8], [3, 6, 9]],
    ...     "Sheet2": [['A', 'B', 'C'], [1, 4, 7], [2, 5, 8], [3, 6, 9]]
    ... }

And want to save them to two django models:

    >>> model1 = FakeDjangoModel()
    >>> model2 = FakeDjangoModel()

In order to store a dictionary data structure, you need to do some transformation::

    >>> importer = DjangoModelImporter()
    >>> adapter1 = DjangoModelImportAdapter(model1)
    >>> adapter1.column_names = data['Sheet1'][0]
    >>> adapter2 = DjangoModelImportAdapter(model2)
    >>> adapter2.column_names = data['Sheet2'][0]
    >>> importer.append(adapter1)
    >>> importer.append(adapter2)
    >>> to_store = {
    ...    adapter1.get_name(): data['Sheet1'][1:],
    ...    adapter2.get_name(): data['Sheet2'][1:]
    ... }
    >>> save_data(importer, to_store, file_type=DB_DJANGO)
    >>> pprint.pprint(model1.objects.objs)
    [{'X': 1, 'Y': 4, 'Z': 7}, {'X': 2, 'Y': 5, 'Z': 8}, {'X': 3, 'Y': 6, 'Z': 9}]
    >>> pprint.pprint(model2.objects.objs)
    [{'A': 1, 'B': 4, 'C': 7}, {'A': 2, 'B': 5, 'C': 8}, {'A': 3, 'B': 6, 'C': 9}]

.. testcode:
   :hide:

   >>> model1._meta.update(["X", "Y", "Z"])
   >>> model2._meta.update(["A", "B", "C"])

Read content from multiple tables
--------------------------------------------------------------------------------

Here's what you need to do:

    >>> exporter = DjangoModelExporter()
    >>> adapter1 = DjangoModelExportAdapter(model1)
    >>> adapter2 = DjangoModelExportAdapter(model2)
    >>> exporter.append(adapter1)
    >>> exporter.append(adapter2)
    >>> data = get_data(exporter, file_type=DB_DJANGO)
    >>> data
    OrderedDict([('Sheet1', [['X', 'Y', 'Z'], [1, 4, 7], [2, 5, 8], [3, 6, 9]]), ('Sheet2', [['A', 'B', 'C'], [1, 4, 7], [2, 5, 8], [3, 6, 9]])])

What if we need only a subset of each model

    >>> exporter = DjangoModelExporter()
    >>> adapter1 = DjangoModelExportAdapter(model1, ['X'])
    >>> adapter2 = DjangoModelExportAdapter(model2, ['A'])
    >>> exporter.append(adapter1)
    >>> exporter.append(adapter2)
    >>> data = get_data(exporter, file_type=DB_DJANGO)
    >>> data
    OrderedDict([('Sheet1', [['X'], [1], [2], [3]]), ('Sheet2', [['A'], [1], [2], [3]])])


text:
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

const { Route } = Ember;

export default Route.extend(ApplicationRouteMixin, {
  actions: {
    logout () {
      this.get('session').invalidate();
      this.get('flashMessages').success('Logged out');
    }
  }
});


text:
<?php

/**
 * admin side controller
 * accessible in $polylang global object
 *
 * properties:
 * options          => inherited, reference to Polylang options array
 * model            => inherited, reference to PLL_Model object
 * links_model      => inherited, reference to PLL_Links_Model object
 * links            => inherited, reference to PLL_Admin_Links object
 * static_pages     => inherited, reference to PLL_Admin_Static_Pages object
 * filters_links    => inherited, reference to PLL_Filters_Links object
 * curlang          => inherited, optional, current language used to filter the content (language of the post or term being edited, equal to filter_lang otherwise)
 * filter_lang      => inherited, optional, current status of the admin languages filter (in the admin bar)
 * pref_lang        => inherited, preferred language used as default when saving posts or terms
 * filters          => reference to PLL_Filters object
 * filters_columns  => reference to PLL_Admin_Filters_Columns object
 * filters_post     => reference to PLL_Admin_Filters_Post object
 * filters_term     => reference to PLL_Admin_filters_Term object
 * nav_menu         => reference to PLL_Admin_Nav_Menu object
 * filters_media    => optional, reference to PLL_Admin_Filters_Media object
 *
 * @since 1.2
 */
class PLL_Admin extends PLL_Admin_Base {
	public $filters, $filters_columns, $filters_post, $filters_term, $nav_menu, $sync, $filters_media;

	/**
	 * loads the polylang text domain
	 * setups filters and action needed on all admin pages and on plugins page
	 *
	 * @since 1.2
	 *
	 * @param object $links_model
	 */
	public function __construct( &$links_model ) {
		parent::__construct( $links_model );

		// adds a 'settings' link in the plugins table
		add_filter( 'plugin_action_links_' . POLYLANG_BASENAME, array( $this, 'plugin_action_links' ) );
		add_action( 'in_plugin_update_message-' . POLYLANG_BASENAME, array( $this, 'plugin_update_message' ), 10, 2 );
	}

	/**
	 * setups filters and action needed on all admin pages and on plugins page
	 * loads the settings pages or the filters base on the request
	 *
	 * @since 1.2
	 *
	 * @param object $links_model
	 */
	public function init() {
		parent::init();

		// setup filters for admin pages
		// priority 5 to make sure filters are there before customize_register is fired
		if ( $this->model->get_languages_list() ) {
			add_action( 'wp_loaded', array( $this, 'add_filters' ), 5 );
		}
	}

	/**
	 * adds a 'settings' link in the plugins table
	 *
	 * @since 0.1
	 *
	 * @param array $links list of links associated to the plugin
	 * @return array modified list of links
	 */
	public function plugin_action_links( $links ) {
		array_unshift( $links, '' . __( 'Settings', 'polylang' ) . '' );
		return $links;
	}

	/**
	 * adds the upgrade notice in plugins table
	 *
	 * @since 1.1.6
	 *
	 * @param array $plugin_data not used
	 * @param object $r plugin update data
	 */
	function plugin_update_message( $plugin_data, $r ) {
		if ( isset( $r->upgrade_notice ) ) {
			printf( '
%s
', esc_html( $r->upgrade_notice ) );
		}
	}

	/**
	 * setup filters for admin pages
	 *
	 * @since 1.2
	 */
	public function add_filters() {
		// all these are separated just for convenience and maintainability
		$classes = array( 'Filters', 'Filters_Columns', 'Filters_Post', 'Filters_Term', 'Nav_Menu', 'Sync' );

		// don't load media filters if option is disabled or if user has no right
		if ( $this->options['media_support'] && ( $obj = get_post_type_object( 'attachment' ) ) && ( current_user_can( $obj->cap->edit_posts ) || current_user_can( $obj->cap->create_posts ) ) ) {
			$classes[] = 'Filters_Media';
		}

		foreach ( $classes as $class ) {
			$obj = strtolower( $class );

			/**
			 * Filter the class to instantiate when loding admin filters
			 *
			 * @since 1.5
			 *
			 * @param string $class class name
			 */
			$class = apply_filters( 'pll_' . $obj, 'PLL_Admin_' . $class );
			$this->$obj = new $class( $this );
		}
	}
}


text:
using GRA.Abstract;
using GRA.Domain.Model;
using GRA.Domain.Model.Filters;
using GRA.Domain.Repository;
using GRA.Domain.Service.Abstract;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;
using ExcelDataReader;
using System;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.IO;

namespace GRA.Domain.Service
{
    public class VendorCodeService : BaseUserService<VendorCodeService>
    {
        private readonly ICodeGenerator _codeGenerator;
        private readonly IUserRepository _userRepository;
        private readonly IVendorCodeRepository _vendorCodeRepository;
        private readonly IVendorCodeTypeRepository _vendorCodeTypeRepository;
        private readonly MailService _mailService;
        public VendorCodeService(ILogger<VendorCodeService> logger,
            GRA.Abstract.IDateTimeProvider dateTimeProvider,
            IUserContextProvider userContextProvider,
            IUserRepository userRepository,
            ICodeGenerator codeGenerator,
            IVendorCodeRepository vendorCodeRepository,
            IVendorCodeTypeRepository vendorCodeTypeRepository,
            MailService mailService)
            : base(logger, dateTimeProvider, userContextProvider)
        {
            SetManagementPermission(Permission.ManageVendorCodes);
            _codeGenerator = Require.IsNotNull(codeGenerator, nameof(codeGenerator));
            _userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
            _vendorCodeRepository = Require.IsNotNull(vendorCodeRepository, nameof(vendorCodeRepository));
            _vendorCodeTypeRepository = Require.IsNotNull(vendorCodeTypeRepository, nameof(vendorCodeTypeRepository));
            _mailService = mailService ?? throw new ArgumentNullException(nameof(mailService));
        }

        public async Task<VendorCodeType> GetTypeById(int id)
        {
            return await _vendorCodeTypeRepository.GetByIdAsync(id);
        }

        public async Task<ICollection<VendorCodeType>> GetTypeAllAsync()
        {
            VerifyManagementPermission();
            return await _vendorCodeTypeRepository.GetAllAsync(GetCurrentSiteId());
        }

        public async Task<DataWithCount<ICollection<VendorCodeType>>> GetTypePaginatedListAsync(BaseFilter filter)
        {
            VerifyManagementPermission();
            filter.SiteId = GetCurrentSiteId();
            return new DataWithCount<ICollection<VendorCodeType>>
            {
                Data = await _vendorCodeTypeRepository.PageAsync(filter),
                Count = await _vendorCodeTypeRepository.CountAsync(filter)
            };
        }

        public async Task<VendorCodeType> AddTypeAsync(VendorCodeType vendorCodeType)
        {
            VerifyManagementPermission();
            vendorCodeType.SiteId = GetCurrentSiteId();
            return await _vendorCodeTypeRepository.AddSaveAsync(GetClaimId(ClaimType.UserId),
                vendorCodeType);
        }

        public async Task<VendorCodeType> UpdateTypeAsync(VendorCodeType vendorCodeType)
        {
            VerifyManagementPermission();
            vendorCodeType.SiteId = GetCurrentSiteId();
            return await _vendorCodeTypeRepository.UpdateSaveAsync(GetClaimId(ClaimType.UserId),
                vendorCodeType);
        }

        public async Task RemoveTypeAsync(int vendorCodeTypeId)
        {
            VerifyManagementPermission();
            await _vendorCodeTypeRepository.RemoveSaveAsync(GetClaimId(ClaimType.UserId),
                vendorCodeTypeId);
        }

        public async Task<int> GenerateVendorCodesAsync(int vendorCodeTypeId, int numberOfCodes)
        {
            VerifyManagementPermission();
            var codeType = await _vendorCodeTypeRepository.GetByIdAsync(vendorCodeTypeId);
            if (codeType == null)
            {
                throw new GraException("Unable to find vendor code type.");
            }
            if (codeType.SiteId != GetCurrentSiteId())
            {
                throw new GraException("Code type provided does not match current site.");
            }

            int count = 1;
            var vendorCode = new VendorCode
            {
                IsUsed = false,
                SiteId = codeType.SiteId,
                VendorCodeTypeId = codeType.Id,
            };
            for (; count <= System.Math.Min(numberOfCodes, 5000); count++)
            {
                vendorCode.Code = _codeGenerator.Generate(15);
                await _vendorCodeRepository.AddAsync(GetClaimId(ClaimType.UserId), vendorCode);
                if (count % 1000 == 0)
                {
                    await _vendorCodeRepository.SaveAsync();
                }
            }
            await _vendorCodeRepository.SaveAsync();

            return --count;
        }

        public async Task<VendorCode> GetUserVendorCodeAsync(int userId)
        {
            var authorized = false;
            var authId = GetClaimId(ClaimType.UserId);
            if (userId == authId || userId == GetActiveUserId() || HasPermission(Permission.ViewParticipantDetails))
            {
                authorized = true;
            }

            if (!authorized)
            {
                var user = await _userRepository.GetByIdAsync(userId);
                authorized = user.HouseholdHeadUserId == authId;
            }

            if (authorized)
            {
                var vendorCode = await _vendorCodeRepository.GetUserVendorCode(userId);
                if (vendorCode != null)
                {
                    var codeType = await _vendorCodeTypeRepository
                        .GetByIdAsync(vendorCode.VendorCodeTypeId);
                    vendorCode.CanBeDonated = !string.IsNullOrEmpty(codeType.DonationMessage);
                    if (!string.IsNullOrEmpty(codeType.Url))
                    {
                        vendorCode.Url = codeType.Url.Contains(TemplateToken.VendorCodeToken)
                            ? codeType.Url.Replace(TemplateToken.VendorCodeToken, vendorCode.Code)
                            : codeType.Url;
                    }
                    return vendorCode;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                _logger.LogError($"User {authId} doesn't have permission to view details for {userId}.");
                throw new GraException("Permission denied.");
            }
        }

        private const string CouponRowHeading = "Coupon";
        private const string OrderDateRowHeading = "Order Date";
        private const string ShipDateRowHeading = "Ship Date";

        public async Task<OperationStatus> UpdateStatusFromExcel(string filename,
            CancellationToken token,
            IProgress<OperationStatus> progress = null)
        {
            var requestingUser = GetClaimId(ClaimType.UserId);

            if (HasPermission(Permission.ManageVendorCodes))
            {
                var sw = new Stopwatch();
                sw.Start();
                token.Register(() =>
                {
                    string duration = "";
                    if (sw != null && sw.Elapsed != null)
                    {
                        duration = $" after {((TimeSpan)sw.Elapsed).TotalSeconds.ToString("N2")} seconds";
                    }
                    _logger.LogWarning($"Import of {filename} for user {requestingUser} was cancelled{duration}.");
                });

                string fullPath = Path.Combine(Path.GetTempPath(), filename);

                if (!File.Exists(fullPath))
                {
                    _logger.LogError($"Could not find {fullPath}");
                    return new OperationStatus
                    {
                        PercentComplete = 0,
                        Status = "Could not find the import file.",
                        Error = true,
                        Complete = true
                    };
                }

                try
                {
                    using (var stream = new FileStream(fullPath, FileMode.Open))
                    {
                        int couponColumnId = 0;
                        int orderDateColumnId = 0;
                        int shipDateColumnId = 0;
                        var issues = new List<string>();
                        int row = 0;
                        int totalRows = 0;
                        int updated = 0;
                        int alreadyCurrent = 0;
                        using (var excelReader = ExcelReaderFactory.CreateBinaryReader(stream))
                        {
                            while (excelReader.Read())
                            {
                                row++;
                            }
                            totalRows = row;
                            row = 0;

                            excelReader.Reset();
                            while (excelReader.Read())
                            {
                                row++;
                                if (row % 10 == 0)
                                {
                                    progress.Report(new OperationStatus
                                    {
                                        PercentComplete = row * 100 / totalRows,
                                        Status = $"Processing row {row}/{totalRows}...",
                                        Error = false
                                    });
                                }
                                if (row == 1)
                                {
                                    progress.Report(new OperationStatus
                                    {
                                        PercentComplete = 1,
                                        Status = $"Processing row {row}/{totalRows}...",
                                        Error = false
                                    });
                                    for (int i = 0; i < excelReader.FieldCount; i++)
                                    {
                                        switch (excelReader.GetString(i).Trim() ?? $"Column{i}")
                                        {
                                            case CouponRowHeading:
                                                couponColumnId = i;
                                                break;
                                            case OrderDateRowHeading:
                                                orderDateColumnId = i;
                                                break;
                                            case ShipDateRowHeading:
                                                shipDateColumnId = i;
                                                break;
                                        }
                                    }
                                }
                                else
                                {
                                    string coupon = null;
                                    DateTime? orderDate = null;
                                    DateTime? shipDate = null;
                                    try
                                    {
                                        coupon = excelReader.GetString(couponColumnId);
                                    }
                                    catch (Exception ex)
                                    {
                                        _logger.LogError($"Parse error on code, row {row}: {ex.Message}");
                                        issues.Add($"Issue reading code on line {row}: {ex.Message}");
                                    }
                                    try
                                    {
                                        orderDate = excelReader.GetDateTime(orderDateColumnId);
                                    }
                                    catch (Exception ex)
                                    {
                                        _logger.LogError($"Parse error on order date, row {row}: {ex.Message}");
                                        issues.Add($"Issue reading order date on row {row}: {ex.Message}");
                                    }
                                    try
                                    {
                                        shipDate = excelReader.GetDateTime(shipDateColumnId);
                                    }
                                    catch (Exception ex)
                                    {
                                        _logger.LogError($"Parse error on ship date, row {row}: {ex.Message}");
                                        issues.Add($"Issue reading ship date on row {row}: {ex.Message}");
                                    }
                                    if (!string.IsNullOrEmpty(coupon)
                                        && (orderDate != null && shipDate != null))
                                    {
                                        var code = await _vendorCodeRepository.GetByCode(coupon);
                                        if (code == null)
                                        {
                                            _logger.LogError($"File contained code {coupon} which was not found in the database");
                                            issues.Add($"Uploaded file contained code {coupon} which couldn't be found in the database.");
                                        }
                                        else
                                        {
                                            if (orderDate == code.OrderDate && shipDate == code.ShipDate)
                                            {
                                                alreadyCurrent++;
                                            }
                                            else
                                            {
                                                code.IsUsed = true;
                                                if (orderDate != null)
                                                {
                                                    code.OrderDate = orderDate;
                                                }
                                                if (shipDate != null)
                                                {
                                                    code.ShipDate = shipDate;
                                                }
                                                await _vendorCodeRepository.UpdateSaveNoAuditAsync(code);
                                                updated++;
                                            }
                                        }
                                    }
                                }
                                if (token.IsCancellationRequested)
                                {
                                    break;
                                }
                            }

                            if (!excelReader.IsClosed)
                            {
                                excelReader.Close();
                            }
                        }

                        if (token.IsCancellationRequested)
                        {
                            return new OperationStatus
                            {
                                PercentComplete = 100,
                                Status = $"Operation cancelled at row {row}."
                            };
                        }

                        var sb = new StringBuilder("Import complete");
                        if (updated > 0)
                        {
                            sb.Append($": {updated} records were updated");
                        }
                        if (alreadyCurrent > 0)
                        {
                            if (updated > 0)
                            {
                                sb.Append(", ");
                            }
                            else
                            {
                                sb.Append(": ");
                            }
                            sb.Append($"{alreadyCurrent} records were already current");
                        }
                        sb.Append(".");

                        if (issues.Count > 0)
                        {
                            _logger.LogInformation($"Import complete with issues: {sb.ToString()}");
                            sb.Append(" Issues detected:
");
                            foreach (string issue in issues)
                            {
                                sb.Append($"
{issue}
");
                            }
                            sb.Append("
");
                            return new OperationStatus
                            {
                                PercentComplete = 100,
                                Status = sb.ToString(),
                                Error = true
                            };
                        }
                        else
                        {
                            _logger.LogInformation(sb.ToString());
                            return new OperationStatus
                            {
                                PercentComplete = 100,
                                Status = sb.ToString(),
                            };
                        }
                    }
                }
                finally
                {
                    File.Delete(fullPath);
                }
            }
            else
            {
                _logger.LogError($"User {requestingUser} doesn't have permission to view all reporting.");
                return new OperationStatus
                {
                    PercentComplete = 0,
                    Status = "Permission denied.",
                    Error = true,
                    Complete = true
                };
            }
        }

        public async Task<bool> SiteHasCodesAsync()
        {
            return await _vendorCodeTypeRepository.SiteHasCodesAsync(GetCurrentSiteId());
        }

        public async Task<VendorCode> ResolveDonationStatusAsync(int userId, bool? donate)
        {
            var authorized = false;
            var authId = GetClaimId(ClaimType.UserId);
            if (userId == authId || userId == GetActiveUserId() || HasPermission(Permission.ViewParticipantDetails))
            {
                authorized = true;
            }

            if (!authorized)
            {
                var user = await _userRepository.GetByIdAsync(userId);
                authorized = user.HouseholdHeadUserId == authId;
            }

            if (authorized)
            {
                var siteId = GetClaimId(ClaimType.SiteId);

                var vendorCode = await _vendorCodeRepository.GetUserVendorCode(userId);
                vendorCode.IsDonated = donate;
                await _vendorCodeRepository.UpdateSaveAsync(userId, vendorCode);

                var vendorCodeType = await _vendorCodeTypeRepository.GetByIdAsync(vendorCode.VendorCodeTypeId);

                if (donate == null || donate == false)
                {
                    await SendVendorCodeMailAsync(userId, siteId, vendorCodeType, vendorCode.Code);
                }
                else if (donate == true
                  && !string.IsNullOrEmpty(vendorCodeType.DonationSubject)
                  && !string.IsNullOrEmpty(vendorCodeType.DonationMail))
                {
                    await SendVendorDonationMailAsync(userId, siteId, vendorCodeType);
                }

                return vendorCode;
            }
            else
            {
                _logger.LogError($"User {authId} doesn't have permission to update code donation status for {userId}.");
                throw new GraException("Permission denied.");
            }
        }

        public async Task PopulateVendorCodeStatusAsync(User user)
        {
            var vendorCode = await GetUserVendorCodeAsync(user.Id);
            if (vendorCode != null)
            {
                user.Donated = vendorCode.IsDonated;
                if (vendorCode.CanBeDonated && vendorCode.IsDonated == null)
                {
                    user.NeedsToAnswerDonationQuestion = true;
                }
                else if (vendorCode.CanBeDonated && vendorCode.IsDonated == true)
                {
                    var vendorCodeType
                        = await _vendorCodeTypeRepository.GetByIdAsync(vendorCode.VendorCodeTypeId);
                    user.VendorCode = vendorCodeType.DonationMessage;
                }
                else
                {
                    user.VendorCode = vendorCode.Code;
                    user.VendorCodeUrl = vendorCode.Url;
                    if (vendorCode.ShipDate.HasValue)
                    {
                        user.VendorCodeMessage = $"Shipped: {vendorCode.ShipDate.Value.ToString("d")}";
                    }
                    else if (vendorCode.OrderDate.HasValue)
                    {
                        user.VendorCodeMessage = $"Ordered: {vendorCode.OrderDate.Value.ToString("d")}";
                    }
                }
            }
        }

        private async Task SendVendorCodeMailAsync(int userId,
            int? siteId,
            VendorCodeType codeType,
            string assignedCode)
        {
            string body = null;
            if (!codeType.Mail.Contains(TemplateToken.VendorCodeToken))
            {
                // the token isn't in the message, just append the code to the end
                body = $"{codeType.Mail} {assignedCode}";
            }
            else
            {
                if (string.IsNullOrEmpty(codeType.Url))
                {
                    // we have a token but no url, replace the token with the code
                    body = codeType.Mail.Replace(TemplateToken.VendorCodeToken, assignedCode);
                }
                else
                {
                    string url = null;
                    // see if the url has the token in it, if so swap in the code
                    if(!codeType.Url.Contains(TemplateToken.VendorCodeToken))
                    {
                        url = codeType.Url;
                    }
                    else
                    {
                        url = codeType.Url.Replace(TemplateToken.VendorCodeToken, assignedCode);
                    }
                    // token and url - make token clickable to go to url
                    body = codeType.Mail.Replace(TemplateToken.VendorCodeToken,
                        $"{assignedCode}");
                }
            }

            await _mailService.SendSystemMailAsync(new Mail
            {
                ToUserId = userId,
                CanParticipantDelete = false,
                Subject = codeType.MailSubject,
                Body = body
            }, siteId);
        }

        private async Task SendVendorDonationMailAsync(int userId,
            int? siteId,
            VendorCodeType codeType)
        {
            await _mailService.SendSystemMailAsync(new Mail
            {
                ToUserId = userId,
                CanParticipantDelete = false,
                Subject = codeType.DonationSubject,
                Body = codeType.DonationMail
            }, siteId);
        }
    }
}


text:
package com.sixrr.stockmetrics.interfaceCalculators;

import com.intellij.psi.JavaRecursiveElementVisitor;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElementVisitor;
import com.sixrr.metrics.utils.ClassUtils;

public class CommentRatioInterfaceCalculator extends InterfaceCalculator
{
	private int commentLines = 0;

	@Override
	protected PsiElementVisitor createVisitor()
	{
		return new Visitor();
	}

	private class Visitor extends JavaRecursiveElementVisitor
	{

		@Override
		public void visitClass(PsiClass aClass)
		{
			int prevCommentLines = 0;
			if(!ClassUtils.isAnonymous(aClass))
			{
				prevCommentLines = commentLines;
				commentLines = 0;
			}
			super.visitClass(aClass);
			if(!ClassUtils.isAnonymous(aClass))
			{
				if(isInterface(aClass))
				{
					int linesOfCode = com.sixrr.stockmetrics.utils.LineUtil.countLines(aClass);
					final PsiClass[] innerClasses = aClass.getInnerClasses();
					for(PsiClass innerClass : innerClasses)
					{
						linesOfCode -= com.sixrr.stockmetrics.utils.LineUtil.countLines(innerClass);
					}
					postMetric(aClass, commentLines, linesOfCode);
				}
				commentLines = prevCommentLines;
			}
		}

		@Override
		public void visitComment(PsiComment comment)
		{
			super.visitComment(comment);
			commentLines += com.sixrr.stockmetrics.utils.LineUtil.countLines(comment);
		}
	}
}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using System.Security;
using Microsoft.WindowsAzure.Commands.Common.Models;
using Microsoft.WindowsAzure.Commands.Common.Test.Mocks;
using Microsoft.WindowsAzure.Commands.Utilities.Common.Authentication;

namespace Microsoft.WindowsAzure.Commands.Test.Utilities.Common
{
    public class MockAccessTokenProvider : ITokenProvider
    {
        private readonly IAccessToken accessToken;

        public MockAccessTokenProvider(string token)
            : this(token, "user@live.com")
        { }

        public MockAccessTokenProvider(string token, string userId)
        {
            this.accessToken = new MockAccessToken()
            {
                AccessToken = token,
                UserId = userId
            };
        }

        public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password,
            AzureAccount.AccountType credentialType)
        {
            return this.accessToken;
        }
    }
}


text:
package main.scala.cloud4things.configuration

import main.scala.cloud4things.events.EventCycle
import main.scala.cloud4things.readers.Reader

class Configuration(var id: String, var endpoint: String) {

  // List of Readers
  private val readers = scala.collection.mutable.Map[String, Reader]()

  // List of EventCycles
  private val eventCycles = scala.collection.mutable.Map[String, EventCycle]()

  // Add a new reader to a configuration
  def addReader(reader: Reader) = {
    readers += (reader.readerName -> reader)
  }

  // Delete a Reader with name {name}
  def deleteReader(name: String) = {
    readers -= name
  }

  // List all Readers of a given smart-place
  def showReaders = {
    println("Printing readers ....")
    readers.foreach( r => println (r._1))
  }

  // Get all readers
  def getAllReaders = {
    readers.values
  }

  // Add a new EventCycle to a configuration
  def addEventCycle(eventCycle: EventCycle) {
    eventCycles += (eventCycle.eventName -> eventCycle)
  }

  // Delete a EventCycle with name {name}
  def deleteEventCycle(name: String) = {
    eventCycles -= name
  }

  // List all EventCycles
  def showEventCycles() = {
    println("Printing event cycles ....")
    eventCycles.foreach( e => println (e._1))
  }

  // Get all EventCyles
  def getAllEvents = {
    eventCycles.values
  }

}


text:
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Xunit;

namespace System.Reflection.Emit.Tests
{
    public class EnumBuilderBaseType
    {
        private AssemblyBuilder _myAssemblyBuilder;
        private ModuleBuilder _myModuleBuilder;
        private EnumBuilder _myEnumBuilder;
        private void CreateCallee()
        {
            AssemblyName myAssemblyName = new AssemblyName();
            myAssemblyName.Name = "EnumAssembly";
            _myAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run);
            _myModuleBuilder = TestLibrary.Utilities.GetModuleBuilder(_myAssemblyBuilder, "EnumModule.mod");
        }

        [Fact]
        public void TestBaseTypeProperty()
        {
            CreateCallee();
            _myEnumBuilder = _myModuleBuilder.DefineEnum("myEnum", TypeAttributes.Public, typeof(int));
            _myEnumBuilder.AsType();
            Type myBaseType = _myEnumBuilder.BaseType;
            Assert.Equal(typeof(Enum), myBaseType);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">

    <!-- value for the phone mode menu -->
    <string name="bbn_phone_view_behavior" translatable="false" tools:ignore="UnusedResources">it.sephiroth.android.library.bottomnavigation.BottomBehavior</string>

    <!-- behavior for the tablet mode menu -->
    <string name="bbn_tablet_view_behavior" translatable="false" tools:ignore="UnusedResources">it.sephiroth.android.library.bottomnavigation.TabletBehavior</string>

    <!-- this is the default value -->
    <string name="bbn_default_view_behavior" translatable="false" tools:ignore="UnusedResources">it.sephiroth.android.library.bottomnavigation.BottomBehavior</string>

    <!-- default badge provider -->
    <string name="bbn_badgeProvider" translatable="false" tools:ignore="UnusedResources">it.sephiroth.android.library.bottomnavigation.BadgeProvider</string>

    <!-- default floating action button behavior -->
    <string name="bbn_fab_default_behavior" translatable="false" tools:ignore="UnusedResources">it.sephiroth.android.library.bottomnavigation.FloatingActionButtonBehavior</string>
</resources>