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

using DPek.Raconteur.RenPy.Parser;
using DPek.Raconteur.RenPy.Script;
using DPek.Raconteur.RenPy.State;

namespace DPek.Raconteur.RenPy.Display
{
	/// <summary>
	/// Interface for a RenPyView to interact with. Manages running a Ren'Py
	/// script as well as all of the relevant GameObject references created by
	/// the script.
	/// </summary>
	public sealed class RenPyController : MonoBehaviour
	{
		/// <summary>
		/// The script that the display will run.
		/// </summary>
		[SerializeField]
		private RenPyScriptAsset m_renPyScript;
		public RenPyScriptAsset Script
		{
			get {
				return m_renPyScript;
			}
		}

		/// <summary>
		/// The state of the script's execution.
		/// </summary>
		private RenPyState m_state;

		/// <summary>
		/// Whether or not the display is running the script
		/// </summary>
		private bool running = false;
		public bool Running
		{
			get {
				return running && m_state != null && m_state.Execution.Running;
			}
		}

		/// <summary>
		/// A reference to the helper parent.
		/// </summary>
		GameObject helperParent;

		/// <summary>
		/// A reference to the music channel. Will be deprecated.
		/// </summary>
		public RenPyAudioSource m_music;
		/// <summary>
		/// A reference to the sound channel. Will be deprecated.
		/// </summary>
		public RenPyAudioSource m_sound;
		/// <summary>
		/// A reference to the voice channel. Will be deprecated.
		/// </summary>
		public RenPyAudioSource m_voice;

		/// <summary>
		/// Creates all of the GameObjects that the script will need to run.
		/// </summary>
		public void Awake()
		{
			if (m_renPyScript == null) {
				throw new System.Exception("Script property is not set!");
			}

			m_state = new RenPyState(ref m_renPyScript);

			// Create the children gameobjects
			Transform parentTransform = this.gameObject.transform.parent;
			GameObject parent = null;
			if (parentTransform != null) {
				parent = parentTransform.gameObject;
			}
			var str = name + " Helpers";
			helperParent = CreateChildGameObject(parent, str);

			if (m_music == null)
			{
				GameObject go = CreateChildGameObject(helperParent, "Music");
				m_music = go.AddComponent<RenPyAudioSource>();
				m_music.m_state = m_state;
				m_music.m_channel = "music";
			}

			if (m_sound == null)
			{
				GameObject go = CreateChildGameObject(helperParent, "Sounds");
				m_sound = go.AddComponent<RenPyAudioSource>();
				m_sound.m_state = m_state;
				m_sound.m_channel = "sound";
			}

			if (m_voice == null)
			{
				GameObject go = CreateChildGameObject(helperParent, "Voice");
				m_voice = go.AddComponent<RenPyAudioSource>();
				m_voice.m_state = m_state;
				m_voice.m_channel = "voice";
			}
		}

		void OnDestroy()
		{
			GameObject.Destroy(helperParent);
		}

		/// <summary>
		/// Starts the script from the beginning.
		/// </summary>
		public void StartDialog()
		{
			StopAllCoroutines();
			running = true;

			if (m_state != null) {
				m_state.Reset();
				m_state.Execution.NextStatement(m_state);
			}
		}

		/// <summary>
		/// Stops the script.
		/// </summary>
		public void StopDialog()
		{
			running = false;
		}

		private GameObject CreateChildGameObject(GameObject parent, string name)
		{
			GameObject go = new GameObject();
			go.name = name;
			if (parent != null)
			{
				go.transform.parent = parent.transform;
			}
			return go;
		}

		#region State Wrapper Methods

		/// <summary>
		/// Gets the speaker of the passed RenPySay statement.
		/// </summary>
		/// <param name="statement">
		/// The statement to get the speaker of.
		/// </param>
		/// <returns>
		/// The RenPyCharacterData of the speaker.
		/// </returns>
		public RenPyCharacterData GetSpeaker(RenPySay statement)
		{
			return statement.GetSpeaker(m_state);
		}

		#endregion

		#region Visual Wrapper Methods

		/// <summary>
		/// Returns the background image.
		/// </summary>
		/// <returns>
		/// The background image.
		/// </returns>
		public RenPyImageData GetBackgroundImage()
		{
			return m_state.Visual.BgImage;
		}

		/// <summary>
		/// Returns a collection of images that are on the screen.
		/// </summary>
		/// <returns>
		/// A collection of images that are on the screen.
		/// </returns>
		public Dictionary<string, RenPyImageData>.ValueCollection GetImages()
		{
			return m_state.Visual.GetImages();
		}

		/// <summary>
		/// Whether or not the dialog window should be drawn. Specifically, this
		/// is true when the current statement is a RenPySay statement or if
		/// the dialog window has been requested and the current statement is
		/// not a menu statement.
		/// </summary>
		/// <returns>
		/// True if the dialog window should be rendered.
		/// </returns>
		public bool ShouldDrawWindow()
		{
			var statement = m_state.Execution.CurrentStatement;
			if(statement == null) {
				return false;
			}

			if (statement.Type == RenPyStatementType.SAY) {
				return true;
			}

			if(statement.Type != RenPyStatementType.MENU) {
				return m_state.Visual.WindowRequested;
			}

			return false;
		}

		#endregion

		#region Execution Wrapper Methods

		/// <summary>
		/// Returns the current RenPyStatement.
		/// </summary>
		/// <returns>
		/// The current RenPyStatement
		/// </returns>
		public RenPyStatement GetCurrentStatement()
		{
			return m_state.Execution.CurrentStatement;
		}

		/// <summary>
		/// Executes and returns the next RenPyStatement.
		/// </summary>
		/// <returns>
		/// The next RenPyStatement.
		/// </returns>
		public RenPyStatement NextStatement()
		{
			return m_state.Execution.NextStatement(m_state);
		}

		/// <summary>
		/// Picks a choice in a RenPyMenu.
		/// </summary>
		/// <param name="menu">
		/// The menu to pick a choice in.
		/// </param>
		/// <param name="choice">
		/// The choice to pick.
		/// </param>
		public void PickChoice(RenPyMenu menu, string choice)
		{
			menu.PickChoice(m_state, choice);
		}

		#endregion
	}
}


text:
package pl.joegreen.sergeants.framework.model;

import org.junit.Test;

import java.util.stream.Stream;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class PositionTest {

    @Test
    public void threeByThreeSquareShouldBeVisible() {
        Position centralPosition = new Position(1, 1);
        Stream.of(
                new Position(0, 0),
                new Position(0, 1),
                new Position(0, 2),
                new Position(1, 0),
                new Position(1, 1),
                new Position(1, 2),
                new Position(2, 0),
                new Position(2, 1),
                new Position(2, 2)
        ).forEach(otherPosition -> {
            assertTrue(centralPosition.isVisibleFrom(otherPosition));
            assertTrue(otherPosition.isVisibleFrom(centralPosition));
        });
    }

    @Test
    public void positionsTooFarShouldNotBeVisible() {
        Position centralPosition = new Position(2, 2);
        Stream.of(
                new Position(0, 0),
                new Position(10, 10),
                new Position(2, 10),
                new Position(10, 2)
        ).forEach(otherPosition -> {
            assertFalse(centralPosition.isVisibleFrom(otherPosition));
            assertFalse(otherPosition.isVisibleFrom(centralPosition));
        });
    }

    @Test
    public void fourNonDiagonalNeighboursShouldBeMovable() {
        Position centralPosition = new Position(1, 1);
        Stream.of(
                new Position(0, 1),
                new Position(1, 0),
                new Position(1, 2),
                new Position(2, 1)
        ).forEach(otherPosition -> {
            assertTrue(centralPosition.isMovableFrom(otherPosition));
            assertTrue(otherPosition.isMovableFrom(centralPosition));
        });
    }

    @Test
    public void diagonalNeighboursShouldNotBeMovable() {
        Position centralPosition = new Position(1, 1);
        Stream.of(
                new Position(0, 0),
                new Position(2, 2),
                new Position(2, 0),
                new Position(0, 2)
        ).forEach(otherPosition -> {
            assertFalse(centralPosition.isMovableFrom(otherPosition));
            assertFalse(otherPosition.isMovableFrom(centralPosition));
        });
    }

    @Test
    public void positionsTooFarAwayShouldNotBeMovable() {
        Position centralPosition = new Position(1, 1);
        Stream.of(
                new Position(1, 10),
                new Position(10, 1),
                new Position(20, 20)
        ).forEach(otherPosition -> {
            assertFalse(centralPosition.isMovableFrom(otherPosition));
            assertFalse(otherPosition.isMovableFrom(centralPosition));
        });
    }

    @Test
    public void positionShouldNotBeMovableFromItself(){
        Stream.of(
                new Position(1, 1),
                new Position(0, 0),
                new Position(0, 10)
        ).forEach(position -> {
            assertFalse(position.isMovableFrom(position));
        });
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function(){
    function _$rapyd$_extends(child, parent) {
        child.prototype = new parent;
        child.prototype.constructor = child;
    }
    function len(obj) {
        if (obj instanceof Array || typeof obj === "string") return obj.length;
        else {
            var count = 0;
            for (var i in obj) {
                if (obj.hasOwnProperty(i)) count++;
            }
            return count;
        }
    }
    function _$rapyd$_in(val, arr) {
        if (arr instanceof Array || typeof arr === "string") return arr.indexOf(val) != -1;
        else return val in arr;
    }
    var BRUSH, ERASER, LINE, SELECT, COLORSELECT, LASSO, RECT, ELLIPSE, SAMPLER, BUCKET, TEXT, X, Y, CLICK, RCLICK;
        BRUSH = 0;
    ERASER = 1;
    LINE = 2;
    SELECT = 3;
    COLORSELECT = 4;
    LASSO = 5;
    RECT = 6;
    ELLIPSE = 7;
    SAMPLER = 8;
    BUCKET = 9;
    TEXT = 10;
    X = 0;
    Y = 1;
    CLICK = 1;
    RCLICK = 3;
    function Drawing(){
        var self = this;
        var ctx, $tmpCanvas, tmpCanvas, tmpCtx, canvasWidth, canvasHeight, dragging, points, selection, lastPt, transparent_bg, getXY, normalize, ellipse, drawSpline, sample, matchStartColor, eachPixel, clear, onMouseDown, onMouseMove, onMouseUp, onMouseLeave;
        self._canvas = $("#perm-dwg").get(0);
        self._ctx = ctx = self._canvas.getContext("2d");
        self._undoStack = [];
        self._redoStack = [];
        self._fillColor = null;
        self._strokeColor = null;
        $tmpCanvas = $("#temp-dwg");
        tmpCanvas = $tmpCanvas.get(0);
        tmpCtx = tmpCanvas.getContext("2d");
        canvasWidth = tmpCanvas.width;
        canvasHeight = tmpCanvas.height;
        dragging = false;
        points = [];
        selection = null;
        lastPt = [ 0, 0 ];
        transparent_bg = true;
        getXY = function(obj, event) {
            var absolute;
            absolute = $(obj).offset();
            return [event.pageX - absolute.left, event.pageY - absolute.top];
        };
        normalize = function(x, y, width, height) {
            if (width < 0) {
                width = -width;
                x = x - width;
            }
            if (height < 0) {
                height = -height;
                y = y - height;
            }
            return [x, y, width, height];
        };
        ellipse = function(context, x, y, width, height) {
            var _$rapyd$_Unpack, ctrX, ctrY, circ, scaleX, scaleY;
            _$rapyd$_Unpack = normalize(x, y, width, height);
            x = _$rapyd$_Unpack[0];
            y = _$rapyd$_Unpack[1];
            width = _$rapyd$_Unpack[2];
            height = _$rapyd$_Unpack[3];
            ctrX = (x + x + width) / 2;
            ctrY = (y + y + height) / 2;
            circ = Math.max(width, height);
            scaleX = width / circ;
            scaleY = height / circ;
            context.save();
            context.translate(ctrX, ctrY);
            context.scale(scaleX, scaleY);
            context.arc(0, 0, circ / 2, 0, 2 * Math.PI);
            context.restore();
        };
        drawSpline = function(context, lastPoint) {
            if (lastPoint === undefined) {
                lastPoint = points[len(points) - 1];
            }
            context.beginPath();
            context.moveTo(points[0][X], points[0][Y]);
            if (len(points) == 1) {
                context.lineTo(lastPoint[X], lastPoint[Y]);
            } else if (len(points) == 2) {
                context.quadraticCurveTo(points[1][X], points[1][Y], lastPoint[X], lastPoint[Y]);
            } else {
                context.bezierCurveTo(points[1][X], points[1][Y], points[2][X], points[2][Y], lastPoint[X], lastPoint[Y]);
            }
            context.stroke();
        };
        sample = function(x, y, click) {
            var data, tag, color;
            data = ctx.getImageData(x, y, 1, 1).data;
            if (data[3]) {
                color = "rgb(" + data[0] + "," + data[1] + "," + data[2] + ")";
            } else {
                color = "transparent";
            }
            if (click == CLICK) {
                tag = "#stroke";
            } else {
                tag = "#fill";
            }
            if (color == "transparent") {
                color = null;
                $(tag).css("background", "");
            } else {
                $(tag).css("background", color);
            }
            if (click == CLICK) {
                self._brushColor = color;
            } else {
                self._fillColor = color;
            }
        };
        matchStartColor = function(colorLayer, pixelPos, startPixel) {
            var r, g, b, a;
            r = colorLayer[pixelPos];
            g = colorLayer[pixelPos + 1];
            b = colorLayer[pixelPos + 2];
            a = colorLayer[pixelPos + 3];
            return r == startPixel[0] && g == startPixel[1] && b == startPixel[2] && !!(a) == !!(startPixel[3]);
        };
        eachPixel = function(imageData, callback) {
            var length, offset;
            offset = 0;
            length = imageData.height * imageData.width * 4;
            while (offset < length) {
                callback(offset);
                offset += 4;
            }
        };
        self._clear = clear = function(context) {
            context.clearRect(0, 0, canvasWidth, canvasHeight);
        };
        onMouseDown = function(event) {
            var pixelStack, colorLayer, startPixel, _$rapyd$_Unpack, locX, locY, swatchPixel, newPos, x, y, reachLeft, reachRight, pixelPos, tmp, data, merge;
            event.preventDefault();
            dragging = true;
            _$rapyd$_Unpack = getXY(this, event);
            x = _$rapyd$_Unpack[0];
            y = _$rapyd$_Unpack[1];
            self._undoStack.append(ctx.getImageData(0, 0, canvasWidth, canvasHeight));
            self._redoStack = [];
            ctx.save();
            tmpCtx.save();
            if (_$rapyd$_in(self._mode, [ BRUSH, ERASER ])) {
                ctx.lineWidth = self._lineWidth;
                if (self._mode == BRUSH) {
                    ctx.strokeStyle = self._brushColor;
                } else {
                    ctx.globalCompositeOperation = "destination-out";
                }
                ctx.beginPath();
                ctx.moveTo(x, y);
            } else if (_$rapyd$_in(self._mode, [ RECT, ELLIPSE ])) {
                tmpCtx.lineWidth = self._lineWidth;
                tmpCtx.strokeStyle = self._brushColor;
                tmpCtx.fillStyle = self._fillColor;
                points.append([ x, y ]);
            } else if (self._mode == LINE) {
                tmpCtx.lineWidth = self._lineWidth;
                tmpCtx.strokeStyle = self._brushColor;
                points.append([ x, y ]);
            } else if (self._mode == SAMPLER) {
                sample(x, y, event.which);
            } else if (self._mode == BUCKET && self._fillColor) {
                pixelStack = [ [x, y] ];
                colorLayer = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
                data = colorLayer.data;
                startPixel = ctx.getImageData(x, y, 1, 1).data;
                tmpCtx.save();
                tmpCtx.fillStyle = self._fillColor;
                _$rapyd$_Unpack = [50, 50];
                locX = _$rapyd$_Unpack[0];
                locY = _$rapyd$_Unpack[1];
                tmpCtx.fillRect(locX, locY, 1, 1);
                swatchPixel = tmpCtx.getImageData(locX, locY, 1, 1).data;
                tmpCtx.clearRect(locX, locY, 1, 1);
                tmpCtx.restore();
                if (!matchStartColor(swatchPixel, 0, startPixel)) {
                    while (len(pixelStack)) {
                        newPos = pixelStack.pop();
                        x = newPos[X];
                        y = newPos[Y];
                        pixelPos = (y * canvasWidth + x) * 4;
                        while (y >= 0 && matchStartColor(data, pixelPos, startPixel)) {
                            y -= 1;
                            pixelPos -= canvasWidth * 4;
                        }
                        pixelPos += canvasWidth * 4;
                        y += 1;
                        reachLeft = false;
                        reachRight = false;
                        while (y < canvasHeight - 1 && matchStartColor(data, pixelPos, startPixel)) {
                            y += 1;
                            data[pixelPos] = swatchPixel[0];
                            data[pixelPos + 1] = swatchPixel[1];
                            data[pixelPos + 2] = swatchPixel[2];
                            data[pixelPos + 3] = swatchPixel[3];
                            if (x > 0) {
                                if (matchStartColor(data, pixelPos - 4, startPixel)) {
                                    if (!reachLeft) {
                                        pixelStack.append([x - 1, y]);
                                        reachLeft = true;
                                    }
                                } else if (reachLeft) {
                                    reachLeft = false;
                                }
                            }
                            if (x < canvasWidth - 1) {
                                if (matchStartColor(data, pixelPos + 4, startPixel)) {
                                    if (!reachRight) {
                                        pixelStack.append([x + 1, y]);
                                    }
                                } else if (reachRight) {
                                    reachRight = false;
                                }
                            }
                            pixelPos += canvasWidth * 4;
                        }
                    }
                    ctx.putImageData(colorLayer, 0, 0);
                }
            } else if (self._mode == SELECT) {
                lastPt = [ x, y ];
                if (selection === null) {
                    tmpCtx.lineWidth = 1;
                    tmpCtx.strokeStyle = "rgb(0,255,0)";
                    points.append([ x, y ]);
                } else if (!(points[0][X] < x && x < points[1][X] && points[0][Y] < y && y < points[1][Y])) {
                    if (transparent_bg) {
                        tmp = ctx.getImageData(points[0][X], points[0][Y], points[1][X] - points[0][X], points[1][Y] - points[0][Y]).data;
                        data = selection.data;
                        merge = function(offset) {
                            if (!data[offset + 3]) {
                                data[offset] = tmp[offset];
                                data[offset + 1] = tmp[offset + 1];
                                data[offset + 2] = tmp[offset + 2];
                                data[offset + 3] = tmp[offset + 3];
                            }
                        };
                        eachPixel(selection, merge);
                    }
                    ctx.putImageData(selection, points[0][X], points[0][Y]);
                    clear(tmpCtx);
                    selection = null;
                    points = [ [ x, y ] ];
                }
            }
        };
        onMouseMove = function(event) {
            var _$rapyd$_Unpack, point, x, y;
            if (self._mode == LINE && len(points)) {
                _$rapyd$_Unpack = getXY(this, event);
                x = _$rapyd$_Unpack[0];
                y = _$rapyd$_Unpack[1];
                clear(tmpCtx);
                drawSpline(tmpCtx, [x, y]);
            } else if (dragging) {
                _$rapyd$_Unpack = getXY(this, event);
                x = _$rapyd$_Unpack[0];
                y = _$rapyd$_Unpack[1];
                if (_$rapyd$_in(self._mode, [ BRUSH, ERASER ])) {
                    ctx.lineTo(x, y);
                    ctx.stroke();
                } else if (_$rapyd$_in(self._mode, [ RECT, ELLIPSE ])) {
                    clear(tmpCtx);
                    tmpCtx.beginPath();
                    if (self._mode == RECT) {
                        tmpCtx.rect(points[0][X], points[0][Y], x - points[0][X], y - points[0][Y]);
                    } else {
                        ellipse(tmpCtx, points[0][X], points[0][Y], x - points[0][X], y - points[0][Y]);
                    }
                    if (self._fillColor !== null) {
                        tmpCtx.fill();
                    }
                    if (self._brushColor !== null) {
                        tmpCtx.stroke();
                    }
                } else if (self._mode == SAMPLER) {
                    sample(x, y, event.which);
                } else if (self._mode == SELECT) {
                    clear(tmpCtx);
                    if (selection !== null) {
                        var _$rapyd$_Iter0 = points;
                        for (var _$rapyd$_Index0 = 0; _$rapyd$_Index0 < _$rapyd$_Iter0.length; _$rapyd$_Index0++) {
                            point = _$rapyd$_Iter0[_$rapyd$_Index0];
                            point[0] += x - lastPt[X];
                            point[1] += y - lastPt[Y];
                        }
                        lastPt = [ x, y ];
                        x = points[1][X];
                        y = points[1][Y];
                        tmpCtx.putImageData(selection, points[0][X], points[0][Y]);
                    }
                    tmpCtx.strokeRect(points[0][X], points[0][Y], x - points[0][X], y - points[0][Y]);
                }
            }
        };
        onMouseUp = function(event) {
            var _$rapyd$_Unpack, sx, sy, width, height, x, y;
            if (_$rapyd$_in(self._mode, [ RECT, ELLIPSE ])) {
                _$rapyd$_Unpack = getXY(this, event);
                x = _$rapyd$_Unpack[0];
                y = _$rapyd$_Unpack[1];
                ctx.beginPath();
                ctx.lineWidth = self._lineWidth;
                ctx.strokeStyle = self._brushColor;
                ctx.fillStyle = self._fillColor;
                if (self._mode == RECT) {
                    ctx.rect(points[0][X], points[0][Y], x - points[0][X], y - points[0][Y]);
                } else {
                    ellipse(ctx, points[0][X], points[0][Y], x - points[0][X], y - points[0][Y]);
                }
                if (self._fillColor !== null) {
                    ctx.fill();
                }
                if (self._brushColor !== null) {
                    ctx.stroke();
                }
            } else if (self._mode == LINE && event.which == CLICK && len(points) > 1) {
                ctx.lineWidth = self._lineWidth;
                ctx.strokeStyle = self._brushColor;
                drawSpline(ctx);
            } else if (self._mode == SELECT) {
                _$rapyd$_Unpack = getXY(this, event);
                x = _$rapyd$_Unpack[0];
                y = _$rapyd$_Unpack[1];
                if (selection === null && x != points[0][X] && y != points[0][Y]) {
                    sx = points[0][X];
                    sy = points[0][Y];
                    width = x - sx;
                    height = y - sy;
                    _$rapyd$_Unpack = normalize(sx, sy, width, height);
                    sx = _$rapyd$_Unpack[0];
                    sy = _$rapyd$_Unpack[1];
                    width = _$rapyd$_Unpack[2];
                    height = _$rapyd$_Unpack[3];
                    points = [ [ sx, sy ] ];
                    x = sx + width;
                    y = sy + height;
                    selection = ctx.getImageData(sx, sy, width, height);
                    ctx.clearRect(sx, sy, width, height);
                    tmpCtx.putImageData(selection, points[0][X], points[0][Y]);
                    tmpCtx.strokeRect(points[0][X], points[0][Y], x - points[0][X], y - points[0][Y]);
                    points.append([ x, y ]);
                }
            }
            dragging = false;
            ctx.restore();
            if ((!selection || x == points[0][X] && y == points[0][Y]) && (self._mode != LINE || event.which == CLICK && len(points) > 1)) {
                points = [];
                clear(tmpCtx);
                tmpCtx.restore();
            }
        };
        self._filter = function(callback) {
            var pixels, data, invoke;
            if (selection) {
                pixels = selection;
            } else {
                pixels = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
            }
            data = pixels.data;
            invoke = function(offset) {
                callback(data, offset);
            };
            eachPixel(pixels, invoke);
            if (selection) {
                clear(tmpCtx);
                tmpCtx.putImageData(pixels, points[0][X], points[0][Y]);
                tmpCtx.strokeRect(points[0][X], points[0][Y], points[1][X] - points[0][X], points[1][Y] - points[0][Y]);
            } else {
                ctx.putImageData(pixels, 0, 0);
            }
        };
        $tmpCanvas.mousedown(onMouseDown);
        $tmpCanvas.mousemove(onMouseMove);
        $tmpCanvas.mouseup(onMouseUp);
        onMouseLeave = function(event) {
            if (dragging) {
                onMouseUp(event);
            }
        };
        $tmpCanvas.mouseleave(onMouseLeave);
        self._ctx.lineJoin = tmpCtx.lineJoin = self._ctx.lineCap = tmpCtx.lineCap = "round";
    };

    Drawing.prototype.undo = function undo(){
        var self = this;
        var state;
        state = self._undoStack.pop();
        if (state) {
            self._redoStack.append(state);
            self._ctx.putImageData(state, 0, 0);
        }
    };

    Drawing.prototype.redo = function redo(){
        var self = this;
        var state;
        state = self._redoStack.pop();
        if (state) {
            self._undoStack.append(state);
            self._ctx.putImageData(state, 0, 0);
        }
    };

    Drawing.prototype.setMode = function setMode(mode){
        var self = this;
        self._mode = mode;
    };

    Drawing.prototype.setStroke = function setStroke(style){
        var self = this;
        self._brushColor = style;
    };

    Drawing.prototype.setFill = function setFill(style){
        var self = this;
        self._fillColor = style;
    };

    Drawing.prototype.setWidth = function setWidth(value){
        var self = this;
        self._lineWidth = value;
    };

    Drawing.prototype.clear = function clear(){
        var self = this;
        self._clear(self._ctx);
    };

    Drawing.prototype.exportDwg = function exportDwg(){
        var self = this;
        return self._canvas.toDataURL();
    };

    Drawing.prototype.invert = function invert(){
        var self = this;
        var invert;
        invert = function(data, offset) {
            data[offset] = 255 - data[offset];
            data[offset + 1] = 255 - data[offset + 1];
            data[offset + 2] = 255 - data[offset + 2];
        };
        self._filter(invert);
    };

    Drawing.prototype.redFilter = function redFilter(){
        var self = this;
        var remove;
        remove = function(data, offset) {
            data[offset] = 0;
        };
        self._filter(remove);
    };

    Drawing.prototype.greenFilter = function greenFilter(){
        var self = this;
        var remove;
        remove = function(data, offset) {
            data[offset + 1] = 0;
        };
        self._filter(remove);
    };

    Drawing.prototype.blueFilter = function blueFilter(){
        var self = this;
        var remove;
        remove = function(data, offset) {
            data[offset + 2] = 0;
        };
        self._filter(remove);
    };

    Drawing.prototype.darken = function darken(){
        var self = this;
        var darken;
        darken = function(data, offset) {
            data[offset] /= 2;
            data[offset + 1] /= 2;
            data[offset + 2] /= 2;
        };
        self._filter(darken);
    };

    Drawing.prototype.lighten = function lighten(){
        var self = this;
        var lighten;
        lighten = function(data, offset) {
            data[offset] = Math.min(data[offset] * 2, 255);
            data[offset + 1] = Math.min(data[offset + 1] * 2, 255);
            data[offset + 2] = Math.min(data[offset + 2] * 2, 255);
        };
        self._filter(lighten);
    };

    function ColorSwatch(){
        var self = this;
        var fg, bg;
        fg = $("<div></div>").width(36).height(36).css({
            "position": "absolute",
            "border": "1px solid black"
        });
        fg.change = function(color) {
            $(self).css("background", color);
        };
        bg = fg.clone();
        $("#color-swatch");
    };

    function main() {
        var dwg, onChange, $brushWidget, triggerChange, $tools, makeMode, $stroke, $fill, setStroke, setFill, $colorPickers, $colorPicker, makeHandler, makeReset, _$rapyd$_Unpack, $swatch, idtag, resetid, callback, popupUnder, $menus, makeMenu, hideMenus, $about;
        dwg = new Drawing();
        onChange = function() {
            dwg.setWidth($(this).val());
        };
        $brushWidget = $("#brush-size").spinner({
            "min": 1,
            "max": 40
        });
        $brushWidget.change(onChange);
        triggerChange = function() {
            $(this).siblings("input").change();
        };
        $(".ui-spinner-button").click(triggerChange);
        $brushWidget.val(1);
        $tools = $(".toolbox-item");
        makeMode = function(mode) {
            var setMode;
            setMode = function(event) {
                dwg.setMode(mode);
                $tools.removeClass("selected");
                $(event.target).parent().addClass("selected");
            };
            return setMode;
        };
        $("#toolbox-brush").click(makeMode(BRUSH));
        $("#toolbox-eraser").click(makeMode(ERASER));
        $("#toolbox-line").click(makeMode(LINE));
        $("#toolbox-select").click(makeMode(SELECT));
        $("#toolbox-colorselect").click(makeMode(COLORSELECT));
        $("#toolbox-lasso").click(makeMode(LASSO));
        $("#toolbox-rectangle").click(makeMode(RECT));
        $("#toolbox-ellipse").click(makeMode(ELLIPSE));
        $("#toolbox-sampler").click(makeMode(SAMPLER));
        $("#toolbox-bucket").click(makeMode(BUCKET));
        $("#toolbox-text").click(makeMode(TEXT));
        $("#toolbox-brush").click();
        $stroke = $("#stroke");
        $fill = $("#fill");
        setStroke = function(style) {
            dwg.setStroke(style);
            $stroke.css("background", style);
        };
        setFill = function(style) {
            dwg.setFill(style);
            $fill.css("background", style);
        };
        setStroke("black");
        $colorPickers = $(".colorpicker");
        var _$rapyd$_Iter1 = [ [$stroke, "#fg-color", "#no-stroke", setStroke], [$fill,
        "#bg-color", "#no-fill", setFill] ];
        for (var _$rapyd$_Index1 = 0; _$rapyd$_Index1 < _$rapyd$_Iter1.length; _$rapyd$_Index1++) {
            _$rapyd$_Unpack = _$rapyd$_Iter1[_$rapyd$_Index1];
            $swatch = _$rapyd$_Unpack[0];
            idtag = _$rapyd$_Unpack[1];
            resetid = _$rapyd$_Unpack[2];
            callback = _$rapyd$_Unpack[3];
            $colorPicker = $(idtag);
            $colorPicker.farbtastic(callback);
            makeHandler = function($target, $popup) {
                var showColorpicker;
                showColorpicker = function(event) {
                    $colorPickers.hide();
                    popupUnder(event, $target, $popup);
                };
                return showColorpicker;
            };
            $swatch.click(makeHandler($swatch, $colorPicker));
            makeReset = function($target, setFunction) {
                var reset;
                reset = function() {
                    event.stopPropagation();
                    setFunction("transparent");
                    $target.css("background", "");
                };
                return reset;
            };
            $(resetid).click(makeReset($swatch, callback));
        }
        popupUnder = function(event, $element, $popup) {
            var absolute;
            event.stopPropagation();
            absolute = $element.offset();
            $popup.css({
                "left": absolute.left,
                "top": absolute.top + $element.outerHeight()
            }).show();
        };
        $menus = $(".menubar-menu");
        makeMenu = function() {
            var $this, idtag, showMenu;
            $this = $(this);
            idtag = $this.attr("id").split("-")[2];
            showMenu = function(event) {
                $menus.hide();
                popupUnder(event, $this, $("#menubar-menu-" + idtag));
            };
            $this.click(showMenu);
        };
        hideMenus = function() {
            $menus.hide();
            $colorPickers.hide();
        };
        $(document).click(hideMenus);
        $menus.menu().removeClass("ui-widget");
        $(".menubar-item").each(makeMenu);
        $("#menubar-menu-item-new").click(function() {
            dwg.clear();
        });
        $("#menubar-menu-item-export-to-image").click(function() {
            var url;
            url = dwg.exportDwg();
            window.open(url, "_blank");
        });
        $("#menubar-menu-item-undo").click(function() {
            dwg.undo();
        });
        $("#menubar-menu-item-redo").click(function() {
            dwg.redo();
        });
        $("#menubar-menu-item-invert-colors").click(function() {
            dwg.invert();
        });
        $("#menubar-menu-item-red-filter").click(function() {
            dwg.redFilter();
        });
        $("#menubar-menu-item-green-filter").click(function() {
            dwg.greenFilter();
        });
        $("#menubar-menu-item-blue-filter").click(function() {
            dwg.blueFilter();
        });
        $("#menubar-menu-item-darken").click(function() {
            dwg.darken();
        });
        $("#menubar-menu-item-lighten").click(function() {
            dwg.lighten();
        });
        $about = $("#about").dialog({
            "modal": true
        });
        $("#menubar-menu-item-about").click(function() {
            $about.dialog("open");
        });
        window.oncontextmenu = function() {
            return false;
        };
    }
    $(document).ready(main);
})();


text:
<component name="InspectionProjectProfileManager">
  <profile version="1.0" is_locked="false">
    <option name="myName" value="Project Default" />
    <option name="myLocal" value="false" />
    <inspection_tool class="SerializableHasSerialVersionUIDField" enabled="true" level="WARNING" enabled_by_default="true">
      <option name="ignoreAnonymousInnerClasses" value="false" />
      <option name="superClassString" value="" />
    </inspection_tool>
    <inspection_tool class="W3CssValidation" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="myCssVersion" value="css3" />
      <option name="myIgnoreVendorSpecificProperties" value="false" />
    </inspection_tool>
  </profile>
</component>


text:
namespace YKToolkit.Sample.Views
{
    using System.Windows.Controls;

    /// <summary>
    /// FourierView.xaml の相互作用ロジック
    /// </summary>
    public partial class FourierView : UserControl
    {
        public FourierView()
        {
            InitializeComponent();
        }
    }
}


text:
package serial

import (
	"encoding/json"
)

func (this *StringLiteral) UnmarshalJSON(data []byte) error {
	var str string
	if err := json.Unmarshal(data, &str); err != nil {
		return err
	}
	*this = StringLiteral(str)
	return nil
}


text:
package de.lessvoid.nifty.elements.events;

import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.input.NiftyMouseInputEvent;

import javax.annotation.Nonnull;

public class NiftyMouseSecondaryReleaseEvent extends NiftyMouseBaseEvent {
  public NiftyMouseSecondaryReleaseEvent(final Element element, @Nonnull final NiftyMouseInputEvent mouseEvent) {
    super(element, mouseEvent);
  }
}


text:
<?php

namespace LEM_projet2\AdminBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use LEM_projet2\AdminBundle\Entity\OrderItem;
use LEM_projet2\AdminBundle\Form\OrderItemType;

/**
 * OrderItem controller.
 *
 * @Route("/admin/orderitem")
 */
class OrderItemController extends Controller
{

    /**
     * Lists all OrderItem entities.
     *
     * @Route("/", name="admin_orderitem")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AdminBundle:OrderItem')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new OrderItem entity.
     *
     * @Route("/", name="admin_orderitem_create")
     * @Method("POST")
     * @Template("AdminBundle:OrderItem:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new OrderItem();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_orderitem_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
    * Creates a form to create a OrderItem entity.
    *
    * @param OrderItem $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(OrderItem $entity)
    {
        $form = $this->createForm(new OrderItemType(), $entity, array(
            'action' => $this->generateUrl('admin_orderitem_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new OrderItem entity.
     *
     * @Route("/new", name="admin_orderitem_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new OrderItem();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a OrderItem entity.
     *
     * @Route("/{id}", name="admin_orderitem_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AdminBundle:OrderItem')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find OrderItem entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing OrderItem entity.
     *
     * @Route("/{id}/edit", name="admin_orderitem_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AdminBundle:OrderItem')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find OrderItem entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a OrderItem entity.
    *
    * @param OrderItem $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(OrderItem $entity)
    {
        $form = $this->createForm(new OrderItemType(), $entity, array(
            'action' => $this->generateUrl('admin_orderitem_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing OrderItem entity.
     *
     * @Route("/{id}", name="admin_orderitem_update")
     * @Method("PUT")
     * @Template("AdminBundle:OrderItem:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AdminBundle:OrderItem')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find OrderItem entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('admin_orderitem_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a OrderItem entity.
     *
     * @Route("/{id}", name="admin_orderitem_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AdminBundle:OrderItem')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find OrderItem entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('admin_orderitem'));
    }

    /**
     * Creates a form to delete a OrderItem entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('admin_orderitem_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
<?php

	class Positions_types_model extends CI_Model {

		public function __construct() {

			$this->load->database();

		}

		public function get_positions_types( $id = FALSE ) {

			if( $id === FALSE ) {
				$query = $this->db->get( "positions_types" );
				return $query->result_array();
			}

			$query = $this->db->get_where( "positions_types", array( "id" => $id ) );
			return $query->row_array();

		}

		public function set_positions_type() {

			$data = array(
					"name" => $this->input->post( "name" ),
					"description" => $this->input->post( "description" )
				);

			return $this->db->insert( "positions_types", $data );

		}

		public function update_positions_type( $id ) {

			$data = array(
					"name" => $this->input->post( "name" ),
					"description" => $this->input->post( "description" )
				);

			$this->db->where( "id", $id );
			return $this->db->update( "positions_types", $data );

		}

		public function delete_positions_type( $id ) {

			return $this->db->delete( "positions_types", array( "id" => $id ) );

		}
	}

?>


text:
package com.faviotorres.pariaguas.home;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.faviotorres.pariaguas.R;
import com.faviotorres.pariaguas.model.Forecast;
import com.faviotorres.pariaguas.utils.DateUtils;
import com.faviotorres.pariaguas.utils.TemperatureUtils;

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

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RecyclerForecast extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    @Inject DateUtils dateUtils;
    @Inject TemperatureUtils temperatureUtils;

    private int units;
    private Context context;
    private List<Forecast> days;

    RecyclerForecast(ActivityHome activityHome, Context context, int units) {
        this.units = units;
        this.context = context;
        this.days = new ArrayList<>();
        activityHome.getPariaguasApplication().getAppComponent().inject(this);
    }

    @Override
    public int getItemCount() {
        return this.days.size();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new HolderForecast(LayoutInflater.from(context)
                .inflate(R.layout.row_forecast, parent, false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        HolderForecast h = (HolderForecast) holder;
        Forecast forecast = this.days.get(position);
        h.dayTV.setText(dateUtils.DAYS[forecast.getDay()-1]);
        String min = temperatureUtils.getTemperature(units, forecast.getKelvinMin());
        String max = temperatureUtils.getTemperature(units, forecast.getKelvinMax());
        h.maxTV.setText(max);
        h.minTV.setText(min);
    }

    void setupForecast(List<Forecast> forecasts) {
        this.days = forecasts;
        notifyDataSetChanged();
    }

    void updateTempScale(int units) {
        this.units = units;
        notifyDataSetChanged();
    }

    class HolderForecast extends RecyclerView.ViewHolder {

        @BindView(R.id.row_forecast_day_tv) TextView dayTV;
        @BindView(R.id.row_forecast_max_tv) TextView maxTV;
        @BindView(R.id.row_forecast_min_tv) TextView minTV;

        HolderForecast(View v) {
            super(v);
            ButterKnife.bind(this, v);
        }
    }
}


text:
<?php include('header.php');?>

 SHOPPING BAG
<?php echo $this->session->flashdata('redirect');?>

<?php if ($this->go_cart->total_items()==0):?>

There are no products in your cart!

<?php else: ?>
	<?php echo form_open('cart/update_cart', array('id'=>'update_cart_form'));?>

Continue Shopping

    <?php
	$subtotal = 0;

	foreach ($this->go_cart->contents() as $cartkey=>$product):?>
    	<?php //print_r($this->go_cart->contents());
		?>

                    <img src="<?php echo base_url('uploads/product/thumb/'.$product['images']);?>" alt="Blue Striped Braces" height="63" />

                        <a href="<?php echo base_url($product['slug']);?>" id="idNomeVariante_3220"><?php echo $product['name']; ?>

                    Item #1586013-01
                    <?php echo format_currency($product['base_price']);   ?>

                    Size

						<?php
						if(isset($product['options'])) {
                            foreach ($product['options'] as $name=>$value)
                            {
                                if(is_array($value))
                                {
                                    echo 'One size';
                                }
                                else
                                {
                                    echo $value;
                                }
                            }
                        }
                        ?>

                    Quantity

                    <input name="cartkey[<?php echo $cartkey;?>]" type="text" id="qty_3220" size="2" maxlength="2" value="<?php echo $product['quantity'] ?>" class="SB-outOfStockProduct">

Subtotal

<?php echo format_currency($product['price']*$product['quantity']); ?>

<a href="<?php echo site_url('cart/remove_item/'.$cartkey);?>">Delete product

Update product

    <?php endforeach; ?>

	<?php echo "Discount Code: ";?><input type="text" name="coupon_code"> <input type="submit" class="button1" style="font-size: 11px;height: 20px; padding: 0 15px 0 15px !important; font-weight: bold; " value="<?php echo "ESTIMATE";?>"/>

TOTAL: 40.00 EUR

    <input id="redirect_path" type="hidden" name="redirect" value=""/>
    <?php if ($this->Customer_model->is_logged_in(false,false) || !$this->config->item('require_login')): ?>
        <input style="padding:10px 15px; font-size:16px;" type="submit" onclick="$('#redirect_path').val('checkout/order_summary');" value="Checkout »"/>
    <?php else:?>
    	<input style="padding:10px 15px; font-size:16px;" type="submit" onclick="$('#redirect_path').val('checkout/order_summary');" value="Checkout »"/>
    <?php endif;?>

</form>
<?php endif; ?>

<?php include('footer.php'); ?>


text:
/*************************************************************************/
/*  test_macros.cpp                                                      */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#define DOCTEST_CONFIG_IMPLEMENT
#include "test_macros.h"

Map<String, TestFunc> *test_commands = nullptr;

int register_test_command(String p_command, TestFunc p_function) {
	if (!test_commands) {
		test_commands = new Map<String, TestFunc>;
	}
	test_commands->insert(p_command, p_function);
	return 0;
}


text:
using System;
using Nohros.Configuration;

namespace Nohros.RestQL
{
  public partial class Settings : Configuration.Configuration, IConfiguration,
                                  ISettings
  {
    readonly string query_server_address_;
    readonly int response_timeout_;

    #region .ctor
    public Settings(Builder builder) : base(builder) {
      query_server_address_ = builder.QueryServerAddress;
      response_timeout_ = builder.ResponseTimeout;
    }
    #endregion

    public string QueryServerAddress {
      get { return query_server_address_; }
    }

    public int ResponseTimeout {
      get { return response_timeout_; }
    }
  }
}


text:
package org.apache.hadoop.hbase.client;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.CompareOperator;
import org.apache.hadoop.hbase.DoNotRetryIOException;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.ipc.HBaseRpcController;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.HRegionServer;
import org.apache.hadoop.hbase.testclassification.ClientTests;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.shaded.protobuf.RequestConverter;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos;
import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos;

/**
 * The purpose of this test is to ensure whether rs deals with the malformed cells correctly.
 */
@Category({ MediumTests.class, ClientTests.class })
public class TestMalformedCellFromClient {
  private static final Logger LOG = LoggerFactory.getLogger(TestMalformedCellFromClient.class);
  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestMalformedCellFromClient.class);

  private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
  private static final byte[] FAMILY = Bytes.toBytes("testFamily");
  private static final int CELL_SIZE = 100;
  private static final TableName TABLE_NAME = TableName.valueOf("TestMalformedCellFromClient");

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    // disable the retry
    TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 0);
    TEST_UTIL.startMiniCluster(1);
  }

  @Before
  public void before() throws Exception {
    TableDescriptor desc = TableDescriptorBuilder.newBuilder(TABLE_NAME)
      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(FAMILY))
      .setValue(HRegion.HBASE_MAX_CELL_SIZE_KEY, String.valueOf(CELL_SIZE)).build();
    TEST_UTIL.getConnection().getAdmin().createTable(desc);
  }

  @After
  public void tearDown() throws Exception {
    for (TableDescriptor htd : TEST_UTIL.getAdmin().listTableDescriptors()) {
      TEST_UTIL.deleteTable(htd.getTableName());
    }
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    TEST_UTIL.shutdownMiniCluster();
  }

  /**
   * The purpose of this ut is to check the consistency between the exception and results. If the
   * RetriesExhaustedWithDetailsException contains the whole batch, each result should be of IOE.
   * Otherwise, the row operation which is not in the exception should have a true result.
   */
  @Test
  public void testRegionException() throws InterruptedException, IOException {
    List<Row> batches = new ArrayList<>();
    batches.add(new Put(Bytes.toBytes("good")).addColumn(FAMILY, null, new byte[10]));
    // the rm is used to prompt the region exception.
    // see RSRpcServices#multi
    RowMutations rm = new RowMutations(Bytes.toBytes("fail"));
    rm.add(new Put(rm.getRow()).addColumn(FAMILY, null, new byte[CELL_SIZE]));
    batches.add(rm);
    Object[] results = new Object[batches.size()];

    try (Table table = TEST_UTIL.getConnection().getTable(TABLE_NAME)) {
      Throwable exceptionByCaught = null;
      try {
        table.batch(batches, results);
        fail("Where is the exception? We put the malformed cells!!!");
      } catch (RetriesExhaustedWithDetailsException e) {
        for (Throwable throwable : e.getCauses()) {
          assertNotNull(throwable);
        }
        assertEquals(1, e.getNumExceptions());
        exceptionByCaught = e.getCause(0);
      }
      for (Object obj : results) {
        assertNotNull(obj);
      }
      assertEquals(Result.class, results[0].getClass());
      assertEquals(exceptionByCaught.getClass(), results[1].getClass());
      Result result = table.get(new Get(Bytes.toBytes("good")));
      assertEquals(1, result.size());
      Cell cell = result.getColumnLatestCell(FAMILY, null);
      assertTrue(Bytes.equals(CellUtil.cloneValue(cell), new byte[10]));
    }
  }

  /**
   * This test verifies region exception doesn't corrupt the results of batch. The prescription is
   * shown below. 1) honor the action result rather than region exception. If the action have both
   * of true result and region exception, the action is fine as the exception is caused by other
   * actions which are in the same region. 2) honor the action exception rather than region
   * exception. If the action have both of action exception and region exception, we deal with the
   * action exception only. If we also handle the region exception for the same action, it will
   * introduce the negative count of actions in progress. The AsyncRequestFuture#waitUntilDone will
   * block forever. If the RetriesExhaustedWithDetailsException contains the whole batch, each
   * result should be of IOE. Otherwise, the row operation which is not in the exception should have
   * a true result. The no-cluster test is in TestAsyncProcessWithRegionException.
   */
  @Test
  public void testRegionExceptionByAsync() throws Exception {
    List<Row> batches = new ArrayList<>();
    batches.add(new Put(Bytes.toBytes("good")).addColumn(FAMILY, null, new byte[10]));
    // the rm is used to prompt the region exception.
    // see RSRpcServices#multi
    RowMutations rm = new RowMutations(Bytes.toBytes("fail"));
    rm.add(new Put(rm.getRow()).addColumn(FAMILY, null, new byte[CELL_SIZE]));
    batches.add(rm);
    try (AsyncConnection asyncConnection =
      ConnectionFactory.createAsyncConnection(TEST_UTIL.getConfiguration()).get()) {
      AsyncTable<AdvancedScanResultConsumer> table = asyncConnection.getTable(TABLE_NAME);
      List<CompletableFuture<AdvancedScanResultConsumer>> results = table.batch(batches);
      assertEquals(2, results.size());
      try {
        results.get(1).get();
        fail("Where is the exception? We put the malformed cells!!!");
      } catch (ExecutionException e) {
        // pass
      }
      Result result = table.get(new Get(Bytes.toBytes("good"))).get();
      assertEquals(1, result.size());
      Cell cell = result.getColumnLatestCell(FAMILY, null);
      assertTrue(Bytes.equals(CellUtil.cloneValue(cell), new byte[10]));
    }
  }

  /**
   * The invalid cells is in rm. The rm should fail but the subsequent mutations should succeed.
   * Currently, we have no client api to submit the request consisting of condition-rm and mutation.
   * Hence, this test build the request manually.
   */
  @Test
  public void testAtomicOperations() throws Exception {
    RowMutations rm = new RowMutations(Bytes.toBytes("fail"));
    rm.add(new Put(rm.getRow()).addColumn(FAMILY, null, new byte[CELL_SIZE]));
    rm.add(new Put(rm.getRow()).addColumn(FAMILY, null, new byte[10]));
    Put put = new Put(Bytes.toBytes("good")).addColumn(FAMILY, null, new byte[10]);

    // build the request
    HRegion r = TEST_UTIL.getMiniHBaseCluster().getRegions(TABLE_NAME).get(0);
    ClientProtos.MultiRequest request =
      ClientProtos.MultiRequest.newBuilder(createRequest(rm, r.getRegionInfo().getRegionName()))
        .addRegionAction(ClientProtos.RegionAction.newBuilder()
          .setRegion(RequestConverter.buildRegionSpecifier(
            HBaseProtos.RegionSpecifier.RegionSpecifierType.REGION_NAME,
            r.getRegionInfo().getRegionName()))
          .addAction(ClientProtos.Action.newBuilder().setMutation(
            ProtobufUtil.toMutationNoData(ClientProtos.MutationProto.MutationType.PUT, put))))
        .build();

    List<Cell> cells = new ArrayList<>();
    for (Mutation m : rm.getMutations()) {
      cells.addAll(m.getCellList(FAMILY));
    }
    cells.addAll(put.getCellList(FAMILY));
    assertEquals(3, cells.size());
    HBaseRpcController controller = Mockito.mock(HBaseRpcController.class);
    Mockito.when(controller.cellScanner()).thenReturn(CellUtil.createCellScanner(cells));
    HRegionServer rs = TEST_UTIL.getMiniHBaseCluster().getRegionServer(TEST_UTIL
      .getMiniHBaseCluster().getServerHoldingRegion(TABLE_NAME, r.getRegionInfo().getRegionName()));

    ClientProtos.MultiResponse response = rs.getRSRpcServices().multi(controller, request);
    assertEquals(2, response.getRegionActionResultCount());
    assertTrue(response.getRegionActionResultList().get(0).hasException());
    assertFalse(response.getRegionActionResultList().get(1).hasException());
    assertEquals(1, response.getRegionActionResultList().get(1).getResultOrExceptionCount());
    assertTrue(
      response.getRegionActionResultList().get(1).getResultOrExceptionList().get(0).hasResult());
    try (Table table = TEST_UTIL.getConnection().getTable(TABLE_NAME)) {
      Result result = table.get(new Get(Bytes.toBytes("good")));
      assertEquals(1, result.size());
      Cell cell = result.getColumnLatestCell(FAMILY, null);
      assertTrue(Bytes.equals(CellUtil.cloneValue(cell), new byte[10]));
    }
  }

  private static ClientProtos.MultiRequest createRequest(RowMutations rm, byte[] regionName)
    throws IOException {
    ClientProtos.RegionAction.Builder builder = RequestConverter
      .getRegionActionBuilderWithRegion(ClientProtos.RegionAction.newBuilder(), regionName);
    builder.setAtomic(true);
    ClientProtos.Action.Builder actionBuilder = ClientProtos.Action.newBuilder();
    ClientProtos.MutationProto.Builder mutationBuilder = ClientProtos.MutationProto.newBuilder();
    ClientProtos.Condition condition = ProtobufUtil.toCondition(rm.getRow(), FAMILY, null,
      CompareOperator.EQUAL, new byte[10], null, null);
    for (Mutation mutation : rm.getMutations()) {
      ClientProtos.MutationProto.MutationType mutateType = null;
      if (mutation instanceof Put) {
        mutateType = ClientProtos.MutationProto.MutationType.PUT;
      } else if (mutation instanceof Delete) {
        mutateType = ClientProtos.MutationProto.MutationType.DELETE;
      } else {
        throw new DoNotRetryIOException(
          "RowMutations supports only put and delete, not " + mutation.getClass().getName());
      }
      mutationBuilder.clear();
      ClientProtos.MutationProto mp =
        ProtobufUtil.toMutationNoData(mutateType, mutation, mutationBuilder);
      actionBuilder.clear();
      actionBuilder.setMutation(mp);
      builder.addAction(actionBuilder.build());
    }
    ClientProtos.MultiRequest request = ClientProtos.MultiRequest.newBuilder()
      .addRegionAction(builder.setCondition(condition).build()).build();
    return request;
  }

  /**
   * This test depends on how regionserver process the batch ops. 1) group the put/delete until
   * meeting the increment 2) process the batch of put/delete 3) process the increment see
   * RSRpcServices#doNonAtomicRegionMutation
   */
  @Test
  public void testNonAtomicOperations() throws InterruptedException, IOException {
    Increment inc = new Increment(Bytes.toBytes("good")).addColumn(FAMILY, null, 100);
    List<Row> batches = new ArrayList<>();
    // the first and second puts will be group by regionserver
    batches.add(new Put(Bytes.toBytes("fail")).addColumn(FAMILY, null, new byte[CELL_SIZE]));
    batches.add(new Put(Bytes.toBytes("fail")).addColumn(FAMILY, null, new byte[CELL_SIZE]));
    // this Increment should succeed
    batches.add(inc);
    // this put should succeed
    batches.add(new Put(Bytes.toBytes("good")).addColumn(FAMILY, null, new byte[1]));
    Object[] objs = new Object[batches.size()];
    try (Table table = TEST_UTIL.getConnection().getTable(TABLE_NAME)) {
      table.batch(batches, objs);
      fail("Where is the exception? We put the malformed cells!!!");
    } catch (RetriesExhaustedWithDetailsException e) {
      assertEquals(2, e.getNumExceptions());
      for (int i = 0; i != e.getNumExceptions(); ++i) {
        assertNotNull(e.getCause(i));
        assertEquals(DoNotRetryIOException.class, e.getCause(i).getClass());
        assertEquals("fail", Bytes.toString(e.getRow(i).getRow()));
      }
    } finally {
      assertObjects(objs, batches.size());
      assertTrue(objs[0] instanceof IOException);
      assertTrue(objs[1] instanceof IOException);
      assertEquals(Result.class, objs[2].getClass());
      assertEquals(Result.class, objs[3].getClass());
    }
  }

  @Test
  public void testRowMutations() throws InterruptedException, IOException {
    Put put = new Put(Bytes.toBytes("good")).addColumn(FAMILY, null, new byte[1]);
    List<Row> batches = new ArrayList<>();
    RowMutations mutations = new RowMutations(Bytes.toBytes("fail"));
    // the first and second puts will be group by regionserver
    mutations.add(new Put(Bytes.toBytes("fail")).addColumn(FAMILY, null, new byte[CELL_SIZE]));
    mutations.add(new Put(Bytes.toBytes("fail")).addColumn(FAMILY, null, new byte[CELL_SIZE]));
    batches.add(mutations);
    // this bm should succeed
    mutations = new RowMutations(Bytes.toBytes("good"));
    mutations.add(put);
    mutations.add(put);
    batches.add(mutations);
    Object[] objs = new Object[batches.size()];
    try (Table table = TEST_UTIL.getConnection().getTable(TABLE_NAME)) {
      table.batch(batches, objs);
      fail("Where is the exception? We put the malformed cells!!!");
    } catch (RetriesExhaustedWithDetailsException e) {
      assertEquals(1, e.getNumExceptions());
      for (int i = 0; i != e.getNumExceptions(); ++i) {
        assertNotNull(e.getCause(i));
        assertTrue(e.getCause(i) instanceof IOException);
        assertEquals("fail", Bytes.toString(e.getRow(i).getRow()));
      }
    } finally {
      assertObjects(objs, batches.size());
      assertTrue(objs[0] instanceof IOException);
      assertEquals(Result.class, objs[1].getClass());
    }
  }

  private static void assertObjects(Object[] objs, int expectedSize) {
    int count = 0;
    for (Object obj : objs) {
      assertNotNull(obj);
      ++count;
    }
    assertEquals(expectedSize, count);
  }
}


text:
package grpc_logrus_test

import (
	"io"
	"runtime"
	"strings"
	"testing"
	"time"

	"github.com/grpc-ecosystem/go-grpc-middleware"
	"github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
	"github.com/grpc-ecosystem/go-grpc-middleware/tags"
	pb_testproto "github.com/grpc-ecosystem/go-grpc-middleware/testing/testproto"
	"github.com/sirupsen/logrus"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/stretchr/testify/suite"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
)

func TestLogrusServerSuite(t *testing.T) {
	if strings.HasPrefix(runtime.Version(), "go1.7") {
		t.Skipf("Skipping due to json.RawMessage incompatibility with go1.7")
		return
	}
	opts := []grpc_logrus.Option{
		grpc_logrus.WithLevels(customCodeToLevel),
	}
	b := newLogrusBaseSuite(t)
	b.InterceptorTestSuite.ServerOpts = []grpc.ServerOption{
		grpc_middleware.WithStreamServerChain(
			grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
			grpc_logrus.StreamServerInterceptor(logrus.NewEntry(b.logger), opts...)),
		grpc_middleware.WithUnaryServerChain(
			grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
			grpc_logrus.UnaryServerInterceptor(logrus.NewEntry(b.logger), opts...)),
	}
	suite.Run(t, &logrusServerSuite{b})
}

type logrusServerSuite struct {
	*logrusBaseSuite
}

func (s *logrusServerSuite) TestPing_WithCustomTags() {
	deadline := time.Now().Add(3 * time.Second)
	_, err := s.Client.Ping(s.DeadlineCtx(deadline), goodPing)
	require.NoError(s.T(), err, "there must be not be an error on a successful call")

	msgs := s.getOutputJSONs()
	require.Len(s.T(), msgs, 2, "two log statements should be logged")

	for _, m := range msgs {
		assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain the correct service name")
		assert.Equal(s.T(), m["grpc.method"], "Ping", "all lines must contain the correct method name")
		assert.Equal(s.T(), m["span.kind"], "server", "all lines must contain the kind of call (server)")
		assert.Equal(s.T(), m["custom_tags.string"], "something", "all lines must contain `custom_tags.string` with expected value")
		assert.Equal(s.T(), m["grpc.request.value"], "something", "all lines must contain the correct request value")
		assert.Equal(s.T(), m["custom_field"], "custom_value", "all lines must contain `custom_field` with the correct value")

		assert.Contains(s.T(), m, "custom_tags.int", "all lines must contain `custom_tags.int`")
		require.Contains(s.T(), m, "grpc.start_time", "all lines must contain the start time of the call")
		_, err := time.Parse(time.RFC3339, m["grpc.start_time"].(string))
		assert.NoError(s.T(), err, "should be able to parse start time as RFC3339")

		require.Contains(s.T(), m, "grpc.request.deadline", "all lines must contain the deadline of the call")
		_, err = time.Parse(time.RFC3339, m["grpc.request.deadline"].(string))
		require.NoError(s.T(), err, "should be able to parse deadline as RFC3339")
		assert.Equal(s.T(), m["grpc.request.deadline"], deadline.Format(time.RFC3339), "should have the same deadline that was set by the caller")
	}

	assert.Equal(s.T(), msgs[0]["msg"], "some ping", "first message must contain the correct user message")
	assert.Equal(s.T(), msgs[1]["msg"], "finished unary call with code OK", "second message must contain the correct user message")
	assert.Equal(s.T(), msgs[1]["level"], "info", "OK codes must be logged on info level.")

	assert.Contains(s.T(), msgs[1], "grpc.time_ms", "interceptor log statement should contain execution time")
}

func (s *logrusServerSuite) TestPingError_WithCustomLevels() {
	for _, tcase := range []struct {
		code  codes.Code
		level logrus.Level
		msg   string
	}{
		{
			code:  codes.Internal,
			level: logrus.ErrorLevel,
			msg:   "Internal must remap to ErrorLevel in DefaultCodeToLevel",
		},
		{
			code:  codes.NotFound,
			level: logrus.InfoLevel,
			msg:   "NotFound must remap to InfoLevel in DefaultCodeToLevel",
		},
		{
			code:  codes.FailedPrecondition,
			level: logrus.WarnLevel,
			msg:   "FailedPrecondition must remap to WarnLevel in DefaultCodeToLevel",
		},
		{
			code:  codes.Unauthenticated,
			level: logrus.ErrorLevel,
			msg:   "Unauthenticated is overwritten to ErrorLevel with customCodeToLevel override, which probably didn't work",
		},
	} {
		s.buffer.Reset()
		_, err := s.Client.PingError(
			s.SimpleCtx(),
			&pb_testproto.PingRequest{Value: "something", ErrorCodeReturned: uint32(tcase.code)})
		require.Error(s.T(), err, "each call here must return an error")

		msgs := s.getOutputJSONs()
		require.Len(s.T(), msgs, 1, "only the interceptor log message is printed in PingErr")
		m := msgs[0]
		assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain the correct service name")
		assert.Equal(s.T(), m["grpc.method"], "PingError", "all lines must contain the correct method name")
		assert.Equal(s.T(), m["grpc.code"], tcase.code.String(), "a gRPC code must be present")
		assert.Equal(s.T(), m["level"], tcase.level.String(), tcase.msg)
		assert.Equal(s.T(), m["msg"], "finished unary call with code "+tcase.code.String(), "must have the correct finish message")

		require.Contains(s.T(), m, "grpc.start_time", "all lines must contain a start time for the call")
		_, err = time.Parse(time.RFC3339, m["grpc.start_time"].(string))
		assert.NoError(s.T(), err, "should be able to parse the start time as RFC3339")

		require.Contains(s.T(), m, "grpc.request.deadline", "all lines must contain the deadline of the call")
		_, err = time.Parse(time.RFC3339, m["grpc.request.deadline"].(string))
		require.NoError(s.T(), err, "should be able to parse deadline as RFC3339")
	}
}

func (s *logrusServerSuite) TestPingList_WithCustomTags() {
	stream, err := s.Client.PingList(s.SimpleCtx(), goodPing)
	require.NoError(s.T(), err, "should not fail on establishing the stream")
	for {
		_, err := stream.Recv()
		if err == io.EOF {
			break
		}
		require.NoError(s.T(), err, "reading stream should not fail")
	}

	msgs := s.getOutputJSONs()
	require.Len(s.T(), msgs, 2, "two log statements should be logged")
	for _, m := range msgs {
		assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain the correct service name")
		assert.Equal(s.T(), m["grpc.method"], "PingList", "all lines must contain the correct method name")
		assert.Equal(s.T(), m["span.kind"], "server", "all lines must contain the kind of call (server)")
		assert.Equal(s.T(), m["custom_tags.string"], "something", "all lines must contain the correct `custom_tags.string`")
		assert.Equal(s.T(), m["grpc.request.value"], "something", "all lines must contain the correct request value")

		assert.Contains(s.T(), m, "custom_tags.int", "all lines must contain `custom_tags.int`")
		require.Contains(s.T(), m, "grpc.start_time", "all lines must contain the start time for the call")
		_, err := time.Parse(time.RFC3339, m["grpc.start_time"].(string))
		assert.NoError(s.T(), err, "should be able to parse start time as RFC3339")

		require.Contains(s.T(), m, "grpc.request.deadline", "all lines must contain the deadline of the call")
		_, err = time.Parse(time.RFC3339, m["grpc.request.deadline"].(string))
		require.NoError(s.T(), err, "should be able to parse deadline as RFC3339")
	}

	assert.Equal(s.T(), msgs[0]["msg"], "some pinglist", "msg must be the correct message")
	assert.Equal(s.T(), msgs[1]["msg"], "finished streaming call with code OK", "msg must be the correct message")
	assert.Equal(s.T(), msgs[1]["level"], "info", "OK codes must be logged on info level.")

	assert.Contains(s.T(), msgs[1], "grpc.time_ms", "interceptor log statement should contain execution time")
}

func TestLogrusServerOverrideSuite(t *testing.T) {
	if strings.HasPrefix(runtime.Version(), "go1.7") {
		t.Skip("Skipping due to json.RawMessage incompatibility with go1.7")
		return
	}
	opts := []grpc_logrus.Option{
		grpc_logrus.WithDurationField(grpc_logrus.DurationToDurationField),
	}
	b := newLogrusBaseSuite(t)
	b.InterceptorTestSuite.ServerOpts = []grpc.ServerOption{
		grpc_middleware.WithStreamServerChain(
			grpc_ctxtags.StreamServerInterceptor(),
			grpc_logrus.StreamServerInterceptor(logrus.NewEntry(b.logger), opts...)),
		grpc_middleware.WithUnaryServerChain(
			grpc_ctxtags.UnaryServerInterceptor(),
			grpc_logrus.UnaryServerInterceptor(logrus.NewEntry(b.logger), opts...)),
	}
	suite.Run(t, &logrusServerOverrideSuite{b})
}

type logrusServerOverrideSuite struct {
	*logrusBaseSuite
}

func (s *logrusServerOverrideSuite) TestPing_HasOverriddenDuration() {
	_, err := s.Client.Ping(s.SimpleCtx(), goodPing)
	require.NoError(s.T(), err, "there must be not be an error on a successful call")

	msgs := s.getOutputJSONs()
	require.Len(s.T(), msgs, 2, "two log statements should be logged")
	for _, m := range msgs {
		assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain service name")
		assert.Equal(s.T(), m["grpc.method"], "Ping", "all lines must contain method name")
	}

	assert.Equal(s.T(), msgs[0]["msg"], "some ping", "first message must be correct")
	assert.NotContains(s.T(), msgs[0], "grpc.time_ms", "first message must not contain default duration")
	assert.NotContains(s.T(), msgs[0], "grpc.duration", "first message must not contain overridden duration")

	assert.Equal(s.T(), msgs[1]["msg"], "finished unary call with code OK", "second message must be correct")
	assert.Equal(s.T(), msgs[1]["level"], "info", "second must be logged on info level.")
	assert.NotContains(s.T(), msgs[1], "grpc.time_ms", "second message must not contain default duration")
	assert.Contains(s.T(), msgs[1], "grpc.duration", "second message must contain overridden duration")
}

func (s *logrusServerOverrideSuite) TestPingList_HasOverriddenDuration() {
	stream, err := s.Client.PingList(s.SimpleCtx(), goodPing)
	require.NoError(s.T(), err, "should not fail on establishing the stream")
	for {
		_, err := stream.Recv()
		if err == io.EOF {
			break
		}
		require.NoError(s.T(), err, "reading stream should not fail")
	}
	msgs := s.getOutputJSONs()
	require.Len(s.T(), msgs, 2, "two log statements should be logged")

	for _, m := range msgs {
		assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain service name")
		assert.Equal(s.T(), m["grpc.method"], "PingList", "all lines must contain method name")
	}

	assert.Equal(s.T(), msgs[0]["msg"], "some pinglist", "first message must contain user message")
	assert.NotContains(s.T(), msgs[0], "grpc.time_ms", "first message must not contain default duration")
	assert.NotContains(s.T(), msgs[0], "grpc.duration", "first message must not contain overridden duration")

	assert.Equal(s.T(), msgs[1]["msg"], "finished streaming call with code OK", "second message must contain correct message")
	assert.Equal(s.T(), msgs[1]["level"], "info", "second message must be logged on info level.")
	assert.NotContains(s.T(), msgs[1], "grpc.time_ms", "second message must not contain default duration")
	assert.Contains(s.T(), msgs[1], "grpc.duration", "second message must contain overridden duration")
}

func TestLogrusServerOverrideDeciderSuite(t *testing.T) {
	if strings.HasPrefix(runtime.Version(), "go1.7") {
		t.Skip("Skipping due to json.RawMessage incompatibility with go1.7")
		return
	}
	opts := []grpc_logrus.Option{
		grpc_logrus.WithDecider(func(method string, err error) bool {
			if err != nil && method == "/mwitkow.testproto.TestService/PingError" {
				return true
			}

			return false
		}),
	}
	b := newLogrusBaseSuite(t)
	b.InterceptorTestSuite.ServerOpts = []grpc.ServerOption{
		grpc_middleware.WithStreamServerChain(
			grpc_ctxtags.StreamServerInterceptor(),
			grpc_logrus.StreamServerInterceptor(logrus.NewEntry(b.logger), opts...)),
		grpc_middleware.WithUnaryServerChain(
			grpc_ctxtags.UnaryServerInterceptor(),
			grpc_logrus.UnaryServerInterceptor(logrus.NewEntry(b.logger), opts...)),
	}
	suite.Run(t, &logrusServerOverrideDeciderSuite{b})
}

type logrusServerOverrideDeciderSuite struct {
	*logrusBaseSuite
}

func (s *logrusServerOverrideDeciderSuite) TestPing_HasOverriddenDecider() {
	_, err := s.Client.Ping(s.SimpleCtx(), goodPing)
	require.NoError(s.T(), err, "there must be not be an error on a successful call")

	msgs := s.getOutputJSONs()
	require.Len(s.T(), msgs, 1, "single log statements should be logged")
	assert.Equal(s.T(), msgs[0]["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain service name")
	assert.Equal(s.T(), msgs[0]["grpc.method"], "Ping", "all lines must contain method name")
	assert.Equal(s.T(), msgs[0]["msg"], "some ping", "handler's message must contain user message")
}

func (s *logrusServerOverrideDeciderSuite) TestPingError_HasOverriddenDecider() {
	code := codes.NotFound
	level := logrus.InfoLevel
	msg := "NotFound must remap to InfoLevel in DefaultCodeToLevel"

	s.buffer.Reset()
	_, err := s.Client.PingError(
		s.SimpleCtx(),
		&pb_testproto.PingRequest{Value: "something", ErrorCodeReturned: uint32(code)})
	require.Error(s.T(), err, "each call here must return an error")

	msgs := s.getOutputJSONs()
	require.Len(s.T(), msgs, 1, "only the interceptor log message is printed in PingErr")
	m := msgs[0]
	assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain service name")
	assert.Equal(s.T(), m["grpc.method"], "PingError", "all lines must contain method name")
	assert.Equal(s.T(), m["grpc.code"], code.String(), "all lines must correct gRPC code")
	assert.Equal(s.T(), m["level"], level.String(), msg)
}

func (s *logrusServerOverrideDeciderSuite) TestPingList_HasOverriddenDecider() {
	stream, err := s.Client.PingList(s.SimpleCtx(), goodPing)
	require.NoError(s.T(), err, "should not fail on establishing the stream")
	for {
		_, err := stream.Recv()
		if err == io.EOF {
			break
		}
		require.NoError(s.T(), err, "reading stream should not fail")
	}

	msgs := s.getOutputJSONs()
	require.Len(s.T(), msgs, 1, "single log statements should be logged")
	assert.Equal(s.T(), msgs[0]["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain service name")
	assert.Equal(s.T(), msgs[0]["grpc.method"], "PingList", "all lines must contain method name")
	assert.Equal(s.T(), msgs[0]["msg"], "some pinglist", "handler's message must contain user message")

	assert.NotContains(s.T(), msgs[0], "grpc.time_ms", "handler's message must not contain default duration")
	assert.NotContains(s.T(), msgs[0], "grpc.duration", "handler's message must not contain overridden duration")
}


text:
package com.intellij.openapi.wm.impl;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAware;
import org.jetbrains.annotations.NotNull;

final class PreviousProjectWindow extends AnAction implements DumbAware {
  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    WindowDressing.getWindowActionGroup().activatePreviousWindow(e);
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    e.getPresentation().setEnabled(WindowDressing.getWindowActionGroup().isEnabled());
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="An approach to developing modern web applications">
    <meta name="author" content="Marc J. Greenberg">
    <title>ElectricDiscoTech</title>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="css/style.min.css" type="text/css">

Conceptual

Dance Floor

First Steps

Do the Hustle

Disco Duck

Disco Pig

Source

                            ElectricDiscoTech is built by
                            dancing on the shoulders of the giants, open source giants. Edt
                            is hosted on GitHub and licensed under the
                            MIT license. You are welcome to use it for all
                            your personal and commercial projects. To access its source files, just
                            clone the repository on GitHub or download the latest
                            version. In fact this file is part of the developers documentation in the dev/doc directory.

                            Download source

File structure

                        ElectricDiscoTech employs an intuitive file layout/organization. There is great wisdom that can be
                        derived from the notion of convention over configuration. By adopting this layout as a convention
                        you can decrease the number little of decisions that need to be made, reducing complexity and "free
                        your mind" to focus on content:

Folder

Content

/

Top level root of the client side of a modern webapp, It is the resolution to the
                                    href="/".
                                    Your apps markup is served from here this location. Any subfolder not listed below
                                    may be used to organize your apps content.

/css

Your compiled/minified css code. Compiled from what? There is a question here
                                    less vs. sass, which one?
                                    ElectricDiscoTech is using less for now. And in the end the only guidance here
                                    is that you use a preprocessor.

/fonts

Fonts definitions. Another topic that spurs debate, Some say that fonts should be
                                    pulled from a Content delivery network (CDN) and there are several valid reasons why
                                    you might choose to. There are just as many reasons why you would not want this so
                                    one again the choice is left open.

/img

Images files used site wide. Its is a good idea to normalize your images as leads to a more
                                    consistent environment. Just like fonts the topic is connected with the CDN debate.

/js

This is the location from which minified "production" javascript is served.

/dev

An entire subtree of functionality used to build your modern web application. This is where you
                                    put your typescript source and definitions, as well as any node, and bower managed content.
                                    Additionally I typically use /dev/docs as a location to author and host documentation for an
                                    edt created site.


text:
#include "ogr_sosi.h"

static int bFYBAInit = FALSE;

/************************************************************************/
/*                        OGRSOSIDriverUnload()                         */
/************************************************************************/

static void OGRSOSIDriverUnload(CPL_UNUSED GDALDriver* poDriver) {

    if ( bFYBAInit )
    {
        LC_Close(); /* Close FYBA */
        bFYBAInit = FALSE;
    }
}

/************************************************************************/
/*                              Open()                                  */
/************************************************************************/

static GDALDataset *OGRSOSIDriverOpen( GDALOpenInfo* poOpenInfo )
{
    if( poOpenInfo->fpL == NULL ||
        strstr((const char*)poOpenInfo->pabyHeader, ".HODE") == NULL )
        return NULL;

    if ( !bFYBAInit )
    {
        LC_Init();  /* Init FYBA */
        bFYBAInit = TRUE;
    }

    OGRSOSIDataSource   *poDS = new OGRSOSIDataSource();
    if ( !poDS->Open( poOpenInfo->pszFilename, 0 ) ) {
        delete poDS;
        return NULL;
    }

    return poDS;
}

/************************************************************************/
/*                              Create()                                */
/************************************************************************/

static GDALDataset *OGRSOSIDriverCreate( const char * pszName,
                                         CPL_UNUSED int nBands, CPL_UNUSED int nXSize,
                                         CPL_UNUSED int nYSize, CPL_UNUSED GDALDataType eDT,
                                         CPL_UNUSED char **papszOptions )
{
    if ( !bFYBAInit )
    {
        LC_Init();  /* Init FYBA */
        bFYBAInit = TRUE;
    }
    OGRSOSIDataSource   *poDS = new OGRSOSIDataSource();
    if ( !poDS->Create( pszName ) ) {
        delete poDS;
        return NULL;
    }
    return poDS;
}

/************************************************************************/
/*                         RegisterOGRSOSI()                            */
/************************************************************************/

void RegisterOGRSOSI() {
    if( GDALGetDriverByName( "SOSI" ) == NULL )
        return;

    GDALDriver *poDriver = new GDALDriver();

    poDriver->SetDescription( "SOSI" );
    poDriver->SetMetadataItem( GDAL_DCAP_VECTOR, "YES" );
    poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "Norwegian SOSI Standard" );
    poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "drv_sosi.html" );

    poDriver->pfnOpen = OGRSOSIDriverOpen;
    poDriver->pfnCreate = OGRSOSIDriverCreate;
    poDriver->pfnUnloadDriver = OGRSOSIDriverUnload;

    GetGDALDriverManager()->RegisterDriver( poDriver );
}


text:
package org.keycloak.account.freemarker.model;

/**
 * @author Stian Thorgersen
 */
public class ReferrerBean {

    private String[] referrer;

    public ReferrerBean(String[] referrer) {
        this.referrer = referrer;
    }

    public String getName() {
        return referrer[0];
    }

    public String getUrl() {
        return referrer[1];
    }

}


text:
package routes

import (
	"fmt"
	"net/http"
	"strconv"

	"app/config"
	"app/data"
	"app/page"
	"app/utils"

	"github.com/gorilla/mux"
	"google.golang.org/appengine"
	"google.golang.org/appengine/datastore"
	"google.golang.org/appengine/log"
)

//UserExportHandler is the http request handler for /x/userID
//where userID is a valid user ID that Davine has previously discovered.
//It exports all the user's data using data.ExportUser.
func UserExportHandler(w http.ResponseWriter, r *http.Request) {
	var (
		c    = appengine.NewContext(r)
		db   = data.NewRequest(c)
		vars = mux.Vars(r)
		cnfg = config.Load(c)
	)

	if r.Method == "GET" {
		userID, err := strconv.ParseInt(vars["user"], 10, 64)
		if err != nil {
			log.Errorf(c, "got err: %v", err)
			http.Redirect(w, r, "/404", 301)
			return
		}
		userRecord, err := db.GetUserRecord(userID)
		if err == datastore.ErrNoSuchEntity {
			http.Redirect(w, r, "/404", 301)
			return
		}
		data := map[string]string{"username": userRecord.Username, "userId": userRecord.UserId, "captcha": cnfg["captchaPublic"]}
		p := page.New("export.html")
		p.LoadData(data)
		p.Write(w)
	} else if r.Method == "POST" {
		captcha := utils.VerifyCaptcha(c, map[string]string{
			"response": r.FormValue("g-recaptcha-response"),
			"remoteip": r.RemoteAddr,
		})
		if captcha {
			db.ExportUser(vars["user"], w)
		} else {
			fmt.Fprint(w, "Seems like your CAPTCHA was wrong. Please press back and try again.")
		}
	}
}