public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; // make set for keeping track of which cards have already been drawn (and therefore shouldn't be drawn again), // also add our three special 'cards' so we don't get those from our random card generator usedCards = new HashSet<Point>(); usedCards.Add(CARD_BACKING); usedCards.Add(CARD_FOUNDATION); usedCards.Add(CARD_DECK_END); rng = new Random(System.DateTime.Now.Millisecond); // new seed every time we run (likely) toDraw = new List<DrawInfo>(); // Generate the various positioning numbers: DISTANCE_BETWEEN_ITEMS = (Window.ClientBounds.Width - (7 * CARD_WIDTH)) / 8; DECK_POSITION = new Vector2(DISTANCE_BETWEEN_ITEMS, DISTANCE_BETWEEN_ITEMS); DISCARD_POSITION = new Vector2(DECK_POSITION.X + CARD_WIDTH + DISTANCE_BETWEEN_ITEMS, DECK_POSITION.Y); FOUNDATION_POSITIONS = new Vector2[4]; FOUNDATION_POSITIONS[0] = new Vector2(DISCARD_POSITION.X + CARD_WIDTH * 2 + DISTANCE_BETWEEN_ITEMS * 2, DECK_POSITION.Y); for (int i = 1; i < FOUNDATION_POSITIONS.Length; i++) { FOUNDATION_POSITIONS[i].X = FOUNDATION_POSITIONS[i - 1].X + CARD_WIDTH + DISTANCE_BETWEEN_ITEMS; FOUNDATION_POSITIONS[i].Y = FOUNDATION_POSITIONS[i - 1].Y; } TABLEAU_POSITIONS = new Vector2[7]; TABLEAU_POSITIONS[0] = new Vector2(DECK_POSITION.X, DECK_POSITION.Y + CARD_HEIGHT + DISTANCE_BETWEEN_ITEMS * 3); for (int i = 1; i < TABLEAU_POSITIONS.Length; i++) { TABLEAU_POSITIONS[i].X = TABLEAU_POSITIONS[i - 1].X + CARD_WIDTH + DISTANCE_BETWEEN_ITEMS; TABLEAU_POSITIONS[i].Y = TABLEAU_POSITIONS[i - 1].Y; } }
private static void SaveAllConncectedComponents(Node<int> node, HashSet<int> visitedNodes, List<string> connectedComponents) { string graphs = string.Empty; Stack<Node<int>> nodesStack = new Stack<Node<int>>(); nodesStack.Push(node); while (nodesStack.Count > 0) { Node<int> currentNode = nodesStack.Pop(); visitedNodes.Add(currentNode.Value); graphs += " -> " + currentNode.Value; foreach (var child in currentNode.Children) { if (!visitedNodes.Contains(child.Value)) { visitedNodes.Add(child.Value); nodesStack.Push(child); } } } connectedComponents.Add(graphs.Substring(4)); }
internal IEnumerable<SortingInfo> GetFullSort() { var memo = new HashSet<string>(); var result = new List<SortingInfo>(); if(HasGroups) { foreach(var g in Group) { if(memo.Contains(g.Selector)) continue; memo.Add(g.Selector); result.Add(g); } } if(HasSort) { foreach(var s in Sort) { if(memo.Contains(s.Selector)) continue; memo.Add(s.Selector); result.Add(s); } } IEnumerable<string> requiredSort = new string[0]; if(HasDefaultSort) requiredSort = requiredSort.Concat(new[] { DefaultSort }); if(HasPrimaryKey) requiredSort = requiredSort.Concat(PrimaryKey); return Utils.AddRequiredSort(result, requiredSort); }
/// <summary> /// Writes index files into the specified directory. /// </summary> /// <param name="indexDirectory">The directory into which the index files should be written.</param> /// <param name="recordMapper">The mapper for the records.</param> /// <param param name="records">The records which should be written.</param> public void WriteDirectory(DirectoryInfo indexDirectory, IRecordMapper<string> recordMapper, IEnumerable<IReferenceRecord> records) { if (!indexDirectory.Exists) { indexDirectory.Create(); } var directoryNames = new HashSet<string>(); foreach (var directory in indexDirectory.GetDirectories()) { if (!directoryNames.Contains(directory.Name)) { directoryNames.Add(directory.Name); } } foreach (var record in records) { var directoryName = recordMapper.Map(record); if (!directoryNames.Contains(directoryName)) { indexDirectory.CreateSubdirectory(directoryName); directoryNames.Add(directoryName); } // Write index files into the index directory } }
private static HashSet<string> GetFieldsInternal(IndexQuery query, Regex queryTerms) { var fields = new HashSet<string>(); if (string.IsNullOrEmpty(query.DefaultField) == false) { fields.Add(query.DefaultField); } if(query.Query == null) return fields; var dates = dateQuery.Matches(query.Query); // we need to exclude dates from this check var queryTermMatches = queryTerms.Matches(query.Query); for (int x = 0; x < queryTermMatches.Count; x++) { Match match = queryTermMatches[x]; String field = match.Groups[1].Value; var isDate = false; for (int i = 0; i < dates.Count; i++) { if(match.Index < dates[i].Index) continue; if (match.Index >= dates[i].Index + dates[i].Length) continue; isDate = true; break; } if (isDate == false) fields.Add(field); } return fields; }
protected IEnumerable<Bundle> CreateExternalBundlesFromReferences(IEnumerable<Bundle> bundlesArray, CassetteSettings settings) { var referencesAlreadyCreated = new HashSet<string>(); foreach (var bundle in bundlesArray) { foreach (var reference in bundle.References) { if (reference.IsUrl() == false) continue; if (referencesAlreadyCreated.Contains(reference)) continue; var externalBundle = CreateExternalBundle(reference, bundle, settings); referencesAlreadyCreated.Add(externalBundle.Path); yield return externalBundle; } foreach (var asset in bundle.Assets) { foreach (var assetReference in asset.References) { if (assetReference.Type != AssetReferenceType.Url || referencesAlreadyCreated.Contains(assetReference.Path)) continue; var externalBundle = CreateExternalBundle(assetReference.Path, bundle, settings); referencesAlreadyCreated.Add(externalBundle.Path); yield return externalBundle; } } } }
/// <summary> /// Performs initialization when the adapter's node is set</summary> protected override void OnNodeSet() { m_subGraphs = new HashSet<Group>(); m_circuits = new HashSet<Circuit>(); m_historyContexts = new HashSet<HistoryContext>(); foreach (DomNode node in DomNode.Subtree) { if (CircuitUtil.IsGroupTemplateInstance(node)) { var template = CircuitUtil.GetGroupTemplate(node); m_templateInstances.Add(template.DomNode, node); m_subGraphs.Add(template); } else if (node.Is<Group>()) { m_subGraphs.Add(node.Cast<Group>()); } else if (node.Is<Circuit>()) { m_circuits.Add(node.Cast<Circuit>()); } } base.OnNodeSet(); }
public DirectionDeviceSelectorViewModel(Direction direction, DriverType driverType) { Title = "Выбор устройства"; var devices = new HashSet<Device>(); foreach (var device in FiresecManager.Devices) { if (device.Driver.DriverType == driverType) { if (device.Parent.Children.Any(x => x.Driver.IsZoneDevice && x.ZoneUID != Guid.Empty && direction.ZoneUIDs.Contains(x.ZoneUID))) { device.AllParents.ForEach(x => { devices.Add(x); }); devices.Add(device); } } } Devices = new ObservableCollection<DeviceViewModel>(); foreach (var device in devices) { var deviceViewModel = new DeviceViewModel(device); deviceViewModel.IsExpanded = true; Devices.Add(deviceViewModel); } foreach (var device in Devices.Where(x => x.Device.Parent != null)) { var parent = Devices.FirstOrDefault(x => x.Device.UID == device.Device.Parent.UID); parent.AddChild(device); } SelectedDevice = Devices.FirstOrDefault(x => x.HasChildren == false); }
private void InitAssemblyCache() { if (this.assemblies != null) return; // Retrieve a list of all loaded, non-disposed Assemblies Assembly[] loadedAssemblies = DualityApp.PluginLoader.LoadedAssemblies .Where(a => !DualityApp.PluginManager.DisposedPlugins.Contains(a)) .ToArray(); // Aggregate selectable assemblies based on Duality core Assemblies and their dependencies HashSet<Assembly> selectableAssemblies = new HashSet<Assembly>(); foreach (Assembly coreAssembly in DualityApp.GetDualityAssemblies()) { selectableAssemblies.Add(coreAssembly); AssemblyName[] referencedAssemblies = coreAssembly.GetReferencedAssemblies(); foreach (AssemblyName reference in referencedAssemblies) { string shortName = reference.GetShortAssemblyName(); Assembly dependency = loadedAssemblies.FirstOrDefault(a => a.GetShortAssemblyName() == shortName); if (dependency != null) selectableAssemblies.Add(dependency); } } this.assemblies = selectableAssemblies.ToArray(); this.namespaces = this.assemblies .SelectMany(a => { try { return a.GetExportedTypes(); } catch (Exception) { return new Type[0]; } }) .Select(t => t.Namespace) .Distinct() .Where(n => !string.IsNullOrEmpty(n)) .ToArray(); }
public int AddNewErrors(IVsEnumExternalErrors pErrors) { var projectErrors = new HashSet<DiagnosticData>(); var documentErrorsMap = new Dictionary<DocumentId, HashSet<DiagnosticData>>(); var errors = new ExternalError[1]; uint fetched; while (pErrors.Next(1, errors, out fetched) == VSConstants.S_OK && fetched == 1) { var error = errors[0]; DiagnosticData diagnostic; if (error.bstrFileName != null) { diagnostic = CreateDocumentDiagnosticItem(error); if (diagnostic != null) { var diagnostics = documentErrorsMap.GetOrAdd(diagnostic.DocumentId, _ => new HashSet<DiagnosticData>()); diagnostics.Add(diagnostic); continue; } projectErrors.Add(CreateProjectDiagnosticItem(error)); } else { projectErrors.Add(CreateProjectDiagnosticItem(error)); } } _diagnosticProvider.AddNewErrors(_projectId, projectErrors, documentErrorsMap); return VSConstants.S_OK; }
public void DiagnosticAnalyzerAllInOne() { var source = TestResource.AllInOneCSharpCode; // AllInOneCSharpCode has no properties with initializers or named types with primary constructors. var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>(); symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property); symbolKindsWithNoCodeBlocks.Add(SymbolKind.NamedType); var syntaxKindsMissing = new HashSet<SyntaxKind>(); // AllInOneCSharpCode has no deconstruction or declaration expression syntaxKindsMissing.Add(SyntaxKind.SingleVariableDesignation); syntaxKindsMissing.Add(SyntaxKind.ParenthesizedVariableDesignation); syntaxKindsMissing.Add(SyntaxKind.ForEachVariableStatement); syntaxKindsMissing.Add(SyntaxKind.DeclarationExpression); syntaxKindsMissing.Add(SyntaxKind.DiscardDesignation); var analyzer = new CSharpTrackingDiagnosticAnalyzer(); CreateCompilationWithMscorlib45(source).VerifyAnalyzerDiagnostics(new[] { analyzer }); analyzer.VerifyAllAnalyzerMembersWereCalled(); analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds(); analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(syntaxKindsMissing); analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks); }
public static List<int> GenerateRandom(int count, int min = 27560000, int max = 27569999) { if (max <= min || count < 0 || (count > max - min && max - min > 0)) { throw new ArgumentOutOfRangeException("Range or count " + count + " is illegal"); } HashSet<int> candidates = new HashSet<int>(); for (int top = max - count; top < max; top++) { if (!candidates.Add(random.Next(min, top + 1))) { candidates.Add(top); } } List<int> result = candidates.ToList(); for (int i = result.Count - 1; i > 0; i--) { int k = random.Next(i + 1); int tmp = result[k]; result[k] = result[i]; result[i] = tmp; } return result; }
/** Returns all nodes reachable from the seed node. * This function performs a BFS (breadth-first-search) or flood fill of the graph and returns all nodes which can be reached from * the seed node. In almost all cases this will be identical to returning all nodes which have the same area as the seed node. * In the editor areas are displayed as different colors of the nodes. * The only case where it will not be so is when there is a one way path from some part of the area to the seed node * but no path from the seed node to that part of the graph. * * The returned list is sorted by node distance from the seed node * i.e distance is measured in the number of nodes the shortest path from \a seed to that node would pass through. * Note that the distance measurement does not take heuristics, penalties or tag penalties. * * Depending on the number of reachable nodes, this function can take quite some time to calculate * so don't use it too often or it might affect the framerate of your game. * * \param seed The node to start the search from * \param tagMask Optional mask for tags. This is a bitmask. * * \returns A List<Node> containing all nodes reachable from the seed node. * For better memory management the returned list should be pooled, see Pathfinding.Util.ListPool */ public static List<GraphNode> GetReachableNodes (GraphNode seed, int tagMask = -1) { var stack = StackPool<GraphNode>.Claim (); var list = ListPool<GraphNode>.Claim (); /** \todo Pool */ var map = new HashSet<GraphNode>(); GraphNodeDelegate callback; if (tagMask == -1) { callback = delegate (GraphNode node) { if (node.Walkable && map.Add (node)) { list.Add (node); stack.Push (node); } }; } else { callback = delegate (GraphNode node) { if (node.Walkable && ((tagMask >> (int)node.Tag) & 0x1) != 0 && map.Add (node)) { list.Add (node); stack.Push (node); } }; } callback (seed); while (stack.Count > 0) { stack.Pop ().GetConnections (callback); } StackPool<GraphNode>.Release (stack); return list; }
public static BlockResource Create(BlockEntity2 blockEntity) { if (guidePaths == null) { guidePaths = new HashSet<string>(); guidePaths.Add("BlockGuide"); var blockTable = TableLoader.GetTable<BlockEntity2>(); var vfxTable = TableLoader.GetTable<VFXEntity>(); foreach (var entity in blockTable.Values) { VFXEntity res = vfxTable.Get(entity.chargeVFX1); if (res != null) { if (!guidePaths.Contains(res.resource)) { guidePaths.Add(res.resource); } } } } BlockResource blockResource = new GameObject(blockEntity.blockType.ToString()).AddComponent<BlockResource>(); blockResource.blockEntity = blockEntity; GameObject tileObj = CreateGameObject(blockEntity); tileObj.transform.parent = blockResource.transform; tileObj.transform.localPosition = Vector3.zero; return blockResource; }
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(); }
public bool IsValid(Color askedColor, out Color forbiddenColor, IEnumerable <Color> terrainColors, IEnumerable <Color> playerColors, HashSet <string> errorMessages = null) { // Validate color against HSV askedColor.ToAhsv(out _, out _, out var s, out var v); if (s < HsvSaturationRange[0] || s > HsvSaturationRange[1] || v <HsvValueRange[0] || v> HsvValueRange[1]) { errorMessages?.Add("Color was adjusted to be inside the allowed range."); forbiddenColor = askedColor; return(false); } // Validate color against the current map tileset if (!IsValid(askedColor, terrainColors, out forbiddenColor)) { errorMessages?.Add("Color was adjusted to be less similar to the terrain."); return(false); } // Validate color against other clients if (!IsValid(askedColor, playerColors, out forbiddenColor)) { errorMessages?.Add("Color was adjusted to be less similar to another player."); return(false); } // Color is valid forbiddenColor = default(Color); return(true); }
public HashSet<Action> actions(System.Object state) { EightPuzzleBoard board = (EightPuzzleBoard)state; HashSet<Action> actions = new HashSet<Action>(); if (board.canMoveGap(EightPuzzleBoard.UP)) { actions.Add(EightPuzzleBoard.UP); } if (board.canMoveGap(EightPuzzleBoard.DOWN)) { actions.Add(EightPuzzleBoard.DOWN); } if (board.canMoveGap(EightPuzzleBoard.LEFT)) { actions.Add(EightPuzzleBoard.LEFT); } if (board.canMoveGap(EightPuzzleBoard.RIGHT)) { actions.Add(EightPuzzleBoard.RIGHT); } return actions; }
private void PopulateTypeList(ITypeDescriptorContext context) { _typeList = new HashSet<string>(); if (context != null) { var propertyDescriptor = context.Instance as EFPropertyDescriptor; if (propertyDescriptor != null && propertyDescriptor.TypedEFElement != null) { var artifact = propertyDescriptor.TypedEFElement.Artifact; Debug.Assert(artifact != null, "Unable to find artifact."); if (artifact != null) { foreach (var primType in ModelHelper.AllPrimitiveTypesSorted(artifact.SchemaVersion)) { _typeList.Add(primType); } } var conceptualModel = (ConceptualEntityModel)propertyDescriptor.TypedEFElement.GetParentOfType(typeof(ConceptualEntityModel)); Debug.Assert(conceptualModel != null, "Unable to find conceptual model."); if (conceptualModel != null) { foreach (var enumType in conceptualModel.EnumTypes()) { _typeList.Add(enumType.NormalizedNameExternal); } } } } }
static void Main(string[] args) { Standard s1 = new Standard("ГОСТ Р 21.1101-2009"); Standard s2 = new Standard("ГОСТ", "2.101"); HashSet<Standard> sl1 = new HashSet<Standard>(); HashSet<Standard> sl2 = new HashSet<Standard>(); sl1.Add(s1); sl1.Add(s2); string[] test = { "tesT", "best", "rest" }; IEnumerable<string> tt = test.Take(test.Length - 1).ToList(); ConfigManager.ConfigManager cm = ConfigManager.ConfigManager.Instance; HashSet<Document> s1d = s1.Check(); Console.WriteLine(s1d.First()); string str = "333-ГОСТ--444"; Console.WriteLine(str.cleanAllWithWhiteList()); NormaCS ncs = new NormaCS(sl1); ncs.checkStandards(); ReportWindow.Main mn = new ReportWindow.Main(ncs.Documents); Application app = new Application(); app.Run(mn); }
public static TreeNode BuildTree(Color[,] board) { MapNode head = BuildMap(board); TreeNode root = new TreeNode(null, head.Color); Queue<MapTreeKeyValuePair> frontLine = new Queue<MapTreeKeyValuePair>(); ISet<MapNode> visited = new HashSet<MapNode>(); frontLine.Enqueue(new MapTreeKeyValuePair{MapNode = head, TreeNode = root}); visited.Add(head); while (frontLine.Count > 0) { MapTreeKeyValuePair mapTree = frontLine.Dequeue(); foreach (MapNode neighbor in mapTree.MapNode.GetNeighbors()) { if(!visited.Contains(neighbor)) { TreeNode childTreeNode = new TreeNode(mapTree.TreeNode, neighbor.Color); //Claim this map node as your child mapTree.TreeNode.AddChildern(childTreeNode); //mark map node as visited, no one can claim this map node again visited.Add(neighbor); //queue it up to find it's children frontLine.Enqueue(new MapTreeKeyValuePair { MapNode = neighbor, TreeNode = childTreeNode }); } } } return root; }
public ICollection<AuthorModel> GetRandomAuthors(int rightAuthorId) { var authorIds = this.data.Authors .All() .Select(a => a.Id) .ToList(); var randomAuthorIds = new HashSet<int>(); randomAuthorIds.Add(rightAuthorId); while (randomAuthorIds.Count() < GlobalConstants.NumberOfAuthorsToChoose) { var randomAuthorId = this.GetRandomAuthorId(authorIds); randomAuthorIds.Add(randomAuthorId); } var randomAuthors = this.data.Authors .All() .Where(a => randomAuthorIds.Contains(a.Id)) .OrderBy(a => a.FullName) .ProjectTo<AuthorModel>() .ToList(); return randomAuthors; }
/// <summary> /// Determines which methods can be proxied from /// the given <paramref name="baseType"/> and <paramref name="baseInterfaces"/>. /// </summary> /// <remarks>By default, only public virtual methods will be proxied.</remarks> /// <param name="baseType">The base class of the proxy type currently being generated.</param> /// <param name="baseInterfaces">The list of interfaces that the proxy must implement.</param> /// <returns>A list of <see cref="MethodInfo"/> objects that can be proxied.</returns> public IEnumerable<MethodInfo> ChooseProxyMethodsFrom(Type baseType, IEnumerable<Type> baseInterfaces) { var results = new HashSet<MethodInfo>(); var baseMethods = from method in baseType.GetMethods() where method.IsVirtual && !method.IsFinal && !method.IsPrivate select method; // Add the virtual methods defined // in the base type foreach (var method in baseMethods) { if (!results.Contains(method)) results.Add(method); } var interfaceMethods = from currentInterface in baseInterfaces from method in currentInterface.GetMethods() where method.IsPublic && method.IsVirtual && !method.IsFinal && !results.Contains(method) select method; // Add the virtual methods defined // in the interface types foreach (var method in interfaceMethods) { results.Add(method); } return results; }
/// <summary> /// Returns the CSS classes (if any) associated with the theme(s) of the content, as decided by its categories /// </summary> /// <param name="content"></param> /// <returns>CSS classes associated with the content's theme(s), or an empty string array if no theme is applicable</returns> /// <remarks>Content's categorization may map to more than one theme. This method assumes there are website categories called "Meet", "Track", and "Plan"</remarks> public static string[] GetThemeCssClassNames(this ICategorizable content) { if (content.Category == null) { return new string[0]; } var cssClasses = new HashSet<string>(); // Although with some overhead, a HashSet allows us to ensure we never add a CSS class more than once foreach (var categoryName in content.Category.Select(category => content.Category.GetCategoryName(category).ToLower())) { switch (categoryName) { case "meet": cssClasses.Add("theme1"); break; case "track": cssClasses.Add("theme2"); break; case "plan": cssClasses.Add("theme3"); break; } } return cssClasses.ToArray(); }
private static void DontModifyInner() { Console.WriteLine("\nMake a snapshot and add it to outer"); ICollection<ISequenced<int>> outer = new HashSet<ISequenced<int>>(); for (int i = 0; i < 100; i++) { ISequenced<int> inner = new TreeSet<int>(); inner.Add(i); inner.Add(i + 1); outer.Add(inner); } IPersistentSorted<int> inner1 = new TreeSet<int>(), inner2 = new TreeSet<int>(), inner3 = new TreeSet<int>(); inner1.AddAll(new[] { 2, 3, 5, 7, 11 }); inner2.AddAll(inner1); inner2.Add(13); inner3.AddAll(inner1); // Take a snapshot and add it to outer: outer.Add(inner1.Snapshot()); Console.WriteLine("inner1 in outer: {0}", outer.Contains(inner1)); Console.WriteLine("inner2 in outer: {0}", outer.Contains(inner2)); Console.WriteLine("inner3 in outer: {0}", outer.Contains(inner3)); inner1.Add(13); Console.WriteLine("inner1 equals inner2: {0}", outer.EqualityComparer.Equals(inner1, inner2)); Console.WriteLine("inner1 equals inner3: {0}", outer.EqualityComparer.Equals(inner1, inner3)); Console.WriteLine("inner1 in outer: {0}", outer.Contains(inner1)); Console.WriteLine("inner2 in outer: {0}", outer.Contains(inner2)); Console.WriteLine("inner3 in outer: {0}", outer.Contains(inner3)); Console.WriteLine("outer.Count: {0}", outer.Count); }
public List<Graph> ConnectedComponents() { List<Graph> ret = new List<Graph>(); HashSet<int> visited = new HashSet<int>(); Queue<int> queue = new Queue<int>(); ForEachVertex((v) => { if (!visited.Contains(v)) { Graph g = new Graph(); queue.Enqueue(v); visited.Add(v); while (queue.Count != 0) { int u = queue.Dequeue(); g.storage[u] = storage[u]; ForEachNeighbor(u, (w) => { if (!visited.Contains(w)) { queue.Enqueue(w); visited.Add(w); } }); } ret.Add(g); } }); return ret; }
public static HashSet<string> FindPermutations(string word) { if (word.Length == 2) { char[] _c = word.ToCharArray(); string s = new string(new char[] { _c[1], _c[0] }); return new HashSet<string> { word, s }; } var _result = new HashSet<string>(); var _subsetPermutations = FindPermutations(word.Substring(1)); char _firstChar = word[0]; foreach (string s in _subsetPermutations) { string _temp = _firstChar.ToString() + s; _result.Add(_temp); char[] _chars = _temp.ToCharArray(); for (int i = 0; i < _temp.Length - 1; i++) { char t = _chars[i]; _chars[i] = _chars[i + 1]; _chars[i + 1] = t; string s2 = new string(_chars); _result.Add(s2); } } return _result; }
private static void BFS(ref string[,] arr, AllowedCoords start) { var set = new Set<int>(); var queue = new Queue<AllowedCoords>(); var set = new HashSet<AllowedCoords>(); int depth = 1; queue.Enqueue(start); set.Add(start); while (queue.Count > 0) { var coords = queue.Dequeue(); if (arr[coords.Row, coords.Col] == "0") { arr[coords.Row, coords.Col] = depth.ToString(); } var neighbors = coords.GetAdjacent(); for (int i = 0; i < neighbors.Count; i++) { var coordinates = neighbors[i]; if (!set.Contains(coordinates)) { depth++; set.Add(coordinates); queue.Enqueue(coordinates); } } } }
public void AddDuplicateItemTest() { HashSet<string> names = new HashSet<string>(); names.Add("Pesho"); names.Add("Pesho"); }
private void AddAdditionalSpelling(string identifier, object value) { // Had a mapping for it. It will either map to a single // spelling, or to a set of spellings. if (value is string) { if (!string.Equals(identifier, value as string, StringComparison.Ordinal)) { // We now have two spellings. Create a collection for // that and map the name to it. var set = new HashSet<string>(); set.Add(identifier); set.Add((string)value); map[identifier] = set; } } else { // We have multiple spellings already. var spellings = value as HashSet<string>; // Note: the set will prevent duplicates. spellings.Add(identifier); } }
public IEnumerable<string> GetEdgesCsv(IEnumerable<OnergeDetay> onergeDetays) { // SOURCE_NODE_TYPE, SOURCE_NODE_NAME, EDGE_TYPE, TARGET_NODE_TYPE, TARGET_NODE_NAME, WEIGHT var quote = "\""; var nodes = new HashSet<string>(); int batchCount = 1; var ret = new StringBuilder(); foreach (var detay in onergeDetays) { if (nodes.Count + 3 >= batchCount * 500) { yield return ret.ToString(); batchCount++; ret.Clear(); } ret.AppendFormat("{0}, {1}, {2}, {3}, {4}, {5}\n", "Milletvekili", detay.OnergeninSahibi, "UYE", "Parti", detay.Parti, 1); ret.AppendFormat("{0}, {1}, {2}, {3}, {4}, {5}\n", "Milletvekili", detay.OnergeninSahibi, "SAHIP", "Soru Önergesi", detay.EsasNumarasi, 1); ret.AppendFormat("{0}, {1}, {2}, {3}, {4}, {5}\n", "Soru Önergesi", quote + detay.EsasNumarasi + quote, "MUHATAP", "Bakan", quote + detay.OnergeninMuhatabi + quote, 1); nodes.Add(detay.OnergeninSahibi); nodes.Add(detay.Parti); nodes.Add(detay.EsasNumarasi); nodes.Add(detay.OnergeninMuhatabi); } yield return ret.ToString(); }
static void Main(string[] args) { var deployments = new HashSet<Deployment>(); deployments.Add(new Deployment("WestEurope1")); deployments.Add(new Deployment("WestEurope2")); deployments.Add(new Deployment("CentraUS")); deployments.Add(new Deployment("EastAsia")); var storages = new HashSet<Storage>(); storages.Add(new Storage("WestEurope1")); storages.Add(new Storage("CentralUS")); storages.Add(new Storage("EastAsia")); var tasks = new List<Task>(); foreach (var deployment in deployments) { tasks.Add(Task.Run(() => deployment.ApiCalls())); tasks.Add(Task.Run(() => deployment.CpuLoads())); } foreach (var storage in storages) { tasks.Add(Task.Run(() => storage.StorageUsed())); } Task.WaitAll(tasks.ToArray()); }
/// <summary> /// Perform the necessary operations for a move, check liberties, capture, etc. Also /// updates the Move and IsLegal properties. /// </summary> /// <param name="x">The X coordinate of the move.</param> /// <param name="y">The Y coordinate of the move.</param> /// <returns>True if the move was legal.</returns> protected bool InternalMakeMove(int x, int y) { var legal = true; var oturn = Turn.Opposite(); if (Board[x, y] != Content.Empty) { legal = false; // Overwrite move } Board[x, y] = oturn; Move = new Point(x, y); var capturedGroups = Board.GetCapturedGroups(x, y); if (capturedGroups.Count == 0 && Board.GetLiberties(x, y) == 0) // Suicide move { _captures[Turn] += Board.Capture(Board.GetGroupAt(x, y)); legal = false; } else { _captures[oturn] += Board.Capture(capturedGroups.Where(p => p.Content == oturn.Opposite())); } if (_superKoSet?.Contains(Board) == true) // Violates super-ko { legal = false; } _superKoSet?.Add(Board); IsLegal = legal; return(legal); }
public List <Slide> GetSlides(List <Photo> photos) { var PhotosV = photos?.Where(x => !x.IsHorizontal).ToList(); var photosAlreadyPaired = new HashSet <Photo>(); var slides = photos?.Where(x => x.IsHorizontal) .Select(x => new Slide(x)) .ToList(); foreach (var photo in PhotosV) { if (photosAlreadyPaired.Contains(photo)) { continue; } for (var i = 0; i < photo?.Scores?.Count; i++) { if (!photosAlreadyPaired.Contains(photo?.Scores[i]?.Item1) && !(photo?.Scores[i]?.Item1 as Photo).IsHorizontal) { slides.Add(new Slide(photo, photo.Scores[i]?.Item1 as Photo)); photosAlreadyPaired?.Add(photo.Scores[i]?.Item1 as Photo); } } } return(slides); }
public void EnsurePathExists( string path, HashSet <string> createdDirectories, Action <string> beforeDirectoryCreatedCallback) { string parentPath = Path.GetDirectoryName(path); if (string.IsNullOrEmpty(parentPath)) { return; } PathBuilder parentPathBuilder = new PathBuilder(parentPath); parentPath = parentPathBuilder.ToUnixPath(); bool doesCreatedDirectoriesContainParentPath = createdDirectories != null && createdDirectories.Contains(parentPath); if (parentPath == "/" || doesCreatedDirectoriesContainParentPath) { return; } EnsurePathExists(parentPath, createdDirectories, beforeDirectoryCreatedCallback); beforeDirectoryCreatedCallback?.Invoke(parentPath); CreateDirectory(parentPath, false); createdDirectories?.Add(parentPath); }
private static bool AreValuesEqual( [NotNull] EqualFieldValuesCondition condition, [NotNull] IRow row1, int tableIndex1, [NotNull] IRow row2, int tableIndex2, [CanBeNull] out string message, [CanBeNull] HashSet <string> unequalFieldNames = null) { StringBuilder sb = null; foreach (UnequalField unequalField in condition.GetNonEqualFields( row1, tableIndex1, row2, tableIndex2)) { if (sb == null) { sb = new StringBuilder(); } sb.AppendFormat(sb.Length == 0 ? "{0}" : ";{0}", unequalField.Message); unequalFieldNames?.Add(unequalField.FieldName.ToUpper()); } if (sb != null) { message = sb.ToString(); return(false); } message = null; return(true); }
private void HandleWhitelistChanged(object transaction, HashSet <string> unbanList) { // if the whitelist changed, we have no choice but to loop the entire db to remove ip // this should not happen very often so not a problem if (whitelistChanged) { whitelistChanged = false; foreach (IPBanDB.IPAddressEntry ipAddress in ipDB.EnumerateIPAddresses(null, null, transaction)) { if (IsWhitelisted(ipAddress.IPAddress)) { if (ipAddress.State == IPBanDB.IPAddressState.Active) { Logger.Warn("Un-banning whitelisted ip address {0}", ipAddress.IPAddress); unbanList?.Add(ipAddress.IPAddress); DB.SetIPAddressesState(new string[] { ipAddress.IPAddress }, IPBanDB.IPAddressState.RemovePending, transaction); firewallNeedsBlockedIPAddressesUpdate = true; } else { Logger.Warn("Forgetting whitelisted ip address {0}", ipAddress.IPAddress); DB.DeleteIPAddress(ipAddress.IPAddress, transaction); } } } } }
private void Watch(INotifyPropertyChanged source, HashSet <INotifyPropertyChanged> toWatch) { lock (Watching) { if (!Watching.Contains(source)) { source.PropertyChanged += OnPropertyChanged; Watching.Add(source); } toWatch?.Add(source); var properties = source.GetType().GetProperties(); foreach (var property in properties) { if (typeof(INotifyPropertyChanged).IsAssignableFrom(property.PropertyType)) { var value = (INotifyPropertyChanged)property.GetValue(source, null); if (value != null) { Watch(value, toWatch); } } } } }
/// <summary> /// Update the AoiEntity /// </summary> /// <param name="key"></param> /// <param name="area"></param> /// <param name="enter"></param> /// <returns></returns> public AoiEntity UpdateIncludingMyself(long key, Vector2 area, out HashSet <long> enter) { var entity = Update(key, area, out enter); enter?.Add(key); return(entity); }
/// <summary> /// Refresh the AoiEntity /// </summary> /// <param name="key">key</param> /// <param name="x">X MinValue = -3.402823E+38f</param> /// <param name="y">Y MinValue = -3.402823E+38f</param> /// <param name="area">view</param> /// <param name="enter"></param> /// <returns></returns> public AoiEntity RefreshIncludingMyself(long key, float x, float y, Vector2 area, out HashSet <long> enter) { var entity = Refresh(key, x, y, area, out enter); enter?.Add(key); return(entity); }
private static bool HasUnequalFields( [NotNull] IEnumerable <UnequalField> unequalFields, [CanBeNull] out string message, [CanBeNull] HashSet <string> unequalFieldNames = null) { StringBuilder sb = null; foreach (UnequalField unequalField in unequalFields) { if (sb == null) { sb = new StringBuilder(); } sb.AppendFormat(sb.Length == 0 ? "{0}" : ";{0}", unequalField.Message); unequalFieldNames?.Add(unequalField.FieldName.ToUpper()); } if (sb != null) { message = sb.ToString(); return(true); } message = null; return(false); }
/// <summary> /// Get the names of the operations /// </summary> /// <param name="opNames">If provided, this HashSet will be filled with names of operations</param> /// <param name="potentialInputs">If provided, this HashSet will be filled with names of operations that may be a input operation.</param> /// <param name="potentialOutputs">If provided, this HashSet will be filled with names of operations that may be an output operation.</param> public void GetOpNames( HashSet <string> opNames = null, HashSet <string> potentialInputs = null, HashSet <string> potentialOutputs = null) { foreach (Operation op in this) { String name = op.Name; if (potentialInputs != null) { if (op.NumInputs == 0 && op.OpType.Equals("Placeholder")) { potentialInputs.Add(name); } } if (potentialOutputs != null) { foreach (Output output in op.Outputs) { int[] shape = GetTensorShape(output); if (output.NumConsumers == 0) { potentialOutputs.Add(name); } } } opNames?.Add(name); } }
internal void PrefetchCompositeRoleRelationTable(HashSet <Reference> associations, IRoleType roleType, HashSet <long> nestedObjectIds, HashSet <long> leafs) { var references = nestedObjectIds == null?this.FilterForPrefetchRoles(associations, roleType) : this.FilterForPrefetchCompositeRoles(associations, roleType, nestedObjectIds); if (references.Count == 0) { return; } Command command; if (!this.PrefetchCompositeRoleByRoleType.TryGetValue(roleType, out command)) { var sql = this.Database.Mapping.ProcedureNameForPrefetchRoleByRelationType[roleType.RelationType]; command = this.Session.Connection.CreateCommand(); command.CommandText = sql; command.CommandType = CommandType.StoredProcedure; command.AddObjectTableParameter(references); this.prefetchCompositeRoleByRoleType[roleType] = command; } else { command.Parameters[Mapping.ParamNameForTableType].Value = this.Database.CreateObjectTable(references); } var roleByAssociation = new Dictionary <Reference, long>(); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var associationId = reader.GetInt64(0); var associationReference = this.Session.State.ReferenceByObjectId[associationId]; var roleId = reader.GetInt64(1); roleByAssociation.Add(associationReference, roleId); } } var cache = this.Database.Cache; foreach (var reference in references) { var cachedObject = cache.GetOrCreateCachedObject(reference.Class, reference.ObjectId, reference.VersionId); long roleId; if (roleByAssociation.TryGetValue(reference, out roleId)) { cachedObject.SetValue(roleType, roleId); nestedObjectIds?.Add(roleId); if (nestedObjectIds == null) { leafs.Add(roleId); } } else { cachedObject.SetValue(roleType, null); } } }
private static void AfterUpdatePowerState_MarkPower(PhoenixFacilityController __instance) { try { lock ( MarkFacilities ) { PhoenixFacilityController me = __instance; GeoPhoenixFacility facility = me.Facility; if (facility == null || facility.IsWorking) { me.FacilityName.color = Color.white; me.RepairBuildContainer.SetActive(false); } else { me.FacilityName.color = Color.red; //Log.Info( "{0} {1}", facility.ViewElementDef.DisplayName1.Localize(), facility.State ); if (facility.State == GeoPhoenixFacility.FacilityState.Functioning && facility.CanBePowered && !facility.IsPowered) { me.RepairBuildContainer.SetActive(true); me.RepairBuildSlidingContainer.gameObject.SetActive(true); me.RepairBuildSlidingContainer.offsetMin = new Vector2(__instance.RepairBuildSlidingContainer.offsetMin.x, 0); me.RepairBuildText.enabled = true; me.RepairBuildText.GetComponent <Localize>().SetTerm("KEY_BASE_POWER_OFF"); } MarkFacilities?.Add(me); } } } catch (Exception ex) { Error(ex); } }
/// <summary> /// Builds a sub tree under root: target framework or Dependencies node when there is only one target. /// </summary> private async Task <IProjectTree> BuildSubTreeAsync( IProjectTree rootNode, TargetedDependenciesSnapshot targetedSnapshot, List <IDependency> dependencies, bool isActiveTarget, bool shouldCleanup) { HashSet <IProjectTree>?currentNodes = shouldCleanup ? new HashSet <IProjectTree>(capacity: dependencies.Count) : null; foreach (IDependency dependency in dependencies) { IProjectTree?dependencyNode = rootNode.FindChildWithCaption(dependency.Caption); bool isNewDependencyNode = dependencyNode == null; if (dependencyNode != null && dependency.Flags.Contains(DependencyTreeFlags.SupportsHierarchy)) { if ((dependency.Resolved && dependencyNode.Flags.Contains(DependencyTreeFlags.Unresolved)) || (!dependency.Resolved && dependencyNode.Flags.Contains(DependencyTreeFlags.Resolved))) { // when transition from unresolved to resolved or vise versa - remove old node // and re-add new one to allow GraphProvider to recalculate children isNewDependencyNode = true; rootNode = dependencyNode.Remove(); dependencyNode = null; } } // NOTE this project system supports multiple implicit configuration dimensions (such as target framework) // which is a concept not modelled by DTE/VSLangProj. In order to produce a sensible view of the project // via automation, we expose only the active target framework at any given time. // // This is achieved by using IProjectItemTree for active target framework items, and IProjectTree for inactive // target frameworks. CPS only creates automation objects for items with "Reference" flag if they implement // IProjectItemTree. See SimpleItemNode.Initialize (in CPS) for details. dependencyNode = await CreateOrUpdateNodeAsync( dependencyNode, dependency, targetedSnapshot, isProjectItem : isActiveTarget); currentNodes?.Add(dependencyNode); IProjectTree?parent = isNewDependencyNode ? rootNode.Add(dependencyNode).Parent : dependencyNode.Parent; Assumes.NotNull(parent); rootNode = parent !; } return(currentNodes != null // shouldCleanup ? CleanupOldNodes(rootNode, currentNodes) : rootNode); }
public void JoinRoom(string newRoomName) { string proxyUrl = $"{serverAddress}/api/user/{loginModel.MyUserId}/joinRoom?roomName={newRoomName}"; //StringContent content = new StringContent($"\"{message}\"", Encoding.UTF8, "application/json"); Task dummy = this.httpClient.PutAsync(proxyUrl, null); joindedRooms?.Add(newRoomName); SelectedRoomName = newRoomName; }
private static ExpressionSyntax EnumValue(Type t, object value, HashSet <string> usings) { usings?.Add(t.Namespace); var valName = Enum.GetName(t, value); return(SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName(t.Name), SyntaxFactory.IdentifierName(valName))); }
internal void PrefetchCompositeAssociationObjectTable(HashSet <Reference> roles, IAssociationType associationType, HashSet <long> nestedObjectIds, HashSet <long> leafs) { var references = nestedObjectIds == null?this.FilterForPrefetchAssociations(roles, associationType) : this.FilterForPrefetchCompositeAssociations(roles, associationType, nestedObjectIds); if (references.Count == 0) { return; } if (!this.PrefetchCompositeAssociationByAssociationType.TryGetValue(associationType, out var command)) { var roleType = associationType.RoleType; var sql = this.Database.Mapping.ProcedureNameForPrefetchAssociationByRelationType[roleType.RelationType]; command = this.Session.Connection.CreateCommand(); command.CommandText = sql; command.CommandType = CommandType.StoredProcedure; command.AddObjectTableParameter(references); this.prefetchCompositeAssociationByAssociationType[associationType] = command; } else { command.Parameters[Mapping.ParamNameForTableType].Value = this.Database.CreateObjectTable(references); } using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var roleId = reader.GetInt64(1); var role = this.Session.State.ReferenceByObjectId[roleId]; var associationByRole = this.Session.State.GetAssociationByRole(associationType); if (!associationByRole.ContainsKey(role)) { var associationIdValue = reader[0]; Reference association = null; if (associationIdValue != null && associationIdValue != DBNull.Value) { var associationId = (long)associationIdValue; association = associationType.ObjectType.ExistExclusiveClass ? this.Session.State.GetOrCreateReferenceForExistingObject(associationType.ObjectType.ExclusiveClass, associationId, this.Session) : this.Session.State.GetOrCreateReferenceForExistingObject(associationId, this.Session); nestedObjectIds?.Add(association.ObjectId); if (nestedObjectIds == null) { leafs.Add(associationId); } } associationByRole[role] = association; this.Session.FlushConditionally(roleId, associationType); } } } }
/// <summary> /// Method to check a GetCapabilities request URL for completeness and valididity /// </summary> /// <param name="query">The query part of the request URL</param> /// <param name="parameters"> /// An optional set that stores the supplied parameters. /// All encountered parameters are added to the set. /// This set can be used to later supply missing values /// </param> /// <returns><value>true</value>If the request string contains all mandatory parameters</returns> /// <exception cref="ArgumentException">Thrown if supplied</exception> internal static bool ValidateGetCapabilitiesRequest(string query, HashSet <string> parameters = null) { var flag = 0; var posQuestion = query.IndexOf("?", StringComparison.OrdinalIgnoreCase); if (posQuestion > -1) { foreach (var parameter in query.Substring(posQuestion + 1).Split('&')) { var kvp = parameter.ToUpperInvariant().Split('='); parameters?.Add(kvp[0]); switch (kvp[0]) { case "SERVICE": if (kvp[1] != "WMS") { throw new ArgumentException( $"Wrong service name ('{parameter.Substring(kvp[0].Length + 1)}')", nameof(query)); } flag |= 1; break; case "VERSION": switch (kvp[1]) { case "1.0.0": case "1.0.7": case "1.1.0": case "1.1.1": case "1.3": case "1.3.0": flag |= 2; continue; } throw new ArgumentException( $"Invalid version for WMS ('{parameter.Substring(kvp[0].Length + 1)}')", nameof(query)); case "REQUEST": if (kvp[1] != "GETCAPABILITIES") { throw new ArgumentException( $"Wrong operation name for GetCapabilities ('{parameter.Substring(kvp[0].Length + 1)}')", nameof(query)); } flag |= 4; break; } } } return(flag == 7); }
private void HandleExpiredLoginsAndBans(DateTime failLoginCutOff, DateTime banCutOff, object transaction, HashSet <string> unbanList) { TimeSpan[] banTimes = Config.BanTimes; // fast query into database for entries that should be deleted due to un-ban or forgetting failed logins foreach (IPBanDB.IPAddressEntry ipAddress in ipDB.EnumerateIPAddresses(failLoginCutOff, banCutOff, transaction)) { // never un-ban a blacklisted entry if (Config.IsBlackListed(ipAddress.IPAddress) && !Config.IsWhitelisted(ipAddress.IPAddress)) { Logger.Debug("Not unbanning blacklisted ip {0}", ipAddress.IPAddress); continue; } // if ban duration has expired, un-ban, check this first as these must trigger a firewall update else if (ipAddress.State == IPBanDB.IPAddressState.Active && ipAddress.BanStartDate != null && ipAddress.BanEndDate != null) { // check gap of ban end date vs ban date and see where we are in the ban times, if we have gone beyond the last ban time, // we need to unban the ip address and remove from db, otherwise the ban end date needs to be increased to the next ban interval and // the ip address needs to be unbanned but turn back into a failed login TimeSpan span = ipAddress.BanEndDate.Value - ipAddress.BanStartDate.Value; int i = banTimes.Length; firewallNeedsBlockedIPAddressesUpdate = true; unbanList?.Add(ipAddress.IPAddress); // if more than one ban time, we have tiered ban times where the ban time increases if (banTimes.Length > 1) { for (i = 0; i < banTimes.Length; i++) { if (span < banTimes[i]) { // this is the next span to ban Logger.Info("Ban duration {0} at index {1} expired for ip {2}", banTimes[i], i, ipAddress); break; } } } if (i < banTimes.Length) { Logger.Warn("Preparing ip address {0} for next ban time {1}", ipAddress.IPAddress, banTimes[i]); ipDB.SetIPAddressesState(new string[] { ipAddress.IPAddress }, IPBanDB.IPAddressState.RemovePendingBecomeFailedLogin, transaction); } else { Logger.Warn("Un-banning ip address {0}, ban expired", ipAddress.IPAddress); ipDB.SetIPAddressesState(new string[] { ipAddress.IPAddress }, IPBanDB.IPAddressState.RemovePending, transaction); } } // if fail login has expired, remove ip address from db else if (ipAddress.State == IPBanDB.IPAddressState.FailedLogin) { Logger.Warn("Forgetting failed login ip address {0}, time expired", ipAddress.IPAddress); DB.DeleteIPAddress(ipAddress.IPAddress, transaction); } } }
public ICommandProcedure OpenCommand(string commandName, params string[] args) { lock (openCommandLock) { var commandProcedure = new CommandProcedure(commandName, args); commandProcedure.Disposed += CommandProcedure_Disposed; notDisposeds?.Add(commandProcedure); return(commandProcedure); } }
internal void PrefetchCompositeRoleObjectTable(HashSet <Reference> associations, IRoleType roleType, HashSet <long> nestedObjectIds, HashSet <long> leafs) { var references = nestedObjectIds == null?this.FilterForPrefetchRoles(associations, roleType) : this.FilterForPrefetchCompositeRoles(associations, roleType, nestedObjectIds); if (references.Count == 0) { return; } if (!this.PrefetchCompositeRoleByRoleType.TryGetValue(roleType, out var command)) { command = this.Session.Connection.CreateCommand(); command.CommandText = this.Database.Mapping.ProcedureNameForPrefetchRoleByRelationType[roleType.RelationType]; command.CommandType = CommandType.StoredProcedure; command.AddObjectTableParameter(references); this.prefetchCompositeRoleByRoleType[roleType] = command; } else { command.Parameters[Mapping.ParamNameForTableType].Value = this.Database.CreateObjectTable(references); } using (DbDataReader reader = command.ExecuteReader()) { var cache = this.Database.Cache; while (reader.Read()) { var associationId = reader.GetInt64(0); var associationReference = this.Session.State.ReferenceByObjectId[associationId]; var cachedObject = cache.GetOrCreateCachedObject(associationReference.Class, associationId, associationReference.Version); var roleIdValue = reader[1]; if (roleIdValue == null || roleIdValue == DBNull.Value) { cachedObject.SetValue(roleType, null); } else { var roleId = (long)roleIdValue; cachedObject.SetValue(roleType, roleId); nestedObjectIds?.Add(roleId); if (nestedObjectIds == null) { leafs.Add(roleId); } } } } }
private static void AddTopLevelType( HashSet <string> names, Cci.INamespaceTypeDefinition type ) { names?.Add( MetadataHelpers.BuildQualifiedName( type.NamespaceName, Cci.MetadataWriter.GetMangledName(type) ) ); }
string CreateFolder(string folderName, string[] assetNames, HashSet<object> guids = null) { var path = GetPath(folderName); Directory.CreateDirectory(path); foreach (var a in assetNames) { var guid = a.EndsWith(".unity") ? CreateScene(Path.Combine(path, a)) : CreateAsset(a, Path.Combine(path, a)); guids?.Add(guid); } AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); return AssetDatabase.AssetPathToGUID(path); }
protected void AddPutResult(DocumentsStorage.PutOperationResults putResult) { LastChangeVector = putResult.ChangeVector; ModifiedCollections?.Add(putResult.Collection.Name); // Make sure all the metadata fields are always been add var putReply = new DynamicJsonValue { ["Type"] = nameof(CommandType.PUT), [Constants.Documents.Metadata.Id] = putResult.Id, [Constants.Documents.Metadata.Collection] = putResult.Collection.Name, [Constants.Documents.Metadata.ChangeVector] = putResult.ChangeVector, [Constants.Documents.Metadata.LastModified] = putResult.LastModified }; if (putResult.Flags != DocumentFlags.None) { putReply[Constants.Documents.Metadata.Flags] = putResult.Flags; } Reply.Add(putReply); }
/********* ** Private methods *********/ /// <summary>Parse the input arguments if valid.</summary> /// <param name="input">The input arguments.</param> /// <param name="playerIds">The parsed player IDs to populate, if any.</param> /// <param name="error">The error indicating why the input is invalid, if applicable.</param> /// <returns>Returns whether the input is valid.</returns> private bool TryParseInput(IInputArguments input, HashSet <long>?playerIds, [NotNullWhen(false)] out string?error) { foreach (string arg in input.PositionalArgs) { if (long.TryParse(arg, out long playerId)) { playerIds?.Add(playerId); } else if (Enum.TryParse(arg, ignoreCase: true, out PlayerType type)) { switch (type) { case PlayerType.HostPlayer: playerIds?.Add(this.HostPlayerId); break; case PlayerType.CurrentPlayer: playerIds?.Add(this.LocalPlayerId); break; case PlayerType.AnyPlayer: playerIds?.AddMany(this.Values.Keys); break; default: throw new InvalidOperationException($"Unknown player type {type}."); } } else { error = $"invalid input arguments ({input.TokenString}) for {this.Name} token, expected any combination of '{string.Join("', '", Enum.GetNames(typeof(PlayerType)))}', or player IDs."; return(false); } } error = null; return(true); }
void CreateAndAddScenesToEditorBuildSettings(string scenePrefix, int count, HashSet<object> guids = null) { var sceneList = new List<EditorBuildSettingsScene>(); for (int i = 0; i < count; i++) { var path = GetPath($"{scenePrefix}{i}.unity"); var scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, i == 0 ? NewSceneMode.Single : NewSceneMode.Additive); EditorSceneManager.SaveScene(scene, path); var guid = AssetDatabase.AssetPathToGUID(path); guids?.Add(guid); sceneList.Add(new EditorBuildSettingsScene(path, true)); } EditorBuildSettings.scenes = sceneList.ToArray(); }
public ICommandProcedure OpenCommand(string commandName, params string[] args) { lock (openCommandLock) { var commandProcedure = new CommandProcedure() { FileName = commandName, Arguments = string.Join(" ", args) }; commandProcedure.InitializeAdbEnvironment(this.adbClientDir, this.adbPort); commandProcedure.Disposed += CommandProcedure_Disposed; notDisposeds?.Add(commandProcedure); return(commandProcedure); } }
/// <returns>true if only part of the solution was processed and the method needs to be called again, false if all done</returns> public bool Generate(HashSet <string> processedAssemblyList = null, Folder <Project> solutionExplorerRoot = null) { if (solution == null) { // we failed to open the solution earlier; just return Log.Message("Solution is null: " + this.ProjectFilePath); return(false); } var allProjects = solution.Projects.ToArray(); if (allProjects.Length == 0) { Log.Exception("Solution " + this.ProjectFilePath + " has 0 projects - this is suspicious"); } var projectsToProcess = allProjects .Where(p => processedAssemblyList == null || !processedAssemblyList.Contains(p.AssemblyName)) .ToArray(); var currentBatch = projectsToProcess .ToArray(); foreach (var project in currentBatch) { try { CurrentAssemblyName = project.AssemblyName; var generator = new ProjectGenerator(this, project); generator.Generate().GetAwaiter().GetResult(); File.AppendAllText(Paths.ProcessedAssemblies, project.AssemblyName + Environment.NewLine, Encoding.UTF8); processedAssemblyList?.Add(project.AssemblyName); } finally { CurrentAssemblyName = null; } } new TypeScriptSupport().Generate(typeScriptFiles, SolutionDestinationFolder); AddProjectsToSolutionExplorer( solutionExplorerRoot, currentBatch); return(currentBatch.Length < projectsToProcess.Length); }
public bool Apply(HashSet <object> appliedSetters) { if (predicate(element)) { foreach (var setter in actor) { setter.Set(); appliedSetters?.Add(setter.Key); } return(true); } else { return(false); } }
// deletedEnumDefines 现在只能用于 var 本身,没有被其他地方引用,所以最多只返回一个。 // deletedBeanDefines 可能多个,也可能是其他配置文件里面的定义。 public void Delete(HashSet <BeanDefine> deletedBeanDefines, HashSet <EnumDefine> deletedEnumDefines) { if (null != Self) { Self.ParentNode.RemoveChild(Self); } var enumDefine = Parent.GetEnumDefine(Name); if (null != enumDefine) { enumDefine.Delete(); deletedEnumDefines?.Add(enumDefine); } Parent.RemoveVariable(this); Reference?.RemoveReferenceFrom(this, deletedBeanDefines, deletedEnumDefines); Parent.Document.IsChanged = true; }