text:
package com.amazonaws.services.clouddirectory.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.clouddirectory.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * BatchListOutgoingTypedLinksResponse JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class BatchListOutgoingTypedLinksResponseJsonUnmarshaller implements Unmarshaller<BatchListOutgoingTypedLinksResponse, JsonUnmarshallerContext> {

    public BatchListOutgoingTypedLinksResponse unmarshall(JsonUnmarshallerContext context) throws Exception {
        BatchListOutgoingTypedLinksResponse batchListOutgoingTypedLinksResponse = new BatchListOutgoingTypedLinksResponse();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("TypedLinkSpecifiers", targetDepth)) {
                    context.nextToken();
                    batchListOutgoingTypedLinksResponse.setTypedLinkSpecifiers(new ListUnmarshaller<TypedLinkSpecifier>(TypedLinkSpecifierJsonUnmarshaller
                            .getInstance())

                    .unmarshall(context));
                }
                if (context.testExpression("NextToken", targetDepth)) {
                    context.nextToken();
                    batchListOutgoingTypedLinksResponse.setNextToken(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return batchListOutgoingTypedLinksResponse;
    }

    private static BatchListOutgoingTypedLinksResponseJsonUnmarshaller instance;

    public static BatchListOutgoingTypedLinksResponseJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new BatchListOutgoingTypedLinksResponseJsonUnmarshaller();
        return instance;
    }
}


text:
package com.popomusic.data;

import com.popomusic.bean.MusicBean;
import com.popomusic.presenter.BasePresenter;
import com.popomusic.videoModel.ItemList;
import com.popomusic.videoModel.SectionList;
import com.popomusic.view.BaseView;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created by popo on 2017/5/20 0020.
 */
public interface VideoData {
    interface View extends BaseView {
        void setData(List<ItemList> list);
        void hideProgress();
        void showProgress();

    }

    interface Presenter  {
        void requestData(int id);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPEhtml>

		<meta charset="UTF-8">
		<link rel="stylesheet" href="stylesheet.css">

Hello World

Nav container

LEFT ARROW

RIGHT ARROW

One

Two

Three

Four

Five


text:
package org.javers.core.json.typeadapter.commit;

import com.google.gson.*;
import org.javers.common.collections.Lists;
import org.javers.common.validation.Validate;
import org.javers.core.json.JsonTypeAdapter;
import org.javers.core.metamodel.object.GlobalId;
import org.javers.core.metamodel.object.InstanceId;
import org.javers.core.metamodel.object.UnboundedValueObjectId;
import org.javers.core.metamodel.object.ValueObjectId;
import org.javers.core.metamodel.type.EntityType;
import org.javers.core.metamodel.type.TypeMapper;

import java.util.List;
import java.util.Optional;

/**
 * @author bartosz walacik
 */
class GlobalIdTypeAdapter implements JsonTypeAdapter<GlobalId> {
    static final String ENTITY_FIELD = "entity";
    static final String CDO_ID_FIELD = "cdoId";
    static final String OWNER_ID_FIELD = "ownerId";
    static final String VALUE_OBJECT_FIELD = "valueObject";
    static final String FRAGMENT_FIELD = "fragment";

    private final TypeMapper typeMapper;

    public GlobalIdTypeAdapter(TypeMapper typeMapper) {
        this.typeMapper = typeMapper;
    }

    @Override
    public GlobalId fromJson(JsonElement json, JsonDeserializationContext context) {
        if (!(json instanceof JsonObject)) {
            return null; //when user's class is refactored, a property can have changed type
        }
        JsonObject jsonObject = (JsonObject) json;

        if (jsonObject.get(ENTITY_FIELD) != null) {
            return parseInstanceId(jsonObject, context);
        } else if (jsonObject.get(OWNER_ID_FIELD) != null) {
            return parseValueObjectId(jsonObject, context);
        } else {
            return parseUnboundedValueObject(jsonObject);
        }
    }

    private UnboundedValueObjectId parseUnboundedValueObject(JsonObject jsonObject){
        String typeName = jsonObject.get(VALUE_OBJECT_FIELD).getAsString();
        return new UnboundedValueObjectId(typeName);
    }

    private ValueObjectId parseValueObjectId(JsonObject jsonObject, JsonDeserializationContext context) {
        Validate.argumentCheck(jsonObject.get(VALUE_OBJECT_FIELD) != null, "empty "+ VALUE_OBJECT_FIELD + " in json:" +jsonObject);
        String typeName = jsonObject.get(VALUE_OBJECT_FIELD).getAsString();
        String fragment = jsonObject.get(FRAGMENT_FIELD).getAsString();
        GlobalId ownerId = context.deserialize(jsonObject.get(OWNER_ID_FIELD), GlobalId.class);

        return new ValueObjectId(typeName, ownerId, fragment);
    }

    private InstanceId parseInstanceId(JsonObject jsonObject, JsonDeserializationContext context) {

        JsonElement cdoIdElement = jsonObject.get(CDO_ID_FIELD);

        String typeName = jsonObject.get(ENTITY_FIELD).getAsString();
        Optional<EntityType> entityMaybe = typeMapper.getJaversManagedTypeMaybe(typeName, EntityType.class);

        return entityMaybe.map(entity -> deserializeInstanceId(cdoIdElement, entity, context)
        ).orElseGet(() ->
            new InstanceId(typeName, context.deserialize(cdoIdElement, Object.class), cdoIdElement.getAsString())
        );
    }

    private InstanceId deserializeInstanceId(JsonElement cdoIdElement, EntityType entity, JsonDeserializationContext context) {
        try {
            Object localId = context.deserialize(cdoIdElement, entity.getLocalIdDehydratedJsonType());
            return entity.createIdFromDeserializedJsonLocalId(localId);
        } catch (JsonSyntaxException e) {
            //legacy format support
            Object localId = context.deserialize(cdoIdElement, entity.getIdProperty().getGenericType());
            return entity.createIdFromInstanceId(localId);
        }
    }

    @Override
    public JsonElement toJson(GlobalId globalId, JsonSerializationContext context) {
        if (globalId == null) {
            return JsonNull.INSTANCE;
        }

        JsonObject jsonObject = new JsonObject();

        //managedClass
        if (globalId instanceof InstanceId) {
            jsonObject.addProperty(ENTITY_FIELD, globalId.getTypeName());
            jsonObject.add(CDO_ID_FIELD, context.serialize(((InstanceId)globalId).getCdoId()));
        } else {
            jsonObject.addProperty(VALUE_OBJECT_FIELD, globalId.getTypeName());
        }

        //owningId & fragment
        if (globalId instanceof ValueObjectId) {
            ValueObjectId valueObjectId = (ValueObjectId) globalId;

            jsonObject.add(OWNER_ID_FIELD, context.serialize(valueObjectId.getOwnerId()));
            jsonObject.addProperty(FRAGMENT_FIELD, valueObjectId.getFragment());
        }

        return jsonObject;
    }

    @Override
    public List<Class> getValueTypes() {
        return (List) Lists.immutableListOf(GlobalId.class,
                InstanceId.class,
                UnboundedValueObjectId.class,
                ValueObjectId.class);
    }

    public static boolean looksLikeGlobalId(JsonElement propertyElement) {
        if (propertyElement instanceof  JsonObject) {
            JsonObject json = (JsonObject) propertyElement;
            return hasStringField(json, ENTITY_FIELD) || hasStringField(json, VALUE_OBJECT_FIELD);
        }
        return false;
    }

    private static boolean hasStringField(JsonObject json, String childName) {
        return json.has(childName) && json.get(childName) instanceof JsonPrimitive && ((JsonPrimitive)json.get(childName)).isString();

    }
}


text:
repo: wq.app
date: 2015-02-23
---

# wq.app 0.7.2

wq.app 0.7.2 brings a number of enhancements to [SCSS theme](https://github.com/wq/wq.app/tree/v1.3.0/packages/jquery-mobile) support, including:
- A new [wq/swatches.scss](https://github.com/wq/wq.app/blob/v1.3.0/packages/jquery-mobile/scss/swatches.scss) with a number of useful pre-defined theme swatches (including an approximation of jQuery Mobile 1.3's default theme)
- Compass and PySCSS are now automatically installed with wq.app so you don't need to download them separately (#34).

Check out the [Swatch Preview Tool](https://github.com/wq/wq.app/tree/v1.3.0/packages/jquery-mobile) to play around with the new themes.


text:
Migrator.config do |config|
	config.ignore_fields = "dc.description.abstract"
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>selenium.webdriver.opera.service — Selenium 2.0 documentation</title>

    <link rel="stylesheet" href="../../../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />

    <link rel="top" title="Selenium 2.0 documentation" href="../../../../index.html" />
    <link rel="up" title="Module code" href="../../../index.html" />

Navigation

          index

          modules |

Selenium 2.0 documentation »

Module code »

Source code for selenium.webdriver.opera.service

#!/usr/bin/python
#
# Copyright 2011 Webdriver_name committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import subprocess
from subprocess import PIPE
import time
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common import utils

[docs]class Service(object):
    """
    Object that manages the starting and stopping of the OperaDriver
    """

    def __init__(self, executable_path, port=0):
        """
        Creates a new instance of the Service

        :Args:
         - executable_path : Path to the OperaDriver
         - port : Port the service is running on """

        self.port = port
        self.path = executable_path
        if self.port == 0:
            self.port = utils.free_port()

[docs]    def start(self):
        """
        Starts the OperaDriver Service.

        :Exceptions:
         - WebDriverException : Raised either when it can't start the service
           or when it can't connect to the service
        """
        try:
            self.process = subprocess.Popen(["java", "-jar", self.path, "-port", "%s" % self.port])
        except:
            raise WebDriverException(
                "OperaDriver executable needs to be available in the path. \
                ")
        time.sleep(10)
        count = 0
        while not utils.is_connectable(self.port):
            count += 1
            time.sleep(1)
            if count == 30:
                 raise WebDriverException("Can not connect to the OperaDriver")

    @property

[docs]    def service_url(self):
        """
        Gets the url of the OperaDriver Service
        """
        return "http://localhost:%d/wd/hub" % self.port

[docs]    def stop(self):
        """
        Tells the OperaDriver to stop and cleans up the process
        """
        #If its dead dont worry
        if self.process is None:
            return

        self.process.kill()
        self.process.wait()

Quick search

    <form class="search" action="../../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

Selenium 2.0 documentation »

Module code »

        © Copyright 2011, plightbo, simon.m.stewart, hbchai, jrhuggins, et al..


text:
/**
 * Created by MihaiCotizo on 5/10/2014.
 */

var Article = require('../Article');
var marked = require('marked');
marked.setOptions({
    sanitize: true
});

function home(db) {
    return function (req, res) {
        var LIMIT = 10;
        var page = req.query.page ? req.query.page : 1;
        var toSkip = (page - 1) * LIMIT;
        Article.count(function (err, count) {
            if (err) { console.error(err); res.send(400); return; }
            Article.find().sort('-date').skip(toSkip).limit(LIMIT).exec(function (err, articles) {
                if (err) {
                    console.error(err);
                    res.send(404);
                    return;
                }

                articles = articles.map(function (x) {
                    x.content = marked(x.content);
                    return x;
                });
                var isFirst = page == 1;
                var prev = !isFirst ? page - 1 : "#";
                var isLast = toSkip + LIMIT >= count;
                var next = !isLast ? page + 1 : "#";
                res.render('index', {
                    articles: articles,
                    first: isFirst,
                    prev: prev,
                    last: isLast,
                    next: next});
            });
        });
    }
}

function article(db) {
    return function (req, res) {
        var id = req.params.id;
        Article.find({_id: id}, function (err, article) {
            if (err) { console.error(err); res.send(400); return; }
            if (article.length !== 1) { res.send(404); return; }
            res.render('article', {article: article[0]});
        })
    }
}

module.exports = {
    home: home,
    article: article
};


text:
<?php

namespace Phactory\Sql;

class Logger {

    const LEVEL_DEBUG = 1;
    const LEVEL_WARN = 2;
    const LEVEL_ERROR = 4;
    const LEVEL_FATAL = 8;
    const LEVEL_ALL = 15;

    protected static $_level = self::LEVEL_ALL;

    protected static $_level_strs = array(self::LEVEL_DEBUG => 'DEBUG',
                                          self::LEVEL_WARN  => 'WARN',
                                          self::LEVEL_ERROR => 'ERROR',
                                          self::LEVEL_FATAL => 'FATAL');

    public static function setLogLevel($level) {
        self::$_level = $level;
    }

    public static function debug($msg, $backtrace = false) {
       self::outputMessage(self::LEVEL_DEBUG, $msg, $backtrace);
    }

    public static function warn($msg, $backtrace = false) {
       self::outputMessage(self::LEVEL_WARN, $msg, $backtrace);
    }

    public static function error($msg, $backtrace = false) {
       self::outputMessage(self::LEVEL_ERROR, $msg, $backtrace);
       throw new \Exception($msg);
    }

    public static function fatal($msg, $backtrace = true) {
       self::outputMessage(self::LEVEL_FATAL, $msg, $backtrace);
       die;
    }

    protected static function outputMessage($log_level, $msg, $backtrace) {
        if(self::$_level & $log_level) {
            print(strftime("%Y-%m-%d %H:%M:%S Phactory ") . self::$_level_strs[$log_level] . ' - ' . $msg . "\n");

            if($backtrace) {
                debug_print_backtrace();
            }
        }
    }

}


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

import com.facebook.presto.Session;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.spi.ConstantProperty;
import com.facebook.presto.spi.GroupingProperty;
import com.facebook.presto.spi.LocalProperty;
import com.facebook.presto.spi.SortingProperty;
import com.facebook.presto.spi.WarningCollector;
import com.facebook.presto.spi.plan.AggregationNode;
import com.facebook.presto.spi.plan.DistinctLimitNode;
import com.facebook.presto.spi.plan.LimitNode;
import com.facebook.presto.spi.plan.MarkDistinctNode;
import com.facebook.presto.spi.plan.PlanNode;
import com.facebook.presto.spi.plan.PlanNodeIdAllocator;
import com.facebook.presto.spi.plan.TopNNode;
import com.facebook.presto.spi.plan.UnionNode;
import com.facebook.presto.spi.relation.VariableReferenceExpression;
import com.facebook.presto.sql.parser.SqlParser;
import com.facebook.presto.sql.planner.Partitioning;
import com.facebook.presto.sql.planner.PartitioningScheme;
import com.facebook.presto.sql.planner.PlanVariableAllocator;
import com.facebook.presto.sql.planner.TypeProvider;
import com.facebook.presto.sql.planner.optimizations.StreamPropertyDerivations.StreamProperties;
import com.facebook.presto.sql.planner.plan.ApplyNode;
import com.facebook.presto.sql.planner.plan.EnforceSingleRowNode;
import com.facebook.presto.sql.planner.plan.ExchangeNode;
import com.facebook.presto.sql.planner.plan.ExplainAnalyzeNode;
import com.facebook.presto.sql.planner.plan.IndexJoinNode;
import com.facebook.presto.sql.planner.plan.InternalPlanVisitor;
import com.facebook.presto.sql.planner.plan.JoinNode;
import com.facebook.presto.sql.planner.plan.LateralJoinNode;
import com.facebook.presto.sql.planner.plan.OutputNode;
import com.facebook.presto.sql.planner.plan.RowNumberNode;
import com.facebook.presto.sql.planner.plan.SemiJoinNode;
import com.facebook.presto.sql.planner.plan.SortNode;
import com.facebook.presto.sql.planner.plan.SpatialJoinNode;
import com.facebook.presto.sql.planner.plan.StatisticAggregations;
import com.facebook.presto.sql.planner.plan.StatisticsWriterNode;
import com.facebook.presto.sql.planner.plan.TableFinishNode;
import com.facebook.presto.sql.planner.plan.TableWriterMergeNode;
import com.facebook.presto.sql.planner.plan.TableWriterNode;
import com.facebook.presto.sql.planner.plan.TopNRowNumberNode;
import com.facebook.presto.sql.planner.plan.WindowNode;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;

import static com.facebook.presto.SystemSessionProperties.getTaskConcurrency;
import static com.facebook.presto.SystemSessionProperties.getTaskPartitionedWriterCount;
import static com.facebook.presto.SystemSessionProperties.getTaskWriterCount;
import static com.facebook.presto.SystemSessionProperties.isDistributedSortEnabled;
import static com.facebook.presto.SystemSessionProperties.isEnforceFixedDistributionForOutputOperator;
import static com.facebook.presto.SystemSessionProperties.isJoinSpillingEnabled;
import static com.facebook.presto.SystemSessionProperties.isSpillEnabled;
import static com.facebook.presto.SystemSessionProperties.isTableWriterMergeOperatorEnabled;
import static com.facebook.presto.common.type.BigintType.BIGINT;
import static com.facebook.presto.common.type.VarbinaryType.VARBINARY;
import static com.facebook.presto.operator.aggregation.AggregationUtils.hasSingleNodeExecutionPreference;
import static com.facebook.presto.operator.aggregation.AggregationUtils.isDecomposable;
import static com.facebook.presto.sql.planner.SystemPartitioningHandle.FIXED_ARBITRARY_DISTRIBUTION;
import static com.facebook.presto.sql.planner.SystemPartitioningHandle.FIXED_HASH_DISTRIBUTION;
import static com.facebook.presto.sql.planner.SystemPartitioningHandle.SINGLE_DISTRIBUTION;
import static com.facebook.presto.sql.planner.optimizations.StreamPreferredProperties.any;
import static com.facebook.presto.sql.planner.optimizations.StreamPreferredProperties.defaultParallelism;
import static com.facebook.presto.sql.planner.optimizations.StreamPreferredProperties.exactlyPartitionedOn;
import static com.facebook.presto.sql.planner.optimizations.StreamPreferredProperties.fixedParallelism;
import static com.facebook.presto.sql.planner.optimizations.StreamPreferredProperties.singleStream;
import static com.facebook.presto.sql.planner.optimizations.StreamPropertyDerivations.StreamProperties.StreamDistribution.SINGLE;
import static com.facebook.presto.sql.planner.optimizations.StreamPropertyDerivations.derivePropertiesRecursively;
import static com.facebook.presto.sql.planner.plan.ChildReplacer.replaceChildren;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.Scope.LOCAL;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.Type.GATHER;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.Type.REPARTITION;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.gatheringExchange;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.mergingExchange;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.partitionedExchange;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.roundRobinExchange;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.systemPartitionedExchange;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;

public class AddLocalExchanges
        implements PlanOptimizer
{
    private final Metadata metadata;
    private final SqlParser parser;

    public AddLocalExchanges(Metadata metadata, SqlParser parser)
    {
        this.metadata = requireNonNull(metadata, "metadata is null");
        this.parser = requireNonNull(parser, "parser is null");
    }

    @Override
    public PlanNode optimize(PlanNode plan, Session session, TypeProvider types, PlanVariableAllocator variableAllocator, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector)
    {
        PlanWithProperties result = plan.accept(new Rewriter(variableAllocator, idAllocator, session), any());
        return result.getNode();
    }

    private class Rewriter
            extends InternalPlanVisitor<PlanWithProperties, StreamPreferredProperties>
    {
        private final PlanVariableAllocator variableAllocator;
        private final PlanNodeIdAllocator idAllocator;
        private final Session session;
        private final TypeProvider types;

        public Rewriter(PlanVariableAllocator variableAllocator, PlanNodeIdAllocator idAllocator, Session session)
        {
            this.variableAllocator = variableAllocator;
            this.types = variableAllocator.getTypes();
            this.idAllocator = idAllocator;
            this.session = session;
        }

        @Override
        public PlanWithProperties visitPlan(PlanNode node, StreamPreferredProperties parentPreferences)
        {
            return planAndEnforceChildren(
                    node,
                    parentPreferences.withoutPreference().withDefaultParallelism(session),
                    parentPreferences.withDefaultParallelism(session));
        }

        @Override
        public PlanWithProperties visitApply(ApplyNode node, StreamPreferredProperties parentPreferences)
        {
            throw new IllegalStateException("Unexpected node: " + node.getClass().getName());
        }

        @Override
        public PlanWithProperties visitLateralJoin(LateralJoinNode node, StreamPreferredProperties parentPreferences)
        {
            throw new IllegalStateException("Unexpected node: " + node.getClass().getName());
        }

        @Override
        public PlanWithProperties visitOutput(OutputNode node, StreamPreferredProperties parentPreferences)
        {
            return planAndEnforceChildren(
                    node,
                    any().withOrderSensitivity(),
                    any().withOrderSensitivity());
        }

        @Override
        public PlanWithProperties visitExplainAnalyze(ExplainAnalyzeNode node, StreamPreferredProperties parentPreferences)
        {
            // Although explain analyze discards all output, we want to maintain the behavior
            // of a normal output node, so declare the node to be order sensitive
            return planAndEnforceChildren(
                    node,
                    singleStream().withOrderSensitivity(),
                    singleStream().withOrderSensitivity());
        }

        //
        // Nodes that always require a single stream
        //

        @Override
        public PlanWithProperties visitSort(SortNode node, StreamPreferredProperties parentPreferences)
        {
            if (isDistributedSortEnabled(session)) {
                PlanWithProperties sortPlan = planAndEnforceChildren(node, fixedParallelism(), fixedParallelism());

                if (!sortPlan.getProperties().isSingleStream()) {
                    return deriveProperties(
                            mergingExchange(
                                    idAllocator.getNextId(),
                                    LOCAL,
                                    sortPlan.getNode(),
                                    node.getOrderingScheme()),
                            sortPlan.getProperties());
                }

                return sortPlan;
            }
            // sort requires that all data be in one stream
            // this node changes the input organization completely, so we do not pass through parent preferences
            return planAndEnforceChildren(node, singleStream(), defaultParallelism(session));
        }

        @Override
        public PlanWithProperties visitStatisticsWriterNode(StatisticsWriterNode node, StreamPreferredProperties context)
        {
            // analyze finish requires that all data be in one stream
            // this node changes the input organization completely, so we do not pass through parent preferences
            return planAndEnforceChildren(node, singleStream(), defaultParallelism(session));
        }

        @Override
        public PlanWithProperties visitTableFinish(TableFinishNode node, StreamPreferredProperties parentPreferences)
        {
            // table commit requires that all data be in one stream
            // this node changes the input organization completely, so we do not pass through parent preferences
            return planAndEnforceChildren(node, singleStream(), defaultParallelism(session));
        }

        @Override
        public PlanWithProperties visitTopN(TopNNode node, StreamPreferredProperties parentPreferences)
        {
            if (node.getStep().equals(TopNNode.Step.PARTIAL)) {
                return planAndEnforceChildren(
                        node,
                        parentPreferences.withoutPreference().withDefaultParallelism(session),
                        parentPreferences.withDefaultParallelism(session));
            }

            // final topN requires that all data be in one stream
            // also, a final changes the input organization completely, so we do not pass through parent preferences
            return planAndEnforceChildren(
                    node,
                    singleStream(),
                    defaultParallelism(session));
        }

        @Override
        public PlanWithProperties visitLimit(LimitNode node, StreamPreferredProperties parentPreferences)
        {
            if (node.isPartial()) {
                return planAndEnforceChildren(
                        node,
                        parentPreferences.withoutPreference().withDefaultParallelism(session),
                        parentPreferences.withDefaultParallelism(session));
            }

            // final limit requires that all data be in one stream
            // also, a final changes the input organization completely, so we do not pass through parent preferences
            return planAndEnforceChildren(
                    node,
                    singleStream(),
                    defaultParallelism(session));
        }

        @Override
        public PlanWithProperties visitDistinctLimit(DistinctLimitNode node, StreamPreferredProperties parentPreferences)
        {
            // final limit requires that all data be in one stream
            StreamPreferredProperties requiredProperties;
            StreamPreferredProperties preferredProperties;
            if (node.isPartial()) {
                requiredProperties = parentPreferences.withoutPreference().withDefaultParallelism(session);
                preferredProperties = parentPreferences.withDefaultParallelism(session);
            }
            else {
                // a final changes the input organization completely, so we do not pass through parent preferences
                requiredProperties = singleStream();
                preferredProperties = defaultParallelism(session);
            }

            return planAndEnforceChildren(node, requiredProperties, preferredProperties);
        }

        @Override
        public PlanWithProperties visitEnforceSingleRow(EnforceSingleRowNode node, StreamPreferredProperties parentPreferences)
        {
            return planAndEnforceChildren(node, singleStream(), defaultParallelism(session));
        }

        //
        // Nodes that require parallel streams to be partitioned
        //

        @Override
        public PlanWithProperties visitAggregation(AggregationNode node, StreamPreferredProperties parentPreferences)
        {
            checkState(node.getStep() == AggregationNode.Step.SINGLE, "step of aggregation is expected to be SINGLE, but it is %s", node.getStep());

            if (hasSingleNodeExecutionPreference(node, metadata.getFunctionAndTypeManager())) {
                return planAndEnforceChildren(node, singleStream(), defaultParallelism(session));
            }

            List<VariableReferenceExpression> groupingKeys = node.getGroupingKeys();
            if (node.hasDefaultOutput()) {
                checkState(isDecomposable(node, metadata.getFunctionAndTypeManager()));

                // Put fixed local exchange directly below final aggregation to ensure that final and partial aggregations are separated by exchange (in a local runner mode)
                // This is required so that default outputs from multiple instances of partial aggregations are passed to a single final aggregation.
                PlanWithProperties child = planAndEnforce(node.getSource(), any(), defaultParallelism(session));
                PlanWithProperties exchange = deriveProperties(
                        systemPartitionedExchange(
                                idAllocator.getNextId(),
                                LOCAL,
                                child.getNode(),
                                groupingKeys,
                                Optional.empty()),
                        child.getProperties());
                return rebaseAndDeriveProperties(node, ImmutableList.of(exchange));
            }

            StreamPreferredProperties childRequirements = parentPreferences
                    .constrainTo(node.getSource().getOutputVariables())
                    .withDefaultParallelism(session)
                    .withPartitioning(groupingKeys);

            PlanWithProperties child = planAndEnforce(node.getSource(), childRequirements, childRequirements);

            List<VariableReferenceExpression> preGroupedSymbols = ImmutableList.of();
            if (!LocalProperties.match(child.getProperties().getLocalProperties(), LocalProperties.grouped(groupingKeys)).get(0).isPresent()) {
                // !isPresent() indicates the property was satisfied completely
                preGroupedSymbols = groupingKeys;
            }

            AggregationNode result = new AggregationNode(
                    node.getId(),
                    child.getNode(),
                    node.getAggregations(),
                    node.getGroupingSets(),
                    preGroupedSymbols,
                    node.getStep(),
                    node.getHashVariable(),
                    node.getGroupIdVariable());

            return deriveProperties(result, child.getProperties());
        }

        @Override
        public PlanWithProperties visitWindow(WindowNode node, StreamPreferredProperties parentPreferences)
        {
            StreamPreferredProperties childRequirements = parentPreferences
                    .constrainTo(node.getSource().getOutputVariables())
                    .withDefaultParallelism(session)
                    .withPartitioning(node.getPartitionBy());

            PlanWithProperties child = planAndEnforce(node.getSource(), childRequirements, childRequirements);

            List<LocalProperty<VariableReferenceExpression>> desiredProperties = new ArrayList<>();
            if (!node.getPartitionBy().isEmpty()) {
                desiredProperties.add(new GroupingProperty<>(node.getPartitionBy()));
            }
            node.getOrderingScheme().ifPresent(orderingScheme ->
                    orderingScheme.getOrderByVariables().stream()
                            .map(variable -> new SortingProperty<>(variable, orderingScheme.getOrdering(variable)))
                            .forEach(desiredProperties::add));
            Iterator<Optional<LocalProperty<VariableReferenceExpression>>> matchIterator = LocalProperties.match(child.getProperties().getLocalProperties(), desiredProperties).iterator();

            Set<VariableReferenceExpression> prePartitionedInputs = ImmutableSet.of();
            if (!node.getPartitionBy().isEmpty()) {
                Optional<LocalProperty<VariableReferenceExpression>> groupingRequirement = matchIterator.next();
                Set<VariableReferenceExpression> unPartitionedInputs = groupingRequirement.map(LocalProperty::getColumns).orElse(ImmutableSet.of());
                prePartitionedInputs = node.getPartitionBy().stream()
                        .filter(variable -> !unPartitionedInputs.contains(variable))
                        .collect(toImmutableSet());
            }

            int preSortedOrderPrefix = 0;
            if (prePartitionedInputs.equals(ImmutableSet.copyOf(node.getPartitionBy()))) {
                while (matchIterator.hasNext() && !matchIterator.next().isPresent()) {
                    preSortedOrderPrefix++;
                }
            }

            WindowNode result = new WindowNode(
                    node.getId(),
                    child.getNode(),
                    node.getSpecification(),
                    node.getWindowFunctions(),
                    node.getHashVariable(),
                    prePartitionedInputs,
                    preSortedOrderPrefix);

            return deriveProperties(result, child.getProperties());
        }

        @Override
        public PlanWithProperties visitMarkDistinct(MarkDistinctNode node, StreamPreferredProperties parentPreferences)
        {
            // mark distinct requires that all data partitioned
            StreamPreferredProperties childRequirements = parentPreferences
                    .constrainTo(node.getSource().getOutputVariables())
                    .withDefaultParallelism(session)
                    .withPartitioning(node.getDistinctVariables());

            PlanWithProperties child = planAndEnforce(node.getSource(), childRequirements, childRequirements);

            MarkDistinctNode result = new MarkDistinctNode(
                    node.getId(),
                    child.getNode(),
                    node.getMarkerVariable(),
                    pruneMarkDistinctVariables(node, child.getProperties().getLocalProperties()),
                    node.getHashVariable());

            return deriveProperties(result, child.getProperties());
        }

        /**
         * Prune redundant distinct symbols to reduce CPU cost of hashing corresponding values and amount of memory
         * needed to store all the distinct values.
         * <p>
         * Consider the following plan,
         * <pre>
         *  - MarkDistinctNode (unique, c1, c2)
         *      - Join
         *          - AssignUniqueId (unique)
         *              - probe (c1, c2)
         *          - build
         * </pre>
         * In this case MarkDistinctNode (unique, c1, c2) is equivalent to MarkDistinctNode (unique),
         * because if two rows match on `unique`, they must match on `c1` and `c2` as well.
         * <p>
         * More generally, any distinct symbol that is functionally dependent on a subset of
         * other distinct symbols can be dropped.
         * <p>
         * Ideally, this logic would be encapsulated in a separate rule, but currently no rule other
         * than AddLocalExchanges can reason about local properties.
         */
        private List<VariableReferenceExpression> pruneMarkDistinctVariables(MarkDistinctNode node, List<LocalProperty<VariableReferenceExpression>> localProperties)
        {
            if (localProperties.isEmpty()) {
                return node.getDistinctVariables();
            }

            // Identify functional dependencies between distinct symbols: in the list of local properties any constant
            // symbol is functionally dependent on the set of symbols that appears earlier.
            ImmutableSet.Builder<VariableReferenceExpression> redundantVariablesBuilder = ImmutableSet.builder();
            for (LocalProperty<VariableReferenceExpression> property : localProperties) {
                if (property instanceof ConstantProperty) {
                    redundantVariablesBuilder.add(((ConstantProperty<VariableReferenceExpression>) property).getColumn());
                }
                else if (!node.getDistinctVariables().containsAll(property.getColumns())) {
                    // Ran into a non-distinct symbol. There will be no more symbols that are functionally dependent on distinct symbols exclusively.
                    break;
                }
            }

            Set<VariableReferenceExpression> redundantVariables = redundantVariablesBuilder.build();
            List<VariableReferenceExpression> remainingSymbols = node.getDistinctVariables().stream()
                    .filter(variable -> !redundantVariables.contains(variable))
                    .collect(toImmutableList());
            if (remainingSymbols.isEmpty()) {
                // This happens when all distinct symbols are constants.
                // In that case, keep the first symbol (don't drop them all).
                return ImmutableList.of(node.getDistinctVariables().get(0));
            }
            return remainingSymbols;
        }

        @Override
        public PlanWithProperties visitRowNumber(RowNumberNode node, StreamPreferredProperties parentPreferences)
        {
            // row number requires that all data be partitioned
            StreamPreferredProperties requiredProperties = parentPreferences.withDefaultParallelism(session).withPartitioning(node.getPartitionBy());
            return planAndEnforceChildren(node, requiredProperties, requiredProperties);
        }

        @Override
        public PlanWithProperties visitTopNRowNumber(TopNRowNumberNode node, StreamPreferredProperties parentPreferences)
        {
            StreamPreferredProperties requiredProperties = parentPreferences.withDefaultParallelism(session);

            // final topN row number requires that all data be partitioned
            if (!node.isPartial()) {
                requiredProperties = requiredProperties.withPartitioning(node.getPartitionBy());
            }

            return planAndEnforceChildren(node, requiredProperties, requiredProperties);
        }

        //
        // Table Writer
        //

        @Override
        public PlanWithProperties visitTableWriter(TableWriterNode originalTableWriterNode, StreamPreferredProperties parentPreferences)
        {
            if (originalTableWriterNode.getTablePartitioningScheme().isPresent() && getTaskPartitionedWriterCount(session) == 1) {
                return planAndEnforceChildren(originalTableWriterNode, singleStream(), defaultParallelism(session));
            }

            if (!originalTableWriterNode.getTablePartitioningScheme().isPresent() && getTaskWriterCount(session) == 1) {
                return planAndEnforceChildren(originalTableWriterNode, singleStream(), defaultParallelism(session));
            }

            if (!isTableWriterMergeOperatorEnabled(session)) {
                return planAndEnforceChildren(originalTableWriterNode, fixedParallelism(), fixedParallelism());
            }

            Optional<StatisticAggregations.Parts> statisticAggregations = originalTableWriterNode
                    .getStatisticsAggregation()
                    .map(aggregations -> aggregations.splitIntoPartialAndIntermediate(
                            variableAllocator,
                            metadata.getFunctionAndTypeManager()));

            PlanWithProperties tableWriter;

            if (!originalTableWriterNode.getTablePartitioningScheme().isPresent()) {
                int taskWriterCount = getTaskWriterCount(session);
                int taskConcurrency = getTaskConcurrency(session);
                if (taskWriterCount == taskConcurrency) {
                    tableWriter = planAndEnforceChildren(
                            new TableWriterNode(
                                    originalTableWriterNode.getId(),
                                    originalTableWriterNode.getSource(),
                                    originalTableWriterNode.getTarget(),
                                    variableAllocator.newVariable("partialrowcount", BIGINT),
                                    variableAllocator.newVariable("partialfragments", VARBINARY),
                                    variableAllocator.newVariable("partialcontext", VARBINARY),
                                    originalTableWriterNode.getColumns(),
                                    originalTableWriterNode.getColumnNames(),
                                    originalTableWriterNode.getNotNullColumnVariables(),
                                    originalTableWriterNode.getTablePartitioningScheme(),
                                    originalTableWriterNode.getPreferredShufflePartitioningScheme(),
                                    statisticAggregations.map(StatisticAggregations.Parts::getPartialAggregation)),
                            fixedParallelism(),
                            fixedParallelism());
                }
                else {
                    PlanWithProperties source = originalTableWriterNode.getSource().accept(this, defaultParallelism(session));
                    PlanWithProperties exchange = deriveProperties(
                            roundRobinExchange(idAllocator.getNextId(), LOCAL, source.getNode()),
                            source.getProperties());
                    tableWriter = deriveProperties(
                            new TableWriterNode(
                                    originalTableWriterNode.getId(),
                                    exchange.getNode(),
                                    originalTableWriterNode.getTarget(),
                                    variableAllocator.newVariable("partialrowcount", BIGINT),
                                    variableAllocator.newVariable("partialfragments", VARBINARY),
                                    variableAllocator.newVariable("partialcontext", VARBINARY),
                                    originalTableWriterNode.getColumns(),
                                    originalTableWriterNode.getColumnNames(),
                                    originalTableWriterNode.getNotNullColumnVariables(),
                                    originalTableWriterNode.getTablePartitioningScheme(),
                                    originalTableWriterNode.getPreferredShufflePartitioningScheme(),
                                    statisticAggregations.map(StatisticAggregations.Parts::getPartialAggregation)),
                            exchange.getProperties());
                }
            }
            else {
                PlanWithProperties source = originalTableWriterNode.getSource().accept(this, defaultParallelism(session));
                PlanWithProperties exchange = deriveProperties(
                        partitionedExchange(
                                idAllocator.getNextId(),
                                LOCAL,
                                source.getNode(),
                                originalTableWriterNode.getTablePartitioningScheme().get()),
                        source.getProperties());
                tableWriter = deriveProperties(
                        new TableWriterNode(
                                originalTableWriterNode.getId(),
                                exchange.getNode(),
                                originalTableWriterNode.getTarget(),
                                variableAllocator.newVariable("partialrowcount", BIGINT),
                                variableAllocator.newVariable("partialfragments", VARBINARY),
                                variableAllocator.newVariable("partialcontext", VARBINARY),
                                originalTableWriterNode.getColumns(),
                                originalTableWriterNode.getColumnNames(),
                                originalTableWriterNode.getNotNullColumnVariables(),
                                originalTableWriterNode.getTablePartitioningScheme(),
                                originalTableWriterNode.getPreferredShufflePartitioningScheme(),
                                statisticAggregations.map(StatisticAggregations.Parts::getPartialAggregation)),
                        exchange.getProperties());
            }

            PlanWithProperties gatheringExchange = deriveProperties(
                    gatheringExchange(
                            idAllocator.getNextId(),
                            LOCAL,
                            tableWriter.getNode()),
                    tableWriter.getProperties());

            return deriveProperties(
                    new TableWriterMergeNode(
                            idAllocator.getNextId(),
                            gatheringExchange.getNode(),
                            originalTableWriterNode.getRowCountVariable(),
                            originalTableWriterNode.getFragmentVariable(),
                            originalTableWriterNode.getTableCommitContextVariable(),
                            statisticAggregations.map(StatisticAggregations.Parts::getIntermediateAggregation)),
                    gatheringExchange.getProperties());
        }

        @Override
        public PlanWithProperties visitTableWriteMerge(TableWriterMergeNode node, StreamPreferredProperties context)
        {
            throw new IllegalArgumentException("Unexpected TableWriterMergeNode");
        }

        //
        // Exchanges
        //

        @Override
        public PlanWithProperties visitExchange(ExchangeNode node, StreamPreferredProperties parentPreferences)
        {
            checkArgument(!node.getScope().isLocal(), "AddLocalExchanges can not process a plan containing a local exchange");
            // this node changes the input organization completely, so we do not pass through parent preferences
            if (node.getOrderingScheme().isPresent()) {
                return planAndEnforceChildren(
                        node,
                        any().withOrderSensitivity(),
                        any().withOrderSensitivity());
            }
            return planAndEnforceChildren(
                    node,
                    isEnforceFixedDistributionForOutputOperator(session) ? fixedParallelism() : any(),
                    defaultParallelism(session));
        }

        @Override
        public PlanWithProperties visitUnion(UnionNode node, StreamPreferredProperties preferredProperties)
        {
            // Union is replaced with an exchange which does not retain streaming properties from the children
            List<PlanWithProperties> sourcesWithProperties = node.getSources().stream()
                    .map(source -> source.accept(this, defaultParallelism(session)))
                    .collect(toImmutableList());

            List<PlanNode> sources = sourcesWithProperties.stream()
                    .map(PlanWithProperties::getNode)
                    .collect(toImmutableList());

            List<StreamProperties> inputProperties = sourcesWithProperties.stream()
                    .map(PlanWithProperties::getProperties)
                    .collect(toImmutableList());

            List<List<VariableReferenceExpression>> inputLayouts = new ArrayList<>(sources.size());
            for (int i = 0; i < sources.size(); i++) {
                inputLayouts.add(node.sourceOutputLayout(i));
            }

            if (preferredProperties.isSingleStreamPreferred()) {
                ExchangeNode exchangeNode = new ExchangeNode(
                        idAllocator.getNextId(),
                        GATHER,
                        LOCAL,
                        new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), node.getOutputVariables()),
                        sources,
                        inputLayouts,
                        false,
                        Optional.empty());
                return deriveProperties(exchangeNode, inputProperties);
            }

            Optional<List<VariableReferenceExpression>> preferredPartitionColumns = preferredProperties.getPartitioningColumns();
            if (preferredPartitionColumns.isPresent()) {
                ExchangeNode exchangeNode = new ExchangeNode(
                        idAllocator.getNextId(),
                        REPARTITION,
                        LOCAL,
                        new PartitioningScheme(
                                Partitioning.create(FIXED_HASH_DISTRIBUTION, preferredPartitionColumns.get()),
                                node.getOutputVariables()),
                        sources,
                        inputLayouts,
                        false,
                        Optional.empty());
                return deriveProperties(exchangeNode, inputProperties);
            }

            // multiple streams preferred
            ExchangeNode result = new ExchangeNode(
                    idAllocator.getNextId(),
                    REPARTITION,
                    LOCAL,
                    new PartitioningScheme(Partitioning.create(FIXED_ARBITRARY_DISTRIBUTION, ImmutableList.of()), node.getOutputVariables()),
                    sources,
                    inputLayouts,
                    false,
                    Optional.empty());
            ExchangeNode exchangeNode = result;

            return deriveProperties(exchangeNode, inputProperties);
        }

        //
        // Joins
        //

        @Override
        public PlanWithProperties visitJoin(JoinNode node, StreamPreferredProperties parentPreferences)
        {
            PlanWithProperties probe;
            if (isSpillEnabled(session) && isJoinSpillingEnabled(session)) {
                probe = planAndEnforce(
                        node.getLeft(),
                        fixedParallelism(),
                        parentPreferences.constrainTo(node.getLeft().getOutputVariables()).withFixedParallelism());
            }
            else {
                probe = planAndEnforce(
                        node.getLeft(),
                        defaultParallelism(session),
                        parentPreferences.constrainTo(node.getLeft().getOutputVariables()).withDefaultParallelism(session));
            }

            // this build consumes the input completely, so we do not pass through parent preferences
            List<VariableReferenceExpression> buildHashVariables = node.getCriteria().stream()
                    .map(JoinNode.EquiJoinClause::getRight)
                    .collect(toImmutableList());
            StreamPreferredProperties buildPreference;
            if (getTaskConcurrency(session) > 1) {
                buildPreference = exactlyPartitionedOn(buildHashVariables);
            }
            else {
                buildPreference = singleStream();
            }
            PlanWithProperties build = planAndEnforce(node.getRight(), buildPreference, buildPreference);

            return rebaseAndDeriveProperties(node, ImmutableList.of(probe, build));
        }

        @Override
        public PlanWithProperties visitSemiJoin(SemiJoinNode node, StreamPreferredProperties parentPreferences)
        {
            PlanWithProperties source = planAndEnforce(
                    node.getSource(),
                    defaultParallelism(session),
                    parentPreferences.constrainTo(node.getSource().getOutputVariables()).withDefaultParallelism(session));

            // this filter source consumes the input completely, so we do not pass through parent preferences
            PlanWithProperties filteringSource = planAndEnforce(node.getFilteringSource(), singleStream(), singleStream());

            return rebaseAndDeriveProperties(node, ImmutableList.of(source, filteringSource));
        }

        @Override
        public PlanWithProperties visitSpatialJoin(SpatialJoinNode node, StreamPreferredProperties parentPreferences)
        {
            PlanWithProperties probe = planAndEnforce(
                    node.getLeft(),
                    defaultParallelism(session),
                    parentPreferences.constrainTo(node.getLeft().getOutputVariables())
                            .withDefaultParallelism(session));

            PlanWithProperties build = planAndEnforce(node.getRight(), singleStream(), singleStream());

            return rebaseAndDeriveProperties(node, ImmutableList.of(probe, build));
        }

        @Override
        public PlanWithProperties visitIndexJoin(IndexJoinNode node, StreamPreferredProperties parentPreferences)
        {
            PlanWithProperties probe = planAndEnforce(
                    node.getProbeSource(),
                    defaultParallelism(session),
                    parentPreferences.constrainTo(node.getProbeSource().getOutputVariables()).withDefaultParallelism(session));

            // index source does not support local parallel and must produce a single stream
            StreamProperties indexStreamProperties = derivePropertiesRecursively(node.getIndexSource(), metadata, session, types, parser);
            checkArgument(indexStreamProperties.getDistribution() == SINGLE, "index source must be single stream");
            PlanWithProperties index = new PlanWithProperties(node.getIndexSource(), indexStreamProperties);

            return rebaseAndDeriveProperties(node, ImmutableList.of(probe, index));
        }

        //
        // Helpers
        //

        private PlanWithProperties planAndEnforceChildren(PlanNode node, StreamPreferredProperties requiredProperties, StreamPreferredProperties preferredProperties)
        {
            // plan and enforce each child, but strip any requirement not in terms of symbols produced from the child
            // Note: this assumes the child uses the same symbols as the parent
            List<PlanWithProperties> children = node.getSources().stream()
                    .map(source -> planAndEnforce(
                            source,
                            requiredProperties.constrainTo(source.getOutputVariables()),
                            preferredProperties.constrainTo(source.getOutputVariables())))
                    .collect(toImmutableList());

            return rebaseAndDeriveProperties(node, children);
        }

        private PlanWithProperties planAndEnforce(PlanNode node, StreamPreferredProperties requiredProperties, StreamPreferredProperties preferredProperties)
        {
            // verify properties are in terms of symbols produced by the node
            checkArgument(requiredProperties.getPartitioningColumns().map(node.getOutputVariables()::containsAll).orElse(true));
            checkArgument(preferredProperties.getPartitioningColumns().map(node.getOutputVariables()::containsAll).orElse(true));

            // plan the node using the preferred properties
            PlanWithProperties result = node.accept(this, preferredProperties);

            // enforce the required properties
            result = enforce(result, requiredProperties);

            checkState(requiredProperties.isSatisfiedBy(result.getProperties()), "required properties not enforced");
            return result;
        }

        private PlanWithProperties enforce(PlanWithProperties planWithProperties, StreamPreferredProperties requiredProperties)
        {
            if (requiredProperties.isSatisfiedBy(planWithProperties.getProperties())) {
                return planWithProperties;
            }

            if (requiredProperties.isSingleStreamPreferred()) {
                ExchangeNode exchangeNode = gatheringExchange(idAllocator.getNextId(), LOCAL, planWithProperties.getNode());
                return deriveProperties(exchangeNode, planWithProperties.getProperties());
            }

            Optional<List<VariableReferenceExpression>> requiredPartitionColumns = requiredProperties.getPartitioningColumns();
            if (!requiredPartitionColumns.isPresent()) {
                // unpartitioned parallel streams required
                return deriveProperties(
                        roundRobinExchange(idAllocator.getNextId(), LOCAL, planWithProperties.getNode()),
                        planWithProperties.getProperties());
            }

            if (requiredProperties.isParallelPreferred()) {
                // partitioned parallel streams required
                ExchangeNode exchangeNode = systemPartitionedExchange(
                        idAllocator.getNextId(),
                        LOCAL,
                        planWithProperties.getNode(),
                        requiredPartitionColumns.get(),
                        Optional.empty());
                return deriveProperties(exchangeNode, planWithProperties.getProperties());
            }

            // no explicit parallel requirement, so gather to a single stream
            ExchangeNode exchangeNode = gatheringExchange(
                    idAllocator.getNextId(),
                    LOCAL,
                    planWithProperties.getNode());
            return deriveProperties(exchangeNode, planWithProperties.getProperties());
        }

        private PlanWithProperties rebaseAndDeriveProperties(PlanNode node, List<PlanWithProperties> children)
        {
            PlanNode result = replaceChildren(
                    node,
                    children.stream()
                            .map(PlanWithProperties::getNode)
                            .collect(toList()));

            List<StreamProperties> inputProperties = children.stream()
                    .map(PlanWithProperties::getProperties)
                    .collect(toImmutableList());

            return deriveProperties(result, inputProperties);
        }

        private PlanWithProperties deriveProperties(PlanNode result, StreamProperties inputProperties)
        {
            return new PlanWithProperties(result, StreamPropertyDerivations.deriveProperties(result, inputProperties, metadata, session, types, parser));
        }

        private PlanWithProperties deriveProperties(PlanNode result, List<StreamProperties> inputProperties)
        {
            return new PlanWithProperties(result, StreamPropertyDerivations.deriveProperties(result, inputProperties, metadata, session, types, parser));
        }
    }

    private static class PlanWithProperties
    {
        private final PlanNode node;
        private final StreamProperties properties;

        public PlanWithProperties(PlanNode node, StreamProperties properties)
        {
            this.node = requireNonNull(node, "node is null");
            this.properties = requireNonNull(properties, "StreamProperties is null");
        }

        public PlanNode getNode()
        {
            return node;
        }

        public StreamProperties getProperties()
        {
            return properties;
        }
    }
}


text:
require './test/test_helper'

class MilkbottleProductsTest < Minitest::Test
  def setup
    Milkbottle.reset!
    @client = test_client
  end

  def teardown
    Milkbottle.reset!
  end

  def test_exists
    assert Milkbottle::Client::Products
  end

  def test_it_gives_back_all_the_products
    VCR.use_cassette('products') do
      result = @client.products

      assert result[:Products].kind_of?(Array)

      assert_equal 17, result[:Products].length
    end
  end
end


text:
using System;
using Xunit;
using Xunit.Sdk;

namespace FluentAssertions.Specs.Primitives;

public class NullableGuidAssertionSpecs
{
    [Fact]
    public void Should_succeed_when_asserting_nullable_guid_value_with_a_value_to_have_a_value()
    {
        // Arrange
        Guid? nullableGuid = Guid.NewGuid();

        // Act / Assert
        nullableGuid.Should().HaveValue();
    }

    [Fact]
    public void Should_succeed_when_asserting_nullable_guid_value_with_a_value_to_not_be_null()
    {
        // Arrange
        Guid? nullableGuid = Guid.NewGuid();

        // Act / Assert
        nullableGuid.Should().NotBeNull();
    }

    [Fact]
    public void Should_fail_when_asserting_nullable_guid_value_without_a_value_to_have_a_value()
    {
        // Arrange
        Guid? nullableGuid = null;

        // Act
        Action act = () => nullableGuid.Should().HaveValue();

        // Assert
        act.Should().Throw<XunitException>();
    }

    [Fact]
    public void Should_fail_when_asserting_nullable_guid_value_without_a_value_to_not_be_null()
    {
        // Arrange
        Guid? nullableGuid = null;

        // Act
        Action act = () => nullableGuid.Should().NotBeNull();

        // Assert
        act.Should().Throw<XunitException>();
    }

    [Fact]
    public void Should_fail_with_descriptive_message_when_asserting_nullable_guid_value_without_a_value_to_have_a_value()
    {
        // Arrange
        Guid? nullableGuid = null;

        // Act
        Action act = () => nullableGuid.Should().HaveValue("because we want to test the failure {0}", "message");

        // Assert
        act.Should().Throw<XunitException>()
            .WithMessage("Expected a value because we want to test the failure message.");
    }

    [Fact]
    public void Should_fail_with_descriptive_message_when_asserting_nullable_guid_value_without_a_value_to_not_be_null()
    {
        // Arrange
        Guid? nullableGuid = null;

        // Act
        Action act = () => nullableGuid.Should().NotBeNull("because we want to test the failure {0}", "message");

        // Assert
        act.Should().Throw<XunitException>()
            .WithMessage("Expected a value because we want to test the failure message.");
    }

    [Fact]
    public void Should_succeed_when_asserting_nullable_guid_value_without_a_value_to_not_have_a_value()
    {
        // Arrange
        Guid? nullableGuid = null;

        // Act / Assert
        nullableGuid.Should().NotHaveValue();
    }

    [Fact]
    public void Should_succeed_when_asserting_nullable_guid_value_without_a_value_to_be_null()
    {
        // Arrange
        Guid? nullableGuid = null;

        // Act / Assert
        nullableGuid.Should().BeNull();
    }

    [Fact]
    public void Should_fail_when_asserting_nullable_guid_value_with_a_value_to_not_have_a_value()
    {
        // Arrange
        Guid? nullableGuid = Guid.NewGuid();

        // Act
        Action act = () => nullableGuid.Should().NotHaveValue();

        // Assert
        act.Should().Throw<XunitException>();
    }

    [Fact]
    public void Should_fail_when_asserting_nullable_guid_value_with_a_value_to_be_null()
    {
        // Arrange
        Guid? nullableGuid = Guid.NewGuid();

        // Act
        Action act = () => nullableGuid.Should().BeNull();

        // Assert
        act.Should().Throw<XunitException>();
    }

    [Fact]
    public void Should_fail_when_guid_is_null_while_asserting_guid_equals_another_guid()
    {
        // Arrange
        Guid? guid = null;
        var someGuid = new Guid("55555555-ffff-eeee-dddd-444444444444");

        // Act
        Action act = () =>
            guid.Should().Be(someGuid, "because we want to test the failure {0}", "message");

        // Assert
        act.Should().Throw<XunitException>().WithMessage(
            "Expected Guid to be {55555555-ffff-eeee-dddd-444444444444} because we want to test the failure message, but found <null>.");
    }

    [Fact]
    public void Should_succeed_when_asserting_nullable_guid_null_equals_null()
    {
        // Arrange
        Guid? nullGuid = null;
        Guid? otherNullGuid = null;

        // Act
        Action act = () =>
            nullGuid.Should().Be(otherNullGuid);

        // Assert
        act.Should().NotThrow();
    }

    [Fact]
    public void Should_fail_with_descriptive_message_when_asserting_nullable_guid_value_with_a_value_to_not_have_a_value()
    {
        // Arrange
        Guid? nullableGuid = new Guid("11111111-aaaa-bbbb-cccc-999999999999");

        // Act
        Action act = () => nullableGuid.Should().NotHaveValue("because we want to test the failure {0}", "message");

        // Assert
        act.Should().Throw<XunitException>()
            .WithMessage("Did not expect a value because we want to test the failure message, but found {11111111-aaaa-bbbb-cccc-999999999999}.");
    }

    [Fact]
    public void Should_fail_with_descriptive_message_when_asserting_nullable_guid_value_with_a_value_to_be_null()
    {
        // Arrange
        Guid? nullableGuid = new Guid("11111111-aaaa-bbbb-cccc-999999999999");

        // Act
        Action act = () => nullableGuid.Should().BeNull("because we want to test the failure {0}", "message");

        // Assert
        act.Should().Throw<XunitException>()
            .WithMessage("Did not expect a value because we want to test the failure message, but found {11111111-aaaa-bbbb-cccc-999999999999}.");
    }

    [Fact]
    public void Should_fail_when_asserting_null_equals_some_guid()
    {
        // Arrange
        Guid? nullableGuid = null;
        var someGuid = new Guid("11111111-aaaa-bbbb-cccc-999999999999");

        // Act
        Action act = () =>
            nullableGuid.Should().Be(someGuid, "because we want to test the failure {0}", "message");

        // Assert
        act.Should().Throw<XunitException>().WithMessage(
            "Expected nullableGuid to be {11111111-aaaa-bbbb-cccc-999999999999} because we want to test the failure message, but found <null>.");
    }

    [Fact]
    public void Should_support_chaining_constraints_with_and()
    {
        // Arrange
        Guid? nullableGuid = Guid.NewGuid();

        // Act / Assert
        nullableGuid.Should()
            .HaveValue()
            .And
            .NotBeEmpty();
    }
}


text:
using System.Collections;
using System.Linq;
using System.Net.Sockets;

namespace Content.Server.IP
{
    public static class IPAddressExt
    {
        // Taken from https://stackoverflow.com/a/56461160/4678631
        public static bool IsInSubnet(this System.Net.IPAddress address, string subnetMask)
        {
            var slashIdx = subnetMask.IndexOf("/", StringComparison.Ordinal);
            if (slashIdx == -1)
            {
                // We only handle netmasks in format "IP/PrefixLength".
                throw new NotSupportedException("Only SubNetMasks with a given prefix length are supported.");
            }

            // First parse the address of the netmask before the prefix length.
            var maskAddress = System.Net.IPAddress.Parse(subnetMask[..slashIdx]);

            if (maskAddress.AddressFamily != address.AddressFamily)
            {
                // We got something like an IPV4-Address for an IPv6-Mask. This is not valid.
                return false;
            }

            // Now find out how long the prefix is.
            int maskLength = int.Parse(subnetMask[(slashIdx + 1)..]);

            return address.IsInSubnet(maskAddress, maskLength);
        }

        public static bool IsInSubnet(this System.Net.IPAddress address, (System.Net.IPAddress maskAddress, int maskLength) tuple)
        {
            return address.IsInSubnet(tuple.maskAddress, tuple.maskLength);
        }

        public static bool IsInSubnet(this System.Net.IPAddress address, System.Net.IPAddress maskAddress, int maskLength)
        {
            if (maskAddress.AddressFamily == AddressFamily.InterNetwork)
            {
                // Convert the mask address to an unsigned integer.
                var maskAddressBits = BitConverter.ToUInt32(maskAddress.GetAddressBytes().Reverse().ToArray(), 0);

                // And convert the IpAddress to an unsigned integer.
                var ipAddressBits = BitConverter.ToUInt32(address.GetAddressBytes().Reverse().ToArray(), 0);

                // Get the mask/network address as unsigned integer.
                uint mask = uint.MaxValue << (32 - maskLength);

                // https://stackoverflow.com/a/1499284/3085985
                // Bitwise AND mask and MaskAddress, this should be the same as mask and IpAddress
                // as the end of the mask is 0000 which leads to both addresses to end with 0000
                // and to start with the prefix.
                return (maskAddressBits & mask) == (ipAddressBits & mask);
            }

            if (maskAddress.AddressFamily == AddressFamily.InterNetworkV6)
            {
                // Convert the mask address to a BitArray.
                var maskAddressBits = new BitArray(maskAddress.GetAddressBytes());

                // And convert the IpAddress to a BitArray.
                var ipAddressBits = new BitArray(address.GetAddressBytes());

                if (maskAddressBits.Length != ipAddressBits.Length)
                {
                    throw new ArgumentException("Length of IP Address and Subnet Mask do not match.");
                }

                // Compare the prefix bits.
                for (int maskIndex = 0; maskIndex < maskLength; maskIndex++)
                {
                    if (ipAddressBits[maskIndex] != maskAddressBits[maskIndex])
                    {
                        return false;
                    }
                }

                return true;
            }

            throw new NotSupportedException("Only InterNetworkV6 or InterNetwork address families are supported.");
        }
    }
}


text:
Reads `data-` attributes from the element and assigns them to the Vue instance/component.

You can use the mixin on components and as global mixin. See [mixin documentation](https://vuejs.org/v2/guide/mixins.html).

```html
<my-message data-message="This is OK"></my-message>
```

```js
import dataAttributes from 'vue-mixin-data-attributes';

Vue.component('my-message', {
    mixins: [dataAttributes],

    data: () => {
        return {
            message: 'Default message',
        },
    },

    mounted() {
        console.log(this.message); // Logs: This is OK
    }
});
```

## Installation

`npm install vue-mixin-data-attributes`


text:
<!DOCTYPE html>
<title>drag & drop - simple file drop with dropzone attribute</title>

Save this image to your desktop. Use your pointing device to drag the saved file from your desktop onto the orange box, and release it. If a confirmation dialog appears, accept it. Fail if nothing happens, or if the browser simply displays the image.

Enable JavaScript and reload


text:
namespace http2 {

template <typename T> inline T dieIfNull(T&& ptr) {
  QUICHE_CHECK((ptr) != nullptr);
  return std::forward<T>(ptr);
}

} // namespace http2


text:
class CreateGames < ActiveRecord::Migration
  def change
    create_table :games do |t|
      t.references :level, index: true

      t.timestamps
    end
  end
end


text:
import re
import urllib
from contextlib import contextmanager
from contextlib import nested

import mock
import testify as T
from pushmanager.core import db
from pushmanager.core.util import get_servlet_urlspec
from pushmanager.servlets.checklist import ChecklistServlet
from pushmanager.servlets.checklist import ChecklistToggleServlet
from pushmanager.testing.mocksettings import MockedSettings
from pushmanager.testing.testdb import FakeDataMixin
from pushmanager.testing.testservlet import ServletTestMixin

@contextmanager
def fake_checklist_request():
    with nested(
        mock.patch.dict(db.Settings, MockedSettings),
        mock.patch.object(
            ChecklistToggleServlet,
            "get_current_user",
            return_value="testuser"
        ),
        mock.patch.object(
            ChecklistServlet,
            "get_current_user",
            return_value="testuser"
        )
    ):
        yield

def on_db_return(success, db_results):
    assert success

class ChecklistServletTest(T.TestCase, ServletTestMixin, FakeDataMixin):

    def get_handlers(self):
        return [get_servlet_urlspec(ChecklistServlet)]

    def test_no_checklist(self):
        with fake_checklist_request():
            uri = "/checklist?id=1"
            response = self.fetch(uri)
            T.assert_equal(response.error, None)
            T.assert_in("No checklist items for this push", response.body)

    def test_checklist_duplicate(self):
        with fake_checklist_request():
            # insert fake data from FakeDataMixin
            fake_pushid = 2
            self.insert_pushes()
            self.insert_requests()
            test1_request = self.get_requests_by_user('testuser1')[0]
            test2_request = self.get_requests_by_user('testuser2')[0]
            self.insert_pushcontent(test1_request['id'], fake_pushid)
            self.insert_pushcontent(test2_request['id'], fake_pushid)

            # insert fake checklist data
            checklist_queries = []
            for req in (test1_request, test2_request):
                checklist_queries.append(db.push_checklist.insert({
                    'request': req['id'],
                    'type': 'search',
                    'target': 'prod'
                }))
                checklist_queries.append(db.push_checklist.insert({
                    'request': req['id'],
                    'type': 'search-cleanup',
                    'target': 'post-verify-prod'
                }))
            db.execute_transaction_cb(checklist_queries, on_db_return)

            uri = "/checklist?id=%d" % fake_pushid
            response = self.fetch(uri)
            T.assert_equal(response.error, None)
            T.assert_not_in("No checklist items for this push", response.body)
            T.assert_not_equal(re.search("for testuser\d,testuser\d", response.body), None)
            T.assert_in("Before Certifying - Do In Prod", response.body)

    def test_checklist_single_search_tag(self):
        with fake_checklist_request():
            # insert fake data from FakeDataMixin
            fake_pushid = 2
            self.insert_pushes()
            self.insert_requests()
            test1_request = self.get_requests_by_user('testuser1')[0]
            self.insert_pushcontent(test1_request['id'], fake_pushid)

            # insert fake checklist data
            checklist_queries = [
                db.push_checklist.insert({
                    'request': test1_request['id'],
                    'type': 'search',
                    'target': 'prod'
                }),
                db.push_checklist.insert({
                    'request': test1_request['id'],
                    'type': 'search-cleanup',
                    'target': 'post-verify-prod'
                }),
            ]
            db.execute_transaction_cb(checklist_queries, on_db_return)

            uri = "/checklist?id=%d" % fake_pushid
            response = self.fetch(uri)
            T.assert_equal(response.error, None)
            T.assert_not_in("No checklist items for this push", response.body)
            T.assert_not_in("multiple requests", response.body)
            T.assert_in("for testuser1", response.body)
            T.assert_in("Before Certifying - Do In Prod", response.body)

    def test_checklist_pushplans_tag(self):
        with fake_checklist_request():
            # insert fake data from FakeDataMixin
            fake_pushid = 2
            self.insert_pushes()
            self.insert_requests()
            test1_request = self.get_requests_by_user('testuser1')[0]
            self.insert_pushcontent(test1_request['id'], fake_pushid)

            # insert fake checklist data
            checklist_queries = [
                db.push_checklist.insert({
                    'request': test1_request['id'],
                    'type': 'pushplans',
                    'target': 'prod'
                }),
                db.push_checklist.insert({
                    'request': test1_request['id'],
                    'type': 'pushplans-cleanup',
                    'target': 'post-verify-stage'
                }),
            ]
            db.execute_transaction_cb(checklist_queries, on_db_return)

            uri = "/checklist?id=%d" % fake_pushid
            response = self.fetch(uri)
            T.assert_equal(response.error, None)
            T.assert_not_in("No checklist items for this push", response.body)
            T.assert_not_in("multiple requests", response.body)
            T.assert_in("for testuser1", response.body)
            T.assert_in("Before Certifying - Do In Stage", response.body)

    def test_hoods_checklists(self):
        with fake_checklist_request():
            # insert fake data from FakeDataMixin
            fake_pushid = 2
            self.insert_pushes()
            self.insert_requests()
            req = self.get_requests_by_user('testuser1')[0]
            self.insert_pushcontent(req['id'], fake_pushid)

            # insert fake checklist data
            checklist_queries = []
            checklist_items = (
                {'request': req['id'], 'type': 'hoods', 'target': 'stage'},
                {'request': req['id'], 'type': 'hoods', 'target': 'prod'},
                {'request': req['id'], 'type': 'hoods-cleanup', 'target': 'post-verify-stage'},
            )
            for checklist_item in checklist_items:
                checklist_queries.append(db.push_checklist.insert(checklist_item))

            db.execute_transaction_cb(checklist_queries, on_db_return)

            uri = "/checklist?id=%d" % fake_pushid
            response = self.fetch(uri)
            T.assert_equal(response.error, None)
            T.assert_not_in("No checklist items for this push", response.body)
            T.assert_in("Notify testuser1 to deploy Geoservices to stage", response.body)
            T.assert_in("Notify testuser1 to deploy Geoservices to prod", response.body)

class ChecklistToggleServletTest(T.TestCase, ServletTestMixin, FakeDataMixin):

    def get_handlers(self):
        return [get_servlet_urlspec(ChecklistToggleServlet)]

    def test_checklist_toggle_post(self):
        complete = 0
        checklist_item = [None]

        def check_toggle(success, db_results):
            assert success
            checklist_item[0] = db_results.fetchone()
            T.assert_equal(checklist_item[0]['complete'], complete)

        with fake_checklist_request():
            # insert fake data from FakeDataMixin
            self.insert_requests()
            test_request1 = self.get_requests_by_user('testuser1')[0]
            # insert fake checklist data
            checklist_query = db.push_checklist.insert({
                'request': test_request1['id'],
                'type': 'search',
                'target': 'prod'
            })
            db.execute_cb(checklist_query, on_db_return)

            checklist_toggle_query = db.push_checklist.select(
                db.push_checklist.c.request == test_request1['id']
            )

            complete = 0
            db.execute_cb(checklist_toggle_query, check_toggle)

            complete = 1
            response = self.fetch(
                "/checklisttoggle",
                method="POST",
                body=urllib.urlencode({'id': checklist_item[0]['id'], 'complete': complete})
            )
            T.assert_equal(response.error, None)

            db.execute_cb(checklist_toggle_query, check_toggle)


text:
This repository contains one of the two components of my Google Summer of Code'17 project with The Linux Foundation, i.e the **CPD libraries** for Frontend and Backend. The other component can be found [here](https://github.com/NilanjanaLodh/OpenPrinting_CUPS_Backend).

These libraries allow the CPD frontend and backends to communicate with each other over the D-Bus.
The Frontend library also provides some extra functionality to deal with Printers, Settings, etc. in a high level manner.

## Background

### The Problem

Printing out of desktop applications is managed by many very different dialogs, mostly depending on which GUI toolkit is used for an application. Some applications like even have their own dialogs, which expose different kind of printing options. This is confuses users a lot, having them to do the printing operation in many different ways. In addition, many dialogs are missing important features.

### The solution

The [Common Printing Dialog](https://wiki.ubuntu.com/CommonPrintingDialog) project aims to solve these problems provide a uniform printing experience on Linux Desktop Environments.

### My contributions

I specifically have contributed to the project in the following two ways :

 - Developed backend and frontend libraries which provides allows the frontend and backend to communicate to each other over the D-Bus. The frontend library also provides various abstractions for dealing with Printers , Options, etc, making it easier to develop a dialog. It is hosted in **this repository**.
 - Developed the CUPS Backend for the dialog; Available [here](https://github.com/NilanjanaLodh/OpenPrinting_CUPS_Backend).

## Dependencies

 - [CUPS](https://github.com/apple/cups/releases) : Version >= 2.2

 Installing bleeding edge release from [here](https://github.com/apple/cups/releases). (Preferable!)

 OR

`sudo apt install cups libcups2-dev`

 - GLIB 2.0 :
`sudo apt install libglib2.0-dev`

## Build and installation

    $ ./autogen
    $ ./configure
    $ make
    $ sudo make install
    $ sudo ldconfig

Use the sample frontend client to check that the library and the installed backends work as expected:

## Testing the library

The project also includes a sample command line frontend that you can use to test whether the installed library and print backends work as expected.

    $ cd demo/
    $ make
    $ ./print_frontend

The list of printers from various printers should start appearing automatically. Type `help` to get the list of available commands. Make sure to stop the frontend using the `stop` command only.

The library also provides support for serializing a printer. Use the `pickle-printer` command to serialize it, and run the `pickle_test` executable after that to deserialize and test it.

## Using the frontend and backend libraries in your code

To develop a frontend client you need to use the CPDFrontend library.

It has pkg-config support: `pkg-config --cflags --libs CPDFrontend`.
Include `CPDFrontend.h` in your code.

Similarly, to develop a backend you need to use the CPDBackend library.
It has pkg-config support: `pkg-config --cflags --libs CPDBackend`.
Include `CPDBackend.h` in your code.


text:
/// <reference path="fourslash.ts" />

// #37091

// @lib: dom
// @allowJs: true

// @Filename: globals.d.ts
//// declare var global: { console: Console };

// @Filename: index.js
//// window.f = function() { console/*1*/ }
//// self.g = function() { console/*2*/ }
//// global.h = function() { console/*3*/ }
//// globalThis.i = function() { console/*4*/ }

test.markerNames().forEach(marker => {
  verify.completions({
    marker,
    includes: [{
      name: "console",
      insertText: undefined,
      kind: "var",
      kindModifiers: "declare",
      sortText: completion.SortText.GlobalsOrKeywords
    }]
  }, {
    preferences: {
      includeInsertTextCompletions: true
    }
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;

namespace Faking.Test.Tests
{
	[TestFixtureAttribute]
    public class IntegerGeneratorTest
    {
        private Faker faker;

        [SetUp]
        public void Initialize()
        {
            faker = new Faker();
        }

        [Test]
        public void CreationTest()
        {
            var value = faker.Create<int>();
            Assert.IsInstanceOf<int>(value);
        }

        [Test]
        public void AgeTest()
        {
            var value = faker.Create<int>("age");
            Assert.IsTrue(value > 0 && value < 100);
        }

        [Test]
        public void DatesTest()
        {
            var value = faker.Create<long>("date");
            Assert.IsTrue(value > 1000000);

            value = faker.Create<int>("month");
            Assert.IsTrue(value > 0 && value < 13);

            value = faker.Create<int>("day");
            Assert.IsTrue(value > 0 && value < 30);

            value = faker.Create<int>("year");
            Assert.IsTrue(value > 1900);
        }
    }
}


text:
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

/**
 * Generated class for the CallbackPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-callback',
  templateUrl: 'callback.html',
})
export class CallbackPage {

  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad CallbackPage');
  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Apache log4cxx: Logging macros</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Logging macros

Defines

#define 	LOG4CXX_UNLIKELY(expr)   expr

 	Provides optimization hint to the compiler to optimize for the expression being false.

#define 	LOG4CXX_LOG(logger, level, message)

 	Logs a message to a specified logger with a specified level.

#define 	LOG4CXX_LOGLS(logger, level, message)

 	Logs a message to a specified logger with a specified level.

#define 	LOG4CXX_DEBUG(logger, message)

 	Logs a message to a specified logger with the DEBUG level.

#define 	LOG4CXX_TRACE(logger, message)

 	Logs a message to a specified logger with the TRACE level.

#define 	LOG4CXX_INFO(logger, message)

 	Logs a message to a specified logger with the INFO level.

#define 	LOG4CXX_WARN(logger, message)

 	Logs a message to a specified logger with the WARN level.

#define 	LOG4CXX_ERROR(logger, message)

 	Logs a message to a specified logger with the ERROR level.

#define 	LOG4CXX_ASSERT(logger, condition, message)

 	Logs a error if the condition is not true.

#define 	LOG4CXX_FATAL(logger, message)

 	Logs a message to a specified logger with the FATAL level.

#define 	LOG4CXX_L7DLOG(logger, level, key)

 	Logs a localized message with no parameter.

#define 	LOG4CXX_L7DLOG1(logger, level, key, p1)

 	Logs a localized message with one parameter.

#define 	LOG4CXX_L7DLOG2(logger, level, key, p1, p2)

 	Logs a localized message with two parameters.

#define 	LOG4CXX_L7DLOG3(logger, level, key, p1, p2, p3)

 	Logs a localized message with three parameters.

Define Documentation

          #define LOG4CXX_ASSERT
          (
          logger,

          condition,

          message

           )

Value:

{ \
        if (!(condition) && logger->isErrorEnabled()) {\
           ::log4cxx::helpers::MessageBuffer oss_; \
           logger->forcedLog(::log4cxx::Level::getError(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }}

Logs a error if the condition is not true.

Parameters:

	logger 	the logger to be used.

	condition 	condition

	message 	the message string to log.

          #define LOG4CXX_DEBUG
          (
          logger,

          message

           )

Value:

{ \
        if (LOG4CXX_UNLIKELY(logger->isDebugEnabled())) {\
           ::log4cxx::helpers::MessageBuffer oss_; \
           logger->forcedLog(::log4cxx::Level::getDebug(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }}

Logs a message to a specified logger with the DEBUG level.

Parameters:

	logger 	the logger to be used.

	message 	the message string to log.

          #define LOG4CXX_ERROR
          (
          logger,

          message

           )

Value:

{ \
        if (logger->isErrorEnabled()) {\
           ::log4cxx::helpers::MessageBuffer oss_; \
           logger->forcedLog(::log4cxx::Level::getError(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }}

Logs a message to a specified logger with the ERROR level.

Parameters:

	logger 	the logger to be used.

	message 	the message string to log.

          #define LOG4CXX_FATAL
          (
          logger,

          message

           )

Value:

{ \
        if (logger->isFatalEnabled()) {\
           ::log4cxx::helpers::MessageBuffer oss_; \
           logger->forcedLog(::log4cxx::Level::getFatal(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }}

Logs a message to a specified logger with the FATAL level.

Parameters:

	logger 	the logger to be used.

	message 	the message string to log.

          #define LOG4CXX_INFO
          (
          logger,

          message

           )

Value:

{ \
        if (logger->isInfoEnabled()) {\
           ::log4cxx::helpers::MessageBuffer oss_; \
           logger->forcedLog(::log4cxx::Level::getInfo(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }}

Logs a message to a specified logger with the INFO level.

Parameters:

	logger 	the logger to be used.

	message 	the message string to log.

          #define LOG4CXX_L7DLOG
          (
          logger,

          level,

          key

           )

Value:

{ \
        if (logger->isEnabledFor(level)) {\
        logger->l7dlog(level, key, LOG4CXX_LOCATION); }}

Logs a localized message with no parameter.

Parameters:

	logger 	the logger to be used.

	level 	the level to log.

	key 	the key to be searched in the resourceBundle of the logger.

          #define LOG4CXX_L7DLOG1
          (
          logger,

          level,

          key,

          p1

           )

Value:

{ \
        if (logger->isEnabledFor(level)) {\
        logger->l7dlog(level, key, LOG4CXX_LOCATION, p1); }}

Logs a localized message with one parameter.

Parameters:

	logger 	the logger to be used.

	level 	the level to log.

	key 	the key to be searched in the resourceBundle of the logger.

	p1 	the unique parameter.

          #define LOG4CXX_L7DLOG2
          (
          logger,

          level,

          key,

          p1,

          p2

           )

Value:

{ \
        if (logger->isEnabledFor(level)) {\
        logger->l7dlog(level, key, LOG4CXX_LOCATION, p1, p2); }}

Logs a localized message with two parameters.

Parameters:

	logger 	the logger to be used.

	level 	the level to log.

	key 	the key to be searched in the resourceBundle of the logger.

	p1 	the first parameter.

	p2 	the second parameter.

          #define LOG4CXX_L7DLOG3
          (
          logger,

          level,

          key,

          p1,

          p2,

          p3

           )

Value:

{ \
        if (logger->isEnabledFor(level)) {\
        logger->l7dlog(level, key, LOG4CXX_LOCATION, p1, p2, p3); }}

Logs a localized message with three parameters.

Parameters:

	logger 	the logger to be used.

	level 	the level to log.

	key 	the key to be searched in the resourceBundle of the logger.

	p1 	the first parameter.

	p2 	the second parameter.

	p3 	the third parameter.

          #define LOG4CXX_LOG
          (
          logger,

          level,

          message

           )

Value:

{ \
        if (logger->isEnabledFor(level)) {\
           ::log4cxx::helpers::MessageBuffer oss_; \
           logger->forcedLog(level, oss_.str(oss_ << message), LOG4CXX_LOCATION); } }

Logs a message to a specified logger with a specified level.

Parameters:

	logger 	the logger to be used.

	level 	the level to log.

	message 	the message string to log.

          #define LOG4CXX_LOGLS
          (
          logger,

          level,

          message

           )

Value:

{ \
        if (logger->isEnabledFor(level)) {\
           ::log4cxx::helpers::LogCharMessageBuffer oss_; \
           logger->forcedLog(level, oss_.str(oss_ << message), LOG4CXX_LOCATION); } }

Logs a message to a specified logger with a specified level.

Parameters:

	logger 	the logger to be used.

	level 	the level to log.

	message 	the message string to log in the internal encoding.

          #define LOG4CXX_TRACE
          (
          logger,

          message

           )

Value:

{ \
        if (LOG4CXX_UNLIKELY(logger->isTraceEnabled())) {\
           ::log4cxx::helpers::MessageBuffer oss_; \
           logger->forcedLog(::log4cxx::Level::getTrace(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }}

Logs a message to a specified logger with the TRACE level.

Parameters:

	logger 	the logger to be used.

	message 	the message string to log.

          #define LOG4CXX_UNLIKELY
          (
          expr

           )
             expr

Provides optimization hint to the compiler to optimize for the expression being false.

Parameters:

	expr 	boolean expression.

Returns:

value of expression.

          #define LOG4CXX_WARN
          (
          logger,

          message

           )

Value:

{ \
        if (logger->isWarnEnabled()) {\
           ::log4cxx::helpers::MessageBuffer oss_; \
           logger->forcedLog(::log4cxx::Level::getWarn(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }}

Logs a message to a specified logger with the WARN level.

Parameters:

	logger 	the logger to be used.

	message 	the message string to log.


text:
import Ember from 'ember';
import layout from '../templates/components/bootstrap-textarea';
import InputableMixin from '../mixins/components/inputable';

export default Ember.Component.extend(InputableMixin, {
  layout: layout,

  classNames: ['form-group', 'bootstrap-textarea-component'],
  classNameBindings: ['hasSuccess:has-success', 'hasWarning:has-warning', 'showError:has-error'],

  placeholder: null,
  value: null,
  type: null,
  tabindex: 0,
  required: false,
});