text:
'use strict';

// TODO: refactor JSDoc
// TODO: add tests

var chai = require('chai');
var queue = require('./lib/queue');
var PropertyAssertion = require('./lib/assertions/property-assertion');
var StateAssertion = require('./lib/assertions/state-assertion');
var tinto = require('./lib/tinto');
var bundle = require('./lib/utils/bundle');
var config = require('./lib/utils/config');
var html = require('./lib/html');

module.exports = tinto;
global.tinto = tinto;

module.exports.Component = require('./lib/component');
module.exports.Page = require('./lib/page');
module.exports.ComponentCollection = require('./lib/component-collection');
module.exports.Browser = require('./lib/browser');

var browser = new module.exports.Browser();

module.exports.browser = browser;
module.exports.pause = require('./lib/utils/pause');
module.exports.sleep = require('./lib/utils/sleep');
module.exports.find = require('./lib/utils/find');
module.exports.inherits = require('./lib/utils/inherits');
module.exports.bundle = bundle;
module.exports.keyboard = require('./lib/utils/keyboard');
module.exports.done = queue.process.bind(queue);
module.exports.be = require('./lib/utils/delegate');
module.exports.have = require('./lib/utils/delegate');
module.exports.load = require('./lib/utils/load');
// TODO: not with negate=true

/**
 * @name tinto.page
 * @type {tinto.Page}
 */
Object.defineProperty(module.exports, 'page', {
  get: browser.getPage.bind(browser)
});

// TODO: replace with built in assertions
chai.use(require('./lib/assertions'));

// Default bundle
bundle('html', html);

// Load user config
config.load();


text:
"""Calendar is a dictionary like Python object that can render itself as VCAL
files according to rfc2445.

These are the defined components.
"""
from datetime import datetime, timedelta
from icalendar.caselessdict import CaselessDict
from icalendar.parser import Contentline
from icalendar.parser import Contentlines
from icalendar.parser import Parameters
from icalendar.parser import q_join
from icalendar.parser import q_split
from icalendar.parser_tools import DEFAULT_ENCODING
from icalendar.prop import TypesFactory
from icalendar.prop import vText, vDDDLists
from icalendar.timezone_cache import _timezone_cache

import pytz
import dateutil.rrule
from pytz.tzinfo import DstTzInfo

######################################
# The component factory

class ComponentFactory(CaselessDict):
    """All components defined in rfc 2445 are registered in this factory class.
    To get a component you can use it like this.
    """

    def __init__(self, *args, **kwargs):
        """Set keys to upper for initial dict.
        """
        super(ComponentFactory, self).__init__(*args, **kwargs)
        self['VEVENT'] = Event
        self['VTODO'] = Todo
        self['VJOURNAL'] = Journal
        self['VFREEBUSY'] = FreeBusy
        self['VTIMEZONE'] = Timezone
        self['STANDARD'] = TimezoneStandard
        self['DAYLIGHT'] = TimezoneDaylight
        self['VALARM'] = Alarm
        self['VCALENDAR'] = Calendar

# These Properties have multiple property values inlined in one propertyline
# seperated by comma. Use CaselessDict as simple caseless set.
INLINE = CaselessDict({
    'CATEGORIES': 1,
    'RESOURCES': 1,
    'FREEBUSY': 1,
})

_marker = []

class Component(CaselessDict):
    """Component is the base object for calendar, Event and the other
    components defined in RFC 2445. normally you will not use this class
    directy, but rather one of the subclasses.
    """

    name = None         # should be defined in each component
    required = ()       # These properties are required
    singletons = ()     # These properties must only appear once
    multiple = ()       # may occur more than once
    exclusive = ()      # These properties are mutually exclusive
    inclusive = ()      # if any occurs the other(s) MUST occur
                        # ('duration', 'repeat')
    ignore_exceptions = False   # if True, and we cannot parse this
                                # component, we will silently ignore
                                # it, rather than let the exception
                                # propagate upwards
    # not_compliant = [''] # List of non-compliant properties.

    def __init__(self, *args, **kwargs):
        """Set keys to upper for initial dict.
        """
        super(Component, self).__init__(*args, **kwargs)
        # set parameters here for properties that use non-default values
        self.subcomponents = []  # Components can be nested.
        self.is_broken = False  # True if we ignored an exception while
                                # parsing a property

    # def is_compliant(self, name):
    #    """Returns True is the given property name is compliant with the
    #    icalendar implementation.
    #
    #    If the parser is too strict it might prevent parsing erroneous but
    #    otherwise compliant properties. So the parser is pretty lax, but it is
    #    possible to test for non-complience by calling this method.
    #    """
    #    return name in not_compliant

    #############################
    # handling of property values

    def _encode(self, name, value, parameters=None, encode=1):
        """Encode values to icalendar property values.

        :param name: Name of the property.
        :type name: string

        :param value: Value of the property. Either of a basic Python type of
                      any of the icalendar's own property types.
        :type value: Python native type or icalendar property type.

        :param parameters: Property parameter dictionary for the value. Only
                           available, if encode is set to True.
        :type parameters: Dictionary

        :param encode: True, if the value should be encoded to one of
                       icalendar's own property types (Fallback is "vText")
                       or False, if not.
        :type encode: Boolean

        :returns: icalendar property value
        """
        if not encode:
            return value
        if isinstance(value, types_factory.all_types):
            # Don't encode already encoded values.
            return value
        klass = types_factory.for_property(name)
        obj = klass(value)
        if parameters:
            if isinstance(parameters, dict):
                params = Parameters()
                for key, item in parameters.items():
                    params[key] = item
                parameters = params
            assert isinstance(parameters, Parameters)
            obj.params = parameters
        return obj

    def add(self, name, value, parameters=None, encode=1):
        """Add a property.

        :param name: Name of the property.
        :type name: string

        :param value: Value of the property. Either of a basic Python type of
                      any of the icalendar's own property types.
        :type value: Python native type or icalendar property type.

        :param parameters: Property parameter dictionary for the value. Only
                           available, if encode is set to True.
        :type parameters: Dictionary

        :param encode: True, if the value should be encoded to one of
                       icalendar's own property types (Fallback is "vText")
                       or False, if not.
        :type encode: Boolean

        :returns: None
        """
        if isinstance(value, datetime) and\
                name.lower() in ('dtstamp', 'created', 'last-modified'):
            # RFC expects UTC for those... force value conversion.
            if getattr(value, 'tzinfo', False) and value.tzinfo is not None:
                value = value.astimezone(pytz.utc)
            else:
                # assume UTC for naive datetime instances
                value = pytz.utc.localize(value)

        # encode value
        if encode and isinstance(value, list) \
                and name.lower() not in ['rdate', 'exdate']:
            # Individually convert each value to an ical type except rdate and
            # exdate, where lists of dates might be passed to vDDDLists.
            value = [self._encode(name, v, parameters, encode) for v in value]
        else:
            value = self._encode(name, value, parameters, encode)

        # set value
        if name in self:
            # If property already exists, append it.
            oldval = self[name]
            if isinstance(oldval, list):
                if isinstance(value, list):
                    value = oldval + value
                else:
                    oldval.append(value)
                    value = oldval
            else:
                value = [oldval, value]
        self[name] = value

    def _decode(self, name, value):
        """Internal for decoding property values.
        """

        # TODO: Currently the decoded method calls the icalendar.prop instances
        # from_ical. We probably want to decode properties into Python native
        # types here. But when parsing from an ical string with from_ical, we
        # want to encode the string into a real icalendar.prop property.
        if isinstance(value, vDDDLists):
            # TODO: Workaround unfinished decoding
            return value
        decoded = types_factory.from_ical(name, value)
        # TODO: remove when proper decoded is implemented in every prop.* class
        # Workaround to decode vText properly
        if isinstance(decoded, vText):
            decoded = decoded.encode(DEFAULT_ENCODING)
        return decoded

    def decoded(self, name, default=_marker):
        """Returns decoded value of property.
        """
        # XXX: fail. what's this function supposed to do in the end?
        # -rnix

        if name in self:
            value = self[name]
            if isinstance(value, list):
                return [self._decode(name, v) for v in value]
            return self._decode(name, value)
        else:
            if default is _marker:
                raise KeyError(name)
            else:
                return default

    ########################################################################
    # Inline values. A few properties have multiple values inlined in in one
    # property line. These methods are used for splitting and joining these.

    def get_inline(self, name, decode=1):
        """Returns a list of values (split on comma).
        """
        vals = [v.strip('" ') for v in q_split(self[name])]
        if decode:
            return [self._decode(name, val) for val in vals]
        return vals

    def set_inline(self, name, values, encode=1):
        """Converts a list of values into comma seperated string and sets value
        to that.
        """
        if encode:
            values = [self._encode(name, value, encode=1) for value in values]
        self[name] = types_factory['inline'](q_join(values))

    #########################
    # Handling of components

    def add_component(self, component):
        """Add a subcomponent to this component.
        """
        self.subcomponents.append(component)

    def _walk(self, name):
        """Walk to given component.
        """
        result = []
        if name is None or self.name == name:
            result.append(self)
        for subcomponent in self.subcomponents:
            result += subcomponent._walk(name)
        return result

    def walk(self, name=None):
        """Recursively traverses component and subcomponents. Returns sequence
        of same. If name is passed, only components with name will be returned.
        """
        if name is not None:
            name = name.upper()
        return self._walk(name)

    #####################
    # Generation

    def property_items(self, recursive=True, sorted=True):
        """Returns properties in this component and subcomponents as:
        [(name, value), ...]
        """
        vText = types_factory['text']
        properties = [('BEGIN', vText(self.name).to_ical())]
        if sorted:
            property_names = self.sorted_keys()
        else:
            property_names = self.keys()

        for name in property_names:
            values = self[name]
            if isinstance(values, list):
                # normally one property is one line
                for value in values:
                    properties.append((name, value))
            else:
                properties.append((name, values))
        if recursive:
            # recursion is fun!
            for subcomponent in self.subcomponents:
                properties += subcomponent.property_items(sorted=sorted)
        properties.append(('END', vText(self.name).to_ical()))
        return properties

    @classmethod
    def from_ical(cls, st, multiple=False):
        """Populates the component recursively from a string.
        """
        stack = []  # a stack of components
        comps = []
        for line in Contentlines.from_ical(st):  # raw parsing
            if not line:
                continue

            try:
                name, params, vals = line.parts()
            except ValueError:
                # if unable to parse a line within a component
                # that ignores exceptions, mark the component
                # as broken and skip the line. otherwise raise.
                component = stack[-1] if stack else None
                if not component or not component.ignore_exceptions:
                    raise
                component.is_broken = True
                continue

            uname = name.upper()
            # check for start of component
            if uname == 'BEGIN':
                # try and create one of the components defined in the spec,
                # otherwise get a general Components for robustness.
                c_name = vals.upper()
                c_class = component_factory.get(c_name, cls)
                component = c_class()
                if not getattr(component, 'name', ''):  # undefined components
                    component.name = c_name
                stack.append(component)
            # check for end of event
            elif uname == 'END':
                # we are done adding properties to this component
                # so pop it from the stack and add it to the new top.
                component = stack.pop()
                if not stack:  # we are at the end
                    comps.append(component)
                else:
                    if not component.is_broken:
                        stack[-1].add_component(component)
                if vals == 'VTIMEZONE' and \
                        'TZID' in component and \
                        component['TZID'] not in pytz.all_timezones and \
                        component['TZID'] not in _timezone_cache:
                    _timezone_cache[component['TZID']] = component.to_tz()
            # we are adding properties to the current top of the stack
            else:
                factory = types_factory.for_property(name)
                component = stack[-1]
                datetime_names = ('DTSTART', 'DTEND', 'RECURRENCE-ID', 'DUE',
                                  'FREEBUSY', 'RDATE', 'EXDATE')
                try:
                    if name in datetime_names and 'TZID' in params:
                        vals = factory(factory.from_ical(vals, params['TZID']))
                    else:
                        vals = factory(factory.from_ical(vals))
                except ValueError:
                    if not component.ignore_exceptions:
                        raise
                    component.is_broken = True
                else:
                    vals.params = params
                    component.add(name, vals, encode=0)

        if multiple:
            return comps
        if len(comps) > 1:
            raise ValueError('Found multiple components where '
                             'only one is allowed: {st!r}'.format(**locals()))
        if len(comps) < 1:
            raise ValueError('Found no components where '
                             'exactly one is required: '
                             '{st!r}'.format(**locals()))
        return comps[0]

    def content_line(self, name, value, sorted=True):
        """Returns property as content line.
        """
        params = getattr(value, 'params', Parameters())
        return Contentline.from_parts(name, params, value, sorted=sorted)

    def content_lines(self, sorted=True):
        """Converts the Component and subcomponents into content lines.
        """
        contentlines = Contentlines()
        for name, value in self.property_items(sorted=sorted):
            cl = self.content_line(name, value, sorted=sorted)
            contentlines.append(cl)
        contentlines.append('')  # remember the empty string in the end
        return contentlines

    def to_ical(self, sorted=True):
        '''
        :param sorted: Whether parameters and properties should be
                       lexicographically sorted.
        '''

        content_lines = self.content_lines(sorted=sorted)
        return content_lines.to_ical()

    def __repr__(self):
        """String representation of class with all of it's subcomponents.
        """
        subs = ', '.join([str(it) for it in self.subcomponents])
        return '%s(%s%s)' % (
            self.name or type(self).__name__,
            dict(self),
            ', %s' % subs if subs else ''
        )

#######################################
# components defined in RFC 2445

class Event(Component):

    name = 'VEVENT'

    canonical_order = (
        'SUMMARY', 'DTSTART', 'DTEND', 'DURATION', 'DTSTAMP',
        'UID', 'RECURRENCE-ID', 'SEQUENCE',
        'RRULE' 'EXRULE', 'RDATE', 'EXDATE',
    )

    required = ('UID',)
    singletons = (
        'CLASS', 'CREATED', 'DESCRIPTION', 'DTSTART', 'GEO', 'LAST-MODIFIED',
        'LOCATION', 'ORGANIZER', 'PRIORITY', 'DTSTAMP', 'SEQUENCE', 'STATUS',
        'SUMMARY', 'TRANSP', 'URL', 'RECURRENCE-ID', 'DTEND', 'DURATION',
        'DTSTART',
    )
    exclusive = ('DTEND', 'DURATION', )
    multiple = (
        'ATTACH', 'ATTENDEE', 'CATEGORIES', 'COMMENT', 'CONTACT', 'EXDATE',
        'EXRULE', 'RSTATUS', 'RELATED', 'RESOURCES', 'RDATE', 'RRULE'
    )
    ignore_exceptions = True

class Todo(Component):

    name = 'VTODO'

    required = ('UID',)
    singletons = (
        'CLASS', 'COMPLETED', 'CREATED', 'DESCRIPTION', 'DTSTAMP', 'DTSTART',
        'GEO', 'LAST-MODIFIED', 'LOCATION', 'ORGANIZER', 'PERCENT-COMPLETE',
        'PRIORITY', 'RECURRENCE-ID', 'SEQUENCE', 'STATUS', 'SUMMARY', 'UID',
        'URL', 'DUE', 'DURATION',
    )
    exclusive = ('DUE', 'DURATION',)
    multiple = (
        'ATTACH', 'ATTENDEE', 'CATEGORIES', 'COMMENT', 'CONTACT', 'EXDATE',
        'EXRULE', 'RSTATUS', 'RELATED', 'RESOURCES', 'RDATE', 'RRULE'
    )

class Journal(Component):

    name = 'VJOURNAL'

    required = ('UID',)
    singletons = (
        'CLASS', 'CREATED', 'DESCRIPTION', 'DTSTART', 'DTSTAMP',
        'LAST-MODIFIED', 'ORGANIZER', 'RECURRENCE-ID', 'SEQUENCE', 'STATUS',
        'SUMMARY', 'UID', 'URL',
    )
    multiple = (
        'ATTACH', 'ATTENDEE', 'CATEGORIES', 'COMMENT', 'CONTACT', 'EXDATE',
        'EXRULE', 'RELATED', 'RDATE', 'RRULE', 'RSTATUS',
    )

class FreeBusy(Component):

    name = 'VFREEBUSY'

    required = ('UID',)
    singletons = (
        'CONTACT', 'DTSTART', 'DTEND', 'DURATION', 'DTSTAMP', 'ORGANIZER',
        'UID', 'URL',
    )
    multiple = ('ATTENDEE', 'COMMENT', 'FREEBUSY', 'RSTATUS',)

class Timezone(Component):
    name = 'VTIMEZONE'
    canonical_order = ('TZID', 'STANDARD', 'DAYLIGHT',)
    required = ('TZID', 'STANDARD', 'DAYLIGHT',)
    singletons = ('TZID', 'LAST-MODIFIED', 'TZURL',)

    @staticmethod
    def _extract_offsets(component, zone):
        """extract offsets and transition times from a VTIMEZONE component
        :param component: a STANDARD or DAYLIGHT component
        :param zone: the name of the zone, used for constructing a TZNAME if
                     this component has none
        """
        try:
            tzname = str(component['TZNAME'])
        except KeyError:
            tzname = '{0}_{1}'.format(
                zone,
                component['DTSTART'].to_ical().decode('utf-8')
            )
        offsetfrom = component['TZOFFSETFROM'].td
        offsetto = component['TZOFFSETTO'].td
        dtstart = component['DTSTART'].dt

        # offsets need to be rounded to the next minute, we might loose up
        # to 30 seconds accuracy, but it can't be helped (datetime
        # supposedly cannot handle smaller offsets)
        offsetto_s = int((offsetto.seconds + 30) / 60) * 60
        offsetto = timedelta(days=offsetto.days, seconds=offsetto_s)
        offsetfrom_s = int((offsetfrom.seconds + 30) / 60) * 60
        offsetfrom = timedelta(days=offsetfrom.days, seconds=offsetfrom_s)

        # expand recurrences
        if 'RRULE' in component:
            rrulestr = component['RRULE'].to_ical().decode('utf-8')
            rrule = dateutil.rrule.rrulestr(rrulestr, dtstart=dtstart)
            if not set(['UNTIL', 'COUNT']).intersection(
                    component['RRULE'].keys()):
                # pytz.timezones don't know any transition dates after 2038
                # either
                rrule._until = datetime(2038, 12, 31)
            elif rrule._until.tzinfo:
                rrule._until = rrule._until.replace(tzinfo=None)
            transtimes = rrule
        # or rdates
        elif 'RDATE' in component:
            if not isinstance(component['RDATE'], list):
                rdates = [component['RDATE']]
            else:
                rdates = component['RDATE']
            transtimes = [dtstart] + [leaf.dt for tree in rdates for
                                      leaf in tree.dts]
        else:
            transtimes = [dtstart]

        transitions = [(transtime, offsetfrom, offsetto, tzname) for
                       transtime in set(transtimes)]

        if component.name == 'STANDARD':
            is_dst = 0
        elif component.name == 'DAYLIGHT':
            is_dst = 1
        return is_dst, transitions

    def to_tz(self):
        """convert this VTIMEZONE component to a pytz.timezone object
        """
        zone = str(self['TZID'])
        transitions = list()
        dst = dict()
        for component in self.walk():
            if type(component) == Timezone:
                continue
            try:
                tzname = str(component['TZNAME'])
            except KeyError:
                tzname = '{0}_{1}'.format(
                    zone,
                    component['DTSTART'].to_ical().decode('utf-8')
                )
            dst[tzname], component_transitions = self._extract_offsets(
                component, zone
            )
            transitions.extend(component_transitions)

        transitions.sort()
        transition_times = [
            transtime - osfrom for transtime, osfrom, _, _ in transitions
        ]

        # transition_info is a list with tuples in the format
        # (utcoffset, dstoffset, name)
        # dstoffset = 0, if current transition is to standard time
        #           = this_utcoffset - prev_standard_utcoffset, otherwise
        transition_info = list()
        for num, (transtime, osfrom, osto, name) in enumerate(transitions):
            dst_offset = False
            if not dst[name]:
                dst_offset = timedelta(seconds=0)
            else:
                # go back in time until we find a transition to dst
                for index in range(num - 1, -1, -1):
                    if not dst[transitions[index][3]]:  # [3] is the name
                        dst_offset = osto - transitions[index][2]  # [2] is osto  # noqa
                        break
                # when the first transition is to dst, we didn't find anything
                # in the past, so we have to look into the future
                if not dst_offset:
                    for index in range(num, len(transitions)):
                        if not dst[transitions[index][3]]:  # [3] is the name
                            dst_offset = osto - transitions[index][2]  # [2] is osto  # noqa
                            break
            transition_info.append((osto, dst_offset, name))

        cls = type(zone, (DstTzInfo,), dict(
            zone=zone,
            _utc_transition_times=transition_times,
            _transition_info=transition_info))

        return cls()

class TimezoneStandard(Component):
    name = 'STANDARD'
    required = ('DTSTART', 'TZOFFSETTO', 'TZOFFSETFROM')
    singletons = ('DTSTART', 'TZOFFSETTO', 'TZOFFSETFROM', 'RRULE')
    multiple = ('COMMENT', 'RDATE', 'TZNAME')

class TimezoneDaylight(Component):
    name = 'DAYLIGHT'
    required = ('DTSTART', 'TZOFFSETTO', 'TZOFFSETFROM')
    singletons = ('DTSTART', 'TZOFFSETTO', 'TZOFFSETFROM', 'RRULE')
    multiple = ('COMMENT', 'RDATE', 'TZNAME')

class Alarm(Component):

    name = 'VALARM'
    # not quite sure about these ...
    required = ('ACTION', 'TRIGGER',)
    singletons = ('ATTACH', 'ACTION', 'TRIGGER', 'DURATION', 'REPEAT',)
    inclusive = (('DURATION', 'REPEAT',),)

class Calendar(Component):
    """This is the base object for an iCalendar file.
    """
    name = 'VCALENDAR'
    canonical_order = ('VERSION', 'PRODID', 'CALSCALE', 'METHOD',)
    required = ('prodid', 'version', )
    singletons = ('prodid', 'version', )
    multiple = ('calscale', 'method', )

# These are read only singleton, so one instance is enough for the module
types_factory = TypesFactory()
component_factory = ComponentFactory()

redpajama_set_name: RedPajamaGithub


text:
package deployment

import (
	"fmt"
	"testing"

	"k8s.io/kubernetes/pkg/api"
	exp "k8s.io/kubernetes/pkg/apis/extensions"
	"k8s.io/kubernetes/pkg/client/record"
	"k8s.io/kubernetes/pkg/client/unversioned/testclient"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/util"
)

func TestDeploymentController_reconcileNewRC(t *testing.T) {
	tests := []struct {
		deploymentReplicas  int
		maxSurge            util.IntOrString
		oldReplicas         int
		newReplicas         int
		scaleExpected       bool
		expectedNewReplicas int
	}{
		{
			// Should not scale up.
			deploymentReplicas: 10,
			maxSurge:           util.NewIntOrStringFromInt(0),
			oldReplicas:        10,
			newReplicas:        0,
			scaleExpected:      false,
		},
		{
			deploymentReplicas:  10,
			maxSurge:            util.NewIntOrStringFromInt(2),
			oldReplicas:         10,
			newReplicas:         0,
			scaleExpected:       true,
			expectedNewReplicas: 2,
		},
		{
			deploymentReplicas:  10,
			maxSurge:            util.NewIntOrStringFromInt(2),
			oldReplicas:         5,
			newReplicas:         0,
			scaleExpected:       true,
			expectedNewReplicas: 7,
		},
		{
			deploymentReplicas: 10,
			maxSurge:           util.NewIntOrStringFromInt(2),
			oldReplicas:        10,
			newReplicas:        2,
			scaleExpected:      false,
		},
		{
			// Should scale down.
			deploymentReplicas:  10,
			maxSurge:            util.NewIntOrStringFromInt(2),
			oldReplicas:         2,
			newReplicas:         11,
			scaleExpected:       true,
			expectedNewReplicas: 10,
		},
	}

	for i, test := range tests {
		t.Logf("executing scenario %d", i)
		newRc := rc("foo-v2", test.newReplicas)
		oldRc := rc("foo-v2", test.oldReplicas)
		allRcs := []*api.ReplicationController{newRc, oldRc}
		deployment := deployment("foo", test.deploymentReplicas, test.maxSurge, util.NewIntOrStringFromInt(0))
		fake := &testclient.Fake{}
		controller := &DeploymentController{
			client:        fake,
			eventRecorder: &record.FakeRecorder{},
		}
		scaled, err := controller.reconcileNewRC(allRcs, newRc, deployment)
		if err != nil {
			t.Errorf("unexpected error: %v", err)
			continue
		}
		if !test.scaleExpected {
			if scaled || len(fake.Actions()) > 0 {
				t.Errorf("unexpected scaling: %v", fake.Actions())
			}
			continue
		}
		if test.scaleExpected && !scaled {
			t.Errorf("expected scaling to occur")
			continue
		}
		if len(fake.Actions()) != 1 {
			t.Errorf("expected 1 action during scale, got: %v", fake.Actions())
			continue
		}
		updated := fake.Actions()[0].(testclient.UpdateAction).GetObject().(*api.ReplicationController)
		if e, a := test.expectedNewReplicas, updated.Spec.Replicas; e != a {
			t.Errorf("expected update to %d replicas, got %d", e, a)
		}
	}
}

func TestDeploymentController_reconcileOldRCs(t *testing.T) {
	tests := []struct {
		deploymentReplicas  int
		maxUnavailable      util.IntOrString
		readyPods           int
		oldReplicas         int
		scaleExpected       bool
		expectedOldReplicas int
	}{
		{
			deploymentReplicas: 10,
			maxUnavailable:     util.NewIntOrStringFromInt(0),
			readyPods:          10,
			oldReplicas:        10,
			scaleExpected:      false,
		},
		{
			deploymentReplicas:  10,
			maxUnavailable:      util.NewIntOrStringFromInt(2),
			readyPods:           10,
			oldReplicas:         10,
			scaleExpected:       true,
			expectedOldReplicas: 8,
		},
		{
			deploymentReplicas: 10,
			maxUnavailable:     util.NewIntOrStringFromInt(2),
			readyPods:          8,
			oldReplicas:        10,
			scaleExpected:      false,
		},
		{
			deploymentReplicas: 10,
			maxUnavailable:     util.NewIntOrStringFromInt(2),
			readyPods:          10,
			oldReplicas:        0,
			scaleExpected:      false,
		},
	}

	for i, test := range tests {
		t.Logf("executing scenario %d", i)
		oldRc := rc("foo-v2", test.oldReplicas)
		allRcs := []*api.ReplicationController{oldRc}
		oldRcs := []*api.ReplicationController{oldRc}
		deployment := deployment("foo", test.deploymentReplicas, util.NewIntOrStringFromInt(0), test.maxUnavailable)
		fake := &testclient.Fake{}
		fake.AddReactor("list", "pods", func(action testclient.Action) (handled bool, ret runtime.Object, err error) {
			switch action.(type) {
			case testclient.ListAction:
				podList := &api.PodList{}
				for podIndex := 0; podIndex < test.readyPods; podIndex++ {
					podList.Items = append(podList.Items, api.Pod{
						ObjectMeta: api.ObjectMeta{
							Name: fmt.Sprintf("%s-pod-%d", oldRc.Name, podIndex),
						},
						Status: api.PodStatus{
							Conditions: []api.PodCondition{
								{
									Type:   api.PodReady,
									Status: api.ConditionTrue,
								},
							},
						},
					})
				}
				return true, podList, nil
			}
			return false, nil, nil
		})
		controller := &DeploymentController{
			client:        fake,
			eventRecorder: &record.FakeRecorder{},
		}
		scaled, err := controller.reconcileOldRCs(allRcs, oldRcs, nil, deployment)
		if err != nil {
			t.Errorf("unexpected error: %v", err)
			continue
		}
		if !test.scaleExpected {
			if scaled {
				t.Errorf("unexpected scaling: %v", fake.Actions())
			}
			continue
		}
		if test.scaleExpected && !scaled {
			t.Errorf("expected scaling to occur; actions: %v", fake.Actions())
			continue
		}
		// There are both list and update actions logged, so extract the update
		// action for verification.
		var updateAction testclient.UpdateAction
		for _, action := range fake.Actions() {
			switch a := action.(type) {
			case testclient.UpdateAction:
				if updateAction != nil {
					t.Errorf("expected only 1 update action; had %v and found %v", updateAction, a)
				} else {
					updateAction = a
				}
			}
		}
		if updateAction == nil {
			t.Errorf("expected an update action")
			continue
		}
		updated := updateAction.GetObject().(*api.ReplicationController)
		if e, a := test.expectedOldReplicas, updated.Spec.Replicas; e != a {
			t.Errorf("expected update to %d replicas, got %d", e, a)
		}
	}
}

func rc(name string, replicas int) *api.ReplicationController {
	return &api.ReplicationController{
		ObjectMeta: api.ObjectMeta{
			Name: name,
		},
		Spec: api.ReplicationControllerSpec{
			Replicas: replicas,
			Template: &api.PodTemplateSpec{},
		},
	}
}

func deployment(name string, replicas int, maxSurge, maxUnavailable util.IntOrString) exp.Deployment {
	return exp.Deployment{
		ObjectMeta: api.ObjectMeta{
			Name: name,
		},
		Spec: exp.DeploymentSpec{
			Replicas: replicas,
			Strategy: exp.DeploymentStrategy{
				Type: exp.RollingUpdateDeploymentStrategyType,
				RollingUpdate: &exp.RollingUpdateDeployment{
					MaxSurge:       maxSurge,
					MaxUnavailable: maxUnavailable,
				},
			},
		},
	}
}


text:
  Blendecques est
      une ville située dans le département des Pas-de-Calais en Nord-Pas-de-Calais. Elle comptait 5 087 habitants en 2008.

À proximité de Blendecques sont positionnées géographiquement les villes de
Wisques localisée à 5 km, 248 habitants,
Wizernes à 3 km, 3 344 habitants,
Arques localisée à 3 km, 9 615 habitants,
Clairmarais à 5 km, 656 habitants,
Tatinghem à 5 km, 1 796 habitants,
Saint-Omer située à 3 km, 15 004 habitants,
 entre autres. De plus, Blendecques est située à seulement 18 km de Hazebrouck.

À Blendecques, la valorisation moyenne à la vente d'un appartement se situe à 1 258 € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 1 326 € du m². À la location la valeur moyenne se situe à 9,19 € du m² mensuel.

À Blendecques le salaire moyen mensuel par personne est situé à environ 1 859 €  net. C'est inférieur à la moyenne du pays.

La ville propose quelques  équipements, elle propose entre autres deux terrains de sport.

Le parc d'habitations, à Blendecques, était réparti en 2011 en 99 appartements et 1 999 maisons soit
 un marché plutôt équilibré.


text:
{-# LANGUAGE TypeFamilies, PartialTypeSignatures #-}

-- In #12033 this was called HaskellBug.hs

module T12033 where
tripleStoreToRuleSet :: v -> v
tripleStoreToRuleSet getAtom
 = makeTuple getAtom
 where
   makeRule v = makeExpression v
   makeTuple v = makeExpression v
   makeExpression :: _
   makeExpression v = makeTuple getAtom


text:
package helpers.tree;

import org.antlr.runtime.tree.CommonTreeAdaptor;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.Token;
import org.antlr.runtime.TokenStream;

public class DashTreeAdaptor extends CommonTreeAdaptor {

    public Object create(Token payload) {
        return new DashAST(payload);
    }

    public Object dupNode(Object t) {
        if ( t==null ) return null;
        return create(((DashAST)t).token);
    }
}


text:
use env_logger;
#[allow(unused_imports)]
use pact_matching::models::PactSpecification;
#[allow(unused_imports)]
use pact_matching::models::Request;
#[allow(unused_imports)]
use pact_matching::match_request;
#[allow(unused_imports)]
use expectest::prelude::*;
#[allow(unused_imports)]
use serde_json;

#[test]
fn different_order() {
    env_logger::init().unwrap_or(());
    let pact : serde_json::Value = serde_json::from_str(r#"
      {
        "match": true,
        "comment": "Queries are the same but in different key order",
        "expected" : {
          "method": "GET",
          "path": "/path",
          "query": "alligator=Mary&hippo=John",
          "headers": {}

        },
        "actual": {
          "method": "GET",
          "path": "/path",
          "query": "hippo=John&alligator=Mary",
          "headers": {}

        }
      }
    "#).unwrap();

    let expected = Request::from_json(&pact.get("expected").unwrap(), &PactSpecification::V2);
    println!("{:?}", expected);
    let actual = Request::from_json(&pact.get("actual").unwrap(), &PactSpecification::V2);
    println!("{:?}", actual);
    let pact_match = pact.get("match").unwrap();
    let result = match_request(expected, actual);
    if pact_match.as_bool().unwrap() {
       expect!(result.iter()).to(be_empty());
    } else {
       expect!(result.iter()).to_not(be_empty());
    }
}

#[test]
fn different_params() {
    env_logger::init().unwrap_or(());
    let pact : serde_json::Value = serde_json::from_str(r#"
      {
        "match": false,
        "comment": "Queries are not the same - hippo is Fred instead of John",
        "expected" : {
          "method": "GET",
          "path": "/path",
          "query": "alligator=Mary&hippo=John",
          "headers": {}

        },
        "actual": {
          "method": "GET",
          "path": "/path",
          "query": "alligator=Mary&hippo=Fred",
          "headers": {}

        }
      }
    "#).unwrap();

    let expected = Request::from_json(&pact.get("expected").unwrap(), &PactSpecification::V2);
    println!("{:?}", expected);
    let actual = Request::from_json(&pact.get("actual").unwrap(), &PactSpecification::V2);
    println!("{:?}", actual);
    let pact_match = pact.get("match").unwrap();
    let result = match_request(expected, actual);
    if pact_match.as_bool().unwrap() {
       expect!(result.iter()).to(be_empty());
    } else {
       expect!(result.iter()).to_not(be_empty());
    }
}

#[test]
fn matches_with_equals_in_the_query_value() {
    env_logger::init().unwrap_or(());
    let pact : serde_json::Value = serde_json::from_str(r#"
      {
        "match": true,
        "comment": "Queries are equivalent",
        "expected" : {
          "method": "GET",
          "path": "/path",
          "query": "options=delete.topic.enable=true&broker=1",
          "headers": {}

        },
        "actual": {
          "method": "GET",
          "path": "/path",
          "query": "options=delete.topic.enable%3Dtrue&broker=1",
          "headers": {}

        }
      }
    "#).unwrap();

    let expected = Request::from_json(&pact.get("expected").unwrap(), &PactSpecification::V2);
    println!("{:?}", expected);
    let actual = Request::from_json(&pact.get("actual").unwrap(), &PactSpecification::V2);
    println!("{:?}", actual);
    let pact_match = pact.get("match").unwrap();
    let result = match_request(expected, actual);
    if pact_match.as_bool().unwrap() {
       expect!(result.iter()).to(be_empty());
    } else {
       expect!(result.iter()).to_not(be_empty());
    }
}

#[test]
fn matches() {
    env_logger::init().unwrap_or(());
    let pact : serde_json::Value = serde_json::from_str(r#"
      {
        "match": true,
        "comment": "Queries are the same",
        "expected" : {
          "method": "GET",
          "path": "/path",
          "query": "alligator=Mary&hippo=John",
          "headers": {}

        },
        "actual": {
          "method": "GET",
          "path": "/path",
          "query": "alligator=Mary&hippo=John",
          "headers": {}

        }
      }
    "#).unwrap();

    let expected = Request::from_json(&pact.get("expected").unwrap(), &PactSpecification::V2);
    println!("{:?}", expected);
    let actual = Request::from_json(&pact.get("actual").unwrap(), &PactSpecification::V2);
    println!("{:?}", actual);
    let pact_match = pact.get("match").unwrap();
    let result = match_request(expected, actual);
    if pact_match.as_bool().unwrap() {
       expect!(result.iter()).to(be_empty());
    } else {
       expect!(result.iter()).to_not(be_empty());
    }
}

#[test]
fn missing_params() {
    env_logger::init().unwrap_or(());
    let pact : serde_json::Value = serde_json::from_str(r#"
      {
        "match": false,
        "comment": "Queries are not the same - elephant is missing",
        "expected" : {
          "method": "GET",
          "path": "/path",
          "query": "alligator=Mary&hippo=Fred&elephant=missing",
          "headers": {}

        },
        "actual": {
          "method": "GET",
          "path": "/path",
          "query": "alligator=Mary&hippo=Fred",
          "headers": {}

        }
      }
    "#).unwrap();

    let expected = Request::from_json(&pact.get("expected").unwrap(), &PactSpecification::V2);
    println!("{:?}", expected);
    let actual = Request::from_json(&pact.get("actual").unwrap(), &PactSpecification::V2);
    println!("{:?}", actual);
    let pact_match = pact.get("match").unwrap();
    let result = match_request(expected, actual);
    if pact_match.as_bool().unwrap() {
       expect!(result.iter()).to(be_empty());
    } else {
       expect!(result.iter()).to_not(be_empty());
    }
}

#[test]
fn same_parameter_different_values() {
    env_logger::init().unwrap_or(());
    let pact : serde_json::Value = serde_json::from_str(r#"
      {
        "match": false,
        "comment": "Queries are not the same - animals are alligator, hippo versus alligator, elephant",
        "expected" : {
          "method": "GET",
          "path": "/path",
          "query": "animal=alligator&animal=hippo",
          "headers": {}

        },
        "actual": {
          "method": "GET",
          "path": "/path",
          "query": "animal=alligator&animal=elephant",
          "headers": {}

        }
      }
    "#).unwrap();

    let expected = Request::from_json(&pact.get("expected").unwrap(), &PactSpecification::V2);
    println!("{:?}", expected);
    let actual = Request::from_json(&pact.get("actual").unwrap(), &PactSpecification::V2);
    println!("{:?}", actual);
    let pact_match = pact.get("match").unwrap();
    let result = match_request(expected, actual);
    if pact_match.as_bool().unwrap() {
       expect!(result.iter()).to(be_empty());
    } else {
       expect!(result.iter()).to_not(be_empty());
    }
}

#[test]
fn same_parameter_multiple_times_in_different_order() {
    env_logger::init().unwrap_or(());
    let pact : serde_json::Value = serde_json::from_str(r#"
      {
        "match": false,
        "comment": "Queries are not the same - values are in different order",
        "expected" : {
          "method": "GET",
          "path": "/path",
          "query": "animal=alligator&animal=hippo&animal=elephant",
          "headers": {}

        },
        "actual": {
          "method": "GET",
          "path": "/path",
          "query": "animal=hippo&animal=alligator&animal=elephant",
          "headers": {}
        }
      }
    "#).unwrap();

    let expected = Request::from_json(&pact.get("expected").unwrap(), &PactSpecification::V2);
    println!("{:?}", expected);
    let actual = Request::from_json(&pact.get("actual").unwrap(), &PactSpecification::V2);
    println!("{:?}", actual);
    let pact_match = pact.get("match").unwrap();
    let result = match_request(expected, actual);
    if pact_match.as_bool().unwrap() {
       expect!(result.iter()).to(be_empty());
    } else {
       expect!(result.iter()).to_not(be_empty());
    }
}

#[test]
fn same_parameter_multiple_times() {
    env_logger::init().unwrap_or(());
    let pact : serde_json::Value = serde_json::from_str(r#"
      {
        "match": true,
        "comment": "Queries are the same - multiple values are in same order",
        "expected" : {
          "method": "GET",
          "path": "/path",
          "query": "animal=alligator&animal=hippo&animal=elephant&hippo=Fred",
          "headers": {}

        },
        "actual": {
          "method": "GET",
          "path": "/path",
          "query": "animal=alligator&hippo=Fred&animal=hippo&animal=elephant",
          "headers": {}
        }
      }
    "#).unwrap();

    let expected = Request::from_json(&pact.get("expected").unwrap(), &PactSpecification::V2);
    println!("{:?}", expected);
    let actual = Request::from_json(&pact.get("actual").unwrap(), &PactSpecification::V2);
    println!("{:?}", actual);
    let pact_match = pact.get("match").unwrap();
    let result = match_request(expected, actual);
    if pact_match.as_bool().unwrap() {
       expect!(result.iter()).to(be_empty());
    } else {
       expect!(result.iter()).to_not(be_empty());
    }
}

#[test]
fn trailing_ampersand() {
    env_logger::init().unwrap_or(());
    let pact : serde_json::Value = serde_json::from_str(r#"
      {
        "match": true,
        "comment": "Trailing amperands can be ignored",
        "expected" : {
          "method": "GET",
          "path": "/path",
          "query": "alligator=Mary&hippo=John",
          "headers": {}

        },
        "actual": {
          "method": "GET",
          "path": "/path",
          "query": "alligator=Mary&hippo=John&",
          "headers": {}

        }
      }
    "#).unwrap();

    let expected = Request::from_json(&pact.get("expected").unwrap(), &PactSpecification::V2);
    println!("{:?}", expected);
    let actual = Request::from_json(&pact.get("actual").unwrap(), &PactSpecification::V2);
    println!("{:?}", actual);
    let pact_match = pact.get("match").unwrap();
    let result = match_request(expected, actual);
    if pact_match.as_bool().unwrap() {
       expect!(result.iter()).to(be_empty());
    } else {
       expect!(result.iter()).to_not(be_empty());
    }
}

#[test]
fn unexpected_param() {
    env_logger::init().unwrap_or(());
    let pact : serde_json::Value = serde_json::from_str(r#"
      {
        "match": false,
        "comment": "Queries are not the same - elephant is not expected",
        "expected" : {
          "method": "GET",
          "path": "/path",
          "query": "alligator=Mary&hippo=John",
          "headers": {}

        },
        "actual": {
          "method": "GET",
          "path": "/path",
          "query": "alligator=Mary&hippo=John&elephant=unexpected",
          "headers": {}

        }
      }
    "#).unwrap();

    let expected = Request::from_json(&pact.get("expected").unwrap(), &PactSpecification::V2);
    println!("{:?}", expected);
    let actual = Request::from_json(&pact.get("actual").unwrap(), &PactSpecification::V2);
    println!("{:?}", actual);
    let pact_match = pact.get("match").unwrap();
    let result = match_request(expected, actual);
    if pact_match.as_bool().unwrap() {
       expect!(result.iter()).to(be_empty());
    } else {
       expect!(result.iter()).to_not(be_empty());
    }
}


text:
var _indexOfInstanceProperty = require("@babel/runtime-corejs3/core-js/instance/index-of");

var _Object$keys = require("@babel/runtime-corejs3/core-js/object/keys");

function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null) return {};
  var target = {};

  var sourceKeys = _Object$keys(source);

  var key, i;

  for (i = 0; i < sourceKeys.length; i++) {
    key = sourceKeys[i];
    if (_indexOfInstanceProperty(excluded).call(excluded, key) >= 0) continue;
    target[key] = source[key];
  }

  return target;
}

module.exports = _objectWithoutPropertiesLoose;


text:
package com.planet_ink.coffee_mud.Abilities.Traps;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("unchecked")
public class Trap_RoomPit extends StdTrap
{
	public String ID() { return "Trap_RoomPit"; }
	public String name(){ return "pit trap";}
	protected int canAffectCode(){return Ability.CAN_ROOMS;}
	protected int canTargetCode(){return 0;}
	protected int trapLevel(){return 1;}
	public String requiresToSet(){return "";}
	protected Vector pit=null;

	public void unInvoke()
	{
		if((pit!=null)
		&&(canBeUninvoked())
		&&(pit.size()>1))
		{
			Room R1=(Room)pit.firstElement();
			Room R2=(Room)pit.lastElement();
			while(R1.numInhabitants()>0)
			{
				MOB M=R1.fetchInhabitant(0);
				if(M!=null){
					M.killMeDead(false);
					R1.delInhabitant(M);
				}
			}
			while(R2.numInhabitants()>0)
			{
				MOB M=R2.fetchInhabitant(0);
				if(M!=null){
					M.killMeDead(false);
					R2.delInhabitant(M);
				}
			}
			Room R=R2.getRoomInDir(Directions.UP);
			if((R!=null)&&(R.getRoomInDir(Directions.DOWN)==R2))
			{
				R.rawDoors()[Directions.DOWN]=null;
				R.setRawExit(Directions.DOWN,null);
			}
			R2.rawDoors()[Directions.UP]=null;
			R2.setRawExit(Directions.UP,null);
			R2.rawDoors()[Directions.DOWN]=null;
			R2.setRawExit(Directions.DOWN,null);
			R1.rawDoors()[Directions.UP]=null;
			R1.setRawExit(Directions.UP,null);
			pit=null;
            R1.destroy();
            R2.destroy();
			super.unInvoke();
		}
		else
		{
			pit=null;
			super.unInvoke();
		}
	}

    public boolean canSetTrapOn(MOB mob, Environmental E)
    {
        if(!super.canSetTrapOn(mob,E)) return false;
        if(E instanceof Room)
        {
            if(((Room)E).getRoomInDir(Directions.DOWN)!=null)
            {
                mob.tell("The flooring here won't support a pit.");
                return false;
            }
        }
        return true;
    }

	public boolean tick(Tickable ticking, int tickID)
	{
		if((unInvoked)&&(canBeUninvoked()))
			return false;

		if((tickID==Tickable.TICKID_TRAP_DESTRUCTION)
		&&(canBeUninvoked())
		&&(pit!=null)
		&&(pit.size()>1)
		&&(((((Room)pit.firstElement()).numPCInhabitants()>0)
			||(((Room)pit.lastElement()).numPCInhabitants()>0))))
			return true;
		return super.tick(ticking,tickID);
	}

	protected synchronized void makePit(MOB target)
	{
		if((pit==null)||(pit.size()<2))
		{
			Vector V=new Vector();
			Room myPitUp=CMClass.getLocale("ClimbableSurface");
			myPitUp.setRoomID("");
			myPitUp.setArea(target.location().getArea());
			myPitUp.baseEnvStats().setDisposition(myPitUp.baseEnvStats().disposition()|EnvStats.IS_DARK);
			myPitUp.setDisplayText("Inside a dark pit");
			myPitUp.setDescription("The walls here are slick and tall.  The trap door has already closed.");
			myPitUp.recoverEnvStats();

			Room myPit=CMClass.getLocale("StdRoom");
			myPit.setRoomID("");
			myPit.setArea(target.location().getArea());
			myPit.baseEnvStats().setDisposition(myPit.baseEnvStats().disposition()|EnvStats.IS_DARK);
			myPit.setDisplayText("Inside a dark pit");
			myPit.setDescription("The walls here are slick and tall.  You can barely see the closed trap door well above you.");
			myPit.setRawExit(Directions.UP,CMClass.getExit("StdOpenDoorway"));
			myPit.rawDoors()[Directions.UP]=myPitUp;
			myPitUp.setRawExit(Directions.DOWN,CMClass.getExit("StdOpenDoorway"));
			myPitUp.rawDoors()[Directions.DOWN]=myPit;
			myPitUp.recoverEnvStats();
			V.addElement(myPit);
			V.addElement(myPitUp);
			pit=V;
		}
	}

	public void executeMsg(Environmental myHost, CMMsg msg)
	{
		boolean unSpring=false;
		if((!sprung)
		&&(affected instanceof Room)
		&&(msg.amITarget(affected))
		&&((msg.targetMinor()==CMMsg.TYP_ENTER)
		&&(!msg.source().isMine(affected)))
		&&(msg.tool()!=null)
		&&(msg.tool() instanceof Exit))
		{
			Room room=(Room)affected;
			if((room.getExitInDir(Directions.DOWN)==msg.tool())
			||(room.getReverseExit(Directions.DOWN)==msg.tool()))
			{
				unSpring=true;
				sprung=true;
			}
		}
		super.executeMsg(myHost,msg);
		if(unSpring) sprung=false;
	}
	public void finishSpringing(MOB target)
	{
		if((!invoker().mayIFight(target))||(target.envStats().weight()<5))
			target.location().show(target,null,CMMsg.MSG_OK_ACTION,"<S-NAME> float(s) gently into the pit!");
		else
		{
			target.location().show(target,null,CMMsg.MSG_OK_ACTION,"<S-NAME> hit(s) the pit floor with a THUMP!");
			int damage=CMLib.dice().roll(trapLevel()+abilityCode(),6,1);
			CMLib.combat().postDamage(invoker(),target,this,damage,CMMsg.MASK_ALWAYS|CMMsg.TYP_JUSTICE,-1,null);
		}
		CMLib.commands().postLook(target,true);
	}

	public void spring(MOB target)
	{
		if((target!=invoker())&&(target.location()!=null)&&(!CMLib.flags().isInFlight(target)))
		{
			if((!invoker().mayIFight(target))
			||(isLocalExempt(target))
			||(invoker().getGroupMembers(new HashSet()).contains(target))
			||(target==invoker())
			||(CMLib.dice().rollPercentage()<=target.charStats().getSave(CharStats.STAT_SAVE_TRAPS)))
				target.location().show(target,null,null,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,"<S-NAME> avoid(s) falling into a pit!");
			else
			if(target.location().show(target,target,this,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,"<S-NAME> fall(s) into a pit!"))
			{
				super.spring(target);
				makePit(target);
				((Room)pit.lastElement()).setRawExit(Directions.UP,CMClass.getExit("StdClosedDoorway"));
				((Room)pit.lastElement()).rawDoors()[Directions.UP]=target.location();
				if((target.location().getRoomInDir(Directions.DOWN)==null)
				&&(target.location().getExitInDir(Directions.DOWN)==null))
				{
					target.location().setRawExit(Directions.DOWN,CMClass.getExit("StdClosedDoorway"));
					target.location().rawDoors()[Directions.DOWN]=((Room)pit.lastElement());
				}
				((Room)pit.firstElement()).bringMobHere(target,false);
				finishSpringing(target);
			}
		}
	}
}


text:
package org.apache.commons.vfs2;

import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

import org.junit.Test;

/**
 * File system test that check that a file system can be modified.
 */
public class ProviderWriteAppendTests extends AbstractProviderTestCase {

    /**
     * Sets up a scratch folder for the test to use.
     */
    protected FileObject createScratchFolder() throws Exception {
        final FileObject scratchFolder = getWriteFolder();

        // Make sure the test folder is empty
        scratchFolder.delete(Selectors.EXCLUDE_SELF);
        scratchFolder.createFolder();

        return scratchFolder;
    }

    /**
     * Returns the capabilities required by the tests of this test case.
     */
    @Override
    protected Capability[] getRequiredCapabilities() {
        return new Capability[] {Capability.CREATE, Capability.DELETE, Capability.GET_TYPE, Capability.LIST_CHILDREN, Capability.READ_CONTENT,
            Capability.WRITE_CONTENT, Capability.APPEND_CONTENT};
    }

    /**
     * Tests create-delete-create-a-file sequence on the same file system.
     */
    @Test
    public void testAppendContent() throws Exception {
        try (FileObject scratchFolder = createScratchFolder();

            // Create direct child of the test folder
            final FileObject file = scratchFolder.resolveFile("file1.txt")) {
            assertFalse(file.exists());

            // Create the source file
            final String content = "Here is some sample content for the file.  Blah Blah Blah.";
            final String contentAppend = content + content;

            try (FileContent fileContent = file.getContent(); OutputStream os = fileContent.getOutputStream()) {
                os.write(content.getBytes(StandardCharsets.UTF_8));
            }
            assertSameContent(content, file);

            // Append to the new file
            try (FileContent fileContent = file.getContent(); OutputStream os2 = fileContent.getOutputStream(true)) {
                os2.write(content.getBytes(StandardCharsets.UTF_8));
            }
            assertSameContent(contentAppend, file);

            // Make sure we can copy the new file to another file on the same filesystem
            try (FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt")) {
                assertFalse(fileCopy.exists());
                fileCopy.copyFrom(file, Selectors.SELECT_SELF);

                assertSameContent(contentAppend, fileCopy);

                // Delete the file.
                assertTrue(fileCopy.exists());
                assertTrue(fileCopy.delete());
            }
        }
    }

    /**
     * Tests append-write into a non-existing file.
     *
     * See [VFS-807].
     */
    @Test
    public void testAppendToNonExisting() throws Exception {
        try (FileObject scratchFolder = createScratchFolder();

            // Create direct child of the test folder
            final FileObject file = scratchFolder.resolveFile("file2.txt")) {
            assertFalse(file.exists());

            // Create the source file
            final String content1 = "Here is some sample content for the file. Blah Blah Blah.";

            try (FileContent fileContent = file.getContent(); OutputStream os = fileContent.getOutputStream(true)) {
                os.write(content1.getBytes(StandardCharsets.UTF_8));
            }
            assertSameContent(content1, file);
        }
    }

}


text:
package com.ajoshow.mock.web;

import com.ajoshow.mock.web.dto.EmptyDto;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

/**
 * @author Andy on 2017/4/25.
 */
public class EmptyResponseEntity extends ResponseEntity<EmptyDto> {

    public EmptyResponseEntity() {
        super(new EmptyDto(), HttpStatus.OK);
    }
}