private static ISet<Block> GetAll(Block initial, Func<Block, IEnumerable<Block>> getNexts) { var toProcess = new Queue<Block>(); var alreadyProcesses = new HashSet<Block>(); getNexts(initial).ToList().ForEach(b => toProcess.Enqueue(b)); while (toProcess.Count != 0) { var current = toProcess.Dequeue(); if (alreadyProcesses.Contains(current)) { continue; } alreadyProcesses.Add(current); getNexts(current).ToList().ForEach(b => toProcess.Enqueue(b)); } return alreadyProcesses.ToImmutableHashSet(); }
private IImmutableSet <ISymbol> ReadWhitelist() { var query = from additionalFile in AnalyzerOptions.AdditionalFiles where StringComparer.Ordinal.Equals(Path.GetFileName(additionalFile.Path), ImmutableTypesFileName) let sourceText = additionalFile.GetText(CancellationToken) where sourceText != null from line in sourceText.Lines let text = line.ToString() where !string.IsNullOrWhiteSpace(text) select text; var entries = query.ToList(); entries.Add("System.Guid"); entries.Add("System.TimeSpan"); entries.Add("System.DateTimeOffset"); entries.Add("System.Uri"); entries.Add("System.Nullable`1"); entries.Add("System.Collections.Generic.KeyValuePair`2"); var result = new HashSet <ISymbol>(SymbolEqualityComparer.Default); foreach (var entry in entries) { var symbols = DocumentationCommentId.GetSymbolsForDeclarationId($"T:{entry}", Compilation); if (symbols.IsDefaultOrEmpty) { continue; } foreach (var symbol in symbols) { result.Add(symbol); } } return(result.ToImmutableHashSet(SymbolEqualityComparer.Default)); }
public static ImmutableHashSet <Member> PickHighestPriority(IEnumerable <Member> a, IEnumerable <Member> b) { // group all members by Address => Seq[Member] var groupedByAddress = (a.Concat(b)).GroupBy(x => x.UniqueAddress); var acc = new HashSet <Member>(); foreach (var g in groupedByAddress) { if (g.Count() == 2) { acc.Add(HighestPriorityOf(g.First(), g.Skip(1).First())); } else { var m = g.First(); if (!Gossip.RemoveUnreachableWithMemberStatus.Contains(m.Status)) { acc.Add(m); } } } return(acc.ToImmutableHashSet()); }
internal void CalculateLiveSpan() { SIns = new List <Set>(new Set[List.Count]); VIns = new List <Set>(new Set[List.Count]); SOuts = new List <Set>(new Set[List.Count]); VOuts = new List <Set>(new Set[List.Count]); while (true) { var node = List.Last; for (int i = List.Count - 1; node != null; i--, node = node.Previous) { Assembly ins = node.Value; if (ins.OPCode == "ret") { ins.SOut = ins.SUse; } SIns[i] = ins.SIn; SOuts[i] = ins.SOut; ins.SIn = ins.SUse.Union(ins.SOut.Except(ins.SDef)); if (ins.OPCode != "ret") { HashSet <string> tempSIn = new HashSet <string>(); foreach (var assembly in ins.Successor) { tempSIn.UnionWith(assembly.SIn); } ins.SOut = tempSIn.ToImmutableHashSet(); } } bool pass = true; node = List.First; for (int i = 0; node != null; i++, node = node.Next) { if (!SIns[i].SetEquals(node.Value.SIn)) { pass = false; break; } } if (!pass) { continue; } node = List.First; for (int i = 0; node != null; i++, node = node.Next) { if (!SOuts[i].SetEquals(node.Value.SOut)) { pass = false; break; } } if (!pass) { continue; } break; } while (true) { var node = List.Last; for (int i = List.Count - 1; node != null; i--, node = node.Previous) { Assembly ins = node.Value; if (ins.OPCode == "ret") { ins.VOut = ins.VUse; } VIns[i] = ins.VIn; VOuts[i] = ins.VOut; ins.VIn = ins.VUse.Union(ins.VOut.Except(ins.VDef)); if (ins.OPCode != "ret") { HashSet <string> tempVIn = new HashSet <string>(); foreach (var assembly in ins.Successor) { tempVIn.UnionWith(assembly.VIn); } ins.VOut = tempVIn.ToImmutableHashSet(); } } bool pass = true; node = List.First; for (int i = 0; node != null; i++, node = node.Next) { if (!VIns[i].SetEquals(node.Value.VIn)) { pass = false; break; } } if (!pass) { continue; } node = List.First; for (int i = 0; node != null; i++, node = node.Next) { if (!VOuts[i].SetEquals(node.Value.VOut)) { pass = false; break; } } if (!pass) { continue; } break; } }
/// <summary> /// Moves the entity to the specified location with collision. /// </summary> /// <remarks> /// This always assumes that after moving entities by their MTVs they won't escape the NEARBY_BOUNDS, but /// if isLargeMovement is true it recalculates EntityNearbyIds from loc rather than reusing the existing /// one. /// </remarks> /// <param name="world">The world</param> /// <param name="entity">The entity to move</param> /// <param name="loc">The desired location of the entity</param> /// <param name="isLargeMovement">If the entity might intersect entities that aren't in its EntityNearbyIds</param> /// <returns>The entity after attempting to move it to loc</returns> public static Entity DoMoveEntity(MutatingWorld world, Entity entity, Vector2 loc, Stopwatch watch, bool isLargeMovement = false) { loc.X = Math.Min(Math.Max(loc.X, 0), world.Width - entity.Attributes.Bounds.AABB.Width); loc.Y = Math.Min(Math.Max(loc.Y, 0), world.Height - entity.Attributes.Bounds.AABB.Height); int entId = entity.ID; HashSet <int> ignoreIds = null; IEnumerable <int> potentialCollisionIds; if (isLargeMovement) { var potColIds = new ConcurrentQueue <int>(); Parallel.ForEach(world.Entities, (value, pls, index) => { if (value.Key != entId && Rect2.Intersects(value.Value.Attributes.Bounds.AABB, NEARBY_BOUNDS, value.Value.Location, loc, true)) { potColIds.Enqueue(value.Key); } }); potentialCollisionIds = potColIds; } else { potentialCollisionIds = entity.NearbyEntityIds; } watch.Start(); while (true) { int collidingId = -1; Tuple <Vector2, float> collidingMTV = null; foreach (var potentialCollidingEntityID in potentialCollisionIds) { var potentialCollidingEntity = world.Entities[potentialCollidingEntityID]; if (potentialCollidingEntity.ID != entId && (ignoreIds == null || !ignoreIds.Contains(potentialCollidingEntity.ID))) { if (!Rect2.Intersects(entity.Attributes.Bounds.AABB, potentialCollidingEntity.Attributes.Bounds.AABB, entity.Location, potentialCollidingEntity.Location, true)) { continue; } var mtv = Polygon2.IntersectMTV(entity.Attributes.Bounds, potentialCollidingEntity.Attributes.Bounds, loc, potentialCollidingEntity.Location); if (mtv != null) { collidingId = potentialCollidingEntity.ID; collidingMTV = mtv; break; } } } ; if (collidingMTV != null) { if (ignoreIds == null) { ignoreIds = new HashSet <int>(new[] { collidingId }); } else { ignoreIds.Add(collidingId); } loc += collidingMTV.Item1 * collidingMTV.Item2; } else { break; } } watch.Stop(); var elapsed = watch.ElapsedMilliseconds; if (elapsed > 2) { Console.WriteLine($"Took a long time to resolve collisions: {elapsed} ms"); } watch.Start(); var nearbyIds = new HashSet <int>(); var keys = new List <int>(world.Entities.Keys); foreach (var id in keys) { var e = world.Entities[id]; if (e.ID != entId && Rect2.Intersects(e.Attributes.Bounds.AABB, NEARBY_BOUNDS, e.Location, loc, true)) { nearbyIds.Add(e.ID); } } foreach (var oldNearby in entity.NearbyEntityIds) { if (!nearbyIds.Contains(oldNearby)) { Entity oldEnt; if (world.Entities.TryGetValue(oldNearby, out oldEnt)) { world.Entities[oldNearby] = new Entity(oldEnt, nearby: (Maybe <ImmutableHashSet <int> >)oldEnt.NearbyEntityIds.Remove(entId)); } } } foreach (var nearby in nearbyIds) { var ent = world.Entities[nearby]; if (!ent.NearbyEntityIds.Contains(entId)) { world.Entities[nearby] = new Entity(ent, nearby: (Maybe <ImmutableHashSet <int> >)ent.NearbyEntityIds.Add(entId)); } } watch.Stop(); elapsed = watch.ElapsedMilliseconds; if (elapsed > 3) { Console.WriteLine($"Took a long time to update nearby: {elapsed} ms"); } return(new Entity(entity, location: loc, nearby: (Maybe <ImmutableHashSet <int> >)nearbyIds.ToImmutableHashSet())); }
public void ForkStateReferences(int branchPointIndex) { Address address1 = Fx.Address1; Address address2 = Fx.Address2; Block <DumbAction> prevBlock = Fx.Block3; Guid targetChainId = Guid.NewGuid(); Transaction <DumbAction> tx1 = Fx.MakeTransaction( new List <DumbAction>(), new HashSet <Address> { address1 }.ToImmutableHashSet()); Transaction <DumbAction> tx2 = Fx.MakeTransaction( new List <DumbAction>(), new HashSet <Address> { address2 }.ToImmutableHashSet()); var txs1 = new[] { tx1 }; var blocks = new List <Block <DumbAction> > { TestUtils.MineNext(prevBlock, txs1), }; blocks.Add(TestUtils.MineNext(blocks[0], txs1)); blocks.Add(TestUtils.MineNext(blocks[1], txs1)); HashSet <Address> updatedAddresses; foreach (Block <DumbAction> block in blocks) { updatedAddresses = new HashSet <Address> { address1 }; Fx.Store.StoreStateReference( Fx.StoreChainId, updatedAddresses.ToImmutableHashSet(), block.Hash, block.Index ); } var txs2 = new[] { tx2 }; blocks.Add(TestUtils.MineNext(blocks[2], txs2)); updatedAddresses = new HashSet <Address> { address2 }; Fx.Store.StoreStateReference( Fx.StoreChainId, updatedAddresses.ToImmutableHashSet(), blocks[3].Hash, blocks[3].Index ); var branchPoint = blocks[branchPointIndex]; Fx.Store.ForkStateReferences( Fx.StoreChainId, targetChainId, branchPoint); var actual = Fx.Store.LookupStateReference( Fx.StoreChainId, address1, blocks[3]); Assert.Equal( Tuple.Create(blocks[2].Hash, blocks[2].Index), Fx.Store.LookupStateReference(Fx.StoreChainId, address1, blocks[3])); Assert.Equal( Tuple.Create(blocks[3].Hash, blocks[3].Index), Fx.Store.LookupStateReference(Fx.StoreChainId, address2, blocks[3])); Assert.Equal( Tuple.Create(blocks[branchPointIndex].Hash, blocks[branchPointIndex].Index), Fx.Store.LookupStateReference(targetChainId, address1, blocks[3])); Assert.Null( Fx.Store.LookupStateReference(targetChainId, address2, blocks[3])); }
public Hangman(string word) { HashSet <char> emptySetOfChars = new HashSet <char>(); var stateSubject = new BehaviorSubject <HangmanState>(new HangmanState(MaskedWord(word, emptySetOfChars), emptySetOfChars.ToImmutableHashSet(), MaxGuessCount)); StateObservable = stateSubject; GuessObserver = Observer.Create <char>(x => { HashSet <char> guessedChars = new HashSet <char>(stateSubject.Value.GuessedChars); bool isHit = !guessedChars.Contains(x) && word.Contains(x); guessedChars.Add(x); string maskedWord = MaskedWord(word, guessedChars); if (maskedWord == word) { stateSubject.OnCompleted(); } else if (stateSubject.Value.RemainingGuesses < 1) { stateSubject.OnError(new TooManyGuessesException()); } else { stateSubject.OnNext(new HangmanState(maskedWord, guessedChars.ToImmutableHashSet(), isHit ? stateSubject.Value.RemainingGuesses : stateSubject.Value.RemainingGuesses - 1)); } }); }
internal BlockChain <T> Fork(HashDigest <SHA256> point) { var forked = new BlockChain <T>(Policy, Store, Guid.NewGuid()); string id = Id.ToString(); string forkedId = forked.Id.ToString(); try { _rwlock.EnterReadLock(); foreach (var index in Store.IterateIndex(id)) { Store.AppendIndex(forkedId, index); if (index.Equals(point)) { break; } } Block <T> pointBlock = Blocks[point]; var addressesToStrip = new HashSet <Address>(); var signersToStrip = new Dictionary <Address, int>(); for ( Block <T> block = Tip; block.PreviousHash is HashDigest <SHA256> hash && !block.Hash.Equals(point); block = Blocks[hash]) { ImmutableHashSet <Address> addresses = Store.GetBlockStates(block.Hash) .Select(kv => kv.Key) .ToImmutableHashSet(); addressesToStrip.UnionWith(addresses); IEnumerable <(Address, int)> signers = block .Transactions .GroupBy(tx => tx.Signer) .Select(g => (g.Key, g.Count())); foreach ((Address address, int txCount) in signers) { int existingValue = 0; signersToStrip.TryGetValue(address, out existingValue); signersToStrip[address] = existingValue + txCount; } } Store.ForkStateReferences( id, forked.Id.ToString(), pointBlock, addressesToStrip.ToImmutableHashSet()); foreach (KeyValuePair <Address, long> pair in Store.ListTxNonces(id)) { Address address = pair.Key; long existingNonce = pair.Value; long txNonce = existingNonce; int staleTxCount = 0; if (signersToStrip.TryGetValue(address, out staleTxCount)) { txNonce -= staleTxCount; } if (txNonce < 0) { throw new InvalidOperationException( $"A tx nonce for {address} in the store seems broken.\n" + $"Existing tx nonce: {existingNonce}\n" + $"# of stale transactions: {staleTxCount}\n" ); } // Note that at this point every address has tx nonce = 0 // it's merely "setting" rather than "increasing." Store.IncreaseTxNonce(forkedId, address, txNonce); } } finally { _rwlock.ExitReadLock(); } return(forked); }
public AnalysisResult ToResult() { var documentIds = _lazySet == null ? ImmutableHashSet <DocumentId> .Empty : _lazySet.ToImmutableHashSet(); var syntaxLocals = Convert(_lazySyntaxLocals); var semanticLocals = Convert(_lazySemanticLocals); var nonLocals = Convert(_lazyNonLocals); var others = _lazyOthers == null ? ImmutableArray <DiagnosticData> .Empty : _lazyOthers.ToImmutableArray(); return(new AnalysisResult(_project.Id, _version, syntaxLocals, semanticLocals, nonLocals, others, documentIds, fromBuild: false)); }
public void Apply(MutatingWorld world) { var watch = new Stopwatch(); watch.Start(); var spawnBounds = SpawnBounds; var team = Team; if (team == -1) { MutatingTeam teamObj = null; foreach (var teamkvp in world.Teams) { if (teamObj == null || teamkvp.Value.Members.Count < teamObj.Members.Count) { team = teamkvp.Key; teamObj = teamkvp.Value; } } world.Teams[team].LastSpawnTimeMS = world.Timestamp; spawnBounds = world.Teams[team].SpawnRect; } Vector2 spawnLoc; while (true) { spawnLoc = new Vector2( (float)(spawnBounds.Min.X + world.RandomGen.NextDouble() * spawnBounds.Width), (float)(spawnBounds.Min.Y + world.RandomGen.NextDouble() * spawnBounds.Height)); var alreadyCollidedIds = new HashSet <int>(); var done = true; while (true) { var inter = world.Entities.Select((e) => Tuple.Create(e, Polygon2.IntersectMTV(e.Value.Attributes.Bounds, Attributes.Bounds, e.Value.Location, spawnLoc))).FirstOrDefault((tup) => tup.Item2 != null); if (inter != null) { if (alreadyCollidedIds.Contains(inter.Item1.Key)) { break; } alreadyCollidedIds.Add(inter.Item1.Key); spawnLoc += inter.Item2.Item1 * (inter.Item2.Item2 * 1.1f); done = false; } else { break; } } if (done) { break; } } var entId = world.IDCounter++; var nearbyBounds = Logic.NEARBY_BOUNDS; var nearby = new HashSet <int>(); foreach (var kvp in world.Entities) { if (Rect2.Intersects(kvp.Value.Attributes.Bounds.AABB, nearbyBounds, kvp.Value.Location, spawnLoc, true)) { nearby.Add(kvp.Key); } } foreach (var id in nearby) { var e = world.Entities[id]; world.Entities[id] = new Entity(e, nearby: (Maybe <ImmutableHashSet <int> >)e.NearbyEntityIds.Add(entId)); } var ent = new Entity(entId, team, Name, Attributes, spawnLoc, Vector2.Zero, Attributes.MaxHealth, Attributes.MaxMana, null, ImmutableDictionary.Create <int, int>(), nearby.ToImmutableHashSet(), ImmutableList <IModifier> .Empty); world.Add(ent); world.FinishedCallbacks.Add(() => Callback?.Invoke(ent)); watch.Stop(); var elapsedMS = watch.ElapsedMilliseconds; if (elapsedMS > 2) { Console.WriteLine($"Took a long time to spawn new entity! ({elapsedMS} ms)"); } }
/// <summary> /// Deserialises settings from configuraton file. /// </summary> private void DeserialiseSettings() { CalendarId = Config["testCalID"]; DemoPath = Config["DemoPath"]; CasualConfig = Config["casualConfig"]; CompConfig = Config["compConfig"]; PostConfig = Config["postConfig"]; CatFactPath = Config["catFactPath"]; PenguinFactPath = Config["penguinFactPath"]; TanookiFactPath = Config["tanookiFactPath"]; AlertUser = Config["alertUser"]; ImgurApi = Config["imgurAPI"]; PakRatEavesDrop = Config["pakRatEavesDropCSV"].Split(',').Select(v => v.Trim()).ToImmutableHashSet(); HowToPackEavesDrop = Config["howToPackEavesDropCSV"].Split(',').Select(v => v.Trim()).ToImmutableHashSet(); CarveEavesDrop = Config["carveEavesDropCSV"].Split(',').Select(v => v.Trim()).ToImmutableHashSet(); PropperEavesDrop = Config["propperEavesDropCSV"].Split(',').Select(v => v.Trim()).ToImmutableHashSet(); VbEavesDrop = Config["vbEavesDropCSV"].Split(',').Select(v => v.Trim()).ToImmutableHashSet(); ShitpostAgreeReplies = Config["agreeStringsCSV"].Split(',').Select(v => v.Trim()).ToImmutableHashSet(); PublicCommandWhiteList = Config["publicCommandWhiteListCSV"].Split(',').Select(v => v.Trim()).ToImmutableHashSet(); PlayingStrings = Config["playingStringsCSV"].Split(',').Select(v => v.Trim()).ToImmutableHashSet(); if (int.TryParse(Config["startDelay"], out int temp)) { StartDelay = temp; } else { Console.WriteLine($"Key 'startDelay' not found or valid. Using default {StartDelay}."); } if (int.TryParse(Config["updateInterval"], out temp)) { UpdateInterval = temp; } else { Console.WriteLine($"Key 'updateInterval' not found or valid. Using default {UpdateInterval}."); } if (int.TryParse(Config["ShitPostDelay"], out temp)) { ShitPostDelay = temp; } else { Console.WriteLine($"Key 'ShitPostDelay' not found or valid. Using default {ShitPostDelay}."); } if (int.TryParse(Config["calUpdateTicks"], out temp)) { CalUpdateTicks = temp; } else { Console.WriteLine($"Key 'calUpdateTicks' not found or valid. Using default {CalUpdateTicks}."); } CalUpdateTicks -= 1; var agreeUserIds = new HashSet <ulong>(); foreach (string idStr in Config["agreeUserCSV"].Split(',')) { if (ulong.TryParse(idStr.Trim(), out ulong id)) { agreeUserIds.Add(id); } } ShitpostAgreeUserIds = agreeUserIds.ToImmutableHashSet(); }
public async Task <IBuildResult> BuildAsync(string target, IDictionary <string, string> globalProperties) { if (globalProperties == null) { globalProperties = new Dictionary <string, string>(); } await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); IVsOutputWindowPane outputWindowPane = null; IVsOutputWindow outputWindow = ServiceProvider.GlobalProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow; if (outputWindow != null) { outputWindow.GetPane(VSConstants.GUID_BuildOutputWindowPane, out outputWindowPane); } var hostObjects = new HashSet <IHostObject>(); ILogger logger = null; if (outputWindowPane != null) { outputWindowPane.Activate(); logger = new PublishLogger(outputWindowPane); } var loggers = new HashSet <ILogger>() { logger }; if (_buildProject == null) { _buildProject = await GetBuildProject(_hier.GetUnconfiguredProject()); } _hier.GetDTEProject().DTE.Solution.SolutionBuild.BuildProject(globalProperties["Configuration"], _hier.GetDTEProject().UniqueName, true); IBuildResult result = await _buildProject?.BuildAsync(new string[] { target }, CancellationToken.None, true, ImmutableDictionary.ToImmutableDictionary(globalProperties), hostObjects.ToImmutableHashSet(), BuildRequestPriority.High, loggers.ToImmutableHashSet()); return(result); }
public IEnumerable <IScene> GetScenes() => _scenes.ToImmutableHashSet();
/// <summary> /// Generates proxies by discovering proxy factory method invocations in the given /// source documents. /// </summary> /// <param name="workspace">Creating a workspace is typically a bit heavy because of the MEF discovery, /// so this argument allows reusing a previously created one across multiple calls.</param> /// <param name="languageName">The language name to generate code for, such as 'C#' or 'Visual Basic'. See <see cref="LanguageNames"/>.</param> /// <param name="references">The metadata references to use when analyzing the <paramref name="sources"/>.</param> /// <param name="sources">The source documents to analyze to discover proxy usage.</param> /// <param name="additionalInterfaces">Additional interfaces (by full type name) that should be implemented by generated proxies.</param> /// <param name="additionalProxies">Additional types (by full type name) that should be proxied.</param> /// <param name="cancellationToken">Cancellation token to cancel the generation process.</param> /// <returns>An immutable array of the generated proxies as <see cref="Document"/> instances.</returns> public async Task <ImmutableArray <Document> > GenerateProxiesAsync( AdhocWorkspace workspace, string languageName, ImmutableArray <string> references, ImmutableArray <string> sources, ImmutableArray <string> additionalInterfaces, ImmutableArray <string> additionalProxies, CancellationToken cancellationToken) { var options = languageName == LanguageNames.CSharp ? (CompilationOptions) new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) : (CompilationOptions) new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionStrict: OptionStrict.On); var project = workspace.AddProject(ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "pgen", "pgen.dll", languageName, compilationOptions: options, metadataReferences: references .Select(path => MetadataReference.CreateFromFile(path)))); foreach (var source in sources) { var document = workspace.AddDocument(DocumentInfo.Create( DocumentId.CreateNewId(project.Id), Path.GetFileName(source), filePath: Path.GetTempFileName(), loader: TextLoader.From(TextAndVersion.Create(SourceText.From(File.ReadAllText(source)), VersionStamp.Create())))); project = document.Project; } var compilation = await project.GetCompilationAsync(); var additionalInterfaceSymbols = new List <ITypeSymbol>(); foreach (var additionalInterface in additionalInterfaces) { var additionalSymbol = compilation.GetTypeByMetadataName(additionalInterface) ?? // TODO: improve reporting throw new ArgumentException(additionalInterface); additionalInterfaceSymbols.Add(additionalSymbol); } var additionalProxySymbols = new List <ITypeSymbol>(); foreach (var additionalProxy in additionalProxies) { var additionalSymbol = compilation.GetTypeByMetadataName(additionalProxy) ?? // TODO: improve reporting throw new ArgumentException(additionalProxy); additionalProxySymbols.Add(additionalSymbol); } var discoverer = new ProxyDiscoverer(); var proxies = await discoverer.DiscoverProxiesAsync(project, cancellationToken); if (additionalProxySymbols.Count != 0) { var set = new HashSet <ImmutableArray <ITypeSymbol> >(proxies, StructuralComparer <ImmutableArray <ITypeSymbol> > .Default); foreach (var additionalProxySymbol in additionalProxySymbols) { // Adding to the set an existing item will no-op. set.Add(ImmutableArray.Create(additionalProxySymbol)); } // No need to ass the comparer since we've already ensured uniqueness above. proxies = set.ToImmutableHashSet(); } var documents = new List <Document>(proxies.Count); var additional = additionalInterfaceSymbols.ToImmutableArray(); foreach (var proxy in proxies) { // NOTE: we add the additional interfaces at this point, so that they affect both the // originally discovered proxies, as well as the additional proxy types explicitly // requested. documents.Add(await GenerateProxyAsync(workspace, project, cancellationToken, proxy, additional)); } return(documents.ToImmutableArray()); }
//public async Task ReceiveMessageAsync(IEntityDescriptor source, // IMessage message, // IMethodEntityGrain destinationGrain) //{ // //await destinationGrain.ProcessMessaggeAsync(source, message,this); //} /// <summary> /// /// </summary> /// <returns></returns> public ImmutableHashSet<IEntity> GetAllEntites() { var result = new HashSet<IEntity>(); var solutionGrain = SolutionGrainFactory.GetGrain("Solution"); var methodDescriptors = solutionGrain.GetMethodDescriptors().Result; foreach (var methodDescriptor in methodDescriptors) { var orleansEnitityDesc = new OrleansEntityDescriptor(methodDescriptor); IMethodEntityGrain entity = (IMethodEntityGrain)GetEntityAsync(orleansEnitityDesc).Result; result.Add(entity); } return result.ToImmutableHashSet<IEntity>(); }
public ImmutableHashSet<IEntityDescriptor> GetAllEntitiesDescriptors() { var result = new HashSet<IEntityDescriptor>(); var solutionGrain = SolutionGrainFactory.GetGrain("Solution"); var methodDescriptors = solutionGrain.GetMethodDescriptors().Result; foreach (var methodDescriptor in methodDescriptors) { var orleansEnitityDesc = new OrleansEntityDescriptor(methodDescriptor); result.Add(orleansEnitityDesc); } return result.ToImmutableHashSet<IEntityDescriptor>(); }
public MessageOut(IChatParticipant author, string text, HashSet <IPlayer> listeners = null) { Author = author; Listeners = listeners?.ToImmutableHashSet() ?? ImmutableHashSet <IPlayer> .Empty; Text = text; }
internal BlockChain <T> Fork( HashDigest <SHA256> point, DateTimeOffset currentTime) { var forked = new BlockChain <T>(Policy, Store, Guid.NewGuid()); try { _rwlock.EnterReadLock(); foreach (var index in Store.IterateIndex(Id.ToString())) { Store.AppendIndex(forked.Id.ToString(), index); if (index.Equals(point)) { break; } } Block <T> pointBlock = Blocks[point]; var addressesToStrip = new HashSet <Address>(); var signersToStrip = new HashSet <Address>(); for ( Block <T> block = Tip; block.PreviousHash is HashDigest <SHA256> hash && !block.Hash.Equals(point); block = Blocks[hash]) { ImmutableHashSet <Address> addresses = Store.GetBlockStates(block.Hash) .Select(kv => kv.Key) .ToImmutableHashSet(); ImmutableHashSet <Address> signers = block .Transactions .Select(tx => tx.Signer) .ToImmutableHashSet(); addressesToStrip.UnionWith(addresses); signersToStrip.UnionWith(signers); } Store.ForkStateReferences( Id.ToString(), forked.Id.ToString(), pointBlock, addressesToStrip.ToImmutableHashSet()); Store.ForkTxNonce( Id.ToString(), forked.Id.ToString(), pointBlock, signersToStrip.ToImmutableHashSet()); } finally { _rwlock.ExitReadLock(); } return(forked); }
internal static Level FromFile(string path) { if (!File.Exists(path)) { throw new FileNotFoundException($"The requested level (at path: {path}) does not exist."); } var lines = File.ReadAllLines(path); var playerPosition = default(Tile?); var walls = new HashSet <Tile>(); var boxPositions = new HashSet <Tile>(); var targetPositions = new HashSet <Tile>(); var height = lines.Length; var width = lines.Max(s => s.Length); for (var y = 0; y < lines.Length; y++) { var line = lines[y]; for (var x = 0; x < line.Length; x++) { ParseCharacter(line[x], new Tile(x, y)); } } if (playerPosition == default(Tile?)) { throw new InvalidOperationException("Level does not contain a player"); } if (boxPositions.Count != targetPositions.Count) { throw new InvalidOperationException("Level does not contain the same number of boxes and targets"); } return(new Level(width, height, walls.ToImmutableHashSet(), targetPositions.ToImmutableHashSet(), boxPositions.ToImmutableHashSet(), playerPosition.Value)); void ParseCharacter(char c, Tile point) { switch (c) { case EmptyTile: break; case WallTile: walls.Add(point); break; case TargetTile: targetPositions.Add(point); break; case Player: playerPosition = point; break; case PlayerOnTarget: playerPosition = Tile.Clone(point); targetPositions.Add(point); break; case Box: boxPositions.Add(point); break; case BoxOnTarget: targetPositions.Add(point); boxPositions.Add(point); break; default: throw new ArgumentOutOfRangeException(); } } }
public UnidirectionalSymbolSet(FindReferencesSearchEngine engine, MetadataUnifyingSymbolHashSet initialSymbols, HashSet <ISymbol> upSymbols) : base(engine) { _initialAndDownSymbols = initialSymbols; _upSymbols = upSymbols.ToImmutableHashSet(); }
public IImmutableSet <DbEntity> GetEntitiesToUpdate() { return(entitiesToUpdate.ToImmutableHashSet()); }