text:
/*
 * This file is subject to the terms and conditions defined in
 * file 'LICENSE', which is part of this source code package.
 *
 * @author Christopher Armenio
 */
#include "cxa_mqtt_message_pingResponse.h"

// ******** includes ********
#include <cxa_assert.h>

// ******** local macro definitions ********

// ******** local type definitions ********

// ******** local function prototypes ********

// ********  local variable declarations *********

// ******** global function implementations ********
bool cxa_mqtt_message_pingResponse_init(cxa_mqtt_message_t *const msgIn)
{
	cxa_assert(msgIn);

	// fixed header 1
	if( !cxa_linkedField_initRoot_fixedLen(&msgIn->field_packetTypeAndFlags, msgIn->buffer, 0, 1) ||
			!cxa_linkedField_append_uint8(&msgIn->field_packetTypeAndFlags, (CXA_MQTT_MSGTYPE_PINGRESP << 4) ) ) return false;

	// remaining length
	if( !cxa_linkedField_initChild(&msgIn->field_remainingLength, &msgIn->field_packetTypeAndFlags, 0) ) return false;

	msgIn->areFieldsConfigured = true;
	return true;
}

bool cxa_mqtt_message_pingResponse_validateReceivedBytes(cxa_mqtt_message_t *const msgIn)
{
	cxa_assert(msgIn);

	// @TODO should probably make sure there aren't any following bytes (per spec)

	return true;
}

// ******** local function implementations ********


text:
echo Note: this new demo script is not yet making use of the $BIN, $DATA structure.
echo Take care to avoid re-downloading and training data you already have locally.
echo Edit script to remove this safety message and exit.
exit 1

###############################################################################################
#
# Script for training good word and phrase vector model using public corpora, version 1.0.
# The training time will be from several hours to about a day.
#
# Downloads about 8 billion words, makes phrases using two runs of word2phrase, trains
# a 500-dimensional vector model and evaluates it on word and phrase analogy tasks.
#
###############################################################################################

# This function will convert text to lowercase and remove special characters
normalize_text() {
  awk '{print tolower($0);}' | sed -e "s/'/'/g" -e "s/′/'/g" -e "s/''/ /g" -e "s/'/ ' /g" -e "s/"/\"/g" -e "s/"/\"/g" \
  -e 's/"/ " /g' -e 's/\./ \. /g' -e 's/<br \/>/ /g' -e 's/, / , /g' -e 's/(/ ( /g' -e 's/)/ ) /g' -e 's/\!/ \! /g' \
  -e 's/\?/ \? /g' -e 's/\;/ /g' -e 's/\:/ /g' -e 's/-/ - /g' -e 's/=/ /g' -e 's/=/ /g' -e 's/*/ /g' -e 's/|/ /g' \
  -e 's/«/ /g' | tr 0-9 " "
}

mkdir word2vec
cd word2vec

wget http://www.statmt.org/wmt14/training-monolingual-news-crawl/news.2012.en.shuffled.gz
wget http://www.statmt.org/wmt14/training-monolingual-news-crawl/news.2013.en.shuffled.gz
gzip -d news.2012.en.shuffled.gz
gzip -d news.2013.en.shuffled.gz
normalize_text < news.2012.en.shuffled > data.txt
normalize_text < news.2013.en.shuffled >> data.txt

wget http://www.statmt.org/lm-benchmark/1-billion-word-language-modeling-benchmark-r13output.tar.gz
tar -xvf 1-billion-word-language-modeling-benchmark-r13output.tar.gz
for i in `ls 1-billion-word-language-modeling-benchmark-r13output/training-monolingual.tokenized.shuffled`; do
  normalize_text < 1-billion-word-language-modeling-benchmark-r13output/training-monolingual.tokenized.shuffled/$i >> data.txt
done

wget http://ebiquity.umbc.edu/redirect/to/resource/id/351/UMBC-webbase-corpus
tar -zxvf umbc_webbase_corpus.tar.gz webbase_all/*.txt
for i in `ls webbase_all`; do
  normalize_text < webbase_all/$i >> data.txt
done

wget http://dumps.wikimedia.org/enwiki/latest/enwiki-latest-pages-articles.xml.bz2
bzip2 -c -d enwiki-latest-pages-articles.xml.bz2 | awk '{print tolower($0);}' | perl -e '
# Program to filter Wikipedia XML dumps to "clean" text consisting only of lowercase
# letters (a-z, converted from A-Z), and spaces (never consecutive)...
# All other characters are converted to spaces.  Only text which normally appears.
# in the web browser is displayed.  Tables are removed.  Image captions are.
# preserved.  Links are converted to normal text.  Digits are spelled out.
# *** Modified to not spell digits or throw away non-ASCII characters ***

# Written by Matt Mahoney, June 10, 2006.  This program is released to the public domain.

$/=">";                     # input record separator
while (<>) {
  if (/<text /) {$text=1;}  # remove all but between <text> ... </text>
  if (/#redirect/i) {$text=0;}  # remove #REDIRECT
  if ($text) {

    # Remove any text not normally visible
    if (/<\/text>/) {$text=0;}
    s/<.*>//;               # remove xml tags
    s/&/&/g;            # decode URL encoded chars
    s/</</g;
    s/>/>/g;
    s/<ref[^<]*<\/ref>//g;  # remove references <ref...> ... </ref>
    s/<[^>]*>//g;           # remove xhtml tags
    s/\[http:[^] ]*/[/g;    # remove normal url, preserve visible text
    s/\|thumb//ig;          # remove images links, preserve caption
    s/\|left//ig;
    s/\|right//ig;
    s/\|\d+px//ig;
    s/\[\[image:[^\[\]]*\|//ig;
    s/\[\[category:([^|\]]*)[^]]*\]\]/[[$1]]/ig;  # show categories without markup
    s/\[\[[a-z\-]*:[^\]]*\]\]//g;  # remove links to other languages
    s/\[\[[^\|\]]*\|/[[/g;  # remove wiki url, preserve visible text
    s/{{[^}]*}}//g;         # remove {{icons}} and {tables}
    s/{[^}]*}//g;
    s/\[//g;                # remove [ and ]
    s/\]//g;
    s/&[^;]*;/ /g;          # remove URL encoded chars

    $_=" $_ ";
    chop;
    print $_;
  }
}
' | normalize_text | awk '{if (NF>1) print;}' >> data.txt

wget http://word2vec.googlecode.com/svn/trunk/word2vec.c
wget http://word2vec.googlecode.com/svn/trunk/word2phrase.c
wget http://word2vec.googlecode.com/svn/trunk/compute-accuracy.c
wget http://word2vec.googlecode.com/svn/trunk/questions-words.txt
wget http://word2vec.googlecode.com/svn/trunk/questions-phrases.txt
gcc word2vec.c -o word2vec -lm -pthread -O3 -march=native -funroll-loops
gcc word2phrase.c -o word2phrase -lm -pthread -O3 -march=native -funroll-loops
gcc compute-accuracy.c -o compute-accuracy -lm -pthread -O3 -march=native -funroll-loops
./word2phrase -train data.txt -output data-phrase.txt -threshold 200 -debug 2
./word2phrase -train data-phrase.txt -output data-phrase2.txt -threshold 100 -debug 2
./word2vec -train data-phrase2.txt -output vectors.bin -cbow 1 -size 500 -window 10 -negative 10 -hs 0 -sample 1e-5 -threads 40 -binary 1 -iter 3 -min-count 10
./compute-accuracy vectors.bin 400000 < questions-words.txt     # should get to almost 78% accuracy on 99.7% of questions
./compute-accuracy vectors.bin 1000000 < questions-phrases.txt  # about 78% accuracy with 77% coverage

redpajama_set_name: RedPajamaGithub


text:
package com.sun.tools.ws.processor.generator;

import com.sun.tools.ws.processor.ProcessorException;

/**
 *
 * @author WS Development Team
 */
public class GeneratorException extends ProcessorException {

    private static final long serialVersionUID = 1459715621872011795L;

    public GeneratorException(String key, Object... args) {
        super(key, args);
    }

    public GeneratorException(Throwable throwable) {
        super(throwable);
    }

    @Override
    public String getDefaultResourceBundleName() {
        return "com.sun.tools.ws.resources.generator";
    }
}


text:
_packages="dev-lang/python dev-python/pip"
#_keep_headers=true

#
# This hook is called just before starting the build of the root fs
#
configure_rootfs_build()
{
    echo 'PYTHON_TARGETS="python3_4"' >> /etc/portage/make.conf
    echo 'PYTHON_SINGLE_TARGET="python3_4"' >> /etc/portage/make.conf
    echo 'USE_PYTHON="3.4"' >> /etc/portage/make.conf
    update_use '+sqlite'
}

#
# This hook is called just before packaging the root fs tar ball, ideal for any post-install tasks, clean up, etc
#
finish_rootfs_build()
{
    :
}


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.resourcehealth.implementation;

import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
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.PathParam;
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.resourcehealth.fluent.AvailabilityStatusesClient;
import com.azure.resourcemanager.resourcehealth.fluent.models.AvailabilityStatusInner;
import com.azure.resourcemanager.resourcehealth.models.AvailabilityStatusListResult;
import reactor.core.publisher.Mono;

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

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

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

    /**
     * The interface defining all the services for MicrosoftResourceHealthAvailabilityStatuses to be used by the proxy
     * service to perform REST calls.
     */
    @Host("{$host}")
    @ServiceInterface(name = "MicrosoftResourceHea")
    private interface AvailabilityStatusesService {
        @Headers({"Content-Type: application/json"})
        @Get("/subscriptions/{subscriptionId}/providers/Microsoft.ResourceHealth/availabilityStatuses")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<AvailabilityStatusListResult>> listBySubscriptionId(
            @HostParam("$host") String endpoint,
            @QueryParam("api-version") String apiVersion,
            @QueryParam("$filter") String filter,
            @PathParam("subscriptionId") String subscriptionId,
            @QueryParam("$expand") String expand,
            @HeaderParam("Accept") String accept,
            Context context);

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

        @Headers({"Content-Type: application/json"})
        @Get("/{resourceUri}/providers/Microsoft.ResourceHealth/availabilityStatuses/current")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<AvailabilityStatusInner>> getByResource(
            @HostParam("$host") String endpoint,
            @PathParam(value = "resourceUri", encoded = true) String resourceUri,
            @QueryParam("api-version") String apiVersion,
            @QueryParam("$filter") String filter,
            @QueryParam("$expand") String expand,
            @HeaderParam("Accept") String accept,
            Context context);

        @Headers({"Content-Type: application/json"})
        @Get("/{resourceUri}/providers/Microsoft.ResourceHealth/availabilityStatuses")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<AvailabilityStatusListResult>> list(
            @HostParam("$host") String endpoint,
            @PathParam(value = "resourceUri", encoded = true) String resourceUri,
            @QueryParam("api-version") String apiVersion,
            @QueryParam("$filter") String filter,
            @QueryParam("$expand") String expand,
            @HeaderParam("Accept") String accept,
            Context context);

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

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

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

    /**
     * Lists the current availability status for all the resources in the subscription.
     *
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response along with {@link PagedResponse} on successful completion
     *     of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<AvailabilityStatusInner>> listBySubscriptionIdSinglePageAsync(
        String filter, String expand) {
        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."));
        }
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .listBySubscriptionId(
                            this.client.getEndpoint(),
                            this.client.getApiVersion(),
                            filter,
                            this.client.getSubscriptionId(),
                            expand,
                            accept,
                            context))
            .<PagedResponse<AvailabilityStatusInner>>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 the current availability status for all the resources in the subscription.
     *
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response along with {@link PagedResponse} on successful completion
     *     of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<AvailabilityStatusInner>> listBySubscriptionIdSinglePageAsync(
        String filter, String expand, 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."));
        }
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .listBySubscriptionId(
                this.client.getEndpoint(),
                this.client.getApiVersion(),
                filter,
                this.client.getSubscriptionId(),
                expand,
                accept,
                context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null));
    }

    /**
     * Lists the current availability status for all the resources in the subscription.
     *
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response as paginated response with {@link PagedFlux}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<AvailabilityStatusInner> listBySubscriptionIdAsync(String filter, String expand) {
        return new PagedFlux<>(
            () -> listBySubscriptionIdSinglePageAsync(filter, expand),
            nextLink -> listBySubscriptionIdNextSinglePageAsync(nextLink));
    }

    /**
     * Lists the current availability status for all the resources in the 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 the List availabilityStatus operation response as paginated response with {@link PagedFlux}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<AvailabilityStatusInner> listBySubscriptionIdAsync() {
        final String filter = null;
        final String expand = null;
        return new PagedFlux<>(
            () -> listBySubscriptionIdSinglePageAsync(filter, expand),
            nextLink -> listBySubscriptionIdNextSinglePageAsync(nextLink));
    }

    /**
     * Lists the current availability status for all the resources in the subscription.
     *
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response as paginated response with {@link PagedFlux}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<AvailabilityStatusInner> listBySubscriptionIdAsync(
        String filter, String expand, Context context) {
        return new PagedFlux<>(
            () -> listBySubscriptionIdSinglePageAsync(filter, expand, context),
            nextLink -> listBySubscriptionIdNextSinglePageAsync(nextLink, context));
    }

    /**
     * Lists the current availability status for all the resources in the 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 the List availabilityStatus operation response as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<AvailabilityStatusInner> listBySubscriptionId() {
        final String filter = null;
        final String expand = null;
        return new PagedIterable<>(listBySubscriptionIdAsync(filter, expand));
    }

    /**
     * Lists the current availability status for all the resources in the subscription.
     *
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<AvailabilityStatusInner> listBySubscriptionId(String filter, String expand, Context context) {
        return new PagedIterable<>(listBySubscriptionIdAsync(filter, expand, context));
    }

    /**
     * Lists the current availability status for all the resources in the resource group.
     *
     * @param resourceGroupName The name of the resource group.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response along with {@link PagedResponse} on successful completion
     *     of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<AvailabilityStatusInner>> listByResourceGroupSinglePageAsync(
        String resourceGroupName, String filter, String expand) {
        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."));
        }
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .listByResourceGroup(
                            this.client.getEndpoint(),
                            this.client.getSubscriptionId(),
                            resourceGroupName,
                            this.client.getApiVersion(),
                            filter,
                            expand,
                            accept,
                            context))
            .<PagedResponse<AvailabilityStatusInner>>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 the current availability status for all the resources in the resource group.
     *
     * @param resourceGroupName The name of the resource group.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response along with {@link PagedResponse} on successful completion
     *     of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<AvailabilityStatusInner>> listByResourceGroupSinglePageAsync(
        String resourceGroupName, String filter, String expand, 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."));
        }
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .listByResourceGroup(
                this.client.getEndpoint(),
                this.client.getSubscriptionId(),
                resourceGroupName,
                this.client.getApiVersion(),
                filter,
                expand,
                accept,
                context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null));
    }

    /**
     * Lists the current availability status for all the resources in the resource group.
     *
     * @param resourceGroupName The name of the resource group.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response as paginated response with {@link PagedFlux}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<AvailabilityStatusInner> listByResourceGroupAsync(
        String resourceGroupName, String filter, String expand) {
        return new PagedFlux<>(
            () -> listByResourceGroupSinglePageAsync(resourceGroupName, filter, expand),
            nextLink -> listByResourceGroupNextSinglePageAsync(nextLink));
    }

    /**
     * Lists the current availability status for all the resources in the resource group.
     *
     * @param resourceGroupName The name of the resource group.
     * @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 List availabilityStatus operation response as paginated response with {@link PagedFlux}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<AvailabilityStatusInner> listByResourceGroupAsync(String resourceGroupName) {
        final String filter = null;
        final String expand = null;
        return new PagedFlux<>(
            () -> listByResourceGroupSinglePageAsync(resourceGroupName, filter, expand),
            nextLink -> listByResourceGroupNextSinglePageAsync(nextLink));
    }

    /**
     * Lists the current availability status for all the resources in the resource group.
     *
     * @param resourceGroupName The name of the resource group.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response as paginated response with {@link PagedFlux}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<AvailabilityStatusInner> listByResourceGroupAsync(
        String resourceGroupName, String filter, String expand, Context context) {
        return new PagedFlux<>(
            () -> listByResourceGroupSinglePageAsync(resourceGroupName, filter, expand, context),
            nextLink -> listByResourceGroupNextSinglePageAsync(nextLink, context));
    }

    /**
     * Lists the current availability status for all the resources in the resource group.
     *
     * @param resourceGroupName The name of the resource group.
     * @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 List availabilityStatus operation response as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<AvailabilityStatusInner> listByResourceGroup(String resourceGroupName) {
        final String filter = null;
        final String expand = null;
        return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, filter, expand));
    }

    /**
     * Lists the current availability status for all the resources in the resource group.
     *
     * @param resourceGroupName The name of the resource group.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<AvailabilityStatusInner> listByResourceGroup(
        String resourceGroupName, String filter, String expand, Context context) {
        return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, filter, expand, context));
    }

    /**
     * Gets current availability status for a single resource.
     *
     * @param resourceUri The fully qualified ID of the resource, including the resource name and resource type.
     *     Currently the API support not nested and one nesting level resource types :
     *     /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
     *     and
     *     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 current availability status for a single resource along with {@link Response} on successful completion of
     *     {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<AvailabilityStatusInner>> getByResourceWithResponseAsync(
        String resourceUri, String filter, String expand) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceUri == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null."));
        }
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .getByResource(
                            this.client.getEndpoint(),
                            resourceUri,
                            this.client.getApiVersion(),
                            filter,
                            expand,
                            accept,
                            context))
            .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
    }

    /**
     * Gets current availability status for a single resource.
     *
     * @param resourceUri The fully qualified ID of the resource, including the resource name and resource type.
     *     Currently the API support not nested and one nesting level resource types :
     *     /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
     *     and
     *     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 current availability status for a single resource along with {@link Response} on successful completion of
     *     {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<AvailabilityStatusInner>> getByResourceWithResponseAsync(
        String resourceUri, String filter, String expand, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceUri == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null."));
        }
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .getByResource(
                this.client.getEndpoint(), resourceUri, this.client.getApiVersion(), filter, expand, accept, context);
    }

    /**
     * Gets current availability status for a single resource.
     *
     * @param resourceUri The fully qualified ID of the resource, including the resource name and resource type.
     *     Currently the API support not nested and one nesting level resource types :
     *     /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
     *     and
     *     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 current availability status for a single resource on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<AvailabilityStatusInner> getByResourceAsync(String resourceUri, String filter, String expand) {
        return getByResourceWithResponseAsync(resourceUri, filter, expand)
            .flatMap(
                (Response<AvailabilityStatusInner> res) -> {
                    if (res.getValue() != null) {
                        return Mono.just(res.getValue());
                    } else {
                        return Mono.empty();
                    }
                });
    }

    /**
     * Gets current availability status for a single resource.
     *
     * @param resourceUri The fully qualified ID of the resource, including the resource name and resource type.
     *     Currently the API support not nested and one nesting level resource types :
     *     /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
     *     and
     *     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}.
     * @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 current availability status for a single resource on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<AvailabilityStatusInner> getByResourceAsync(String resourceUri) {
        final String filter = null;
        final String expand = null;
        return getByResourceWithResponseAsync(resourceUri, filter, expand)
            .flatMap(
                (Response<AvailabilityStatusInner> res) -> {
                    if (res.getValue() != null) {
                        return Mono.just(res.getValue());
                    } else {
                        return Mono.empty();
                    }
                });
    }

    /**
     * Gets current availability status for a single resource.
     *
     * @param resourceUri The fully qualified ID of the resource, including the resource name and resource type.
     *     Currently the API support not nested and one nesting level resource types :
     *     /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
     *     and
     *     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}.
     * @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 current availability status for a single resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public AvailabilityStatusInner getByResource(String resourceUri) {
        final String filter = null;
        final String expand = null;
        return getByResourceAsync(resourceUri, filter, expand).block();
    }

    /**
     * Gets current availability status for a single resource.
     *
     * @param resourceUri The fully qualified ID of the resource, including the resource name and resource type.
     *     Currently the API support not nested and one nesting level resource types :
     *     /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
     *     and
     *     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 current availability status for a single resource along with {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Response<AvailabilityStatusInner> getByResourceWithResponse(
        String resourceUri, String filter, String expand, Context context) {
        return getByResourceWithResponseAsync(resourceUri, filter, expand, context).block();
    }

    /**
     * Lists all historical availability transitions and impacting events for a single resource.
     *
     * @param resourceUri The fully qualified ID of the resource, including the resource name and resource type.
     *     Currently the API support not nested and one nesting level resource types :
     *     /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
     *     and
     *     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response along with {@link PagedResponse} on successful completion
     *     of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<AvailabilityStatusInner>> listSinglePageAsync(
        String resourceUri, String filter, String expand) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceUri == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null."));
        }
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .list(
                            this.client.getEndpoint(),
                            resourceUri,
                            this.client.getApiVersion(),
                            filter,
                            expand,
                            accept,
                            context))
            .<PagedResponse<AvailabilityStatusInner>>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 all historical availability transitions and impacting events for a single resource.
     *
     * @param resourceUri The fully qualified ID of the resource, including the resource name and resource type.
     *     Currently the API support not nested and one nesting level resource types :
     *     /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
     *     and
     *     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response along with {@link PagedResponse} on successful completion
     *     of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<AvailabilityStatusInner>> listSinglePageAsync(
        String resourceUri, String filter, String expand, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceUri == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null."));
        }
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .list(this.client.getEndpoint(), resourceUri, this.client.getApiVersion(), filter, expand, accept, context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null));
    }

    /**
     * Lists all historical availability transitions and impacting events for a single resource.
     *
     * @param resourceUri The fully qualified ID of the resource, including the resource name and resource type.
     *     Currently the API support not nested and one nesting level resource types :
     *     /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
     *     and
     *     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response as paginated response with {@link PagedFlux}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<AvailabilityStatusInner> listAsync(String resourceUri, String filter, String expand) {
        return new PagedFlux<>(
            () -> listSinglePageAsync(resourceUri, filter, expand), nextLink -> listNextSinglePageAsync(nextLink));
    }

    /**
     * Lists all historical availability transitions and impacting events for a single resource.
     *
     * @param resourceUri The fully qualified ID of the resource, including the resource name and resource type.
     *     Currently the API support not nested and one nesting level resource types :
     *     /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
     *     and
     *     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}.
     * @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 List availabilityStatus operation response as paginated response with {@link PagedFlux}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<AvailabilityStatusInner> listAsync(String resourceUri) {
        final String filter = null;
        final String expand = null;
        return new PagedFlux<>(
            () -> listSinglePageAsync(resourceUri, filter, expand), nextLink -> listNextSinglePageAsync(nextLink));
    }

    /**
     * Lists all historical availability transitions and impacting events for a single resource.
     *
     * @param resourceUri The fully qualified ID of the resource, including the resource name and resource type.
     *     Currently the API support not nested and one nesting level resource types :
     *     /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
     *     and
     *     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response as paginated response with {@link PagedFlux}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<AvailabilityStatusInner> listAsync(
        String resourceUri, String filter, String expand, Context context) {
        return new PagedFlux<>(
            () -> listSinglePageAsync(resourceUri, filter, expand, context),
            nextLink -> listNextSinglePageAsync(nextLink, context));
    }

    /**
     * Lists all historical availability transitions and impacting events for a single resource.
     *
     * @param resourceUri The fully qualified ID of the resource, including the resource name and resource type.
     *     Currently the API support not nested and one nesting level resource types :
     *     /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
     *     and
     *     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}.
     * @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 List availabilityStatus operation response as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<AvailabilityStatusInner> list(String resourceUri) {
        final String filter = null;
        final String expand = null;
        return new PagedIterable<>(listAsync(resourceUri, filter, expand));
    }

    /**
     * Lists all historical availability transitions and impacting events for a single resource.
     *
     * @param resourceUri The fully qualified ID of the resource, including the resource name and resource type.
     *     Currently the API support not nested and one nesting level resource types :
     *     /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
     *     and
     *     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}.
     * @param filter The filter to apply on the operation. For more information please see
     *     https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN.
     * @param expand Setting $expand=recommendedactions in url query expands the recommendedactions in the response.
     * @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 List availabilityStatus operation response as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<AvailabilityStatusInner> list(
        String resourceUri, String filter, String expand, Context context) {
        return new PagedIterable<>(listAsync(resourceUri, filter, expand, context));
    }

    /**
     * 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 the List availabilityStatus operation response along with {@link PagedResponse} on successful completion
     *     of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<AvailabilityStatusInner>> listBySubscriptionIdNextSinglePageAsync(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.listBySubscriptionIdNext(nextLink, this.client.getEndpoint(), accept, context))
            .<PagedResponse<AvailabilityStatusInner>>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 the List availabilityStatus operation response along with {@link PagedResponse} on successful completion
     *     of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<AvailabilityStatusInner>> listBySubscriptionIdNextSinglePageAsync(
        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
            .listBySubscriptionIdNext(nextLink, this.client.getEndpoint(), accept, 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 the List availabilityStatus operation response along with {@link PagedResponse} on successful completion
     *     of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<AvailabilityStatusInner>> listByResourceGroupNextSinglePageAsync(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.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context))
            .<PagedResponse<AvailabilityStatusInner>>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 the List availabilityStatus operation response along with {@link PagedResponse} on successful completion
     *     of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<AvailabilityStatusInner>> listByResourceGroupNextSinglePageAsync(
        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
            .listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, 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 the List availabilityStatus operation response along with {@link PagedResponse} on successful completion
     *     of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<AvailabilityStatusInner>> listNextSinglePageAsync(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.listNext(nextLink, this.client.getEndpoint(), accept, context))
            .<PagedResponse<AvailabilityStatusInner>>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 the List availabilityStatus operation response along with {@link PagedResponse} on successful completion
     *     of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<AvailabilityStatusInner>> listNextSinglePageAsync(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
            .listNext(nextLink, this.client.getEndpoint(), accept, context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null));
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.execution;

import com.facebook.presto.Session;
import com.facebook.presto.event.query.QueryMonitor;
import com.facebook.presto.execution.QueryExecution.QueryExecutionFactory;
import com.facebook.presto.execution.StateMachine.StateChangeListener;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.sql.parser.ParsingException;
import com.facebook.presto.sql.parser.SqlParser;
import com.facebook.presto.sql.tree.Statement;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture;
import io.airlift.concurrent.AsyncSemaphore;
import io.airlift.concurrent.SetThreadName;
import io.airlift.concurrent.ThreadPoolExecutorMBean;
import io.airlift.log.Logger;
import io.airlift.units.Duration;
import org.joda.time.DateTime;
import org.weakref.jmx.Flatten;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;

import javax.annotation.PreDestroy;
import javax.annotation.concurrent.ThreadSafe;
import javax.inject.Inject;

import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

import static com.facebook.presto.SystemSessionProperties.isBigQueryEnabled;
import static com.facebook.presto.spi.StandardErrorCode.QUERY_QUEUE_FULL;
import static com.facebook.presto.spi.StandardErrorCode.USER_CANCELED;
import static com.facebook.presto.util.ImmutableCollectors.toImmutableList;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.airlift.concurrent.Threads.threadsNamed;
import static java.util.concurrent.Executors.newCachedThreadPool;

@ThreadSafe
public class SqlQueryManager
        implements QueryManager
{
    private static final Logger log = Logger.get(SqlQueryManager.class);

    private final SqlParser sqlParser;

    private final ExecutorService queryExecutor;
    private final ThreadPoolExecutorMBean queryExecutorMBean;
    private final QueryStarter queryStarter;

    private final int maxQueryHistory;
    private final Duration maxQueryAge;

    private final ConcurrentMap<QueryId, QueryExecution> queries = new ConcurrentHashMap<>();
    private final Queue<QueryExecution> expirationQueue = new LinkedBlockingQueue<>();

    private final Duration clientTimeout;

    private final ScheduledExecutorService queryManagementExecutor;
    private final ThreadPoolExecutorMBean queryManagementExecutorMBean;

    private final QueryMonitor queryMonitor;
    private final LocationFactory locationFactory;
    private final QueryIdGenerator queryIdGenerator;

    private final Map<Class<? extends Statement>, QueryExecutionFactory<?>> executionFactories;

    private final SqlQueryManagerStats stats = new SqlQueryManagerStats();

    @Inject
    public SqlQueryManager(
            SqlParser sqlParser,
            QueryManagerConfig config,
            QueryMonitor queryMonitor,
            QueryIdGenerator queryIdGenerator,
            LocationFactory locationFactory,
            Map<Class<? extends Statement>, QueryExecutionFactory<?>> executionFactories)
    {
        this.sqlParser = checkNotNull(sqlParser, "sqlParser is null");

        this.executionFactories = checkNotNull(executionFactories, "executionFactories is null");

        this.queryExecutor = newCachedThreadPool(threadsNamed("query-scheduler-%s"));
        this.queryExecutorMBean = new ThreadPoolExecutorMBean((ThreadPoolExecutor) queryExecutor);

        checkNotNull(config, "config is null");
        this.queryStarter = new QueryStarter(queryExecutor, stats, config);

        this.queryMonitor = checkNotNull(queryMonitor, "queryMonitor is null");
        this.locationFactory = checkNotNull(locationFactory, "locationFactory is null");
        this.queryIdGenerator = checkNotNull(queryIdGenerator, "queryIdGenerator is null");

        this.maxQueryAge = config.getMaxQueryAge();
        this.maxQueryHistory = config.getMaxQueryHistory();
        this.clientTimeout = config.getClientTimeout();

        queryManagementExecutor = Executors.newScheduledThreadPool(config.getQueryManagerExecutorPoolSize(), threadsNamed("query-management-%s"));
        queryManagementExecutorMBean = new ThreadPoolExecutorMBean((ThreadPoolExecutor) queryManagementExecutor);
        queryManagementExecutor.scheduleWithFixedDelay(new Runnable()
        {
            @Override
            public void run()
            {
                try {
                    failAbandonedQueries();
                }
                catch (Throwable e) {
                    log.warn(e, "Error cancelling abandoned queries");
                }

                try {
                    removeExpiredQueries();
                }
                catch (Throwable e) {
                    log.warn(e, "Error removing expired queries");
                }
            }
        }, 1, 1, TimeUnit.SECONDS);
    }

    @PreDestroy
    public void stop()
    {
        queryManagementExecutor.shutdownNow();
        queryExecutor.shutdownNow();
    }

    @Override
    public List<QueryId> getAllQueryIds()
    {
        return queries.values().stream()
                .map(queryExecution -> {
                    try {
                        return queryExecution.getQueryId();
                    }
                    catch (RuntimeException ignored) {
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(toImmutableList());
    }

    @Override
    public List<QueryInfo> getAllQueryInfo()
    {
        return queries.values().stream()
                .map(queryExecution -> {
                    try {
                        return queryExecution.getQueryInfo();
                    }
                    catch (RuntimeException ignored) {
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(toImmutableList());
    }

    @Override
    public Duration waitForStateChange(QueryId queryId, QueryState currentState, Duration maxWait)
            throws InterruptedException
    {
        Preconditions.checkNotNull(queryId, "queryId is null");
        Preconditions.checkNotNull(maxWait, "maxWait is null");

        QueryExecution query = queries.get(queryId);
        if (query == null) {
            return maxWait;
        }

        query.recordHeartbeat();
        return query.waitForStateChange(currentState, maxWait);
    }

    @Override
    public QueryInfo getQueryInfo(QueryId queryId)
    {
        checkNotNull(queryId, "queryId is null");

        QueryExecution query = queries.get(queryId);
        if (query == null) {
            throw new NoSuchElementException();
        }

        query.recordHeartbeat();
        return query.getQueryInfo();
    }

    @Override
    public QueryInfo createQuery(Session session, String query)
    {
        checkNotNull(query, "query is null");
        Preconditions.checkArgument(!query.isEmpty(), "query must not be empty string");

        QueryId queryId = queryIdGenerator.createNextQueryId();

        Statement statement;
        try {
            statement = sqlParser.createStatement(query);
        }
        catch (ParsingException e) {
            return createFailedQuery(session, query, queryId, e);
        }

        QueryExecutionFactory<?> queryExecutionFactory = executionFactories.get(statement.getClass());
        Preconditions.checkState(queryExecutionFactory != null, "Unsupported statement type %s", statement.getClass().getName());
        final QueryExecution queryExecution = queryExecutionFactory.createQueryExecution(queryId, query, session, statement);
        queryMonitor.createdEvent(queryExecution.getQueryInfo());

        queryExecution.addStateChangeListener(new StateChangeListener<QueryState>()
        {
            @Override
            public void stateChanged(QueryState newValue)
            {
                if (newValue.isDone()) {
                    QueryInfo info = queryExecution.getQueryInfo();

                    stats.queryFinished(info);
                    queryMonitor.completionEvent(info);
                    expirationQueue.add(queryExecution);
                }
            }
        });

        queries.put(queryId, queryExecution);

        // start the query in the background
        if (!queryStarter.submit(queryExecution)) {
            return createFailedQuery(session, query, queryId, new PrestoException(QUERY_QUEUE_FULL, "Too many queued queries!"));
        }

        return queryExecution.getQueryInfo();
    }

    @Override
    public void cancelQuery(QueryId queryId)
    {
        checkNotNull(queryId, "queryId is null");

        log.debug("Cancel query %s", queryId);

        QueryExecution query = queries.get(queryId);
        if (query != null) {
            query.fail(new PrestoException(USER_CANCELED, "Query was canceled"));
        }
    }

    @Override
    public void cancelStage(StageId stageId)
    {
        Preconditions.checkNotNull(stageId, "stageId is null");

        log.debug("Cancel stage %s", stageId);

        QueryExecution query = queries.get(stageId.getQueryId());
        if (query != null) {
            query.cancelStage(stageId);
        }
    }

    @Managed
    public int getQueryQueueSize()
    {
        return queryStarter.getQueryQueueSize();
    }

    @Managed
    public int getBigQueryQueueSize()
    {
        return queryStarter.getBigQueryQueueSize();
    }

    @Managed
    @Flatten
    public SqlQueryManagerStats getStats()
    {
        return stats;
    }

    @Managed(description = "Query scheduler executor")
    @Nested
    public ThreadPoolExecutorMBean getExecutor()
    {
        return queryExecutorMBean;
    }

    @Managed(description = "Query garbage collector executor")
    @Nested
    public ThreadPoolExecutorMBean getManagementExecutor()
    {
        return queryManagementExecutorMBean;
    }

    /**
     * Remove completed queries after a waiting period
     */
    public void removeExpiredQueries()
    {
        DateTime timeHorizon = DateTime.now().minus(maxQueryAge.toMillis());

        // we're willing to keep queries beyond timeHorizon as long as we have fewer than maxQueryHistory
        while (expirationQueue.size() > maxQueryHistory) {
            QueryInfo queryInfo = expirationQueue.peek().getQueryInfo();

            // expirationQueue is FIFO based on query end time. Stop when we see the
            // first query that's too young to expire
            if (queryInfo.getQueryStats().getEndTime().isAfter(timeHorizon)) {
                return;
            }

            // only expire them if they are older than maxQueryAge. We need to keep them
            // around for a while in case clients come back asking for status
            QueryId queryId = queryInfo.getQueryId();

            log.debug("Remove query %s", queryId);
            queries.remove(queryId);
            expirationQueue.remove();
        }
    }

    public void failAbandonedQueries()
    {
        for (QueryExecution queryExecution : queries.values()) {
            QueryInfo queryInfo = queryExecution.getQueryInfo();
            if (queryInfo.getState().isDone()) {
                continue;
            }

            if (isAbandoned(queryExecution)) {
                log.info("Failing abandoned query %s", queryExecution.getQueryInfo().getQueryId());
                queryExecution.fail(new AbandonedException("Query " + queryInfo.getQueryId(), queryInfo.getQueryStats().getLastHeartbeat(), DateTime.now()));
            }
        }
    }

    private boolean isAbandoned(QueryExecution query)
    {
        DateTime oldestAllowedHeartbeat = DateTime.now().minus(clientTimeout.toMillis());
        DateTime lastHeartbeat = query.getQueryInfo().getQueryStats().getLastHeartbeat();

        return lastHeartbeat != null && lastHeartbeat.isBefore(oldestAllowedHeartbeat);
    }

    private QueryInfo createFailedQuery(Session session, String query, QueryId queryId, Throwable cause)
    {
        URI self = locationFactory.createQueryLocation(queryId);
        QueryExecution execution = new FailedQueryExecution(queryId, query, session, self, queryExecutor, cause);

        queries.put(queryId, execution);
        stats.queryStarted();
        queryMonitor.createdEvent(execution.getQueryInfo());
        queryMonitor.completionEvent(execution.getQueryInfo());
        stats.queryFinished(execution.getQueryInfo());
        expirationQueue.add(execution);

        return execution.getQueryInfo();
    }

    /**
     * Set up a callback to fire when a query is completed. The callback will be called at most once.
     */
    private static void addCompletionCallback(QueryExecution queryExecution, Runnable callback)
    {
        AtomicBoolean taskExecuted = new AtomicBoolean();
        queryExecution.addStateChangeListener(newValue -> {
            if (newValue.isDone() && taskExecuted.compareAndSet(false, true)) {
                callback.run();
            }
        });
        // Need to do this check in case the state changed before we added the previous state change listener
        if (queryExecution.getQueryInfo().getState().isDone() && taskExecuted.compareAndSet(false, true)) {
            callback.run();
        }
    }

    @ThreadSafe
    private static class QueryStarter
    {
        private final QueryQueue queryQueue;
        private final QueryQueue bigQueryQueue;

        public QueryStarter(Executor queryExecutor, SqlQueryManagerStats stats, QueryManagerConfig config)
        {
            checkNotNull(queryExecutor, "queryExecutor is null");
            checkNotNull(stats, "stats is null");
            checkNotNull(config, "config is null");

            this.queryQueue = new QueryQueue(queryExecutor, stats, config.getMaxQueuedQueries(), config.getMaxConcurrentQueries());
            this.bigQueryQueue = new QueryQueue(queryExecutor, stats, config.getMaxQueuedBigQueries(), config.getMaxConcurrentBigQueries());
        }

        public boolean submit(QueryExecution queryExecution)
        {
            if (isBigQueryEnabled(queryExecution.getQueryInfo().getSession(), false)) {
                return bigQueryQueue.enqueue(queryExecution);
            }
            else {
                return queryQueue.enqueue(queryExecution);
            }
        }

        public int getQueryQueueSize()
        {
            return queryQueue.getQueueSize();
        }

        public int getBigQueryQueueSize()
        {
            return bigQueryQueue.getQueueSize();
        }

        private static class QueryQueue
        {
            private final int maxQueuedQueries;
            private final AtomicInteger queryQueueSize = new AtomicInteger();
            private final AsyncSemaphore<QueueEntry> asyncSemaphore;

            private QueryQueue(Executor queryExecutor, SqlQueryManagerStats stats, int maxQueuedQueries, int maxConcurrentQueries)
            {
                checkNotNull(queryExecutor, "queryExecutor is null");
                checkNotNull(stats, "stats is null");
                checkArgument(maxQueuedQueries > 0, "maxQueuedQueries must be greater than zero");
                checkArgument(maxConcurrentQueries > 0, "maxConcurrentQueries must be greater than zero");

                this.maxQueuedQueries = maxQueuedQueries;
                this.asyncSemaphore = new AsyncSemaphore<>(maxConcurrentQueries,
                        queryExecutor,
                        queueEntry -> {
                            QueryExecution queryExecution = queueEntry.dequeue();
                            if (queryExecution == null) {
                                // Entry was dequeued earlier and so this query is already done
                                return Futures.immediateFuture(null);
                            }
                            else {
                                SettableFuture<?> settableFuture = SettableFuture.create();
                                addCompletionCallback(queryExecution, () -> settableFuture.set(null));
                                if (!settableFuture.isDone()) { // Only execute if the query is not already completed (e.g. cancelled)
                                    queryExecutor.execute(() -> {
                                        try (SetThreadName setThreadName = new SetThreadName("Query-%s", queryExecution.getQueryInfo().getQueryId())) {
                                            stats.queryStarted();
                                            queryExecution.start();
                                        }
                                    });
                                }
                                return settableFuture;
                            }
                        });
            }

            public int getQueueSize()
            {
                return queryQueueSize.get();
            }

            public boolean enqueue(QueryExecution queryExecution)
            {
                if (queryQueueSize.incrementAndGet() > maxQueuedQueries) {
                    queryQueueSize.decrementAndGet();
                    return false;
                }

                QueueEntry queueEntry = new QueueEntry(queryExecution, aVoid -> queryQueueSize.decrementAndGet());
                // Add a callback to dequeue the entry if it is ever completed.
                // This enables us to remove the entry sooner if is cancelled before starting,
                // and has no effect if called after starting.
                addCompletionCallback(queryExecution, queueEntry::dequeue);
                asyncSemaphore.submit(queueEntry);
                return true;
            }

            private static class QueueEntry
            {
                private final AtomicBoolean dequeued = new AtomicBoolean();
                private final AtomicReference<QueryExecution> queryExecution;
                private final Consumer<Void> onDequeue;

                private QueueEntry(QueryExecution queryExecution, Consumer<Void> onDequeue)
                {
                    checkNotNull(queryExecution, "queryExecution is null");
                    checkNotNull(onDequeue, "onDequeue is null");

                    this.queryExecution = new AtomicReference<>(queryExecution);
                    this.onDequeue = onDequeue;
                }

                /**
                 * Can be called multiple times on the same QueueEntry, but the onDequeue Consumer will only be called once
                 * and only one caller will get the QueryExecution.
                 */
                public QueryExecution dequeue()
                {
                    if (dequeued.compareAndSet(false, true)) {
                        onDequeue.accept(null);
                    }
                    return queryExecution.getAndSet(null);
                }
            }
        }
    }
}


text:
%% Meta list
baseDir = 'data/2017-12/';
patchList = {'head2', 'legs2', 'larm', 'rarm', 'lfoot', 'rfoot','left_hand','right_hand'};
modelList = {'0093'};

%% Generate List
subDirNameList = {};
workPathList = {};
sourceNameList = {};
targetNameList = {};
for model = modelList
    for patch = patchList
        subDirNameList = [subDirNameList, patch];
        workPathList = [workPathList, fullfile(baseDir, model)];
        sourceNameList = [sourceNameList, 'template'];
        targetNameList = [targetNameList, 'target'];
    end
end

for dirIndex = 1:length(subDirNameList)

    subDirName = subDirNameList{dirIndex};
    workPath = workPathList{dirIndex};
    sourceName = sourceNameList{dirIndex};
    targetName = targetNameList{dirIndex};

    %% Set file paths
    basePath = pwd;
    subDirPath = strcat(workPath, '/', subDirName);

    outputPath = strcat(workPath, '/OUTPUT/');
    if exist(outputPath, 'dir') ~= 7
        mkdir(outputPath);
    end

    sourceFile = strcat(subDirPath, '/', sourceName, '.ply');
    % targetFile = strcat(subDirPath, '/', targetName, '.ply');
    targetFile = strcat(subDirPath, '/../', targetName, '.ply');

    sourceMarker = strcat(subDirPath, '/', sourceName, '_markers.xyz');
    targetMarker = strcat(subDirPath, '/', targetName, '_markers.xyz');

    sourceTransName = strcat(sourceName, '_transformed');
    sourceMarkerTransName = strcat(sourceName, '_markers_transformed');
    sourceFileTrans = strcat(subDirPath, '/', sourceTransName, '.ply');
    sourceMarkerTrans = strcat(subDirPath, '/', sourceMarkerTransName, '.xyz');

    % targetBoundary = strcat(subDirPath, '/', targetName, '.bd');
    targetBoundary = strcat(subDirPath, '/../', targetName, '.bd');

    %% Step 4: Remove overlaps
    cd(basePath);

    Options.ignoreBoundary = 0;
    Options.ignoreBoundaryBool = 1;
    Options.useColor = 1;
    Options.useMarker = 1;

    readData

    outFile = strcat(outputPath, subDirName, '_out.ply');
    pcOut = pcread(outFile);
    Out.vertices = double(pcOut.Location);
    Out.normals = double(pcOut.Normal);
    [~, Out.faces] = readPLY(outFile);

    %%%%
    Options.overlapDistThreshold = 2;
    Options.plot = 0;

    [OutCropped, knnDist] = removeOverlap(Out, Target, Options);

    if Options.plot
        [N,edges] = histcounts(knnDist);
        edgeLabels = cell(1, length(edges(2:end)));
        for i = 1:length(edges(2:end))
            edgeLabels{i} = num2str(edges(1 + i));
        end
        figure; pie(N, edges(2:end), edgeLabels);
    end

    % Write output
    if isfield(OutCropped, 'colors')
        writePlyVFNC(strcat(outputPath, subDirName, '_out_cropped.ply'), OutCropped.vertices, OutCropped.faces, OutCropped.normals, OutCropped.colors, 'binary_little_endian');
    else
        writePlyVFN(strcat(outputPath, subDirName, '_out_cropped.ply'), OutCropped.vertices, OutCropped.faces, OutCropped.normals, 'binary_little_endian');
    end

end


text:
var arr = [2, 3, 4, 5, 6, 5, 3, 2],  //change array elements for different cases :)
    i = 0,							// [2,1,3] will return index 0
    firstIndex;						// [2,2,3] will return last index
    								// [2,2,2] will return no such element :)
firstIndex = check(arr);
if (firstIndex >= 0) {
    console.log('First element in array that is larger than its neighbours is at position: ' + firstIndex);
} else {
    console.log('There's no such element!');
}

function check(arr) {
    var position;
    for (position = 0; position < arr.length; position += 1) {

        if (arr[position] > arr[position + 1] && arr[position] > arr[position - 1]) {
            return position;
        } else if (!position && arr[0] > arr[1]) {
            return 0;
        } else if (position === arr.length - 1 && arr[arr.length - 1] > arr[arr.length - 2]) {
            return arr.length - 1;
        }
    }
    return -1;
}


text:
package com.dt.ez.hbase.utils;

import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.util.Bytes;

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

public class TableBuilder {

	private String tbName;
	private int maxVersion = 1;
	private HBaseConfig conf;

	private List <HColumnDescriptor> cList;

	public TableBuilder (String name) {
		this.tbName = name;
	}

	public TableBuilder (String name, HBaseConfig conf) {
		this (name);
		this.conf = conf;
	}

	public TableBuilder setName (String name) {
		tbName = name;
		return this;
	}

	public TableBuilder setVersion (int version) {
		this.maxVersion = version;
		return this;
	}

	private void _checkColumnList () {
		if (null == cList) cList = new ArrayList <HColumnDescriptor> ();
	}

	public TableBuilder addColumnFamily (String cf) {
		_checkColumnList ();
		cList.add (new HColumnDescriptor (cf));
		return this;
	}

	public TableBuilder addColumnFamily (byte [] cf) {
		return addColumnFamily (Bytes.toString (cf));
	}

	public TableBuilder addColumnFamily (HColumnDescriptor cdesc) {
		_checkColumnList ();
		cList.add (cdesc);
		return this;
	}

	public TableBuilder setConf (HBaseConfig conf) {
		this.conf = conf;
		return this;
	}

	public Table getTable () throws IOException {
		if (null == conf) return null;
		return HConn.getConn (conf)
			.getTable (TableName.valueOf (tbName));
	}

	public HTableDescriptor getTableDesc () {
		HTableDescriptor td = new HTableDescriptor (TableName.valueOf (this.tbName));
		for (HColumnDescriptor cp: cList)
			td.addFamily (cp);
		// TODO... Other properties to add into HColumnDescriptor;
		return td;
	}

	@Override
	public String toString () {
		return "[" + tbName + " version " + maxVersion + "]";
	}

}


text:
<?php namespace SmallTeam\ImageBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * Configuration
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('smallteam_image');

        $rootNode
            ->children()
                ->scalarNode('base_dir')->defaultValue('%kernel.root_dir%/../web/uploads')->end()
                ->scalarNode('image_engine')->defaultValue('SmallTeam\ImageBundle\Engines\GDImageEngine')->end()
                ->scalarNode('imagick_path')->defaultNull()->end()
            ->end()
        ;

        return $treeBuilder;
    }
}


text:
$packageName = 'produkey.install'
$installerType = 'exe'
$url = 'http://www.nirsoft.net/utils/produkey_setup.exe'
$checksum = '811f5e15e33f0a66ce3e993901ebae18d236fff0'
$checksumType = 'sha1'
$silentArgs = '/S'
$validExitCodes = @(0)

Install-ChocolateyPackage -PackageName "$packageName" `
                          -FileType "$installerType" `
                          -Url "$url" `
                          -SilentArgs "$silentArgs" `
                          -ValidExitCodes $validExitCodes `
                          -Checksum "$checksum" `
                          -ChecksumType "$checksumType"