void InitCellResults() { if (m_CellArray == null || m_CellArray.Length <= 0 || m_BoundsArray == null || m_BoundsArray.Length <= 0) { return; } int cnt = Mathf.CeilToInt(m_GlobalNodeId / 8.0f); m_CellsResult = new PVSCell[m_CellArray.Length]; for (int i = 0; i < m_CellsResult.Length; ++i) { var pt = m_CellArray[i]; if (!m_CellIngoreArray.Contains(i) && pt.magnitude > Vector3.kEpsilon) { PVSCell cell = new PVSCell(); m_CellsResult[i] = cell; cell.visibleBits = new byte[cnt]; cell.position = pt; } else { m_CellsResult[i] = null; } } }
public List <S> Find_path(S start, S end) { System.Collections.Generic.HashSet <S> closedSet = new System.Collections.Generic.HashSet <S>(); IntervalHeap <Node> openSet = new IntervalHeap <Node>(); Node curr = new Node(start, null); while (!curr.state.Equals(end)) { if (!closedSet.Contains(curr.state)) { foreach (S state in curr.state.AvailableMoves()) { if (closedSet.Contains(state)) { continue; } openSet.Add(new Node(state, curr)); } closedSet.Add(curr.state); } curr = openSet.DeleteMin(); } Stack <S> stack = new Stack <S>(); while (curr != null) { stack.Push(curr.state); curr = curr.parent; } return(stack.ToList <S>()); }
public void add_bad_mapping(string p_key) { if (!FoundPaths.Contains(p_key)) { FoundPaths.Add(p_key); BadMappingLog.WriteLine(p_key); } }
//! Calculate path. public State RunOnce() { // While we got something while (openSet.Count > 0) { K current = openSetPriority.Pop().tile; openSet.Remove(current); // Got the goal if (current.Equals(end_)) { result = ReconstructPath(cameFrom, end_).ToArray(); return(State.DONE); } closedSet.Add(current); // Get tile from current foreach (K neigh in GetNeigbours(current)) { float tentative_g = g_score[current] + Distance(current, neigh); // Got some tile in closed set if (closedSet.Contains(neigh)) { // If actual g(x) is bigger, no need to examine if (tentative_g >= g_score[neigh]) { continue; } } // New tile to examine or g(x) has got better if (!openSet.Contains(neigh) || tentative_g < g_score[neigh]) { cameFrom[neigh] = current; g_score[neigh] = tentative_g; f_score[neigh] = tentative_g + Heurestic(neigh, end_); if (!openSet.Contains(neigh)) { openSet.Add(neigh); openSetPriority.Push(new NodeTag(f_score[neigh], neigh)); } } } return(State.WAIT); } return(State.FAIL); }
public static string HexEscape(this string text, params char[] anyCharOf) { if (string.IsNullOrEmpty(text)) { return(text); } if (anyCharOf == null || anyCharOf.Length == 0) { return(text); } var encodeCharMap = new System.Collections.Generic.HashSet <char>(anyCharOf); var sb = new StringBuilder(); var textLength = text.Length; for (var i = 0; i < textLength; i++) { var c = text[i]; if (encodeCharMap.Contains(c)) { sb.Append('%' + ((int)c).ToString("x")); } else { sb.Append(c); } } return(sb.ToString()); }
public Stack <Point> Run() { while (!Open.IsEmpty) { var node = Open.DeleteMin(); // node.State.print(); if (Game.IsFinishState(node.State)) { var stack = new Stack <Point>(); while (node.Parent != null) { stack.Push(node.Move); node = node.Parent; } return(stack); } foreach (var move in ProductionSystem) { var newNode = new Node(node, Game.MakeMove(node.State, move), move); if (!Closed.Contains(newNode)) { Open.Add(newNode); } } Closed.Add(node); } System.Console.WriteLine("No solution found."); return(null); }
public static void Write(TextWriter writer, IEnumerable<Dictionary<string, string>> records) { if (records == null) return; //AOT var allKeys = new System.Collections.Generic.HashSet<string>(); var cachedRecords = new List<IDictionary<string, string>>(); foreach (var record in records) { foreach (var key in record.Keys) { if (!allKeys.Contains(key)) { allKeys.Add(key); } } cachedRecords.Add(record); } var headers = allKeys.OrderBy(key => key).ToList(); if (!CsvConfig<Dictionary<string, string>>.OmitHeaders) { WriteRow(writer, headers); } foreach (var cachedRecord in cachedRecords) { var fullRecord = new List<string>(); foreach (var header in headers) { fullRecord.Add(cachedRecord.ContainsKey(header) ? cachedRecord[header] : null); } WriteRow(writer, fullRecord); } }
public System.Collections.Generic.List <string> GetMissingPlugins(System.Collections.Generic.HashSet <AkPluginInfo> usedPlugins) { var pluginList = new System.Collections.Generic.List <string>(); if (usedPlugins == null) { return(pluginList); } foreach (var plugin in usedPlugins) { if (string.IsNullOrEmpty(plugin.StaticLibName)) { continue; } string includeFilename = plugin.StaticLibName + "Factory.h"; if (!FactoriesHeaderFilenames.Contains(includeFilename)) { pluginList.Add(plugin.StaticLibName); } } return(pluginList); }
public static void Write(TextWriter writer, IEnumerable <Dictionary <string, string> > records) { if (records == null) { return; //AOT } var allKeys = new System.Collections.Generic.HashSet <string>(); var cachedRecords = new List <IDictionary <string, string> >(); foreach (var record in records) { foreach (var key in record.Keys) { if (!allKeys.Contains(key)) { allKeys.Add(key); } } cachedRecords.Add(record); } var headers = allKeys.OrderBy(key => key).ToList(); if (!CsvConfig <Dictionary <string, string> > .OmitHeaders) { WriteRow(writer, headers); } foreach (var cachedRecord in cachedRecords) { var fullRecord = headers.ConvertAll(header => cachedRecord.ContainsKey(header) ? cachedRecord[header] : null); WriteRow(writer, fullRecord); } }
public static void LoadXmlDocumentation(Assembly assembly) { string xmlFilePath; if (LoadedAssemblies.Contains(assembly)) { return; } var directoryPath = assembly.GetDirectoryPath(); if (!string.IsNullOrEmpty(directoryPath)) { xmlFilePath = Path.Combine(directoryPath, assembly.GetName().Name + ".xml"); } else { xmlFilePath = assembly.GetName().Name + ".xml"; } if (File.Exists(xmlFilePath)) { using var streamReader = new StreamReader(xmlFilePath); LoadXmlDocumentation(streamReader); } // currently marking assembly as loaded even if the XML file was not found // may want to adjust in future, but I think this is good for now LoadedAssemblies.Add(assembly); }
public void Drop(ICollection collection) { if (collection is IInternalCollection collectionToRemove && _collections.Contains(collectionToRemove)) { using (var transaction = _connection.BeginTransaction()) { var tableName = collectionToRemove.TableName; using (var command = _connection.CreateCommand()) { command.CommandText = string.Format("DROP TABLE {0}", tableName); command.ExecuteNonQuery(); } using (var command = _connection.CreateCommand()) { command.CommandText = string.Format("DELETE FROM {0} WHERE tableName = @tableName", TableName); command.Parameters.AddWithValue("@tableName", tableName); command.ExecuteNonQuery(); } transaction.Commit(); } _collectionsByName.Remove(collectionToRemove.Name); _collections.Remove(collectionToRemove); collectionToRemove.MarkAsDropped(); } }
static void fs_Changed(object sender, FileSystemEventArgs e) { FileInfo f = new FileInfo(e.FullPath); if (WatchedFiles.Contains(f.Name)) { try { string current_hash = GetHash(f.FullName); string key_name = GetKeyName(f); if (!WatchDictionary.ContainsKey(key_name)) { WatchDictionary.Add(key_name, current_hash); } if (current_hash != WatchDictionary[key_name]) { var worker = new MyTaskWorkerDelegate(MyTaskWorker); worker.BeginInvoke(key_name, current_hash, null, null); } } catch (System.Exception ex) { System.Console.Write("FileChanged exception:\n {0}", ex); } } }
public ListNode DetectCycle(ListNode head) { /* Dictionary<ListNode, int> tmp = new Dictionary<ListNode, int> (); * int pos = -1; * while (head != null) { * pos++; * if (tmp.ContainsKey (head)) { * return head; * } * tmp.Add (head, pos); * head = head.next; * } * return null; */ HashSet <ListNode> nodeset = new System.Collections.Generic.HashSet <ListNode> (); while (head != null) { if (nodeset.Contains(head)) { return(head); } nodeset.Add(head); head = head.next; } return(null); }
public MvcHtmlString AvailableItems(IDictionary <string, object> htmlAttributes = null) { List <ExtendedSelectListItem> NotSelected = new List <ExtendedSelectListItem>(); foreach (ExtendedSelectListItem sel in allItems) { if (!valuesSet.Contains(sel.Value)) { NotSelected.Add(sel); } } if (htmlAttributes == null) { htmlAttributes = new Dictionary <string, object>(); } htmlAttributes["data-elementispart"] = "true"; return(MvcHtmlString.Create ( CurrHtmlHelper.DropDownbase <TModel, TChoiceItem, TDisplay, TValue>( BasicHtmlHelper.AddField(Prefix, "$.PackedValue") + DualSelect_SelectAvial, new List <TValue>() as IEnumerable <TValue>, NotSelected, htmlAttributes, true, false).ToString() )); }
private static IEnumerable <ITweekAddon> GetAddons(IConfiguration configuration) { if (mAddonsCache != null) { return(mAddonsCache); } var selectedAddons = new System.Collections.Generic.HashSet <string>( configuration.GetSection("Addons") .GetChildren() .Select(x => Assembly.CreateQualifiedName(x["AssemblyName"], x["ClassName"])) ); var dependencies = DependencyContext.Default.RuntimeLibraries; var assemblies = dependencies .SelectMany(library => library.GetDefaultAssemblyNames(DependencyContext.Default).Select(Assembly.Load)); var addonTypes = assemblies.Bind(x => x.GetTypes()) .Filter(x => x != typeof(ITweekAddon) && typeof(ITweekAddon).IsAssignableFrom(x)); mAddonsCache = addonTypes.Filter(type => selectedAddons.Contains(type.AssemblyQualifiedNameWithoutVersion())) .Map(t => (ITweekAddon)Activator.CreateInstance(t)); return(mAddonsCache); }
/// <summary> /// Do DFS to find all unique edges. /// </summary> private void dfs(WeightedGraphVertex <T, TW> currentVertex, System.Collections.Generic.HashSet <T> visitedVertices, Dictionary <T, System.Collections.Generic.HashSet <T> > visitedEdges, List <MSTEdge <T, TW> > result) { if (!visitedVertices.Contains(currentVertex.Value)) { visitedVertices.Add(currentVertex.Value); foreach (var edge in currentVertex.Edges) { if (!visitedEdges.ContainsKey(currentVertex.Value) || !visitedEdges[currentVertex.Value].Contains(edge.Key.Value)) { result.Add(new MSTEdge <T, TW>(currentVertex.Value, edge.Key.Value, edge.Value)); //update visited edge if (!visitedEdges.ContainsKey(currentVertex.Value)) { visitedEdges.Add(currentVertex.Value, new HashSet <T>()); } visitedEdges[currentVertex.Value].Add(edge.Key.Value); //update visited back edge if (!visitedEdges.ContainsKey(edge.Key.Value)) { visitedEdges.Add(edge.Key.Value, new HashSet <T>()); } visitedEdges[edge.Key.Value].Add(currentVertex.Value); } dfs(edge.Key, visitedVertices, visitedEdges, result); } } }
/// <summary> /// Do DFS to pick smallest weight neighbour edges /// of current spanning tree one by one /// </summary> /// <param name="graph"></param> /// <param name="currentVertex"></param> /// <param name="spanTreeVertices"></param> /// <param name="spanTreeNeighbours"> Use Fibornacci Min Heap to pick smallest edge neighbour </param> /// <param name="spanTreeEdges">result MST edges</param> private void dfs(WeightedGraph <T, W> graph, WeightedGraphVertex <T, W> currentVertex, BMinHeap <MSTEdge <T, W> > spanTreeNeighbours, System.Collections.Generic.HashSet <T> spanTreeVertices, List <MSTEdge <T, W> > spanTreeEdges) { while (true) { //add all edges to Fibornacci Heap //So that we can pick the min edge in next step foreach (var edge in currentVertex.Edges) { spanTreeNeighbours.Insert(new MSTEdge <T, W>(currentVertex.Value, edge.Key.Value, edge.Value)); } //pick min edge var minNeighbourEdge = spanTreeNeighbours.ExtractMin(); //skip edges already in MST while (spanTreeVertices.Contains(minNeighbourEdge.Source) && spanTreeVertices.Contains(minNeighbourEdge.Destination)) { minNeighbourEdge = spanTreeNeighbours.ExtractMin(); //if no more neighbours to explore //time to end exploring if (spanTreeNeighbours.Count == 0) { return; } } //keep track of visited vertices //do not duplicate vertex if (!spanTreeVertices.Contains(minNeighbourEdge.Source)) { spanTreeVertices.Add(minNeighbourEdge.Source); } //Destination vertex will never be a duplicate //since this is an unexplored Vertex spanTreeVertices.Add(minNeighbourEdge.Destination); //add edge to result spanTreeEdges.Add(minNeighbourEdge); //now explore the destination vertex var graph1 = graph; currentVertex = graph1.Vertices[minNeighbourEdge.Destination]; } }
public static void CollectMapping(Activity rootActivity1, Activity rootActivity2, Dictionary<object, SourceLocation> mapping, string path) { Activity activity = (rootActivity1.RootActivity != null) ? rootActivity1.RootActivity : rootActivity1; if (!activity.IsRuntimeReady) { IList<ValidationError> validationErrors = null; ActivityUtilities.CacheRootMetadata(activity, new ActivityLocationReferenceEnvironment(), ProcessActivityTreeOptions.ValidationOptions, null, ref validationErrors); } Activity activity2 = (rootActivity2.RootActivity != null) ? rootActivity2.RootActivity : rootActivity2; if (!activity2.IsRuntimeReady) { IList<ValidationError> list2 = null; ActivityUtilities.CacheRootMetadata(activity2, new ActivityLocationReferenceEnvironment(), ProcessActivityTreeOptions.ValidationOptions, null, ref list2); } Queue<KeyValuePair<Activity, Activity>> queue = new Queue<KeyValuePair<Activity, Activity>>(); queue.Enqueue(new KeyValuePair<Activity, Activity>(rootActivity1, rootActivity2)); System.Collections.Generic.HashSet<Activity> set = new System.Collections.Generic.HashSet<Activity>(); while (queue.Count > 0) { SourceLocation location; KeyValuePair<Activity, Activity> pair = queue.Dequeue(); Activity key = pair.Key; Activity activity4 = pair.Value; set.Add(key); if (TryGetSourceLocation(activity4, path, out location)) { mapping.Add(key, location); } else if (!(activity4 is IExpressionContainer) && !(activity4 is IValueSerializableExpression)) { Debugger.Log(2, "Workflow", "WorkflowDebugger: Does not have corresponding Xaml node for: " + activity4.DisplayName + "\n"); } if ((!(key is IExpressionContainer) && !(activity4 is IExpressionContainer)) && (!(key is IValueSerializableExpression) && !(activity4 is IValueSerializableExpression))) { IEnumerator<Activity> enumerator = WorkflowInspectionServices.GetActivities(key).GetEnumerator(); IEnumerator<Activity> enumerator2 = WorkflowInspectionServices.GetActivities(activity4).GetEnumerator(); bool flag = enumerator.MoveNext(); bool flag2 = enumerator2.MoveNext(); while (flag && flag2) { if (!set.Contains(enumerator.Current)) { if (enumerator.Current.GetType() != enumerator2.Current.GetType()) { Debugger.Log(2, "Workflow", "Unmatched type: " + enumerator.Current.GetType().FullName + " vs " + enumerator2.Current.GetType().FullName + "\n"); } queue.Enqueue(new KeyValuePair<Activity, Activity>(enumerator.Current, enumerator2.Current)); } flag = enumerator.MoveNext(); flag2 = enumerator2.MoveNext(); } if (flag || flag2) { Debugger.Log(2, "Workflow", "Unmatched number of children\n"); } } } }
public virtual void DoDelete(Bar db, System.Collections.Generic.HashSet <IDelRecord> deletionList) { if (_company != null) { if (!deletionList.Contains(_company)) { _company._departments.Remove(this); } } foreach (Employee _that_ in _employees) { if (!deletionList.Contains(_that_)) { _that_._departments.Remove(this); } } db._department_Title.Remove(this); db._department_pk.Remove(_id); }
public void IssueAction(string ActionType, float ActionValue = 0.0f) { if (!knownActions.Contains(ActionType)) { return; } IssuedAction = ActionType; IssuedActionValue = ActionValue; }
public virtual void DoDelete(Bar db, System.Collections.Generic.HashSet <IDelRecord> deletionList) { if (_owner != null) { if (!deletionList.Contains(_owner)) { _owner._items.Remove(this); } } db._item_pk.Remove(_id); }
static void AddCandidate(State currentBest, Point newPositionOf0, System.Collections.Generic.HashSet <string> visitedStates, IPriorityQueue <State> candidates) { State newState = Swap(currentBest, newPositionOf0); string newStateAsString = newState.ToString(); if (!visitedStates.Contains(newStateAsString)) { candidates.Add(newState); visitedStates.Add(newStateAsString); } }
public virtual void DoDelete(Bar db, System.Collections.Generic.HashSet <IDelRecord> deletionList) { if (_marketing != null) { if (!deletionList.Contains(_marketing)) { _marketing._refCount--; } } db._company_pk.Remove(_id); }
public virtual void EnsureCanDelete(System.Collections.Generic.HashSet <IDelRecord> deletionList) { foreach (Employee _that_ in _employees) { if (!deletionList.Contains(_that_)) { throw new ArgumentException(String.Format( "'Department' with id '{0}' is referenced by other record.", _id)); } } }
public override void PreDeleteOuter(System.Collections.Generic.HashSet <IDelRecord> deletionList, bool master) { if (deletionList.Contains(this)) { return; } else { deletionList.Add(this); } PreDeleteInner(deletionList); }
public virtual void DoDelete(Bar db, System.Collections.Generic.HashSet <IDelRecord> deletionList) { if (_department != null) { if (!deletionList.Contains(_department)) { _department._employees.Remove(this); } } db._employee_Department_Name.Remove(this); db._employee_pk.Remove(_id); }
/// <summary> /// Called once the move operation has been initialized /// </summary> /// <remarks> /// Calculates which components stay fixed and which nodes will be moved by the user. /// </remarks> private void OnMoveInitialized(object sender, EventArgs eventArgs) { if (layout != null) { CopiedLayoutGraph copy = this.copiedLayoutGraph; var componentNumber = copy.CreateNodeMap(); GraphConnectivity.ConnectedComponents(copy, componentNumber); System.Collections.Generic.HashSet <int> movedComponents = new System.Collections.Generic.HashSet <int>(); System.Collections.Generic.HashSet <Node> selectedNodes = new System.Collections.Generic.HashSet <Node>(); foreach (INode node in movedNodes) { Node copiedNode = copy.GetCopiedNode(node); if (copiedNode != null) { // remember that we nailed down this node selectedNodes.Add(copiedNode); // remember that we are moving this component movedComponents.Add(componentNumber.GetInt(copiedNode)); //Update the position of the node in the CLG to match the one in the IGraph layout.SetCenter(copiedNode, node.Layout.X + node.Layout.Width * 0.5, node.Layout.Y + node.Layout.Height * 0.5); //Actually, the node itself is fixed at the start of a drag gesture layout.SetInertia(copiedNode, 1.0); //Increasing has the effect that the layout will consider this node as not completely placed... // In this case, the node itself is fixed, but it's neighbors will wake up IncreaseHeat(copiedNode, layout, 0.5); } } // there are components that won't be moved - nail the nodes down so that they don't spread apart infinitely foreach (var copiedNode in copy.Nodes) { if (!movedComponents.Contains(componentNumber.GetInt(copiedNode))) { layout.SetInertia(copiedNode, 1); } else { if (!selectedNodes.Contains(copiedNode)) { // make it float freely layout.SetInertia(copiedNode, 0); } } } // dispose the map copy.DisposeNodeMap(componentNumber); //Notify the layout algorithm that there is new work to do... layout.WakeUp(); } }
/// <summary> /// 返回未能成功下载的块标记 /// </summary> List <int> DownloadData(byte[] hash, int[] indexs, IPAddress iP) { var failStat = $"target: {iP} don't have this block"; List <P2PMessage> result; StringBuilder @string = new StringBuilder(); foreach (var i in indexs) { @string.Append($"{i} "); } _logger.Info($"Now Download {@string} from {iP}"); using (var transMan = new DownloadTransManager(iP)) { transMan.GetData(hash, indexs); result = transMan.GetReply(indexs.Length); if (result.Count == 0) { transMan.SendCloseMessage(); // 如果进入了这里,说明请求的IP里,请求的块一个也没有 return(new List <int>(indexs)); } HashSet <int> set = new System.Collections.Generic.HashSet <int>(indexs); foreach (var i in result) { _logger.Info($"Get {i.type} from {iP}"); if (i.type == P2PMessageType.DATA) { var data = (DataMessage)i; var index = data.p2PDatas.block.index; if (set.Contains(index)) { transMan.SendOkMessage(hash, data.p2PDatas.block.index); try { fmanager.OnBlockDownloadSuccess(hash, index, data.p2PDatas.data); set.Remove(index); } catch (FailToDownloadException) { } } } else if (i.type == P2PMessageType.ERROR) { var index = ((ErrorMessage)i).Block.index; fmanager.SetRemoteBlockPresentStat(hash, iP, index, false); } } transMan.SendCloseMessage(); return(set.ToList()); } }
private static List <DelegateArgument> RemoveHiddenDelegateArguments(System.Collections.Generic.HashSet <string> existingNames, IEnumerable <DelegateArgument> ancestorDelegateArguments) { List <DelegateArgument> list = new List <DelegateArgument>(); foreach (DelegateArgument argument in ancestorDelegateArguments) { if (((argument != null) && (argument.Name != null)) && !existingNames.Contains(argument.Name)) { list.Add(argument); existingNames.Add(argument.Name); } } return(list); }
private static List <RuntimeArgument> RemoveHiddenArguments(System.Collections.Generic.HashSet <string> existingNames, IList <RuntimeArgument> ancestorArguments) { List <RuntimeArgument> list = new List <RuntimeArgument>(ancestorArguments.Count); foreach (RuntimeArgument argument in ancestorArguments) { if (!existingNames.Contains(argument.Name)) { list.Add(argument); existingNames.Add(argument.Name); } } return(list); }
private T[] BuildCleanedArray <T>(T[] input, System.Collections.Generic.HashSet <int> indicesToSkip) { var toReturn = new List <T>(); for (int i = 0; i < input.Length; i++) { if (!indicesToSkip.Contains(i)) { toReturn.Add(input[i]); } } return(toReturn.ToArray()); }
public char FirstRepeatChr(string s) { HashSet <char> listCh = new System.Collections.Generic.HashSet <char>(); foreach (char c in s) { if (listCh.Contains(c)) { System.Console.WriteLine(c); return(c); } listCh.Add(c); } return(char.MinValue); }
private static void setupAsterismGrabbers() { GameObject starRoot = new GameObject("StarRoot"); for(int i=0; i < AsterismData.Length; i++) { Asterism asterism = AsterismData[i]; Vector3 centroid = averageStarLocations(asterism.HD_ids); GameObject newRoot = new GameObject(); GameObject rest = new GameObject(); GameObject jewelcase = new GameObject(); newRoot.name = asterism.name + "_root"; newRoot.transform.position = centroid; newRoot.transform.rotation = Quaternion.identity; rest.name = "rest"; rest.transform.parent = newRoot.transform; rest.transform.localPosition = Vector3.zero; rest.transform.localRotation = Quaternion.identity; rest.transform.localScale = new Vector3(1.0f,1.0f,1.0f); jewelcase.name = "jewelcase"; jewelcase.transform.parent = newRoot.transform; jewelcase.transform.localPosition = Vector3.zero; jewelcase.transform.localRotation = Quaternion.identity; jewelcase.transform.localScale = new Vector3(1.0f,1.0f,1.0f); PullToHold pullscript = jewelcase.AddComponent<PullToHold>(); pullscript.asterismKey = i; pullscript.rest = rest.transform; pullscript.maxSpeed = 20.0f; newRoot.transform.parent = starRoot.transform; asterism.root = newRoot; asterism.rest = rest; asterism.mover = jewelcase; System.Collections.Generic.HashSet<uint> used = new System.Collections.Generic.HashSet<uint>(); GameObject constellationLabel = GameObject.Instantiate(Stars.StarUpdater.Instance.ConstellationLabelPrototype) as GameObject; constellationLabel.SetActive(true); ConstellationLabel labelBehavior = constellationLabel.GetComponent<ConstellationLabel>(); if ( asterism.root != null ) { labelBehavior.transform.parent = asterism.root.transform; } labelBehavior.Label = asterism.name; labelBehavior.transform.localPosition = (asterism.root.transform.position.normalized * 500.0f); asterism.label = labelBehavior; labelBehavior.LabelComp.color = new Color(1.0f, 1.0f, 1.0f, Stars.StarUpdater.Instance.LabelOpacity * 0.8f); Stars.StarUpdater.Instance.m_constellationLabels.Add(labelBehavior); foreach(uint hdId in asterism.HD_ids) { if ( !Stars.StarParser.HD_idToIndex.ContainsKey(hdId) ) { continue; } int index = Stars.StarParser.HD_idToIndex[hdId]; Stars.StarData star = Stars.StarParser.Instance.Stars[index]; star.AsterismIndex = i; Stars.StarParser.Instance.Stars[index] = star; if ( star.GameObjectRepresentation != null ) { star.GameObjectRepresentation.name = hdId.ToString(); star.GameObjectRepresentation.transform.parent = jewelcase.transform; if (star.Label != ""){ if(used.Contains(star.HD_id)) { continue; } Stars.StarUpdater.Instance.GenerateStarLabel(star, star.GameObjectRepresentation.transform); used.Add(star.HD_id); } } } AsterismData[i] = asterism; } }
//uPrime is the child of u //the result of the join is returned. private PrimeNode NodeJoin(SplitTree ST, Node u, Node uPrime) { MarkerVertex qPrime = uPrime.rootMarkerVertex; MarkerVertex q = qPrime.opposite as MarkerVertex; PrimeNode ret = null; List<GLTVertex> uPrimeChildren = new List<GLTVertex>(); if (u is DegenerateNode) { ret = (u as DegenerateNode).ConvertToPrime(); //u.parentLink = ret; //u.unionFind_parent = null; u.active = true; } else ret = u as PrimeNode; var representative = ret.childSetRepresentative; if (uPrime is DegenerateNode && (uPrime as DegenerateNode).isStar && qPrime != (uPrime as DegenerateNode).center)//qPrime has degree 1, not center. { var center = (uPrime as DegenerateNode).center; var centerOpposite = center.GetOppositeGLTVertex(); //Algorithm 8 says q now represents the center of u', so we have to update the center's opposite.. if (centerOpposite is Node) { (centerOpposite as Node).rootMarkerVertex.opposite = q; } else (centerOpposite as Leaf).opposite = q; uPrimeChildren.Add(centerOpposite); //And also copy the center's perfect state, and opposite. q.perfect = center.perfect; q.opposite = center.opposite; (uPrime as DegenerateNode).ForEachMarkerVertex((v) => { if (v != center && v != qPrime) { ret.AddMarkerVertex(v, new HashSet<MarkerVertex> { q }); uPrimeChildren.Add(v.GetOppositeGLTVertex()); } return IterationFlag.Continue; }); } else { List<MarkerVertex> qNeighbor = new List<MarkerVertex>(); ret.ForEachNeighbor(q, (v) => { qNeighbor.Add(v); return IterationFlag.Continue; }); ret.RemoveMarkerVertex(q); var qPrimeNeighbor = new System.Collections.Generic.HashSet<MarkerVertex>(); uPrime.ForEachNeighbor(qPrime, (v) => { qPrimeNeighbor.Add(v); return IterationFlag.Continue; }); uPrime.ForEachMarkerVertex((v) => { if (v != qPrime) { if (qPrimeNeighbor.Contains(v)) { HashSet<MarkerVertex> nSet = new HashSet<MarkerVertex>(qNeighbor); uPrime.ForEachNeighbor(v, (w) => { if (w != qPrime) nSet.Add(w); return IterationFlag.Continue; }); ret.AddMarkerVertex(v, nSet); } else { HashSet<MarkerVertex> nSet = new HashSet<MarkerVertex>(); uPrime.ForEachNeighbor(v, (w) => { if (w != qPrime) nSet.Add(w); return IterationFlag.Continue; }); ret.AddMarkerVertex(v, nSet); } } return IterationFlag.Continue; }); if (uPrime is PrimeNode) { uPrimeChildren.Add((uPrime as PrimeNode).childSetRepresentative); } else { uPrime.ForEachChild(v => { uPrimeChildren.Add(v); return IterationFlag.Continue; }, false); } } //union the children of uPrime for (int i = 0, n = uPrimeChildren.Count; i < n; ++i) { uPrimeChildren[i].parentLink = null; uPrimeChildren[i].unionFind_parent = representative; } //set deletion flag for uPrime, or if it's the child representative, make it a fake node uPrime.active = true; if (uPrime == representative) { uPrime.parentLink = ret;//update the parentLink to the new prime node //don't touch the unoinFind_parent field. leave it pointing to uPrime itself. } else//uPrime is not a fake node. { uPrime.parentLink = ret; //uPrime.unionFind_parent = null; } return ret; }
private void DecorateCodeNamespace(CodeNamespace codeNamespace) { // Generate the schema set code namespace CodeNamespace schemaSetCodeNamespace = GenerateSchemaTypes(); // Add the code namespace to a fast search structure // KeyValuePair<type , namespace> HashSet<KeyValuePair<string, string>> typeSet = new System.Collections.Generic.HashSet<KeyValuePair<string, string>>(); foreach (CodeTypeDeclaration ctd in codeNamespace.Types) { XmlQualifiedName typeQn = GetCodeTypeXmlQName(ctd); typeSet.Add(new KeyValuePair<string, string>(typeQn.Name, typeQn.Namespace)); } // add the missing types from the schema code namespace to the main code namespace foreach (CodeTypeDeclaration sctd in schemaSetCodeNamespace.Types) { XmlQualifiedName typeQn = GetCodeTypeXmlQName(sctd); if (!typeSet.Contains(new KeyValuePair<string, String>(typeQn.Name, typeQn.Namespace))) { codeNamespace.Types.Add(sctd); } } }
public CaseIdentification_ResultType SplitTree_CaseIdentification(SplitTree ST, List<int> sigma, int idx, out TreeEdge e, out Vertex u, out SplitTree tree) { //nodeOrder is the inverse permutation of sigma //Here idx is the index of x. e = new TreeEdge(); u = null; #region Line 1 MarkerVertex.ResetPerfectFlags();//new N(x) will be generated. All old perfect flags outdated. tree = SmallestSpanningTree(ST, sigma[idx]);//N(x) is implied in neighbor flag of each vertex #endregion //remember tree is rooted in tree.root,and it perhaps has a valid parent! //Also, check visited flag when traversing, as only those with visited flag true are included in subtree. #region Line 2 int nodeCount = 0; Queue<Node> processingQueue = new Queue<Node>(); Action<Node> testAllLeave = (n) => { bool? allLeave = null; (n as Node).ForEachChild((v) => { if (!(v is Leaf)) { allLeave = false; return IterationFlag.Break; } allLeave = true; return IterationFlag.Continue; }, subtree: false);//TODO XXX here subtree should be true, according to Algorithm 5 if (!(allLeave == null || !allLeave.Value))//has all leave processingQueue.Enqueue(n); }; foreach (var n in tree.vertices) if (n is Node) { ++nodeCount; testAllLeave(n as Node); } if (nodeCount > 1)//since there're not only 1 node, a node with all leaf children will certainly not be root { while (processingQueue.Count != 0) { var node = processingQueue.Dequeue(); //cast the spell of Remark 5.5 List<MarkerVertex> P, M, E; node.ComputeStates(out P, out M, out E, exclude: node.rootMarkerVertex); //since node has all leaf children, when we exclude the rootMarkerVertex, the time complexity is bound to |Children| //also, M should be empty. Thus case 2 automatically satisfied. <- XXX not really, cannot assert here //Debug.Assert(M.Count == 0, "A node with all leaf children has a mixed marker vertex!!"); var Pset = new System.Collections.Generic.HashSet<MarkerVertex>(P); var inCount = 0; var neighborCount = 0; node.ForEachNeighbor(node.rootMarkerVertex, (q) => { ++neighborCount; if (Pset.Contains(q)) ++inCount; return IterationFlag.Continue; }); //P == N_Gu(q) iff P.Count == inCount == neighborCount if (P.Count == inCount && inCount == neighborCount && M.Count == 0)//now we say that rootMarkerVertex'es opposite vertex is perfect { //(node.rootMarkerVertex.opposite as GLTVertex). node.rootMarkerVertex.opposite.MarkAsPerfect(); tree.RemoveSubTree(node); if (node.parent is Node) testAllLeave(node.parent as Node); } } } #endregion #region Line 3 u = tree.root; bool unique = true; Debug.Assert(u != null, "the root of subtree is null, after removing pendant perfect subtrees"); while (true) { Node child = null; if (u is Leaf) { child = (u as Leaf).opposite.node; if (child == null || !child.visited)//now the leaf root u is the unique vertex in T' { //this case is not discussed in paper... Thanks Emeric, problem solved. return CaseIdentification_ResultType.SingleLeaf; } } else { (u as Node).ForEachChild((v) => { if (v is Node) { if (child == null) { unique = true; child = v as Node; } else { unique = false; return IterationFlag.Break; } } return IterationFlag.Continue; }, subtree: true); } //here unique indicates whether u has a unique node child if (unique == false) break;//there are at least two non-leaf children of the current root; break out and return the subtree, now. else if (child == null)//u contains no non-leaf child { //now we can say u is the unique node in T' break; } else// the unique child node is located { if (u is Leaf) { //the root is a leaf, which indicates that root \in N(x), thus perfect. (u as Leaf).visited = false; tree.vertices.Remove(u as Leaf); u = child;//prune it directly. } else { List<MarkerVertex> P, M, E; (u as Node).ComputeStates(out P, out M, out E, exclude: child.rootMarkerVertex.opposite as MarkerVertex, excludeRootMarkerVertex: false); bool perfect = false; if (M.Count == 0)//condition 2 is satisfied { var Pset = new System.Collections.Generic.HashSet<MarkerVertex>(P); var inCount = 0; var neighborCount = 0; (u as Node).ForEachNeighbor(child.rootMarkerVertex.opposite as MarkerVertex, (q) => { ++neighborCount; if (Pset.Contains(q)) ++inCount; return IterationFlag.Continue; }); //P == N_Gu(q) iff P.Count == inCount == neighborCount if (P.Count == inCount && inCount == neighborCount)//now we say that child's rootMarkerVertex is perfect { child.rootMarkerVertex.MarkAsPerfect(); perfect = true; } } if (perfect) { tree.RemoveSubTree(u as Node, exclude: child); u = child; } else { //the tree edge uv is fully mixed. thus the subtree T' is fully mixed. unique = false; break; } } } tree.root = u as GLTVertex;//let the tree root follow u after each iteration of the processing loop } #endregion #region Line 4 if (!unique) return CaseIdentification_ResultType.FullyMixedSubTree; else { #region if (u is DegenerateNode) if (u is DegenerateNode) { #region Lemma 5.6 var uDeg = u as DegenerateNode; MarkerVertex q = null; List<MarkerVertex> P, M, E; //Note, we computed P(u), thus if q exists, its perfect flag is available (uDeg).ComputeStates(out P, out M, out E); //Debug.Assert(M.Count == 0, "Algorithm 5 Line 4, lemma 5.6 requires P(u) == NE(u)!"); if (M.Count == 0) { if (P.Count == 1 && uDeg.isStar && uDeg.center == P[0])//case 3 { uDeg.ForEachMarkerVertex((v) => { if (v != uDeg.center) { q = v; return IterationFlag.Break; } return IterationFlag.Continue; }); } else if (P.Count == 2 && uDeg.isStar && P.Contains(uDeg.center))//case 4 { if (uDeg.center == P[0]) q = P[1]; else q = P[0]; } else { int count = P.Count + E.Count;//faster than the commented line below //uDeg.ForEachMarkerVertex((v) => { ++count; return IterationFlag.Continue; }); if (count == P.Count)//case 1 { if (uDeg.isClique) q = P[0]; else q = uDeg.center; } else if (P.Count == count - 1 && (uDeg.isClique || E[0] == uDeg.center))//case 2 { //E[0]: V(u) \ P(u) q = E[0]; } } } #endregion if (q != null) { e.u = q; e.v = q.opposite; q.opposite.MarkAsPerfect(); return CaseIdentification_ResultType.TreeEdge; } else { return CaseIdentification_ResultType.HybridNode; } } #endregion #region else: prime node else//prime node { var uPrime = u as PrimeNode; MarkerVertex q = uPrime.lastMarkerVertex;//last leaf vertex in \sigma[G(u)] MarkerVertex qPrime = (u as PrimeNode).universalMarkerVetex;//the universal marker (if any) //Again cast the spell of Remark 5.5 List<MarkerVertex> P, M, E; //Note, here we didn't exclude anything. Which means that, if a PP/PE edge is returned, perfect flags will be available. uPrime.ComputeStates(out P, out M, out E); //first, for q if (M.Count == 0 || (M.Count == 1 && M[0] == q))//condition 2 { var Pset = new System.Collections.Generic.HashSet<MarkerVertex>(P); var inCount = 0; var neighborCount = 0; uPrime.ForEachNeighbor(q, (r) => { ++neighborCount; if (Pset.Contains(r)) ++inCount; return IterationFlag.Continue; }); //P == N_Gu(q) iff P.Count == inCount == neighborCount, or P.Count == inCount+1 == neighborCount+1 and q in P if ((P.Count == inCount && inCount == neighborCount) || (P.Count == inCount + 1 && P.Count == neighborCount + 1 && Pset.Contains(q))) { e.u = q; e.v = q.opposite; q.opposite.MarkAsPerfect(); return CaseIdentification_ResultType.TreeEdge; } } //then for q' if (qPrime != null) { if (M.Count == 0 || (M.Count == 1 && M[0] == qPrime))//condition 2 { var Pset = new System.Collections.Generic.HashSet<MarkerVertex>(P); var inCount = 0; var neighborCount = 0; uPrime.ForEachNeighbor(qPrime, (r) => { ++neighborCount; if (Pset.Contains(r)) ++inCount; return IterationFlag.Continue; }); //P == N_Gu(q) iff P.Count == inCount == neighborCount, or P.Count == inCount+1 == neighborCount+1 and q in P if ((P.Count == inCount && inCount == neighborCount) || (P.Count == inCount + 1 && P.Count == neighborCount + 1 && Pset.Contains(qPrime))) { e.u = qPrime; e.v = qPrime.opposite; qPrime.opposite.MarkAsPerfect(); return CaseIdentification_ResultType.TreeEdge; } } } //else, just return u return CaseIdentification_ResultType.HybridNode; } #endregion } #endregion }