text:
package org.apache.phoenix.compile;

import static org.apache.phoenix.query.QueryServices.WILDCARD_QUERY_DYNAMIC_COLS_ATTRIB;
import static org.apache.phoenix.query.QueryServicesOptions.DEFAULT_WILDCARD_QUERY_DYNAMIC_COLS_ATTRIB;

import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.phoenix.thirdparty.com.google.common.base.Optional;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.phoenix.compile.GroupByCompiler.GroupBy;
import org.apache.phoenix.compile.JoinCompiler.JoinSpec;
import org.apache.phoenix.compile.JoinCompiler.JoinTable;
import org.apache.phoenix.compile.JoinCompiler.Table;
import org.apache.phoenix.compile.OrderByCompiler.OrderBy;
import org.apache.phoenix.coprocessor.BaseScannerRegionObserver;
import org.apache.phoenix.exception.SQLExceptionCode;
import org.apache.phoenix.exception.SQLExceptionInfo;
import org.apache.phoenix.execute.AggregatePlan;
import org.apache.phoenix.execute.BaseQueryPlan;
import org.apache.phoenix.execute.ClientAggregatePlan;
import org.apache.phoenix.execute.ClientScanPlan;
import org.apache.phoenix.execute.HashJoinPlan;
import org.apache.phoenix.execute.HashJoinPlan.HashSubPlan;
import org.apache.phoenix.execute.HashJoinPlan.WhereClauseSubPlan;
import org.apache.phoenix.execute.LiteralResultIterationPlan;
import org.apache.phoenix.execute.ScanPlan;
import org.apache.phoenix.execute.SortMergeJoinPlan;
import org.apache.phoenix.execute.TupleProjectionPlan;
import org.apache.phoenix.execute.TupleProjector;
import org.apache.phoenix.execute.UnionPlan;
import org.apache.phoenix.expression.Expression;
import org.apache.phoenix.expression.LiteralExpression;
import org.apache.phoenix.expression.RowValueConstructorExpression;
import org.apache.phoenix.hbase.index.util.ImmutableBytesPtr;
import org.apache.phoenix.iterate.ParallelIteratorFactory;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.jdbc.PhoenixStatement;
import org.apache.phoenix.join.HashJoinInfo;
import org.apache.phoenix.optimize.Cost;
import org.apache.phoenix.parse.AliasedNode;
import org.apache.phoenix.parse.EqualParseNode;
import org.apache.phoenix.parse.HintNode.Hint;
import org.apache.phoenix.parse.JoinTableNode.JoinType;
import org.apache.phoenix.parse.OrderByNode;
import org.apache.phoenix.parse.ParseNode;
import org.apache.phoenix.parse.ParseNodeFactory;
import org.apache.phoenix.parse.SQLParser;
import org.apache.phoenix.parse.SelectStatement;
import org.apache.phoenix.parse.SubqueryParseNode;
import org.apache.phoenix.parse.TableNode;
import org.apache.phoenix.query.ConnectionQueryServices;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.query.QueryServicesOptions;
import org.apache.phoenix.schema.AmbiguousColumnException;
import org.apache.phoenix.schema.ColumnNotFoundException;
import org.apache.phoenix.schema.PDatum;
import org.apache.phoenix.schema.PTable;
import org.apache.phoenix.schema.RowValueConstructorOffsetNotCoercibleException;
import org.apache.phoenix.schema.TableNotFoundException;
import org.apache.phoenix.schema.TableRef;
import org.apache.phoenix.util.EnvironmentEdgeManager;
import org.apache.phoenix.util.ParseNodeUtil;
import org.apache.phoenix.util.ParseNodeUtil.RewriteResult;
import org.apache.phoenix.util.QueryUtil;
import org.apache.phoenix.util.ScanUtil;

import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;
import org.apache.phoenix.thirdparty.com.google.common.collect.Sets;

/**
 *
 * Class used to build an executable query plan
 *
 *
 * @since 0.1
 */
public class QueryCompiler {
    private static final ParseNodeFactory NODE_FACTORY = new ParseNodeFactory();
    private final PhoenixStatement statement;
    private final Scan scan;
    private final Scan originalScan;
    private final ColumnResolver resolver;
    private final BindManager bindManager;
    private final SelectStatement select;
    private final List<? extends PDatum> targetColumns;
    private final ParallelIteratorFactory parallelIteratorFactory;
    private final SequenceManager sequenceManager;
    private final boolean projectTuples;
    private final boolean noChildParentJoinOptimization;
    private final boolean usePersistentCache;
    private final boolean optimizeSubquery;
    private final Map<TableRef, QueryPlan> dataPlans;
    private final boolean costBased;

    public QueryCompiler(PhoenixStatement statement, SelectStatement select, ColumnResolver resolver, boolean projectTuples, boolean optimizeSubquery, Map<TableRef, QueryPlan> dataPlans) throws SQLException {
        this(statement, select, resolver, Collections.<PDatum>emptyList(), null, new SequenceManager(statement), projectTuples, optimizeSubquery, dataPlans);
    }

    public QueryCompiler(PhoenixStatement statement, SelectStatement select, ColumnResolver resolver, BindManager bindManager, boolean projectTuples, boolean optimizeSubquery, Map<TableRef, QueryPlan> dataPlans) throws SQLException {
        this(statement, select, resolver, bindManager, Collections.<PDatum>emptyList(), null, new SequenceManager(statement), projectTuples, optimizeSubquery, dataPlans);
    }

    public QueryCompiler(PhoenixStatement statement, SelectStatement select, ColumnResolver resolver, List<? extends PDatum> targetColumns, ParallelIteratorFactory parallelIteratorFactory, SequenceManager sequenceManager, boolean projectTuples, boolean optimizeSubquery, Map<TableRef, QueryPlan> dataPlans) throws SQLException {
        this(statement, select, resolver, new BindManager(statement.getParameters()), targetColumns, parallelIteratorFactory, sequenceManager, projectTuples, optimizeSubquery, dataPlans);
    }

    public QueryCompiler(PhoenixStatement statement, SelectStatement select, ColumnResolver resolver, BindManager bindManager, List<? extends PDatum> targetColumns, ParallelIteratorFactory parallelIteratorFactory, SequenceManager sequenceManager, boolean projectTuples, boolean optimizeSubquery, Map<TableRef, QueryPlan> dataPlans) throws SQLException {
        this.statement = statement;
        this.select = select;
        this.resolver = resolver;
        this.bindManager = bindManager;
        this.scan = new Scan();
        this.targetColumns = targetColumns;
        this.parallelIteratorFactory = parallelIteratorFactory;
        this.sequenceManager = sequenceManager;
        this.projectTuples = projectTuples;
        this.noChildParentJoinOptimization = select.getHint().hasHint(Hint.NO_CHILD_PARENT_JOIN_OPTIMIZATION) || select.getHint().hasHint(Hint.USE_PERSISTENT_CACHE);
        this.usePersistentCache = select.getHint().hasHint(Hint.USE_PERSISTENT_CACHE);
        ConnectionQueryServices services = statement.getConnection().getQueryServices();
        this.costBased = services.getProps().getBoolean(QueryServices.COST_BASED_OPTIMIZER_ENABLED, QueryServicesOptions.DEFAULT_COST_BASED_OPTIMIZER_ENABLED);
        scan.setLoadColumnFamiliesOnDemand(true);
        if (select.getHint().hasHint(Hint.NO_CACHE)) {
            scan.setCacheBlocks(false);
        }

        scan.setCaching(statement.getFetchSize());
        this.originalScan = ScanUtil.newScan(scan);
        this.optimizeSubquery = optimizeSubquery;
        this.dataPlans = dataPlans == null ? Collections.<TableRef, QueryPlan>emptyMap() : dataPlans;
    }

    public QueryCompiler(PhoenixStatement statement, SelectStatement select, ColumnResolver resolver, List<? extends PDatum> targetColumns, ParallelIteratorFactory parallelIteratorFactory, SequenceManager sequenceManager) throws SQLException {
        this(statement, select, resolver, targetColumns, parallelIteratorFactory, sequenceManager, true, false, null);
    }

    /**
     * Builds an executable query plan from a parsed SQL statement
     * @return executable query plan
     * @throws SQLException if mismatched types are found, bind value do not match binds,
     * or invalid function arguments are encountered.
     * @throws SQLFeatureNotSupportedException if an unsupported construct is encountered
     * @throws TableNotFoundException if table name not found in schema
     * @throws ColumnNotFoundException if column name could not be resolved
     * @throws AmbiguousColumnException if an unaliased column name is ambiguous across multiple tables
     */
    public QueryPlan compile() throws SQLException{
        verifySCN();
        QueryPlan plan;
        if (select.isUnion()) {
            plan = compileUnionAll(select);
        } else {
            plan = compileSelect(select);
        }
        return plan;
    }

    private void verifySCN() throws SQLException {
        PhoenixConnection conn = statement.getConnection();
        if (conn.isRunningUpgrade()) {
            // PHOENIX-6179 : if upgrade is going on, we don't need to
            // perform MaxLookBackAge check
            return;
        }
        Long scn = conn.getSCN();
        if (scn == null) {
            return;
        }
        long maxLookBackAgeInMillis =
            BaseScannerRegionObserver.getMaxLookbackInMillis(conn.getQueryServices().
            getConfiguration());
        long now = EnvironmentEdgeManager.currentTimeMillis();
        if (maxLookBackAgeInMillis > 0 && now - maxLookBackAgeInMillis > scn){
            throw new SQLExceptionInfo.Builder(
                SQLExceptionCode.CANNOT_QUERY_TABLE_WITH_SCN_OLDER_THAN_MAX_LOOKBACK_AGE)
                .build().buildException();
        }
    }

    public QueryPlan compileUnionAll(SelectStatement select) throws SQLException {
        List<SelectStatement> unionAllSelects = select.getSelects();
        List<QueryPlan> plans = new ArrayList<QueryPlan>();

        for (int i=0; i < unionAllSelects.size(); i++ ) {
            SelectStatement subSelect = unionAllSelects.get(i);
            // Push down order-by and limit into sub-selects.
            if (!select.getOrderBy().isEmpty() || select.getLimit() != null) {
                if (select.getOffset() == null) {
                    subSelect = NODE_FACTORY.select(subSelect, select.getOrderBy(), select.getLimit(), null);
                } else {
                    subSelect = NODE_FACTORY.select(subSelect, select.getOrderBy(), null, null);
                }
            }
            QueryPlan subPlan = compileSubquery(subSelect, true);
            plans.add(subPlan);
        }
        TableRef tableRef = UnionCompiler.contructSchemaTable(statement, plans,
            select.hasWildcard() ? null : select.getSelect());
        ColumnResolver resolver = FromCompiler.getResolver(tableRef);
        StatementContext context = new StatementContext(statement, resolver, bindManager, scan, sequenceManager);
        QueryPlan plan = compileSingleFlatQuery(
                context,
                select,
                statement.getParameters(),
                false,
                false,
                null,
                false,
                true);
        plan = new UnionPlan(context, select, tableRef, plan.getProjector(), plan.getLimit(),
            plan.getOffset(), plan.getOrderBy(), GroupBy.EMPTY_GROUP_BY, plans,
            context.getBindManager().getParameterMetaData());
        return plan;
    }

    public QueryPlan compileSelect(SelectStatement select) throws SQLException{
        List<Object> binds = statement.getParameters();
        StatementContext context = new StatementContext(statement, resolver, bindManager, scan, sequenceManager);
        if (select.isJoin()) {
            JoinTable joinTable = JoinCompiler.compile(statement, select, context.getResolver());
            return compileJoinQuery(context, binds, joinTable, false, false, null);
        } else {
            return compileSingleQuery(context, select, binds, false, true);
        }
    }

    /**
     * Call compileJoinQuery() for join queries recursively down to the leaf JoinTable nodes.
     * If it is a leaf node, call compileSingleFlatQuery() or compileSubquery(), otherwise:
     *      1) If option COST_BASED_OPTIMIZER_ENABLED is on and stats are available, return the
     *         join plan with the best cost. Note that the "best" plan is only locally optimal,
     *         and might or might not be globally optimal.
     *      2) Otherwise, return the join plan compiled with the default strategy.
     * @see JoinCompiler.JoinTable#getApplicableJoinStrategies()
     */
    protected QueryPlan compileJoinQuery(StatementContext context, List<Object> binds, JoinTable joinTable, boolean asSubquery, boolean projectPKColumns, List<OrderByNode> orderBy) throws SQLException {
        if (joinTable.getJoinSpecs().isEmpty()) {
            Table table = joinTable.getLeftTable();
            SelectStatement subquery = table.getAsSubquery(orderBy);
            if (!table.isSubselect()) {
                context.setCurrentTable(table.getTableRef());
                PTable projectedTable = table.createProjectedTable(!projectPKColumns, context);
                TupleProjector projector = new TupleProjector(projectedTable);
                boolean wildcardIncludesDynamicCols = context.getConnection().getQueryServices()
                        .getConfiguration().getBoolean(WILDCARD_QUERY_DYNAMIC_COLS_ATTRIB,
                                DEFAULT_WILDCARD_QUERY_DYNAMIC_COLS_ATTRIB);
                TupleProjector.serializeProjectorIntoScan(context.getScan(), projector,
                        wildcardIncludesDynamicCols);
                context.setResolver(FromCompiler.getResolverForProjectedTable(projectedTable, context.getConnection(), subquery.getUdfParseNodes()));
                table.projectColumns(context.getScan());
                return compileSingleFlatQuery(
                        context,
                        subquery,
                        binds,
                        asSubquery,
                        !asSubquery,
                        null,
                        true,
                        false);
            }
            QueryPlan plan = compileSubquery(subquery, false);
            PTable projectedTable = table.createProjectedTable(plan.getProjector());
            context.setResolver(FromCompiler.getResolverForProjectedTable(projectedTable, context.getConnection(), subquery.getUdfParseNodes()));
            return new TupleProjectionPlan(
                    plan,
                    new TupleProjector(plan.getProjector()),
                    context,
                    null);
        }

        List<JoinCompiler.Strategy> strategies = joinTable.getApplicableJoinStrategies();
        assert strategies.size() > 0;
        if (!costBased || strategies.size() == 1) {
            return compileJoinQuery(
                    strategies.get(0), context, binds, joinTable, asSubquery, projectPKColumns, orderBy);
        }

        QueryPlan bestPlan = null;
        Cost bestCost = null;
        for (JoinCompiler.Strategy strategy : strategies) {
            StatementContext newContext = new StatementContext(
                    context.getStatement(), context.getResolver(), context.getBindManager(), new Scan(), context.getSequenceManager());
            QueryPlan plan = compileJoinQuery(
                    strategy, newContext, binds, joinTable, asSubquery, projectPKColumns, orderBy);
            Cost cost = plan.getCost();
            if (bestPlan == null || cost.compareTo(bestCost) < 0) {
                bestPlan = plan;
                bestCost = cost;
            }
        }
        context.setResolver(bestPlan.getContext().getResolver());
        context.setCurrentTable(bestPlan.getContext().getCurrentTable());
        return bestPlan;
    }

    protected QueryPlan compileJoinQuery(JoinCompiler.Strategy strategy, StatementContext context, List<Object> binds, JoinTable joinTable, boolean asSubquery, boolean projectPKColumns, List<OrderByNode> orderBy) throws SQLException {
        byte[] emptyByteArray = new byte[0];
        List<JoinSpec> joinSpecs = joinTable.getJoinSpecs();
        boolean wildcardIncludesDynamicCols = context.getConnection().getQueryServices()
                .getConfiguration().getBoolean(WILDCARD_QUERY_DYNAMIC_COLS_ATTRIB,
                        DEFAULT_WILDCARD_QUERY_DYNAMIC_COLS_ATTRIB);
        switch (strategy) {
            case HASH_BUILD_RIGHT: {
                boolean[] starJoinVector = joinTable.getStarJoinVector();
                Table table = joinTable.getLeftTable();
                PTable initialProjectedTable;
                TableRef tableRef;
                SelectStatement query;
                TupleProjector tupleProjector;
                if (!table.isSubselect()) {
                    context.setCurrentTable(table.getTableRef());
                    initialProjectedTable = table.createProjectedTable(!projectPKColumns, context);
                    tableRef = table.getTableRef();
                    table.projectColumns(context.getScan());
                    query = joinTable.getAsSingleSubquery(table.getAsSubquery(orderBy), asSubquery);
                    tupleProjector = new TupleProjector(initialProjectedTable);
                } else {
                    SelectStatement subquery = table.getAsSubquery(orderBy);
                    QueryPlan plan = compileSubquery(subquery, false);
                    initialProjectedTable = table.createProjectedTable(plan.getProjector());
                    tableRef = plan.getTableRef();
                    context.getScan().setFamilyMap(plan.getContext().getScan().getFamilyMap());
                    query = joinTable.getAsSingleSubquery((SelectStatement) plan.getStatement(), asSubquery);
                    tupleProjector = new TupleProjector(plan.getProjector());
                }
                context.setCurrentTable(tableRef);
                PTable projectedTable = initialProjectedTable;
                int count = joinSpecs.size();
                ImmutableBytesPtr[] joinIds = new ImmutableBytesPtr[count];
                List<Expression>[] joinExpressions = new List[count];
                JoinType[] joinTypes = new JoinType[count];
                PTable[] tables = new PTable[count];
                int[] fieldPositions = new int[count];
                StatementContext[] subContexts = new StatementContext[count];
                QueryPlan[] subPlans = new QueryPlan[count];
                HashSubPlan[] hashPlans = new HashSubPlan[count];
                fieldPositions[0] = projectedTable.getColumns().size() - projectedTable.getPKColumns().size();
                for (int i = 0; i < count; i++) {
                    JoinSpec joinSpec = joinSpecs.get(i);
                    Scan subScan = ScanUtil.newScan(originalScan);
                    subContexts[i] = new StatementContext(statement, context.getResolver(), context.getBindManager(), subScan, new SequenceManager(statement));
                    subPlans[i] = compileJoinQuery(
                            subContexts[i],
                            binds,
                            joinSpec.getRhsJoinTable(),
                            true,
                            true,
                            null);
                    boolean hasPostReference = joinSpec.getRhsJoinTable().hasPostReference();
                    if (hasPostReference) {
                        tables[i] = subContexts[i].getResolver().getTables().get(0).getTable();
                        projectedTable = JoinCompiler.joinProjectedTables(projectedTable, tables[i], joinSpec.getType());
                    } else {
                        tables[i] = null;
                    }
                }
                for (int i = 0; i < count; i++) {
                    JoinSpec joinSpec = joinSpecs.get(i);
                    context.setResolver(FromCompiler.getResolverForProjectedTable(projectedTable, context.getConnection(), query.getUdfParseNodes()));
                    joinIds[i] = new ImmutableBytesPtr(emptyByteArray); // place-holder
                    Pair<List<Expression>, List<Expression>> joinConditions = joinSpec.compileJoinConditions(context, subContexts[i], strategy);
                    joinExpressions[i] = joinConditions.getFirst();
                    List<Expression> hashExpressions = joinConditions.getSecond();
                    Pair<Expression, Expression> keyRangeExpressions = new Pair<Expression, Expression>(null, null);
                    boolean optimized = getKeyExpressionCombinations(
                            keyRangeExpressions,
                            context,
                            joinTable.getOriginalJoinSelectStatement(),
                            tableRef,
                            joinSpec.getType(),
                            joinExpressions[i],
                            hashExpressions);
                    Expression keyRangeLhsExpression = keyRangeExpressions.getFirst();
                    Expression keyRangeRhsExpression = keyRangeExpressions.getSecond();
                    joinTypes[i] = joinSpec.getType();
                    if (i < count - 1) {
                        fieldPositions[i + 1] = fieldPositions[i] + (tables[i] == null ? 0 : (tables[i].getColumns().size() - tables[i].getPKColumns().size()));
                    }
                    hashPlans[i] = new HashSubPlan(i, subPlans[i], optimized ? null : hashExpressions, joinSpec.isSingleValueOnly(), usePersistentCache, keyRangeLhsExpression, keyRangeRhsExpression);
                }
                TupleProjector.serializeProjectorIntoScan(context.getScan(), tupleProjector,
                        wildcardIncludesDynamicCols);
                QueryPlan plan = compileSingleFlatQuery(
                        context,
                        query,
                        binds,
                        asSubquery,
                        !asSubquery && joinTable.isAllLeftJoin(),
                        null, true, false);
                Expression postJoinFilterExpression = joinTable.compilePostFilterExpression(context);
                Integer limit = null;
                Integer offset = null;
                if (!query.isAggregate() && !query.isDistinct() && query.getOrderBy().isEmpty()) {
                    limit = plan.getLimit();
                    offset = plan.getOffset();
                }
                HashJoinInfo joinInfo = new HashJoinInfo(projectedTable, joinIds, joinExpressions, joinTypes,
                        starJoinVector, tables, fieldPositions, postJoinFilterExpression, QueryUtil.getOffsetLimit(limit, offset));
                return HashJoinPlan.create(joinTable.getOriginalJoinSelectStatement(), plan, joinInfo, hashPlans);
            }
            case HASH_BUILD_LEFT: {
                JoinSpec lastJoinSpec = joinSpecs.get(joinSpecs.size() - 1);
                JoinType type = lastJoinSpec.getType();
                JoinTable rhsJoinTable = lastJoinSpec.getRhsJoinTable();
                Table rhsTable = rhsJoinTable.getLeftTable();
                JoinTable lhsJoin = joinTable.createSubJoinTable(statement.getConnection());
                Scan subScan = ScanUtil.newScan(originalScan);
                StatementContext lhsCtx = new StatementContext(statement, context.getResolver(), context.getBindManager(), subScan, new SequenceManager(statement));
                QueryPlan lhsPlan = compileJoinQuery(lhsCtx, binds, lhsJoin, true, true, null);
                PTable rhsProjTable;
                TableRef rhsTableRef;
                SelectStatement rhs;
                TupleProjector tupleProjector;
                if (!rhsTable.isSubselect()) {
                    context.setCurrentTable(rhsTable.getTableRef());
                    rhsProjTable = rhsTable.createProjectedTable(!projectPKColumns, context);
                    rhsTableRef = rhsTable.getTableRef();
                    rhsTable.projectColumns(context.getScan());
                    rhs = rhsJoinTable.getAsSingleSubquery(rhsTable.getAsSubquery(orderBy), asSubquery);
                    tupleProjector = new TupleProjector(rhsProjTable);
                } else {
                    SelectStatement subquery = rhsTable.getAsSubquery(orderBy);
                    QueryPlan plan = compileSubquery(subquery, false);
                    rhsProjTable = rhsTable.createProjectedTable(plan.getProjector());
                    rhsTableRef = plan.getTableRef();
                    context.getScan().setFamilyMap(plan.getContext().getScan().getFamilyMap());
                    rhs = rhsJoinTable.getAsSingleSubquery((SelectStatement) plan.getStatement(), asSubquery);
                    tupleProjector = new TupleProjector(plan.getProjector());
                }
                context.setCurrentTable(rhsTableRef);
                context.setResolver(FromCompiler.getResolverForProjectedTable(rhsProjTable, context.getConnection(), rhs.getUdfParseNodes()));
                ImmutableBytesPtr[] joinIds = new ImmutableBytesPtr[]{new ImmutableBytesPtr(emptyByteArray)};
                Pair<List<Expression>, List<Expression>> joinConditions = lastJoinSpec.compileJoinConditions(lhsCtx, context, strategy);
                List<Expression> joinExpressions = joinConditions.getSecond();
                List<Expression> hashExpressions = joinConditions.getFirst();
                boolean needsMerge = lhsJoin.hasPostReference();
                PTable lhsTable = needsMerge ? lhsCtx.getResolver().getTables().get(0).getTable() : null;
                int fieldPosition = needsMerge ? rhsProjTable.getColumns().size() - rhsProjTable.getPKColumns().size() : 0;
                PTable projectedTable = needsMerge ? JoinCompiler.joinProjectedTables(rhsProjTable, lhsTable, type == JoinType.Right ? JoinType.Left : type) : rhsProjTable;
                TupleProjector.serializeProjectorIntoScan(context.getScan(), tupleProjector,
                        wildcardIncludesDynamicCols);
                context.setResolver(FromCompiler.getResolverForProjectedTable(projectedTable, context.getConnection(), rhs.getUdfParseNodes()));
                QueryPlan rhsPlan = compileSingleFlatQuery(
                        context,
                        rhs,
                        binds,
                        asSubquery,
                        !asSubquery && type == JoinType.Right,
                        null,
                        true,
                        false);
                Expression postJoinFilterExpression = joinTable.compilePostFilterExpression(context);
                Integer limit = null;
                Integer offset = null;
                if (!rhs.isAggregate() && !rhs.isDistinct() && rhs.getOrderBy().isEmpty()) {
                    limit = rhsPlan.getLimit();
                    offset = rhsPlan.getOffset();
                }
                HashJoinInfo joinInfo = new HashJoinInfo(projectedTable, joinIds, new List[]{joinExpressions},
                        new JoinType[]{type == JoinType.Right ? JoinType.Left : type}, new boolean[]{true},
                        new PTable[]{lhsTable}, new int[]{fieldPosition}, postJoinFilterExpression, QueryUtil.getOffsetLimit(limit, offset));
                boolean usePersistentCache = joinTable.getOriginalJoinSelectStatement().getHint().hasHint(Hint.USE_PERSISTENT_CACHE);
                Pair<Expression, Expression> keyRangeExpressions = new Pair<Expression, Expression>(null, null);
                getKeyExpressionCombinations(
                        keyRangeExpressions,
                        context,
                        joinTable.getOriginalJoinSelectStatement(),
                        rhsTableRef,
                        type,
                        joinExpressions,
                        hashExpressions);
                return HashJoinPlan.create(
                        joinTable.getOriginalJoinSelectStatement(),
                        rhsPlan,
                        joinInfo,
                        new HashSubPlan[]{
                                new HashSubPlan(
                                        0,
                                        lhsPlan,
                                        hashExpressions,
                                        false,
                                        usePersistentCache,
                                        keyRangeExpressions.getFirst(),
                                        keyRangeExpressions.getSecond())});
            }
            case SORT_MERGE: {
                JoinTable lhsJoin =  joinTable.createSubJoinTable(statement.getConnection());
                JoinSpec lastJoinSpec = joinSpecs.get(joinSpecs.size() - 1);
                JoinType type = lastJoinSpec.getType();
                JoinTable rhsJoin = lastJoinSpec.getRhsJoinTable();
                if (type == JoinType.Right) {
                    JoinTable temp = lhsJoin;
                    lhsJoin = rhsJoin;
                    rhsJoin = temp;
                }

                List<EqualParseNode> joinConditionNodes = lastJoinSpec.getOnConditions();
                List<OrderByNode> lhsOrderBy = Lists.<OrderByNode>newArrayListWithExpectedSize(joinConditionNodes.size());
                List<OrderByNode> rhsOrderBy = Lists.<OrderByNode>newArrayListWithExpectedSize(joinConditionNodes.size());
                for (EqualParseNode condition : joinConditionNodes) {
                    lhsOrderBy.add(NODE_FACTORY.orderBy(type == JoinType.Right ? condition.getRHS() : condition.getLHS(), false, true));
                    rhsOrderBy.add(NODE_FACTORY.orderBy(type == JoinType.Right ? condition.getLHS() : condition.getRHS(), false, true));
                }

                Scan lhsScan = ScanUtil.newScan(originalScan);
                StatementContext lhsCtx = new StatementContext(statement, context.getResolver(), context.getBindManager(), lhsScan, new SequenceManager(statement));
                boolean preserveRowkey = !projectPKColumns && type != JoinType.Full;
                QueryPlan lhsPlan = compileJoinQuery(lhsCtx, binds, lhsJoin, true, !preserveRowkey, lhsOrderBy);
                PTable lhsProjTable = lhsCtx.getResolver().getTables().get(0).getTable();

                Scan rhsScan = ScanUtil.newScan(originalScan);
                StatementContext rhsCtx = new StatementContext(statement, context.getResolver(), context.getBindManager(), rhsScan, new SequenceManager(statement));
                QueryPlan rhsPlan = compileJoinQuery(rhsCtx, binds, rhsJoin, true, true, rhsOrderBy);
                PTable rhsProjTable = rhsCtx.getResolver().getTables().get(0).getTable();

                Pair<List<Expression>, List<Expression>> joinConditions = lastJoinSpec.compileJoinConditions(type == JoinType.Right ? rhsCtx : lhsCtx, type == JoinType.Right ? lhsCtx : rhsCtx, strategy);
                List<Expression> lhsKeyExpressions = type == JoinType.Right ? joinConditions.getSecond() : joinConditions.getFirst();
                List<Expression> rhsKeyExpressions = type == JoinType.Right ? joinConditions.getFirst() : joinConditions.getSecond();

                boolean needsMerge = rhsJoin.hasPostReference();
                int fieldPosition = needsMerge ? lhsProjTable.getColumns().size() - lhsProjTable.getPKColumns().size() : 0;
                PTable projectedTable = needsMerge ? JoinCompiler.joinProjectedTables(lhsProjTable, rhsProjTable, type == JoinType.Right ? JoinType.Left : type) : lhsProjTable;

                ColumnResolver resolver = FromCompiler.getResolverForProjectedTable(projectedTable, context.getConnection(), joinTable.getOriginalJoinSelectStatement().getUdfParseNodes());
                TableRef tableRef = resolver.getTables().get(0);
                StatementContext subCtx = new StatementContext(statement, resolver, context.getBindManager(), ScanUtil.newScan(originalScan), new SequenceManager(statement));
                subCtx.setCurrentTable(tableRef);
                QueryPlan innerPlan = new SortMergeJoinPlan(
                        subCtx,
                        joinTable.getOriginalJoinSelectStatement(),
                        tableRef,
                        type == JoinType.Right ? JoinType.Left : type,
                        lhsPlan,
                        rhsPlan,
                        new Pair<List<Expression>,List<Expression>>(lhsKeyExpressions, rhsKeyExpressions),
                        rhsKeyExpressions,
                        projectedTable,
                        lhsProjTable,
                        needsMerge ? rhsProjTable : null,
                        fieldPosition,
                        lastJoinSpec.isSingleValueOnly(),
                        new Pair<List<OrderByNode>,List<OrderByNode>>(lhsOrderBy, rhsOrderBy));
                context.setCurrentTable(tableRef);
                context.setResolver(resolver);
                TableNode from = NODE_FACTORY.namedTable(tableRef.getTableAlias(), NODE_FACTORY.table(tableRef.getTable().getSchemaName().getString(), tableRef.getTable().getTableName().getString()));
                ParseNode where = joinTable.getPostFiltersCombined();
                SelectStatement select = asSubquery ?
                        NODE_FACTORY.select(
                                from,
                                joinTable.getOriginalJoinSelectStatement().getHint(),
                                false,
                                Collections.<AliasedNode>emptyList(),
                                where,
                                null,
                                null,
                                orderBy,
                                null,
                                null,
                                0,
                                false,
                                joinTable.getOriginalJoinSelectStatement().hasSequence(),
                                Collections.<SelectStatement>emptyList(),
                                joinTable.getOriginalJoinSelectStatement().getUdfParseNodes()) :
                         NODE_FACTORY.select(
                                 joinTable.getOriginalJoinSelectStatement(),
                                 from,
                                 where);

                return compileSingleFlatQuery(
                        context,
                        select,
                        binds,
                        asSubquery,
                        false,
                        innerPlan,
                        true,
                        false);
            }
            default:
                throw new IllegalArgumentException("Invalid join strategy '" + strategy + "'");
        }
    }

    private boolean getKeyExpressionCombinations(Pair<Expression, Expression> combination, StatementContext context, SelectStatement select, TableRef table, JoinType type, final List<Expression> joinExpressions, final List<Expression> hashExpressions) throws SQLException {
        if ((type != JoinType.Inner && type != JoinType.Semi) || this.noChildParentJoinOptimization)
            return false;

        Scan scanCopy = ScanUtil.newScan(context.getScan());
        StatementContext contextCopy = new StatementContext(statement, context.getResolver(), context.getBindManager(), scanCopy, new SequenceManager(statement));
        contextCopy.setCurrentTable(table);
        List<Expression> lhsCombination = Lists.<Expression> newArrayList();
        boolean complete = WhereOptimizer.getKeyExpressionCombination(lhsCombination, contextCopy, select, joinExpressions);
        if (lhsCombination.isEmpty())
            return false;

        List<Expression> rhsCombination = Lists.newArrayListWithExpectedSize(lhsCombination.size());
        for (int i = 0; i < lhsCombination.size(); i++) {
            Expression lhs = lhsCombination.get(i);
            for (int j = 0; j < joinExpressions.size(); j++) {
                if (lhs == joinExpressions.get(j)) {
                    rhsCombination.add(hashExpressions.get(j));
                    break;
                }
            }
        }

        if (lhsCombination.size() == 1) {
            combination.setFirst(lhsCombination.get(0));
            combination.setSecond(rhsCombination.get(0));
        } else {
            combination.setFirst(new RowValueConstructorExpression(lhsCombination, false));
            combination.setSecond(new RowValueConstructorExpression(rhsCombination, false));
        }

        return type == JoinType.Semi && complete;
    }

    protected QueryPlan compileSubquery(
            SelectStatement subquerySelectStatement,
            boolean pushDownMaxRows) throws SQLException {
        PhoenixConnection phoenixConnection = this.statement.getConnection();
        RewriteResult rewriteResult =
                ParseNodeUtil.rewrite(subquerySelectStatement, phoenixConnection);
        int maxRows = this.statement.getMaxRows();
        this.statement.setMaxRows(pushDownMaxRows ? maxRows : 0); // overwrite maxRows to avoid its impact on inner queries.
        QueryPlan queryPlan = new QueryCompiler(
                this.statement,
                rewriteResult.getRewrittenSelectStatement(),
                rewriteResult.getColumnResolver(),
                bindManager,
                false,
                optimizeSubquery,
                null).compile();
        if (optimizeSubquery) {
            queryPlan = statement.getConnection().getQueryServices().getOptimizer().optimize(
                    statement,
                    queryPlan);
        }
        this.statement.setMaxRows(maxRows); // restore maxRows.
        return queryPlan;
    }

    protected QueryPlan compileSingleQuery(StatementContext context, SelectStatement select, List<Object> binds, boolean asSubquery, boolean allowPageFilter) throws SQLException{
        SelectStatement innerSelect = select.getInnerSelectStatement();
        if (innerSelect == null) {
            return compileSingleFlatQuery(context, select, binds, asSubquery, allowPageFilter, null, false, false);
        }

        if((innerSelect.getOffset() != null && (!innerSelect.getOffset().isIntegerOffset()) ||
                select.getOffset() != null && !select.getOffset().isIntegerOffset())) {
            throw new SQLException("RVC Offset not allowed with subqueries.");
        }

        QueryPlan innerPlan = compileSubquery(innerSelect, false);
        RowProjector innerQueryPlanRowProjector = innerPlan.getProjector();
        TupleProjector tupleProjector = new TupleProjector(innerQueryPlanRowProjector);

        // Replace the original resolver and table with those having compiled type info.
        TableRef tableRef = context.getResolver().getTables().get(0);
        ColumnResolver resolver = FromCompiler.getResolverForCompiledDerivedTable(statement.getConnection(), tableRef, innerQueryPlanRowProjector);
        context.setResolver(resolver);
        tableRef = resolver.getTables().get(0);
        context.setCurrentTable(tableRef);
        innerPlan = new TupleProjectionPlan(innerPlan, tupleProjector, context, null);

        return compileSingleFlatQuery(context, select, binds, asSubquery, allowPageFilter, innerPlan, false, false);
    }

    protected QueryPlan compileSingleFlatQuery(
            StatementContext context,
            SelectStatement select,
            List<Object> binds,
            boolean asSubquery,
            boolean allowPageFilter,
            QueryPlan innerPlan,
            boolean inJoin,
            boolean inUnion) throws SQLException {
        boolean isApplicable = true;
        PTable projectedTable = null;
        if (this.projectTuples) {
            projectedTable = TupleProjectionCompiler.createProjectedTable(select, context);
            if (projectedTable != null) {
                context.setResolver(FromCompiler.getResolverForProjectedTable(projectedTable, context.getConnection(), select.getUdfParseNodes()));
            }
        }

        ColumnResolver resolver = context.getResolver();
        TableRef tableRef = context.getCurrentTable();
        PTable table = tableRef.getTable();

        ParseNode viewWhere = null;
        if (table.getViewStatement() != null) {
            viewWhere = new SQLParser(table.getViewStatement()).parseQuery().getWhere();
        }
        Integer limit = LimitCompiler.compile(context, select);

        CompiledOffset compiledOffset = null;
        Integer offset = null;
        try {
            compiledOffset = OffsetCompiler.getOffsetCompiler().compile(context, select, inJoin, inUnion);
            offset = compiledOffset.getIntegerOffset().orNull();
        } catch(RowValueConstructorOffsetNotCoercibleException e){
            //This current plan is not executable
            compiledOffset = new CompiledOffset(Optional.<Integer>absent(),Optional.<byte[]>absent());
            isApplicable = false;
        }

        GroupBy groupBy = GroupByCompiler.compile(context, select);
        // Optimize the HAVING clause by finding any group by expressions that can be moved
        // to the WHERE clause
        select = HavingCompiler.rewrite(context, select, groupBy);
        Expression having = HavingCompiler.compile(context, select, groupBy);
        // Don't pass groupBy when building where clause expression, because we do not want to wrap these
        // expressions as group by key expressions since they're pre, not post filtered.
        if (innerPlan == null && !tableRef.equals(resolver.getTables().get(0))) {
        	context.setResolver(FromCompiler.getResolver(context.getConnection(), tableRef, select.getUdfParseNodes()));
        }
        Set<SubqueryParseNode> subqueries = Sets.<SubqueryParseNode> newHashSet();
        Expression where = WhereCompiler.compile(context, select, viewWhere, subqueries, compiledOffset.getByteOffset());
        // Recompile GROUP BY now that we've figured out our ScanRanges so we know
        // definitively whether or not we'll traverse in row key order.
        groupBy = groupBy.compile(context, innerPlan, where);
        context.setResolver(resolver); // recover resolver
        boolean wildcardIncludesDynamicCols = context.getConnection().getQueryServices()
                .getConfiguration().getBoolean(WILDCARD_QUERY_DYNAMIC_COLS_ATTRIB,
                        DEFAULT_WILDCARD_QUERY_DYNAMIC_COLS_ATTRIB);
        RowProjector projector = ProjectionCompiler.compile(context, select, groupBy,
                asSubquery ? Collections.emptyList() : targetColumns, where,
                wildcardIncludesDynamicCols);
        OrderBy orderBy = OrderByCompiler.compile(
                context,
                select,
                groupBy,
                limit,
                compiledOffset,
                projector,
                innerPlan,
                where);
        context.getAggregationManager().compile(context, groupBy);
        // Final step is to build the query plan
        if (!asSubquery) {
            int maxRows = statement.getMaxRows();
            if (maxRows > 0) {
                if (limit != null) {
                    limit = Math.min(limit, maxRows);
                } else {
                    limit = maxRows;
                }
            }
        }

        if (projectedTable != null) {
            TupleProjector.serializeProjectorIntoScan(context.getScan(),
                    new TupleProjector(projectedTable), wildcardIncludesDynamicCols &&
                            projector.projectDynColsInWildcardQueries());
        }

        QueryPlan plan = innerPlan;
        QueryPlan dataPlan = dataPlans.get(tableRef);
        if (plan == null) {
            ParallelIteratorFactory parallelIteratorFactory = asSubquery ? null : this.parallelIteratorFactory;
            plan = select.getFrom() == null
                    ? new LiteralResultIterationPlan(context, select, tableRef, projector, limit, offset, orderBy,
                            parallelIteratorFactory)
                    : (select.isAggregate() || select.isDistinct()
                            ? new AggregatePlan(context, select, tableRef, projector, limit, offset, orderBy,
                                    parallelIteratorFactory, groupBy, having, dataPlan)
                            : new ScanPlan(context, select, tableRef, projector, limit, offset, orderBy,
                                    parallelIteratorFactory, allowPageFilter, dataPlan, compiledOffset.getByteOffset()));
        }
        SelectStatement planSelect = asSubquery ? select : this.select;
        if (!subqueries.isEmpty()) {
            int count = subqueries.size();
            WhereClauseSubPlan[] subPlans = new WhereClauseSubPlan[count];
            int i = 0;
            for (SubqueryParseNode subqueryNode : subqueries) {
                SelectStatement stmt = subqueryNode.getSelectNode();
                subPlans[i++] = new WhereClauseSubPlan(compileSubquery(stmt, false), stmt, subqueryNode.expectSingleRow());
            }
            plan = HashJoinPlan.create(planSelect, plan, null, subPlans);
        }

        if (innerPlan != null) {
            if (LiteralExpression.isTrue(where)) {
                where = null; // we do not pass "true" as filter
            }
            plan = select.isAggregate() || select.isDistinct()
                    ? new ClientAggregatePlan(context, planSelect, tableRef, projector, limit, offset, where, orderBy,
                            groupBy, having, plan)
                    : new ClientScanPlan(context, planSelect, tableRef, projector, limit, offset, where, orderBy, plan);

        }

        if(plan instanceof BaseQueryPlan){
            ((BaseQueryPlan) plan).setApplicable(isApplicable);
        }
        return plan;
    }
}


text:
```cpp
constexpr bool is_primitive() const noexcept;
```

This function returns `#!cpp true` if and only if the JSON type is primitive (string, number, boolean, `#!json null`,
binary).

## Return value

`#!cpp true` if type is primitive (string, number, boolean, `#!json null`, or binary), `#!cpp false` otherwise.

## Exception safety

No-throw guarantee: this member function never throws exceptions.

## Complexity

Constant.

## Possible implementation

```cpp
constexpr bool is_primitive() const noexcept
{
    return is_null() || is_string() || is_boolean() || is_number() || is_binary();
}
```

## Notes

The term *primitive* stems from [RFC 8259](https://tools.ietf.org/html/rfc8259):

> JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and
> arrays).

This library extends primitive types to binary types, because binary types are  roughly comparable to strings. Hence,
`is_primitive()` returns `#!cpp true` for binary values.

## Examples

??? example

    The following code exemplifies `is_primitive()` for all JSON types.

    ```cpp
    --8<-- "examples/is_primitive.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/is_primitive.output"
    ```

## See also

- [is_structured()](is_structured.md) returns whether JSON value is structured
- [is_null()](is_null.md) returns whether JSON value is `null`
- [is_string()](is_string.md) returns whether JSON value is a string
- [is_boolean()](is_boolean.md) returns whether JSON value is a boolean
- [is_number()](is_number.md) returns whether JSON value is a number
- [is_binary()](is_binary.md) returns whether JSON value is a binary array

## Version history

- Added in version 1.0.0.
- Extended to return `#!cpp true` for binary types in version 3.8.0.

redpajama_set_name: RedPajamaGithub


text:
'use strict';

describe('ReactPropTypesProduction', function() {
  var oldProcess;

  var PropTypes;
  var React;
  var ReactPropTypeLocations;
  var ReactTestUtils;

  beforeEach(function() {
    __DEV__ = false;
    oldProcess = process;
    global.process = {
      env: Object.assign({}, process.env, {NODE_ENV: 'production'}),
    };

    jest.resetModules();
    PropTypes = require('ReactPropTypes');
    React = require('React');
    ReactPropTypeLocations = require('ReactPropTypeLocations');
    ReactTestUtils = require('ReactTestUtils');
  });

  afterEach(function() {
    __DEV__ = true;
    global.process = oldProcess;
  });

  function expectThrowsInProduction(declaration, value) {
    var props = {testProp: value};
    expect(() => {
      declaration(
        props,
        'testProp',
        'testComponent',
        ReactPropTypeLocations.prop
      );
    }).toThrowError(
      'React.PropTypes type checking code is stripped in production.'
    );
  }

  describe('Primitive Types', function() {
    it('should be a no-op', function() {
      expectThrowsInProduction(PropTypes.array, /please/);
      expectThrowsInProduction(PropTypes.array.isRequired, /please/);
      expectThrowsInProduction(PropTypes.array.isRequired, null);
      expectThrowsInProduction(PropTypes.array.isRequired, undefined);
      expectThrowsInProduction(PropTypes.bool, []);
      expectThrowsInProduction(PropTypes.bool.isRequired, []);
      expectThrowsInProduction(PropTypes.bool.isRequired, null);
      expectThrowsInProduction(PropTypes.bool.isRequired, undefined);
      expectThrowsInProduction(PropTypes.func, false);
      expectThrowsInProduction(PropTypes.func.isRequired, false);
      expectThrowsInProduction(PropTypes.func.isRequired, null);
      expectThrowsInProduction(PropTypes.func.isRequired, undefined);
      expectThrowsInProduction(PropTypes.number, function() {});
      expectThrowsInProduction(PropTypes.number.isRequired, function() {});
      expectThrowsInProduction(PropTypes.number.isRequired, null);
      expectThrowsInProduction(PropTypes.number.isRequired, undefined);
      expectThrowsInProduction(PropTypes.string, 0);
      expectThrowsInProduction(PropTypes.string.isRequired, 0);
      expectThrowsInProduction(PropTypes.string.isRequired, null);
      expectThrowsInProduction(PropTypes.string.isRequired, undefined);
      expectThrowsInProduction(PropTypes.symbol, 0);
      expectThrowsInProduction(PropTypes.symbol.isRequired, 0);
      expectThrowsInProduction(PropTypes.symbol.isRequired, null);
      expectThrowsInProduction(PropTypes.symbol.isRequired, undefined);
      expectThrowsInProduction(PropTypes.object, '');
      expectThrowsInProduction(PropTypes.object.isRequired, '');
      expectThrowsInProduction(PropTypes.object.isRequired, null);
      expectThrowsInProduction(PropTypes.object.isRequired, undefined);
    });
  });

  describe('Any Type', function() {
    it('should be a no-op', function() {
      expectThrowsInProduction(PropTypes.any, null);
      expectThrowsInProduction(PropTypes.any.isRequired, null);
      expectThrowsInProduction(PropTypes.any.isRequired, undefined);
    });
  });

  describe('ArrayOf Type', function() {
    it('should be a no-op', function() {
      expectThrowsInProduction(
        PropTypes.arrayOf({ foo: PropTypes.string }),
        { foo: 'bar' }
      );
      expectThrowsInProduction(
        PropTypes.arrayOf(PropTypes.number),
        [1, 2, 'b']
      );
      expectThrowsInProduction(
        PropTypes.arrayOf(PropTypes.number),
        {'0': 'maybe-array', length: 1}
      );
      expectThrowsInProduction(PropTypes.arrayOf(PropTypes.number).isRequired, null);
      expectThrowsInProduction(PropTypes.arrayOf(PropTypes.number).isRequired, undefined);
    });
  });

  describe('Component Type', function() {
    it('should be a no-op', function() {
      expectThrowsInProduction(PropTypes.element, [<div />, <div />]);
      expectThrowsInProduction(PropTypes.element, 123);
      expectThrowsInProduction(PropTypes.element, 'foo');
      expectThrowsInProduction(PropTypes.element, false);
      expectThrowsInProduction(PropTypes.element.isRequired, null);
      expectThrowsInProduction(PropTypes.element.isRequired, undefined);
    });
  });

  describe('Instance Types', function() {
    it('should be a no-op', function() {
      expectThrowsInProduction(PropTypes.instanceOf(Date), {});
      expectThrowsInProduction(PropTypes.instanceOf(Date).isRequired, {});
    });
  });

  describe('React Component Types', function() {
    it('should be a no-op', function() {
      expectThrowsInProduction(PropTypes.node, {});
      expectThrowsInProduction(PropTypes.node.isRequired, null);
      expectThrowsInProduction(PropTypes.node.isRequired, undefined);
    });
  });

  describe('ObjectOf Type', function() {
    it('should be a no-op', function() {
      expectThrowsInProduction(
        PropTypes.objectOf({ foo: PropTypes.string }),
        { foo: 'bar' }
      );
      expectThrowsInProduction(
        PropTypes.objectOf(PropTypes.number),
        {a: 1, b: 2, c: 'b'}
      );
      expectThrowsInProduction(PropTypes.objectOf(PropTypes.number), [1, 2]);
      expectThrowsInProduction(PropTypes.objectOf(PropTypes.number), null);
      expectThrowsInProduction(PropTypes.objectOf(PropTypes.number), undefined);
    });
  });

  describe('OneOf Types', function() {
    it('should be a no-op', function() {
      expectThrowsInProduction(PropTypes.oneOf('red', 'blue'), 'red');
      expectThrowsInProduction(PropTypes.oneOf(['red', 'blue']), true);
      expectThrowsInProduction(PropTypes.oneOf(['red', 'blue']), null);
      expectThrowsInProduction(PropTypes.oneOf(['red', 'blue']), undefined);
    });
  });

  describe('Union Types', function() {
    it('should be a no-op', function() {
      expectThrowsInProduction(
        PropTypes.oneOfType(PropTypes.string, PropTypes.number),
        'red'
      );
      expectThrowsInProduction(
        PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
        []
      );
      expectThrowsInProduction(
        PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
        null
      );
      expectThrowsInProduction(
        PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
        undefined
      );
    });
  });

  describe('Shape Types', function() {
    it('should be a no-op', function() {
      expectThrowsInProduction(PropTypes.shape({}), 'some string');
      expectThrowsInProduction(
        PropTypes.shape({key: PropTypes.number}).isRequired,
        null
      );
      expectThrowsInProduction(
        PropTypes.shape({key: PropTypes.number}).isRequired,
        undefined
      );
    });
  });

  describe('Custom validator', function() {
    beforeEach(function() {
      jest.resetModules();
    });

    it('should not have been called', function() {
      var spy = jest.fn();
      var Component = React.createClass({
        propTypes: {num: spy},

        render: function() {
          return <div />;
        },
      });

      var instance = <Component num={5} />;
      ReactTestUtils.renderIntoDocument(instance);

      expect(spy).not.toBeCalled();
    });
  });
});


text:
<?php

namespace GraphAware\Neo4j\OGM\Metadata;

final class PropertyAnnotationMetadata
{
    /**
     * @var string
     */
    private $type;

    /**
     * @var null|string
     */
    private $key;

    /**
     * @var bool
     */
    private $nullable;

    public function __construct($type, $key = null, $nullable = null)
    {
        $this->type = $type;
        $this->key = $key;
        $this->nullable = null !== $nullable ? (bool) $nullable : true;
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @return bool
     */
    public function hasCustomKey()
    {
        return null !== $this->key;
    }

    /**
     * @return null|string
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * @return bool
     */
    public function isNullable()
    {
        return $this->nullable;
    }
}


text:
#include "CMFGame.hpp"
#include "CArchitectureQueue.hpp"
#include "World/CPlayer.hpp"
#include "MP1.hpp"
#include "AutoMapper/CAutoMapper.hpp"
#include "CSamusHud.hpp"
#include "TCastTo.hpp"
#include "Audio/CMidiManager.hpp"
#include "Camera/CCinematicCamera.hpp"

namespace urde::MP1 {

CMFGame::CMFGame(const std::weak_ptr<CStateManager>& stateMgr, const std::weak_ptr<CInGameGuiManager>& guiMgr,
                 const CArchitectureQueue&)
: CMFGameBase("CMFGame"), x14_stateManager(stateMgr.lock()), x18_guiManager(guiMgr.lock()) {
  x2a_25_samusAlive = true;
  static_cast<CMain&>(*g_Main).SetMFGameBuilt(true);
}

CMFGame::~CMFGame() {
  CMain& main = static_cast<CMain&>(*g_Main);
  main.SetMFGameBuilt(false);
  main.SetScreenFading(false);
  CDecalManager::Reinitialize();
}

CIOWin::EMessageReturn CMFGame::OnMessage(const CArchitectureMessage& msg, CArchitectureQueue& queue) {
  switch (msg.GetType()) {
  case EArchMsgType::FrameBegin:
    x14_stateManager->FrameBegin(msg.GetParm<CArchMsgParmInt32>()->x4_parm);
    break;
  case EArchMsgType::TimerTick: {
    bool wasInitialized = x2a_24_initialized;
    x2a_24_initialized = true;
    float dt = MakeMsg::GetParmTimerTick(msg).x4_parm;

    /* URDE addition: this is continuously updated for animated UVs even when game paused */
    x14_stateManager->UpdateGraphicsTiming(dt);

    switch (x1c_flowState) {
    case EGameFlowState::CinematicSkip: {
      x20_cineSkipTime += dt;
      const CEntity* cam = x14_stateManager->GetCameraManager()->GetCurrentCamera(*x14_stateManager);
      TCastToConstPtr<CCinematicCamera> cineCam = cam;
      if ((x20_cineSkipTime >= 1.f && x14_stateManager->SpecialSkipCinematic()) || !cineCam ||
          (cineCam->GetFlags() & 0x10 && x28_skippedCineCam != cineCam->GetUniqueId())) {
        static_cast<CMain&>(*g_Main).SetScreenFading(false);
        x1c_flowState = EGameFlowState::InGame;
        x18_guiManager->StartFadeIn();
        x28_skippedCineCam = kInvalidUniqueId;
        break;
      }
      [[fallthrough]];
    }
    case EGameFlowState::InGame: {
      x14_stateManager->SetActiveRandomToDefault();
      switch (x14_stateManager->GetDeferredStateTransition()) {
      case EStateManagerTransition::InGame:
        x14_stateManager->Update(dt);
        if (!x14_stateManager->ShouldQuitGame())
          break;
        // CGraphics::SetIsBeginSceneClearFb();
        break;
      case EStateManagerTransition::MapScreen:
        EnterMapScreen();
        break;
      case EStateManagerTransition::PauseGame:
        PauseGame();
        break;
      case EStateManagerTransition::LogBook:
        EnterLogBook();
        break;
      case EStateManagerTransition::SaveGame:
        SaveGame();
        break;
      case EStateManagerTransition::MessageScreen:
        EnterMessageScreen(x14_stateManager->GetHUDMessageTime());
        break;
      }

      if (x2a_25_samusAlive && !x14_stateManager->GetPlayerState()->IsPlayerAlive()) {
        PlayerDied();
      }
      x14_stateManager->ClearActiveRandom();
      break;
    }
    case EGameFlowState::Paused: {
      if (x18_guiManager->WasInGame() && x18_guiManager->IsInGame()) {
        x14_stateManager->SetInSaveUI(x18_guiManager->IsInSaveUI());
        UnpauseGame();
        if (x14_stateManager->GetPauseHUDMessage().IsValid())
          x14_stateManager->IncrementHUDMessageFrameCounter();
      }
      break;
    }
    case EGameFlowState::SamusDied: {
      if (x14_stateManager->GetPlayer().IsPlayerDeadEnough()) {
        static_cast<CMain&>(*g_Main).SetFlowState(EFlowState::LoseGame);
        queue.Push(MakeMsg::CreateQuitGameplay(EArchMsgTarget::Game));
      } else {
        x14_stateManager->SetActiveRandomToDefault();
        x14_stateManager->Update(dt);
        x14_stateManager->ClearActiveRandom();
      }
      break;
    }
    default:
      break;
    }

    x18_guiManager->Update(*x14_stateManager, dt, queue, IsCameraActiveFlow());
    if (!wasInitialized)
      g_GameState->GetWorldTransitionManager()->EndTransition();

    return EMessageReturn::Exit;
  }
  case EArchMsgType::UserInput: {
    if (!x2a_24_initialized)
      break;
    const CFinalInput& input = MakeMsg::GetParmUserInput(msg).x4_parm;
    if (x1c_flowState == EGameFlowState::InGame) {
      if (input.ControllerIdx() == 0) {
        const CEntity* cam = x14_stateManager->GetCameraManager()->GetCurrentCamera(*x14_stateManager);
        TCastToConstPtr<CCinematicCamera> cineCam = cam;
        if (input.PStart() || input.PSpecialKey(boo::ESpecialKey::Esc)) {
          if (cineCam && x14_stateManager->GetSkipCinematicSpecialFunction() != kInvalidUniqueId) {
            CMidiManager::StopAll();
            x28_skippedCineCam = cineCam->GetUniqueId();
            x1c_flowState = EGameFlowState::CinematicSkip;
            x20_cineSkipTime = 0.f;
          } else if (!cineCam) {
            x14_stateManager->DeferStateTransition(EStateManagerTransition::PauseGame);
          }
        } else if ((input.PZ() || input.PKey('\t')) && !cineCam && x14_stateManager->CanShowMapScreen()) {
          x14_stateManager->DeferStateTransition(EStateManagerTransition::MapScreen);
        }
      }

      x14_stateManager->SetActiveRandomToDefault();
      x14_stateManager->ProcessInput(input);
      x14_stateManager->ClearActiveRandom();
    }
    x18_guiManager->ProcessControllerInput(*x14_stateManager, input, queue);
    break;
  }
  case EArchMsgType::FrameEnd: {
    x14_stateManager->FrameEnd();
    if (x14_stateManager->ShouldQuitGame())
      queue.Push(MakeMsg::CreateQuitGameplay(EArchMsgTarget::Game));
    break;
  }
  case EArchMsgType::QuitGameplay:
    return EMessageReturn::RemoveIOWin;
  default:
    break;
  }

  return EMessageReturn::Normal;
}

void CMFGame::Touch() {
  x14_stateManager->TouchSky();
  x14_stateManager->TouchPlayerActor();

  bool gunVisible = false;
  bool ballVisible = false;
  bool samusVisible = false;
  CPlayer& player = x14_stateManager->GetPlayer();
  switch (player.GetMorphballTransitionState()) {
  case CPlayer::EPlayerMorphBallState::Unmorphed:
    gunVisible = true;
    break;
  case CPlayer::EPlayerMorphBallState::Morphed:
    ballVisible = true;
    break;
  case CPlayer::EPlayerMorphBallState::Morphing:
    ballVisible = true;
    samusVisible = true;
    break;
  case CPlayer::EPlayerMorphBallState::Unmorphing:
    gunVisible = true;
    samusVisible = true;
    break;
  }

  if (gunVisible)
    player.GetPlayerGun()->TouchModel(*x14_stateManager);
  if (samusVisible)
    player.GetModelData()->Touch(*x14_stateManager, 0);
  if (ballVisible)
    player.GetMorphBall()->TouchModel(*x14_stateManager);
}

void CMFGame::Draw() const {
  if (!x2a_24_initialized)
    return;
  SCOPED_GRAPHICS_DEBUG_GROUP("CMFGame::Draw", zeus::skGreen);

  const_cast<CMFGame&>(*this).Touch();
  if (x18_guiManager->GetIsGameDraw()) {
    static_cast<CMain&>(*g_Main).SetGameFrameDrawn();
    x14_stateManager->PreRender();
    x14_stateManager->DrawWorld();
    x14_stateManager->GetPlayer().IsPlayerDeadEnough();
  }

  x18_guiManager->PreDraw(*x14_stateManager, IsCameraActiveFlow());
  x18_guiManager->Draw(*x14_stateManager);

  if (x1c_flowState == EGameFlowState::CinematicSkip) {
    float c = std::min(1.f, 1.f - x20_cineSkipTime);
    const_cast<CColoredQuadFilter&>(m_fadeToBlack).draw(zeus::CColor{c, c, c, c});
  }
}

void CMFGame::PlayerDied() {
  x1c_flowState = EGameFlowState::SamusDied;
  x2a_25_samusAlive = false;
}

void CMFGame::UnpauseGame() {
  x1c_flowState = EGameFlowState::InGame;
  CSfxManager::SetChannel(CSfxManager::ESfxChannels::Game);
  x14_stateManager->DeferStateTransition(EStateManagerTransition::InGame);
}

void CMFGame::EnterMessageScreen(float time) {
  x1c_flowState = EGameFlowState::Paused;
  x18_guiManager->ShowPauseGameHudMessage(*x14_stateManager, x14_stateManager->GetPauseHUDMessage(), time);
}

void CMFGame::SaveGame() {
  x1c_flowState = EGameFlowState::Paused;
  x18_guiManager->PauseGame(*x14_stateManager, EInGameGuiState::PauseSaveGame);
}

void CMFGame::EnterLogBook() {
  x1c_flowState = EGameFlowState::Paused;
  x18_guiManager->PauseGame(*x14_stateManager, EInGameGuiState::PauseLogBook);
}

void CMFGame::PauseGame() {
  x1c_flowState = EGameFlowState::Paused;
  x18_guiManager->PauseGame(*x14_stateManager, EInGameGuiState::PauseGame);
}

void CMFGame::EnterMapScreen() {
  x1c_flowState = EGameFlowState::Paused;
  x18_guiManager->PauseGame(*x14_stateManager, EInGameGuiState::MapScreen);
  x14_stateManager->SetInMapScreen(true);
}

CMFGameLoader::CMFGameLoader() : CMFGameLoaderBase("CMFGameLoader") {
  CMain* m = static_cast<CMain*>(g_Main);
  switch (m->GetFlowState()) {
  case EFlowState::Default:
  case EFlowState::StateSetter: {
    CAssetId mlvlId = g_GameState->CurrentWorldAssetId();
    if (g_MemoryCardSys->HasSaveWorldMemory(mlvlId)) {
      const CSaveWorldMemory& savwMem = g_MemoryCardSys->GetSaveWorldMemory(mlvlId);
      if (savwMem.GetWorldNameId().IsValid()) {
        CAssetId wtMgrFont = g_ResFactory->TranslateOriginalToNew(0xB7BBD0B4);
        g_GameState->GetWorldTransitionManager()->EnableTransition(wtMgrFont, savwMem.GetWorldNameId(), 1, false, 0.1f,
                                                                   16.f, 1.f);
      }
    }
    break;
  }
  default:
    break;
  }

  if (g_GameState->CurrentWorldAssetId() == g_ResFactory->TranslateOriginalToNew(0x158EFE17) &&
      g_GameState->CurrentWorldState().GetCurrentAreaId() == 0) {
    const SObjectTag* strgTag = g_ResFactory->GetResourceIdByName("STRG_IntroLevelLoad");
    if (strgTag)
      g_GameState->GetWorldTransitionManager()->EnableTransition(-1, strgTag->id, 0, false, 0.1f, 16.f, 1.f);
  }
}

CMFGameLoader::~CMFGameLoader() {}

static const char* LoadDepPAKs[] = {"TestAnim", "SamusGun", "SamGunFx", nullptr};

void CMFGameLoader::MakeLoadDependencyList() {
  std::vector<SObjectTag> tags;
  for (int i = 0; LoadDepPAKs[i]; ++i)
    g_ResFactory->GetTagListForFile(LoadDepPAKs[i], tags);

  x1c_loadList.reserve(tags.size());
  for (const SObjectTag& tag : tags)
    x1c_loadList.push_back(g_SimplePool->GetObj(tag));
}

CIOWin::EMessageReturn CMFGameLoader::OnMessage(const CArchitectureMessage& msg, CArchitectureQueue& queue) {
  std::shared_ptr<CWorldTransManager> wtMgr = g_GameState->GetWorldTransitionManager();

  switch (msg.GetType()) {
  case EArchMsgType::TimerTick: {
    const CArchMsgParmReal32& tick = MakeMsg::GetParmTimerTick(msg);
    float dt = tick.x4_parm;
    if (!x2c_24_initialized) {
      if (x1c_loadList.empty()) {
        MakeLoadDependencyList();
        wtMgr->StartTransition();
        return EMessageReturn::Exit;
      }
      u32 loadingCount = 0;
      for (CToken& tok : x1c_loadList) {
        tok.Lock();
        if (!tok.IsLoaded())
          ++loadingCount;
      }
      wtMgr->Update(dt);
      if (loadingCount)
        return EMessageReturn::Exit;
      x2c_24_initialized = true;
    } else {
      wtMgr->Update(dt);
    }

    if (!x14_stateMgr) {
      CWorldTransManager::WaitForModelsAndTextures();
      CWorldState& wldState = g_GameState->CurrentWorldState();
      x14_stateMgr = std::make_shared<CStateManager>(wldState.RelayTracker(), wldState.MapWorldInfo(),
                                                     g_GameState->GetPlayerState(), wtMgr, wldState.GetLayerState());
    }

    if (x14_stateMgr->xb3c_initPhase != CStateManager::EInitPhase::Done) {
      CWorldState& wldState = g_GameState->CurrentWorldState();
      x14_stateMgr->InitializeState(wldState.GetWorldAssetId(), wldState.GetCurrentAreaId(),
                                    wldState.GetDesiredAreaAssetId());
      return EMessageReturn::Exit;
    }

    if (!x18_guiMgr)
      x18_guiMgr = std::make_shared<CInGameGuiManager>(*x14_stateMgr, queue);
    if (!x18_guiMgr->CheckLoadComplete(*x14_stateMgr))
      return EMessageReturn::Exit;

    x1c_loadList.clear();

    if (!CGraphics::g_BooFactory->areShadersReady())
      return EMessageReturn::Exit;

    wtMgr->StartTextFadeOut();
    x2c_25_transitionFinished = wtMgr->IsTransitionFinished();
    return EMessageReturn::Exit;
  }
  case EArchMsgType::FrameEnd: {
    if (x2c_25_transitionFinished) {
      queue.Push(MakeMsg::CreateCreateIOWin(EArchMsgTarget::IOWinManager, 10, 1000,
                                            std::make_shared<CMFGame>(x14_stateMgr, x18_guiMgr, queue)));
      return EMessageReturn::RemoveIOWinAndExit;
    }
    break;
  }
  default:
    break;
  }
  return EMessageReturn::Exit;
}

void CMFGameLoader::Draw() const {
  SCOPED_GRAPHICS_DEBUG_GROUP("CMFGameLoader::Draw", zeus::skGreen);
  g_GameState->GetWorldTransitionManager()->Draw();
}

} // namespace urde::MP1


text:
var azure = require('azure');

function update(item, user, request) {

    var accountName = 'accountname';
    var accountKey = 'accountkey';
    var host = accountName + '.table.core.windows.net';
    var tableService = azure.createTableService(accountName, accountKey, host);

    tableService.updateEntity(request.parameters.table, item, function (error) {
        if (!error) {
            request.respond(200, item);
        } else {
            request.respond(500);
        }
    });
}


text:
<?php

/**
 * Rebuild the index of solr.
 *
 * @package tjSolrDoctrineBehaviorPlugin
 * @subpackage task
 * @author Marc Weistroff <mweistroff@uneviemoinschere.com>
 * @author Thibault Jouannic <thibault@jouannic.fr>
 * @author Ashton Honnecke <ashton@pixelstub.com>
 */
class rebuildIndexTask extends sfBaseTask
{
  /**
   * @see sfTask
   */
  protected function configure()
  {
    // add your own arguments here
    $this->addArguments(array(
      // We need a model class to have the connexion parameters
      new sfCommandArgument('model', sfCommandArgument::REQUIRED, 'The model name'),
    ));

    $this->addOptions(array(
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', null),
      new sfCommandOption('offset', null, sfCommandOption::PARAMETER_REQUIRED, 'The offset', 0),
      new sfCommandOption('limit', null, sfCommandOption::PARAMETER_REQUIRED, 'The limit', 20)
    ));

    $this->namespace        = 'solr';
    $this->name             = 'rebuild-index';
    $this->briefDescription = 'rebuild the solr index';
    $this->detailedDescription = <<<EOF
The [rebuild-index|INFO] rebuilds the entire solr index.
Call it with:

  [php symfony solr:rebuild-index ModelClass|INFO]
EOF;
  }

  /**
   * @see sfTask
   */
  protected function execute($arguments = array(), $options = array())
  {
    $databaseManager = new sfDatabaseManager($this->configuration);

    $confirm = $this->askConfirmation(
      "\n This will rebuild everything in the Solr index. Are you sure you want to proceed? (y/N)\n",
      'QUESTION',
      false);
    if(!$confirm)
    {
      $this->logSection('solr', 'task aborted');
      return 1;
    }

    $model = $arguments['model'];
    $objects = Doctrine_Core::getTable($model)->createQuery('m')
        ->limit($options['limit'])
        ->offset($options['offset'])
        ->execute()
    ;

    foreach($objects as $object) {
        $object->deleteFromIndex();
        $object->addToIndex();
        $object->free();
    }

    $this->logSection('solr', 'Index has been rebuilt');
  }
}


text:
module RSpec
  module Mocks
    module AnyInstance
      # Given a class `TheClass`, `TheClass.any_instance` returns a `Recorder`,
      # which records stubs and message expectations for later playback on
      # instances of `TheClass`.
      #
      # Further constraints are stored in instances of [Chain](Chain).
      #
      # @see AnyInstance
      # @see Chain
      class Recorder
        # @private
        attr_reader :message_chains

        def initialize(klass)
          @message_chains = MessageChains.new
          @observed_methods = []
          @played_methods = {}
          @klass = klass
          @expectation_set = false
        end

        # Initializes the recording a stub to be played back against any
        # instance of this object that invokes the submitted method.
        #
        # @see Methods#stub
        def stub(method_name_or_method_map, &block)
          if method_name_or_method_map.is_a?(Hash)
            method_name_or_method_map.each do |method_name, return_value|
              stub(method_name).and_return(return_value)
            end
          else
            observe!(method_name_or_method_map)
            message_chains.add(method_name_or_method_map, StubChain.new(method_name_or_method_map, &block))
          end
        end

        # Initializes the recording a stub chain to be played back against any
        # instance of this object that invokes the method matching the first
        # argument.
        #
        # @see Methods#stub_chain
        def stub_chain(*method_names_and_optional_return_values, &block)
          normalize_chain(*method_names_and_optional_return_values) do |method_name, args|
            observe!(method_name)
            message_chains.add(method_name, StubChainChain.new(*args, &block))
          end
        end

        # Initializes the recording a message expectation to be played back
        # against any instance of this object that invokes the submitted
        # method.
        #
        # @see Methods#should_receive
        def should_receive(method_name, &block)
          @expectation_set = true
          observe!(method_name)
          message_chains.add(method_name, PositiveExpectationChain.new(method_name, &block))
        end

        def should_not_receive(method_name, &block)
          observe!(method_name)
          message_chains.add(method_name, NegativeExpectationChain.new(method_name, &block))
        end

        # Removes any previously recorded stubs, stub_chains or message
        # expectations that use `method_name`.
        #
        # @see Methods#unstub
        def unstub(method_name)
          unless @observed_methods.include?(method_name.to_sym)
            raise RSpec::Mocks::MockExpectationError, "The method `#{method_name}` was not stubbed or was already unstubbed"
          end
          message_chains.remove_stub_chains_for!(method_name)
          stop_observing!(method_name) unless message_chains.has_expectation?(method_name)
        end

        # @api private
        #
        # Used internally to verify that message expectations have been
        # fulfilled.
        def verify
          if @expectation_set && !message_chains.all_expectations_fulfilled?
            raise RSpec::Mocks::MockExpectationError, "Exactly one instance should have received the following message(s) but didn't: #{message_chains.unfulfilled_expectations.sort.join(', ')}"
          end
        end

        # @private
        def stub!(*)
          raise "stub! is not supported on any_instance. Use stub instead."
        end

        # @private
        def stop_all_observation!
          @observed_methods.each {|method_name| restore_method!(method_name)}
        end

        # @private
        def playback!(instance, method_name)
          RSpec::Mocks::space.add(instance)
          message_chains.playback!(instance, method_name)
          @played_methods[method_name] = instance
          received_expected_message!(method_name) if message_chains.has_expectation?(method_name)
        end

        # @private
        def instance_that_received(method_name)
          @played_methods[method_name]
        end

        private

        def normalize_chain(*args)
          args.shift.to_s.split('.').map {|s| s.to_sym}.reverse.each {|a| args.unshift a}
          yield args.first, args
        end

        def received_expected_message!(method_name)
          message_chains.received_expected_message!(method_name)
          restore_method!(method_name)
          mark_invoked!(method_name)
        end

        def restore_method!(method_name)
          if public_protected_or_private_method_defined?(build_alias_method_name(method_name))
            restore_original_method!(method_name)
          else
            remove_dummy_method!(method_name)
          end
        end

        def build_alias_method_name(method_name)
          "__#{method_name}_without_any_instance__"
        end

        def restore_original_method!(method_name)
          alias_method_name = build_alias_method_name(method_name)
          @klass.class_eval do
            remove_method method_name
            alias_method  method_name, alias_method_name
            remove_method alias_method_name
          end
        end

        def remove_dummy_method!(method_name)
          @klass.class_eval do
            remove_method method_name
          end
        end

        def backup_method!(method_name)
          alias_method_name = build_alias_method_name(method_name)
          @klass.class_eval do
            alias_method alias_method_name, method_name
          end if public_protected_or_private_method_defined?(method_name)
        end

        def public_protected_or_private_method_defined?(method_name)
          @klass.method_defined?(method_name) || @klass.private_method_defined?(method_name)
        end

        def stop_observing!(method_name)
          restore_method!(method_name)
          @observed_methods.delete(method_name)
        end

        def already_observing?(method_name)
          @observed_methods.include?(method_name)
        end

        def observe!(method_name)
          stop_observing!(method_name) if already_observing?(method_name)
          @observed_methods << method_name
          backup_method!(method_name)
          @klass.class_eval(<<-EOM, __FILE__, __LINE__)
            def #{method_name}(*args, &blk)
              self.class.__recorder.playback!(self, :#{method_name})
              self.__send__(:#{method_name}, *args, &blk)
            end
          EOM
        end

        def mark_invoked!(method_name)
          backup_method!(method_name)
          @klass.class_eval(<<-EOM, __FILE__, __LINE__)
            def #{method_name}(*args, &blk)
              method_name = :#{method_name}
              invoked_instance = self.class.__recorder.instance_that_received(method_name)
              raise RSpec::Mocks::MockExpectationError, "The message '#{method_name}' was received by \#{self.inspect} but has already been received by \#{invoked_instance}"
            end
          EOM
        end
      end
    end
  end
end


text:
#ifndef SkiaVulkan_DEFINED
#define SkiaVulkan_DEFINED

#include "include/core/SkTypes.h"

#if SKIA_IMPLEMENTATION || !defined(SK_VULKAN)
#include "include/third_party/vulkan/vulkan/vulkan_core.h"
#else
// For google3 builds we don't set SKIA_IMPLEMENTATION so we need to make sure that the vulkan
// headers stay up to date for our needs
#include <vulkan/vulkan_core.h>
#endif

#ifdef SK_BUILD_FOR_ANDROID
// This is needed to get android extensions for external memory
#if SKIA_IMPLEMENTATION || !defined(SK_VULKAN)
#include "include/third_party/vulkan/vulkan/vulkan_android.h"
#else
// For google3 builds we don't set SKIA_IMPLEMENTATION so we need to make sure that the vulkan
// headers stay up to date for our needs
#include <vulkan/vulkan_android.h>
#endif
#endif

#endif


text:
using namespace std;

template <typename T, typename = void>
struct has_begin
  : std::false_type
{ };

template <typename T>
struct has_begin<T, decltype((void)begin(std::declval<T>()))>
  : std::true_type
{ };

int main()
{
    cout << boolalpha;
    cout << has_begin<vector<int>>::value << endl;
    cout << has_begin<pair<int, int>>::value << endl;
}


text:
package gui.swt;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;

public class CollageGenerationButtonPanel extends Composite {

	private Button generateCollageButton;
	private Button saveCollageButton;

	public CollageGenerationButtonPanel(Composite parent) {
		super(parent, SWT.NONE);
		this.setLayout(new GridLayout(1, true));

		this.generateCollageButton = new Button(this, SWT.PUSH);
		this.generateCollageButton.setText("Generate Collage");
		this.generateCollageButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

		this.saveCollageButton = new Button(this, SWT.PUSH);
		this.saveCollageButton.setText("Save Collage");
		this.saveCollageButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
	}

	/**
	 * @return the generateCollageButton
	 */
	public Button getGenerateCollageButton() {
		return generateCollageButton;
	}

	/**
	 * @return the saveCollageButton
	 */
	public Button getSaveCollageButton() {
		return saveCollageButton;
	}

}


text:
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

    private

    def find_verified_user
      if verified_user = find_user
        verified_user
      else
        reject_unauthorized_connection
      end
    end

    def token_from_request_headers
      unless request.headers['Authorization'].nil?
        request.headers['Authorization'].split.last
      end
    end

    def token
      request.params[:jwt] || token_from_request_headers
    end

    def find_user
      Knock::AuthToken.new(token: token).entity_for(User)
    rescue Knock.not_found_exception_class, JWT::DecodeError
      nil
    end
  end
end


text:
#include "tensorflow/core/grappler/optimizers/graph_rewriter.h"
#include <unordered_map>
#include <unordered_set>
#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_def.pb.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/op_types.h"
#include "tensorflow/core/grappler/utils.h"

namespace tensorflow {
namespace grappler {

GraphRewriter::GraphRewriter(const GrapplerItem& item) {
  OpRegistryInterface* op_registry = OpRegistry::Global();
  for (auto& node : item.graph.node()) {
    NodeInfo* info = new NodeInfo();
    info->def = &node;

    const OpRegistrationData* op_reg_data = nullptr;
    Status s = op_registry->LookUp(node.op(), &op_reg_data);
    // TODO(bsteiner): make this not a best-effort lookup and evaluation?
    if (s.ok()) {
      DataTypeVector inputs;
      s = InOutTypesForNode(node, op_reg_data->op_def, &inputs, &info->outputs);
      if (!s.ok()) {
        info->outputs.clear();
      }
    }

    nodes_[node.name()].reset(info);
  }

  std::unordered_set<string> function_names;
  for (const auto& function : item.graph.library().function()) {
    function_names.insert(function.signature().name());
  }

  for (auto& node : item.graph.node()) {
    RecordConnectivity(node, function_names);
  }
}

void GraphRewriter::ForwardInputs(
    const NodeDef& original_node,
    const std::unordered_set<const NodeDef*>& nodes_to_delete,
    NodeDef* new_node) {
  ForwardInputsInternal(original_node, nodes_to_delete, false, new_node);
  if (!new_node->name().empty()) {
    optimized_nodes_[new_node->name()] = new_node;
  }
  // Reorder inputs such that control inputs come after regular inputs.
  int pos = 0;
  for (int i = 0; i < new_node->input_size(); ++i) {
    if (!IsControlInput(new_node->input(i))) {
      new_node->mutable_input()->SwapElements(pos, i);
      ++pos;
    }
  }
  DedupControlInputs(new_node);
}

bool GraphRewriter::DrivesControlDependency(const NodeDef& node) const {
  return control_dependency_drivers_.find(&node) !=
         control_dependency_drivers_.end();
}

bool GraphRewriter::FeedsMerge(const NodeDef& node) const {
  return merge_feeders_.find(&node) != merge_feeders_.end();
}

bool GraphRewriter::IsDrivenByControlDependency(const NodeDef& node) const {
  for (const auto& input : node.input()) {
    CHECK(!input.empty());
    if (input[0] == '^') {
      return true;
    }
  }
  return false;
}

bool GraphRewriter::IsConnectedToFunction(const NodeDef& node) const {
  return function_neighbors_.find(&node) != function_neighbors_.end();
}

bool GraphRewriter::IsDrivenByAnotherDevice(const NodeDef& node) const {
  return cross_device_receivers_.find(&node) != cross_device_receivers_.end();
}

bool GraphRewriter::ReceivesRefValue(const NodeDef& node) const {
  return ref_receivers_.find(&node) != ref_receivers_.end();
}

bool GraphRewriter::IsDrivenBySwitch(const NodeDef& node) const {
  return switch_receivers_.find(&node) != switch_receivers_.end();
}

bool GraphRewriter::RemovalIncreasesEdgeCount(const NodeDef& node) const {
  const int in_degree = node.input_size();
  auto itr = nodes_.find(node.name());
  if (itr == nodes_.end()) {
    return true;
  }
  const int out_degree = itr->second->out_degree;
  return in_degree * out_degree > in_degree + out_degree;
}

void GraphRewriter::RecordConnectivity(
    const NodeDef& node, const std::unordered_set<string>& function_names) {
  const bool is_function =
      function_names.find(node.op()) != function_names.end();

  bool ref_receiver = false;
  bool switch_receiver = false;
  for (const auto& input : node.input()) {
    int position = 0;
    string input_node_name = ParseNodeName(input, &position);
    auto itr = nodes_.find(input_node_name);
    if (itr == nodes_.end()) {
      continue;
    }

    NodeInfo* fanin_info = itr->second.get();
    const NodeDef* fanin = fanin_info->def;
    if (IsMerge(node)) {
      merge_feeders_.insert(fanin);
    }
    // Update out_degree of fanin.
    ++fanin_info->out_degree;
    if (position < 0) {
      // This is a control edge
      control_dependency_drivers_.insert(fanin);
    } else {
      // This is a regular edge
      if (function_names.find(fanin->op()) != function_names.end()) {
        function_neighbors_.insert(&node);
      }
      if (is_function) {
        function_neighbors_.insert(fanin);
      }
      if (IsSwitch(*fanin)) {
        switch_receiver = true;
      }
      if (position < fanin_info->outputs.size() &&
          IsRefType(fanin_info->outputs[position])) {
        ref_receiver = true;
      }
    }
    if (fanin->device() != node.device()) {
      cross_device_receivers_.insert(&node);
    }
  }

  if (ref_receiver) {
    ref_receivers_.insert(&node);
  }
  if (switch_receiver) {
    switch_receivers_.insert(&node);
  }
}

void GraphRewriter::ForwardInputsInternal(
    const NodeDef& node,
    const std::unordered_set<const NodeDef*>& nodes_to_delete,
    bool add_as_control, NodeDef* new_node) {
  // To speed things up, use the optimized version of the node if
  // available.
  auto itr = optimized_nodes_.find(node.name());
  if (itr != optimized_nodes_.end()) {
    for (const string& input : itr->second->input()) {
      *new_node->add_input() =
          add_as_control ? AsControlDependency(NodeName(input)) : input;
    }
    return;
  }
  for (const auto& input : node.input()) {
    const string input_node_name = NodeName(input);
    auto itr = nodes_.find(input_node_name);
    if (itr == nodes_.end()) {
      // Invalid input, preserve it as is.
      *new_node->add_input() =
          add_as_control ? AsControlDependency(NodeName(input)) : input;
      continue;
    }
    const NodeDef* input_node = itr->second->def;
    if (nodes_to_delete.find(input_node) != nodes_to_delete.end()) {
      ForwardInputsInternal(*input_node, nodes_to_delete,
                            add_as_control || IsControlInput(input), new_node);
    } else {
      *new_node->add_input() =
          add_as_control ? AsControlDependency(NodeName(input)) : input;
    }
  }
}

}  // end namespace grappler
}  // end namespace tensorflow


text:
(function($, eucalyptus) {
  eucalyptus.help = function(args){
    language = args['language']; // not used yet
    try{
      try{
        help_keypair.load({language:language});
      }catch(e){
        help_keypair.load({language:'en_US'});
      }
      try{
        help_volume.load({language:language});
      }catch(e){
        help_volume.load({language:'en_US'});
      }
      try{
        help_sgroup.load({language:language});
      }catch(e){
        help_sgroup.load({language:'en_US'});
      }
      try{
        help_instance.load({language:language});
      }catch(e){
        help_instance.load({language:'en_US'});
      }
      try{
        help_snapshot.load({language:language});
      }catch(e){
        help_snapshot.load({language:'en_US'});
      }
      try{
        help_image.load({language:language});
      }catch(e){
        help_image.load({language:'en_US'});
      }
      try{
        help_eip.load({language:language});
      }catch(e){
        help_eip.load({language:'en_US'});
      }
      try{
        help_launcher.load({language:language});
      }catch(e){
        help_launcher.load({language:'en_US'});
      }
      try{
        help_dashboard.load({language:language});
      }catch(e){
        help_dashboard.load({language:'en_US'});
      }
      try{
        help_about.load({language:language});
      }catch(e){
        help_about.load({language:'en_US'});
      }
    }catch(e){
      ;
    }
  }
})(jQuery,
   window.eucalyptus ? window.eucalyptus : window.eucalyptus = {});

function getLandingHelpHeader(args){
  var $helpHeader = $('<div>').addClass('euca-table-header').append(
                     $('<div>').addClass('help-link').append(
                       $('<a>').attr('href','#').html(' ')));
  return $helpHeader;
}

function loadHtml(url, handler){
    $.ajax(url, {
        type:"GET",
        data:"",
        dataType:"html",
        async:false, // async option deprecated as of jQuery 1.8
        success: function (data){
          handler(data);
        },
        error : function (){
          //handler($.i18n.prop('error_loading_help_file'));
          throw "static html files not found";
        }
    });
}

var help_dashboard = {
   load : function(arg){
    help_dashboard.landing_content_url = 'help/'+arg.language+'/console_dashboard.html',
    loadHtml(help_dashboard.landing_content_url, function(data){help_dashboard.landing_content=data})
   },
   landing_content: '',
   landing_content_url : '',
}
  //[keypair]
var help_keypair = {
  load : function(arg){
    help_keypair.landing_content_url = 'help/'+arg.language+'/console_manage_keypairs.html';
    help_keypair.dialog_add_content_url = 'help/'+arg.language+'/console_create_keypair.html';
    help_keypair.dialog_delete_content_url = 'help/'+arg.language+'/console_delete_keypair.html';
    help_keypair.dialog_import_content_url = 'help/'+arg.language+'/console_import_keypair.html';
    loadHtml(help_keypair.landing_content_url , function(data){help_keypair.landing_content=data})
    loadHtml(help_keypair.dialog_add_content_url, function(data){help_keypair.dialog_add_content=data})
    loadHtml(help_keypair.dialog_delete_content_url, function(data){help_keypair.dialog_delete_content=data})
    loadHtml(help_keypair.dialog_import_content_url, function(data){help_keypair.dialog_import_content=data})
  },
  landing_content: '',
  landing_content_url: '',
  dialog_add_content: '',
  dialog_add_content_url: '',
  dialog_delete_content: '',
  dialog_delete_content_url: '',
  dialog_import_content: '',
  dialog_import_content_url: '',

};

var help_image = {
  load : function(arg){
    help_image.landing_content_url = 'help/'+arg.language+'/console_manage_images.html';
    loadHtml(help_image.landing_content_url, function(data){help_image.landing_content=data})
  },
  landing_content:'',
  landing_content_url: '',
};

var help_snapshot = {
  load : function(arg){
    help_snapshot.landing_content_url = 'help/'+arg.language+'/console_manage_snapshots.html';
    help_snapshot.dialog_create_content_url = 'help/'+arg.language+'/console_create_snapshot.html';
    help_snapshot.dialog_delete_content_url  = 'help/'+arg.language+'/console_delete_snapshot.html';
    loadHtml(help_snapshot.landing_content_url, function(data){help_snapshot.landing_content=data})
    loadHtml(help_snapshot.dialog_create_content_url, function(data){help_snapshot.dialog_create_content=data})
    loadHtml(help_snapshot.dialog_delete_content_url, function(data){help_snapshot.dialog_delete_content=data})
  },
  landing_content: '',
  landing_content_url: '',
  dialog_delete_content: '',
  dialog_delete_content_url: '',
  dialog_create_content: '',
  dialog_create_content_url: '',
  dialog_register_content: '',
  dialog_register_content_url: '',
};

var help_eip = {
  load : function(arg){
    help_eip.landing_content_url = 'help/'+arg.language+'/console_manage_eips.html';
    help_eip.dialog_allocate_content_url = 'help/'+arg.language+'/console_allocate_eip.html';
    help_eip.dialog_release_content_url = 'help/'+arg.language+'/console_release_eip.html';
    help_eip.dialog_associate_content_url = 'help/'+arg.language+'/console_associate_eip.html';
    help_eip.dialog_disassociate_content_url = 'help/'+arg.language+'/console_disassociate_eip.html';
    loadHtml(help_eip.landing_content_url, function(data){help_eip.landing_content=data})
    loadHtml(help_eip.dialog_allocate_content_url, function(data){help_eip.dialog_allocate_content=data})
    loadHtml(help_eip.dialog_release_content_url, function(data){help_eip.dialog_release_content=data})
    loadHtml(help_eip.dialog_associate_content_url, function(data){help_eip.dialog_associate_content=data})
    loadHtml(help_eip.dialog_disassociate_content_url, function(data){help_eip.dialog_disassociate_content=data})
  },
  landing_content: '',
  landing_content_url: '',
  dialog_release_content: '',
  dialog_release_content_url: '',
  dialog_allocate_content: '',
  dialog_allocate_content_url: '',
  dialog_associate_content: '',
  dialog_associate_content_url: '',
  dialog_disassociate_content: '' ,
  dialog_disassociate_content_url: ''
};

var help_volume = {
  load : function(arg){
    help_volume.landing_content_url = 'help/'+arg.language+'/console_manage_volumes.html';
    help_volume.dialog_add_content_url = 'help/'+arg.language+'/console_create_volume.html';
    help_volume.dialog_attach_content_url = 'help/'+arg.language+'/console_attach_volume.html';
    help_volume.dialog_detach_content_url = 'help/'+arg.language+'/console_detach_volume.html';
    help_volume.dialog_delete_content_url = 'help/'+arg.language+'/console_delete_volumes.html';

    loadHtml(help_volume.landing_content_url, function(data){help_volume.landing_content=data})
    loadHtml(help_volume.dialog_add_content_url, function(data){help_volume.dialog_add_content=data})
    loadHtml(help_volume.dialog_attach_content_url, function(data){help_volume.dialog_attach_content=data})
    loadHtml(help_volume.dialog_detach_content_url, function(data){help_volume.dialog_detach_content=data})
    loadHtml(help_volume.dialog_delete_content_url, function(data){help_volume.dialog_delete_content=data})
  },
  landing_content: '',
  landing_content_url: '',
  dialog_add_content: '',
  dialog_add_content_url: '',
  dialog_attach_content: '',
  dialog_attach_content_url: '',
  dialog_detach_content: '',
  dialog_detach_content_url: '',
  dialog_delete_content:  '',
  dialog_delete_content_url:  ''
};

var help_sgroup = {
  load : function(arg){
    help_sgroup.landing_content_url = 'help/'+arg.language+'/console_manage_security_groups.html';
    help_sgroup.dialog_add_content_url = 'help/'+arg.language+'/console_create_security_group.html';
    help_sgroup.dialog_edit_content_url = 'help/'+arg.language+'/console_edit_security_group.html';
    help_sgroup.dialog_delete_content_url = 'help/'+arg.language+'/console_delete_security_group.html';
    loadHtml(help_sgroup.landing_content_url, function(data){help_sgroup.landing_content=data})
    loadHtml(help_sgroup.dialog_add_content_url, function(data){help_sgroup.dialog_add_content=data})
    loadHtml(help_sgroup.dialog_edit_content_url, function(data){help_sgroup.dialog_edit_content=data})
    loadHtml(help_sgroup.dialog_delete_content_url, function(data){help_sgroup.dialog_delete_content=data})
  },
  landing_content: '',
  landing_content_url: '',
  dialog_add_content: '',
  dialog_add_content_url: '',
  dialog_edit_content: '',
  dialog_edit_content_url: '',
  dialog_delete_content:'',
  dialog_delete_content_url:'',
}

var help_instance = {
  load : function(arg){
    help_instance.landing_content_url = 'help/'+arg.language+'/console_manage_instances.html';
    help_instance.dialog_reboot_content_url = 'help/'+arg.language+'/console_reboot_instances.html';
    help_instance.dialog_stop_content_url = 'help/'+arg.language+'/console_stop_instances.html';
    help_instance.dialog_terminate_content_url = 'help/'+arg.language+'/console_terminate_instances.html';
    help_instance.dialog_launchmore_content_url = 'help/'+arg.language+'/console_launch_more_instances.html';

    loadHtml(help_instance.landing_content_url, function(data){help_instance.landing_content=data})
    loadHtml(help_instance.dialog_reboot_content_url, function(data){help_instance.dialog_reboot_content=data})
    loadHtml(help_instance.dialog_stop_content_url, function(data){help_instance.dialog_stop_content=data})
    loadHtml(help_instance.dialog_terminate_content_url, function(data){help_instance.dialog_terminate_content=data})
    loadHtml(help_instance.dialog_launchmore_content_url, function(data){help_instance.dialog_launchmore_content=data})
  },
  landing_content: '',
  landing_content_url: '',
  dialog_reboot_content: '',
  dialog_reboot_content_url: '',
  dialog_stop_content: '',
  dialog_stop_content_url: '',
  dialog_terminate_content: '',
  dialog_terminate_content_url: '',
  dialog_launchmore_content: '',
  dialog_launchmore_content_url: '',
}

var help_about = {
  load : function(arg){
    help_about.dialog_content_url = 'help/'+arg.language+'/console_about.html';
    loadHtml(help_about.dialog_content_url, function(data){help_about.dialog_content=data})
  },
  dialog_content: '',
  dialog_content_url: '',
}

var help_launcher = {
  load : function(arg) {
    help_launcher.landing_content_url = 'help/'+arg.language+'/console_create_instances.html';
    loadHtml(help_launcher.landing_content_url, function(data){help_launcher.landing_content=data})
  },
  landing_content: '',
  landing_content_url: '',
}