text:
<?php

/*
 * GENERATED CODE WARNING
 * This file was automatically generated - do not edit!
 */

namespace Google\Cloud\Compute\Tests\Unit\V1;

use Google\ApiCore\ApiException;
use Google\ApiCore\CredentialsWrapper;
use Google\ApiCore\Testing\GeneratedTest;

use Google\ApiCore\Testing\MockTransport;
use Google\Cloud\Compute\V1\GetRegionOperationRequest;
use Google\Cloud\Compute\V1\Operation;
use Google\Cloud\Compute\V1\Operation\Status;
use Google\Cloud\Compute\V1\RegionOperationsClient;
use Google\Cloud\Compute\V1\RegionTargetHttpProxiesClient;
use Google\Cloud\Compute\V1\TargetHttpProxy;
use Google\Cloud\Compute\V1\TargetHttpProxyList;
use Google\Cloud\Compute\V1\UrlMapReference;
use Google\Rpc\Code;
use stdClass;

/**
 * @group compute
 *
 * @group gapic
 */
class RegionTargetHttpProxiesClientTest extends GeneratedTest
{
    /**
     * @return TransportInterface
     */
    private function createTransport($deserialize = null)
    {
        return new MockTransport($deserialize);
    }

    /**
     * @return CredentialsWrapper
     */
    private function createCredentials()
    {
        return $this->getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock();
    }

    /**
     * @return RegionTargetHttpProxiesClient
     */
    private function createClient(array $options = [])
    {
        $options += [
            'credentials' => $this->createCredentials(),
        ];
        return new RegionTargetHttpProxiesClient($options);
    }

    /**
     * @test
     */
    public function deleteTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new RegionOperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $client = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('customOperations/deleteTest');
        $incompleteOperation->setStatus(Status::RUNNING);
        $transport->addResponse($incompleteOperation);
        $completeOperation = new Operation();
        $completeOperation->setName('customOperations/deleteTest');
        $completeOperation->setStatus(Status::DONE);
        $operationsTransport->addResponse($completeOperation);
        // Mock request
        $project = 'project-309310695';
        $region = 'region-934795532';
        $targetHttpProxy = 'targetHttpProxy206872421';
        $response = $client->delete($project, $region, $targetHttpProxy);
        $this->assertFalse($response->isDone());
        $apiRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($apiRequests));
        $operationsRequestsEmpty = $operationsTransport->popReceivedCalls();
        $this->assertSame(0, count($operationsRequestsEmpty));
        $actualApiFuncCall = $apiRequests[0]->getFuncCall();
        $actualApiRequestObject = $apiRequests[0]->getRequestObject();
        $this->assertSame('/google.cloud.compute.v1.RegionTargetHttpProxies/Delete', $actualApiFuncCall);
        $actualValue = $actualApiRequestObject->getProject();
        $this->assertProtobufEquals($project, $actualValue);
        $actualValue = $actualApiRequestObject->getRegion();
        $this->assertProtobufEquals($region, $actualValue);
        $actualValue = $actualApiRequestObject->getTargetHttpProxy();
        $this->assertProtobufEquals($targetHttpProxy, $actualValue);
        $expectedOperationsRequestObject = new GetRegionOperationRequest();
        $expectedOperationsRequestObject->setOperation($completeOperation->getName());
        $expectedOperationsRequestObject->setProject($project);
        $expectedOperationsRequestObject->setRegion($region);
        $response->pollUntilComplete([
            'initialPollDelayMillis' => 1,
        ]);
        $this->assertTrue($response->isDone());
        $apiRequestsEmpty = $transport->popReceivedCalls();
        $this->assertSame(0, count($apiRequestsEmpty));
        $operationsRequests = $operationsTransport->popReceivedCalls();
        $this->assertSame(1, count($operationsRequests));
        $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall();
        $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject();
        $this->assertSame('/google.cloud.compute.v1.RegionOperations/Get', $actualOperationsFuncCall);
        $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function deleteExceptionTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new RegionOperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $client = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('customOperations/deleteExceptionTest');
        $incompleteOperation->setStatus(Status::RUNNING);
        $transport->addResponse($incompleteOperation);
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $operationsTransport->addResponse(null, $status);
        // Mock request
        $project = 'project-309310695';
        $region = 'region-934795532';
        $targetHttpProxy = 'targetHttpProxy206872421';
        $response = $client->delete($project, $region, $targetHttpProxy);
        $this->assertFalse($response->isDone());
        $this->assertNull($response->getResult());
        try {
            $response->pollUntilComplete([
                'initialPollDelayMillis' => 1,
            ]);
            // If the pollUntilComplete() method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stubs are exhausted
        $transport->popReceivedCalls();
        $operationsTransport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function getTest()
    {
        $transport = $this->createTransport();
        $client = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        // Mock response
        $creationTimestamp = 'creationTimestamp567396278';
        $description = 'description-1724546052';
        $fingerprint = 'fingerprint-1375934236';
        $id = 3355;
        $kind = 'kind3292052';
        $name = 'name3373707';
        $proxyBind = true;
        $region2 = 'region2-690338393';
        $selfLink = 'selfLink-1691268851';
        $urlMap = 'urlMap-169850228';
        $expectedResponse = new TargetHttpProxy();
        $expectedResponse->setCreationTimestamp($creationTimestamp);
        $expectedResponse->setDescription($description);
        $expectedResponse->setFingerprint($fingerprint);
        $expectedResponse->setId($id);
        $expectedResponse->setKind($kind);
        $expectedResponse->setName($name);
        $expectedResponse->setProxyBind($proxyBind);
        $expectedResponse->setRegion($region2);
        $expectedResponse->setSelfLink($selfLink);
        $expectedResponse->setUrlMap($urlMap);
        $transport->addResponse($expectedResponse);
        // Mock request
        $project = 'project-309310695';
        $region = 'region-934795532';
        $targetHttpProxy = 'targetHttpProxy206872421';
        $response = $client->get($project, $region, $targetHttpProxy);
        $this->assertEquals($expectedResponse, $response);
        $actualRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($actualRequests));
        $actualFuncCall = $actualRequests[0]->getFuncCall();
        $actualRequestObject = $actualRequests[0]->getRequestObject();
        $this->assertSame('/google.cloud.compute.v1.RegionTargetHttpProxies/Get', $actualFuncCall);
        $actualValue = $actualRequestObject->getProject();
        $this->assertProtobufEquals($project, $actualValue);
        $actualValue = $actualRequestObject->getRegion();
        $this->assertProtobufEquals($region, $actualValue);
        $actualValue = $actualRequestObject->getTargetHttpProxy();
        $this->assertProtobufEquals($targetHttpProxy, $actualValue);
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function getExceptionTest()
    {
        $transport = $this->createTransport();
        $client = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage  = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $transport->addResponse(null, $status);
        // Mock request
        $project = 'project-309310695';
        $region = 'region-934795532';
        $targetHttpProxy = 'targetHttpProxy206872421';
        try {
            $client->get($project, $region, $targetHttpProxy);
            // If the $client method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stub is exhausted
        $transport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function insertTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new RegionOperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $client = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('customOperations/insertTest');
        $incompleteOperation->setStatus(Status::RUNNING);
        $transport->addResponse($incompleteOperation);
        $completeOperation = new Operation();
        $completeOperation->setName('customOperations/insertTest');
        $completeOperation->setStatus(Status::DONE);
        $operationsTransport->addResponse($completeOperation);
        // Mock request
        $project = 'project-309310695';
        $region = 'region-934795532';
        $targetHttpProxyResource = new TargetHttpProxy();
        $response = $client->insert($project, $region, $targetHttpProxyResource);
        $this->assertFalse($response->isDone());
        $apiRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($apiRequests));
        $operationsRequestsEmpty = $operationsTransport->popReceivedCalls();
        $this->assertSame(0, count($operationsRequestsEmpty));
        $actualApiFuncCall = $apiRequests[0]->getFuncCall();
        $actualApiRequestObject = $apiRequests[0]->getRequestObject();
        $this->assertSame('/google.cloud.compute.v1.RegionTargetHttpProxies/Insert', $actualApiFuncCall);
        $actualValue = $actualApiRequestObject->getProject();
        $this->assertProtobufEquals($project, $actualValue);
        $actualValue = $actualApiRequestObject->getRegion();
        $this->assertProtobufEquals($region, $actualValue);
        $actualValue = $actualApiRequestObject->getTargetHttpProxyResource();
        $this->assertProtobufEquals($targetHttpProxyResource, $actualValue);
        $expectedOperationsRequestObject = new GetRegionOperationRequest();
        $expectedOperationsRequestObject->setOperation($completeOperation->getName());
        $expectedOperationsRequestObject->setProject($project);
        $expectedOperationsRequestObject->setRegion($region);
        $response->pollUntilComplete([
            'initialPollDelayMillis' => 1,
        ]);
        $this->assertTrue($response->isDone());
        $apiRequestsEmpty = $transport->popReceivedCalls();
        $this->assertSame(0, count($apiRequestsEmpty));
        $operationsRequests = $operationsTransport->popReceivedCalls();
        $this->assertSame(1, count($operationsRequests));
        $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall();
        $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject();
        $this->assertSame('/google.cloud.compute.v1.RegionOperations/Get', $actualOperationsFuncCall);
        $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function insertExceptionTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new RegionOperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $client = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('customOperations/insertExceptionTest');
        $incompleteOperation->setStatus(Status::RUNNING);
        $transport->addResponse($incompleteOperation);
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $operationsTransport->addResponse(null, $status);
        // Mock request
        $project = 'project-309310695';
        $region = 'region-934795532';
        $targetHttpProxyResource = new TargetHttpProxy();
        $response = $client->insert($project, $region, $targetHttpProxyResource);
        $this->assertFalse($response->isDone());
        $this->assertNull($response->getResult());
        try {
            $response->pollUntilComplete([
                'initialPollDelayMillis' => 1,
            ]);
            // If the pollUntilComplete() method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stubs are exhausted
        $transport->popReceivedCalls();
        $operationsTransport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function listTest()
    {
        $transport = $this->createTransport();
        $client = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        // Mock response
        $id = 'id3355';
        $kind = 'kind3292052';
        $nextPageToken = '';
        $selfLink = 'selfLink-1691268851';
        $itemsElement = new TargetHttpProxy();
        $items = [
            $itemsElement,
        ];
        $expectedResponse = new TargetHttpProxyList();
        $expectedResponse->setId($id);
        $expectedResponse->setKind($kind);
        $expectedResponse->setNextPageToken($nextPageToken);
        $expectedResponse->setSelfLink($selfLink);
        $expectedResponse->setItems($items);
        $transport->addResponse($expectedResponse);
        // Mock request
        $project = 'project-309310695';
        $region = 'region-934795532';
        $response = $client->list($project, $region);
        $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject());
        $resources = iterator_to_array($response->iterateAllElements());
        $this->assertSame(1, count($resources));
        $this->assertEquals($expectedResponse->getItems()[0], $resources[0]);
        $actualRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($actualRequests));
        $actualFuncCall = $actualRequests[0]->getFuncCall();
        $actualRequestObject = $actualRequests[0]->getRequestObject();
        $this->assertSame('/google.cloud.compute.v1.RegionTargetHttpProxies/List', $actualFuncCall);
        $actualValue = $actualRequestObject->getProject();
        $this->assertProtobufEquals($project, $actualValue);
        $actualValue = $actualRequestObject->getRegion();
        $this->assertProtobufEquals($region, $actualValue);
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function listExceptionTest()
    {
        $transport = $this->createTransport();
        $client = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage  = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $transport->addResponse(null, $status);
        // Mock request
        $project = 'project-309310695';
        $region = 'region-934795532';
        try {
            $client->list($project, $region);
            // If the $client method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stub is exhausted
        $transport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function setUrlMapTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new RegionOperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $client = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('customOperations/setUrlMapTest');
        $incompleteOperation->setStatus(Status::RUNNING);
        $transport->addResponse($incompleteOperation);
        $completeOperation = new Operation();
        $completeOperation->setName('customOperations/setUrlMapTest');
        $completeOperation->setStatus(Status::DONE);
        $operationsTransport->addResponse($completeOperation);
        // Mock request
        $project = 'project-309310695';
        $region = 'region-934795532';
        $targetHttpProxy = 'targetHttpProxy206872421';
        $urlMapReferenceResource = new UrlMapReference();
        $response = $client->setUrlMap($project, $region, $targetHttpProxy, $urlMapReferenceResource);
        $this->assertFalse($response->isDone());
        $apiRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($apiRequests));
        $operationsRequestsEmpty = $operationsTransport->popReceivedCalls();
        $this->assertSame(0, count($operationsRequestsEmpty));
        $actualApiFuncCall = $apiRequests[0]->getFuncCall();
        $actualApiRequestObject = $apiRequests[0]->getRequestObject();
        $this->assertSame('/google.cloud.compute.v1.RegionTargetHttpProxies/SetUrlMap', $actualApiFuncCall);
        $actualValue = $actualApiRequestObject->getProject();
        $this->assertProtobufEquals($project, $actualValue);
        $actualValue = $actualApiRequestObject->getRegion();
        $this->assertProtobufEquals($region, $actualValue);
        $actualValue = $actualApiRequestObject->getTargetHttpProxy();
        $this->assertProtobufEquals($targetHttpProxy, $actualValue);
        $actualValue = $actualApiRequestObject->getUrlMapReferenceResource();
        $this->assertProtobufEquals($urlMapReferenceResource, $actualValue);
        $expectedOperationsRequestObject = new GetRegionOperationRequest();
        $expectedOperationsRequestObject->setOperation($completeOperation->getName());
        $expectedOperationsRequestObject->setProject($project);
        $expectedOperationsRequestObject->setRegion($region);
        $response->pollUntilComplete([
            'initialPollDelayMillis' => 1,
        ]);
        $this->assertTrue($response->isDone());
        $apiRequestsEmpty = $transport->popReceivedCalls();
        $this->assertSame(0, count($apiRequestsEmpty));
        $operationsRequests = $operationsTransport->popReceivedCalls();
        $this->assertSame(1, count($operationsRequests));
        $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall();
        $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject();
        $this->assertSame('/google.cloud.compute.v1.RegionOperations/Get', $actualOperationsFuncCall);
        $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function setUrlMapExceptionTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new RegionOperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $client = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('customOperations/setUrlMapExceptionTest');
        $incompleteOperation->setStatus(Status::RUNNING);
        $transport->addResponse($incompleteOperation);
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $operationsTransport->addResponse(null, $status);
        // Mock request
        $project = 'project-309310695';
        $region = 'region-934795532';
        $targetHttpProxy = 'targetHttpProxy206872421';
        $urlMapReferenceResource = new UrlMapReference();
        $response = $client->setUrlMap($project, $region, $targetHttpProxy, $urlMapReferenceResource);
        $this->assertFalse($response->isDone());
        $this->assertNull($response->getResult());
        try {
            $response->pollUntilComplete([
                'initialPollDelayMillis' => 1,
            ]);
            // If the pollUntilComplete() method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stubs are exhausted
        $transport->popReceivedCalls();
        $operationsTransport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }
}


text:
test:
	nosetests --with-coverage --cover-package=faker_schema --cover-erase -v --cover-html

flake8:
	flake8 --max-line-length 99 faker_schema/ tests/

redpajama_set_name: RedPajamaGithub


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

package org.chromium.chrome.browser.download;

import androidx.annotation.VisibleForTesting;

import org.chromium.chrome.browser.download.items.OfflineContentAggregatorFactory;
import org.chromium.chrome.browser.preferences.ChromePreferenceKeys;
import org.chromium.chrome.browser.preferences.SharedPreferencesManager;
import org.chromium.components.offline_items_collection.ContentId;
import org.chromium.components.offline_items_collection.OfflineContentProvider;
import org.chromium.components.offline_items_collection.OfflineItem;
import org.chromium.components.offline_items_collection.UpdateDelta;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Keeps track of offline-available content addition and removal from Chrome. This information is
 * used to decide whether or not users should see messages in the UI about offline content
 * availability in Chrome.
 */
public class OfflineContentAvailabilityStatusProvider implements OfflineContentProvider.Observer {
    private static OfflineContentAvailabilityStatusProvider sInstance;

    // Keeps track of suggested content.
    private Set<ContentId> mSuggestedItems = new HashSet<>();
    // Keeps track of persistent content, i.e. non-transient content, including prefetch, downloads,
    // offline pages, etc. The idea is that this set will be empty iff Download Home would be empty.
    private Set<ContentId> mPersistentItems = new HashSet<>();

    /**
     * @return An {@link OfflineContentAvailabilityStatusProvider} instance singleton.  If one
     *         is not available this will create a new one.
     */
    public static OfflineContentAvailabilityStatusProvider getInstance() {
        if (sInstance == null) {
            sInstance = new OfflineContentAvailabilityStatusProvider();
            OfflineContentProvider provider = OfflineContentAggregatorFactory.get();
            provider.addObserver(sInstance);
            provider.getAllItems(sInstance::onItemsAdded);
        }
        return sInstance;
    }

    @VisibleForTesting
    OfflineContentAvailabilityStatusProvider() {}

    /**
     * @return Whether or not there is any suggested offline content available in Chrome.
     */
    public boolean isSuggestedContentAvailable() {
        return SharedPreferencesManager.getInstance().readBoolean(
                ChromePreferenceKeys.EXPLORE_OFFLINE_CONTENT_AVAILABILITY_STATUS, false);
    }

    /**
     * @return Whether or not there is any persistent (i.e. non-transient) offline content
     *         available in Chrome.
     */
    public boolean isPersistentContentAvailable() {
        return SharedPreferencesManager.getInstance().readBoolean(
                ChromePreferenceKeys.PERSISTENT_OFFLINE_CONTENT_AVAILABILITY_STATUS, false);
    }

    // OfflineContentProvider.Observer overrides

    @Override
    public void onItemsAdded(List<OfflineItem> items) {
        if (items.isEmpty()) return;

        for (OfflineItem item : items) {
            if (item.isSuggested) mSuggestedItems.add(item.id);
            if (!item.isTransient) mPersistentItems.add(item.id);
        }
        updateSharedPrefs();
    }

    @Override
    public void onItemRemoved(ContentId id) {
        boolean prefetch_removed = mSuggestedItems.remove(id);
        boolean persistent_removed = mPersistentItems.remove(id);
        if (prefetch_removed || persistent_removed) updateSharedPrefs();
    }

    @Override
    public void onItemUpdated(OfflineItem item, UpdateDelta updateDelta) {}

    private void updateSharedPrefs() {
        SharedPreferencesManager.getInstance().writeBoolean(
                ChromePreferenceKeys.EXPLORE_OFFLINE_CONTENT_AVAILABILITY_STATUS,
                !mSuggestedItems.isEmpty());
        SharedPreferencesManager.getInstance().writeBoolean(
                ChromePreferenceKeys.PERSISTENT_OFFLINE_CONTENT_AVAILABILITY_STATUS,
                !mPersistentItems.isEmpty());
    }
}


text:
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import { RechercheService } from './Recherche.service';

@Component({
	selector: 'menu',
	templateUrl: 'templates/menuRecherche.html',
	styleUrls: ['styles/menu.css']
	})

export class MenuRechercheComponent{
       titre = 'Recherche sur les produits';
       marque :string;
       type :string;
       nom :string;
       prixmin :number;
       prixmax :number;
       setMarque(value :string){
       		       this.marque=value;
       }
       setType(value :string){
       this.type=value;
	}
       setNom(value :string){
       this.nom=value;
       }
       setPrixMin(value :number){
       this.prixmin=value;
       }
       setPrixMax(value :number){
       this.prixmax=value;
       }

public items :any;
       public constructor(private recherche :RechercheService) {}

  ngOnInit() {

                    this.recherche.getJSON("paramRecherche")
		    .subscribe(res => this.items = res,
       				       err => console.error(err),
       				       	   () => console.log('done'));

}

}


text:
import modules.options_helper as opt_helper
from modules.file.file_helper import File
import sys

def main(options):
    # available config keys
    options_registry = ["path","content"]

    # verify config option provided match registry
    opt_helper.check_options(options, options_registry)

    path = options.get("path", False)
    content = options.get("content", False)

    if path:
        f = File(path)
        if f.get_ftype() == "absent":
            print "Creating new file at: " + path
            f.touch()
        else:
            print "Did not create. File aready exists: " + path

        if content and not f.is_in_file(content):
            print "Appending content [" + content + "] into begining of the file."
            f.append_to_file(content)
        else:
            print "Content [" + content + "] is in file already."
    else:
        sys.exit("Path is required.")

if __name__ == '__main__':
    main(options)


text:
<?php

namespace AlphaLabs\Pagination\Factory;

use AlphaLabs\Pagination\PaginatedCollection\PaginatedCollectionRequest;

/**
 * The default pagination factory provides the default pagination
 * (useful to provide a base pagination information if no pagination information is provided elsewhere).
 *
 * @package AlphaLabs\Pagination\Factory
 *
 * @author  Sylvain Mauduit <swop@swop.io>
 */
class DefaultPaginatedCollectionRequestFactory implements PaginatedCollectionRequestFactoryInterface
{
    /**
     * {@inheritDoc}
     */
    public function build()
    {
        $paginationInfo = new PaginatedCollectionRequest();
        $paginationInfo->setPage(1);

        return $paginationInfo;
    }
}


text:
//
//  ZKXibViewController.m
//  ZKDemo
//
//  Created by ZK on 16/2/26.
//  Copyright © 2016年 ZK. All rights reserved.
//

#import "ZKXibViewController.h"

@interface ZKXibViewController ()

@end

@implementation ZKXibViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
title: e-Riik, bs-WiFi
category: Opinions
tags:
- e-riik
- leping
- Rakvere
- Wi-Fi
---

Istusin Rakvere Bussijaamas ja tahtsin internetti pääseda. Siinkohal pean Tele2-te kiitma: ~4€ eest pakutakse piiramatu mahuga (aeglast) internetti läbi nutitelefoni. Ubuntul pole seadme äratundmise ja seadistamisega mingit probleemi ning Internett on arvutis olemas alati (st. kui levi on).

Bussijaamas leviv Wifi oli aga eriline. Vaatasin kasutamistingimusi ja -juhendit ja oli ikka jama küll, pool tundi ootamine ei olnud seda vaeva väärt.

Jah, ei saa lasta igasugustel pättidel, kaabakatel ja reidikatel takistamatult WiFi-tada, aga võrk võiks siiski olla kergemini ligipääsetav.

Allpool on "leping", mis mind võrgust välja saatis.

# Eesti Maaomavalitsuste Liidu avalik WiFi leviala.

Avaliku WiFi leviala kasutusleping.

* Eesti maaomavalitsuste Liidu avaliku WiFi kasutajatel ei ole lubatud:

* Saata e-mailiga massipostitusena reklaami ja muud EV seadusega vastuolus olevat materjali.

* Hankida omale illegaalsel teel juurdepääsu andmetele ja arvutitele.

* *Sisestada teisi isikuid laimavaid kommentaare internetiportaalidesse.*

* *Kasutadades P2P failivahetustarkvara või ftp-d laadida oma arvutisse või internetti
* autoriõigusega kaitstud tarkvara, filme ja muusikat.*

* Tehniline info:

* *Teie ID kaardiga audentitud* internetisessioon aegub 60 min pärast.

* Väljasaadetav e-mail on suunatud mail.neti.ee serverisse.

* Veebibrauseri tarkvaral tuleb *lubada avada hüpikaknad*

* Probleemide korral tuleb avalehele saamiseks *välja lülitada IPv6 protokoll*

Kuidas paremini teha? Registreerimislehel teavitada kasutajat, et ta on avalikus võrgus (viidata inimkeeles kirjutatud artiklitele turvalisusest avatud WiFi-s), öelda talle lühidalt, millest hoiduda, teavitada, et tegevus logitakse ning lubada võrku kasutama peale "OK" nupu vajutust. That's it.


text:
package com.bootcwenao.bigdataserver.hbase.controller;

import com.bootcwenao.bigdataserver.hbase.domain.pojo.UserInfo;
import com.bootcwenao.bigdataserver.hbase.service.HbaseAccountInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @author cwenao
 * @version $Id HbaseAccountController.java, v 0.1 2017-02-21 22:20 cwenao Exp $$
 */
@Controller
public class HbaseAccountController {

    private final static String TABLE_NAME = "user";

    private final static String FAMILY_INFO = "info";

    @Autowired
    private HbaseAccountInfoService hbaseAccountInfoServiceImpl;
    @RequestMapping(value = "/bigdata/find")
    public String findUserInfoByName(String name, ModelMap modelMap) {
        UserInfo userInfo = hbaseAccountInfoServiceImpl.findUserInfoByEntity(TABLE_NAME, FAMILY_INFO,
                "1", new UserInfo());

        modelMap.addAttribute("userInfo", userInfo);

        return "hbase/hbasetest";

        /*List<UserInfo> list = hbaseAccountInfoServiceImpl.findAll(TABLE_NAME, FAMILY_INFO);*/

    }
}


text:
function call_user_method_array(method, obj, params) {
  // http://kevin.vanzonneveld.net
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // +   input by: dnukem
  // +   improved by: Brett Zamir (http://brett-zamir.me)
  // -    depends on: Exception
  // %        note 1: Deprecated in PHP
  // *     example 1: call_user_method_array('alert', this.window, ['Hello!']);
  // *     returns 1: 'Hello!'
  // *     example 1: call_user_method_array([this.window, 'alert'], ['Hello!']);
  // *     returns 1: 'Hello!'

  var func, object = obj, methodName = method;
  if (method && typeof method === 'object' && method.length) {
    params = obj;
    object = method[0];
    object = typeof object === 'string' ? this.window[object] : object;
    methodName = method[1];
  }
  func = object[methodName];

  if (typeof func !== 'function') {
    throw new this.Exception(func + ' is not a valid method');
  }

  return func.apply(object, params);
}


text:
//
//  ========================================================================
//  Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.server.session;

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import junit.framework.Assert;

import org.eclipse.jetty.client.Address;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpDestination;
import org.eclipse.jetty.http.HttpCookie;
import org.eclipse.jetty.http.HttpMethods;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.log.Log;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * AbstractNewSessionTest
 */
public abstract class AbstractSessionCookieTest
{
    public abstract AbstractTestServer createServer(int port, int max, int scavenge);

    public void pause(int scavenge)
    {
        try
        {
            Thread.sleep(scavenge * 2500L);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    @Test
    @Ignore("failing because an http cookie with null value is coming over as \"null\"")
    public void testSessionCookie() throws Exception
    {
        String contextPath = "";
        String servletMapping = "/server";
        int scavengePeriod = 3;
        AbstractTestServer server = createServer(0, 1, scavengePeriod);
        ServletContextHandler context = server.addContext(contextPath);
        context.addServlet(TestServlet.class, servletMapping);
        server.start();
        int port=server.getPort();
        try
        {
            HttpClient client = new HttpClient();
            client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
            client.start();
            try
            {
                ContentExchange exchange = new ContentExchange(true);
                exchange.setMethod(HttpMethods.GET);
                exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=create");
                client.send(exchange);
                exchange.waitForDone();
                assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
                String sessionCookie = exchange.getResponseFields().getStringField("Set-Cookie");
                assertTrue(sessionCookie != null);
                // Mangle the cookie, replacing Path with $Path, etc.
                //sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");

                // Let's wait for the scavenger to run, waiting 2.5 times the scavenger period
                //pause(scavengePeriod);

                exchange = new ContentExchange(true);
                exchange.setMethod(HttpMethods.GET);
                exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=check-cookie");
                exchange.getRequestFields().add("Cookie", sessionCookie);
                client.send(exchange);
                exchange.waitForDone();
                assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());

                exchange = new ContentExchange(true);
                exchange.setMethod(HttpMethods.GET);
                exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=null-cookie");
                //exchange.getRequestFields().add("Cookie", "null");
                HttpDestination dest = client.getDestination(new Address("localhost",port),false);

                dest.addCookie(new HttpCookie("Cookie",null));

                client.send(exchange);
                exchange.waitForDone();
                assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
            }
            finally
            {
                client.stop();
            }
        }
        finally
        {
            server.stop();
        }

    }
    public static class TestServlet extends HttpServlet
    {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        {
            String action = request.getParameter("action");
            if ("create".equals(action))
            {
                HttpSession session = request.getSession(true);
                assertTrue(session.isNew());
            }
            else if ("check-cookie".equals(action))
            {
                HttpSession session = request.getSession(false);

                assertTrue(session != null);

                //request.getSession(true);
            }
            else if ("null-cookie".equals(action))
            {
                HttpSession session = request.getSession(false);

                assertEquals(1, request.getCookies().length);

                Assert.assertFalse("null".equals(request.getCookies()[0].getValue()));

                assertTrue(session == null);

            }
            else
            {
                assertTrue(false);
            }
        }
    }
}


text:
<?php

namespace Magento\Sales\Model\Rss;

use Magento\TestFramework\Helper\ObjectManager as ObjectManagerHelper;

/**
 * Class OrderStatusTest
 * @package Magento\Sales\Model\Rss
 */
class OrderStatusTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Sales\Model\Rss\OrderStatus
     */
    protected $model;

    /**
     * @var ObjectManagerHelper
     */
    protected $objectManagerHelper;

    /**
     * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $objectManager;

    /**
     * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $urlInterface;

    /**
     * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $requestInterface;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $orderStatusFactory;

    /**
     * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $timezoneInterface;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $orderFactory;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $scopeConfigInterface;

    /**
     * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $order;
    /**
     * @var array
     */
    protected $feedData = [
        'title' => 'Order # 100000001 Notification(s)',
        'link' => 'http://magento.com/sales/order/view/order_id/1',
        'description' => 'Order # 100000001 Notification(s)',
        'charset' => 'UTF-8',
        'entries' => [
            [
                'title' => 'Details for Order #100000001',
                'link' => 'http://magento.com/sales/order/view/order_id/1',
                'description' => '
Notified Date:
Comment: Some comment

',
            ],
            [
                'title' => 'Order #100000001 created at ',
                'link' => 'http://magento.com/sales/order/view/order_id/1',
                'description' => '
Current Status: Pending
Total: 15.00

'
            ],
        ],
    ];

    protected function setUp()
    {
        $this->objectManager = $this->getMock('Magento\Framework\ObjectManagerInterface');
        $this->urlInterface = $this->getMock('Magento\Framework\UrlInterface');
        $this->requestInterface = $this->getMock('Magento\Framework\App\RequestInterface');
        $this->orderStatusFactory = $this->getMockBuilder('Magento\Sales\Model\Resource\Order\Rss\OrderStatusFactory')
            ->setMethods(['create'])
            ->disableOriginalConstructor()
            ->getMock();
        $this->timezoneInterface = $this->getMock('Magento\Framework\Stdlib\DateTime\TimezoneInterface');
        $this->orderFactory = $this->getMock('Magento\Sales\Model\OrderFactory', ['create'], [], '', false);
        $this->scopeConfigInterface = $this->getMock('Magento\Framework\App\Config\ScopeConfigInterface');

        $this->order = $this->getMockBuilder('Magento\Sales\Model\Order')
            ->setMethods([
                '__sleep',
                '__wakeup',
                'getIncrementId',
                'getId',
                'getCustomerId',
                'load',
                'getStatusLabel',
                'formatPrice',
                'getGrandTotal',
            ])->disableOriginalConstructor()->getMock();
        $this->order->expects($this->any())->method('getId')->will($this->returnValue(1));
        $this->order->expects($this->any())->method('getIncrementId')->will($this->returnValue('100000001'));
        $this->order->expects($this->any())->method('getCustomerId')->will($this->returnValue(1));
        $this->order->expects($this->any())->method('getStatusLabel')->will($this->returnValue('Pending'));
        $this->order->expects($this->any())->method('formatPrice')->will($this->returnValue('15.00'));
        $this->order->expects($this->any())->method('getGrandTotal')->will($this->returnValue(15));
        $this->order->expects($this->any())->method('load')->with(1)->will($this->returnSelf());

        $this->objectManagerHelper = new ObjectManagerHelper($this);
        $this->model = $this->objectManagerHelper->getObject(
            'Magento\Sales\Model\Rss\OrderStatus',
            [
                'objectManager' => $this->objectManager,
                'urlBuilder' => $this->urlInterface,
                'request' => $this->requestInterface,
                'orderResourceFactory' => $this->orderStatusFactory,
                'localeDate' => $this->timezoneInterface,
                'orderFactory' => $this->orderFactory,
                'scopeConfig' => $this->scopeConfigInterface
            ]
        );
    }
    public function testGetData()
    {
        $this->orderFactory->expects($this->once())->method('create')->will($this->returnValue($this->order));
        $this->requestInterface->expects($this->any())->method('getParam')
            ->with('data')
            ->will($this->returnValue('eyJvcmRlcl9pZCI6MSwiaW5jcmVtZW50X2lkIjoiMTAwMDAwMDAxIiwiY3VzdG9tZXJfaWQiOjF9'));
        $resource = $this->getMockBuilder('\Magento\Sales\Model\Resource\Order\Rss\OrderStatus')
            ->setMethods(['getAllCommentCollection'])
            ->disableOriginalConstructor()
            ->getMock();
        $comment = [
            'entity_type_code' => 'order',
            'increment_id' => '100000001',
            'created_at' => '2014-10-09 18:25:50',
            'comment' => 'Some comment',
        ];
        $resource->expects($this->once())->method('getAllCommentCollection')->will($this->returnValue([$comment]));
        $this->orderStatusFactory->expects($this->once())->method('create')->will($this->returnValue($resource));
        $this->urlInterface->expects($this->any())->method('getUrl')
            ->with('sales/order/view', ['order_id' => 1])
            ->will($this->returnValue('http://magento.com/sales/order/view/order_id/1'));

        $this->assertEquals($this->feedData, $this->model->getRssData());
    }

    public function testIsAllowed()
    {
        $this->scopeConfigInterface->expects($this->once())->method('getValue')
            ->with('rss/order/status', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)
            ->will($this->returnValue(true));
        $this->assertTrue($this->model->isAllowed());
    }

    public function testGetCacheKey()
    {
        $this->requestInterface->expects($this->any())->method('getParam')
            ->with('data')
            ->will($this->returnValue('eyJvcmRlcl9pZCI6MSwiaW5jcmVtZW50X2lkIjoiMTAwMDAwMDAxIiwiY3VzdG9tZXJfaWQiOjF9'));
        $this->orderFactory->expects($this->once())->method('create')->will($this->returnValue($this->order));
        $this->assertEquals('rss_order_status_data_' . md5('11000000011'), $this->model->getCacheKey());
    }

    public function testGetCacheLifetime()
    {
        $this->assertEquals(600, $this->model->getCacheLifetime());
    }
}


text:
layout: post-index
title: Blog por Categorias
description: "Um qrquivo de posts por categoria."
comments: false
---

{% capture site_cats %}{% for cat in site.categories %}{{ cat | first }}{% unless forloop.last %},{% endunless %}{% endfor %}{% endcapture %}
{% assign cats_list = site_cats | split:',' | sort %}

  {% for item in (0..site.categories.size) %}{% unless forloop.last %}
    {% capture this_word %}{{ cats_list[item] | strip_newlines }}{% endcapture %}

{{ this_word }} {{ site.categories[this_word].size }}

  {% endunless %}{% endfor %}

{% for item in (0..site.categories.size) %}{% unless forloop.last %}
  {% capture this_word %}{{ cats_list[item] | strip_newlines }}{% endcapture %}

{{ this_word }}

    {% for post in site.categories[this_word] %}{% if post.title != null %}

{{ post.title }}

    {% endif %}{% endfor %}

{% endunless %}{% endfor %}


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', '..', 'lib'))
require "prawn"

file = "lazy_bounding_boxes.pdf"
Prawn::Document.generate(file, :skip_page_creation => true) do
  point = [bounds.right-50, bounds.bottom + 25]
  page_counter = lazy_bounding_box(point, :width => 50) do
    text "Page: #{page_count}"
  end

  10.times do
    start_new_page
    text "Some filler text for the page"
    page_counter.draw
  end
end


text:
```cpp
class exception : public std::exception;
```

This class is an extension of [`std::exception`](https://en.cppreference.com/w/cpp/error/exception) objects with a
member `id` for exception ids. It is used as the base class for all exceptions thrown by the `basic_json` class. This
class can hence be used as "wildcard" to catch exceptions, see example below.

```plantuml
std::exception <|-- basic_json::exception
basic_json::exception <|-- basic_json::parse_error
basic_json::exception <|-- basic_json::invalid_iterator
basic_json::exception <|-- basic_json::type_error
basic_json::exception <|-- basic_json::out_of_range
basic_json::exception <|-- basic_json::other_error

interface std::exception {}

class basic_json::exception #FFFF00 {
    + const int id
    + const char* what() const
}

class basic_json::parse_error {
    + const std::size_t byte
}
```

Subclasses:

- [`parse_error`](parse_error.md) for exceptions indicating a parse error
- [`invalid_iterator`](invalid_iterator.md) for exceptions indicating errors with iterators
- [`type_error`](type_error.md) for exceptions indicating executing a member function with a wrong type
- [`out_of_range`](out_of_range.md) for exceptions indicating access out of the defined range
- [`other_error`](other_error.md) for exceptions indicating other library errors

## Member functions

- **what** - returns explanatory string

## Member variables

- **id** - the id of the exception

## Notes

To have nothrow-copy-constructible exceptions, we internally use `std::runtime_error` which can cope with
arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual
constructor.

## Examples

??? example

    The following code shows how arbitrary library exceptions can be caught.

    ```cpp
    --8<-- "examples/exception.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/exception.output"
    ```

## See also

[List of exceptions](127.0.0.1:8000/home/exceptions/)

## Version history

- Since version 3.0.0.


text:
<?xml version="1.0" standalone=no>
<!-- A comment -->
<INPUT_FILE>
  <OUTPUT>
    <Output_type> DUMP </Output_type>
    <Checkpoint_frequency> 10000 </Checkpoint_frequency>
    <Output_directory> /scratch/pmaginot/Marshak_Results/ </Output_directory>
  </OUTPUT>

  <REGIONS>
    <Number_of_regions> 1 </Number_of_regions>
    <Number_of_materials> 1 </Number_of_materials>
    <Region> 0
      <N_cells> 20 </N_cells>
      <Left_bound> 0.0 </Left_bound>
      <Right_bound> 1.0  </Right_bound>
      <Spacing> Equal   </Spacing>
      <Material_number> 0 </Material_number>
    </Region>
  </REGIONS>

  <MATERIALS>
    <!-- CM_SH_KEV or  UNITY-->
    <Units> Unity </Units>
    <Material> 0
      <Scattering_opacity_type> Constant_xs
        <Constant_value> 0.0 </Constant_value>
      </Scattering_opacity_type>

      <Absorption_opacity_type> Rational
        <Multiplier> 1 </Multiplier>
        <Denominator_power> 3</Denominator_power>
        <Denominator_offset> 0</Denominator_offset>
      </Absorption_opacity_type>

      <Cv_type> Constant_cv
        <Cv_constant> 1 </Cv_constant>
      </Cv_type>

      <Radiation_fixed_source_type> NO_SOURCE   </Radiation_fixed_source_type>
      <Temperature_fixed_source_type> No_source </Temperature_fixed_source_type>
    </Material>
  </MATERIALS>

  <TIME>
    <Dt_min> 0.0005 </Dt_min>
    <Dt_max> 0.01 </Dt_max>
    <T_start> 0.0 </T_start>
    <T_end> 1.0 </T_end>
     <Time_solver> Alexander_2_2</Time_solver>
    <!--
      <Starting_method> Exponential </Starting_method>
    <Increase_factor> 1.25 </Increase_factor>
    -->

    <Starting_method> Exponential
      <Increase_factor> 1.1 </Increase_factor>
    </Starting_method>
  </TIME>

  <SPATIAL_DISCRETIZATION>
    <DFEM_degree> 2 </DFEM_degree>
    <Integration_type> Self_lumping </Integration_type>
    <DFEM_interpolation_point_type> Lobatto </DFEM_interpolation_point_type>
    <Opacity_treatment> SLXS
    </Opacity_treatment>
  </SPATIAL_DISCRETIZATION>

  <ANGULAR_DISCRETIZATION>
    <Number_of_angles> 2  </Number_of_angles>
    <Number_of_groups> 1 </Number_of_groups>
    <Quadrature_type> Gauss_angle </Quadrature_type>
    <Number_of_legendre_moments> 1 </Number_of_legendre_moments>
  </ANGULAR_DISCRETIZATION>

  <SOLVER>
    <!-- Valid options are FP_SWEEPS, FP_DSA, KRYLOV_SWEEPS, KRYLOV_DSA   -->
    <WG_solver_type> FP_DSA
      <Max_within_group_sweeps> 200 </Max_within_group_sweeps>
      <MIP_solve_options>
        <Z_mip> 2.0 </Z_mip>
      </MIP_solve_options>
    </WG_solver_type>

    <WG_tolerance> 1.0E-12 </WG_tolerance>
    <Thermal_tolerance> 1.0E-10 </Thermal_tolerance>
    <Damping_factor> 0.7 </Damping_factor>
    <Iteration_increase_factor> 2 </Iteration_increase_factor>
    <Iterations_before_damping> 40 </Iterations_before_damping>
    <Max_damping_resets> 5 </Max_damping_resets>
    <Max_thermal_iterations_per_stage> 10000 </Max_thermal_iterations_per_stage>
  </SOLVER>

  <BC_IC>
   <Temperature_ic_type> Constant_Temperature_Ic
    <Region> 0
      <Material_temperature> 0.05623413251903 </Material_temperature>
    </Region>
   </Temperature_ic_type>

   <Radiation_ic_type> PLanckian_IC
    <Region> 0
      <Radiation_temperature> 0.05623413251903 </Radiation_temperature>
    </Region>
   </Radiation_ic_type>

   <!-- Valid options are INCIDENT_BC, VACUUM_BC, REFLECTIVE_BC   -->
   <Left_radiation_bc_type> Incident_BC
    <BC_value_type> INCIDENT_CURRENT </BC_value_type>
    <BC_angle_dependence> BC_ISOTROPIC </BC_angle_dependence>
    <BC_time_dependence> BC_CONSTANT </BC_time_dependence>
    <BC_value> 1.0 </BC_value>
   </Left_radiation_bc_type>

   <!-- Valid options are PLANCKIAN_BC, VACUUM   -->
   <Right_radiation_bc_type> Vacuum_BC </Right_radiation_bc_type>

  </BC_IC>

</INPUT_FILE>


text:
namespace app {
namespace Uno {
namespace Content {
namespace Models {

::uEnumType* PsgReaderInternal_PsgSplineType__typeof();

}}}}

#endif


text:
package org.apache.rocketmq.replicator;

import io.openmessaging.KeyValue;
import io.openmessaging.connector.api.Task;
import io.openmessaging.connector.api.source.SourceConnector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.TopicConfig;
import org.apache.rocketmq.common.protocol.body.TopicList;
import org.apache.rocketmq.common.protocol.route.BrokerData;
import org.apache.rocketmq.common.protocol.route.QueueData;
import org.apache.rocketmq.common.protocol.route.TopicRouteData;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.replicator.common.ConstDefine;
import org.apache.rocketmq.replicator.common.Utils;
import org.apache.rocketmq.replicator.config.ConfigDefine;
import org.apache.rocketmq.replicator.config.DataType;
import org.apache.rocketmq.replicator.config.RmqConnectorConfig;
import org.apache.rocketmq.replicator.config.TaskDivideConfig;
import org.apache.rocketmq.replicator.config.TaskTopicInfo;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RmqSourceReplicator extends SourceConnector {

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

    private boolean syncDLQ = false;

    private boolean syncRETRY = false;

    private RmqConnectorConfig replicatorConfig;

    private Map<String, Set<TaskTopicInfo>> topicRouteMap;

    private volatile boolean configValid = false;

    private DefaultMQAdminExt srcMQAdminExt;
    private DefaultMQAdminExt targetMQAdminExt;

    private volatile boolean adminStarted;

    private ScheduledExecutorService executor;

    public RmqSourceReplicator() {
        topicRouteMap = new HashMap<>();
        replicatorConfig = new RmqConnectorConfig();
        executor = Executors.newSingleThreadScheduledExecutor(new BasicThreadFactory.Builder().namingPattern("RmqSourceReplicator-SourceWatcher-%d").daemon(true).build());
    }

    private synchronized void startMQAdminTools() {
        if (!configValid || adminStarted) {
            return;
        }
        RPCHook rpcHook = null;
        this.srcMQAdminExt = new DefaultMQAdminExt(rpcHook);
        this.srcMQAdminExt.setNamesrvAddr(this.replicatorConfig.getSrcNamesrvs());
        this.srcMQAdminExt.setAdminExtGroup(Utils.createGroupName(ConstDefine.REPLICATOR_ADMIN_PREFIX));
        this.srcMQAdminExt.setInstanceName(Utils.createInstanceName(this.replicatorConfig.getSrcNamesrvs()));

        this.targetMQAdminExt = new DefaultMQAdminExt(rpcHook);
        this.targetMQAdminExt.setNamesrvAddr(this.replicatorConfig.getTargetNamesrvs());
        this.targetMQAdminExt.setAdminExtGroup(Utils.createGroupName(ConstDefine.REPLICATOR_ADMIN_PREFIX));
        this.targetMQAdminExt.setInstanceName(Utils.createInstanceName(this.replicatorConfig.getTargetNamesrvs()));

        try {
            this.srcMQAdminExt.start();
            log.info("RocketMQ srcMQAdminExt started");

            this.targetMQAdminExt.start();
            log.info("RocketMQ targetMQAdminExt started");
        } catch (MQClientException e) {
            log.error("Replicator start failed for `srcMQAdminExt` exception.", e);
        }

        adminStarted = true;
    }

    @Override
    public String verifyAndSetConfig(KeyValue config) {

        // Check the need key.
        for (String requestKey : ConfigDefine.REQUEST_CONFIG) {
            if (!config.containsKey(requestKey)) {
                return "Request config key: " + requestKey;
            }
        }

        try {
            this.replicatorConfig.validate(config);
        } catch (IllegalArgumentException e) {
            return e.getMessage();
        }
        this.configValid = true;
        return "";
    }

    @Override
    public void start() {
        startMQAdminTools();
        buildRoute();
        startListner();
    }

    public void startListner() {
        executor.scheduleAtFixedRate(new Runnable() {

            boolean first = true;
            Map<String, Set<TaskTopicInfo>> origin = null;

            @Override public void run() {

                buildRoute();
                if (first) {
                    origin = new HashMap<>(topicRouteMap);
                    first = false;
                }
                if (!compare(origin, topicRouteMap)) {
                    context.requestTaskReconfiguration();
                    origin = new HashMap<>(topicRouteMap);
                }
            }
        }, replicatorConfig.getRefreshInterval(), replicatorConfig.getRefreshInterval(), TimeUnit.SECONDS);
    }

    public boolean compare(Map<String, Set<TaskTopicInfo>> origin, Map<String, Set<TaskTopicInfo>> updated) {
        if (origin.size() != updated.size()) {
            return false;
        }
        for (Map.Entry<String, Set<TaskTopicInfo>> entry : origin.entrySet()) {
            if (!updated.containsKey(entry.getKey())) {
                return false;
            }
            Set<TaskTopicInfo> originTasks = entry.getValue();
            Set<TaskTopicInfo> updateTasks = updated.get(entry.getKey());
            if (originTasks.size() != updateTasks.size()) {
                return false;
            }

            if (!originTasks.containsAll(updateTasks)) {
                return false;
            }
        }

        return true;
    }

    @Override
    public void stop() {
        executor.shutdown();
        this.srcMQAdminExt.shutdown();
        this.targetMQAdminExt.shutdown();
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public Class<? extends Task> taskClass() {

        return RmqSourceTask.class;
    }

    @Override
    public List<KeyValue> taskConfigs() {
        if (!configValid) {
            return new ArrayList<KeyValue>();
        }

        startMQAdminTools();

        buildRoute();

        TaskDivideConfig tdc = new TaskDivideConfig(
            this.replicatorConfig.getSrcNamesrvs(),
            this.replicatorConfig.getSrcCluster(),
            this.replicatorConfig.getStoreTopic(),
            this.replicatorConfig.getConverter(),
            DataType.COMMON_MESSAGE.ordinal(),
            this.replicatorConfig.getTaskParallelism()
        );
        return this.replicatorConfig.getTaskDivideStrategy().divide(this.topicRouteMap, tdc);
    }

    public void buildRoute() {
        List<Pattern> patterns = new ArrayList<Pattern>();
        String srcCluster = this.replicatorConfig.getSrcCluster();
        try {
            Set<String> targetTopicSet = fetchTargetTopics();
            for (String topic : this.replicatorConfig.getWhiteList()) {
                Pattern pattern = Pattern.compile(topic);
                patterns.add(pattern);
            }

            TopicList topics = srcMQAdminExt.fetchAllTopicList();
            for (String topic : topics.getTopicList()) {
                if ((syncRETRY && topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) ||
                    (syncDLQ && topic.startsWith(MixAll.DLQ_GROUP_TOPIC_PREFIX)) ||
                    !topic.equals(ConfigDefine.CONN_STORE_TOPIC)) {

                    for (Pattern pattern : patterns) {
                        Matcher matcher = pattern.matcher(topic);
                        if (matcher.matches()) {
                            String targetTopic = generateTargetTopic(topic);
                            if (!targetTopicSet.contains(targetTopic)) {
                                ensureTargetTopic(topic, targetTopic);
                            }

                            // different from BrokerData with cluster field, which can ensure the brokerData is from expected cluster.
                            // QueueData use brokerName as unique info on cluster of rocketmq. so when we want to get QueueData of
                            // expected cluster, we should get brokerNames of expected cluster, and then filter queueDatas.
                            List<BrokerData> brokerList = Utils.examineBrokerData(this.srcMQAdminExt, topic, srcCluster);
                            Set<String> brokerNameSet = new HashSet<String>();
                            for (BrokerData b : brokerList) {
                                brokerNameSet.add(b.getBrokerName());
                            }

                            TopicRouteData topicRouteData = srcMQAdminExt.examineTopicRouteInfo(topic);
                            if (!topicRouteMap.containsKey(topic)) {
                                topicRouteMap.put(topic, new HashSet<>(16));
                            }
                            for (QueueData qd : topicRouteData.getQueueDatas()) {
                                if (brokerNameSet.contains(qd.getBrokerName())) {
                                    for (int i = 0; i < qd.getReadQueueNums(); i++) {
                                        TaskTopicInfo taskTopicInfo = new TaskTopicInfo(topic, qd.getBrokerName(), i, targetTopic);
                                        topicRouteMap.get(topic).add(taskTopicInfo);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("Fetch topic list error.", e);
        }
    }

    public Map<String, Set<TaskTopicInfo>> getTopicRouteMap() {
        return this.topicRouteMap;
    }

    public Set<String> fetchTargetTopics() throws RemotingException, MQClientException, InterruptedException {
        String targetCluster = this.replicatorConfig.getTargetCluster();
        TopicList targetTopics = this.targetMQAdminExt.fetchTopicsByCLuster(targetCluster);
        return targetTopics.getTopicList();
    }

    /**
     * ensure target topic eixst. if target topic does not exist, ensureTopic will create target topic on target
     * cluster, with same TopicConfig but using target topic name. any exception will be caught and then throw
     * IllegalStateException.
     *
     * @param srcTopic
     * @param targetTopic
     * @throws RemotingException
     * @throws MQClientException
     * @throws InterruptedException
     */
    public void ensureTargetTopic(String srcTopic,
        String targetTopic) throws RemotingException, MQClientException, InterruptedException {
        String srcCluster = this.replicatorConfig.getSrcCluster();
        String targetCluster = this.replicatorConfig.getTargetCluster();

        List<BrokerData> brokerList = Utils.examineBrokerData(this.srcMQAdminExt, srcTopic, srcCluster);
        if (brokerList.size() == 0) {
            throw new IllegalStateException(String.format("no broker found for srcTopic: %s srcCluster: %s", srcTopic, srcCluster));
        }

        final TopicRouteData topicRouteData = this.srcMQAdminExt.examineTopicRouteInfo(srcTopic);
        final TopicConfig topicConfig = new TopicConfig();
        final List<QueueData> queueDatas = topicRouteData.getQueueDatas();
        QueueData queueData = queueDatas.get(0);
        topicConfig.setPerm(queueData.getPerm());
        topicConfig.setReadQueueNums(queueData.getReadQueueNums());
        topicConfig.setWriteQueueNums(queueData.getWriteQueueNums());
        topicConfig.setTopicSysFlag(queueData.getTopicSynFlag());
        topicConfig.setTopicName(targetTopic);
        Utils.createTopic(this.targetMQAdminExt, topicConfig, targetCluster);
    }

    public String generateTargetTopic(String topic) {
        String fmt = this.replicatorConfig.getRenamePattern();
        if (StringUtils.isNotEmpty(fmt)) {
            Map<String, String> params = new HashMap<String, String>();
            params.put("topic", topic);
            return StrSubstitutor.replace(fmt, params);
        }
        return topic;
    }
}


text:
Rails.application.routes.draw do

  devise_for :admins
  devise_for :users

  # for devise - must set root to something
  # root to: "persistent_rider_profiles#index"

  root to: "static_pages#home_page"

  get 'donors' => 'static_pages#donors'
  get '/site_is_not_active' => 'static_pages#site_is_not_active'

  # donations new nested under riders, and ALSO without nesting.
  # if nested under rider-- donate to rider
  # if no rider spec'd, donate to org

  resources :persistent_rider_profiles, :path => "riders" do
    post '/deactivate'=> 'persistent_rider_profiles#deactivate_current_ryr', as: :deactivate_current_ryr
    post '/reactivate'=> 'persistent_rider_profiles#reactivate_current_ryr', as: :reactivate_current_ryr

    resources :donations, only: [:new, :create, :index]
    resources :rider_year_registrations, only: :new
  end
  resources :donations, only: [:new], as: :donation_to_organization

  resources :donations, only: [:create, :edit, :update, :destroy]

  resources :mailing_addresses, except: [:show, :index]

  get 'donations/:id/new_donation_payment' => 'donations#new_donation_payment', as: :new_donation_payment
  post 'donations/:id/create_donation_payment' => 'donations#create_donation_payment', as: :create_donation_payment

  # resources :persistent_rider_profiles, :path => "riders"

  ## all the custom routes in new rider year registration - nested resources associated with new r_y_r

  get 'rider_year_registrations/agree_to_terms' => 'rider_year_registrations#new_agree_to_terms'
  post 'rider_year_registrations/agree_to_terms' => 'rider_year_registrations#create_agree_to_terms'

  get 'rider_year_registrations/persistent_rider_profile' => 'rider_year_registrations#new_persistent_rider_profile'
  post 'rider_year_registrations/persistent_rider_profile' => 'rider_year_registrations#create_persistent_rider_profile'

  get 'rider_year_registrations/mailing_address' => 'rider_year_registrations#new_mailing_address'
  post 'rider_year_registrations/mailing_address' => 'rider_year_registrations#create_mailing_address'

  get 'rider_year_registrations/pay_reg_fee' => 'rider_year_registrations#new_pay_reg_fee'
  post 'rider_year_registrations/pay_reg_fee' => 'rider_year_registrations#create_pay_reg_fee'

  resources :rider_year_registrations

  get 'admin' => 'admin/admins#index'

  namespace :admin do
    resources :users do
      resources :rider_year_registrations, only: [:new, :create]
      resources :mailing_addresses, only: [:new, :create]
    end
    resources :admins
    resources :ride_years do
      resources :donations, only: :index
      resources :rider_year_registrations, only: :index
      resources :custom_ride_options, only: [:new, :create, :index]
    end
    resources :custom_ride_options, only: [ :update, :destroy, :edit ]
    resources :donations
    resources :mailing_addresses, except: [:show, :index, :new, :create]

    resources :rider_year_registrations, except: [:new, :create] do
      post '/deactivate'=> 'rider_year_registrations#deactivate', as: :deactivate
      post '/reactivate'=> 'rider_year_registrations#reactivate', as: :reactivate

    end

    get 'donations/:id/new_donation_payment' => 'donations#new_donation_payment', as: :new_donation_payment

    post 'donations/:id/create_donation_payment' => 'donations#create_donation_payment', as: :create_donation_payment
  end

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  # root 'welcome#index'

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
end


text:
package org.mongodb.scala

import org.bson.BsonString

class SmokeTestISpec extends RequiresMongoDBISpec with FuturesSpec {

  "The Scala driver" should "handle common scenarios without error" in withDatabase(databaseName) {
    database =>
      val client = mongoClient()
      val document = Document("_id" -> 1)
      val updatedDocument = Document("_id" -> 1, "a" -> 1)

      client.listDatabaseNames().futureValue

      info("Creating a collection")
      val created = database.createCollection(collectionName).futureValue
      created should equal(Completed())
      created.toString() should equal("The operation completed successfully")

      info("Database names should include the new collection")
      val updatedNames = client.listDatabaseNames().futureValue
      updatedNames should contain(databaseName)

      info("The collection name should be in the collection names list")
      val collectionNames = database.listCollectionNames().futureValue
      collectionNames should contain(collectionName)

      info("The collection should be empty")
      val collection = database.getCollection(collectionName)
      collection.countDocuments().futureValue shouldBe 0

      info("find first should return null if no documents")
      collection.find().first().futureValue shouldBe null // scalastyle:ignore

      info("find should return an empty list")
      collection.find().futureValue shouldBe empty

      info("Insert a document")
      collection.insertOne(document).futureValue should equal(Completed())

      info("The count should be one")
      collection.countDocuments().futureValue shouldBe 1

      info("the find that document")
      collection.find().futureValue.head shouldBe document

      info("update that document")
      collection.updateOne(document, Document("$set" -> Document("a" -> 1))).futureValue.wasAcknowledged shouldBe true

      info("the find the updated document")
      collection.find().first().futureValue shouldBe updatedDocument

      info("aggregate the collection")
      collection.aggregate(List(Document("$match" -> Document("a" -> 1)))).futureValue.head shouldBe updatedDocument

      info("remove all documents")
      collection.deleteOne(Document()).futureValue.getDeletedCount() shouldBe 1

      info("The count is zero")
      collection.countDocuments().futureValue shouldBe 0

      info("create an index")
      collection.createIndex(Document("test" -> 1)).futureValue shouldBe "test_1"

      info("has the newly created index")
      val indexNames = collection.listIndexes().futureValue.map(doc => doc[BsonString]("name")).map(name => name.getValue)
      indexNames should contain("_id_")
      indexNames should contain("test_1")

      info("drop the index")
      collection.dropIndex("test_1").futureValue should equal(Completed())

      info("has a single index left '_id'")
      collection.listIndexes.futureValue.length shouldBe 1

      info("can rename the collection")
      val newCollectionName = "new" + collectionName.capitalize
      collection.renameCollection(MongoNamespace(databaseName, newCollectionName)).futureValue should equal(Completed())

      info("the new collection name is in the collection names list")
      database.listCollectionNames().futureValue should contain(newCollectionName)

      info("drop the new collection")
      val newCollection = database.getCollection(newCollectionName)
      newCollection.drop().futureValue should equal(Completed())

      info("there are no indexes")
      newCollection.listIndexes().futureValue.length shouldBe 0

      info("the new collection name is no longer in the collection names list")
      database.listCollectionNames().futureValue should not contain (newCollectionName)
  }
}


text:
package com.googlesource.gerrit.plugins.ci.server.schema;

import java.io.IOException;
import java.io.InputStream;

import com.googlesource.gerrit.plugins.ci.server.CiDb;

public abstract class CiBaseDataSourceType implements CiDataSourceType {

  private final String driver;

  protected CiBaseDataSourceType(String driver) {
    this.driver = driver;
  }

  @Override
  public final String getDriver() {
    return driver;
  }

  @Override
  public boolean usePool() {
    return true;
  }

  @Override
  public ScriptRunner getIndexScript() throws IOException {
    return getScriptRunner("index_generic.sql");
  }

  protected static final ScriptRunner getScriptRunner(String path) throws IOException {
    if (path == null) {
      return ScriptRunner.NOOP;
    }
    ScriptRunner runner;
    try (InputStream in = CiDb.class.getResourceAsStream(path)) {
      if (in == null) {
        throw new IllegalStateException("SQL script " + path + " not found");
      }
      runner = new ScriptRunner(path, in);
    }
    return runner;
  }
}


text:
using Castle.Core.Logging;
using SOURCE.Domaine;
using SOURCE.Domaine.Composite;
using SOURCE.Infrastructure.Constant;
using SOURCE.Infrastructure.Services.Depots;
using SOURCE.Infrastructure.Services.Caching;
using SOURCE.BackOffice.Web.ViewModels.Pages.Reference.Details;
using SOURCE.BackOffice.Web.ViewModels.Pages.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SOURCE.BackOffice.Web.ViewModels.ModelBuilders.Reference
{
    public class ReferenceModelBuilder : ModelBuilderBase, IReferenceModelBuilder
    {
        public ReferenceModelBuilder(ILogger logger, IDepotFactory depotFactory, ICaching cachingService)
            : base(logger, depotFactory, cachingService)
        { }

        public InfosGeneralesViewModel BuildInfosGeneralesViewModel(Context context, string type, long id, long options)
        {
            InfosGeneralesViewModel vm;

            if (id > 0)
            {
                var reference = _depotFactory.ReferenceOMDepot.GetReferenceOMByID(type, id, options).FirstOrDefault();
                vm = AutoMapper.Mapper.Map<ReferenceOMDto, InfosGeneralesViewModel>(reference);
                vm.Options = options;
                vm.TimeStamp = _depotFactory.GenericDepot.GetTimeStamp(context.User.ID, (long)VueEnum.ReferenceInformationsGenerales, id);
            }
            else {
                vm = new InfosGeneralesViewModel() { TypeOM = type, Options = options};
            }

            return vm;
        }
    }
}