text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MeshGeometryHelper.cs" company="Helix Toolkit">
//   Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// <summary>
//   Provides helper methods for mesh geometries.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#if SHARPDX
#if NETFX_CORE
#if CORE
namespace HelixToolkit.SharpDX.Core
#else
namespace HelixToolkit.UWP
#endif
#else
namespace HelixToolkit.Wpf.SharpDX
#endif
#else
namespace HelixToolkit.Wpf
#endif
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Text;
#if SHARPDX
    using Vector3D = global::SharpDX.Vector3;
    using Point3D = global::SharpDX.Vector3;
    using Point = global::SharpDX.Vector2;
    using Int32Collection = IntCollection;
    using Vector3DCollection = Vector3Collection;
    using Point3DCollection = Vector3Collection;
    using PointCollection = Vector2Collection;
    using DoubleOrSingle = System.Single;
#else
    using System.Windows;
    using System.Windows.Media;
    using System.Windows.Media.Media3D;

    using DoubleOrSingle = System.Double;
#endif

    /// <summary>
    /// Provides helper methods for mesh geometries.
    /// </summary>
    public static class MeshGeometryHelper
    {
        // Optimizing 3D Collections in WPF
        // http://blogs.msdn.com/timothyc/archive/2006/08/31/734308.aspx
        // - Remember to disconnect collections from the MeshGeometry when changing it

        /// <summary>
        /// Calculates the normal vectors.
        /// </summary>
        /// <param name="mesh">
        /// The mesh.
        /// </param>
        /// <returns>
        /// Collection of normal vectors.
        /// </returns>
        public static Vector3DCollection CalculateNormals(this MeshGeometry3D mesh)
        {
            return CalculateNormals(mesh.Positions, mesh.TriangleIndices);
        }

        /// <summary>
        /// Calculates the normal vectors.
        /// </summary>
        /// <param name="positions">
        /// The positions.
        /// </param>
        /// <param name="triangleIndices">
        /// The triangle indices.
        /// </param>
        /// <returns>
        /// Collection of normal vectors.
        /// </returns>
        public static Vector3DCollection CalculateNormals(IList<Point3D> positions, IList<int> triangleIndices)
        {
            var normals = new Vector3DCollection(positions.Count);
            for (var i = 0; i < positions.Count; i++)
            {
                normals.Add(new Vector3D());
            }

            for (var i = 0; i < triangleIndices.Count; i += 3)
            {
                var index0 = triangleIndices[i];
                var index1 = triangleIndices[i + 1];
                var index2 = triangleIndices[i + 2];
                var p0 = positions[index0];
                var p1 = positions[index1];
                var p2 = positions[index2];
                var u = p1 - p0;
                var v = p2 - p0;
                var w = SharedFunctions.CrossProduct(ref u, ref v);
                w.Normalize();
                normals[index0] += w;
                normals[index1] += w;
                normals[index2] += w;
            }

            for (var i = 0; i < normals.Count; i++)
            {
                var n = normals[i];
                n.Normalize();
                normals[i] = n;
            }

            return normals;
        }

        /// <summary>
        /// Finds edges that are only connected to one triangle.
        /// </summary>
        /// <param name="mesh">
        /// A mesh geometry.
        /// </param>
        /// <returns>
        /// The edge indices for the edges that are only used by one triangle.
        /// </returns>
        public static Int32Collection FindBorderEdges(this MeshGeometry3D mesh)
        {
            var dict = new Dictionary<ulong, int>();

            for (var i = 0; i < mesh.TriangleIndices.Count / 3; i++)
            {
                var i0 = i * 3;
                for (var j = 0; j < 3; j++)
                {
                    var index0 = mesh.TriangleIndices[i0 + j];
                    var index1 = mesh.TriangleIndices[i0 + ((j + 1) % 3)];
                    var minIndex = Math.Min(index0, index1);
                    var maxIndex = Math.Max(index1, index0);
                    var key = CreateKey((uint)minIndex, (uint)maxIndex);
                    if (dict.ContainsKey(key))
                    {
                        dict[key] = dict[key] + 1;
                    }
                    else
                    {
                        dict.Add(key, 1);
                    }
                }
            }

            var edges = new Int32Collection();
            foreach (var kvp in dict)
            {
                // find edges only used by 1 triangle
                if (kvp.Value == 1)
                {
                    uint i0, i1;
                    ReverseKey(kvp.Key, out i0, out i1);
                    edges.Add((int)i0);
                    edges.Add((int)i1);
                }
            }

            return edges;
        }

        /// <summary>
        /// Finds all edges in the mesh (each edge is only included once).
        /// </summary>
        /// <param name="mesh">
        /// A mesh geometry.
        /// </param>
        /// <returns>
        /// The edge indices (minimum index first).
        /// </returns>
        public static Int32Collection FindEdges(this MeshGeometry3D mesh)
        {
            var edges = new Int32Collection();
            var dict = new HashSet<ulong>();

            for (var i = 0; i < mesh.TriangleIndices.Count / 3; i++)
            {
                var i0 = i * 3;
                for (var j = 0; j < 3; j++)
                {
                    var index0 = mesh.TriangleIndices[i0 + j];
                    var index1 = mesh.TriangleIndices[i0 + ((j + 1) % 3)];
                    var minIndex = Math.Min(index0, index1);
                    var maxIndex = Math.Max(index1, index0);
                    var key = CreateKey((uint)minIndex, (uint)maxIndex);
                    if (!dict.Contains(key))
                    {
                        edges.Add(minIndex);
                        edges.Add(maxIndex);
                        dict.Add(key);
                    }
                }
            }

            return edges;
        }

        private struct EdgeKey
        {
            private readonly Vector3D position0;
            private readonly Vector3D position1;
            public EdgeKey(Vector3D position0, Vector3D position1)
            {
                this.position0 = position0;
                this.position1 = position1;
            }
        }
        /// <summary>
        /// Finds all edges where the angle between adjacent triangle normal vectors.
        /// is larger than minimumAngle
        /// </summary>
        /// <param name="mesh">
        /// A mesh geometry.
        /// </param>
        /// <param name="minimumAngle">
        /// The minimum angle between the normal vectors of two adjacent triangles (degrees).
        /// </param>
        /// <returns>
        /// The edge indices.
        /// </returns>
        public static Int32Collection FindSharpEdges(this MeshGeometry3D mesh, double minimumAngle)
        {
            var edgeIndices = new Int32Collection();
            var edgeNormals = new Dictionary<EdgeKey, Vector3D>();
            for (var i = 0; i < mesh.TriangleIndices.Count / 3; i++)
            {
                var i0 = i * 3;
                var p0 = mesh.Positions[mesh.TriangleIndices[i0]];
                var p1 = mesh.Positions[mesh.TriangleIndices[i0 + 1]];
                var p2 = mesh.Positions[mesh.TriangleIndices[i0 + 2]];
                var triangleNormal = SharedFunctions.CrossProduct(p1 - p0, p2 - p0);

                // Handle degenerated triangles.
                if (SharedFunctions.LengthSquared(ref triangleNormal) < 0.001f)
                    continue;

                triangleNormal.Normalize();
                for (var j = 0; j < 3; j++)
                {
                    var index0 = mesh.TriangleIndices[i0 + j];
                    var index1 = mesh.TriangleIndices[i0 + (j + 1) % 3];
                    var position0 = SharedFunctions.ToVector3D(mesh.Positions[index0]);
                    var position1 = SharedFunctions.ToVector3D(mesh.Positions[index1]);
                    var edgeKey = new EdgeKey(position0, position1);
                    var reverseEdgeKey = new EdgeKey(position1, position0);
                    if (edgeNormals.TryGetValue(edgeKey, out var value) ||
                        edgeNormals.TryGetValue(reverseEdgeKey, out value))
                    {
                        var rawDot = SharedFunctions.DotProduct(ref triangleNormal, ref value);

                        // Acos returns NaN if rawDot > 1 or rawDot < -1
                        var dot = Math.Max(-1, Math.Min(rawDot, 1));

                        var angle = 180 / Math.PI * Math.Acos(dot);
                        if (angle > minimumAngle)
                        {
                            edgeIndices.Add(index0);
                            edgeIndices.Add(index1);
                        }
                    }
                    else
                    {
                        edgeNormals.Add(edgeKey, triangleNormal);
                    }
                }
            }
            return edgeIndices;
        }

        /// <summary>
        /// Creates a new mesh where no vertices are shared.
        /// </summary>
        /// <param name="input">
        /// The input mesh.
        /// </param>
        /// <returns>
        /// A new mesh.
        /// </returns>
        public static MeshGeometry3D NoSharedVertices(this MeshGeometry3D input)
        {
            var p = new Point3DCollection();
            var ti = new Int32Collection();
            Vector3DCollection n = null;
            if (input.Normals != null)
            {
                n = new Vector3DCollection();
            }

            PointCollection tc = null;
            if (input.TextureCoordinates != null)
            {
                tc = new PointCollection();
            }

            for (var i = 0; i < input.TriangleIndices.Count; i += 3)
            {
                var i0 = i;
                var i1 = i + 1;
                var i2 = i + 2;
                var index0 = input.TriangleIndices[i0];
                var index1 = input.TriangleIndices[i1];
                var index2 = input.TriangleIndices[i2];
                var p0 = input.Positions[index0];
                var p1 = input.Positions[index1];
                var p2 = input.Positions[index2];
                p.Add(p0);
                p.Add(p1);
                p.Add(p2);
                ti.Add(i0);
                ti.Add(i1);
                ti.Add(i2);
                if (n != null && input.Normals.Count>0)
                {
                    n.Add(input.Normals[index0]);
                    n.Add(input.Normals[index1]);
                    n.Add(input.Normals[index2]);
                }

                if (tc != null)
                {
                    tc.Add(input.TextureCoordinates[index0]);
                    tc.Add(input.TextureCoordinates[index1]);
                    tc.Add(input.TextureCoordinates[index2]);
                }
            }

#if SHARPDX
            return new MeshGeometry3D { Positions = p, TriangleIndices = new IntCollection(ti), Normals = n, TextureCoordinates = tc };
#else
            return new MeshGeometry3D { Positions = p, TriangleIndices = ti, Normals = n, TextureCoordinates = tc };
#endif
        }

        /// <summary>
        /// Simplifies the specified mesh.
        /// </summary>
        /// <param name="mesh">
        /// The mesh.
        /// </param>
        /// <param name="eps">
        /// The tolerance.
        /// </param>
        /// <returns>
        /// A simplified mesh.
        /// </returns>
        public static MeshGeometry3D Simplify(this MeshGeometry3D mesh, DoubleOrSingle eps)
        {
            // Find common positions
            var dict = new Dictionary<int, int>(); // map position index to first occurence of same position
            for (var i = 0; i < mesh.Positions.Count; i++)
            {
                for (var j = i + 1; j < mesh.Positions.Count; j++)
                {
                    if (dict.ContainsKey(j))
                    {
                        continue;
                    }
                    var v = mesh.Positions[i] - mesh.Positions[j];
                    var l2 = SharedFunctions.LengthSquared(ref v);
                    if (l2 < eps)
                    {
                        dict.Add(j, i);
                    }
                }
            }

            var p = new Point3DCollection();
            var ti = new Int32Collection();

            // create new positions array
            var newIndex = new Dictionary<int, int>(); // map old index to new index
            for (var i = 0; i < mesh.Positions.Count; i++)
            {
                if (!dict.ContainsKey(i))
                {
                    newIndex.Add(i, p.Count);
                    p.Add(mesh.Positions[i]);
                }
            }

            // Update triangle indices
            foreach (var index in mesh.TriangleIndices)
            {
                int j;
                ti.Add(dict.TryGetValue(index, out j) ? newIndex[j] : newIndex[index]);
            }
#if SHARPDX
            var result = new MeshGeometry3D { Positions = p, TriangleIndices = new IntCollection(ti), };
#else
            var result = new MeshGeometry3D { Positions = p, TriangleIndices = ti };
#endif
            return result;
        }

        /// <summary>
        /// Validates the specified mesh.
        /// </summary>
        /// <param name="mesh">The mesh.</param>
        /// <returns>Validation report or null if no issues were found.</returns>
        public static string Validate(this MeshGeometry3D mesh)
        {
            var sb = new StringBuilder();
            if (mesh.Normals != null && mesh.Normals.Count != 0 && mesh.Normals.Count != mesh.Positions.Count)
            {
                sb.AppendLine("Wrong number of normal vectors");
            }

            if (mesh.TextureCoordinates != null && mesh.TextureCoordinates.Count != 0
                && mesh.TextureCoordinates.Count != mesh.Positions.Count)
            {
                sb.AppendLine("Wrong number of TextureCoordinates");
            }

            if (mesh.TriangleIndices.Count % 3 != 0)
            {
                sb.AppendLine("TriangleIndices not complete");
            }

            for (var i = 0; i < mesh.TriangleIndices.Count; i++)
            {
                var index = mesh.TriangleIndices[i];
                if (index < 0 || index >= mesh.Positions.Count)
                {
                    sb.AppendFormat("Wrong index {0} in triangle {1} vertex {2}", index, i / 3, i % 3);
                    sb.AppendLine();
                }
            }

            return sb.Length > 0 ? sb.ToString() : null;
        }

        /// <summary>
        /// Cuts the mesh with the specified plane.
        /// </summary>
        /// <param name="mesh">
        /// The mesh.
        /// </param>
        /// <param name="plane">
        /// The plane origin.
        /// </param>
        /// <param name="normal">
        /// The plane normal.
        /// </param>
        /// <returns>
        /// The <see cref="MeshGeometry3D"/>.
        /// </returns>
        public static MeshGeometry3D Cut(this MeshGeometry3D mesh, Point3D plane, Vector3D normal)
        {
            var hasTextureCoordinates = mesh.TextureCoordinates != null && mesh.TextureCoordinates.Count > 0;
            var hasNormals = mesh.Normals != null && mesh.Normals.Count > 0;
            var meshBuilder = new MeshBuilder(hasNormals, hasTextureCoordinates);
            var contourHelper = new ContourHelper(plane, normal, mesh);
            foreach (var position in mesh.Positions)
            {
                meshBuilder.Positions.Add(position);
            }

            if (hasTextureCoordinates)
            {
                foreach (var textureCoordinate in mesh.TextureCoordinates)
                {
                    meshBuilder.TextureCoordinates.Add(textureCoordinate);
                }
            }

            if (hasNormals)
            {
                foreach (var n in mesh.Normals)
                {
                    meshBuilder.Normals.Add(n);
                }
            }

            for (var i = 0; i < mesh.TriangleIndices.Count; i += 3)
            {
                var index0 = mesh.TriangleIndices[i];
                var index1 = mesh.TriangleIndices[i + 1];
                var index2 = mesh.TriangleIndices[i + 2];

                Point3D[] positions;
                Vector3D[] normals;
                Point[] textureCoordinates;
                int[] triangleIndices;

                contourHelper.ContourFacet(index0, index1, index2, out positions, out normals, out textureCoordinates, out triangleIndices);

                foreach (var p in positions)
                {
                    meshBuilder.Positions.Add(p);
                }

                foreach (var tc in textureCoordinates)
                {
                    meshBuilder.TextureCoordinates.Add(tc);
                }

                foreach (var n in normals)
                {
                    meshBuilder.Normals.Add(n);
                }

                foreach (var ti in triangleIndices)
                {
                    meshBuilder.TriangleIndices.Add(ti);
                }
            }

            return meshBuilder.ToMesh();
        }

        /// <summary>
        /// Gets the contour segments.
        /// </summary>
        /// <param name="mesh">
        /// The mesh.
        /// </param>
        /// <param name="plane">
        /// The plane origin.
        /// </param>
        /// <param name="normal">
        /// The plane normal.
        /// </param>
        /// <returns>
        /// The segments of the contour.
        /// </returns>
        public static IList<Point3D> GetContourSegments(this MeshGeometry3D mesh, Point3D plane, Vector3D normal)
        {
            var segments = new List<Point3D>();
            var contourHelper = new ContourHelper(plane, normal, mesh);
            for (var i = 0; i < mesh.TriangleIndices.Count; i += 3)
            {
                Point3D[] positions;
                Vector3D[] normals;
                Point[] textureCoordinates;
                int[] triangleIndices;

                contourHelper.ContourFacet(
                    mesh.TriangleIndices[i],
                    mesh.TriangleIndices[i + 1],
                    mesh.TriangleIndices[i + 2],
                    out positions,
                    out normals,
                    out textureCoordinates,
                    out triangleIndices);
                segments.AddRange(positions);
            }

            return segments;
        }

        /// <summary>
        /// Combines the segments.
        /// </summary>
        /// <param name="segments">
        /// The segments.
        /// </param>
        /// <param name="eps">
        /// The tolerance.
        /// </param>
        /// <returns>
        /// Enumerated connected contour curves.
        /// </returns>
        public static IEnumerable<IList<Point3D>> CombineSegments(IList<Point3D> segments, DoubleOrSingle eps)
        {
            // This is a simple, slow, naïve method - should be improved:
            // http://stackoverflow.com/questions/1436091/joining-unordered-line-segments
            var curve = new List<Point3D>();
            var curveCount = 0;

            var segmentCount = segments.Count;
            int segment1 = -1, segment2 = -1;
            while (segmentCount > 0)
            {
                if (curveCount > 0)
                {
                    // Find a segment that is connected to the head of the contour
                    segment1 = FindConnectedSegment(segments, curve[0], eps);
                    if (segment1 >= 0)
                    {
                        if (segment1 % 2 == 1)
                        {
                            curve.Insert(0, segments[segment1 - 1]);
                            segments.RemoveAt(segment1 - 1);
                            segments.RemoveAt(segment1 - 1);
                        }
                        else
                        {
                            curve.Insert(0, segments[segment1 + 1]);
                            segments.RemoveAt(segment1);
                            segments.RemoveAt(segment1);
                        }

                        curveCount++;
                        segmentCount -= 2;
                    }

                    // Find a segment that is connected to the tail of the contour
                    segment2 = FindConnectedSegment(segments, curve[curveCount - 1], eps);
                    if (segment2 >= 0)
                    {
                        if (segment2 % 2 == 1)
                        {
                            curve.Add(segments[segment2 - 1]);
                            segments.RemoveAt(segment2 - 1);
                            segments.RemoveAt(segment2 - 1);
                        }
                        else
                        {
                            curve.Add(segments[segment2 + 1]);
                            segments.RemoveAt(segment2);
                            segments.RemoveAt(segment2);
                        }

                        curveCount++;
                        segmentCount -= 2;
                    }
                }

                if ((segment1 < 0 && segment2 < 0) || segmentCount == 0)
                {
                    if (curveCount > 0)
                    {
                        yield return curve;
                        curve = new List<Point3D>();
                        curveCount = 0;
                    }

                    if (segmentCount > 0)
                    {
                        curve.Add(segments[0]);
                        curve.Add(segments[1]);
                        curveCount += 2;
                        segments.RemoveAt(0);
                        segments.RemoveAt(0);
                        segmentCount -= 2;
                    }
                }
            }
        }

        /// <summary>
        /// Create a 64-bit key from two 32-bit indices
        /// </summary>
        /// <param name="i0">
        /// The i 0.
        /// </param>
        /// <param name="i1">
        /// The i 1.
        /// </param>
        /// <returns>
        /// The create key.
        /// </returns>
        private static ulong CreateKey(uint i0, uint i1)
        {
            return ((ulong)i0 << 32) + i1;
        }

        /// <summary>
        /// Extract two 32-bit indices from the 64-bit key
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <param name="i0">
        /// The i 0.
        /// </param>
        /// <param name="i1">
        /// The i 1.
        /// </param>
        private static void ReverseKey(ulong key, out uint i0, out uint i1)
        {
            i0 = (uint)(key >> 32);
            i1 = (uint)((key << 32) >> 32);
        }

        /// <summary>
        /// Finds the nearest connected segment to the specified point.
        /// </summary>
        /// <param name="segments">
        /// The segments.
        /// </param>
        /// <param name="point">
        /// The point.
        /// </param>
        /// <param name="eps">
        /// The tolerance.
        /// </param>
        /// <returns>
        /// The index of the nearest point.
        /// </returns>
        private static int FindConnectedSegment(IList<Point3D> segments, Point3D point, DoubleOrSingle eps)
        {
            var best = eps;
            var result = -1;
            for (var i = 0; i < segments.Count; i++)
            {
                var v = point - segments[i];
                var ls0 = SharedFunctions.LengthSquared(ref v);
                if (ls0 < best)
                {
                    result = i;
                    best = ls0;
                }
            }

            return result;
        }

        /// <summary>
        /// Remove isolated(not connected to any triangles) vertices
        /// </summary>
        /// <param name="mesh"></param>
        /// <returns></returns>
        public static MeshGeometry3D RemoveIsolatedVertices(this MeshGeometry3D mesh)
        {
            Point3DCollection vertNew;
            Int32Collection triNew;
            PointCollection textureNew;
            Vector3DCollection normalNew;
            RemoveIsolatedVertices(mesh.Positions, mesh.TriangleIndices, mesh.TextureCoordinates, mesh.Normals, out vertNew, out triNew, out textureNew, out normalNew);
            var newMesh = new MeshGeometry3D() { Positions = vertNew, TriangleIndices = triNew, TextureCoordinates = textureNew, Normals = normalNew };
            return newMesh;
        }

        /// <summary>
        /// Remove isolated(not connected to any triangles) vertices
        /// </summary>
        /// <param name="vertices"></param>
        /// <param name="triangles"></param>
        /// <param name="texture"></param>
        /// <param name="normals"></param>
        /// <param name="verticesOut"></param>
        /// <param name="trianglesOut"></param>
        /// <param name="textureOut"></param>
        /// <param name="normalOut"></param>
        public static void RemoveIsolatedVertices(IList<Point3D> vertices, IList<int> triangles, IList<Point> texture, IList<Vector3D> normals,
            out Point3DCollection verticesOut, out Int32Collection trianglesOut, out PointCollection textureOut, out Vector3DCollection normalOut)
        {
            verticesOut = null;
            trianglesOut = null;
            textureOut = null;
            normalOut = null;
            var tracking = new List<List<int>>(vertices.Count);
            Debug.WriteLine(string.Format("NumVert:{0}; NumTriangle:{1};", vertices.Count, triangles.Count));
            for (var i = 0; i < vertices.Count; ++i)
            {
                tracking.Add(new List<int>());
            }
            for (var i = 0; i < triangles.Count; ++i)
            {
                tracking[triangles[i]].Add(i);
            }

            var vertToRemove = new List<int>(vertices.Count);
            for (var i = 0; i < vertices.Count; ++i)
            {
                if (tracking[i].Count == 0)
                {
                    vertToRemove.Add(i);
                }
            }
            verticesOut = new Point3DCollection(vertices.Count - vertToRemove.Count);
            trianglesOut = new Int32Collection(triangles);
            if (texture != null)
            {
                textureOut = new PointCollection(vertices.Count - vertToRemove.Count);
            }
            if (normals != null)
            {
                normalOut = new Vector3DCollection(vertices.Count - vertToRemove.Count);
            }
            if (vertices.Count == vertToRemove.Count)
            {
                return;
            }
            var counter = 0;
            for (var i = 0; i < vertices.Count; ++i)
            {
                if (counter == vertToRemove.Count || i < vertToRemove[counter])
                {
                    verticesOut.Add(vertices[i]);
                    if (texture != null)
                    {
                        textureOut.Add(texture[i]);
                    }
                    if (normals != null)
                    {
                        normalOut.Add(normals[i]);
                    }
                    foreach (var t in tracking[i])
                    {
                        trianglesOut[t] -= counter;
                    }
                }
                else
                {
                    ++counter;
                }
            }
            Debug.WriteLine(string.Format("Remesh finished. Output NumVert:{0};", verticesOut.Count));
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="triangles"></param>
        /// <param name="numVerts"></param>
        public static void RemoveOutOfRangeTriangles(this IList<int> triangles, int numVerts)
        {
            var removeOutOfRangeTriangles = new List<int>();
            for (var i = 0; i < triangles.Count; i += 3)
            {
                if (triangles[i] >= numVerts || triangles[i + 1] >= numVerts || triangles[i + 2] >= numVerts)
                {
                    removeOutOfRangeTriangles.Add(i);
                }
            }
            if (removeOutOfRangeTriangles.Count > 0)
            {
                removeOutOfRangeTriangles.Reverse();
                foreach (var idx in removeOutOfRangeTriangles)
                {
                    removeOutOfRangeTriangles.RemoveRange(idx, 3);
                }
            }
        }

        public static Point3D GetCentroid(this IList<Point3D> vertices)
        {
            if (vertices.Count == 0)
            {
                return default;
            }
            var centroid = vertices[0];
            for (var i = 1; i < vertices.Count; i++)
            {
                centroid += (vertices[i] - centroid) / (i + 1);
            }
            return centroid;
        }
    }
}


text:
<?php

namespace app\classes;

/**
 * Security class
 *
 * Class Security
 * @package app\classes
 * @author  Juan Monsalve
 */
class Security{

    CONST ENCRYPT_METHOD = "AES-256-CBC";

    CONST SECRET_KEY = 'ijsb';

    CONST SECRET_IV = 'ijsb123';

    public static function getInstance(){

    	return new self();
    }

	public function encrypt($string){

		$output = false;

		// hash
    	$key = hash('sha256', self::SECRET_KEY);

    	// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
    	$iv = substr(hash('sha256', self::SECRET_IV), 0, 16);

    	$output = openssl_encrypt($string, self::ENCRYPT_METHOD, $key, 0, $iv);
        $output = base64_encode($output);

		return $output;
	}

	public function decrypt($string){

		// hash
    	$key = hash('sha256', self::SECRET_KEY);

	    // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
	    $iv = substr(hash('sha256', self::SECRET_IV), 0, 16);
		//decrypt the given text/string/number
        $output = openssl_decrypt(base64_decode($string), self::ENCRYPT_METHOD, $key, 0, $iv);

        return $output;
	}
}

?>

redpajama_set_name: RedPajamaGithub


text:
package spark.rdd

import java.util.{HashMap => JHashMap}
import scala.collection.JavaConversions._
import scala.collection.mutable.ArrayBuffer
import spark.RDD
import spark.Partitioner
import spark.Dependency
import spark.TaskContext
import spark.Partition
import spark.SparkEnv
import spark.ShuffleDependency
import spark.OneToOneDependency

/**
 * An optimized version of cogroup for set difference/subtraction.
 *
 * It is possible to implement this operation with just `cogroup`, but
 * that is less efficient because all of the entries from `rdd2`, for
 * both matching and non-matching values in `rdd1`, are kept in the
 * JHashMap until the end.
 *
 * With this implementation, only the entries from `rdd1` are kept in-memory,
 * and the entries from `rdd2` are essentially streamed, as we only need to
 * touch each once to decide if the value needs to be removed.
 *
 * This is particularly helpful when `rdd1` is much smaller than `rdd2`, as
 * you can use `rdd1`'s partitioner/partition size and not worry about running
 * out of memory because of the size of `rdd2`.
 */
private[spark] class SubtractedRDD[K: ClassManifest, V: ClassManifest, W: ClassManifest](
    @transient var rdd1: RDD[(K, V)],
    @transient var rdd2: RDD[(K, W)],
    part: Partitioner,
    val serializerClass: String = null)
  extends RDD[(K, V)](rdd1.context, Nil) {

  override def getDependencies: Seq[Dependency[_]] = {
    Seq(rdd1, rdd2).map { rdd =>
      if (rdd.partitioner == Some(part)) {
        logInfo("Adding one-to-one dependency with " + rdd)
        new OneToOneDependency(rdd)
      } else {
        logInfo("Adding shuffle dependency with " + rdd)
        new ShuffleDependency(rdd.asInstanceOf[RDD[(K, Any)]], part, serializerClass)
      }
    }
  }

  override def getPartitions: Array[Partition] = {
    val array = new Array[Partition](part.numPartitions)
    for (i <- 0 until array.size) {
      // Each CoGroupPartition will depend on rdd1 and rdd2
      array(i) = new CoGroupPartition(i, Seq(rdd1, rdd2).zipWithIndex.map { case (rdd, j) =>
        dependencies(j) match {
          case s: ShuffleDependency[_, _] =>
            new ShuffleCoGroupSplitDep(s.shuffleId)
          case _ =>
            new NarrowCoGroupSplitDep(rdd, i, rdd.partitions(i))
        }
      }.toArray)
    }
    array
  }

  override val partitioner = Some(part)

  override def compute(p: Partition, context: TaskContext): Iterator[(K, V)] = {
    val partition = p.asInstanceOf[CoGroupPartition]
    val serializer = SparkEnv.get.serializerManager.get(serializerClass)
    val map = new JHashMap[K, ArrayBuffer[V]]
    def getSeq(k: K): ArrayBuffer[V] = {
      val seq = map.get(k)
      if (seq != null) {
        seq
      } else {
        val seq = new ArrayBuffer[V]()
        map.put(k, seq)
        seq
      }
    }
    def integrate(dep: CoGroupSplitDep, op: ((K, V)) => Unit) = dep match {
      case NarrowCoGroupSplitDep(rdd, _, itsSplit) => {
        for (t <- rdd.iterator(itsSplit, context))
          op(t.asInstanceOf[(K, V)])
      }
      case ShuffleCoGroupSplitDep(shuffleId) => {
        val iter = SparkEnv.get.shuffleFetcher.fetch(shuffleId, partition.index,
          context.taskMetrics, serializer)
        for (t <- iter)
          op(t.asInstanceOf[(K, V)])
      }
    }
    // the first dep is rdd1; add all values to the map
    integrate(partition.deps(0), t => getSeq(t._1) += t._2)
    // the second dep is rdd2; remove all of its keys
    integrate(partition.deps(1), t => map.remove(t._1))
    map.iterator.map { t =>  t._2.iterator.map { (t._1, _) } }.flatten
  }

  override def clearDependencies() {
    super.clearDependencies()
    rdd1 = null
    rdd2 = null
  }

}


text:
module Edmunds

  module Media
    def send_request(path, options={})
      api_call 'media', path, options
    end
  end

  class Api
    def photos
      self.extend Edmunds::Media::Photos
    end
  end

end


text:
var assert = require('assert');
var common = require('../common.js');
var Readable = require('_stream_readable');

var len = 0;
var chunks = new Array(10);
for (var i = 1; i <= 10; i++) {
  chunks[i-1] = new Buffer(i);
  len += i;
}

var test = new Readable();
var n = 0;
test._read = function(size) {
  var chunk = chunks[n++];
  setTimeout(function() {
    test.push(chunk);
  });
};

test.on('end', thrower);
function thrower() {
  throw new Error('this should not happen!');
}

var bytesread = 0;
test.on('readable', function() {
  var b = len - bytesread - 1;
  var res = test.read(b);
  if (res) {
    bytesread += res.length;
    console.error('br=%d len=%d', bytesread, len);
    setTimeout(next);
  }
  test.read(0);
});
test.read(0);

function next() {
  // now let's make 'end' happen
  test.removeListener('end', thrower);

  var endEmitted = false;
  process.on('exit', function() {
    assert(endEmitted, 'end should be emitted by now');
  });
  test.on('end', function() {
    endEmitted = true;
  });

  // one to get the last byte
  var r = test.read();
  assert(r);
  assert.equal(r.length, 1);
  r = test.read();
  assert.equal(r, null);
}


text:
require 'spec_helper'

describe "Scopes pages: " do

  subject { page }

### SCOPE1 to test that Scope Page has header and title only when signed-in
  describe "when not signed_in " do

    describe "page" do
      before { visit scopes_path }

      it {should have_content('sign in')}
    end
  end

  describe "when signed_in" do
      before { visit signin_path }
      let(:user) { FactoryGirl.create(:user) }
      before do
        fill_in "Login",    with: user.login
        fill_in "Password", with: user.password
        click_button "Sign in"
      end

    describe "Page" do
      before { visit scopess_path }

      it { should have_selector('h1', text: 'Scopes') }
      it { should have_title('Managing scopess') }
      it { should have_content('New Scope') }
    end
  end

end


text:
#ifndef WEBRTC_MODULES_AUDIO_CODING_NETEQ_DECISION_LOGIC_H_
#define WEBRTC_MODULES_AUDIO_CODING_NETEQ_DECISION_LOGIC_H_

#include "webrtc/base/constructormagic.h"
#include "webrtc/modules/audio_coding/neteq/defines.h"
#include "webrtc/modules/audio_coding/neteq/interface/neteq.h"
#include "webrtc/typedefs.h"

namespace webrtc {

// Forward declarations.
class BufferLevelFilter;
class DecoderDatabase;
class DelayManager;
class Expand;
class PacketBuffer;
class SyncBuffer;
struct RTPHeader;

// This is the base class for the decision tree implementations. Derived classes
// must implement the method GetDecisionSpecialized().
class DecisionLogic {
 public:
  // Static factory function which creates different types of objects depending
  // on the |playout_mode|.
  static DecisionLogic* Create(int fs_hz,
                               size_t output_size_samples,
                               NetEqPlayoutMode playout_mode,
                               DecoderDatabase* decoder_database,
                               const PacketBuffer& packet_buffer,
                               DelayManager* delay_manager,
                               BufferLevelFilter* buffer_level_filter);

  // Constructor.
  DecisionLogic(int fs_hz,
                size_t output_size_samples,
                NetEqPlayoutMode playout_mode,
                DecoderDatabase* decoder_database,
                const PacketBuffer& packet_buffer,
                DelayManager* delay_manager,
                BufferLevelFilter* buffer_level_filter);

  // Destructor.
  virtual ~DecisionLogic() {}

  // Resets object to a clean state.
  void Reset();

  // Resets parts of the state. Typically done when switching codecs.
  void SoftReset();

  // Sets the sample rate and the output block size.
  void SetSampleRate(int fs_hz, size_t output_size_samples);

  // Returns the operation that should be done next. |sync_buffer| and |expand|
  // are provided for reference. |decoder_frame_length| is the number of samples
  // obtained from the last decoded frame. If there is a packet available, the
  // packet header should be supplied in |packet_header|; otherwise it should
  // be NULL. The mode resulting form the last call to NetEqImpl::GetAudio is
  // supplied in |prev_mode|. If there is a DTMF event to play, |play_dtmf|
  // should be set to true. The output variable |reset_decoder| will be set to
  // true if a reset is required; otherwise it is left unchanged (i.e., it can
  // remain true if it was true before the call).
  // This method end with calling GetDecisionSpecialized to get the actual
  // return value.
  Operations GetDecision(const SyncBuffer& sync_buffer,
                         const Expand& expand,
                         size_t decoder_frame_length,
                         const RTPHeader* packet_header,
                         Modes prev_mode,
                         bool play_dtmf,
                         bool* reset_decoder);

  // These methods test the |cng_state_| for different conditions.
  bool CngRfc3389On() const { return cng_state_ == kCngRfc3389On; }
  bool CngOff() const { return cng_state_ == kCngOff; }

  // Resets the |cng_state_| to kCngOff.
  void SetCngOff() { cng_state_ = kCngOff; }

  // Reports back to DecisionLogic whether the decision to do expand remains or
  // not. Note that this is necessary, since an expand decision can be changed
  // to kNormal in NetEqImpl::GetDecision if there is still enough data in the
  // sync buffer.
  virtual void ExpandDecision(Operations operation);

  // Adds |value| to |sample_memory_|.
  void AddSampleMemory(int32_t value) {
    sample_memory_ += value;
  }

  // Accessors and mutators.
  void set_sample_memory(int32_t value) { sample_memory_ = value; }
  size_t generated_noise_samples() const { return generated_noise_samples_; }
  void set_generated_noise_samples(size_t value) {
    generated_noise_samples_ = value;
  }
  size_t packet_length_samples() const { return packet_length_samples_; }
  void set_packet_length_samples(size_t value) {
    packet_length_samples_ = value;
  }
  void set_prev_time_scale(bool value) { prev_time_scale_ = value; }
  NetEqPlayoutMode playout_mode() const { return playout_mode_; }

 protected:
  // The value 6 sets maximum time-stretch rate to about 100 ms/s.
  static const int kMinTimescaleInterval = 6;

  enum CngState {
    kCngOff,
    kCngRfc3389On,
    kCngInternalOn
  };

  // Returns the operation that should be done next. |sync_buffer| and |expand|
  // are provided for reference. |decoder_frame_length| is the number of samples
  // obtained from the last decoded frame. If there is a packet available, the
  // packet header should be supplied in |packet_header|; otherwise it should
  // be NULL. The mode resulting form the last call to NetEqImpl::GetAudio is
  // supplied in |prev_mode|. If there is a DTMF event to play, |play_dtmf|
  // should be set to true. The output variable |reset_decoder| will be set to
  // true if a reset is required; otherwise it is left unchanged (i.e., it can
  // remain true if it was true before the call).
  // Should be implemented by derived classes.
  virtual Operations GetDecisionSpecialized(const SyncBuffer& sync_buffer,
                                            const Expand& expand,
                                            size_t decoder_frame_length,
                                            const RTPHeader* packet_header,
                                            Modes prev_mode,
                                            bool play_dtmf,
                                            bool* reset_decoder) = 0;

  // Updates the |buffer_level_filter_| with the current buffer level
  // |buffer_size_packets|.
  void FilterBufferLevel(size_t buffer_size_packets, Modes prev_mode);

  DecoderDatabase* decoder_database_;
  const PacketBuffer& packet_buffer_;
  DelayManager* delay_manager_;
  BufferLevelFilter* buffer_level_filter_;
  int fs_mult_;
  size_t output_size_samples_;
  CngState cng_state_;  // Remember if comfort noise is interrupted by other
                        // event (e.g., DTMF).
  size_t generated_noise_samples_;
  size_t packet_length_samples_;
  int sample_memory_;
  bool prev_time_scale_;
  int timescale_hold_off_;
  int num_consecutive_expands_;
  const NetEqPlayoutMode playout_mode_;

 private:
  RTC_DISALLOW_COPY_AND_ASSIGN(DecisionLogic);
};

}  // namespace webrtc
#endif  // WEBRTC_MODULES_AUDIO_CODING_NETEQ_DECISION_LOGIC_H_


text:
FROM ubuntu:16.04
COPY openebs-provisioner /
CMD ["/openebs-provisioner"]


text:
package org.infinispan.protostream.descriptors;

import java.util.Map;

import org.infinispan.protostream.AnnotationParserException;

/**
 * Base class for all descriptors. Provides common methods for naming, accessing the attached documentation and
 * annotations.
 *
 * @author anistor@redhat.com
 * @since 2.0
 */
public interface AnnotatedDescriptor {

   /**
    * Return the name of the descriptor.
    *
    * @return the name of the descriptor (never {@code null})
    */
   String getName();

   /**
    * Return the full name of the descriptor.
    *
    * @return the name of the descriptor (never {@code null})
    */
   String getFullName();

   /**
    * Return the containing files's descriptor
    *
    * @return the containing files's descriptor (never {@code null})
    */
   FileDescriptor getFileDescriptor();

   /**
    * Return the documentation text associated with this descriptor.
    *
    * @return the documentation text or {@code null} if not present
    */
   String getDocumentation();

   /**
    * Get the documentation annotations in the form of a map of abstract syntax trees of {@link AnnotationElement} nodes.
    * Only the configured annotations are returned. The unconfigured ones are discarded immediately after parsing.
    * <p>
    * The parsing of annotations is performed lazily on first invocation.
    *
    * @return the map of annotations
    * @throws AnnotationParserException if parsing of annotations fails
    */
   Map<String, AnnotationElement.Annotation> getAnnotations() throws AnnotationParserException;

   /**
    * Get the 'processed' annotation object created by the registered {@link org.infinispan.protostream.AnnotationMetadataCreator}
    * or {@code null} if the annotation is missing or no {@link org.infinispan.protostream.AnnotationMetadataCreator}
    * was registered.
    *
    * @param annotationName the name of the annotation
    * @param <T>            the expected type of the object created by the {@link org.infinispan.protostream.AnnotationMetadataCreator}
    * @return the 'processed' annotation object or {@code null} if not found
    * @throws AnnotationParserException if parsing of annotations fails
    */
   <T> T getProcessedAnnotation(String annotationName) throws AnnotationParserException;
}


text:
package in.brewcode.test.persistence;

import in.brewcode.api.config.PersistenceConfig;
import in.brewcode.api.persistence.dao.IAdminAuthorDao;
import in.brewcode.api.persistence.dao.IArticleDao;
import in.brewcode.api.persistence.entity.Article;
import in.brewcode.api.persistence.entity.Author;
import in.brewcode.api.persistence.entity.Content;

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

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.log4j.Logger;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { PersistenceConfig.class })
public class ArticleDaoTest {
	private final Logger log = Logger.getLogger(ArticleDaoTest.class);
	@Autowired
	private IArticleDao articleDao;
	@Autowired
	private IAdminAuthorDao adminAuthorDao;

	@Autowired
	private Environment env;
	/**
	 * Test includes creating Content, Author, Article. And Deleting Article(and
	 * Cascaded Contents)
	 */
	@Test
	@Transactional
	public void createArticlewithNoErrors() {
		final Article article = new Article();
		final Author author = new Author();
		author.setAuthorUserName(RandomStringUtils.randomAlphabetic(10));

		log.debug("before saving author");
		adminAuthorDao.save(author);
		article.setArticeName(RandomStringUtils.randomAlphabetic(10));
		article.setArticleAuthor(author);
		final Content content = new Content();
		content.setContentBody("hey a ");
		content.setArticle(article);
		List<Content> articleContents = new ArrayList<Content>();
		articleContents.add(content);
		article.setArticleContents(articleContents);
		log.debug("before saving article");
		articleDao.save(article);

		List<Article> topfive = articleDao.getTopFiveArticles();

		Assert.notNull(topfive);

	}

}


text:
sf::Vector2f VPath::getBezierPoint(float t)
{
	tmp.resize(points.size());
	std::copy(points.begin(), points.end(), tmp.begin());

	unsigned int maxi = points.size() - 1;
	for (unsigned int i = 0; i < maxi; i++)
	{
		unsigned int maxj = maxi - i;
		for (unsigned int j = 0; j < maxj; j++)
			tmp[j] += t * (tmp[j + 1] - tmp[j]);
	}

	return tmp[0];
}

void VPath::SetPath(const std::vector<sf::Vector2f>& p)
{
	points.resize(p.size());
	std::copy(p.begin(), p.end(), points.begin());
	dirty = true;
}

void VPath::AddPoint(sf::Vector2f point)
{
	t *= 1.0f / points.size();
	points.push_back(point);
	dirty = true;
}

void VPath::RemovePoint(unsigned int index)
{
	if (index >= points.size())
		return;

	points.erase(points.begin() + index);
	dirty = true;
}

void VPath::ClearPath()
{
	points.clear();
	points.shrink_to_fit();
	tmp.clear();
	tmp.shrink_to_fit();
}

int VPath::GetNumPoints()
{
	return points.size();
}

void VPath::SetPathType(VPathType pathType)
{
	this->pathType = pathType;
	dirty = true;
}

VPath::VPathType VPath::GetPathType()
{
	return (VPath::VPathType)pathType;
}

void VPath::SetSpeed(float speed)
{
	this->speed = speed;
}

float VPath::GetSpeed()
{
	return speed;
}

void VPath::SetUpdateAngle(bool active)
{
	angle = active;
}

void VPath::SetInterpolationType(VInterpolate::VInterpolateType type)
{
	interpolationType = type;
}

VInterpolate::VInterpolateType VPath::GetInterpolationType()
{
	return interpolationType;
}

bool VPath::IsActive()
{
	return active;
}

void VPath::StartFollowing(VObject* object, std::function<void()> onComplete)
{
	if (active || points.size() == 0)
		return;

	this->object = object;
	this->onComplete = onComplete;

	t = 0.0f;

	active = true;
	lastPos = points[0];
}

void VPath::StopFollowing()
{
	active = false;
	object = NULL;
}

#include "VInterpolate.h"
sf::Vector2f VPath::GetPoint(float t)
{
	t = std::min(t, 1.0f);

	switch (pathType)
	{
		case VPath::LINE:
		{
			unsigned int size = points.size() - 1;
			float frac = 1.0f / size;
			unsigned int part = static_cast<int>(t / frac);

			if (part >= size)
				return points.back();

			float partT = t - (part * frac);
			return VInterpolate::Vector2f(points[part], points[part + 1], partT, frac);
		}
		case VPath::CURVE:
		{
			return getBezierPoint(t);
		}
		default:
		{
			return getBezierPoint(0);
		}
	}
}

void VPath::SetPoint(unsigned int index, sf::Vector2f point)
{
	if (index < points.size())
		points[index] = point;
}

void VPath::Update(float dt)
{
	if (!active)
		return;

	t += dt * speed;

	if (t > 1.0f)
	{
		if (object)
			object->SetPositionAtCentre(points[points.size() - 1]);

		StopFollowing();
		t = 1.0f;

		if (onComplete)
			onComplete();

		return;
	}

	sf::Vector2f p1 = GetPoint(VInterpolate::Float(0.0f, 1.0f, t, 1.0f, interpolationType));

	if (object)
	{
		object->SetPositionAtCentre(p1);
		if (angle)
		{
			sf::Vector2f diff = p1 - lastPos;
			object->Angle = atan2f(diff.y, diff.x) * (180 / VFRAME_PI);
		}
	}

	lastPos = p1;
}

void VPath::Draw(sf::RenderTarget& RenderTarget)
{
	if (GetNumPoints() < 2)
		return;

	if (dirty)
	{
		int points = 5 * GetNumPoints();
		float thickness = 5.0f / 2.0f;
		float dt = 0.0f;
		float step = 1.0f / points;

		vertexArray.setPrimitiveType(sf::TrianglesStrip);
		vertexArray.clear();
		while (dt < 1.0f)
		{
			sf::Vector2f p1 = GetPoint(dt);
			sf::Vector2f p2 = GetPoint(dt + step);

			sf::Vector2f diff = p2 - p1;
			diff /= sqrtf((diff.x * diff.x) + (diff.y * diff.y));
			sf::Vector2f norm(-diff.y, diff.x);

			vertexArray.append(sf::Vertex(p1 + (norm * thickness), sf::Color::White));
			vertexArray.append(sf::Vertex(p1 + (norm * -thickness), sf::Color::White));

			dt += step;
		}

		sf::Vector2f p1 = GetPoint(dt - step);
		sf::Vector2f p2 = GetPoint(dt);

		sf::Vector2f diff = p2 - p1;
		diff /= sqrtf((diff.x * diff.x) + (diff.y * diff.y));
		sf::Vector2f norm(-diff.y, diff.x);

		vertexArray.append(sf::Vertex(p2 + (norm * thickness), sf::Color::White));
		vertexArray.append(sf::Vertex(p2 + (norm * -thickness), sf::Color::White));
	}

	RenderTarget.draw(vertexArray);
}


text:
var expect = require('chai').expect;
var fs = require('fs.extra');
var path = require('path');
var async = require('async');
var util = require('util');
var stream = require('stream');
var fsCtrlModule = require(process.cwd() + '/build/server/fsService.js');
var log = require(process.cwd() + '/build/server/logging.js').getLogger('fsServiceTest.js');

var testDataPath = path.join(process.cwd(), 'testData');

describe('FsService', function() {
	beforeEach(function(done) {
		fs.mkdir(testDataPath, function(err) {
			if (err) {
				if (err.code !== 'EEXIST') {
					throw err;
				}
			}
			done();
		});
	});

	afterEach(function(done) {
		fs.rmrf(testDataPath, function(err) {
			done();
		});
	});

	var fsCtrl = new fsCtrlModule.FsCtrl({rootPath: testDataPath});

	it('should be instantiated correctly by require()', function(done) {
		expect(fsCtrlModule).to.include.key('FsCtrl');

		done();
	});

	it('should identify safe/unsafe paths', function(done) {
		var fsCtrl = new fsCtrlModule.FsCtrl({rootPath: testDataPath});
		expect(fsCtrl.isPathSafe(path.join(testDataPath, '../data/'))).to.be.false();
		expect(fsCtrl.isPathSafe(path.join(testDataPath, '/data/'))).to.be.true();
		done();
	});

	it('should calculate intended fs path from url', function(done) {
		var fsCtrl = new fsCtrlModule.FsCtrl({
			rootPath: testDataPath,
			filePathRegexp: /^\/fs\/\w+\//i
		});

		expect(fsCtrl.calculateFsPath('/dir/file.jpg')).to.be.equal(path.join(testDataPath, '/dir/file.jpg'));

		done();
	});

	it('should list directory', function(done) {
		fs.mkdirSync(path.join(testDataPath, 'lsDir'));
		fs.writeFileSync(path.join(testDataPath, 'lsDir/f1'), "xxxx");
		fs.writeFileSync(path.join(testDataPath, 'lsDir/f2'), "yyy");
		fs.mkdirSync(path.join(testDataPath, 'lsDir/subdir'));

		var fsCtrl = new fsCtrlModule.FsCtrl({rootPath: testDataPath});

		var reqMock =  '/lsDir';
		var resMock = {
			statusCode: null,
			data: null,
			send: function(data) {
				// this.statusCode = code;
				this.data = data;
			}
		};

		fsCtrl.ls(reqMock, resMock,  function(err) {
			expect(err).to.not.exist();
			expect(resMock.data.length).to.be.equal(3);

			done();
		});
	});

	it('should list directory and filter reults', function(done) {
		fs.mkdirSync(path.join(testDataPath, 'lsDir'));
		fs.writeFileSync(path.join(testDataPath, 'lsDir/f1'), "xxxx");
		fs.writeFileSync(path.join(testDataPath, 'lsDir/f3.1'), "xxxx.2");
		fs.writeFileSync(path.join(testDataPath, 'lsDir/f2'), "yyy");
		fs.mkdirSync(path.join(testDataPath, 'lsDir/subdir'));

		var filterMeth= function(item){
			if (! /.*\.[0-9]+/.test(item.name)) {
				return true;

			}
			return false;
		};

		var fsCtrl = new fsCtrlModule.FsCtrl({rootPath: testDataPath, fileFilter:filterMeth});

		var reqMock = '/lsDir';
		var resMock = {
			statusCode: null,
			data: null,
			send: function( data) {
				// this.statusCode = code;
				this.data = data;
			}
		};

		var filter= function( item){
			var regexp = /.*\.[0-9]+/;
			if (!regexp.test(item.name)) {
				return true;
			}
			return false;
		};

		fsCtrl.ls(reqMock, resMock,  function(err) {
			expect(err).to.not.exist();
			expect(resMock.data.length).to.be.equal(3);
			done();
		});
	});

	it('should remove files and directories', function(done) {
		fs.mkdirSync(path.join(testDataPath, 'lsDir'));
		fs.writeFileSync(path.join(testDataPath, 'lsDir/f1'), "xxxx");
		fs.writeFileSync(path.join(testDataPath, 'lsDir/f2'), "yyy");
		fs.mkdirSync(path.join(testDataPath, 'lsDir/subdir'));
		fs.mkdirSync(path.join(testDataPath, 'lsDir/subdir2'));
		fs.writeFileSync(path.join(testDataPath, 'lsDir/subdir2/f3'), "yyy");

		var fsCtrl = new fsCtrlModule.FsCtrl({rootPath: testDataPath});

		var reqMock = function(_path) {
			this.path = _path;
		};

		var resMock = function() {
			this.statusCode = null;
			this.data = null;
			this.send = function(code, data) {
				this.statusCode = code;
				this.data = data;
			};
		};

		async.parallel([
			function(callback) {
				var req = '/lsDir/f1';
				var res = new resMock();

				fsCtrl.rm(req, res, function(err) {
					expect(err).to.not.exist();

					fs.exists(path.join(testDataPath, 'lsDir/f1'), function(exists) {
						expect(exists).to.be.false();
						callback();
					});
				});
			},
			function(callback) {
				var req = '/lsDir/subdir';
				var res = new resMock();

				fsCtrl.rm(req, res, function(err) {
					expect(err).to.not.exist();

					fs.exists(path.join(testDataPath, 'lsDir/subdir'), function(exists) {
						expect(exists).to.be.false();
						callback();
					});
				});
			},
			function(callback) {
				var req = '/lsDir/subdir2';
				var res = new resMock();

				fsCtrl.rm(req, res, function(err) {
					expect(err).to.exist();
					expect(err.statusCode||500).to.be.equal(500);
					callback();
				});
			},
			function(callback) {
				var req = '/lsDir/nonexisting';
				var res = new resMock();

				fsCtrl.rm(req, res, function(err) {
					expect(err).to.exist();
					expect(err.code).to.be.equal(404);
					callback();
				});
			}
		],
		function(err) {
			done();
		});
	});

	it('should increment index if existing dstfile', function(done) {

		fs.mkdirSync(path.join(testDataPath, 'replaceDir'));

		fs.writeFileSync(path.join(testDataPath, 'replaceDir/f1'), "xxxx");

		var fsCtrl = new fsCtrlModule.FsCtrl({rootPath: testDataPath});

		var reqMock = function(_path, _data) {
			stream.Readable.call(this);
			this.path = _path;
			this.data = _data;
		};
		util.inherits(reqMock, stream.Readable);

		reqMock.prototype._read = function(size) {
			this.push(this.data);
			this.push(null);
		};

		var resMock = function() {
			require('stream').Writable.call(this);
			this.statusCode = null;
			this.data = '';
			this.send = function(code, data) {
				this.statusCode = code;
				if (data) {
					this.data += data;
				}
			};
		};
		util.inherits(resMock, require('stream').Writable);

		resMock.prototype._write = function(chunk, encoding, callback) {
			if (chunk) {
				this.data += chunk.toString(encoding);
			}

			callback();
		};
		async.parallel([
			function(callback) {
				var req = new reqMock('replaceDir/f1','yyyy');
				var res = new resMock();

				fsCtrl.replace('/replaceDir/f1',req, res, function(err) {

					expect(err).to.not.exist();
					expect(fs.existsSync(path.join(testDataPath, "replaceDir/f1.1"))).to.be.true();
					expect(fs.existsSync(path.join(testDataPath, "replaceDir/f1"))).to.be.true();
					callback();
				});
			}
		],
		function(err) {
			done();
		});
	});

	it('should create new file index if dst does not exist no index files', function(done) {

		fs.mkdirSync(path.join(testDataPath, 'replaceDir'));

		var fsCtrl = new fsCtrlModule.FsCtrl({rootPath: testDataPath});

		var reqMock = function(_path, _data) {
			stream.Readable.call(this);
			this.path = _path;
			this.data = _data;
		};
		util.inherits(reqMock, stream.Readable);

		reqMock.prototype._read = function(size) {
			this.push(this.data);
			this.push(null);
		};

		var resMock = function() {
			require('stream').Writable.call(this);
			this.statusCode = null;
			this.data = '';
			this.send = function(code, data) {
				this.statusCode = code;
				if (data) {
					this.data += data;
				}
			};
		};
		util.inherits(resMock, require('stream').Writable);

		resMock.prototype._write = function(chunk, encoding, callback) {
			if (chunk) {
				this.data += chunk.toString(encoding);
			}

			callback();
		};
		async.parallel([
			function(callback) {
				var req = new reqMock('/replaceDir/f2','yyyy');
				var res = new resMock();

				fsCtrl.replace('/replaceDir/f2',req, res, function(err) {

					expect(err).to.not.exist();
					expect(fs.existsSync(path.join(testDataPath, "replaceDir/f2.1"))).to.be.false();
					expect(fs.existsSync(path.join(testDataPath, "replaceDir/f2"))).to.be.true();
					callback();
				});
			}
		],
		function(err) {
			done();
		});
	});

	it('should get file', function(done) {
		fs.writeFileSync(path.join(testDataPath, 'f1'), "xxxx");

		var fsCtrl = new fsCtrlModule.FsCtrl({rootPath: testDataPath});

		var reqMock = function(_path) {
			this.path = _path;
		};

		var resMock = function() {
			require('stream').Writable.call(this);
			this.statusCode = null;
			this.data = '';
			this.send = function(code, data) {
				this.statusCode = code;
				if (data) {
					this.data += data;
				}
			};
		};
		util.inherits(resMock, require('stream').Writable);

		resMock.prototype._write = function(chunk, encoding, callback) {
			if (chunk) {
				this.data += chunk.toString('utf8');
			}

			callback();
		};

		fsCtrl.get('f1', res = new resMock(), function(err) {
			expect(err).to.not.exist();
			expect(res.data).to.be.equal('xxxx');
			done();
		});
	});

	it('should create directory', function(done) {
		var fsCtrl = new fsCtrlModule.FsCtrl({rootPath: testDataPath});

		var reqMock = function(_path) {
			this.path = _path;
		};

		var resMock = function() {
			this.statusCode = null;
			this.data = null;
			this.send = function(data) {
				this.data = data;
			};
		};

		fsCtrl.mkdir('/xxx', res = new resMock(), function(err) {
			expect(err).to.not.exist();
			fs.exists(path.join(testDataPath, '/xxx'), function(exists) {
				expect(exists).to.be.true();
				done();
			});
		});
	});

	it('should put file into dir and return path', function(done) {
		fs.writeFileSync(path.join(testDataPath, 'fX3'), "xxxxiYYYY");

		var fsCtrl = new fsCtrlModule.FsCtrl({rootPath: testDataPath});

		var reqMock = function(_path, _data) {
			stream.Readable.call(this);
			this.path = _path;
			this.data = _data;
		};
		util.inherits(reqMock, stream.Readable);

		reqMock.prototype._read = function(size) {
			this.push(this.data);
			this.push(null);
		};

		var resMock = function() {
			require('stream').Writable.call(this);
			this.statusCode = null;
			this.data = '';
			this.send = function(code, data) {
				this.statusCode = code;
				if (data) {
					this.data += data;
				}
			};
		};
		util.inherits(resMock, require('stream').Writable);

		resMock.prototype._write = function(chunk, encoding, callback) {
			if (chunk) {
				this.data += chunk.toString(encoding);
			}

			callback();
		};

		async.parallel([function(callback) {
			// no content type
			var req = new reqMock('.', 'abcd');
			var res = new resMock();
			fsCtrl.putGetPath('.', req, null, function(err, path) {
				expect(err).to.not.exist();
				expect(path).to.exist();
				callback();
			});
		},
		function(callback) {
			var req = new reqMock('.', 'abcd');
			var res = new resMock();
			fsCtrl.putGetPath('.', req, 'image/jpeg', function(err, path) {
				expect(err).to.not.exist();
				expect(path).to.exist();
				callback();
			});

		}],
		function(err) {
			done();
		});
	});

	it('should put file', function(done) {
		fs.writeFileSync(path.join(testDataPath, 'f1'), "xxxx");

		var fsCtrl = new fsCtrlModule.FsCtrl({rootPath: testDataPath});

		var reqMock = function(_path, _data) {
			stream.Readable.call(this);
			this.path = _path;
			this.data = _data;
		};
		util.inherits(reqMock, stream.Readable);

		reqMock.prototype._read = function(size) {
			this.push(this.data);
			this.push(null);
		};

		var resMock = function() {
			require('stream').Writable.call(this);
			this.statusCode = null;
			this.data = '';
			this.send = function(code, data) {
				this.statusCode = code;
				if (data) {
					this.data += data;
				}
			};
		};
		util.inherits(resMock, require('stream').Writable);

		resMock.prototype._write = function(chunk, encoding, callback) {
			if (chunk) {
				this.data += chunk.toString(encoding);
			}

			callback();
		};

		async.parallel([function(callback) {
			// saving to existing file
			var req = new reqMock('f1', 'abcd');
			var res = new resMock();
			fsCtrl.put('f1',req, res, function(err) {
				expect(err).to.exist();
				callback();
			});
		}, function(callback) {
			// correct save
			var req = new reqMock('f2', 'abcd');
			var res = new resMock();
			fsCtrl.put('f2',req, res, function(err) {
				expect(err).to.not.exist();
				expect(fs.readFileSync(path.join(testDataPath, 'f2'), {encoding:'utf8'})).to.be.eql('abcd');
				callback();
			});
		}, function(callback) {
			// wrong path
			var req = new reqMock('../../../f2', 'abcd');
			var res = new resMock();
			fsCtrl.put('../../../f2',req, res, function(err) {
				expect(err).to.exist();
				callback();
			});
		}],
		function(err) {
			done();
		});
	});
});


text:
<?php
/**
 * @created 27.11.13 - 14:38
 * @author stefanriedel
 */

namespace Srit83\Extsentry\Facades;
use Illuminate\Support\Facades\Facade;

class Extsentry extends Facade {
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'extsentry';
    }
}


text:
"""Handler to make calls against the AdWords API."""

import time

from demo import VERSION
from googleads.adwords import AdWordsClient
from googleads.common import ZeepServiceProxy
from googleads.errors import GoogleAdsError
from googleads.oauth2 import GoogleRefreshTokenClient

class APIHandler(object):
  """Handler for the AdWords API using the Ads Python Client Libraries."""

  # The user-agent sent in requests from this demo.
  _USER_AGENT = 'AppEngine Googleads Demo v%s' % VERSION

  def __init__(self, client_id, client_secret, refresh_token,
               manager_account_id, dev_token):
    """Initializes an APIHandler.

    Args:
      client_id: The client customer id retrieved from the Developers Console.
      client_secret: The client secret retrieved from the Developers Console.
      refresh_token: The refresh token retrieved with generate_refresh_token.py.
      manager_account_id: The AdWords manager account Id.
      dev_token: The AdWords Developer Token.
    """
    credentials = GoogleRefreshTokenClient(client_id, client_secret,
                                           refresh_token)
    self.client = AdWordsClient(dev_token, credentials, self._USER_AGENT,
                                client_customer_id=manager_account_id,
                                cache=ZeepServiceProxy.NO_CACHE)

  def AddAdGroup(self, client_customer_id, campaign_id, name, status):
    """Create a new ad group.

    Args:
      client_customer_id: str Client Customer Id used to create the AdGroup.
      campaign_id: str Id of the campaign to use.
      name: str Name to assign to the AdGroup.
      status: str Status to assign to the AdGroup when it is created.
    """
    self.client.SetClientCustomerId(client_customer_id)

    ad_group_service = self.client.GetService('AdGroupService')
    operations = [{
        'operator': 'ADD',
        'operand': {
            'campaignId': campaign_id,
            'name': name,
            'status': status
        }
    }]
    ad_group_service.mutate(operations)

  def AddBudget(self, client_customer_id, micro_amount):
    """Create a new Budget with the given microAmount.

    Args:
      client_customer_id: str Client Customer Id used to create Budget.
      micro_amount: str The budget represented in micros.

    Returns:
      str BudgetId of the newly created Budget.
    """
    self.client.SetClientCustomerId(client_customer_id)

    budget_service = self.client.GetService('BudgetService')

    operations = [{
        'operator': 'ADD',
        'operand': {
            'name': 'Budget #%s' % time.time(),
            'amount': {
                'microAmount': micro_amount
            },
            'deliveryMethod': 'STANDARD'
        }
    }]

    return budget_service.mutate(operations)['value'][0]['budgetId']

  def AddCampaign(self, client_customer_id, campaign_name, ad_channel_type,
                  budget):
    """Add a Campaign to the client account.

    Args:
      client_customer_id: str Client Customer Id to use when creating Campaign.
      campaign_name: str Name of the campaign to be added.
      ad_channel_type: str Primary serving target the campaign's ads.
      budget: str a budget amount (in micros) to use.
    """
    self.client.SetClientCustomerId(client_customer_id)
    campaign_service = self.client.GetService('CampaignService')
    budget_id = self.AddBudget(client_customer_id, budget)

    operations = [{
        'operator': 'ADD',
        'operand': {
            'name': campaign_name,
            'status': 'PAUSED',
            'biddingStrategyConfiguration': {
                'biddingStrategyType': 'MANUAL_CPC',
                'biddingScheme': {
                    'xsi_type': 'ManualCpcBiddingScheme',
                    'enhancedCpcEnabled': 'false'
                }
            },
            'budget': {
                'budgetId': budget_id
            },
            'advertisingChannelType': ad_channel_type
        }
    }]

    campaign_service.mutate(operations)

  def GetAccounts(self):
    """Return the client accounts associated with the user's manager account.

    Returns:
      list List of ManagedCustomer data objects.
    """
    selector = {
        'fields': ['CustomerId', 'CanManageClients']
    }

    accounts = self.client.GetService('ManagedCustomerService').get(selector)

    return accounts['entries']

  def GetAdGroups(self, client_customer_id, campaign_id):
    """Retrieves all AdGroups for the given campaign that haven't been removed.

    Args:
      client_customer_id: str Client Customer Id being used in API request.
      campaign_id: str id of the campaign for which to fetch ad groups.

    Returns:
      list List of AdGroup data objects.
    """
    self.client.SetClientCustomerId(client_customer_id)
    selector = {
        'fields': ['Id', 'Name', 'Status'],
        'predicates': [
            {
                'field': 'CampaignId',
                'operator': 'EQUALS',
                'values': [campaign_id]
            },
            {
                'field': 'Status',
                'operator': 'NOT_EQUALS',
                'values': ['REMOVED']
            }
        ]
    }
    adgroups = self.client.GetService('AdGroupService').get(selector)

    if int(adgroups['totalNumEntries']) > 0:
      return adgroups['entries']
    else:
      return None

  def GetBudget(self, client_customer_id, budget_id):
    """Return a Budget with the associated budgetId.

    Args:
      client_customer_id: str Client Customer Id to which the budget belongs.
      budget_id: str id of the budget we want to examine.

    Returns:
      Budget A Budget data object.
    """
    self.client.SetClientCustomerId(client_customer_id)
    selector = {
        'fields': ['BudgetId', 'BudgetName', 'BudgetStatus', 'Amount',
                   'DeliveryMethod', 'BudgetReferenceCount',
                   'IsBudgetExplicitlyShared'],
        'predicates': [
            {
                'field': 'BudgetId',
                'operator': 'EQUALS',
                'values': [budget_id]
            }
        ]
    }
    budgets = self.client.GetService('BudgetService').get(selector)

    if int(budgets['totalNumEntries']) > 0:
      return budgets['entries'][0]
    else:
      return None

  def GetCampaigns(self, client_customer_id):
    """Returns a client account's Campaigns that haven't been removed.

    Args:
      client_customer_id: str Client Customer Id used to retrieve Campaigns.

    Returns:
      list List of Campaign data objects.
    """
    self.client.SetClientCustomerId(client_customer_id)
    # A somewhat hackish workaround for "The read operation timed out" error,
    # which could be triggered on AppEngine's end if the request is too large
    # and is taking too long.
    max_tries = 3
    today = time.strftime('%Y%m%d', time.localtime())
    for i in range(1, max_tries + 1):
      try:
        selector = {
            'fields': ['Id', 'Name', 'Status', 'BudgetId', 'Amount'],
            'predicates': [
                {
                    'field': 'Status',
                    'operator': 'NOT_EQUALS',
                    'values': ['REMOVED']
                }
            ],
            'dateRange': {
                'min': today,
                'max': today
            }
        }
        campaigns = self.client.GetService('CampaignService').get(selector)
        if int(campaigns['totalNumEntries']) > 0:
          return campaigns['entries']
        else:
          return None
      except Exception as e:
        if i == max_tries:
          raise GoogleAdsError(e)
        continue

  def UpdateBudget(self, client_customer_id, budget_id, micro_amount,
                   delivery_method):
    """Update a Budget with the given budgetId.

    Args:
      client_customer_id: str Client Customer Id used to update Budget.
      budget_id: str Id of the budget to be updated.
      micro_amount: str New value for the microAmount field.
      delivery_method: str New value for the deliveryMethod field.
    """
    self.client.SetClientCustomerId(client_customer_id)
    operations = [{
        'operator': 'SET',
        'operand': {
            'budgetId': budget_id,
            'amount': {
                'microAmount': micro_amount
            },
            'deliveryMethod': delivery_method
        }
    }]
    self.client.GetService('BudgetService').mutate(operations)


text:
/* $Id: IRepositoryConnector.java 996524 2010-09-13 13:38:01Z kwright $ */

/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.crawler.interfaces;

import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.agents.interfaces.*;

import java.io.*;
import java.util.*;

/** This interface describes an instance of a connection between a repository and ManifoldCF's
* standard "pull" ingestion agent.
*
* Each instance of this interface is used in only one thread at a time.  Connection Pooling
* on these kinds of objects is performed by the factory which instantiates repository connectors
* from symbolic names and config parameters, and is pooled by these parameters.  That is, a pooled connector
* handle is used only if all the connection parameters for the handle match.
*
* Implementers of this interface should provide a default constructor which has this signature:
*
* xxx();
*
* Connectors are either configured or not.  If configured, they will persist in a pool, and be
* reused multiple times.  Certain methods of a connector may be called before the connector is
* configured.  This includes basically all methods that permit inspection of the connector's
* capabilities.  The complete list is:
*
*
* The purpose of the repository connector is to allow documents to be fetched from the repository.
*
* Each repository connector describes a set of documents that are known only to that connector.
* It therefore establishes a space of document identifiers.  Each connector will only ever be
* asked to deal with identifiers that have in some way originated from the connector.
*
* Documents are fetched by ManifoldCF in two stages.  First, the addSeedDocuments() method is called in the connector
* implementation.  This method is meant to add a set of document identifiers to the queue.  When ManifoldCF is ready
* to process a document, the document identifier is used to build a version string for the document and check whether
* the document needs to be indexed, and index it if needed (the second stage).  The second stage
* consists of the processDocuments() method.
*
* All of these methods interact with ManifoldCF by means of an "activity" interface.
*
* A note on connector models:
*
* These values describe what the connector returns for the addSeedDocuments() method.  The framework
* uses these to figure out how to most efficiently use the connector.  It is desirable to pick a model that
* is the most restrictive that is still accurate.  For example, if MODEL_ADD_CHANGE_DELETE applies, you would
* return that value rather than MODEL_ADD.
*
* For the CHAINED models, what the connector is describing are the documents that will be processed IF the seeded
* documents are followed to their leaves.  For instance, imagine a hierarchy where the root document is the only one ever
* seeded, but if that document is processed, and its discovered changed children are processed as well, then all documents
* that have been added, changed, or deleted will eventually be discovered.  In that case, model
* MODEL_CHAINED_ADD_CHANGE_DELETE would be appropriate.  But, if a changed node can only discover child
* additions and changes, then MODEL_CHAINED_ADD_CHANGE would be the right choice.
*
* A CHAINED model also requires cooperation on the part of the connector for processing.  Specifically,
* a document may be unchanged but its references are expected to still be extracted in order for a CHAINED
* model to do the right thing.  For non-CHAINED models, re-extraction of references if there are no reference changes
* for a document is NOT required.
*/
public interface IRepositoryConnector extends IConnector
{
  public static final String _rcsid = "@(#)$Id: IRepositoryConnector.java 996524 2010-09-13 13:38:01Z kwright $";

  /** This is the legacy ManifoldCF catch-all crawling model.  All existing documents will be rechecked when a crawl
  * is done, every time.  This model was typically used for models where seeds were essentially fixed and all
  * real documents were discovered during crawling. */
  public static final int MODEL_ALL = 0;
  /** This indicates that the seeds are never complete; the previous seeds are lost and cannot be retrieved. */
  public static final int MODEL_PARTIAL = 4;

  /** Supply at least the documents that have been added since the specified start time.  Connector is
  * aware of the start time and end time of the request, and supplies at least the documents that have been
  * added within the specified time range. */
  public static final int MODEL_ADD = 1;
  /** Supply at least the documents that have been added or changed within the specified time range. */
  public static final int MODEL_ADD_CHANGE = 2;
  /** Supply at least the documents that have been added, changed, or deleted within the specified time range. */
  public static final int MODEL_ADD_CHANGE_DELETE = 3;

  /** Like MODEL_ADD, except considering document discovery */
  public static final int MODEL_CHAINED_ADD = 9;
  /** Like MODEL_ADD_CHANGE, except considering document discovery */
  public static final int MODEL_CHAINED_ADD_CHANGE = 10;
  /** Like MODEL_ADD_CHANGE_DELETE, except considering document discovery */
  public static final int MODEL_CHAINED_ADD_CHANGE_DELETE = 11;

  // These are the job modes the connector may want to know about.
  // For a once-only job, it is essential that documents that are processed by processDocuments() always queue up their child links,
  // This is not true for continuous jobs, which never delete unreachable links because they never terminate.
  public static final int JOBMODE_ONCEONLY = IJobDescription.TYPE_SPECIFIED;
  public static final int JOBMODE_CONTINUOUS = IJobDescription.TYPE_CONTINUOUS;

  /** This is the global deny token.  This should be ingested with all documents. */
  public static final String GLOBAL_DENY_TOKEN = "DEAD_AUTHORITY";

  /** Tell the world what model this connector uses for addSeedDocuments().
  * This must return a model value as specified above.  The connector does not have to be connected
  * for this method to be called.
  *@return the model type value.
  */
  public int getConnectorModel();

  /** Return the list of activities that this connector supports (i.e. writes into the log).
  * The connector does not have to be connected for this method to be called.
  *@return the list.
  */
  public String[] getActivitiesList();

  /** Return the list of relationship types that this connector recognizes.
  * The connector does not need to be connected for this method to be called.
  *@return the list.
  */
  public String[] getRelationshipTypes();

  /** Get the bin name strings for a document identifier.  The bin name describes the queue to which the
  * document will be assigned for throttling purposes.  Throttling controls the rate at which items in a
  * given queue are fetched; it does not say anything about the overall fetch rate, which may operate on
  * multiple queues or bins.
  * For example, if you implement a web crawler, a good choice of bin name would be the server name, since
  * that is likely to correspond to a real resource that will need real throttle protection.
  * The connector must be connected for this method to be called.
  *@param documentIdentifier is the document identifier.
  *@return the set of bin names.  If an empty array is returned, it is equivalent to there being no request
  * rate throttling available for this identifier.
  */
  public String[] getBinNames(String documentIdentifier);

  /** Request arbitrary connector information.
  * This method is called directly from the API in order to allow API users to perform any one of several
  * connector-specific queries.  These are usually used to create external UI's.  The connector will be
  * connected before this method is called.
  *@param output is the response object, to be filled in by this method.
  *@param command is the command, which is taken directly from the API request.
  *@return true if the resource is found, false if not.  In either case, output may be filled in.
  */
  public boolean requestInfo(Configuration output, String command)
    throws ManifoldCFException;

  /** Queue "seed" documents.  Seed documents are the starting places for crawling activity.  Documents
  * are seeded when this method calls appropriate methods in the passed in ISeedingActivity object.
  *
  * This method can choose to find repository changes that happen only during the specified time interval.
  * The seeds recorded by this method will be viewed by the framework based on what the
  * getConnectorModel() method returns.
  *
  * It is not a big problem if the connector chooses to create more seeds than are
  * strictly necessary; it is merely a question of overall work required.
  *
  * The end time and seeding version string passed to this method may be interpreted for greatest efficiency.
  * For continuous crawling jobs, this method will
  * be called once, when the job starts, and at various periodic intervals as the job executes.
  *
  * When a job's specification is changed, the framework automatically resets the seeding version string to null.  The
  * seeding version string may also be set to null on each job run, depending on the connector model returned by
  * getConnectorModel().
  *
  * Note that it is always ok to send MORE documents rather than less to this method.
  * The connector will be connected before this method can be called.
  *@param activities is the interface this method should use to perform whatever framework actions are desired.
  *@param spec is a document specification (that comes from the job).
  *@param seedTime is the end of the time range of documents to consider, exclusive.
  *@param lastSeedVersionString is the last seeding version string for this job, or null if the job has no previous seeding version string.
  *@param jobMode is an integer describing how the job is being run, whether continuous or once-only.
  *@return an updated seeding version string, to be stored with the job.
  */
  public String addSeedDocuments(ISeedingActivity activities, Specification spec,
    String lastSeedVersion, long seedTime, int jobMode)
    throws ManifoldCFException, ServiceInterruption;

  /** Process a set of documents.
  * This is the method that should cause each document to be fetched, processed, and the results either added
  * to the queue of documents for the current job, and/or entered into the incremental ingestion manager.
  * The document specification allows this class to filter what is done based on the job.
  * The connector will be connected before this method can be called.
  *@param documentIdentifiers is the set of document identifiers to process.
  *@param statuses are the currently-stored document versions for each document in the set of document identifiers
  * passed in above.
  *@param activities is the interface this method should use to queue up new document references
  * and ingest documents.
  *@param jobMode is an integer describing how the job is being run, whether continuous or once-only.
  *@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one.
  */
  public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec,
    IProcessActivity activities, int jobMode, boolean usesDefaultAuthority)
    throws ManifoldCFException, ServiceInterruption;

  /** Get the maximum number of documents to amalgamate together into one batch, for this connector.
  * The connector does not need to be connected for this method to be called.
  *@return the maximum number. 0 indicates "unlimited".
  */
  public int getMaxDocumentRequest();

  // UI support methods.
  //
  // The UI support methods come in two varieties.  The first group (inherited from IConnector) is involved
  //  in setting up connection configuration information.
  //
  // The second group is listed here.  These methods are is involved in presenting and editing document specification
  //  information for a job.
  //
  // The two kinds of methods are accordingly treated differently, in that the first group cannot assume that
  // the current connector object is connected, while the second group can.  That is why the first group
  // receives a thread context argument for all UI methods, while the second group does not need one
  // (since it has already been applied via the connect() method).

  /** Obtain the name of the form check javascript method to call.
  *@param connectionSequenceNumber is the unique number of this connection within the job.
  *@return the name of the form check javascript method.
  */
  public String getFormCheckJavascriptMethodName(int connectionSequenceNumber);

  /** Obtain the name of the form presave check javascript method to call.
  *@param connectionSequenceNumber is the unique number of this connection within the job.
  *@return the name of the form presave check javascript method.
  */
  public String getFormPresaveCheckJavascriptMethodName(int connectionSequenceNumber);

  /** Output the specification header section.
  * This method is called in the head section of a job page which has selected a repository connection of the
  * current type.  Its purpose is to add the required tabs to the list, and to output any javascript methods
  * that might be needed by the job editing HTML.
  * The connector will be connected before this method can be called.
  *@param out is the output to which any HTML should be sent.
  *@param locale is the locale the output is preferred to be in.
  *@param ds is the current document specification for this job.
  *@param connectionSequenceNumber is the unique number of this connection within the job.
  *@param tabsArray is an array of tab names.  Add to this array any tab names that are specific to the connector.
  */
  public void outputSpecificationHeader(IHTTPOutput out, Locale locale, Specification ds,
    int connectionSequenceNumber, List<String> tabsArray)
    throws ManifoldCFException, IOException;

  /** Output the specification body section.
  * This method is called in the body section of a job page which has selected a repository connection of the
  * current type.  Its purpose is to present the required form elements for editing.
  * The coder can presume that the HTML that is output from this configuration will be within appropriate
  *  <html>, <body>, and <form> tags.  The name of the form is always "editjob".
  * The connector will be connected before this method can be called.
  *@param out is the output to which any HTML should be sent.
  *@param locale is the locale the output is preferred to be in.
  *@param ds is the current document specification for this job.
  *@param connectionSequenceNumber is the unique number of this connection within the job.
  *@param actualSequenceNumber is the connection within the job that has currently been selected.
  *@param tabName is the current tab name.  (actualSequenceNumber, tabName) form a unique tuple within
  *  the job.
  */
  public void outputSpecificationBody(IHTTPOutput out, Locale locale, Specification ds,
    int connectionSequenceNumber, int actualSequenceNumber, String tabName)
    throws ManifoldCFException, IOException;

  /** Process a specification post.
  * This method is called at the start of job's edit or view page, whenever there is a possibility that form
  * data for a connection has been posted.  Its purpose is to gather form information and modify the
  * document specification accordingly.  The name of the posted form is always "editjob".
  * The connector will be connected before this method can be called.
  *@param variableContext contains the post data, including binary file-upload information.
  *@param locale is the locale the output is preferred to be in.
  *@param ds is the current document specification for this job.
  *@param connectionSequenceNumber is the unique number of this connection within the job.
  *@return null if all is well, or a string error message if there is an error that should prevent saving of
  * the job (and cause a redirection to an error page).
  */
  public String processSpecificationPost(IPostParameters variableContext, Locale locale, Specification ds,
    int connectionSequenceNumber)
    throws ManifoldCFException;

  /** View specification.
  * This method is called in the body section of a job's view page.  Its purpose is to present the document
  * specification information to the user.  The coder can presume that the HTML that is output from
  * this configuration will be within appropriate <html> and <body> tags.
  * The connector will be connected before this method can be called.
  *@param out is the output to which any HTML should be sent.
  *@param locale is the locale the output is preferred to be in.
  *@param ds is the current document specification for this job.
  *@param connectionSequenceNumber is the unique number of this connection within the job.
  */
  public void viewSpecification(IHTTPOutput out, Locale locale, Specification ds,
    int connectionSequenceNumber)
    throws ManifoldCFException, IOException;

}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

    <title>
  Ethos
 — Omni4D</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="/static/omni4d.css">

    <link rel="shortcut icon" href="static/images/omni4d-32x32.png">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Omni4D

Models

Projects

Contributing

Community

News

About

Ethos

The way we behave...and what we do if we don't

            We are still working on this page. It's not finished yet!

© Owen Campbell 2016


text:
package net.runelite.client.plugins.timetracking;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import net.runelite.client.game.AsyncBufferedImage;
import net.runelite.client.game.ItemManager;
import net.runelite.client.plugins.timetracking.clocks.ClockManager;
import net.runelite.client.plugins.timetracking.farming.FarmingTracker;
import net.runelite.client.plugins.timetracking.hunter.BirdHouseTracker;
import net.runelite.client.ui.ColorScheme;
import net.runelite.client.ui.PluginPanel;
import net.runelite.client.ui.components.materialtabs.MaterialTab;
import net.runelite.client.ui.components.materialtabs.MaterialTabGroup;

class TimeTrackingPanel extends PluginPanel
{
	private final ItemManager itemManager;
	private final TimeTrackingConfig config;

	/* This is the panel the tabs' respective panels will be displayed on. */
	private final JPanel display = new JPanel();
	private final Map<Tab, MaterialTab> uiTabs = new HashMap<>();
	private final MaterialTabGroup tabGroup = new MaterialTabGroup(display);

	private boolean active;

	@Nullable
	private TabContentPanel activeTabPanel = null;

	TimeTrackingPanel(ItemManager itemManager, TimeTrackingConfig config,
		FarmingTracker farmingTracker, BirdHouseTracker birdHouseTracker, ClockManager clockManager)
	{
		super(false);

		this.itemManager = itemManager;
		this.config = config;

		setLayout(new BorderLayout());
		setBackground(ColorScheme.DARK_GRAY_COLOR);

		display.setBorder(new EmptyBorder(10, 10, 8, 10));

		tabGroup.setLayout(new GridLayout(0, 6, 7, 7));
		tabGroup.setBorder(new EmptyBorder(10, 10, 0, 10));

		add(tabGroup, BorderLayout.NORTH);
		add(display, BorderLayout.CENTER);

		addTab(Tab.OVERVIEW, new OverviewTabPanel(itemManager, config, this, farmingTracker, birdHouseTracker, clockManager));
		addTab(Tab.CLOCK, clockManager.getClockTabPanel());
		addTab(Tab.BIRD_HOUSE, birdHouseTracker.createBirdHouseTabPanel());

		for (Tab tab : Tab.FARMING_TABS)
		{
			addTab(tab, farmingTracker.createTabPanel(tab));
		}
	}

	private void addTab(Tab tab, TabContentPanel tabContentPanel)
	{
		JPanel wrapped = new JPanel(new BorderLayout());
		wrapped.add(tabContentPanel, BorderLayout.NORTH);
		wrapped.setBackground(ColorScheme.DARK_GRAY_COLOR);

		JScrollPane scroller = new JScrollPane(wrapped);
		scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		scroller.getVerticalScrollBar().setPreferredSize(new Dimension(16, 0));
		scroller.getVerticalScrollBar().setBorder(new EmptyBorder(0, 9, 0, 0));
		scroller.setBackground(ColorScheme.DARK_GRAY_COLOR);

		// Use a placeholder icon until the async image gets loaded
		MaterialTab materialTab = new MaterialTab(new ImageIcon(), tabGroup, scroller);
		materialTab.setPreferredSize(new Dimension(30, 27));
		materialTab.setName(tab.getName());
		materialTab.setToolTipText(tab.getName());

		AsyncBufferedImage icon = itemManager.getImage(tab.getItemID());
		Runnable resize = () ->
		{
			BufferedImage subIcon = icon.getSubimage(0, 0, 32, 32);
			materialTab.setIcon(new ImageIcon(subIcon.getScaledInstance(24, 24, Image.SCALE_SMOOTH)));
		};
		icon.onChanged(resize);
		resize.run();

		materialTab.setOnSelectEvent(() ->
		{
			config.setActiveTab(tab);
			activeTabPanel = tabContentPanel;

			tabContentPanel.update();
			return true;
		});

		uiTabs.put(tab, materialTab);
		tabGroup.addTab(materialTab);

		if (config.activeTab() == tab)
		{
			tabGroup.select(materialTab);
		}
	}

	void switchTab(Tab tab)
	{
		tabGroup.select(uiTabs.get(tab));
	}

	/**
	 * Gets the update interval of the active tab panel, in units of 200 milliseconds.
	 */
	int getUpdateInterval()
	{
		return activeTabPanel == null ? Integer.MAX_VALUE : activeTabPanel.getUpdateInterval();
	}

	/**
	 * Updates the active tab panel, if this plugin panel is displayed.
	 */
	void update()
	{
		if (!active || activeTabPanel == null)
		{
			return;
		}

		SwingUtilities.invokeLater(activeTabPanel::update);
	}

	@Override
	public void onActivate()
	{
		active = true;
		update();
	}

	@Override
	public void onDeactivate()
	{
		active = false;
	}
}


text:
package manager;

import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;

public class config {

	 public static void setModelColumn(TableColumn tb,String a){
	        tb.setCellValueFactory(new PropertyValueFactory(a));
	    }
}