static void Main() { // -9,223,372,036,854,775,808 == long.MinValue // 9,223,372,036,854,775,807 == long.MaxValue // long.MinValue <= a[i] <= long.MaxValue // 1 <= i <= 99,999 // Input data int n = int.Parse(Console.ReadLine()); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = long.Parse(Console.ReadLine()); } // Calculate HashSet<long> oddElementValues = new HashSet<long>(); for (int i = 0; i < n; i++) { if (oddElementValues.Contains(a[i])) { oddElementValues.Remove(a[i]); } else { oddElementValues.Add(a[i]); } } HashSet<long>.Enumerator enumerator = oddElementValues.GetEnumerator(); enumerator.MoveNext(); // Output data Console.WriteLine(enumerator.Current); }
public TrustedHtml AddAttributes(string tag, params string[] keys) { if (string.IsNullOrEmpty(tag)) { throw new System.ArgumentNullException("tag"); } if (keys == null) { throw new System.ArgumentNullException("keys"); } HashSet<string> hashSet = new HashSet<string>(); for (int i = 0; i < keys.Length; i++) { string text = keys[i]; if (string.IsNullOrEmpty(text)) { throw new System.Exception("key"); } hashSet.Add(text); } if (this._attributes.ContainsKey(tag)) { using (HashSet<string>.Enumerator enumerator = hashSet.GetEnumerator()) { while (enumerator.MoveNext()) { string current = enumerator.Current; this._attributes[tag].Add(current); } return this; } } this._attributes.Add(tag, hashSet); return this; }
public void TestIterators() { List<int> myList = new List<int> { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 }; HashSet<int> mySet = new HashSet<int> { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 }; for (int i = 0; i < myList.Count; i++) Console.Write("{0} ", myList[i]); Console.WriteLine(); IEnumerator<int> pi = mySet.GetEnumerator(); while (pi.MoveNext()) { int x = pi.Current; Console.Write("{0} ", x); } Console.WriteLine(); foreach (int x in myList) Console.Write("{0} ", x); Console.WriteLine(); MyIntList myIntList = new MyIntList { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 }; IEnumerator<int> px = myIntList.GetEnumerator(x => 0 == x % 3); while ( px.MoveNext()) Console.Write("{0} ", px.Current); Console.WriteLine(); // displays 3 9 6 3 foreach(int x in myIntList) Console.Write("{0} ", x); Console.WriteLine(); // displays 3 1 4 1 5 9 2 6 5 3 5 Console.ReadKey(); }
public int[] allClique(string[] graphEdge) { int n = graphEdge.Length; int[] ret = new int[n]; HashSet<int> c = new HashSet<int>(); HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { ret[i] = 0; c.Add(1<<i); } ret[0] = n; for (int k = 1; k < n; k++) { HashSet<int> cc = new HashSet<int>(); HashSet<int>.Enumerator ee = c.GetEnumerator(); while(ee.MoveNext()) { List<int> l = new List<int>(); int set = ee.Current; for (int i = 0; i < n; i++) { if ((set & (1 << i)) == (1 << i)) continue; bool found = true; int e = set; int p = 0; while (e > 0) { if ((e & 1) == 1) { if (graphEdge[p][i] == '0') { found = false; break; } } e = e >> 1; p++; } if (found) { l.Add(i); } } for (int i = 0; i < l.Count; i++) { cc.Add(set | (1 << l[i])); } } ret[k] = cc.Count; c = cc; } return ret; }
public static void Main () { var hs = new HashSet<string>() { "a", "b", "c" }; foreach (var s in hs) Console.WriteLine(s); Console.WriteLine(hs.Count); var test = hs.GetEnumerator(); }
static int lonelyinteger(int[] a) { HashSet<int> myInts = new HashSet<int>(); foreach (int item in a) { if (myInts.Contains(item)) myInts.Remove(item); else myInts.Add(item); } IEnumerator<int> itr = myInts.GetEnumerator(); itr.MoveNext(); return itr.Current; }
public NetworkGraph( int numNodePairs ) { HashSet<Edge> initialEdges = new HashSet<Edge>(); String nodeType1; String nodeType2; for (int i = 0; i < numNodePairs; i++) { String address1 = this.GenerateIPAddress(); String address2 = this.GenerateIPAddress(); if (uniqueAddresses.Contains(address1) || uniqueAddresses.Contains(address2)) continue; do { nodeType1 = GenerateNodeType(); nodeType2 = GenerateNodeType(); } while (!ValidateNodeConnection(nodeType1, nodeType2)); Node x = new Node(nodeType1, address1); Node y = new Node(nodeType2, address2); Edge edge = new Edge(x, y, GenerateWeight()); x.AddEdge(edge); y.AddEdge(edge); initialEdges.Add(edge); networkGraph.Add(x); networkGraph.Add(y); uniqueAddresses.Add(address1); uniqueAddresses.Add(address2); } using (IEnumerator<Edge> it = initialEdges.GetEnumerator()) { it.MoveNext(); Edge curEdge = it.Current; while (it.MoveNext()) { Edge nextEdge = it.Current; Node curX = curEdge.GetX(); Node curY = curEdge.GetY(); Node nextX = nextEdge.GetX(); Node nextY = nextEdge.GetY(); if (ValidateNodeConnection(curX.GetType().ToString(), nextX.GetType().ToString())) { Edge newXX = new Edge(curX, nextX, GenerateWeight()); curX.AddEdge(newXX); nextX.AddEdge(newXX); } else if (ValidateNodeConnection(curX.GetType().ToString(), nextY.GetType().ToString())) { Edge newXY = new Edge(curX, nextY, GenerateWeight()); curX.AddEdge(newXY); nextY.AddEdge(newXY); } else if (ValidateNodeConnection(curY.GetType().ToString(), nextX.GetType().ToString())) { Edge newYX = new Edge(curY, nextX, GenerateWeight()); curX.AddEdge(newYX); nextY.AddEdge(newYX); } else if (ValidateNodeConnection(curY.GetType().ToString(), nextY.GetType().ToString())) { Edge newYY = new Edge(curY, nextY, GenerateWeight()); curX.AddEdge(newYY); nextY.AddEdge(newYY); } curEdge = nextEdge; } } }
public IEnumerator <UpstreamHost> GetEnumerator() { return(_hosts.GetEnumerator()); }
internal static void _CrossOver(Location[] locations1, Location[] locations2, bool mutateFailedCrossovers) { // I am not validating parameters because this method is internal. // If you want to make it public, you should validate the parameters. var availableLocations = new HashSet<Location>(locations1); int startPosition = GetRandomValue(locations1.Length); int crossOverCount = GetRandomValue(locations1.Length - startPosition); if (mutateFailedCrossovers) { bool useMutation = true; int pastEndPosition = startPosition + crossOverCount; for (int i=startPosition; i<pastEndPosition; i++) { if (locations1[i] != locations2[i]) { useMutation = false; break; } } // if the crossover is not going to give any change, we // force a mutation. if (useMutation) { MutateRandomLocations(locations1); return; } } Array.Copy(locations2, startPosition, locations1, startPosition, crossOverCount); List<int> toReplaceIndexes = null; // Now we will remove the used locations from the available locations. // If we can't remove one, this means it was used in duplicate. At this // moment we only register those indexes that have duplicate locations. int index = 0; foreach(var value in locations1) { if (!availableLocations.Remove(value)) { if (toReplaceIndexes == null) toReplaceIndexes = new List<int>(); toReplaceIndexes.Add(index); } index++; } // Finally we will replace duplicated items by those that are still available. // This is how we avoid having chromosomes that contain duplicated places to go. if (toReplaceIndexes != null) { // To do this, we enumerate two objects in parallel. // If we could use foreach(var indexToReplace, location from toReplaceIndexex, location1) it would be great. using(var enumeratorIndex = toReplaceIndexes.GetEnumerator()) { using(var enumeratorLocation = availableLocations.GetEnumerator()) { while(true) { if (!enumeratorIndex.MoveNext()) { Debug.Assert(!enumeratorLocation.MoveNext()); break; } if (!enumeratorLocation.MoveNext()) throw new InvalidOperationException("Something wrong happened."); locations1[enumeratorIndex.Current] = enumeratorLocation.Current; } } } } }
public void EnterSSA() { IRControlFlowGraph cfg = IRControlFlowGraph.Build(this); if (cfg == null) return; int originalCount = Locals.Count; bool[] originalAssignments = new bool[originalCount]; int[] originalIterations = new int[originalCount]; IRLocal tempLocal = null; Locals.ForEach(l => l.SSAData = new IRLocal.IRLocalSSAData(l)); // Add new local iterations for each assignment to an original local, and keep // track of final iterations for each node, assigning true to indicate it was // assigned, false means propagated (used later) foreach (IRControlFlowGraphNode node in cfg.Nodes) { node.SSAFinalIterations = new Tuple<IRLocal, bool>[originalCount]; node.SSAPhis = new IRLocal[originalCount]; foreach (IRInstruction instruction in node.Instructions) { if (instruction.Destination == null || instruction.Destination.Type != IRLinearizedLocationType.Local) continue; tempLocal = Locals[instruction.Destination.Local.LocalIndex]; if (!originalAssignments[tempLocal.Index]) { originalAssignments[tempLocal.Index] = true; node.SSAFinalIterations[tempLocal.Index] = new Tuple<IRLocal, bool>(tempLocal, true); continue; } tempLocal = tempLocal.Clone(this); Locals.Add(tempLocal); tempLocal.SSAData.Iteration = ++originalIterations[tempLocal.SSAData.Original.Index]; instruction.Destination.Local.LocalIndex = tempLocal.Index; node.SSAFinalIterations[tempLocal.SSAData.Original.Index] = new Tuple<IRLocal, bool>(tempLocal, true); } } // Any SSAFinalIterations missing from the entry node means the entry node // did not assign to the original local, so they can be filled in with // propagated original locals by, assigning false to indicate propagated for (int index = 0; index < originalCount; ++index) { if (cfg.Nodes[0].SSAFinalIterations[index] == null) cfg.Nodes[0].SSAFinalIterations[index] = new Tuple<IRLocal, bool>(Locals[index], false); } // Any SSAFinalIterations missing from any node means the node did not // assign to the original local, so they can be filled in with propagated // locals using the dominance tree, assigning false to indicate propagated foreach (IRControlFlowGraphNode node in cfg.Nodes) { for (int index = 0; index < originalCount; ++index) { if (node.SSAFinalIterations[index] == null) { IRControlFlowGraphNode treeNode = node.Dominator; while (treeNode.SSAFinalIterations[index] == null) treeNode = treeNode.Dominator; node.SSAFinalIterations[index] = new Tuple<IRLocal, bool>(treeNode.SSAFinalIterations[index].Item1, false); } } } // Now that all final iterations are known, we also know if the final // iteration for a node was assigned or propagated // So now we can create a phi, in the dominance frontiers of nodes which // have assignments to original locals // If the phi is the only assignment in a dominance frontier node, then // the phi destination becomes the final iteration for that node int localsBeforePhis = Locals.Count; BitArray phiInserted = new BitArray(cfg.Nodes.Count, false); BitArray localAssigned = new BitArray(cfg.Nodes.Count, false); HashSet<IRControlFlowGraphNode> unprocessedNodes = new HashSet<IRControlFlowGraphNode>(); HashSet<IRControlFlowGraphNode>.Enumerator unprocessedNodesEnumerator; IRControlFlowGraphNode processingNode = null; for (int originalIndex = 0; originalIndex < originalCount; ++originalIndex) { phiInserted.SetAll(false); localAssigned.SetAll(false); foreach (IRControlFlowGraphNode node in cfg.Nodes) { if (node.SSAFinalIterations[originalIndex].Item2) { localAssigned.Set(node.Index, true); unprocessedNodes.Add(node); } } while (unprocessedNodes.Count > 0) { unprocessedNodesEnumerator = unprocessedNodes.GetEnumerator(); unprocessedNodesEnumerator.MoveNext(); processingNode = unprocessedNodesEnumerator.Current; unprocessedNodes.Remove(processingNode); foreach (IRControlFlowGraphNode frontierNode in processingNode.Frontiers) { if (!phiInserted[frontierNode.Index]) { tempLocal = Locals[originalIndex].Clone(this); Locals.Add(tempLocal); tempLocal.SSAData.Iteration = ++originalIterations[originalIndex]; tempLocal.SSAData.Phi = true; frontierNode.SSAPhis[originalIndex] = tempLocal; if (!frontierNode.SSAFinalIterations[originalIndex].Item2) frontierNode.SSAFinalIterations[originalIndex] = new Tuple<IRLocal, bool>(tempLocal, true); phiInserted.Set(frontierNode.Index, true); if (!localAssigned[frontierNode.Index]) { localAssigned.Set(frontierNode.Index, true); unprocessedNodes.Add(frontierNode); } } } } } // Now we have assignments expanded, phi's created, and we can // determine phi sources from a nodes parents final iterations, // which we will use later // Initial iterations for each original local in a node can now // be found through using the SSAPhi's if available, otherwise // using immediate dominator final iterations, the entry node // cannot have phis, and has no immediate dominator, so we just // copy the original locals (iteration 0) as the currentIterations // So finally, now we can retarget uses of original locals by // keeping track of the current iterations, replacing source uses // with current iterations, and updating the current iterations // when there is local assignments IRLocal[] currentIterations = new IRLocal[originalCount]; foreach (IRControlFlowGraphNode node in cfg.Nodes) { if (node.Index == 0) Locals.CopyTo(0, currentIterations, 0, originalCount); else { for (int index = 0; index < originalCount; ++index) currentIterations[index] = node.SSAPhis[index] ?? node.Dominator.SSAFinalIterations[index].Item1; } foreach (IRInstruction instruction in node.Instructions) { instruction.Sources.ForEach(l => l.RetargetLocals(currentIterations)); if (instruction.Destination != null) { if (instruction.Destination.Type == IRLinearizedLocationType.Local) { tempLocal = Locals[instruction.Destination.Local.LocalIndex]; currentIterations[tempLocal.SSAData.Original.Index] = tempLocal; } else { instruction.Destination.RetargetLocals(currentIterations); } } } } // At this point, most of the requirements set by SSA have been // fulfilled, all we want to do now is insert a move instruction // with a linearized phi source for each phi in the frontiers using // the parent final iterations created earlier, with phi reductions // based on lifetime analysis, so that various optimizations occuring // before leaving SSA can be done much more effectively IRMoveInstruction moveInstruction = null; IRLinearizedLocation location = null; HashSet<int> sourceLocals = new HashSet<int>(); // Used to prevent us from adding the same source twice foreach (IRControlFlowGraphNode node in cfg.Nodes) { for (int originalIndex = originalCount - 1; originalIndex >= 0; --originalIndex) { if (node.SSAPhis[originalIndex] != null) { moveInstruction = new IRMoveInstruction(); moveInstruction.Destination = new IRLinearizedLocation(moveInstruction, IRLinearizedLocationType.Local); moveInstruction.Destination.Local.LocalIndex = node.SSAPhis[originalIndex].Index; location = new IRLinearizedLocation(moveInstruction, IRLinearizedLocationType.Phi); location.Phi.SourceLocations = new List<IRLinearizedLocation>(); foreach (IRControlFlowGraphNode parentNode in node.ParentNodes) { int finalIterationIndex = parentNode.SSAFinalIterations[originalIndex].Item1.Index; if (sourceLocals.Add(finalIterationIndex)) { IRLinearizedLocation phiSourceLocation = new IRLinearizedLocation(moveInstruction, IRLinearizedLocationType.Local); phiSourceLocation.Local.LocalIndex = finalIterationIndex; location.Phi.SourceLocations.Add(phiSourceLocation); } } sourceLocals.Clear(); if (location.Phi.SourceLocations.Count == 1) { location.Type = IRLinearizedLocationType.Local; location.Local.LocalIndex = location.Phi.SourceLocations[0].Local.LocalIndex; location.Phi.SourceLocations = null; } moveInstruction.Sources.Add(location); InsertInstruction(node.Instructions[0].IRIndex, moveInstruction); node.Instructions.Insert(0, moveInstruction); } } } mInstructions.FixInsertedTargetInstructions(); // Analyze local lifespans CalculateLocalSSALifespans(cfg); // Find dead phis that got move instructions inserted, and remove // the unneeded instructions, then fix branch targets again List<IRLocal> deadPhis = mLocals.FindAll(l => l.SSAData.Phi && l.SSAData.LifeBegins == l.SSAData.LifeEnds); IRInstruction onlyInstruction = null; foreach (IRLocal deadPhi in deadPhis) { onlyInstruction = deadPhi.SSAData.LifeBegins; mInstructions.Remove(onlyInstruction); deadPhi.SSAData.LifeBegins = null; deadPhi.SSAData.LifeEnds = null; } mInstructions.FixRemovedTargetInstructions(); // Ensure that SSA lifespan analysis data is unusable, as it was // invalidated by dead phi removal mLocals.ForEach(l => l.SSAData.LifeBegins = l.SSAData.LifeEnds = null); //LayoutLocals(); // Test that we did stuff right, make sure no local is assigned // more than once, though some may never get assigned due to // phi reductions that occur, if an exception is thrown here // it is most likely due to something that caused dead code // but never removed it before entering SSA, or a bug with // branching that removed a valid node and we luckily caught a // duplicate assignment due to unprocessed instructions bool[] assigned = new bool[Locals.Count]; foreach (IRInstruction instruction in Instructions) { if (instruction.Destination != null && instruction.Destination.Type == IRLinearizedLocationType.Local) { if (assigned[instruction.Destination.Local.LocalIndex]) throw new Exception(); assigned[instruction.Destination.Local.LocalIndex] = true; } } }
public override bool Begin() { if( !RaiseBeginningEvent( this ) ) return false; UndoState = Player.DrawBegin( this ); StartTime = DateTime.UtcNow; if( !(Brush is NormalBrush) ) { // for nonstandard brushes, cache all coordinates up front nonStandardBrush = true; // Generate a list if all coordinates allCoords = new HashSet<Vector3I>(); while( coordEnumerator.MoveNext() ) { allCoords.Add( coordEnumerator.Current ); } coordEnumerator.Dispose(); // Replace our F2D enumerator with a HashSet enumerator coordEnumerator = allCoords.GetEnumerator(); } HasBegun = true; Map.QueueDrawOp( this ); RaiseBeganEvent( this ); return true; }
/// <summary> /// /// <para> /// This causes the set of players that can see this object to be rebuild. The OnRebuildObservers callback function will be invoked on each NetworkBehaviour. /// </para> /// /// </summary> /// <param name="initialize">True if this is the first time.</param> public void RebuildObservers(bool initialize) { if (this.m_Observers == null) return; bool flag = false; HashSet<NetworkConnection> observers = new HashSet<NetworkConnection>(); HashSet<NetworkConnection> hashSet = new HashSet<NetworkConnection>((IEnumerable<NetworkConnection>) this.m_Observers); for (int index = 0; index < this.m_NetworkBehaviours.Length; ++index) { NetworkBehaviour networkBehaviour = this.m_NetworkBehaviours[index]; flag |= networkBehaviour.OnRebuildObservers(observers, initialize); } if (!flag) { if (!initialize) return; using (List<NetworkConnection>.Enumerator enumerator = NetworkServer.connections.GetEnumerator()) { while (enumerator.MoveNext()) { NetworkConnection current = enumerator.Current; if (current != null && current.isReady) this.AddObserver(current); } } using (List<NetworkConnection>.Enumerator enumerator = NetworkServer.localConnections.GetEnumerator()) { while (enumerator.MoveNext()) { NetworkConnection current = enumerator.Current; if (current != null && current.isReady) this.AddObserver(current); } } } else { using (HashSet<NetworkConnection>.Enumerator enumerator = observers.GetEnumerator()) { while (enumerator.MoveNext()) { NetworkConnection current = enumerator.Current; if (initialize || !hashSet.Contains(current)) { current.AddToVisList(this); if (LogFilter.logDebug) { object[] objArray = new object[4]; int index1 = 0; string str1 = "New Observer for "; objArray[index1] = (object) str1; int index2 = 1; GameObject gameObject = this.gameObject; objArray[index2] = (object) gameObject; int index3 = 2; string str2 = " "; objArray[index3] = (object) str2; int index4 = 3; NetworkConnection networkConnection = current; objArray[index4] = (object) networkConnection; Debug.Log((object) string.Concat(objArray)); } } } } using (HashSet<NetworkConnection>.Enumerator enumerator = hashSet.GetEnumerator()) { while (enumerator.MoveNext()) { NetworkConnection current = enumerator.Current; if (!observers.Contains(current)) { current.RemoveFromVisList(this, false); if (LogFilter.logDebug) { object[] objArray = new object[4]; int index1 = 0; string str1 = "Removed Observer for "; objArray[index1] = (object) str1; int index2 = 1; GameObject gameObject = this.gameObject; objArray[index2] = (object) gameObject; int index3 = 2; string str2 = " "; objArray[index3] = (object) str2; int index4 = 3; NetworkConnection networkConnection = current; objArray[index4] = (object) networkConnection; Debug.Log((object) string.Concat(objArray)); } } } } if (initialize) { using (List<NetworkConnection>.Enumerator enumerator = NetworkServer.localConnections.GetEnumerator()) { while (enumerator.MoveNext()) { NetworkConnection current = enumerator.Current; if (!observers.Contains(current)) this.OnSetLocalVisibility(false); } } } this.m_Observers = new List<NetworkConnection>((IEnumerable<NetworkConnection>) observers); } }
private static void ExcludeModuleManagers(ref HashSet<string> nativeClasses) { string[] moduleNames = ModuleMetadata.GetModuleNames(); int classId = BaseObjectTools.StringToClassID("GlobalGameManager"); foreach (string moduleName in moduleNames) { if (ModuleMetadata.GetModuleStrippable(moduleName)) { int[] moduleClasses = ModuleMetadata.GetModuleClasses(moduleName); HashSet<int> intSet = new HashSet<int>(); HashSet<string> stringSet = new HashSet<string>(); foreach (int num in moduleClasses) { if (BaseObjectTools.IsDerivedFromClassID(num, classId)) intSet.Add(num); else stringSet.Add(BaseObjectTools.ClassIDToString(num)); } if (stringSet.Count != 0 && !nativeClasses.Overlaps((IEnumerable<string>) stringSet)) { using (HashSet<int>.Enumerator enumerator = intSet.GetEnumerator()) { while (enumerator.MoveNext()) { int current = enumerator.Current; nativeClasses.Remove(BaseObjectTools.ClassIDToString(current)); } } } } } }
internal static void _CrossOver(Location[] locations1, Location[] locations2, bool mutateFailedCrossovers) { // I am not validating parameters because this method is internal. // If you want to make it public, you should validate the parameters. var availableLocations = new HashSet <Location>(locations1); int startPosition = GetRandomValue(locations1.Length); int crossOverCount = GetRandomValue(locations1.Length - startPosition); if (mutateFailedCrossovers) { bool useMutation = true; int pastEndPosition = startPosition + crossOverCount; for (int i = startPosition; i < pastEndPosition; i++) { if (locations1[i] != locations2[i]) { useMutation = false; break; } } // if the crossover is not going to give any change, we // force a mutation. if (useMutation) { MutateRandomLocations(locations1); return; } } Array.Copy(locations2, startPosition, locations1, startPosition, crossOverCount); List <int> toReplaceIndexes = null; // Now we will remove the used locations from the available locations. // If we can't remove one, this means it was used in duplicate. At this // moment we only register those indexes that have duplicate locations. int index = 0; foreach (var value in locations1) { if (!availableLocations.Remove(value)) { if (toReplaceIndexes == null) { toReplaceIndexes = new List <int>(); } toReplaceIndexes.Add(index); } index++; } // Finally we will replace duplicated items by those that are still available. // This is how we avoid having chromosomes that contain duplicated places to go. if (toReplaceIndexes != null) { // To do this, we enumerate two objects in parallel. // If we could use foreach(var indexToReplace, location from toReplaceIndexex, location1) it would be great. using (var enumeratorIndex = toReplaceIndexes.GetEnumerator()) { using (var enumeratorLocation = availableLocations.GetEnumerator()) { while (true) { if (!enumeratorIndex.MoveNext()) { Debug.Assert(!enumeratorLocation.MoveNext()); break; } if (!enumeratorLocation.MoveNext()) { throw new InvalidOperationException("Something wrong happened."); } locations1[enumeratorIndex.Current] = enumeratorLocation.Current; } } } } }
public MyConcurrentHashSetEnumerator(HashSet <T> set, SpinLockRef.Token ilock) { setEnumerator = set.GetEnumerator(); this.ilock = ilock; }
public static QueryWrapper <T, EnumerableQueryOp <T, HashSet <T> .Enumerator> > Query <T>(this HashSet <T> hashSet) { return(new QueryWrapper <T, EnumerableQueryOp <T, HashSet <T> .Enumerator> >(new EnumerableQueryOp <T, HashSet <T> .Enumerator>(hashSet.GetEnumerator()))); }
public HashSet <TEntity> .Enumerator GetEnumerator() { return(_entities.GetEnumerator()); }
/// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection. /// </returns> public IEnumerator <MetaField> GetEnumerator() { return(_fields.GetEnumerator()); }
public IEnumerator <BoundaryGraphNode> GetEnumerator() { return(nodes.GetEnumerator()); }
public IEnumerator <T> GetEnumerator() { return(_items.GetEnumerator()); }
private void CheckTermsOrder(IndexReader r, ISet<string> allTerms, bool isTop) { TermsEnum terms = MultiFields.GetFields(r).Terms("f").Iterator(null); BytesRef last = new BytesRef(); HashSet<string> seenTerms = new HashSet<string>(); while (true) { BytesRef term = terms.Next(); if (term == null) { break; } Assert.IsTrue(last.CompareTo(term) < 0); last.CopyBytes(term); string s = term.Utf8ToString(); Assert.IsTrue(allTerms.Contains(s), "term " + TermDesc(s) + " was not added to index (count=" + allTerms.Count + ")"); seenTerms.Add(s); } if (isTop) { Assert.IsTrue(allTerms.SetEquals(seenTerms)); } // Test seeking: IEnumerator<string> it = seenTerms.GetEnumerator(); while (it.MoveNext()) { BytesRef tr = new BytesRef(it.Current); Assert.AreEqual(TermsEnum.SeekStatus.FOUND, terms.SeekCeil(tr), "seek failed for term=" + TermDesc(tr.Utf8ToString())); } }
public IEnumerator <Dependency> GetEnumerator() { return(dependencies.GetEnumerator()); }
private bool included(){ List<Pair<Arc, HashSet<Arc>>> Q1=this.buildSingleCharacterSuperGraphs(); foreach (Pair<Arc, HashSet<Arc>> g in Q1) { if (!double_graph_test(g, g, spec.InitialState.id)) { return false; } } HashSet<Pair<Arc, HashSet<Arc>>> Next = new HashSet<Pair<Arc, HashSet<Arc>>>(Q1); HashSet<Pair<Arc, HashSet<Arc>>> Processed=new HashSet<Pair<Arc, HashSet<Arc>>>(); while(Next.Count > 0){ HashSet<Pair<Arc, HashSet<Arc>>>.Enumerator Enumerator = Next.GetEnumerator(); Pair<Arc, HashSet<Arc>> g = Enumerator.Current; foreach (Pair<Arc, HashSet<Arc>> h in Processed) { if(!double_graph_test(g, h, spec.InitialState.id)||!double_graph_test(h, g, spec.InitialState.id)) return false; } Next.Remove(g); Processed.Add(g); //debug("Processed:"+Processed); //debug("Next:"+Next); foreach (Pair<Arc, HashSet<Arc>> h in Q1) { List<Pair<Arc, HashSet<Arc>>> toRemove=new List<Pair<Arc, HashSet<Arc>>>(); if(composable(g,h)){ Pair<Arc, HashSet<Arc>> f=compose(g, h); bool discard=false; //debug("f:"+f +"="+g+";"+h); foreach (Pair<Arc, HashSet<Arc>> p in Processed) { if(smallerThan(f, p)){ toRemove.Add(p); } if(smallerThan(p, f)){ discard=true; break; } } if(discard) continue; foreach (Pair<Arc, HashSet<Arc>> p in Next) { if(smallerThan(f, p)){ toRemove.Add(p); } if(smallerThan(p, f)){ discard=true; break; } } if(discard) continue; if(!double_graph_test(f, f, spec.InitialState.id)) return false; //Processed.removeAll(toRemove); //Next.removeAll(toRemove); foreach (Pair<Arc, HashSet<Arc>> pair in toRemove) { Processed.Remove(pair); Next.Remove(pair); } if(opt2) Next.Add(min(f)); else Next.Add(f); } } } return true; }
/// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// An enumerator that can be used to iterate through the collection. /// </returns> public IEnumerator <ILocalDbDefaultConstraint <TEntity> > GetEnumerator() { return(_constraints.GetEnumerator()); }
/// <summary> /// カットを実行 /// </summary> public void ExecuteCut() { int h = plateBuildMap_.GetLength(0); int w = plateBuildMap_.GetLength(1); var labelMap = new int[h,w]; var labelLinkTbl = new Dictionary<int,int>(); int labelSeed = 0; // ラベリングしていきます for (int yy = 0; yy < h; yy++) { if (yy == 0) { // 縦の開始の場合 int nowLabel = labelSeed++; for (int xx = 0; xx < w; xx++) { if (xx != 0) { if(cutting_.GetVertLineCutOp(xx-1, yy) == CuttingInfo_.CutOperations.Cut) { nowLabel = labelSeed++; } } labelMap[yy, xx] = nowLabel; } } else { // 一つ上のブロックを起点にします int nowLabel = labelMap[yy-1, 0]; for (int xx = 0; xx < w; xx++) { if (cutting_.GetHoriLineCutOp(yy - 1, xx) == CuttingInfo_.CutOperations.None) { if (xx==0 || cutting_.GetVertLineCutOp(xx - 1, yy) == CuttingInfo_.CutOperations.None) { //上とつながる、左とつながる場合 if (labelMap[yy - 1, xx] != nowLabel) { // 上と違うラベルの場合、2つの領域が連結されます labelLinkTbl[nowLabel] = labelMap[yy - 1, xx]; } } else { //上とつながる、左とつながら無い場合 nowLabel = labelMap[yy - 1, xx]; } } else { if (xx==0) { //上とつながら無い、横の起点び場合 nowLabel = labelSeed++; } else if(cutting_.GetVertLineCutOp(xx - 1, yy) == CuttingInfo_.CutOperations.None) { //上とつながら無い、左とつながる場合 } else { //上とつながら無い、左とつながら無い場合 nowLabel = labelSeed++; } } labelMap[yy, xx] = nowLabel; } } } // ラベルを振りなおします var labelSet = new HashSet<int>(); for (int yy = 0; yy < h; yy++) { for (int xx = 0; xx < w; xx++) { if (labelLinkTbl.ContainsKey(labelMap[yy, xx])) { labelMap[yy, xx] = labelLinkTbl[labelMap[yy, xx]]; } labelSet.Add(labelMap[yy, xx]); } } // 領域が2つ以上であれば分割します if(labelSet.Count>1) { Debug.Log(string.Format("labelSet.Count = {0}", labelSet.Count)); for (int zz = 0; zz < h; zz++) { for (int xx = 0; xx < w; xx++) { if(labelMap[zz, xx] != labelSet.GetEnumerator().Current) { plateBuildMap_[zz, xx].TestOffsetY = -labelMap[zz, xx] * 2.8f; } } } RebuildDrawPlateObject_(); cutting_.ClearAll(); cutting_.ReBuildDrawObject(); } }
public IEnumerator <IPAddress> GetEnumerator() { InitOnece(); return(_hashSet.GetEnumerator()); }
private static void WriteModuleAndClassRegistrationFile(string file, HashSet<string> nativeModules, HashSet<string> nativeClasses, HashSet<string> classesToSkip) { using (TextWriter w = (TextWriter) new StreamWriter(file)) { CodeStrippingUtils.WriteStaticallyLinkedModuleRegistration(w, nativeModules, nativeClasses); w.WriteLine(); w.WriteLine("void RegisterAllClasses()"); w.WriteLine("{"); if (nativeClasses == null) { w.WriteLine("\tvoid RegisterAllClassesGranular();"); w.WriteLine("\tRegisterAllClassesGranular();"); } else { w.WriteLine("\t//Total: {0} classes", (object) nativeClasses.Count); int num = 0; using (HashSet<string>.Enumerator enumerator = nativeClasses.GetEnumerator()) { while (enumerator.MoveNext()) { string current = enumerator.Current; w.WriteLine("\t//{0}. {1}", (object) num, (object) current); if (classesToSkip.Contains(current)) { w.WriteLine("\t//Skipping {0}", (object) current); } else { w.WriteLine("\tvoid RegisterClass_{0}();", (object) current); w.WriteLine("\tRegisterClass_{0}();", (object) current); } w.WriteLine(); ++num; } } } w.WriteLine("}"); w.Close(); } }
/// <summary> /// Returns an enumerator that iterates through the hash set. /// </summary> /// <returns> /// An enumerator for the hash set. /// </returns> public virtual HashSet <T> .Enumerator GetEnumerator() => _set.GetEnumerator();
/// <summary> /// Tries all filenames (complete path) included in the fullFileNameFile file. /// </summary> /// <param name="fullFileNameFile"></param> /// <returns> number of newly found filenames</returns> public long ParseFilenames(string fullFileNameFile) { Start(); hashDic.CreateHelpers(); long result = 0; if (File.Exists(fullFileNameFile)) { Hasher warhash = new Hasher(hasherType); //Read the file FileStream fs = new FileStream(fullFileNameFile, FileMode.Open); StreamReader reader = new StreamReader(fs); HashSet<string> fileList = new HashSet<string>(); string line; while ((line = reader.ReadLine()) != null) fileList.Add(line.ToLower().Replace('\\', '/')); reader.Close(); fs.Close(); // strip input file from duplicates. File.Delete(fullFileNameFile); fs = new FileStream(fullFileNameFile, FileMode.Create); StreamWriter writer = new StreamWriter(fs); foreach (string file in fileList) writer.WriteLine(file); writer.Close(); fs.Close(); foundNames = new Dictionary<string, bool>(); foreach (string fn in fileList) { foundNames[fn] = false; } //Just in case someday we want to multi thread. parseFileList = fileList.GetEnumerator(); string filename; while ((filename = GetFileName_ParseFilenames()) != null) { warhash.Hash(filename, 0xDEADBEEF); UpdateResults found = hashDic.UpdateHash(warhash.ph, warhash.sh, filename, 0); if (found == UpdateResults.NAME_UPDATED || found == UpdateResults.ARCHIVE_UPDATED) result++; if (found != UpdateResults.NOT_FOUND) foundNames[filename] = true; } if (active) { string outputFileRoot = Path.GetDirectoryName(fullFileNameFile) + "/" + Path.GetFileNameWithoutExtension(fullFileNameFile); FileStream ofsFound = new FileStream(outputFileRoot + "-found.txt", FileMode.Create); FileStream ofsNotFound = new FileStream(outputFileRoot + "-notfound.txt", FileMode.Create); StreamWriter swf = new StreamWriter(ofsFound); StreamWriter swnf = new StreamWriter(ofsNotFound); foreach (KeyValuePair<string, Boolean> file in foundNames) if (file.Value == true) { warhash.Hash(file.Key, 0xDEADBEEF); swf.WriteLine("{0:X8}" + HashDictionary.hashSeparator + "{1:X8}" + HashDictionary.hashSeparator + "{2}", warhash.ph, warhash.sh, file.Key); } else { //this is a quick and dirty fix to get some more debug info // to be removed in the future !!! warhash.Hash(file.Key, 0xDEADBEEF); //swnf.WriteLine("{0:X8}" + HashDictionary.hashSeparator // + "{1:X8}" + HashDictionary.hashSeparator // + "{2}", warhash.ph, warhash.sh, file.Key); swnf.WriteLine(file.Key); } swnf.Close(); swf.Close(); ofsFound.Close(); ofsNotFound.Close(); } } return result; }
public IEnumerator GetEnumerator() { return(HashSet.GetEnumerator()); }
/// <summary> Reads the connection rule data file, and initialize the object.</summary> /// <param name="filePath">- the path for the connection rule file /// </param> /// <param name="tagCount">- the number of total tags in the tag set /// </param> /// <param name="tagSet">- the tag set which is used in the connection rules /// </param> /// <throws> IOException </throws> private void readFile(System.String filePath, int tagCount, TagSet tagSet) { System.IO.StreamReader br = new System.IO.StreamReader( new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read), System.Text.Encoding.UTF8); System.String line = null; HashSet<int> tagSetA = new HashSet<int>(); HashSet<int> tagSetB = new HashSet<int>(); title = ""; version = ""; copyright = ""; author = ""; date = ""; editor = ""; startTag = ""; connectionTable = new bool[tagCount][]; for (int i = 0; i < tagCount; i++) { connectionTable[i] = new bool[tagCount]; } for (int i = 0; i < tagCount; i++) { for (int j = 0; j < tagCount; j++) { connectionTable[i][j] = false; } } while ((line = br.ReadLine()) != null) { StringTokenizer lineTokenizer = new StringTokenizer(line, "\t"); if (lineTokenizer.HasMoreTokens == false) { continue; } System.String lineToken = lineTokenizer.NextToken; if (lineToken.StartsWith("@")) { if ("@title".Equals(lineToken)) { title = lineTokenizer.NextToken; } else if ("@version".Equals(lineToken)) { version = lineTokenizer.NextToken; } else if ("@copyright".Equals(lineToken)) { copyright = lineTokenizer.NextToken; } else if ("@author".Equals(lineToken)) { author = lineTokenizer.NextToken; } else if ("@date".Equals(lineToken)) { date = lineTokenizer.NextToken; } else if ("@editor".Equals(lineToken)) { editor = lineTokenizer.NextToken; } } else if ("CONNECTION".Equals(lineToken)) { lineToken = lineTokenizer.NextToken; System.String[] tagLists = lineToken.Split("\\*", 2); StringTokenizer tagTokenizer = new StringTokenizer(tagLists[0], ",()"); while (tagTokenizer.HasMoreTokens) { System.String tagToken = tagTokenizer.NextToken; StringTokenizer tok = new StringTokenizer(tagToken, "-"); while (tok.HasMoreTokens) { System.String t = tok.NextToken; int[] fullTagIDSet = tagSet.getTags(t); if (fullTagIDSet != null) { for (int i = 0; i < fullTagIDSet.Length; i++) { tagSetA.Add(fullTagIDSet[i]); } } else { tagSetA.Add(tagSet.getTagID(t)); } while (tok.HasMoreTokens) { tagSetA.Remove(tagSet.getTagID(tok.NextToken)); } } } tagTokenizer = new StringTokenizer(tagLists[1], ",()"); while (tagTokenizer.HasMoreTokens) { System.String tagToken = tagTokenizer.NextToken; StringTokenizer tok = new StringTokenizer(tagToken, "-"); while (tok.HasMoreTokens) { System.String t = tok.NextToken; int[] fullTagIDSet = tagSet.getTags(t); if (fullTagIDSet != null) { for (int i = 0; i < fullTagIDSet.Length; i++) { tagSetB.Add(fullTagIDSet[i]); } } else { tagSetB.Add(tagSet.getTagID(t)); } while (tok.HasMoreTokens) { tagSetB.Remove(tagSet.getTagID(tok.NextToken)); } } } IEnumerator<int> iterA = tagSetA.GetEnumerator(); while (iterA.MoveNext()) { int leftSide = iterA.Current; IEnumerator<int> iterB = tagSetB.GetEnumerator(); while (iterB.MoveNext()) { connectionTable[leftSide][iterB.Current] = true; } } tagSetA.Clear(); tagSetB.Clear(); } else if ("START_TAG".Equals(lineToken)) { startTag = lineTokenizer.NextToken; } } br.Close(); }
/// <nodoc /> public Enumerator(HashSet <int> set) : this() { m_setEnumerator = set.GetEnumerator(); }
/// <inheritdoc /> public IEnumerator <MethodOverride> GetEnumerator() { return(_overrides?.GetEnumerator() ?? Enumerable.Empty <MethodOverride>().GetEnumerator()); }
public HashSet <MyEntityOreDeposit> .Enumerator GetEnumerator() { return(m_markers.GetEnumerator()); }
public IEnumerator <byte[]> GetEnumerator() { return(_items.GetEnumerator()); }
public IEnumerator <string> GetEnumerator() { return(_keys.GetEnumerator()); }
public override bool run() { BoardState boardState = new BoardState(droids, tiles, mapWidth(), mapHeight(), playerID()); Console.WriteLine("Turn Number: " + turnNumber().ToString()); // Find rightmost enemy turret and spawn terminator // If this is our first turn if (turnNumber() < 2) { int x1 = 10; int y1 = 0; int x2 = 10; int y2 = 0; bool foundSpot = false; bool foundSecondSpot = false; for (int i = 0; i < droids.Length; i++) { if (droids[i].Variant == (int)Unit.TURRET) { if (droids[i].Owner != playerID()) { if (getTile(droids[i].X, droids[i].Y).TurnsUntilAssembled == 0) { if (playerID() == 0) { if (droids[i].X > x1) { foundSpot = true; x1 = droids[i].X; y1 = droids[i].Y; } else if (droids[i].X > x2) { foundSecondSpot = true; x2 = droids[i].X; y2 = droids[i].Y; } } else { if (droids[i].X < x1) { foundSpot = true; x1 = droids[i].X; y1 = droids[i].Y; } else if (droids[i].X < x2) { foundSecondSpot = true; x2 = droids[i].X; y2 = droids[i].Y; } } } } } } if (players[playerID()].ScrapAmount >= modelVariants[(int)Unit.TERMINATOR].Cost && foundSpot) { players[playerID()].orbitalDrop(x1, y1, (int)Unit.TERMINATOR); } if (players[playerID()].ScrapAmount >= modelVariants[(int)Unit.TERMINATOR].Cost && foundSecondSpot) { players[playerID()].orbitalDrop(x2, y2, (int)Unit.TERMINATOR); } } // Find and spawn claws on enemy turrets // also count how many of each type we have int terminators = 0, claws = 0, archers = 0, hackers = 0, repair = 0; for (int i = 0; i < droids.Length; i++) { if (droids[i].Variant == (int)Unit.TURRET) { if (droids[i].Owner != playerID()) { if (getTile(droids[i].X, droids[i].Y).TurnsUntilAssembled == 0) { if (players[playerID()].ScrapAmount >= modelVariants[(int)Unit.CLAW].Cost) { players[playerID()].orbitalDrop(droids[i].X, droids[i].Y, (int)Unit.CLAW); } } } } else { if (droids[i].Owner == playerID()) { switch (droids[i].Variant) { case (int)Unit.TERMINATOR: terminators++; break; case (int)Unit.CLAW: claws++; break; case (int)Unit.ARCHER: archers++; break; case (int)Unit.HACKER: hackers++; break; case (int)Unit.REPAIRER: repair++; break; } } } } // DETECT WALLS int numUnits = 0; int colWithWall = -1; for (int i = 15; i < 25; i++) { int tempCount = 0; for (int j = 0; j < 20; j++) { if (boardState.theirMovables.getValueFromSpot(i, j) && !(getTile(i, j).TurnsUntilAssembled > 0)) tempCount++; } if (tempCount > numUnits) { numUnits = tempCount; colWithWall = i; } } // SPAWN CLAWS ON WALLS if (numUnits > 5) { for (int i = 0; i < 20; i++) { if (getTile(colWithWall, i).TurnsUntilAssembled == 0 && boardState.theirMovables.getValueFromSpot(colWithWall, i)) { if (players[playerID()].ScrapAmount >= modelVariants[(int)Unit.CLAW].Cost) { players[playerID()].orbitalDrop(colWithWall, i, (int)Unit.CLAW); } } } } Func<Point, bool> isWalkable = delegate(Point p) { return boardState.walkable.getValueFromSpot(p.X, p.Y); }; // Search for best spawn location int bestRow = 0; Bb middleRows = new Bb(mapWidth(), mapHeight()); HashSet<int> badRows = new HashSet<int>(); for (int i = 19; i < 21; i++) { for (int j = 0; j < mapHeight(); j++) { middleRows.setValueAtSpot(i, j); } } bool foundRow = false; int curCol = (playerID() == 0) ? 0 : mapWidth() - 1; Func<Point, bool> middleTarget = spot => { return middleRows.getValueFromSpot(spot.X, spot.Y); }; Bb spawnWalkable = new Bb(mapWidth(), mapHeight()); spawnWalkable.board = spawnWalkable.board.Or(boardState.walkable.board); spawnWalkable.board = spawnWalkable.board.Or(boardState.ourMovables.board); spawnWalkable.board = spawnWalkable.board.Or(boardState.theirMovables.board); int searches = 0; Func<Point, bool> spawnWalkableFunc = spot => { return spawnWalkable.getValueFromSpot(spot.X, spot.Y); }; while (!foundRow && searches < 15) { int shortest = 50; searches++; for (int i = 0; i < mapHeight(); i++) { if (getTile(curCol, i).TurnsUntilAssembled == 0) { IEnumerable<Point> path = Searcher.findPath(new Point(curCol, i), middleTarget, spawnWalkableFunc); int temp = -1; foreach (Point p in path) { temp++; } if (temp != -1 && temp < shortest) { shortest = temp; bestRow = i; foundRow = true; } else if (temp == -1) { badRows.Add(i); } } } if (!foundRow) { curCol = playerID() == 0 ? curCol + 1 : curCol - 1; badRows.Clear(); if (curCol < 0 || curCol >= mapWidth()) { curCol = (playerID() == 0) ? 0 : mapWidth() - 1; break; } } } if (searches >= 5) { curCol = playerID() == 0 ? curCol + 1 : curCol - 1; badRows.Clear(); bestRow = 0; } // want 1 terminator and hacker per 2 archers and 3 claws bool spawnClaws = terminators > claws && turnNumber() < 250; bool spawnArch = 2 * terminators > archers && !spawnClaws; bool spawnHack = terminators > hackers && turnNumber() > 25 && !spawnArch; bool spawnRepair = .5 * terminators > repair && turnNumber() > 75 && !spawnHack; int cost = 10; int unitID = 0; bool doomDrop = false; if (spawnClaws) { unitID = (int)Unit.CLAW; cost = modelVariants[(int)Unit.CLAW].Cost; } else if (spawnArch) { unitID = (int)Unit.ARCHER; cost = modelVariants[(int)Unit.ARCHER].Cost; } else if (spawnHack) { unitID = (int)Unit.HACKER; cost = modelVariants[(int)Unit.HACKER].Cost; } else if (spawnRepair) { unitID = (int)Unit.REPAIRER; cost = modelVariants[(int)Unit.REPAIRER].Cost; } else { Random rand = new Random(); if (rand.Next() % 3 == 0 && 500 - turnNumber() > 90) { // DOOM DROP TERMINATORS doomDrop = true; } unitID = (int)Unit.TERMINATOR; cost = modelVariants[(int)Unit.TERMINATOR].Cost; } Bb myUnits = new Bb(mapWidth(), mapHeight()); myUnits.board = myUnits.board.Or(boardState.ourHangers.board); myUnits.board = myUnits.board.Or(boardState.ourImmovables.board); myUnits.board = myUnits.board.Or(boardState.ourMovables.board); int iter = bestRow; int rowsChecked = 0; if (doomDrop) { // Search for walls bool foundAWall = true; while (players[playerID()].ScrapAmount >= modelVariants[(int)Unit.TERMINATOR].Cost && foundAWall) { bool foundWallThisIter = false; for (int i = 0; i < droids.Length; i++) { if (droids[i].Owner != playerID()) { if (droids[i].Variant == (int)Unit.WALL) { if (getTile(droids[i].X, droids[i].Y).TurnsUntilAssembled == 0) { if (playerID() == 0) { if (droids[i].X > 20) { players[playerID()].orbitalDrop(droids[i].X, droids[i].Y, (int)Unit.TERMINATOR); foundWallThisIter = true; } } else { if (droids[i].X < 20) { players[playerID()].orbitalDrop(droids[i].X, droids[i].Y, (int)Unit.TERMINATOR); foundWallThisIter = true; } } } } } } if (!foundWallThisIter) foundAWall = false; } if (players[playerID()].ScrapAmount >= modelVariants[(int)Unit.TERMINATOR].Cost) { // search for unreachable squares int theirFirstCol = mapWidth() - 1; if (playerID() == 1) theirFirstCol = 0; int doomSearchIter = 0; bool blockedSpotFound = false; HashSet<int> rowsToSpawn = new HashSet<int>(); while (doomSearchIter < 12 && !blockedSpotFound) { for (int i = 0; i < mapHeight(); i++) { if (!(getTile(theirFirstCol, i).TurnsUntilAssembled > 0)) { IEnumerable<Point> path = Searcher.findPath(new Point(theirFirstCol, i), middleTarget, spawnWalkableFunc); int temp = -1; foreach (Point p in path) { temp++; } if (temp == -1) { rowsToSpawn.Add(i); } } } if (rowsToSpawn.Count > 0) { blockedSpotFound = true; } else { doomSearchIter++; if (playerID() == 0) { theirFirstCol--; } else { theirFirstCol++; } } } Console.WriteLine("Doom drop search spot done"); if (doomSearchIter >= 7) { doomSearchIter = 0; } int anotherIter = 0; while (players[playerID()].ScrapAmount >= modelVariants[(int)Unit.TERMINATOR].Cost && rowsToSpawn.Count > 0 && anotherIter < 2) { int chooseRow = rowsToSpawn.GetEnumerator().Current; players[playerID()].orbitalDrop(theirFirstCol, chooseRow, (int)Unit.TERMINATOR); rowsToSpawn.Remove(chooseRow); anotherIter++; } Console.WriteLine("Best spots have been tried"); if (players[playerID()].ScrapAmount >= modelVariants[(int)Unit.TERMINATOR].Cost) { theirFirstCol = mapWidth() - 1; if (playerID() == 1) theirFirstCol = 0; for (int i = 0; i < mapHeight() && players[playerID()].ScrapAmount >= modelVariants[(int)Unit.TERMINATOR].Cost; i++) { if (!(getTile(theirFirstCol, i).TurnsUntilAssembled > 0)) { if (!boardState.theirHangers.getValueFromSpot(theirFirstCol, i)) { players[playerID()].orbitalDrop(theirFirstCol, i, (int)Unit.TERMINATOR); } } } } } } else { while (rowsChecked < mapHeight()) { // Not a bad row if (!badRows.Contains(iter)) { // enough scrap if (players[playerID()].ScrapAmount >= cost) { // nothing spawning here if (getTile(curCol, iter).TurnsUntilAssembled == 0) { if (!myUnits.getValueFromSpot(curCol, iter)) { // spawn it players[playerID()].orbitalDrop(curCol, iter, unitID); } } } iter++; if (iter >= mapHeight()) iter = 0; } rowsChecked++; } } // ATTACK Func<Point, bool> isAttackable = delegate(Point p) { return boardState.theirHangers.getValueFromSpot(p.X, p.Y) || boardState.hackTargets.getValueFromSpot(p.X, p.Y); }; Func<Point, bool> nope = delegate(Point p) { return false; }; for (int i = 0; i < droids.Length; i++) { //if you have control of the droid if ((droids[i].Owner == playerID() && droids[i].HackedTurnsLeft <= 0) || (droids[i].Owner != playerID() && droids[i].HackedTurnsLeft > 0)) { //if there are any attacks left if (droids[i].AttacksLeft > 0) { if (droids[i].Variant == (int)Unit.REPAIRER) { Bb targets = new Bb(boardState.ourHangers.width, boardState.ourHangers.height); targets.board = targets.board.Or(boardState.ourHangers.board); targets.board = targets.board.Or(boardState.ourMovables.board); targets.board = targets.board.Or(boardState.ourImmovables.board); Func<Point, bool> target = spot => { return targets.getValueFromSpot(spot.X, spot.Y); }; CIA.runMission(new Mission(MissionTypes.attackInRange, droids[i], target, isWalkable, nope)); } else { Func<Point, bool> hackerTarget = spot => { return boardState.hackTargets.getValueFromSpot(spot.X, spot.Y); }; Func<Point, bool> target = spot => { return boardState.attackTargets.getValueFromSpot(spot.X, spot.Y); }; if (droids[i].Variant != (int)Unit.HACKER) { CIA.runMission(new Mission(MissionTypes.attackInRange, droids[i], target, isWalkable, nope)); } else { CIA.runMission(new Mission(MissionTypes.attackInRange, droids[i], hackerTarget, isWalkable, nope)); } } boardState.update(droids, tiles); } } } Func<Point, bool> isEnemyHangar = delegate(Point p) { return boardState.theirHangers.getValueFromSpot(p.X, p.Y); }; Func<Point, bool> isNotAttacked = delegate(Point p) { return boardState.notAttackedByEnemy.getValueFromSpot(p.X, p.Y); }; Func<Point, bool> isGoalHacker = delegate(Point p) { return boardState.hackTargets.getValueFromSpot(p.X, p.Y); }; for (int i = 0; i < droids.Length; i++) { if (droids[i].MovementLeft > 0 && ((droids[i].Owner == playerID() && droids[i].HackedTurnsLeft == 0) || (droids[i].Owner != playerID() && droids[i].HackedTurnsLeft > 0))) { if (droids[i].HealthLeft < .3 * droids[i].MaxHealth) { Bb spotsOnOurSide = new Bb(mapWidth(), mapHeight()); spotsOnOurSide.board = spotsOnOurSide.board.Or(boardState.ourHalf.board); if (droids[i].Variant == (int)Unit.REPAIRER) { Bb ourUnitsOurSide = new Bb(mapWidth(), mapHeight()); ourUnitsOurSide.board = ourUnitsOurSide.board.Or(boardState.ourHalf.board); ourUnitsOurSide.board = ourUnitsOurSide.board.And(boardState.ourMovables.board); Func<Point, bool> healTarget = spot => { return ourUnitsOurSide.getValueFromSpot(spot.X, spot.Y); }; CIA.runMission(new Mission(MissionTypes.goTo, droids[i], healTarget, isWalkable, nope)); spotsOnOurSide.board = spotsOnOurSide.board.And(boardState.walkable.board); Func<Point, bool> runAway = spot => { return spotsOnOurSide.getValueFromSpot(spot.X, spot.Y); }; CIA.runMission(new Mission(MissionTypes.goTo, droids[i], runAway, isWalkable, isAttackable)); } else { Bb theirUnitsOurSide = new Bb(mapWidth(), mapHeight()); theirUnitsOurSide.board = theirUnitsOurSide.board.Or(boardState.ourHalf.board); theirUnitsOurSide.board = theirUnitsOurSide.board.And(boardState.theirMovables.board); Func<Point, bool> attackOurSide = spot => { return theirUnitsOurSide.getValueFromSpot(spot.X, spot.Y); }; CIA.runMission(new Mission(MissionTypes.goTo, droids[i], attackOurSide, isWalkable, isAttackable)); spotsOnOurSide.board = spotsOnOurSide.board.And(boardState.walkable.board); Func<Point, bool> runAway = spot => { return spotsOnOurSide.getValueFromSpot(spot.X, spot.Y); }; CIA.runMission(new Mission(MissionTypes.goTo, droids[i], runAway, isWalkable, isAttackable)); } } else { if (!(droids[i].Variant == (int)Unit.HACKER)) { if (droids[i].Variant == (int)Unit.REPAIRER) { Func<Point, bool> healTarget = spot => { return boardState.ourUnitsLowArmor.getValueFromSpot(spot.X, spot.Y); }; CIA.runMission(new Mission(MissionTypes.goTo, droids[i], healTarget, isWalkable, nope)); } else if (droids[i].Variant == (int)Unit.TERMINATOR) { if (!CIA.runMission(new Mission(MissionTypes.goTo, droids[i], isEnemyHangar, isWalkable, isAttackable))) { CIA.runMission(new Mission(MissionTypes.goTo, droids[i], isGoalHacker, isWalkable, isAttackable)); } } else { if (!CIA.runMission(new Mission(MissionTypes.goTo, droids[i], isGoalHacker, isWalkable, isAttackable))) { CIA.runMission(new Mission(MissionTypes.goTo, droids[i], isEnemyHangar, isWalkable, isAttackable)); } } } else { CIA.runMission(new Mission(MissionTypes.goTo, droids[i], isGoalHacker, isWalkable, isAttackable)); } } boardState.update(droids, tiles); } } // ATTACK again for (int i = 0; i < droids.Length; i++) { //if you have control of the droid if ((droids[i].Owner == playerID() && droids[i].HackedTurnsLeft <= 0) || (droids[i].Owner != playerID() && droids[i].HackedTurnsLeft > 0)) { //if there are any attacks left if (droids[i].AttacksLeft > 0) { if (droids[i].Variant == (int)Unit.REPAIRER) { Bb targets = new Bb(boardState.ourHangers.width, boardState.ourHangers.height); targets.board = targets.board.Or(boardState.ourHangers.board); targets.board = targets.board.Or(boardState.ourMovables.board); targets.board = targets.board.Or(boardState.ourImmovables.board); Func<Point, bool> target = spot => { return targets.getValueFromSpot(spot.X, spot.Y); }; CIA.runMission(new Mission(MissionTypes.attackInRange, droids[i], target, isWalkable, nope)); } else { Func<Point, bool> hackerTarget = spot => { return boardState.hackTargets.getValueFromSpot(spot.X, spot.Y); }; Func<Point, bool> target = spot => { return boardState.attackTargets.getValueFromSpot(spot.X, spot.Y); }; if (droids[i].Variant != (int)Unit.HACKER) { CIA.runMission(new Mission(MissionTypes.attackInRange, droids[i], target, isWalkable, nope)); } else { CIA.runMission(new Mission(MissionTypes.attackInRange, droids[i], hackerTarget, isWalkable, nope)); } } boardState.update(droids, tiles); } } } #region Old Spawn Code //for (int i = 0; i < mapHeight(); i++) //{ // //make sure you own enough scrap // if (players[playerID()].ScrapAmount >= modelVariants[(int)Unit.CLAW].Cost) // { // //make sure nothing is spawning there // if (getTile((mapWidth() - 1) * playerID(), i).TurnsUntilAssembled == 0) // { // //make sure there isn't a hangar there // if (!boardState.ourHangers.getValueFromSpot((mapWidth() - 1) * playerID(), i)) // { // //spawn the claw // players[playerID()].orbitalDrop((mapWidth() - 1) * playerID(), i, (int)Unit.CLAW); // } // } // } //} #endregion return true; }
private void DrawDeferredDecals_Normal(Camera cam) { int hqCount = 0; // Specular //var copy1id = Shader.PropertyToID("_CameraGBufferTexture1Copy"); //_bufferDeferred.GetTemporaryRT(copy1id, -1, -1, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32); // Normal var copy2id = Shader.PropertyToID("_CameraGBufferTexture2Copy"); _bufferDeferred.GetTemporaryRT(copy2id, -1, -1, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32); _bufferDeferred.Blit(BuiltinRenderTextureType.GBuffer2, copy2id); var allDecalEnum = _Decals.GetEnumerator(); while (allDecalEnum.MoveNext()) { Material material = allDecalEnum.Current.Key; HashSet <OzoneDecal> decals = allDecalEnum.Current.Value; int n = 0; var decalListEnum = decals.GetEnumerator(); while (decalListEnum.MoveNext()) { OzoneDecal decal = decalListEnum.Current; if (decal != null && decal.Dec.Shared.DrawNormal) { if (hqCount < HightQualityMaxCount) { // Create of copy of GBuffer1 (specular / smoothness) and GBuffer 2 (normal) //_bufferDeferred.Blit(BuiltinRenderTextureType.GBuffer1, copy1id); _bufferDeferred.Blit(BuiltinRenderTextureType.GBuffer2, copy2id); _bufferDeferred.SetRenderTarget(_normalRenderTarget, BuiltinRenderTextureType.CameraTarget); _directBlock.Clear(); _directBlock.SetFloat("_NearCutOffLOD", decal.NearCutOff); _directBlock.SetFloat("_CutOffLOD", decal.CutOff); _bufferDeferred.DrawMesh(_cubeMesh, decal.tr.localToWorldMatrix, material, 0, 1, _directBlock); hqCount++; } else { if (UseInstancing) { // Instanced drawing _matrices[n] = decal.tr.localToWorldMatrix; _CutOffLODValues[n] = decal.CutOff * CutoffMultiplier; _NearCutOffLODValues[n] = decal.NearCutOff; ++n; if (n == 1023) { //_bufferDeferred.Blit(BuiltinRenderTextureType.GBuffer1, copy1id); //_bufferDeferred.Blit(BuiltinRenderTextureType.GBuffer2, copy2id); _bufferDeferred.SetRenderTarget(_normalRenderTarget, BuiltinRenderTextureType.CameraTarget); _instancedBlock.Clear(); _instancedBlock.SetFloatArray("_NearCutOffLOD", _NearCutOffLODValues); _instancedBlock.SetFloatArray("_CutOffLOD", _CutOffLODValues); _bufferDeferred.DrawMeshInstanced(_cubeMesh, 0, material, 1, _matrices, n, _instancedBlock); n = 0; } } else { if (n == 0) { // Create of copy of GBuffer1 (specular / smoothness) and GBuffer 2 (normal) //_bufferDeferred.Blit(BuiltinRenderTextureType.GBuffer1, copy1id); _bufferDeferred.Blit(BuiltinRenderTextureType.GBuffer2, copy2id); } _bufferDeferred.SetRenderTarget(_normalRenderTarget, BuiltinRenderTextureType.CameraTarget); _directBlock.Clear(); _directBlock.SetFloat("_NearCutOffLOD", decal.NearCutOff * CutoffMultiplier); _directBlock.SetFloat("_CutOffLOD", decal.CutOff); _bufferDeferred.DrawMesh(_cubeMesh, decal.tr.localToWorldMatrix, material, 0, 1, _directBlock); ++n; } } } } #if UNITY_5_5_OR_NEWER if (UseInstancing && n > 0) { // Create of copy of GBuffer1 (specular / smoothness) and GBuffer 2 (normal) //_bufferDeferred.Blit(BuiltinRenderTextureType.GBuffer1, copy1id); //_bufferDeferred.Blit(BuiltinRenderTextureType.GBuffer2, copy2id); _bufferDeferred.SetRenderTarget(_normalRenderTarget, BuiltinRenderTextureType.CameraTarget); _instancedBlock.Clear(); _instancedBlock.SetFloatArray("_NearCutOffLOD", _NearCutOffLODValues); _instancedBlock.SetFloatArray("_CutOffLOD", _CutOffLODValues); _bufferDeferred.DrawMeshInstanced(_cubeMesh, 0, material, 1, _matrices, n, _instancedBlock); } #endif } }
private ObjectId GetFirst(HashSet<ObjectId> hashSet) { var enumerator = hashSet.GetEnumerator(); enumerator.MoveNext(); return enumerator.Current; }
private void DrawDeferredDecals_AlbedoInstanced(Camera cam) { _bufferDeferred.SetRenderTarget(_albedoRenderTarget, BuiltinRenderTextureType.CameraTarget); //var copy1id = Shader.PropertyToID("_CameraGBufferTexture0Copy"); //_bufferDeferred.GetTemporaryRT(copy1id, -1, -1, 0, FilterMode.Point, RenderTextureFormat.ARGB32); //_bufferDeferred.Blit(BuiltinRenderTextureType.GBuffer0, copy1id); //var copy2id = Shader.PropertyToID("_CameraGBufferTexture4Copy"); //_bufferDeferred.GetTemporaryRT(copy2id, -1, -1, 0, FilterMode.Point, RenderTextureFormat.ARGB2101010); var allDecalEnum = _Decals.GetEnumerator(); while (allDecalEnum.MoveNext()) { Material material = allDecalEnum.Current.Key; HashSet <OzoneDecal> decals = allDecalEnum.Current.Value; int decalCount = decals.Count; int n = 0; var decalListEnum = decals.GetEnumerator(); while (decalListEnum.MoveNext()) { OzoneDecal decal = decalListEnum.Current; if (decal != null && decal.Dec.Shared.DrawAlbedo) { if (UseInstancing && AllowAlbedoInstancing) { _matrices[n] = decal.tr.localToWorldMatrix; _NearCutOffLODValues[n] = decal.NearCutOff; _CutOffLODValues[n] = decal.CutOff * CutoffMultiplier; ++n; if (n == 1023) { //_bufferDeferred.Blit(BuiltinRenderTextureType.GBuffer0, copy1id); //_bufferDeferred.Blit(BuiltinRenderTextureType.CameraTarget, copy2id); //_bufferDeferred.SetRenderTarget(_albedoRenderTarget, BuiltinRenderTextureType.CameraTarget); _instancedBlock.Clear(); _instancedBlock.SetFloatArray("_NearCutOffLOD", _NearCutOffLODValues); _instancedBlock.SetFloatArray("_CutOffLOD", _CutOffLODValues); _bufferDeferred.DrawMeshInstanced(_cubeMesh, 0, material, 0, _matrices, n, _instancedBlock); n = 0; } } else { //if(n == 0) //_bufferDeferred.Blit(BuiltinRenderTextureType.CameraTarget, copy2id); _directBlock.Clear(); _directBlock.SetFloat("_NearCutOffLOD", decal.NearCutOff); _directBlock.SetFloat("_CutOffLOD", decal.CutOff); _bufferDeferred.DrawMesh(_cubeMesh, decal.tr.localToWorldMatrix, material, 0, 0, _directBlock); } } } if (UseInstancing && n > 0 && AllowAlbedoInstancing) { //_bufferDeferred.Blit(BuiltinRenderTextureType.CameraTarget, copy2id); //_bufferDeferred.SetRenderTarget(_albedoRenderTarget, BuiltinRenderTextureType.CameraTarget); _instancedBlock.Clear(); _instancedBlock.SetFloatArray("_NearCutOffLOD", _NearCutOffLODValues); _instancedBlock.SetFloatArray("_CutOffLOD", _CutOffLODValues); _bufferDeferred.DrawMeshInstanced(_cubeMesh, 0, material, 0, _matrices, n, _instancedBlock); } } }
public OpResult show_stats(string template, HashSet<int> results) { OpResult op_return = new OpResult(OpStatusCode.Ok); string template_list = ""; int pic_count = photo_media_play_list.count; if (results.Count > 0) pic_count = results.Count; string output_template = getTemplate(template + "+", DEFAULT_STATS_HEAD); output_template += getTemplate(template, DEFAULT_STATS_RESULT); output_template += getTemplate(template + "-", DEFAULT_STATS_FOOT); if (output_template.Length > 0) { output_template = file_includer(output_template); output_template = do_conditional_replace(output_template, "results_count", String.Format("{0}", pic_count)); output_template = do_conditional_replace(output_template, "tag_count", String.Format("{0}", kw_count)); output_template = do_conditional_replace(output_template, "start_date", String.Format("{0}", first_date.ToShortDateString())); output_template = do_conditional_replace(output_template, "end_date", String.Format("{0}", last_date.ToShortDateString())); output_template = do_conditional_replace(output_template, "filter_is_tagged", String.Format("{0}", param_is_tagged)); output_template = do_conditional_replace(output_template, "filter_not_tagged", String.Format("{0}", param_not_tagged)); output_template = do_conditional_replace(output_template, "filter_start_date", String.Format("{0}", param_start_date)); output_template = do_conditional_replace(output_template, "filter_end_date", String.Format("{0}", param_end_date)); if (output_template.IndexOf("%available_templates%") >= 0) { foreach (KeyValuePair<string, string> t in m_templates) { if (!t.Key.EndsWith("+") && !t.Key.EndsWith("-")) { if (template_list.Length > 0) template_list += ", "; template_list += t.Key; } } } /* get random image index in results if needed */ if (output_template.Contains("%random_id%")) { int random_index = new Random().Next(pic_count); string random = ""; if (results.Count > 0) { HashSet<int>.Enumerator results_enum = results.GetEnumerator(); for (int i = 0; i < random_index; i++) results_enum.MoveNext(); random = "" + results_enum.Current; } else random = "" + random_index; output_template = do_conditional_replace(output_template, "random_id", random); } output_template = do_conditional_replace(output_template, "available_templates", template_list); op_return.AppendFormat("{0}", output_template); } return op_return; }
public IEnumerator <T> GetEnumerator() { return(_hashSet.GetEnumerator()); }
public void TransientOrphanDelete() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Baz baz = new Baz(); var bars = new HashSet<BarProxy> { new Bar(), new Bar(), new Bar() }; baz.CascadingBars = bars; IList<Foo> foos = new List<Foo>(); foos.Add(new Foo()); foos.Add(new Foo()); baz.FooBag = foos; s.Save(baz); IEnumerator enumer = new JoinedEnumerable(new IEnumerable[] {foos, bars}).GetEnumerator(); while (enumer.MoveNext()) { FooComponent cmp = ((Foo) enumer.Current).Component; s.Delete(cmp.Glarch); cmp.Glarch = null; } t.Commit(); s.Close(); var enumerBar = bars.GetEnumerator(); enumerBar.MoveNext(); bars.Remove(enumerBar.Current); foos.RemoveAt(1); s = OpenSession(); t = s.BeginTransaction(); s.Update(baz); Assert.AreEqual(2, s.CreateQuery("from Bar bar").List().Count); Assert.AreEqual(3, s.CreateQuery("from Foo foo").List().Count); t.Commit(); s.Close(); foos.RemoveAt(0); s = OpenSession(); t = s.BeginTransaction(); s.Update(baz); enumerBar = bars.GetEnumerator(); enumerBar.MoveNext(); bars.Remove(enumerBar.Current); s.Delete(baz); s.Flush(); Assert.AreEqual(0, s.CreateQuery("from Foo foo").List().Count); t.Commit(); s.Close(); }
public IEnumerator <string> GetEnumerator() => _files.GetEnumerator();
void ModifiedBFS() { HashSet<Node> tempRoadSet = new HashSet<Node>(grid.RoadSet); Queue<Node> trafficQ = new Queue<Node>(); trafficQ.Enqueue(grid.ARoadNode); while (tempRoadSet.Count != 0) { while (trafficQ.Count > 0) { Node current = trafficQ.Dequeue(); if (tempRoadSet.Remove(current)) { foreach (Node n in grid.BFSGetRoadNeighbours(current)) // GetRoadNeighbors adds in/out => trafficWeight { if(tempRoadSet.Contains(n)) trafficQ.Enqueue(n); } } } // Stranded roads // There maybe a chance that we take the small set. Need to improve this more. while (tempRoadSet.Count > 0) { HashSet<Node>.Enumerator node = tempRoadSet.GetEnumerator(); if (node.MoveNext()) { grid.RoadSet.Remove(node.Current); // remove stranded road tempRoadSet.Remove(node.Current); node.Current.IsRoad = false; } } } }
/// <summary cref="IEnumerator.Reset"/> public void Reset() => enumerator = set.GetEnumerator();
private static void WriteStaticallyLinkedModuleRegistration(TextWriter w, HashSet<string> nativeModules, HashSet<string> nativeClasses) { w.WriteLine("struct ClassRegistrationContext;"); w.WriteLine("void InvokeRegisterStaticallyLinkedModuleClasses(ClassRegistrationContext& context)"); w.WriteLine("{"); if (nativeClasses == null) { w.WriteLine("\tvoid RegisterStaticallyLinkedModuleClasses(ClassRegistrationContext&);"); w.WriteLine("\tRegisterStaticallyLinkedModuleClasses(context);"); } else w.WriteLine("\t// Do nothing (we're in stripping mode)"); w.WriteLine("}"); w.WriteLine(); w.WriteLine("void RegisterStaticallyLinkedModulesGranular()"); w.WriteLine("{"); using (HashSet<string>.Enumerator enumerator = nativeModules.GetEnumerator()) { while (enumerator.MoveNext()) { string current = enumerator.Current; w.WriteLine("\tvoid RegisterModule_" + current + "();"); w.WriteLine("\tRegisterModule_" + current + "();"); w.WriteLine(); } } w.WriteLine("}"); }
public IEnumerator <RecipeIngredient> GetEnumerator() => _recipeIngredients.GetEnumerator();
/** Resume selectors on a set of targets. This can be useful for undoing a call to pauseAllSelectors. @since v2.0.0 */ public void resumeTargets(HashSet<System.Object> targetsToResume){ var enumerator = targetsToResume.GetEnumerator(); while (enumerator.MoveNext()) { var target = enumerator.Current; resumeTarget(target); } }
public override IEnumerator <ISQLTableColumn> GetEnumerator( ) { return(_Data?.GetEnumerator( )); }
/// <summary> /// /// </summary> /// <param name="dirs"></param> /// <param name="files"></param> /// <param name="exts"></param> /// <param name="saveFileListsFile">The complete file name (minus dot and extension) of result files</param> /// <returns></returns> public long ParseDirFilenamesAndExtension(HashSet<String> dirs, HashSet<String> files, HashSet<String> exts, string outputFileRoot) { Start(); hashDic.CreateHelpers(); long result = 0; // make it dual core friendly. cut by dirs... filenamesFoundInTest = 0; if (outputFileRoot != null) { foundNames = new Dictionary<string, bool>(); foreach (string filename in files) foundNames[filename] = false; } parseDirList = dirs.GetEnumerator(); threadList = new List<Thread>(); // launches as many threads as processors for (int i = 0; i < System.Environment.ProcessorCount && i < HashCreatorConfig.MaxOperationThread; i++) { Thread t = new Thread(new ParameterizedThreadStart(calc)); t.Start(new ThreadParam(dirs, files, exts, 0, dirs.Count / 2, outputFileRoot)); threadList.Add(t); } for (int i = 0; i < threadList.Count; i++) { threadList[i].Join(); } //if (dirs.Count > 10) //{ // Thread t1 = new Thread(new ParameterizedThreadStart(calc)); // Thread t2 = new Thread(new ParameterizedThreadStart(calc)); // t1.Start(new ThreadParam(dirs, files, exts, 0, dirs.Count / 2, outputFileRoot)); // t2.Start(new ThreadParam(dirs, files, exts, dirs.Count / 2, dirs.Count, outputFileRoot)); // t1.Join(); // t2.Join(); //} //else //{ // Thread t1 = new Thread(new ParameterizedThreadStart(calc)); // t1.Start(new ThreadParam(dirs, files, exts, 0, dirs.Count, outputFileRoot)); // t1.Join(); //} result = filenamesFoundInTest; filenamesFoundInTest = 0; // ok. The threads just exited. if (outputFileRoot != null && active) { FileStream ofsFound = new FileStream(outputFileRoot + "-found.txt", FileMode.Create); FileStream ofsNotFound = new FileStream(outputFileRoot + "-notfound.txt", FileMode.Create); StreamWriter swf = new StreamWriter(ofsFound); StreamWriter swnf = new StreamWriter(ofsNotFound); foreach (KeyValuePair<string, Boolean> file in foundNames) if (file.Value == true) swf.WriteLine(file.Key); else swnf.WriteLine(file.Key); swnf.Close(); swf.Close(); ofsFound.Close(); ofsNotFound.Close(); } return result; }
void FixAllTransforms() { var objects_iter = _objects.GetEnumerator(); while ( objects_iter.MoveNext() ) { objects_iter.Current.FixTransform(); } }
public IEnumerator <int> GetEnumerator() { return(Selected.GetEnumerator()); }
/// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> /// public virtual IEnumerator <T> GetEnumerator() { return(set.GetEnumerator()); }
/// <summary> /// Reads events into a linked list. The predicates associated with each event are /// counted and any which occur at least N times (cutoff) are added to the /// <paramref name="predicatesInOut"/> map along with a unique integer index. /// </summary> /// <param name="eventStore">A writer to which the events are written to for later processing.</param> /// <param name="predicatesInOut">The predicates in out.</param> /// <returns>The number of events readed from the event stream.</returns> private int ComputeEventCounts(StreamWriter eventStore, Dictionary<string, int> predicatesInOut) { int eventCount = 0; var counter = new Dictionary<string, int>(); //var predicateSet = new Java.HashSet<string>(); var predicateSet = new HashSet<string>(); Event ev; while ((ev = EventStream.Read()) != null) { if (Monitor != null && Monitor.Token.CanBeCanceled) Monitor.Token.ThrowIfCancellationRequested(); eventCount++; eventStore.Write(FileEventStream.ToLine(ev)); Update(ev.Context, predicateSet, counter, Cutoff); } predCounts = new int[predicateSet.Count]; int index = 0; for (var e = predicateSet.GetEnumerator(); e.MoveNext(); index++) { if (e.Current != null) { predCounts[index] = counter[e.Current]; predicatesInOut.Add(e.Current, index); } } eventStore.Flush(); eventStore.Close(); return eventCount; }
/** * Allowed end-points /activities/{userId}/{groupId}/{optionalActvityId}+ * /activities/{userId}+/{groupId} * * examples: /activities/john.doe/@self/1 /activities/john.doe/@self * /activities/john.doe,jane.doe/@friends */ protected override object handleGet(RequestItem request) { request.applyUrlTemplate(ACTIVITY_ID_PATH); HashSet<UserId> userIds = request.getUsers(); HashSet<String> optionalActivityIds = new HashSet<string>(request.getListParameter("activityId")); // Preconditions Preconditions<UserId>.requireNotEmpty(userIds, "No userId specified"); if (userIds.Count > 1 && optionalActivityIds.Count != 0) { throw new ArgumentException("Cannot fetch same activityIds for multiple userIds"); } CollectionOptions options = new CollectionOptions(); options.setSortBy(request.getSortBy()); options.setSortOrder(request.getSortOrder()); options.setFilter(request.getFilterBy()); options.setFilterOperation(request.getFilterOperation()); options.setFilterValue(request.getFilterValue()); options.setFirst(request.getStartIndex()); options.setMax(request.getCount() ?? RequestItem.DEFAULT_COUNT); if (optionalActivityIds.Count != 0) { if (optionalActivityIds.Count == 1) { IEnumerator<UserId> iuserid = userIds.GetEnumerator(); iuserid.MoveNext(); IEnumerator<string> iactivity = optionalActivityIds.GetEnumerator(); iactivity.MoveNext(); return service.getActivity(iuserid.Current, request.getGroup(), request.getAppId(), options, request.getFields(), iactivity.Current, request.getToken()); } else { IEnumerator<UserId> iuserid = userIds.GetEnumerator(); iuserid.MoveNext(); return service.getActivities(iuserid.Current, request.getGroup(), request.getAppId(), request.getFields(), optionalActivityIds, request.getToken()); } } return service.getActivities(userIds, request.getGroup(), request.getAppId(), options, request.getFields(), request.getToken()); }
/// <summary> /// Reads the events from <paramref name="eventStream"/> into a <see cref="Collections.Generic.LinkedList"/>. /// The predicates associated with each event are counted and any which occur at least <paramref name="cutoff"/> /// times are added to the <paramref name="predicateIndex"/> dictionary along /// with an unique integer index. /// </summary> /// <param name="eventStream">The event stream.</param> /// <param name="predicateIndex">Index of the predicate.</param> /// <param name="cutoff">The cutoff.</param> /// <returns>A <see cref="Collections.Generic.LinkedList"/> of events.</returns> private LinkedList<Event> ComputeEventCounts(IEventStream eventStream, Dictionary<string, int> predicateIndex, int cutoff) { LinkedList<Event> events = new LinkedList<Event>(); HashSet<string> predicatesSet = new HashSet<string>(); IDictionary<string, int> counter = new Dictionary<string, int>(); while (eventStream.HasNext()) { Event next = eventStream.Next(); events.AddLast(next); Update(next.Context, predicatesSet, counter, cutoff); } PredicateCounts = new int[predicatesSet.Count]; int index = 0; HashSet<string>.Enumerator enumerator = predicatesSet.GetEnumerator(); while (enumerator.MoveNext()) { string predicate = enumerator.Current; PredicateCounts[index] = counter[predicate]; predicateIndex[predicate] = index; } return events; }
public IEnumerator <Entity> GetEnumerator() => entities.GetEnumerator();
public IEnumerator <ReferencePartialSpanContext> GetEnumerator() { return(References?.GetEnumerator()); }
public HashSet<List<Tuple<long, long>>> GetShortestPath(HashSet<Node> myIntersectNodes) { foundLeft = foundRight = false; //set maximum part lengths _MaxPartLengthLeft = _MaxPartLengthRight = (_MaxPathLength / 2); //if the max path length is odd add one if (_MaxPathLength % 2 != 0) { _MaxPartLengthLeft += 1; _MaxPartLengthRight += 1; } var enumerator = myIntersectNodes.GetEnumerator(); while (enumerator.MoveNext() && _Paths.Count == 0) { //calculate parts from intersect node to end getShortestPathDownwards(enumerator.Current); ///recalculate the max part length... ///it could happen that the intersect node is not in the middle, ///so the max part length left could be less than calculated, ///if this happens the right part length must be adapted _MaxPartLengthRight = _MaxPathLength - _MaxPartLengthLeft; //check if max path length is odd if (_MaxPathLength % 2 != 0) { _MaxPartLengthRight += 1; } //calculate parts from intersect node to start getShortestPathUpwards(enumerator.Current); //calculate full path if (_PathsLeft.Count > 0 && _PathsRight.Count > 0) { //forach part from left foreach (var leftPath in _PathsLeft) { var first = leftPath.First(); //foreach part from right foreach (var rightPath in _PathsRight) //if there starts are the same (the intersect node) if (rightPath.First().Equals(first) && ((rightPath.Count + leftPath.Count - 1) <= _MaxPathLength)) { var temp = new List<Tuple<long, long>>(rightPath); temp.Reverse(); leftPath.RemoveAt(0); temp.InsertRange(temp.Count, leftPath); _Paths.Add(temp); return _Paths; } } } } return null; }