private static bool RecoursiveCheckGraph(Task root, ImmutableList<Guid> previousTasks) { Contract.Requires(root != null); Contract.Requires(root.Inputs != null); Contract.Requires(previousTasks != null); if (previousTasks.Contains(root.Id)) { Logger.Write( LogCategories.Error(string.Format( "{0} is cycled.", root), LogCategories.TaskServices)); return false; } foreach (var task in root.Inputs) { if (previousTasks.Contains(task.Id)) { Logger.Write( LogCategories.Error(string.Format( "{0} is cycled.", task), LogCategories.TaskServices)); return false; } if (!RecoursiveCheckGraph(task, previousTasks.Add(root.Id))) return false; } return true; }
public void FindElementIn100() { tml.setTestCaseName("Find elements in 100"); ImmutableList <Payload> list = this.creatASListWithNelement(100); Payload toBeFound_25 = new Payload("Load 25"); Payload toBeFound_50 = new Payload("Load 50"); Payload toBeFound_75 = new Payload("Load 75"); Payload toBeFound_100 = new Payload("Load 99"); // Assert.AreEqual(100, list.Count); tml.setInitialTimeAndMemory(); bool outcome = list.Contains(toBeFound_25); Assert.IsTrue(outcome, toBeFound_25 + " not found"); tml.logTimeAndMemoryUsage(25); outcome = list.Contains(toBeFound_50); Assert.IsTrue(outcome, toBeFound_50 + " not found"); tml.logTimeAndMemoryUsage(50); outcome = list.Contains(toBeFound_75); Assert.IsTrue(outcome, toBeFound_75 + " not found"); tml.logTimeAndMemoryUsage(75); outcome = list.Contains(toBeFound_100); Assert.IsTrue(outcome, toBeFound_100 + " not found"); tml.logTimeAndMemoryUsage(100); }
public Socket Open() { string transportName; if (RememberUpgrade && PriorWebsocketSuccess && Transports.Contains(WebSocket.NAME)) { transportName = WebSocket.NAME; } else { transportName = Transports[0]; } ReadyState = ReadyStateEnum.OPENING; var transport = CreateTransport(transportName); SetTransport(transport); // EventTasks.Exec((n) => Task.Run(() => { var log2 = LogManager.GetLogger(Global.CallerName()); log2.Info("Task.Run Open start"); transport.Open(); log2.Info("Task.Run Open finish"); }); return(this); }
public void RemoveTest() { ImmutableList <int> list = ImmutableList <int> .Empty; for (int i = 1; i <= 10; i++) { list = list.Add(i * 10); } list = list.Remove(30); Assert.Equal(9, list.Count); Assert.False(list.Contains(30)); list = list.Remove(100); Assert.Equal(8, list.Count); Assert.False(list.Contains(100)); list = list.Remove(10); Assert.Equal(7, list.Count); Assert.False(list.Contains(10)); var removeList = new int[] { 20, 70 }; list = list.RemoveAll(removeList.Contains); Assert.Equal(5, list.Count); Assert.False(list.Contains(20)); Assert.False(list.Contains(70)); IImmutableList <int> list2 = ImmutableList <int> .Empty; for (int i = 1; i <= 10; i++) { list2 = list2.Add(i * 10); } list2 = list2.Remove(30); Assert.Equal(9, list2.Count); Assert.False(list2.Contains(30)); list2 = list2.Remove(100); Assert.Equal(8, list2.Count); Assert.False(list2.Contains(100)); list2 = list2.Remove(10); Assert.Equal(7, list2.Count); Assert.False(list2.Contains(10)); list2 = list2.RemoveAll(removeList.Contains); Assert.Equal(5, list2.Count); Assert.False(list2.Contains(20)); Assert.False(list2.Contains(70)); }
public override async Task ExecuteAsync(CancellationToken cancellationToken) { Mailbox mailbox = await _mailstore.GetMailBoxAsync(_channel.AuthenticatedUser, _mailbox, true, cancellationToken); if (mailbox == null) { await EndWithResultAsync(_channel, CommandResult.No, "no mailbox with that name", cancellationToken); return; } var messageData = new List <IMessageData>(); if (_items.Contains("MESSAGES")) { messageData.Add(new AtomMessageData("MESSAGES")); messageData.Add(new NumberMessageData(mailbox.Messages.Count)); } if (_items.Contains("RECENT")) { messageData.Add(new AtomMessageData("RECENT")); messageData.Add(new NumberMessageData(mailbox.Recent.Count)); } if (_items.Contains("UIDNEXT")) { messageData.Add(new AtomMessageData("UIDNEXT")); messageData.Add(new NumberMessageData(mailbox.NextUid)); } if (_items.Contains("UIDVALIDITY")) { messageData.Add(new AtomMessageData("UIDVALIDITY")); messageData.Add(new NumberMessageData(mailbox.UidValidity)); } if (_items.Contains("UNSEEN")) { messageData.Add(new AtomMessageData("UNSEEN")); messageData.Add(new NumberMessageData(mailbox.Messages.Count(m => m.Flags.Contains(Tags.Seen)))); } await _channel.SendMessageAsync( new ImapMessage(UntaggedTag, CommandName, new ListMessageData(messageData)), cancellationToken); await EndOkAsync(_channel, cancellationToken); }
public async Task <Brain> Light(IBulb bulb, int?intensity = null, int?autoDimBy = null) { if (Bulbs.Contains(bulb)) { throw new ArgumentException( $"Bulb '{bulb}' is already lighted.", nameof(bulb)); } var adjustedBulb = await bulb.Adjust(intensity, autoDimBy); var nextBrain = await WithBulb(adjustedBulb); return(nextBrain); }
protected void AddFriend(string address, string cert) { SocialUser user = _node.AddFriend(address, cert, null, null); if (_pending.Contains(user.Address)) { _pending = _pending.RemoveFromNew(user.Address); } if (!_auto_allow && !IsVerified(user)) { _node.Block(user.Address); } }
/// <summary> /// Registers a target tag that supports conversion on this adapter. /// </summary> /// <param name="tag">Tag that is supported by this adapter.</param> protected void RegisterSupportTag(string tag) { if (!_supportedTags.Contains(tag)) { _supportedTags = _supportedTags.Add(tag); } }
/// <summary> /// Removes the listener /// </summary> /// <param name="eventString">an event name</param> /// <param name="fn"></param> /// <returns>a reference to this object.</returns> public Emitter Off(string eventString, IListener fn) { try { if (this.callbacks.ContainsKey(eventString)) { ImmutableList <IListener> callbacksLocal = this.callbacks[eventString]; IListener offListener; _onceCallbacks.TryGetValue(fn, out offListener); _onceCallbacks = _onceCallbacks.Remove(fn); if (callbacksLocal.Count > 0 && callbacksLocal.Contains(offListener ?? fn)) { callbacksLocal = callbacksLocal.Remove(offListener ?? fn); this.callbacks = this.callbacks.Remove(eventString); this.callbacks = this.callbacks.Add(eventString, callbacksLocal); } } }catch (Exception) { this.Off(); } return(this); }
protected override void SaveItems(ImmutableList <I> items, ImmutableList <ItemData> .Builder listBuilder) { if (!_conditionResult) { return; } // bug in ImmutableList<T>.Builder.RemoveAll. In some cases it will remove elements for which the RemoveAll predicate is false // MSBuild issue: https://github.com/Microsoft/msbuild/issues/2069 // corefx issue: https://github.com/dotnet/corefx/issues/20609 //listBuilder.RemoveAll(itemData => items.Contains(itemData.Item)); // Replacing RemoveAll with Remove fixes the above issue // DeLINQified for perf //var itemDataToRemove = listBuilder.Where(itemData => items.Contains(itemData.Item)).ToList(); var itemDataToRemove = new List <ItemData>(); foreach (var itemData in listBuilder) { if (items.Contains(itemData.Item)) { itemDataToRemove.Add(itemData); } } foreach (var itemToRemove in itemDataToRemove) { listBuilder.Remove(itemToRemove); } }
private static string?Untokenize(string key, string value, IConfiguration configuration, ImmutableList <string> stackTrace) { // First check the stack trace doesn't contain the key if (stackTrace.Contains(key)) { throw new ArgumentException("Circular dependency detected"); } if (value is null) { return(value); } // Get the value var tokenStart = value.IndexOf("${"); var tokenEnd = value.IndexOf('}'); // No tokens, return the old value if (tokenStart == -1 || tokenEnd == -1) { return(value); } // Get the string between the tokenized characters. This should be the new key string innerString = value.Substring(tokenStart + 2, tokenEnd - 2); var innerKeyValue = configuration[innerString]; // Replace the value with the untokenized value value = value.Replace("${" + innerString + "}", Untokenize(innerString, innerKeyValue, configuration, stackTrace.Add(key))); // Then untokenize any other tokens return(Untokenize(key, value, configuration, stackTrace)); }
public PureEngineIoSocket Open() { string transportName; if (RememberUpgrade && PriorWebsocketSuccess && Transports.Contains(WebSocket.NAME)) { transportName = WebSocket.NAME; } else { transportName = Transports[0]; } ReadyState = ReadyStateEnum.OPENING; var transport = CreateTransport(transportName); SetTransport(transport); Task.Run(() => { Logger.Log("Task.Run Open start"); transport.Open(); Logger.Log("Task.Run Open finish"); }); return(this); }
public string Render(object?obj, IExampleRendererHandler renderer, ImmutableList <object?> path) { if (path.Contains(obj)) { return("<Circular reference>"); } if (path.Count >= _depthLimit) { return("..."); } try { var innerHandler = _innerHandlers.Where(h => h.CanRender(obj)).FirstOrDefault(); if (innerHandler == null) { return(obj?.ToString() ?? "null"); } return(innerHandler.Render(obj, renderer, path.Add(obj))); } catch { return("<Rendering failed>"); } }
public override ImmutableList<char> FreeVariableNames(ImmutableList<Symbol> boundVariables) { if (boundVariables.Contains(_variable)) return ImmutableList<char>.Empty; else return new char[] { _variable.Default }.ToImmutableList(); }
protected void VerifyFriends() { foreach (SocialUser user in _node.Friends.Values) { if (_pending.Contains(user.Address)) { _pending = _pending.RemoveFromNew(user.Address); } if (!_node.IsAllowed(user.Address) && !_blocked.Contains(user.Address)) { foreach (ISocialNetwork network in _networks.Values) { IDictionary <string, string> fprs = network.Fingerprints; IDictionary <string, string> addrs = network.Addresses; string fpr; string uid; if (fprs.TryGetValue(user.Address, out fpr) && fpr == user.Fingerprint && addrs.TryGetValue(user.Address, out uid) && uid == user.Uid) { _node.Unblock(user.Address); break; } } } } }
private static bool RecoursiveCheckGraph(TaskRequest root, ImmutableList<Guid> previousTasks) { if (previousTasks.Contains(root.Id)) return false; foreach (var task in root.Dependencies) { if (previousTasks.Contains(task.Id)) return false; if (!RecoursiveCheckGraph(task, previousTasks.Add(root.Id))) return false; } return true; }
public bool AppliesInUiMode(string uiMode) { if (_uiModes.Any()) { return(_uiModes.Contains(uiMode)); } return(!_exceptInUiModes.Contains(uiMode)); }
/// <summary> /// Puts value at given key into builder dictionary. /// </summary> /// <param name="key">Key</param> /// <param name="value">Value</param> /// <returns>Builder instance</returns> public OrderedHashImmutableDictionaryBuilder Put(T key, TV value) { if (!keysOrder.Contains(key)) { keysOrder.Add(key); } dictionary.Put(key, value); return(this); }
public Builder Put(T key, TV value) { if (!keysOrder.Contains(key)) { keysOrder.Add(key); } dictionary.Put(key, value); return(this); }
internal void SetInitialData(string receiverPort, object v) { if (!InputPorts.Contains(receiverPort)) { InputPorts = InputPorts.Add(receiverPort); } InputPortInitialDatas = InputPortInitialDatas.Add(receiverPort, v); }
private static bool IsExemptType(Type type) { if (type.IsConstructedGenericType) { return(IsExemptType(type.GetGenericTypeDefinition())); } return(s_exemptTypes.Contains(type.FullName) || s_exemptNamespaces.Any(n => type.FullName.StartsWith(n))); }
/// <summary> /// Adds the supplied path to the list. /// </summary> /// <param name="path">the path to add.</param> public void AddPath(string path) { TestForEditable(); PathHelpers.ValidatePathName(path); if (!m_importPaths.Contains(path, StringComparer.Create(CultureInfo.CurrentCulture, true))) { m_importPaths.Add(path); } }
protected override void SaveItems(ImmutableList <I> items, ImmutableList <ItemData> .Builder listBuilder) { if (!_conditionResult) { return; } listBuilder.RemoveAll(itemData => items.Contains(itemData.Item)); }
/// <summary> /// Register a new observer of projection shard events. The return disposable /// can be used to unsubscribe the observer from the tracker /// </summary> /// <param name="observer"></param> /// <returns></returns> public IDisposable Subscribe(IObserver <ShardState> observer) { if (!_listeners.Contains(observer)) { _listeners = _listeners.Add(observer); } return(new Unsubscriber(this, observer)); }
/// <summary> /// Adds the supplied extension to the list. /// </summary> /// <param name="extension">the extension to add.</param> public void AddExtension(string extension) { TestForEditable(); extension = PathHelpers.FormatExtension(extension); if (!m_importExtensions.Contains(extension, StringComparer.Create(CultureInfo.CurrentCulture, true))) { m_importExtensions.Add(extension); } }
public async Task <int> RemovePeopleFromFamilies(ImmutableList <long> peopleIds) { await using var db = CommonRepository.GetDatabase(serviceScopeFactory: _serviceScopeFactory); var people = await db.People.Where(predicate : p => p.PeopleId.HasValue && peopleIds.Contains(p.PeopleId.Value)) .ToListAsync().ConfigureAwait(continueOnCapturedContext: false); people.ForEach(action: p => p.FamilyId = null); return(await db.SaveChangesAsync()); }
protected override bool TryParseArguments(ImmutableList <IMessageData> arguments) { if (arguments.Count != 3) { return(false); } string storeType = MessageData.GetString(arguments[0], Encoding.ASCII); _messageRange = arguments[1] as NumberRangeMessageData; _valueList = arguments[2] as ListMessageData; if (string.IsNullOrEmpty(storeType) || _messageRange == null || _valueList == null) { return(false); } Match argumentMatch = ArgumentPattern.Match(storeType); if (!argumentMatch.Success) { return(false); } switch (argumentMatch.Groups[1].Value) { case "": _operation = StoreOperation.Set; break; case "+": _operation = StoreOperation.Add; break; case "-": _operation = StoreOperation.Remove; break; default: return(false); } _command = argumentMatch.Groups[2].Value; if (!KnownCommands.Contains(_command, StringComparer.OrdinalIgnoreCase)) { return(false); } _silent = string.Equals(argumentMatch.Groups[3].Value, ".SILENT", StringComparison.OrdinalIgnoreCase); return(true); }
public void RegisterRigidBody(RigidBody body) { if (Bodies.Contains(body)) { return; } Bodies = Bodies.Add(body); body.Index = Bodies.Count - 1; body.UID = nextID++; }
private ManualSolverModel ToggleHighlighted(int index) { if (SelectedSegmentIndices.Contains(index)) { return(With(Segments, HighlightedSegmentIndex, SelectedSegmentIndices.Remove(index), PendingOperationType.None, mirrors)); } else { return(With(Segments, HighlightedSegmentIndex, SelectedSegmentIndices.Add(index), PendingOperationType.None, mirrors)); } }
public bool IsActiveEditorContext(string contextId) { Requires.NotNullOrEmpty(contextId, nameof(contextId)); if (!_contexts.Contains(contextId)) { throw new InvalidOperationException($"'{nameof(contextId)}' has not been registered or has already been unregistered"); } return(StringComparers.WorkspaceProjectContextIds.Equals(ActiveIntellisenseProjectContext, contextId)); }
public async Task <NonNullImmutableList <Post> > GetByIds(ImmutableList <int> ids) { if (ids == null) { throw new ArgumentNullException(nameof(ids)); } return(new NonNullImmutableList <Post>( (await _postRetriever.Get()).Where(p => ids.Contains(p.Id)).OrderByDescending(p => p.Posted) )); }
public bool ImmutableList() { bool result = default; ImmutableList <T> collection = _immutableList; T[] notFound = _notFound; for (int i = 0; i < notFound.Length; i++) { result ^= collection.Contains(notFound[i]); } return(result); }
private static bool RecoursiveCheckGraph(Japi.Task root, ImmutableList<Japi.Task> previousTasks) { if(previousTasks.Contains(root)) { Console.WriteLine("1: {0}", root); return false; } foreach(var task in root.Dependencies) { if(previousTasks.Contains(task)) { Console.WriteLine("2: {0}", root); return false; } if(!RecoursiveCheckGraph(task, previousTasks.Add(root))) return false; } return true; }
public void AddFlag(string flag) { //if(Name[0] != '.') //{ // if (flag == "abstract") AddFlag("newlot"); //} if (Flags.Contains(flag)) { return; } Flags = Flags.Add(flag); }
private IProperty VerifyRootPrincipal( IProperty principalProperty, Dictionary<IProperty, IProperty> verifiedProperties, ImmutableList<IForeignKey> visitedForeignKeys, out string errorMessage) { errorMessage = null; IProperty rootPrincipal; if (verifiedProperties.TryGetValue(principalProperty, out rootPrincipal)) { return rootPrincipal; } var rootPrincipals = new Dictionary<IProperty, IForeignKey>(); foreach (var foreignKey in principalProperty.DeclaringEntityType.GetForeignKeys()) { for (var index = 0; index < foreignKey.Properties.Count; index++) { if (principalProperty == foreignKey.Properties[index]) { var nextPrincipalProperty = foreignKey.PrincipalKey.Properties[index]; if (visitedForeignKeys.Contains(foreignKey)) { var cycleStart = visitedForeignKeys.IndexOf(foreignKey); var cycle = visitedForeignKeys.GetRange(cycleStart, visitedForeignKeys.Count - cycleStart); errorMessage = Strings.CircularDependency(cycle.Select(fk => fk.ToString()).Join()); continue; } rootPrincipal = VerifyRootPrincipal(nextPrincipalProperty, verifiedProperties, visitedForeignKeys.Add(foreignKey), out errorMessage); if (rootPrincipal == null) { if (principalProperty.RequiresValueGenerator) { rootPrincipals[principalProperty] = foreignKey; } continue; } if (principalProperty.RequiresValueGenerator) { ShowError(Strings.ForeignKeyValueGenerationOnAdd( principalProperty.Name, principalProperty.DeclaringEntityType.DisplayName(), Property.Format(foreignKey.Properties))); return principalProperty; } rootPrincipals[rootPrincipal] = foreignKey; } } } if (rootPrincipals.Count == 0) { if (errorMessage != null) { return null; } if (!principalProperty.RequiresValueGenerator) { ShowError(Strings.PrincipalKeyNoValueGenerationOnAdd(principalProperty.Name, principalProperty.DeclaringEntityType.DisplayName())); return null; } return principalProperty; } if (rootPrincipals.Count > 1) { var firstRoot = rootPrincipals.Keys.ElementAt(0); var secondRoot = rootPrincipals.Keys.ElementAt(1); ShowWarning(Strings.MultipleRootPrincipals( rootPrincipals[firstRoot].DeclaringEntityType.DisplayName(), Property.Format(rootPrincipals[firstRoot].Properties), firstRoot.DeclaringEntityType.DisplayName(), firstRoot.Name, Property.Format(rootPrincipals[secondRoot].Properties), secondRoot.DeclaringEntityType.DisplayName(), secondRoot.Name)); return firstRoot; } errorMessage = null; rootPrincipal = rootPrincipals.Keys.Single(); verifiedProperties[principalProperty] = rootPrincipal; return rootPrincipal; }