text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Html;
using System.Xml;
using System.Html.Services;
using System.Html.Media.Graphics;

namespace wwtlib
{
    public enum CoordinatesTypes { Spherical = 0, Rectangular = 1, Orbital = 2 };
    public enum AltTypes { Depth = 0, Altitude = 1, Distance = 2, SeaLevel = 3, Terrain = 4 };

    public enum MarkerMixes { Same_For_All = 0, /*Group_by_Range, Group_by_Values */};
    public enum ColorMaps { Same_For_All = 0, /*Group_by_Range=1, */Group_by_Values = 2, Per_Column_Literal = 3/*, Gradients_by_Range=4*/ };

    public enum PlotTypes { Gaussian = 0, Point = 1, Circle = 2,/* Square,*/ PushPin = 3/*, Custom */};

    public enum MarkerScales { Screen = 0, World = 1 };
    public enum RAUnits { Hours = 0, Degrees = 1 };

    public class TimeSeriesLayer : Layer
    {
        protected bool isLongIndex = false;
        protected int shapeVertexCount;

        protected bool lines = false;
        protected int latColumn = -1;
        protected float fixedSize = 1;
        protected float decay = 16;
        protected bool timeSeries = false;

        private bool dynamicData = false;

        public bool DynamicData
        {
            get { return dynamicData; }
            set { dynamicData = value; }
        }

        private bool autoUpdate = false;

        public bool AutoUpdate
        {
            get { return autoUpdate; }
            set { autoUpdate = value; }
        }

        string dataSourceUrl = "";

        public string DataSourceUrl
        {
            get { return dataSourceUrl; }
            set { dataSourceUrl = value; }
        }

        public bool TimeSeries
        {
            get { return timeSeries; }
            set
            {
                if (timeSeries != value)
                {
                    version++;
                    timeSeries = value;
                }
            }
        }

        public virtual List<string> Header
        {
            get
            {
                return null;
            }
        }

        Date beginRange = new Date("1/1/2100");

        public Date BeginRange
        {
            get { return beginRange; }
            set
            {
                if (beginRange != value)
                {
                    version++;
                    beginRange = value;
                }
            }
        }
        Date endRange = new Date("01/01/1800");

        public Date EndRange
        {
            get { return endRange; }
            set
            {
                if (endRange != value)
                {
                    version++;
                    endRange = value;
                }
            }
        }

        public override void InitializeFromXml(XmlNode node)
        {
            TimeSeries = bool.Parse(node.Attributes.GetNamedItem("TimeSeries").Value);
            BeginRange = new Date(node.Attributes.GetNamedItem("BeginRange").Value);
            EndRange = new Date(node.Attributes.GetNamedItem("EndRange").Value);
            Decay = Single.Parse(node.Attributes.GetNamedItem("Decay").Value);

            switch (node.Attributes.GetNamedItem("CoordinatesType").Value)
            {
                case "Spherical":
                    CoordinatesType = CoordinatesTypes.Spherical;
                    break;
                case "Rectangular": CoordinatesType = CoordinatesTypes.Rectangular;
                    break;
                case "Orbital":
                    CoordinatesType = CoordinatesTypes.Orbital;
                    break;
                default:
                    break;
            }

            if ((int)CoordinatesType < 0)
            {
                CoordinatesType = CoordinatesTypes.Spherical;
            }
            LatColumn = int.Parse(node.Attributes.GetNamedItem("LatColumn").Value);
            LngColumn = int.Parse(node.Attributes.GetNamedItem("LngColumn").Value);
            if (node.Attributes.GetNamedItem("GeometryColumn") != null)
            {
                GeometryColumn = int.Parse(node.Attributes.GetNamedItem("GeometryColumn").Value);
            }

            switch (node.Attributes.GetNamedItem("AltType").Value)
            {
                case "Depth":
                    AltType = AltTypes.Depth;
                    break;
                case "Altitude":
                    AltType = AltTypes.Altitude;
                    break;
                case "Distance":
                    AltType = AltTypes.Distance;
                    break;
                case "SeaLevel":
                    AltType = AltTypes.SeaLevel;
                    break;
                case "Terrain":
                    AltType = AltTypes.Terrain;
                    break;
                default:
                    break;
            }

            MarkerMix = MarkerMixes.Same_For_All;

            switch (node.Attributes.GetNamedItem("ColorMap").Value)
            {
                case "Same_For_All":
                    ColorMap = ColorMaps.Same_For_All;
                    break;
                case "Group_by_Values":
                    ColorMap = ColorMaps.Group_by_Values;
                    break;
                case "Per_Column_Literal":
                    ColorMap = ColorMaps.Per_Column_Literal;
                    break;
                default:
                    break;
            }

            MarkerColumn = int.Parse(node.Attributes.GetNamedItem("MarkerColumn").Value);
            ColorMapColumn = int.Parse(node.Attributes.GetNamedItem("ColorMapColumn").Value);

            switch (node.Attributes.GetNamedItem("PlotType").Value)
            {
                case "Gaussian":
                    PlotType = PlotTypes.Gaussian;
                    break;
                case "Point":
                    PlotType = PlotTypes.Point;
                    break;
                case "Circle":
                    PlotType = PlotTypes.Circle;
                    break;
                case "PushPin":
                    PlotType = PlotTypes.PushPin;
                    break;
                default:
                    break;
            }

            MarkerIndex = int.Parse(node.Attributes.GetNamedItem("MarkerIndex").Value);

            switch (node.Attributes.GetNamedItem("MarkerScale").Value)
            {
                case "Screen":
                    MarkerScale = MarkerScales.Screen;
                    break;
                case "World":
                    MarkerScale = MarkerScales.World;
                    break;
                default:
                    break;
            }

            switch (node.Attributes.GetNamedItem("AltUnit").Value)
            {
                case "Meters":
                    AltUnit = AltUnits.Meters;
                    break;
                case "Feet":
                    AltUnit = AltUnits.Feet;
                    break;
                case "Inches":
                    AltUnit = AltUnits.Inches;
                    break;
                case "Miles":
                    AltUnit = AltUnits.Miles;
                    break;
                case "Kilometers":
                    AltUnit = AltUnits.Kilometers;
                    break;
                case "AstronomicalUnits":
                    AltUnit = AltUnits.AstronomicalUnits;
                    break;
                case "LightYears":
                    AltUnit = AltUnits.LightYears;
                    break;
                case "Parsecs":
                    AltUnit = AltUnits.Parsecs;
                    break;
                case "MegaParsecs":
                    AltUnit = AltUnits.MegaParsecs;
                    break;
                case "Custom":
                    AltUnit = AltUnits.Custom;
                    break;
                default:
                    break;
            }

            AltColumn = int.Parse(node.Attributes.GetNamedItem("AltColumn").Value);
            StartDateColumn = int.Parse(node.Attributes.GetNamedItem("StartDateColumn").Value);
            EndDateColumn = int.Parse(node.Attributes.GetNamedItem("EndDateColumn").Value);
            SizeColumn = int.Parse(node.Attributes.GetNamedItem("SizeColumn").Value);
            HyperlinkFormat = node.Attributes.GetNamedItem("HyperlinkFormat").Value;
            HyperlinkColumn = int.Parse(node.Attributes.GetNamedItem("HyperlinkColumn").Value);
            ScaleFactor = Single.Parse(node.Attributes.GetNamedItem("ScaleFactor").Value);

            switch (node.Attributes.GetNamedItem("PointScaleType").Value)
            {
                case "Linear":
                    PointScaleType = PointScaleTypes.Linear;
                    break;
                case "Power":
                    PointScaleType = PointScaleTypes.Power;
                    break;
                case "Log":
                    PointScaleType = PointScaleTypes.Log;
                    break;
                case "Constant":
                    PointScaleType = PointScaleTypes.Constant;
                    break;
                case "StellarMagnitude":
                    PointScaleType = PointScaleTypes.StellarMagnitude;
                    break;
                default:
                    break;
            }

            if (node.Attributes.GetNamedItem("ShowFarSide") != null)
            {
                ShowFarSide = Boolean.Parse(node.Attributes.GetNamedItem("ShowFarSide").Value);
            }

            if (node.Attributes.GetNamedItem("RaUnits") != null)
            {
               // RaUnits = (RAUnits)Enum.Parse(typeof(RAUnits), node.Attributes["RaUnits"].Value);

                switch (node.Attributes.GetNamedItem("RaUnits").Value)
                {
                    case "Hours":
                        RaUnits = RAUnits.Hours;
                        break;
                    case "Degrees":
                        RaUnits = RAUnits.Degrees;
                        break;
                }
            }

            if (node.Attributes.GetNamedItem("HoverTextColumn") != null)
            {
                NameColumn = int.Parse(node.Attributes.GetNamedItem("HoverTextColumn").Value);
            }

            if (node.Attributes.GetNamedItem("XAxisColumn") != null)
            {
                XAxisColumn = int.Parse(node.Attributes.GetNamedItem("XAxisColumn").Value);
                XAxisReverse = bool.Parse(node.Attributes.GetNamedItem("XAxisReverse").Value);
                YAxisColumn = int.Parse(node.Attributes.GetNamedItem("YAxisColumn").Value);
                YAxisReverse = bool.Parse(node.Attributes.GetNamedItem("YAxisReverse").Value);
                ZAxisColumn = int.Parse(node.Attributes.GetNamedItem("ZAxisColumn").Value);
                ZAxisReverse = bool.Parse(node.Attributes.GetNamedItem("ZAxisReverse").Value);

                switch (node.Attributes.GetNamedItem("CartesianScale").Value)
                {
                    case "Meters":
                        CartesianScale = AltUnits.Meters;
                        break;
                    case "Feet":
                        CartesianScale = AltUnits.Feet;
                        break;
                    case "Inches":
                        CartesianScale = AltUnits.Inches;
                        break;
                    case "Miles":
                        CartesianScale = AltUnits.Miles;
                        break;
                    case "Kilometers":
                        CartesianScale = AltUnits.Kilometers;
                        break;
                    case "AstronomicalUnits":
                        CartesianScale = AltUnits.AstronomicalUnits;
                        break;
                    case "LightYears":
                        CartesianScale = AltUnits.LightYears;
                        break;
                    case "Parsecs":
                        CartesianScale = AltUnits.Parsecs;
                        break;
                    case "MegaParsecs":
                        CartesianScale = AltUnits.MegaParsecs;
                        break;
                    case "Custom":
                        CartesianScale = AltUnits.Custom;
                        break;
                    default:
                        break;
                }

                CartesianCustomScale = double.Parse(node.Attributes.GetNamedItem("CartesianCustomScale").Value);

            }

            if (node.Attributes.GetNamedItem("DynamicData") != null)
            {
                DynamicData = bool.Parse(node.Attributes.GetNamedItem("DynamicData").Value);
                AutoUpdate = bool.Parse(node.Attributes.GetNamedItem("AutoUpdate").Value);
                DataSourceUrl = node.Attributes.GetNamedItem("DataSourceUrl").Value;
            }

        }

        public virtual void ComputeDateDomainRange(int columnStart, int columnEnd)
        {
        }
        public Dictionary<string, DomainValue> MarkerDomainValues = new Dictionary<string, DomainValue>();
        public Dictionary<string, DomainValue> ColorDomainValues = new Dictionary<string, DomainValue>();

        public virtual List<string> GetDomainValues(int column)
        {
            return new List<string>();
        }

        public float Decay
        {
            get { return decay; }
            set
            {
                if (decay != value)
                {
                    version++;
                    decay = value;
                }
            }
        }

        private CoordinatesTypes coordinatesType = CoordinatesTypes.Spherical;

        public CoordinatesTypes CoordinatesType
        {
            get { return coordinatesType; }
            set
            {
                if (coordinatesType != value)
                {
                    version++;
                    coordinatesType = value;
                }
            }
        }

        public int LatColumn
        {
            get { return latColumn; }
            set
            {
                if (latColumn != value)
                {
                    version++;
                    latColumn = value;
                }
            }
        }
        protected int lngColumn = -1;

        public int LngColumn
        {
            get { return lngColumn; }
            set
            {
                if (lngColumn != value)
                {
                    version++;
                    lngColumn = value;
                }
            }
        }

        protected int geometryColumn = -1;

        public int GeometryColumn
        {
            get { return geometryColumn; }
            set
            {
                if (geometryColumn != value)
                {
                    version++;
                    geometryColumn = value;
                }
            }
        }

        private int xAxisColumn = -1;

        public int XAxisColumn
        {
            get { return xAxisColumn; }
            set
            {
                if (xAxisColumn != value)
                {
                    version++;
                    xAxisColumn = value;
                }
            }
        }
        private int yAxisColumn = -1;

        public int YAxisColumn
        {
            get { return yAxisColumn; }
            set
            {
                if (yAxisColumn != value)
                {
                    version++;
                    yAxisColumn = value;
                }
            }
        }
        private int zAxisColumn = -1;

        public int ZAxisColumn
        {
            get { return zAxisColumn; }
            set
            {
                if (zAxisColumn != value)
                {
                    version++;
                    zAxisColumn = value;
                }
            }
        }

        private bool xAxisReverse = false;

        public bool XAxisReverse
        {
            get { return xAxisReverse; }
            set
            {
                if (xAxisReverse != value)
                {
                    version++;
                    xAxisReverse = value;
                }
            }
        }
        private bool yAxisReverse = false;

        public bool YAxisReverse
        {
            get { return yAxisReverse; }
            set
            {
                if (yAxisReverse != value)
                {
                    version++;
                    yAxisReverse = value;
                }
            }
        }
        private bool zAxisReverse = false;

        public bool ZAxisReverse
        {
            get { return zAxisReverse; }
            set
            {
                if (zAxisReverse != value)
                {
                    version++;
                    zAxisReverse = value;
                }
            }
        }

        private AltTypes altType = AltTypes.SeaLevel;

        public AltTypes AltType
        {
            get { return altType; }
            set
            {
                if (altType != value)
                {
                    version++;
                    altType = value;
                }
            }
        }

        private MarkerMixes markerMix = MarkerMixes.Same_For_All;

        public MarkerMixes MarkerMix
        {
            get { return markerMix; }
            set
            {
                if (markerMix != value)
                {
                    version++;
                    markerMix = value;
                }
            }
        }

        RAUnits raUnits = RAUnits.Hours;

        public RAUnits RaUnits
        {
            get { return raUnits; }
            set
            {

                if (raUnits != value)
                {
                    version++;
                    raUnits = value;
                }
            }
        }

        private ColorMaps colorMap = ColorMaps.Per_Column_Literal;

        internal ColorMaps ColorMap
        {
            get { return colorMap; }
            set
            {
                if (colorMap != value)
                {
                    version++;
                    colorMap = value;
                }
            }
        }

        private int markerColumn = -1;

        public int MarkerColumn
        {
            get { return markerColumn; }
            set
            {
                if (markerColumn != value)
                {
                    version++;
                    markerColumn = value;
                }
            }
        }

        private int colorMapColumn = -1;

        public int ColorMapColumn
        {
            get { return colorMapColumn; }
            set
            {
                if (colorMapColumn != value)
                {
                    version++;
                    colorMapColumn = value;
                }
            }
        }

        private PlotTypes plotType = PlotTypes.Gaussian;

        public PlotTypes PlotType
        {
            get { return plotType; }
            set
            {
                if (plotType != value)
                {
                    version++;
                    plotType = value;
                }

            }
        }

        private int markerIndex = 0;

        public int MarkerIndex
        {
            get { return markerIndex; }
            set
            {
                if (markerIndex != value)
                {
                    version++;
                    markerIndex = value;
                }
            }
        }

        private bool showFarSide = false;

        public bool ShowFarSide
        {
            get { return showFarSide; }
            set
            {
                if (showFarSide != value)
                {
                    version++;
                    showFarSide = value;
                }
            }
        }

        private MarkerScales markerScale = MarkerScales.World;

        public MarkerScales MarkerScale
        {
            get { return markerScale; }
            set
            {
                if (markerScale != value)
                {
                    version++;
                    markerScale = value;
                }
            }
        }

        private AltUnits altUnit = AltUnits.Meters;

        public AltUnits AltUnit
        {
            get { return altUnit; }
            set
            {
                if (altUnit != value)
                {
                    version++;
                    altUnit = value;
                }
            }
        }
        private AltUnits cartesianScale = AltUnits.Meters;

        public AltUnits CartesianScale
        {
            get { return cartesianScale; }
            set
            {
                if (cartesianScale != value)
                {
                    version++;
                    cartesianScale = value;
                }
            }
        }

        private double cartesianCustomScale = 1;

        public double CartesianCustomScale
        {
            get { return cartesianCustomScale; }
            set
            {
                if (cartesianCustomScale != value)
                {
                    version++;
                    cartesianCustomScale = value;
                }
            }
        }

        protected int altColumn = -1;

        public int AltColumn
        {
            get { return altColumn; }
            set
            {
                if (altColumn != value)
                {
                    version++;
                    altColumn = value;
                }
            }
        }

        protected int startDateColumn = -1;

        public int StartDateColumn
        {
            get { return startDateColumn; }
            set
            {
                if (startDateColumn != value)
                {
                    version++;
                    startDateColumn = value;
                }
            }
        }
        protected int endDateColumn = -1;

        public int EndDateColumn
        {
            get { return endDateColumn; }
            set
            {
                if (endDateColumn != value)
                {
                    version++;
                    endDateColumn = value;
                }
            }
        }

        protected int sizeColumn = -1;

        public int SizeColumn
        {
            get { return sizeColumn; }
            set
            {
                if (sizeColumn != value)
                {
                    version++;
                    sizeColumn = value;
                }
            }
        }
        protected int nameColumn = 0;

        public int NameColumn
        {
            get { return nameColumn; }
            set
            {
                if (nameColumn != value)
                {
                    version++;
                    nameColumn = value;
                }
            }
        }
        private string hyperlinkFormat = "";

        public string HyperlinkFormat
        {
            get { return hyperlinkFormat; }
            set
            {
                if (hyperlinkFormat != value)
                {
                    version++; hyperlinkFormat = value;
                }
            }
        }

        private int hyperlinkColumn = -1;

        public int HyperlinkColumn
        {
            get { return hyperlinkColumn; }
            set
            {
                if (hyperlinkColumn != value)
                {
                    version++;
                    hyperlinkColumn = value;
                }
            }
        }

        protected float scaleFactor = 1.0f;

        public float ScaleFactor
        {
            get { return scaleFactor; }
            set
            {
                if (scaleFactor != value)
                {
                    version++;

                    scaleFactor = value;
                }
            }
        }

        protected PointScaleTypes pointScaleType = PointScaleTypes.Power;

        public PointScaleTypes PointScaleType
        {
            get { return pointScaleType; }
            set
            {
                if (pointScaleType != value)
                {
                    version++;
                    pointScaleType = value;
                }
            }
        }

        protected List<Vector3d> positions = new List<Vector3d>();

        protected LineList lineList;
        protected LineList lineList2d;
        protected TriangleList triangleList;
        protected TriangleList triangleList2d;

        protected PointList pointList;

        protected bool bufferIsFlat = false;

        protected Date baseDate = new Date(2010, 0, 1, 12, 00, 00);

        static ImageElement circleTexture = null;

        static ImageElement CircleTexture
        {
            get
            {
                //if (circleTexture == null)
                //{
                //    circleTexture = UiTools.LoadTextureFromBmp(Tile.prepDevice, Properties.Resources.circle, 0);
                //}

                return circleTexture;
            }
        }
        public bool dirty = true;
        protected virtual bool PrepVertexBuffer(RenderContext renderContext, float opacity)
        {
            return true;
        }

        public override bool Draw(RenderContext renderContext, float opacity, bool flat)
        {

            RenderContext device = renderContext;

            //if (shaderA == null)
            //{
            //    MakeVertexShaderA(device);
            //}

            if (bufferIsFlat != flat)
            {
                CleanUp();
                bufferIsFlat = flat;
            }

            if (dirty)
            {
                PrepVertexBuffer(device, opacity);
            }

            double jNow =  SpaceTimeController.JNow - SpaceTimeController.UtcToJulian(baseDate);

            if (triangleList2d != null)
            {
                triangleList2d.Decay = decay;
                triangleList2d.Sky = this.Astronomical;
                triangleList2d.TimeSeries = timeSeries;
                triangleList2d.JNow = jNow;
                triangleList2d.Draw(renderContext, opacity * Opacity, CullMode.Clockwise);
            }

            if (triangleList != null)
            {

                triangleList.Decay = decay;
                triangleList.Sky = this.Astronomical;
                triangleList.TimeSeries = timeSeries;
                triangleList.JNow = jNow;
                triangleList.Draw(renderContext, opacity * Opacity, CullMode.Clockwise);
            }

            if (pointList != null)
            {
                pointList.DepthBuffered = false;
                pointList.Decay = decay;
                pointList.Sky = this.Astronomical;
                pointList.TimeSeries = timeSeries;
                pointList.JNow = jNow;
                pointList.Draw(renderContext, opacity * Opacity, false);
            }

            if (lineList != null)
            {
                lineList.Sky = this.Astronomical;
                lineList.Decay = decay;
                lineList.TimeSeries = timeSeries;
                lineList.JNow = jNow;
                lineList.DrawLines(renderContext, opacity * Opacity);
            }

            if (lineList2d != null)
            {
                lineList2d.Sky = this.Astronomical;
                lineList2d.Decay = decay;
                lineList2d.TimeSeries = timeSeries;
                lineList2d.ShowFarSide = ShowFarSide;
                lineList2d.JNow = jNow;
                lineList2d.DrawLines(renderContext, opacity * Opacity);
            }

            //device.RenderState.AlphaBlendEnable = true;
            //device.RenderState.SourceBlend = Microsoft.DirectX.Direct3D.Blend.SourceAlpha;
            //device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.InvSourceAlpha;
            //device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlueAlpha;

            //TextureOperation oldTexOp = device.TextureState[0].ColorOperation;

            //bool zBufferEnabled = device.RenderState.ZBufferEnable;

            //if (astronomical && !bufferIsFlat)
            //{
            //    device.RenderState.ZBufferEnable = true;
            //}
            //else
            //{
            //    device.RenderState.ZBufferEnable = false;
            //}
            //device.TextureState[0].ColorOperation = TextureOperation.Disable;

            //FillMode oldMode = device.RenderState.FillMode;
            //DateTime baseDate = new DateTime(2010, 1, 1, 12, 00, 00);
            //device.RenderState.FillMode = FillMode.Solid;
            //device.SetTexture(0, null);
            //device.Indices = shapeFileIndex;
            //device.VertexShader = shaderA;
            //// Vector3 cam = Vector3d.TransformCoordinate(Earth3d.cameraPosition, Matrix3d.Invert(renderContext.World)).Vector3;
            //Vector3 cam = Vector3.TransformCoordinate(renderContext.CameraPosition.Vector3, Matrix.Invert(renderContext.Device.Transform.World));
            //constantTableA.SetValue(device, cameraHandleA, new Vector4(cam.X, cam.Y, cam.Z, 1));
            //constantTableA.SetValue(device, jNowHandleA, (float)(SpaceTimeController.JNow - SpaceTimeController.UtcToJulian(baseDate)));
            //constantTableA.SetValue(device, decayHandleA, timeSeries ? decay : 0f);

            //float adjustedScale = scaleFactor;

            //if (flat && astronomical && (markerScale == MarkerScales.World))
            //{
            //    adjustedScale = (float)(scaleFactor / (Earth3d.MainWindow.ZoomFactor / 360));
            //}
            //constantTableA.SetValue(device, scaleHandleA, (markerScale == MarkerScales.World) ? (float)adjustedScale : -(float)adjustedScale);
            //constantTableA.SetValue(device, skyHandleA, astronomical ? -1 : 1);
            //constantTableA.SetValue(device, opacityHandleA, opacity * this.Opacity);
            //constantTableA.SetValue(device, showFarSideHandleA, ShowFarSide ? 1f : 0f);

            //// Matrix matrixWVP = Earth3d.WorldMatrix * Earth3d.ViewMatrix * Earth3d.ProjMatrix;
            ////Matrix matrixWVP = device.Transform.World * device.Transform.View * device.Transform.Projection;
            //Matrix3d matrixWVP = renderContext.World * renderContext.View * renderContext.Projection;

            //constantTableA.SetValue(device, worldViewHandleA, matrixWVP.Matrix);

            //device.SetStreamSource(0, shapeFileVertex, 0);
            ////device.VertexFormat = VertexFormats.None;
            ////device.VertexDeclaration = vertexDeclA;
            //device.VertexFormat = PointVertex.Format;

            //device.RenderState.PointSpriteEnable = plotType != PlotTypes.Point;

            //device.RenderState.PointScaleEnable = (markerScale == MarkerScales.World && plotType != PlotTypes.Point) ? true : false;
            //device.RenderState.PointSize = 0;
            //device.RenderState.PointScaleA = 0;
            //device.RenderState.PointScaleB = 0;

            //device.RenderState.PointScaleC = 10000000f;

            //switch (plotType)
            //{
            //    case PlotTypes.Gaussian:
            //        device.SetTexture(0, Grids.StarProfile);
            //        break;
            //    case PlotTypes.Circle:
            //        device.SetTexture(0, CircleTexture);
            //        break;
            //    case PlotTypes.Point:
            //        device.SetTexture(0, null);
            //        break;
            //    //case PlotTypes.Square:
            //    //    device.SetTexture(0, null);
            //    //    break;
            //    //case PlotTypes.Custom:
            //    //    break;
            //    case PlotTypes.PushPin:
            //        device.SetTexture(0, PushPin.GetPushPinTexture(markerIndex));
            //        break;

            //    default:
            //        break;
            //}

            //device.RenderState.CullMode = Cull.None;
            //device.RenderState.AlphaBlendEnable = true;
            //device.RenderState.SourceBlend = Microsoft.DirectX.Direct3D.Blend.SourceAlpha;
            //if (plotType == PlotTypes.Gaussian)
            //{
            //    device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.One;
            //}
            //else
            //{
            //    device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.InvSourceAlpha;
            //}

            //device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlueAlpha;
            //device.TextureState[0].ColorOperation = TextureOperation.Modulate;
            //device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor;
            //device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse;
            //device.TextureState[0].AlphaOperation = TextureOperation.Modulate;
            //device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor;
            //device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse;

            //device.TextureState[1].ColorOperation = TextureOperation.Disable;
            //device.TextureState[1].ColorArgument1 = TextureArgument.Current;
            //device.TextureState[1].ColorArgument2 = TextureArgument.Constant;
            //device.TextureState[1].AlphaOperation = TextureOperation.Disable;
            //device.TextureState[1].AlphaArgument1 = TextureArgument.Current;
            //device.TextureState[1].AlphaArgument2 = TextureArgument.Constant;

            //device.TextureState[1].ConstantColor = Color.FromArgb(255, 255, 255, 255);
            ////                device.TextureState[1].ConstantColor = Color.FromArgb(0, 0, 0, 0);

            //device.DrawPrimitives(PrimitiveType.PointList, 0, shapeVertexCount);
            //device.RenderState.PointSpriteEnable = false;

            ////device.DrawUserPrimitives(PrimitiveType.LineList, segments, points);

            //device.RenderState.FillMode = oldMode;
            //device.TextureState[0].ColorOperation = oldTexOp;
            //device.VertexShader = null;

            //device.RenderState.ZBufferEnable = zBufferEnabled;
            //device.RenderState.AlphaBlendEnable = false;
            //device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlue;
            return true;
        }

        //protected static EffectHandle worldViewHandleA = null;
        //protected static EffectHandle cameraHandleA = null;
        //protected static EffectHandle jNowHandleA = null;
        //protected static EffectHandle decayHandleA = null;
        //protected static EffectHandle scaleHandleA = null;
        //protected static EffectHandle skyHandleA = null;
        //protected static EffectHandle opacityHandleA = null;
        //protected static EffectHandle showFarSideHandleA = null;
        //protected static ConstantTable constantTableA = null;
        //protected static VertexShader shaderA = null;
        //protected static VertexDeclaration vertexDeclA = null;

        //protected static void MakeVertexShaderA(Device device)
        //{
        //    // Create the vertex shader and declaration
        //    VertexElement[] elements = new VertexElement[]
        //        {
        //            new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
        //            new VertexElement(0, 0, DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.PointSize, 0),
        //            new VertexElement(0, 0, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0),
        //            new VertexElement(0, 0, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0),
        //            VertexElement.VertexDeclarationEnd
        //        };

        //    vertexDeclA = new VertexDeclaration(device, elements);

        //    ShaderFlags shaderFlags = 0;

        //    string errors;

        //    string shaderText =

        //            " float4x4 matWVP;              " +
        //            " float4 camPos : POSITION;                               " +
        //            " float1 jNow;                               " +
        //            " float1 decay;                               " +
        //            " float1 scale;                               " +
        //            " float1 opacity;                               " +
        //            " float1 sky;                         " +
        //            " float1 showFarSide;                         " +
        //            " struct VS_IN                                 " +
        //            " {                                            " +
        //            "     float4 ObjPos   : POSITION;              " + // Object space position
        //            "     float1 PointSize   : PSIZE;              " + // Object Point size
        //            "     float4 Color    : COLOR;                 " + // Vertex color
        //            "     float2 Time   : TEXCOORD0;              " + // Object Point size
        //            " };                                           " +
        //            "                                              " +
        //            " struct VS_OUT                                " +
        //            " {                                            " +
        //            "     float4 ProjPos  : POSITION;              " + // Projected space position
        //            "     float1 PointSize   : PSIZE;              " + // Object Point size
        //            "     float4 Color    : COLOR;                 " +
        //            "     float2 Time   : TEXCOORD0;              " + // Object Point size
        //            " };                                           " +
        //            "                                              " +
        //            " VS_OUT main( VS_IN In )                      " +
        //            " {                                            " +
        //            "     float dotCam = dot((camPos.xyz - In.ObjPos.xyz), In.ObjPos.xyz);   " +
        //            "     float dist = distance(In.ObjPos, camPos.xyz);   " +
        //            "     VS_OUT Out;                              " +
        //            "     float dAlpha = 1;                         " +
        //            "     if ( decay > 0)                           " +
        //            "     {                                        " +
        //            "          dAlpha = 1 - ((jNow - In.Time.y) / decay);          " +
        //            "          if (dAlpha > 1 )           " +
        //            "          {                                     " +
        //            "               dAlpha = 1;                     " +
        //            "          }                                    " +
        //            "                                               " +
        //            "     }                                        " +
        //            "     Out.ProjPos = mul(In.ObjPos,  matWVP );  " + // Transform vertex into
        //            "     if (showFarSide == 0 && (dotCam * sky) < 0 || (jNow < In.Time.x && decay > 0))   " +
        //            "     {                                        " +
        //            "        Out.Color.a = 0;                     " +
        //            "     }                                        " +
        //            "     else                                     " +
        //            "     {                                        " +
        //            "        Out.Color.a = In.Color.a * dAlpha * opacity;    " +
        //            "     }                                        " +
        //            "     Out.Color.r = In.Color.r;              " +
        //            "     Out.Color.g = In.Color.g;              " +
        //            "     Out.Color.b = In.Color.b;              " +
        //            "     Out.Time.x = 0;                        " +
        //            "     Out.Time.y = 0;                        " +
        //            "     if ( scale > 0)                           " +
        //            "     {                                        " +
        //            "       Out.PointSize = scale * (In.PointSize )/ dist;" +
        //            "     }                                        " +
        //            "     else                                     " +
        //            "     {                                        " +
        //            "       Out.PointSize = -scale *In.PointSize;" +
        //            "     }                                        " +
        //             " if (Out.PointSize > 256)                     " +
        //             " {                                            " +
        //             "      Out.PointSize = 256;                                        " +
        //             " }                                            " +
        //             "     return Out;                              " + // Transfer color
        //            " }                                            ";

        //    using (GraphicsStream code = ShaderLoader.CompileShader(shaderText, "main", null, null,
        //              "vs_2_0", shaderFlags, out errors, out constantTableA))
        //    {

        //        // We will store these constants in an effect handle here for performance reasons.
        //        // You could simply use the string value (i.e., "worldViewProj") in the SetValue call
        //        // and it would work just as well, but that actually requires an allocation to be made
        //        // and can actually slow your performance down.  It's much more efficient to simply
        //        // cache these handles for use later
        //        worldViewHandleA = constantTableA.GetConstant(null, "matWVP");
        //        cameraHandleA = constantTableA.GetConstant(null, "camPos");
        //        jNowHandleA = constantTableA.GetConstant(null, "jNow");
        //        decayHandleA = constantTableA.GetConstant(null, "decay");
        //        scaleHandleA = constantTableA.GetConstant(null, "scale");
        //        skyHandleA = constantTableA.GetConstant(null, "sky");
        //        opacityHandleA = constantTableA.GetConstant(null, "opacity");
        //        showFarSideHandleA = constantTableA.GetConstant(null, "showFarSide");

        //        // Create the shader
        //        shaderA = new VertexShader(device, code);
        //    }
        //}

        public override void CleanUp()
        {

            if (lineList != null)
            {
                lineList.Clear();
            }
            if (lineList2d != null)
            {
                lineList2d.Clear();
            }

            if (triangleList2d != null)
            {
                triangleList2d.Clear();
            }

            if (pointList != null)
            {
                pointList.Clear();
            }

            if (triangleList != null)
            {
                triangleList.Clear();
            }
        }

        public virtual bool DynamicUpdate()
        {
            return false;
        }
    }

}


text:
package org.apache.geode.internal.cache.tier.sockets;

import org.apache.geode.Statistics;
import org.apache.geode.StatisticsType;
import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.Scope;
import org.apache.geode.cache.client.PoolFactory;
import org.apache.geode.cache.client.PoolManager;
import org.apache.geode.cache.client.ServerConnectivityException;
import org.apache.geode.cache.client.internal.Connection;
import org.apache.geode.cache.client.internal.PoolImpl;
import org.apache.geode.cache.client.internal.ServerRegionProxy;
import org.apache.geode.cache.server.CacheServer;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.internal.AvailablePort;
import org.apache.geode.internal.cache.EventID;
import org.apache.geode.test.dunit.Wait;
import org.apache.geode.test.dunit.WaitCriterion;
import org.apache.geode.test.junit.categories.ClientServerTest;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.junit.After;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.util.Properties;

import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

/**
 * This is a functional-test for ClientHealthMonitor.
 *
 *
 */
@Category({IntegrationTest.class, ClientServerTest.class})
public class ClientHealthMonitorJUnitTest {
  /**
   * Default to 0; override in sub tests to add thread pool
   */
  protected int getMaxThreads() {
    return 0;
  }

  /** connection proxy object for the client */
  PoolImpl proxy = null;

  /** the distributed system instance for the test */
  DistributedSystem system;

  /** the cache instance for the test */
  Cache cache;

  /** name of the region created */
  final String regionName = "region1";

  private static int PORT;

  /**
   * Close the cache and disconnects from the distributed system
   */
  @After
  public void tearDown() throws Exception

  {
    removeExceptions();
    this.cache.close();
    this.system.disconnect();
  }

  /**
   * Initializes proxy object and creates region for client
   *
   */
  private void createProxyAndRegionForClient() {
    try {
      // props.setProperty("retryAttempts", "5");
      PoolFactory pf = PoolManager.createFactory();
      proxy = (PoolImpl) pf.addServer("localhost", PORT).setThreadLocalConnections(true)
          .setReadTimeout(10000).setPingInterval(10000).setMinConnections(0).create("junitPool");
      AttributesFactory factory = new AttributesFactory();
      factory.setScope(Scope.DISTRIBUTED_ACK);
      cache.createVMRegion(regionName, factory.createRegionAttributes());
    } catch (Exception ex) {
      ex.printStackTrace();
      fail("Failed to initialize client");
    }
  }

  private final static int TIME_BETWEEN_PINGS = 2500;

  /**
   * Creates and starts the server instance
   *
   */
  private int createServer() {
    CacheServer server = null;
    try {
      Properties p = new Properties();
      // make it a loner
      p.put(MCAST_PORT, "0");
      p.put(LOCATORS, "");

      this.system = DistributedSystem.connect(p);
      this.cache = CacheFactory.create(system);
      server = this.cache.addCacheServer();
      int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
      server.setMaximumTimeBetweenPings(TIME_BETWEEN_PINGS);
      server.setMaxThreads(getMaxThreads());
      server.setPort(port);
      server.start();
    } catch (Exception e) {
      e.printStackTrace();
      fail("Failed to create server");
    }
    return server.getPort();
  }

  /**
   * This test performs the following:

   * 1)create server

   * 2)initialize proxy object and create region for client

   * 3)perform a PUT on client by acquiring Connection through proxy

   * 4)stop server monitor threads in client to ensure that server treats this as dead client

   * 5)wait for some time to allow server to clean up the dead client artifacts

   * 6)again perform a PUT on client through same Connection and verify after the put that the
   * Connection object used was new one.
   */
  @Test
  public void testDeadClientRemovalByServer() throws Exception {
    PORT = createServer();
    createProxyAndRegionForClient();
    // String connection2String = null;
    StatisticsType st = this.system.findType("CacheServerStats");
    final Statistics s = this.system.findStatisticsByType(st)[0];
    assertEquals(0, s.getInt("currentClients"));
    assertEquals(0, s.getInt("currentClientConnections"));
    this.system.getLogWriter().info("beforeAcquireConnection clients=" + s.getInt("currentClients")
        + " cnxs=" + s.getInt("currentClientConnections"));
    Connection connection1 = proxy.acquireConnection();
    this.system.getLogWriter().info("afterAcquireConnection clients=" + s.getInt("currentClients")
        + " cnxs=" + s.getInt("currentClientConnections"));
    this.system.getLogWriter().info("acquired connection " + connection1);
    WaitCriterion ev = new WaitCriterion() {
      public boolean done() {
        return s.getInt("currentClients") != 0;
      }

      public String description() {
        return null;
      }
    };
    Wait.waitForCriterion(ev, 20 * 1000, 200, true);

    assertEquals(1, s.getInt("currentClients"));
    assertEquals(1, s.getInt("currentClientConnections"));
    // String connection1String = connection1.toString();
    ServerRegionProxy srp = new ServerRegionProxy("region1", proxy);
    srp.putOnForTestsOnly(connection1, "key-1", "value-1", new EventID(new byte[] {1}, 1, 1), null);
    this.system.getLogWriter().info("did put 1");
    // proxy.testfinalizeServerConnectionMonitor();
    ev = new WaitCriterion() {
      public boolean done() {
        return s.getInt("currentClients") == 0;
      }

      public String description() {
        return null;
      }
    };
    Wait.waitForCriterion(ev, TIME_BETWEEN_PINGS * 5, 200, true);

    {
      this.system.getLogWriter().info("currentClients=" + s.getInt("currentClients")
          + " currentClientConnections=" + s.getInt("currentClientConnections"));
      assertEquals(0, s.getInt("currentClients"));
      assertEquals(0, s.getInt("currentClientConnections"));
    }
    addExceptions();
    // the connection should now fail since the server timed it out
    try {
      srp.putOnForTestsOnly(connection1, "key-1", "fail", new EventID(new byte[] {1}, 1, 2), null);
      fail("expected EOF");
    } catch (ServerConnectivityException expected) {
    }
    // The rest of this test no longer works.
    // connection1.finalizeConnection();
    // proxy.release();

    // connection1 = proxy.acquireConnection();
    // connection2String = connection1.toString();
    // this.system.getLogWriter().info("connection is now " + connection2String);

    // if (connection1String.equals(connection2String)) {
    // fail("New connection object was not obtained");
    // }
    // connection1.putObject("region1", "key-1", "value-2", new EventID(new byte[] {1},1,3), null);
    // this.system.getLogWriter().info("did put 2");
    // assertIndexDetailsEquals(1, s.getInt("currentClients"));
    // assertIndexDetailsEquals(1, s.getInt("currentClientConnections"));

    // // now lets see what happens when we close our connection
    // // note we use a nasty close which just closes the socket instead
    // // of sending a nice message to the server telling him we are going away
    // ((ConnectionImpl)connection1).finalizeConnection();
    // {
    // int retry = (TIME_BETWEEN_PINGS*5) / 100;
    // while (s.getInt("currentClients") > 0 && retry-- > 0) {
    // Thread.sleep(100);
    // }
    // this.system.getLogWriter().info("currentClients="
    // + s.getInt("currentClients")
    // + " currentClientConnections="
    // + s.getInt("currentClientConnections"));
    // assertIndexDetailsEquals(0, s.getInt("currentClients"));
    // assertIndexDetailsEquals(0, s.getInt("currentClientConnections"));
    // }
  }

  public void addExceptions() throws Exception {
    if (this.system != null) {
      this.system.getLogWriter()
          .info("<ExpectedException action=add>" + "java.io.EOFException" + "</ExpectedException>");
    }
  }

  public void removeExceptions() {
    if (this.system != null) {
      this.system.getLogWriter().info(
          "<ExpectedException action=remove>" + "java.io.EOFException" + "</ExpectedException>");
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.sirix.service.xml.xpath.functions;

import java.util.List;
import org.sirix.api.Axis;
import org.sirix.api.xml.XmlNodeReadOnlyTrx;
import org.sirix.exception.SirixXPathException;
import org.sirix.service.xml.xpath.AtomicValue;
import org.sirix.service.xml.xpath.EXPathError;
import org.sirix.service.xml.xpath.expr.AbstractExpression;

/**
 *

 * Abstract super class for all function classes.
 *

 *

 * All functions that extend the abstract class only need take care of the result computation.
 * Everything else, like checking if arguments are valid and adding the result with the
 * corresponding type to the transaction list is done by the abstract super class.
 *

 *
Developer Example

 *
 *
 *

 *   Must extend <code>AbstractFunction</code> and implement <code>IAxis</code>.
 *   And the implement the abstract method computeResult(), that returns the
 *   computed value as a bye-array
 *
 *
 *
 *   public class ExampleFunctionAxis extends AbstractFunction implements IAxis {
 *
 *     public ExampleAxis(final IReadTransaction rtx, final List<IAxis> args,
 *       final int min, final int max, final int returnType) {
 *       // Must be called as first.
 *       super(rtx, args, min, max, returnType);
 *     }
 *     protected byte[] computeResult() {
 *       .... compute value and return as byte array
 *     }
 *
 *   }
 *

 *
 */
public abstract class AbstractFunction extends AbstractExpression {

  /** The function's arguments. */
  private final List<Axis> mArgs;

  /** Minimum number of possible function arguments. */
  private final int mMin;

  /** Maximum number of possible function arguments. */
  private final int mMax;

  /** The function's return type. */
  private final int mReturnType;

  /**
   * Constructor. Initializes internal state and do a statical analysis concerning the function's
   * arguments.
   *
   * @param rtx Transaction to operate on
   * @param args List of function arguments
   * @param min min number of allowed function arguments
   * @param max max number of allowed function arguments
   * @param returnType the type that the function's result will have
   * @throws SirixXPathException if the verify process is failing.
   */
  public AbstractFunction(final XmlNodeReadOnlyTrx rtx, final List<Axis> args, final int min,
      final int max, final int returnType) throws SirixXPathException {

    super(rtx);
    mArgs = args;
    mMin = min;
    mMax = max;
    mReturnType = returnType;
    varifyParam(args.size());
  }

  /**
   * Checks if the number of input arguments of this function is a valid according to the function
   * specification in  XQuery 1.0 and XPath 2.0
   * Functions and Operators. Throws an XPath error in case of a non-valid number.
   *
   * @param mNumber number of given function arguments
   * @throws SirixXPathException if function call fails.
   */
  public final void varifyParam(final int mNumber) throws SirixXPathException {

    if (mNumber < mMin || mNumber > mMax) {
      throw EXPathError.XPST0017.getEncapsulatedException();
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void reset(final long mNodeKey) {

    super.reset(mNodeKey);
    if (mArgs != null) {
      for (Axis ax : mArgs) {
        ax.reset(mNodeKey);
      }
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void evaluate() throws SirixXPathException {

    // compute the function's result
    final byte[] value = computeResult();

    // create an atomic value, add it to the list and move the cursor to it.
    final int itemKey = asXmlNodeReadTrx().getItemList().addItem(new AtomicValue(value, mReturnType));
    key = itemKey;

  }

  /**
   * Computes the result value of the function. This implementation is acts as a hook operation and
   * needs to be overridden by the concrete function classes, otherwise an exception is thrown.
   *
   * @return value of the result
   * @throws SirixXPathException if anythin odd happens while execution
   */
  protected abstract byte[] computeResult() throws SirixXPathException;

  /**
   * Get all the arguments provided to the function
   * @return the list of function arguments
   */
  protected List<Axis> getArgs() {
    return mArgs;
  }

}


text:
package model

import (
	"crypto/sha1"
	"encoding/hex"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"sort"
	"strings"
	"unicode/utf8"
)

type ChannelType string

const (
	ChannelTypeOpen    ChannelType = "O"
	ChannelTypePrivate ChannelType = "P"
	ChannelTypeDirect  ChannelType = "D"
	ChannelTypeGroup   ChannelType = "G"

	ChannelGroupMaxUsers       = 8
	ChannelGroupMinUsers       = 3
	DefaultChannelName         = "town-square"
	ChannelDisplayNameMaxRunes = 64
	ChannelNameMinLength       = 1
	ChannelNameMaxLength       = 64
	ChannelHeaderMaxRunes      = 1024
	ChannelPurposeMaxRunes     = 250
	ChannelCacheSize           = 25000

	ChannelSortByUsername = "username"
	ChannelSortByStatus   = "status"
)

type Channel struct {
	Id                string                 `json:"id"`
	CreateAt          int64                  `json:"create_at"`
	UpdateAt          int64                  `json:"update_at"`
	DeleteAt          int64                  `json:"delete_at"`
	TeamId            string                 `json:"team_id"`
	Type              ChannelType            `json:"type"`
	DisplayName       string                 `json:"display_name"`
	Name              string                 `json:"name"`
	Header            string                 `json:"header"`
	Purpose           string                 `json:"purpose"`
	LastPostAt        int64                  `json:"last_post_at"`
	TotalMsgCount     int64                  `json:"total_msg_count"`
	ExtraUpdateAt     int64                  `json:"extra_update_at"`
	CreatorId         string                 `json:"creator_id"`
	SchemeId          *string                `json:"scheme_id"`
	Props             map[string]interface{} `json:"props"`
	GroupConstrained  *bool                  `json:"group_constrained"`
	Shared            *bool                  `json:"shared"`
	TotalMsgCountRoot int64                  `json:"total_msg_count_root"`
	PolicyID          *string                `json:"policy_id"`
	LastRootPostAt    int64                  `json:"last_root_post_at"`
}

type ChannelWithTeamData struct {
	Channel
	TeamDisplayName string `json:"team_display_name"`
	TeamName        string `json:"team_name"`
	TeamUpdateAt    int64  `json:"team_update_at"`
}

type ChannelsWithCount struct {
	Channels   ChannelListWithTeamData `json:"channels"`
	TotalCount int64                   `json:"total_count"`
}

type ChannelPatch struct {
	DisplayName      *string `json:"display_name"`
	Name             *string `json:"name"`
	Header           *string `json:"header"`
	Purpose          *string `json:"purpose"`
	GroupConstrained *bool   `json:"group_constrained"`
}

type ChannelForExport struct {
	Channel
	TeamName   string
	SchemeName *string
}

type DirectChannelForExport struct {
	Channel
	Members *[]string
}

type ChannelModeration struct {
	Name  string                 `json:"name"`
	Roles *ChannelModeratedRoles `json:"roles"`
}

type ChannelModeratedRoles struct {
	Guests  *ChannelModeratedRole `json:"guests"`
	Members *ChannelModeratedRole `json:"members"`
}

type ChannelModeratedRole struct {
	Value   bool `json:"value"`
	Enabled bool `json:"enabled"`
}

type ChannelModerationPatch struct {
	Name  *string                     `json:"name"`
	Roles *ChannelModeratedRolesPatch `json:"roles"`
}

type ChannelModeratedRolesPatch struct {
	Guests  *bool `json:"guests"`
	Members *bool `json:"members"`
}

// ChannelSearchOpts contains options for searching channels.
//
// NotAssociatedToGroup will exclude channels that have associated, active GroupChannels records.
// ExcludeDefaultChannels will exclude the configured default channels (ex 'town-square' and 'off-topic').
// IncludeDeleted will include channel records where DeleteAt != 0.
// ExcludeChannelNames will exclude channels from the results by name.
// Paginate whether to paginate the results.
// Page page requested, if results are paginated.
// PerPage number of results per page, if paginated.
//
type ChannelSearchOpts struct {
	NotAssociatedToGroup     string
	ExcludeDefaultChannels   bool
	IncludeDeleted           bool
	Deleted                  bool
	ExcludeChannelNames      []string
	TeamIds                  []string
	GroupConstrained         bool
	ExcludeGroupConstrained  bool
	PolicyID                 string
	ExcludePolicyConstrained bool
	IncludePolicyID          bool
	Public                   bool
	Private                  bool
	Page                     *int
	PerPage                  *int
	LastDeleteAt             int
	LastUpdateAt             int
}

type ChannelMemberCountByGroup struct {
	GroupId                     string `json:"group_id"`
	ChannelMemberCount          int64  `json:"channel_member_count"`
	ChannelMemberTimezonesCount int64  `json:"channel_member_timezones_count"`
}

type ChannelOption func(channel *Channel)

func WithID(ID string) ChannelOption {
	return func(channel *Channel) {
		channel.Id = ID
	}
}

// The following are some GraphQL methods necessary to return the
// data in float64 type. The spec doesn't support 64 bit integers,
// so we have to pass the data in float64. The _ at the end is
// a hack to keep the attribute name same in GraphQL schema.

func (o *Channel) CreateAt_() float64 {
	return float64(o.CreateAt)
}

func (o *Channel) UpdateAt_() float64 {
	return float64(o.UpdateAt)
}

func (o *Channel) DeleteAt_() float64 {
	return float64(o.DeleteAt)
}

func (o *Channel) LastPostAt_() float64 {
	return float64(o.LastPostAt)
}

func (o *Channel) TotalMsgCount_() float64 {
	return float64(o.TotalMsgCount)
}

func (o *Channel) DeepCopy() *Channel {
	copy := *o
	if copy.SchemeId != nil {
		copy.SchemeId = NewString(*o.SchemeId)
	}
	return &copy
}

func (o *Channel) Etag() string {
	return Etag(o.Id, o.UpdateAt)
}

func (o *Channel) IsValid() *AppError {
	if !IsValidId(o.Id) {
		return NewAppError("Channel.IsValid", "model.channel.is_valid.id.app_error", nil, "", http.StatusBadRequest)
	}

	if o.CreateAt == 0 {
		return NewAppError("Channel.IsValid", "model.channel.is_valid.create_at.app_error", nil, "id="+o.Id, http.StatusBadRequest)
	}

	if o.UpdateAt == 0 {
		return NewAppError("Channel.IsValid", "model.channel.is_valid.update_at.app_error", nil, "id="+o.Id, http.StatusBadRequest)
	}

	if utf8.RuneCountInString(o.DisplayName) > ChannelDisplayNameMaxRunes {
		return NewAppError("Channel.IsValid", "model.channel.is_valid.display_name.app_error", nil, "id="+o.Id, http.StatusBadRequest)
	}

	if !IsValidChannelIdentifier(o.Name) {
		return NewAppError("Channel.IsValid", "model.channel.is_valid.1_or_more.app_error", nil, "id="+o.Id, http.StatusBadRequest)
	}

	if !(o.Type == ChannelTypeOpen || o.Type == ChannelTypePrivate || o.Type == ChannelTypeDirect || o.Type == ChannelTypeGroup) {
		return NewAppError("Channel.IsValid", "model.channel.is_valid.type.app_error", nil, "id="+o.Id, http.StatusBadRequest)
	}

	if utf8.RuneCountInString(o.Header) > ChannelHeaderMaxRunes {
		return NewAppError("Channel.IsValid", "model.channel.is_valid.header.app_error", nil, "id="+o.Id, http.StatusBadRequest)
	}

	if utf8.RuneCountInString(o.Purpose) > ChannelPurposeMaxRunes {
		return NewAppError("Channel.IsValid", "model.channel.is_valid.purpose.app_error", nil, "id="+o.Id, http.StatusBadRequest)
	}

	if len(o.CreatorId) > 26 {
		return NewAppError("Channel.IsValid", "model.channel.is_valid.creator_id.app_error", nil, "", http.StatusBadRequest)
	}

	userIds := strings.Split(o.Name, "__")
	if o.Type != ChannelTypeDirect && len(userIds) == 2 && IsValidId(userIds[0]) && IsValidId(userIds[1]) {
		return NewAppError("Channel.IsValid", "model.channel.is_valid.name.app_error", nil, "", http.StatusBadRequest)
	}

	return nil
}

func (o *Channel) PreSave() {
	if o.Id == "" {
		o.Id = NewId()
	}

	o.Name = SanitizeUnicode(o.Name)
	o.DisplayName = SanitizeUnicode(o.DisplayName)

	o.CreateAt = GetMillis()
	o.UpdateAt = o.CreateAt
	o.ExtraUpdateAt = 0
}

func (o *Channel) PreUpdate() {
	o.UpdateAt = GetMillis()
	o.Name = SanitizeUnicode(o.Name)
	o.DisplayName = SanitizeUnicode(o.DisplayName)
}

func (o *Channel) IsGroupOrDirect() bool {
	return o.Type == ChannelTypeDirect || o.Type == ChannelTypeGroup
}

func (o *Channel) IsOpen() bool {
	return o.Type == ChannelTypeOpen
}

func (o *Channel) Patch(patch *ChannelPatch) {
	if patch.DisplayName != nil {
		o.DisplayName = *patch.DisplayName
	}

	if patch.Name != nil {
		o.Name = *patch.Name
	}

	if patch.Header != nil {
		o.Header = *patch.Header
	}

	if patch.Purpose != nil {
		o.Purpose = *patch.Purpose
	}

	if patch.GroupConstrained != nil {
		o.GroupConstrained = patch.GroupConstrained
	}
}

func (o *Channel) MakeNonNil() {
	if o.Props == nil {
		o.Props = make(map[string]interface{})
	}
}

func (o *Channel) AddProp(key string, value interface{}) {
	o.MakeNonNil()

	o.Props[key] = value
}

func (o *Channel) IsGroupConstrained() bool {
	return o.GroupConstrained != nil && *o.GroupConstrained
}

func (o *Channel) IsShared() bool {
	return o.Shared != nil && *o.Shared
}

func (o *Channel) GetOtherUserIdForDM(userId string) string {
	if o.Type != ChannelTypeDirect {
		return ""
	}

	userIds := strings.Split(o.Name, "__")

	var otherUserId string

	if userIds[0] != userIds[1] {
		if userIds[0] == userId {
			otherUserId = userIds[1]
		} else {
			otherUserId = userIds[0]
		}
	}

	return otherUserId
}

func (ChannelType) ImplementsGraphQLType(name string) bool {
	return name == "ChannelType"
}

func (t ChannelType) MarshalJSON() ([]byte, error) {
	return json.Marshal(string(t))
}

func (t *ChannelType) UnmarshalGraphQL(input interface{}) error {
	chType, ok := input.(string)
	if !ok {
		return errors.New("wrong type")
	}

	*t = ChannelType(chType)
	return nil
}

func GetDMNameFromIds(userId1, userId2 string) string {
	if userId1 > userId2 {
		return userId2 + "__" + userId1
	}
	return userId1 + "__" + userId2
}

func GetGroupDisplayNameFromUsers(users []*User, truncate bool) string {
	usernames := make([]string, len(users))
	for index, user := range users {
		usernames[index] = user.Username
	}

	sort.Strings(usernames)

	name := strings.Join(usernames, ", ")

	if truncate && len(name) > ChannelNameMaxLength {
		name = name[:ChannelNameMaxLength]
	}

	return name
}

func GetGroupNameFromUserIds(userIds []string) string {
	sort.Strings(userIds)

	h := sha1.New()
	for _, id := range userIds {
		io.WriteString(h, id)
	}

	return hex.EncodeToString(h.Sum(nil))
}


text:
<?php

class Crunchbutton_Order_Logistics_Communityspeed extends Cana_Table
{
    const DEFAULT_MPH = 25;

    public function __construct($id = null)
    {
        parent::__construct();
        $this
            ->table('order_logistics_communityspeed')
            ->idVar('id_order_logistics_communityspeed')
            ->load($id);
    }
}


text:
package org.apache.helix.controller.rebalancer.waged.constraints;

import java.util.List;

import org.apache.helix.controller.rebalancer.waged.model.AssignableNode;
import org.apache.helix.controller.rebalancer.waged.model.AssignableReplica;
import org.apache.helix.controller.rebalancer.waged.model.ClusterContext;

class ReplicaActivateConstraint extends HardConstraint {
  @Override
  boolean isAssignmentValid(AssignableNode node, AssignableReplica replica,
      ClusterContext clusterContext) {
    List<String> disabledPartitions =
        node.getDisabledPartitionsMap().get(replica.getResourceName());
    return disabledPartitions == null || !disabledPartitions.contains(replica.getPartitionName());
  }

  @Override
  String getDescription() {
    return "Cannot assign the inactive replica";
  }
}


text:
ARG RUNC_VERSION=v1.1.3
ARG CONTAINERD_VERSION=v1.6.6
# containerd v1.5 for integration tests
ARG CONTAINERD_ALT_VERSION_15=v1.5.11
# containerd v1.4 for integration tests
ARG CONTAINERD_ALT_VERSION_14=v1.4.13
# BUILDKIT_TARGET defines buildkitd worker mode (buildkitd, buildkitd.oci_only, buildkitd.containerd_only)
ARG BUILDKIT_TARGET=buildkitd
ARG REGISTRY_VERSION=2.8.0
ARG ROOTLESSKIT_VERSION=v0.14.6
ARG CNI_VERSION=v1.1.0
ARG STARGZ_SNAPSHOTTER_VERSION=v0.11.4
ARG NERDCTL_VERSION=v0.17.1

# ALPINE_VERSION sets version for the base layers
ARG ALPINE_VERSION=3.15

# git stage is used for checking out remote repository sources
FROM --platform=$BUILDPLATFORM alpine:${ALPINE_VERSION} AS git
RUN apk add --no-cache git

# xx is a helper for cross-compilation
FROM --platform=$BUILDPLATFORM tonistiigi/xx@sha256:1e96844fadaa2f9aea021b2b05299bc02fe4c39a92d8e735b93e8e2b15610128 AS xx

FROM --platform=$BUILDPLATFORM golang:1.18-alpine AS golatest

# gobuild is base stage for compiling go/cgo
FROM golatest AS gobuild-base
RUN apk add --no-cache file bash clang lld pkgconfig git make
COPY --link --from=xx / /

# runc source
FROM git AS runc-src
ARG RUNC_VERSION
WORKDIR /usr/src
RUN git clone https://github.com/opencontainers/runc.git runc \
  && cd runc && git checkout -q "$RUNC_VERSION"

# build runc binary
FROM gobuild-base AS runc
WORKDIR $GOPATH/src/github.com/opencontainers/runc
ARG TARGETPLATFORM
# gcc is only installed for libgcc
# lld has issues building static binaries for ppc so prefer ld for it
RUN set -e; xx-apk add musl-dev gcc libseccomp-dev libseccomp-static; \
  [ "$(xx-info arch)" != "ppc64le" ] || XX_CC_PREFER_LINKER=ld xx-clang --setup-target-triple
RUN --mount=from=runc-src,src=/usr/src/runc,target=. --mount=target=/root/.cache,type=cache \
  CGO_ENABLED=1 xx-go build -mod=vendor -ldflags '-extldflags -static' -tags 'apparmor seccomp netgo cgo static_build osusergo' -o /usr/bin/runc ./ && \
  xx-verify --static /usr/bin/runc

FROM gobuild-base AS buildkit-base
WORKDIR /src
ENV GOFLAGS=-mod=vendor

# scan the version/revision info
FROM buildkit-base AS buildkit-version
# TODO: PKG should be inferred from go modules
RUN --mount=target=. \
  PKG=github.com/moby/buildkit VERSION=$(git describe --match 'v[0-9]*' --dirty='.m' --always --tags) REVISION=$(git rev-parse HEAD)$(if ! git diff --no-ext-diff --quiet --exit-code; then echo .m; fi); \
  echo "-X ${PKG}/version.Version=${VERSION} -X ${PKG}/version.Revision=${REVISION} -X ${PKG}/version.Package=${PKG}" | tee /tmp/.ldflags; \
  echo -n "${VERSION}" | tee /tmp/.version;

# build buildctl binary
FROM buildkit-base AS buildctl
ENV CGO_ENABLED=0
ARG TARGETPLATFORM
RUN --mount=target=. --mount=target=/root/.cache,type=cache \
  --mount=target=/go/pkg/mod,type=cache \
  --mount=source=/tmp/.ldflags,target=/tmp/.ldflags,from=buildkit-version \
  xx-go build -ldflags "$(cat /tmp/.ldflags)" -o /usr/bin/buildctl ./cmd/buildctl && \
  xx-verify --static /usr/bin/buildctl

# build buildkitd binary
FROM buildkit-base AS buildkitd
# BUILDKITD_TAGS defines additional Go build tags for compiling buildkitd
ARG BUILDKITD_TAGS
ARG TARGETPLATFORM
RUN --mount=target=. --mount=target=/root/.cache,type=cache \
  --mount=target=/go/pkg/mod,type=cache \
  --mount=source=/tmp/.ldflags,target=/tmp/.ldflags,from=buildkit-version \
  CGO_ENABLED=0 xx-go build -ldflags "$(cat /tmp/.ldflags) -extldflags '-static'" -tags "osusergo netgo static_build seccomp ${BUILDKITD_TAGS}" -o /usr/bin/buildkitd ./cmd/buildkitd && \
  xx-verify --static /usr/bin/buildkitd

FROM scratch AS binaries-linux-helper
COPY --link --from=runc /usr/bin/runc /buildkit-runc
# built from https://github.com/tonistiigi/binfmt/releases/tag/buildkit%2Fv6.2.0-24
COPY --link --from=tonistiigi/binfmt:buildkit@sha256:ea7632b4e0b2406db438730c604339b38c23ac51a2f73c89ba50abe5e2146b4b / /
FROM binaries-linux-helper AS binaries-linux
COPY --link --from=buildctl /usr/bin/buildctl /
COPY --link --from=buildkitd /usr/bin/buildkitd /

FROM scratch AS binaries-darwin
COPY --link --from=buildctl /usr/bin/buildctl /

FROM scratch AS binaries-windows
COPY --link --from=buildctl /usr/bin/buildctl /buildctl.exe

FROM binaries-$TARGETOS AS binaries

FROM --platform=$BUILDPLATFORM alpine:${ALPINE_VERSION} AS releaser
RUN apk add --no-cache tar gzip
WORKDIR /work
ARG TARGETPLATFORM
RUN --mount=from=binaries \
  --mount=source=/tmp/.version,target=/tmp/.version,from=buildkit-version \
  mkdir -p /out && tar czvf "/out/buildkit-$(cat /tmp/.version).$(echo $TARGETPLATFORM | sed 's/\//-/g').tar.gz" --mtime='2015-10-21 00:00Z' --sort=name --transform 's/^./bin/' .

FROM scratch AS release
COPY --link --from=releaser /out/ /

# tonistiigi/alpine supports riscv64
FROM tonistiigi/alpine:${ALPINE_VERSION} AS buildkit-export
RUN apk add --no-cache fuse3 git openssh pigz xz \
  && ln -s fusermount3 /usr/bin/fusermount
COPY --link examples/buildctl-daemonless/buildctl-daemonless.sh /usr/bin/
VOLUME /var/lib/buildkit

FROM git AS containerd-src
ARG CONTAINERD_VERSION
ARG CONTAINERD_ALT_VERSION
WORKDIR /usr/src
RUN git clone https://github.com/containerd/containerd.git containerd

FROM gobuild-base AS containerd-base
WORKDIR /go/src/github.com/containerd/containerd
ARG TARGETPLATFORM
ENV CGO_ENABLED=1 BUILDTAGS=no_btrfs GO111MODULE=off
RUN xx-apk add musl-dev gcc && xx-go --wrap

FROM containerd-base AS containerd
ARG CONTAINERD_VERSION
RUN --mount=from=containerd-src,src=/usr/src/containerd,readwrite --mount=target=/root/.cache,type=cache \
  git fetch origin \
  && git checkout -q "$CONTAINERD_VERSION" \
  && make bin/containerd \
  && make bin/containerd-shim-runc-v2 \
  && make bin/ctr \
  && mv bin /out

# containerd v1.5 for integration tests
FROM containerd-base as containerd-alt-15
ARG CONTAINERD_ALT_VERSION_15
RUN --mount=from=containerd-src,src=/usr/src/containerd,readwrite --mount=target=/root/.cache,type=cache \
  git fetch origin \
  && git checkout -q "$CONTAINERD_ALT_VERSION_15" \
  && make bin/containerd \
  && make bin/containerd-shim-runc-v2 \
  && mv bin /out

# containerd v1.4 for integration tests
FROM containerd-base as containerd-alt-14
ARG CONTAINERD_ALT_VERSION_14
RUN --mount=from=containerd-src,src=/usr/src/containerd,readwrite --mount=target=/root/.cache,type=cache \
  git fetch origin \
  && git checkout -q "$CONTAINERD_ALT_VERSION_14" \
  && make bin/containerd \
  && make bin/containerd-shim-runc-v2 \
  && mv bin /out

ARG REGISTRY_VERSION
FROM registry:$REGISTRY_VERSION AS registry

FROM gobuild-base AS rootlesskit
ARG ROOTLESSKIT_VERSION
RUN git clone https://github.com/rootless-containers/rootlesskit.git /go/src/github.com/rootless-containers/rootlesskit
WORKDIR /go/src/github.com/rootless-containers/rootlesskit
ARG TARGETPLATFORM
RUN  --mount=target=/root/.cache,type=cache \
  git checkout -q "$ROOTLESSKIT_VERSION"  && \
  CGO_ENABLED=0 xx-go build -o /rootlesskit ./cmd/rootlesskit && \
  xx-verify --static /rootlesskit

FROM gobuild-base AS stargz-snapshotter
ARG STARGZ_SNAPSHOTTER_VERSION
RUN git clone https://github.com/containerd/stargz-snapshotter.git /go/src/github.com/containerd/stargz-snapshotter
WORKDIR /go/src/github.com/containerd/stargz-snapshotter
ARG TARGETPLATFORM
RUN --mount=target=/root/.cache,type=cache \
  git checkout -q "$STARGZ_SNAPSHOTTER_VERSION" && \
  xx-go --wrap && \
  mkdir /out && CGO_ENABLED=0 PREFIX=/out/ make && \
  xx-verify --static /out/containerd-stargz-grpc && \
  xx-verify --static /out/ctr-remote

# Copy together all binaries needed for oci worker mode
FROM buildkit-export AS buildkit-buildkitd.oci_only
COPY --link --from=buildkitd.oci_only /usr/bin/buildkitd.oci_only /usr/bin/
COPY --link --from=buildctl /usr/bin/buildctl /usr/bin/
ENTRYPOINT ["buildkitd.oci_only"]

# Copy together all binaries for containerd worker mode
FROM buildkit-export AS buildkit-buildkitd.containerd_only
COPY --link --from=buildkitd.containerd_only /usr/bin/buildkitd.containerd_only /usr/bin/
COPY --link --from=buildctl /usr/bin/buildctl /usr/bin/
ENTRYPOINT ["buildkitd.containerd_only"]

# Copy together all binaries for oci+containerd mode
FROM buildkit-export AS buildkit-buildkitd-linux
COPY --link --from=binaries / /usr/bin/
ENTRYPOINT ["buildkitd"]

FROM binaries AS buildkit-buildkitd-darwin

FROM binaries AS buildkit-buildkitd-windows
# this is not in binaries-windows because it is not intended for release yet, just CI
COPY --link --from=buildkitd /usr/bin/buildkitd /buildkitd.exe

FROM buildkit-buildkitd-$TARGETOS AS buildkit-buildkitd

FROM alpine:${ALPINE_VERSION} AS containerd-runtime
COPY --link --from=runc /usr/bin/runc /usr/bin/
COPY --link --from=containerd /out/containerd* /usr/bin/
COPY --link --from=containerd /out/ctr /usr/bin/
VOLUME /var/lib/containerd
VOLUME /run/containerd
ENTRYPOINT ["containerd"]

FROM --platform=$BUILDPLATFORM alpine:${ALPINE_VERSION} AS cni-plugins
RUN apk add --no-cache curl
ARG CNI_VERSION
ARG TARGETOS
ARG TARGETARCH
WORKDIR /opt/cni/bin
RUN curl -Ls https://github.com/containernetworking/plugins/releases/download/$CNI_VERSION/cni-plugins-$TARGETOS-$TARGETARCH-$CNI_VERSION.tgz | tar xzv

FROM buildkit-base AS integration-tests-base
ENV BUILDKIT_INTEGRATION_ROOTLESS_IDPAIR="1000:1000"
ARG NERDCTL_VERSION
RUN apk add --no-cache shadow shadow-uidmap sudo vim iptables fuse curl \
  && useradd --create-home --home-dir /home/user --uid 1000 -s /bin/sh user \
  && echo "XDG_RUNTIME_DIR=/run/user/1000; export XDG_RUNTIME_DIR" >> /home/user/.profile \
  && mkdir -m 0700 -p /run/user/1000 \
  && chown -R user /run/user/1000 /home/user \
  && ln -s /sbin/iptables-legacy /usr/bin/iptables \
  && xx-go --wrap \
  && curl -Ls https://raw.githubusercontent.com/containerd/nerdctl/$NERDCTL_VERSION/extras/rootless/containerd-rootless.sh > /usr/bin/containerd-rootless.sh \
  && chmod 0755 /usr/bin/containerd-rootless.sh
# musl is needed to directly use the registry binary that is built on alpine
ENV BUILDKIT_INTEGRATION_CONTAINERD_EXTRA="containerd-1.4=/opt/containerd-alt-14/bin,containerd-1.5=/opt/containerd-alt-15/bin"
ENV BUILDKIT_INTEGRATION_SNAPSHOTTER=stargz
ENV CGO_ENABLED=0
COPY --link --from=stargz-snapshotter /out/* /usr/bin/
COPY --link --from=rootlesskit /rootlesskit /usr/bin/
COPY --link --from=containerd-alt-14 /out/containerd* /opt/containerd-alt-14/bin/
COPY --link --from=containerd-alt-15 /out/containerd* /opt/containerd-alt-15/bin/
COPY --link --from=registry /bin/registry /usr/bin/
COPY --link --from=runc /usr/bin/runc /usr/bin/
COPY --link --from=containerd /out/containerd* /usr/bin/
COPY --link --from=cni-plugins /opt/cni/bin/bridge /opt/cni/bin/host-local /opt/cni/bin/loopback /opt/cni/bin/
COPY --link hack/fixtures/cni.json /etc/buildkit/cni.json
COPY --link --from=binaries / /usr/bin/

# integration-tests prepares an image suitable for running all tests
FROM integration-tests-base AS integration-tests
COPY . .
ENV BUILDKIT_RUN_NETWORK_INTEGRATION_TESTS=1 BUILDKIT_CNI_INIT_LOCK_PATH=/run/buildkit_cni_bridge.lock

FROM integration-tests AS dev-env
VOLUME /var/lib/buildkit

# Rootless mode.
FROM tonistiigi/alpine:${ALPINE_VERSION} AS rootless
RUN apk add --no-cache fuse3 fuse-overlayfs git openssh pigz shadow-uidmap xz
RUN adduser -D -u 1000 user \
  && mkdir -p /run/user/1000 /home/user/.local/tmp /home/user/.local/share/buildkit \
  && chown -R user /run/user/1000 /home/user \
  && echo user:100000:65536 | tee /etc/subuid | tee /etc/subgid
COPY --link --from=rootlesskit /rootlesskit /usr/bin/
COPY --link --from=binaries / /usr/bin/
COPY --link examples/buildctl-daemonless/buildctl-daemonless.sh /usr/bin/
# Kubernetes runAsNonRoot requires USER to be numeric
USER 1000:1000
ENV HOME /home/user
ENV USER user
ENV XDG_RUNTIME_DIR=/run/user/1000
ENV TMPDIR=/home/user/.local/tmp
ENV BUILDKIT_HOST=unix:///run/user/1000/buildkit/buildkitd.sock
VOLUME /home/user/.local/share/buildkit
ENTRYPOINT ["rootlesskit", "buildkitd"]

# buildkit builds the buildkit container image
FROM buildkit-${BUILDKIT_TARGET} AS buildkit


text:
<?php

class OldNotificationRepository extends \Doctrine\ORM\EntityRepository
{

}


text:
package org.jvmmonitor.internal.core;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.management.ObjectName;

import org.jvmmonitor.core.mbean.IMonitoredMXBeanAttribute;

/**
 * The monitored MXBean attributes.
 */
public class MonitoredMXBeanAttribute implements IMonitoredMXBeanAttribute {

    /** The number of durations. */
    private static final long NUM_OF_DURATIONS = 500;

    /** The object name. */
    private ObjectName objectName;

    /** The attribute name. */
    private String atributeName;

    /** The attribute values. */
    private List<Number> values;

    /** The time values. */
    private List<Date> dates;

    /** The previous duration index. */
    private int previousDurationIndex;

    /** The RGB. */
    private int[] rgb;

    /**
     * The constructor.
     *
     * @param objectName
     *            The object name
     * @param attributeName
     *            The qualified attribute name
     * @param rgb
     *            The RGB
     */
    public MonitoredMXBeanAttribute(ObjectName objectName,
            String attributeName, int[] rgb) {
        this.objectName = objectName;
        this.atributeName = attributeName;
        previousDurationIndex = 0;
        this.rgb = rgb;

        values = new CopyOnWriteArrayList<Number>();
        dates = new CopyOnWriteArrayList<Date>();
    }

    /*
     * @see IMonitoredMXBeanAttribute#getObjectName()
     */
    @Override
    public ObjectName getObjectName() {
        return objectName;
    }

    /*
     * @see IMonitoredMXBeanAttribute#getAttributeName()
     */
    @Override
    public String getAttributeName() {
        return atributeName;
    }

    /*
     * @see IMonitoredMXBeanAttribute#getRGB()
     */
    @Override
    public int[] getRGB() {
        return rgb;
    }

    /*
     * @see IMonitoredMXBeanAttribute#getDates()
     */
    @Override
    public List<Date> getDates() {
        return dates;
    }

    /*
     * @see IMonitoredMXBeanAttribute#getValues()
     */
    @Override
    public List<Number> getValues() {
        return values;
    }

    /*
     * @see IMonitoredMXBeanAttribute#setRGB(int, int, int)
     */
    @Override
    public void setRGB(int r, int g, int b) {
        rgb = new int[] { r, g, b };
    }

    /*
     * @see IMonitoredMXBeanAttribute#clear()
     */
    @Override
    public void clear() {
        dates.clear();
        values.clear();
        previousDurationIndex = 0;
    }

    /**
     * Adds the attribute value.
     *
     * @param value
     *            The attribute value
     * @param date
     *            The date
     */
    public void add(Number value, Date date) {
        values.add(value);
        dates.add(date);

        // compress data if exceeding the certain size
        if (dates.size() > NUM_OF_DURATIONS * 2) {
            compress();
        }
    }

    /**
     * Gets the data size.
     *
     * @return The data size.
     */
    public int getSize() {
        return dates.size();
    }

    /**
     * Compresses the data diving into several durations and keeping only the
     * min / max value in each duration.
     */
    private void compress() {
        ArrayList<Date> compressedDates = new ArrayList<Date>();
        ArrayList<Number> compressedValues = new ArrayList<Number>();

        int minIndex = 0;
        int maxIndex = 0;
        previousDurationIndex = 0;
        for (int i = 0; i < dates.size(); i++) {
            if (isInSameDurationAsPrevious(dates.get(i).getTime())) {

                // get the min / max values in the same duration
                double value = values.get(i).doubleValue();
                if (value > values.get(maxIndex).doubleValue()) {
                    maxIndex = i;
                }
                if (value < values.get(minIndex).doubleValue()) {
                    minIndex = i;
                }
            } else {
                addValues(compressedDates, compressedValues, minIndex, maxIndex);
                maxIndex = i;
                minIndex = i;
            }
        }

        addValues(compressedDates, compressedValues, minIndex, maxIndex);

        dates = compressedDates;
        values = compressedValues;
    }

    /**
     * Adds the values to the given array.
     *
     * @param datesArray
     *            The array of dates
     * @param valuesArray
     *            The array of values
     * @param indexA
     *            The index of {@link #dates} and {@link #values} to add
     * @param indexB
     *            The index of {@link #values} and {@link #values} to add
     */
    private void addValues(ArrayList<Date> datesArray,
            ArrayList<Number> valuesArray, int indexA, int indexB) {
        if (indexA < indexB) {
            datesArray.add(dates.get(indexA));
            valuesArray.add(values.get(indexA));
            datesArray.add(dates.get(indexB));
            valuesArray.add(values.get(indexB));
        } else if (indexA > indexB) {
            datesArray.add(dates.get(indexB));
            valuesArray.add(values.get(indexB));
            datesArray.add(dates.get(indexA));
            valuesArray.add(values.get(indexA));
        } else {
            datesArray.add(dates.get(indexB));
            valuesArray.add(values.get(indexB));
        }
    }

    /**
     * Checks if the given date is in the same duration as previous.
     *
     * @param date
     *            the date
     * @return true if the given date is in the same duration as previous
     */
    private boolean isInSameDurationAsPrevious(long date) {

        double minDate = dates.get(0).getTime();
        double maxDate = dates.get(dates.size() - 1).getTime();

        // calculate the duration index
        int durationIndex = (int) ((date - minDate) / (maxDate - minDate) * NUM_OF_DURATIONS);

        // check if the duration index is the same as previous
        boolean isInSameGridAsPrevious = (durationIndex == previousDurationIndex);

        // store the previous duration index
        previousDurationIndex = durationIndex;

        return isInSameGridAsPrevious;
    }
}


text:
package v1

import (
	"context"
	time "time"

	operatorv1 "github.com/openshift/api/operator/v1"
	versioned "github.com/openshift/client-go/operator/clientset/versioned"
	internalinterfaces "github.com/openshift/client-go/operator/informers/externalversions/internalinterfaces"
	v1 "github.com/openshift/client-go/operator/listers/operator/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	runtime "k8s.io/apimachinery/pkg/runtime"
	watch "k8s.io/apimachinery/pkg/watch"
	cache "k8s.io/client-go/tools/cache"
)

// OpenShiftControllerManagerInformer provides access to a shared informer and lister for
// OpenShiftControllerManagers.
type OpenShiftControllerManagerInformer interface {
	Informer() cache.SharedIndexInformer
	Lister() v1.OpenShiftControllerManagerLister
}

type openShiftControllerManagerInformer struct {
	factory          internalinterfaces.SharedInformerFactory
	tweakListOptions internalinterfaces.TweakListOptionsFunc
}

// NewOpenShiftControllerManagerInformer constructs a new informer for OpenShiftControllerManager type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewOpenShiftControllerManagerInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
	return NewFilteredOpenShiftControllerManagerInformer(client, resyncPeriod, indexers, nil)
}

// NewFilteredOpenShiftControllerManagerInformer constructs a new informer for OpenShiftControllerManager type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredOpenShiftControllerManagerInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
	return cache.NewSharedIndexInformer(
		&cache.ListWatch{
			ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
				if tweakListOptions != nil {
					tweakListOptions(&options)
				}
				return client.OperatorV1().OpenShiftControllerManagers().List(context.TODO(), options)
			},
			WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
				if tweakListOptions != nil {
					tweakListOptions(&options)
				}
				return client.OperatorV1().OpenShiftControllerManagers().Watch(context.TODO(), options)
			},
		},
		&operatorv1.OpenShiftControllerManager{},
		resyncPeriod,
		indexers,
	)
}

func (f *openShiftControllerManagerInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
	return NewFilteredOpenShiftControllerManagerInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}

func (f *openShiftControllerManagerInformer) Informer() cache.SharedIndexInformer {
	return f.factory.InformerFor(&operatorv1.OpenShiftControllerManager{}, f.defaultInformer)
}

func (f *openShiftControllerManagerInformer) Lister() v1.OpenShiftControllerManagerLister {
	return v1.NewOpenShiftControllerManagerLister(f.Informer().GetIndexer())
}


text:
<web-app>

  <servlet>
    <servlet-name>test</servlet-name>
    <servlet-class>servlets.TestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>test</servlet-name>
    <url-pattern>/test</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>h2g2</servlet-name>
    <servlet-class>servlets.H2G2Servlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>h2g2</servlet-name>
    <url-pattern>/h2g2</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>annotation</servlet-name>
    <servlet-class>servlets.AnnotationServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>annotation</servlet-name>
    <url-pattern>/annotation</url-pattern>
  </servlet-mapping>

</web-app>


text:
from pstats import Stats
from time import sleep
import sys

output = open(sys.argv[1]+'.stats', 'w')
statistics = Stats(sys.argv[1], stream=output)

statistics.print_stats()
sleep(5)


text:
package azurerm

import (
	"fmt"
	"net/http"
	"testing"

	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestResourceAzureRMRouteTableNextHopType_validation(t *testing.T) {
	cases := []struct {
		Value    string
		ErrCount int
	}{
		{
			Value:    "Random",
			ErrCount: 1,
		},
		{
			Value:    "VirtualNetworkGateway",
			ErrCount: 0,
		},
		{
			Value:    "VNETLocal",
			ErrCount: 0,
		},
		{
			Value:    "Internet",
			ErrCount: 0,
		},
		{
			Value:    "VirtualAppliance",
			ErrCount: 0,
		},
		{
			Value:    "None",
			ErrCount: 0,
		},
		{
			Value:    "VIRTUALNETWORKGATEWAY",
			ErrCount: 0,
		},
		{
			Value:    "virtualnetworkgateway",
			ErrCount: 0,
		},
	}

	for _, tc := range cases {
		_, errors := validateRouteTableNextHopType(tc.Value, "azurerm_route_table")

		if len(errors) != tc.ErrCount {
			t.Fatalf("Expected the Azure RM Route Table nextHopType to trigger a validation error")
		}
	}
}

func TestAccAzureRMRouteTable_basic(t *testing.T) {

	ri := acctest.RandInt()
	config := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMRouteTableDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMRouteTableExists("azurerm_route_table.test"),
				),
			},
		},
	})
}

func TestAccAzureRMRouteTable_disappears(t *testing.T) {

	ri := acctest.RandInt()
	config := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMRouteTableDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMRouteTableExists("azurerm_route_table.test"),
					testCheckAzureRMRouteTableDisappears("azurerm_route_table.test"),
				),
				ExpectNonEmptyPlan: true,
			},
		},
	})
}

func TestAccAzureRMRouteTable_withTags(t *testing.T) {

	ri := acctest.RandInt()
	preConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTags, ri, ri)
	postConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTagsUpdate, ri, ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMRouteTableDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: preConfig,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMRouteTableExists("azurerm_route_table.test"),
					resource.TestCheckResourceAttr(
						"azurerm_route_table.test", "tags.%", "2"),
					resource.TestCheckResourceAttr(
						"azurerm_route_table.test", "tags.environment", "Production"),
					resource.TestCheckResourceAttr(
						"azurerm_route_table.test", "tags.cost_center", "MSFT"),
				),
			},

			resource.TestStep{
				Config: postConfig,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMRouteTableExists("azurerm_route_table.test"),
					resource.TestCheckResourceAttr(
						"azurerm_route_table.test", "tags.%", "1"),
					resource.TestCheckResourceAttr(
						"azurerm_route_table.test", "tags.environment", "staging"),
				),
			},
		},
	})
}

func TestAccAzureRMRouteTable_multipleRoutes(t *testing.T) {

	ri := acctest.RandInt()
	preConfig := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri)
	postConfig := fmt.Sprintf(testAccAzureRMRouteTable_multipleRoutes, ri, ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMRouteTableDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: preConfig,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMRouteTableExists("azurerm_route_table.test"),
					resource.TestCheckResourceAttr(
						"azurerm_route_table.test", "route.#", "1"),
				),
			},

			resource.TestStep{
				Config: postConfig,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMRouteTableExists("azurerm_route_table.test"),
					resource.TestCheckResourceAttr(
						"azurerm_route_table.test", "route.#", "2"),
				),
			},
		},
	})
}

func testCheckAzureRMRouteTableExists(name string) resource.TestCheckFunc {
	return func(s *terraform.State) error {

		rs, ok := s.RootModule().Resources[name]
		if !ok {
			return fmt.Errorf("Not found: %s", name)
		}

		name := rs.Primary.Attributes["name"]
		resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
		if !hasResourceGroup {
			return fmt.Errorf("Bad: no resource group found in state for route table: %s", name)
		}

		conn := testAccProvider.Meta().(*ArmClient).routeTablesClient

		resp, err := conn.Get(resourceGroup, name, "")
		if err != nil {
			return fmt.Errorf("Bad: Get on routeTablesClient: %s", err)
		}

		if resp.StatusCode == http.StatusNotFound {
			return fmt.Errorf("Bad: Route Table %q (resource group: %q) does not exist", name, resourceGroup)
		}

		return nil
	}
}

func testCheckAzureRMRouteTableDisappears(name string) resource.TestCheckFunc {
	return func(s *terraform.State) error {

		rs, ok := s.RootModule().Resources[name]
		if !ok {
			return fmt.Errorf("Not found: %s", name)
		}

		name := rs.Primary.Attributes["name"]
		resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
		if !hasResourceGroup {
			return fmt.Errorf("Bad: no resource group found in state for route table: %s", name)
		}

		conn := testAccProvider.Meta().(*ArmClient).routeTablesClient

		_, err := conn.Delete(resourceGroup, name, make(chan struct{}))
		if err != nil {
			return fmt.Errorf("Bad: Delete on routeTablesClient: %s", err)
		}

		return nil
	}
}

func testCheckAzureRMRouteTableDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*ArmClient).routeTablesClient

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "azurerm_route_table" {
			continue
		}

		name := rs.Primary.Attributes["name"]
		resourceGroup := rs.Primary.Attributes["resource_group_name"]

		resp, err := conn.Get(resourceGroup, name, "")

		if err != nil {
			return nil
		}

		if resp.StatusCode != http.StatusNotFound {
			return fmt.Errorf("Route Table still exists:\n%#v", resp.RouteTablePropertiesFormat)
		}
	}

	return nil
}

var testAccAzureRMRouteTable_basic = `
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}

resource "azurerm_route_table" "test" {
    name = "acctestrt%d"
    location = "West US"
    resource_group_name = "${azurerm_resource_group.test.name}"

    route {
    	name = "route1"
		address_prefix = "10.1.0.0/16"
		next_hop_type = "vnetlocal"
    }
}
`

var testAccAzureRMRouteTable_multipleRoutes = `
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}

resource "azurerm_route_table" "test" {
    name = "acctestrt%d"
    location = "West US"
    resource_group_name = "${azurerm_resource_group.test.name}"

    route {
    	name = "route1"
		address_prefix = "10.1.0.0/16"
		next_hop_type = "vnetlocal"
    }

    route {
    	name = "route2"
		address_prefix = "10.2.0.0/16"
		next_hop_type = "vnetlocal"
    }
}
`

var testAccAzureRMRouteTable_withTags = `
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}

resource "azurerm_route_table" "test" {
    name = "acctestrt%d"
    location = "West US"
    resource_group_name = "${azurerm_resource_group.test.name}"

    route {
    	name = "route1"
    	address_prefix = "10.1.0.0/16"
    	next_hop_type = "vnetlocal"
    }

    tags {
	environment = "Production"
	cost_center = "MSFT"
    }
}
`

var testAccAzureRMRouteTable_withTagsUpdate = `
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}

resource "azurerm_route_table" "test" {
    name = "acctestrt%d"
    location = "West US"
    resource_group_name = "${azurerm_resource_group.test.name}"

    route {
    	name = "route1"
    	address_prefix = "10.1.0.0/16"
    	next_hop_type = "vnetlocal"
    }

    tags {
	environment = "staging"
    }
}
`


text:
"""Unit tests for wx.GraphicsFont.

Methods yet to test:
__del__"""

import unittest
import wx

import testGraphicsObject

class GraphicsFontTest(testGraphicsObject.GraphicsObjectTest):
    def setUp(self):
        self.app = wx.PySimpleApp()
        self.renderer = wx.GraphicsRenderer.GetDefaultRenderer()
        self.font = wx.Font(8, wx.FONTFAMILY_ROMAN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
        self.testControl = self.renderer.CreateFont(self.font)

    def testConstructor_wxGraphicsFontOnly(self):
        """__init__"""
        self.testControl = wx.GraphicsFont()
        self.assert_(isinstance(self.testControl, wx.GraphicsFont))

    def testGetRenderer(self):
        """GetRenderer"""
        # Overrides test in testGraphicsObject.GraphicsObjectTest
        self.assertEquals(repr(self.renderer), repr(self.testControl.GetRenderer()))

    def testIsNullTrue(self):
        """IsNull"""
        # Overrides test in testGraphicsObject.GraphicsObjectTest
        self.testControl = wx.GraphicsFont()
        self.assert_(self.testControl.IsNull())

if __name__ == '__main__':
    unittest.main()