text:
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.StoragePool.Models;

namespace Azure.ResourceManager.StoragePool
{
    internal partial class DiskPoolsRestOperations
    {
        private readonly TelemetryDetails _userAgent;
        private readonly HttpPipeline _pipeline;
        private readonly Uri _endpoint;
        private readonly string _apiVersion;

        /// <summary> Initializes a new instance of DiskPoolsRestOperations. </summary>
        /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
        /// <param name="applicationId"> The application id to use for user agent. </param>
        /// <param name="endpoint"> server parameter. </param>
        /// <param name="apiVersion"> Api Version. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception>
        public DiskPoolsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default)
        {
            _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline));
            _endpoint = endpoint ?? new Uri("https://management.azure.com");
            _apiVersion = apiVersion ?? "2021-08-01";
            _userAgent = new TelemetryDetails(GetType().Assembly, applicationId);
        }

        internal HttpMessage CreateListBySubscriptionRequest(string subscriptionId)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/providers/Microsoft.StoragePool/diskPools", false);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Gets a list of Disk Pools in a subscription. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<DiskPoolListResult>> ListBySubscriptionAsync(string subscriptionId, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));

            using var message = CreateListBySubscriptionRequest(subscriptionId);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        DiskPoolListResult value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = DiskPoolListResult.DeserializeDiskPoolListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Gets a list of Disk Pools in a subscription. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<DiskPoolListResult> ListBySubscription(string subscriptionId, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));

            using var message = CreateListBySubscriptionRequest(subscriptionId);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        DiskPoolListResult value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = DiskPoolListResult.DeserializeDiskPoolListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListByResourceGroupRequest(string subscriptionId, string resourceGroupName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.StoragePool/diskPools", false);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Gets a list of DiskPools in a resource group. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<DiskPoolListResult>> ListByResourceGroupAsync(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));

            using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        DiskPoolListResult value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = DiskPoolListResult.DeserializeDiskPoolListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Gets a list of DiskPools in a resource group. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<DiskPoolListResult> ListByResourceGroup(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));

            using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        DiskPoolListResult value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = DiskPoolListResult.DeserializeDiskPoolListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string diskPoolName, DiskPoolCreateOrUpdateContent content)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Put;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.StoragePool/diskPools/", false);
            uri.AppendPath(diskPoolName, true);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");
            var content0 = new Utf8JsonRequestContent();
            content0.JsonWriter.WriteObjectValue(content);
            request.Content = content0;
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Create or Update Disk pool. This create or update operation can take 15 minutes to complete. This is expected service behavior. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="content"> Request payload for Disk Pool create operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="diskPoolName"/> or <paramref name="content"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, string diskPoolName, DiskPoolCreateOrUpdateContent content, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));
            Argument.AssertNotNull(content, nameof(content));

            using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, diskPoolName, content);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                case 201:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Create or Update Disk pool. This create or update operation can take 15 minutes to complete. This is expected service behavior. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="content"> Request payload for Disk Pool create operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="diskPoolName"/> or <paramref name="content"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, string diskPoolName, DiskPoolCreateOrUpdateContent content, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));
            Argument.AssertNotNull(content, nameof(content));

            using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, diskPoolName, content);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                case 201:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string diskPoolName, DiskPoolPatch patch)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Patch;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.StoragePool/diskPools/", false);
            uri.AppendPath(diskPoolName, true);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");
            var content = new Utf8JsonRequestContent();
            content.JsonWriter.WriteObjectValue(patch);
            request.Content = content;
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Update a Disk pool. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="patch"> Request payload for Disk Pool update operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="diskPoolName"/> or <paramref name="patch"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response> UpdateAsync(string subscriptionId, string resourceGroupName, string diskPoolName, DiskPoolPatch patch, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));
            Argument.AssertNotNull(patch, nameof(patch));

            using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, diskPoolName, patch);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Update a Disk pool. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="patch"> Request payload for Disk Pool update operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="diskPoolName"/> or <paramref name="patch"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response Update(string subscriptionId, string resourceGroupName, string diskPoolName, DiskPoolPatch patch, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));
            Argument.AssertNotNull(patch, nameof(patch));

            using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, diskPoolName, patch);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string diskPoolName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Delete;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.StoragePool/diskPools/", false);
            uri.AppendPath(diskPoolName, true);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Delete a Disk pool; attached disks are not affected. This delete operation can take 10 minutes to complete. This is expected service behavior. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, diskPoolName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                case 204:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Delete a Disk pool; attached disks are not affected. This delete operation can take 10 minutes to complete. This is expected service behavior. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response Delete(string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, diskPoolName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                case 204:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string diskPoolName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.StoragePool/diskPools/", false);
            uri.AppendPath(diskPoolName, true);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Get a Disk pool. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<DiskPoolData>> GetAsync(string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateGetRequest(subscriptionId, resourceGroupName, diskPoolName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        DiskPoolData value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = DiskPoolData.DeserializeDiskPoolData(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                case 404:
                    return Response.FromValue((DiskPoolData)null, message.Response);
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Get a Disk pool. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<DiskPoolData> Get(string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateGetRequest(subscriptionId, resourceGroupName, diskPoolName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        DiskPoolData value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = DiskPoolData.DeserializeDiskPoolData(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                case 404:
                    return Response.FromValue((DiskPoolData)null, message.Response);
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListOutboundNetworkDependenciesEndpointsRequest(string subscriptionId, string resourceGroupName, string diskPoolName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.StoragePool/diskPools/", false);
            uri.AppendPath(diskPoolName, true);
            uri.AppendPath("/outboundNetworkDependenciesEndpoints", false);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Gets the network endpoints of all outbound dependencies of a Disk Pool. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<StoragePoolOutboundEnvironmentList>> ListOutboundNetworkDependenciesEndpointsAsync(string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateListOutboundNetworkDependenciesEndpointsRequest(subscriptionId, resourceGroupName, diskPoolName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        StoragePoolOutboundEnvironmentList value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = StoragePoolOutboundEnvironmentList.DeserializeStoragePoolOutboundEnvironmentList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Gets the network endpoints of all outbound dependencies of a Disk Pool. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<StoragePoolOutboundEnvironmentList> ListOutboundNetworkDependenciesEndpoints(string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateListOutboundNetworkDependenciesEndpointsRequest(subscriptionId, resourceGroupName, diskPoolName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        StoragePoolOutboundEnvironmentList value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = StoragePoolOutboundEnvironmentList.DeserializeStoragePoolOutboundEnvironmentList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateStartRequest(string subscriptionId, string resourceGroupName, string diskPoolName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Post;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.StoragePool/diskPools/", false);
            uri.AppendPath(diskPoolName, true);
            uri.AppendPath("/start", false);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> The operation to start a Disk Pool. This start operation can take 10 minutes to complete. This is expected service behavior. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response> StartAsync(string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateStartRequest(subscriptionId, resourceGroupName, diskPoolName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> The operation to start a Disk Pool. This start operation can take 10 minutes to complete. This is expected service behavior. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response Start(string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateStartRequest(subscriptionId, resourceGroupName, diskPoolName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateDeallocateRequest(string subscriptionId, string resourceGroupName, string diskPoolName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Post;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.StoragePool/diskPools/", false);
            uri.AppendPath(diskPoolName, true);
            uri.AppendPath("/deallocate", false);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Shuts down the Disk Pool and releases the compute resources. You are not billed for the compute resources that this Disk Pool uses. This operation can take 10 minutes to complete. This is expected service behavior. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response> DeallocateAsync(string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateDeallocateRequest(subscriptionId, resourceGroupName, diskPoolName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Shuts down the Disk Pool and releases the compute resources. You are not billed for the compute resources that this Disk Pool uses. This operation can take 10 minutes to complete. This is expected service behavior. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response Deallocate(string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateDeallocateRequest(subscriptionId, resourceGroupName, diskPoolName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateUpgradeRequest(string subscriptionId, string resourceGroupName, string diskPoolName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Post;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.StoragePool/diskPools/", false);
            uri.AppendPath(diskPoolName, true);
            uri.AppendPath("/upgrade", false);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Upgrade replaces the underlying virtual machine hosts one at a time. This operation can take 10-15 minutes to complete. This is expected service behavior. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response> UpgradeAsync(string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateUpgradeRequest(subscriptionId, resourceGroupName, diskPoolName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Upgrade replaces the underlying virtual machine hosts one at a time. This operation can take 10-15 minutes to complete. This is expected service behavior. </summary>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response Upgrade(string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateUpgradeRequest(subscriptionId, resourceGroupName, diskPoolName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListBySubscriptionNextPageRequest(string nextLink, string subscriptionId)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendRawNextLink(nextLink, false);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Gets a list of Disk Pools in a subscription. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<DiskPoolListResult>> ListBySubscriptionNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));

            using var message = CreateListBySubscriptionNextPageRequest(nextLink, subscriptionId);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        DiskPoolListResult value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = DiskPoolListResult.DeserializeDiskPoolListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Gets a list of Disk Pools in a subscription. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<DiskPoolListResult> ListBySubscriptionNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));

            using var message = CreateListBySubscriptionNextPageRequest(nextLink, subscriptionId);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        DiskPoolListResult value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = DiskPoolListResult.DeserializeDiskPoolListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListByResourceGroupNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendRawNextLink(nextLink, false);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Gets a list of DiskPools in a resource group. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<DiskPoolListResult>> ListByResourceGroupNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));

            using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        DiskPoolListResult value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = DiskPoolListResult.DeserializeDiskPoolListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Gets a list of DiskPools in a resource group. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<DiskPoolListResult> ListByResourceGroupNextPage(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));

            using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        DiskPoolListResult value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = DiskPoolListResult.DeserializeDiskPoolListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListOutboundNetworkDependenciesEndpointsNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string diskPoolName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendRawNextLink(nextLink, false);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Gets the network endpoints of all outbound dependencies of a Disk Pool. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<StoragePoolOutboundEnvironmentList>> ListOutboundNetworkDependenciesEndpointsNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateListOutboundNetworkDependenciesEndpointsNextPageRequest(nextLink, subscriptionId, resourceGroupName, diskPoolName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        StoragePoolOutboundEnvironmentList value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = StoragePoolOutboundEnvironmentList.DeserializeStoragePoolOutboundEnvironmentList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Gets the network endpoints of all outbound dependencies of a Disk Pool. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
        /// <param name="diskPoolName"> The name of the Disk Pool. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="diskPoolName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<StoragePoolOutboundEnvironmentList> ListOutboundNetworkDependenciesEndpointsNextPage(string nextLink, string subscriptionId, string resourceGroupName, string diskPoolName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(diskPoolName, nameof(diskPoolName));

            using var message = CreateListOutboundNetworkDependenciesEndpointsNextPageRequest(nextLink, subscriptionId, resourceGroupName, diskPoolName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        StoragePoolOutboundEnvironmentList value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = StoragePoolOutboundEnvironmentList.DeserializeStoragePoolOutboundEnvironmentList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }
    }
}


text:
package com.amazonaws.services.dynamodbv2.document.internal;

import java.util.Iterator;
import java.util.NoSuchElementException;

import com.amazonaws.services.dynamodbv2.document.Page;

/**
 * An internal iterator implementation for {@link PageBasedCollection}.
 *

 * NOTE: this internal class is marked as public since it has been incorrectly
 * exposed in the public method {@link PageBasedCollection#iterator()}, and it
 * will be changed to be package private in the next major version.
 *
 * @param <T>
 *            resource type
 * @param <R>
 *            low level result type
 */
public class IteratorSupport<T,R> implements Iterator<T> {
    /**
     * Used to iterate through the resource pages, dynamically making network
     * calls as needed.
     */
    final PageIterator<T,R> resourcePageIterator;
    /**
     * Used to iterate through a list of resources already retrieved.
     */
    private Iterator<T> localResourceIterator;
    private T resource;

    IteratorSupport(PageIterator<T,R> resourcePageIterator) {
        this.resourcePageIterator = resourcePageIterator;
    }

    @Override
    public boolean hasNext() {
        if (resource != null) {
            return true;
        }
        resource = nextResource();
        return (resource != null);
    }

    @Override
    public T next() {
        T rval = resource;
        if (rval == null) {
            rval = nextResource();
            if (rval == null) {
                throw new NoSuchElementException("No more elements");
            }
        } else {
            resource = null;
        }
        return rval;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException(
                "Collection is read-only");
    }

    private T nextResource() {
        while (true) {
            if (localResourceIterator != null && localResourceIterator.hasNext()) {
                return localResourceIterator.next();
            }
            if (!resourcePageIterator.hasNext()) {
                return null;
            }
            Page<T,R> resourcePage = resourcePageIterator.next();
            localResourceIterator = resourcePage.iterator();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
MachineName=CircleCI_GitHub
BuildType=Release
CTestCommand=ctest
DashboardDir=/usr/src/

cd ${DashboardDir}
${CTestCommand} -D Experimental -D SITE_CTEST_MODE:STRING=Experimental -D SITE_BUILD_TYPE:STRING=${BuildType} -S /usr/src/TubeTK/CMake/CircleCI/CircleCI_$1_Docker.cmake -V -VV -O CircleCI_$1_Docker.log


text:
package com.infoeducatie.app.activities;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;

import com.infoeducatie.app.R;
import com.infoeducatie.app.client.entities.News;
import com.infoeducatie.app.fragments.NewsFragment;
import com.infoeducatie.app.fragments.WebViewDialogFragment;
import com.infoeducatie.app.recyclerviews.news.NewsAdapter;

public class NewsActivity extends ActionBarActivity {

    private NewsFragment mNewsFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);

        mNewsFragment = (NewsFragment) getSupportFragmentManager().findFragmentById(R.id.activity_news_fragment);
        mNewsFragment.setNewsOnClickListener(new NewsAdapter.NewsAdapterListener() {
            @Override
            public void onClick(News news) {
                if (news != null) {
                    /* we clicked a news item */
                    new WebViewDialogFragment().setHtml(news.getBody()).show(getSupportFragmentManager(), "tag");
                }
            }

        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_news, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        return super.onOptionsItemSelected(item);
    }
}


text:
package org.apache.druid.segment.incremental;

import org.apache.druid.java.util.common.parsers.ParseException;

import javax.annotation.Nullable;

public class IncrementalIndexAddResult
{
  private final int rowCount;
  private final long bytesInMemory;

  @Nullable
  private final ParseException parseException;
  @Nullable
  private String reasonOfNotAdded;

  public IncrementalIndexAddResult(
      int rowCount,
      long bytesInMemory,
      @Nullable ParseException parseException,
      @Nullable String reasonOfNotAdded
  )
  {
    this.rowCount = rowCount;
    this.bytesInMemory = bytesInMemory;
    this.parseException = parseException;
    this.reasonOfNotAdded = reasonOfNotAdded;
  }

  public IncrementalIndexAddResult(
      int rowCount,
      long bytesInMemory,
      @Nullable ParseException parseException
  )
  {
    this(rowCount, bytesInMemory, parseException, null);
  }

  public int getRowCount()
  {
    return rowCount;
  }

  public long getBytesInMemory()
  {
    return bytesInMemory;
  }

  @Nullable
  public ParseException getParseException()
  {
    return parseException;
  }

  @Nullable
  public String getReasonOfNotAdded()
  {
    return reasonOfNotAdded;
  }
}


text:
/**
 * Created by Bart on 7-4-2017.
 */
import { Component, OnInit} from '@angular/core';
@Component({
  selector: 'app-home',
  templateUrl: './dashboard.component.html'
})
export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() { }
}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderIniteb4536a4207ab6de9450db06375341fa::getLoader();


text:
"""
Tests the code completion mode
"""
import functools
import pytest

from pyqode.qt import QtCore, QtGui
from pyqode.qt.QtTest import QTest

from pyqode.core.api import TextHelper
from pyqode.core import modes
from pyqode.core.modes.code_completion import SubsequenceCompleter
from ..helpers import server_path, wait_for_connected
from ..helpers import ensure_visible, ensure_connected

def get_mode(editor):
    return editor.modes.get(modes.CodeCompletionMode)

code = '''"""
Empty module
"""
string = 'a string'
'''

def ensure_empty(func):
    @functools.wraps(func)
    def wrapper(editor, *args, **kwds):
        editor.file._path = None
        editor.setPlainText(code, 'text/x-python', 'utf-8')
        return func(editor, *args, **kwds)
    return wrapper

@ensure_empty
@ensure_visible
@ensure_connected
def test_enabled(editor):
    mode = get_mode(editor)
    assert mode.enabled
    mode.enabled = False
    mode.enabled = True

@ensure_empty
@ensure_visible
@ensure_connected
def test_properties(editor):
    mode = get_mode(editor)
    mode.trigger_key = 'A'
    assert mode.trigger_key == 'A'
    mode.trigger_length = 3
    assert mode.trigger_length == 3
    mode.trigger_symbols = ['.', '->']
    assert len(mode.trigger_symbols) == 2
    assert '.' in mode.trigger_symbols
    assert '->' in mode.trigger_symbols
    mode.show_tooltips = False
    assert mode.show_tooltips is False
    mode.case_sensitive = True
    assert mode.case_sensitive is True
    mode.trigger_key = 1

@ensure_empty
@ensure_visible
@ensure_connected
def test_request_completion(editor):
    mode = get_mode(editor)
    QTest.qWait(1000)
    if editor.backend.running:
        editor.backend.stop()
    # starts the server after the request to test the retry on NotConnected
    # mechanism
    TextHelper(editor).goto_line(0)
    QTest.qWait(2000)
    mode.request_completion()
    editor.backend.start(server_path())
    QTest.qWait(1000)
    assert editor.backend.running is True
    # now this should work
    TextHelper(editor).goto_line(3)
    QTest.qWait(100)
    assert mode.request_completion() is True
    QTest.qWait(100)

@ensure_empty
@ensure_visible
@ensure_connected
def test_successive_requests(editor):
    mode = get_mode(editor)
    QTest.qWait(1000)
    TextHelper(editor).goto_line(3)
    assert editor.backend.running
    # only the first request should be accepted
    ret1 = mode.request_completion()
    ret2 = mode.request_completion()
    assert ret1 is True
    assert ret2 is True

@ensure_visible
@ensure_empty
@ensure_connected
def test_events(editor):
    assert editor.backend.running
    QTest.qWait(1000)
    TextHelper(editor).goto_line(3)
    QTest.keyPress(editor, QtCore.Qt.Key_Space, QtCore.Qt.ControlModifier)
    QTest.qWait(2000)
    QTest.keyPress(editor, QtCore.Qt.Key_Escape)
    QTest.qWait(500)
    QTest.keyPress(editor, 'm')
    QTest.keyPress(editor, 'o')
    QTest.qWait(1000)
    QTest.keyPress(editor, QtCore.Qt.Key_Escape)
    QTest.keyPress(editor, ' ')
    QTest.keyPress(editor, 'm')
    QTest.keyPress(editor, 'o')
    QTest.keyPress(editor, 'd')
    QTest.qWait(10)
    QTest.keyPress(editor, ' ')
    QTest.qWait(500)
    QTest.keyPress(editor, 'e')
    QTest.keyPress(editor, 'n')
    QTest.keyPress(editor, 'a')
    QTest.keyPress(editor, 'b')
    QTest.keyPress(editor, 'l')
    QTest.keyPress(editor, 'e')
    QTest.keyPress(editor, 'd')
    QTest.qWait(500)

    QTest.keyPress(editor, ' ')
    QTest.keyPress(editor, 'Q')
    QTest.keyPress(editor, 't')
    QTest.keyPress(editor, '.')
    QTest.qWait(500)

    QTest.keyPress(editor, 'Q')
    QTest.keyPress(editor, 't')
    QTest.qWait(500)
    QTest.keyPress(editor, QtCore.Qt.Key_Space, QtCore.Qt.ControlModifier)

@ensure_empty
@ensure_visible
@ensure_connected
def test_insert_completions(editor):
    assert editor.backend.running
    TextHelper(editor).goto_line(3)
    # check insert completions
    QTest.keyPress(editor, 'm')
    QTest.keyPress(editor, 'o')
    QTest.qWait(500)
    QTest.keyPress(editor, QtCore.Qt.Key_Return)

    # feature request #126: Key_Tab should select a completion
    QTest.keyPress(editor, QtCore.Qt.Key_Return)
    QTest.keyPress(editor, 'Q')
    QTest.keyPress(editor, 'T')
    QTest.keyPress(editor, 'e')
    QTest.keyPress(editor, 's')
    QTest.qWait(500)
    QTest.keyPress(editor, 't')

    QTest.qWait(100)

@ensure_empty
@ensure_connected
def test_show_completion_with_tooltip(editor):
    mode = get_mode(editor)
    mode.show_tooltips = True
    mode._show_completions([{'name': 'test', 'tooltip': 'test desc'}])
    mode._display_completion_tooltip('test')
    mode._display_completion_tooltip('spam')
    mode.show_tooltips = False
    mode._display_completion_tooltip('test')

@ensure_empty
@ensure_connected
def test_show_completion_with_icon(editor):
    mode = get_mode(editor)
    mode._show_completions([{'name': 'test',
                             'icon': ':/pyqode-icons/rc/edit-undo.png'}])

@pytest.mark.parametrize('case', [
    QtCore.Qt.CaseSensitive, QtCore.Qt.CaseInsensitive])
def test_subsequence_completer(case):
    completer = SubsequenceCompleter()
    words = ['actionA', 'actionB', 'setMySuperAction',
             'geTToolTip', 'setStatusTip', 'seTToolTip']
    model = QtGui.QStandardItemModel()
    for word in words:
        item = QtGui.QStandardItem()
        item.setData(word, QtCore.Qt.DisplayRole)
        model.appendRow(item)
    completer.setCaseSensitivity(case)
    completer.setModel(model)
    if case == QtCore.Qt.CaseInsensitive:
        completer.setCompletionPrefix('tip')
        completer.update_model()
        assert completer.completionCount() == 3
        completer.setCompletionPrefix('settip')
        completer.update_model()
        assert completer.completionCount() == 2
        completer.update_model()
        completer.setCompletionPrefix('action')
        completer.update_model()
        assert completer.completionCount() == 3
    else:
        completer.setCompletionPrefix('tip')
        completer.update_model()
        assert completer.completionCount() == 1  # setStatusTip
        completer.setCompletionPrefix('Tip')
        completer.update_model()
        assert completer.completionCount() == 3  # all word ending with Tip
        completer.setCompletionPrefix('setTip')
        completer.update_model()
        assert completer.completionCount() == 1  # setStatusTip
        completer.setCompletionPrefix('action')
        completer.update_model()
        assert completer.completionCount() == 2


text:
Catta a CSS Framework based on material design

### Current Version : v0.1


text:
namespace More.Collections.Generic
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Diagnostics.Contracts;

    /// <summary>
    /// Defines the behavior of a stack data structure.
    /// </summary>
    /// <typeparam name="T">The <see cref="Type">type</see> of elements in the stack.</typeparam>
    [SuppressMessage( "Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "This is an appropriate name." )]
    [SuppressMessage( "Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "A stack is a well-known collection type." )]
    [ContractClass( typeof( IStackContract<> ) )]
#pragma warning disable CA1010 // Collections should implement generic interface
    public interface IStack<T> : IReadOnlyCollection<T>, ICollection
#pragma warning restore CA1010 // Collections should implement generic interface
    {
        /// <summary>
        /// Returns the item at the top of the <see cref="IStack{T}" /> without removing it.
        /// </summary>
        /// <remarks>This method is similar to the <see cref="IStack{T}.Pop"/> method, but
        /// <see cref="IStack{T}.Peek"/> does not modify the <see cref="IStack{T}" />.</remarks>
        /// <returns>The item at the top of the <see cref="IStack{T}" />.</returns>
        T Peek();

        /// <summary>
        /// Removes and returns the item at the top of the <see cref="IStack{T}" />.
        /// </summary>
        /// <remarks>This method is similar to the <see cref="IStack{T}.Peek"/> method, but
        /// <see cref="IStack{T}.Peek"/> does not modify the <see cref="IStack{T}" />.</remarks>
        /// <returns>The item removed from the top of the <see cref="IStack{T}" />.</returns>
        T Pop();

        /// <summary>
        /// Adds an item to the top of the <see cref="IStack{T}" />.
        /// </summary>
        /// <param name="item">The item to push onto the <see cref="IStack{T}" />.</param>
        void Push( T item );

        /// <summary>
        /// Removes all items from the <see cref="IStack{T}" />.
        /// </summary>
        void Clear();

        /// <summary>
        /// Determines whether the <see cref="ObservableStack{T}"/> contains a specific value.
        /// </summary>
        /// <param name="item">The item to locate in the <see cref="IStack{T}" />. The value can be null for reference types.</param>
        /// <returns><see langkeyword="true">True</see> if <paramref name="item" /> is found in the <see cref="IStack{T}" />;
        /// otherwise, <see langkeyword="false">false</see>.</returns>
        bool Contains( T item );

        /// <summary>
        /// Copies the items of the <see cref="IStack{T}" /> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
        /// </summary>
        /// <param name="array">The one-dimensional <see cref="Array" /> that is the destination of the items copied from the <see cref="IStack{T}" />.
        /// The <see cref="Array" /> must have zero-based indexing.</param>
        /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param>
        void CopyTo( T[] array, int arrayIndex );
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2006 The Android Open Source Project

     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.
-->

<!-- Layout for a Preference in a PreferenceActivity. The
     Preference is able to place a specific widget for its particular
     type in the "widget_frame" layout. -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:gravity="center_vertical"
    android:paddingRight="?android:attr/scrollbarSize">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="24dip"
        android:layout_marginRight="4dip"
        android:layout_marginTop="4dip"
        android:layout_marginBottom="6dip"
        android:layout_weight="1">

        <TextView android:id="@+android:id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/my_text_light"
            android:ellipsize="marquee"
            android:fadingEdge="horizontal" />

        <TextView android:id="@+android:id/summary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@android:id/title"
            android:layout_alignLeft="@android:id/title"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="@color/my_text_light"
            android:maxLines="4" />

    </RelativeLayout>

    <!-- Preference should place its actual preference widget here. -->
    <LinearLayout android:id="@+android:id/widget_frame"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:orientation="vertical" />

</LinearLayout>


text: export * from './sysinfo.component';


text:
require 'test_helper'

class Api::V1::DependenciesControllerTest < ActionController::TestCase
  ## JSON ENDPOINTS:
  # NO GEMS:
  context "On GET to index --> with empty gems param --> JSON" do
    setup do
      get :index, params: { gems: "" }, format: "json"
    end

    should "return 200" do
      assert_response :success
    end

    should "return an empty body" do
      assert_empty response.body
    end
  end

  context "On GET to index --> with no gems param --> JSON" do
    setup do
      get :index, format: "json"
    end

    should "return 200" do
      assert_response :success
    end

    should "return an empty body" do
      assert_empty response.body
    end
  end

  # WITH GEMS:
  context "On GET to index --> with gems --> JSON" do
    setup do
      rubygem = create(:rubygem, name: "rails")
      create(:version, number: "1.0.0", rubygem_id: rubygem.id)
      get :index, params: { gems: "rails" }, format: "json"
    end

    should "return 200" do
      assert_response :success
    end

    should "return body" do
      result = [{
        'name'              => 'rails',
        'number'            => '1.0.0',
        'platform'          => 'ruby',
        'dependencies'      => []
      }]

      assert_equal result, JSON.load(response.body)
    end
  end

  # WITH COMPLEX GEMS:
  context "on GET to index --> with complex gems --> JSON" do
    setup do
      rubygem1 = create(:rubygem, name: "myrails")
      rubygem2 = create(:rubygem, name: "mybundler")
      create(:version, number: "1.0.0", rubygem_id: rubygem1.id)
      create(:version, number: "2.0.0", rubygem_id: rubygem2.id)
      create(:version, number: "3.0.0", rubygem_id: rubygem1.id)
      get :index, params: { gems: "myrails,mybundler" }, format: "json"
    end

    should "return 200" do
      assert_response :success
    end

    should "return surrogate key header" do
      assert_equal "dependencyapi gem/myrails gem/mybundler", @response.headers['Surrogate-Key']
    end

    should "return body" do
      result = [
        {
          'name'              => 'myrails',
          'number'            => '1.0.0',
          'platform'          => 'ruby',
          'dependencies'      => []
        },

        {
          'name'              => 'myrails',
          'number'            => '3.0.0',
          'platform'          => 'ruby',
          'dependencies'      => []
        },

        {
          'name'              => 'mybundler',
          'number'            => '2.0.0',
          'platform'          => 'ruby',
          'dependencies'      => []
        }
      ]

      assert_same_elements result, JSON.load(response.body)
    end
  end

  # TOO MANY GEMS:
  context "On GET to index --> with gems --> JSON" do
    setup do
      gems = Array.new(300) { create(:rubygem) }.join(',')
      get :index, params: { gems: gems }, format: "json"
    end

    should "return 422" do
      assert_response :unprocessable_entity
    end

    should "return an error body" do
      result = {
        "error" => "Too many gems! (use --full-index instead)",
        "code" => 422
      }

      assert_equal result, JSON.load(response.body)
    end
  end

  ## MARSHAL ENDPOINTS:
  # NO GEMS:
  context "On GET to index --> with no gems --> Marshal" do
    setup do
      rubygem = create(:rubygem, name: "testgem")
      @version = create(:version, number: "1.0.0", rubygem_id: rubygem.id)
      get :index, params: { gems: "" }, format: "marshal"
    end

    should "return 200" do
      assert_response :success
    end

    should "return an empty body" do
      assert_empty response.body
    end
  end

  # WITH GEMS:
  context "On GET to index --> with gems --> Marshal" do
    setup do
      rubygem = create(:rubygem, name: "testgem")
      create(:version, number: "1.0.0", rubygem_id: rubygem.id)
      get :index, params: { gems: "testgem" }, format: "marshal"
    end

    should "return 200" do
      assert_response :success
    end

    should "return body" do
      result = [{
        name:              'testgem',
        number:            '1.0.0',
        platform:          'ruby',
        dependencies:      []
      }]

      assert_equal result, Marshal.load(response.body)
    end
  end

  # TOO MANY GEMS:
  context "On GET to index --> with gems --> Marshal" do
    setup do
      gems = Array.new(300) { create(:rubygem) }.join(',')
      get :index, params: { gems: gems }, format: "marshal"
    end

    should "return 422" do
      assert_response :unprocessable_entity
    end

    should "return an error body" do
      assert_equal "Too many gems! (use --full-index instead)", response.body
    end
  end
end


text:
package org.drools.workbench.models.testscenarios.backend;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.drools.core.addon.ClassTypeResolver;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.workbench.models.testscenarios.backend.populators.FactPopulator;
import org.drools.workbench.models.testscenarios.backend.populators.FactPopulatorFactory;
import org.drools.workbench.models.testscenarios.shared.ActivateRuleFlowGroup;
import org.drools.workbench.models.testscenarios.shared.CallMethod;
import org.drools.workbench.models.testscenarios.shared.ExecutionTrace;
import org.drools.workbench.models.testscenarios.shared.Expectation;
import org.drools.workbench.models.testscenarios.shared.FactData;
import org.drools.workbench.models.testscenarios.shared.Fixture;
import org.drools.workbench.models.testscenarios.shared.RetractFact;
import org.drools.workbench.models.testscenarios.shared.Scenario;
import org.kie.api.runtime.KieSession;
import org.mvel2.MVEL;

/**
 * This actually runs the test scenarios.
 */
public class ScenarioRunnerImpl
        implements ScenarioRunner {

    private final KieSession ksession;
    private final int maximumAmountOfRuleFirings;
    private TestScenarioKSessionWrapper workingMemoryWrapper;
    private FactPopulatorFactory factPopulatorFactory;
    private FactPopulator factPopulator;

    /**
     * @param ksession A populated type resolved to be used to resolve the types in
     * the scenario.
     * @param maximumAmountOfRuleFirings Limit for amount of rules that can fire. To prevent infinite loops.
     * @throws ClassNotFoundException
     */
    public ScenarioRunnerImpl(final KieSession ksession,
                              final int maximumAmountOfRuleFirings) {
        this.ksession = ksession;
        this.maximumAmountOfRuleFirings = maximumAmountOfRuleFirings;
    }

    static Set<String> getImports(final Scenario scenario) {
        final Set<String> imports = new HashSet<String>();
        imports.addAll(scenario.getImports().getImportStrings());
        if (scenario.getPackageName() != null && !scenario.getPackageName().isEmpty()) {
            imports.add(scenario.getPackageName() + ".*");
        }
        return imports;
    }

    public void run(final Scenario scenario) throws Exception {

        // This looks safe!
        final InternalKnowledgeBase kieBase = (InternalKnowledgeBase) ksession.getKieBase();

        final Map<String, Object> populatedData = new HashMap<>();
        final Map<String, Object> globalData = new HashMap<>();

        final ClassLoader classloader2 = kieBase.getRootClassLoader();

        final ClassTypeResolver resolver = new ClassTypeResolver(getImports(scenario),
                                                                 classloader2);

        this.workingMemoryWrapper = new TestScenarioKSessionWrapper(ksession,
                                                                    resolver,
                                                                    populatedData,
                                                                    globalData,
                                                                    scenarioUsesTimeWalk(scenario));
        this.factPopulatorFactory = new FactPopulatorFactory(populatedData,
                                                             globalData,
                                                             resolver);
        this.factPopulator = new FactPopulator(ksession,
                                               populatedData);

        MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
        scenario.setLastRunResult(new Date());

        populateGlobals(scenario.getGlobals());

        applyFixtures(scenario.getFixtures(),
                      createScenarioSettings(scenario));
    }

    private boolean scenarioUsesTimeWalk(Scenario scenario) {
        for (Fixture fixture : scenario.getFixtures()) {
            if (fixture instanceof ExecutionTrace) {
                if (((ExecutionTrace) fixture).getScenarioSimulatedDate() != null) {
                    return true;
                }
            }
        }
        return false;
    }

    private ScenarioSettings createScenarioSettings(final Scenario scenario) {
        final ScenarioSettings scenarioSettings = new ScenarioSettings();
        scenarioSettings.setRuleList(scenario.getRules());
        scenarioSettings.setInclusive(scenario.isInclusive());
        scenarioSettings.setMaxRuleFirings(getMaxRuleFirings(scenario));
        return scenarioSettings;
    }

    private int getMaxRuleFirings(final Scenario scenario) {
        if (maximumAmountOfRuleFirings <= 0) {
            return scenario.getMaxRuleFirings();
        } else {
            return maximumAmountOfRuleFirings;
        }
    }

    private void applyFixtures(final List<Fixture> fixtures,
                               final ScenarioSettings scenarioSettings)
            throws ClassNotFoundException,
            InstantiationException,
            IllegalAccessException,
            InvocationTargetException,
            NoSuchMethodException, InvalidClockTypeException {

        for (Iterator<Fixture> iterator = fixtures.iterator(); iterator.hasNext(); ) {
            Fixture fixture = iterator.next();

            if (fixture instanceof FactData) {

                factPopulator.add(factPopulatorFactory.createFactPopulator((FactData) fixture));
            } else if (fixture instanceof RetractFact) {

                factPopulator.retractFact(((RetractFact) fixture).getName());
            } else if (fixture instanceof CallMethod) {

                workingMemoryWrapper.executeMethod((CallMethod) fixture);
            } else if (fixture instanceof ActivateRuleFlowGroup) {

                workingMemoryWrapper.activateRuleFlowGroup(((ActivateRuleFlowGroup) fixture).getName());
            } else if (fixture instanceof ExecutionTrace) {

                factPopulator.populate();

                workingMemoryWrapper.executeSubScenario((ExecutionTrace) fixture,
                                                        scenarioSettings);
            } else if (fixture instanceof Expectation) {

                factPopulator.populate();

                workingMemoryWrapper.verifyExpectation((Expectation) fixture);
            } else {
                throw new IllegalArgumentException("Not sure what to do with " + fixture);
            }
        }

        factPopulator.populate();
    }

    private void populateGlobals(final List<FactData> globals) throws Exception {

        for (final FactData fact : globals) {
            factPopulator.add(
                    factPopulatorFactory.createGlobalFactPopulator(fact));
        }

        factPopulator.populate();
    }
}


text:
<?php

namespace app\modules\store\models;

use alexBond\thumbler\Thumbler;
use app\modules\cms\components\TranslitBehavior;
use app\modules\cms\models\Image;
use Yii;
use yii\helpers\Url;

/**
 * This is the model class for table "{{%product_modificator_category}}".
 *
 * @property integer $id
 * @property integer $productId
 * @property Product $product
 * @property Category $category
 * @property ModificatorItem[] $items
 * @property Image $image
 * @property integer $categoryId
 * @property string $title
 * @property string $titleLink
 * @property string $alias
 * @property string $memo
 */
class ModificatorCategory extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%product_modificator_category}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['productId', 'categoryId'], 'integer'],
            [['title', 'titleLink', 'alias', 'memo'], 'string', 'max' => 128]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'productId' => Yii::t('app', 'Товар'),
            'categoryId' => Yii::t('app', 'Категория'),
            'title' => Yii::t('app', 'Название'),
            'titleLink' => Yii::t('app', 'Название ссылки'),
            'alias' => Yii::t('app', 'Url'),
            'memo' => Yii::t('app', 'Дополнительная информация'),
        ];
    }

    public  function beforeDelete()
    {
        ModificatorItem::deleteAll(['categoryId'=>$this->id]);
        return parent::beforeDelete();
    }

    public function behaviors()
    {
        return [
            'translit' => [
                'class' => TranslitBehavior::className(),
            ],
        ];
    }

    public function getProduct()
    {
        return $this->hasOne(Product::className(),['id'=>'productId']);
    }

    public function getCategory()
    {
        return $this->hasOne(Category::className(),['id'=>'categoryId']);
    }

    public function getItems()
    {
        return $this->hasMany(ModificatorItem::className(),['categoryId'=>'id']);
    }

    public function getImage()
    {
        return $this->hasOne(Image::className(),['primaryKey'=>'id'])
            ->andWhere(['model'=>self::className()]);
    }

    public function imageSrc($size,$method=Thumbler::METHOD_BOXED)
    {
        $image = $this->image;
        return $image ? $image->resize($size,$method) : 'http://placehold.it/'.$size;
    }

    public function getPath()
    {
        return Url::to(['/store/product/modificator','productAlias'=>$this->product->alias,'categoryAlias'=>$this->category->alias,'alias'=>$this->alias]);
    }
}


text:
package com.palantir.atlasdb.util;

import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.SlidingTimeWindowArrayReservoir;
import com.codahale.metrics.Snapshot;
import java.util.concurrent.TimeUnit;

public class SlidingWindowMeanGauge implements Gauge<Double> {
    private final Histogram histogram;

    public SlidingWindowMeanGauge() {
        histogram = new Histogram(new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS));
    }

    @Override
    public Double getValue() {
        return getSnapshot().getMean();
    }

    public void update(long entry) {
        histogram.update(entry);
    }

    // VisibleForTesting
    public Snapshot getSnapshot() {
        return histogram.getSnapshot();
    }
}


text:
import { SugarElement, SugarLocation, SugarNode, Traverse } from '@ephox/sugar';

const point = (type: string, element: SugarElement<Node>, x: number, y: number): void => {
  const touch = {
    identifier: Date.now(),
    target: element.dom,
    clientX: x,
    clientY: y,
    pageX: x,
    pageY: y,
    radiusX: 2.5,
    radiusY: 2.5,
    rotationAngle: 10,
    force: 0.5
  };

  // Adapted from https://stackoverflow.com/a/42447620/11275515
  if (typeof TouchEvent === 'function' && typeof Touch === 'function') {
    const touchAction = new Touch(touch);
    const ev: TouchEvent = new TouchEvent(type, {
      cancelable: true,
      bubbles: true,
      view: window,
      touches: [ touchAction ],
      targetTouches: [],
      changedTouches: [ touchAction ]
    });
    element.dom.dispatchEvent(ev);
  } else {
    // No native touch event support, so we need to simulate with a UIEvent
    const ev: any = new UIEvent(type, {
      cancelable: true,
      bubbles: true,
      view: window
    });
    // Patch in the touch properties
    ev.touches = [ touch ];
    ev.targetTouches = [];
    ev.changedTouches = [ touch ];
    element.dom.dispatchEvent(ev);
  }
};

const findElement = (element: SugarElement<Node>): SugarElement<Element> =>
  (SugarNode.isText(element) ? Traverse.parent(element).getOrDie() : element) as SugarElement<Element>;

const touch = (eventType: string) => (element: SugarElement<Node>): void => {
  const position = SugarLocation.absolute(findElement(element));
  point(eventType, element, position.left, position.top);
};

const touchAt = (eventType: string) => (dx: number, dy: number) => (element: SugarElement<Node>): void => {
  const position = SugarLocation.absolute(findElement(element));
  point(eventType, element, position.left + dx, position.top + dy);
};

const touchstart = touch('touchstart');
const touchstartAt = touchAt('touchstart');
const touchend = touch('touchend');
const touchendAt = touchAt('touchend');
const touchmove = touch('touchmove');
const touchmoveTo = touchAt('touchmove');

export {
  touchstart,
  touchstartAt,
  touchend,
  touchendAt,
  touchmove,
  touchmoveTo,
  point
};