text:
'use strict';

const util = require('../util/util');
const interpolate = require('../util/interpolate');
const browser = require('../util/browser');
const LngLat = require('../geo/lng_lat');
const LngLatBounds = require('../geo/lng_lat_bounds');
const Point = require('point-geometry');
const Evented = require('../util/evented');

/**
 * Options common to {@link Map#jumpTo}, {@link Map#easeTo}, and {@link Map#flyTo},
 * controlling the destination's location, zoom level, bearing, and pitch.
 * All properties are optional. Unspecified
 * options will default to the map's current value for that property.
 *
 * @typedef {Object} CameraOptions
 * @property {LngLatLike} center The destination's center.
 * @property {number} zoom The destination's zoom level.
 * @property {number} bearing The destination's bearing (rotation), measured in degrees counter-clockwise from north.
 * @property {number} pitch The destination's pitch (tilt), measured in degrees.
 * @property {LngLatLike} around If a `zoom` is specified, `around` determines the zoom center (defaults to the center of the map).
 */

/**
 * Options common to map movement methods that involve animation, such as {@link Map#panBy} and
 * {@link Map#easeTo}, controlling the duration and easing function of the animation. All properties
 * are optional.
 *
 * @typedef {Object} AnimationOptions
 * @property {number} duration The animation's duration, measured in milliseconds.
 * @property {Function} easing A function taking a time in the range 0..1 and returning a number where 0 is
 *   the initial state and 1 is the final state.
 * @property {PointLike} offset `x` and `y` coordinates representing the animation's origin of movement relative to the map's center.
 * @property {boolean} animate If `false`, no animation will occur.
 */

/**
 * Options for setting padding on a call to {@link Map#fitBounds}. All properties of this object must be
 * non-negative integers.
 *
 * @typedef {Object} PaddingOptions
 * @property {number} top Padding in pixels from the top of the map canvas.
 * @property {number} bottom Padding in pixels from the bottom of the map canvas.
 * @property {number} left Padding in pixels from the left of the map canvas.
 * @property {number} right Padding in pixels from the right of the map canvas.
 */

class Camera extends Evented {

    constructor(transform, options) {
        super();
        this.moving = false;
        this.transform = transform;
        this._bearingSnap = options.bearingSnap;
    }

    /**
     * Returns the map's geographical centerpoint.
     *
     * @memberof Map#
     * @returns {LngLat} The map's geographical centerpoint.
     */
    getCenter() { return this.transform.center; }

    /**
     * Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`.
     *
     * @memberof Map#
     * @param {LngLatLike} center The centerpoint to set.
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires moveend
     * @returns {Map} `this`
     * @example
     * map.setCenter([-74, 38]);
     * @see [Move symbol with the keyboard](https://www.mapbox.com/mapbox-gl-js/example/rotating-controllable-marker/)
     */
    setCenter(center, eventData) {
        this.jumpTo({center: center}, eventData);
        return this;
    }

    /**
     * Pans the map by the specified offest.
     *
     * @memberof Map#
     * @param {Array<number>} offset `x` and `y` coordinates by which to pan the map.
     * @param {AnimationOptions} [options]
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires moveend
     * @returns {Map} `this`
     * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)
     */
    panBy(offset, options, eventData) {
        this.panTo(this.transform.center,
            util.extend({offset: Point.convert(offset).mult(-1)}, options), eventData);
        return this;
    }

    /**
     * Pans the map to the specified location, with an animated transition.
     *
     * @memberof Map#
     * @param {LngLatLike} lnglat The location to pan the map to.
     * @param {AnimationOptions} [options]
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires moveend
     * @returns {Map} `this`
     */
    panTo(lnglat, options, eventData) {
        return this.easeTo(util.extend({
            center: lnglat
        }, options), eventData);
    }

    /**
     * Returns the map's current zoom level.
     *
     * @memberof Map#
     * @returns {number} The map's current zoom level.
     */
    getZoom() { return this.transform.zoom; }

    /**
     * Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`.
     *
     * @memberof Map#
     * @param {number} zoom The zoom level to set (0-20).
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires zoomstart
     * @fires move
     * @fires zoom
     * @fires moveend
     * @fires zoomend
     * @returns {Map} `this`
     * @example
     * // zoom the map to 5
     * map.setZoom(5);
     */
    setZoom(zoom, eventData) {
        this.jumpTo({zoom: zoom}, eventData);
        return this;
    }

    /**
     * Zooms the map to the specified zoom level, with an animated transition.
     *
     * @memberof Map#
     * @param {number} zoom The zoom level to transition to.
     * @param {AnimationOptions} [options]
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires zoomstart
     * @fires move
     * @fires zoom
     * @fires moveend
     * @fires zoomend
     * @returns {Map} `this`
     */
    zoomTo(zoom, options, eventData) {
        return this.easeTo(util.extend({
            zoom: zoom
        }, options), eventData);
    }

    /**
     * Increases the map's zoom level by 1.
     *
     * @memberof Map#
     * @param {AnimationOptions} [options]
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires zoomstart
     * @fires move
     * @fires zoom
     * @fires moveend
     * @fires zoomend
     * @returns {Map} `this`
     */
    zoomIn(options, eventData) {
        this.zoomTo(this.getZoom() + 1, options, eventData);
        return this;
    }

    /**
     * Decreases the map's zoom level by 1.
     *
     * @memberof Map#
     * @param {AnimationOptions} [options]
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires zoomstart
     * @fires move
     * @fires zoom
     * @fires moveend
     * @fires zoomend
     * @returns {Map} `this`
     */
    zoomOut(options, eventData) {
        this.zoomTo(this.getZoom() - 1, options, eventData);
        return this;
    }

    /**
     * Returns the map's current bearing (rotation).
     *
     * @memberof Map#
     * @returns {number} The map's current bearing, measured in degrees counter-clockwise from north.
     * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)
     */
    getBearing() { return this.transform.bearing; }

    /**
     * Sets the maps' bearing (rotation). Equivalent to `jumpTo({bearing: bearing})`.
     *
     * @memberof Map#
     * @param {number} bearing The bearing to set, measured in degrees counter-clockwise from north.
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires moveend
     * @returns {Map} `this`
     * @example
     * // rotate the map to 90 degrees
     * map.setBearing(90);
     */
    setBearing(bearing, eventData) {
        this.jumpTo({bearing: bearing}, eventData);
        return this;
    }

    /**
     * Rotates the map to the specified bearing, with an animated transition.
     *
     * @memberof Map#
     * @param {number} bearing The bearing to rotate the map to, measured in degrees counter-clockwise from north.
     * @param {AnimationOptions} [options]
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires moveend
     * @returns {Map} `this`
     */
    rotateTo(bearing, options, eventData) {
        return this.easeTo(util.extend({
            bearing: bearing
        }, options), eventData);
    }

    /**
     * Rotates the map to a bearing of 0 (due north), with an animated transition.
     *
     * @memberof Map#
     * @param {AnimationOptions} [options]
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires moveend
     * @returns {Map} `this`
     */
    resetNorth(options, eventData) {
        this.rotateTo(0, util.extend({duration: 1000}, options), eventData);
        return this;
    }

    /**
     * Snaps the map's bearing to 0 (due north), if the current bearing is close enough to it (i.e. within the `bearingSnap` threshold).
     *
     * @memberof Map#
     * @param {AnimationOptions} [options]
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires moveend
     * @returns {Map} `this`
     */
    snapToNorth(options, eventData) {
        if (Math.abs(this.getBearing()) < this._bearingSnap) {
            return this.resetNorth(options, eventData);
        }
        return this;
    }

    /**
     * Returns the map's current pitch (tilt).
     *
     * @memberof Map#
     * @returns {number} The map's current pitch, measured in degrees away from the plane of the screen.
     */
    getPitch() { return this.transform.pitch; }

    /**
     * Sets the map's pitch (tilt). Equivalent to `jumpTo({pitch: pitch})`.
     *
     * @memberof Map#
     * @param {number} pitch The pitch to set, measured in degrees away from the plane of the screen (0-60).
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires moveend
     * @returns {Map} `this`
     */
    setPitch(pitch, eventData) {
        this.jumpTo({pitch: pitch}, eventData);
        return this;
    }

    /**
     * Pans and zooms the map to contain its visible area within the specified geographical bounds.
     * This function will also reset the map's bearing to 0 if bearing is nonzero.
     *
     * @memberof Map#
     * @param {LngLatBoundsLike} bounds Center these bounds in the viewport and use the highest
     *      zoom level up to and including `Map#getMaxZoom()` that fits them in the viewport.
     * @param {AnimationOptions | CameraOptions } [options]
     * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.
     * @param {boolean} [options.linear=false] If `true`, the map transitions using
     *     {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. See
     *     those functions and @{link AnimationOptions} for information about options available.
     * @param {Function} [options.easing] An easing function for the animated transition. See [AnimationOptions](#AnimationOptions).
     * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels.
     * @param {number} [options.maxZoom] The maximum zoom level to allow when the map view transitions to the specified bounds.
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires moveend
     * @returns {Map} `this`
	 * @example
     * var bbox = [[-79, 43], [-73, 45]];
     * map.fitBounds(bbox, {
     *   padding: {top: 10, bottom:25, left: 15, right: 5}
     * });
     * @see [Fit a map to a bounding box](https://www.mapbox.com/mapbox-gl-js/example/fitbounds/)
     */
    fitBounds(bounds, options, eventData) {

        options = util.extend({
            padding: {
                top: 0,
                bottom: 0,
                right: 0,
                left: 0
            },
            offset: [0, 0],
            maxZoom: this.transform.maxZoom
        }, options);

        if (typeof options.padding === 'number') {
            const p = options.padding;
            options.padding = {
                top: p,
                bottom: p,
                right: p,
                left: p
            };
        }
        if (!util.deepEqual(Object.keys(options.padding).sort((a, b) => {
            if (a < b) return -1;
            if (a > b) return 1;
            return 0;
        }), ["bottom", "left", "right", "top"])) {
            util.warnOnce("options.padding must be a positive number, or an Object with keys 'bottom', 'left', 'right', 'top'");
            return;
        }

        bounds = LngLatBounds.convert(bounds);

        // we separate the passed padding option into two parts, the part that does not affect the map's center
        // (lateral and vertical padding), and the part that does (paddingOffset). We add the padding offset
        // to the options `offset` object where it can alter the map's center in the subsequent calls to
        // `easeTo` and `flyTo`.
        const paddingOffset = [options.padding.left - options.padding.right, options.padding.top - options.padding.bottom],
            lateralPadding = Math.min(options.padding.right, options.padding.left),
            verticalPadding = Math.min(options.padding.top, options.padding.bottom);
        options.offset = [options.offset[0] + paddingOffset[0], options.offset[1] + paddingOffset[1]];

        const offset = Point.convert(options.offset),
            tr = this.transform,
            nw = tr.project(bounds.getNorthWest()),
            se = tr.project(bounds.getSouthEast()),
            size = se.sub(nw),
            scaleX = (tr.width - lateralPadding * 2 - Math.abs(offset.x) * 2) / size.x,
            scaleY = (tr.height - verticalPadding * 2 - Math.abs(offset.y) * 2) / size.y;

        if (scaleY < 0 || scaleX < 0) {
            util.warnOnce('Map cannot fit within canvas with the given bounds, padding, and/or offset.');
            return;
        }

        options.center = tr.unproject(nw.add(se).div(2));
        options.zoom = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom);
        options.bearing = 0;

        return options.linear ?
            this.easeTo(options, eventData) :
            this.flyTo(options, eventData);
    }

    /**
     * Changes any combination of center, zoom, bearing, and pitch, without
     * an animated transition. The map will retain its current values for any
     * details not specified in `options`.
     *
     * @memberof Map#
     * @param {CameraOptions} options
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires zoomstart
     * @fires move
     * @fires zoom
     * @fires rotate
     * @fires pitch
     * @fires zoomend
     * @fires moveend
     * @returns {Map} `this`
     */
    jumpTo(options, eventData) {
        this.stop();

        const tr = this.transform;
        let zoomChanged = false,
            bearingChanged = false,
            pitchChanged = false;

        if ('zoom' in options && tr.zoom !== +options.zoom) {
            zoomChanged = true;
            tr.zoom = +options.zoom;
        }

        if ('center' in options) {
            tr.center = LngLat.convert(options.center);
        }

        if ('bearing' in options && tr.bearing !== +options.bearing) {
            bearingChanged = true;
            tr.bearing = +options.bearing;
        }

        if ('pitch' in options && tr.pitch !== +options.pitch) {
            pitchChanged = true;
            tr.pitch = +options.pitch;
        }

        this.fire('movestart', eventData)
            .fire('move', eventData);

        if (zoomChanged) {
            this.fire('zoomstart', eventData)
                .fire('zoom', eventData)
                .fire('zoomend', eventData);
        }

        if (bearingChanged) {
            this.fire('rotate', eventData);
        }

        if (pitchChanged) {
            this.fire('pitch', eventData);
        }

        return this.fire('moveend', eventData);
    }

    /**
     * Changes any combination of center, zoom, bearing, and pitch, with an animated transition
     * between old and new values. The map will retain its current values for any
     * details not specified in `options`.
     *
     * @memberof Map#
     * @param {Object} options Options describing the destination and animation of the transition.
    *            Accepts [CameraOptions](#CameraOptions) and [AnimationOptions](#AnimationOptions).
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires zoomstart
     * @fires move
     * @fires zoom
     * @fires rotate
     * @fires pitch
     * @fires zoomend
     * @fires moveend
     * @returns {Map} `this`
     * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)
     */
    easeTo(options, eventData) {
        this.stop();

        options = util.extend({
            offset: [0, 0],
            duration: 500,
            easing: util.ease
        }, options);

        const tr = this.transform,
            offset = Point.convert(options.offset),
            startZoom = this.getZoom(),
            startBearing = this.getBearing(),
            startPitch = this.getPitch(),

            zoom = 'zoom' in options ? +options.zoom : startZoom,
            bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing,
            pitch = 'pitch' in options ? +options.pitch : startPitch;

        let toLngLat,
            toPoint;

        if ('center' in options) {
            toLngLat = LngLat.convert(options.center);
            toPoint = tr.centerPoint.add(offset);
        } else if ('around' in options) {
            toLngLat = LngLat.convert(options.around);
            toPoint = tr.locationPoint(toLngLat);
        } else {
            toPoint = tr.centerPoint.add(offset);
            toLngLat = tr.pointLocation(toPoint);
        }

        const fromPoint = tr.locationPoint(toLngLat);

        if (options.animate === false) options.duration = 0;

        this.zooming = (zoom !== startZoom);
        this.rotating = (startBearing !== bearing);
        this.pitching = (pitch !== startPitch);

        if (options.smoothEasing && options.duration !== 0) {
            options.easing = this._smoothOutEasing(options.duration);
        }

        if (!options.noMoveStart) {
            this.moving = true;
            this.fire('movestart', eventData);
        }
        if (this.zooming) {
            this.fire('zoomstart', eventData);
        }

        clearTimeout(this._onEaseEnd);

        this._ease(function (k) {
            if (this.zooming) {
                tr.zoom = interpolate(startZoom, zoom, k);
            }

            if (this.rotating) {
                tr.bearing = interpolate(startBearing, bearing, k);
            }

            if (this.pitching) {
                tr.pitch = interpolate(startPitch, pitch, k);
            }

            tr.setLocationAtPoint(toLngLat, fromPoint.add(toPoint.sub(fromPoint)._mult(k)));

            this.fire('move', eventData);
            if (this.zooming) {
                this.fire('zoom', eventData);
            }
            if (this.rotating) {
                this.fire('rotate', eventData);
            }
            if (this.pitching) {
                this.fire('pitch', eventData);
            }
        }, () => {
            if (options.delayEndEvents) {
                this._onEaseEnd = setTimeout(this._easeToEnd.bind(this, eventData), options.delayEndEvents);
            } else {
                this._easeToEnd(eventData);
            }
        }, options);

        return this;
    }

    _easeToEnd(eventData) {
        const wasZooming = this.zooming;
        this.moving = false;
        this.zooming = false;
        this.rotating = false;
        this.pitching = false;

        if (wasZooming) {
            this.fire('zoomend', eventData);
        }
        this.fire('moveend', eventData);

    }

    /**
     * Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that
     * evokes flight. The animation seamlessly incorporates zooming and panning to help
     * the user maintain her bearings even after traversing a great distance.
     *
     * @memberof Map#
     * @param {Object} options Options describing the destination and animation of the transition.
     *     Accepts [CameraOptions](#CameraOptions), [AnimationOptions](#AnimationOptions),
     *     and the following additional options.
     * @param {number} [options.curve=1.42] The zooming "curve" that will occur along the
     *     flight path. A high value maximizes zooming for an exaggerated animation, while a low
     *     value minimizes zooming for an effect closer to {@link Map#easeTo}. 1.42 is the average
     *     value selected by participants in the user study discussed in
     *     [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf). A value of
     *     `Math.pow(6, 0.25)` would be equivalent to the root mean squared average velocity. A
     *     value of 1 would produce a circular motion.
     * @param {number} [options.minZoom] The zero-based zoom level at the peak of the flight path. If
     *     `options.curve` is specified, this option is ignored.
     * @param {number} [options.speed=1.2] The average speed of the animation defined in relation to
     *     `options.curve`. A speed of 1.2 means that the map appears to move along the flight path
     *     by 1.2 times `options.curve` screenfuls every second. A _screenful_ is the map's visible span.
     *     It does not correspond to a fixed physical distance, but varies by zoom level.
     * @param {number} [options.screenSpeed] The average speed of the animation measured in screenfuls
     *     per second, assuming a linear timing curve. If `options.speed` is specified, this option is ignored.
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires movestart
     * @fires zoomstart
     * @fires move
     * @fires zoom
     * @fires rotate
     * @fires pitch
     * @fires zoomend
     * @fires moveend
     * @returns {Map} `this`
     * @example
     * // fly with default options to null island
     * map.flyTo({center: [0, 0], zoom: 9});
     * // using flyTo options
     * map.flyTo({
     *   center: [0, 0],
     *   zoom: 9,
     *   speed: 0.2,
     *   curve: 1,
     *   easing(t) {
     *     return t;
     *   }
     * });
     * @see [Fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto/)
     * @see [Slowly fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto-options/)
     * @see [Fly to a location based on scroll position](https://www.mapbox.com/mapbox-gl-js/example/scroll-fly-to/)
     */
    flyTo(options, eventData) {
        // This method implements an "optimal path" animation, as detailed in:
        //
        // Van Wijk, Jarke J.; Nuij, Wim A. A. "Smooth and efficient zooming and panning." INFOVIS
        //   '03. pp. 15–22. <https://www.win.tue.nl/~vanwijk/zoompan.pdf#page=5>.
        //
        // Where applicable, local variable documentation begins with the associated variable or
        // function in van Wijk (2003).

        this.stop();

        options = util.extend({
            offset: [0, 0],
            speed: 1.2,
            curve: 1.42,
            easing: util.ease
        }, options);

        const tr = this.transform,
            offset = Point.convert(options.offset),
            startZoom = this.getZoom(),
            startBearing = this.getBearing(),
            startPitch = this.getPitch();

        const center = 'center' in options ? LngLat.convert(options.center) : this.getCenter();
        const zoom = 'zoom' in options ?  +options.zoom : startZoom;
        const bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing;
        const pitch = 'pitch' in options ? +options.pitch : startPitch;

        // If a path crossing the antimeridian would be shorter, extend the final coordinate so that
        // interpolating between the two endpoints will cross it.
        if (Math.abs(tr.center.lng) + Math.abs(center.lng) > 180) {
            if (tr.center.lng > 0 && center.lng < 0) {
                center.lng += 360;
            } else if (tr.center.lng < 0 && center.lng > 0) {
                center.lng -= 360;
            }
        }

        const scale = tr.zoomScale(zoom - startZoom),
            from = tr.point,
            to = 'center' in options ? tr.project(center).sub(offset.div(scale)) : from;

        let rho = options.curve;

            // w₀: Initial visible span, measured in pixels at the initial scale.
        const w0 = Math.max(tr.width, tr.height),
            // w₁: Final visible span, measured in pixels with respect to the initial scale.
            w1 = w0 / scale,
            // Length of the flight path as projected onto the ground plane, measured in pixels from
            // the world image origin at the initial scale.
            u1 = to.sub(from).mag();

        if ('minZoom' in options) {
            const minZoom = util.clamp(Math.min(options.minZoom, startZoom, zoom), tr.minZoom, tr.maxZoom);
            // w<sub>m</sub>: Maximum visible span, measured in pixels with respect to the initial
            // scale.
            const wMax = w0 / tr.zoomScale(minZoom - startZoom);
            rho = Math.sqrt(wMax / u1 * 2);
        }

        // ρ²
        const rho2 = rho * rho;

        /**
         * rᵢ: Returns the zoom-out factor at one end of the animation.
         *
         * @param i 0 for the ascent or 1 for the descent.
         * @private
         */
        function r(i) {
            const b = (w1 * w1 - w0 * w0 + (i ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (i ? w1 : w0) * rho2 * u1);
            return Math.log(Math.sqrt(b * b + 1) - b);
        }

        function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
        function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
        function tanh(n) { return sinh(n) / cosh(n); }

        // r₀: Zoom-out factor during ascent.
        const r0 = r(0);
            /**
             * w(s): Returns the visible span on the ground, measured in pixels with respect to the
             * initial scale.
             *
             * Assumes an angular field of view of 2 arctan ½ ≈ 53°.
             * @private
             */
        let w = function (s) { return (cosh(r0) / cosh(r0 + rho * s)); },
            /**
             * u(s): Returns the distance along the flight path as projected onto the ground plane,
             * measured in pixels from the world image origin at the initial scale.
             * @private
             */
            u = function (s) { return w0 * ((cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2) / u1; },
            // S: Total length of the flight path, measured in ρ-screenfuls.
            S = (r(1) - r0) / rho;

        // When u₀ = u₁, the optimal path doesn't require both ascent and descent.
        if (Math.abs(u1) < 0.000001) {
            // Perform a more or less instantaneous transition if the path is too short.
            if (Math.abs(w0 - w1) < 0.000001) return this.easeTo(options, eventData);

            const k = w1 < w0 ? -1 : 1;
            S = Math.abs(Math.log(w1 / w0)) / rho;

            u = function() { return 0; };
            w = function(s) { return Math.exp(k * rho * s); };
        }

        if ('duration' in options) {
            options.duration = +options.duration;
        } else {
            const V = 'screenSpeed' in options ? +options.screenSpeed / rho : +options.speed;
            options.duration = 1000 * S / V;
        }

        this.moving = true;
        this.zooming = true;
        if (startBearing !== bearing) this.rotating = true;
        if (startPitch !== pitch) this.pitching = true;

        this.fire('movestart', eventData);
        this.fire('zoomstart', eventData);

        this._ease(function (k) {
            // s: The distance traveled along the flight path, measured in ρ-screenfuls.
            const s = k * S,
                us = u(s);

            const scale = 1 / w(s);
            tr.zoom = startZoom + tr.scaleZoom(scale);
            tr.center = tr.unproject(from.add(to.sub(from).mult(us)).mult(scale));

            if (this.rotating) {
                tr.bearing = interpolate(startBearing, bearing, k);
            }
            if (this.pitching) {
                tr.pitch = interpolate(startPitch, pitch, k);
            }

            this.fire('move', eventData);
            this.fire('zoom', eventData);
            if (this.rotating) {
                this.fire('rotate', eventData);
            }
            if (this.pitching) {
                this.fire('pitch', eventData);
            }
        }, function() {
            this.moving = false;
            this.zooming = false;
            this.rotating = false;
            this.pitching = false;

            this.fire('zoomend', eventData);
            this.fire('moveend', eventData);
        }, options);

        return this;
    }

    isEasing() {
        return !!this._abortFn;
    }

    /**
     * Returns a Boolean indicating whether the camera is moving.
     *
     * @memberof Map#
     * @returns {boolean} A Boolean indicating whether the camera is moving.
     */
    isMoving() {
        return this.moving;
    }

    /**
     * Stops any animated transition underway.
     *
     * @memberof Map#
     * @returns {Map} `this`
     */
    stop() {
        if (this._abortFn) {
            this._abortFn();
            this._finishEase();
        }
        return this;
    }

    _ease(frame, finish, options) {
        this._finishFn = finish;
        this._abortFn = browser.timed(function (t) {
            frame.call(this, options.easing(t));
            if (t === 1) {
                this._finishEase();
            }
        }, options.animate === false ? 0 : options.duration, this);
    }

    _finishEase() {
        delete this._abortFn;
        // The finish function might emit events which trigger new eases, which
        // set a new _finishFn. Ensure we don't delete it unintentionally.
        const finish = this._finishFn;
        delete this._finishFn;
        finish.call(this);
    }

    // convert bearing so that it's numerically close to the current one so that it interpolates properly
    _normalizeBearing(bearing, currentBearing) {
        bearing = util.wrap(bearing, -180, 180);
        const diff = Math.abs(bearing - currentBearing);
        if (Math.abs(bearing - 360 - currentBearing) < diff) bearing -= 360;
        if (Math.abs(bearing + 360 - currentBearing) < diff) bearing += 360;
        return bearing;
    }

    // only used on mouse-wheel zoom to smooth out animation
    _smoothOutEasing(duration) {
        let easing = util.ease;

        if (this._prevEase) {
            const ease = this._prevEase,
                t = (Date.now() - ease.start) / ease.duration,
                speed = ease.easing(t + 0.01) - ease.easing(t),

                // Quick hack to make new bezier that is continuous with last
                x = 0.27 / Math.sqrt(speed * speed + 0.0001) * 0.01,
                y = Math.sqrt(0.27 * 0.27 - x * x);

            easing = util.bezier(x, y, 0.25, 1);
        }

        this._prevEase = {
            start: (new Date()).getTime(),
            duration: duration,
            easing: easing
        };

        return easing;
    }
}

/**
 * Fired whenever the map's pitch (tilt) changes.
 *
 * @event pitch
 * @memberof Map
 * @instance
 * @property {MapEventData} data
 */

module.exports = Camera;


text:
@implementation UINavigationController (BFCustomTitleView)

#pragma mark - Custom Title View

- (void)setCustomTitleViewText:(NSString *)text {
    // title view appearance
    UIFont *font = [[[UINavigationBar appearance]titleTextAttributes]objectForKey:NSFontAttributeName];
    if(!font) {
        font = [UIFont BFN_robotoMediumWithSize:15];
    }
    UIColor *color = [[[UINavigationBar appearance]titleTextAttributes]objectForKey:NSForegroundColorAttributeName];
    if(!color) {
        color = [UIColor blackColor];
    }
    // set title view
    [self setCustomTitleViewInternalText:text withFont:font color:color];
}

- (void)setCustomTitleViewText:(NSString *)text withFont:(UIFont *)font color:(UIColor *)color {
    // set title view
    [self setCustomTitleViewInternalText:text withFont:font color:color];
}

- (void)setCustomTitleViewInternalText:(id)text withFont:(UIFont *)font color:(UIColor *)color {
    // navigation bar size
    CGFloat navBarHeight = self.navigationBar.frame.size.height;
    CGFloat navBarWidth = self.navigationBar.frame.size.width;
    // custom wrapping title view
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectZero];
    // custom title view content
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];

    // title view font
    if(font) {
        titleLabel.font = font;
    }
    // title view text color
    if(color) {
        titleLabel.textColor = color;
    }

    // Set the width of the views according to the text size
    NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
    style.lineHeightMultiple = 1.2;
    style.lineBreakMode = NSLineBreakByTruncatingTail;
    style.alignment = NSTextAlignmentCenter;

    // title view width calculation
    CGFloat desiredWidth;
    if([text isKindOfClass:[NSAttributedString class]]) {
        desiredWidth = [text boundingRectWithSize:CGSizeMake(navBarWidth, navBarHeight) options:NSStringDrawingUsesFontLeading context:nil].size.width;
    }
    else {
        desiredWidth = [text boundingRectWithSize:CGSizeMake(navBarWidth, navBarHeight) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : titleLabel.font, NSParagraphStyleAttributeName : style} context:nil].size.width;
    }

    // title view frame
    CGRect titleViewFrame = ({
        CGRect frame = titleLabel.frame;
        frame.size = CGSizeMake(desiredWidth, navBarHeight);
        frame;
    });
    titleLabel.frame = titleViewFrame;
    titleView.frame = titleViewFrame;

    // title view text attributes
    titleLabel.numberOfLines = 1;
    titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    if([text isKindOfClass:[NSAttributedString class]]) {
        titleLabel.attributedText = text;
    }
    else {
        titleLabel.text = text;
    }

    // autoresizing to restrict the bounds to the area that the custom title view allows
    titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    titleView.autoresizesSubviews = YES;
    titleLabel.autoresizingMask = titleView.autoresizingMask;

    // set the custom nav bar titleview
    [titleView addSubview:titleLabel];
    self.visibleViewController.navigationItem.titleView = titleView;
}

- (void)setCustomTitleViewAttributedText:(NSAttributedString *)attributedText {
    // set title view
    [self setCustomTitleViewInternalText:attributedText withFont:nil color:nil];
}

- (void)setCustomTitleViewImage:(UIImage *)image {
    // custom wrapping title view
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectZero];
    // custom title view content
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    imageView.image = image;

    // wrapping title view frame
    titleView.frame = imageView.frame;

    // set the custom nav bar titleview
    [titleView addSubview:imageView];
    self.visibleViewController.navigationItem.titleView = titleView;
}

@end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
LoadTest
</TITLE>

<META NAME="date" CONTENT="2011-09-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

it.essepuntato.earmark.core.test

Class LoadTest

java.lang.Object
  it.essepuntato.earmark.core.test.AbstractTest
      it.essepuntato.earmark.core.test.LoadTest

All Implemented Interfaces:
EARMARKTest

public class LoadTest
extends AbstractTest

A test aims to check the loading of EARMARK documents.

Author:

Silvio Peroni

Constructor Summary

LoadTest()

Method Summary

 java.util.List<java.lang.String>
doTest()

          Apply the test and returns a list of string explaining successes and failures of them.

 java.lang.String
getTestName()

          Get the name of the test.

 boolean
useDocument(EARMARKDocument document)

          Specify an EARMARK document to be used in the test.

Methods inherited from class it.essepuntato.earmark.core.test.AbstractTest

failed, failed, passed

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

LoadTest

public LoadTest()

Method Detail

doTest

public java.util.List<java.lang.String> doTest()

Description copied from interface: EARMARKTest

Apply the test and returns a list of string explaining successes and failures of them.

Returns:
a list of string describing the test results.

getTestName

public java.lang.String getTestName()

Description copied from interface: EARMARKTest

Get the name of the test.

Returns:
the name of the test.

useDocument

public boolean useDocument(EARMARKDocument document)

Description copied from interface: EARMARKTest

Specify an EARMARK document to be used in the test.

Parameters:
document - the document to be used in the test.

Returns:
true if the document will be actually used in the test, false otherwise.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package records

import (
	"encoding/json"
	"errors"
	"hash/fnv"
	"io/ioutil"
	"net"
	"net/http"
	"strconv"
	"strings"

	"github.com/mesosphere/mesos-dns/logging"
	"github.com/mesosphere/mesos-dns/records/labels"
)

// Map host/service name to DNS answer
// REFACTOR - when discoveryinfo is integrated
// Will likely become map[string][]discoveryinfo
type rrs map[string][]string

// Mesos-DNS state
// Refactor when discovery id is available
type RecordGenerator struct {
	As     rrs
	SRVs   rrs
	Slaves map[string]string
}

// The following types help parse state.json
// Resources holds our SRV ports
type Resources struct {
	Ports string `json:"ports"`
}

// Tasks holds mesos task information read in from state.json
type Tasks []struct {
	FrameworkId string `json:"framework_id"`
	Id          string `json:"id"`
	Name        string `json:"name"`
	SlaveId     string `json:"slave_id"`
	State       string `json:"state"`
	Resources   `json:"resources"`
}

// Frameworks holds mesos frameworks information read in from state.json
type Frameworks []struct {
	Tasks `json:"tasks"`
	Name  string `json:"name"`
}

// Slaves is a mapping of id to hostname read in from state.json
type slave struct {
	Id       string `json:"id"`
	Hostname string `json:"hostname"`
}
type Slaves []slave

// StateJSON is a representation of mesos master state.json
type StateJSON struct {
	Frameworks `json:"frameworks"`
	Slaves     `json:"slaves"`
	Leader     string `json:"leader"`
}

// Finds the master and inserts DNS state
func (rg *RecordGenerator) ParseState(leader string, c Config) error {

	// find master -- return if error
	sj, err := rg.findMaster(leader, c.Masters)
	if err != nil {
		logging.Error.Println("no master")
		return err
	}
	if sj.Leader == "" {
		logging.Error.Println("Unexpected error")
		err = errors.New("empty master")
		return err
	}

	// insert state
	rg.InsertState(sj, c.Domain, c.SOARname, c.Listener, c.Masters)
	return nil
}

// Tries each master and looks for the leader
// if no leader responds it errors
func (rg *RecordGenerator) findMaster(leader string, masters []string) (StateJSON, error) {
	var sj StateJSON

	// Check if ZK master is correct
	if leader != "" {
		logging.VeryVerbose.Println("Zookeeper says the leader is: ", leader)
		ip, port, err := getProto(leader)
		if err != nil {
			logging.Error.Println(err)
		}

		sj, _ = rg.loadWrap(ip, port)
		if sj.Leader == "" {
			logging.Verbose.Println("Warning: Zookeeper is wrong about leader")
			if len(masters) == 0 {
				return sj, errors.New("no master")
			} else {
				logging.Verbose.Println("Warning: falling back to Masters config field: ", masters)
			}
		} else {
			return sj, nil
		}
	}

	// try each listed mesos master before dying
	for i, master := range masters {
		ip, port, err := getProto(master)
		if err != nil {
			logging.Error.Println(err)
		}

		sj, _ = rg.loadWrap(ip, port)
		if sj.Leader == "" {
			logging.VeryVerbose.Println("Warning: not a leader - trying next one")
			if len(masters)-1 == i {
				return sj, errors.New("no master")
			}

		} else {
			return sj, nil
		}

	}

	return sj, errors.New("no master")
}

// Loads state.json from mesos master
func (rg *RecordGenerator) loadFromMaster(ip string, port string) (sj StateJSON) {
	// REFACTOR: state.json security
	url := "http://" + ip + ":" + port + "/master/state.json"

	req, err := http.NewRequest("GET", url, nil)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		logging.Error.Println(err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logging.Error.Println(err)
	}

	err = json.Unmarshal(body, &sj)
	if err != nil {
		logging.Error.Println(err)
	}

	return sj
}

// Catches an attempt to load state.json from a mesos master
// attempts can fail from down server or mesos master secondary
// it also reloads from a different master if the master it attempted to
// load from was not the leader
func (rg *RecordGenerator) loadWrap(ip string, port string) (StateJSON, error) {
	var err error
	var sj StateJSON

	defer func() {
		if rec := recover(); rec != nil {
			err = errors.New("can't connect to master")
		}

	}()

	logging.VeryVerbose.Println("reloading from master " + ip)
	sj = rg.loadFromMaster(ip, port)

	if rip := leaderIP(sj.Leader); rip != ip {
		logging.VeryVerbose.Println("Warning: master changed to " + ip)
		sj = rg.loadFromMaster(rip, port)
	}

	return sj, err
}

// hash two long strings into a short one
func hashString(s string) string {
	var upper, lower, sum uint16
	h := fnv.New32a()
	h.Write([]byte(s))
	lower = uint16(h.Sum32())
	upper = uint16(h.Sum32() >> 16)
	sum = uint16(lower + upper)
	return strconv.Itoa(int(sum))
}

// InsertState transforms a StateJSON into RecordGenerator RRs
func (rg *RecordGenerator) InsertState(sj StateJSON, domain string, ns string,
	listener string, masters []string) error {

	// creates a map with slave IP addresses (IPv4)
	rg.Slaves = make(map[string]string)
	for _, slave := range sj.Slaves {
		// if slave is a hostname, translate it
		if net.ParseIP(slave.Hostname) == nil {
			t, err := net.ResolveIPAddr("ip4", slave.Hostname)
			if err != nil {
				logging.Error.Println("cannot translate hostname " + slave.Hostname)
			}
			rg.Slaves[slave.Id] = t.IP.String()
		} else {
			rg.Slaves[slave.Id] = slave.Hostname
		}
	}

	rg.SRVs = make(rrs)
	rg.As = make(rrs)

	// complete crap - refactor me
	for _, f := range sj.Frameworks {
		fname := labels.AsDomainFrag(f.Name)

		for _, task := range f.Tasks {
			host, ok := rg.Slaves[task.SlaveId]
			// skip not running or not discoverable tasks
			if !ok || (task.State != "TASK_RUNNING") {
				continue
			}

			tname := labels.AsDNS952(task.Name)
			sid := slaveIdTail(task.SlaveId)
			tag := hashString(task.Id)
			tail := fname + "." + domain + "."

			// A records for task and task-sid
			arec := tname + "." + tail
			rg.insertRR(arec, host, "A")
			trec := tname + "-" + tag + "-" + sid + "." + tail
			rg.insertRR(trec, host, "A")

			// SRV records
			if task.Resources.Ports != "" {
				ports := yankPorts(task.Resources.Ports)
				for _, port := range ports {
					var srvhost string = trec + ":" + port
					tcp := "_" + tname + "._tcp." + tail
					udp := "_" + tname + "._udp." + tail
					rg.insertRR(tcp, srvhost, "SRV")
					rg.insertRR(udp, srvhost, "SRV")
				}
			}
		}
	}

	rg.listenerRecord(listener, ns)
	rg.masterRecord(domain, masters, sj.Leader)
	return nil
}

// A records for the mesos masters
func (rg *RecordGenerator) masterRecord(domain string, masters []string, leader string) {
	// create records for leader
	// A records
	h := strings.Split(leader, "@")
	if len(h) < 2 {
		logging.Error.Println(leader)
	}
	ip, port, err := getProto(h[1])
	if err != nil {
		logging.Error.Println(err)
	}
	arec := "leader." + domain + "."
	rg.insertRR(arec, ip, "A")
	arec = "master." + domain + "."
	rg.insertRR(arec, ip, "A")
	// SRV records
	tcp := "_leader._tcp." + domain + "."
	udp := "_leader._udp." + domain + "."
	host := "leader." + domain + "." + ":" + port
	rg.insertRR(tcp, host, "SRV")
	rg.insertRR(udp, host, "SRV")

	// if there is a list of masters, insert that as well
	for i, master := range masters {

		// skip leader
		if leader == master {
			continue
		}

		ip, _, err := getProto(master)
		if err != nil {
			logging.Error.Println(err)
		}

		// A records (master and masterN)
		arec := "master." + domain + "."
		rg.insertRR(arec, ip, "A")
		arec = "master" + strconv.Itoa(i) + "." + domain + "."
		rg.insertRR(arec, ip, "A")
	}
}

// A record for mesos-dns (the name is listed in SOA replies)
func (rg *RecordGenerator) listenerRecord(listener string, ns string) {
	if listener == "0.0.0.0" {
		rg.setFromLocal(listener, ns)
	} else if listener == "127.0.0.1" {
		rg.insertRR(ns, "127.0.0.1", "A")
	} else {
		rg.insertRR(ns, listener, "A")
	}
}

// A records for each local interface
// If this causes problems you should explicitly set the
// listener address in config.json
func (rg *RecordGenerator) setFromLocal(host string, ns string) {

	ifaces, err := net.Interfaces()
	if err != nil {
		logging.Error.Println(err)
	}

	// handle err
	for _, i := range ifaces {

		addrs, err := i.Addrs()
		if err != nil {
			logging.Error.Println(err)
		}

		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}

			if ip == nil || ip.IsLoopback() {
				continue
			}

			ip = ip.To4()
			if ip == nil {
				continue
			}

			rg.insertRR(ns, ip.String(), "A")
		}
	}
}

// insertRR inserts host to name's map
// REFACTOR when storage is updated
func (rg *RecordGenerator) insertRR(name string, host string, rtype string) {
	logging.VeryVerbose.Println("[" + rtype + "]\t" + name + ": " + host)

	if rtype == "A" {
		if val, ok := rg.As[name]; ok {
			// check if A record already exists
			// identical tasks on same slave
			for _, b := range val {
				if b == host {
					return
				}
			}
			rg.As[name] = append(val, host)
		} else {
			rg.As[name] = []string{host}
		}
	} else {
		if val, ok := rg.SRVs[name]; ok {
			// check if SRV record already exists
			for _, b := range val {
				if b == host {
					return
				}
			}
			rg.SRVs[name] = append(val, host)
		} else {
			rg.SRVs[name] = []string{host}
		}
	}
}

// returns an array of ports from a range
func yankPorts(ports string) []string {
	rhs := strings.Split(ports, "[")[1]
	lhs := strings.Split(rhs, "]")[0]

	yports := []string{}

	mports := strings.Split(lhs, ",")
	for _, port := range mports {
		tmp := strings.TrimSpace(port)
		pz := strings.Split(tmp, "-")
		lo, _ := strconv.Atoi(pz[0])
		hi, _ := strconv.Atoi(pz[1])

		for t := lo; t <= hi; t++ {
			yports = append(yports, strconv.Itoa(t))
		}
	}
	return yports
}

// leaderIP returns the ip for the mesos master
// input format master@ip:port
func leaderIP(leader string) string {
	pair := strings.Split(leader, "@")[1]
	return strings.Split(pair, ":")[0]
}

// return the slave number from a Mesos slave id
func slaveIdTail(slaveID string) string {
	fields := strings.Split(slaveID, "-")
	return strings.ToLower(fields[len(fields)-1])
}

// should be able to accept
// ip:port
// zk://host1:port1,host2:port2,.../path
// zk://username:password@host1:port1,host2:port2,.../path
// file:///path/to/file (where file contains one of the above)
func getProto(pair string) (string, string, error) {
	h := strings.Split(pair, ":")
	return h[0], h[1], nil
}


text:
package ij.gui;
import java.awt.*;
import java.util.*;

/**Custom component for displaying multiple lines. Based on
   MultiLineLabel class from "Java in a Nutshell" by David Flanagan.*/
public class MultiLineLabel extends Canvas {
	String[] lines;
	int num_lines;
	int margin_width = 6;
	int margin_height = 6;
	int line_height;
	int line_ascent;
	int[] line_widths;
	int min_width, max_width;

    // Breaks the specified label up into an array of lines.
    public MultiLineLabel(String label) {
        init(label);
    }

    public MultiLineLabel(String label, int minimumWidth) {
        init(label);
        min_width = minimumWidth;
    }

    private void init(String text) {
        StringTokenizer t = new StringTokenizer(text, "\n");
        num_lines = t.countTokens();
        lines = new String[num_lines];
        line_widths = new int[num_lines];
        for (int i=0; i<num_lines; i++)
        	lines[i] = t.nextToken();
    }

    // Figures out how wide each line of the label
    // is, and how wide the widest line is.
    protected void measure() {
        FontMetrics fm = this.getFontMetrics(this.getFont());
        // If we don't have font metrics yet, just return.
        if (fm == null) return;
        line_height = fm.getHeight();
        line_ascent = fm.getAscent();
        max_width = 0;
        for(int i = 0; i < num_lines; i++) {
            line_widths[i] = fm.stringWidth(lines[i]);
            if (line_widths[i] > max_width) max_width = line_widths[i];
        }
    }

    public void setText(String text) {
        init(text);
        measure();
        repaint();
    }

    public void setFont(Font f) {
        super.setFont(f);
        measure();
        repaint();
    }

	// This method is invoked after our Canvas is first created
	// but before it can actually be displayed.  After we've
	// invoked our superclass's addNotify() method, we have font
	// metrics and can successfully call measure() to figure out
	// how big the label is.
	public void addNotify() {
		super.addNotify();
		measure();
	}

    // Called by a layout manager when it wants to
    // know how big we'd like to be.
    public Dimension getPreferredSize() {
        return new Dimension(Math.max(min_width, max_width + 2*margin_width),
                     num_lines * line_height + 2*margin_height);
    }

    // Called when the layout manager wants to know
    // the bare minimum amount of space we need to get by.
    public Dimension getMinimumSize() {
        return new Dimension(Math.max(min_width, max_width), num_lines * line_height);
    }

    // Draws the label
    public void paint(Graphics g) {
        int x, y;
        Dimension d = this.getSize();
		if (!ij.IJ.isLinux()) setAntialiasedText(g);
        y = line_ascent + (d.height - num_lines * line_height)/2;
        for(int i = 0; i < num_lines; i++, y += line_height) {
            x = margin_width;
            g.drawString(lines[i], x, y);
        }
    }

	void setAntialiasedText(Graphics g) {
			Graphics2D g2d = (Graphics2D)g;
			g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
	}

}


text:
namespace scene
{

namespace
{
template <typename eval> class interp_impl : public interpolation
{
public:
    using calc_type = interpolation::calc_type;

    interp_impl( void )           = default;
    ~interp_impl( void ) override = default;

    calc_type
    offset( const time &start, const time &end, const time &t ) const override
    {
        return eval::offset( start, end, t );
    }

    size_t storage_size( void ) const override { return eval::storage_size; }

    size_t control_points( void ) const override
    {
        return eval::control_points;
    }
};

template <interp_style> struct interp_eval
{};

template <> struct interp_eval<interp_style::constant>
{
    static constexpr size_t storage_size   = 0;
    static constexpr size_t control_points = 0;

    static constexpr interpolation::calc_type
    offset( const time &, const time &, const time & )
    {
        return interpolation::calc_type( 0 );
    }
};

using constant_impl = interp_impl<interp_eval<interp_style::constant>>;

} // namespace

////////////////////////////////////////

interpolation::interpolation( void ) {}

////////////////////////////////////////

interpolation::~interpolation( void ) {}

////////////////////////////////////////

std::unique_ptr<interpolation> interpolation::create( interp_style i )
{
    switch ( i )
    {
        case interp_style::constant:
            return std::unique_ptr<interpolation>( new constant_impl );

        default: break;
    }
    throw_logic( "Specified interpolation style not yet implemented" );
}

} // namespace scene


text:
package de.assertagile.workshop.agiletesting;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    Logger log = LoggerFactory.getLogger(getClass());

    public static void main(final String[] args) {
        final SpringApplication application = new SpringApplication(Application.class);
        application.run(args);
    }
}


text:
◊headline{About Pollen}

If you check the source code of this website, you may wonder why the HTML contains non-standard HTML tag. It's because I compose this website by using the ◊link["http://pollenpub.com"]{Pollen}—A racket package that encourages writing books like a program.


text:
#ifndef _PARSER_H_
#define _PARSER_H_

class BlockStmt;
class CallExpr;

#include "symbol.h"

extern int         chplLineno;
extern bool        chplParseString;
extern const char* chplParseStringMsg;

extern ModTag      currentModuleType;
extern bool        currentFileNamedOnCommandLine;

extern int         yystartlineno;
extern const char* yyfilename;
extern BlockStmt*  yyblock;

ModuleSymbol*      parseFile(const char* filename,
                             ModTag      modtype,
                             bool        namedOnCommandLine = false);

ModuleSymbol*      parseMod(const char* modname,
                            ModTag      modtype);

BlockStmt*         parseString(const char* string,
                               const char* filename,
                               const char* msg);

void               addModuleToParseList(const char* name,
                                        CallExpr*   newUse);

void               parseDependentModules(ModTag modtype);

#endif


text:
package org.github.arnaudroger.csv.orig;

import org.github.arnaudroger.csv.CellConsumer;

public final class CsvCharConsumer extends CharConsumer {

    public static final char escapeChar = '"';
    public static final char separatorChar = ',';

    public CsvCharConsumer(CharBuffer csvBuffer) {
        super(csvBuffer, false);
    }

    @Override
    protected final boolean isSeparator(char character) {
        return character == separatorChar;
    }

    @Override
    protected final boolean isNotEscapeCharacter(char character) {
        return character != escapeChar;
    }

    @Override
    protected final void pushCell(char[] chars, int start, int end, CellConsumer cellConsumer) {
        int strStart = start;
        int strEnd = end;

        if (strStart < strEnd && chars[strStart] == escapeChar) {
            strStart ++;
            strEnd = unescape(chars, strStart, strEnd);
        }

        cellConsumer.newCell(chars, strStart, strEnd - strStart);
    }

    private int unescape(final char[] chars, final int start, final int end) {
        for(int i = start; i < end - 1; i ++) {
            if (chars[i] == escapeChar) {
                return removeEscapeChars(chars, end, i);
            }
        }

        if (start < end && chars[end - 1]  == escapeChar) {
            return end - 1;
        }

        return end;
    }

    private int removeEscapeChars(final char[] chars, final int end, final int firstEscapeChar) {
        int j = firstEscapeChar;
        boolean escaped = true;
        for(int i = firstEscapeChar + 1;i < end; i++) {
            escaped = chars[i]  == escapeChar && ! escaped;
            if (!escaped) {
                chars[j++] = chars[i];
            }
        }
        return j;
    }
}


text:
{{modalProperties.title}}

{{modalProperties.text}}

Please enter the plotting recipe and click {{modalProperties.button}} to continue.

            <fieldset>

                    <textarea rows="6" cols="75" ng-model="$parent.plotterRecipe"></textarea>

            </fieldset>

Please enter the processing recipe and click {{modalProperties.button}} to continue.

            <fieldset>

                    <textarea rows="6" cols="75" ng-model="$parent.processRecipe"></textarea>

            </fieldset>

        <button class="btn btn-default" ng-click="cancel()">
             Cancel
        </button>
        <button class="btn btn-primary" ng-if="!modalProperties.type" ng-click="modalAction(); ok();">
             {{modalProperties.button}}
        </button>
        <button class="btn btn-primary" ng-if="modalProperties.type == 'plot'"
            ng-disabled="$parent.plotterRecipe == null || $parent.plotterRecipe == ''" ng-click="plotAction(); ok();">
             {{modalProperties.button}}
        </button>
        <button class="btn btn-primary" ng-if="modalProperties.type == 'process'"
            ng-disabled="$parent.processRecipe == null || $parent.processRecipe == ''" ng-click="processAction(); ok();">
             {{modalProperties.button}}
        </button>


text:
Letter is a simple, highly customizable tool to create letters in your browser.

![Letter Screenshot](https://user-images.githubusercontent.com/24532/64169395-064d2200-ce4e-11e9-8315-a19b6f571a16.png)

Instead of messing around in Word, Pages or even Indesign, you can write your letters in the browser, export them as HTML or PDF (via Apple Preview).

Written in plain HTML, CSS and some PHP, Letter can be installed in seconds and run either on your machine with PHP's built-in server, something like MAMP or on a server.

You can setup your own letter template and customize the design with CSS.

## Demo

This is how Letter looks like: https://bastianallgeier.com/projects/letter/

## Installation

### PHP's built-in server

```
git clone https://github.com/bastianallgeier/letter.git
cd letter
php -S localhost:8888
```

### MAMP

1. Download Letter and move it to the htdocs folder of your MAMP installation.
2. Open http://localhost/letter in your browser

## How to…

### Save Letters
You can save your letters by simply using the browser save dialog. Make sure to choose "Save HTML only" as the export option. You will get a nice and clean HTML file of your letter, which can be kept for later at any place you prefer.

### Print Letters
Use your browser's print dialog to print your finished Letters. Make sure to set "No margins" in your printing dialog to avoid broken dimensions of your document.

### Export PDFs
On macOS you can use your browser's print dialog to export your Letter to PDF via Apple Preview. As long as you get the printing settings correct, the PDF will look good too.

## Setup

### Configuration

You can setup the global content of your Letter in `config/config.php`. Adjust the settings and add your own data there.

#### Available options

```php
return [
  'title'      => 'Letter',
  'dateFormat' => 'd. F Y',
  'name'       => 'John Doe',
  'street'     => 'Infinite Loop 12',
  'city'       => '34512 Examplia',
  'country'    => 'Germany',
  'phone'      => '+49 1234 349192',
  'mobile'     => '+49 0171 12761878',
  'email'      => 'john@doe.com',
  'website'    => 'doe.com',
  'bank'       => 'GLS',
  'iban'       => 'DE 1283 1982 9182 91',
  'bic'        => 'GENODEM1GLS',
  'vatId'      => 'DE 2128127981729',
  'taxId'      => '31281/12912',
  'closing'    => 'All the best,',
  'placeholders' => [
    'address' => 'Acme Corp.<br>Sesamestreet 23<br>12345 Gotham City<br>USA',
    'subject' => 'Subject',
    'text'    => '<p>Dear…</p><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.</p>'
  ],
  'labels' => [
    'phone'   => 'Phone',
    'mobile'  => 'Mobile',
    'email'   => 'Email',
    'website' => 'Web',
    'bank'    => 'Bank',
    'iban'    => 'IBAN',
    'bic'     => 'BIC',
    'vatId'   => 'VAT-ID',
    'taxId'   => 'TAX-ID'
  ]
];
```

### Custom stylesheet

If you want to adjust Letter's custom styles, go to `config/styles.css` and add your own CSS there. Check out Letter's custom HTML tags in the browser for further information what to adjust.

### Signature

Replace Letter's example signature.png in `config/signature.png` with your own, to load it automatically

### Custom template

If you want to further modify your Letter, you can copy the default template file from `app/template.php` to `config/template.php` to overwrite Letter's default HTML.

## Requirements

- PHP 5.6+
- Latest Chrome or Opera

Firefox and Safari have issues with margins, when you want to print your letter. I haven't tested IE and Edge yet. Help with additional CSS adjustments is highly welcome!

## License

<http://www.opensource.org/licenses/mit-license.php>

## Author

Bastian Allgeier
<bastian@getkirby.com>
<http://twitter.com/bastianallgeier>


text:
The cond statement
==================

.. code-block:: guess

    Account.transfer_amount(123535353, 252224, 150.40) -> {:ok, "Success"}
                                                    -> {:error, "Failure"}

Transfer Depends on Validation
------------------------------

The validation for a transfer involves the amount transferred and the hour of the day.

.. code-block:: guess

    defmodule Account do
        def transfer_amount(from_amount, to_account, amount) do
            hourOfDay = DateTime.utc_now.hour

            if ! valid_transfer?(amount, hourOfDay) do
                {:error, "Invalid Transfer"}
            else
                perform_transfer(from_account, to_account, amount)
            end

        end
    end

The cond statement
------------------

.. code-block:: guess

    def valid_transfer?(amount, hourOfDay) do
        cond do
            hourOfDay < 12 -> amount <= 5000
            hourOfDay <18 -> amount <= 1000
            true -> amount <= 300
        end
    end

.. image:: https://dl.dropbox.com/s/sczz7kuqssjn4z5/Screenshot%202017-09-09%2006.49.54.png?dl=0
   :width: 640
   :height: 580


text:
$(document).ready(function() {var formatter = new CucumberHTML.DOMFormatter($('.cucumber-report'));formatter.uri("bdd/groups.feature");
formatter.feature({
  "line": 1,
  "name": "Groups",
  "description": "",
  "id": "groups",
  "keyword": "Feature"
});
formatter.scenarioOutline({
  "line": 3,
  "name": "Group creation",
  "description": "",
  "id": "groups;group-creation",
  "type": "scenario_outline",
  "keyword": "Scenario Outline"
});
formatter.step({
  "line": 4,
  "name": "a set of groups",
  "keyword": "Given "
});
formatter.step({
  "line": 5,
  "name": "I create a new group whith name \u003cname\u003e, header \u003cheader\u003e and footer \u003cfooter\u003e",
  "keyword": "When "
});
formatter.step({
  "line": 6,
  "name": "the new set of groups is equal to the old set with the added group",
  "keyword": "Then "
});
formatter.examples({
  "line": 8,
  "name": "",
  "description": "",
  "id": "groups;group-creation;",
  "rows": [
    {
      "cells": [
        "name",
        "footer",
        "header"
      ],
      "line": 9,
      "id": "groups;group-creation;;1"
    },
    {
      "cells": [
        "test name",
        "test footer",
        "test header"
      ],
      "line": 10,
      "id": "groups;group-creation;;2"
    }
  ],
  "keyword": "Examples"
});
formatter.before({
  "duration": 16578942891,
  "status": "passed"
});
formatter.scenario({
  "line": 10,
  "name": "Group creation",
  "description": "",
  "id": "groups;group-creation;;2",
  "type": "scenario",
  "keyword": "Scenario Outline"
});
formatter.step({
  "line": 4,
  "name": "a set of groups",
  "keyword": "Given "
});
formatter.step({
  "line": 5,
  "name": "I create a new group whith name test name, header test header and footer test footer",
  "matchedColumns": [
    0,
    1,
    2
  ],
  "keyword": "When "
});
formatter.step({
  "line": 6,
  "name": "the new set of groups is equal to the old set with the added group",
  "keyword": "Then "
});
formatter.match({
  "location": "GroupStepDefinitions.loadGroups()"
});
formatter.result({
  "duration": 477899910,
  "status": "passed"
});
formatter.match({
  "arguments": [
    {
      "val": "test name",
      "offset": 32
    },
    {
      "val": "test header",
      "offset": 50
    },
    {
      "val": "test footer",
      "offset": 73
    }
  ],
  "location": "GroupStepDefinitions.createGroups(String,String,String)"
});
formatter.result({
  "duration": 3941872345,
  "status": "passed"
});
formatter.match({
  "location": "GroupStepDefinitions.verifyGroupCreated()"
});
formatter.result({
  "duration": 75176059,
  "status": "passed"
});
formatter.after({
  "duration": 1257411831,
  "status": "passed"
});
});


text:
using System;
using System.Runtime.InteropServices;
using System.Windows.Threading;

using System.Diagnostics;
using System.Collections;
using System.Security.Permissions;
using MS.Utility;
using MS.Win32;

namespace System.Windows.Input
{
    //------------------------------------------------------
    //
    //  TextServicesCompartmentManager class
    //
    //------------------------------------------------------

    /// <summary>
    /// This is a class to have a real implement of ITfCompartmentEventSink.
    /// </summary>
    internal class TextServicesCompartmentEventSink : UnsafeNativeMethods.ITfCompartmentEventSink
    {
        //------------------------------------------------------
        //
        //  Constructors
        //
        //------------------------------------------------------

        internal TextServicesCompartmentEventSink(InputMethod inputmethod)
        {
            _inputmethod = inputmethod;
        }

        //------------------------------------------------------
        //
        //  Public Method
        //
        //------------------------------------------------------

        /// <summary>
        ///  This is OnChange method of ITfCompartmentEventSink internface.
        /// </summary>
        public void OnChange(ref Guid rguid)
        {
            _inputmethod.OnChange(ref rguid);
        }

        //------------------------------------------------------
        //
        //  Private Fields
        //
        //------------------------------------------------------

        #region Private Fields

        private InputMethod _inputmethod;

        #endregion Private Fields
    }
}


text:
class Equal < Operation
end


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

// tslint:disable
// TODO: cleanup this file, it's copied as is from Angular CLI.
const build_optimizer_1 = require("@angular-devkit/build-optimizer");
const path = require("path");
const webpack_1 = require("@ngtools/webpack");
const utils_1 = require("../../../utils");
function _pluginOptionsOverrides(buildOptions, pluginOptions) {
    const compilerOptions = {
        ...(pluginOptions.compilerOptions || {})
    };
    const hostReplacementPaths = {};
    if (buildOptions.fileReplacements) {
        for (const replacement of buildOptions.fileReplacements) {
            hostReplacementPaths[replacement.replace] = replacement.with;
        }
    }
    if (utils_1.fullDifferential && buildOptions.scriptTargetOverride) {
        compilerOptions.target = buildOptions.scriptTargetOverride;
    }
    if (buildOptions.preserveSymlinks) {
        compilerOptions.preserveSymlinks = true;
    }
    return {
        ...pluginOptions,
        hostReplacementPaths,
        compilerOptions
    };
}
function _createAotPlugin(wco, options, i18nExtract = false) {
    const { root, buildOptions } = wco;
    const i18nInFile = buildOptions.i18nFile
        ? path.resolve(root, buildOptions.i18nFile)
        : undefined;
    const i18nFileAndFormat = i18nExtract
        ? {
            i18nOutFile: buildOptions.i18nFile,
            i18nOutFormat: buildOptions.i18nFormat,
        } : {
        i18nInFile: i18nInFile,
        i18nInFormat: buildOptions.i18nFormat,
    };
    const additionalLazyModules = {};
    if (buildOptions.lazyModules) {
        for (const lazyModule of buildOptions.lazyModules) {
            additionalLazyModules[lazyModule] = path.resolve(root, lazyModule);
        }
    }
    let pluginOptions = {
        mainPath: path.join(root, buildOptions.main),
        ...i18nFileAndFormat,
        locale: buildOptions.i18nLocale,
        platform: buildOptions.platform === 'server' ? webpack_1.PLATFORM.Server : webpack_1.PLATFORM.Browser,
        missingTranslation: buildOptions.i18nMissingTranslation,
        sourceMap: buildOptions.sourceMap.scripts,
        additionalLazyModules,
        nameLazyFiles: buildOptions.namedChunks,
        forkTypeChecker: buildOptions.forkTypeChecker,
        contextElementDependencyConstructor: require('webpack/lib/dependencies/ContextElementDependency'),
        logger: wco.logger,
        directTemplateLoading: true,
        ...options,
    };
    pluginOptions = _pluginOptionsOverrides(buildOptions, pluginOptions);
    return new webpack_1.AngularCompilerPlugin(pluginOptions);
}
function getNonAotConfig(wco) {
    const { tsConfigPath } = wco;
    return {
        module: { rules: [{ test: /\.tsx?$/, loader: webpack_1.NgToolsLoader }] },
        plugins: [_createAotPlugin(wco, { tsConfigPath, skipCodeGeneration: true })]
    };
}
exports.getNonAotConfig = getNonAotConfig;
function getAotConfig(wco, i18nExtract = false) {
    const { tsConfigPath, buildOptions } = wco;
    const loaders = [webpack_1.NgToolsLoader];
    if (buildOptions.buildOptimizer) {
        loaders.unshift({
            loader: build_optimizer_1.buildOptimizerLoaderPath,
            options: { sourceMap: buildOptions.sourceMap.scripts }
        });
    }
    const test = /(?:\.ngfactory\.js|\.ngstyle\.js|\.tsx?)$/;
    return {
        module: { rules: [{ test, use: loaders }] },
        plugins: [_createAotPlugin(wco, { tsConfigPath }, i18nExtract)]
    };
}
exports.getAotConfig = getAotConfig;
function getTypescriptWorkerPlugin(wco, workerTsConfigPath) {
    const { buildOptions } = wco;
    let pluginOptions = {
        skipCodeGeneration: true,
        tsConfigPath: workerTsConfigPath,
        mainPath: undefined,
        platform: webpack_1.PLATFORM.Browser,
        sourceMap: buildOptions.sourceMap.scripts,
        forkTypeChecker: buildOptions.forkTypeChecker,
        contextElementDependencyConstructor: require('webpack/lib/dependencies/ContextElementDependency'),
        logger: wco.logger,
        // Run no transformers.
        platformTransformers: [],
        // Don't attempt lazy route discovery.
        discoverLazyRoutes: false,
    };
    pluginOptions = _pluginOptionsOverrides(buildOptions, pluginOptions);
    return new webpack_1.AngularCompilerPlugin(pluginOptions);
}
exports.getTypescriptWorkerPlugin = getTypescriptWorkerPlugin;


text:
This is home page for college website.
It will have campus photos as slide show.
It will have brief college history and a link to read more.


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@android:color/transparent"/>
    <corners android:radius="5dp"/>
    <stroke  android:width="2dp" android:color="#FFFFFF"/>
</shape>


text:
class Gn
  module DSL
    def template(constant, dest, &block)
      klass = Class.new
      klass.send(:define_method, :destination) { dest }
      klass.class_eval(&block) if block_given?
      self.const_set constant, klass
    end
  end
end


text:
<!--start-code-->

```js
const styles = {
  radioGroupLabel: {
    padding: '8px 12px',
    display: 'inline-block',
    verticalAlign: 'middle'
  }
};
function App() {
  const [placement, setPlacement] = React.useState('bottom');
  const [shape, setShape] = React.useState('dot');
  return (
    <div>
      <RadioGroup
        name="radioList"
        inline
        appearance="picker"
        defaultValue={placement}
        onChange={setPlacement}
      >
        <span style={styles.radioGroupLabel}>Placement: </span>
        <Radio value="top">Top</Radio>
        <Radio value="bottom">Bottom</Radio>
        <Radio value="left">Left</Radio>
        <Radio value="right">Right</Radio>
      </RadioGroup>
      <Divider vertical />
      <RadioGroup
        name="radioList"
        inline
        appearance="picker"
        defaultValue={shape}
        onChange={setShape}
      >
        <span style={styles.radioGroupLabel}>Shape: </span>
        <Radio value="dot">Dot</Radio>
        <Radio value="bar">Bar</Radio>
      </RadioGroup>
      <Carousel key={`${placement}.${shape}`} placement={placement} shape={shape} className="custom-slider">
        <img
          src="https://via.placeholder.com/600x250/8f8e94/FFFFFF?text=1"
          height="250"
        />
        <img
          src="https://via.placeholder.com/600x250/8f8e94/FFFFFF?text=2"
          height="250"
        />
        <img
          src="https://via.placeholder.com/600x250/8f8e94/FFFFFF?text=3"
          height="250"
        />
        <img
          src="https://via.placeholder.com/600x250/8f8e94/FFFFFF?text=4"
          height="250"
        />
        <img
          src="https://via.placeholder.com/600x250/8f8e94/FFFFFF?text=5"
          height="250"
        />
      </Carousel>
    </div>
  );
}

ReactDOM.render(<App />);
```

<!--end-code-->


text:
package migrations

import "github.com/BurntSushi/migration"

func MakeContainersLinkToWorkerIds(tx migration.LimitedTx) error {
	_, err := tx.Exec(`
		ALTER TABLE workers
		ADD COLUMN id BIGSERIAL PRIMARY KEY;
	`)
	if err != nil {
		return err
	}

	_, err = tx.Exec(`
		ALTER TABLE containers
		ADD COLUMN worker_id INT NULL;
	`)
	if err != nil {
		return err
	}

	_, err = tx.Exec(`
		UPDATE containers c SET worker_id =
		(select id from workers w where w.name = c.worker_name);
	`)
	if err != nil {
		return err
	}

	_, err = tx.Exec(`
		ALTER TABLE containers
		DROP COLUMN worker_name;
	`)
	return err
}


text:
package org.apache.ignite.internal.processors.cache.dr;

import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.CacheObject;
import org.apache.ignite.internal.processors.cache.GridCacheManager;
import org.apache.ignite.internal.processors.cache.KeyCacheObject;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.internal.processors.dr.GridDrType;
import org.jetbrains.annotations.Nullable;

/**
 * Replication manager class which processes all replication events.
 */
public interface GridCacheDrManager extends GridCacheManager {
    /**
     * @return Data center ID.
     */
    public byte dataCenterId();

    /**
     * Performs replication.
     *
     * @param key Key.
     * @param val Value.
     * @param ttl TTL.
     * @param expireTime Expire time.
     * @param ver Version.
     * @param drType Replication type.
     * @param topVer Topology version.
     * @throws IgniteCheckedException If failed.
     */
    public void replicate(KeyCacheObject key,
        @Nullable CacheObject val,
        long ttl,
        long expireTime,
        GridCacheVersion ver,
        GridDrType drType,
        AffinityTopologyVersion topVer)throws IgniteCheckedException;

    /**
     * Process partitions exchange event.
     *
     * @param topVer Topology version.
     * @param left {@code True} if exchange has been caused by node leave.
     * @throws IgniteCheckedException If failed.
     */
    public void onExchange(AffinityTopologyVersion topVer, boolean left) throws IgniteCheckedException;

    /**
     * @return {@code True} is DR is enabled.
     */
    public boolean enabled();

    /**
     * @return {@code True} if receives DR data.
     */
    public boolean receiveEnabled();

    /**
     * In case some partition is evicted, we remove entries of this partition from backup queue.
     *
     * @param part Partition.
     */
    public void partitionEvicted(int part);

    /**
     * Callback for received entries from receiver hub.
     *
     * @param entriesCnt Number of received entries.
     */
    public void onReceiveCacheEntriesReceived(int entriesCnt);

    /**
     * Callback for manual conflict resolution.
     *
     * @param useNew Use new.
     * @param useOld Use old.
     * @param merge Merge.
     */
    public void onReceiveCacheConflictResolved(boolean useNew, boolean useOld, boolean merge);

    /**
     * Resets metrics for current cache.
     */
    public void resetMetrics();
}


text:
'use strict';

exports.__esModule = true;

var utils = require('./utils');
var between = require('./between');
var cheerio = require('cheerio');
var _ = require('lodash');
var inquirer = require('inquirer');
var recursive = require('recursive-readdir-synchronous');
var objectPath = require("object-path");
var path = require("path");

var extractor = {};
extractor._inquirer = inquirer;
extractor.variables = {};
extractor.values = {};
extractor.clear = function () {
    extractor.variables = {};
}
extractor._tag = 'prompt';
extractor.setTag = function (tag) {
    extractor._tag = tag;
};
extractor.prepareVariable = function (objects) {
    try {
        objects = objects.sort(function (a, b) {
            if (a['attrCount'] < b['attrCount']) {
                return 1;
            }
            if (a['attrCount'] > b['attrCount']) {
                return -1;
            }
            return 0;
        });
        Object.keys(objects).map(function (key, objectIndex) {
            var object = objects[key];
            var maxObject = {};
            if (objectIndex > 0) {
                maxObject = object;
            }
            if (object['updater'] === undefined) {
                object['updater'] = "javascript:return __value";
            }
            Object.keys(object).map(function (key, index) {
                if (object[key] !== undefined && typeof object[key] == 'string') {
                    if (object[key].toLowerCase() === 'false') {
                        object[key] = false;
                    } else {
                        if (object[key].toLowerCase() === 'true') {
                            object[key] = true;
                        } else {
                            if (object[key].indexOf('javascript:') === 0) {
                                var code = object[key].substring('javascript:'.length);
                                try {
                                    if (code.indexOf('arguments') != -1 || code.indexOf('__value') != -1 || code.indexOf('__current') != -1 || code.indexOf('__max') != -1) {
                                        var code = `
                                    var __value = arguments.length > 0 ? arguments[0] : null;
                                    var __current = arguments.length > 1 ? arguments[1] : {};
                                    var __max = arguments.length > 2 ? arguments[2] : {};
                                    var _ = arguments.length > 3 ? arguments[3] : null;
                                    var path = arguments.length > 4 ? arguments[4] : null;
                                    var require = arguments.length > 5 ? arguments[5] : null;
                                    var console = arguments.length > 6 ? arguments[6] : null;
                                    ${code};`;
                                        object[key] = new Function(code);
                                    } else {
                                        object[key] = new Function(code)();
                                    }
                                } catch (err) {
                                    console.error(key, code);
                                }
                            }
                        }
                    }
                }
            });
            objects[key] = object;
        });
        return objects;
    } catch (error) {
        console.error(error);
    }
};
extractor.scan = function (filepath, prepareVariable) {
    try {
        var content = utils.load(filepath);
        if (prepareVariable === undefined) {
            prepareVariable = false;
        }
        if (content === null) {
            return null;
        }
        var items = between.get(content, `<${extractor._tag}`, `</${extractor._tag}>`);
        if (items.length === 0)
            return null;
        var objects = {};
        items.map(function (item) {
            var $ = cheerio.load(`<${extractor._tag}${item}</${extractor._tag}>`);
            var name = $(`${extractor._tag}`).attr('name');
            var object = $(`${extractor._tag}`).attr();
            object['attrCount'] = Object.keys(object).length;
            object.outer = `<${extractor._tag}${item}</${extractor._tag}>`;
            object.inner = $(`${extractor._tag}`).html();
            if (object['type'] === undefined) {
                object['type'] = 'text';
            }
            if (object['message'] === undefined) {
                object['message'] = name;
            }
            if (object['default'] === undefined) {
                object['default'] = object.inner;
            }
            if (objects[name] === undefined) {
                objects[name] = [];
            }
            if (extractor.variables[name] === undefined) {
                extractor.variables[name] = [];
            }
            objects[name].push(object);
            extractor.variables[name].push(object);
        });
        if (prepareVariable === true) {
            for (var key in objects) {
                objects[key] = extractor.prepareVariable(objects[key]);
            }
        }
        return {
            file: filepath,
            content: content,
            variables: objects
        };
    } catch (error) {
        console.error(error);
    }
}
extractor.folder = {};
extractor.folder.scan = function (srcFolderpath, prepareVariable) {
    try {
        if (prepareVariable === undefined) {
            prepareVariable = false;
        }
        extractor.clear();
        var files = recursive(srcFolderpath);
        files = files.map(function (file) {
            return extractor.scan(file);
        });
        files = files.filter(function (file) {
            return file !== null;
        });
        var variables = {};
        files.map(function (file, index) {
            Object.keys(file.variables).map(function (key, variableIndex) {
                if (variables[key] === undefined) {
                    variables[key] = [];
                }
                variables[key] = variables[key].concat(file.variables[key]);
            });
            return files;
        });
        if (prepareVariable === true) {
            for (var key in variables) {
                variables[key] = extractor.prepareVariable(variables[key]);
            }
        }
        return {
            files: files,
            variables: variables
        };
    } catch (error) {
        console.error(error);
    }
}
extractor.folder._updateVariablesByAnswers = function (variables, answers, data) {
    try {
        for (var key in variables) {
            if (objectPath.get(data, key) === undefined) {
                for (var i = 0; i < variables[key].length; i++) {
                    var maxVariable = i == 0 ? null : variables[key][0];
                    variables[key][i].inner = variables[key][i].updater(
                        objectPath.get(answers, key),
                        variables[key][i],
                        maxVariable,
                        _,
                        path,
                        require,
                        console
                    );
                }
            } else {
                for (var i = 0; i < variables[key].length; i++) {
                    var maxVariable = i == 0 ? null : variables[key][0];
                    variables[key][i].inner = variables[key][i].updater(
                        objectPath.get(data, key),
                        variables[key][i],
                        maxVariable,
                        _,
                        path,
                        require,
                        console
                    );
                }
            }
            if (objectPath.get(answers, key) !== undefined) {
                objectPath.set(data, key, objectPath.get(answers, key));
            }
        }
        return {
            variables: variables,
            data: data
        };
    } catch (error) {
        console.error(error);
    }
}
extractor.folder.prompt = function (srcFolderpath, data) {
    if (!data) {
        data = {};
    }
    return new Promise(function (resolve, reject) {
        try {
            var result = extractor.folder.scan(path.resolve(srcFolderpath), true);
            var prompts = [];
            for (var key in result.variables) {
                if (objectPath.get(data, key) === undefined) {
                    prompts.push(result.variables[key][0]);
                }
            }
            extractor._inquirer.prompt(prompts).then(function (answers) {
                var updated = extractor.folder._updateVariablesByAnswers(result.variables, answers, data);
                result.variables = updated.variables;
                result.data = updated.data;
                resolve(result);
            });
        } catch (err) {
            reject(err);
        }
    });
};
exports['default'] = extractor;
module.exports = exports['default'];


text:
import { Component, OnInit }      from '@angular/core';
import { ViewChild }              from '@angular/core';

import * as moment                from 'moment';
import { Schedule }               from 'primeng/primeng';
import { SlimLoadingBarService }  from 'ng2-slim-loading-bar';

import { AppState, Action }       from '../app.service';
import { ViewAppointment }        from './appointment.viewmodel';
import { Appointment }            from '../api/model/appointment';
import { ViewAppointmentService } from './appointment.service';
import { PatientService }         from '../api/api/patient.service';

@Component({
  templateUrl: './anon.component.html',
  styleUrls: [ './anon.component.scss' ]
})

export class AnonComponent implements OnInit {

  public appointments: ViewAppointment[];
  public locale: string;
  public hiddenDays: number[] = [ 0 ]; // Hide Sundays by default
  public viewDate: moment.Moment = moment();
  public minTime: moment.Duration = moment.duration('07:00:00');
  public maxTime: moment.Duration = moment.duration('20:00:00');
  public viewMode: string = 'basicWeek';
  public refreshCalendar: boolean = false; // Tiny hack to get fullcalendar to refresh

  @ViewChild(Schedule) private schedule: Schedule;

  constructor(
    private _state: AppState,
    private slimLoadingBarService: SlimLoadingBarService,
    private viewAppointmentService: ViewAppointmentService,
    private patientService: PatientService
  ) {}

  public ngOnInit() {
    // Mouseflow integration
    if ((window as any)._mfq) {
      (window as any)._mfq.push(['newPageView', '/appointment/anon']);
    }

    // Set up page
    this._state.isSubPage.next(false); // TODO block menu, this should be a dead-end
    this._state.title.next(this.getTitleFromViewDate());
    this._state.actions.next(this.getActions('agendaWeek'));
    this._state.primaryAction.next();

    // Retrieve data
    this.getAllAppointments();

    // Set up calendar view
    this.locale = localStorage.getItem('locale').startsWith('de') ? 'de' : 'en';
  }

  private getAllAppointments(): void {
    this.slimLoadingBarService.start();
    this.viewAppointmentService
    .appointmentFindAnonymous()
    .subscribe(
      (x) => this.appointments = x,
      (e) => console.log(e),
      () => {
        console.log('Get all appointments complete');
        this.slimLoadingBarService.complete();
      }
    );
  }

  private handleNextClick() {
    this.viewDate = this.viewDate.add(1, 'week');
    this._state.title.next(this.getTitleFromViewDate());
    this.schedule.gotoDate(this.viewDate);
  }

  private handleTodayClick() {
    this.viewDate = moment();
    this._state.title.next(this.getTitleFromViewDate());
    this.schedule.gotoDate(this.viewDate);
  }

  private handlePrevClick() {
    this.viewDate = this.viewDate.subtract(1, 'week');
    this._state.title.next(this.getTitleFromViewDate());
    this.schedule.gotoDate(this.viewDate);
  }

  private handleViewModeChange(viewMode: string) {
    this.refreshCalendar = true;
    this.viewMode = viewMode;
    setTimeout(() => this.refreshCalendar = false, 0);
    this._state.actions.next(
      this.getActions(viewMode === 'agendaWeek' ? 'basicWeek' : 'agendaWeek')
    );
  }

  private getTitleFromViewDate() {
    const startString = this.viewDate.format('MMMM Do');
    let endString;
    const endOfWeekMoment = this.viewDate.clone().add(6, 'days');
    // Check if this week spreads over two months
    if (this.viewDate.month() === endOfWeekMoment.month()) {
      endString = endOfWeekMoment.format('Do YYYY');
    } else {
      endString = endOfWeekMoment.format('MMMM Do YYYY');
    }
    const weekString = this.viewDate.format(
      localStorage.getItem('locale').startsWith('de') ? '[Woche] w' : '[Week] w');
    return startString + ' - ' + endString + ', ' + weekString;
  }

  private getActions(nextViewMode: string): Action[] {
    return [
      {
        icon: nextViewMode === 'basicWeek' ? 'list' : 'schedule',
        clickHandler: this.handleViewModeChange.bind(this, nextViewMode)
      },
      {
        icon: 'keyboard_arrow_left',
        clickHandler: this.handlePrevClick.bind(this)
      },
      {
        icon: 'today',
        clickHandler: this.handleTodayClick.bind(this)
      },
      {
        icon: 'keyboard_arrow_right',
        clickHandler: this.handleNextClick.bind(this)
      }
    ];
  }
}


text:
[![Build Status](https://travis-ci.org/andrei-yanovich/angular-from-scratch.svg?branch=master)](https://travis-ci.org/andrei-yanovich/angular-from-scratch)

http://teropa.info/build-your-own-angular


text:
<?php

class Glitch_Controller_Request_RestTestCaseMock
    extends Glitch_Controller_Request_RestTestCase
{
    private $origServer;

    public function __construct($uri,
                                Glitch_Application_Bootstrap_Bootstrap $bootstrap = null)
    {
        $this->origServer = $_SERVER;

        if($bootstrap != null) {
            $this->_bootstrap = $bootstrap;
        }

        parent::__construct($uri);
    }

    public function __destruct()
    {
        $_SERVER = $this->origServer;
    }
}