text:
require 'rails_helper'

RSpec.describe ResearchOutputPresenter do
  before do
    @research_output = create(:research_output, plan: create(:plan))
    @presenter = described_class.new(research_output: @research_output)
  end

  describe ':selectable_output_types' do
    it 'returns the output types' do
      expect(@presenter.selectable_output_types.any?).to be(true)
    end

    it "packages the output types for a selectbox - [['Audiovisual', 'audiovisual']]" do
      sample = @presenter.selectable_output_types.first
      expect(sample.length).to be(2)
      expect(sample[0].scan(/^[a-zA-Z\s]*$/).any?).to be(true)
      expect(sample[1].scan(/^[a-z]*$/).any?).to be(true)
      expect(sample[0].underscore).to eql(sample[1])
      expect(ResearchOutput.output_types[sample[1]].present?).to be(true)
    end
  end

  describe ':selectable_access_types' do
    it 'returns the output types' do
      expect(@presenter.selectable_access_types.any?).to be(true)
    end

    it "packages the output types for a selectbox - [['Open', 'open']]" do
      sample = @presenter.selectable_access_types.first
      expect(sample.length).to be(2)
      expect(sample[0].scan(/^[a-zA-Z\s]*$/).any?).to be(true)
      expect(sample[1].scan(/^[a-z]*$/).any?).to be(true)
      expect(sample[0].underscore).to eql(sample[1])
      expect(ResearchOutput.accesses[sample[1]].present?).to be(true)
    end
  end

  describe ':selectable_size_units' do
    it 'returns the output types' do
      expect(@presenter.selectable_size_units.any?).to be(true)
    end

    it "packages the output types for a selectbox - [['MB', 'mb']]" do
      sample = @presenter.selectable_size_units.first
      expect(sample.length).to be(2)
      expect(sample[0].scan(/^[a-zA-Z\s]*$/).any?).to be(true)
      expect(sample[1].scan(/^[a-z]*$/).any?).to be(true)
      expect(sample[0].downcase).to eql(sample[1])
    end
  end

  describe ':converted_file_size(size:)' do
    it 'returns an zero MB if size is not present' do
      expect(@presenter.converted_file_size(size: nil)).to eql({ size: nil, unit: 'mb' })
    end

    it 'returns an zero MB if size is not a number' do
      expect(@presenter.converted_file_size(size: 'foo')).to eql({ size: nil, unit: 'mb' })
    end

    it 'returns an zero MB if size is not positive' do
      expect(@presenter.converted_file_size(size: -1)).to eql({ size: nil, unit: 'mb' })
    end

    it 'can handle bytes' do
      expect(@presenter.converted_file_size(size: 100)).to eql({ size: 100, unit: '' })
    end

    it 'can handle megabytes' do
      expect(@presenter.converted_file_size(size: 1.megabytes)).to eql({ size: 1, unit: 'mb' })
    end

    it 'can handle gigabytes' do
      expect(@presenter.converted_file_size(size: 1.gigabytes)).to eql({ size: 1, unit: 'gb' })
    end

    it 'can handle terabytes' do
      expect(@presenter.converted_file_size(size: 1.terabytes)).to eql({ size: 1, unit: 'tb' })
    end

    it 'can handle petabytes' do
      expect(@presenter.converted_file_size(size: 1.petabytes)).to eql({ size: 1, unit: 'pb' })
    end
  end

  describe ':display_name' do
    it 'returns an empty string unless if we do not have a ResearchOutput' do
      presenter = described_class.new(research_output: build(:org))
      expect(presenter.display_name).to eql('')
    end

    it 'does not trim names that are <= 50 characters' do
      presenter = described_class.new(research_output: build(:research_output, title: 'a' * 49))
      expect(presenter.display_name).to eql('a' * 49)
    end

    it 'does not trims names that are > 50 characters' do
      presenter = described_class.new(research_output: build(:research_output, title: 'a' * 51))
      expect(presenter.display_name).to eql("#{'a' * 50} ...")
    end
  end

  describe ':display_type' do
    it 'returns an empty string unless if we do not have a ResearchOutput' do
      presenter = described_class.new(research_output: build(:org))
      expect(presenter.display_type).to eql('')
    end

    it "returns the user's description if the output_type is other" do
      research_output = build(:research_output, output_type: 'other',
                                                output_type_description: 'foo')
      presenter = described_class.new(research_output: research_output)
      expect(presenter.display_type).to eql('foo')
    end

    it 'returns the humanized version of the output_type' do
      presenter = described_class.new(research_output: build(:research_output, output_type: :image))
      expect(presenter.display_type).to eql('Image')
    end
  end

  describe ':display_repository' do
    before do
      @research_output.repositories.clear
    end

    it "returns ['None specified'] if not repositories are assigned" do
      presenter = described_class.new(research_output: @research_output)
      expect(presenter.display_repository).to eql(['None specified'])
    end

    it 'returns an array of names when there is only one repository' do
      repo = build(:repository)
      @research_output.repositories << repo
      presenter = described_class.new(research_output: @research_output)
      expect(presenter.display_repository).to eql([repo.name])
    end

    it 'returns an array of names when there are multiple repositories' do
      repos = [build(:repository), build(:repository)]
      @research_output.repositories << repos
      presenter = described_class.new(research_output: @research_output)
      expect(presenter.display_repository).to eql(repos.collect(&:name))
    end
  end

  describe ':display_access' do
    it "returns 'Unspecified' if :access has not been defined" do
      presenter = described_class.new(research_output: build(:research_output, access: nil))
      expect(presenter.display_access).to eql('Unspecified')
    end

    it 'returns a humanized version of the :access enum selection' do
      presenter = described_class.new(research_output: build(:research_output, access: :open))
      expect(presenter.display_access).to eql('Open')
    end
  end

  describe ':display_release' do
    it "returns 'Unspecified' if :access has not been defined" do
      presenter = described_class.new(research_output: build(:research_output, release_date: nil))
      expect(presenter.display_release).to eql('Unspecified')
    end

    it 'returns a the release_date as a Date' do
      now = Time.zone.now
      presenter = described_class.new(research_output: build(:research_output, release_date: now))
      expect(presenter.display_release.is_a?(Date)).to be(true)
    end
  end

  context 'class methods' do
    describe ':selectable_subjects' do
      it 'returns subjects' do
        expect(described_class.selectable_subjects.any?).to be(true)
      end

      it "packages the subjects for a selectbox - [['Biology', '21 Biology']]" do
        sample = described_class.selectable_subjects.first
        expect(sample.length).to be(2)
        expect(sample[0].scan(/^[a-zA-Z\s,]*$/).any?).to be(true)
        expect(sample[1].scan(/^[0-9]+\s[a-zA-Z\s,]*$/).any?).to be(true)
        expect(sample[1].ends_with?(sample[0])).to be(true)
      end
    end

    describe ':selectable_repository_types' do
      it 'returns repository types' do
        expect(described_class.selectable_repository_types.any?).to be(true)
      end

      it "packages the repo types for a selectbox - [['Discipline specific', 'disciplinary']]" do
        sample = described_class.selectable_repository_types.first
        expect(sample.length).to be(2)
        expect(sample[0].scan(/^[A-Z]{1}[a-z\s()]*$/).any?).to be(true)
        expect(sample[1].scan(/^[a-z]*$/).any?).to be(true)
      end
    end
  end
end


text:
/**
 * Plugin that maintains state for each player in G.players.
 * During a turn, G.player will contain the object for the current player.
 * In two player games, G.opponent will contain the object for the other player.
 *
 * @param {function} initPlayerState - Function of type (playerID) => playerState.
 */
const PlayerPlugin = ({ setup } = {}) => ({
    name: 'player',
    flush: ({ api }) => {
        return { players: api.state };
    },
    api: ({ ctx, data }) => {
        let state = data.players;
        const get = () => {
            return data.players[ctx.currentPlayer];
        };
        const set = value => {
            return (state[ctx.currentPlayer] = value);
        };
        let result = { state, get, set };
        if (ctx.numPlayers === 2) {
            const other = ctx.currentPlayer === '0' ? '1' : '0';
            const get = () => {
                return data.players[other];
            };
            const set = value => {
                return (state[other] = value);
            };
            result.opponent = { get, set };
        }
        return result;
    },
    setup: ({ ctx }) => {
        let players = {};
        for (let i = 0; i < ctx.numPlayers; i++) {
            let playerState = {};
            if (setup !== undefined) {
                playerState = setup(i + '');
            }
            players[i + ''] = playerState;
        }
        return { players };
    },
});

export { PlayerPlugin as PluginPlayer };

redpajama_set_name: RedPajamaGithub


text:
package commandevaluators

import (
	"errors"
	"fmt"
	"strings"

	"github.com/byuoitav/common/log"

	"github.com/byuoitav/av-api/base"
	"github.com/byuoitav/common/db"
	"github.com/byuoitav/common/structs"
	"github.com/byuoitav/common/v2/events"
)

/*

	Video Switchers are a little different by way of port identification.
	Basically our ports are combinations of input + output

	so 0:0 is the input zero set to output zero. So here we run a split on the ':' to assign the input and output separately.

*/

// ChangeVideoInputVideoSwitcher implements the CommandEvaluation struct.
type ChangeVideoInputVideoSwitcher struct {
}

//Evaluate generates a list of actions based on the information given.
func (c *ChangeVideoInputVideoSwitcher) Evaluate(dbRoom structs.Room, room base.PublicRoom, requestor string) ([]base.ActionStructure, int, error) {
	actionList := []base.ActionStructure{}

	if len(room.CurrentVideoInput) != 0 {
		devices := FilterDevicesByRole(dbRoom.Devices, "VideoOut")

		for _, device := range devices {
			action, err := GetSwitcherAndCreateAction(dbRoom, room, device, room.CurrentVideoInput, "ChangeVideoInputVideoSwitcher", requestor)
			if err != nil {
				return []base.ActionStructure{}, 0, err
			}
			actionList = append(actionList, action)

			////////////////////////
			///// MIRROR STUFF /////
			if structs.HasRole(device, "MirrorMaster") {
				for _, port := range device.Ports {
					if port.ID == "mirror" {
						DX, err := db.GetDB().GetDevice(port.DestinationDevice)
						if err != nil {
							return []base.ActionStructure{}, 0, err
						}

						cmd := DX.GetCommandByID("ChangeVideoInputVideoSwitcher")
						if len(cmd.ID) < 1 {
							continue
						}

						mirrorAction, err := GetSwitcherAndCreateAction(dbRoom, room, DX, room.CurrentVideoInput, "ChangeVideoInputVideoSwitcher", requestor)
						if err != nil {
							return []base.ActionStructure{}, 0, err
						}
						//Undecode the format into the
						actionList = append(actionList, mirrorAction)
					}
				}
			}
			///// MIRROR STUFF /////
			////////////////////////
		}
	}

	// if there is at least one display
	if len(room.Displays) != 0 {

		// interate through all displays in the room, create an ActionStructure if it has an input
		for _, display := range room.Displays {

			// if the display has an input, create the action
			if len(display.Input) != 0 {
				deviceID := fmt.Sprintf("%v-%v-%v", room.Building, room.Room, display.Name)
				device := FindDevice(dbRoom.Devices, deviceID)

				action, err := GetSwitcherAndCreateAction(dbRoom, room, device, display.Input, "ChangeVideoInputVideoSwitcher", requestor)
				if err != nil {
					return []base.ActionStructure{}, 0, err
				}
				//Undecode the format into the
				actionList = append(actionList, action)

				////////////////////////
				///// MIRROR STUFF /////
				if structs.HasRole(device, "MirrorMaster") {
					for _, port := range device.Ports {
						if port.ID == "mirror" {
							DX, err := db.GetDB().GetDevice(port.DestinationDevice)
							if err != nil {
								return actionList, len(actionList), err
							}

							cmd := DX.GetCommandByID("ChangeVideoInputVideoSwitcher")
							if len(cmd.ID) < 1 {
								continue
							}

							mirrorAction, err := GetSwitcherAndCreateAction(dbRoom, room, DX, display.Input, "ChangeVideoInputVideoSwitcher", requestor)
							if err != nil {
								return actionList, len(actionList), err
							}
							//Undecode the format into the
							actionList = append(actionList, mirrorAction)
						}
					}
				}
				///// MIRROR STUFF /////
				////////////////////////
			}
		}
	}

	//check the audio devices struct as well
	if len(room.AudioDevices) != 0 {

		for _, audioDevice := range room.AudioDevices {
			if len(audioDevice.Input) != 0 {
				deviceID := fmt.Sprintf("%v-%v-%v", room.Building, room.Room, audioDevice.Name)
				device := FindDevice(dbRoom.Devices, deviceID)

				action, err := GetSwitcherAndCreateAction(dbRoom, room, device, audioDevice.Input, "ChangeVideoInputVideoSwitcher", requestor)
				if err != nil {
					continue
				}
				//Undecode the format into the
				actionList = append(actionList, action)

				////////////////////////
				///// MIRROR STUFF /////
				if structs.HasRole(device, "MirrorMaster") {
					for _, port := range device.Ports {
						if port.ID == "mirror" {
							DX, err := db.GetDB().GetDevice(port.DestinationDevice)
							if err != nil {
								return []base.ActionStructure{}, 0, err
							}

							cmd := DX.GetCommandByID("ChangeVideoInputVideoSwitcher")
							if len(cmd.ID) < 1 {
								continue
							}

							mirrorAction, err := GetSwitcherAndCreateAction(dbRoom, room, DX, audioDevice.Input, "ChangeVideoInputVideoSwitcher", requestor)
							if err != nil {
								return []base.ActionStructure{}, 0, err
							}
							//Undecode the format into the
							actionList = append(actionList, mirrorAction)
						}
					}
				}
				///// MIRROR STUFF /////
				////////////////////////
			}

		}

	}

	for _, action := range actionList {
		p := action.Parameters["output"]
		splitP := strings.Split(p, ":")

		if len(splitP) != 2 {
			return actionList, 0, errors.New("[command_evaluators] Invalid port for a video switcher")
		}

		action.Parameters["input"] = splitP[0]
		action.Parameters["output"] = splitP[1]
	}
	return actionList, len(actionList), nil
}

//GetSwitcherAndCreateAction gets the videoswitcher in a room, matches the destination port to the new port
// and creates an action
func GetSwitcherAndCreateAction(dbRoom structs.Room, room base.PublicRoom, device structs.Device, selectedInput, generatingEvaluator, requestor string) (base.ActionStructure, error) {

	switcher := FilterDevicesByRole(dbRoom.Devices, "VideoSwitcher")

	if len(switcher) != 1 {
		return base.ActionStructure{}, errors.New("[command_evaluators] Too many switchers/none available")
	}

	log.L.Infof("[commandevaluators] Evaluating device %s for a port connecting %s to %s", switcher[0].ID, selectedInput, device.ID)
	for _, port := range switcher[0].Ports {

		if port.DestinationDevice == device.ID && port.SourceDevice == selectedInput {

			m := make(map[string]string)
			m["output"] = port.ID

			eventInfo := events.Event{
				TargetDevice: events.GenerateBasicDeviceInfo(device.ID),
				AffectedRoom: events.GenerateBasicRoomInfo(dbRoom.ID),
				Key:          "input",
				Value:        selectedInput,
				User:         requestor,
			}

			eventInfo.AddToTags(events.CoreState, events.UserGenerated)

			destination := base.DestinationDevice{
				Device: device,
			}

			if structs.HasRole(device, "AudioOut") {
				destination.AudioDevice = true
			}

			if structs.HasRole(device, "VideoOut") {
				destination.Display = true
			}

			tempAction := base.ActionStructure{
				Action:              "ChangeInput",
				GeneratingEvaluator: generatingEvaluator,
				Device:              switcher[0],
				DestinationDevice:   destination,
				Parameters:          m,
				DeviceSpecific:      false,
				Overridden:          false,
				EventLog:            []events.Event{eventInfo},
			}

			return tempAction, nil
		}
	}

	return base.ActionStructure{}, errors.New("[command_evaluators] No switcher found with the matching port")
}

//Validate veries that the action that was created has correct information.
func (c *ChangeVideoInputVideoSwitcher) Validate(action base.ActionStructure) error {
	log.L.Infof("[commandevaluators] Validating action for command %v", action.Action)

	// check if ChangeInput is a valid name of a command (ok is a bool)
	ok, _ := CheckCommands(action.Device.Type.Commands, "ChangeInput")

	// returns and error if the ChangeInput command doesn't exist or if the command isn't ChangeInput
	if !ok || action.Action != "ChangeInput" {
		msg := fmt.Sprintf("[command_evaluators] ERROR. %s is an invalid command for %s", action.Action, action.Device.Name)
		log.L.Error(msg)
		return errors.New(msg)
	}

	log.L.Info("[commandevaluators] Done.")
	return nil
}

//GetIncompatibleCommands f
func (c *ChangeVideoInputVideoSwitcher) GetIncompatibleCommands() []string {
	return nil
}


text:
layout: post
title: Old granny tourist is picked up and screwed
titleinfo: pornvd
desc: Watch Old granny tourist is picked up and screwed. Pornhub is the ultimate xxx porn and sex site.
---

Old granny tourist is picked up and screwed

Watch Old granny tourist is picked up and screwed. Pornhub is the ultimate xxx porn and sex site.


text:
import org.apache.log4j.{Level, Logger}
import org.apache.spark.mllib.linalg.Matrix
import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.mllib.linalg.distributed.{CoordinateMatrix, MatrixEntry}
import org.scalatest.{Outcome, FlatSpec}
import AllPairsShortestPath._
import breeze.linalg.{DenseMatrix => BDM}

class APSPSpec extends FlatSpec {

  val conf = new SparkConf().setAppName("AllPairsShortestPath").setMaster("local[4]").set("spark.driver.allowMultipleContexts", "true")
  val sc = new SparkContext(conf)

  override def withFixture(test: NoArgTest) : Outcome = {
    Logger.getLogger("org").setLevel(Level.ERROR)
    Logger.getLogger("akka").setLevel(Level.ERROR)
    try {
      test() // invoke the test function
    }
  }

  def fourByFourBlockMatrx = {
    val entries = sc.parallelize(Array(
      (0, 1, 20), (0, 2, 4), (0, 3, 2),
      (1, 0, 2), (1, 2, 1), (1, 3, 3), (2, 0, 1),
      (2, 1, 6), (2, 3, 5), (3, 0, 4), (3, 1, 2), (3, 2, 2))).map { case (i, j, v) => MatrixEntry(i, j, v) }
    val coordMat = new CoordinateMatrix(entries)
    val matA = coordMat.toBlockMatrix(2, 2).cache()
    matA
  }

  def ApspPartitioner = {
    GridPartitioner(fourByFourBlockMatrx.numRowBlocks, fourByFourBlockMatrx.numColBlocks, fourByFourBlockMatrx.blocks.partitions.length)
  }

  def toBreeze(A: Matrix): BDM[Double] = {
    new BDM[Double](A.numRows, A.numCols, A.toArray)
  }

  "The sample 4x4 Block Matrix" should "be valid" in {
    fourByFourBlockMatrx.validate()
  }

  it should "match our APSP matrix" in {
    println(fourByFourBlockMatrx.toLocalMatrix())
    val result = new DistributedBlockFW
    val observed = toBreeze(result.compute(fourByFourBlockMatrx).toLocal())
    val expected = BDM(
      (0.0, 4.0, 4.0, 2.0),
      (2.0, 0.0, 1.0, 3.0),
      (1.0, 5.0, 0.0, 3.0),
      (3.0, 2.0, 2.0, 0.0)
    )
    assert(observed === expected)
  }
}


text:
 Login

        <form [formGroup]="loginForm" (ngSubmit)="submit(loginForm)" class="login-form" novalidate>

                        Email:

                        <input type="email" name="email" class="form-control" formControlName="email" />

                            A valid email address is required

                        Password:

                        <input type="password" name="password" class="form-control" formControlName="password" />

                            Password is required (6 or more characters with at least one number)

                        <button type="submit" class="btn btn-success" [disabled]="!loginForm.valid">Login</button>

                          Error: {{ errorMessage }}

        </form>


text:
package sh.komet.gui.action.dashboard;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import sh.isaac.api.Get;
import sh.isaac.api.chronicle.Chronology;
import sh.isaac.api.chronicle.Version;
import sh.isaac.api.chronicle.VersionType;
import sh.isaac.api.task.TimedTaskWithProgressTracker;

/**
 *
 * @author kec
 */
public class AssemblageDashboardStats extends TimedTaskWithProgressTracker<Void> {

    private final int assemblageNid;
    private final AtomicInteger semanticCount = new AtomicInteger();
    private final AtomicInteger versionCount = new AtomicInteger();
    private final ConcurrentHashMap<Long, AtomicInteger> commitTimes = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<Integer, AtomicInteger> modules = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<VersionType, AtomicInteger> semanticTypes = new ConcurrentHashMap<>();

    public AssemblageDashboardStats(int assemblageNid) {
        this.assemblageNid = assemblageNid;
        updateTitle("Computing assemblage statistics");
        Get.activeTasks().add(this);

    }

    @Override
    protected Void call() throws Exception {
        try {
            int count = Get.assemblageService().getSemanticCount(assemblageNid);
            addToTotalWork(count);

            Stream<Chronology> chronologyStream
                    = Get.assemblageService().getChronologyStream(assemblageNid, true);

            chronologyStream.forEach((Chronology chronology) -> {
                semanticCount.incrementAndGet();
                completedUnitOfWork();
                for (Version version : chronology.getVersionList()) {
                    versionCount.incrementAndGet();
                    commitTimes.computeIfAbsent(version.getTime(), (t) -> new AtomicInteger()).incrementAndGet();
                    semanticTypes.computeIfAbsent(version.getSemanticType(), (t) -> new AtomicInteger()).incrementAndGet();
                    modules.computeIfAbsent(version.getModuleNid(), (t) -> new AtomicInteger()).incrementAndGet();
                }
            });

            return null;
        } finally {
            Get.activeTasks().remove(this);
        }
    }

    public AtomicInteger getSemanticCount() {
        return semanticCount;
    }

    public AtomicInteger getVersionCount() {
        return versionCount;
    }

    public ConcurrentHashMap<Long, AtomicInteger> getCommitTimes() {
        return commitTimes;
    }

    public ConcurrentHashMap<Integer, AtomicInteger> getModules() {
        return modules;
    }

    public ConcurrentHashMap<VersionType, AtomicInteger> getSemanticTypes() {
        return semanticTypes;
    }

}


text:
package testclient

import (
	ktestclient "k8s.io/kubernetes/pkg/client/unversioned/testclient"

	oauthapi "github.com/openshift/origin/pkg/oauth/api"
)

// FakeOAuthAccessTokens implements OAuthAccessTokenInterface. Meant to be embedded into a struct to get a default
// implementation. This makes faking out just the methods you want to test easier.
type FakeOAuthAccessTokens struct {
	Fake *Fake
}

func (c *FakeOAuthAccessTokens) Delete(name string) error {
	_, err := c.Fake.Invokes(ktestclient.NewRootDeleteAction("oauthaccesstokens", name), &oauthapi.OAuthAccessToken{})
	return err
}


text:
package twitter4j;

/**
 * A data interface representing Twitter REST API's rate limit status
 *
 * @author Yusuke Yamamoto - yusuke at mac.com
 * @see Rate Limiting | Twitter Developers
 */
public final class RateLimitStatusEvent extends java.util.EventObject {

    private RateLimitStatus rateLimitStatus;

    private boolean isAccountRateLimitStatus;
    private static final long serialVersionUID = -2332507741769177298L;

    RateLimitStatusEvent(Object source, RateLimitStatus rateLimitStatus, boolean isAccountRateLimitStatus) {
        super(source);
        this.rateLimitStatus = rateLimitStatus;
        this.isAccountRateLimitStatus = isAccountRateLimitStatus;
    }

    public RateLimitStatus getRateLimitStatus() {
        return rateLimitStatus;
    }

    public boolean isAccountRateLimitStatus() {
        return isAccountRateLimitStatus;
    }

    public boolean isIPRateLimitStatus() {
        return !isAccountRateLimitStatus;
    }

}


text:
using System;
using System.Collections.Generic;
using Quartz.Spi;
using Quartz.Util;

namespace Quartz.Web.Api.Dto
{
    public class TriggerDetailDto
    {
        protected TriggerDetailDto(ITrigger trigger, ICalendar calendar)
        {
            Description = trigger.Description;
            TriggerType = trigger.GetType().AssemblyQualifiedNameWithoutVersion();
            Name = trigger.Key.Name;
            Group = trigger.Key.Group;
            CalendarName = trigger.CalendarName;
            Priority = trigger.Priority;
            StartTimeUtc = trigger.StartTimeUtc;
            EndTimeUtc = trigger.EndTimeUtc;
            NextFireTimes = TriggerUtils.ComputeFireTimes((IOperableTrigger) trigger, calendar, 10);
        }

        public string Name { get; set; }
        public string Group { get; set; }
        public string TriggerType { get; set; }
        public string Description { get; set; }

        public string CalendarName { get; set; }
        public int Priority { get; set; }
        public DateTimeOffset StartTimeUtc { get; set; }
        public DateTimeOffset? EndTimeUtc { get; set; }

        public IReadOnlyList<DateTimeOffset> NextFireTimes { get; set; }

        public static TriggerDetailDto Create(ITrigger trigger, ICalendar calendar)
        {
            var simpleTrigger = trigger as ISimpleTrigger;
            if (simpleTrigger != null)
            {
                return new SimpleTriggerDetailDto(simpleTrigger, calendar);
            }
            var cronTrigger = trigger as ICronTrigger;
            if (cronTrigger != null)
            {
                return new CronTriggerDetailDto(cronTrigger, calendar);
            }
            var calendarIntervalTrigger = trigger as ICalendarIntervalTrigger;
            if (calendarIntervalTrigger != null)
            {
                return new CalendarIntervalTriggerDetailDto(calendarIntervalTrigger, calendar);
            }
            var dailyTimeIntervalTrigger = trigger as IDailyTimeIntervalTrigger;
            if (dailyTimeIntervalTrigger != null)
            {
                return new DailyTimeIntervalTriggerDetailDto(dailyTimeIntervalTrigger, calendar);
            }

            return new TriggerDetailDto(trigger, calendar);
        }

        public class CronTriggerDetailDto : TriggerDetailDto
        {
            public CronTriggerDetailDto(ICronTrigger trigger, ICalendar calendar) : base(trigger, calendar)
            {
                CronExpression = trigger.CronExpressionString;
                TimeZone = new TimeZoneDto(trigger.TimeZone);
            }

            public string CronExpression { get; }
            public TimeZoneDto TimeZone { get; }
        }

        public class SimpleTriggerDetailDto : TriggerDetailDto
        {
            public SimpleTriggerDetailDto(ISimpleTrigger trigger, ICalendar calendar) : base(trigger, calendar)
            {
                RepeatCount = trigger.RepeatCount;
                RepeatInterval = trigger.RepeatInterval;
                TimesTriggered = trigger.TimesTriggered;
            }

            public TimeSpan RepeatInterval { get; }
            public int RepeatCount { get; }
            public int TimesTriggered { get; }
        }

        public class CalendarIntervalTriggerDetailDto : TriggerDetailDto
        {
            public CalendarIntervalTriggerDetailDto(ICalendarIntervalTrigger trigger, ICalendar calendar) : base(trigger, calendar)
            {
                RepeatInterval = trigger.RepeatInterval;
                TimesTriggered = trigger.TimesTriggered;
                RepeatIntervalUnit = trigger.RepeatIntervalUnit;
                PreserveHourOfDayAcrossDaylightSavings = trigger.PreserveHourOfDayAcrossDaylightSavings;
                TimeZone = new TimeZoneDto(trigger.TimeZone);
                SkipDayIfHourDoesNotExist = trigger.SkipDayIfHourDoesNotExist;
            }

            public TimeZoneDto TimeZone { get; }
            public bool SkipDayIfHourDoesNotExist { get; }
            public bool PreserveHourOfDayAcrossDaylightSavings { get; }
            public IntervalUnit RepeatIntervalUnit { get; }
            public int RepeatInterval { get; }
            public int TimesTriggered { get; }
        }

        public class DailyTimeIntervalTriggerDetailDto : TriggerDetailDto
        {
            public DailyTimeIntervalTriggerDetailDto(IDailyTimeIntervalTrigger trigger, ICalendar calendar) : base(trigger, calendar)
            {
                RepeatInterval = trigger.RepeatInterval;
                TimesTriggered = trigger.TimesTriggered;
                RepeatIntervalUnit = trigger.RepeatIntervalUnit;
                TimeZone = new TimeZoneDto(trigger.TimeZone);
            }

            public TimeZoneDto TimeZone { get; }
            public IntervalUnit RepeatIntervalUnit { get; }
            public int TimesTriggered { get; }
            public int RepeatInterval { get; }
        }
    }
}


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

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.dlm.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * CrossRegionCopyRuleMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CrossRegionCopyRuleMarshaller {

    private static final MarshallingInfo<String> TARGETREGION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("TargetRegion").build();
    private static final MarshallingInfo<String> TARGET_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Target").build();
    private static final MarshallingInfo<Boolean> ENCRYPTED_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Encrypted").build();
    private static final MarshallingInfo<String> CMKARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("CmkArn").build();
    private static final MarshallingInfo<Boolean> COPYTAGS_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CopyTags").build();
    private static final MarshallingInfo<StructuredPojo> RETAINRULE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("RetainRule").build();
    private static final MarshallingInfo<StructuredPojo> DEPRECATERULE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DeprecateRule").build();

    private static final CrossRegionCopyRuleMarshaller instance = new CrossRegionCopyRuleMarshaller();

    public static CrossRegionCopyRuleMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(CrossRegionCopyRule crossRegionCopyRule, ProtocolMarshaller protocolMarshaller) {

        if (crossRegionCopyRule == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(crossRegionCopyRule.getTargetRegion(), TARGETREGION_BINDING);
            protocolMarshaller.marshall(crossRegionCopyRule.getTarget(), TARGET_BINDING);
            protocolMarshaller.marshall(crossRegionCopyRule.getEncrypted(), ENCRYPTED_BINDING);
            protocolMarshaller.marshall(crossRegionCopyRule.getCmkArn(), CMKARN_BINDING);
            protocolMarshaller.marshall(crossRegionCopyRule.getCopyTags(), COPYTAGS_BINDING);
            protocolMarshaller.marshall(crossRegionCopyRule.getRetainRule(), RETAINRULE_BINDING);
            protocolMarshaller.marshall(crossRegionCopyRule.getDeprecateRule(), DEPRECATERULE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
(function(){

  'use strict'

  angular
  .module('ngEnter',[])
  .directive('ngEnter', ngEnter);

  function ngEnter(){

    return function(scope, element, attrs) {
      element.bind("keydown keypress", function(event) {

        if(event.which === 13) {
          scope.$apply(function(){
            scope.$eval(attrs.ngEnter, {'event': event});
          });
          event.preventDefault();

        }

      });

    };
  }
})();


text:
<?php

namespace Drupal\views_ui\Tests;

use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\views\Views;

/**
 * Tests the UI of storage properties of views.
 *
 * @group views_ui
 */
class StorageTest extends UITestBase {

  /**
   * Views used by this test.
   *
   * @var array
   */
  public static $testViews = ['test_view'];

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['views_ui', 'language'];

  /**
   * Tests changing label, description and tag.
   *
   * @see views_ui_edit_details_form
   */
  public function testDetails() {
    $view_name = 'test_view';

    ConfigurableLanguage::createFromLangcode('fr')->save();

    $edit = [
      'label' => $this->randomMachineName(),
      'tag' => $this->randomMachineName(),
      'description' => $this->randomMachineName(30),
      'langcode' => 'fr',
    ];

    $this->drupalPostForm("admin/structure/views/nojs/edit-details/$view_name/default", $edit, t('Apply'));
    $this->drupalPostForm(NULL, [], t('Save'));

    $view = Views::getView($view_name);

    foreach (['label', 'tag', 'description', 'langcode'] as $property) {
      $this->assertEqual($view->storage->get($property), $edit[$property], format_string('Make sure the property @property got probably saved.', ['@property' => $property]));
    }
  }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Abh. Königl. Ges. Wiss. Göttingen 19:82; Pl. lorentz. 34. 1874

#### Original name
null

### Remarks
null


text:
define(['aura_core'], function(mediator) {
  "use strict";

  var sandbox = {};

  // * **param:** {string} subscriber Module name
  // * **param:** {string} channel Event name
  // * **param:** {object} callback Module
  sandbox.subscribe = function(channel, subscriber, callback, context) {
    mediator.subscribe(channel, subscriber, callback, context || this);
  };

  // * **param:** {string} channel Event name
  sandbox.publish = function(channel) {
    mediator.publish.apply(mediator, arguments);
  };

  // * **param:** {Object/Array} an array with objects or single object containing channel and element
  sandbox.start = function(list) {
    mediator.start.apply(mediator, arguments);
  };

  // * **param:** {string} channel Event name
  sandbox.stop = function(channel) {
    mediator.stop.apply(mediator, arguments);
  };

  sandbox.dom = {
    // * **param:** {string} selector CSS selector for the element
    // * **param:** {string} context CSS selector for the context in which
    // to search for selector
    // * **returns:** {object} Found elements or empty array
    find: function(selector, context) {
      return mediator.dom.find(selector, context);
    }
  };

  sandbox.events = {
    // * **param:** {object} context Element to listen on
    // * **param:** {string} events Events to trigger, e.g. click, focus, etc.
    // * **param:** {string} selector Items to listen for
    // * **param:** {object} data
    // * **param:** {object} callback
    listen: function(context, events, selector, callback) {
      mediator.events.listen(context, events, selector, callback);
    },
    bindAll: mediator.events.bindAll
  };

  sandbox.util = {
    each: mediator.util.each,
    extend: mediator.util.extend
  };

  sandbox.data = mediator.data;

  sandbox.template = mediator.template;

  return sandbox;

});


text:
using MediatR;

namespace AllReady.Areas.Admin.Features.Tasks
{
    public class DeleteTaskCommand : IAsyncRequest
    {
        public int TaskId {get; set;}
    }
}


text:
package org.springframework.boot.web.embedded.tomcat;

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.ServletContainerInitializer;

import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Manager;
import org.apache.catalina.Valve;
import org.apache.catalina.WebResource;
import org.apache.catalina.WebResourceRoot.ResourceSetType;
import org.apache.catalina.WebResourceSet;
import org.apache.catalina.Wrapper;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.loader.WebappLoader;
import org.apache.catalina.session.StandardManager;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.Tomcat.FixContextListener;
import org.apache.catalina.util.LifecycleBase;
import org.apache.catalina.webresources.AbstractResourceSet;
import org.apache.catalina.webresources.EmptyResource;
import org.apache.catalina.webresources.StandardRoot;
import org.apache.coyote.AbstractProtocol;
import org.apache.coyote.ProtocolHandler;
import org.apache.coyote.http2.Http2Protocol;
import org.apache.tomcat.util.modeler.Registry;
import org.apache.tomcat.util.scan.StandardJarScanFilter;

import org.springframework.boot.util.LambdaSafe;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.MimeMappings;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.server.AbstractServletWebServerFactory;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

/**
 * {@link AbstractServletWebServerFactory} that can be used to create
 * {@link TomcatWebServer}s. Can be initialized using Spring's
 * {@link ServletContextInitializer}s or Tomcat {@link LifecycleListener}s.
 * <p>
 * Unless explicitly configured otherwise this factory will create containers that listen
 * for HTTP requests on port 8080.
 *
 * @author Phillip Webb
 * @author Dave Syer
 * @author Brock Mills
 * @author Stephane Nicoll
 * @author Andy Wilkinson
 * @author Eddú Meléndez
 * @author Christoffer Sawicki
 * @author Dawid Antecki
 * @since 2.0.0
 * @see #setPort(int)
 * @see #setContextLifecycleListeners(Collection)
 * @see TomcatWebServer
 */
public class TomcatServletWebServerFactory extends AbstractServletWebServerFactory
		implements ConfigurableTomcatWebServerFactory, ResourceLoaderAware {

	private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

	private static final Set<Class<?>> NO_CLASSES = Collections.emptySet();

	/**
	 * The class name of default protocol used.
	 */
	public static final String DEFAULT_PROTOCOL = "org.apache.coyote.http11.Http11NioProtocol";

	private File baseDirectory;

	private List<Valve> engineValves = new ArrayList<>();

	private List<Valve> contextValves = new ArrayList<>();

	private List<LifecycleListener> contextLifecycleListeners = getDefaultLifecycleListeners();

	private Set<TomcatContextCustomizer> tomcatContextCustomizers = new LinkedHashSet<>();

	private Set<TomcatConnectorCustomizer> tomcatConnectorCustomizers = new LinkedHashSet<>();

	private Set<TomcatProtocolHandlerCustomizer<?>> tomcatProtocolHandlerCustomizers = new LinkedHashSet<>();

	private final List<Connector> additionalTomcatConnectors = new ArrayList<>();

	private ResourceLoader resourceLoader;

	private String protocol = DEFAULT_PROTOCOL;

	private Set<String> tldSkipPatterns = new LinkedHashSet<>(TldSkipPatterns.DEFAULT);

	private Charset uriEncoding = DEFAULT_CHARSET;

	private int backgroundProcessorDelay;

	private boolean disableMBeanRegistry = true;

	/**
	 * Create a new {@link TomcatServletWebServerFactory} instance.
	 */
	public TomcatServletWebServerFactory() {
	}

	/**
	 * Create a new {@link TomcatServletWebServerFactory} that listens for requests using
	 * the specified port.
	 * @param port the port to listen on
	 */
	public TomcatServletWebServerFactory(int port) {
		super(port);
	}

	/**
	 * Create a new {@link TomcatServletWebServerFactory} with the specified context path
	 * and port.
	 * @param contextPath the root context path
	 * @param port the port to listen on
	 */
	public TomcatServletWebServerFactory(String contextPath, int port) {
		super(contextPath, port);
	}

	private static List<LifecycleListener> getDefaultLifecycleListeners() {
		AprLifecycleListener aprLifecycleListener = new AprLifecycleListener();
		return AprLifecycleListener.isAprAvailable() ? new ArrayList<>(Arrays.asList(aprLifecycleListener))
				: new ArrayList<>();
	}

	@Override
	public WebServer getWebServer(ServletContextInitializer... initializers) {
		if (this.disableMBeanRegistry) {
			Registry.disableRegistry();
		}
		Tomcat tomcat = new Tomcat();
		File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
		tomcat.setBaseDir(baseDir.getAbsolutePath());
		Connector connector = new Connector(this.protocol);
		connector.setThrowOnFailure(true);
		tomcat.getService().addConnector(connector);
		customizeConnector(connector);
		tomcat.setConnector(connector);
		tomcat.getHost().setAutoDeploy(false);
		configureEngine(tomcat.getEngine());
		for (Connector additionalConnector : this.additionalTomcatConnectors) {
			tomcat.getService().addConnector(additionalConnector);
		}
		prepareContext(tomcat.getHost(), initializers);
		return getTomcatWebServer(tomcat);
	}

	private void configureEngine(Engine engine) {
		engine.setBackgroundProcessorDelay(this.backgroundProcessorDelay);
		for (Valve valve : this.engineValves) {
			engine.getPipeline().addValve(valve);
		}
	}

	protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
		File documentRoot = getValidDocumentRoot();
		TomcatEmbeddedContext context = new TomcatEmbeddedContext();
		if (documentRoot != null) {
			context.setResources(new LoaderHidingResourceRoot(context));
		}
		context.setName(getContextPath());
		context.setDisplayName(getDisplayName());
		context.setPath(getContextPath());
		File docBase = (documentRoot != null) ? documentRoot : createTempDir("tomcat-docbase");
		context.setDocBase(docBase.getAbsolutePath());
		context.addLifecycleListener(new FixContextListener());
		context.setParentClassLoader((this.resourceLoader != null) ? this.resourceLoader.getClassLoader()
				: ClassUtils.getDefaultClassLoader());
		resetDefaultLocaleMapping(context);
		addLocaleMappings(context);
		context.setUseRelativeRedirects(false);
		try {
			context.setCreateUploadTargets(true);
		}
		catch (NoSuchMethodError ex) {
			// Tomcat is < 8.5.39. Continue.
		}
		configureTldSkipPatterns(context);
		WebappLoader loader = new WebappLoader(context.getParentClassLoader());
		loader.setLoaderClass(TomcatEmbeddedWebappClassLoader.class.getName());
		loader.setDelegate(true);
		context.setLoader(loader);
		if (isRegisterDefaultServlet()) {
			addDefaultServlet(context);
		}
		if (shouldRegisterJspServlet()) {
			addJspServlet(context);
			addJasperInitializer(context);
		}
		context.addLifecycleListener(new StaticResourceConfigurer(context));
		ServletContextInitializer[] initializersToUse = mergeInitializers(initializers);
		host.addChild(context);
		configureContext(context, initializersToUse);
		postProcessContext(context);
	}

	/**
	 * Override Tomcat's default locale mappings to align with other servers. See
	 * {@code org.apache.catalina.util.CharsetMapperDefault.properties}.
	 * @param context the context to reset
	 */
	private void resetDefaultLocaleMapping(TomcatEmbeddedContext context) {
		context.addLocaleEncodingMappingParameter(Locale.ENGLISH.toString(), DEFAULT_CHARSET.displayName());
		context.addLocaleEncodingMappingParameter(Locale.FRENCH.toString(), DEFAULT_CHARSET.displayName());
	}

	private void addLocaleMappings(TomcatEmbeddedContext context) {
		getLocaleCharsetMappings().forEach(
				(locale, charset) -> context.addLocaleEncodingMappingParameter(locale.toString(), charset.toString()));
	}

	private void configureTldSkipPatterns(TomcatEmbeddedContext context) {
		StandardJarScanFilter filter = new StandardJarScanFilter();
		filter.setTldSkip(StringUtils.collectionToCommaDelimitedString(this.tldSkipPatterns));
		context.getJarScanner().setJarScanFilter(filter);
	}

	private void addDefaultServlet(Context context) {
		Wrapper defaultServlet = context.createWrapper();
		defaultServlet.setName("default");
		defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
		defaultServlet.addInitParameter("debug", "0");
		defaultServlet.addInitParameter("listings", "false");
		defaultServlet.setLoadOnStartup(1);
		// Otherwise the default location of a Spring DispatcherServlet cannot be set
		defaultServlet.setOverridable(true);
		context.addChild(defaultServlet);
		context.addServletMappingDecoded("/", "default");
	}

	private void addJspServlet(Context context) {
		Wrapper jspServlet = context.createWrapper();
		jspServlet.setName("jsp");
		jspServlet.setServletClass(getJsp().getClassName());
		jspServlet.addInitParameter("fork", "false");
		getJsp().getInitParameters().forEach(jspServlet::addInitParameter);
		jspServlet.setLoadOnStartup(3);
		context.addChild(jspServlet);
		context.addServletMappingDecoded("*.jsp", "jsp");
		context.addServletMappingDecoded("*.jspx", "jsp");
	}

	private void addJasperInitializer(TomcatEmbeddedContext context) {
		try {
			ServletContainerInitializer initializer = (ServletContainerInitializer) ClassUtils
					.forName("org.apache.jasper.servlet.JasperInitializer", null).newInstance();
			context.addServletContainerInitializer(initializer, null);
		}
		catch (Exception ex) {
			// Probably not Tomcat 8
		}
	}

	// Needs to be protected so it can be used by subclasses
	protected void customizeConnector(Connector connector) {
		int port = Math.max(getPort(), 0);
		connector.setPort(port);
		if (StringUtils.hasText(this.getServerHeader())) {
			connector.setAttribute("server", this.getServerHeader());
		}
		if (connector.getProtocolHandler() instanceof AbstractProtocol) {
			customizeProtocol((AbstractProtocol<?>) connector.getProtocolHandler());
		}
		invokeProtocolHandlerCustomizers(connector.getProtocolHandler());
		if (getUriEncoding() != null) {
			connector.setURIEncoding(getUriEncoding().name());
		}
		// Don't bind to the socket prematurely if ApplicationContext is slow to start
		connector.setProperty("bindOnInit", "false");
		if (getSsl() != null && getSsl().isEnabled()) {
			customizeSsl(connector);
		}
		TomcatConnectorCustomizer compression = new CompressionConnectorCustomizer(getCompression());
		compression.customize(connector);
		for (TomcatConnectorCustomizer customizer : this.tomcatConnectorCustomizers) {
			customizer.customize(connector);
		}
	}

	private void customizeProtocol(AbstractProtocol<?> protocol) {
		if (getAddress() != null) {
			protocol.setAddress(getAddress());
		}
	}

	@SuppressWarnings("unchecked")
	private void invokeProtocolHandlerCustomizers(ProtocolHandler protocolHandler) {
		LambdaSafe.callbacks(TomcatProtocolHandlerCustomizer.class, this.tomcatProtocolHandlerCustomizers,
				protocolHandler).invoke((customizer) -> customizer.customize(protocolHandler));
	}

	private void customizeSsl(Connector connector) {
		new SslConnectorCustomizer(getSsl(), getSslStoreProvider()).customize(connector);
		if (getHttp2() != null && getHttp2().isEnabled()) {
			connector.addUpgradeProtocol(new Http2Protocol());
		}
	}

	/**
	 * Configure the Tomcat {@link Context}.
	 * @param context the Tomcat context
	 * @param initializers initializers to apply
	 */
	protected void configureContext(Context context, ServletContextInitializer[] initializers) {
		TomcatStarter starter = new TomcatStarter(initializers);
		if (context instanceof TomcatEmbeddedContext) {
			TomcatEmbeddedContext embeddedContext = (TomcatEmbeddedContext) context;
			embeddedContext.setStarter(starter);
			embeddedContext.setFailCtxIfServletStartFails(true);
		}
		context.addServletContainerInitializer(starter, NO_CLASSES);
		for (LifecycleListener lifecycleListener : this.contextLifecycleListeners) {
			context.addLifecycleListener(lifecycleListener);
		}
		for (Valve valve : this.contextValves) {
			context.getPipeline().addValve(valve);
		}
		for (ErrorPage errorPage : getErrorPages()) {
			org.apache.tomcat.util.descriptor.web.ErrorPage tomcatErrorPage = new org.apache.tomcat.util.descriptor.web.ErrorPage();
			tomcatErrorPage.setLocation(errorPage.getPath());
			tomcatErrorPage.setErrorCode(errorPage.getStatusCode());
			tomcatErrorPage.setExceptionType(errorPage.getExceptionName());
			context.addErrorPage(tomcatErrorPage);
		}
		for (MimeMappings.Mapping mapping : getMimeMappings()) {
			context.addMimeMapping(mapping.getExtension(), mapping.getMimeType());
		}
		configureSession(context);
		new DisableReferenceClearingContextCustomizer().customize(context);
		for (TomcatContextCustomizer customizer : this.tomcatContextCustomizers) {
			customizer.customize(context);
		}
	}

	private void configureSession(Context context) {
		long sessionTimeout = getSessionTimeoutInMinutes();
		context.setSessionTimeout((int) sessionTimeout);
		Boolean httpOnly = getSession().getCookie().getHttpOnly();
		if (httpOnly != null) {
			context.setUseHttpOnly(httpOnly);
		}
		if (getSession().isPersistent()) {
			Manager manager = context.getManager();
			if (manager == null) {
				manager = new StandardManager();
				context.setManager(manager);
			}
			configurePersistSession(manager);
		}
		else {
			context.addLifecycleListener(new DisablePersistSessionListener());
		}
	}

	private void configurePersistSession(Manager manager) {
		Assert.state(manager instanceof StandardManager,
				() -> "Unable to persist HTTP session state using manager type " + manager.getClass().getName());
		File dir = getValidSessionStoreDir();
		File file = new File(dir, "SESSIONS.ser");
		((StandardManager) manager).setPathname(file.getAbsolutePath());
	}

	private long getSessionTimeoutInMinutes() {
		Duration sessionTimeout = getSession().getTimeout();
		if (isZeroOrLess(sessionTimeout)) {
			return 0;
		}
		return Math.max(sessionTimeout.toMinutes(), 1);
	}

	private boolean isZeroOrLess(Duration sessionTimeout) {
		return sessionTimeout == null || sessionTimeout.isNegative() || sessionTimeout.isZero();
	}

	/**
	 * Post process the Tomcat {@link Context} before it's used with the Tomcat Server.
	 * Subclasses can override this method to apply additional processing to the
	 * {@link Context}.
	 * @param context the Tomcat {@link Context}
	 */
	protected void postProcessContext(Context context) {
	}

	/**
	 * Factory method called to create the {@link TomcatWebServer}. Subclasses can
	 * override this method to return a different {@link TomcatWebServer} or apply
	 * additional processing to the Tomcat server.
	 * @param tomcat the Tomcat server.
	 * @return a new {@link TomcatWebServer} instance
	 */
	protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
		return new TomcatWebServer(tomcat, getPort() >= 0, getShutdown().getGracePeriod());
	}

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	@Override
	public void setBaseDirectory(File baseDirectory) {
		this.baseDirectory = baseDirectory;
	}

	/**
	 * Returns a mutable set of the patterns that match jars to ignore for TLD scanning.
	 * @return the list of jars to ignore for TLD scanning
	 */
	public Set<String> getTldSkipPatterns() {
		return this.tldSkipPatterns;
	}

	/**
	 * Set the patterns that match jars to ignore for TLD scanning. See Tomcat's
	 * catalina.properties for typical values. Defaults to a list drawn from that source.
	 * @param patterns the jar patterns to skip when scanning for TLDs etc
	 */
	public void setTldSkipPatterns(Collection<String> patterns) {
		Assert.notNull(patterns, "Patterns must not be null");
		this.tldSkipPatterns = new LinkedHashSet<>(patterns);
	}

	/**
	 * Add patterns that match jars to ignore for TLD scanning. See Tomcat's
	 * catalina.properties for typical values.
	 * @param patterns the additional jar patterns to skip when scanning for TLDs etc
	 */
	public void addTldSkipPatterns(String... patterns) {
		Assert.notNull(patterns, "Patterns must not be null");
		this.tldSkipPatterns.addAll(Arrays.asList(patterns));
	}

	/**
	 * The Tomcat protocol to use when create the {@link Connector}.
	 * @param protocol the protocol
	 * @see Connector#Connector(String)
	 */
	public void setProtocol(String protocol) {
		Assert.hasLength(protocol, "Protocol must not be empty");
		this.protocol = protocol;
	}

	/**
	 * Set {@link Valve}s that should be applied to the Tomcat {@link Engine}. Calling
	 * this method will replace any existing valves.
	 * @param engineValves the valves to set
	 */
	public void setEngineValves(Collection<? extends Valve> engineValves) {
		Assert.notNull(engineValves, "Valves must not be null");
		this.engineValves = new ArrayList<>(engineValves);
	}

	/**
	 * Returns a mutable collection of the {@link Valve}s that will be applied to the
	 * Tomcat {@link Engine}.
	 * @return the engine valves that will be applied
	 */
	public Collection<Valve> getEngineValves() {
		return this.engineValves;
	}

	@Override
	public void addEngineValves(Valve... engineValves) {
		Assert.notNull(engineValves, "Valves must not be null");
		this.engineValves.addAll(Arrays.asList(engineValves));
	}

	/**
	 * Set {@link Valve}s that should be applied to the Tomcat {@link Context}. Calling
	 * this method will replace any existing valves.
	 * @param contextValves the valves to set
	 */
	public void setContextValves(Collection<? extends Valve> contextValves) {
		Assert.notNull(contextValves, "Valves must not be null");
		this.contextValves = new ArrayList<>(contextValves);
	}

	/**
	 * Returns a mutable collection of the {@link Valve}s that will be applied to the
	 * Tomcat {@link Context}.
	 * @return the context valves that will be applied
	 * @see #getEngineValves()
	 */
	public Collection<Valve> getContextValves() {
		return this.contextValves;
	}

	/**
	 * Add {@link Valve}s that should be applied to the Tomcat {@link Context}.
	 * @param contextValves the valves to add
	 */
	public void addContextValves(Valve... contextValves) {
		Assert.notNull(contextValves, "Valves must not be null");
		this.contextValves.addAll(Arrays.asList(contextValves));
	}

	/**
	 * Set {@link LifecycleListener}s that should be applied to the Tomcat
	 * {@link Context}. Calling this method will replace any existing listeners.
	 * @param contextLifecycleListeners the listeners to set
	 */
	public void setContextLifecycleListeners(Collection<? extends LifecycleListener> contextLifecycleListeners) {
		Assert.notNull(contextLifecycleListeners, "ContextLifecycleListeners must not be null");
		this.contextLifecycleListeners = new ArrayList<>(contextLifecycleListeners);
	}

	/**
	 * Returns a mutable collection of the {@link LifecycleListener}s that will be applied
	 * to the Tomcat {@link Context}.
	 * @return the context lifecycle listeners that will be applied
	 */
	public Collection<LifecycleListener> getContextLifecycleListeners() {
		return this.contextLifecycleListeners;
	}

	/**
	 * Add {@link LifecycleListener}s that should be added to the Tomcat {@link Context}.
	 * @param contextLifecycleListeners the listeners to add
	 */
	public void addContextLifecycleListeners(LifecycleListener... contextLifecycleListeners) {
		Assert.notNull(contextLifecycleListeners, "ContextLifecycleListeners must not be null");
		this.contextLifecycleListeners.addAll(Arrays.asList(contextLifecycleListeners));
	}

	/**
	 * Set {@link TomcatContextCustomizer}s that should be applied to the Tomcat
	 * {@link Context}. Calling this method will replace any existing customizers.
	 * @param tomcatContextCustomizers the customizers to set
	 */
	public void setTomcatContextCustomizers(Collection<? extends TomcatContextCustomizer> tomcatContextCustomizers) {
		Assert.notNull(tomcatContextCustomizers, "TomcatContextCustomizers must not be null");
		this.tomcatContextCustomizers = new LinkedHashSet<>(tomcatContextCustomizers);
	}

	/**
	 * Returns a mutable collection of the {@link TomcatContextCustomizer}s that will be
	 * applied to the Tomcat {@link Context}.
	 * @return the listeners that will be applied
	 */
	public Collection<TomcatContextCustomizer> getTomcatContextCustomizers() {
		return this.tomcatContextCustomizers;
	}

	@Override
	public void addContextCustomizers(TomcatContextCustomizer... tomcatContextCustomizers) {
		Assert.notNull(tomcatContextCustomizers, "TomcatContextCustomizers must not be null");
		this.tomcatContextCustomizers.addAll(Arrays.asList(tomcatContextCustomizers));
	}

	/**
	 * Set {@link TomcatConnectorCustomizer}s that should be applied to the Tomcat
	 * {@link Connector}. Calling this method will replace any existing customizers.
	 * @param tomcatConnectorCustomizers the customizers to set
	 */
	public void setTomcatConnectorCustomizers(
			Collection<? extends TomcatConnectorCustomizer> tomcatConnectorCustomizers) {
		Assert.notNull(tomcatConnectorCustomizers, "TomcatConnectorCustomizers must not be null");
		this.tomcatConnectorCustomizers = new LinkedHashSet<>(tomcatConnectorCustomizers);
	}

	@Override
	public void addConnectorCustomizers(TomcatConnectorCustomizer... tomcatConnectorCustomizers) {
		Assert.notNull(tomcatConnectorCustomizers, "TomcatConnectorCustomizers must not be null");
		this.tomcatConnectorCustomizers.addAll(Arrays.asList(tomcatConnectorCustomizers));
	}

	/**
	 * Returns a mutable collection of the {@link TomcatConnectorCustomizer}s that will be
	 * applied to the Tomcat {@link Connector}.
	 * @return the customizers that will be applied
	 */
	public Collection<TomcatConnectorCustomizer> getTomcatConnectorCustomizers() {
		return this.tomcatConnectorCustomizers;
	}

	/**
	 * Set {@link TomcatProtocolHandlerCustomizer}s that should be applied to the Tomcat
	 * {@link Connector}. Calling this method will replace any existing customizers.
	 * @param tomcatProtocolHandlerCustomizer the customizers to set
	 * @since 2.2.0
	 */
	public void setTomcatProtocolHandlerCustomizers(
			Collection<? extends TomcatProtocolHandlerCustomizer<?>> tomcatProtocolHandlerCustomizer) {
		Assert.notNull(tomcatProtocolHandlerCustomizer, "TomcatProtocolHandlerCustomizers must not be null");
		this.tomcatProtocolHandlerCustomizers = new LinkedHashSet<>(tomcatProtocolHandlerCustomizer);
	}

	/**
	 * Add {@link TomcatProtocolHandlerCustomizer}s that should be added to the Tomcat
	 * {@link Connector}.
	 * @param tomcatProtocolHandlerCustomizers the customizers to add
	 * @since 2.2.0
	 */
	@Override
	public void addProtocolHandlerCustomizers(TomcatProtocolHandlerCustomizer<?>... tomcatProtocolHandlerCustomizers) {
		Assert.notNull(tomcatProtocolHandlerCustomizers, "TomcatProtocolHandlerCustomizers must not be null");
		this.tomcatProtocolHandlerCustomizers.addAll(Arrays.asList(tomcatProtocolHandlerCustomizers));
	}

	/**
	 * Returns a mutable collection of the {@link TomcatProtocolHandlerCustomizer}s that
	 * will be applied to the Tomcat {@link Connector}.
	 * @return the customizers that will be applied
	 * @since 2.2.0
	 */
	public Collection<TomcatProtocolHandlerCustomizer<?>> getTomcatProtocolHandlerCustomizers() {
		return this.tomcatProtocolHandlerCustomizers;
	}

	/**
	 * Add {@link Connector}s in addition to the default connector, e.g. for SSL or AJP
	 * @param connectors the connectors to add
	 */
	public void addAdditionalTomcatConnectors(Connector... connectors) {
		Assert.notNull(connectors, "Connectors must not be null");
		this.additionalTomcatConnectors.addAll(Arrays.asList(connectors));
	}

	/**
	 * Returns a mutable collection of the {@link Connector}s that will be added to the
	 * Tomcat.
	 * @return the additionalTomcatConnectors
	 */
	public List<Connector> getAdditionalTomcatConnectors() {
		return this.additionalTomcatConnectors;
	}

	@Override
	public void setUriEncoding(Charset uriEncoding) {
		this.uriEncoding = uriEncoding;
	}

	/**
	 * Returns the character encoding to use for URL decoding.
	 * @return the URI encoding
	 */
	public Charset getUriEncoding() {
		return this.uriEncoding;
	}

	@Override
	public void setBackgroundProcessorDelay(int delay) {
		this.backgroundProcessorDelay = delay;
	}

	/**
	 * Set whether the factory should disable Tomcat's MBean registry prior to creating
	 * the server.
	 * @param disableMBeanRegistry whether to disable the MBean registry
	 * @since 2.2.0
	 */
	public void setDisableMBeanRegistry(boolean disableMBeanRegistry) {
		this.disableMBeanRegistry = disableMBeanRegistry;
	}

	/**
	 * {@link LifecycleListener} to disable persistence in the {@link StandardManager}. A
	 * {@link LifecycleListener} is used so not to interfere with Tomcat's default manager
	 * creation logic.
	 */
	private static class DisablePersistSessionListener implements LifecycleListener {

		@Override
		public void lifecycleEvent(LifecycleEvent event) {
			if (event.getType().equals(Lifecycle.START_EVENT)) {
				Context context = (Context) event.getLifecycle();
				Manager manager = context.getManager();
				if (manager instanceof StandardManager) {
					((StandardManager) manager).setPathname(null);
				}
			}
		}

	}

	private final class StaticResourceConfigurer implements LifecycleListener {

		private final Context context;

		private StaticResourceConfigurer(Context context) {
			this.context = context;
		}

		@Override
		public void lifecycleEvent(LifecycleEvent event) {
			if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) {
				addResourceJars(getUrlsOfJarsWithMetaInfResources());
			}
		}

		private void addResourceJars(List<URL> resourceJarUrls) {
			for (URL url : resourceJarUrls) {
				String path = url.getPath();
				if (path.endsWith(".jar") || path.endsWith(".jar!/")) {
					String jar = url.toString();
					if (!jar.startsWith("jar:")) {
						// A jar file in the file system. Convert to Jar URL.
						jar = "jar:" + jar + "!/";
					}
					addResourceSet(jar);
				}
				else {
					addResourceSet(url.toString());
				}
			}
		}

		private void addResourceSet(String resource) {
			try {
				if (isInsideNestedJar(resource)) {
					// It's a nested jar but we now don't want the suffix because Tomcat
					// is going to try and locate it as a root URL (not the resource
					// inside it)
					resource = resource.substring(0, resource.length() - 2);
				}
				URL url = new URL(resource);
				String path = "/META-INF/resources";
				this.context.getResources().createWebResourceSet(ResourceSetType.RESOURCE_JAR, "/", url, path);
			}
			catch (Exception ex) {
				// Ignore (probably not a directory)
			}
		}

		private boolean isInsideNestedJar(String dir) {
			return dir.indexOf("!/") < dir.lastIndexOf("!/");
		}

	}

	private static final class LoaderHidingResourceRoot extends StandardRoot {

		private LoaderHidingResourceRoot(TomcatEmbeddedContext context) {
			super(context);
		}

		@Override
		protected WebResourceSet createMainResourceSet() {
			return new LoaderHidingWebResourceSet(super.createMainResourceSet());
		}

	}

	private static final class LoaderHidingWebResourceSet extends AbstractResourceSet {

		private final WebResourceSet delegate;

		private final Method initInternal;

		private LoaderHidingWebResourceSet(WebResourceSet delegate) {
			this.delegate = delegate;
			try {
				this.initInternal = LifecycleBase.class.getDeclaredMethod("initInternal");
				this.initInternal.setAccessible(true);
			}
			catch (Exception ex) {
				throw new IllegalStateException(ex);
			}
		}

		@Override
		public WebResource getResource(String path) {
			if (path.startsWith("/org/springframework/boot")) {
				return new EmptyResource(getRoot(), path);
			}
			return this.delegate.getResource(path);
		}

		@Override
		public String[] list(String path) {
			return this.delegate.list(path);
		}

		@Override
		public Set<String> listWebAppPaths(String path) {
			return this.delegate.listWebAppPaths(path).stream()
					.filter((webAppPath) -> !webAppPath.startsWith("/org/springframework/boot"))
					.collect(Collectors.toSet());
		}

		@Override
		public boolean mkdir(String path) {
			return this.delegate.mkdir(path);
		}

		@Override
		public boolean write(String path, InputStream is, boolean overwrite) {
			return this.delegate.write(path, is, overwrite);
		}

		@Override
		public URL getBaseUrl() {
			return this.delegate.getBaseUrl();
		}

		@Override
		public void setReadOnly(boolean readOnly) {
			this.delegate.setReadOnly(readOnly);
		}

		@Override
		public boolean isReadOnly() {
			return this.delegate.isReadOnly();
		}

		@Override
		public void gc() {
			this.delegate.gc();
		}

		@Override
		protected void initInternal() throws LifecycleException {
			if (this.delegate instanceof LifecycleBase) {
				try {
					ReflectionUtils.invokeMethod(this.initInternal, this.delegate);
				}
				catch (Exception ex) {
					throw new LifecycleException(ex);
				}
			}
		}

	}

}


text:
<?php

namespace ONGR\ElasticsearchBundle\Tests\Unit\Result\Suggestion;

use ONGR\ElasticsearchBundle\Result\Suggestion\Option\CompletionOption;

/**
 * Unit tests for completion option.
 */
class CompletionOptionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Check if getters works as expected.
     */
    public function testGetters()
    {
        $completion = new CompletionOption('test', 1.0, ['my' => 'test']);
        $this->assertEquals('test', $completion->getText());
        $this->assertEquals(1.0, $completion->getScore());
        $this->assertEquals(['my' => 'test'], $completion->getPayload());
    }
}


text:
# Localization

In order to handle the complex international differences in number and date formats `react-widgets` relies on third party
parsing and formatting libraries through the use of specific "localizers". `react-widgets` comes with
built-in localizers for __Globalize.js__, __Moment.js__ and a simple number localizer, but you can easily write
your own for whatever library you are using.

Localization sensitive widgets have `format` props that passed directly to your chosen localizer. The type and shape
of these format props is determined by the api of the backing I18n strategy. Moment.js, for instance,
uses string based date formats like: `MMM dd YYYY` whereas the newer Globalize.js may take an object like:
`{ skeleton: GyMMMd }`. Regardless of the localizer, formats always accept `function` values for doing on-the-fly custom
formatting.

### Globalize.js (recommended) date, number

Globalize can be a bit of a challenge to set up correctly so please consult the [globalize docs](https://github.com/jquery/globalize#getting-started) for a lot of info on setting up
Globalize and integrating into lots of different app environments.

The globalize localizer handles both __number__ and __date__ localization so there is no need for any additional
localizers.

__NOTE: If you like the pre `1.0.0` globalize api, the localizer still supports that version, just be sure
to install it, and follow the old docs for setup__

```js

var Globalize = require('globalize')
var globalizeLocalizer = require('../lib/localizers/globalize')

Globalize.load(/* load the date and number modules */)
Globalize.locale('en-GB')

globalizeLocalizer(Globalize);

```

Globalize [formats](https://github.com/jquery/globalize/blob/master/doc/api/date/date-formatter.md#parameters) can
be either `string`s, or `object`s. Date `string` formats are automatically considered `raw` patterns,
and are equivalent to `globalize.formatDate(date, { raw: format })`. Number formats accept any of
the [Globalize number options](https://github.com/jquery/globalize/blob/master/doc/api/number/number-formatter.md#parameters).
In addition you can specify _currencies_ by adding the `currency` key like: `{ currency: "USD", style: 'decimal' }`.

```js
  <DateTimePicker format='mmm YYY'/>
  <DateTimePicker format={{ date: 'full' }}/>

  <NumberPicker format={{ style: 'percent', maximumFractionDigits: 2 }}/>
  <NumberPicker format={{ currency: 'USD', style: "accounting" }}/>
```

### Moment.js date

Again see the official [Moment docs](http://momentjs.com/) for information on integrating Moment into your build
pipeline effectively.

Moment only provides __date__ localization, if you also need Number localization consider
the __simple-number__ localizer below, or Globalize.js.

```js
var Moment = require('moment')
var momentLocalizer = require('../lib/localizers/moment')

momentLocalizer(Moment);
```

Moment [format](http://momentjs.com/docs/#/displaying/format/) props accept `string`s

```js
 <DateTimePicker format='mmm YYY'/>
```

### Simple Number number

The `simple-number` localizer provides a minimal number formatting and parsing strategy. Its best when you don't need
robust locale support for currencies, and numbers;

```js
var numberLocalizer = require('../lib/localizers/simple-number')

numberLocalizer();
```

Check out the documentation for [format-number-with-string](https://www.npmjs.com/package/format-number-with-string) for
a complete guide to its format syntax.

```js
  <NumberPicker format='-$#,###.00'/>
```

## Creating a Localizer

Creating a localizer is as easy as providing `react-widgets` an localizer options object.
Localizers must provide `parse()` and `format()` functions as well as provide default values for all the
required formats the widgets need.

Formats can be whatever type your localization strategy requires (strings, objects, etc), however functions are
always valid. The default formats, for example, can be strings or functions.
If you wanted to use the built-in `Intl` api's for formatting, formats might be an options object to
pass to `Intl.DateTimeFormat()`. Function formats are called automatically by the localizer with the `value`,
the `culture` string and the localizer instance.

```js
var localizer = {

  formats: {
    day: 'DD',
    month: 'mmm',
    // we always pass a function for more advanced formats such as returning a year 'range'
    // to represent a decade e.g "2000 - 2009". Notice the localizer instance is the third argument,
    // which can be used to format or parse as needed.
    decade: (date, culture, localizer) => {
      return localizer.format(date, 'YYYY') + ' - ' + localizer.format(lastYearOfDecade(date), 'YYYY')
    }
  },

  parse(value, format, cultureStr){
    return parsedDate
  },

  format(value, format, cultureStr){
    return formattedDateString
  }
}

ReactWidgets.setDateLocalizer(localizer)
```

## Localizer Api

### `DateLocalizer`
An Object implementing the following api.

```
{
  propType: PropType?,
  formats: Object,
  firstOfWeek: Function,
  parse: Function,
  format: Function
}
```

#### required formats
_Localizers must provide default values for each required format._

- `default`: the default date diaplay format, generally a "long" format showing both date and time
- `date`: A date only format
- `time`: A time only format
- `header`: The heading of the Calendar month view, contextuals the current month, e.g. "Jan 2014"
- `footer`: The Calendar footer format, for displaying Today's date
- `dayOfMonth`: The day of the month
- `month`: Month name, used in the Year view of the Calendar
- `year`: year format, used in the Decade view of the Calendar
- `decade`: a decade format, used in the Century view of the Calendar, eg. "2010 - 2019"
- `century`: A century format, used the in the Calendar heading

#### `propType` (optional)
A React PropType that is used to validate the Date formats

#### `parse`
Convert a locale formatted string to a JavaScript Date object.

```
function(
  value: String,
  format: String|Object,
  culture: String?
) -> Date?
```

#### `format`
Convert a Date object to a locale specific string

```
function(
  value: Date?,
  format: String|Object,
  culture: String?
) -> String
```

#### `firstOfWeek`

Return the locale specific first day of the week from 0 (Sunday) to 6 (Saturday).

```
function(
  culture: String?
) -> number (0 -6)
```

### `NumberLocalizer`
An Object implementing the following api.
```
{
  propType: PropType?,
  formats: Object,
  parse: Function,
  format: Function,
  precision: Function
}
```

#### required formats
_Localizers must provide default values for each required format._

- `default` The number picker display format.

#### `propType` (optional)
A React PropType that is used to validate the number formats.

#### `parse`
Convert a locale specific string to a JavaScript Number.
```
function(
 value: String,
 culture: String?
) -> Date?

```

#### `format`

Convert a Number to a locale specific string.

```
function(
 value: Number?,
 format: String|Object,
 culture: String?
) -> String
```

#### `precision`

Return the decimal precision for a given format or culture. Necessary for dealing with the quirks of floating point math.

```
function(
 format: String|Object,
 culture: String?
) -> Number
```


text:
<?php
namespace Neos\Flow\Tests\Functional\ObjectManagement\Fixtures;

use Neos\Flow\Annotations as Flow;

/**
 * A class for testing setting injection
 */
class ClassWithInjectedConfiguration
{
    /**
     * @Flow\InjectConfiguration(path="some.nonExisting.setting")
     * @var string
     */
    protected $nonExistingSetting = 'defaultValue';

    /**
     * @Flow\InjectConfiguration(path="tests.functional.settingInjection.someSetting")
     * @var string
     */
    protected $injectedSettingA;

    /**
     * @Flow\InjectConfiguration(path="tests.functional.settingInjection.someSetting", package="Neos.Flow")
     * @var string
     */
    protected $injectedSettingB;

    /**
     * @Flow\InjectConfiguration(path="tests.functional.settingInjection.someSetting", package="Neos.Flow")
     * @var string
     */
    protected $injectedSettingWithSetter;

    /**
     * @Flow\InjectConfiguration(package="Neos.Flow")
     * @var array
     */
    protected $injectedSpecifiedPackageSettings;

    /**
     * @Flow\InjectConfiguration
     * @var array
     */
    protected $injectedCurrentPackageSettings;

    /**
     * @var array
     */
    protected $settings;

    /**
     * @Flow\InjectConfiguration(type="Views")
     * @var array
     */
    protected $injectedViewsConfiguration;

    /**
     * @param array $settings
     * @return void
     */
    public function injectSettings(array $settings)
    {
        $this->settings = $settings;
    }

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

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

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

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

    /**
     * @param string $injectedSettingWithSetter
     * @return void
     */
    public function setInjectedSettingWithSetter($injectedSettingWithSetter)
    {
        $this->injectedSettingWithSetter = strtoupper($injectedSettingWithSetter);
    }

    /**
     * @return array
     */
    public function getSettings()
    {
        return $this->settings;
    }

    /**
     * @return array
     */
    public function getInjectedSpecifiedPackageSettings()
    {
        return $this->injectedSpecifiedPackageSettings;
    }

    /**
     * @return array
     */
    public function getInjectedCurrentPackageSettings()
    {
        return $this->injectedCurrentPackageSettings;
    }

    /**
     * @return array
     */
    public function getInjectedViewsConfiguration()
    {
        return $this->injectedViewsConfiguration;
    }
}


text:
<?php

namespace Zpi\PaperBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Zpi\UserBundle\Entity\User;

/**
 * Zpi\PaperBundle\Entity\UserPaper
 *
 * @ORM\Table(name="users_papers")
 * @ORM\Entity
 */
class UserPaper
{
    const TYPE_EDITOR = 3;
    const TYPE_TECH_EDITOR = 4;
    const TYPE_AUTHOR = 1;
    const TYPE_AUTHOR_EXISTING = 2;

    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Zpi\UserBundle\Entity\User", cascade={"persist"})
     */
    private $user;

    /**
     * @ORM\ManyToOne(targetEntity="Zpi\PaperBundle\Entity\Paper")
     */
    private $paper;

    /**
     * @var integer $author
     *
     * @ORM\Column(name="author", type="smallint")
     */
    private $author;

     /**
     * @var integer $editor
     *
     * @ORM\Column(name="editor", type="smallint")
     */
    private $editor;

     /**
     * @var integer $techEditor
     *
     * @ORM\Column(name="tech_editor", type="smallint")
     */
    private $techEditor;

    public function __construct(User $user, Paper $paper, $author = 0, $editor = 0, $techEditor = 0)
    {
        $this->user = $user;
        $this->paper = $paper;
        $this->author = $author;
        $this->editor = $editor;
        $this->techEditor = $techEditor;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set user
     *
     * @param Zpi\PaperBundle\Entity\UserPaper $user
     */
    public function setUser(\Zpi\PaperBundle\Entity\UserPaper $user)
    {
        $this->user = $user;
    }

    /**
     * Get user
     *
     * @return Zpi\PaperBundle\Entity\UserPaper
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Set paper
     *
     * @param Zpi\PaperBundle\Entity\UserPaper $paper
     */
    public function setPaper(\Zpi\PaperBundle\Entity\UserPaper $paper)
    {
        $this->paper = $paper;
    }

    /**
     * Get paper
     *
     * @return Zpi\PaperBundle\Entity\UserPaper
     */
    public function getPaper()
    {
        return $this->paper;
    }

    /**
     * Get paper title
     *
     * @return Zpi\PaperBundle\Entity\Paper
     */
    public function getTitle()
    {
        return $this->getPaper()->getTitle();
    }

    /**
     * Get paper abstract
     *
     * @return Zpi\PaperBundle\Entity\Paper
     */
    public function getAbstract()
    {
        return $this->getPaper()->getAbstract();
    }

    /**
     * Set author
     *
     * @param smallint $author
     */
    public function setAuthor($author)
    {
        $this->author = $author;
    }

    /**
     * Get author
     *
     * @return smallint
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * Set editor
     *
     * @param smallint $editor
     */
    public function setEditor($editor)
    {
        $this->editor = $editor;
    }

    /**
     * Get editor
     *
     * @return smallint
     */
    public function getEditor()
    {
        return $this->editor;
    }

    /**
     * Set techEditor
     *
     * @param smallint $techEditor
     */
    public function setTechEditor($techEditor)
    {
        $this->techEditor = $techEditor;
    }

    /**
     * Get techEditor
     *
     * @return smallint
     */
    public function getTechEditor()
    {
        return $this->techEditor;
    }

    public function isType($type)
    {
        switch ($type)
        {
            case UserPaper::TYPE_AUTHOR:
                return $this->author;
            case UserPaper::TYPE_EDITOR:
                return $this->editor;
            case UserPaper::TYPE_TECH_EDITOR;
                return $this->techEditor;
        }
    }
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RandomColorScript : MonoBehaviour {

    Renderer ren;

	// Use this for initialization
	void Start () {
        RandomColor();
	}

	// Update is called once per frame
	void Update () {

	}

    public void RandomColor()
    {
        if (ren == null) ren = gameObject.GetComponent<Renderer>();
        ren.material.color = Random.ColorHSV(0, 1);
    }
}


text:
class Object #:nodoc:#
	def hm_metaclass #:nodoc:#
    class << self
      self
    end
  end

	def hm_meta_eval(&blk) #:nodoc:#
    hm_metaclass.instance_eval(&blk)
  end

	def hm_meta_def(name, &blk) #:nodoc:#
		hm_meta_eval { define_method name, &blk }
	end
end

module Hardmock

  # == Hardmock: Stubbing and Mocking Concrete Methods
  #
  # Hardmock lets you stub and/or mock methods on concrete classes or objects.
  #
  # * To "stub" a concrete method is to rig it to return the same thing always, disregarding any arguments.
  # * To "mock" a concrete method is to surplant its funcionality by delegating to a mock object who will cover this behavior.
  #
  # Mocked methods have their expectations considered along with all other mock object expectations.
  #
  # If you use stubbing or concrete mocking in the absence (or before creation) of other mocks, you need to invoke <tt>prepare_hardmock_control</tt>.
  # Once <tt>verify_mocks</tt> or <tt>clear_expectaions</tt> is called, the overriden behavior in the target objects is restored.
  #
  # == Examples
  #
  #   River.stubs!(:sounds_like).returns("gurgle")
  #
  #   River.expects!(:jump).returns("splash")
  #
  #   rogue.stubs!(:sounds_like).returns("pshshsh")
  #
  #   rogue.expects!(:rawhide_tanning_solvents).returns("giant snapping turtles")
  #
  module Stubbing
    # Exists only for documentation
  end

  class ReplacedMethod #:nodoc:#
    attr_reader :target, :method_name

    def initialize(target, method_name)
      @target = target
      @method_name = method_name

      Hardmock.track_replaced_method self
    end
  end

  class StubbedMethod < ReplacedMethod #:nodoc:#
    def invoke(args)
      raise @raises if @raises
      @return_value
    end

    def returns(stubbed_return)
      @return_value = stubbed_return
    end

    def raises(err)
      err = RuntimeError.new(err) unless err.kind_of?(Exception)
      @raises = err
    end
  end

  class ::Object
    def stubs!(method_name)
      method_name = method_name.to_s
      already_stubbed = Hardmock.has_replaced_method?(self, method_name)

      stubbed_method = Hardmock::StubbedMethod.new(self, method_name)

      unless _is_mock? or already_stubbed
        if methods.map do |m| m.to_s end.include?(method_name)
          hm_meta_eval do
            alias_method "_hardmock_original_#{method_name}".to_sym, method_name.to_sym
          end
        end
      end

      hm_meta_def method_name do |*args|
        stubbed_method.invoke(args)
      end

      stubbed_method
    end

    def expects!(method_name, *args, &block)
      if self._is_mock?
        raise Hardmock::StubbingError, "Cannot use 'expects!(:#{method_name})' on a Mock object; try 'expects' instead"
      end

      method_name = method_name.to_s

      @_my_mock = Mock.new(_my_name, $main_mock_control) if @_my_mock.nil?

      unless Hardmock.has_replaced_method?(self, method_name)
        # Track the method as replaced
        Hardmock::ReplacedMethod.new(self, method_name)

        # Preserver original implementation of the method by aliasing it away
        if methods.map do |m| m.to_s end.include?(method_name.to_s)
          hm_meta_eval do
            alias_method "_hardmock_original_#{method_name}".to_sym, method_name.to_sym
          end
        end

        # Re-define the method to utilize our patron mock instance.
        # (This global-temp-var thing is hokey but I was having difficulty generating
        # code for the meta class.)
        begin
          $method_text_temp = %{
            def #{method_name}(*args,&block)
              @_my_mock.__send__(:#{method_name}, *args, &block)
            end
          }
          class << self
            eval $method_text_temp
          end
        ensure
          $method_text_temp = nil
        end
      end

      return @_my_mock.expects(method_name, *args, &block)
    end

    def _is_mock?
      self.kind_of?(Mock)
    end

    def _my_name
      self.kind_of?(Class) ? self.name : self.class.name
    end

    def _clear_mock
      @_my_mock = nil
    end

  end

  class ::NilClass
    # Use this only if you really mean it
    alias_method :intentionally_stubs!, :stubs!

    # Use this only if you really mean it
    alias_method :intentionally_expects!, :expects!

    # Overridden to protect against accidental nil reference self delusion
    def stubs!(mname)
      raise StubbingError, "Cannot stub #{mname} method on nil.  (If you really mean to, try 'intentionally_stubs!')"
    end

    # Overridden to protect against accidental nil reference self delusion
    def expects!(mname, *args)
      raise StubbingError, "Cannot mock #{mname} method on nil.  (If you really mean to, try 'intentionally_expects!')"
    end
  end

  class << self
    def track_replaced_method(replaced_method)
      all_replaced_methods << replaced_method
    end

    def all_replaced_methods
      $all_replaced_methods ||= []
    end

    def has_replaced_method?(obj, method_name)
      hits = all_replaced_methods.select do |replaced|
        (replaced.target.object_id == obj.object_id) and (replaced.method_name.to_s == method_name.to_s)
      end
      return !hits.empty?
    end

    def restore_all_replaced_methods
      all_replaced_methods.each do |replaced|
        unless replaced.target._is_mock?
          backed_up = "_hardmock_original_#{replaced.method_name}"
          if replaced.target.methods.map do |m| m.to_s end.include?(backed_up)
            replaced.target.hm_meta_eval do
              alias_method replaced.method_name.to_sym, backed_up.to_sym
            end
          end
          replaced.target._clear_mock
        end
      end
      all_replaced_methods.clear
    end
  end

end


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Email/etc/email_templates.xsd">
    <template id="customer_create_account_email_template" label="New Account" file="account_new.html" type="html" module="Magento_Customer"/>
    <template id="customer_create_account_email_confirmation_template" label="New Account Confirmation Key" file="account_new_confirmation.html" type="html" module="Magento_Customer"/>
    <template id="customer_create_account_email_confirmed_template" label="New Account Confirmed" file="account_new_confirmed.html" type="html" module="Magento_Customer"/>
    <template id="customer_password_forgot_email_template" label="Forgot Password" file="password_reset_confirmation.html" type="html" module="Magento_Customer"/>
    <template id="customer_password_remind_email_template" label="Remind Password" file="password_new.html" type="html" module="Magento_Customer"/>
    <template id="customer_password_reset_password_template" label="Reset Password" file="password_reset.html" type="html" module="Magento_Customer"/>
</config>


text:
package xhandler

import (
	"net/http"

	"golang.org/x/net/context"
)

// Chain is a helper for chaining middleware handlers together for easier
// management.
type Chain []func(next HandlerC) HandlerC

// Add appends a variable number of additional middleware handlers
// to the middleware chain. Middleware handlers can either be
// context-aware or non-context aware handlers with the appropriate
// function signatures.
func (c *Chain) Add(f ...interface{}) {
	for _, h := range f {
		switch v := h.(type) {
		case func(http.Handler) http.Handler:
			c.Use(v)
		case func(HandlerC) HandlerC:
			c.UseC(v)
		default:
			panic("Adding invalid handler to the middleware chain")
		}
	}
}

// With creates a new middleware chain from an existing chain,
// extending it with additional middleware. Middleware handlers
// can either be context-aware or non-context aware handlers
// with the appropriate function signatures.
func (c *Chain) With(f ...interface{}) *Chain {
	n := make(Chain, len(*c))
	copy(n, *c)
	n.Add(f...)
	return &n
}

// UseC appends a context-aware handler to the middleware chain.
func (c *Chain) UseC(f func(next HandlerC) HandlerC) {
	*c = append(*c, f)
}

// Use appends a standard http.Handler to the middleware chain without
// losing track of the context when inserted between two context aware handlers.
//
// Caveat: the f function will be called on each request so you are better off putting
// any initialization sequence outside of this function.
func (c *Chain) Use(f func(next http.Handler) http.Handler) {
	xf := func(next HandlerC) HandlerC {
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			n := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				next.ServeHTTPC(ctx, w, r)
			})
			f(n).ServeHTTP(w, r)
		})
	}
	*c = append(*c, xf)
}

// Handler wraps the provided final handler with all the middleware appended to
// the chain and returns a new standard http.Handler instance.
// The context.Background() context is injected automatically.
func (c Chain) Handler(xh HandlerC) http.Handler {
	ctx := context.Background()
	return c.HandlerCtx(ctx, xh)
}

// HandlerFC is a helper to provide a function (HandlerFuncC) to Handler().
//
// HandlerFC is equivalent to:
//  c.Handler(xhandler.HandlerFuncC(xhc))
func (c Chain) HandlerFC(xhf HandlerFuncC) http.Handler {
	ctx := context.Background()
	return c.HandlerCtx(ctx, HandlerFuncC(xhf))
}

// HandlerH is a helper to provide a standard http handler (http.HandlerFunc)
// to Handler(). Your final handler won't have access to the context though.
func (c Chain) HandlerH(h http.Handler) http.Handler {
	ctx := context.Background()
	return c.HandlerCtx(ctx, HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		h.ServeHTTP(w, r)
	}))
}

// HandlerF is a helper to provide a standard http handler function
// (http.HandlerFunc) to Handler(). Your final handler won't have access
// to the context though.
func (c Chain) HandlerF(hf http.HandlerFunc) http.Handler {
	ctx := context.Background()
	return c.HandlerCtx(ctx, HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		hf(w, r)
	}))
}

// HandlerCtx wraps the provided final handler with all the middleware appended to
// the chain and returns a new standard http.Handler instance.
func (c Chain) HandlerCtx(ctx context.Context, xh HandlerC) http.Handler {
	return New(ctx, c.HandlerC(xh))
}

// HandlerC wraps the provided final handler with all the middleware appended to
// the chain and returns a HandlerC instance.
func (c Chain) HandlerC(xh HandlerC) HandlerC {
	for i := len(c) - 1; i >= 0; i-- {
		xh = c[i](xh)
	}
	return xh
}

// HandlerCF wraps the provided final handler func with all the middleware appended to
// the chain and returns a HandlerC instance.
//
// HandlerCF is equivalent to:
//  c.HandlerC(xhandler.HandlerFuncC(xhc))
func (c Chain) HandlerCF(xhc HandlerFuncC) HandlerC {
	return c.HandlerC(HandlerFuncC(xhc))
}


text:
<?php
$host='localhost';
$dbtype='mysql';
$user='bbctest';
$pass='bbctest';
$database='bbctest';


text:
package gw.xml;

import gw.lang.PublishInGosu;

@PublishInGosu
public abstract class XmlSchemaAccess<T extends XmlElement> {

  /**
   * Returns the schema represented by this XmlSchemaAccess type.
   *
   * @return the schema
   */
  public abstract T getSchema();

  /**
   * Returns the package name of this schema.
   *
   * @return the package name of this schema
   */
  @Override
  public abstract String toString();

}


text:
class HeadingComponent < Rafters::Component
  setting :title, default: "No Title Specified"
end


text: from .defer_handler import install_defer_routes  # noqa: F401


text:
package de.florianthievessen.javautils;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class StringUtilsTest extends TestCase {

	public StringUtilsTest(String testName) {
		super(testName);
	}

	public static Test suite() {
		return new TestSuite(StringUtilsTest.class);
	}

	@Override
	protected void setUp() throws Exception {

	}

	public void testPluralizeGeneralWords() {
		assertEquals("item", StringUtils.pluralize("item", 1));
		assertEquals("items", StringUtils.pluralize("item", 2));
	}

	public void testPluralizeWordsEndingInS() {
		assertEquals("bus", StringUtils.pluralize("bus", 1));
		assertEquals("buses", StringUtils.pluralize("bus", 2));
	}

	public void testPluralizeWordsEndingInX() {
		assertEquals("box", StringUtils.pluralize("box", 1));
		assertEquals("boxes", StringUtils.pluralize("box", 2));
	}

	public void testPluralizeWordsEndingInZ() {
		assertEquals("quiz", StringUtils.pluralize("quiz", 1));
		assertEquals("quizzes", StringUtils.pluralize("quiz", 2));
	}

	public void testPluralizeWordsEndingInCH() {
		assertEquals("pitch", StringUtils.pluralize("pitch", 1));
		assertEquals("pitches", StringUtils.pluralize("pitch", 2));
	}

	public void testPluralizeWordsEndingInSH() {
		assertEquals("wish", StringUtils.pluralize("wish", 1));
		assertEquals("wishes", StringUtils.pluralize("wish", 2));
	}

	public void testPluralizeWordsEndingInY() {
		assertEquals("penny", StringUtils.pluralize("penny", 1));
		assertEquals("pennies", StringUtils.pluralize("penny", 2));
	}

	public void testPluralizeIrregularWords() {
		assertEquals("man", StringUtils.pluralize("man", 1));
		assertEquals("men", StringUtils.pluralize("man", 2));
	}

}


text:
PoliCSS (pronounced Po-lis) will Enforce a CSS methodology, Suppress individual coding styles, Control specificity and Oppress team members.

## What is it?
PoliCSS is a CSS methodology and a PostCSS based linter designed to enforce it.

## Benefits

* Easier maintenance
* Reduce Bugs
* Portable between projects

## Key Concepts

* Use semantically named classes/modules
* Reduce and __Control__ specificity. Keeps as low as possible, without equalling selectors
* Well-defined structure to selectors
  * Order of selectors should not make a difference
  * Module should not care about parent selectors
* n types of selector:
  1. single html tags e.g. `p` - defined in `base` folder
  2. nested html tags. Can only be used for tags that could have different parent tags e.g. `ul li` - defined in `base` folder. Limited to `ul/ol li`, `thead/tbody/tfoot tr/th/td`
  3. microformat selectors - TODO
  4. module selector. single class name e.g. `.foo`. Must have same name as module file i.e. `modules/foo.css`
  5. module sub-tag. Used to target a specific tag inside the module e.g. `.foo h3` or `article.foo`. Cannot be parent element of module
  6. module sub-component. Single class name, prefixed with module name e.g. `.foo-bar` for `bar sub-component`
  7. nested module. Used to alter the css of a child module e.g. `.foo .baz` or `.foo .baz a` where `.baz a` has already been defined in `.baz` module
  8. status. Must be prefixed with `is-` or `has-`. These are classes that are likely to be added/removed to an element at runtime. Typical selectors would be `.foo.is-active` or `.foo.has-children`
  9. Media query. TODO

## how it works
[PostCSS](https://github.com/postcss/postcss)
[cssnext](http://cssnext.io/)
[Stylelint](http://stylelint.io/)

## Folder Structure

`index.css` includes all files in specific folder order. Files within folders imported alphabetically
to reduce chances of order specificity bugs

1. vendor - any 3rd party css files to import e.g. normalise.css
2. variables - all variables are defined here
3. mixins - mixins defined here
4. base - styles for html tags. no `class` or `id` selectors. `status` selectors allowed
5. microformats - (Optional). Standardized class names and markup patterns
5. modules - Most of the development

## Rules

* Formatting rules - provided by stylelint
* Methodology rules - provided by stylelint
* Methodology rules - custom stylelint plugins
* Methodology rules - Unenforceable

### Enforceable Rules
1. no `div` in selectors - too generic
1. no `span` in selectors - too generic
1. no __id__ selectors - too specific
1. no generic class/module names e.g. `.container, .row, .column`
1. no floating status selectors - must be attached to an element
1. Only allow genuine tag names
1. don't use tag names for class names
1. widths should be % or rem - no px units etc
1. variables used for colors etc
1. module names must match filename
1. filenames should be included alphabetically
1. mixins at top of properties
1. no block elements inside inline elements

### Unenforceable Rules
May be able to provide warnings
1. no __presentational__ class/module names e.g. `.red-border`
1. no __media query__ restricted class/module names e.g. `.col-md-3`
1. don't use `i` tags for icons

## FAQs
1. Empty tags are OK. These should be removed by PostCSS plugins

## Other considerations
1. MaintainableCSS http://maintainablecss.com/ - very good!
1. modernizr
1. css-modules on github