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.msi.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.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.core.util.logging.ClientLogger;
import com.azure.resourcemanager.msi.fluent.UserAssignedIdentitiesClient;
import com.azure.resourcemanager.msi.fluent.models.IdentityInner;
import com.azure.resourcemanager.msi.models.IdentityUpdate;
import com.azure.resourcemanager.msi.models.UserAssignedIdentitiesListResult;
import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsDelete;
import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsGet;
import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsListing;
import reactor.core.publisher.Mono;

/** An instance of this class provides access to all the operations defined in UserAssignedIdentitiesClient. */
public final class UserAssignedIdentitiesClientImpl
    implements InnerSupportsGet<IdentityInner>,
        InnerSupportsListing<IdentityInner>,
        InnerSupportsDelete<Void>,
        UserAssignedIdentitiesClient {
    private final ClientLogger logger = new ClientLogger(UserAssignedIdentitiesClientImpl.class);

    /** The proxy service used to perform REST calls. */
    private final UserAssignedIdentitiesService service;

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

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

    /**
     * The interface defining all the services for ManagedServiceIdentityClientUserAssignedIdentities to be used by the
     * proxy service to perform REST calls.
     */
    @Host("{$host}")
    @ServiceInterface(name = "ManagedServiceIdenti")
    private interface UserAssignedIdentitiesService {
        @Headers({"Accept: application/json", "Content-Type: application/json"})
        @Get("/subscriptions/{subscriptionId}/providers/Microsoft.ManagedIdentity/userAssignedIdentities")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<UserAssignedIdentitiesListResult>> list(
            @HostParam("$host") String endpoint,
            @PathParam("subscriptionId") String subscriptionId,
            @QueryParam("api-version") String apiVersion,
            Context context);

        @Headers({"Accept: application/json", "Content-Type: application/json"})
        @Get(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity"
                + "/userAssignedIdentities")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<UserAssignedIdentitiesListResult>> listByResourceGroup(
            @HostParam("$host") String endpoint,
            @PathParam("subscriptionId") String subscriptionId,
            @PathParam("resourceGroupName") String resourceGroupName,
            @QueryParam("api-version") String apiVersion,
            Context context);

        @Headers({"Accept: application/json", "Content-Type: application/json"})
        @Put(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity"
                + "/userAssignedIdentities/{resourceName}")
        @ExpectedResponses({200, 201})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<IdentityInner>> createOrUpdate(
            @HostParam("$host") String endpoint,
            @PathParam("subscriptionId") String subscriptionId,
            @PathParam("resourceGroupName") String resourceGroupName,
            @PathParam("resourceName") String resourceName,
            @QueryParam("api-version") String apiVersion,
            @BodyParam("application/json") IdentityInner parameters,
            Context context);

        @Headers({"Accept: application/json", "Content-Type: application/json"})
        @Patch(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity"
                + "/userAssignedIdentities/{resourceName}")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<IdentityInner>> update(
            @HostParam("$host") String endpoint,
            @PathParam("subscriptionId") String subscriptionId,
            @PathParam("resourceGroupName") String resourceGroupName,
            @PathParam("resourceName") String resourceName,
            @QueryParam("api-version") String apiVersion,
            @BodyParam("application/json") IdentityUpdate parameters,
            Context context);

        @Headers({"Accept: application/json", "Content-Type: application/json"})
        @Get(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity"
                + "/userAssignedIdentities/{resourceName}")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<IdentityInner>> getByResourceGroup(
            @HostParam("$host") String endpoint,
            @PathParam("subscriptionId") String subscriptionId,
            @PathParam("resourceGroupName") String resourceGroupName,
            @PathParam("resourceName") String resourceName,
            @QueryParam("api-version") String apiVersion,
            Context context);

        @Headers({"Accept: application/json;q=0.9", "Content-Type: application/json"})
        @Delete(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity"
                + "/userAssignedIdentities/{resourceName}")
        @ExpectedResponses({200, 204})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<Void>> delete(
            @HostParam("$host") String endpoint,
            @PathParam("subscriptionId") String subscriptionId,
            @PathParam("resourceGroupName") String resourceGroupName,
            @PathParam("resourceName") String resourceName,
            @QueryParam("api-version") String apiVersion,
            Context context);

        @Headers({"Accept: application/json", "Content-Type: application/json"})
        @Get("{nextLink}")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<UserAssignedIdentitiesListResult>> listBySubscriptionNext(
            @PathParam(value = "nextLink", encoded = true) String nextLink, Context context);

        @Headers({"Accept: application/json", "Content-Type: application/json"})
        @Get("{nextLink}")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<UserAssignedIdentitiesListResult>> listByResourceGroupNext(
            @PathParam(value = "nextLink", encoded = true) String nextLink, Context context);
    }

    /**
     * Lists all the userAssignedIdentities available under the specified subscription.
     *
     * @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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<IdentityInner>> listSinglePageAsync() {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() 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."));
        }
        return FluxUtil
            .withContext(
                context ->
                    service
                        .list(
                            this.client.getEndpoint(),
                            this.client.getSubscriptionId(),
                            this.client.getApiVersion(),
                            context))
            .<PagedResponse<IdentityInner>>map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * Lists all the userAssignedIdentities available under the specified subscription.
     *
     * @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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<IdentityInner>> listSinglePageAsync(Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() 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."));
        }
        context = this.client.mergeContext(context);
        return service
            .list(this.client.getEndpoint(), this.client.getSubscriptionId(), this.client.getApiVersion(), context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null));
    }

    /**
     * Lists all the userAssignedIdentities available under the specified subscription.
     *
     * @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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedFlux<IdentityInner> listAsync() {
        return new PagedFlux<>(
            () -> listSinglePageAsync(), nextLink -> listBySubscriptionNextSinglePageAsync(nextLink));
    }

    /**
     * Lists all the userAssignedIdentities available under the specified subscription.
     *
     * @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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<IdentityInner> listAsync(Context context) {
        return new PagedFlux<>(
            () -> listSinglePageAsync(context), nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context));
    }

    /**
     * Lists all the userAssignedIdentities available under the specified subscription.
     *
     * @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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<IdentityInner> list() {
        return new PagedIterable<>(listAsync());
    }

    /**
     * Lists all the userAssignedIdentities available under the specified subscription.
     *
     * @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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<IdentityInner> list(Context context) {
        return new PagedIterable<>(listAsync(context));
    }

    /**
     * Lists all the userAssignedIdentities available under the specified ResourceGroup.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<IdentityInner>> listByResourceGroupSinglePageAsync(String resourceGroupName) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() 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 (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        return FluxUtil
            .withContext(
                context ->
                    service
                        .listByResourceGroup(
                            this.client.getEndpoint(),
                            this.client.getSubscriptionId(),
                            resourceGroupName,
                            this.client.getApiVersion(),
                            context))
            .<PagedResponse<IdentityInner>>map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * Lists all the userAssignedIdentities available under the specified ResourceGroup.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<IdentityInner>> listByResourceGroupSinglePageAsync(
        String resourceGroupName, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() 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 (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        context = this.client.mergeContext(context);
        return service
            .listByResourceGroup(
                this.client.getEndpoint(),
                this.client.getSubscriptionId(),
                resourceGroupName,
                this.client.getApiVersion(),
                context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null));
    }

    /**
     * Lists all the userAssignedIdentities available under the specified ResourceGroup.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedFlux<IdentityInner> listByResourceGroupAsync(String resourceGroupName) {
        return new PagedFlux<>(
            () -> listByResourceGroupSinglePageAsync(resourceGroupName),
            nextLink -> listByResourceGroupNextSinglePageAsync(nextLink));
    }

    /**
     * Lists all the userAssignedIdentities available under the specified ResourceGroup.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<IdentityInner> listByResourceGroupAsync(String resourceGroupName, Context context) {
        return new PagedFlux<>(
            () -> listByResourceGroupSinglePageAsync(resourceGroupName, context),
            nextLink -> listByResourceGroupNextSinglePageAsync(nextLink, context));
    }

    /**
     * Lists all the userAssignedIdentities available under the specified ResourceGroup.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<IdentityInner> listByResourceGroup(String resourceGroupName) {
        return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName));
    }

    /**
     * Lists all the userAssignedIdentities available under the specified ResourceGroup.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<IdentityInner> listByResourceGroup(String resourceGroupName, Context context) {
        return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, context));
    }

    /**
     * Create or update an identity in the specified subscription and resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @param parameters Describes an identity resource.
     * @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 describes an identity resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<IdentityInner>> createOrUpdateWithResponseAsync(
        String resourceGroupName, String resourceName, IdentityInner parameters) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() 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 (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (resourceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceName 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();
        }
        return FluxUtil
            .withContext(
                context ->
                    service
                        .createOrUpdate(
                            this.client.getEndpoint(),
                            this.client.getSubscriptionId(),
                            resourceGroupName,
                            resourceName,
                            this.client.getApiVersion(),
                            parameters,
                            context))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * Create or update an identity in the specified subscription and resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @param parameters Describes an identity resource.
     * @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 describes an identity resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<IdentityInner>> createOrUpdateWithResponseAsync(
        String resourceGroupName, String resourceName, IdentityInner parameters, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() 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 (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (resourceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceName 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();
        }
        context = this.client.mergeContext(context);
        return service
            .createOrUpdate(
                this.client.getEndpoint(),
                this.client.getSubscriptionId(),
                resourceGroupName,
                resourceName,
                this.client.getApiVersion(),
                parameters,
                context);
    }

    /**
     * Create or update an identity in the specified subscription and resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @param parameters Describes an identity resource.
     * @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 describes an identity resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<IdentityInner> createOrUpdateAsync(
        String resourceGroupName, String resourceName, IdentityInner parameters) {
        return createOrUpdateWithResponseAsync(resourceGroupName, resourceName, parameters)
            .flatMap(
                (Response<IdentityInner> res) -> {
                    if (res.getValue() != null) {
                        return Mono.just(res.getValue());
                    } else {
                        return Mono.empty();
                    }
                });
    }

    /**
     * Create or update an identity in the specified subscription and resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @param parameters Describes an identity resource.
     * @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 describes an identity resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public IdentityInner createOrUpdate(String resourceGroupName, String resourceName, IdentityInner parameters) {
        return createOrUpdateAsync(resourceGroupName, resourceName, parameters).block();
    }

    /**
     * Create or update an identity in the specified subscription and resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @param parameters Describes an identity resource.
     * @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 describes an identity resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Response<IdentityInner> createOrUpdateWithResponse(
        String resourceGroupName, String resourceName, IdentityInner parameters, Context context) {
        return createOrUpdateWithResponseAsync(resourceGroupName, resourceName, parameters, context).block();
    }

    /**
     * Update an identity in the specified subscription and resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @param parameters Describes an identity resource.
     * @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 describes an identity resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<IdentityInner>> updateWithResponseAsync(
        String resourceGroupName, String resourceName, IdentityUpdate parameters) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() 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 (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (resourceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceName 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();
        }
        return FluxUtil
            .withContext(
                context ->
                    service
                        .update(
                            this.client.getEndpoint(),
                            this.client.getSubscriptionId(),
                            resourceGroupName,
                            resourceName,
                            this.client.getApiVersion(),
                            parameters,
                            context))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * Update an identity in the specified subscription and resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @param parameters Describes an identity resource.
     * @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 describes an identity resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<IdentityInner>> updateWithResponseAsync(
        String resourceGroupName, String resourceName, IdentityUpdate parameters, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() 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 (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (resourceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceName 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();
        }
        context = this.client.mergeContext(context);
        return service
            .update(
                this.client.getEndpoint(),
                this.client.getSubscriptionId(),
                resourceGroupName,
                resourceName,
                this.client.getApiVersion(),
                parameters,
                context);
    }

    /**
     * Update an identity in the specified subscription and resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @param parameters Describes an identity resource.
     * @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 describes an identity resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<IdentityInner> updateAsync(String resourceGroupName, String resourceName, IdentityUpdate parameters) {
        return updateWithResponseAsync(resourceGroupName, resourceName, parameters)
            .flatMap(
                (Response<IdentityInner> res) -> {
                    if (res.getValue() != null) {
                        return Mono.just(res.getValue());
                    } else {
                        return Mono.empty();
                    }
                });
    }

    /**
     * Update an identity in the specified subscription and resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @param parameters Describes an identity resource.
     * @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 describes an identity resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public IdentityInner update(String resourceGroupName, String resourceName, IdentityUpdate parameters) {
        return updateAsync(resourceGroupName, resourceName, parameters).block();
    }

    /**
     * Update an identity in the specified subscription and resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @param parameters Describes an identity resource.
     * @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 describes an identity resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Response<IdentityInner> updateWithResponse(
        String resourceGroupName, String resourceName, IdentityUpdate parameters, Context context) {
        return updateWithResponseAsync(resourceGroupName, resourceName, parameters, context).block();
    }

    /**
     * Gets the identity.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @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 identity.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<IdentityInner>> getByResourceGroupWithResponseAsync(
        String resourceGroupName, String resourceName) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() 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 (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (resourceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null."));
        }
        return FluxUtil
            .withContext(
                context ->
                    service
                        .getByResourceGroup(
                            this.client.getEndpoint(),
                            this.client.getSubscriptionId(),
                            resourceGroupName,
                            resourceName,
                            this.client.getApiVersion(),
                            context))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * Gets the identity.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @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 identity.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<IdentityInner>> getByResourceGroupWithResponseAsync(
        String resourceGroupName, String resourceName, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() 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 (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (resourceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null."));
        }
        context = this.client.mergeContext(context);
        return service
            .getByResourceGroup(
                this.client.getEndpoint(),
                this.client.getSubscriptionId(),
                resourceGroupName,
                resourceName,
                this.client.getApiVersion(),
                context);
    }

    /**
     * Gets the identity.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @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 identity.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<IdentityInner> getByResourceGroupAsync(String resourceGroupName, String resourceName) {
        return getByResourceGroupWithResponseAsync(resourceGroupName, resourceName)
            .flatMap(
                (Response<IdentityInner> res) -> {
                    if (res.getValue() != null) {
                        return Mono.just(res.getValue());
                    } else {
                        return Mono.empty();
                    }
                });
    }

    /**
     * Gets the identity.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @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 identity.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public IdentityInner getByResourceGroup(String resourceGroupName, String resourceName) {
        return getByResourceGroupAsync(resourceGroupName, resourceName).block();
    }

    /**
     * Gets the identity.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @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 identity.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Response<IdentityInner> getByResourceGroupWithResponse(
        String resourceGroupName, String resourceName, Context context) {
        return getByResourceGroupWithResponseAsync(resourceGroupName, resourceName, context).block();
    }

    /**
     * Deletes the identity.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @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 completion.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<Void>> deleteWithResponseAsync(String resourceGroupName, String resourceName) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() 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 (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (resourceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null."));
        }
        return FluxUtil
            .withContext(
                context ->
                    service
                        .delete(
                            this.client.getEndpoint(),
                            this.client.getSubscriptionId(),
                            resourceGroupName,
                            resourceName,
                            this.client.getApiVersion(),
                            context))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * Deletes the identity.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @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 completion.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<Void>> deleteWithResponseAsync(
        String resourceGroupName, String resourceName, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() 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 (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (resourceName == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null."));
        }
        context = this.client.mergeContext(context);
        return service
            .delete(
                this.client.getEndpoint(),
                this.client.getSubscriptionId(),
                resourceGroupName,
                resourceName,
                this.client.getApiVersion(),
                context);
    }

    /**
     * Deletes the identity.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @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 completion.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Void> deleteAsync(String resourceGroupName, String resourceName) {
        return deleteWithResponseAsync(resourceGroupName, resourceName).flatMap((Response<Void> res) -> Mono.empty());
    }

    /**
     * Deletes the identity.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @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 resourceName) {
        deleteAsync(resourceGroupName, resourceName).block();
    }

    /**
     * Deletes the identity.
     *
     * @param resourceGroupName The name of the Resource Group to which the identity belongs.
     * @param resourceName The name of the identity resource.
     * @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 response.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Response<Void> deleteWithResponse(String resourceGroupName, String resourceName, Context context) {
        return deleteWithResponseAsync(resourceGroupName, resourceName, 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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<IdentityInner>> listBySubscriptionNextSinglePageAsync(String nextLink) {
        if (nextLink == null) {
            return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
        }
        return FluxUtil
            .withContext(context -> service.listBySubscriptionNext(nextLink, context))
            .<PagedResponse<IdentityInner>>map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * 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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<IdentityInner>> listBySubscriptionNextSinglePageAsync(String nextLink, Context context) {
        if (nextLink == null) {
            return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
        }
        context = this.client.mergeContext(context);
        return service
            .listBySubscriptionNext(nextLink, context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null));
    }

    /**
     * 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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<IdentityInner>> listByResourceGroupNextSinglePageAsync(String nextLink) {
        if (nextLink == null) {
            return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
        }
        return FluxUtil
            .withContext(context -> service.listByResourceGroupNext(nextLink, context))
            .<PagedResponse<IdentityInner>>map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * 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 values returned by the List operation.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<IdentityInner>> listByResourceGroupNextSinglePageAsync(
        String nextLink, Context context) {
        if (nextLink == null) {
            return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
        }
        context = this.client.mergeContext(context);
        return service
            .listByResourceGroupNext(nextLink, context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null));
    }
}


text:
import { error } from "../ui";
import * as _ from "lodash";
import {
  BotState,
  DeviceAccountSettings,
  HardwareState,
  RpcBotLog
} from "./interfaces";
import { generateReducer } from "../redux/generate_reducer";
import { isBotLog } from "./is_bot_log";
import { ReduxAction } from "../redux/interfaces";
import * as i18next from "i18next";
import { ChangeSettingsBuffer } from "./interfaces";
import { Sequence } from "../sequences/interfaces";
import { Regimen } from "../regimens/interfaces";
import { Configuration } from "farmbot/dist/interfaces";
import { Sync } from "../interfaces";

let status = {
  NOT_READY: (): string => { return i18next.t("never connected to device"); },
  CONNECTING: (): string => { return i18next.t("initiating connection"); },
  AWAITING_API: (): string => {
    return i18next.t("downloading device credentials");
  },
  API_ERROR: (): string => {
    return i18next.t("Unable to download device credentials");
  },
  AWAITING_WEBSOCKET: (): string => {
    return i18next.t("calling FarmBot with credentials");
  },
  WEBSOCKET_ERR: (): string => {
    return i18next.t("Error establishing socket connection");
  },
  CONNECTED: (): string => {
    return i18next.t("Socket Connection Established");
  },
  READY: (): string => { return i18next.t("Bot ready"); }
};

let initialState: BotState = {
  account: { id: 0, name: "" },
  logQueueSize: 20,
  logQueue: [],
  status: status.NOT_READY(),
  stepSize: 1000,
  hardware: {
    mcu_params: {},
    location: [-1, -1, -1],
    pins: {},
    configuration: {},
    informational_settings: {},
    farm_scheduler: {
      process_info: [],
      sequence_log: [],
      current_sequence: null,
    }
  },
  axisBuffer: {},
  settingsBuffer: {},
  configBuffer: {},
  dirty: false,
  currentOSVersion: undefined,
  currentFWVersion: undefined,
};

export let botReducer = generateReducer<BotState>(initialState)
  .add<HardwareState>("SETTING_TOGGLE_OK",
  function (state: BotState, action: ReduxAction<HardwareState>) {

    let hardware = action.payload;
    return Object.assign({},
      state, {
        hardware: hardware
      }, {
        status: status.READY()
      });
  })
  .add<{}>("CLEAR_BOT_LOG", function (state, action) {
    state.logQueue = [];
    return state;
  })
  .add<{}>("COMMIT_SETTINGS_OK", function (state, action) {
    let nextState = Object.assign({}, state, {
      settingsBuffer: {}
    });
    return nextState;
  })
  .add<Sequence>("SAVE_SEQUENCE_OK", function (state, action) {
    state.dirty = false;
    return state;
  })
  .add<Sequence>("DELETE_SEQUENCE_OK", function (state, action) {
    state.dirty = false;
    return state;
  })
  .add<Regimen>("SAVE_REGIMEN_OK", function (state, action) {
    state.dirty = false;
    return state;
  })
  .add<Regimen>("DELETE_REGIMEN_OK", function (state, action) {
    state.dirty = false;
    return state;
  })
  .add<{}>("BOT_SYNC_OK", function (state, action) {
    state.dirty = false;
    return state;
  })
  .add<{}>("COMMIT_AXIS_CHANGE_OK", function (oldState, action) {
    let hardware = Object.assign({}, oldState.hardware, action.payload);
    let state = Object.assign<{}, BotState>({}, oldState);

    return Object.assign({}, state, {
      axisBuffer: {},
      hardware
    });
  })
  .add<{ key: "x" | "y" | "z", val: string }>("CHANGE_AXIS_BUFFER",
  function (state, action) {
    state.axisBuffer[action.payload.key] = action.payload.val;
    return Object.assign({}, state, {
      axisBuffer: state.axisBuffer
    });
  })
  .add<Configuration>("CHANGE_CONFIG_BUFFER", function (state, action) {
    let old_buffer = state.configBuffer;
    let new_buffer = action.payload;
    Object.assign(old_buffer, new_buffer);
    let new_state = Object.assign({}, state, { config_buffer: new_buffer });
    return new_state; // I am doing something wrong.
  })
  .add<ChangeSettingsBuffer>("CHANGE_SETTINGS_BUFFER",
  function (state, action) {
    let newVal = action.payload.val;
    if (newVal) {
      state.settingsBuffer[action.payload.key] = action.payload.val.toString();
    } else {
      delete state.settingsBuffer[action.payload.key];
    }
    return Object.assign({}, state, {
      settingsBuffer: state.settingsBuffer
    });
  })
  .add<number>("CHANGE_STEP_SIZE", function (state, action) {
    return Object.assign({}, state, {
      stepSize: action.payload
    });
  })
  .add<HardwareState>("BOT_CHANGE",
  function (state, action) {
    state.hardware = action.payload;
    return state;
  })
  .add<DeviceAccountSettings>("CHANGE_DEVICE", function (s, a) {
    Object.assign(s.account, a.payload, { dirty: true });
    return s;
  })
  .add<any>("FETCH_DEVICE", function (state, action) {
    return state;
  })
  .add<any>("FETCH_DEVICE_OK", function (state, { payload }) {
    return Object.assign({},
      state,
      payload, {
        status: status.AWAITING_WEBSOCKET
      });
  })
  .add<any>("FETCH_DEVICE_ERR", function (state, action) {
    // TODO: Toast messages do not belong in a reducer.
    return Object.assign({},
      state, {
        status: status.API_ERROR
      });
  })
  .add<any>("SAVE_DEVICE_ERR", function (state, action) {
    switch (action.payload.status) {
      case 422:
        let errors = _.map(action.payload.responseJSON, v => v)
          .join(". ");
        error(errors, i18next.t("Couldn\'t save device."));
        break;
      default:
        error(i18next.t("Error while saving device."));
        break;
    }
    return state;
  })
  .add<any>("SAVE_DEVICE_OK", function (state, action) {
    return Object.assign({}, state, action.payload, {
      dirty: false
    });
  })
  .add<RpcBotLog>("BOT_LOG", function (state, { payload }) {
    if (isBotLog(payload)) {
      state.logQueue.unshift(payload);
      state.logQueue = _.take(state.logQueue, state.logQueueSize);
    } else {
      console.warn(i18next.t("Unexpected log message?"));
    }
    return state;
  })
  .add<DeviceAccountSettings>("REPLACE_DEVICE_ACCOUNT_INFO", function (s, a) {
    s.account = a.payload;
    return s;
  })
  .add<Sync>("FETCH_SYNC_OK", function (s, a) {
    s.account = a.payload.device;
    return s;
  })
  .add<string>("CHANGE_WEBCAM_URL", function (s, a) {
    s.account.dirty = true;
    s.account.webcam_url = a.payload;
    return s;
  })
  .add<string>("FETCH_OS_UPDATE_INFO_OK", function (s, a) {
    s.currentOSVersion = a.payload;
    return s;
  })
  .add<string>("FETCH_FW_UPDATE_INFO_OK", function (s, a) {
    s.currentFWVersion = a.payload;
    return s;
  });

redpajama_set_name: RedPajamaGithub


text:
from tempest.api.volume import base
from tempest.common import waiters
from tempest.lib.common.utils import test_utils
from tempest.lib import decorators

class VolumesTransfersTest(base.BaseVolumeTest):
    """Test volume transfer"""

    credentials = ['primary', 'alt', 'admin']

    @classmethod
    def setup_clients(cls):
        super(VolumesTransfersTest, cls).setup_clients()

        cls.client = cls.os_primary.volume_transfers_client_latest
        cls.alt_client = cls.os_alt.volume_transfers_client_latest
        cls.alt_volumes_client = cls.os_alt.volumes_client_latest
        cls.adm_volumes_client = cls.os_admin.volumes_client_latest

    @decorators.idempotent_id('4d75b645-a478-48b1-97c8-503f64242f1a')
    def test_create_get_list_accept_volume_transfer(self):
        """Test creating, getting, listing and accepting of volume transfer"""
        # Create a volume first
        volume = self.create_volume()
        self.addCleanup(self.delete_volume,
                        self.adm_volumes_client,
                        volume['id'])

        # Create a volume transfer
        transfer = self.client.create_volume_transfer(
            volume_id=volume['id'])['transfer']
        transfer_id = transfer['id']
        self.addCleanup(test_utils.call_and_ignore_notfound_exc,
                        self.client.delete_volume_transfer,
                        transfer_id)
        auth_key = transfer['auth_key']
        waiters.wait_for_volume_resource_status(
            self.volumes_client, volume['id'], 'awaiting-transfer')

        # Get a volume transfer
        body = self.client.show_volume_transfer(transfer_id)['transfer']
        self.assertEqual(volume['id'], body['volume_id'])

        # List volume transfers, the result should be greater than
        # or equal to 1
        body = self.client.list_volume_transfers()['transfers']
        self.assertNotEmpty(body)

        # Accept a volume transfer by alt_tenant
        body = self.alt_client.accept_volume_transfer(
            transfer_id, auth_key=auth_key)['transfer']
        waiters.wait_for_volume_resource_status(self.alt_volumes_client,
                                                volume['id'], 'available')
        accepted_volume = self.alt_volumes_client.show_volume(
            volume['id'])['volume']
        self.assertEqual(self.os_alt.credentials.user_id,
                         accepted_volume['user_id'])
        self.assertEqual(self.os_alt.credentials.project_id,
                         accepted_volume['os-vol-tenant-attr:tenant_id'])

    @decorators.idempotent_id('ab526943-b725-4c07-b875-8e8ef87a2c30')
    def test_create_list_delete_volume_transfer(self):
        """Test creating, listing and deleting volume transfer"""
        # Create a volume first
        volume = self.create_volume()
        self.addCleanup(self.delete_volume,
                        self.adm_volumes_client,
                        volume['id'])

        # Create a volume transfer
        transfer_id = self.client.create_volume_transfer(
            volume_id=volume['id'])['transfer']['id']
        self.addCleanup(test_utils.call_and_ignore_notfound_exc,
                        self.client.delete_volume_transfer,
                        transfer_id)
        waiters.wait_for_volume_resource_status(
            self.volumes_client, volume['id'], 'awaiting-transfer')

        # List all volume transfers with details, check the detail-specific
        # elements, and look for the created transfer.
        transfers = self.client.list_volume_transfers(detail=True)['transfers']
        self.assertNotEmpty(transfers)
        volume_list = [transfer['volume_id'] for transfer in transfers]
        self.assertIn(volume['id'], volume_list,
                      'Transfer not found for volume %s' % volume['id'])

        # Delete a volume transfer
        self.client.delete_volume_transfer(transfer_id)
        waiters.wait_for_volume_resource_status(
            self.volumes_client, volume['id'], 'available')


text:
//  (C) Copyright Rani Sharoni 2003-2005.
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).
//
//  See http://www.boost.org/libs/type_traits for most recent version including documentation.

#ifndef BOOST_TT_IS_BASE_OF_HPP_INCLUDED
#define BOOST_TT_IS_BASE_OF_HPP_INCLUDED

#include <boost/type_traits/is_base_and_derived.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_class.hpp>
#include <boost/type_traits/detail/ice_or.hpp>
#include <boost/type_traits/detail/ice_and.hpp>

// should be the last #include
#include <boost/type_traits/detail/bool_trait_def.hpp>

namespace boost {

   namespace detail{
      template <class B, class D>
      struct is_base_of_imp
      {
          typedef typename remove_cv<B>::type ncvB;
          typedef typename remove_cv<D>::type ncvD;
          BOOST_STATIC_CONSTANT(bool, value = (::boost::type_traits::ice_or<
            (::boost::detail::is_base_and_derived_impl<ncvB,ncvD>::value),
            (::boost::type_traits::ice_and< ::boost::is_same<ncvB,ncvD>::value, ::boost::is_class<ncvB>::value>::value)>::value));
      };
   }

BOOST_TT_AUX_BOOL_TRAIT_DEF2(
      is_base_of
    , Base
    , Derived
    , (::boost::detail::is_base_of_imp<Base, Derived>::value))

BOOST_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC2_2(typename Base,typename Derived,is_base_of,Base&,Derived,false)
BOOST_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC2_2(typename Base,typename Derived,is_base_of,Base,Derived&,false)
BOOST_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC2_2(typename Base,typename Derived,is_base_of,Base&,Derived&,false)

} // namespace boost

#include <boost/type_traits/detail/bool_trait_undef.hpp>

#endif // BOOST_TT_IS_BASE_AND_DERIVED_HPP_INCLUDED


text:
<?php

namespace Tests\Unit\Theorx\AutoLoaderMap;

use Theorx\AutoLoaderMap\AutoLoaderMap;
use Theorx\AutoLoaderMap\Exceptions\MapLoadingException;

/**
 * Class AutoLoaderMapTest
 *
 * @author             Lauri Orgla <theorx@hotmail.com>
 * @coversDefaultClass Theorx\AutoLoaderMap\AutoLoaderMap
 * @package            Tests\Unit\Theorx\AutoLoaderMap
 */
class AutoLoaderMapTest extends \PHPUnit_Framework_TestCase {

    /**
     * @author Lauri Orgla <theorx@hotmail.com>
     * @return array
     */
    public function provideMapsMethodsAndData() {

        $dir = realpath(__DIR__ . '/../../../library/');

        return [
            [
                'getClassMap',
                $dir . '/../../../composer/autoload_classmap.php',
                [
                    'class1' => 'file1.php',
                    'class2' => 'file2.php'
                ]
            ],
            [
                'getNamespaces',
                $dir . '/../../../composer/autoload_namespaces.php',
                [
                    'Ns/test/1',
                    'Ns/test/2',
                    'Ns/test/3'
                ]
            ],
            [
                'getPSR4',
                $dir . '/../../../composer/autoload_psr4.php',
                [
                    'psr4Class2341'  => 'file4.php',
                    'someOtherClass' => 'file5.php'
                ]
            ]
        ];
    }

    /**
     * @author       Lauri Orgla <theorx@hotmail.com>
     * @covers ::getClassMap
     * @covers ::getNamespaces
     * @covers ::getPSR4
     * @dataProvider provideMapsMethodsAndData
     *
     * @param $method
     * @param $path
     * @param $data
     */
    public function testReadClassMaps($method, $path, $data) {

        $mock = $this->getMockBuilder(AutoLoaderMap::class)->setMethods(['requireMap'])->getMock();
        $mock->expects($this->once())->method('requireMap')
            ->with($this->equalTo($path))->willReturn($data);

        /**
         * @var $mock AutoLoaderMap
         */
        $this->assertEquals($mock->{$method}(), $data);
    }

    /**
     * @author Lauri Orgla <theorx@hotmail.com>
     * @covers ::requireMap
     * @expectedException \Theorx\AutoLoaderMap\Exceptions\MapLoadingException
     */
    public function testRequireMapThrowsMapLoadingException() {

        $instance = new AutoLoaderMap();
        $instance->requireMap('invalid file');
    }

    /**
     * @author Lauri Orgla <theorx@hotmail.com>
     * @covers ::requireMap
     * @covers ::fileExists
     */
    public function testRequireMapReturnsData() {

        $instance = new AutoLoaderMap();
        $result = $instance->requireMap(__DIR__ . '/../../stub/ExampleFile.php');
        $this->assertCount(3, $result);
    }
}


text:
import java.util.Iterator;
import java.util.NoSuchElementException;

public class RandomizedQueue<Item> implements Iterable<Item> {
	private Item[] items;
	private int size;
	private int capacity = 10;
	private int head = 0;
	private int tail = 0;

	@SuppressWarnings("unchecked")
	public RandomizedQueue() {
		this.items = (Item[]) new Object[10];
		this.size = 0;
	}

	// is the queue empty?
	public boolean isEmpty() {
		return size == 0;
	}

	// return the number of items on the queue
	public int size() {
		return size;
	}

	// add the item
	public void enqueue(Item item) {
		if (item == null)
			throw new NullPointerException();

		if (tail == capacity)
			resize(2 * capacity);

		size++;
		items[tail++] = item;
	}

	// Resizing array
	private void resize(int capacity) {
		this.capacity = capacity;

		@SuppressWarnings("unchecked")
		Item[] copy = (Item[]) new Object[capacity];

		int i = 0;
		for (int j = head; j < tail; i++, j++)
			copy[i] = items[head++];

		tail = i;
		head = 0;
		items = copy;

	}

	// delete and return a random item
	public Item dequeue() {
		if (size == 0)
			throw new NoSuchElementException();

		int random = StdRandom.uniform(head, tail);

		Item item = items[random];

		items[random] = items[head++];
		items[head - 1] = null;
		size--;

		if (size > 0 && size == items.length / 4)
			resize(items.length / 2);

		return item;
	}

	// return (but do not delete) a random item
	public Item sample() {
		if (size == 0)
			throw new NoSuchElementException();

		int random = StdRandom.uniform(head, tail);
		return items[random];
	}

	// return an independent iterator over items in random order
	public Iterator<Item> iterator() {
		return new ListIterator();
	}

	private class ListIterator implements Iterator<Item> {

		private Item[] tempItems = items.clone();
		private int tempTail = tail;
		private int tempHead = head;
		private int tempSize = size;

		public boolean hasNext() {
			return tempSize != 0 && tempHead != tempTail;
		}

		public Item next() {
			if (!hasNext())
				throw new NoSuchElementException();

			int random = StdRandom.uniform(tempHead, tempTail);

			Item item = tempItems[random];
			tempItems[random] = tempItems[tempHead++];
			tempItems[tempHead - 1] = null;
			tempSize--;
			return item;
		}

		public void remove() {
			throw new UnsupportedOperationException();
		}
	}

	/*
	 * private String toString() { // TODO Auto-generated method stub return
	 * Arrays.toString((Object[]) items); }
	 */

	// unit testing
	public static void main(String[] args) {
	}
}


text:
package com.flipkart.foxtrot.core.querystore.query;

import com.flipkart.foxtrot.common.query.Filter;
import com.flipkart.foxtrot.common.query.FilterCombinerType;
import com.flipkart.foxtrot.common.query.FilterVisitor;
import com.flipkart.foxtrot.common.query.datetime.LastFilter;
import com.flipkart.foxtrot.common.query.datetime.TimeWindow;
import com.flipkart.foxtrot.common.query.general.*;
import com.flipkart.foxtrot.common.query.numeric.*;
import com.flipkart.foxtrot.common.query.string.ContainsFilter;
import org.elasticsearch.index.query.*;

import java.util.List;

/**
 * User: Santanu Sinha (santanu.sinha@flipkart.com)
 * Date: 14/03/14
 * Time: 2:31 PM
 */
public class ElasticSearchQueryGenerator extends FilterVisitor {
    private final BoolFilterBuilder boolFilterBuilder;
    private final FilterCombinerType combinerType;

    public ElasticSearchQueryGenerator(FilterCombinerType combinerType) {
        this.boolFilterBuilder = FilterBuilders.boolFilter();
        this.combinerType = combinerType;
    }

    @Override
    public void visit(BetweenFilter betweenFilter) throws Exception {
        addFilter(FilterBuilders.rangeFilter(betweenFilter.getField())
                .from(betweenFilter.getFrom())
                .to(betweenFilter.getTo())
                .cache(!betweenFilter.isTemporal()));
    }

    @Override
    public void visit(EqualsFilter equalsFilter) throws Exception {
        addFilter(FilterBuilders.termFilter(equalsFilter.getField(), equalsFilter.getValue()));
    }

    @Override
    public void visit(NotEqualsFilter notEqualsFilter) throws Exception {
        addFilter(FilterBuilders.boolFilter().mustNot(
                FilterBuilders.termFilter(notEqualsFilter.getField(), notEqualsFilter.getValue())));
    }

    @Override
    public void visit(ContainsFilter stringContainsFilterElement) throws Exception {
        addFilter(
                FilterBuilders.queryFilter(
                QueryBuilders.queryString(
                        stringContainsFilterElement.getValue())
                        .defaultField(stringContainsFilterElement.getField() + ".analyzed"))
                .cache(false));
    }

    @Override
    public void visit(GreaterThanFilter greaterThanFilter) throws Exception {
        addFilter(
                FilterBuilders.rangeFilter(greaterThanFilter.getField())
                        .gt(greaterThanFilter.getValue())
                        .cache(!greaterThanFilter.isTemporal()));
    }

    @Override
    public void visit(GreaterEqualFilter greaterEqualFilter) throws Exception {
        addFilter(
                FilterBuilders.rangeFilter(greaterEqualFilter.getField())
                        .gte(greaterEqualFilter.getValue())
                        .cache(!greaterEqualFilter.isTemporal()));
    }

    @Override
    public void visit(LessThanFilter lessThanFilter) throws Exception {
        addFilter(
                FilterBuilders.rangeFilter(lessThanFilter.getField())
                        .lt(lessThanFilter.getValue())
                        .cache(!lessThanFilter.isTemporal()));

    }

    @Override
    public void visit(LessEqualFilter lessEqualFilter) throws Exception {
        addFilter(
                FilterBuilders.rangeFilter(lessEqualFilter.getField())
                        .lte(lessEqualFilter.getValue())
                        .cache(!lessEqualFilter.isTemporal()));

    }

    @Override
    public void visit(AnyFilter anyFilter) throws Exception {
        addFilter(FilterBuilders.matchAllFilter());
    }

    @Override
    public void visit(InFilter inFilter) throws Exception {
        addFilter(
                FilterBuilders.inFilter(inFilter.getField(), inFilter.getValues()));
    }

    @Override
    public void visit(ExistsFilter existsFilter) throws Exception {
        addFilter(FilterBuilders.existsFilter(existsFilter.getField()));
    }

    public void visit(LastFilter lastFilter) throws Exception {
        TimeWindow timeWindow = lastFilter.getWindow();
        addFilter(
                FilterBuilders.rangeFilter(lastFilter.getField())
                        .from(timeWindow.getStartTime())
                        .to(timeWindow.getEndTime())
                        .cache(false));
    }

    @Override public void visit(MissingFilter missingFilter) throws Exception {
        addFilter(FilterBuilders.missingFilter(missingFilter.getField()));
    }

    private void addFilter(FilterBuilder elasticSearchFilter) throws Exception {
        if (combinerType == FilterCombinerType.and) {
            boolFilterBuilder.must(elasticSearchFilter);
            return;
        }
        //boolFilterBuilder.should(elasticSearchFilter);
        throw new UnsupportedOperationException(FilterCombinerType.or.name() + " is not supported");
    }

    public QueryBuilder genFilter(List<Filter> filters) throws Exception {
        for (Filter filter : filters) {
            filter.accept(this);
        }
        return QueryBuilders.constantScoreQuery(boolFilterBuilder);
    }

}


text:
class CMediaplayer : public CWnd
{
protected:
	DECLARE_DYNCREATE(CMediaplayer)
public:
	CLSID const& GetClsid()
	{
		static CLSID const clsid
			= { 0x6BF52A52, 0x394A, 0x11D3, { 0xB1, 0x53, 0x0, 0xC0, 0x4F, 0x79, 0xFA, 0xA6 } };
		return clsid;
	}
	virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle,
						const RECT& rect, CWnd* pParentWnd, UINT nID,
						CCreateContext* pContext = NULL)
	{
		return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID);
	}

    BOOL Create(LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd,
				UINT nID, CFile* pPersist = NULL, BOOL bStorage = FALSE,
				BSTR bstrLicKey = NULL)
	{
		return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID,
		pPersist, bStorage, bstrLicKey);
	}

// Attributes
public:
enum
{
    amvUninitialized = 0,
    amvLoading = 1,
    amvInteractive = 3,
    amvComplete = 4
}ReadyStateConstants;
enum
{
    mpStopped = 0,
    mpPaused = 1,
    mpPlaying = 2,
    mpWaiting = 3,
    mpScanForward = 4,
    mpScanReverse = 5,
    mpClosed = 6
}MPPlayStateConstants;
enum
{
    mpDefaultSize = 0,
    mpHalfSize = 1,
    mpDoubleSize = 2,
    mpFullScreen = 3,
    mpFitToSize = 4,
    mpOneSixteenthScreen = 5,
    mpOneFourthScreen = 6,
    mpOneHalfScreen = 7
}MPDisplaySizeConstants;
enum
{
    mpReadyStateUninitialized = 0,
    mpReadyStateLoading = 1,
    mpReadyStateInteractive = 3,
    mpReadyStateComplete = 4
}MPReadyStateConstants;
enum
{
    mpTime = 0,
    mpFrames = 1
}MPDisplayModeConstants;
enum
{
    mpShowURL = 0,
    mpClipURL = 1,
    mpBannerURL = 2
}MPMoreInfoType;
enum
{
    mpShowFilename = 0,
    mpShowTitle = 1,
    mpShowAuthor = 2,
    mpShowCopyright = 3,
    mpShowRating = 4,
    mpShowDescription = 5,
    mpShowLogoIcon = 6,
    mpClipFilename = 7,
    mpClipTitle = 8,
    mpClipAuthor = 9,
    mpClipCopyright = 10,
    mpClipRating = 11,
    mpClipDescription = 12,
    mpClipLogoIcon = 13,
    mpBannerImage = 14,
    mpBannerMoreInfo = 15,
    mpWatermark = 16
}MPMediaInfoType;
enum
{
    dvdMenu_Title = 2,
    dvdMenu_Root = 3,
    dvdMenu_Subpicture = 4,
    dvdMenu_Audio = 5,
    dvdMenu_Angle = 6,
    dvdMenu_Chapter = 7
}DVDMenuIDConstants;
enum
{
    mpShowDialogHelp = 0,
    mpShowDialogStatistics = 1,
    mpShowDialogOptions = 2,
    mpShowDialogContextMenu = 3
}MPShowDialogConstants;

// Operations
public:

};