Example #1
0
        public OutputData RenderScene(Scene scene)
        {
            ISet<Task<RenderData>> results = new HashSet<Task<RenderData>>();
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    Vector3f rayDirection = renderManager.CalculateEyeRayDirection(x, y);
                    Vector3f rayStart = new Vector3f(x, y, 0.0f);

                    results.Add(taskFactory.StartNew(() => CastEyeRay(new Ray(rayStart, rayDirection), scene)));
                }
            }
            Task<RenderData>[] resultsArray = new Task<RenderData>[results.Count];
            results.CopyTo(resultsArray, 0);

            Task.WaitAll(resultsArray);

            BasicOutputConverter coverter = new BasicOutputConverter(1, width, height);

            RenderData[] finalData = new RenderData[resultsArray.Length];

            for (int i = 0; i < finalData.Length; i++)
            {
                finalData[i] = resultsArray[i].Result;
            }

            return coverter.DoConversion(finalData);
        }
Example #2
0
    private List<Line> lines = new List<Line>(); // The lines contain info about all blocks from bottom to top.

    #endregion Fields

    #region Methods

    /// <summary>
    /// Add the chip blocks to grid.
    /// </summary>
    /// <param name='toAdd'>
    /// The chip is will be added.
    /// </param>
    public void Add(Chip toAdd)
    {
        int lineIndex, blockIndex;
        Vector3 blockPos;
        Line tempLine;
        HashSet<Line> affectedLines=new HashSet<Line>();
        foreach(Transform blockTrans in toAdd.blocks){
            blockPos=transform.TransformPoint(blockTrans.position);
            lineIndex=Mathf.RoundToInt(blockPos.y);
            if(lineIndex>=lines.Count){
                for(int i=lineIndex-lines.Count; i>=0; i--){
                    tempLine=Instantiate(lineEtalon)as Line;
                    tempLine.transform.SetParent(transform);
                    tempLine.transform.rotation=Quaternion.identity;
                    tempLine.transform.localPosition=new Vector3(0f, lines.Count, 0f);
                    lines.Add(tempLine);
                }
            }
            tempLine=lines[lineIndex];
            affectedLines.Add(tempLine);

            blockIndex=Mathf.RoundToInt(blockPos.x);
            tempLine.blocks[blockIndex]=blockTrans;
            blockTrans.SetParent(tempLine.transform);
        }
        //remove chip
        toAdd.blocks.Clear();
        Destroy(toAdd.gameObject);
        //check lines for remove
        Line[] checkList=new Line[affectedLines.Count];
        affectedLines.CopyTo(checkList);
        RemoveFilledLines(checkList);
    }
Example #3
0
    public int[] Intersection(int[] nums1, int[] nums2)
    {
        int[] intersectArray = new int[0];

        if (nums1.Length == 0 || nums2.Length == 0)
        {
            return intersectArray;
        }

        foreach(int i in nums1)
        {
            if (!valueSet.Contains(i))
            {
                valueSet.Add(i);
            }
        }

        HashSet<int> intersectSet = new HashSet<int>();
        foreach(int j in nums2)
        {
            if (valueSet.Contains(j))
            {
                intersectSet.Add(j);
            }
        }

        intersectArray = new int[intersectSet.Count];
        intersectSet.CopyTo(intersectArray);
        return intersectArray;
    }
        protected AuditSaveRequest GetAuditSaveRequest(ISaveRequestHandler handler)
        {
            var auditFields = new HashSet<Field>();
            var flag = handler.IsCreate ? FieldFlags.Insertable : FieldFlags.Updatable;
            foreach (var field in handler.Row.GetFields())
                if (field.Flags.HasFlag(flag))
                    auditFields.Add(field);

            Field[] array = new Field[auditFields.Count];
            auditFields.CopyTo(array);

            var auditRequest = new AuditSaveRequest(handler.Row.Table, (IIdRow)handler.Old, (IIdRow)handler.Row, array);

            var parentIdRow = handler.Row as IParentIdRow;
            if (parentIdRow != null)
            {
                var parentIdField = (Field)parentIdRow.ParentIdField;

                if (!parentIdField.ForeignTable.IsTrimmedEmpty())
                {
                    auditRequest.ParentTypeId = parentIdField.ForeignTable;
                    auditRequest.OldParentId = handler.IsCreate ? null : parentIdRow.ParentIdField[handler.Old];
                    auditRequest.NewParentId = parentIdRow.ParentIdField[handler.Row];
                }
            }

            return auditRequest;
        }
        /// <summary>
        /// Initializes this force-directed layout. Assumes that graph has some
        /// reasonable initial node positions.
        /// </summary>
        /// <param name="graph">The graph to layout.</param>
        /// <param name="start_node">The node to start layout from.</param>
        public ForceDirectedLayout(IReadOnlyGraph<FDLNode, FDLEdge> graph, FDLNode start_node)
        {
            if (graph == null)
                throw new ArgumentNullException("graph");
            if (start_node == null)
                throw new ArgumentNullException("start_node");
            if (!graph.ContainsNode(start_node))
                throw new ArgumentException("start_node must be in this graph");

            //initialize nodes array to only the reachable nodes
            ArrayList n = new ArrayList(graph.NodeCount);
            Algorithms.Algorithms.BreadthFirstSearch(graph, start_node, null, delegate(FDLNode node){
                n.Add(node);
            });
            nodes = new FDLNode[n.Count];
            n.CopyTo(nodes);

            new_positions = new MutablePoint[nodes.Length];
            accels = new double[nodes.Length];

            //summarize constraints
            HashSet<FDLEdge> h = new HashSet<FDLEdge>();
            for (int i = 0; i < nodes.Length; i++)
            {
                foreach (FDLEdge edge in nodes[i].OutEdges)
                {
                    DefaultEdge reverse = edge.Target.GetEdgeTo(edge.Source);
                    if(h.Contains(edge) || (reverse != null && h.Contains(reverse)))
                        continue;
                    h.Add(edge);
                }
            }
            constraints = new FDLEdge[h.Count];
            h.CopyTo(constraints);
        }
 public static string[] RemoveDuplicates(string[] s)
 {
     HashSet<string> set = new HashSet<string>(s);
     string[] result = new string[set.Count];
     set.CopyTo(result);
     return result;
 }
        public IGeometry Union()
        {
            PointLocator locater = new PointLocator();
            // use a set to eliminate duplicates, as required for union
            var exteriorCoords = new HashSet<Coordinate>();

            foreach (IPoint point in PointExtracter.GetPoints(_pointGeom))
            {
                Coordinate coord = point.Coordinate;
                Location loc = locater.Locate(coord, _otherGeom);

                if (loc == Location.Exterior)
                {
                    exteriorCoords.Add(coord);
                }
            }

            // if no points are in exterior, return the other geom
            if (exteriorCoords.Count == 0)
            {
                return _otherGeom;
            }

            // make a puntal geometry of appropriate size
            var exteriorCoordsArray = new Coordinate[exteriorCoords.Count];
            exteriorCoords.CopyTo(exteriorCoordsArray, 0);
            Array.Sort(exteriorCoordsArray);
            ICoordinateSequence coords = _geomFact.CoordinateSequenceFactory.Create(exteriorCoordsArray);
            IGeometry ptComp = coords.Count == 1 ? (IGeometry)_geomFact.CreatePoint(coords.GetCoordinate(0)) : _geomFact.CreateMultiPoint(coords);

            // add point component to the other geometry
            return GeometryCombiner.Combine(ptComp, _otherGeom);
        }
        void IInitializable.Initialize()
        {

            // parse resource metadata annotation.

            HashSet<string> metafileExts = new HashSet<string>();            
            char[] sep = { ';' };
            foreach (ChildInfo chInfo in m_schemaLoader.GetRootElements())
            {
                DomNodeType domtype = chInfo.Type;
                IEnumerable<XmlNode> annotations = domtype.GetTag<IEnumerable<XmlNode>>();
                if (annotations == null)
                    continue;
                
                foreach (XmlElement annot in annotations)
                {
                    if (annot.LocalName != "ResourceMetadata")
                        continue;

                    string metaExt = annot.GetAttribute("metadataFileExt").ToLower();
                    metafileExts.Add(metaExt);
                    string[] resExts = annot.GetAttribute("resourceFileExts").ToLower().Split(sep, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string ext in resExts)
                    {
                        ResourceMetadataInfo metadataInfo
                            = new ResourceMetadataInfo(chInfo, metaExt);
                        m_extMap.Add(ext, metadataInfo);
                    }                    
                }                
            }
            m_metadataFileExts = new string[metafileExts.Count];
            metafileExts.CopyTo(m_metadataFileExts);
            
        }
        public static void Init()
        {
            if ( !PluginSettings.Instance.PlayerBlockEnforcementEnabled )
                return;

            if (_init)
                return;

            _init = true;

            MyEntities.OnEntityAdd += MyEntities_OnEntityAdd;

            HashSet<MyEntity> allEntities = new HashSet<MyEntity>();
            Wrapper.GameAction( () => allEntities = MyEntities.GetEntities() );

            MyEntity[] entitiesCopy = new MyEntity[allEntities.Count];
            allEntities.CopyTo( entitiesCopy );

            Parallel.ForEach( entitiesCopy, ( entity ) =>
                                            {
                                                var grid = entity as MyCubeGrid;
                                                if ( grid == null )
                                                    return;

                                                InitGrid( grid );
                                            } );
            Essentials.Log.Info( "Initialized player block enforcement." );
            ProcessEnforcement();
        }
Example #10
0
 protected virtual void Filter(HashSet<Tile> tiles)
 {
     Tile[] array = new Tile[tiles.Count];
     tiles.CopyTo(array);
     for (int i = array.Length - 1; i >= 0; --i)
         if (array[i].unit != null)
             tiles.Remove(array[i]);
 }
Example #11
0
 public void Test_CopyTo()
 {
     hs = new HashSet<int>();
     hs.Add(1); hs.Add(2); hs.Add(3);
     int[] mass = { 1, 2, 3 };
     int[] mass1 = new int[3];
     hs.CopyTo(mass1);
     Assert.That(mass1, Is.EqualTo(mass));
 }
Example #12
0
        public static void CopyTo_Array_Test2()
        {
            HashSet<int> hashSet = new HashSet<int>(new int[] { 1, 2, 3, 4, 5, 6, 7 });
            int[] array = new int[] { -1, -2, -3, -4, -5, -6, -7, -8, -9 };
            hashSet.CopyTo(array);
            HashSet<int> hashSet2 = new HashSet<int>(array);

            HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 5, 6, 7 }, EqualityComparer<int>.Default);
            HashSetTestSupport<int>.VerifyHashSet(hashSet2, new int[] { 1, 2, 3, 4, 5, 6, 7, -8, -9 }, EqualityComparer<int>.Default);
        }
Example #13
0
 private uint[] ReadBeats(StoryBeat[] beats)
 {
     HashSet<uint> seenIds = new HashSet<uint>();
     foreach (StoryBeat beat in beats)
         foreach (StoryEvent evt in beat.Events)
             foreach (uint id in evt.Participants)
                 seenIds.Add(id);
     uint[] result = new uint[seenIds.Count];
     seenIds.CopyTo(result);
     return result;
 }
Example #14
0
        public static void CopyTo_Array_Exceptions()
        {
            //Test 1: Array is null
            HashSet<int> hashSet = new HashSet<int>(new int[] { 1, 2, 3, 4, 5, 6, 7 });
            int[] array = null;
            Assert.Throws<ArgumentNullException>(() => hashSet.CopyTo(array)); //"Expected ArgumentNullException"

            //Test 2: Array is one smaller than set size
            hashSet = new HashSet<int>(new int[] { 1, 2, 3, 4, 5, 6, 7 });
            array = new int[6];
            Assert.Throws<ArgumentException>(() => hashSet.CopyTo(array)); //"Expected ArgumentException"
        }
Example #15
0
 public void setIntTuplesWithSwapsAndSignChange(IntTuple[] inputIntTuples, IntTupleEqualityComparer comparer)
 {
     HashSet<IntTuple> container = new HashSet<IntTuple>(comparer);
     foreach (var intTuple in inputIntTuples)
     {
         container.Add(intTuple);
         addOppositeElements(container, intTuple);
         addSwapElements(container);
     }
     this.intTuples = new IntTuple[container.Count];
     container.CopyTo(this.intTuples);
 }
Example #16
0
        /// <summary>
        /// Generates the sequence of integer numbers.
        /// </summary>
        private void Generate()
        {
            var seq = new HashSet<int>();
            var array = new int[ this.Target ];

            while ( seq.Count < this.Target ) {
                seq.Add( this.rnd.Next( this.Target ) );
            }

            seq.CopyTo( array );
            this.sequence = new ReadOnlyCollection<int>( array );
        }
Example #17
0
 public string CreateResourceFilters(Table sel)
 {
     HashSet<string> resIds = new HashSet<string>();
     int resCol = sel.ColumnDefinitions.IndexOf("ResID");
     for (int i = 0; i < sel.Rows; i++) {
         resIds.Add((string)sel[i, resCol]);
     }
     if (resIds.Count == 0) return null;
     string[] ids = new string[resIds.Count];
     resIds.CopyTo(ids);
     if (ids.Length == 1) return "ResID=" + ids[0];
     else return "ResID in (" + string.Join(",", ids) + ")";
 }
Example #18
0
        protected AbstractMatcher(int[] indices)
        {
            var indicesSet = new HashSet<int>(indices);
            _indices = new int[indicesSet.Count];
            indicesSet.CopyTo(_indices);
            Array.Sort(_indices);

            int hash = GetType().GetHashCode();
            for (int i = 0, indicesLength = _indices.Length; i < indicesLength; i++) {
                hash ^= _indices[i] * 647;
            }
            hash ^= _indices.Length * 997;
            _hash = hash;
        }
Example #19
0
		public static bool Overlap(this Collider2D collider, Vector2 point1, Vector2 point2,
			out Collider2D[] listOverlap)
		{
			var res = new HashSet<Collider2D>();
			var layer = collider.gameObject.layer;
			var colliders = Physics2D.OverlapAreaAll(point1, point2);

			foreach (Collider2D item in colliders)
				if (!item.isTrigger &&
					!Physics2D.GetIgnoreLayerCollision(layer, item.gameObject.layer))
					res.Add(item);

			listOverlap = new Collider2D[res.Count];
			res.CopyTo(listOverlap);
			return (listOverlap.Length > 0);
		}
 public static AttributeInfo[] GetCustomAttributes(Assembly assembly, Type attribute)
 {
     if (assembly == null)
     {
         throw new ArgumentNullException("assembly");
     }
     HashSet<AttributeInfo> attributes = new HashSet<AttributeInfo>();
     foreach (Type type in assembly.GetExportedTypes())
     {
         foreach (Attribute attr in type.GetCustomAttributes(attribute, true))
         {
             AttributeInfo attributeInfo = new AttributeInfo(type, attr);
             attributes.Add(attributeInfo);
         }
     }
     AttributeInfo[] result = new AttributeInfo[attributes.Count];
     attributes.CopyTo(result);
     return result;
 }
Example #21
0
    public Color[] UniqueColors(int amount)
    {
        if (amount > tileColors.Length) {
            amount = tileColors.Length;
            Debug.LogWarning("Can't get " + amount +
                             " unique colors when there are only " + tileColors.Length +
                             " colors to choose from!");
        }

        Color[] uniqueColors = new Color[amount];

        HashSet<Color> uniqueColorsSet = new HashSet<Color>();
        while (uniqueColorsSet.Count != amount) {
            uniqueColorsSet.Add(RandomColor());
        }
        uniqueColorsSet.CopyTo(uniqueColors);

        return uniqueColors;
    }
        static int Main(string[] args)
        {
            object obj = new object();
            HashSet<object> hashset;
            Object[] oa = new Object[2];

            hashset = new HashSet<object>();
            hashset.Add(obj);
            hashset.Remove(obj);

            //Regression test: make sure these don't throw.
            foreach (object o in hashset)
            {
            }
            hashset.CopyTo(oa, 0, 2);
            hashset.RemoveWhere(MyPredicate);

            return 100;
        }
Example #23
0
        private void Awake()
        {
            mesh = GetComponent<MeshFilter>().sharedMesh;

            HashSet<Vector4> meshPlanes = new HashSet<Vector4>();
            for(int i=0 ; i<mesh.triangles.Length ; i+=3)
            {
                Plane face = new Plane(GetVertex(i), GetVertex(i + 1), GetVertex(i + 2));
                Vector4 planeEq = new Vector4(face.normal.x, face.normal.y, face.normal.z, face.distance);

                if (!meshPlanes.Contains(planeEq))
                {
                    meshPlanes.Add(planeEq);
                }
            }

            initPlanes = new Vector4[meshPlanes.Count];
            meshPlanes.CopyTo(initPlanes);
        }
        public void DistributedCacheEmulator_Increment_WorksMultiThreaded()
        {
            var cache = new DistributedCacheEmulator();
            cache.Set("MultiThreadedValue", 12345);
            var values = new HashSet<long>();

            Parallel.ForEach(new int[100], x =>
            {
                var result = cache.Increment("MultiThreadedValue");
                lock (values)
                    values.Add(result);
            });

            Assert.Equal(100, values.Count);
            var sorted = new long[100];
            values.CopyTo(sorted);
            Array.Sort(sorted);
            for (var i = 0; i < sorted.Length; i++)
                Assert.Equal(i + 1 + 12345, sorted[i]);
        }
Example #25
0
        public void CopyToTest()
        {
            var set = new HashSet<int>();
            var limit = rnd.Next(10, 100);
            for (int i = 0; i < limit; i++)
            {
                set.Add(i);
            }
            var arr = new int[10+limit];
            for (int i = 0; i < 10; i++)
            {
                arr[i] = -i-1;
            }

            set.CopyTo(arr, 10);
            for (int i = 10; i < arr.Length; i++)
            {
                Assert.AreEqual(arr[i],i-10);
            }
        }
        public static void Regression_Dev10_624201()
        {
            Predicate<object> predicate = (Object o) => { return false; };

            object obj = new object();
            HashSet<object> hashset;
            Object[] oa = new Object[2];

            hashset = new HashSet<object>();
            hashset.Add(obj);
            hashset.Remove(obj);

            //Regression test: make sure these don't throw.
            foreach (object o in hashset)
            { }
            hashset.CopyTo(oa, 0, 2);
            hashset.RemoveWhere(predicate);

            // we just want to make sure it doesn't throw.
        }
        private static char[] GetInvalidPathChars()
        {
            // Union InvalidFileNameChars and InvalidPathChars together
            // while excluding slash.
            HashSet<char> charSet = new HashSet<char>(Path.GetInvalidPathChars());

            foreach (char c in invalidFileNameChars)
            {
                if ('\\' == c || '/' == c || charSet.Contains(c))
                {
                    continue;
                }

                charSet.Add(c);
            }

            invalidPathChars = new char[charSet.Count];
            charSet.CopyTo(invalidPathChars);

            return invalidPathChars;
        }
Example #28
0
        public void Analize()
        {
            Assembly assembly;
            Type[] types;
            ISet<CodeDetails> allCodes = new HashSet<CodeDetails>();

            assembly = Assembly.LoadFrom(path);
            types = assembly.GetExportedTypes();

            foreach (Type type in types)
            {
                if (type.IsClass && !type.IsInterface && !type.IsAbstract && !type.IsGenericType)
                {
                    if (typeof(ICode).IsAssignableFrom(type))
                        allCodes.Add(RetriveDetails(type));
                }
            }

            codes = new CodeDetails[allCodes.Count];
            allCodes.CopyTo(codes, 0);
        }
Example #29
0
        public IList<KeyValuePair<string, string>> Map(string fileLine)
        {
            IList<KeyValuePair<String, String>> result = new List<KeyValuePair<String, String>>();

            string[] splitWords = fileLine.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' },
                StringSplitOptions.RemoveEmptyEntries);

            HashSet<string> set = new HashSet<string>(splitWords);
            string[] noDuplicateWords = new string[set.Count];
            set.CopyTo(noDuplicateWords);

            try {
                foreach (string word in noDuplicateWords) {
                    int wordCount = Regex.Matches(fileLine, word).Count;
                    result.Add(new KeyValuePair<String, String>(word, wordCount.ToString()));
                }
            } catch (Exception) {
                // Do not add line to result
            }

            return result;
        }
        public override void Execute()
        {
            var regularExpression = new StringBuilder();

            // Name the grouping "Parameter", make it start with ":" or "@", then a letter, and followed by up to 29 letters, numbers, or underscores.  Finally, look ahead
            // and make sure the next character is not a letter, number, or underscore.
            regularExpression.Append(@"(?<Parameter>[:@][a-zA-Z][a-zA-Z0-9_\.]{0,127})(?=[^a-zA-Z0-9_\.])");

            // Or, allow the same thing as above accept look ahead and allow the string to end immediately after the parameter.
            regularExpression.Append(@"|(?<Parameter>[:@][a-zA-Z][a-zA-Z0-9_\.]{0,127})$");

            var regex = new Regex(regularExpression.ToString(), RegexOptions.Multiline);
            var matches = regex.Matches(CommandText);

            var parameterNameSet = new HashSet<string>();
            for (var i = 0; i < matches.Count; i++)
            {
                parameterNameSet.Add(matches[i].Groups["Parameter"].Value);
            }
            ParameterNames = new string[parameterNameSet.Count];
            parameterNameSet.CopyTo(ParameterNames);
        }