public int LongestConsecutiveSolution(int[] nums) { int length = nums.Length; HashSet<int> set = new HashSet<int>(); int max=0; foreach(int cur in nums) set.Add(cur); foreach (int cur in nums) { int len=1; int left = cur - 1; int right = cur + 1; while (set.Contains(left)) { len++; set.Remove(left); left--; } while (set.Contains(right)) { len++; set.Remove(left); right++; } max = max > len ? max : len; } return max; }
/// <summary> /// Starts the clustering. /// </summary> /// <param name="elements"></param> /// <param name="fusion"></param> /// <param name="metric"></param> /// <returns></returns> protected internal Cluster[] Cluster(List<Element> elements, Fusion fusion, IDistanceMetric metric) { HashSet<Cluster> clusters = new HashSet<Cluster>(); ClusterPairs pairs = new ClusterPairs(); // 1. Initialize each element as a cluster foreach (Element el in elements) { Cluster cl = new Cluster(fusion); cl.AddElement(el); clusters.Add(cl); } // 2. a) Calculate the distances of all clusters to all other clusters foreach (Cluster cl1 in clusters) { foreach (Cluster cl2 in clusters) { if (cl1 == cl2) continue; ClusterPair pair = new ClusterPair(cl1, cl2, cl1.CalculateDistance(cl2)); pairs.AddPair(pair); } } // 2. b) Initialize the pair with the lowest distance to each other. ClusterPair lowestDistancePair = pairs.LowestDistancePair; // 3. Merge clusters to new clusters and recalculate distances in a loop until there are only countCluster clusters while (!isFinished(clusters, lowestDistancePair)) { // a) Merge: Create a new cluster and add the elements of the two old clusters lowestDistancePair = pairs.LowestDistancePair; Cluster newCluster = new Cluster(fusion); newCluster.AddElements(lowestDistancePair.Cluster1.GetElements()); newCluster.AddElements(lowestDistancePair.Cluster2.GetElements()); // b)Remove the two old clusters from clusters clusters.Remove(lowestDistancePair.Cluster1); clusters.Remove(lowestDistancePair.Cluster2); // c) Remove the two old clusters from pairs pairs.RemovePairsByOldClusters(lowestDistancePair.Cluster1, lowestDistancePair.Cluster2); // d) Calculate the distance of the new cluster to all other clusters and save each as pair foreach (Cluster cluster in clusters) { ClusterPair pair = new ClusterPair(cluster, newCluster, cluster.CalculateDistance(newCluster)); pairs.AddPair(pair); } // e) Add the new cluster to clusters clusters.Add(newCluster); } return clusters.ToArray<Cluster>(); }
/// <summary> /// Find Longest Consequitive Sequence /// </summary> /// <param name="arr">Source Array</param> /// <returns>Length of longest consecutive numbers</returns> public static int LongestConsecutiveSequenceLength(int[] arr) { HashSet<int> allElements = new HashSet<int>(arr); int maxConsecutiveLength = 1; while (allElements.Count > 0) { int firstValue = allElements.First(); int leftElement = firstValue; int currentLength = 1; while (allElements.Contains(leftElement - 1)) { allElements.Remove(leftElement - 1); leftElement--; currentLength++; } int rightElement = firstValue; while (allElements.Contains(rightElement + 1)) { allElements.Remove(rightElement + 1); rightElement++; currentLength++; } if (currentLength > maxConsecutiveLength) { maxConsecutiveLength = currentLength; } allElements.Remove(firstValue); } return maxConsecutiveLength; }
public int LongestConsecutive(int[] num) { HashSet<int> hset = new HashSet<int>(num); int answer = 1; for (int i = 0; i < num.Length; i++) { int current = num[i]; if (hset.Remove(current)) { int tmp = 1; int higher = current +1; while (hset.Remove(higher++)) { tmp++; } int lower = current - 1; while (hset.Remove(lower--)) { tmp++; } answer = Math.Max(answer, tmp); } } return answer; }
public void AddRemove() { var set = new HashSet<int>(); foreach (int item in Enumerable.Range(100, 100)) { bool added = set.Add(item); Assert.IsTrue(added); } Assert.AreEqual(100, set.Count); Assert.IsFalse(set.Add(120)); foreach (int item in Enumerable.Range(120, 20)) { bool removed = set.Remove(item); Assert.IsTrue(removed); } Assert.AreEqual(80, set.Count); Assert.IsFalse(set.Remove(120)); foreach (int item in Enumerable.Range(100, 200)) set.Add(item); Assert.AreEqual(200, set.Count); }
static void drawCodeGenerators(CodeGeneratorConfig codeGeneratorConfig, Type[] codeGenerators) { EditorGUILayout.Space(); EditorGUILayout.LabelField("Code Generators", EditorStyles.boldLabel); var enabledCodeGenerators = new HashSet<string>(codeGeneratorConfig.enabledCodeGenerators); var availableGeneratorNames = new HashSet<string>(); foreach (var codeGenerator in codeGenerators) { availableGeneratorNames.Add(codeGenerator.Name); var isEnabled = enabledCodeGenerators.Contains(codeGenerator.Name); isEnabled = EditorGUILayout.Toggle(codeGenerator.Name, isEnabled); if (isEnabled) { enabledCodeGenerators.Add(codeGenerator.Name); } else { enabledCodeGenerators.Remove(codeGenerator.Name); } } foreach (var generatorName in codeGeneratorConfig.enabledCodeGenerators.ToArray()) { if (!availableGeneratorNames.Contains(generatorName)) { enabledCodeGenerators.Remove(generatorName); } } var sortedCodeGenerators = enabledCodeGenerators.ToArray(); Array.Sort(sortedCodeGenerators); codeGeneratorConfig.enabledCodeGenerators = sortedCodeGenerators; }
public int LongestConsecutive(int[] num) { int max = 0; HashSet<int> hashSet = new HashSet<int>(num); foreach (int val in num) { if (hashSet.Remove(val)) { int tempResult = 1; int upperVal = val + 1; while (hashSet.Remove(upperVal++)) { tempResult++; } int lowerVal = val - 1; while (hashSet.Remove(lowerVal--)) { tempResult++; } max = Math.Max(max, tempResult); } } return max; }
public int[] FindBest() { var remaining = new HashSet<Point>(_cities); var first = remaining.First(); var route = new List<Point> { first }; remaining.Remove(first); var numericRoute = new List<int>{_cities.IndexOf(first)}; var distance = 0.0d; while (remaining.Any()) { var shortest = double.MaxValue; Point next = null; foreach (var p in remaining) { var d = Distance(route.Last(), p); if (d < shortest) { shortest = d; next = p; } } route.Add(next); numericRoute.Add(_cities.IndexOf(next)); remaining.Remove(next); distance += shortest; } distance += Distance(route.First(), route.Last()); Console.WriteLine("Distance calculated in closestneighbour: " + distance); return numericRoute.ToArray(); }
public int LengthOfLongestSubstring(string s) { if (string.IsNullOrEmpty(s)) return 0; char[] sArrays = s.ToCharArray(); int backPointer = 0; int result = 0; HashSet<char> hs = new HashSet<char>(); for (int frontPointer = 0; frontPointer < s.Length; ) { while (frontPointer < s.Length && !hs.Contains(sArrays[frontPointer])) { hs.Add(sArrays[frontPointer++]); } result = Math.Max(result, frontPointer - backPointer); while (frontPointer < s.Length && sArrays[backPointer] != sArrays[frontPointer]) { hs.Remove(sArrays[backPointer++]); } if (backPointer <= frontPointer && backPointer < s.Length) { hs.Remove(sArrays[backPointer++]); } } return result; }
// HACK: HashSet parameter is ugly public static IEnumerable<string> FindFreeVariablesInLambda(IEnumerable<string> parameters, IEnumerable<object> body, HashSet<string> localVariablesDefinedInLambda) { HashSet<string> accessedVariables = new HashSet<string>(); foreach (object o in body) FindAccessedVariables(o, accessedVariables, localVariablesDefinedInLambda); accessedVariables.Remove("nil"); foreach (string p in parameters) accessedVariables.Remove(p); foreach (string i in localVariablesDefinedInLambda) accessedVariables.Remove(i); return accessedVariables; }
public Node[] FindPath() { HashSet<Node> open = new HashSet<Node>(); HashSet<Node> closed = new HashSet<Node>(); Node current = start; current.G = 0; Node destination = finish; current.F = HeuristicCost(current, destination); open.Add(current); while (open.Count != 0) { current = Lowest_f(open); if (current.Equals(destination)) { if (current.previous != null) { return Path(current, start); } } open.Remove(current); closed.Add(current); foreach (Node node in GetNeighbours(current)) { double t = current.G + Distance(current, node); if (t < node.G) { if (open.Contains(node)) { open.Remove(node); } if (closed.Contains(node)) { closed.Remove(node); } } if (!open.Contains(node) && !(closed.Contains(node))) { node.G = t; node.F = HeuristicCost(node, destination); node.previous = current; open.Add(node); } } } return null; }
internal static void Main() { string decorationLine = new string('-', Console.WindowWidth); Console.Write(decorationLine); Console.WriteLine("***Presenting the functionality of the data structure 'Hash set'***"); Console.Write(decorationLine); HashSet<int> years = new HashSet<int>(); Console.WriteLine("---Add operation---"); years.Add(1990); years.Add(1992); years.Add(2013); years.Add(2016); years.Add(2022); Console.WriteLine("Count = " + years.Count); Console.WriteLine(); Console.WriteLine("---Iterator functionality---"); PrintYears(years); Console.WriteLine(); Console.WriteLine("---Contains operation---"); Console.WriteLine("Does years set contain {0}? - {1}", 1992, years.Contains(1992)); Console.WriteLine("Does years set contain {0}? - {1}", 2012, years.Contains(2012)); Console.WriteLine(); Console.WriteLine("---Remove operation---"); Console.WriteLine("Is {0} removed from years set? - {1}", 1996, years.Remove(1996)); Console.WriteLine("Years set count: " + years.Count); Console.WriteLine("Is {0} removed from years set? - {1}", 1990, years.Remove(1990)); Console.WriteLine("Years set count: " + years.Count); Console.WriteLine(); Console.WriteLine("---UnionWith operation---"); int[] yearsToUnionWith = new int[] { 2005, 2009, 2021, 2016, 1992, 2013 }; years.UnionWith(yearsToUnionWith); Console.WriteLine("All years after a union with: {0}", string.Join(", ", yearsToUnionWith)); PrintYears(years); Console.WriteLine("Years set count: " + years.Count); Console.WriteLine(); Console.WriteLine("---IntersectWith operation---"); int[] yearsToIntersectWith = new int[] { 2045, 2025, 2021, 2016, 1999, 2017, 2013 }; years.IntersectWith(yearsToIntersectWith); Console.WriteLine("All years after an intersect with: {0}", string.Join(", ", yearsToIntersectWith)); PrintYears(years); Console.WriteLine("Years set count: " + years.Count); Console.WriteLine(); Console.WriteLine("---Clear operation---"); years.Clear(); Console.WriteLine("Years count after clearing: " + years.Count); }
private AppMetadata(string json) { JsonValue data; try { data = JsonValue.Parse(json); } catch (FormatException e) { MessageBox.Show("Apparently the metadata contains an error. Sorry about that! Please try again in a minute.\n\nThe error is: " + e.Message, "Error in apps.json", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(1); return; } if ((int) data["version"] != 1) { MessageBox.Show("This version of Steam Disk Saver is too old. The metadata uses format " + data["version"] + ", but this version only supports format 1. Please download the latest version.", "Outdated version", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); Environment.Exit(0); } foreach (var item in data["categories"]) { Categories.Add(new Category(item.Key, item.Value)); } var engines = data["engines"]; foreach (var item in data["apps"]) { var id = int.Parse(item.Key); var app = item.Value; Known.Add(id); var categoriesInApp = new HashSet<string>(); foreach (var cat in app) { categoriesInApp.Add(cat.Key); } categoriesInApp.Remove("engine"); foreach (var cat in Categories) { categoriesInApp.Remove(cat.Key); cat.AddApp(id, app, engines); } foreach (var cat in categoriesInApp) { Debug.WriteLine("Unknown category {0} in {1}", cat, id); } } }
// Method establishes which values can fill an empty square by eliminating any values already occurring in row/column/box. public List<int> DetermineValidOptionsForSquare(SquareCoordinate squareCoordinate, IImmutableSudokuGrid grid) { HashSet<int> validSquareOptions = new HashSet<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; for (int offset = 1; offset < 9; offset++) { validSquareOptions.Remove(grid.Elements[(squareCoordinate.Row + offset) % 9, squareCoordinate.Column]); validSquareOptions.Remove(grid.Elements[(squareCoordinate.Row), (squareCoordinate.Column + offset) % 9]); validSquareOptions.Remove(grid.Elements[(3 * (squareCoordinate.Row / 3)) + offset % 3, (3 * (squareCoordinate.Column / 3)) + (offset - offset % 3) / 3]); } return validSquareOptions.ToList<int>(); }
public override Card[] RequestExhangeCards() { List<Card> retCards = new List<Card>(); //arrange he cards by suits List<Card>[] suitsCount = ArrangeCardBySuits(Cards); //look at each suit which has 2 cards or less and add those cards to the returned array foreach (List<Card> suit in suitsCount) { if (suit.Count <= 2) { retCards.AddRange(suit); suit.Clear(); } } //see how many cards are in the returned array if (retCards.Count == 3) { return retCards.ToArray(); } else if (retCards.Count > 3) { //find lowest card and throw away while (retCards.Count > 3) { //remove the card with the lowest value - till we have only 3 cards left Card current = GetLowestCardInCollection(retCards); retCards.Remove(current); } } else if (retCards.Count < 3) { //copy cards for operation & remove cards already picked from that collection ICollection<Card> cards_cpy = new HashSet<Card>(Cards); foreach (Card c in retCards) { cards_cpy.Remove(c); } //add highest card in my hand to return array - till I have 3 cards while (retCards.Count < 3) { Card current = GetHighestCardInCollection(cards_cpy); retCards.Add(current); cards_cpy.Remove(current); } } return retCards.ToArray(); }
public static IEnumerable<Cluster<Word>> GenerateCognateSets(this CogProject project, Meaning meaning) { var words = new HashSet<Word>(); var noise = new HashSet<Word>(); foreach (VarietyPair vp in project.VarietyPairs) { WordPair wp; if (vp.WordPairs.TryGetValue(meaning, out wp)) { if (wp.Cognacy) { words.Add(wp.Word1); words.Add(wp.Word2); noise.Remove(wp.Word1); noise.Remove(wp.Word2); } else { if (!words.Contains(wp.Word1)) noise.Add(wp.Word1); if (!words.Contains(wp.Word2)) noise.Add(wp.Word2); } } } double min = double.MaxValue; var distanceMatrix = new Dictionary<UnorderedTuple<Word, Word>, double>(); Word[] wordArray = words.ToArray(); for (int i = 0; i < wordArray.Length; i++) { for (int j = i + 1; j < wordArray.Length; j++) { Word w1 = wordArray[i]; Word w2 = wordArray[j]; double score = 0; WordPair wp; if (w1.Variety != w2.Variety && w1.Variety.VarietyPairs[w2.Variety].WordPairs.TryGetValue(meaning, out wp) && wp.Cognacy && wp.GetWord(w1.Variety) == w1 && wp.GetWord(w2.Variety) == w2) { score = wp.PredictedCognacyScore; } double distance = 1.0 - score; min = Math.Min(min, distance); distanceMatrix[UnorderedTuple.Create(w1, w2)] = distance; } } var clusterer = new FlatUpgmaClusterer<Word>((w1, w2) => distanceMatrix[UnorderedTuple.Create(w1, w2)], (1.0 + min) / 2); return clusterer.GenerateClusters(words).Concat(new Cluster<Word>(noise, true)); }
public async Task<IEnumerable<Album>> AlbumsFromCommaSeparatedValuesAndUserId(string albumsAsCommaSeparatedValues, string userId) { if (string.IsNullOrWhiteSpace(albumsAsCommaSeparatedValues)) { return Enumerable.Empty<Album>(); } var albumsValues = new HashSet<string>(); albumsAsCommaSeparatedValues.Split(new[] { GlobalConstants.CommaSeparatedCollectionSeparator }, StringSplitOptions.RemoveEmptyEntries) .ToList() .ForEach(val => { albumsValues.Add(val.Trim()); }); var resultAlbum = await this.albums .All() .Where(a => (albumsValues.Contains(a.Name.ToLower()) || albumsValues.Contains(a.Id.ToString())) && a.Creator.Id == userId) .ToListAsync(); (await this.albums .All() .Where(a => (albumsValues.Contains(a.Name.ToLower()) || albumsValues.Contains(a.Id.ToString())) && a.Creator.Id == userId) .Select(a => a.Name.ToLower()) .ToListAsync()) .ForEach(a => albumsValues.Remove(a)); var idValues = new List<string>(); albumsValues.ForEach(v => { int id; var isId = int.TryParse(v, out id); if (isId) { idValues.Add(v); } }); idValues.ForEach(a => albumsValues.Remove(a)); albumsValues.ForEach(tagName => resultAlbum.Add(new Album() { Name = tagName })); return resultAlbum; }
public static List<NavigationItem> GetNavigationItems(Func<string, string> resolveUrl = null, Func<NavigationItemAttribute, bool> filter = null) { var result = new List<NavigationItem>(); var menuItems = GetNavigationItemAttributes(filter); var remaining = new HashSet<string>(); foreach (var item in menuItems) remaining.Add(item.Key); Action<List<NavigationItem>, NavigationItemAttribute> processMenu = null; processMenu = (parent, menu) => { var path = (menu.Category.IsEmptyOrNull() ? "" : (menu.Category + "/")); path += (menu.Title.TrimToNull() ?? ""); remaining.Remove(path); var section = new NavigationItem { Title = menu.Title, Url = (!string.IsNullOrEmpty(menu.Url) && resolveUrl != null) ? resolveUrl(menu.Url) : menu.Url, IconClass = menu.IconClass.TrimToNull(), Target = menu.Target.TrimToNull() }; bool isAuthorizedSection = !menu.Url.IsEmptyOrNull() && (menu.Permission.IsEmptyOrNull() || Authorization.HasPermission(menu.Permission)); var children = menuItems[path]; foreach (var child in children) processMenu(section.Children, child); if (section.Children.Count > 0 || isAuthorizedSection) parent.Add(section); }; remaining.Remove(""); foreach (var menu in menuItems[""]) processMenu(result, menu); while (remaining.Count > 0) { var first = remaining.First(); remaining.Remove(first); var menu = new NavigationMenuAttribute(Int32.MaxValue, first); processMenu(result, menu); } return result; }
private int getLength(HashSet<int> hs, int cur) { int len = 1, left = cur - 1, right = cur + 1; while (hs.Contains(left)) { ++len; hs.Remove(left--); } while (hs.Contains(right)) { ++len; hs.Remove(right++); } return len; }
private void Images_ImageLoadSuccess(object sender, ImageLoadEventArgs e) { if (_failedImagePaths?.Remove(e.Path) ?? false) { InvalidateStatusReport(); } }
public StockActor(string stockSymbol) { _stockSymbol = stockSymbol; _subscribers = new HashSet<IActorRef>(); _priceLookupChild = Context.ActorOf(Context.DI().Props<StockPriceLookupActor>()); Receive<SubscribeToNewStockPricesMessage>(message => _subscribers.Add(message.Subscriber)); Receive<UnSubscribeFromNewStockPricesMessage>(message => _subscribers.Remove(message.Subscriber)); Receive<RefreshStockPriceMessage>(message => _priceLookupChild.Tell(message)); Receive<UpdatedStockPriceMessage>(message => { _stockPrice = message.Price; var stockPriceMessage = new StockPriceMessage(_stockSymbol, _stockPrice, message.Date); foreach (var subscriber in _subscribers) { subscriber.Tell(stockPriceMessage); } }); }
public ObjectInstance GetOrCreate(string key) { if (OwnValues.TryGetValue(key, out var property) == false) { property = GenerateProperty(key); OwnValues[key] = property; Deletes?.Remove(key); } return(property.Value.AsObject()); BlittableObjectProperty GenerateProperty(string propertyName) { var propertyIndex = Blittable.GetPropertyIndex(propertyName); var prop = new BlittableObjectProperty(this, propertyName); if (propertyIndex == -1) { prop.Value = new ObjectInstance(Engine) { Extensible = true }; } return(prop); } }
/// <summary> /// Determines whether the interpreter factory contains the specified /// modules. /// </summary> /// <returns>The names of the modules that were found.</returns> public static async Task<HashSet<string>> FindModulesAsync(this IPythonInterpreterFactory factory, params string[] moduleNames) { var withDb = factory as PythonInterpreterFactoryWithDatabase; if (withDb != null && withDb.IsCurrent) { var db = withDb.GetCurrentDatabase(); var set = new HashSet<string>(moduleNames.Where(m => db.GetModule(m) != null)); return set; } var expected = new HashSet<string>(moduleNames); if (withDb != null) { var paths = PythonTypeDatabase.GetCachedDatabaseSearchPaths(withDb.DatabasePath) ?? await PythonTypeDatabase.GetUncachedDatabaseSearchPathsAsync(withDb.Configuration.InterpreterPath).ConfigureAwait(false); var db = PythonTypeDatabase.GetDatabaseExpectedModules(withDb.Configuration.Version, paths) .SelectMany() .Select(g => g.ModuleName); expected.IntersectWith(db); return expected; } return await Task.Run(() => { var result = new HashSet<string>(); foreach (var mp in ModulePath.GetModulesInLib(factory)) { if (expected.Count == 0) { break; } if (expected.Remove(mp.ModuleName)) { result.Add(mp.ModuleName); } } return result; }); }
public override bool Control( GameEntity control, TimeSpan gameTime, Microsoft.Xna.Framework.Input.KeyboardState keyState ) { if ( control is Projectile ) { HashSet<Tank> tanks = new HashSet<Tank>(); if ( control.Variables.ContainsKey( "Hypnotize" ) ) { tanks = ( ( HashSet<Tank> )control.Variables[ "Hypnotize" ] ); } if ( Vector2.Distance( control.Position, Owner.Position ) < rad )// && !Tools.IsGoingTowardsMe( Owner.Position, control.Angle, control.Position ) ) { if ( !control.Variables.ContainsKey( "Hypnotize" ) || !tanks.Contains( Owner ) ) { DeflectorController d = new DeflectorController( Tools.Angle( Owner.Position, control.Position ) ); control.AppendController( d ); tanks.Add( Owner ); } } else { tanks.Remove( Owner ); } control.Variables[ "Hypnotize" ] = tanks; } return base.Control( control, gameTime, keyState ); }
public override void BuildNode (ITreeBuilder treeBuilder, object dataObject, NodeInfo nodeInfo) { //modules do no have names/IDs, but genrally the only reason they exist //is because they have additional, optional dependencies //so find the dependencies that are not referenced in other modules //and use one as the label var module = (ModuleDescription)dataObject; var deps = new HashSet<string> (); foreach (Dependency dep in module.Dependencies) { deps.Add (dep.Name); } foreach (ModuleDescription other in module.ParentAddinDescription.AllModules) { if (other == module) { continue; } foreach (Dependency dep in other.Dependencies) { deps.Remove (dep.Name); } } if (deps.Count > 0) { nodeInfo.Label = deps.First ().Split (new[] { ' '})[0]; } else { nodeInfo.Label = "Module"; } }
public static string Travelse(List<List<int>> graph) { var visited = new HashSet<int>(); var planned = new HashSet<int>(); var candidates = new Stack<int>(); candidates.Push(0); planned.Add(0); var resultBuilder = new StringBuilder(); while (candidates.Count > 0) { var currentVisited = candidates.Pop(); planned.Remove(currentVisited); visited.Add(currentVisited); resultBuilder.Append(currentVisited); foreach (var vertex in graph[currentVisited]) { if (!visited.Contains(vertex) && !planned.Contains(vertex)) { candidates.Push(vertex); planned.Add(vertex); } } } return resultBuilder.ToString(); }
private static double FindMinimalCost(HashSet<ISet<int>> allTrees) { // Kruskal -> Sorting edges by their weight Array.Sort(paths, (a, b) => a.Item3.CompareTo(b.Item3)); double result = 0; foreach (var path in paths) { var tree1 = allTrees.Where(tree => tree.Contains(path.Item1)).First(); var tree2 = allTrees.Where(tree => tree.Contains(path.Item2)).First(); // Elements are in same tree if (tree1.Equals(tree2)) continue; result += path.Item3; tree1.UnionWith(tree2); allTrees.Remove(tree2); // Small optimization if (allTrees.Count == 1) break; } return result; }
///<summary>Gets all files that indirectly depend on the specified file.</summary> public async Task<IEnumerable<string>> GetRecursiveDependentsAsync(string fileName) { HashSet<GraphNode> visited; fileName = Path.GetFullPath(fileName); using (await rwLock.ReadLockAsync()) { GraphNode rootNode; if (!nodes.TryGetValue(fileName, out rootNode)) return Enumerable.Empty<string>(); var stack = new Stack<GraphNode>(); stack.Push(rootNode); visited = new HashSet<GraphNode> { rootNode }; while (stack.Count > 0) { foreach (var child in stack.Pop().Dependents) { if (!visited.Add(child)) continue; stack.Push(child); } } // Don't return the original file. visited.Remove(rootNode); } return visited.Select(n => n.FileName); }
long Solve(int N, List<int> A, int I, HashSet<int> used, int need) { long result = 0; for (int i = 1; i <= N; i++) { if (used.Contains(i)) { continue; } var n = i - A[I] > 0 ? need - (i - A[I]) : need; if (n <= 0) { int c = 0; for (int j = 1; j <= N; j++) { if (!used.Contains(j) && j != i) { c++; } } result += Prod(Enumerable.Range(1, c).ToList()); } else { used.Add(i); result += Solve(N, A, I + 1, used, n); used.Remove(i); } } return result; }
internal override bool FixElement(XElement rt, FwDataFixer.ErrorLogger logger) { var classAttr = rt.Attribute("class"); if (classAttr == null) return true; // bizarre, but leave it alone List<string> requiredFields; if (!m_customFields.TryGetValue(classAttr.Value, out requiredFields)) return true; // has no custom fields we care about var missingFields = new HashSet<string>(requiredFields); foreach (var child in rt.Elements()) { if (child.Name == "Custom") { var nameAttr = child.Attribute("name"); if (nameAttr != null) missingFields.Remove(nameAttr.Value); // not missing, we don't need to add it. } } foreach (var fieldName in missingFields) { rt.Add(new XElement("Custom", new XAttribute("name", fieldName), new XAttribute("val", "0"))); var guid = rt.Attribute("guid").Value; // This is such an insignificant fix from the user's point of view that we might prefer not // even to report it. But don't remove the logging without adding another mechanism for // the system to know that a problem has been fixed...this controls the important behavior // of re-splitting the file before we commit. logger(guid, DateTime.Now.ToShortDateString(), String.Format(Strings.ksAddingMissingDefaultForValueType, guid)); } return true; }
public static IEnumerable<string> GetBaseTypeAndInterfacesFullNames(this Type type) { Queue<Type> typesToSearch = new Queue<Type>(); HashSet<string> typeNames = new HashSet<string>(); typesToSearch.Enqueue(type); while(typesToSearch.Count > 0) { Type currentType = typesToSearch.Dequeue(); if (typeNames.Contains(currentType.FullName)) continue; // Skip types we have already searched typeNames.Add(currentType.FullName); if(currentType.BaseType != null) { typesToSearch.Enqueue(currentType.BaseType); } foreach(var @interface in currentType.GetInterfaces()) { typesToSearch.Enqueue(@interface); } } typeNames.Remove(type.FullName); return typeNames; }
//build tree and track the leastcostleaf node; public bool BuildTree(PlanNode parent, HashSet<Action> actionList, Dictionary<string, object> goalState, PlanNode leastCostLeaf) { bool hasPath = false; foreach (Action a in actionList) { if (AreConditionsInState (a.preconditions, parent.currentState)) { Dictionary<string, object> newState = CreateStateWithEffects (a.effects, parent.currentState); PlanNode newNode = new PlanNode (parent, parent.totalCost + a.cost, newState, a); if (AreConditionsInState (goalState, newState)) { if (leastCostLeaf == null) { leastCostLeaf = newNode; } else if (newNode.totalCost < leastCostLeaf.totalCost) { leastCostLeaf = newNode; } hasPath = true; } else { //remove the current action from list of available actions and build tree based on remaining actions HashSet<Action> actionsMinusOne = new HashSet<Action> (actionList); actionsMinusOne.Remove (a); //if any path was found, set to true hasPath = hasPath || BuildTree (newNode, actionsMinusOne, goalState, leastCostLeaf); } } } return hasPath; }
public ObjectInstance GetOrCreate(JsValue key) { BlittableObjectProperty property = default; if (OwnValues?.TryGetValue(key, out property) == true && property != null) { return(property.Value.AsObject()); } property = GenerateProperty(key.AsString()); OwnValues ??= new Dictionary <JsValue, BlittableObjectProperty>(Blittable.Count); OwnValues[key] = property; Deletes?.Remove(key); return(property.Value.AsObject()); BlittableObjectProperty GenerateProperty(string propertyName) { var propertyIndex = Blittable.GetPropertyIndex(propertyName); var prop = new BlittableObjectProperty(this, propertyName); if (propertyIndex == -1) { prop.Value = new ObjectInstance(Engine); } return(prop); } }
private void CommandProcedure_Disposed(object sender, EventArgs e) { if (sender is ICommandProcedure cp) { cp.Disposed -= CommandProcedure_Disposed; notDisposeds?.Remove(cp); } }
public void unsubscribe(RouteAware routeAware) { D.assert(routeAware != null); foreach (R route in this._listeners.Keys) { HashSet<RouteAware> subscribers = this._listeners[route]; subscribers?.Remove(routeAware); } }
public void SetSection <T>(T data) where T : new() { var s = sections.OfType <T>().SingleOrDefault(); sections?.Remove(s); sections.Add(data); provider.SetSection(data); }
public void _markDetached(FocusNode node) { D.assert(FocusManagerUtils._focusDebug($"Node was detached: {node}")); if (_primaryFocus == node) { _primaryFocus = null; } _dirtyNodes?.Remove(node); }
public void AddMapping(Type t, object result) { if (_initialRequestedType == t) { _initialRequestedTypeResult = result; } _container.Add(t, result); _fromTypes?.Remove(t); }
public void IncludeOpcode(string opcode) { excludedOpcodes?.Remove(opcode); includedOpcodes ??= new HashSet <string>(); if (includedOpcodes.Add(opcode) && opcode.EndsWith("*")) { includedOpcodesWildcards ??= new(); includedOpcodesWildcards.Add(opcode.Substring(0, opcode.Length - 1)); } }
internal void RemoveResource([NotNull] HardwareResource resource) { if (resource == null) { throw new ArgumentNullException(nameof(resource)); } mResources?.Remove(resource); DiagnosticsWriter.WriteDebug("Removed association of resource \"{0}\" from device.", resource); }
public void RemoveCd(string key) { if (_cdDict == null || _cdDict.Count <= 0) { return; } if (_cdDict.TryGetValue(key, out SkillCdCacheData data)) { _tickDict?.Remove(data); _cdDict.Remove(key); } }
public ObjectInstance GetOrCreate(string key) { BlittableObjectProperty value; if (OwnValues.TryGetValue(key, out value) == false) { var propertyIndex = Blittable.GetPropertyIndex(key); value = new BlittableObjectProperty(this, key); if (propertyIndex == -1) { value.Value = new JsValue(new ObjectInstance(Engine)); } OwnValues[key] = value; Deletes?.Remove(key); } return(value.Value.AsObject()); }
public object Singleton(Type type) { var tableInfo = AutoRegisterType(type); tableInfo.EnsureClientTypeVersion(); var oid = (ulong)tableInfo.SingletonOid; var obj = GetObjFromObjCacheByOid(oid); if (obj == null) { var content = tableInfo.SingletonContent(_transactionNumber); if (content == null) { _keyValueTrProtector.Start(); _keyValueTr.SetKeyPrefix(ObjectDB.AllObjectsPrefix); if (_keyValueTr.FindExactKey(BuildKeyFromOid(oid))) { content = _keyValueTr.GetValueAsByteArray(); tableInfo.CacheSingletonContent(_transactionNumber, content); } } if (content != null) { var reader = new ByteArrayReader(content); reader.SkipVUInt32(); obj = ReadObjFinish(oid, tableInfo, reader); } } if (obj != null) { if (!type.IsInstanceOfType(obj)) { throw new BTDBException($"Internal error oid {oid} does not belong to {tableInfo.Name}"); } return(obj); } _updatedTables?.Remove(tableInfo); var metadata = new DBObjectMetadata(oid, DBObjectState.Dirty); obj = tableInfo.Creator(this, metadata); tableInfo.Initializer(this, metadata, obj); AddToObjCache(oid, obj, metadata); AddToDirtySet(oid, obj); return(obj); }
private CdsEntity BuildEntity(JObject rawRecord, HashSet <string> unusedFields = null, Guid?recordId = null) { var record = new CdsEntity(); if (recordId.HasValue) { record.Id = recordId.Value; } foreach (var property in rawRecord.Properties()) { if (property.Name.StartsWith("@odata.", StringComparison.InvariantCultureIgnoreCase)) { continue; } else if (property.Value is JObject) { record.Attributes.Add(property.Name.ToLower(), BuildEntity((JObject)property.Value)); continue; } var value = property.Value.ToObject <object>(); record.Attributes.Add(property.Name.ToLower(), value); unusedFields?.Remove(property.Name); } if (unusedFields != null) { foreach (var field in unusedFields) { record.Attributes.Add(field, null); } } return(record); }
public void ProcessSubscriptionEnding(IItem item) => _subscribedItems?.Remove(item);
public static ImmutableArray <ISymbol> GetMembers(this INamedTypeSymbol typeSymbol, Func <ISymbol, bool> predicate, bool includeInherited = false) { if (includeInherited) { if (typeSymbol.TypeKind == TypeKind.Interface) { return(GetInterfaceMembersIncludingInherited()); } else { return(GetMembersIncludingInherited()); } } else if (predicate != null) { return(typeSymbol .GetMembers() .Where(predicate) .ToImmutableArray()); } return(typeSymbol.GetMembers()); ImmutableArray <ISymbol> GetMembersIncludingInherited() { var symbols = new HashSet <ISymbol>(MemberSymbolEqualityComparer.Instance); HashSet <ISymbol> overriddenSymbols = null; foreach (ISymbol symbol in GetMembers(typeSymbol, predicate: predicate)) { ISymbol overriddenSymbol = symbol.OverriddenSymbol(); if (overriddenSymbol != null) { (overriddenSymbols ??= new HashSet <ISymbol>()).Add(overriddenSymbol); } symbols.Add(symbol); } INamedTypeSymbol baseType = typeSymbol.BaseType; while (baseType != null) { bool areInternalsVisible = typeSymbol.ContainingAssembly.Identity.Equals(baseType.ContainingAssembly.Identity) || baseType.ContainingAssembly.GivesAccessTo(typeSymbol.ContainingAssembly); foreach (ISymbol symbol in baseType.GetMembers()) { if (!symbol.IsStatic && (predicate == null || predicate(symbol)) && (symbol.DeclaredAccessibility != Accessibility.Internal || areInternalsVisible)) { if (overriddenSymbols?.Remove(symbol) != true) { symbols.Add(symbol); } ISymbol overriddenSymbol = symbol.OverriddenSymbol(); if (overriddenSymbol != null) { (overriddenSymbols ??= new HashSet <ISymbol>()).Add(overriddenSymbol); } } } baseType = baseType.BaseType; } return(symbols.ToImmutableArray()); } ImmutableArray <ISymbol> GetInterfaceMembersIncludingInherited() { var symbols = new HashSet <ISymbol>(MemberSymbolEqualityComparer.Instance); foreach (ISymbol symbol in GetMembers(typeSymbol, predicate: predicate)) { symbols.Add(symbol); } foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.AllInterfaces) { foreach (ISymbol symbol in GetMembers(interfaceSymbol, predicate: predicate)) { symbols.Add(symbol); } } return(symbols.ToImmutableArray()); } }
static void loadOrReset(bool reset) { lock (settingsFieldFullNames2SettingsFieldInfo) { set_settingsFieldFullNames2SettingsFieldInfo(); IEnumerable <SettingsFieldInfo> settingsFieldInfos = settingsFieldFullNames2SettingsFieldInfo.Values; if (InitializationOrderedSettingsTypes != null) { SettingsTypeComparer settingsTypeComparer = new SettingsTypeComparer(InitializationOrderedSettingsTypes); settingsFieldInfos = settingsFieldInfos.OrderBy(a => a.Type, settingsTypeComparer); } HashSet <string> requiredOptionalFieldFullNames = RequiredOptionalFieldFullNames == null ? null : new HashSet <string>(RequiredOptionalFieldFullNames); foreach (SettingsFieldInfo settingsFieldInfo in settingsFieldInfos) { if (!settingsFieldInfo.Optional /*|| RequiredOptionalSettingsTypes?.Contains(settingsFieldInfo.Type) == true*/ || requiredOptionalFieldFullNames?.Remove(settingsFieldInfo.FullName) == true) { settingsFieldInfo.SetObject(Settings.Create(settingsFieldInfo, reset)); } } if (requiredOptionalFieldFullNames?.Count > 0) { throw new Exception("RequiredOptionalFieldFullNames contains name which was not found: '" + RequiredOptionalFieldFullNames[0] + "'"); } } }
void ICascadingValueComponent.Unsubscribe(ComponentState subscriber) { _subscribers?.Remove(subscriber); }
internal static void UnRegisterDeserializer <T>() { InDeserializerFns?.Remove(typeof(T)); }
public void RemoveAlias(string alias) { _aliases?.Remove(alias); }
public void RemoveSubscribedTopic(string topic) { _subscribedTopics?.Remove(topic); }
private void DeattachManager(IManager manager) { _managers?.Remove(manager); }
private void HandleUnwatch(Unwatch uw) { _watchers?.Remove(uw.Watcher); }
public void Remove(ILoadingCommand command) { m_Commands?.Remove(command); }
public void DisposeOf <T>(T disposable) where T : IDisposable { _Disposables?.Remove(disposable); disposable.Dispose(); }
public override HashSet <Entity> DetermineRenderOrder(HashSet <Entity> renderList, MapInstance map) { if (RenderLevel == 1) { return(base.DetermineRenderOrder(renderList, map)); } renderList?.Remove(this); if (map == null || Globals.Me == null || Globals.Me.MapInstance == null) { return(null); } var gridX = Globals.Me.MapInstance.MapGridX; var gridY = Globals.Me.MapInstance.MapGridY; for (var x = gridX - 1; x <= gridX + 1; x++) { for (var y = gridY - 1; y <= gridY + 1; y++) { if (x >= 0 && x < Globals.MapGridWidth && y >= 0 && y < Globals.MapGridHeight && Globals.MapGrid[x, y] != Guid.Empty) { if (Globals.MapGrid[x, y] == CurrentMap) { if (RenderLevel == 0) { y--; } if (RenderLevel == 2) { y++; } var priority = mRenderPriority; if (Z != 0) { priority += 3; } HashSet <Entity> renderSet = null; if (y == gridY - 2) { renderSet = Graphics.RenderingEntities[priority, Y]; } else if (y == gridY - 1) { renderSet = Graphics.RenderingEntities[priority, Options.MapHeight + Y]; } else if (y == gridY) { renderSet = Graphics.RenderingEntities[priority, Options.MapHeight * 2 + Y]; } else if (y == gridY + 1) { renderSet = Graphics.RenderingEntities[priority, Options.MapHeight * 3 + Y]; } else if (y == gridY + 2) { renderSet = Graphics.RenderingEntities[priority, Options.MapHeight * 4 + Y]; } renderSet?.Add(this); renderList = renderSet; return(renderList); } } } } return(renderList); }
internal void RemoveOwnedObject(NetworkIdentity obj) { _clientOwnedObjects?.Remove(obj.netId); }
/// <summary> /// Removes the class with the specified name from the current entry. /// </summary> /// <param name="className">The name of the class to remove.</param> public void RemoveClass(string className) { _classes.Remove(className); _optionalClasses?.Remove(className); }
public void DissociateFromValidationMessageStore(ValidationMessageStore validationMessageStore) => _validationMessageStores?.Remove(validationMessageStore);
public override void ExposeData() { Scribe_Collections.Look(ref _managers, "managers", LookMode.Deep); _managers?.Remove(null); }