text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.search.documents;

import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.ServiceVersion;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.serializer.JsonSerializer;
import com.azure.search.documents.implementation.SearchIndexClientImpl;
import com.azure.search.documents.implementation.converters.IndexActionConverter;
import com.azure.search.documents.implementation.converters.SearchResultConverter;
import com.azure.search.documents.implementation.converters.SuggestResultConverter;
import com.azure.search.documents.implementation.models.AutocompleteRequest;
import com.azure.search.documents.implementation.models.SearchContinuationToken;
import com.azure.search.documents.implementation.models.SearchDocumentsResult;
import com.azure.search.documents.implementation.models.SearchFirstPageResponseWrapper;
import com.azure.search.documents.implementation.models.SearchRequest;
import com.azure.search.documents.implementation.models.SuggestDocumentsResult;
import com.azure.search.documents.implementation.models.SuggestRequest;
import com.azure.search.documents.implementation.util.DocumentResponseConversions;
import com.azure.search.documents.implementation.util.MappingUtils;
import com.azure.search.documents.implementation.util.SuggestOptionsHandler;
import com.azure.search.documents.implementation.util.Utility;
import com.azure.search.documents.indexes.models.IndexDocumentsBatch;
import com.azure.search.documents.models.AutocompleteOptions;
import com.azure.search.documents.models.FacetResult;
import com.azure.search.documents.models.IndexAction;
import com.azure.search.documents.models.IndexActionType;
import com.azure.search.documents.models.IndexBatchException;
import com.azure.search.documents.models.IndexDocumentsOptions;
import com.azure.search.documents.models.IndexDocumentsResult;
import com.azure.search.documents.models.QueryAnswerType;
import com.azure.search.documents.models.QueryCaptionType;
import com.azure.search.documents.models.ScoringParameter;
import com.azure.search.documents.models.SearchOptions;
import com.azure.search.documents.models.SearchResult;
import com.azure.search.documents.models.SuggestOptions;
import com.azure.search.documents.models.SuggestResult;
import com.azure.search.documents.util.AutocompletePagedFlux;
import com.azure.search.documents.util.AutocompletePagedResponse;
import com.azure.search.documents.util.SearchPagedFlux;
import com.azure.search.documents.util.SearchPagedResponse;
import com.azure.search.documents.util.SuggestPagedFlux;
import com.azure.search.documents.util.SuggestPagedResponse;
import reactor.core.publisher.Mono;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.azure.core.util.FluxUtil.monoError;
import static com.azure.core.util.FluxUtil.withContext;
import static com.azure.core.util.serializer.TypeReference.createInstance;

/**
 * This class provides a client that contains the operations for querying an index and uploading, merging, or deleting
 * documents in an Azure Cognitive Search service.
 *
 * @see SearchClientBuilder
 */
@ServiceClient(builder = SearchClientBuilder.class, isAsync = true)
public final class SearchAsyncClient {
    private static final ClientLogger LOGGER = new ClientLogger(SearchAsyncClient.class);

    /**
     * Search REST API Version
     */
    private final SearchServiceVersion serviceVersion;

    /**
     * The endpoint for the Azure Cognitive Search service.
     */
    private final String endpoint;

    /**
     * The name of the Azure Cognitive Search index.
     */
    private final String indexName;

    /**
     * The underlying AutoRest client used to interact with the Azure Cognitive Search service
     */
    private final SearchIndexClientImpl restClient;

    /**
     * The pipeline that powers this client.
     */
    private final HttpPipeline httpPipeline;

    final JsonSerializer serializer;

    /**
     * Package private constructor to be used by {@link SearchClientBuilder}
     */
    SearchAsyncClient(String endpoint, String indexName, SearchServiceVersion serviceVersion,
        HttpPipeline httpPipeline, JsonSerializer serializer, SearchIndexClientImpl restClient) {
        this.endpoint = endpoint;
        this.indexName = indexName;
        this.serviceVersion = serviceVersion;
        this.httpPipeline = httpPipeline;
        this.serializer = serializer;
        this.restClient = restClient;
    }

    /**
     * Gets the name of the Azure Cognitive Search index.
     *
     * @return the indexName value.
     */
    public String getIndexName() {
        return this.indexName;
    }

    /**
     * Gets the {@link HttpPipeline} powering this client.
     *
     * @return the pipeline.
     */
    HttpPipeline getHttpPipeline() {
        return this.httpPipeline;
    }

    /**
     * Gets the endpoint for the Azure Cognitive Search service.
     *
     * @return the endpoint value.
     */
    public String getEndpoint() {
        return this.endpoint;
    }

    /**
     * Uploads a collection of documents to the target index.
     *
     *
Code Sample

     *
     *
 Upload dynamic SearchDocument.

     *
     *
     *

     * SearchDocument searchDocument = new SearchDocument();
     * searchDocument.put("hotelId", "1");
     * searchDocument.put("hotelName", "test");
     * SEARCH_ASYNC_CLIENT.uploadDocuments(Collections.singletonList(searchDocument))
     *     .subscribe(result -> {
     *         for (IndexingResult indexingResult : result.getResults()) {
     *             System.out.printf("Does document with key %s upload successfully? %b%n",
     *                 indexingResult.getKey(), indexingResult.isSucceeded());
     *         }
     *     });
     *

     *
     *
     * @param documents collection of documents to upload to the target Index.
     * @return The result of the document indexing actions.
     * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the
     * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch
     * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result
     * reports the status of each indexing action in the batch, making it possible to determine the state of the index
     * after a partial failure.
     * @see Add, update, or
     * delete documents
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<IndexDocumentsResult> uploadDocuments(Iterable<?> documents) {
        return uploadDocumentsWithResponse(documents, null).map(Response::getValue);
    }

    /**
     * Uploads a collection of documents to the target index.
     *
     *
Code Sample

     *
     *
 Upload dynamic SearchDocument.

     *
     *
     *

     * SearchDocument searchDocument = new SearchDocument();
     * searchDocument.put("hotelId", "1");
     * searchDocument.put("hotelName", "test");
     * searchAsyncClient.uploadDocumentsWithResponse(Collections.singletonList(searchDocument), null)
     *     .subscribe(resultResponse -> {
     *         System.out.println("The status code of the response is " + resultResponse.getStatusCode());
     *         for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
     *             System.out.printf("Does document with key %s upload successfully? %b%n", indexingResult.getKey(),
     *                 indexingResult.isSucceeded());
     *         }
     *     });
     *

     *
     *
     * @param documents collection of documents to upload to the target Index.
     * @param options Options that allow specifying document indexing behavior.
     * @return A response containing the result of the document indexing actions.
     * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the
     * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch
     * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result
     * reports the status of each indexing action in the batch, making it possible to determine the state of the index
     * after a partial failure.
     * @see Add, update, or
     * delete documents
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<IndexDocumentsResult>> uploadDocumentsWithResponse(Iterable<?> documents,
        IndexDocumentsOptions options) {
        return withContext(context -> uploadDocumentsWithResponse(documents, options, context));
    }

    Mono<Response<IndexDocumentsResult>> uploadDocumentsWithResponse(Iterable<?> documents,
        IndexDocumentsOptions options, Context context) {
        return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.UPLOAD), options, context);
    }

    /**
     * Merges a collection of documents with existing documents in the target index.
     *

     * If the type of the document contains non-nullable primitive-typed properties, these properties may not merge
     * correctly. If you do not set such a property, it will automatically take its default value (for example,
     * {@code 0} for {@code int} or false for {@code boolean}), which will override the value of the property currently
     * stored in the index, even if this was not your intent. For this reason, it is strongly recommended that you
     * always declare primitive-typed properties with their class equivalents (for example, an integer property should
     * be of type {@code Integer} instead of {@code int}).
     *
     *
Code Sample

     *
     *
 Merge dynamic SearchDocument.

     *
     *
     *

     * SearchDocument searchDocument = new SearchDocument();
     * searchDocument.put("hotelName", "merge");
     * SEARCH_ASYNC_CLIENT.mergeDocuments(Collections.singletonList(searchDocument))
     *     .subscribe(result -> {
     *         for (IndexingResult indexingResult : result.getResults()) {
     *             System.out.printf("Does document with key %s merge successfully? %b%n", indexingResult.getKey(),
     *                 indexingResult.isSucceeded());
     *         }
     *     });
     *

     *
     *
     * @param documents collection of documents to be merged
     * @return document index result
     * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the
     * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch
     * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result
     * reports the status of each indexing action in the batch, making it possible to determine the state of the index
     * after a partial failure.
     * @see Add, update, or
     * delete documents
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<IndexDocumentsResult> mergeDocuments(Iterable<?> documents) {
        return mergeDocumentsWithResponse(documents, null).map(Response::getValue);
    }

    /**
     * Merges a collection of documents with existing documents in the target index.
     *

     * If the type of the document contains non-nullable primitive-typed properties, these properties may not merge
     * correctly. If you do not set such a property, it will automatically take its default value (for example,
     * {@code 0} for {@code int} or false for {@code boolean}), which will override the value of the property currently
     * stored in the index, even if this was not your intent. For this reason, it is strongly recommended that you
     * always declare primitive-typed properties with their class equivalents (for example, an integer property should
     * be of type {@code Integer} instead of {@code int}).
     *
     *
Code Sample

     *
     *
 Merge dynamic SearchDocument.

     *
     *
     *

     * SearchDocument searchDocument = new SearchDocument();
     * searchDocument.put("hotelName", "test");
     * searchAsyncClient.mergeDocumentsWithResponse(Collections.singletonList(searchDocument), null)
     *     .subscribe(resultResponse -> {
     *         System.out.println("The status code of the response is " + resultResponse.getStatusCode());
     *         for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
     *             System.out.printf("Does document with key %s merge successfully? %b%n", indexingResult.getKey(),
     *                 indexingResult.isSucceeded());
     *         }
     *     });
     *

     *
     *
     * @param documents collection of documents to be merged
     * @param options Options that allow specifying document indexing behavior.
     * @return response containing the document index result.
     * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the
     * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch
     * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result
     * reports the status of each indexing action in the batch, making it possible to determine the state of the index
     * after a partial failure.
     * @see Add, update, or
     * delete documents
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<IndexDocumentsResult>> mergeDocumentsWithResponse(Iterable<?> documents,
        IndexDocumentsOptions options) {
        return withContext(context -> mergeDocumentsWithResponse(documents, options, context));
    }

    Mono<Response<IndexDocumentsResult>> mergeDocumentsWithResponse(Iterable<?> documents,
        IndexDocumentsOptions options, Context context) {
        return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.MERGE), options, context);
    }

    /**
     * This action behaves like merge if a document with the given key already exists in the index. If the document does
     * not exist, it behaves like upload with a new document.
     *

     * If the type of the document contains non-nullable primitive-typed properties, these properties may not merge
     * correctly. If you do not set such a property, it will automatically take its default value (for example,
     * {@code 0} for {@code int} or false for {@code boolean}), which will override the value of the property currently
     * stored in the index, even if this was not your intent. For this reason, it is strongly recommended that you
     * always declare primitive-typed properties with their class equivalents (for example, an integer property should
     * be of type {@code Integer} instead of {@code int}).
     *
     *
Code Sample

     *
     *
 Merge or upload dynamic SearchDocument.

     *
     *
     *

     * SearchDocument searchDocument = new SearchDocument();
     * searchDocument.put("hotelId", "1");
     * searchDocument.put("hotelName", "test");
     * SEARCH_ASYNC_CLIENT.mergeOrUploadDocuments(Collections.singletonList(searchDocument))
     *     .subscribe(result -> {
     *         for (IndexingResult indexingResult : result.getResults()) {
     *             System.out.printf("Does document with key %s mergeOrUpload successfully? %b%n",
     *                 indexingResult.getKey(), indexingResult.isSucceeded());
     *         }
     *     });
     *

     *
     *
     * @param documents collection of documents to be merged, if exists, otherwise uploaded
     * @return document index result
     * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the
     * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch
     * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result
     * reports the status of each indexing action in the batch, making it possible to determine the state of the index
     * after a partial failure.
     * @see Add, update, or
     * delete documents
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<IndexDocumentsResult> mergeOrUploadDocuments(Iterable<?> documents) {
        return mergeOrUploadDocumentsWithResponse(documents, null).map(Response::getValue);
    }

    /**
     * This action behaves like merge if a document with the given key already exists in the index. If the document does
     * not exist, it behaves like upload with a new document.
     *

     * If the type of the document contains non-nullable primitive-typed properties, these properties may not merge
     * correctly. If you do not set such a property, it will automatically take its default value (for example,
     * {@code 0} for {@code int} or false for {@code boolean}), which will override the value of the property currently
     * stored in the index, even if this was not your intent. For this reason, it is strongly recommended that you
     * always declare primitive-typed properties with their class equivalents (for example, an integer property should
     * be of type {@code Integer} instead of {@code int}).
     *
     *
Code Sample

     *
     *
 Merge or upload dynamic SearchDocument.

     *
     *
     *

     * SearchDocument searchDocument = new SearchDocument();
     * searchDocument.put("hotelId", "1");
     * searchDocument.put("hotelName", "test");
     * searchAsyncClient.mergeOrUploadDocumentsWithResponse(Collections.singletonList(searchDocument), null)
     *     .subscribe(resultResponse -> {
     *         System.out.println("The status code of the response is " + resultResponse.getStatusCode());
     *         for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
     *             System.out.printf("Does document with key %s mergeOrUpload successfully? %b%n",
     *                 indexingResult.getKey(), indexingResult.isSucceeded());
     *         }
     *     });
     *

     *
     *
     * @param documents collection of documents to be merged, if exists, otherwise uploaded
     * @param options Options that allow specifying document indexing behavior.
     * @return document index result
     * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the
     * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch
     * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result
     * reports the status of each indexing action in the batch, making it possible to determine the state of the index
     * after a partial failure.
     * @see Add, update, or
     * delete documents
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<IndexDocumentsResult>> mergeOrUploadDocumentsWithResponse(Iterable<?> documents,
        IndexDocumentsOptions options) {
        return withContext(context -> mergeOrUploadDocumentsWithResponse(documents, options, context));
    }

    Mono<Response<IndexDocumentsResult>> mergeOrUploadDocumentsWithResponse(Iterable<?> documents,
        IndexDocumentsOptions options, Context context) {
        return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.MERGE_OR_UPLOAD), options,
            context);
    }

    /**
     * Deletes a collection of documents from the target index.
     *
     *
Code Sample

     *
     *
 Delete dynamic SearchDocument.

     *
     *
     *

     * SearchDocument searchDocument = new SearchDocument();
     * searchDocument.put("hotelId", "1");
     * searchDocument.put("hotelName", "test");
     * SEARCH_ASYNC_CLIENT.deleteDocuments(Collections.singletonList(searchDocument))
     *     .subscribe(result -> {
     *         for (IndexingResult indexingResult : result.getResults()) {
     *             System.out.printf("Does document with key %s delete successfully? %b%n", indexingResult.getKey(),
     *                 indexingResult.isSucceeded());
     *         }
     *     });
     *

     *
     *
     * @param documents collection of documents to delete from the target Index. Fields other than the key are ignored.
     * @return document index result.
     * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the
     * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch
     * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result
     * reports the status of each indexing action in the batch, making it possible to determine the state of the index
     * after a partial failure.
     * @see Add, update, or
     * delete documents
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<IndexDocumentsResult> deleteDocuments(Iterable<?> documents) {
        return deleteDocumentsWithResponse(documents, null).map(Response::getValue);
    }

    /**
     * Deletes a collection of documents from the target index.
     *
     *
Code Sample

     *
     *
 Delete dynamic SearchDocument.

     *
     *
     *

     * SearchDocument searchDocument = new SearchDocument();
     * searchDocument.put("hotelId", "1");
     * searchDocument.put("hotelName", "test");
     * searchAsyncClient.deleteDocumentsWithResponse(Collections.singletonList(searchDocument), null)
     *     .subscribe(resultResponse -> {
     *         System.out.println("The status code of the response is " + resultResponse.getStatusCode());
     *         for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
     *             System.out.printf("Does document with key %s delete successfully? %b%n", indexingResult.getKey(),
     *                 indexingResult.isSucceeded());
     *         }
     *     });
     *

     *
     *
     * @param documents collection of documents to delete from the target Index. Fields other than the key are ignored.
     * @param options Options that allow specifying document indexing behavior.
     * @return response containing the document index result.
     * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the
     * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch
     * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result
     * reports the status of each indexing action in the batch, making it possible to determine the state of the index
     * after a partial failure.
     * @see Add, update, or
     * delete documents
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<IndexDocumentsResult>> deleteDocumentsWithResponse(Iterable<?> documents,
        IndexDocumentsOptions options) {
        return withContext(context -> deleteDocumentsWithResponse(documents, options, context));
    }

    Mono<Response<IndexDocumentsResult>> deleteDocumentsWithResponse(Iterable<?> documents,
        IndexDocumentsOptions options, Context context) {
        return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.DELETE), options, context);
    }

    /**
     * Sends a batch of upload, merge, and/or delete actions to the search index.
     *
     *
Code Sample

     *
     *
 Index batch operation on dynamic SearchDocument.

     *
     *
     *

     * SearchDocument searchDocument1 = new SearchDocument();
     * searchDocument1.put("hotelId", "1");
     * searchDocument1.put("hotelName", "test1");
     * SearchDocument searchDocument2 = new SearchDocument();
     * searchDocument2.put("hotelId", "2");
     * searchDocument2.put("hotelName", "test2");
     * IndexDocumentsBatch<SearchDocument> indexDocumentsBatch = new IndexDocumentsBatch<>();
     * indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1));
     * indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2));
     * SEARCH_ASYNC_CLIENT.indexDocuments(indexDocumentsBatch)
     *     .subscribe(result -> {
     *         for (IndexingResult indexingResult : result.getResults()) {
     *             System.out.printf("Does document with key %s finish successfully? %b%n", indexingResult.getKey(),
     *                 indexingResult.isSucceeded());
     *         }
     *     });
     *

     *
     *
     * @param batch The batch of index actions
     * @return Response containing the status of operations for all actions in the batch.
     * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the
     * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch
     * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result
     * reports the status of each indexing action in the batch, making it possible to determine the state of the index
     * after a partial failure.
     * @see Add, update, or
     * delete documents
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<IndexDocumentsResult> indexDocuments(IndexDocumentsBatch<?> batch) {
        return indexDocumentsWithResponse(batch, null).map(Response::getValue);
    }

    /**
     * Sends a batch of upload, merge, and/or delete actions to the search index.
     *
     *
Code Sample

     *
     *
 Index batch operation on dynamic SearchDocument.

     *
     *
     *

     * SearchDocument searchDocument1 = new SearchDocument();
     * searchDocument1.put("hotelId", "1");
     * searchDocument1.put("hotelName", "test1");
     * SearchDocument searchDocument2 = new SearchDocument();
     * searchDocument2.put("hotelId", "2");
     * searchDocument2.put("hotelName", "test2");
     * IndexDocumentsBatch<SearchDocument> indexDocumentsBatch = new IndexDocumentsBatch<>();
     * indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1));
     * indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2));
     * searchAsyncClient.indexDocumentsWithResponse(indexDocumentsBatch, null)
     *     .subscribe(resultResponse -> {
     *         System.out.println("The status code of the response is " + resultResponse.getStatusCode());
     *         for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
     *             System.out.printf("Does document with key %s finish successfully? %b%n", indexingResult.getKey(),
     *                 indexingResult.isSucceeded());
     *         }
     *     });
     *

     *
     *
     * @param batch The batch of index actions
     * @param options Options that allow specifying document indexing behavior.
     * @return Response containing the status of operations for all actions in the batch
     * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the
     * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch
     * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result
     * reports the status of each indexing action in the batch, making it possible to determine the state of the index
     * after a partial failure.
     * @see Add, update, or
     * delete documents
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<IndexDocumentsResult>> indexDocumentsWithResponse(IndexDocumentsBatch<?> batch,
        IndexDocumentsOptions options) {
        return withContext(context -> indexDocumentsWithResponse(batch, options, context));
    }

    Mono<Response<IndexDocumentsResult>> indexDocumentsWithResponse(IndexDocumentsBatch<?> batch,
        IndexDocumentsOptions options, Context context) {
        List<com.azure.search.documents.implementation.models.IndexAction> indexActions = batch.getActions()
            .stream()
            .map(document -> IndexActionConverter.map(document, serializer))
            .collect(Collectors.toList());

        boolean throwOnAnyError = options == null || options.throwOnAnyError();
        return Utility.indexDocumentsWithResponse(restClient, indexActions, throwOnAnyError, context, LOGGER);
    }

    /**
     * Retrieves a document from the Azure Cognitive Search index.
     *

     * View naming rules for guidelines on
     * constructing valid document keys.
     *
     *
Code Sample

     *
     *
 Get dynamic SearchDocument.

     *
     *
     *

     * SEARCH_ASYNC_CLIENT.getDocument("hotelId", SearchDocument.class)
     *     .subscribe(result -> {
     *         for (Map.Entry<String, Object> keyValuePair : result.entrySet()) {
     *             System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(),
     *                 keyValuePair.getValue());
     *         }
     *     });
     *

     *
     *
     * @param key The key of the document to retrieve.
     * @param modelClass The model class converts to.
     * @param <T> Convert document to the generic type.
     * @return the document object
     * @see Lookup document
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public <T> Mono<T> getDocument(String key, Class<T> modelClass) {
        return getDocumentWithResponse(key, modelClass, null).map(Response::getValue);
    }

    /**
     * Retrieves a document from the Azure Cognitive Search index.
     *

     * View naming rules for guidelines on
     * constructing valid document keys.
     *
     *
Code Sample

     *
     *
 Get dynamic SearchDocument.

     *
     *
     *

     * SEARCH_ASYNC_CLIENT.getDocumentWithResponse("hotelId", SearchDocument.class, null)
     *     .subscribe(resultResponse -> {
     *         System.out.println("The status code of the response is " + resultResponse.getStatusCode());
     *         for (Map.Entry<String, Object> keyValuePair : resultResponse.getValue().entrySet()) {
     *             System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(),
     *                 keyValuePair.getValue());
     *         }
     *     });
     *

     *
     *
     * @param <T> Convert document to the generic type.
     * @param key The key of the document to retrieve.
     * @param modelClass The model class converts to.
     * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will have null or
     * default as its corresponding property value in the returned object.
     * @return a response containing the document object
     * @see Lookup document
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public <T> Mono<Response<T>> getDocumentWithResponse(String key, Class<T> modelClass, List<String> selectedFields) {
        return withContext(context -> getDocumentWithResponse(key, modelClass, selectedFields, context));
    }

    <T> Mono<Response<T>> getDocumentWithResponse(String key, Class<T> modelClass, List<String> selectedFields,
        Context context) {
        try {
            return restClient.getDocuments()
                .getWithResponseAsync(key, selectedFields, null, context)
                .onErrorMap(DocumentResponseConversions::exceptionMapper)
                .map(res -> {
                    if (serializer == null) {
                        try {
                            return new SimpleResponse<>(res, Utility.convertValue(res.getValue(), modelClass));
                        } catch (IOException ex) {
                            throw LOGGER.logExceptionAsError(
                                new RuntimeException("Failed to deserialize document.", ex));
                        }
                    }
                    ByteArrayOutputStream sourceStream = new ByteArrayOutputStream();
                    serializer.serialize(sourceStream, res.getValue());
                    T doc = serializer.deserialize(new ByteArrayInputStream(sourceStream.toByteArray()),
                        createInstance(modelClass));
                    return new SimpleResponse<>(res, doc);
                }).map(Function.identity());
        } catch (RuntimeException ex) {
            return monoError(LOGGER, ex);
        }
    }

    /**
     * Queries the number of documents in the search index.
     *
     *
Code Sample

     *
     *
 Get document count.

     *
     *
     *

     * SEARCH_ASYNC_CLIENT.getDocumentCount()
     *     .subscribe(count -> System.out.printf("There are %d documents in service.", count));
     *

     *
     *
     * @return the number of documents.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Long> getDocumentCount() {
        return this.getDocumentCountWithResponse().map(Response::getValue);
    }

    /**
     * Queries the number of documents in the search index.
     *
     *
Code Sample

     *
     *
 Get document count.

     *
     *
     *

     * SEARCH_ASYNC_CLIENT.getDocumentCountWithResponse()
     *     .subscribe(countResponse -> {
     *         System.out.println("The status code of the response is " + countResponse.getStatusCode());
     *         System.out.printf("There are %d documents in service.", countResponse.getValue());
     *     });
     *

     *
     *
     * @return response containing the number of documents.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<Long>> getDocumentCountWithResponse() {
        return withContext(this::getDocumentCountWithResponse);
    }

    Mono<Response<Long>> getDocumentCountWithResponse(Context context) {
        try {
            return restClient.getDocuments()
                .countWithResponseAsync(null, context)
                .onErrorMap(MappingUtils::exceptionMapper)
                .map(Function.identity());
        } catch (RuntimeException ex) {
            return monoError(LOGGER, ex);
        }
    }

    /**
     * Searches for documents in the Azure Cognitive Search index.
     *

     * If {@code searchText} is set to null or {@code "*"} all documents will be matched, see
     * simple query
     * syntax in Azure Cognitive Search for more information about search query syntax.
     *
     *
Code Sample

     *
     *
 Search text from documents in service.

     *
     *
     *

     * SearchPagedFlux searchPagedFlux = SEARCH_ASYNC_CLIENT.search("searchText");
     * searchPagedFlux.getTotalCount().subscribe(
     *     count -> System.out.printf("There are around %d results.", count)
     * );
     * searchPagedFlux.byPage()
     *     .subscribe(resultResponse -> {
     *         for (SearchResult result: resultResponse.getValue()) {
     *             SearchDocument searchDocument = result.getDocument(SearchDocument.class);
     *             for (Map.Entry<String, Object> keyValuePair: searchDocument.entrySet()) {
     *                 System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), keyValuePair.getValue());
     *             }
     *         }
     *     });
     *

     *
     *
     * @param searchText A full-text search query expression.
     * @return A {@link SearchPagedFlux} that iterates over {@link SearchResult} objects and provides access to the
     * {@link SearchPagedResponse} object for each page containing HTTP response and count, facet, and coverage
     * information.
     * @see Search documents
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public SearchPagedFlux search(String searchText) {
        return this.search(searchText, null);
    }

    /**
     * Searches for documents in the Azure Cognitive Search index.
     *

     * If {@code searchText} is set to null or {@code "*"} all documents will be matched, see
     * simple query
     * syntax in Azure Cognitive Search for more information about search query syntax.
     *
     *
Code Sample

     *
     *
 Search text from documents in service with option.

     *
     *
     *

     * SearchPagedFlux pagedFlux = SEARCH_ASYNC_CLIENT.search("searchText",
     *     new SearchOptions().setOrderBy("hotelId desc"));
     *
     * pagedFlux.getTotalCount().subscribe(count -> System.out.printf("There are around %d results.", count));
     *
     * pagedFlux.byPage()
     *     .subscribe(searchResultResponse -> searchResultResponse.getValue().forEach(searchDocument -> {
     *         for (Map.Entry<String, Object> keyValuePair
     *             : searchDocument.getDocument(SearchDocument.class).entrySet()) {
     *             System.out.printf("Document key %s, document value %s", keyValuePair.getKey(),
     *                 keyValuePair.getValue());
     *         }
     *     }));
     *

     *
     *
     * @param searchText A full-text search query expression.
     * @param searchOptions Parameters to further refine the search query
     * @return A {@link SearchPagedFlux} that iterates over {@link SearchResult} objects and provides access to the
     * {@link SearchPagedResponse} object for each page containing HTTP response and count, facet, and coverage
     * information.
     * @see Search documents
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public SearchPagedFlux search(String searchText, SearchOptions searchOptions) {
        SearchRequest request = createSearchRequest(searchText, searchOptions);
        // The firstPageResponse shared among all functional calls below.
        // Do not initial new instance directly in func call.
        final SearchFirstPageResponseWrapper firstPageResponse = new SearchFirstPageResponseWrapper();
        Function<String, Mono<SearchPagedResponse>> func = continuationToken -> withContext(context ->
            search(request, continuationToken, firstPageResponse, context));
        return new SearchPagedFlux(() -> func.apply(null), func);
    }

    SearchPagedFlux search(String searchText, SearchOptions searchOptions, Context context) {
        SearchRequest request = createSearchRequest(searchText, searchOptions);
        // The firstPageResponse shared among all functional calls below.
        // Do not initial new instance directly in func call.
        final SearchFirstPageResponseWrapper firstPageResponseWrapper = new SearchFirstPageResponseWrapper();
        Function<String, Mono<SearchPagedResponse>> func = continuationToken ->
            search(request, continuationToken, firstPageResponseWrapper, context);
        return new SearchPagedFlux(() -> func.apply(null), func);
    }

    private Mono<SearchPagedResponse> search(SearchRequest request, String continuationToken,
        SearchFirstPageResponseWrapper firstPageResponseWrapper, Context context) {
        if (continuationToken == null && firstPageResponseWrapper.getFirstPageResponse() != null) {
            return Mono.just(firstPageResponseWrapper.getFirstPageResponse());
        }
        SearchRequest requestToUse = (continuationToken == null)
            ? request
            : SearchContinuationToken.deserializeToken(serviceVersion.getVersion(), continuationToken);

        return restClient.getDocuments().searchPostWithResponseAsync(requestToUse, null, context)
            .onErrorMap(MappingUtils::exceptionMapper)
            .map(response -> {
                SearchDocumentsResult result = response.getValue();

                SearchPagedResponse page = new SearchPagedResponse(
                    new SimpleResponse<>(response, getSearchResults(result)),
                    createContinuationToken(result, serviceVersion), getFacets(result), result.getCount(),
                    result.getCoverage(), result.getAnswers());
                if (continuationToken == null) {
                    firstPageResponseWrapper.setFirstPageResponse(page);
                }
                return page;
            });
    }

    private List<SearchResult> getSearchResults(SearchDocumentsResult result) {
        return result.getResults().stream()
            .map(searchResult -> SearchResultConverter.map(searchResult, serializer))
            .collect(Collectors.toList());
    }

    private static String createContinuationToken(SearchDocumentsResult result, ServiceVersion serviceVersion) {
        return SearchContinuationToken.serializeToken(serviceVersion.getVersion(), result.getNextLink(),
            result.getNextPageParameters());
    }

    private static Map<String, List<FacetResult>> getFacets(SearchDocumentsResult result) {
        if (result.getFacets() == null) {
            return null;
        }

        return result.getFacets();
    }

    /**
     * Suggests documents in the index that match the given partial query.
     *
     *
Code Sample

     *
     *
 Suggest text from documents in service.

     *
     *
     *

     * SEARCH_ASYNC_CLIENT.suggest("searchText", "sg")
     *     .subscribe(results -> {
     *         for (Map.Entry<String, Object> keyValuePair: results.getDocument(SearchDocument.class).entrySet()) {
     *             System.out.printf("Document key %s, document value %s", keyValuePair.getKey(),
     *                 keyValuePair.getValue());
     *         }
     *     });
     *

     *
     *
     * @param searchText The search text.
     * @param suggesterName The name of the suggester.
     * @return A {@link SuggestPagedFlux} that iterates over {@link SuggestResult} objects and provides access to the
     * {@link SuggestPagedResponse} object for each page containing HTTP response and coverage information.
     * @see Suggestions
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public SuggestPagedFlux suggest(String searchText, String suggesterName) {
        return suggest(searchText, suggesterName, null);
    }

    /**
     * Suggests documents in the index that match the given partial query.
     *
     *
Code Sample

     *
     *
 Suggest text from documents in service with option.

     *
     *
     *

     * SEARCH_ASYNC_CLIENT.suggest("searchText", "sg",
     *     new SuggestOptions().setOrderBy("hotelId desc"))
     *     .subscribe(results -> {
     *         for (Map.Entry<String, Object> keyValuePair: results.getDocument(SearchDocument.class).entrySet()) {
     *             System.out.printf("Document key %s, document value %s", keyValuePair.getKey(),
     *                 keyValuePair.getValue());
     *         }
     *     });
     *

     *
     *
     * @param searchText The search text.
     * @param suggesterName The name of the suggester.
     * @param suggestOptions Parameters to further refine the suggestion query.
     * @return A {@link SuggestPagedFlux} that iterates over {@link SuggestResult} objects and provides access to the
     * {@link SuggestPagedResponse} object for each page containing HTTP response and coverage information.
     * @see Suggestions
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public SuggestPagedFlux suggest(String searchText, String suggesterName, SuggestOptions suggestOptions) {
        SuggestRequest suggestRequest = createSuggestRequest(searchText, suggesterName,
            SuggestOptionsHandler.ensureSuggestOptions(suggestOptions));

        return new SuggestPagedFlux(() -> withContext(context -> suggest(suggestRequest, context)));
    }

    SuggestPagedFlux suggest(String searchText, String suggesterName, SuggestOptions suggestOptions, Context context) {
        SuggestRequest suggestRequest = createSuggestRequest(searchText,
            suggesterName, SuggestOptionsHandler.ensureSuggestOptions(suggestOptions));

        return new SuggestPagedFlux(() -> suggest(suggestRequest, context));
    }

    private Mono<SuggestPagedResponse> suggest(SuggestRequest suggestRequest, Context context) {
        return restClient.getDocuments().suggestPostWithResponseAsync(suggestRequest, null, context)
            .onErrorMap(MappingUtils::exceptionMapper)
            .map(response -> {
                SuggestDocumentsResult result = response.getValue();

                return new SuggestPagedResponse(new SimpleResponse<>(response, getSuggestResults(result)),
                    result.getCoverage());
            });
    }

    private static List<SuggestResult> getSuggestResults(SuggestDocumentsResult result) {
        return result.getResults().stream()
            .map(SuggestResultConverter::map)
            .collect(Collectors.toList());
    }

    /**
     * Autocompletes incomplete query terms based on input text and matching terms in the index.
     *
     *
Code Sample

     *
     *
 Autocomplete text from documents in service.

     *
     *
     *

     * SEARCH_ASYNC_CLIENT.autocomplete("searchText", "sg")
     *     .subscribe(result -> System.out.printf("The complete term is %s", result.getText()));
     *

     *
     *
     * @param searchText search text
     * @param suggesterName suggester name
     * @return auto complete result.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public AutocompletePagedFlux autocomplete(String searchText, String suggesterName) {
        return autocomplete(searchText, suggesterName, null);
    }

    /**
     * Autocompletes incomplete query terms based on input text and matching terms in the index.
     *
     *
Code Sample

     *
     *
 Autocomplete text from documents in service with option.

     *
     *
     *

     * SEARCH_ASYNC_CLIENT.autocomplete("searchText", "sg",
     *     new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT))
     *     .subscribe(result ->
     *         System.out.printf("The complete term is %s", result.getText())
     *     );
     *

     *
     *
     * @param searchText search text
     * @param suggesterName suggester name
     * @param autocompleteOptions autocomplete options
     * @return auto complete result.
     */
    public AutocompletePagedFlux autocomplete(String searchText, String suggesterName,
        AutocompleteOptions autocompleteOptions) {
        AutocompleteRequest request = createAutoCompleteRequest(searchText, suggesterName, autocompleteOptions);

        return new AutocompletePagedFlux(() -> withContext(context -> autocomplete(request, context)));
    }

    AutocompletePagedFlux autocomplete(String searchText, String suggesterName, AutocompleteOptions autocompleteOptions,
        Context context) {
        AutocompleteRequest request = createAutoCompleteRequest(searchText, suggesterName, autocompleteOptions);

        return new AutocompletePagedFlux(() -> autocomplete(request, context));
    }

    private Mono<AutocompletePagedResponse> autocomplete(AutocompleteRequest request, Context context) {
        return restClient.getDocuments().autocompletePostWithResponseAsync(request, null, context)
            .onErrorMap(MappingUtils::exceptionMapper)
            .map(response -> new AutocompletePagedResponse(new SimpleResponse<>(response, response.getValue())));
    }

    /**
     * Create search request from search text and parameters
     *
     * @param searchText search text
     * @param options search options
     * @return SearchRequest
     */
    private static SearchRequest createSearchRequest(String searchText, SearchOptions options) {
        SearchRequest request = new SearchRequest().setSearchText(searchText);

        if (options == null) {
            return request;
        }

        List<String> scoringParameters = options.getScoringParameters() == null
            ? null
            : options.getScoringParameters().stream().map(ScoringParameter::toString).collect(Collectors.toList());

        return request.setIncludeTotalResultCount(options.isTotalCountIncluded())
            .setFacets(options.getFacets())
            .setFilter(options.getFilter())
            .setHighlightFields(nullSafeStringJoin(options.getHighlightFields()))
            .setHighlightPostTag(options.getHighlightPostTag())
            .setHighlightPreTag(options.getHighlightPreTag())
            .setMinimumCoverage(options.getMinimumCoverage())
            .setOrderBy(nullSafeStringJoin(options.getOrderBy()))
            .setQueryType(options.getQueryType())
            .setScoringParameters(scoringParameters)
            .setScoringProfile(options.getScoringProfile())
            .setSemanticConfiguration(options.getSemanticConfigurationName())
            .setSearchFields(nullSafeStringJoin(options.getSearchFields()))
            .setQueryLanguage(options.getQueryLanguage())
            .setSpeller(options.getSpeller())
            .setAnswers(createSearchRequestAnswers(options))
            .setSearchMode(options.getSearchMode())
            .setScoringStatistics(options.getScoringStatistics())
            .setSessionId(options.getSessionId())
            .setSelect(nullSafeStringJoin(options.getSelect()))
            .setSkip(options.getSkip())
            .setTop(options.getTop())
            .setCaptions(createSearchRequestCaptions(options))
            .setSemanticFields(nullSafeStringJoin(options.getSemanticFields()));
    }

    static String createSearchRequestAnswers(SearchOptions searchOptions) {
        QueryAnswerType answer = searchOptions.getAnswers();
        Integer answersCount = searchOptions.getAnswersCount();

        // No answer has been defined.
        if (answer == null) {
            return null;
        }

        // No count, just send the QueryAnswer.
        if (answersCount == null) {
            return answer.toString();
        }

        // Answer and count, format it as the service expects.
        return answer + "|count-" + answersCount;
    }

    static String createSearchRequestCaptions(SearchOptions searchOptions) {
        QueryCaptionType queryCaption = searchOptions.getQueryCaption();
        Boolean queryCaptionHighlight = searchOptions.getQueryCaptionHighlightEnabled();

        // No caption has been defined.
        if (queryCaption == null) {
            return null;
        }

        // No highlight, just send the Caption.
        if (queryCaptionHighlight == null) {
            return queryCaption.toString();
        }

        // Caption and highlight, format it as the service expects.
        return queryCaption + "|highlight-" + queryCaptionHighlight;
    }

    /**
     * Create suggest request from search text, suggester name, and parameters
     *
     * @param searchText search text
     * @param suggesterName search text
     * @param options suggest options
     * @return SuggestRequest
     */
    private static SuggestRequest createSuggestRequest(String searchText, String suggesterName,
        SuggestOptions options) {
        SuggestRequest request = new SuggestRequest(searchText, suggesterName);

        if (options == null) {
            return request;
        }

        return request.setFilter(options.getFilter())
            .setUseFuzzyMatching(options.useFuzzyMatching())
            .setHighlightPostTag(options.getHighlightPostTag())
            .setHighlightPreTag(options.getHighlightPreTag())
            .setMinimumCoverage(options.getMinimumCoverage())
            .setOrderBy(nullSafeStringJoin(options.getOrderBy()))
            .setSearchFields(nullSafeStringJoin(options.getSearchFields()))
            .setSelect(nullSafeStringJoin(options.getSelect()))
            .setTop(options.getTop());
    }

    /**
     * Create Autocomplete request from search text, suggester name, and parameters
     *
     * @param searchText search text
     * @param suggesterName search text
     * @param options autocomplete options
     * @return AutocompleteRequest
     */
    private static AutocompleteRequest createAutoCompleteRequest(String searchText, String suggesterName,
        AutocompleteOptions options) {
        AutocompleteRequest request = new AutocompleteRequest(searchText, suggesterName);

        if (options == null) {
            return request;
        }

        return request.setAutocompleteMode(options.getAutocompleteMode())
            .setFilter(options.getFilter())
            .setUseFuzzyMatching(options.useFuzzyMatching())
            .setHighlightPostTag(options.getHighlightPostTag())
            .setHighlightPreTag(options.getHighlightPreTag())
            .setMinimumCoverage(options.getMinimumCoverage())
            .setSearchFields(nullSafeStringJoin(options.getSearchFields()))
            .setTop(options.getTop());
    }

    private static String nullSafeStringJoin(Iterable<? extends CharSequence> elements) {
        if (elements == null) {
            return null;
        }

        return String.join(",", elements);
    }

    private static <T> IndexDocumentsBatch<T> buildIndexBatch(Iterable<T> documents, IndexActionType actionType) {
        List<IndexAction<T>> actions = new ArrayList<>();
        documents.forEach(d -> actions.add(new IndexAction<T>()
            .setActionType(actionType)
            .setDocument(d)));

        return new IndexDocumentsBatch<T>().addActions(actions);
    }

}


text:
import java.util.LinkedList;
import java.util.List;

import com.highgo.hgdbadmin.model.ConstraintCK;
import com.highgo.hgdbadmin.model.ConstraintFK;
import com.highgo.hgdbadmin.model.ConstraintPK;
import com.highgo.hgdbadmin.model.ConstraintUK;
import com.highgo.hgdbadmin.model.Function;
import com.highgo.hgdbadmin.model.Index;
import com.highgo.hgdbadmin.model.Procedure;
import com.highgo.hgdbadmin.model.Schema;
import com.highgo.hgdbadmin.model.Sequence;
import com.highgo.hgdbadmin.model.Table;
import com.highgo.hgdbadmin.model.Trigger;
import com.highgo.hgdbadmin.model.View;

public class Constants {

	// Õâ¸öÓÃResourceÏà¹ØµÄ·½·¨³õ'»¯Ê±»ñÈ¡¡£
	public static final String PATH = "D:\\code\\ASqlServer-C3P0\\src\\c3p0-config.xml";
	public static final List<Schema> SCHEMAS = new LinkedList<>();
	public static final List<Table> TABLES = new LinkedList<>();
	public static final List<Sequence> SEQUENCES = new LinkedList<>();
	public static final List<View> VIEWS = new LinkedList<>();
	public static final List<Index> INDEXES = new LinkedList<>();
	public static final List<Procedure> PROCEDURES = new LinkedList<>();
	public static final List<Function> FUNCTIONS = new LinkedList<>();
	public static final List<Trigger> TRIGGERS = new LinkedList<>();
	public static final List<ConstraintCK> CKS = new LinkedList<>();
	public static final List<ConstraintPK> PKS = new LinkedList<>();
	public static final List<ConstraintUK> UKS = new LinkedList<>();
	public static final List<ConstraintFK> FKS = new LinkedList<>();

	public static final String RESOURCE_NAME = "shell-resource";
	public static final String BOLD_STR_SEQUENCE = "@|bold";
	public static final String END_STR_SEQUENCE = "|@";

	public static final String PROP_CURDIR = "user.dir";

	private Constants() {
	}
}

redpajama_set_name: RedPajamaGithub


text:
package edu.wustl.common.participant.client;

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

import edu.wustl.common.lookup.LookupLogic;
import edu.wustl.common.lookup.LookupParameters;
import edu.wustl.common.participant.domain.IParticipant;

public interface IParticipantManagerLookupLogic extends LookupLogic
{
	/**
	 * @param params Lookup Parameters.
	 * @return List
	 * @throws Exception Exception.
	 */
	List lookup(LookupParameters params,Set<Long> csList) throws Exception;

	void initParticipantCache() throws Exception;

	void updatePartiicpantCache(IParticipant participant);
}


text:
* [Get messages](/api/get-messages)
* [Get a raw message](/api/get-raw-message)
* [Send a message](/api/send-message)
* [Update a message](/api/update-message)
* [Render a message](/api/render-message)
* [Upload a file](/api/upload-file)
* [Delete a message](/api/delete-message)
* [Construct a narrow](/api/construct-narrow)
* [Get a message's edit history](/api/get-message-history)
* [Update a message's flags](/api/update-message-flags)
* [Mark messages as read in bulk](/api/mark-as-read-bulk)

#### Streams

* [Get all streams](/api/get-all-streams)
* [Get subscribed streams](/api/get-subscribed-streams)
* [Add subscriptions](/api/add-subscriptions)
* [Update subscription settings](/api/update-subscription-properties)
* [Remove subscriptions](/api/remove-subscriptions)
* [Get topics in a stream](/api/get-stream-topics)
* [Topic muting](/api/mute-topics)
* [Create a stream](/api/create-stream)
* [Get stream ID](/api/get-stream-id)

#### Users

* [Get all users](/api/get-all-users)
* [Get profile](/api/get-profile)
* [Create a user](/api/create-user)
* [Set "typing" status](/api/typing)
* [Get user presence](/api/get-presence)
* [Get all user groups](/api/get-user-groups)

#### Server & organizations

* [Get server settings](/api/server-settings)
* [List linkifiers](/api/list-linkifiers)
* [Create linkifiers](/api/add-linkifiers)
* [Remove linkifiers](/api/remove-linkifiers)
* [Get all custom emoji](/api/get-org-emoji)
* [Upload custom emoji](/api/upload-custom-emoji)

#### Real-time events

* [Real time events API](/api/real-time-events)
* [Register an event queue](/api/register-queue)
* [Get events from an event queue](/api/get-events-from-queue)
* [Delete an event queue](/api/delete-queue)

#### Specialty endpoints
* [Fetch a development API key](/api/dev-fetch-api-key)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ ACDDExtension Project
  ~ file ids.xml  is  part of ACDDExtension
  ~ The MIT License (MIT)  Copyright (c) 2015 Bunny Blue.
  ~
  ~
  ~ Permission is hereby granted, free of charge, to any person obtaining a copy
  ~ of this software and associated documentation files (the "Software"), to deal
  ~ in the Software without restriction, including without limitation the rights
  ~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  ~ copies of the Software, and to permit persons to whom the Software is
  ~ furnished to do so, subject to the following conditions:
  ~
  ~ The above copyright notice and this permission notice shall be included in all
  ~ copies or substantial portions of the Software.
  ~
  ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  ~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  ~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  ~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  ~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  ~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  ~ SOFTWARE.
  ~
  ~
  -->
<resources>
  <!-- Messages IDs -->
  <item type="id" name="auto_focus"/>
  <item type="id" name="decode"/>
  <item type="id" name="decode_failed"/>
  <item type="id" name="decode_succeeded"/>
  <item type="id" name="encode_failed"/>
  <item type="id" name="encode_succeeded"/>
  <item type="id" name="launch_product_query"/>
  <item type="id" name="quit"/>
  <item type="id" name="restart_preview"/>
  <item type="id" name="return_scan_result"/>
  <item type="id" name="search_book_contents_failed"/>
  <item type="id" name="search_book_contents_succeeded"/>

  <item type="id" name="gridview" />
  <item type="id" name="webview" />

  <item type="id" name="about_version_code">false</item>
  <item type="id" name="split">false</item>
</resources>


text:
<?php

namespace Granule\Tests\DataBind\_fixtures\SubNs;

use Granule\Util\Enum;

class TestEnum extends Enum {
    private const
        yes = 'yes',
        no = 'no';
}


text:
package org.springframework.cloud.contract.verifier.builder;

import org.springframework.cloud.contract.verifier.file.SingleContractMetadata;

class MockMvcRequestGiven implements Given, MockMvcAcceptor {

	private final BlockBuilder blockBuilder;

	private final GeneratedClassMetaData generatedClassMetaData;

	MockMvcRequestGiven(BlockBuilder blockBuilder, GeneratedClassMetaData metaData) {
		this.blockBuilder = blockBuilder;
		this.generatedClassMetaData = metaData;
	}

	@Override
	public MethodVisitor<Given> apply(SingleContractMetadata metadata) {
		this.blockBuilder.addIndented("MockMvcRequestSpecification request = given()");
		return this;
	}

	@Override
	public boolean accept(SingleContractMetadata metadata) {
		return acceptType(this.generatedClassMetaData, metadata);
	}

}


text:
<?php

namespace PhpDA\Layout;

class Aggregation extends AbstractLayout
{
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Gomphidius viscidula f. truncicola

### Remarks
null


text:
using FluentMigrator.Builders.Rename.Table;
using FluentMigrator.Infrastructure;

namespace FluentMigrator.Builders.Rename
{
    /// <summary>
    /// The expression root for renaming tables or columns
    /// </summary>
    public interface IRenameExpressionRoot : IFluentSyntax
    {
        /// <summary>
        /// Specify the table (or its column) to be renamed
        /// </summary>
        /// <param name="oldName">The current table name</param>
        /// <returns>The next step</returns>
        IRenameTableToOrInSchemaSyntax Table(string oldName);

        /// <summary>
        /// Specify the column to be renamed
        /// </summary>
        /// <param name="oldName">The current column name</param>
        /// <returns>The next step</returns>
        IRenameColumnTableSyntax Column(string oldName);
    }
}


text:
import { Injectable } from '@angular/core';
import { CacheService } from 'ionic-cache';

@Injectable()
export class DataCacheService {
  constructor(protected cache: CacheService) {}

  // set default cache time in seconds
  public setDefaulTime(time) {
    this.cache.setDefaultTTL(time);
  }

  public clearExpired() {
    return this.cache.clearExpired();
  }

  public cacheRequest(url, params, request) {
    const cacheKey = url + params.toString();
    return this.cache.loadFromObservable(cacheKey, request);
  }
  public clearAll() {
    return this.cache.clearAll();
  }

  public disableCache(value) {
    this.cache.enableCache(false);
  }
  public cacheSingleRequest(url, params, request, time) {
    const ttl = time;
    const cacheKey = url + params.toString();
    return this.cache.loadFromObservable(cacheKey, request, ttl);
  }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "phonebook_opt.h"

/* FILL YOUR OWN IMPLEMENTATION HERE! */
lastNameEntry *findName_opt(char lastname[],lastNameEntry *pHead)
{
    /* TODO: implement */
    while(pHead!=NULL){
        if(strcmp(lastname,pHead->lastName)==0){
            printf(" %12s  is found!\n", lastname);
            return pHead;
        }
        pHead = pHead->pNext;
    }
    printf(" %12s  is not found!\n", lastname);
    return NULL;
}

lastNameEntry *append_opt(char lastName[], lastNameEntry *e)
{
    strcpy(e->lastName,lastName);
    e->pNext = (lastNameEntry *)malloc(sizeof(lastNameEntry));
    e = e->pNext;
    e->pNext = NULL;
    return e;
}


text:
#include <platform.h>
#include <gtest/gtest.h>

#include <ds/fun.h>

/** Hashing the same integer returns the same key.
 *
 */
TEST(DsFunTest, HashSameIntGivesSameKey)
{
  uint64_t i = 2701197231051989;

  uint64_t key1 = ponyint_hash_int64(i);
  uint64_t key2 = ponyint_hash_int64(i);

  ASSERT_EQ(key1, key2);
}

/** Hasing the same string, returns the same key.
 *
 */
TEST(DsFunTest, HashSameStringGivesSameKey)
{
  const char* s = "Pony";

  uint64_t key1 = ponyint_hash_str(s);
  uint64_t key2 = ponyint_hash_str(s);

  ASSERT_EQ(key1, key2);
}

/** Hashing the same pointer returns the same key.
 *
 */
TEST(DsFunTest, HashSamePointerGivesSameKey)
{
  void* p = malloc(sizeof(void*));

  uint64_t key2 = ponyint_hash_ptr(p);
  uint64_t key1 = ponyint_hash_ptr(p);

  ASSERT_EQ(key1, key2);

  free(p);
}

/** Numbers are rounded to the next power of two.
 *
 */
TEST(DsFunTest, NumbersToNextPow)
{
  ASSERT_EQ(4, (unsigned int)ponyint_next_pow2(3));
  ASSERT_EQ(8, (unsigned int)ponyint_next_pow2(5));
  ASSERT_EQ(16, (unsigned int)ponyint_next_pow2(10));
  ASSERT_EQ(32, (unsigned int)ponyint_next_pow2(25));
  ASSERT_EQ(64, (unsigned int)ponyint_next_pow2(50));
  ASSERT_EQ(128, (unsigned int)ponyint_next_pow2(100));
  ASSERT_EQ(256, (unsigned int)ponyint_next_pow2(200));
}

/** Powers of two are not rounded.
 *
 */
TEST(DsFunTest, PowersOfTwoAreNotRounded)
{
  ASSERT_EQ((size_t)128, ponyint_next_pow2(128));
}


text:
namespace System.Windows.Forms
{

#if !CONFIG_COMPACT_FORMS

using System.Runtime.InteropServices;

#if !ECMA_COMPAT
[ComVisible(true)]
#endif
public class GiveFeedbackEventArgs : EventArgs
{
	// Internal state.
	private DragDropEffects effect;
	private bool useDefaultCursors;

	// Constructor.
	public GiveFeedbackEventArgs(DragDropEffects effect,
								 bool useDefaultCursors)
			{
				this.effect = effect;
				this.useDefaultCursors = useDefaultCursors;
			}

	// Get this object's properties.
	public DragDropEffects Effect
			{
				get
				{
					return effect;
				}
			}
	public bool UseDefaultCursors
			{
				get
				{
					return useDefaultCursors;
				}
				set
				{
					useDefaultCursors = value;
				}
			}

}; // class GiveFeedbackEventArgs

#endif // !CONFIG_COMPACT_FORMS

}; // namespace System.Windows.Forms


text:
package de.codepitbull.objectsize.strategy;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.instrument.Instrumentation;

import de.codepitbull.objectsize.agent.ISizeOfStrategy;

/**
 * NOTE: Taken from the wicket distribution.
 *
 *
 * Object size of strategy that is based on instrumentation.
 *
 * @author eelcohillenius
 */
public class InstrumentationObjectSizeOfStrategy implements ISizeOfStrategy
{

	/**
	 * Records the size of an object and it's dependants as if they were serialized but using the
	 * instrumentation API to calculate.
	 */
	private final class SizeRecodingOuputStream extends ObjectOutputStream
	{

		private long totalSize = 0;

		/**
		 * Construct.
		 *
		 * @throws IOException
		 */
		public SizeRecodingOuputStream() throws IOException
		{
			super(new OutputStream()
			{

				public void write(int b) throws IOException
				{
				}
			});
			enableReplaceObject(true);
		}

		/**
		 * Gets the calculated size.
		 *
		 * @return
		 */
		public long getTotalSize()
		{
			return totalSize;
		}

		protected Object replaceObject(Object obj) throws IOException
		{

			if (obj != null)
			{
				totalSize += instrumentation.getObjectSize(obj);
			}

			return obj;
		}
	}

	/**
	 * Instrumentation instance.
	 */
	private Instrumentation instrumentation;

	/**
	 * Calculates full size of object iterating over its hierarchy graph.
	 *
	 * @param obj
	 *            object to calculate size of
	 * @return object size
	 *
	 * @see org.apache.wicket.util.lang.Objects.IObjectSizeOfStrategy#sizeOf(java.lang.Object)
	 */
	public long sizeOf(Object obj)
	{
		if (obj == null)
		{
			return 0;
		}
		try
		{
			SizeRecodingOuputStream recorder = new SizeRecodingOuputStream();
			recorder.writeObject(obj);
			return recorder.getTotalSize();
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return -1;
		}

	}

	public Long sizeOf(Object object, Instrumentation instrumentation) {
		this.instrumentation=instrumentation;
		return sizeOf(object);
	}

}


text:
module Backup
  module Record
    class SFTP < ActiveRecord::Base

      if DB_CONNECTION_SETTINGS
        establish_connection(DB_CONNECTION_SETTINGS)
      end

      set_table_name 'backup'
      default_scope \
        :order => 'created_at desc',
        :conditions => {:storage => 'sftp'}

      # Callbacks
      after_save :clean_backups

      # Attributes
      attr_accessor :adapter_config, :keep_backups, :ip, :user, :password

      # Receives the options hash and stores it
      # Sets the SCP values
      def load_adapter(adapter)
        self.adapter_config = adapter
        self.storage        = 'sftp'
        self.trigger        = adapter.procedure.trigger
        self.adapter        = adapter.procedure.adapter_name.to_s
        self.filename       = adapter.final_file
        self.keep_backups   = adapter.procedure.attributes['keep_backups']

        %w(ip user password path).each do |method|
          send(:"#{method}=", adapter.procedure.get_storage_configuration.attributes[method])
        end
      end

      # Destroys all backups for the specified trigger from Remote Server (SCP)
      def self.destroy_all_backups(procedure, trigger)
        backups = Backup::Record::SFTP.all(:conditions => {:trigger => trigger})
        unless backups.empty?
          ip        = procedure.get_storage_configuration.attributes['ip']
          user      = procedure.get_storage_configuration.attributes['user']
          password  = procedure.get_storage_configuration.attributes['password']

          Net::SFTP.start(ip, user, :password => password) do |sftp|
            backups.each do |backup|
              puts "\nDestroying backup \"#{backup.filename}\" from path \"#{backup.path}\"."
              begin
                sftp.remove!(File.join(backup.path, backup.filename))
                backup.destroy
              rescue
                backup.destroy
              end
            end
          end

         puts "\nAll \"#{trigger}\" backups destroyed.\n\n"
        end
      end

      private

        # Maintains the backup file amount on the remote server
        # This is invoked after a successful record save
        # This deletes the oldest files when the backup limit has been exceeded
        def clean_backups
          if keep_backups.is_a?(Integer)
            backups = Backup::Record::SFTP.all(:conditions => {:trigger => trigger})
            backups_to_destroy = Array.new
            backups.each_with_index do |backup, index|
              if index >= keep_backups then
                backups_to_destroy << backup
              end
            end

            unless backups_to_destroy.empty?
              Net::SFTP.start(ip, user, :password => password) do |sftp|
                backups_to_destroy.each do |backup|
                  puts "\nDestroying backup \"#{backup.filename}\" from path \"#{backup.path}\"."
                  begin
                    sftp.remove!(File.join(backup.path, backup.filename))
                    backup.destroy
                  rescue
                    puts "Could not find backup #{backup.path}/#{backup.filename}.."
                    backup.destroy
                  end
                end
              end

              puts "\nBackup storage for \"#{trigger}\" is limited to #{keep_backups} backups."
              puts "\nThe #{keep_backups} most recent backups are now stored on the remote server.\n\n"
            end
          end
        end

    end
  end
end


text:
Provides facilities to utilize UUIDs with ActiveRecord, including model and migration extensions.

## Installation

Add this line to your application's Gemfile:

    gem 'has_uuid'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install has_uuid

## Usage

In a migration:

    create_table "comments", :id => false, :force => true do |t|
      t.uuid     "id",      :primary_key => true
      t.uuid     "post_id",                       :null => false
    end

In a model:

    class Posts < ActiveRecord::Base
      include WithUuid::Model

      # ...
    end


text:
using System;
using UIKit;
using CoreGraphics;
using CoreText;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Timers;

namespace IOS.Clock
{
	public class MainViewController : UIKit.UIViewController
	{
		#region UI

		private nfloat _clockDiameter = 150f;
		private UIView _clockView;
		private UIView _secondsArrow;
		private UIView _hourseView;
		private UIView _minutesArrow;

		#endregion

		#region Variables

		private int _seconds = 0;
		private int _minutes = 0;
		private int _hours = 0;

		#endregion

		#region overrides

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			this.View.BackgroundColor = UIColor.White;
			InitUI ();
		}

		#endregion

		#region Methods

		private void InitUI ()
		{
			_hours = DateTime.Now.Hour;
			_minutes = DateTime.Now.Minute;
			_seconds = DateTime.Now.Second;

			_clockView = new UIView (new CGRect ((this.View.Frame.Width - _clockDiameter) / 2,
				(this.View.Frame.Height - _clockDiameter) / 2,
				_clockDiameter,
				_clockDiameter));
			_clockView.BackgroundColor = UIColor.Black;
			_clockView.Layer.CornerRadius = _clockDiameter / 2;
			var centerX = _clockView.Frame.Width / 2f;
			var centerY = _clockView.Frame.Height / 2f;

			nfloat littleDotsDiameter = 2f;
			//center Dot
			var mainDot = new UIView (new CGRect (centerX - 2.5f,
				              centerY - 2.5f,
				              littleDotsDiameter + 5f,
				              littleDotsDiameter + 5f));
			mainDot.Layer.CornerRadius = (littleDotsDiameter + 5f) / 2f;
			mainDot.BackgroundColor = UIColor.Red;

			//adding hours dots
			for (int i = 0; i < 12; i++) {
				double x = centerX + (_clockDiameter / 2 - 7f) * Math.Cos (30 * i * Math.PI / 180);
				double y = centerY + (_clockDiameter / 2 - 7f) * Math.Sin (30 * i * Math.PI / 180);

				var dot = new UIView (new CGRect (x - littleDotsDiameter / 2,
					          y - littleDotsDiameter / 2,
					          littleDotsDiameter,
					          littleDotsDiameter));
				dot.Layer.CornerRadius = littleDotsDiameter / 2f;
				dot.BackgroundColor = UIColor.White;
				_clockView.AddSubview (dot);
			}

			//adding seconds arrow
			var arrowWidth = 1.3f;
			var arrowPadding = 12f;
			_secondsArrow = new UIView (new CGRect (centerX,
				12f,
				arrowWidth,
				_clockDiameter / 2 - 12f));

			_secondsArrow.BackgroundColor = UIColor.Clear.FromHexString ("#bcba2c");
			_secondsArrow.Layer.CornerRadius = arrowWidth / 2f;
			_secondsArrow.Layer.AnchorPoint = new CGPoint (0.5, 1);
			_secondsArrow.Layer.Position = new CGPoint (centerX, centerY);

			arrowWidth = 2f;
			arrowPadding -= 3f;
			_minutesArrow = new UIView (new CGRect (centerX,
				15f,
				arrowWidth,
				_clockDiameter / 2 - 15f));

			_minutesArrow.BackgroundColor = UIColor.Clear.FromHexString ("#f1ed12");
			_minutesArrow.Layer.CornerRadius = arrowWidth / 2f;
			_minutesArrow.Layer.AnchorPoint = new CGPoint (0.5, 1);
			_minutesArrow.Layer.Position = new CGPoint (centerX, centerY);

			var hoursWidth = 2.5f;
			arrowPadding -= 5f;
			_hourseView = new UIView (new CGRect (
				centerX - hoursWidth / 2,
				centerY - _clockDiameter / 3f,
				hoursWidth,
				_clockDiameter / 3f
			));

			_hourseView.BackgroundColor = UIColor.White;
			_hourseView.Layer.CornerRadius = hoursWidth / 2f;
			_hourseView.Layer.AnchorPoint = new CGPoint (0.5, 1);
			_hourseView.Layer.Position = new CGPoint (centerX, centerY);

			_clockView.AddSubview (_hourseView);
			_clockView.AddSubview (_minutesArrow);
			_clockView.AddSubview (_secondsArrow);
			_clockView.AddSubview (mainDot);

			var timer = new Timer (100);
			timer.Elapsed += TimerElapsed;
			timer.Enabled = true;

			_minutesArrow.Transform = CGAffineTransform.MakeRotation ((float)Math.PI / 30 * _minutes);
			_hourseView.Transform = CGAffineTransform.MakeRotation ((_hours * (float)Math.PI / 6) +
			(_minutes / 60f) * ((float)Math.PI / 30f));

			View.AddSubview (_clockView);
		}

		void TimerElapsed (object sender, ElapsedEventArgs e)
		{

			_seconds++;
			InvokeOnMainThread (() => {
				_secondsArrow.Transform = CGAffineTransform.MakeRotation ((float)Math.PI / 300 * _seconds);

				if (_seconds == 60 * 10) { // if one minute passed
					_seconds = 0;
					_minutes++;
					_hourseView.Transform = CGAffineTransform.MakeRotation ((_hours * (float)Math.PI / 6) +
					(_minutes / 60f) * ((float)Math.PI / 30f));
				}
				if (_seconds % (5 * 10) == 0) { //if 5 seconds passed
					_minutesArrow.Transform = CGAffineTransform.MakeRotation (((float)Math.PI / 30 * _minutes) + _seconds / 50 * (float)Math.PI / (30 * 12));
				}

				if (_minutes == 60) {
					_minutes = 0;
					_hours++;
				}
			});
		}

		#endregion
	}
}


text:
set :application, 'rgentpl'

# Git repo URL
set :repo_url, 'git@github.com:jatap/rgentpl.git'

# Stages
set :stages, %w(staging production)
set :default_stage, 'production'

# Default deploy_to directory is /var/www/my_app_name
set :deploy_to, -> { "/usr/local/share/console/#{fetch(:application)}" }

# Default value for :format is :pretty
set :format, :pretty

# Default value for :log_level is :debug
set :log_level, :debug

# Default value for :linked_files is [] (persists across deploys)
set :linked_files, fetch(:linked_files, [])

# Default value for linked_dirs is []
set :linked_dirs, fetch(:linked_dirs, [])

# Default value for default_env is {}
set :default_env, {}

# Default value for keep_releases is 5
set :keep_releases, 5

# Rvm
set :rvm_ruby_version, '2.2.1'
set :rvm_custom_path, '/usr/local/rvm'

# Bundle
set :bundle_env_variables, {}
set :bundle_gemfile, -> { release_path.join('Gemfile') }
set :bundle_dir, -> { shared_path.join('bundle') }
set :bundle_flags, '--quiet'
set :bundle_without, %w(development test).join(' ')
set :bundle_jobs, 4
set :bundle_roles, :all


text:
@interface SVEApplicationDelegate ()

@end

@implementation SVEApplicationDelegate

- (NSArray *) services {
    return nil;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    id<UIApplicationDelegate> service;
    for(service in self.services){
        if ([service respondsToSelector:@selector(application:didFinishLaunchingWithOptions:)]){
            [service application:application didFinishLaunchingWithOptions:launchOptions];
        }
    }

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    id<UIApplicationDelegate> service;
    for(service in self.services){
        if ([service respondsToSelector:@selector(applicationWillResignActive:)]){
            [service applicationWillResignActive:application];
        }
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    id<UIApplicationDelegate> service;
    for(service in self.services){
        if ([service respondsToSelector:@selector(applicationDidEnterBackground:)]){
            [service applicationDidEnterBackground:application];
        }
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    id<UIApplicationDelegate> service;
    for(service in self.services){
        if ([service respondsToSelector:@selector(applicationWillEnterForeground:)]){
            [service applicationWillEnterForeground:application];
        }
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    id<UIApplicationDelegate> service;
    for(service in self.services){
        if ([service respondsToSelector:@selector(applicationDidBecomeActive:)]){
            [service applicationDidBecomeActive:application];
        }
    }

}

- (void)applicationWillTerminate:(UIApplication *)application
{
    id<UIApplicationDelegate> service;
    for(service in self.services){
        if ([service respondsToSelector:@selector(applicationWillTerminate:)]){
            [service applicationWillTerminate:application];
        }
    }
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    id<UIApplicationDelegate> service;
    BOOL result = NO;
    for(service in self.services){
        if ([service respondsToSelector:@selector(application:openURL:sourceApplication:annotation:)]){
            result |= [service application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
        }
    }
    return result;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    id<UIApplicationDelegate> service;
    BOOL result = NO;
    for(service in self.services){
        if ([service respondsToSelector:@selector(application:handleOpenURL:)]){
            result |= [service application:application handleOpenURL:url];
        }
    }
    return result;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    id<UIApplicationDelegate> service;
    for(service in self.services){
        if ([service respondsToSelector:@selector(application:didRegisterForRemoteNotificationsWithDeviceToken:)]){
            [service application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
        }
    }

}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    id<UIApplicationDelegate> service;
    for(service in self.services){
        if ([service respondsToSelector:@selector(application:didFailToRegisterForRemoteNotificationsWithError:)]){
            [service application:application didFailToRegisterForRemoteNotificationsWithError:error];
        }
    }
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    id<UIApplicationDelegate> service;
    for(service in self.services){
        if ([service respondsToSelector:@selector(application:didReceiveLocalNotification:)]){
            [service application:application didReceiveLocalNotification:notification];
        }
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    id<UIApplicationDelegate> service;
    for(service in self.services){
        if ([service respondsToSelector:@selector(application:didReceiveRemoteNotification:)]){
            [service application:application didReceiveRemoteNotification:userInfo];
        }
    }

}

@end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="VisualShaderNodeScalarSmoothStep" inherits="VisualShaderNode" version="3.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
	<brief_description>
		Calculates a scalar SmoothStep function within the visual shader graph.
	</brief_description>
	<description>
		Translates to [code]smoothstep(edge0, edge1, x)[/code] in the shader language.
		Returns [code]0.0[/code] if [code]x[/code] is smaller than [code]edge0[/code] and [code]1.0[/code] if [code]x[/code] is larger than [code]edge1[/code]. Otherwise the return value is interpolated between [code]0.0[/code] and [code]1.0[/code] using Hermite polynomials.
	</description>
	<tutorials>
	</tutorials>
	<methods>
	</methods>
	<constants>
	</constants>
</class>


text:
exports.getBodyParts = function() {
    return {};
};

exports.getSummonerTraits = function() {
    return {
        hydraPicker: function(req) {
            return req.queryParams.user || "anonymous";
        }
    };
};


text:
title: Pageload
subtitle: in under 1 second
id: pageload
classes: overlay--90 centered_content
image: speedy-gonzales.jpg
---
1.0 second is how long you have for the user's state of flow to remain uninterrupted


text:
package net.glowstone.net.handler.play.inv;

import com.flowpowered.network.MessageHandler;
import net.glowstone.net.GlowSession;
import net.glowstone.net.message.play.inv.TransactionMessage;

public final class TransactionHandler implements MessageHandler<GlowSession, TransactionMessage> {
    @Override
    public void handle(GlowSession session, TransactionMessage message) {
        //GlowServer.logger.info(session + ": " + message);
    }
}


text:
var Klass = require('asimov-core').Klass;
var Filesystem = require('asimov-core').Filesystem;
var ChildProcess = require('asimov-core').ChildProcess;

var _super = Klass.prototype;
var _ = require('lodash');
var npath = require('path');

var frameworkDir = __dirname.replace(/\/lib$/, '');

var filesystem = new Filesystem();
var mediator = new Klass();
var child = new ChildProcess();

var colors = require('colors');

module.exports = Klass.extend({

  'namespace': 'asimov',

  'lineDelimiter': '\n\n',
  'lines': [],
  'padding': '       ',

  'signature': [
    'asimov.js'.bold,
    'a better way to build awesome websites',
    'and apps, with javascript and textfiles'
  ],

  'initialize': function () {

    var self = this;
    _super.initialize.apply(self, arguments);
    self.options = self.options || {};

    self.options.frameworkDir = frameworkDir;

    self.filesystem = self.options.filesystem || self.filesystem || filesystem;
    self.child = self.options.child || self.child || child;
    self.mediator = self.options.mediator || self.mediator || mediator;
  },

  'logLines': function (lines) {

    var self = this;
    (lines || self.lines).forEach(function (line) {
      console.log(self.padding + line);
    });
  },

  // prohibit use of this method, everyone should use asimov.error
  'error': null,

  'isHiddenPath': function (path) {

    return path[0] === '_' || path.indexOf('/_') >= 0;
  },

  'restart': function (path) {

    var self = this;

    if (process.send) {
      process.send({
        'restart': true
      });
    }
    else {
      process.exit(1);
    }
  }
});


text:
package org.cloudfoundry.reactor.util;

import static io.netty.handler.codec.http.HttpHeaderNames.AUTHORIZATION;

import org.cloudfoundry.reactor.ConnectionContext;
import org.cloudfoundry.reactor.TokenProvider;

import io.netty.util.AsciiString;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;

public abstract class AbstractReactorOperations {

    protected static final AsciiString APPLICATION_ZIP = new AsciiString("application/zip");

    protected final ConnectionContext connectionContext;

    protected final Mono<String> root;

    protected final TokenProvider tokenProvider;

    protected AbstractReactorOperations(ConnectionContext connectionContext, Mono<String> root, TokenProvider tokenProvider) {
        this.connectionContext = connectionContext;
        this.root = root;
        this.tokenProvider = tokenProvider;
    }

    protected Mono<Operator> createOperator() {
        HttpClient httpClient = connectionContext.getHttpClient();
        return root.map(this::buildOperatorContext)
            .map(context -> new Operator(context, httpClient))
            .flatMap(operator -> tokenProvider.getToken(connectionContext)
                .map(token -> setHeaders(operator, token)));
    }

    private OperatorContext buildOperatorContext(String root) {
        return OperatorContext.builder()
            .connectionContext(connectionContext)
            .root(root)
            .tokenProvider(tokenProvider)
            .build();
    }

    private Operator setHeaders(Operator operator, String token) {
        return operator.headers(httpHeaders -> {
            httpHeaders.set(AUTHORIZATION, token);
            UserAgent.setUserAgent(httpHeaders);
            JsonCodec.setDecodeHeaders(httpHeaders);
        });
    }

}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/appengine/v1/appengine.proto

package com.google.appengine.v1;

public interface UpdateDomainMappingRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.appengine.v1.UpdateDomainMappingRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Name of the resource to update. Example:
   * `apps/myapp/domainMappings/example.com`.
   *

   *
   * string name = 1;
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * Name of the resource to update. Example:
   * `apps/myapp/domainMappings/example.com`.
   *

   *
   * string name = 1;
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();

  /**
   *
   *
   *

   * A domain mapping containing the updated resource. Only fields set
   * in the field mask will be updated.
   *

   *
   * .google.appengine.v1.DomainMapping domain_mapping = 2;
   *
   * @return Whether the domainMapping field is set.
   */
  boolean hasDomainMapping();
  /**
   *
   *
   *

   * A domain mapping containing the updated resource. Only fields set
   * in the field mask will be updated.
   *

   *
   * .google.appengine.v1.DomainMapping domain_mapping = 2;
   *
   * @return The domainMapping.
   */
  com.google.appengine.v1.DomainMapping getDomainMapping();
  /**
   *
   *
   *

   * A domain mapping containing the updated resource. Only fields set
   * in the field mask will be updated.
   *

   *
   * .google.appengine.v1.DomainMapping domain_mapping = 2;
   */
  com.google.appengine.v1.DomainMappingOrBuilder getDomainMappingOrBuilder();

  /**
   *
   *
   *

   * Required. Standard field mask for the set of fields to be updated.
   *

   *
   * .google.protobuf.FieldMask update_mask = 3;
   *
   * @return Whether the updateMask field is set.
   */
  boolean hasUpdateMask();
  /**
   *
   *
   *

   * Required. Standard field mask for the set of fields to be updated.
   *

   *
   * .google.protobuf.FieldMask update_mask = 3;
   *
   * @return The updateMask.
   */
  com.google.protobuf.FieldMask getUpdateMask();
  /**
   *
   *
   *

   * Required. Standard field mask for the set of fields to be updated.
   *

   *
   * .google.protobuf.FieldMask update_mask = 3;
   */
  com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder();
}