text:
import os

DATE = 1810221645

# Building Training Set Paramter
FILTERING = 5					# Ingredient-Compounds Pair / Threshold for Least Compounds
RANDOM_SAMPLING = True			# Whether to Random Sample or not
NUM_SAMPLING = 10				# Number of Random Sampling

# Word2Vec Model Parameter
WOR_DIM = 50

# Doc2Vec Model Parameter
CHAR_EMB = False				# Use pre-trained character-level embeddings
DOC_DIM = 10

"""
General Paths
"""

# Result Path
path_results = ".." + os.sep + "results"

# Data Path
path_data = '..' + os.sep + 'data'

"""
Paths for Chemical Compounds Embedding
"""

# File Name Protocol
file_name_compounds_embeddings = '_f-' + str(FILTERING) + '_rs-' + str(RANDOM_SAMPLING) + '_ns-' + str(NUM_SAMPLING) + '_ifcharemb-' + str(CHAR_EMB) + '_dim-' + str(DOC_DIM) + '_' + str(DATE)

path_comp_info = path_data + os.sep + 'scientific_report' + os.sep + 'comp_info.tsv'

# Embeddings for Chemical Compounds
# Chemical Compounds Embedding with Random Initialization
path_embeddings_compounds_rnd = path_results + os.sep + 'embeddings' + os.sep + 'embeddings_compounds_rnd' + file_name_compounds_embeddings + '.bin'

# Chemical Compounds Embedding with Character-level Embedding
path_embeddings_compounds_char = path_results + os.sep + 'embeddings' + os.sep + 'embeddings_compounds_char' + file_name_compounds_embeddings + '.bin'

# Chemical Compounds Embedding with InChiKey Embedding
path_embeddings_compounds_inchi = path_results + os.sep + 'embeddings' + os.sep + 'embeddings_compounds_inchi' + file_name_compounds_embeddings + '.bin'

# Plottings
path_plottings_compounds_category_char = path_results + os.sep + 'plot_compound_embeddings_category_char' + file_name_compounds_embeddings
path_plottings_compounds_category_inchi = path_results + os.sep + 'plot_compound_embeddings_category_inchi' + file_name_compounds_embeddings

path_plottings_compounds_clustering = path_results + os.sep + 'plot_compound_embeddings_cluster' + file_name_compounds_embeddings

"""
Paths for Ingredients Embedding
"""

# File Name Protocol
file_name_ingredient_embeddings = '_f-' + str(FILTERING) + '_rs-' + str(RANDOM_SAMPLING) + '_ns-' + str(NUM_SAMPLING) + '_ifcharemb-' + str(CHAR_EMB) + '_dim-' + str(DOC_DIM) + '_' + str(DATE)

# Data Path
path_ingr_info = path_data + os.sep + 'scientific_report' + os.sep + 'ingr_info.tsv'
path_comp_info = path_data + os.sep + 'scientific_report' + os.sep + 'comp_info.tsv'
path_comp_info_updated = path_data + os.sep + 'scientific_report' + os.sep + 'comp_info_updated.tsv'
path_ingr_comp = path_data + os.sep + 'scientific_report' + os.sep +'ingr_comp.tsv'

path_culture = path_data + os.sep + 'kaggle_and_nature.csv'

# Embeddings for Ingredients
# Ingredient embedding with chemical compounds
path_embeddings_ingredients_cc_rnd = path_results + os.sep + 'embeddings' + os.sep + 'embeddings_ingredients_cc_rnd' + file_name_ingredient_embeddings + '.bin'
path_embeddings_ingredients_cc_char = path_results + os.sep + 'embeddings' + os.sep + 'embeddings_ingredients_cc_char' + file_name_ingredient_embeddings + '.bin'
path_embeddings_ingredients_cc_inchi = path_results + os.sep + 'embeddings' + os.sep + 'embeddings_ingredients_cc_inchi' + file_name_ingredient_embeddings + '.bin'
# Ingredient embedding with other ingredient contexts
path_embeddings_ingredients_ic = path_results + os.sep + 'embeddings' + os.sep + 'embeddings_ingredients_ic' + file_name_ingredient_embeddings + '.bin'

# Plottings
path_plottings_ingredients_category_cc_rnd = path_results + os.sep + 'plot_ingredient_embeddings_category_cc_rnd' + file_name_ingredient_embeddings
path_plottings_ingredients_category_cc_char = path_results + os.sep + 'plot_ingredient_embeddings_category_cc_char' + file_name_ingredient_embeddings
path_plottings_ingredients_category_cc_inchi = path_results + os.sep + 'plot_ingredient_embeddings_category_cc_inchi' + file_name_ingredient_embeddings
path_plottings_ingredients_clustering = path_results + os.sep + 'plot_ingredient_embeddings_cluster' + file_name_ingredient_embeddings

redpajama_set_name: RedPajamaGithub


text:
const READ_COUNT = 'system_read_count';
const CONTRIBUTING_SERVICES = 'contributing_services';

exports.RESERVED_KEYS = {
	READ_COUNT,
	CONTRIBUTING_SERVICES
};

exports.create = data => {
	const raw = Object.assign({}, data);

	raw[READ_COUNT] = (raw[READ_COUNT] === undefined ? -1 : raw[READ_COUNT]) + 1;
	raw[CONTRIBUTING_SERVICES] = (raw[CONTRIBUTING_SERVICES] || []);

	const toJSON = () => Object.assign({}, raw);

	const cloneWithService = serviceName => exports.create(Object.assign({}, raw, {
		[CONTRIBUTING_SERVICES]: raw[CONTRIBUTING_SERVICES].concat(serviceName),
		[READ_COUNT]: raw[READ_COUNT] - 2
	}));

	const api = {toJSON, cloneWithService};

	return new Proxy(raw, {
		get(object, name) {
			return (object[name] || api[name]);
		},
		set(object, name, value) {
			if (Object.values(exports.RESERVED_KEYS).includes(name)) {
				throw new Error(`"${name}" is a reserved key.`);
			}
			object[name] = value;
			return true;
		}
	});
};


text:
package java.sql;

import java.io.Serializable;

/**
 * An Exception class that is used in conjunction with JDBC operations. It
 * provides information about problems encountered with Database access and
 * other problems related to JDBC
 *

 * The SQLException class provides the following information:
 *

 *
A standard Java exception message, as a String
 *
An SQLState string. This is an error description string which follows
 * either the SQL 99 conventions or the XOPEN SQLstate conventions. The
 * potential values of the SQLState string are described in each of the
 * specifications. Which of the conventions is being used by the SQLState string
 * can be discovered by using the getSQLStateType method of the DatabaseMetaData
 * interface.
 *
An Error Code, an an integer. The error code is specific to each
 * database vendor and is typically the error code returned by the database
 * itself.
 *
A chain to a next Exception, if relevant, which can give access to
 * additional error information.
 *

 */
public class SQLException extends Exception implements Serializable {

    private static final long serialVersionUID = 2135244094396331484L;

    private String SQLState = null;

    private int vendorCode = 0;

    private SQLException next = null;

    /**
     * Creates an SQLException object. The Reason string is set to null, the
     * SQLState string is set to null and the Error Code is set to 0.
     */
    public SQLException() {
        super();
    }

    /**
     * Creates an SQLException object. The Reason string is set to the given
     * reason string, the SQLState string is set to null and the Error Code is
     * set to 0.
     *
     * @param theReason
     *            the string to use as the Reason string
     */
    public SQLException(String theReason) {
        this(theReason, null, 0);
    }

    /**
     * Creates an SQLException object. The Reason string is set to the given
     * reason string, the SQLState string is set to the given SQLState string
     * and the Error Code is set to 0.
     *
     * @param theReason
     *            the string to use as the Reason string
     * @param theSQLState
     *            the string to use as the SQLState string
     */
    public SQLException(String theReason, String theSQLState) {
        this(theReason, theSQLState, 0);
    }

    /**
     * Creates an SQLException object. The Reason string is set to the given
     * reason string, the SQLState string is set to the given SQLState string
     * and the Error Code is set to the given error code value.
     *
     * @param theReason
     *            the string to use as the Reason string
     * @param theSQLState
     *            the string to use as the SQLState string
     * @param theErrorCode
     *            the integer value for the error code
     */
    public SQLException(String theReason, String theSQLState, int theErrorCode) {
        super(theReason);
        SQLState = theSQLState;
        vendorCode = theErrorCode;
    }

    /**
     * Returns the integer error code for this SQLException
     *
     * @return The integer error code for this SQLException. The meaning of the
     *         code is specific to the vendor of the database.
     */
    public int getErrorCode() {
        return vendorCode;
    }

    /**
     * Retrieves the SQLException chained to this SQLException, if any.
     *
     * @return The SQLException chained to this SQLException. null if there is
     *         no SQLException chained to this SQLException.
     */
    public SQLException getNextException() {
        return next;
    }

    /**
     * Retrieves the SQLState description string for this SQLException object
     *
     * @return The SQLState string for this SQLException object. This is an
     *         error description string which follows either the SQL 99
     *         conventions or the XOPEN SQLstate conventions. The potential
     *         values of the SQLState string are described in each of the
     *         specifications. Which of the conventions is being used by the
     *         SQLState string can be discovered by using the getSQLStateType
     *         method of the DatabaseMetaData interface.
     */
    public String getSQLState() {
        return SQLState;
    }

    /**
     * Adds the SQLException to the end of this SQLException chain.
     *
     * @param ex
     *            the new SQLException to be added to the end of the chain
     */
    public void setNextException(SQLException ex) {
        if (next != null) {
            next.setNextException(ex);
        } else {
            next = ex;
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.implementation.query;

import com.azure.cosmos.BridgeInternal;
import com.azure.cosmos.CosmosException;
import com.azure.cosmos.implementation.BadRequestException;
import com.azure.cosmos.implementation.ClientSideRequestStatistics;
import com.azure.cosmos.implementation.DiagnosticsClientContext;
import com.azure.cosmos.implementation.Document;
import com.azure.cosmos.implementation.DocumentClientRetryPolicy;
import com.azure.cosmos.implementation.HttpConstants;
import com.azure.cosmos.implementation.QueryMetrics;
import com.azure.cosmos.implementation.RequestChargeTracker;
import com.azure.cosmos.implementation.ResourceId;
import com.azure.cosmos.implementation.ResourceType;
import com.azure.cosmos.implementation.RxDocumentServiceRequest;
import com.azure.cosmos.implementation.Undefined;
import com.azure.cosmos.implementation.Utils;
import com.azure.cosmos.implementation.Utils.ValueHolder;
import com.azure.cosmos.implementation.apachecommons.lang.tuple.ImmutablePair;
import com.azure.cosmos.implementation.apachecommons.lang.tuple.Pair;
import com.azure.cosmos.implementation.feedranges.FeedRangeEpkImpl;
import com.azure.cosmos.implementation.query.orderbyquery.ComparisonFilters;
import com.azure.cosmos.implementation.query.orderbyquery.ComparisonWithDefinedFilters;
import com.azure.cosmos.implementation.query.orderbyquery.ComparisonWithUndefinedFilters;
import com.azure.cosmos.implementation.query.orderbyquery.OrderByRowResult;
import com.azure.cosmos.implementation.query.orderbyquery.OrderbyRowComparer;
import com.azure.cosmos.implementation.routing.Range;
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.models.FeedResponse;
import com.azure.cosmos.models.ModelBridgeInternal;
import com.azure.cosmos.models.SqlQuerySpec;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.regex.Pattern;

/**
 * While this class is public, but it is not part of our published public APIs.
 * This is meant to be internally used only by our sdk.
 */
public class OrderByDocumentQueryExecutionContext
        extends ParallelDocumentQueryExecutionContextBase<Document> {
    private final static String FormatPlaceHolder = "{documentdb-formattableorderbyquery-filter}";
    private final static String True = "true";
    private static final Pattern QUOTE_PATTERN = Pattern.compile("\"");
    private final String collectionRid;
    private final OrderbyRowComparer<Document> consumeComparer;
    private final RequestChargeTracker tracker;
    private final ConcurrentMap<String, QueryMetrics> queryMetricMap;
    private final List<ClientSideRequestStatistics> clientSideRequestStatisticsList;
    private Flux<OrderByRowResult<Document>> orderByObservable;
    private final Map<FeedRangeEpkImpl, OrderByContinuationToken> targetRangeToOrderByContinuationTokenMap;

    private OrderByDocumentQueryExecutionContext(
            DiagnosticsClientContext diagnosticsClientContext,
            IDocumentQueryClient client,
            ResourceType resourceTypeEnum,
            SqlQuerySpec query,
            CosmosQueryRequestOptions cosmosQueryRequestOptions,
            String resourceLink,
            String rewrittenQuery,
            OrderbyRowComparer<Document> consumeComparer,
            String collectionRid,
            UUID correlatedActivityId,
            boolean hasSelectValue) {
        super(diagnosticsClientContext, client, resourceTypeEnum, Document.class, query, cosmosQueryRequestOptions,
            resourceLink, rewrittenQuery, correlatedActivityId, hasSelectValue);
        this.collectionRid = collectionRid;
        this.consumeComparer = consumeComparer;
        this.tracker = new RequestChargeTracker();
        this.queryMetricMap = new ConcurrentHashMap<>();
        this.clientSideRequestStatisticsList = Collections.synchronizedList(new ArrayList<>());
        targetRangeToOrderByContinuationTokenMap = new ConcurrentHashMap<>();
    }

    public static Flux<IDocumentQueryExecutionComponent<Document>> createAsync(
            DiagnosticsClientContext diagnosticsClientContext,
            IDocumentQueryClient client,
            PipelinedDocumentQueryParams<Document> initParams) {

        QueryInfo queryInfo = initParams.getQueryInfo();

        OrderByDocumentQueryExecutionContext context = new OrderByDocumentQueryExecutionContext(diagnosticsClientContext,
                client,
                initParams.getResourceTypeEnum(),
                initParams.getQuery(),
                initParams.getCosmosQueryRequestOptions(),
                initParams.getResourceLink(),
                initParams.getQueryInfo().getRewrittenQuery(),
                new OrderbyRowComparer<>(queryInfo.getOrderBy()),
                initParams.getCollectionRid(),
                initParams.getCorrelatedActivityId(),
                queryInfo.hasSelectValue());

        context.setTop(initParams.getTop());

        try {
            context.initialize(
                    initParams.getFeedRanges(),
                    initParams.getQueryInfo().getOrderBy(),
                    initParams.getQueryInfo().getOrderByExpressions(),
                    initParams.getInitialPageSize(),
                    ModelBridgeInternal.getRequestContinuationFromQueryRequestOptions(initParams.getCosmosQueryRequestOptions()));

            return Flux.just(context);
        } catch (CosmosException dce) {
            return Flux.error(dce);
        }
    }

    private void initialize(
        List<FeedRangeEpkImpl> feedRanges, List<SortOrder> sortOrders,
        Collection<String> orderByExpressions,
        int initialPageSize,
        String continuationToken) throws CosmosException {
        if (continuationToken == null) {
            // First iteration so use null continuation tokens and "true" filters
            Map<FeedRangeEpkImpl, String> partitionKeyRangeToContinuationToken = new HashMap<>();
            for (FeedRangeEpkImpl feedRangeEpk : feedRanges) {
                partitionKeyRangeToContinuationToken.put(feedRangeEpk,
                        null);
            }
            super.initialize(collectionRid,
                    partitionKeyRangeToContinuationToken,
                    initialPageSize,
                    new SqlQuerySpec(querySpec.getQueryText().replace(FormatPlaceHolder, True),
                            querySpec.getParameters()));
        } else {
            // Check to see if order by continuation token is a valid JSON.
            OrderByContinuationToken orderByContinuationToken;
            ValueHolder<OrderByContinuationToken> outOrderByContinuationToken = new ValueHolder<OrderByContinuationToken>();
            if (!OrderByContinuationToken.tryParse(continuationToken,
                    outOrderByContinuationToken)) {
                String message = String.format("INVALID JSON in continuation token %s for OrderBy~Context",
                        continuationToken);
                throw BridgeInternal.createCosmosException(HttpConstants.StatusCodes.BADREQUEST,
                        message);
            }

            orderByContinuationToken = outOrderByContinuationToken.v;

            CompositeContinuationToken compositeContinuationToken = orderByContinuationToken
                    .getCompositeContinuationToken();
            // Check to see if the ranges inside are valid
            if (compositeContinuationToken.getRange().isEmpty()) {
                String message = String.format("INVALID RANGE in the continuation token %s for OrderBy~Context.",
                        continuationToken);
                throw BridgeInternal.createCosmosException(HttpConstants.StatusCodes.BADREQUEST,
                        message);
            }

            // Checking early if the token has a valid resource id
            Pair<Boolean, ResourceId> booleanResourceIdPair = ResourceId.tryParse(orderByContinuationToken.getRid());
            if (!booleanResourceIdPair.getLeft()) {
                throw new BadRequestException(String.format("INVALID Rid in the continuation token %s for " +
                                                             "OrderBy~Context.",
                                                                        orderByContinuationToken.getCompositeContinuationToken().getToken()));
            }

            // At this point the token is valid.
            FormattedFilterInfo formattedFilterInfo = this.getFormattedFilters(orderByExpressions,
                                                                               orderByContinuationToken
                                                                                .getOrderByItems(),
                                                                               sortOrders,
                                                                               orderByContinuationToken.getInclusive());

            PartitionMapper.PartitionMapping<OrderByContinuationToken> partitionMapping =
                PartitionMapper.getPartitionMapping(feedRanges, Collections.singletonList(orderByContinuationToken));

            initializeWithTokenAndFilter(partitionMapping.getMappingLeftOfTarget(), initialPageSize,
                                         formattedFilterInfo.filterForRangesLeftOfTheTargetRange);
            initializeWithTokenAndFilter(partitionMapping.getTargetMapping(), initialPageSize,
                                         formattedFilterInfo.filterForTargetRange);
            initializeWithTokenAndFilter(partitionMapping.getMappingRightOfTarget(), initialPageSize,
                                         formattedFilterInfo.filterForRangesRightOfTheTargetRange);
        }

        orderByObservable = OrderByUtils.orderedMerge(
                consumeComparer,
                tracker,
                documentProducers,
                queryMetricMap,
                targetRangeToOrderByContinuationTokenMap,
                clientSideRequestStatisticsList);
    }

    private void initializeWithTokenAndFilter(Map<FeedRangeEpkImpl, OrderByContinuationToken> rangeToTokenMapping,
                                              int initialPageSize,
                                              String filter) {
        for (Map.Entry<FeedRangeEpkImpl, OrderByContinuationToken> entry :
            rangeToTokenMapping.entrySet()) {
            //  only put the entry if the value is not null
            if (entry.getValue() != null) {
                targetRangeToOrderByContinuationTokenMap.put(entry.getKey(), entry.getValue());
            }
            Map<FeedRangeEpkImpl, String> partitionKeyRangeToContinuationToken = new HashMap<FeedRangeEpkImpl, String>();
            partitionKeyRangeToContinuationToken.put(entry.getKey(), null);
            super.initialize(collectionRid,
                             partitionKeyRangeToContinuationToken,
                             initialPageSize,
                             new SqlQuerySpec(querySpec.getQueryText().replace(FormatPlaceHolder,
                                                                               filter),
                                              querySpec.getParameters()));

        }
    }

    private OrderByDocumentQueryExecutionContext.FormattedFilterInfo getFormattedFilters(
            Collection<String> orderByExpressionCollection,
            QueryItem[] orderByItems,
            Collection<SortOrder> sortOrderCollection,
            boolean inclusive) {
        // Convert to arrays
        SortOrder[] sortOrders = new SortOrder[sortOrderCollection.size()];
        sortOrderCollection.toArray(sortOrders);

        String[] expressions = new String[orderByExpressionCollection.size()];
        orderByExpressionCollection.toArray(expressions);

        // Validate the inputs
        if (expressions.length != sortOrders.length) {
            throw new IllegalArgumentException("expressions.size() != sortOrders.size()");
        }

        if (expressions.length != orderByItems.length) {
            throw new IllegalArgumentException("expressions.size() != orderByItems.length");
        }

        // When we run cross partition queries,
        // we only serialize the continuation token for the partition that we left off
        // on.
        // The only problem is that when we resume the order by query,
        // we don't have continuation tokens for all other partitions.
        // The saving grace is that the data has a composite sort order(query sort
        // order, partition key range id)
        // so we can generate range filters which in turn the backend will turn into rid
        // based continuation tokens,
        // which is enough to get the streams of data flowing from all partitions.
        // The details of how this is done is described below:

        int numOrderByItems = expressions.length;
        boolean isSingleOrderBy = numOrderByItems == 1;
        StringBuilder left = new StringBuilder();
        StringBuilder target = new StringBuilder();
        StringBuilder right = new StringBuilder();

        if (isSingleOrderBy) {
            // For a single order by query we resume the continuations in this manner
            // Suppose the query is SELECT* FROM c ORDER BY c.string ASC
            // And we left off on partition N with the value "B"
            // Then
            // ALL the partitions to the left will have finished reading "B"
            // Partition N is still reading "B"
            // ALL the partitions to the right have let to read a "B
            // Therefore the filters should be
            // > "B" , >= "B", and >= "B" respectively
            // Repeat the same logic for DESC and you will get
            // < "B", <= "B", and <= "B" respectively
            // The general rule becomes
            // For ASC
            // > for partitions to the left
            // >= for the partition we left off on
            // >= for the partitions to the right
            // For DESC
            // < for partitions to the left
            // <= for the partition we left off on
            // <= for the partitions to the right
            String expression = expressions[0];
            SortOrder sortOrder = sortOrders[0];
            QueryItem orderByItem = orderByItems[0];
            Object rawItem = orderByItem.getItem();

            this.appendToBuilders(left, target, right, "(");

            String orderByItemToString = this.getOrderByItemString(rawItem);

             // Handling undefined needs filter literals
             // What we really want is to support expression > undefined,
             // but the engine evaluates to undefined instead of true or false,
             // so we work around this by using the IS_DEFINED() system function
             // ComparisonWithUndefinedFilters is used to handle the logic mentioned above
            ComparisonFilters filters =
                rawItem == Undefined.value() ? new ComparisonWithUndefinedFilters(expression) : new ComparisonWithDefinedFilters(expression, orderByItemToString);

            left.append(sortOrder == SortOrder.Descending ? filters.lessThan() : filters.greaterThan());
            if (inclusive) {
                target.append(sortOrder == SortOrder.Descending ? filters.lessThanOrEqualTo() : filters.greaterThanOrEqualTo());
            } else {
                target.append(sortOrder == SortOrder.Descending ? filters.lessThan() : filters.greaterThan());
            }
            right.append(sortOrder == SortOrder.Descending ? filters.lessThanOrEqualTo() : filters.greaterThanOrEqualTo());

            // Now we need to include all the types that match the sort order.
            List<String> definedFunctions =
                IsSystemFunctions.getIsDefinedFunctions(ItemTypeHelper.getOrderByItemType(rawItem),
                                                        sortOrder == SortOrder.Ascending);
            StringBuilder isDefinedFuncBuilder = new StringBuilder();
            for (String idf : definedFunctions) {
                isDefinedFuncBuilder.append(" OR ");
                isDefinedFuncBuilder.append(String.format("%s(%s)", idf, expression));
            }

            String isDefinedFunctions = isDefinedFuncBuilder.toString();
            left.append(isDefinedFunctions);
            target.append(isDefinedFunctions);
            right.append(isDefinedFunctions);

            this.appendToBuilders(left, target, right, ")");

        } else {
            // For a multi order by query
            // Suppose the query is SELECT* FROM c ORDER BY c.string ASC, c.number ASC
            // And we left off on partition N with the value("A", 1)
            // Then
            //      All the partitions to the left will have finished reading("A", 1)
            //      Partition N is still reading("A", 1)
            //      All the partitions to the right have let to read a "(A", 1)
            // The filters are harder to derive since there are multiple columns
            // But the problem reduces to "How do you know one document comes after another in a multi order by query"
            // The answer is to just look at it one column at a time.
            // For this particular scenario:
            //      If a first column is greater ex. ("B", blah), then the document comes later in the sort order
            //      Therefore we want all documents where the first column is greater than "A" which means > "A"
            //      Or if the first column is a tie, then you look at the second column ex. ("A", blah).
            //      Therefore we also want all documents where the first column was a tie but the second column is greater which means = "A" AND > 1
            //      Therefore the filters should be
            //      (> "A") OR (= "A" AND > 1), (> "A") OR (= "A" AND >= 1), (> "A") OR (= "A" AND >= 1)
            //      Notice that if we repeated the same logic we for single order by we would have gotten
            //      > "A" AND > 1, >= "A" AND >= 1, >= "A" AND >= 1
            //      which is wrong since we missed some documents
            //      Repeat the same logic for ASC, DESC
            //          (> "A") OR (= "A" AND < 1), (> "A") OR (= "A" AND <= 1), (> "A") OR (= "A" AND <= 1)
            //      Again for DESC, ASC
            //          (< "A") OR (= "A" AND > 1), (< "A") OR (= "A" AND >= 1), (< "A") OR (= "A" AND >= 1)
            //      And again for DESC DESC
            //          (< "A") OR (= "A" AND < 1), (< "A") OR (= "A" AND <= 1), (< "A") OR (= "A" AND <= 1)
            //      The general we look at all prefixes of the order by columns to look for tie breakers.
            //      Except for the full prefix whose last column follows the rules for single item order by
            //      And then you just OR all the possibilities together

            for (int prefixLength = 1; prefixLength <= numOrderByItems; prefixLength++) {
                boolean lastPrefix = prefixLength == numOrderByItems;

                this.appendToBuilders(left, target, right, "(");

                for (int index = 0; index < prefixLength; index++) {
                    String expression = expressions[index];
                    SortOrder sortOrder = sortOrders[index];
                    QueryItem orderbyItem = orderByItems[index];
                    Object orderbyRawItem = orderbyItem.getItem();

                    boolean lastItem = index == prefixLength - 1;

                    this.appendToBuilders(left, target, right, "(");
                    String orderByItemToString = getOrderByItemString(orderbyRawItem);
                    ComparisonFilters filters =
                        orderbyRawItem == Undefined.value() ? new ComparisonWithUndefinedFilters((expression)) : new ComparisonWithDefinedFilters(expression, orderByItemToString);

                    if (lastItem) {
                        if (lastPrefix) {
                            left.append(sortOrder == SortOrder.Descending ? filters.lessThan() : filters.greaterThan());

                            if (inclusive) {
                                target.append(sortOrder == SortOrder.Descending ? filters.lessThanOrEqualTo() : filters.greaterThanOrEqualTo());
                            } else {
                                target.append(sortOrder == SortOrder.Descending ? filters.lessThan() : filters.greaterThan());
                            }

                            right.append(sortOrder == SortOrder.Descending ? filters.lessThanOrEqualTo() : filters.greaterThanOrEqualTo());
                        } else {
                            left.append(sortOrder == SortOrder.Descending ? filters.lessThan() : filters.greaterThan());
                            target.append(sortOrder == SortOrder.Descending ? filters.lessThan() : filters.greaterThan());
                            right.append(sortOrder == SortOrder.Descending ? filters.lessThan() : filters.greaterThan());
                        }

                    } else {
                        left.append(filters.equalTo());
                        target.append(filters.equalTo());
                        right.append(filters.equalTo());
                    }

                    if (lastItem) {
                        // Now we need to include all the types that match the sort order.
                        List<String> definedFunctions =
                            IsSystemFunctions.getIsDefinedFunctions(ItemTypeHelper.getOrderByItemType(orderbyRawItem),
                                sortOrder == SortOrder.Ascending);
                        StringBuilder isDefinedFuncBuilder = new StringBuilder();
                        for (String idf : definedFunctions) {
                            isDefinedFuncBuilder.append(" OR ");
                            isDefinedFuncBuilder.append(String.format("%s(%s)", idf, expression));
                        }

                        String isDefinedFunctions = isDefinedFuncBuilder.toString();
                        left.append(isDefinedFunctions);
                        target.append(isDefinedFunctions);
                        right.append(isDefinedFunctions);
                    }

                    this.appendToBuilders(left, target, right, ")");
                    if (!lastItem) {
                        this.appendToBuilders(left, target, right, " AND ");
                    }
                }

                this.appendToBuilders(left, target, right, ")");
                if (!lastPrefix) {
                    this.appendToBuilders(left, target, right, " OR ");
                }
            }
        }

        return new FormattedFilterInfo(left.toString(),
                target.toString(),
                right.toString());
    }

    private String getOrderByItemString(Object orderbyRawItem) {
        String orderByItemToString;
        if (orderbyRawItem instanceof String) {
            orderByItemToString = "\"" + QUOTE_PATTERN.matcher(orderbyRawItem.toString()).replaceAll("\\\"") + "\"";
        } else {
            if (orderbyRawItem != null) {
                orderByItemToString = orderbyRawItem.toString();
            } else {
                orderByItemToString = "null";
            }
        }

        return orderByItemToString;
    }

    private void appendToBuilders(StringBuilder leftBuilder, StringBuilder targetBuilder, StringBuilder rightBuilder, String appendText) {
        this.appendToBuilders(leftBuilder, targetBuilder, rightBuilder, appendText, appendText, appendText);
    }

    private void appendToBuilders(
        StringBuilder leftBuilder,
        StringBuilder targetBuilder,
        StringBuilder rightBuilder,
        String leftAppendText,
        String targetAppendText,
        String rightAppendText) {

        leftBuilder.append(leftAppendText);
        targetBuilder.append(targetAppendText);
        rightBuilder.append(rightAppendText);
    }

    static class IsSystemFunctions {
        static final String Defined = "IS_DEFINED";
        static final String NotDefined = "NOT IS_DEFINED";
        static final String Null = "IS_NULL";
        static final String Boolean = "IS_BOOLEAN";
        static final String Number = "IS_NUMBER";
        static final String IsString = "IS_STRING";
        static final String Array = "IS_ARRAY";
        static final String Object = "IS_OBJECT";

        static final List<String> systemFunctionSortOrder = Arrays.asList(IsSystemFunctions.NotDefined,
                                                                          IsSystemFunctions.Null,
                                                                          IsSystemFunctions.Boolean,
                                                                          IsSystemFunctions.Number,
                                                                          IsSystemFunctions.IsString,
                                                                          IsSystemFunctions.Array,
                                                                          IsSystemFunctions.Object);

        final List<String> extendedTypesSystemFunctionSortOrder = Arrays.asList(IsSystemFunctions.NotDefined,
                                                                          IsSystemFunctions.Defined);

        private static class SortOrder {
            public static final int Undefined = 0;
            public static final int Null = 1;
            public static final int Boolean = 2;
            public static final int Number = 3;
            public static final int String = 4;
            public static final int Array = 5;
            public static final int Object = 6;
        }

        private static class ExtendedTypesSortOrder {
            public static final int Undefined = 0;
            public static final int Defined = 1;
        }

        public static List<String> getIsDefinedFunctions(ItemType itemtype, boolean isAscending) {
            switch (itemtype) {
                case NoValue:
                    return getIsDefinedFunctionsInternal(SortOrder.Undefined, isAscending);
                case Null:
                    return getIsDefinedFunctionsInternal(SortOrder.Null, isAscending);
                case Boolean:
                    return getIsDefinedFunctionsInternal(SortOrder.Boolean, isAscending);
                case Number:
                    return getIsDefinedFunctionsInternal(SortOrder.Number, isAscending);
                case String:
                    return getIsDefinedFunctionsInternal(SortOrder.String, isAscending);
                case ArrayNode:
                    return getIsDefinedFunctionsInternal(SortOrder.Array, isAscending);
                case ObjectNode:
                    return getIsDefinedFunctionsInternal(SortOrder.Object, isAscending);
            }
            return null;
        }

        private static List<String> getIsDefinedFunctionsInternal(int index, boolean isAscending) {
            return isAscending ? systemFunctionSortOrder.subList(index + 1, systemFunctionSortOrder.size())
                       : systemFunctionSortOrder.subList(0, index);
        }

        // For future use
        List<String> getExtendedTypesIsDefinedFunctions(int index, boolean isAscending) {
            return isAscending ?
                       extendedTypesSystemFunctionSortOrder.subList(index + 1,
                                                                    extendedTypesSystemFunctionSortOrder.size())
                       : extendedTypesSystemFunctionSortOrder.subList(0, index);
        }
    }

    @Override
    protected OrderByDocumentProducer createDocumentProducer(
            String collectionRid,
            String continuationToken,
            int initialPageSize,
            CosmosQueryRequestOptions cosmosQueryRequestOptions,
            SqlQuerySpec querySpecForInit,
            Map<String, String> commonRequestHeaders,
            TriFunction<FeedRangeEpkImpl, String, Integer, RxDocumentServiceRequest> createRequestFunc,
            Function<RxDocumentServiceRequest, Mono<FeedResponse<Document>>> executeFunc,
            Callable<DocumentClientRetryPolicy> createRetryPolicyFunc, FeedRangeEpkImpl feedRange) {
        return new OrderByDocumentProducer(consumeComparer,
                client,
                collectionRid,
                cosmosQueryRequestOptions,
                createRequestFunc,
                executeFunc,
                feedRange,
                collectionRid,
                createRetryPolicyFunc,
                resourceType,
                correlatedActivityId,
                initialPageSize,
                continuationToken,
                top,
                this.targetRangeToOrderByContinuationTokenMap,
                this.getOperationContextTextProvider());
    }

    private static class ItemToPageTransformer
            implements Function<Flux<OrderByRowResult<Document>>, Flux<FeedResponse<Document>>> {
        private final static int DEFAULT_PAGE_SIZE = 100;
        private final RequestChargeTracker tracker;
        private final int maxPageSize;
        private final ConcurrentMap<String, QueryMetrics> queryMetricMap;
        private final Function<OrderByRowResult<Document>, String> orderByContinuationTokenCallback;
        private final List<ClientSideRequestStatistics> clientSideRequestStatisticsList;
        private volatile FeedResponse<OrderByRowResult<Document>> previousPage;

        public ItemToPageTransformer(
            RequestChargeTracker tracker,
            int maxPageSize,
            ConcurrentMap<String, QueryMetrics> queryMetricsMap,
            Function<OrderByRowResult<Document>, String> orderByContinuationTokenCallback,
            List<ClientSideRequestStatistics> clientSideRequestStatisticsList) {
            this.tracker = tracker;
            this.maxPageSize = maxPageSize > 0 ? maxPageSize : DEFAULT_PAGE_SIZE;
            this.queryMetricMap = queryMetricsMap;
            this.orderByContinuationTokenCallback = orderByContinuationTokenCallback;
            this.previousPage = null;
            this.clientSideRequestStatisticsList = clientSideRequestStatisticsList;
        }

        private static Map<String, String> headerResponse(
                double requestCharge) {
            return Utils.immutableMapOf(HttpConstants.HttpHeaders.REQUEST_CHARGE,
                    String.valueOf(requestCharge));
        }

        private FeedResponse<OrderByRowResult<Document>> addOrderByContinuationToken(
                FeedResponse<OrderByRowResult<Document>> page,
                String orderByContinuationToken) {
            Map<String, String> headers = new HashMap<>(page.getResponseHeaders());
            headers.put(HttpConstants.HttpHeaders.CONTINUATION,
                    orderByContinuationToken);
            return BridgeInternal.createFeedResponseWithQueryMetrics(page.getResults(),
                headers,
                BridgeInternal.queryMetricsFromFeedResponse(page),
                ModelBridgeInternal.getQueryPlanDiagnosticsContext(page),
                false,
                false,
                page.getCosmosDiagnostics());
        }

        @Override
        public Flux<FeedResponse<Document>> apply(Flux<OrderByRowResult<Document>> source) {
            return source
                    // .windows: creates an observable of observable where inner observable
                    // emits max maxPageSize elements
                    .window(maxPageSize).map(Flux::collectList)
                    // flattens the observable<Observable<List<OrderByRowResult<T>>>> to
                    // Observable<List<OrderByRowResult<T>>>
                    .flatMap(resultListObs -> resultListObs,
                            1)
                    // translates Observable<List<OrderByRowResult<T>>> to
                    // Observable<FeedResponsePage<OrderByRowResult<T>>>>
                    .map(orderByRowResults -> {
                        // construct a page from result with request charge
                        FeedResponse<OrderByRowResult<Document>> feedResponse = BridgeInternal.createFeedResponse(
                                orderByRowResults,
                                headerResponse(tracker.getAndResetCharge()));
                        if (!queryMetricMap.isEmpty()) {
                            for (Map.Entry<String, QueryMetrics> entry : queryMetricMap.entrySet()) {
                                BridgeInternal.putQueryMetricsIntoMap(feedResponse,
                                    entry.getKey(),
                                    entry.getValue());
                            }
                        }
                        return feedResponse;
                    })
                    // Emit an empty page so the downstream observables know when there are no more
                    // results.
                    .concatWith(Flux.defer(() -> {
                        return Flux.just(BridgeInternal.createFeedResponse(Utils.immutableListOf(),
                                null));
                    }))
                    // CREATE pairs from the stream to allow the observables downstream to "peek"
                    // 1, 2, 3, null -> (null, 1), (1, 2), (2, 3), (3, null)
                    .map(orderByRowResults -> {
                        ImmutablePair<FeedResponse<OrderByRowResult<Document>>, FeedResponse<OrderByRowResult<Document>>> previousCurrent =
                            new ImmutablePair<FeedResponse<OrderByRowResult<Document>>, FeedResponse<OrderByRowResult<Document>>>(
                                this.previousPage,
                                orderByRowResults);
                        this.previousPage = orderByRowResults;
                        return previousCurrent;
                    })
                    // remove the (null, 1)
                    .skip(1)
                    // Add the continuation token based on the current and next page.
                    .map(currentNext -> {
                        FeedResponse<OrderByRowResult<Document>> current = currentNext.left;
                        FeedResponse<OrderByRowResult<Document>> next = currentNext.right;

                        FeedResponse<OrderByRowResult<Document>> page;
                        if (next.getResults().size() == 0) {
                            // No more pages no send current page with null continuation token
                            page = current;
                            page = this.addOrderByContinuationToken(page,
                                    null);
                        } else {
                            // Give the first page but use the first value in the next page to generate the
                            // continuation token
                            page = current;
                            List<OrderByRowResult<Document>> results = next.getResults();
                            OrderByRowResult<Document> firstElementInNextPage = results.get(0);
                            String orderByContinuationToken = this.orderByContinuationTokenCallback
                                    .apply(firstElementInNextPage);
                            page = this.addOrderByContinuationToken(page,
                                    orderByContinuationToken);
                        }

                        return page;
                    }).map(feedOfOrderByRowResults -> {
                        // FeedResponse<OrderByRowResult<T>> to FeedResponse<T>
                        List<Document> unwrappedResults = new ArrayList<>();
                        for (OrderByRowResult<Document> orderByRowResult : feedOfOrderByRowResults.getResults()) {
                            unwrappedResults.add(orderByRowResult.getPayload());
                        }

                    FeedResponse<Document> feedResponse = BridgeInternal.createFeedResponseWithQueryMetrics(unwrappedResults,
                        feedOfOrderByRowResults.getResponseHeaders(),
                        BridgeInternal.queryMetricsFromFeedResponse(feedOfOrderByRowResults),
                        ModelBridgeInternal.getQueryPlanDiagnosticsContext(feedOfOrderByRowResults),
                        false,
                        false, feedOfOrderByRowResults.getCosmosDiagnostics());
                    BridgeInternal.addClientSideDiagnosticsToFeed(feedResponse.getCosmosDiagnostics(),
                                                                  clientSideRequestStatisticsList);
                    return feedResponse;
                }).switchIfEmpty(Flux.defer(() -> {
                        // create an empty page if there is no result
                    FeedResponse<Document> frp =  BridgeInternal.createFeedResponseWithQueryMetrics(Utils.immutableListOf(),
                                headerResponse(
                                    tracker.getAndResetCharge()),
                            queryMetricMap,
                            null,
                            false,
                            false,
                            null);
                    BridgeInternal.addClientSideDiagnosticsToFeed(frp.getCosmosDiagnostics(),
                                                                  clientSideRequestStatisticsList);
                    return Flux.just(frp);
                    }));
        }
    }

    @Override
    public Flux<FeedResponse<Document>> drainAsync(
            int maxPageSize) {
        //// In order to maintain the continuation token for the user we must drain with
        //// a few constraints
        //// 1) We always drain from the partition, which has the highest priority item
        //// first
        //// 2) If multiple partitions have the same priority item then we drain from
        //// the left most first
        //// otherwise we would need to keep track of how many of each item we drained
        //// from each partition
        //// (just like parallel queries).
        //// Visually that look the following case where we have three partitions that
        //// are numbered and store letters.
        //// For teaching purposes I have made each item a tuple of the following form:
        //// <item stored in partition, partition number>
        //// So that duplicates across partitions are distinct, but duplicates within
        //// partitions are indistinguishable.
        //// |-------| |-------| |-------|
        //// | <a,1> | | <a,2> | | <a,3> |
        //// | <a,1> | | <b,2> | | <c,3> |
        //// | <a,1> | | <b,2> | | <c,3> |
        //// | <d,1> | | <c,2> | | <c,3> |
        //// | <d,1> | | <e,2> | | <f,3> |
        //// | <e,1> | | <h,2> | | <j,3> |
        //// | <f,1> | | <i,2> | | <k,3> |
        //// |-------| |-------| |-------|
        //// Now the correct drain order in this case is:
        //// <a,1>,<a,1>,<a,1>,<a,2>,<a,3>,<b,2>,<b,2>,<c,2>,<c,3>,<c,3>,<c,3>,
        //// <d,1>,<d,1>,<e,1>,<e,2>,<f,1>,<f,3>,<h,2>,<i,2>,<j,3>,<k,3>
        //// In more mathematical terms
        //// 1) <x, y> always comes before <z, y> where x < z
        //// 2) <i, j> always come before <i, k> where j < k
        return this.orderByObservable.transformDeferred(new ItemToPageTransformer(tracker,
                maxPageSize,
                this.queryMetricMap,
                this::getContinuationToken,
                this.clientSideRequestStatisticsList));
    }

    @Override
    public Flux<FeedResponse<Document>> executeAsync() {
        return drainAsync(ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(cosmosQueryRequestOptions));
    }

    private String getContinuationToken(
            OrderByRowResult<Document> orderByRowResult) {
        // rid
        String rid = orderByRowResult.getResourceId();

        // CompositeContinuationToken
        String backendContinuationToken = orderByRowResult.getSourceBackendContinuationToken();
        Range<String> range = orderByRowResult.getSourceRange().getRange();

        boolean inclusive = true;
        CompositeContinuationToken compositeContinuationToken = new CompositeContinuationToken(backendContinuationToken,
                range);

        // OrderByItems
        QueryItem[] orderByItems = new QueryItem[orderByRowResult.getOrderByItems().size()];
        orderByRowResult.getOrderByItems().toArray(orderByItems);

        return new OrderByContinuationToken(compositeContinuationToken,
                orderByItems,
                rid,
                inclusive).toJson();
    }

    private static final class FormattedFilterInfo {
        private final String filterForRangesLeftOfTheTargetRange;
        private final String filterForTargetRange;
        private final String filterForRangesRightOfTheTargetRange;

        public FormattedFilterInfo(
                String filterForRangesLeftOfTheTargetRange,
                String filterForTargetRange,
                String filterForRangesRightOfTheTargetRange) {
            if (filterForRangesLeftOfTheTargetRange == null) {
                throw new IllegalArgumentException("filterForRangesLeftOfTheTargetRange must not be null.");
            }

            if (filterForTargetRange == null) {
                throw new IllegalArgumentException("filterForTargetRange must not be null.");
            }

            if (filterForRangesRightOfTheTargetRange == null) {
                throw new IllegalArgumentException("filterForRangesRightOfTheTargetRange must not be null.");
            }

            this.filterForRangesLeftOfTheTargetRange = filterForRangesLeftOfTheTargetRange;
            this.filterForTargetRange = filterForTargetRange;
            this.filterForRangesRightOfTheTargetRange = filterForRangesRightOfTheTargetRange;
        }

        /**
         * @return the filterForRangesLeftOfTheTargetRange
         */
        public String getFilterForRangesLeftOfTheTargetRange() {
            return filterForRangesLeftOfTheTargetRange;
        }

        /**
         * @return the filterForTargetRange
         */
        public String getFilterForTargetRange() {
            return filterForTargetRange;
        }

        /**
         * @return the filterForRangesRightOfTheTargetRange
         */
        public String getFilterForRangesRightOfTheTargetRange() {
            return filterForRangesRightOfTheTargetRange;
        }
    }
}


text:
using Microsoft.AspNetCore.Mvc;
using NBitcoin;
using NBitcoin.RPC;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using WalletWasabi.Backend.Models;
using WalletWasabi.Backend.Models.Responses;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Models;

namespace WalletWasabi.Backend.Controllers
{
	/// <summary>
	/// To make batched requests.
	/// </summary>
	[Produces("application/json")]
	[Route("api/v" + Constants.BackendMajorVersion + "/btc/[controller]")]
	public class BatchController : ControllerBase
	{
		public BatchController(BlockchainController blockchainController, ChaumianCoinJoinController chaumianCoinJoinController, HomeController homeController, OffchainController offchainController, Global global)
		{
			BlockchainController = blockchainController;
			ChaumianCoinJoinController = chaumianCoinJoinController;
			HomeController = homeController;
			OffchainController = offchainController;
			Global = global;
		}

		public Global Global { get; }
		public BlockchainController BlockchainController { get; }
		public ChaumianCoinJoinController ChaumianCoinJoinController { get; }
		public HomeController HomeController { get; }
		public OffchainController OffchainController { get; }

		[HttpGet("synchronize")]
		public async Task<IActionResult> GetSynchronizeAsync([FromQuery, Required] string bestKnownBlockHash, [FromQuery, Required] int maxNumberOfFilters, [FromQuery] string? estimateSmartFeeMode = nameof(EstimateSmartFeeMode.Conservative))
		{
			bool estimateSmartFee = !string.IsNullOrWhiteSpace(estimateSmartFeeMode);
			EstimateSmartFeeMode mode = EstimateSmartFeeMode.Conservative;
			if (estimateSmartFee)
			{
				if (!Enum.TryParse(estimateSmartFeeMode, ignoreCase: true, out mode))
				{
					return BadRequest("Invalid estimation mode is provided, possible values: ECONOMICAL/CONSERVATIVE.");
				}
			}

			if (!uint256.TryParse(bestKnownBlockHash, out var knownHash))
			{
				return BadRequest($"Invalid {nameof(bestKnownBlockHash)}.");
			}

			(Height bestHeight, IEnumerable<FilterModel> filters) = Global.IndexBuilderService.GetFilterLinesExcluding(knownHash, maxNumberOfFilters, out bool found);

			var response = new SynchronizeResponse { Filters = Enumerable.Empty<FilterModel>(), BestHeight = bestHeight };

			if (!found)
			{
				response.FiltersResponseState = FiltersResponseState.BestKnownHashNotFound;
			}
			else if (!filters.Any())
			{
				response.FiltersResponseState = FiltersResponseState.NoNewFilter;
			}
			else
			{
				response.FiltersResponseState = FiltersResponseState.NewFilters;
				response.Filters = filters;
			}

			response.CcjRoundStates = ChaumianCoinJoinController.GetStatesCollection();

			if (estimateSmartFee)
			{
				try
				{
					response.AllFeeEstimate = await BlockchainController.GetAllFeeEstimateAsync(mode);
				}
				catch (Exception ex)
				{
					Logger.LogError(ex);
				}
			}

			response.ExchangeRates = await OffchainController.GetExchangeRatesCollectionAsync();

			response.UnconfirmedCoinJoins = await ChaumianCoinJoinController.GetUnconfirmedCoinJoinCollectionAsync();

			return Ok(response);
		}
	}
}


text:
package com.microsoftopentechnologies.tooling.msservices.serviceexplorer;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.microsoftopentechnologies.tooling.msservices.components.DefaultLoader;
import com.microsoftopentechnologies.tooling.msservices.helpers.NotNull;
import com.microsoftopentechnologies.tooling.msservices.helpers.azure.AzureCmdException;

import java.util.concurrent.Callable;

public abstract class NodeActionListenerAsync extends NodeActionListener {
    private String progressMessage;

    @NotNull
    protected  Callable<Boolean> beforeAsyncActionPerfomed() {
        return new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return true;
            }
        };
    }

    public NodeActionListenerAsync(String progressMessage) {
        this.progressMessage = progressMessage;
    }

    public ListenableFuture<Void> actionPerformedAsync(final NodeActionEvent actionEvent) {

        Callable<Boolean> booleanCallable = beforeAsyncActionPerfomed();

        boolean shouldRun = true;

        try {
            shouldRun = booleanCallable.call();
        } catch (Exception ignored) {}

        final SettableFuture<Void> future = SettableFuture.create();

        if(shouldRun) {
            DefaultLoader.getIdeHelper().runInBackground(actionEvent.getAction().getNode().getProject(), progressMessage, true, false, null, new Runnable() {
                @Override
                public void run() {
                    try {
                        runInBackground(actionEvent);
                        future.set(null);
                    } catch (AzureCmdException e) {
                        future.setException(e);
                    }
                }
            });
        } else {
            future.set(null);
        }

        return future;

    }

    protected void runInBackground(NodeActionEvent actionEvent) throws AzureCmdException {}
}


text:
package org.apache.deltaspike.test.core.api.alternative.local;

import org.apache.deltaspike.test.util.ArchiveUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;

/**
 * Keep in sync with {@link org.apache.deltaspike.test.core.api.alternative.global.GlobalAlternativeTest} -
 * but without configuring the alternatives and check for the default implementations.
 *
 * Tests which checks the behaviour with deactivated global alternates.
 */
@RunWith(Arquillian.class)
public class BdaAlternativeWarFileTest extends BdaAlternativeTest
{
    /**
     * X TODO creating a WebArchive is only a workaround because JavaArchive cannot contain other archives.
     */
    @Deployment
    public static WebArchive deploy()
    {
        String simpleName = BdaAlternativeWarFileTest.class.getSimpleName();
        String archiveName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);

        JavaArchive testJar = ShrinkWrap.create(JavaArchive.class, archiveName + ".jar")
                .addPackage(BdaAlternativeWarFileTest.class.getPackage())
                .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");

        return ShrinkWrap.create(WebArchive.class, archiveName + ".war")
                .addAsLibraries(ArchiveUtils.getDeltaSpikeCoreArchive(new String[]{"META-INF.config"}))
                .addAsLibraries(testJar)
                .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
    }
}


text:
package net.jmreyes.tutelaserver.svc;

import java.util.Collection;

import net.jmreyes.tutelaserver.model.Doctor;
import net.jmreyes.tutelaserver.model.Patient;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserSvc {

	@RequestMapping(value = "/user/me/role", method = RequestMethod.GET)
	public @ResponseBody String getMyRole() {
		String role = null;
		Collection<GrantedAuthority> authorities = null;

		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		if (principal instanceof Patient) {
			Patient activeUser = (Patient) principal;
			authorities = activeUser.getAuthorities();
		} else if (principal instanceof Doctor) {
			Doctor activeUser = (Doctor) principal;
			authorities = activeUser.getAuthorities();
		}

        for (GrantedAuthority auth : authorities) {
        	role = auth.getAuthority();
        }

        return role;
	}
}


text:
function __sdk_update() {
	local candidates_uri="${SDKMAN_CANDIDATES_API}/candidates/all"
	__sdkman_echo_debug "Using candidates endpoint: $candidates_uri"

	local fresh_candidates_csv=$(__sdkman_secure_curl_with_timeouts "$candidates_uri")

	__sdkman_echo_debug "Local candidates: $SDKMAN_CANDIDATES_CSV"
	__sdkman_echo_debug "Fetched candidates: $fresh_candidates_csv"

	if [[ -n "${fresh_candidates_csv}" ]] && ! grep -iq 'html' <<< "${fresh_candidates_csv}"; then
		__sdkman_echo_debug "Fresh and cached candidate lengths: ${#fresh_candidates_csv} ${#SDKMAN_CANDIDATES_CSV}"

		local fresh_candidates combined_candidates diff_candidates

		if [[ "${zsh_shell}" == 'true' ]]; then
			fresh_candidates=(${(s:,:)fresh_candidates_csv})
		else
			IFS=',' read -a fresh_candidates <<< "${fresh_candidates_csv}"
		fi

		combined_candidates=("${fresh_candidates[@]}" "${SDKMAN_CANDIDATES[@]}")

		diff_candidates=($(printf $'%s\n' "${combined_candidates[@]}" | sort | uniq -u))

		if ((${#diff_candidates[@]})); then
			local delta

			delta=("${fresh_candidates[@]}" "${diff_candidates[@]}")
			delta=($(printf $'%s\n' "${delta[@]}" | sort | uniq -d))
			if ((${#delta[@]})); then
				__sdkman_echo_green "\nAdding new candidates(s): ${delta[*]}"
			fi

			delta=("${SDKMAN_CANDIDATES[@]}" "${diff_candidates[@]}")
			delta=($(printf $'%s\n' "${delta[@]}" | sort | uniq -d))
			if ((${#delta[@]})); then
				__sdkman_echo_green "\nRemoving obsolete candidates(s): ${delta[*]}"
			fi

			echo "${fresh_candidates_csv}" >| "${SDKMAN_CANDIDATES_CACHE}"
			__sdkman_echo_yellow $'\nPlease open a new terminal now...'
		else
			touch "${SDKMAN_CANDIDATES_CACHE}"
			__sdkman_echo_green $'\nNo new candidates found at this time.'
		fi
	fi
}


text:
package org.jasig.cas.support.openid.web.support;

import static org.junit.Assert.*;

import javax.servlet.http.HttpServletRequest;

import org.jasig.cas.support.openid.web.support.OpenIdArgumentExtractor;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.mock.web.MockHttpServletRequest;

/**
 * @author Scott Battaglia
 * @version $Revision: 1.1 $ $Date: 2005/08/19 18:27:17 $
 * @since 3.1
 */
public class OpenIdArgumentExtractorTests {

    private OpenIdArgumentExtractor extractor;

    @Before
    public void setUp() throws Exception {
        this.extractor = new OpenIdArgumentExtractor();
    }

    @Test
    public void testNoOpenIdServiceExists() {
        assertNull(this.extractor.extractService(new MockHttpServletRequest()));
    }

    @Test
    public void testOpenIdServiceExists() {

    	HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    	Mockito.when(request.getParameter("openid.identity")).thenReturn("http://intolerableconsent.blogspot.com");
    	//Mockito.when(request.getParameter("openid.sig")).thenReturn("");
    	//Mockito.when(request.getParameter("openid.assoc_handle")).thenReturn("");
    	Mockito.when(request.getParameter("openid.return_to")).thenReturn("http://www.cnn.com");

        assertTrue(this.extractor.extractService(request) != null);
    }
}


text:
package com.prodyna.pac.conference.jsf;

import com.prodyna.pac.conference.ejb.api.datatype.Speaker;
import com.prodyna.pac.conference.ejb.api.exception.ServiceException;
import com.prodyna.pac.conference.ejb.api.service.speaker.SpeakerService;
import org.slf4j.Logger;

import javax.annotation.ManagedBean;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;

/**
 * Bean holding all speaker instances from the database.
 * <p/>
 * Author: Nicolas Moser
 * Date: 26.09.13
 * Time: 20:16
 */
@ManagedBean
@RequestScoped
@Named("speakerListBean")
public class SpeakerListBean {

	@Inject
	private SpeakerService speakerService;

	@Inject
	private Logger logger;

	private List<Speaker> speakers;

	/**
	 * Getter for the list of all conferences.
	 *
	 * @return all conferences
	 */
	public List<Speaker> getSpeakers() {

		return this.speakers;
	}

	/** Initialize the SpeakerListBean by loading all speakers from DB. */
	@PostConstruct
	public void init() {

		try {
			this.speakers = speakerService.getAllSpeakers();

		} catch (ServiceException se) {
			logger.error("Error retrieving Speakers.", se);
		}
	}
}


text:
$('#due').datepicker({
	'dateFormat': 'yy-mm-dd'
});

var options = {
	dataType: 'json',
	type: 'post',
	beforeSerialize: function () {
		nicEditors.findEditor('topic_description').saveContent();
	},
	beforeSubmit: aggressive_message,
	success: process_validation
};
$('#add_topic_form').ajaxForm(options);

function process_validation(data) {
	if (data.result === 'ok') {
		var regex = new RegExp("\_+" + $('#id').val() + '$');
		window.location = site_url + 'cc/topic/resume/' + $('#context').val().replace(regex, '') + '_' + $('#id').val();
	} else {
		hide_aggressive_message();
		alert(data.message);
	}
}

new nicEditor({fullPanel: true}).panelInstance('topic_description', {hasPanel: true});


text:
using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace VideoDesk
{
    /// <summary>
    /// Interaction logic for Home.xaml
    /// </summary>
    public partial class Home : System.Windows.Controls.UserControl
    {

        bool onlyOne;
        bool winSeven;

        // For 1 video per monitor *not yet in*
        public static List<String> FileLoadList;
        public static List<int> FileLoadListSort;
        public static List<Uri> FileLoadListUri;

        string[] lines = new string[4];
        double volumeGeneral = 0;
        bool isPlaying = false;

        public Home()
        {
            InitializeComponent();
            PlayButton.IsEnabled = false;
            winSeven = false;
            FileLoadList = new List<String>();
            FileLoadListSort = new List<int>();
            FileLoadListUri = new List<Uri>();
            onlyOne = true;
            Each.Visibility = Visibility.Hidden;
            lines[0] = MainWindow.file;
            ReadConfig();
            if (MainWindow.setStartupAutoPlay == true)
            {
                if(MainWindow.file != "\0")
                {
                    FileSelected.Text = ReadFileName(MainWindow.file);

                    Volume.Value = volumeGeneral;

                    if (System.IO.File.Exists(MainWindow.file))
                    {
                        MainWindow.fileMedia = new Uri(MainWindow.file);
                        PlayButton.IsEnabled = true;
                        PlayButton.Content = "Stop";
                        if(lines[1].ToString() == "Sound = Y")
                            Sound.IsChecked = true;
                        playingFile();
                    }
                    else
                    {
                        FileSelected.Text = "File not found.";
                        Sound.IsEnabled = false;
                        Sound.IsChecked = false;
                    }
                }
            }

            /*
            //Multiple monitor thing (dynamic button creation)
            if (MainWindow.ScreenList.Count > 1)
            {
                Each.Visibility = Visibility.Visible;

                onlyOne = false;
                for (int i = 0; i < MainWindow.ButtonList.Count; i++)
                {
                    MainWindow.ButtonList[i].Click += new RoutedEventHandler(DynaButton_Click);
                    FileLoadList.Add("");
                   // FileLoadListUri.Add(new Uri(""));

                    ms.Children.Add(MainWindow.ButtonList[i]);
                }
            }
            if (onlyOne)
                Multiple.IsEnabled = false;
            else
                Multiple.IsEnabled = true;
                */
        }

        //Multiple monitors
        //Not working yet, but will be used to load and prepare the video that are going to be played on each monitor
        private void DynaButton_Click(object sender, RoutedEventArgs e)
        {
            var fileDialog = new System.Windows.Forms.OpenFileDialog();
            // Set filter for file extension and default file extension
            fileDialog.Filter = "All files (*.*)|*.*";

            int t = Convert.ToInt32(Tag);
            Console.WriteLine("Value = " + t);
            var result = fileDialog.ShowDialog();
            switch (result)
            {
                case System.Windows.Forms.DialogResult.OK:
                    FileLoadList.Add(fileDialog.FileName);
                    FileLoadListUri.Add(new Uri(fileDialog.FileName));
                    PlayButton.IsEnabled = true;
                    break;
                case System.Windows.Forms.DialogResult.Cancel:
                default:
                    FileSelected.Text = "nothing";
                    PlayButton.IsEnabled = false;

                    break;
            }
        }

        //One monitor or all the same
        public void Button_Click(object sender, RoutedEventArgs e)
        {
            var fileDialog = new System.Windows.Forms.OpenFileDialog();
            // Set filter for file extension and default file extension
            fileDialog.Filter = "All files (*.*)|*.*";

            var result = fileDialog.ShowDialog();
            switch (result)
            {
                case System.Windows.Forms.DialogResult.OK:
                    stoppingFile();
                    MainWindow.file = fileDialog.FileName;
                    MainWindow.fileMedia = new Uri(fileDialog.FileName);
                    FileSelected.Text = ReadFileName(MainWindow.file);
                    PlayButton.IsEnabled = true;
                    PlayButton.Content = "Stop";
                    Sound.IsEnabled = true;

                    lines[0] = MainWindow.file.ToString();
                    WriteConfig();

                    playingFile();

                    break;
                case System.Windows.Forms.DialogResult.Cancel:
                default:
                    FileSelected.Text = "nothing";
                    PlayButton.IsEnabled = false;

                    break;
            }
        }

        private void PlayButton_Click(object sender, RoutedEventArgs e)
        {
            if (!MainWindow.currentlyPlaying)
            {
                playingFile();
                PlayButton.Content = "Stop";
            }
            else
            {
                stoppingFile();
                PlayButton.Content = "Play";
            }
        }

        private void stoppingFile()
        {
            if (MainWindow.currentlyPlaying)
            {
                MainWindow.media.Stop();
                MainWindow.media = null;
                /*for (int i = 0; i < MainWindow.windowList.Count; i++)
                {
                    //MainWindow.mediaList[i].Stop();
                    //MainWindow.mediaList[i] = null;
                    //MainWindow.mediaList[i] = new MediaElement();
                    MainWindow.windowList[i].Close();
                }*/

                MainWindow.currentlyPlaying = false;
            }
        }

        private void playingFile()
        {
            MainWindow.findWorker();
            ReadConfig();
            if (winSeven)
            {
                Window sev = new Window();
                IntPtr windowSev = new WindowInteropHelper(sev).Handle;

                W32.SetParent(windowSev, MainWindow.workerw);

            }
            for (int i = 0; i < MainWindow.windowList.Count; i++)
            {
                MainWindow.windowList[i] = new Window();

                MainWindow.windowList[i].WindowStyle = WindowStyle.None;
                MainWindow.windowList[i].AllowsTransparency = true;

                MainWindow.windowList[i].Top = MainWindow.ScreenList[i].Top;
                MainWindow.windowList[i].Left = MainWindow.ScreenList[i].Left;
                MainWindow.windowList[i].Width = MainWindow.ScreenList[i].Width;
                MainWindow.windowList[i].Height = MainWindow.ScreenList[i].Height;

                MainWindow.windowList[i].Initialized += new EventHandler((s, ea) =>
                {

                    MainWindow.media = new MediaElement();
                    Grid grid = new Grid();
                    MainWindow.windowList[i].Content = grid;
                    grid.Children.Add(MainWindow.media);

                    MainWindow.media.Source = MainWindow.fileMedia;
                    MainWindow.media.LoadedBehavior = MediaState.Manual;
                    MainWindow.media.IsEnabled = true;
                    MainWindow.media.Visibility = Visibility.Visible;
                    // MainWindow.media.MediaEnded += new RoutedEventHandler(m_MediaEnded);

                    MainWindow.media.Volume = volumeGeneral;

                    MainWindow.media.MediaEnded += (send, eArgs) =>
                    {
                        // MainWindow.media.Position = new TimeSpan(0, 0, 1);
                        MainWindow.media.Position = TimeSpan.Zero;

                        MainWindow.media.Play();
                    };
                    MainWindow.media.Play();
                    if (lines[2].ToString() != "Sound = Y")
                        MainWindow.media.IsMuted = false;
                    else
                        MainWindow.media.IsMuted = true;

                    MainWindow.currentlyPlaying = true;
                    MainWindow.media.Stretch = Stretch.Fill;

                    /*
                    Grid grid = new Grid();
                    MainWindow.windowList[i].Content = grid;
                    if (alreadyBind == false)
                    {
                        grid.Children.Add(MainWindow.mediaList[i]);
                    }

                    MainWindow.mediaList[i].Source = MainWindow.fileMedia;
                    MainWindow.mediaList[i].LoadedBehavior = MediaState.Manual;

                    if (MainWindow.soundOrNot)
                        MainWindow.mediaList[i].IsMuted = false;
                    else
                        MainWindow.mediaList[i].IsMuted = true;
                    MainWindow.mediaList[i].Volume = 0;
                    MainWindow.mediaList[i].IsEnabled = true;
                    MainWindow.mediaList[i].Visibility = Visibility.Visible;

                    MainWindow.mediaList[i].Play();
                    MainWindow.currentlyPlaying = true;
                    MainWindow.mediaList[i].Stretch = Stretch.Fill;
                    MainWindow.mediaList[i].MediaEnded += (send, eArgs) =>
                    {
                        MainWindow.mediaList[i].Position = new TimeSpan(0, 0, 1);
                        MainWindow.mediaList[i].Play();
                    };
                    */
                    IntPtr windowHandle = new WindowInteropHelper(MainWindow.windowList[i]).Handle;
                    if (winSeven)
                        W32.SetParent(windowHandle, MainWindow.workerwHidden);
                    else
                        W32.SetParent(windowHandle, MainWindow.workerw);

                });
                MainWindow.windowList[i].UpdateLayout();

                MainWindow.windowList[i].Show();
            }
        }

        public static void m_MediaEnded(object sender, RoutedEventArgs e)
        {
            //MainWindow.media.Position = new TimeSpan(0, 0, 1);
            MainWindow.media.Position = TimeSpan.Zero;

            //MainWindow.media.Position = TimeSpan.FromSeconds(0);
            MainWindow.media.Play();
        }

        private void Sound_Checked(object sender, RoutedEventArgs e)
        {
            MainWindow.soundOrNot = true;

            if (MainWindow.currentlyPlaying == true)
                MainWindow.media.IsMuted = false;

            Sound.IsChecked = true;
            lines[1] = "Sound = Y";
            WriteConfig();

        }

        private void Sound_Unchecked(object sender, RoutedEventArgs e)
        {
            MainWindow.soundOrNot = false;
            if (MainWindow.currentlyPlaying == true)
            {
                MainWindow.media.IsMuted = true;
                Sound.IsChecked = false;
                lines[1] = "Sound = N";
                WriteConfig();
            }

        }

        private void Volume_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            lines[2] = "Volume = " + Volume.Value;
            WriteConfig();
            if (MainWindow.currentlyPlaying)
                MainWindow.media.Volume = Volume.Value;
        }

        //This method read the config file to save the settings
        private void ReadConfig()
        {

            System.IO.StreamReader file = new System.IO.StreamReader(MainWindow.path);
            for (int i=0; i <= 3; i++)
            {
                lines[i] = file.ReadLine();
            }
            if (lines[2] == null)
            {
                file.Close();
                WriteConfig();
            }
            string volume = null;
            for (int i = 8; i < lines[2].ToString().Length; i++)
            {
                volume = volume + lines[2].ToString()[i];
            }
            volumeGeneral = double.Parse(volume);
            file.Close();
        }

        //This method write the config file to save the settings
        private void WriteConfig()
        {
            if (lines[2] == null)
            {
                lines[1] = "Sound = N";
                lines[2] = "Volume = 0";
            }
            System.IO.File.WriteAllLines(MainWindow.path, lines);
        }

        private void Multiple_Unchecked(object sender, RoutedEventArgs e)
        {
            MonoScreen.IsEnabled = true;

            for (int i = 0; i < MainWindow.ButtonList.Count; i++)
            {
                MainWindow.ButtonList[i].IsEnabled = false;
            }
        }

        private string ReadFileName(string file)
        {
            ArrayList name = new ArrayList();

            int flag = 0;

            string finalName = "";

            for (int i = file.Length; i > flag; i--)
            {
                if (file[i-1] == '\\')
                {
                    flag = i;
                    break;
                }
                name.Add(file[i-1]);
            }

            for(int i=0; i < name.Count; i++)
            {
                finalName = finalName + name[name.Count-1-i].ToString();
            }

            return finalName;
        }

        private void Multiple_Checked(object sender, RoutedEventArgs e)
        {
            MonoScreen.IsEnabled = false;
            for (int i = 0; i < MainWindow.ButtonList.Count; i++)
            {
                MainWindow.ButtonList[i].IsEnabled = true;
            }

        }

        private void Windows_Checked(object sender, RoutedEventArgs e)
        {
            winSeven = true;
        }

        private void Windows_Unchecked(object sender, RoutedEventArgs e)
        {
            winSeven = false;
        }

        //For Startup checkbox
        private void Startup_Checked(object sender, RoutedEventArgs e)
        {
            //using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
            //{
            //    key.SetValue("AnimaPaper", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\"");
            //    key.Close();
            //}
            //string[] lnk = System.IO.Directory.GetFiles(System.Windows.Forms.Application.StartupPath, "*.*");
            //foreach (var found in lnk)
            //{
            //    Console.WriteLine(found);
            //}
           System.IO.File.Copy(System.Windows.Forms.Application.StartupPath + "\\AnimaPaper.lnk", Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\AnimaPaper.lnk", true);

        }

        private void Startup_Unchecked(object sender, RoutedEventArgs e)
        {
            //using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
            //{
            //    key.DeleteValue("AnimaPaper", false);
            //    key.Close();
            //}
            System.IO.File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\AnimaPaper");
        }
    }
}


text:
set -ex

BUILD_DIR=/var/lib/rancher/nvidia
KERNEL_VERSION=$(uname -r)

NVIDIA_VERSION=390.48
NVIDIA_DRIVER=NVIDIA-Linux-x86_64-${NVIDIA_VERSION}.run
CUDA_PKG=cuda-repo-ubuntu1604_9.1.85-1_amd64.deb

apt-get update && apt-get upgrade -y
apt install gcc make curl -y
curl -sL http://us.download.nvidia.com/XFree86/Linux-x86_64/${NVIDIA_VERSION}/${NVIDIA_DRIVER} -o ${BUILD_DIR}/${NVIDIA_DRIVER}
ros service enable kernel-headers
ros service up kernel-headers

sh ${BUILD_DIR}/${NVIDIA_DRIVER} --no-drm

if [ ! -e /usr/bin/nvidia-container-cli ]; then
     ln -s ${BUILD_DIR}/bin/nvidia-container-cli /usr/bin/nvidia-container-cli
fi
if [ ! -e /usr/bin/nvidia-container-runtime ]; then
     ln -s ${BUILD_DIR}/bin/nvidia-container-runtime /usr/bin/nvidia-container-runtime
fi
if [ ! -e /usr/bin/nvidia-container-runtime-hook ]; then
     ln -s ${BUILD_DIR}/bin/nvidia-container-runtime-hook /usr/bin/nvidia-container-runtime-hook
fi
if [ ! -e /usr/lib/libnvidia-container.so.1 ]; then
     ln -s ${BUILD_DIR}/lib/libnvidia-container.so.1 /usr/lib/libnvidia-container.so.1
fi

curl -sL http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/${CUDA_PKG} -o ${BUILD_DIR}/${CUDA_PKG}
dpkg -i ${BUILD_DIR}/${CUDA_PKG}
apt-key adv --fetch-keys http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/7fa2af80.pub
apt-get update
apt-get install -y cuda

echo "Cleaning kernel headers && cache"
ros service disable kernel-headers
rm -rf /lib/modules/${KERNEL_VERSION}/build/ && rm -f /lib/modules/${KERNEL_VERSION}/.headers-done
rm -rf ${BUILD_DIR}/${NVIDIA_DRIVER}
rm -rf ${BUILD_DIR}/${CUDA_PKG}

system-docker restart docker


text:
package org.apache.isis.core.metamodel.facets.actions.validate.method;

import java.lang.reflect.Method;
import org.apache.isis.applib.services.i18n.TranslatableString;
import org.apache.isis.applib.services.i18n.TranslationService;
import org.apache.isis.core.commons.lang.StringExtensions;
import org.apache.isis.core.metamodel.facetapi.Facet;
import org.apache.isis.core.metamodel.facetapi.FacetUtil;
import org.apache.isis.core.metamodel.facetapi.FeatureType;
import org.apache.isis.core.metamodel.facetapi.IdentifiedHolder;
import org.apache.isis.core.metamodel.facets.MethodFinderUtils;
import org.apache.isis.core.metamodel.facets.MethodPrefixBasedFacetFactoryAbstract;
import org.apache.isis.core.metamodel.facets.MethodPrefixConstants;
import org.apache.isis.core.metamodel.facets.actions.validate.ActionValidationFacet;
import org.apache.isis.core.metamodel.methodutils.MethodScope;

/**
 * Sets up {@link ActionValidationFacet}.
 */
public class ActionValidationFacetViaMethodFactory extends MethodPrefixBasedFacetFactoryAbstract  {

    private static final String[] PREFIXES = { MethodPrefixConstants.VALIDATE_PREFIX };

    /**
     * Note that the {@link Facet}s registered are the generic ones from
     * noa-architecture (where they exist)
     */
    public ActionValidationFacetViaMethodFactory() {
        super(FeatureType.ACTIONS_AND_PARAMETERS, OrphanValidation.VALIDATE, PREFIXES);
    }

    // ///////////////////////////////////////////////////////
    // Actions
    // ///////////////////////////////////////////////////////

    @Override
    public void process(final ProcessMethodContext processMethodContext) {
        handleValidateAllArgsMethod(processMethodContext);
    }

    private void handleValidateAllArgsMethod(final ProcessMethodContext processMethodContext) {

        final Class<?> cls = processMethodContext.getCls();
        final Method actionMethod = processMethodContext.getMethod();
        final IdentifiedHolder facetHolder = processMethodContext.getFacetHolder();

        final String capitalizedName = StringExtensions.asCapitalizedName(actionMethod.getName());
        final Class<?>[] paramTypes = actionMethod.getParameterTypes();
        final MethodScope onClass = MethodScope.scopeFor(actionMethod);

        final Method validateMethod = MethodFinderUtils.findMethod(
                cls, onClass,
                MethodPrefixConstants.VALIDATE_PREFIX + capitalizedName,
                new Class<?>[]{String.class, TranslatableString.class},
                paramTypes);
        if (validateMethod == null) {
            return;
        }
        processMethodContext.removeMethod(validateMethod);

        final TranslationService translationService = servicesInjector.lookupService(TranslationService.class);
        // sadness: same as in TranslationFactory
        final String translationContext = facetHolder.getIdentifier().toClassAndNameIdentityString();
        final ActionValidationFacetViaMethod facet = new ActionValidationFacetViaMethod(validateMethod, translationService, translationContext, facetHolder);
        FacetUtil.addFacet(facet);
    }

    @Override
    public void processParams(final ProcessParameterContext processParameterContext) {

        final Class<?> cls = processParameterContext.getCls();
        final Method actionMethod = processParameterContext.getMethod();
        final int param = processParameterContext.getParamNum();
        final IdentifiedHolder facetHolder = processParameterContext.getFacetHolder();

        final String capitalizedName = StringExtensions.asCapitalizedName(actionMethod.getName());
        final Class<?>[] paramTypes = actionMethod.getParameterTypes();
        final MethodScope onClass = MethodScope.scopeFor(actionMethod);

        final String validateName = MethodPrefixConstants.VALIDATE_PREFIX + param + capitalizedName;
        final Method validateMethod = MethodFinderUtils.findMethod(
                cls, onClass,
                validateName,
                new Class<?>[]{String.class, TranslatableString.class},
                new Class<?>[]{paramTypes[param]});
        if (validateMethod == null) {
            return;
        }

        processParameterContext.removeMethod(validateMethod);

        final TranslationService translationService = servicesInjector.lookupService(TranslationService.class);
        // sadness: same as in TranslationFactory
        final String translationContext = facetHolder.getIdentifier().toFullIdentityString();
        final Facet facet = new ActionParameterValidationFacetViaMethod(validateMethod, translationService, translationContext, facetHolder);
        FacetUtil.addFacet(facet);
    }

}


text:
var TaskAssigneeModel = function (details) {

    this.id;
    this.firstName;
    this.lastName;
    this.email;

    this.getFirstName = function () {
        return this.firstName;
    };

    this.getId = function () {
        return this.id;
    };

    this.getLastName = function () {
        return this.lastName;
    };

    this.getEmail = function () {
        return this.email;
    };

    this.getEntireName = function() {
        return this.firstName + " " + this.getLastName();
    };

    Object.assign(this, details);

};

module.exports = TaskAssigneeModel;


text:
#include <memory>

#include "AVSCommon/Utils/Logger/Logger.h"
#include "AVSCommon/Utils/Memory/Memory.h"
#include "AVSCommon/Utils/Threading/ThreadPool.h"

/// String to identify log entries originating from this file.
#define TAG "ThreadPool"

/**
 * Create a LogEntry using this file's TAG and the specified event string.
 *
 * @param event The event string for this @c LogEntry.
 */
#define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event)

namespace alexaClientSDK {
namespace avsCommon {
namespace utils {
namespace threading {

using namespace std;
using namespace logger;

ThreadPool::ThreadPool(size_t maxThreads) :
        m_maxPoolThreads{maxThreads},
        m_created{0},
        m_obtained{0},
        m_releasedToPool{0},
        m_releasedFromPool{0} {
}

ThreadPool::~ThreadPool() {
    std::lock_guard<mutex> lock(m_queueMutex);
    // Ensure all threads are stopped and joined
    m_workerQueue.clear();
}

unique_ptr<WorkerThread> ThreadPool::obtainWorker() {
    std::lock_guard<mutex> lock(m_queueMutex);

    m_obtained++;
    unique_ptr<WorkerThread> ret;
    if (m_workerQueue.empty()) {
        m_created++;
        ret = memory::make_unique<WorkerThread>();
    } else {
        auto workerIterator = m_workerQueue.begin();
        ret = std::move(*workerIterator);
        m_workerQueue.erase(workerIterator);
    }

    return ret;
}

void ThreadPool::releaseWorker(std::unique_ptr<WorkerThread> workerThread) {
    std::lock_guard<mutex> lock(m_queueMutex);
    if (m_workerQueue.size() >= m_maxPoolThreads) {
        // In order to allow this to be called from the thread being released,
        // we release the first thread in the queue when we want to stop growing.
        m_workerQueue.pop_front();
        m_releasedFromPool++;
    } else {
        m_releasedToPool++;
    }
    m_workerQueue.push_back(std::move(workerThread));
}

void ThreadPool::setMaxThreads(size_t maxThreads) {
    std::lock_guard<mutex> lock(m_queueMutex);
    m_maxPoolThreads = maxThreads <= 0 ? 1 : maxThreads;
    while (m_workerQueue.size() > m_maxPoolThreads) {
        m_workerQueue.pop_front();
    }
}

size_t ThreadPool::getMaxThreads() {
    std::lock_guard<mutex> lock(m_queueMutex);
    return m_maxPoolThreads;
}

void ThreadPool::getStats(
    uint64_t& threadsCreated,
    uint64_t& threadsObtained,
    uint64_t& threadsReleasedToPool,
    uint64_t& threadsReleasedFromPool) {
    std::lock_guard<mutex> lock(m_queueMutex);
    threadsCreated = m_created;
    threadsObtained = m_obtained;
    threadsReleasedToPool = m_releasedToPool;
    threadsReleasedFromPool = m_releasedFromPool;
}

std::shared_ptr<ThreadPool> ThreadPool::getDefaultThreadPool() {
    static std::mutex singletonMutex;
    static std::weak_ptr<ThreadPool> weakTPRef;

    auto sharedTPRef = weakTPRef.lock();
    if (!sharedTPRef) {
        std::lock_guard<mutex> lock(singletonMutex);
        // Ensure we don't unnecessarily create twice if there was contention on the lock by attempting to lock again.
        sharedTPRef = weakTPRef.lock();
        if (!sharedTPRef) {
            sharedTPRef = std::make_shared<ThreadPool>();
            weakTPRef = sharedTPRef;
        }
    }
    return sharedTPRef;
}

}  // namespace threading
}  // namespace utils
}  // namespace avsCommon
}  // namespace alexaClientSDK


text:
void UServerRow::Setup(class UMainMenu* InParent, uint32 InIndex)
{
	Parent = InParent;
	Index = InIndex;
	RowButton->OnClicked.AddDynamic(this, &UServerRow::OnClicked);
}

void UServerRow::OnClicked()
{
	Parent->SelectIndex(Index);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="2dp">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/title"
        android:text="@string/app_name" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/title_hw"
        android:textSize="16sp"
        android:visibility="gone"
        android:text="00:00:00:00:00:00"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorAccent"
        android:layout_toRightOf="@id/title"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"/>
</RelativeLayout>


text:
require 'devise'

class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
  has_many :plugins, :class_name => "UserPlugin", :order => "position ASC", :dependent => :destroy
  has_friendly_id :username, :use_slug => true

  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  # :login is a virtual attribute for authenticating by either username or email
  # This is in addition to a real persisted field like 'username'
  attr_accessor :login
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :plugins, :login

  validates :username, :presence => true, :uniqueness => true

  class << self
    # Configure authentication_keys here instead of devise.rb initialzer so we don't overwrite standard devise models
    def authentication_keys
      [:login]
    end

    # Find user by email or username.
    # https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign_in-using-their-username-or-email-address
    def find_for_database_authentication(conditions)
      value = conditions[authentication_keys.first]
      where(["username = :value OR email = :value", { :value => value }]).first
    end
  end

  def plugins=(plugin_names)
    if persisted? # don't add plugins when the user_id is nil.
      UserPlugin.delete_all(:user_id => id)

      plugin_names.each_with_index do |plugin_name, index|
        plugins.create(:name => plugin_name, :position => index) if plugin_name.is_a?(String)
      end
    end
  end

  def authorized_plugins
    plugins.collect { |p| p.name } | Refinery::Plugins.always_allowed.names
  end

  def can_delete?(user_to_delete = self)
    user_to_delete.persisted? and
    id != user_to_delete.id and
    !user_to_delete.has_role?(:superuser) and
    Role[:refinery].users.count > 1
  end

  def add_role(title)
    raise ArgumentException, "Role should be the title of the role not a role object." if title.is_a?(Role)
    roles << Role[title] unless has_role?(title)
  end

  def has_role?(title)
    raise ArgumentException, "Role should be the title of the role not a role object." if title.is_a?(Role)
    roles.any?{|r| r.title == title.to_s.camelize}
  end

end


text:
import { Map } from 'immutable';
import { TYPES } from '../../actions/clock';
import { data } from '../utils';

export function clock(state = new Map(), action) {
    if (action.type === TYPES.GET_TIME || action.type === TYPES.UPDATE_TIME)
        return state.merge(data(action));

    return state;
}


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { WeatherComponent } from './weather/weather.component';
import { ModalModule } from 'angular2-modal';
import { BootstrapModalModule } from 'angular2-modal/plugins/bootstrap';

@NgModule({
  declarations: [
    AppComponent,
    WeatherComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    ModalModule.forRoot(),
    BootstrapModalModule
  ],
  providers: [],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule {}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ceské Houby 3: 562 (1921)

#### Original name
Psalliota bivelata Velen.

### Remarks
null