text:
package com.suru.springtest.offers.filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

/**
 * Servlet Filter implementation class TestFilter
 */
//@WebFilter(urlPatterns = "/*", filterName = "TestFilter")
public class TestFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public TestFilter() {
		System.out.println("filter constructor");
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		System.out.println("filter destroy");
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("filter url: " + ((HttpServletRequest) request).getRequestURI());
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		System.out.println("filter init: " + fConfig);
	}

}


text:
package cst

import "github.com/google/gapid/core/data/compare"

// Node is a Fragment in a cst that represents unskipped tokens.
type Node interface {
	Fragment
	// Parent returns the Branch that this node is under.
	Parent() *Branch
	// SetParent replaces the Branch that this node is under.
	SetParent(*Branch)
	// Prefix returns the set of skippable fragments associated with this Node
	// that precede it in the stream. Association is defined by the Skip function
	// in use.
	Prefix() Separator
	// AddPrefix adds more fragments to the Prefix list.
	AddPrefix(Separator)
	// Suffix returns the set of skippable fragments associated with this Node
	// that follow it in the stream. Association is defined by the Skip function
	// in use, the default is until the end of the line.
	Suffix() Separator
	// AddSuffix adds more fragments to the Suffix list.
	AddSuffix(Separator)
}

// NodeBase implements the non-fragment parts of the Node interface.
// NodeBase is intended to be used as an anonymous field of types that implement
// the Node interface.
type NodeBase struct {
	Branch *Branch
	Pre    Separator
	Post   Separator
}

// Parent returns the Branch that this node is under.
func (n *NodeBase) Parent() *Branch {
	return n.Branch
}

// SetParent replaces the Branch that this node is under.
func (n *NodeBase) SetParent(parent *Branch) {
	n.Branch = parent
}

// Prefix returns the set of skippable fragments associated with this Node
// that precede it in the stream. Association is defined by the Skip function
// in use.
func (n *NodeBase) Prefix() Separator {
	return n.Pre
}

// AddPrefix adds more fragments to the Prefix list.
func (n *NodeBase) AddPrefix(s Separator) {
	n.Pre = append(n.Pre, s...)
}

// Suffix returns the set of skippable fragments associated with this Node
// that follow it in the stream. Association is defined by the Skip function
// in use, the default is until the end of the line.
func (n *NodeBase) Suffix() Separator {
	return n.Post
}

// AddSuffix adds more fragments to the Suffix list.
func (n *NodeBase) AddSuffix(s Separator) {
	n.Post = append(n.Post, s...)
}

func compareNodes(c compare.Comparator, reference, value NodeBase) {
	c.With(c.Path.Member("Prefix", reference, value)).Compare(reference.Pre, value.Pre)
	c.With(c.Path.Member("Suffix", reference, value)).Compare(reference.Post, value.Post)
}

func init() {
	compare.Register(compareNodes)
}

redpajama_set_name: RedPajamaGithub


text:
package com.bbn.bue.common.temporal;

import org.joda.time.Interval;
import org.joda.time.Period;

/**
 * Utilities for working with JodaTime {@link Interval}s.
 */
public final class IntervalUtils {

  private IntervalUtils() {
    throw new UnsupportedOperationException();
  }

  /**
   * Move both the start and end of an {@link Interval} into the past by the duration of
   * {@code period}.
   */
  public static Interval minus(final Interval interval, final Period period) {
    return new Interval(interval.getStart().minus(period),
        interval.getEnd().minus(period));
  }

  /**
   * Move both the start and end of an {@link Interval} into the future by the duration of
   * {@code period}.
   */
  public static Interval plus(final Interval interval, final Period period) {
    return new Interval(interval.getStart().plus(period),
        interval.getEnd().plus(period));
  }

  /**
   * Is {@code interval} contained entirely within one calendar day?
   */
  public static boolean containedInDay(final Interval interval) {
    return interval.getStart().dayOfMonth().toInterval().contains(interval);
  }

  /**
   * Is {@code interval} contained entirely within one calendar month?
   */
  public static boolean containedInMonth(final Interval interval) {
    return interval.getStart().monthOfYear().toInterval().contains(interval);
  }

  /**
   * Is {@code interval} contained entirely within one calendar year?
   */
  public static boolean containedInYear(final Interval interval) {
    return interval.getStart().year().toInterval().contains(interval);
  }
}


text:
package org.jboss.hal.client.runtime.subsystem.messaging;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import javax.inject.Inject;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.shared.proxy.PlaceRequest;
import elemental2.dom.HTMLElement;
import org.jboss.hal.ballroom.dialog.DialogFactory;
import org.jboss.hal.client.runtime.subsystem.messaging.Destination.Type;
import org.jboss.hal.core.finder.ColumnActionFactory;
import org.jboss.hal.core.finder.Finder;
import org.jboss.hal.core.finder.FinderColumn;
import org.jboss.hal.core.finder.FinderPathFactory;
import org.jboss.hal.core.finder.FinderSegment;
import org.jboss.hal.core.finder.ItemAction;
import org.jboss.hal.core.finder.ItemActionFactory;
import org.jboss.hal.core.finder.ItemDisplay;
import org.jboss.hal.core.finder.ItemsProvider;
import org.jboss.hal.core.mvp.Places;
import org.jboss.hal.dmr.Composite;
import org.jboss.hal.dmr.CompositeResult;
import org.jboss.hal.dmr.ModelNode;
import org.jboss.hal.dmr.NamedNode;
import org.jboss.hal.dmr.Operation;
import org.jboss.hal.dmr.ResourceAddress;
import org.jboss.hal.dmr.dispatch.Dispatcher;
import org.jboss.hal.meta.AddressTemplate;
import org.jboss.hal.meta.StatementContext;
import org.jboss.hal.meta.security.Constraint;
import org.jboss.hal.resources.Icons;
import org.jboss.hal.resources.Ids;
import org.jboss.hal.resources.Names;
import org.jboss.hal.resources.Resources;
import org.jboss.hal.resources.Strings;
import org.jboss.hal.spi.AsyncColumn;
import org.jboss.hal.spi.Message;
import org.jboss.hal.spi.MessageEvent;
import org.jboss.hal.spi.Requires;

import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static org.jboss.hal.client.runtime.subsystem.messaging.AddressTemplates.*;
import static org.jboss.hal.client.runtime.subsystem.messaging.Destination.Type.DEPLOYMENT_RESOURCES;
import static org.jboss.hal.client.runtime.subsystem.messaging.Destination.Type.SUBSYSTEM_RESOURCES;
import static org.jboss.hal.core.finder.FinderColumn.RefreshMode.RESTORE_SELECTION;
import static org.jboss.hal.dmr.ModelDescriptionConstants.*;
import static org.jboss.hal.resources.CSS.fontAwesome;

@AsyncColumn(Ids.MESSAGING_SERVER_DESTINATION_RUNTIME)
@Requires({MESSAGING_CORE_QUEUE_ADDRESS,
        MESSAGING_JMS_QUEUE_ADDRESS,
        MESSAGING_JMS_TOPIC_ADDRESS,
        MESSAGING_DEPLOYMENT_JMS_QUEUE_ADDRESS,
        MESSAGING_DEPLOYMENT_JMS_TOPIC_ADDRESS})
public class DestinationColumn extends FinderColumn<Destination> {

    private final Dispatcher dispatcher;
    private final EventBus eventBus;
    private final Resources resources;

    @Inject
    public DestinationColumn(Finder finder,
            ColumnActionFactory columnActionFactory,
            ItemActionFactory itemActionFactory,
            FinderPathFactory finderPathFactory,
            Places places,
            Dispatcher dispatcher,
            EventBus eventBus,
            StatementContext statementContext,
            Resources resources) {

        super(new Builder<Destination>(finder, Ids.MESSAGING_SERVER_DESTINATION_RUNTIME, Names.DESTINATION)
                .columnAction(columnActionFactory.refresh(Ids.MESSAGING_SERVER_DESTINATION_REFRESH))
                .onPreview(item -> new DestinationPreview(item, finderPathFactory, places, dispatcher, resources))
                .useFirstActionAsBreadcrumbHandler()
                .pinnable()
                .showCount()
                .filterDescription(resources.messages().destinationFilterDescription())
                .withFilter());

        this.dispatcher = dispatcher;
        this.eventBus = eventBus;
        this.resources = resources;

        ItemsProvider<Destination> itemsProvider = (context, callback) -> {
            // extract server name from the finder path
            FinderSegment segment = context.getPath().findColumn(Ids.MESSAGING_SERVER_RUNTIME);
            if (segment != null) {
                String server = segment.getItemTitle();
                List<Operation> operations = new ArrayList<>();
                for (Type type : SUBSYSTEM_RESOURCES) {
                    ResourceAddress address = MESSAGING_SERVER_TEMPLATE.append(type.resource + "=*")
                            .resolve(statementContext, server);
                    operations.add(new Operation.Builder(address, READ_RESOURCE_OPERATION)
                            .param(INCLUDE_RUNTIME, true)
                            .build());
                }
                for (Type type : DEPLOYMENT_RESOURCES) {
                    ResourceAddress address = MESSAGING_DEPLOYMENT_TEMPLATE.append(type.resource + "=*")
                            .resolve(statementContext);
                    operations.add(new Operation.Builder(address, READ_RESOURCE_OPERATION)
                            .param(INCLUDE_RUNTIME, true)
                            .build());
                }
                dispatcher.execute(new Composite(operations), (CompositeResult result) -> {
                    List<Destination> destinations = new ArrayList<>();
                    for (ModelNode step : result) {
                        if (!step.isFailure()) {
                            for (ModelNode node : step.get(RESULT).asList()) {
                                AddressTemplate template = AddressTemplate.of(new ResourceAddress(node.get(ADDRESS)));
                                if (!template.firstName().equals(HOST)) {
                                    //Add correct host and server before the messaging address if it is missing
                                    template = SELECTED_HOST_SELECTED_SERVER_TEMPLATE.append(template);
                                }
                                destinations.add(new Destination(template.resolve(statementContext), node.get(RESULT)));
                            }
                        }
                    }
                    destinations.sort(Comparator.comparing(NamedNode::getName));
                    callback.onSuccess(destinations);
                });
            } else {
                callback.onSuccess(emptyList());
            }
        };
        setItemsProvider(itemsProvider);
        setBreadcrumbItemsProvider(
                (context, callback) -> itemsProvider.get(context, new AsyncCallback<List<Destination>>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        callback.onFailure(caught);
                    }

                    @Override
                    public void onSuccess(List<Destination> result) {
                        callback.onSuccess(result.stream()
                                .filter(d -> d.type == Type.QUEUE || d.type == Type.JMS_QUEUE)
                                .collect(toList()));
                    }
                }));

        setItemRenderer(item -> new ItemDisplay<Destination>() {
            @Override
            public String getId() {
                return Ids.destination(item.getDeployment(), item.getSubdeployment(), messageServer(), item.type.name(),
                        item.getName());
            }

            @Override
            public String getTitle() {
                return item.getName();
            }

            @Override
            public HTMLElement element() {
                if (item.fromDeployment()) {
                    return ItemDisplay.withSubtitle(item.getName(), item.getPath());
                }
                return null;
            }

            @Override
            public String getTooltip() {
                return item.type.type;
            }

            @Override
            public HTMLElement getIcon() {
                if (item.isPaused()) {
                    return Icons.paused();
                } else {
                    switch (item.type) {
                        case JMS_QUEUE:
                            return Icons.custom(fontAwesome("long-arrow-right"));
                        case JMS_TOPIC:
                            return Icons.custom(fontAwesome("arrows"));
                        case QUEUE:
                            return Icons.custom(fontAwesome("cog"));
                        default:
                            return Icons.unknown();
                    }
                }
            }

            @Override
            public String getFilterData() {
                return item.getName() + " " + item.type.type +
                        (item.fromDeployment() ? " " + Names.DEPLOYMENT : "");
            }

            @Override
            public List<ItemAction<Destination>> actions() {
                List<ItemAction<Destination>> actions = new ArrayList<>();

                if (item.type == Type.JMS_QUEUE || item.type == Type.QUEUE) {
                    PlaceRequest.Builder builder = places.selectedServer(item.type.token);
                    if (item.fromDeployment()) {
                        builder.with(DEPLOYMENT, item.getDeployment());
                        if (item.getSubdeployment() != null) {
                            builder.with(SUBDEPLOYMENT, item.getSubdeployment());
                        }
                    }
                    builder.with(Ids.MESSAGING_SERVER, messageServer()).with(NAME, item.getName());
                    actions.add(itemActionFactory.view(builder.build()));

                    if (item.isPaused()) {
                        actions.add(new ItemAction.Builder<Destination>()
                                .title(resources.constants().resume())
                                .constraint(Constraint.executable(item.template(), RESUME))
                                .handler(DestinationColumn.this::resume)
                                .build());
                    } else {
                        actions.add(new ItemAction.Builder<Destination>()
                                .title(resources.constants().pause())
                                .constraint(Constraint.executable(item.template(), PAUSE))
                                .handler(DestinationColumn.this::pause)
                                .build());
                    }

                } else if (item.type == Type.JMS_TOPIC) {
                    actions.add(new ItemAction.Builder<Destination>()
                            .title(Strings.abbreviateMiddle(resources.constants().dropSubscriptions(), 16))
                            .constraint(Constraint.executable(item.template(), DROP_ALL_SUBSCRIPTIONS))
                            .handler(DestinationColumn.this::dropSubscriptions)
                            .build());
                }
                return actions;
            }
        });
    }

    private String messageServer() {
        String server = UNDEFINED;
        FinderSegment<?> segment = getFinder().getContext().getPath().findColumn(Ids.MESSAGING_SERVER_RUNTIME);
        if (segment != null) {
            server = Ids.extractMessagingServer(segment.getItemId());
        }
        return server;
    }

    private void resume(Destination destination) {
        Operation operation = new Operation.Builder(destination.getAddress(), RESUME).build();
        dispatcher.execute(operation, result -> {
            refresh(RESTORE_SELECTION);
            MessageEvent.fire(eventBus,
                    Message.success(resources.messages().resumeQueueSuccess(destination.getName())));
        });
    }

    private void pause(Destination destination) {
        Operation operation = new Operation.Builder(destination.getAddress(), PAUSE).build();
        dispatcher.execute(operation, result -> {
            refresh(RESTORE_SELECTION);
            MessageEvent.fire(eventBus, Message.success(resources.messages().pauseQueueSuccess(destination.getName())));
        });
    }

    private void dropSubscriptions(Destination destination) {
        DialogFactory.showConfirmation(resources.constants().dropSubscriptions(),
                resources.messages().dropSubscriptionsQuestion(destination.getName()), () -> {
                    Operation operation = new Operation.Builder(destination.getAddress(), DROP_ALL_SUBSCRIPTIONS)
                            .build();
                    dispatcher.execute(operation, result -> {
                        refresh(RESTORE_SELECTION);
                        MessageEvent.fire(eventBus,
                                Message.success(resources.messages().dropSubscriptionsSuccess(destination.getName())));
                    });
                });
    }
}


text:
{-# LANGUAGE PackageImports, TupleSections #-}

import "monads-tf" Control.Monad.State
import "monads-tf" Control.Monad.Error
import Control.Applicative

data AB = A | B deriving Show
data S = Rec S AB | Atom AB deriving Show

-- X = S
-- S = X b | a

data Fail = Fail | LR deriving Show
instance Error Fail where

type Result a = Either Fail (a, Derivs)

data Derivs = Derivs {
	getX :: Result S,
	getS :: Result S,
	chars :: Result AB
 } deriving Show

parse :: [AB] -> Derivs
parse abstr = d
	where
	d = Derivs x s c
	x = runStateT ruleX d { getX = Left LR }
	s = runStateT ruleS d { getS = Left LR }
	c = flip runStateT d $ do
		case abstr of
			ab : abs -> do
				put $ parse abs
				return ab
			_ -> throwError Fail

ruleX :: StateT Derivs (Either Fail) S
ruleX = catchError (StateT getS) $ \e -> case e of
-- ruleX = catchError ruleS $ \e -> case e of
{-
	LR -> grow ruleX
		(\mx d -> d { getX = mx `runStateT` d })
		(throwError Fail)
-}
	_ -> throwError Fail

ruleS :: StateT Derivs (Either Fail) S
ruleS = foldl1 mplus [ catchError (do
	s <- StateT getX
--	s <- ruleX
	c <- StateT chars
	return $ Rec s c) $ \e -> case e of
{-
		LR -> grow ruleS
			(\mx d -> d { getS = mx `runStateT` d })
			(throwError Fail)
-}
		_ -> throwError Fail
 , do	c <- StateT chars
	return $ Atom c
 ]

grow :: (MonadError m, MonadState m, Functor m) =>
	m a -> (m a -> StateType m -> StateType m) -> m a -> m a
grow action update mx = do
	modify $ update mx
	(b, r) <- catchError ((True ,) <$> action) $ const $
		(False ,) <$> mx
	if b then grow action update (return r) else return r

getParseResult :: Derivs -> S
getParseResult d = case getS d of
	Right (r, _) -> r
	_ -> error "parse error"


text:
package inspect

import (
	"bytes"
	"context"
	"testing"

	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/config"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/inspect"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/parser"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/util/stringslice"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/yaml"
	"github.com/GoogleContainerTools/skaffold/proto/v1"
	"github.com/GoogleContainerTools/skaffold/testutil"
)

func TestModifyGcbBuildEnv(t *testing.T) {
	tests := []struct {
		description     string
		profile         string
		modules         []string
		buildEnvOpts    inspect.BuildEnvOptions
		expectedConfigs []string
		errCode         proto.StatusCode
		strict          bool
	}{
		{
			description:  "modify default pipeline; strict true",
			buildEnvOpts: inspect.BuildEnvOptions{ProjectID: "project2"},
			strict:       true,
			expectedConfigs: []string{
				`apiVersion: ""
kind: ""
metadata:
  name: cfg1
requires:
- path: path/to/cfg2
build:
  googleCloudBuild:
    projectId: project2
profiles:
- name: p1
  build:
    googleCloudBuild:
      projectId: project1
- name: p2
  build:
    cluster: {}
`, ``,
			},
		},
		{
			description:  "modify profile pipeline; strict true",
			strict:       true,
			profile:      "p1",
			buildEnvOpts: inspect.BuildEnvOptions{ProjectID: "project2"},
			expectedConfigs: []string{
				`apiVersion: ""
kind: ""
metadata:
  name: cfg1
requires:
- path: path/to/cfg2
build:
  googleCloudBuild:
    projectId: project1
profiles:
- name: p1
  build:
    googleCloudBuild:
      projectId: project2
- name: p2
  build:
    cluster: {}
`, `apiVersion: ""
kind: ""
metadata:
  name: cfg2
build:
  local: {}
profiles:
- name: p1
  build:
    googleCloudBuild:
      projectId: project2
`,
			},
		},
		{
			description:  "add to non-existing profile; strict true",
			strict:       true,
			profile:      "p3",
			buildEnvOpts: inspect.BuildEnvOptions{MachineType: "machine2", Concurrency: 2},
			errCode:      proto.StatusCode_INSPECT_PROFILE_NOT_FOUND_ERR,
		},
		{
			description:  "add to profile with wrong build env type; strict true",
			strict:       true,
			profile:      "p2",
			buildEnvOpts: inspect.BuildEnvOptions{MachineType: "machine2", Concurrency: 2},
			errCode:      proto.StatusCode_INSPECT_BUILD_ENV_INCORRECT_TYPE_ERR,
		},
		{
			description:  "modify default pipeline; strict false",
			buildEnvOpts: inspect.BuildEnvOptions{ProjectID: "project2"},
			strict:       false,
			expectedConfigs: []string{
				`apiVersion: ""
kind: ""
metadata:
  name: cfg1
requires:
- path: path/to/cfg2
build:
  googleCloudBuild:
    projectId: project2
profiles:
- name: p1
  build:
    googleCloudBuild:
      projectId: project1
- name: p2
  build:
    cluster: {}
`, ``,
			},
		},
		{
			description:  "modify profile pipeline; strict false",
			strict:       false,
			profile:      "p1",
			buildEnvOpts: inspect.BuildEnvOptions{ProjectID: "project2"},
			expectedConfigs: []string{
				`apiVersion: ""
kind: ""
metadata:
  name: cfg1
requires:
- path: path/to/cfg2
build:
  googleCloudBuild:
    projectId: project1
profiles:
- name: p1
  build:
    googleCloudBuild:
      projectId: project2
- name: p2
  build:
    cluster: {}
`, `apiVersion: ""
kind: ""
metadata:
  name: cfg2
build:
  local: {}
profiles:
- name: p1
  build:
    googleCloudBuild:
      projectId: project2
`,
			},
		},
		{
			description:  "add to non-existing profile; strict false",
			strict:       false,
			profile:      "p3",
			buildEnvOpts: inspect.BuildEnvOptions{MachineType: "machine2", Concurrency: 2},
			errCode:      proto.StatusCode_INSPECT_PROFILE_NOT_FOUND_ERR,
		},
		{
			description:  "add to profile with wrong build env type; strict false",
			strict:       false,
			profile:      "p2",
			buildEnvOpts: inspect.BuildEnvOptions{MachineType: "machine2", Concurrency: 2},
			expectedConfigs: []string{
				`apiVersion: ""
kind: ""
metadata:
  name: cfg1
requires:
- path: path/to/cfg2
build:
  googleCloudBuild:
    projectId: project1
profiles:
- name: p1
  build:
    googleCloudBuild:
      projectId: project1
- name: p2
  build:
    cluster: {}
`, `apiVersion: ""
kind: ""
metadata:
  name: cfg2
build:
  local: {}
profiles:
- name: p1
  build:
    googleCloudBuild:
      projectId: project1
`,
			},
		},
	}
	for _, test := range tests {
		testutil.Run(t, test.description, func(t *testutil.T) {
			configSet := parser.SkaffoldConfigSet{
				&parser.SkaffoldConfigEntry{SkaffoldConfig: &latest.SkaffoldConfig{
					Metadata:     latest.Metadata{Name: "cfg1"},
					Dependencies: []latest.ConfigDependency{{Path: pathToCfg2}},
					Pipeline:     latest.Pipeline{Build: latest.BuildConfig{BuildType: latest.BuildType{GoogleCloudBuild: &latest.GoogleCloudBuild{ProjectID: "project1"}}}},
					Profiles: []latest.Profile{
						{Name: "p1", Pipeline: latest.Pipeline{Build: latest.BuildConfig{BuildType: latest.BuildType{GoogleCloudBuild: &latest.GoogleCloudBuild{ProjectID: "project1"}}}}},
						{Name: "p2", Pipeline: latest.Pipeline{Build: latest.BuildConfig{BuildType: latest.BuildType{Cluster: &latest.ClusterDetails{}}}}},
					}}, SourceFile: pathToCfg1, IsRootConfig: true, SourceIndex: 0},
				&parser.SkaffoldConfigEntry{SkaffoldConfig: &latest.SkaffoldConfig{
					Metadata: latest.Metadata{Name: "cfg2"},
					Pipeline: latest.Pipeline{Build: latest.BuildConfig{BuildType: latest.BuildType{LocalBuild: &latest.LocalBuild{}}}},
					Profiles: []latest.Profile{
						{Name: "p1", Pipeline: latest.Pipeline{Build: latest.BuildConfig{BuildType: latest.BuildType{GoogleCloudBuild: &latest.GoogleCloudBuild{ProjectID: "project1"}}}}},
					}}, SourceFile: pathToCfg2, SourceIndex: 0},
			}
			t.Override(&inspect.GetConfigSet, func(ctx context.Context, opts config.SkaffoldOptions) (parser.SkaffoldConfigSet, error) {
				if len(opts.ConfigurationFilter) == 0 || stringslice.Contains(opts.ConfigurationFilter, "cfg1") {
					return configSet, nil
				}
				if stringslice.Contains(opts.ConfigurationFilter, "cfg2") {
					return parser.SkaffoldConfigSet{configSet[0]}, nil
				}
				return nil, nil
			})
			t.Override(&inspect.ReadFileFunc, func(filename string) ([]byte, error) {
				if filename == pathToCfg1 {
					return yaml.MarshalWithSeparator([]*latest.SkaffoldConfig{configSet[0].SkaffoldConfig})
				} else if filename == pathToCfg2 {
					return yaml.MarshalWithSeparator([]*latest.SkaffoldConfig{configSet[1].SkaffoldConfig})
				}
				t.FailNow()
				return nil, nil
			})
			var actualCfg1, actualCfg2 string
			t.Override(&inspect.WriteFileFunc, func(filename string, data []byte) error {
				switch filename {
				case pathToCfg1:
					actualCfg1 = string(data)
				case pathToCfg2:
					actualCfg2 = string(data)
				default:
					t.FailNow()
				}
				return nil
			})

			var buf bytes.Buffer
			err := ModifyGcbBuildEnv(context.Background(), &buf, inspect.Options{OutFormat: "json", Modules: test.modules, Profile: test.profile, BuildEnvOptions: test.buildEnvOpts, Strict: test.strict})
			t.CheckNoError(err)
			if test.errCode == proto.StatusCode_OK {
				t.CheckDeepEqual(test.expectedConfigs[0], actualCfg1)
				t.CheckDeepEqual(test.expectedConfigs[1], actualCfg2)
			} else {
				t.CheckContains(test.errCode.String(), buf.String())
			}
		})
	}
}


text:
// -*- tab-width: 4 -*-
package Jet.Chunk;

import Jet.Tipster.*;

/**
 *  a trainable classifier for assigning tags to a sequence of tokens
 */

public abstract class TokenClassifier {

	public abstract void train (Document doc, Annotation[] tokens, String[] tags);

	public abstract void createModel ();

	public abstract void store (String fileName);

	public abstract void load (String fileName);

	public abstract String[] viterbi (Document doc, Annotation[] tokens);

	public String[] nextBest () {
		return null;
	}

	public double getLocalMargin (Document doc, Annotation[] tokens,
	                              String excludedTag, int excludedTagStart,
	                              int excludedTagEnd) {
		return 0.0;
	}

	public void recordMargin() {
	}

	public double getPathProbability() {
		return 0.0;
	}

	public double getMargin() {
		return 0.0;
	}

	public void newDocument () {
	}

}


text:
'use strict';

const test = require('tape-async');
const Person = require('./fixtures/person');

test('Field Metadata contains properties size', function *(t) {
  t.equal(Person.props.name.size, 5);
});

test('Throw TypeError if string value length is greater than size', function *(t) {
  t.plan(2);
  return new Promise(() => {
    return new Person({name: '123456', surname: 'g', age: 12});
  }).catch(err => {
    t.equal(err.constructor.name, 'TypeError');
    t.equal(err.message, 'Invalid value for "name" field:\n "123456" length is more than 5 characters.');
  });
});


text:
from nova import db
from nova.scheduler import filters

class TypeAffinityFilter(filters.BaseHostFilter):
    """TypeAffinityFilter doesn't allow more than one VM type per host.

    Note: this works best with ram_weight_multiplier
    (spread) set to 1 (default).
    """

    def host_passes(self, host_state, filter_properties):
        """Dynamically limits hosts to one instance type

        Return False if host has any instance types other then the requested
        type. Return True if all instance types match or if host is empty.
        """

        instance_type = filter_properties.get('instance_type')
        context = filter_properties['context'].elevated()
        instances_other_type = db.instance_get_all_by_host_and_not_type(
                     context, host_state.host, instance_type['id'])
        return len(instances_other_type) == 0

class AggregateTypeAffinityFilter(filters.BaseHostFilter):
    """AggregateTypeAffinityFilter limits instance_type by aggregate

    return True if no instance_type key is set or if the aggregate metadata
    key 'instance_type' has the instance_type name as a value
    """

    # Aggregate data does not change within a request
    run_filter_once_per_request = True

    def host_passes(self, host_state, filter_properties):
        instance_type = filter_properties.get('instance_type')
        context = filter_properties['context'].elevated()
        metadata = db.aggregate_metadata_get_by_host(
                     context, host_state.host, key='instance_type')
        return (len(metadata) == 0 or
                instance_type['name'] in metadata['instance_type'])


text:
<?php

/**
 * Base class for a Field Implementation.
 *
 * All Fields must inherit form this Model.
 */
namespace Rocket\Entities;

use Illuminate\Database\Eloquent\Model;
use Rocket\Entities\Exceptions\InvalidValueException;

/**
 * Field
 *
 * @property int $id The field id
 * @property string $name The name of the field
 * @property int $weight The order of this field
 * @property int $revision_id The field's revision id
 * @property-read \DateTime $created_at
 * @property-read \DateTime $updated_at
 */
abstract class Field extends Model
{
    /**
     * Convert the model instance to an array.
     *
     * @return array
     */
    public function toArray()
    {
        return $this->getAttribute('value');
    }

    /**
     * Get the revisions for this class
     *
     * @codeCoverageIgnore
     */
    public function revision()
    {
        return $this->belongsTo(Revision::class);
    }

    /**
     * Validate and set the value
     *
     * @param  mixed  $value
     */
    public function setValueAttribute($value)
    {
        if (!$this->isValid($value)) {
            throw new InvalidValueException("The value in the field '" . get_class($this) . "' is invalid");
        }

        $this->attributes['value'] = $this->prepareValue($value);
    }

    /**
     * Prepare the value to be stored.
     *
     * Particularly useful for dates or very special fields
     *
     * @param mixed $value The value to prepare
     * @return mixed
     */
    protected function prepareValue($value)
    {
        return $value;
    }

    /**
     * Checks if a field is valid
     *
     * @param mixed $value The value to validate
     * @return bool
     */
    abstract protected function isValid($value);
}


text:
export UISelectors from './UISelectors';
export RouteSelectors from './RouteSelectors';


text:
class WebUrlRequestInterceptor : public QWebEngineUrlRequestInterceptor
{
    Q_OBJECT
public:
    explicit WebUrlRequestInterceptor(QObject *parent = 0);

    void interceptRequest(QWebEngineUrlRequestInfo &info);
signals:

public slots:
};

#endif // WEBURLREQUESTINTERCEPTOR_H


text:
- [Usage](#usage)
- [Retrieving a value via the getter-setter API](#retrieving-a-value-via-the-getter-setter-api)
- [Integrating to the Mithril redrawing system](#integrating-to-the-mithril-redrawing-system)
- [Differences from Promises/A+](#differences-from-promises-a-)
- [The exception monitor](#the-exception-monitor)
- [Signature](#signature)

---

This is a low-level method in Mithril. It's a modified version of the Thenable API.

A deferred is an asynchrony monad. It exposes a `promise` property which can *bind* callbacks to build a computation tree.

The deferred object can then *apply* a value by calling either `resolve` or `reject`, which then dispatches the value to be processed to the computation tree.

Each computation function takes a value as a parameter and is expected to return another value, which in turns is forwarded along to the next computation function (or functions) in the tree.

The deferred object returned by `m.deferred` has two methods: `resolve` and `reject`, and one property called `promise`. The methods can be called to dispatch a value to the promise tree. The `promise` property is the root of the promise tree. It has a method `then` which takes a `successCallback` and a `errorCallback` callbacks. Calling the `then` method attaches the computations represented by `successCallback` and `errorCallback` to the promise, which will be called when either `resolve` or `reject` is called. The `then` method returns a child promise, which, itself, can have more child promises, recursively.

The `promise` object is actually a function - specifically, it's an [`m.prop`](mithril.prop.md) getter-setter, which gets populated with the value returned by  `successCallback` if the promise is resolved successfully.

Note that Mithril promises are not automatically integrated to its automatic redrawing system. If you wish to use third party asynchronous libraries (for example, `jQuery.ajax`), you should also consider using [`m.startComputation` / `m.endComputation`](mithril.computation.md) if you want views to redraw after requests complete.

---

### Usage

```javascript
//standalone usage
var greetAsync = function() {
	var deferred = m.deferred();
	setTimeout(function() {
		deferred.resolve("hello");
	}, 1000);
	return deferred.promise;
};

greetAsync()
	.then(function(value) {return value + " world"})
	.then(function(value) {console.log(value)}); //logs "hello world" after 1 second
```

---

#### Retrieving a value via the getter-setter API

The promise object is actually a getter-setter function that gets populated when the promise is fulfilled.

```javascript
//asynchronous service
var greetAsync = function() {
	var deferred = m.deferred();
	setTimeout(function() {
		deferred.resolve("hello");
	}, 1000);
	return deferred.promise;
};

//asynchronous consumer
var greeting = greetAsync()
var processed = greeting.then(function(value) {return value + " world"})

console.log(greeting()) // undefined - because `deferred.resolve` has not been called yet

setTimeout(function() {
	//now `deferred.resolve` has been called
	console.log(greeting()) // "hello"
	console.log(processed()) // "hello world"
}, 2000)
```

---

#### Integrating to the Mithril redrawing system

By default, promises are not integrated to the Mithril auto-redrawing system. When dealing with asynchronous functions, you must call [`m.startComputation` / `m.endComputation`] if you want the asynchronous payload to affect the view.

```javascript
//asynchronous service
var greetAsync = function() {
	//tell Mithril to wait for this service to complete before redrawing
	m.startComputation();

	var deferred = m.deferred();
	setTimeout(function() {
		deferred.resolve("hello");

		//the service is done, tell Mithril that it may redraw
		m.endComputation();
	}, 1000);
	return deferred.promise;
};
```

Some cases may not require a redraw upon completion of the asynchronous callbacks. In such cases, simply omit the m.startComputation/m.endComputation calls.

Some asynchronous operations might need to affect redrawing both before and after their completion. In those cases, you can call [`m.redraw`](mithril.redraw.md) instead of using m.startComputation/m.endComputation.

```javascript
//asynchronous service
var greetAsync = function() {
	//don't wait for this service; redraw right away

	var deferred = m.deferred();
	setTimeout(function() {
		deferred.resolve("hello");

		//redraw again
		m.redraw()
	}, 1000);
	return deferred.promise;
};
```

---

### Differences from Promises/A+

For the most part, Mithril promises behave as you'd expect a [Promise/A+](http://promises-aplus.github.io/promises-spec/) promise to behave, but have one difference: Mithril promises attempt to execute synchronously if possible.

#### Synchronous execution

Mithril promises attempt to execute synchronously if possible. To illustrate the difference between Mithril and A+ promises, consider the code below:

```javascript
var deferred = m.deferred()

deferred.promise.then(function() {
	console.log(1)
})

deferred.resolve("value")

console.log(2)
```

In the example above, A+ promises are required to log `2` before logging `1`, whereas Mithril logs `1` before `2`. Typically `resolve`/`reject` are called asynchronously after the `then` method is called, so normally this difference does not matter.

There are a couple of reasons why Mithril runs callbacks synchronously. Conforming to the spec requires either a `setImmediate` polyfill (which is a significantly large library), or `setTimeout` (which is required to take at least 4 milliseconds per call, according to its specs). Neither of these trade-offs are acceptable, given Mithril's focus on nimbleness and performance.

#### Unchecked Error Handling

By default, Mithril does not swallow errors if these errors are subclasses of the Error class. Manually throwing an instance of the Error class itself (or any other objects or primitives) does trigger the rejection callback path as per the Promises/A+ spec.

This deviation from the spec is there to make it easier for developers to find common logical errors such as typos that lead to null reference exceptions. By default, the spec requires that all thrown errors trigger rejection, which result in silent failures if the developer forgets to explicitly handle the failure case.

For example, there is simply never a case where a developer would want to programmatically handle the error of accessing the property of a nullable entity without first checking for its existence. The only reasonable course of action to prevent the potential null reference exceptions in this case is to add the existence check in the source code. It is expected that such an error would bubble up to the console and display a developer-friendly error message and line number there.

```javascript
m.request({method: "GET", url: "/things"})
	.then(function(items) {
		item.foreach(doSomething) //programmer error: typo will throw runtime error to the console
	})
```

The other side of the coin is still supported: if a developer needs to signal an exceptional condition within a promise callback, they can manually throw a `new Error` (for example, if a validation rule failed, and there should be an error message displayed to the user).

```javascript
var error = m.prop()
m.request({method: "GET", url: "/user/:id", data: {id: 1}})
	.then(function(user) {
		if (!user.isAdmin) throw new Error("Sorry, you don't have permissions")
	})
	.then(null, error) //handle the application error: bind to a getter-setter for diplaying it on the template
```

Note that the default promise exception handling semantics can be modified. See the next section.

---

### The exception monitor

Any time an exception is thrown inside a promise callback, Mithril calls `m.deferred.onerror(e)`.

By default, this event handler rethrows the exception to the console if an error is a subclass of Error (but not an instance of Error itself). Otherwise it follows the Promises/A+ specifications. It does this because people expect unexpected errors like null reference exceptions to be thrown to the console for debugging purposes, and these errors are always subclasses of Error.

On the other hand, javascript developers rarely ever throw errors that are subclasses of Error, and for the purposes of application error handling, the underlying prototypal chain of the error class is typically not relevant.

The `onerror` function can be safely replaced if the default error monitoring semantics are not desired.

```
//swallow all errors
m.deferred.onerror = function() {}

//only log errors
m.deferred.onerror = function(e) {console.error(e)}
```

---

### Signature

[How to read signatures](how-to-read-signatures.md)

```clike
Deferred deferred() {void onerror(Error e)}

where:
	Deferred :: Object { Promise promise, void resolve(any value), void reject(any value) }
	Promise :: GetterSetter { Promise then(any successCallback(any value), any errorCallback(any value)), Promise catch(any errorCallback(any value)) }
	GetterSetter :: any getterSetter([any value])
```

-	**GetterSetter { Promise then([any successCallback(any value) [, any errorCallback(any value)]]) } promise**

	A promise has a method called `then` which takes two computation callbacks as parameters.

	The `then` method returns another promise whose computations (if any) receive their inputs from the parent promise's computation.

	A promise is also a getter-setter (see [`m.prop`](mithril.prop.md)). After a call to either `resolve` or `reject`, it holds the result of the parent's computation (or the `resolve`/`reject` value, if the promise has no parent promises)

	Promises also have a method called `catch`, which is equivalent to calling `then(null, errorCallback)`

	-	**Promise then([any successCallback(any value) [, any errorCallback(any value)]])**

		This method accepts two callbacks which process a value passed to the `resolve` and `reject` methods, respectively, and pass the processed value to the returned promise

		-	**any successCallback(any value)** (optional)

			The `successCallback` is called if `resolve` is called in the root `deferred`.

			The default value (if this parameter is falsy) is the identity function `function(value) {return value}`

			If this function returns undefined, then it passes the `value` argument to the next step in the thenable queue, if any

		-	**any errorCallback(any value)** (optional)

			The `errorCallback` is called if `reject` is called in the root `deferred`.

			The default value (if this parameter is falsy) is the identity function `function(value) {return value}`

			If this function returns undefined, then it passes the `value` argument to the next step in the thenable queue, if any

		-	**returns Promise promise**

-	**void resolve(any value)**

	This method passes a value to the `successCallback` of the deferred object's child promise

-	**void reject(any value)**

	This method passes a value to the `errorCallback` of the deferred object's child promise

-

	#### m.deferred.onerror

	**void onerror(Error e)**

	This method gets called every time an exception is thrown inside a promise callback. By default, it rethrows to the console if an error is a subclass of Error (but not an instance of Error itself). Otherwise it follows the Promises/A+ specifications.


text:
(function (root) {
    'use strict';

    module.exports = root.google;
}(window || global));


text:
package org.apache.pulsar.client.impl.conf;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class DefaultCryptoKeyReaderConfigurationData implements Serializable, Cloneable {

    private static final long serialVersionUID = 1L;

    private static final String TO_STRING_FORMAT =
            "%s(defaultPublicKey=%s, defaultPrivateKey=%s, publicKeys=%s, privateKeys=%s)";

    @NonNull
    private String defaultPublicKey;
    @NonNull
    private String defaultPrivateKey;

    @NonNull
    private Map<String, String> publicKeys = new HashMap<>();
    @NonNull
    private Map<String, String> privateKeys = new HashMap<>();

    public void setPublicKey(@NonNull String keyName, @NonNull String publicKey) {
        publicKeys.put(keyName, publicKey);
    }

    public void setPrivateKey(@NonNull String keyName, @NonNull String privateKey) {
        privateKeys.put(keyName, privateKey);
    }

    @Override
    public DefaultCryptoKeyReaderConfigurationData clone() {
        DefaultCryptoKeyReaderConfigurationData clone = new DefaultCryptoKeyReaderConfigurationData();

        if (defaultPublicKey != null) {
            clone.setDefaultPublicKey(defaultPublicKey);
        }

        if (defaultPrivateKey != null) {
            clone.setDefaultPrivateKey(defaultPrivateKey);
        }

        if (publicKeys != null) {
            clone.setPublicKeys(new HashMap<String, String>(publicKeys));
        }

        if (privateKeys != null) {
            clone.setPrivateKeys(new HashMap<String, String>(privateKeys));
        }

        return clone;
    }

    @Override
    public String toString() {
        return String.format(TO_STRING_FORMAT, getClass().getSimpleName(), maskKeyData(defaultPublicKey),
                maskKeyData(defaultPrivateKey), maskKeyData(publicKeys), maskKeyData(privateKeys));
    }

    private static String maskKeyData(Map<String, String> keys) {
        if (keys == null) {
            return "null";
        } else {
            StringBuilder keysStr = new StringBuilder();
            keysStr.append("{");

            List<String> kvList = new ArrayList<>();
            keys.forEach((k, v) -> kvList.add(k + "=" + maskKeyData(v)));
            keysStr.append(String.join(", ", kvList));

            keysStr.append("}");
            return keysStr.toString();
        }
    }

    private static String maskKeyData(String key) {
        if (key == null) {
            return "null";
        } else if (key.startsWith("data:")) {
            return "data:*****";
        } else {
            return key;
        }
    }

}