text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;

using VVVV.PluginInterfaces.V2;
using VVVV.PluginInterfaces.V1;

using VVVV.DX11;
using SlimDXMatrix = SlimDX.Matrix;
using FeralTic.DX11.Resources;
using FeralTic.DX11;
using CraftLie;
using SharpDX;
using VVVV.Utils.VColor;
using VL.Lib.Collections;
using System.Diagnostics;
using VVVV.Utils.VMath;

namespace VVVV.DX11.Nodes
{
    [PluginInfo(Name = "GetDrawDescriptionData", Category = "DX11.Buffer", Version = "CraftLie", Author = "tonfilm")]
    public class GetDrawDescriptionDataNode : IPluginEvaluate, IDX11ResourceHost, IPartImportsSatisfiedNotification, IDisposable
    {
        [Import()]
        protected IPluginHost2 pluginHost;

        [Input("Layer", Order = 5)]
        protected IDiffSpread<DrawDescriptionLayer> FLayerIn;

        [Input("Keep In Memory", DefaultValue = 0, Order = 6)]
        protected ISpread<bool> FKeep;

        [Input("Preferred Buffer Type", DefaultValue = 0, Order = 6, Visibility = PinVisibility.OnlyInspector)]
        protected ISpread<DX11BufferUploadType> FBufferType;

        [Input("Apply", IsBang = true, DefaultValue = 1, Order = 7)]
        protected ISpread<bool> FApply;

        [Output("Layer Order")]
        protected ISpread<int> FLayerOrder;

        //geometry

        [Output("Blend Index")]
        protected ISpread<int> FBlendIndex;

        [Output("Geometry Out")]
        protected Pin<DX11Resource<IDX11Geometry>> FGeometryOutput;

        [Output("Instance Counts")]
        protected ISpread<int> FInstanceCounts;

        [Output("Transformation")]
        protected ISpread<SlimDXMatrix> FTransformation;

        [Output("Color")]
        protected ISpread<RGBAColor> FColor;

        [Output("Texture Path")]
        protected ISpread<string> FTexturePath;

        [Output("Material Index")]
        protected ISpread<int> FMaterialIndex;

        [Output("Space Index")]
        protected ISpread<int> FSpaceIndex;

        [Output("Clip Rect")]
        protected ISpread<Vector4D> FClipRect;

        [Output("Transform Buffer")]
        protected ISpread<DX11Resource<IDX11ReadableStructureBuffer>> FTransformOutput;

        [Output("Transform Counts")]
        protected ISpread<int> FTransformCounts;

        [Output("Color Buffer")]
        protected ISpread<DX11Resource<IDX11ReadableStructureBuffer>> FColorOutput;

        [Output("Color Counts")]
        protected ISpread<int> FColorCounts;

        //sprites

        [Output("Sprites Blend Index")]
        protected ISpread<int> FSpritesBlendIndex;

        [Output("Sprites Geometry Out")]
        protected Pin<DX11Resource<IDX11Geometry>> FSpritesGeometryOutput;

        [Output("Sprites Transformations")]
        protected ISpread<SlimDXMatrix> FSpritesTransformations;

        [Output("Sprites Space Index")]
        protected ISpread<int> FSpritesSpaceIndex;

        [Output("Sprites Position Buffer")]
        protected ISpread<DX11Resource<IDX11ReadableStructureBuffer>> FSpritesPositionOutput;

        [Output("Sprites Position Counts")]
        protected ISpread<int> FSpritesPositionCounts;

        [Output("Sprites Size Buffer")]
        protected ISpread<DX11Resource<IDX11ReadableStructureBuffer>> FSpritesSizeOutput;

        [Output("Sprites Size Counts")]
        protected ISpread<int> FSpritesSizeCounts;

        [Output("Sprites Color Buffer")]
        protected ISpread<DX11Resource<IDX11ReadableStructureBuffer>> FSpritesColorOutput;

        [Output("Sprites Color Counts")]
        protected ISpread<int> FSpritesColorCounts;

        [Output("Sprites Texture Path")]
        protected ISpread<string> FSpritesTexturePath;

        [Output("Sprites Clip Rect")]
        protected ISpread<Vector4D> FSpritesClipRect;

        //text

        [Output("Text Blend Index")]
        protected ISpread<int> FTextBlendIndex;

        [Output("Texts")]
        protected ISpread<string> FTexts;

        [Output("Text Transformations")]
        protected ISpread<SlimDXMatrix> FTextTransformations;

        [Output("Text Space Index")]
        protected ISpread<int> FTextSpaceIndex;

        [Output("Text Colors")]
        protected ISpread<RGBAColor> FTextColors;

        [Output("Text Sizes")]
        protected ISpread<float> FTextSizes;

        [Output("Font Names")]
        protected ISpread<string> FTextFontNames;

        [Output("Font Weights")]
        protected ISpread<SlimDX.DirectWrite.FontWeight> FTextFontWeights;

        [Output("Font Styles")]
        protected ISpread<SlimDX.DirectWrite.FontStyle> FTextFontStyles;

        [Output("Horizontal Alignments")]
        protected ISpread<SharpDX.DirectWrite.TextAlignment> FTextAlignmentsHorizontal;

        [Output("Vertical Alignments")]
        protected ISpread<SlimDX.DirectWrite.ParagraphAlignment> FTextAlignmentsVertical;

        [Output("Text Widths")]
        protected ISpread<float> FTextWidths;

        [Output("Is Valid")]
        protected ISpread<bool> FValid;

        DX11BufferUploadType currentBufferType = DX11BufferUploadType.Dynamic;
        private bool FInvalidate;
        private bool FFirst = true;
        private int FLayerInSpreadMax;

        protected virtual bool NeedConvert { get { return false; } }

        DrawDescriptionLayer FMainBuffer;
        DrawDescriptionLayer FMainBufferUpdate;

        int FOldGeometryOutCount = 0;
        int FOldSpritesGeometryOutCount = 0;

        public void Evaluate(int SpreadMax)
        {
            //buffer outputs
            if (this.FApply[0] || this.FFirst)
            {
                if (this.FLayerIn.SliceCount > 0)
                {
                    this.FTransformOutput.SliceCount = 1;
                    this.FColorOutput.SliceCount = 1;

                    this.FSpritesPositionOutput.SliceCount = 1;
                    this.FSpritesSizeOutput.SliceCount = 1;
                    this.FSpritesColorOutput.SliceCount = 1;

                    this.FValid.SliceCount = 1;

                    //create geometry buffer resources
                    if (this.FTransformOutput[0] == null) { this.FTransformOutput[0] = new DX11Resource<IDX11ReadableStructureBuffer>(); }
                    if (this.FColorOutput[0] == null) { this.FColorOutput[0] = new DX11Resource<IDX11ReadableStructureBuffer>(); }

                    //creates sprites buffer resources
                    if (this.FSpritesPositionOutput[0] == null) { this.FSpritesPositionOutput[0] = new DX11Resource<IDX11ReadableStructureBuffer>(); }
                    if (this.FSpritesSizeOutput[0] == null) { this.FSpritesSizeOutput[0] = new DX11Resource<IDX11ReadableStructureBuffer>(); }
                    if (this.FSpritesColorOutput[0] == null) { this.FSpritesColorOutput[0] = new DX11Resource<IDX11ReadableStructureBuffer>(); }

                    //multiple layer input?
                    if (FLayerIn.SliceCount > 1)
                    {
                        FMainBuffer = DrawDescriptionLayer.Unite(FLayerIn);
                    }
                    else
                    {
                        FMainBuffer = FLayerIn[0];
                    }

                    //null connected?
                    if (FMainBuffer == null)
                        FMainBuffer = DrawDescriptionLayer.Default;
                }
                else //no output
                {
                    //geos
                    this.FBlendIndex.SliceCount = 0;
                    this.FGeometryOutput.SafeDisposeAll();
                    this.FGeometryOutput.SliceCount = 0;

                    this.FTransformOutput.SafeDisposeAll();
                    this.FTransformOutput.SliceCount = 0;

                    this.FColorOutput.SafeDisposeAll();
                    this.FColorOutput.SliceCount = 0;

                    this.FInstanceCounts.SliceCount = 0;
                    this.FTransformation.SliceCount = 0;
                    this.FTexturePath.SliceCount = 0;
                    this.FColor.SliceCount = 0;
                    this.FMaterialIndex.SliceCount = 0;
                    this.FSpaceIndex.SliceCount = 0;
                    this.FClipRect.SliceCount = 0;
                    this.FTransformCounts.SliceCount = 0;
                    this.FColorCounts.SliceCount = 0;

                    //sprites
                    this.FSpritesBlendIndex.SliceCount = 0;
                    this.FSpritesPositionOutput.SafeDisposeAll();
                    this.FSpritesPositionOutput.SliceCount = 0;

                    this.FSpritesSizeOutput.SafeDisposeAll();
                    this.FSpritesSizeOutput.SliceCount = 0;

                    this.FSpritesColorOutput.SafeDisposeAll();
                    this.FSpritesColorOutput.SliceCount = 0;

                    this.FSpritesTransformations.SliceCount = 0;
                    this.FSpritesPositionCounts.SliceCount = 0;
                    this.FSpritesSizeCounts.SliceCount = 0;
                    this.FSpritesColorCounts.SliceCount = 0;
                    this.FSpritesClipRect.SliceCount = 0;
                    this.FSpritesTexturePath.SliceCount = 0;
                    this.FSpritesSpaceIndex.SliceCount = 0;

                    //text
                    this.FTextBlendIndex.SliceCount = 0;
                    this.FTextSpaceIndex.SliceCount = 0;
                    this.FTextTransformations.SliceCount = 0;
                    this.FTextColors.SliceCount = 0;
                    this.FTextSizes.SliceCount = 0;
                    this.FTexts.SliceCount = 0;
                    this.FTextFontNames.SliceCount = 0;
                    this.FTextFontWeights.SliceCount = 0;
                    this.FTextFontStyles.SliceCount = 0;
                    this.FTextAlignmentsHorizontal.SliceCount = 0;
                    this.FTextAlignmentsVertical.SliceCount = 0;
                    this.FTextWidths.SliceCount = 0;

                    this.FValid.SliceCount = 0;
                }

                this.FLayerInSpreadMax = this.FLayerIn.SliceCount;
                this.FInvalidate = true;
                this.FFirst = false;

                //mark buffers changed
                this.FTransformOutput.Stream.IsChanged = true;
                this.FColorOutput.Stream.IsChanged = true;

                this.FSpritesPositionOutput.Stream.IsChanged = true;
                this.FSpritesSizeOutput.Stream.IsChanged = true;
                this.FSpritesColorOutput.Stream.IsChanged = true;

                //set all normal output pins and get the total counts
                UpdateNormalPins();
            }

        }

        int FTotalTransformCount;
        int FTotalColorCount;

        int FTotalSpritesPositionCount;
        int FTotalSpritesSizeCount;
        int FTotalSpritesColorCount;

        protected Matrix[] FBufferTrans = new Matrix[4096];
        protected Color4[] FBufferColor = new Color4[4096];

        protected Vector3[] FBufferSpritesPosition = new Vector3[8192];
        protected Vector2[] FBufferSpritesSize = new Vector2[8192];
        protected Color4[] FBufferSpritesColor = new Color4[8192];

        int FLayerOrderSlice = 0;
        private void UpdateNormalPins()
        {
            if (FMainBuffer == null)
                return;

            FLayerOrder.SliceCount = FMainBuffer.GeometryDescriptions.Count +
                FMainBuffer.SpritesDescriptions.Count +
                FMainBuffer.TextDescriptions.Count;

            FLayerOrderSlice = 0;

            UpdateNormalGeometryPins();
            UpdateNormalSpritesPins();
            UpdateNormalTextPins();

            Debug.Assert(FLayerOrderSlice == FLayerOrder.SliceCount);
        }

        private void UpdateNormalGeometryPins()
        {
            var descriptions = FMainBuffer.GeometryDescriptions;
            var outCount = descriptions.Count;

            FBlendIndex.SliceCount = outCount;
            FGeometryOutput.SliceCount = outCount;
            FTransformation.SliceCount = outCount;
            FTexturePath.SliceCount = outCount;
            FColor.SliceCount = outCount;
            FMaterialIndex.SliceCount = outCount;
            FSpaceIndex.SliceCount = outCount;
            FClipRect.SliceCount = outCount;

            FInstanceCounts.SliceCount = outCount;
            FTransformCounts.SliceCount = outCount;
            FColorCounts.SliceCount = outCount;

            FTotalTransformCount = 0;
            FTotalColorCount = 0;

            //geometry output, always recreate resources since had a bug with changing slices of different geometry types
            //took about 2 days to find the place where to put two slashes... yea :)
            //if (outCount != FOldGeometryOutCount || this.FFirst)
            {
                this.FInvalidate = true;

                //Dispose old
                this.FGeometryOutput.SafeDisposeAll();

                this.FGeometryOutput.SliceCount = outCount;
                this.FOldGeometryOutCount = outCount;

                for (int i = 0; i < outCount; i++)
                {
                    this.FGeometryOutput[i] = new DX11Resource<IDX11Geometry>();
                }
            }

            for (int i = 0; i < outCount; i++)
            {
                var desc = descriptions[i];

                FInstanceCounts[i] = desc.InstanceCount;

                var transCount = desc.InstanceTransformations.Count;
                var colCount = desc.InstanceColors.Count;
                FTransformCounts[i] = transCount;
                FColorCounts[i] = colCount;

                FTotalTransformCount += transCount;
                FTotalColorCount += colCount;

                FTransformation[i] = ToSlimDXMatrix(ref desc.Transformation);
                FTexturePath[i] = desc.TexturePath;
                FColor[i] = ToRGBAColor(desc.Color);
                FBlendIndex[i] = (int)desc.Blending;
                FMaterialIndex[i] = (int)desc.Shading;
                FSpaceIndex[i] = (int)desc.Space;
                FClipRect[i] = ToVector4(ref desc.ClipRect);

                FLayerOrder[FLayerOrderSlice++] = desc.LayerOrder;
            }
        }

        private void UpdateNormalSpritesPins()
        {
            var descriptions = FMainBuffer.SpritesDescriptions;
            var spritesCount = descriptions.Count;

            FSpritesBlendIndex.SliceCount = spritesCount;
            FSpritesGeometryOutput.SliceCount = spritesCount;
            FSpritesTransformations.SliceCount = spritesCount;
            FSpritesSpaceIndex.SliceCount = spritesCount;
            FSpritesTexturePath.SliceCount = spritesCount;
            FSpritesClipRect.SliceCount = spritesCount;

            FSpritesPositionCounts.SliceCount = spritesCount;
            FSpritesSizeCounts.SliceCount = spritesCount;
            FSpritesColorCounts.SliceCount = spritesCount;

            FTotalSpritesPositionCount = 0;
            FTotalSpritesSizeCount = 0;
            FTotalSpritesColorCount = 0;

            //sprites geometry output
            if (spritesCount != FOldSpritesGeometryOutCount || this.FFirst)
            {
                this.FInvalidate = true;

                //Dispose old
                this.FSpritesGeometryOutput.SafeDisposeAll();

                this.FSpritesGeometryOutput.SliceCount = spritesCount;
                this.FOldSpritesGeometryOutCount = spritesCount;

                for (int i = 0; i < spritesCount; i++)
                {
                    this.FSpritesGeometryOutput[i] = new DX11Resource<IDX11Geometry>();
                }
            }

            for (int i = 0; i < spritesCount; i++)
            {
                var desc = descriptions[i];

                var transCount = desc.Positions.Count;
                var sizeCount = desc.Sizes.Count;
                var colCount = desc.Colors.Count;

                FSpritesPositionCounts[i] = transCount;
                FSpritesSizeCounts[i] = sizeCount;
                FSpritesColorCounts[i] = colCount;

                FTotalSpritesPositionCount += transCount;
                FTotalSpritesSizeCount += sizeCount;
                FTotalSpritesColorCount += colCount;

                FSpritesTransformations[i] = ToSlimDXMatrix(ref desc.Transformation);
                FSpritesSpaceIndex[i] = (int)desc.Space;
                FSpritesTexturePath[i] = desc.TexturePath;
                FSpritesBlendIndex[i] = (int)desc.Blending;
                FSpritesClipRect[i] = ToVector4(ref desc.ClipRect);

                FLayerOrder[FLayerOrderSlice++] = desc.LayerOrder;
            }
        }

        private void UpdateNormalTextPins()
        {
            var textDescriptions = FMainBuffer.TextDescriptions;
            var textCount = textDescriptions.Count;

            FTextBlendIndex.SliceCount = textCount;
            FTexts.SliceCount = textCount;
            FTextTransformations.SliceCount = textCount;
            FTextSpaceIndex.SliceCount = textCount;
            FTextColors.SliceCount = textCount;
            FTextSizes.SliceCount = textCount;
            FTextFontNames.SliceCount = textCount;
            FTextFontWeights.SliceCount = textCount;
            FTextFontStyles.SliceCount = textCount;
            FTextAlignmentsHorizontal.SliceCount = textCount;
            FTextAlignmentsVertical.SliceCount = textCount;
            FTextWidths.SliceCount = textCount;

            for (int i = 0; i < textCount; i++)
            {
                var desc = textDescriptions[i];

                FTexts[i] = desc.Text;
                FTextSizes[i] = desc.Size;
                FTextFontNames[i] = desc.FontName;
                FTextFontWeights[i] = (SlimDX.DirectWrite.FontWeight)desc.Weight;
                FTextFontStyles[i] = (SlimDX.DirectWrite.FontStyle)desc.Style;
                FTextAlignmentsHorizontal[i] = (SharpDX.DirectWrite.TextAlignment)desc.HorizontalAlignment;
                FTextAlignmentsVertical[i] = (SlimDX.DirectWrite.ParagraphAlignment)desc.VerticalAlignment;
                FTextWidths[i] = desc.TextWidth;
                FTextTransformations[i] = ToSlimDXMatrix(ref desc.Transformation);
                FTextSpaceIndex[i] = (int)desc.Space;
                FTextColors[i] = ToRGBAColor(desc.Color);
                FTextBlendIndex[i] = (int)desc.Blending;

                FLayerOrder[FLayerOrderSlice++] = desc.LayerOrder;
            }
        }

        public void Update(DX11RenderContext context)
        {
            FMainBufferUpdate = FMainBuffer;
            if (this.FLayerInSpreadMax == 0) { return; }

            var newContext = !this.FTransformOutput[0].Contains(context);

            if (this.FInvalidate || newContext)
            {
                var bufferTypeChanged = this.currentBufferType != this.FBufferType[0];

                //refresh buffers?
                CheckBufferDispose<Matrix>(context, this.FTransformOutput[0], FTotalTransformCount, bufferTypeChanged);
                CheckBufferDispose<Color4>(context, this.FColorOutput[0], FTotalColorCount, bufferTypeChanged);

                CheckBufferDispose<Vector3>(context, this.FSpritesPositionOutput[0], FTotalSpritesPositionCount, bufferTypeChanged);
                CheckBufferDispose<Vector2>(context, this.FSpritesSizeOutput[0], FTotalSpritesSizeCount, bufferTypeChanged);
                CheckBufferDispose<Color4>(context, this.FSpritesColorOutput[0], FTotalSpritesColorCount, bufferTypeChanged);

                PrepareLocalGeometryBufferData(context);
                PrepareLocalSpriteBufferData(context);

                //make new buffers?
                CreateBuffer<Matrix>(FTransformOutput[0], context, FTotalTransformCount, FBufferTrans);
                CreateBuffer<Color4>(FColorOutput[0], context, FTotalColorCount, FBufferColor);

                CreateBuffer<Vector3>(FSpritesPositionOutput[0], context, FTotalSpritesPositionCount, FBufferSpritesPosition);
                CreateBuffer<Vector2>(FSpritesSizeOutput[0], context, FTotalSpritesSizeCount, FBufferSpritesSize);
                CreateBuffer<Color4>(FSpritesColorOutput[0], context, FTotalSpritesColorCount, FBufferSpritesColor);

                //if (FTotalTransformCount < 0 || FTotalColorCount < 0)
                //{
                //    this.FValid[0] = false;
                //}
            }

            this.FValid[0] = true;
            this.currentBufferType = this.FBufferType[0];

            //write to buffers
            bool needContextCopy = this.FBufferType[0] != DX11BufferUploadType.Immutable;
            if (needContextCopy)
            {
                try
                {
                    WriteToBuffer(FTransformOutput[0], context, FBufferTrans, FTotalTransformCount);
                    WriteToBuffer(FColorOutput[0], context, FBufferColor, FTotalColorCount);

                    WriteToBuffer(FSpritesPositionOutput[0], context, FBufferSpritesPosition, FTotalSpritesPositionCount);
                    WriteToBuffer(FSpritesSizeOutput[0], context, FBufferSpritesSize, FTotalSpritesSizeCount);
                    WriteToBuffer(FSpritesColorOutput[0], context, FBufferSpritesColor, FTotalSpritesColorCount);
                }
                catch (Exception ex)
                {
                    this.pluginHost.Log(TLogType.Error, ex.Message);
                }
            }

            FInvalidate = false;
        }

        private static void CheckBufferDispose<T>(DX11RenderContext context, DX11Resource<IDX11ReadableStructureBuffer> bufferResource, int bufferCount, bool bufferTypeChanged)
            where T : struct
        {
            if (bufferResource.Contains(context))
            {
                if (bufferResource[context].ElementCount < bufferCount
                    || bufferTypeChanged
                    || bufferResource[context] is DX11ImmutableStructuredVLBuffer<T>)
                {
                    bufferResource.Dispose(context);
                }
            }
        }

        /// <summary>
        /// Creates a buffer.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bufferResource">The buffer resource</param>
        /// <param name="context">The DX11 context.</param>
        /// <param name="count">The required count. Gets blown up to the next power of 2.</param>
        /// <param name="bufferToCopy">The buffer to copy in case of immutable buffer type</param>
        private void CreateBuffer<T>(DX11Resource<IDX11ReadableStructureBuffer> bufferResource, DX11RenderContext context, int count, T[] bufferToCopy)
            where T : struct
        {
            if (!bufferResource.Contains(context))
            {
                count = NextUpperPow2(count);
                if (this.FBufferType[0] == DX11BufferUploadType.Dynamic)
                {
                    bufferResource[context] = new DX11DynamicStructuredVLBuffer<T>(context, count);
                }
                else if (this.FBufferType[0] == DX11BufferUploadType.Default)
                {
                    bufferResource[context] = new DX11CopyDestStructuredVLBuffer<T>(context, count);
                }
                else
                {
                    bufferResource[context] = new DX11ImmutableStructuredVLBuffer<T>(context.Device, bufferToCopy, count);
                }
            }
        }

        private void WriteToBuffer<T>(DX11Resource<IDX11ReadableStructureBuffer> bufferResource, DX11RenderContext context, T[] bufferToCopy, int elementCount)
            where T : struct
        {
            if (elementCount > 0)
            {
                if (this.FBufferType[0] == DX11BufferUploadType.Dynamic)
                {
                    DX11DynamicStructuredVLBuffer<T> b = (DX11DynamicStructuredVLBuffer<T>)bufferResource[context];
                    b.WriteData(bufferToCopy, 0, elementCount);
                }
                else if (this.FBufferType[0] == DX11BufferUploadType.Default)
                {
                    DX11CopyDestStructuredVLBuffer<T> b = (DX11CopyDestStructuredVLBuffer<T>)bufferResource[context];
                    b.WriteData(bufferToCopy, 0, elementCount);
                }
            }
        }

        private void PrepareLocalGeometryBufferData(DX11RenderContext context)
        {
            //make sure arrays are big enough
            EnsureArraySize(ref this.FBufferTrans, FTotalTransformCount);
            EnsureArraySize(ref this.FBufferColor, FTotalColorCount);

            var descriptions = FMainBufferUpdate.GeometryDescriptions;

            var geoIndex = 0;
            var transIndex = 0;
            var colIndex = 0;
            foreach (var desc in descriptions)
            {
                var geometry = desc.GetGeometry(context);

                //check drawer
                geometry = AssignInstancedDrawer(desc, geometry);

                this.FGeometryOutput[geoIndex++][context] = geometry;

                foreach (var trans in desc.InstanceTransformations)
                {
                    trans.Transpose();
                    FBufferTrans[transIndex++] = trans;
                }

                CopyToLocalBuffer(desc.InstanceColors, FBufferColor, ref colIndex);
            }
        }

        private void PrepareLocalSpriteBufferData(DX11RenderContext context)
        {
            //make sure arrays are big enough
            EnsureArraySize(ref this.FBufferSpritesPosition, FTotalSpritesPositionCount);
            EnsureArraySize(ref this.FBufferSpritesSize, FTotalSpritesSizeCount);
            EnsureArraySize(ref this.FBufferSpritesColor, FTotalSpritesColorCount);

            var descriptions = FMainBufferUpdate.SpritesDescriptions;

            var geoIndex = 0;
            var posIndex = 0;
            var sizeIndex = 0;
            var colIndex = 0;
            foreach (var desc in descriptions)
            {
                //null geometry
                var geometry = desc.GetGeometry(context);

                //assign drawer
                var nullGeometry = (DX11NullGeometry)geometry.ShallowCopy();
                var drawer = new DX11NullInstancedDrawer();
                drawer.VertexCount = desc.SpriteCount;
                drawer.InstanceCount = 1;
                nullGeometry.AssignDrawer(drawer);
                geometry = nullGeometry;

                this.FSpritesGeometryOutput[geoIndex++][context] = geometry;

                CopyToLocalBuffer(desc.Positions, FBufferSpritesPosition, ref posIndex);
                CopyToLocalBuffer(desc.Sizes, FBufferSpritesSize, ref sizeIndex);
                CopyToLocalBuffer(desc.Colors, FBufferSpritesColor, ref colIndex);
            }
        }

        /// <summary>
        /// Copies to local buffer and increments the index. Tries to use Array.Copy();
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <param name="destination">The destination array.</param>
        /// <param name="destinationStartIndex">Start index in the destination array.</param>
        private static void CopyToLocalBuffer<T>(IReadOnlyCollection<T> source, T[] destination, ref int destinationStartIndex)
            where T : struct
        {
            var collection = source as ICollection<T>;
            if (collection != null)
            {
                //direct copy
                collection.CopyTo(destination, destinationStartIndex);
                destinationStartIndex += collection.Count;
                return;
            }
            else
            {
                foreach (var pos in source)
                {
                    //iteration
                    destination[destinationStartIndex++] = pos;
                }
            }
        }

        private static IDX11Geometry AssignInstancedDrawer(DrawGeometryDescription desc, IDX11Geometry geometry)
        {
            var indexedGeometry = geometry as DX11IndexedGeometry;
            if (indexedGeometry != null)
            {
                if (!(indexedGeometry.Drawer is DX11InstancedIndexedDrawer))
                {
                    indexedGeometry = (DX11IndexedGeometry)indexedGeometry.ShallowCopy();
                    var drawer = new DX11InstancedIndexedDrawer();
                    drawer.InstanceCount = desc.InstanceCount;
                    drawer.StartInstanceLocation = 0;
                    indexedGeometry.AssignDrawer(drawer);
                    geometry = indexedGeometry;
                }
            }
            else
            {
                var vertexGeometry = geometry as DX11VertexGeometry;
                if (vertexGeometry != null)
                {
                    if (!(vertexGeometry.Drawer is DX11InstancedVertexDrawer))
                    {
                        vertexGeometry = (DX11VertexGeometry)vertexGeometry.ShallowCopy();
                        var drawer = new DX11InstancedVertexDrawer();
                        drawer.InstanceCount = desc.InstanceCount;
                        drawer.StartInstanceLocation = 0;
                        vertexGeometry.AssignDrawer(drawer);
                        geometry = vertexGeometry;
                    }
                }
            }

            return geometry;
        }

        RGBAColor ToRGBAColor(Color4 color)
        {
            return new RGBAColor(color.Red, color.Green, color.Blue, color.Alpha);
        }

        SlimDXMatrix ToSlimDXMatrix(ref Matrix m)
        {
            return new SlimDXMatrix()
            {
                M11 = m.M11, M12 = m.M12, M13 = m.M13, M14 = m.M14,
                M21 = m.M21, M22 = m.M22, M23 = m.M23, M24 = m.M24,
                M31 = m.M31, M32 = m.M32, M33 = m.M33, M34 = m.M34,
                M41 = m.M41, M42 = m.M42, M43 = m.M43, M44 = m.M44
            };
        }

        private Vector4D ToVector4(ref RectangleF clipRect)
        {
            return new Vector4D(clipRect.Left, clipRect.Top, clipRect.Right, clipRect.Bottom);
        }

        void EnsureArraySize<T>(ref T[] array, int minimumSize)
        {
            var newSize = array.Length;
            if (newSize < minimumSize)
            {
                do
                {
                    newSize = newSize << 1;
                }
                while (newSize < minimumSize);

                array = new T[newSize];
            }
        }

        int NextUpperPow2(int count)
        {
            var pow2 = 2;
            while (pow2 < count)
            {
                pow2 = pow2 << 1;
            }
            return pow2;
        }

        public void Destroy(DX11RenderContext context, bool force)
        {
            if (force || !this.FKeep[0])
            {
                this.FGeometryOutput.SafeDisposeAll(context);
                this.FTransformOutput.SafeDisposeAll(context);
                this.FColorOutput.SafeDisposeAll(context);

                this.FSpritesGeometryOutput.SafeDisposeAll(context);
                this.FSpritesPositionOutput.SafeDisposeAll(context);
                this.FSpritesSizeOutput.SafeDisposeAll(context);
                this.FSpritesColorOutput.SafeDisposeAll(context);
            }
        }

        #region IDisposable Members
        public void Dispose()
        {
            this.FGeometryOutput.SafeDisposeAll();
            this.FTransformOutput.SafeDisposeAll();
            this.FColorOutput.SafeDisposeAll();

            this.FSpritesGeometryOutput.SafeDisposeAll();
            this.FSpritesPositionOutput.SafeDisposeAll();
            this.FSpritesSizeOutput.SafeDisposeAll();
            this.FSpritesColorOutput.SafeDisposeAll();
        }
        #endregion

        public void OnImportsSatisfied()
        {
            this.FGeometryOutput.SliceCount = 1;
            this.FTransformOutput.SliceCount = 1;
            this.FColorOutput.SliceCount = 1;

            this.FSpritesGeometryOutput.SliceCount = 1;
            this.FSpritesPositionOutput.SliceCount = 1;
            this.FSpritesSizeOutput.SliceCount = 1;
            this.FSpritesColorOutput.SliceCount = 1;
        }
    }
}


text:
.class Landroid/support/v4/view/accessibility/AccessibilityEventCompatJellyBean;
.super Ljava/lang/Object;
.source "AccessibilityEventCompatJellyBean.java"

# annotations
.annotation build Landroid/annotation/TargetApi;
    value = 0x10
.end annotation

.annotation build Landroid/support/annotation/RequiresApi;
    value = 0x10
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 25
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static getAction(Landroid/view/accessibility/AccessibilityEvent;)I
    .locals 1
    .param p0, "event"    # Landroid/view/accessibility/AccessibilityEvent;

    .prologue
    .line 39
    invoke-virtual {p0}, Landroid/view/accessibility/AccessibilityEvent;->getAction()I

    move-result v0

    return v0
.end method

.method public static getMovementGranularity(Landroid/view/accessibility/AccessibilityEvent;)I
    .locals 1
    .param p0, "event"    # Landroid/view/accessibility/AccessibilityEvent;

    .prologue
    .line 31
    invoke-virtual {p0}, Landroid/view/accessibility/AccessibilityEvent;->getMovementGranularity()I

    move-result v0

    return v0
.end method

.method public static setAction(Landroid/view/accessibility/AccessibilityEvent;I)V
    .locals 0
    .param p0, "event"    # Landroid/view/accessibility/AccessibilityEvent;
    .param p1, "action"    # I

    .prologue
    .line 35
    invoke-virtual {p0, p1}, Landroid/view/accessibility/AccessibilityEvent;->setAction(I)V

    .line 36
    return-void
.end method

.method public static setMovementGranularity(Landroid/view/accessibility/AccessibilityEvent;I)V
    .locals 0
    .param p0, "event"    # Landroid/view/accessibility/AccessibilityEvent;
    .param p1, "granularity"    # I

    .prologue
    .line 27
    invoke-virtual {p0, p1}, Landroid/view/accessibility/AccessibilityEvent;->setMovementGranularity(I)V

    .line 28
    return-void
.end method

redpajama_set_name: RedPajamaGithub


text:
package com.alexdupre.shapeshift

import com.alexdupre.shapeshift.models._
import com.alexdupre.shapeshift.providers.{ProviderAPI, ProviderResponse}
import org.slf4j.LoggerFactory
import play.api.libs.json._

import scala.concurrent.{ExecutionContext, Future}

class ShapeShiftClient(provider: ProviderAPI, pubApiKey: String = ShapeShiftClient.pubApiKey)(implicit ec: ExecutionContext)
    extends ShapeShiftAPI {

  val logger = LoggerFactory.getLogger(classOf[ShapeShiftClient])

  val apiUrl = "https://shapeshift.io/"

  private def get[T](path: String)(implicit fjs: Reads[T]): Future[T] = {
    val endpoint = apiUrl + path
    logger.debug(s"Request: GET ${endpoint}")
    provider.get(endpoint).map(handleResponse[T](_))
  }

  private def post[T](path: String, params: JsValue, encapsulated: Boolean = false)(implicit fjs: Reads[T]): Future[T] = {
    val endpoint = apiUrl + path
    logger.debug(s"Request: POST ${endpoint}")
    logger.trace(s"Payload:\n${Json.prettyPrint(params)}")
    provider.post(endpoint, params).map(handleResponse[T](_, encapsulated))
  }

  private def handleResponse[T](response: ProviderResponse, encapsulated: Boolean = false)(implicit fjs: Reads[T]): T = {
    val js = response.body
    logger.debug(s"Response Status: ${response.status}")
    logger.trace(s"Response:\n${Json.prettyPrint(js)}")
    if (response.status == 200) {
      val jsres = js match {
        case o: JsObject =>
          o.value.get("error") match {
            case Some(JsString(error)) => throw new ShapeShiftException(error)
            case _ =>
              (if (encapsulated) o.value.get("success") else Some(js)) match {
                case Some(value) => value.validate[T]
                case _           => throw new RuntimeException("ShapeShift Protocol Exception")
              }
          }
        case a: JsArray => a.validate[T]
        case _          => throw new RuntimeException("ShapeShift Protocol Exception")
      }
      jsres match {
        case JsSuccess(r, _) => r
        case JsError(e)      => throw new RuntimeException("ShapeShift Parser Exception", new JsResultException(e))

      }
    } else {
      throw new RuntimeException("ShapeShift Protocol Exception")
    }
  }

  override def getRate(market: Market): Future[Rate] = {
    get[Rate](s"rate/$market")
  }

  override def getDepositLimit(market: Market): Future[Limit] = {
    get[Limit](s"limit/$market")
  }

  override def getMarketInfo(market: Market): Future[MarketInfo] = {
    get[MarketInfo](s"marketinfo/$market")
  }

  override def getMarketsInfo(): Future[Seq[MarketInfo]] = {
    get[Seq[MarketInfo]]("marketinfo")
  }

  override def getCoins(): Future[Map[Coin, CoinInfo]] = {
    get[Map[String, CoinInfo]]("getcoins").map(_.map {
      case (coin, info) => Coin.from(coin) -> info
    })
  }

  override def validateAddress(coin: Coin, address: String): Future[Unit] = {
    get[JsObject](s"validateAddress/$address/$coin").map(_ => ())
  }

  override def createOpenTransaction(
      market: Market,
      outputAddress: String,
      outputSpecial: Option[(String, String)] = None,
      returnAddress: Option[String] = None
  ): Future[OpenOrder] = {
    val req = Json.obj(
      "pair"          -> market,
      "withdrawal"    -> outputAddress,
      "returnAddress" -> returnAddress,
      "apiKey"        -> pubApiKey
    ) ++ outputSpecial.fold(Json.obj()) {
      case (key, value) => Json.obj(key -> value)
    }
    post[OpenOrder]("shift", req)
  }

  override def createFixedInputTransaction(
      market: Market,
      inputAmount: BigDecimal,
      outputAddress: String,
      outputSpecial: Option[(String, String)] = None,
      returnAddress: Option[String] = None
  ): Future[Order] = {
    val req = Json.obj(
      "pair"          -> market,
      "depositAmount" -> inputAmount,
      "withdrawal"    -> outputAddress,
      "returnAddress" -> returnAddress,
      "apiKey"        -> pubApiKey
    ) ++ outputSpecial.fold(Json.obj()) {
      case (key, value) => Json.obj(key -> value)
    }
    post[Order]("sendamount", req, true)
  }

  override def createFixedOutputTransaction(
      market: Market,
      outputAmount: BigDecimal,
      outputAddress: String,
      outputSpecial: Option[(String, String)] = None,
      returnAddress: Option[String] = None
  ): Future[Order] = {
    val req = Json.obj(
      "pair"          -> market,
      "amount"        -> outputAmount,
      "withdrawal"    -> outputAddress,
      "returnAddress" -> returnAddress,
      "apiKey"        -> pubApiKey
    ) ++ outputSpecial.fold(Json.obj()) {
      case (key, value) => Json.obj(key -> value)
    }
    post[Order]("sendamount", req, true)
  }

  override def quoteFixedInputTransaction(market: Market, inputAmount: BigDecimal): Future[Quote] = {
    val req = Json.obj(
      "pair"          -> market,
      "depositAmount" -> inputAmount
    )
    post[Quote]("sendamount", req, true)
  }

  override def quoteFixedOutputTransaction(market: Market, outputAmount: BigDecimal): Future[Quote] = {
    val req = Json.obj(
      "pair"   -> market,
      "amount" -> outputAmount
    )
    post[Quote]("sendamount", req, true)
  }

  override def getOrderInfo(orderId: String): Future[OrderInfo] = {
    get[OrderInfo](s"orderInfo/$orderId")
  }

}

object ShapeShiftClient {

  val pubApiKey =
    "5e2d0e481642e21d2252704ebd4a370efbe50037475544ea599bee265658b555010adc69ef4415c4c3d8fe3be62587b05157bd559adcd8609fd54a731a87094a"

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>Friends - 10.05 The One Where Rachel's Sister Baby-sits</title>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

Friends

  1005 - The One Where Rachel's Sister Baby-sits

Written by: Dana Klein

  Produced by: Robert Carlock and Wendy Knoller

  Transcribed by: Coffee Mug, Eleonora, Sebastiano & Vanessa

[Scene: Central Perk]

Rachel: You know, I'm thinking about letting Emma have her
  first cookie.

Joey: Her first cookie? She has cookies all the time!

Rachel: I've never given her a cookie. Have you?

Joey: No! No... and, for the record, I've also never given her a frosting from
  a can!

Monica: Hey Rach, the adoption agency needs letters of recommendation and we
  were wondering if you would write one for us.

Rachel: Of course, I'd be honored!

Chandler: Thanks!

Monica: Thank you!

(Joey looks at them, disappointed about their decision)

Joey: U-U-Um, I think there's been an oversight.

Chandler: Joey, we would've asked you, we just thought you wouldn't be interested.

Monica: Yeah, it's just we don't think of you as really being so much "with
  the words".

Joey: Whoo-weh hey weh-hey whoo hey!!

Monica: Clearly we were wrong.

Joey: I gotta a lot of nice stuff to say about you guys, ok? And I know how
  much you wanna have a baby, you know, and I would love to help you get one.

Monica: You know what? Then, Joey, we want you to do it.

Joey: Thank you! Alright, let me see how I'm gonna start... "Dear baby
  adoption decider people..."

Chandler: So excited about your letter!

(Phoebe enters)

Phoebe: Hey!

All: Hey Phoebe!

Joey: Hey!

Monica: Wow! Don't you look nice?!

Phoebe: Yes, I do! Today is Mike and my one-year anniversary.

Rachel: OH! What's it the anniversary of? Your first date, your first kiss,
  first time you had sex...

Phoebe: YEAH!

Chandler: So you must be going to somewhere fancy to celebrate?

Phoebe: Uh-uh. Ehm, a Knicks game.

Joey: Uhm... Aren't you a little overdressed?

Phoebe: Hey, you know what, I've never had a one-year anniversary before, so
  no matter where we go, I'm wearing something fancy pants, and... I'm gonna put
  on my finest jewelry and we're gonna have sex in a public rest room.

Monica: You guys do that? Chandler won't even have sex in
our bathroom!

Chandler: That's where people make number two!!

  OPENING CREDITS

[Scene: Ross' apartment. Ross is grading papers. Charlie approaches
  him.]

Charlie: Hey! (They kiss and cuddle a little)

Ross: Hey...

Charlie: So, you know... I have a little time. If you... if you want to...

Ross: (surprised) Oh... (he pauses) (sounds disappointed) Ohh... I'd love to
  but I really have to grade these papers.

Charlie: Fine, it's fine... (she whispers) I'll just shower by myself...

Ross: (Writing on the papers) B, B, B, B, B!

Charlie: Oh, Ross, you gave a B to a Pottery Barn catalogue.

Ross: Well, it had some good ideas, take off your shirt.

(they start kissing but someone knocks at the door)

Ross: Damnit!

Amy: (yelling from outside) Rachel!! Open up!! It's your sister!! (she knocks
  on the door again) I have to talk to you!!

Ross: (he opens the door) Hi Amy!

Amy: You're not Rachel.

Ross: Still sharp as a tack!

Amy: Um... Charlie, this is Rachel's sister Amy. Amy, this is Charlie.

Charlie: Hi!

Amy: Hi!

Charlie: Nice to meet you.

Amy: H-Hi!!(to Ross) And you are...?

Ross: (pause) Ross? I... I grew up on your block! We had Thanksgiving together
  last year... I had a baby with your sister!

Amy: (looks confused) N-no... uhm... did I buy a falafel from you yesterday?

Ross: (gives up) Yes, yes, you did.

[Scene: Joey and Rachel's apartment]

(Ross enters the apartment with Amy)

Ross: Hi Rachel! Here's your sister Amy! She thinks I need
  pec implants!

Rachel: Amy! Hi! Oh-oh-hoh! (they hug) Wow! You remember Joey?

Amy: Yeah! Hey, sure! The "Days of Our Lives" guy!

Joey: That's right, yeah.

Amy: You're not good!

Joey: Always nice to meet a fan!

Rachel: So now, what are you doing here?

Amy: Well, I have huge news.

Rachel: (Emma starts crying in the other room) Oh sorry, hold on. Let me just
  check on the baby!

Amy: Wait, this is important! Can Ella wait? (Rachel goes to Emma)

Ross: Ehm... Her name is Emma.

Amy: Why did you change it, Ella was so much prettier!

Ross: What do I know? I just sell Middle Eastern food from a cart!

Amy: Hey, your English is getting better!!

Ross: (to Joey) Oh my God!

Joey: I know, she may be the hottest girl I've ever hated.

Ross: What... what you working on?

Joey: (using a laptop) Oh, Monica and Chandler's recommendation. I want it
  to sound smart but.. I don't know any big words or anything, so...

Ross: Why don't you use your Thesaurus?

Joey: What did I just say?

Ross: Watch. (he takes the laptop) Here, you ehm... You highlight the word
  you want to change.

  Go under Tools and the Thesaurus generates... 'gives'... 'gives' a whole list
  of choices. You can pick the word that sounds smartest.

Joey: Oh my God, that's great! I'm smart!! No, no, I'm... (he uses the Thesaurus)
  "brainy, bright, clever", I love this thing! Look out ladies, Joey
  Tribbiani's got the whole package!!

[Scene: Rachel's room. Rachel is attending to Emma. Amy is standing
  behind her.]

  Rachel: God!

Amy: So beautiful.

Rachel: Oh, I know, isn't she?

Amy: No, I was talking about your bedding.

Rachel: All right. What's your news, Amy?

Amy: Oh! Um... Well... I'm getting married.

Rachel: What? Oh my God! To who?

Amy: This guy! He has a killer apartment.

Rachel: A-And??

Amy: A-And it's on Fifth. And the elevator opens up right into the living room.

Rachel: No, what's he like?

Amy: Oh! He's ok. Do you remember my old boyfriend Mark?

Rachel: Yeah.

Amy: It's his dad.

Rachel: Huh... wow, so he's gotta be...

Amy: Old? Yeah! But he travels a lot, so he's hardly ever there.

Rachel: Sweety, I gotta tell ya... it sounds a little bit like you like the
  apartment more than you like...

Amy: Myron. Hmm... I told you he was old!

Rachel: Oh... sit down, sit down. Oh, honey, you know, I once also almost married
  somebody that I didn’t love. Do you remember Barry?

Amy: Humpf, remember him? How we used to make out all the time after you went
  to sleep.

Rachel: Sometimes just nodding is ok. (pause) Uhm, so but
  anyway, listen, not marrying Barry was the best decision that I ever, ever
  made. Honey, you deserve
  true love. Your soulmate is out there, somewhere. Someone that is your age,
  that is smart, that is fun and that you care about!

Amy: (thinks about it) You’re right, you’re right! I’m gonna
  do it!

Rachel: Ok.

Amy: I’m gonna marry Myron and keep looking
  for Mr
Right.

Rachel: Ok, let’s keep talking.

[Scene: Madison Square Garden. Mike and Phoebe are walking to
  their seats.]

Phoebe: Excuse me, anniversary. Excuse me, anniversary. (looking
  at her ticket). Uhm, sir, could you move your nachos... they’re in my
  seat. It's my anniversary. (to Mike) Here we are! (Mike nods). Can’t believe
  it's been a whole year!

Mike: I know. This has been the best year... (the crowd starts cheering so
  he starts yelling) THIS HAS BEEN THE BEST YEAR OF MY LIFE!

Phoebe: ME TOO! I NEVER THOUGHT I COULD LOVE SOMEONE THIS MUCH!

Mike: I FEEL THE SAME WAY!

Phoebe: YOU’RE SO GENEROUS AND KIND AND (crowd stops cheering) YOU'RE
  AMAZING IN BED (everyone hears it and stare at them.) (to everybody) IT’S
  OUR ANNIVERSARY!

Announcer: Knicks fans, please turn your attention to the
  big screen on the score board. Someone has a special question to ask. (on the
  screen there’s written ‘Julie, will you marry me?’ and goes
  on to show a guy kneeling down in front of a girl holding out a ring to her)

Phoebe: Oh how lame... oh, it’s so tacky, and impersonal.

Mike: Really?

Phoebe: Oh, it’s the worst way to propose!

Mike: (looks strangely shocked) Excuse me... (he leaves, then Phoebe realizes
what she did).

[Scene: Monica’s apartment. Joey enters the room]

Joey: Hey, finished my recommendation. (he hands it over to
  Chandler) Here. And I think you’ll be very, very happy. It’s the
  longest I ever spent on a computer without looking at porn.

Chandler: (reading) I don’t... uh... understand.

Joey: (sounding very proud of himself) Some of the words are a little too sophisticated
  for ya?

Monica: (also reading it) It doesn’t make any sense.

Joey: Of course it does! It’s smart! I used the the-saurus!

Chandler: On every word?

Joey: Yep!

Monica: Alright, what was this sentence originally? (shows the sentence to
  Joey)

Joey: Oh, ‘They are warm, nice, people with big hearts’.

Chandler: And that became ‘they are humid prepossessing Homo Sapiens
  with full sized aortic pumps...?

Joey: Yeah, yeah and hey, I really mean it, dude.

Monica: Hey Joey, I don’t think we can use this.

Joey: Why not?

Monica: Well, because you signed it baby kangaroo Tribbiani (Joey makes a 'and-what’s-wrong-with-that'
  look). Hey, why don’t you stop worrying about sounding smart and just
  be yourself!

Chandler: You know what? You don’t need a thesaurus, just write from
here, (points at his own heart) your full sized aortic pump.

[Scene: The corridor. Amy knocks Joey’s door and Rachel
  opens the door.]

Rachel: Amy, hi!

Amy: I took your advice, I left Myron.

Rachel: Oh, good for you!

Amy: I know! I'm Erin Brockovich!

Rachel: Yes you are! Oh, I am so proud of you!

Amy: Thank you! So, can I stay with you?

Rachel: But Erin Brockovich had her own house.

(Joey comes out of Monica’s apartment and sees Rachel and Amy but does
  not notice the huge amount of bags)

Joey: Ah, look who’s back! (he sees the bags) Why do you have bags? RACH,
  WHY DOES SHE HAVE BAGS?

Amy: Well, I’m staying with you guys!

Joey: What?

Amy: We’re gonna be roomies! (she snaps her finger and points at Joey,
snaps her fingers again and points to the bags) Come on!

[Scene: Joey’s apartment. Rachel is in the living room
  and Joey comes out of his room.]

Joey: You slept out here?

Rachel: Yeah... Amy kept kicking me in her sleep yelling ‘Myron, get
  off!’

Joey: But uhm, we're getting rid of her, right? Rach, please tell me we’re
  getting rid of her.

Rachel: Joey, I can’t do that!

Joey: Oh, come on! Last night I was finishing off a pizza and she said (aping
  Amy badly) "Uoh oh oh, a moment on the lips, forever on the hips!"
  I don’t need that kind of talk in my house!

Rachel: Well Joey, uhm look, I know that she’s difficult, but I think
  it’s really good that she’s here.

Joey: 'Cause we will appreciate it more when she’s gone?

Rachel: No, it's just... look, you know, when I first moved to the city I was
  a lot like her! I was spoiled, self-centered and you guys really took care of
  me.

Joey: Yeah, Monica made us!

Rachel: Well, uhm... whatever, I have really appreciated it, 'cause I don’t
  think I would be the person that I am today if it wasn’t for you guys.
  See, I wanna help Amy the way you guys helped me. And I know it’s gonna
  take patience, but that’s ok.

Amy: Good morning.

Joey: Yeaah.

Rachel: Amy, that’s what I was supposed to wear today, that’s why
  I hung it on the door.

Amy: Oh, sweety, you can’t pull this off.

Rachel: Amy, you know what? I was thinking that maybe now it'd be a good time
  for us to sit down and, you know, talk about your future.

Amy: Oh, I can’t, honey. I’m gonna go get my eyebrows shaped. (points
  at her eyebrows) I am not happy. (to Joey who has a pizza box in his hands)
  Oh... sure you wanna eat that?

Joey: (yelling at her) I’M CURVY, AND I LIKE IT!

[Scene: Monica’s Apartment. Rachel, Ross, Monica and Chandler
  are there, Phoebe enters the room]

Phoebe: Hi. I just had the worst anniversary ever.

Chandler: I doubt that! Tell her about us last
year.

Monica: Oh, well, I bought Chandler a five hundred dollar watch and he wrote
  me a rap song.

Ross: Seriously?

Chandler: Word!

Phoebe: Well, mine was worse than that.

Rachel: Well, what happened?

Phoebe: We were at the game, and this guy proposed to his girlfriend on the
  big screen thing...

Rachel: Oh, that is so tacky.

Phoebe: Well, that’s what I said, but it turns out, Mike was planning
  on proposing to me that same way last night!

Monica: Oh my God, Mike was gonna propose?

Rachel: Phoebe, that’s huge!

Ross: Well, do you wanna marry him?

Phoebe: Yeah, I really do! Yes, but, after I dumped on the way he was gonna
  propose to me, I don’t think he’s ever gonna ask again! I mean,
  I said no in Barbados and now this!

Chandler: She's right! If I were a guy and... (stops himself
  mid-sentence...everyone stares at him) Did I just say if I were a
  guy..?

Monica: Maybe you don't need him to propose to you, maybe you can propose to
  him!

Phoebe: Oh, I don't know, I don't know, isn't that a little desperate?

Monica: I proposed to Chandler! (Phoebe stops herself from laughing) Alright,
  moving on...

Chandler: Oh, I don't think it was desperate, I think it was amazing!

Monica: Thank you.

Phoebe: (To Rachel and Ross) Well, do you think
  I should propose?

Rachel: I think it could be kind of great!

Ross: Absolutely! You'll love the feeling! There's nothing like it!

Phoebe: Ok, ok, so how should I do it?

Monica: How about at a game, on the big screen?

Rachel: (Sarcastically) Uuuh!! How about at a Footlocker? (claps her hands
  together, faking excitement)

Monica: What? what? He obviously thinks that's a nice way to be proposed to,
  plus he'd never suspect it!

Phoebe: Yeah, that does make sense. Ok, now, would... would you two (points
  to Ross and Chandler) like that?

Chandler: Sounds good to me... but what would a guy think?

(Amy walks in carrying a phone handset)

Amy: (To Rachel) Nana is on the phone (Hands the phone over to Rachel)

Rachel: (Takes the phone) Oh! That's interesting, since she died seven years
  ago!!

Amy: She did? Who got her condo in Boca?

Rachel: (Into the phone) Hello? (announces to Amy) Oh, it's our nanny! (goes
  back to the phone conversation) Hi! Oh... God! I hope you feel better! Ok, bye!
  (Hangs up) (To Ross) That's Molly, she's sick. Can you watch Emma today?

Ross: No, I can't. I have back-to-back classes. Did Molly say what she had?
  Because my throat's been hurting?

Rachel: Menstrual cramps.

Ross: I don't think that's what this is.

Rachel: (To Monica, Chandler and Phoebe) Can any of you watch Emma?

Monica: No, sorry sweety..

Phoebe: No, I've got work and then I'm proposing..

Rachel: (To Ross) Great, shoot, what are we gonna do?

Amy: Well, I can do it.

Rachel: (Thinks for a moment) Well, actually...

Ross: (He interrupts her immediately, and drags her by her arm to the other
  side of the room) Well, can I talk to you for a sec.?

Rachel: Yeah.

Ross: Um, I do not want her baby-sitting our child.

Rachel: Why not?

Ross: Well, for one thing, she keeps calling her Ella!

  Rachel: (Defends Amy) Wha.. well, Ella's a nice name!

Ross: Fine, we'll call the next one Ella.

Rachel: (Shocked) Wha... the next one?

Ross: (a little confused) Okay, um... I don't want her watching our baby.

Rachel: Ross, I am trying to help her become a better person. This is a huge
  breakthrough for her! She just offered to do something for another human being!!

Ross: I... I don't know..

Rachel: Ross, I'm telling you, she's giving up getting her eyebrows (points
  at her own to emphasize the word) shaped to do this alright? Do you understand
  how important that is in our world?

(Amy approaches from behind)

Amy: um... listen, I couldn't help but overhear... 'cause I was trying to...
  Listen, let me do this alright? I really wanna help you guys out, and plus Rachel's
  been so wonderful to me... (looks at hem pleadingly)

(Rachel looks at Ross and her agrees silently)

Rachel: Absolutely.

Amy: (very excited) Oh! Great! So how much does it pay? (Ross just gives up
and leaves)

[Scene: Central Perk. Joey is inside, Chandler and Monica walk
  in.]

Chandler: Hey Joe! How's the second draft of the letter coming?

Joey: Great, I'm finished! In fact, I just dropped it off at the agency.

(Chandler and Monica look shocked)

Monica: You dropped it off?

Joey: Yeah.

Chandler: Can we read it? Can you print out another copy?

Joey: No can do amigo. No, I didn't use the computer. Felt more personal to
  hand-write it. (Chandler and Monica look even more shocked)

Monica: You hand-wrote it?

Joey: Yeah, and don't worry. I didn't try to sound smart at
  all! See ya later! (Leaves)

Monica: Oh my God, oh my God, that letter is gonna go in our
  file! We're never gonna get a kid. No, we're gonna be one of those old couples
  that collects orchids or has a lot of birds!

Chandler: It's ok, it's ok. You know what? (Takes out his mobile) I'll just
  call the agency and tell them to throw out the letter. (starts dialing)

Monica: Okay good.

Chandler: (on the phone) Hello, this is Chandler Bing. Somebody just dropped
  off a handwritten recommendation letter, and.. (listens) Uh-huh... Uh-huh...
  okay... thank you. Good-bye. (hangs up looking very confused).

Monica: Ugh, we're screwed, aren't we? You know what? Just tell me on the way
  to the bird store.

Chandler: (Still looks confused) They loved it.

Monica: What?

Chandler: They thought it was very smart of us to have a
  child write the recommendation letter.

Monica: (surprised) They thought Joey was a child?

Chandler: She guessed 8, 9, based on his drawings.

(Amy comes in with Emma in a stroller)

Amy: Hi!

Monica: Hey, what did you guys do today?

Amy: Ella wanted to go out, so we went shopping and got some sushi.

Chandler: That sounds like fun.

Amy: Yeah, not really. Babies are dull.

(Rachel comes in, sees Amy and Emma)

Rachel: (To Emma) Hey! Hi, how's my girl?

Amy: I'm fine! And, I got you a present for letting me stay with you. Ready?

Rachel: (sounds excited) Yeah!

(Amy takes off Emma's hat)

Amy: Ta-daaa!

(Rachel looks at Emma)

Rachel: (not excited anymore) You pierced her ears!?

Amy: (Very excited about it) Doesn't it make her nose look smaller?

(Rachel looks very shocked)

COMMERCIAL BREAK

  Rachel: You pierced her ears? How could you do this without telling me?

Amy: Well, if I had told you, then it wouldn't have been surprise, now would
  it?

Chandler: I think she looks cute. (Rachel turns around and stares at him angrily)
  ... but I am wrong!

Rachel: Oh my God, Oh my God, here comes Ross. He's gonna flip out.

Amy: Why, did something happen to his falafel cart?

Rachel: Ugh. (takes the hat and covers Emma's head and half her face with it)

(Ross enters)

Ross: Hey guys.

  Monica and Chandler: Hi Ross.

Ross: Hey Emma. Oh, why is she wearing her hat so low? She can barely see.
  (Wants to take the hat off, but Rachel tries to stop him).

Rachel: Nah, I don't really want her to see.

Ross: Why not?

Monica: Because there are so many terrible sights in this world.

Chandler: Like war. Or that thing in Joey's refrigerator. Remember? It was
  in a milk carton but it looked like meat?

Ross: Come here (Removes Emma's hat) Oh! There she is! Hi!

(Rachel looks worried)

Ross: (sees how strangely Monica, Chandler and Rachel are looking at him) What?

Rachel: Nothing.

Ross: (Back to Emma) Hi! (Looks at her) What... (Moves the stroller away from
  him so he can get a better look at her. He looks at her confused. Finally he
  realizes the difference and gasps). Please tell me those are clip-ons.

Rachel: Oh, they're real!

Ross: Did she (points at Amy) do this to her? I told you we shouldn't have
  left Emma with her!

Rachel: I know, I know, and you were right Ross. (To Amy)
  You are soo irresponsible
  I am never letting you baby-sit ever again!

Amy: Hey you know what, this kid needs me, okay? She needs
  to have a cool fun aunt!

Monica: I'm a cool, fun aunt!

Amy: (Sarcastically) O-Okay!

Chandler: Hey! Monica can be cool and fun at organized indoor projects!

Rachel: I can't believe this. All I wanted to do was help you try to figure
  out what to do with your life and this is how you repay me?

Amy: Well, I don't need you to help me, because I already know what I'm going
  to do with my life.

Rachel: Oh yeah? Since when?

Amy: Since today... I am going to be a baby stylist.

Rachel: (looks at Ross and then at Amy again in disbelief) What?

Ross: That's not a thing!

Amy: Well, it should be. I'm gonna help babies learn how to accessorize, what
  colors to wear, what clothes are slimming...

Rachel: (shouting) Babies don't care if they're slim.

Amy: Enter Amy!

Ross: (very angry) Amy, I ju... I just... I just wanna...

Amy: What? What are you gonna do?

Ross: (pointing at Amy, shouting) No more falafel for you!

(Amy looks at Ross, angrily. Rachel clearly doesn't understand what he meant
and looks at Ross who gestures "later".)

[Scene: Madison Square Garden. Phoebe and Mike are watching the
  game. There's cheering, but Phoebe seems distracted.]

Mike: Great game, huh?

Phoebe: Uhuh, uhuh... (seems distracted)

Mike: Why do you keep looking at the screen?

Phoebe: I'm not. I'm praying. (looking up) Please let the Knicks win... Thank
  you Thor! (Mike is standing up) Where... where are you going?

Mike: Going go to the bathroom.

Phoebe: Well, I think you should wait.

Mike: Why?

Phoebe: Well, if you don't... if you don't hold it in, you don't get all the
  nutrients.

Announcer: Knicks fans, please turn your attention to the
  big screen on the scoreboard. Someone has a special question to ask.

(We see the screen where it says: "Mike will you marry me?" and then
  we see Phoebe and Mike on the screen. Phoebe stands up and kneels in front of
  Mike.)

Phoebe: Mike Hannigan... will you marry me? (Mike looks bewildered)

Announcer: Get a load of this... She's proposing
  to him. Guess we know who wears the pants in that family.
  (people are laughing, while
  Mike still seems bewildered)

Phoebe: That's not very enlightened!

(There's booing around them, and Mike sinks in his chair, holding his hand
  in above his eyes, hoping no-one would recognize him)

Phoebe: Hey, hey! (shouting) Boo us? Boo you!

[Scene: Rachel and Joey's. Joey is in the kitchen and the telephone
  rings.]

Joey: (picks up the phone) Hello? Yeah, this is Joey Tribbiani...
  Oh, hi! Well, I'm glad you liked my letter... No my mommy and daddy aren't home
  right now... (looks puzzled) Okay, bye bye. (hangs up) (to himself) She was
  nice!

(Rachel and Amy enter)

Rachel: Joey, get Amy's bags, she is moving out!

Joey: Whoo-hoo! (and leaves for Rachel's room)

Amy: You're kicking me out?

Rachel: You put holes in my baby's ears!

Amy: Yeah well, at least now people will know she is a girl!

Rachel: (gasps) I can't believe I ever even tried to help
  you. You are so  beyond help.

Amy: You know what? Ever since I got here, you have been nothing but negative.

Rachel: Excuse me?

Amy: You didn't want me to marry the old guy with the great apartment. Then,
  I tried to help your daughter to de-emphasize her flaws (frantically pointing
  at her nose) And suddenly I am the bad guy?

Rachel: (yelling) Joey, where are those bags?

Joey: (Yelling from Rachel's room) She has a lot of crap!

Amy: You know what? When I moved in here I thought: This is gonna be so great.
  Just us sisters, back together again like when we were kids, except without
  that stupid Jill... Oh! Who has gotten fat by the way...

Rachel: (doesn't believe what she's hearing) Seriously?

Amy: hm-mmm... Mom said she gained like fifteen pounds.

Rachel: Hips or thighs?

Amy: Ass and face.

Rachel: (gasps) Oh! Oh my God! I thought she was on Atkins.

Amy: She was. Carbs found her... See, this is what I wanted. Two sisters, talking
  about real stuff.

Rachel: (embarrassed) Oh, I can give you that.

Amy: You can?

Rachel: Yeah. I just, I kept trying to make you a better person, but you're...
  you're already a pretty perfect version of what you are.

Amy: (touched) Thank you. I've got to admit, Emma does look
cute.

Rachel: Did you just say Emma?

Amy: Ugh, I'm sorry... Ella.

[Scene: Mike and Phoebe at a restaurant.]

Phoebe: That woman at the game didn't know what she was talking
  about. Mike, obviously you have balls.

Mike: But please, let's just forget the whole thing.

Phoebe: (the waiter puts a piece of cake on the table) I would love it. Consider
  it forgotten... But just so you know... however and whenever you decide to propose,
  I promise I'll say yes. Whether... whether, you know, it is in a basketball
  game, or in sky writing, or you know, like some lame guy in a cheesy movie who
  hides it in the cake.

(Mike's face changes from happy to sad, and he looks at the cake, disappointed.)

Phoebe: It's in the cake, isn't it?

Mike: (puts on a fake smile) Where else would lame Mr. No Balls hide it? (he
  takes the ring from the cake, and cleans it with a napkin)

Phoebe: What's the matter with me? How do I keep ruining this? I'm sorry, I'm
  sorry!

Mike: No! It's my fault. I keep trying to propose in these stupid ways and
  all I wanna do is tell you that I love you and I want to spend the rest of my
  life with you.

(Phoebe has this weird, anxious, nervous look on her face)

Mike: I'm gonna do this now.

Phoebe: Oh my God!

(Mike starts to kneel in front of Phoebe.)

Mike: Phoebe, I...

Phoebe: Wait! Oh wait! (she takes off a ring that was already on her left ring
  finger. After that Mike starts to kneel again, but then...) Oh no! (She was
  wearing rings on all her fingers and her thumb, and takes all of these off.)

Mike: Ready?

Phoebe: Uh-huh! (and now Mike kneels properly)

Mike: Phoebe, I love you. There's no-one else in the world I would ask to marry
  me... three times. But I wanna take care of you, have babies with you, and grow
  old with you... Phoebe Buffay, will you marry me?

Phoebe: Yes!

(Mike puts the ring on her finger)

Mike: I love you!

Phoebe: I love you more!

Mike: Not possible! (they kiss, and then Mike says proudly...) She's gonna
  be Mrs. No Balls.

(They kiss again, and Phoebe looks at the ring.)

COMMERCIAL BREAK

[Scene: The street in front of Central Perk. Rachel and Amy are
  walking on the sidewalk.]

Rachel: So how is the uhm... baby styling business going?

Amy: Not that great. It's almost if people don't want to hear that their babies
  are ugly.

Rachel: That's shocking!

Amy: Oh! It's Ross... Hey Ross! (She says hey to the guy at the falafel stand,
  whose only similarity with Ross would be his black hair.) Hello-oo Ross! (to
  Rachel) He's rude!

THE END


text:
package com.ashish.StackFromArray;

import com.ashish.StackFromArray.Stack;
import org.testng.annotations.Test;

import java.util.EmptyStackException;

/**
 * @author Ashish Sharma
 *         Created on 7/1/2015.
 */
public class StackTest {

    @Test(expectedExceptions = EmptyStackException.class)
    public void stackTest() {
        Stack<Integer> stack = new Stack<Integer>(10);

        stack.push(1);
        stack.push(2);
        stack.push(3);

        System.out.println(stack.peek());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.peek());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
}


text:
import { NotificationsProvider } from '@strapi/helper-plugin';
import React, { useReducer } from 'react';
import PropTypes from 'prop-types';
import { Stack } from '@strapi/design-system/Stack';
import Notification from './Notification';
import reducer, { initialState } from './reducer';

const Notifications = ({ children }) => {
  const [{ notifications }, dispatch] = useReducer(reducer, initialState);

  const displayNotification = config => {
    dispatch({
      type: 'SHOW_NOTIFICATION',
      config,
    });
  };

  return (
    <NotificationsProvider toggleNotification={displayNotification}>
      <Stack
        left="50%"
        marginLeft="-250px"
        position="fixed"
        spacing={2}
        top={`${46 / 16}rem`}
        width={`${500 / 16}rem`}
        zIndex={10}
      >
        {notifications.map(notification => {
          return (
            <Notification key={notification.id} dispatch={dispatch} notification={notification} />
          );
        })}
      </Stack>
      {children}
    </NotificationsProvider>
  );
};

Notifications.propTypes = {
  children: PropTypes.element.isRequired,
};

export default Notifications;


text:
/* global describe, it, loadBinaryResource, jsPDF, comparePdf */

describe("Module: Unicode: Arabic", function() {
  beforeAll(loadGlobals);
  //https://fonts.google.com/specimen/Amiri?selection.family=Amiri
  return;
  var AmiriRegular = loadBinaryResource("reference/Amiri-Regular.ttf");

  it("simple pdf with arabic text", function() {
    const doc = new jsPDF({
      filters: ["ASCIIHexEncode"],
      putOnlyUsedFonts: true
    });

    doc.addFileToVFS("Amiri-Regular.ttf", AmiriRegular);
    doc.addFont("Amiri-Regular.ttf", "Amiri", "normal");

    doc.setFont("Amiri"); // set font
    doc.setFontSize(50);

    var arabicText = "إذا لم تستح فاصنع ما شئت";

    doc.text(arabicText, 10, 60);

    comparePdf(doc.output(), "arabic.pdf", "unicode");
  });

  it("simple pdf with arabic text, right aligned", function() {
    const doc = new jsPDF({
      filters: ["ASCIIHexEncode"],
      putOnlyUsedFonts: true
    });

    doc.addFileToVFS("Amiri-Regular.ttf", AmiriRegular);
    doc.addFont("Amiri-Regular.ttf", "Amiri", "normal");

    doc.setFont("Amiri"); // set font
    doc.setFontSize(10);

    doc.text(
      ["إذا لم تستح فاصنع ما شئت", "إذا لم تستح", "فاصنع ما شئت"],
      200,
      10,
      { align: "right" }
    );

    comparePdf(doc.output(), "arabic-3lines-right.pdf", "unicode");
  });
});


text:
function make(Schema, mongoose, app) {
    // Define Car model

	console.log(Schema+mongoose);
	app.get('/updateadmin',function(req,res){
  res.sendfile("demos/admin/updateadmin.html");
});

}

function makedata(Schema, mongoose, app) {
    // Define Car model

app.get('/login',function(req,res){
  res.sendfile("demos/loginr.html");
});

app.get('/testdata',function(req,res){
  res.sendfile("demos/test.html");
});

app.get('/insertdata',function(req,res){
  res.sendfile("demos/insert.html");
});

app.get('/updatedata',function(req,res){
  res.sendfile("demos/update.html");
});

app.get('/deletedata',function(req,res){
  res.sendfile("demos/delete.html");
});

//admin
app.get('/createadmin',function(req,res){
  res.sendfile("demos/admin/createadmin.html");
});

app.get('/readadminr',function(req,res){
  res.sendfile("demos/admin/readadmin.html");
});

app.get('/updateadmin',function(req,res){
  res.sendfile("demos/admin/updateadmin.html");
});

app.get('/deleteadmin',function(req,res){
  res.sendfile("demos/admin/deleteadmin.html");
});

app.get('/createuseradmin',function(req,res){
  res.sendfile("demos/admin/createuseradmin.html");
});

app.get('/loginadmin',function(req,res){
  res.sendfile("demos/admin/loginadmin.html");
});

app.get('/dashboardadmin',function(req,res){
  res.sendfile("demos/admin/dashboard.html");
});

}

module.exports.make = make;
module.exports.makedata = makedata;


text:
package pro.usura.usuraknob.command;

import pro.usura.usuraknob.KnobView;

public class ResetCommand implements KnobCommand {

	private KnobView knobView;

	public ResetCommand(KnobView knobView) {
		this.knobView = knobView;
	}

	@Override
	public void execute(boolean isEnabled) {
		if (isEnabled) {
			knobView.animateTo(knobView.getStartingAngle());
		}
	}
}


text:
#define C_CFISH_OBJ
#define C_CFISH_CLASS
#define CFISH_USE_SHORT_NAMES

#include "charmony.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "Clownfish/Obj.h"
#include "Clownfish/String.h"
#include "Clownfish/Err.h"
#include "Clownfish/Hash.h"
#include "Clownfish/Class.h"
#include "Clownfish/Util/Memory.h"

Obj*
Obj_init(Obj *self) {
    ABSTRACT_CLASS_CHECK(self, OBJ);
    return self;
}

void
Obj_Destroy_IMP(Obj *self) {
    FREEMEM(self);
}

bool
Obj_is_a(Obj *self, Class *ancestor) {
    Class *klass = self ? self->klass : NULL;

    while (klass != NULL) {
        if (klass == ancestor) {
            return true;
        }
        klass = klass->parent;
    }

    return false;
}

bool
Obj_Equals_IMP(Obj *self, Obj *other) {
    return (self == other);
}

String*
Obj_To_String_IMP(Obj *self) {
#if (CHY_SIZEOF_PTR == 4)
    return Str_newf("%o@0x%x32", Obj_get_class_name(self), self);
#elif (CHY_SIZEOF_PTR == 8)
    int64_t   iaddress   = CHY_PTR_TO_I64(self);
    uint64_t  address    = (uint64_t)iaddress;
    uint32_t  address_hi = address >> 32;
    uint32_t  address_lo = address & 0xFFFFFFFF;
    return Str_newf("%o@0x%x32%x32", Obj_get_class_name(self), address_hi,
                    address_lo);
#else
  #error "Unexpected pointer size."
#endif
}

Class*
Obj_get_class(Obj *self) {
    return self->klass;
}

String*
Obj_get_class_name(Obj *self) {
    return Class_Get_Name(self->klass);
}


text:
import { ElementNavbarToggle } from '../elements'

export default {
  name: 'VkNavbarToggle',
  functional: true,
  props: ElementNavbarToggle.props,
  render: ElementNavbarToggle.render
}


text: Markdown text editor


text:
import Data.Array
import Common.Numbers.Primes (primesTo)

find num (p:ps) = if num * p > 1000000
    then num
    else find (num * p) ps

main = print $ find 1 (primesTo 1000)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Renner & Galloway, Mycotaxon 16(1): 202 (1982)

#### Original name
Pseudocyphellaria allanii D.J. Galloway

### Remarks
null


text:
class BaseSchedule {
	public static getSchedules() {
		//
	}

	public static startClosestPastEvent(schedule, callback) {
		callback();
	}

	public static setSchedules(schedule, callback) {
		callback();
	}

	public static cancelAllJobs() {
		//
	}

	public static getClosestPastSchedule(schedule) {
		//
	}
}

module.exports = {
	BaseSchedule,
};


text:
require 'pheromone'
require 'pheromone/messaging/message_formatter'
require 'pheromone/messaging/message'

# This module is used for sending messages to Kafka
# Dispatch method can be :sync or :async
# When dispatch_method is async, the message object is passed to a job
# the job needs to call `send!` on the WaterDrop::Message object
module Pheromone
  module Messaging
    class MessageDispatcher
      class NoSpecifiedProcessor < StandardError; end

      def initialize(message_parameters:, dispatch_method:)
        @message_parameters = message_parameters
        @dispatch_method = dispatch_method
      end

      def dispatch
        return unless Pheromone.enabled?
        if @dispatch_method == :sync
          Message.new(
            message_body.merge!(
              encoder: @message_parameters[:encoder],
              message_format: @message_parameters[:message_format]
            )
          ).send!
        elsif @dispatch_method == :async
          send_message_asynchronously
        end
      end

      private

      # Allows sending messages via resque or sidekiq. WaterDrop::Message object
      # is passed and calling `send!` on the object will trigger producing
      # messages to Kafka
      def send_message_asynchronously
        if background_processor.name == :resque
          Resque.enqueue(background_processor_klass, message_body)
        elsif background_processor.name == :sidekiq
          background_processor_klass.perform_async(message_body)
        elsif background_processor.name == :custom
          background_processor.custom_processor.call(background_processor_klass, message_body)
        else
          raise NoSpecifiedProcessor
        end
      end

      def message_body
        {
          topic: @message_parameters[:topic],
          blob: @message_parameters[:blob],
          metadata: @message_parameters[:metadata],
          options: @message_parameters[:producer_options] || {},
          embed_blob: @message_parameters[:embed_blob]
        }
      end

      def background_processor
        Pheromone.config.background_processor
      end

      def background_processor_klass
        @klass ||= background_processor.klass.constantize
      end
    end
  end
end


text:
var MatchesForRoundPage = (function() {

	var userBonus,
		maxBonusPerMatch;

	var MatchViewModel = function(params) {
		this.id = params.matchID;
		this.firstTeamGoals = ko.observable(params.firstTeamGoals);
		this.secondTeamGoals = ko.observable(params.secondTeamGoals);
		this.bonus = ko.observable(parseInt(params.bonus || 0));
	};

	var MatchBetViewModel = function(params) {

		var self = this;

		this.$page = params.$page;
		this.$row = params.$row;
		this.$betRow = params.$betRow;
		this.$btnTrigger = params.$btnTrigger;

		this.matchViewModel = new MatchViewModel(params);
		this.savedMatchViewModel = new MatchViewModel(params);

		this.maxBonusPerMatch = maxBonusPerMatch;
		this.maxUserBonus = ko.observable(Math.min(parseInt(userBonus) + this.matchViewModel.bonus(), maxBonusPerMatch));

		this.save = function () {

		    var $btnSave = self.$betRow.find('.btn-save'),
                $container = $btnSave.parent();

		    $btnSave.removeClass("invalid");

			//validate
			if (self.matchViewModel.firstTeamGoals() == '' || self.matchViewModel.secondTeamGoals() == '') {
			    $btnSave.addClass("invalid");
			    setTimeout(function () {
			        $btnSave.removeClass("invalid");
			    }, 200);
				return;
			}

			//inline block
			$btnSave.parents('.cell-BetAction').toggleClass('loading');
			$btnSave.attr('disabled', true);

			AjaxUtils.post({
				url				:	self.$page.data('pagetype') + '/Add',
				json			:	true,
				data			:	ko.toJSON(self.matchViewModel),
				dataType		:	"json",
				success			:	function (response) {

										//refresh user bonus
										userBonus = parseInt(response.UserBonus);
										self.maxUserBonus(Math.min(self.matchViewModel.bonus() + userBonus, maxBonusPerMatch));

										if (response.Success === false)
										    $btnSave.addClass("invalid");
										else
										    self.endEdit();

										$btnSave.parents('.cell-BetAction').toggleClass('loading');
										$btnSave.removeAttr('disabled').removeClass('loading');

                                        // update listing row UI
										var $rowBonusElement = self.$row.find('.bonus-single');
										if (self.matchViewModel.bonus()) {
										    $rowBonusElement.removeClass('hidden');
										}
										else {
										    $rowBonusElement.addClass('hidden');
										}
									},
				error			:	function () {
				                        $btnSave.addClass("invalid");

				                        $btnSave.parents('.cell-BetAction').toggleClass('loading');
				                        $btnSave.removeAttr('disabled').removeClass('loading');
									}
			});
		};

		this.saveOnEnter = function(model, event) {

			//enter
			if (event.which == 13)
				model.save();

			return true;
		};

		this.endEdit = function () {

			//reset UI
			Utils.unblockElement(self.$betRow.find('.btn-save').parent());
			self.$betRow.addClass('hide').removeClass('invalid');
			self.$btnTrigger.removeClass('hide');

			//set changes in saved match
			self.savedMatchViewModel.bonus(self.matchViewModel.bonus());
			self.savedMatchViewModel.firstTeamGoals(self.matchViewModel.firstTeamGoals());
			self.savedMatchViewModel.secondTeamGoals(self.matchViewModel.secondTeamGoals());

			//hide warning
			self.$row.find('.bet-warning').replaceWith($("<span>", { html: " - " }));
		};

		this.updateBonusPoints = function () {

			var $this = $(this),
				val = $this.data('val'),
				newValue = parseInt(self.matchViewModel.bonus() + parseInt(val));

			if (!newValue || newValue < 0)
				newValue = 0;

			if (newValue > self.maxUserBonus())
				newValue = self.maxUserBonus();

			if (newValue > maxBonusPerMatch)
				newValue = maxBonusPerMatch;

			self.matchViewModel.bonus(newValue);
		};
	};

	function init() {

		var betTemplate;

		maxBonusPerMatch = $('#fld-max-bonus').val();
		userBonus = $('#UserBonus').val();
		betTemplate = $("#bet-template").html();

		//show bet container when clicking on bet button
		$('#listing-matchesforcurrentround,#listing-matchesfornextround').delegate('.btn-bet', 'click', function () {

			//if another bet row is shown, hide it
			$('.btn-bet').removeClass('hide');
			$('tr[class*=bet-row]').remove();

			var	$this = $(this),
				$row = $this.parents('tr:first'),
				$page = $this.parents('.listing-page:first');

			//hide bet button
			$this.addClass('hide');

			//make sure to bind only once
			if ($row.next().hasClass('hide')) {
				$row.next().removeClass('hide');
				return;
			}

			var	matchID = $row.data('id'),
				$betRow = $(betTemplate).addClass('bet-row-' + matchID),
				betViewModel;

			//add bet row after current row
			$row.after($betRow);
			$row.addClass('row-' + matchID);

			//validate entered bonus
			$betRow.find('#Bonus').keyup(function (e) {

				if (e.which == 8) //backspace
					return true;

				var $this = $(this),
					val = parseInt($this.val());

				if (!val)
					val = 0;
				else if (val < 0)
					val = 0;
				else if (val > betViewModel.maxUserBonus())
					val = betViewModel.maxUserBonus();

				if (val > maxBonusPerMatch)
					val = maxBonusPerMatch;

				$this.val(val);
			});

			//create view model
			betViewModel = new MatchBetViewModel({
				$page			:	$page,
				$betRow			:	$betRow,
				$row			:	$row,
				$btnTrigger		:	$this,
				matchID			:	matchID,
				firstTeamGoals	:	$row.find('.FirstTeamGoals').text(),
				secondTeamGoals	:	$row.find('.SecondTeamGoals').text(),
				bonus			:	$row.find('.Bonus').text()
			});

			var $btnSingle = $betRow.find('.btn-bonus-single');

			if (betViewModel.bonus) {
			    $btnSingle.addClass('selected');
			}
			else {
			    $btnSingle.removeClass('selected');
			}

			//create and apply bet row bindings
			ko.bindingConventions.conventions({
				".btn-save"			:	{ 	click	:	function(viewModel, event) {
															viewModel.save();
														}
										},
				'#FirstTeamGoals'	:	function(viewModel) {
											return { value : viewModel.matchViewModel.firstTeamGoals, event : { keyup : viewModel.saveOnEnter } };
										},
				'#SecondTeamGoals'	:	function(viewModel) {
											return { value : viewModel.matchViewModel.secondTeamGoals, event : { keyup : viewModel.saveOnEnter } };
										},
				'#Bonus'			:	function(viewModel) {
											return { value : viewModel.matchViewModel.bonus, event : { keyup : viewModel.saveOnEnter } };
										},
				'.MaxUserBonus'		:	function(viewModel) {
											return { text: viewModel.maxUserBonus }
										},
				'.btn-bonus'		:	{	click	:	function(viewModel, event) {
															viewModel.updateBonusPoints.call(event.target);
														}
										},
				'.btn-bonus-single':    {
                                            click   :   function(viewModel, event) {

                                                            var $element = $(event.target);
                                                            $element.toggleClass('selected');

                                                            var bonus = $element.hasClass('selected') ? 1 : 0;
                                                            viewModel.matchViewModel.bonus(bonus);

                                                            $row.find('.Bonus').text(bonus);
                                                        }
                        				}
			});

			ko.applyBindings(betViewModel, $betRow[0]);

			//create and apply listing row bindings
			ko.bindingConventions.conventions({
				'.FirstTeamGoals'	:	function(viewModel) {
											return { text : viewModel.firstTeamGoals };
										},
				'.SecondTeamGoals'	:	function(viewModel) {
											return { text : viewModel.secondTeamGoals };
										}
			});

			ko.applyBindings(betViewModel.savedMatchViewModel, $row[0]);

			//set focus on first team
			$betRow.find('#FirstTeamGoals').focus();
		});

		Bootstrapper.bindMatchView('MatchesForCurrentRound');
	}

	return {
		init	:	init
	};
}());

$(function() { MatchesForRoundPage.init(); })