text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.apimanagement.implementation;

import com.azure.core.annotation.BodyParam;
import com.azure.core.annotation.Delete;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.Head;
import com.azure.core.annotation.HeaderParam;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.Patch;
import com.azure.core.annotation.PathParam;
import com.azure.core.annotation.Put;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.resourcemanager.apimanagement.fluent.GroupsClient;
import com.azure.resourcemanager.apimanagement.fluent.models.GroupContractInner;
import com.azure.resourcemanager.apimanagement.models.GroupCollection;
import com.azure.resourcemanager.apimanagement.models.GroupCreateParameters;
import com.azure.resourcemanager.apimanagement.models.GroupUpdateParameters;
import com.azure.resourcemanager.apimanagement.models.GroupsCreateOrUpdateResponse;
import com.azure.resourcemanager.apimanagement.models.GroupsGetEntityTagResponse;
import com.azure.resourcemanager.apimanagement.models.GroupsGetResponse;
import com.azure.resourcemanager.apimanagement.models.GroupsUpdateResponse;
import reactor.core.publisher.Mono;

/** An instance of this class provides access to all the operations defined in GroupsClient. */
public final class GroupsClientImpl implements GroupsClient {
    /** The proxy service used to perform REST calls. */
    private final GroupsService service;

    /** The service client containing this operation class. */
    private final ApiManagementClientImpl client;

    /**
     * Initializes an instance of GroupsClientImpl.
     *
     * @param client the instance of the service client containing this operation class.
     */
    GroupsClientImpl(ApiManagementClientImpl client) {
        this.service = RestProxy.create(GroupsService.class, client.getHttpPipeline(), client.getSerializerAdapter());
        this.client = client;
    }

    /**
     * The interface defining all the services for ApiManagementClientGroups to be used by the proxy service to perform
     * REST calls.
     */
    @Host("{$host}")
    @ServiceInterface(name = "ApiManagementClientG")
    private interface GroupsService {
        @Headers({"Content-Type: application/json"})
        @Get(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement"
                + "/service/{serviceName}/groups")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<GroupCollection>> listByService(
            @HostParam("$host") String endpoint,
            @PathParam("resourceGroupName") String resourceGroupName,
            @PathParam("serviceName") String serviceName,
            @QueryParam("$filter") String filter,
            @QueryParam("$top") Integer top,
            @QueryParam("$skip") Integer skip,
            @QueryParam("api-version") String apiVersion,
            @PathParam("subscriptionId") String subscriptionId,
            @HeaderParam("Accept") String accept,
            Context context);

        @Headers({"Content-Type: application/json"})
        @Head(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement"
                + "/service/{serviceName}/groups/{groupId}")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<GroupsGetEntityTagResponse> getEntityTag(
            @HostParam("$host") String endpoint,
            @PathParam("resourceGroupName") String resourceGroupName,
            @PathParam("serviceName") String serviceName,
            @PathParam("groupId") String groupId,
            @QueryParam("api-version") String apiVersion,
            @PathParam("subscriptionId") String subscriptionId,
            @HeaderParam("Accept") String accept,
            Context context);

        @Headers({"Content-Type: application/json"})
        @Get(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement"
                + "/service/{serviceName}/groups/{groupId}")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<GroupsGetResponse> get(
            @HostParam("$host") String endpoint,
            @PathParam("resourceGroupName") String resourceGroupName,
            @PathParam("serviceName") String serviceName,
            @PathParam("groupId") String groupId,
            @QueryParam("api-version") String apiVersion,
            @PathParam("subscriptionId") String subscriptionId,
            @HeaderParam("Accept") String accept,
            Context context);

        @Headers({"Content-Type: application/json"})
        @Put(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement"
                + "/service/{serviceName}/groups/{groupId}")
        @ExpectedResponses({200, 201})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<GroupsCreateOrUpdateResponse> createOrUpdate(
            @HostParam("$host") String endpoint,
            @PathParam("resourceGroupName") String resourceGroupName,
            @PathParam("serviceName") String serviceName,
            @PathParam("groupId") String groupId,
            @HeaderParam("If-Match") String ifMatch,
            @QueryParam("api-version") String apiVersion,
            @PathParam("subscriptionId") String subscriptionId,
            @BodyParam("application/json") GroupCreateParameters parameters,
            @HeaderParam("Accept") String accept,
            Context context);

        @Headers({"Content-Type: application/json"})
        @Patch(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement"
                + "/service/{serviceName}/groups/{groupId}")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<GroupsUpdateResponse> update(
            @HostParam("$host") String endpoint,
            @PathParam("resourceGroupName") String resourceGroupName,
            @PathParam("serviceName") String serviceName,
            @PathParam("groupId") String groupId,
            @HeaderParam("If-Match") String ifMatch,
            @QueryParam("api-version") String apiVersion,
            @PathParam("subscriptionId") String subscriptionId,
            @BodyParam("application/json") GroupUpdateParameters parameters,
            @HeaderParam("Accept") String accept,
            Context context);

        @Headers({"Content-Type: application/json"})
        @Delete(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement"
                + "/service/{serviceName}/groups/{groupId}")
        @ExpectedResponses({200, 204})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<Void>> delete(
            @HostParam("$host") String endpoint,
            @PathParam("resourceGroupName") String resourceGroupName,
            @PathParam("serviceName") String serviceName,
            @PathParam("groupId") String groupId,
            @HeaderParam("If-Match") String ifMatch,
            @QueryParam("api-version") String apiVersion,
            @PathParam("subscriptionId") String subscriptionId,
            @HeaderParam("Accept") String accept,
            Context context);

        @Headers({"Content-Type: application/json"})
        @Get("{nextLink}")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<GroupCollection>> listByServiceNext(
            @PathParam(value = "nextLink", encoded = true) String nextLink,
            @HostParam("$host") String endpoint,
            @HeaderParam("Accept") String accept,
            Context context);
    }

    /**
     * Lists a collection of groups defined within a service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param filter | Field | Usage | Supported operators | Supported functions
     *     |
|-------------|-------------|-------------|-------------|
| name | filter | ge, le, eq,
     *     ne, gt, lt | substringof, contains, startswith, endswith |
| displayName | filter | ge, le, eq, ne,
     *     gt, lt | substringof, contains, startswith, endswith |
| description | filter | ge, le, eq, ne, gt,
     *     lt | substringof, contains, startswith, endswith |
| externalId | filter | eq | |
.
     * @param top Number of records to return.
     * @param skip Number of records to skip.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return paged Group list representation along with {@link PagedResponse} on successful completion of {@link
     *     Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<GroupContractInner>> listByServiceSinglePageAsync(
        String resourceGroupName, String serviceName, String filter, Integer top, Integer skip) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (serviceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .listByService(
                            this.client.getEndpoint(),
                            resourceGroupName,
                            serviceName,
                            filter,
                            top,
                            skip,
                            this.client.getApiVersion(),
                            this.client.getSubscriptionId(),
                            accept,
                            context))
            .<PagedResponse<GroupContractInner>>map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null))
            .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
    }

    /**
     * Lists a collection of groups defined within a service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param filter | Field | Usage | Supported operators | Supported functions
     *     |
|-------------|-------------|-------------|-------------|
| name | filter | ge, le, eq,
     *     ne, gt, lt | substringof, contains, startswith, endswith |
| displayName | filter | ge, le, eq, ne,
     *     gt, lt | substringof, contains, startswith, endswith |
| description | filter | ge, le, eq, ne, gt,
     *     lt | substringof, contains, startswith, endswith |
| externalId | filter | eq | |
.
     * @param top Number of records to return.
     * @param skip Number of records to skip.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return paged Group list representation along with {@link PagedResponse} on successful completion of {@link
     *     Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<GroupContractInner>> listByServiceSinglePageAsync(
        String resourceGroupName, String serviceName, String filter, Integer top, Integer skip, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (serviceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .listByService(
                this.client.getEndpoint(),
                resourceGroupName,
                serviceName,
                filter,
                top,
                skip,
                this.client.getApiVersion(),
                this.client.getSubscriptionId(),
                accept,
                context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null));
    }

    /**
     * Lists a collection of groups defined within a service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param filter | Field | Usage | Supported operators | Supported functions
     *     |
|-------------|-------------|-------------|-------------|
| name | filter | ge, le, eq,
     *     ne, gt, lt | substringof, contains, startswith, endswith |
| displayName | filter | ge, le, eq, ne,
     *     gt, lt | substringof, contains, startswith, endswith |
| description | filter | ge, le, eq, ne, gt,
     *     lt | substringof, contains, startswith, endswith |
| externalId | filter | eq | |
.
     * @param top Number of records to return.
     * @param skip Number of records to skip.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return paged Group list representation as paginated response with {@link PagedFlux}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<GroupContractInner> listByServiceAsync(
        String resourceGroupName, String serviceName, String filter, Integer top, Integer skip) {
        return new PagedFlux<>(
            () -> listByServiceSinglePageAsync(resourceGroupName, serviceName, filter, top, skip),
            nextLink -> listByServiceNextSinglePageAsync(nextLink));
    }

    /**
     * Lists a collection of groups defined within a service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return paged Group list representation as paginated response with {@link PagedFlux}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<GroupContractInner> listByServiceAsync(String resourceGroupName, String serviceName) {
        final String filter = null;
        final Integer top = null;
        final Integer skip = null;
        return new PagedFlux<>(
            () -> listByServiceSinglePageAsync(resourceGroupName, serviceName, filter, top, skip),
            nextLink -> listByServiceNextSinglePageAsync(nextLink));
    }

    /**
     * Lists a collection of groups defined within a service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param filter | Field | Usage | Supported operators | Supported functions
     *     |
|-------------|-------------|-------------|-------------|
| name | filter | ge, le, eq,
     *     ne, gt, lt | substringof, contains, startswith, endswith |
| displayName | filter | ge, le, eq, ne,
     *     gt, lt | substringof, contains, startswith, endswith |
| description | filter | ge, le, eq, ne, gt,
     *     lt | substringof, contains, startswith, endswith |
| externalId | filter | eq | |
.
     * @param top Number of records to return.
     * @param skip Number of records to skip.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return paged Group list representation as paginated response with {@link PagedFlux}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<GroupContractInner> listByServiceAsync(
        String resourceGroupName, String serviceName, String filter, Integer top, Integer skip, Context context) {
        return new PagedFlux<>(
            () -> listByServiceSinglePageAsync(resourceGroupName, serviceName, filter, top, skip, context),
            nextLink -> listByServiceNextSinglePageAsync(nextLink, context));
    }

    /**
     * Lists a collection of groups defined within a service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return paged Group list representation as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<GroupContractInner> listByService(String resourceGroupName, String serviceName) {
        final String filter = null;
        final Integer top = null;
        final Integer skip = null;
        return new PagedIterable<>(listByServiceAsync(resourceGroupName, serviceName, filter, top, skip));
    }

    /**
     * Lists a collection of groups defined within a service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param filter | Field | Usage | Supported operators | Supported functions
     *     |
|-------------|-------------|-------------|-------------|
| name | filter | ge, le, eq,
     *     ne, gt, lt | substringof, contains, startswith, endswith |
| displayName | filter | ge, le, eq, ne,
     *     gt, lt | substringof, contains, startswith, endswith |
| description | filter | ge, le, eq, ne, gt,
     *     lt | substringof, contains, startswith, endswith |
| externalId | filter | eq | |
.
     * @param top Number of records to return.
     * @param skip Number of records to skip.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return paged Group list representation as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<GroupContractInner> listByService(
        String resourceGroupName, String serviceName, String filter, Integer top, Integer skip, Context context) {
        return new PagedIterable<>(listByServiceAsync(resourceGroupName, serviceName, filter, top, skip, context));
    }

    /**
     * Gets the entity state (Etag) version of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the entity state (Etag) version of the group specified by its identifier on successful completion of
     *     {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<GroupsGetEntityTagResponse> getEntityTagWithResponseAsync(
        String resourceGroupName, String serviceName, String groupId) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (serviceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null."));
        }
        if (groupId == null) {
            return Mono.error(new IllegalArgumentException("Parameter groupId is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .getEntityTag(
                            this.client.getEndpoint(),
                            resourceGroupName,
                            serviceName,
                            groupId,
                            this.client.getApiVersion(),
                            this.client.getSubscriptionId(),
                            accept,
                            context))
            .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
    }

    /**
     * Gets the entity state (Etag) version of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the entity state (Etag) version of the group specified by its identifier on successful completion of
     *     {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<GroupsGetEntityTagResponse> getEntityTagWithResponseAsync(
        String resourceGroupName, String serviceName, String groupId, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (serviceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null."));
        }
        if (groupId == null) {
            return Mono.error(new IllegalArgumentException("Parameter groupId is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .getEntityTag(
                this.client.getEndpoint(),
                resourceGroupName,
                serviceName,
                groupId,
                this.client.getApiVersion(),
                this.client.getSubscriptionId(),
                accept,
                context);
    }

    /**
     * Gets the entity state (Etag) version of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the entity state (Etag) version of the group specified by its identifier on successful completion of
     *     {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Void> getEntityTagAsync(String resourceGroupName, String serviceName, String groupId) {
        return getEntityTagWithResponseAsync(resourceGroupName, serviceName, groupId)
            .flatMap((GroupsGetEntityTagResponse res) -> Mono.empty());
    }

    /**
     * Gets the entity state (Etag) version of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public void getEntityTag(String resourceGroupName, String serviceName, String groupId) {
        getEntityTagAsync(resourceGroupName, serviceName, groupId).block();
    }

    /**
     * Gets the entity state (Etag) version of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the entity state (Etag) version of the group specified by its identifier.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public GroupsGetEntityTagResponse getEntityTagWithResponse(
        String resourceGroupName, String serviceName, String groupId, Context context) {
        return getEntityTagWithResponseAsync(resourceGroupName, serviceName, groupId, context).block();
    }

    /**
     * Gets the details of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the details of the group specified by its identifier on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<GroupsGetResponse> getWithResponseAsync(String resourceGroupName, String serviceName, String groupId) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (serviceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null."));
        }
        if (groupId == null) {
            return Mono.error(new IllegalArgumentException("Parameter groupId is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .get(
                            this.client.getEndpoint(),
                            resourceGroupName,
                            serviceName,
                            groupId,
                            this.client.getApiVersion(),
                            this.client.getSubscriptionId(),
                            accept,
                            context))
            .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
    }

    /**
     * Gets the details of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the details of the group specified by its identifier on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<GroupsGetResponse> getWithResponseAsync(
        String resourceGroupName, String serviceName, String groupId, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (serviceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null."));
        }
        if (groupId == null) {
            return Mono.error(new IllegalArgumentException("Parameter groupId is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .get(
                this.client.getEndpoint(),
                resourceGroupName,
                serviceName,
                groupId,
                this.client.getApiVersion(),
                this.client.getSubscriptionId(),
                accept,
                context);
    }

    /**
     * Gets the details of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the details of the group specified by its identifier on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<GroupContractInner> getAsync(String resourceGroupName, String serviceName, String groupId) {
        return getWithResponseAsync(resourceGroupName, serviceName, groupId)
            .flatMap(
                (GroupsGetResponse res) -> {
                    if (res.getValue() != null) {
                        return Mono.just(res.getValue());
                    } else {
                        return Mono.empty();
                    }
                });
    }

    /**
     * Gets the details of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the details of the group specified by its identifier.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public GroupContractInner get(String resourceGroupName, String serviceName, String groupId) {
        return getAsync(resourceGroupName, serviceName, groupId).block();
    }

    /**
     * Gets the details of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the details of the group specified by its identifier.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public GroupsGetResponse getWithResponse(
        String resourceGroupName, String serviceName, String groupId, Context context) {
        return getWithResponseAsync(resourceGroupName, serviceName, groupId, context).block();
    }

    /**
     * Creates or Updates a group.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param parameters Create parameters.
     * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return contract details on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<GroupsCreateOrUpdateResponse> createOrUpdateWithResponseAsync(
        String resourceGroupName,
        String serviceName,
        String groupId,
        GroupCreateParameters parameters,
        String ifMatch) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (serviceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null."));
        }
        if (groupId == null) {
            return Mono.error(new IllegalArgumentException("Parameter groupId is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        if (parameters == null) {
            return Mono.error(new IllegalArgumentException("Parameter parameters is required and cannot be null."));
        } else {
            parameters.validate();
        }
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .createOrUpdate(
                            this.client.getEndpoint(),
                            resourceGroupName,
                            serviceName,
                            groupId,
                            ifMatch,
                            this.client.getApiVersion(),
                            this.client.getSubscriptionId(),
                            parameters,
                            accept,
                            context))
            .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
    }

    /**
     * Creates or Updates a group.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param parameters Create parameters.
     * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return contract details on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<GroupsCreateOrUpdateResponse> createOrUpdateWithResponseAsync(
        String resourceGroupName,
        String serviceName,
        String groupId,
        GroupCreateParameters parameters,
        String ifMatch,
        Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (serviceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null."));
        }
        if (groupId == null) {
            return Mono.error(new IllegalArgumentException("Parameter groupId is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        if (parameters == null) {
            return Mono.error(new IllegalArgumentException("Parameter parameters is required and cannot be null."));
        } else {
            parameters.validate();
        }
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .createOrUpdate(
                this.client.getEndpoint(),
                resourceGroupName,
                serviceName,
                groupId,
                ifMatch,
                this.client.getApiVersion(),
                this.client.getSubscriptionId(),
                parameters,
                accept,
                context);
    }

    /**
     * Creates or Updates a group.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param parameters Create parameters.
     * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return contract details on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<GroupContractInner> createOrUpdateAsync(
        String resourceGroupName,
        String serviceName,
        String groupId,
        GroupCreateParameters parameters,
        String ifMatch) {
        return createOrUpdateWithResponseAsync(resourceGroupName, serviceName, groupId, parameters, ifMatch)
            .flatMap(
                (GroupsCreateOrUpdateResponse res) -> {
                    if (res.getValue() != null) {
                        return Mono.just(res.getValue());
                    } else {
                        return Mono.empty();
                    }
                });
    }

    /**
     * Creates or Updates a group.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param parameters Create parameters.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return contract details on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<GroupContractInner> createOrUpdateAsync(
        String resourceGroupName, String serviceName, String groupId, GroupCreateParameters parameters) {
        final String ifMatch = null;
        return createOrUpdateWithResponseAsync(resourceGroupName, serviceName, groupId, parameters, ifMatch)
            .flatMap(
                (GroupsCreateOrUpdateResponse res) -> {
                    if (res.getValue() != null) {
                        return Mono.just(res.getValue());
                    } else {
                        return Mono.empty();
                    }
                });
    }

    /**
     * Creates or Updates a group.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param parameters Create parameters.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return contract details.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public GroupContractInner createOrUpdate(
        String resourceGroupName, String serviceName, String groupId, GroupCreateParameters parameters) {
        final String ifMatch = null;
        return createOrUpdateAsync(resourceGroupName, serviceName, groupId, parameters, ifMatch).block();
    }

    /**
     * Creates or Updates a group.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param parameters Create parameters.
     * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return contract details.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public GroupsCreateOrUpdateResponse createOrUpdateWithResponse(
        String resourceGroupName,
        String serviceName,
        String groupId,
        GroupCreateParameters parameters,
        String ifMatch,
        Context context) {
        return createOrUpdateWithResponseAsync(resourceGroupName, serviceName, groupId, parameters, ifMatch, context)
            .block();
    }

    /**
     * Updates the details of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET
     *     request or it should be * for unconditional update.
     * @param parameters Update parameters.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return contract details on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<GroupsUpdateResponse> updateWithResponseAsync(
        String resourceGroupName,
        String serviceName,
        String groupId,
        String ifMatch,
        GroupUpdateParameters parameters) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (serviceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null."));
        }
        if (groupId == null) {
            return Mono.error(new IllegalArgumentException("Parameter groupId is required and cannot be null."));
        }
        if (ifMatch == null) {
            return Mono.error(new IllegalArgumentException("Parameter ifMatch is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        if (parameters == null) {
            return Mono.error(new IllegalArgumentException("Parameter parameters is required and cannot be null."));
        } else {
            parameters.validate();
        }
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .update(
                            this.client.getEndpoint(),
                            resourceGroupName,
                            serviceName,
                            groupId,
                            ifMatch,
                            this.client.getApiVersion(),
                            this.client.getSubscriptionId(),
                            parameters,
                            accept,
                            context))
            .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
    }

    /**
     * Updates the details of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET
     *     request or it should be * for unconditional update.
     * @param parameters Update parameters.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return contract details on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<GroupsUpdateResponse> updateWithResponseAsync(
        String resourceGroupName,
        String serviceName,
        String groupId,
        String ifMatch,
        GroupUpdateParameters parameters,
        Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (serviceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null."));
        }
        if (groupId == null) {
            return Mono.error(new IllegalArgumentException("Parameter groupId is required and cannot be null."));
        }
        if (ifMatch == null) {
            return Mono.error(new IllegalArgumentException("Parameter ifMatch is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        if (parameters == null) {
            return Mono.error(new IllegalArgumentException("Parameter parameters is required and cannot be null."));
        } else {
            parameters.validate();
        }
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .update(
                this.client.getEndpoint(),
                resourceGroupName,
                serviceName,
                groupId,
                ifMatch,
                this.client.getApiVersion(),
                this.client.getSubscriptionId(),
                parameters,
                accept,
                context);
    }

    /**
     * Updates the details of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET
     *     request or it should be * for unconditional update.
     * @param parameters Update parameters.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return contract details on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<GroupContractInner> updateAsync(
        String resourceGroupName,
        String serviceName,
        String groupId,
        String ifMatch,
        GroupUpdateParameters parameters) {
        return updateWithResponseAsync(resourceGroupName, serviceName, groupId, ifMatch, parameters)
            .flatMap(
                (GroupsUpdateResponse res) -> {
                    if (res.getValue() != null) {
                        return Mono.just(res.getValue());
                    } else {
                        return Mono.empty();
                    }
                });
    }

    /**
     * Updates the details of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET
     *     request or it should be * for unconditional update.
     * @param parameters Update parameters.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return contract details.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public GroupContractInner update(
        String resourceGroupName,
        String serviceName,
        String groupId,
        String ifMatch,
        GroupUpdateParameters parameters) {
        return updateAsync(resourceGroupName, serviceName, groupId, ifMatch, parameters).block();
    }

    /**
     * Updates the details of the group specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET
     *     request or it should be * for unconditional update.
     * @param parameters Update parameters.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return contract details.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public GroupsUpdateResponse updateWithResponse(
        String resourceGroupName,
        String serviceName,
        String groupId,
        String ifMatch,
        GroupUpdateParameters parameters,
        Context context) {
        return updateWithResponseAsync(resourceGroupName, serviceName, groupId, ifMatch, parameters, context).block();
    }

    /**
     * Deletes specific group of the API Management service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET
     *     request or it should be * for unconditional update.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the {@link Response} on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<Void>> deleteWithResponseAsync(
        String resourceGroupName, String serviceName, String groupId, String ifMatch) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (serviceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null."));
        }
        if (groupId == null) {
            return Mono.error(new IllegalArgumentException("Parameter groupId is required and cannot be null."));
        }
        if (ifMatch == null) {
            return Mono.error(new IllegalArgumentException("Parameter ifMatch is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .delete(
                            this.client.getEndpoint(),
                            resourceGroupName,
                            serviceName,
                            groupId,
                            ifMatch,
                            this.client.getApiVersion(),
                            this.client.getSubscriptionId(),
                            accept,
                            context))
            .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
    }

    /**
     * Deletes specific group of the API Management service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET
     *     request or it should be * for unconditional update.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the {@link Response} on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<Void>> deleteWithResponseAsync(
        String resourceGroupName, String serviceName, String groupId, String ifMatch, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (serviceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null."));
        }
        if (groupId == null) {
            return Mono.error(new IllegalArgumentException("Parameter groupId is required and cannot be null."));
        }
        if (ifMatch == null) {
            return Mono.error(new IllegalArgumentException("Parameter ifMatch is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .delete(
                this.client.getEndpoint(),
                resourceGroupName,
                serviceName,
                groupId,
                ifMatch,
                this.client.getApiVersion(),
                this.client.getSubscriptionId(),
                accept,
                context);
    }

    /**
     * Deletes specific group of the API Management service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET
     *     request or it should be * for unconditional update.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return A {@link Mono} that completes when a successful response is received.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Void> deleteAsync(String resourceGroupName, String serviceName, String groupId, String ifMatch) {
        return deleteWithResponseAsync(resourceGroupName, serviceName, groupId, ifMatch)
            .flatMap((Response<Void> res) -> Mono.empty());
    }

    /**
     * Deletes specific group of the API Management service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET
     *     request or it should be * for unconditional update.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public void delete(String resourceGroupName, String serviceName, String groupId, String ifMatch) {
        deleteAsync(resourceGroupName, serviceName, groupId, ifMatch).block();
    }

    /**
     * Deletes specific group of the API Management service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param groupId Group identifier. Must be unique in the current API Management service instance.
     * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET
     *     request or it should be * for unconditional update.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Response<Void> deleteWithResponse(
        String resourceGroupName, String serviceName, String groupId, String ifMatch, Context context) {
        return deleteWithResponseAsync(resourceGroupName, serviceName, groupId, ifMatch, context).block();
    }

    /**
     * Get the next page of items.
     *
     * @param nextLink The nextLink parameter.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return paged Group list representation along with {@link PagedResponse} on successful completion of {@link
     *     Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<GroupContractInner>> listByServiceNextSinglePageAsync(String nextLink) {
        if (nextLink == null) {
            return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
        }
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        final String accept = "application/json";
        return FluxUtil
            .withContext(context -> service.listByServiceNext(nextLink, this.client.getEndpoint(), accept, context))
            .<PagedResponse<GroupContractInner>>map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null))
            .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
    }

    /**
     * Get the next page of items.
     *
     * @param nextLink The nextLink parameter.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return paged Group list representation along with {@link PagedResponse} on successful completion of {@link
     *     Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<GroupContractInner>> listByServiceNextSinglePageAsync(String nextLink, Context context) {
        if (nextLink == null) {
            return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
        }
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .listByServiceNext(nextLink, this.client.getEndpoint(), accept, context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null));
    }
}


text:
import java.util.*;
//import acm.util.*;
import java.io.*;
//import acm.program.*;

import acm.util.ErrorException;

public class HangmanLexicon {

	// This is the HangmanLexicon constructor
	//public HangmanLexicon() throws Exception {
	public HangmanLexicon() {
		//BufferedReader lex;
		try {
			//lex = new BufferedReader(new FileReader("HangmanLexicon.txt"));
			BufferedReader lex = new BufferedReader(new FileReader("HangmanLexicon.txt"));
			while (true) {
				String word = lex.readLine();
				if (word == null) break;
				list.add(word);
			}
			//int nullLength;
			lex.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new ErrorException(e);
			//println("File not found");
		}
	}

	/** Returns the number of words in the lexicon. */
	public int getWordCount() {
		//return 10;
		return list.size();
	}

	/** Returns the word at the specified index. */
	public String getWord(int index) {
		//		switch (index) {
		//		case 0: return "BUOY";
		//		case 1: return "COMPUTER";
		//		case 2: return "CONNOISSEUR";
		//		case 3: return "DEHYDRATE";
		//		case 4: return "FUZZY";
		//		case 5: return "HUBBUB";
		//		case 6: return "KEYHOLE";
		//		case 7: return "QUAGMIRE";
		//		case 8: return "SLITHER";
		//		case 9: return "ZIRCON";
		//		default: throw new ErrorException("getWord: Illegal index");
		//		}
		return list.get(index);
	}

	/* Instance variables */
	private ArrayList<String> list = new ArrayList<String>();
}

redpajama_set_name: RedPajamaGithub


text:
package fr.openwide.core.basicapp.core.test.service;

import org.springframework.stereotype.Service;

import fr.openwide.core.basicapp.core.business.notification.service.EmptyNotificationUrlBuilderServiceImpl;

/**
 * Implémentation bouche-trou, uniquement pour combler la dépendance.
 */
@Service("coreTestNotificationUrlBuilderService")
public class CoreTestNotificationUrlBuilderServiceImpl extends EmptyNotificationUrlBuilderServiceImpl {

}


text:
<module>
  <inherits name='com.google.gwt.core.Core'/>
  <inherits name='arez.dom.Dom'/>
  <inherits name='arez.ArezDev'/>

  <source path='' includes='NetworkStatusExample.java'/>
  <public path='public'/>

  <entry-point class='arez.dom.example.NetworkStatusExample'/>
</module>


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
C. S. Sargent, Pl. wilson. 1:6. 1911

#### Original name
null

### Remarks
null


text:
package edu.uwi.mona.mobileourvle.classes.models;

import android.text.Html;

import com.google.gson.annotations.SerializedName;
import com.orm.SugarRecord;
import com.orm.dsl.Ignore;

/**
 * @author Javon Davis
 *         Created by Javon Davis on 7/8/15.
 */
public class CourseForum extends SugarRecord<CourseForum> {

    public CourseForum()
    {

    }
    // since id is a reserved field in SugarRecord
    @SerializedName("id")
    int forumid;

    @SerializedName("course")
    String courseid;

    @SerializedName("name")
    String name;

    @SerializedName("intro")
    String intro;

    @SerializedName("completiondiscussions")
    int completiondiscussions;

    @SerializedName("completionreplies")
    int completionreplies;

    @SerializedName("completionposts")
    int completionposts;

    @SerializedName("cmid")
    int cmid;

    // Errors. Not to be stored in sql db.
    @Ignore
    @SerializedName("exception")
    String exception;

    @Ignore
    @SerializedName("errorcode")
    String errorcode;

    @Ignore
    @SerializedName("message")
    String message;

    @Ignore
    @SerializedName("debuginfo")
    String debuginfo;

    // Relational and other fields
    long siteid;
    String coursename;

    /**
     * Get coursename of the forum
     *
     * @return
     */
    public String getCoursename() {
        return coursename;
    }

    /**
     * Set coursename of the forum
     *
     * @param coursename
     */
    public void setCoursename(String coursename) {
        this.coursename = coursename;
    }

    /**
     * Get Forum id
     *
     * @return
     */
    public int getForumid() {
        return forumid;
    }

    /**
     * Get The forum type
     *
     * @return
     */
    public String getCourseid() {
        return courseid;
    }

    /**
     * Get Forum name
     *
     * @return
     */
    public String getName() {
        return name;
    }

    /**
     * Get Forum intro
     *
     * @return
     */
    public String getIntro() {
        return Html.fromHtml(intro).toString();
    }

    /**
     * Get Student must create discussions
     *
     * @return
     */
    public int getCompletiondiscussions() {
        return completiondiscussions;
    }

    /**
     * Get Student must post replies
     *
     * @return
     */
    public int getCompletionreplies() {
        return completionreplies;
    }

    /**
     * Get Student must post discussions or replies
     *
     * @return
     */
    public int getCompletionposts() {
        return completionposts;
    }

    /**
     * Get Course module id
     *
     * @return
     */
    public int getCmid() {
        return cmid;
    }

    /**
     * Exception occurred while retrieving
     *
     * @return
     */
    public String getException() {
        return exception;
    }

    /**
     * Errorcode of error occurred while retrieving
     *
     * @return
     */
    public String getErrorcode() {
        return errorcode;
    }

    /**
     * Message of error occurred while retrieving
     *
     * @return
     */
    public String getMessage() {
        return message;
    }

    /**
     * Debug info on the error occurred
     *
     * @return
     */
    public String getDebuginfo() {
        return debuginfo;
    }
}


text:
using MonoMac.Foundation;

namespace macdoc
{
	[Register ("AppleDocMergeWindowController")]
	partial class AppleDocMergeWindowController
	{
		[Outlet]
		MonoMac.AppKit.NSProgressIndicator ProgressWidget { get; set; }

		[Outlet]
		MonoMac.AppKit.NSTextField WizardText { get; set; }

		[Outlet]
		MonoMac.AppKit.NSButton WizardButton { get; set; }

		void ReleaseDesignerOutlets ()
		{
			if (ProgressWidget != null) {
				ProgressWidget.Dispose ();
				ProgressWidget = null;
			}

			if (WizardText != null) {
				WizardText.Dispose ();
				WizardText = null;
			}

			if (WizardButton != null) {
				WizardButton.Dispose ();
				WizardButton = null;
			}
		}
	}

	[Register ("AppleDocMergeWindow")]
	partial class AppleDocMergeWindow
	{

		void ReleaseDesignerOutlets ()
		{
		}
	}
}


text:
require 'fileutils'
require 'colorize'
require 'active_support'
require 'active_support/number_helper'

PATH = '/mnt/d/anime'
# PATH = '/mnt/g/anime'
# PATH = '/entertainment/tv'
OPTS = { encoding: 'UTF-8' }
SHOWS = {}
RESULTS = []

PARTITION_SIZE = 1300 * 1024 * 1024 * 1024
# PARTITION_SIZE = 1250 * 1024 * 1024 * 1024
# PARTITION_SIZE = 1400 * 1000 * 1000 * 1000
# PARTITION_SIZE = 1500 * 1024 * 1024 * 1024
# BUFFER_SIZE = 55 * 1024 * 1024 * 1024
BUFFER_SIZE = 50 * 1024 * 1024 * 1024
TRANSFER_SIZE = PARTITION_SIZE - BUFFER_SIZE
OTHER_FILES_SIZE = 325 * 1024 * 1024 * 1024

original_verbosity = $VERBOSE
$VERBOSE = nil
module ActiveSupport
  module NumberHelper
    class NumberToHumanSizeConverter < NumberConverter #:nodoc:
      STORAGE_UNITS = [:byte, :kb, :mb, :gb]
    end
  end
end
$VERBOSE = original_verbosity

class Anime
  attr_accessor :name, :bytes

  def initialize(name, bytes)
    @name = name
    @bytes = bytes
  end

  def size
    ActiveSupport::NumberHelper.number_to_human_size(@bytes, { precision: 5, strip_insignificant_zeros: false })
  end

  def to_s
    "#{@name.cyan}: #{size}"
  end
end

class Group
  attr_accessor :animes, :number
  @@count = 0

  def initialize(animes = [], number = nil)
    @animes = animes
    if number.nil?
      @@count += 1
      @number = @@count.to_s
    else
      @number = number
    end
  end

  def bytes
    animes.sum(&:bytes)
  end

  def size
    ActiveSupport::NumberHelper.number_to_human_size(bytes, { precision: 5, strip_insignificant_zeros: false })
  end

  def to_s
    if animes.empty?
      "Group ##{number.to_s.cyan} (empty)"
    else
      "Group ##{number.to_s.cyan} (#{size}): \"#{animes.first.name}\" - \"#{animes.last.name}\""
    end
  end
end

def main
  shows = Dir.entries PATH, **OPTS
  shows.each do |show|
    next if show == '.' || show == '..' || show == 'zWatched' || show == 'desktop.ini' || show == 'format.txt'
    calculate_size show
  end
  PATH << '/zWatched'
  watched_shows = Dir.entries PATH, **OPTS
  watched_shows.each do |show|
    next if show == '.' || show == '..' || show == 'desktop.ini'
    calculate_size show
  end

  RESULTS.sort_by! { |a| a.name.downcase }
  print "\r".ljust(120)
  print "\r"

  # plus_minus = 20
  #
  # buffer_sizes = (-plus_minus..plus_minus).map do |buffer_adjustment|
  #   puts "#{buffer_adjustment} GiB Buffer Adjustment"
  #   buffer_size = BUFFER_SIZE + buffer_adjustment * 1024 * 1024 * 1024
  #   transfer_size = PARTITION_SIZE - buffer_size
  #   [ buffer_adjustment, calculate_groups(RESULTS.clone, PARTITION_SIZE, buffer_size, transfer_size, OTHER_FILES_SIZE) ]
  # end.to_h.sort_by { |k, v| [v, k.abs] }
  #
  # puts "\n********************************\n\n"
  # buffer_sizes.each do |adjustment, std_deviation|
  #   puts "#{adjustment}: #{human_size(std_deviation)}"
  # end

  calculate_groups(RESULTS.clone, PARTITION_SIZE, BUFFER_SIZE, TRANSFER_SIZE, OTHER_FILES_SIZE)
end

def calculate_groups(animes, partition_size, buffer_size, transfer_size, other_files_size)
  animes.unshift(Anime.new('other files', other_files_size))
  total_size = animes.sum(&:bytes)
  puts Anime.new('total size', total_size)
  puts Anime.new('Partition size', partition_size)
  puts Anime.new('Buffer size', buffer_size)
  puts Anime.new('Transfer size', transfer_size)

  numb_transfers = total_size / transfer_size.to_f
  puts "numb_transfers: #{numb_transfers}"
  current_group = Group.new()
  groups = [current_group]

  animes.each do |anime|
    if (current_group.bytes + anime.bytes) >= transfer_size
      current_group = Group.new()
      groups << current_group
    end
    current_group.animes << anime
  end

  puts "\nUnbalanced Groups\n\n"
  groups.each do |group|
    puts group
  end
  puts "std_deviation: #{human_size standard_deviation(groups)}"

  groups = balance_groups(groups)

  puts "\nBalanced Groups\n\n"
  groups.each do |group|
    puts group
  end
  puts "std_deviation: #{human_size standard_deviation(groups)}"
  puts

  # puts "\nRight Weighted Groups\n\n"
  # transfer_left_to_right(groups[INDEXES[0]], groups[INDEXES[1]])
  # transfer_left_to_right(groups[INDEXES[1]], groups[INDEXES[2]])
  # groups.each do |group|
  #   puts group
  # end
  # puts "std_deviation: #{human_size standard_deviation(groups)}"
  # transfer_right_to_left(groups[INDEXES[1]], groups[INDEXES[2]])
  # transfer_right_to_left(groups[INDEXES[0]], groups[INDEXES[1]])
  #
  # puts "\nLeft Weighted Groups\n\n"
  # transfer_right_to_left(groups[INDEXES[INDEXES[0]]], groups[INDEXES[1]])
  # transfer_right_to_left(groups[INDEXES[1]], groups[INDEXES[2]])
  # groups.each do |group|
  #   puts group
  # end
  # puts "std_deviation: #{human_size standard_deviation(groups)}"
  # transfer_left_to_right(groups[INDEXES[1]], groups[INDEXES[2]])
  # transfer_left_to_right(groups[INDEXES[0]], groups[INDEXES[1]])
  standard_deviation(groups)
end

def balance_groups(groups)
  loop do
    made_changes = false
    combinations(groups) do |range|
      made_changes ||= balance_left_to_right(groups, range)
      made_changes ||= balance_right_to_left(groups, range)
    end
    return groups unless made_changes
  end
end

# yields to each combination of group index, sorted by difference so that it does the smallest ranges first.
# ex: [0..1, 1..2, 2..3, 0..2, 1..3, 0..4]
def combinations(groups)
  (0...groups.size)
    .to_a
    .combination(2)
    .to_a
    .sort { |a, b| (a.last - a.first) - (b.last - b.first) }
    .map { |s, f| yield s..f }
end

def human_size(n)
  ActiveSupport::NumberHelper.number_to_human_size(n, { precision: 5, strip_insignificant_zeros: false })
end

def balance_left_to_right(groups, range)
  omnibalance(groups, range, ->(l, r) { transfer_left_to_right(l, r) }, ->(l, r) { transfer_right_to_left(l, r) })
end

def balance_right_to_left(groups, range)
  omnibalance(groups, range, ->(l, r) { transfer_right_to_left(l, r) }, ->(l, r) { transfer_left_to_right(l, r) })
end

def omnibalance(groups, range, forwards, backwards)
  made_changes = false
  current = standard_deviation(groups)

  loop do
    range.each_cons(2) do |start_index, end_index|
      forwards.call(groups[start_index], groups[end_index])
    end
    prev = current
    current = standard_deviation(groups)
    # puts "\nprev: #{human_size prev}, current: #{human_size current}" # debug
    if (current > prev)
      range.each_cons(2) do |start_index, end_index|
        backwards.call(groups[start_index], groups[end_index])
      end
      return made_changes
    end
    made_changes = true
  end
end

def transfer_left_to_right(group1, group2)
  anime = group1.animes.pop
  # puts "moving #{anime.name} from group ##{group1.number} to group ##{group2.number}".light_green # debug
  group2.animes.unshift(anime)
end

def transfer_right_to_left(group1, group2)
  anime = group2.animes.shift
  # puts "moving #{anime.name} from group ##{group2.number} to group ##{group1.number}".light_red # debug
  group1.animes << anime
end

def standard_deviation(groups)
  mean = groups.sum(&:bytes) / groups.size.to_f
  variance = (groups.inject(0) { |accum, group| accum + (group.bytes - mean) ** 2 }) / (groups.size - 1).to_f
  Math.sqrt(variance)
end

def directory_size(path)
  # path << '/' unless path.end_with?('/')

  raise RuntimeError, "#{path} is not a directory" unless File.directory?(path)

  total_size = 0
  entries = Dir.entries path, **OPTS
  entries.each do |f|
    next if f == '.' || f == '..' || f == 'zWatched' || f == 'desktop.ini'
    # next unless f.include?(File.basename(path))
    # puts "f: #{f}"
    f = "#{path}/#{f}"
    # puts "basename: #{File.basename path}"
    # puts "path: #{path}"
    # puts f
    total_size += File.size(f) if File.file?(f) && File.size?(f)
    total_size += directory_size f if File.directory? f
  end
  total_size
end

# f: 26.mp4
# basename: Season 2 (Dark Tournament Saga)
# path: /mnt/d/anime/Yu Yu Hakusho; Ghost Files/Season 2 (Dark Tournament Saga)
# /mnt/d/anime/Yu Yu Hakusho; Ghost Files/Season 2 (Dark Tournament Saga)/26.mp4

def calculate_size(show)
  print "\rcalculating size for #{show}".ljust(120)
  size = directory_size "#{PATH}/#{show}"
  if SHOWS.include? show
    anime = SHOWS[show]
    anime.bytes += size
  else
    anime = Anime.new(show, size)
    RESULTS << anime
    SHOWS[anime.name] = anime
  end
end

start = Time.now
main
puts "Took #{Time.now - start} seconds"


text:
"""Script to populate datastore with system test data."""

from __future__ import print_function

import os
import sys
import time
import uuid

import six

from google.cloud import datastore

ANCESTOR = ("Book", "GoT")
RICKARD = ANCESTOR + ("Character", "Rickard")
EDDARD = RICKARD + ("Character", "Eddard")
KEY_PATHS = (
    RICKARD,
    EDDARD,
    ANCESTOR + ("Character", "Catelyn"),
    EDDARD + ("Character", "Arya"),
    EDDARD + ("Character", "Sansa"),
    EDDARD + ("Character", "Robb"),
    EDDARD + ("Character", "Bran"),
    EDDARD + ("Character", "Jon Snow"),
)
CHARACTERS = (
    {"name": u"Rickard", "family": u"Stark", "appearances": 0, "alive": False},
    {"name": u"Eddard", "family": u"Stark", "appearances": 9, "alive": False},
    {
        "name": u"Catelyn",
        "family": [u"Stark", u"Tully"],
        "appearances": 26,
        "alive": False,
    },
    {"name": u"Arya", "family": u"Stark", "appearances": 33, "alive": True},
    {"name": u"Sansa", "family": u"Stark", "appearances": 31, "alive": True},
    {"name": u"Robb", "family": u"Stark", "appearances": 22, "alive": False},
    {"name": u"Bran", "family": u"Stark", "appearances": 25, "alive": True},
    {"name": u"Jon Snow", "family": u"Stark", "appearances": 32, "alive": True},
)

def print_func(message):
    if os.getenv("GOOGLE_CLOUD_NO_PRINT") != "true":
        print(message)

def add_characters(client=None):
    if client is None:
        # Get a client that uses the test dataset.
        client = datastore.Client()
    with client.transaction() as xact:
        for key_path, character in six.moves.zip(KEY_PATHS, CHARACTERS):
            if key_path[-1] != character["name"]:
                raise ValueError(("Character and key don't agree", key_path, character))
            entity = datastore.Entity(key=client.key(*key_path))
            entity.update(character)
            xact.put(entity)
            print_func(
                "Adding Character %s %s" % (character["name"], character["family"])
            )

def add_uid_keys(client=None):
    if client is None:
        # Get a client that uses the test dataset.
        client = datastore.Client()

    num_batches = 2
    batch_size = 500

    for batch_num in range(num_batches):
        with client.batch() as batch:
            for seq_no in range(batch_size):
                uid = str(uuid.uuid4())
                key = client.key("uuid_key", uid)
                entity = datastore.Entity(key=key)
                entity["batch_num"] = batch_num
                entity["seq_no"] = seq_no
                batch.put(entity)

def add_timestamp_keys(client=None):
    if client is None:
        # Get a client that uses the test dataset.
        client = datastore.Client()

    num_batches = 2
    batch_size = 500

    timestamp_micros = set()
    for batch_num in range(num_batches):
        with client.batch() as batch:
            for seq_no in range(batch_size):
                print("time_time: batch: {}, sequence: {}".format(batch_num, seq_no))
                now_micros = int(time.time() * 1e6)
                while now_micros in timestamp_micros:
                    now_micros = int(time.time() * 1e6)
                timestamp_micros.add(now_micros)
                key = client.key("timestamp_key", now_micros)
                entity = datastore.Entity(key=key)
                entity["batch_num"] = batch_num
                entity["seq_no"] = seq_no
                batch.put(entity)

def main():
    client = datastore.Client()
    flags = sys.argv[1:]

    if len(flags) == 0:
        flags = ["--characters", "--uuid", "--timestamps"]

    if "--characters" in flags:
        add_characters(client)

    if "--uuid" in flags:
        add_uid_keys(client)

    if "--timestamps" in flags:
        add_timestamp_keys(client)

if __name__ == "__main__":
    main()


text:
package org.elasticsearch.search.aggregations;

import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.NamedWriteable;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.support.AggregationPath;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * An internal implementation of {@link Aggregation}. Serves as a base class for all aggregation implementations.
 */
public abstract class InternalAggregation implements Aggregation, ToXContent, NamedWriteable {
    /**
     * The aggregation type that holds all the string types that are associated with an aggregation:
     *

     *
name - used as the parser type

     *

     */
    public static class Type {
        private final String name;

        public Type(String name) {
            this.name = name;
        }

        /**
         * @return The name of the type of aggregation.  This is the key for parsing the aggregation from XContent and is the name of the
         * aggregation's builder when serialized.
         */
        public String name() {
            return name;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    public static class ReduceContext {

        private final BigArrays bigArrays;
        private final ScriptService scriptService;

        public ReduceContext(BigArrays bigArrays, ScriptService scriptService) {
            this.bigArrays = bigArrays;
            this.scriptService = scriptService;
        }

        public BigArrays bigArrays() {
            return bigArrays;
        }

        public ScriptService scriptService() {
            return scriptService;
        }
    }

    protected final String name;

    protected final Map<String, Object> metaData;

    private final List<PipelineAggregator> pipelineAggregators;

    /**
     * Constructs an get with a given name.
     *
     * @param name The name of the get.
     */
    protected InternalAggregation(String name, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) {
        this.name = name;
        this.pipelineAggregators = pipelineAggregators;
        this.metaData = metaData;
    }

    /**
     * Read from a stream.
     */
    protected InternalAggregation(StreamInput in) throws IOException {
        name = in.readString();
        metaData = in.readMap();
        pipelineAggregators = in.readNamedWriteableList(PipelineAggregator.class);
    }

    @Override
    public final void writeTo(StreamOutput out) throws IOException {
        out.writeString(name);
        out.writeGenericValue(metaData);
        out.writeNamedWriteableList(pipelineAggregators);
        doWriteTo(out);
    }

    protected abstract void doWriteTo(StreamOutput out) throws IOException;

    @Override
    public String getName() {
        return name;
    }

    /**
     * Reduces the given aggregations to a single one and returns it. In most cases, the assumption will be the all given
     * aggregations are of the same type (the same type as this aggregation). For best efficiency, when implementing,
     * try reusing an existing instance (typically the first in the given list) to save on redundant object
     * construction.
     */
    public final InternalAggregation reduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) {
        InternalAggregation aggResult = doReduce(aggregations, reduceContext);
        for (PipelineAggregator pipelineAggregator : pipelineAggregators) {
            aggResult = pipelineAggregator.reduce(aggResult, reduceContext);
        }
        return aggResult;
    }

    public abstract InternalAggregation doReduce(List<InternalAggregation> aggregations, ReduceContext reduceContext);

    @Override
    public Object getProperty(String path) {
        AggregationPath aggPath = AggregationPath.parse(path);
        return getProperty(aggPath.getPathElementsAsStringList());
    }

    public abstract Object getProperty(List<String> path);

    /**
     * Read a size under the assumption that a value of 0 means unlimited.
     */
    protected static int readSize(StreamInput in) throws IOException {
        final int size = in.readVInt();
        return size == 0 ? Integer.MAX_VALUE : size;
    }

    /**
     * Write a size under the assumption that a value of 0 means unlimited.
     */
    protected static void writeSize(int size, StreamOutput out) throws IOException {
        if (size == Integer.MAX_VALUE) {
            size = 0;
        }
        out.writeVInt(size);
    }

    @Override
    public Map<String, Object> getMetaData() {
        return metaData;
    }

    public List<PipelineAggregator> pipelineAggregators() {
        return pipelineAggregators;
    }

    @Override
    public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject(name);
        if (this.metaData != null) {
            builder.field(CommonFields.META);
            builder.map(this.metaData);
        }
        doXContentBody(builder, params);
        builder.endObject();
        return builder;
    }

    public abstract XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException;

    /**
     * Common xcontent fields that are shared among addAggregation
     */
    public static final class CommonFields extends ParseField.CommonFields {
        // todo convert these to ParseField
        public static final String META = "meta";
        public static final String BUCKETS = "buckets";
        public static final String VALUE = "value";
        public static final String VALUES = "values";
        public static final String VALUE_AS_STRING = "value_as_string";
        public static final String DOC_COUNT = "doc_count";
        public static final String KEY = "key";
        public static final String KEY_AS_STRING = "key_as_string";
        public static final String FROM = "from";
        public static final String FROM_AS_STRING = "from_as_string";
        public static final String TO = "to";
        public static final String TO_AS_STRING = "to_as_string";
    }
}


text:
Installation
--------------
- $ npm install
- $ bower install

Running at
LOLTournaments