public async Task <Block> TakeBlockAsync(Height height, Height lookAheadHeight, CancellationToken ctsToken)
        {
            for (int h = height.Value; h <= lookAheadHeight; h++)
            {
                if (!_downloadedBlocks.ContainsKey(new Height(h)))
                {
                    _blocksToDownload.Add(new Height(h));
                }
            }

            while (!_downloadedBlocks.ContainsKey(height))
            {
                if (ctsToken.IsCancellationRequested)
                {
                    return(null);
                }
                await Task.Delay(100, ctsToken).ContinueWith(tsk => { });
            }

            if (ctsToken.IsCancellationRequested)
            {
                return(null);
            }

            _downloadedBlocks.TryRemove(height, out Block block);
            return(block);
        }
Exemple #2
0
        public void SmartTransactionHashSetTest()
        {
            var tracker = new Tracker(Network.Main);
            var tx1     = new Transaction(
                "0100000003192a9e09a4eb4829dd92e437d50a6d544626a0c0a4345fe85754cf0b509c56da090000006a47304402205ae8feded01cff3dafa698481a0e941a5059b9de234e794335493f863da6b8b702207645e57ec428b553e57e30115eaa3eb8828069e7933e09e4c867d086de2d67290121022f4cae09039d26ee9481ac235d0c74a1c1cdb1780acbb4300ce5a14d2c7a69e0ffffffff05d2352f130dac517aba5e6fdf966d915b15fbf8c674a9809d7706fd9bc2c545290000006a4730440220771193a38f8e05e59dc8233b46e181c9a75808c0ec1efeeedfebe5c7018d2c1f02206c32485d4fab65d47d7d4392d937128af44e918bd0fdded4d0b82b0a9d316dcc0121028fc5d9cd68ba58123ff972bb73682019cd1ee395f92c0b72e73ebc7151e3fe43ffffffff1cb828c3dcb9abbf77d63dbc9a050c70a05c5d0f2988da89811803f7dee4f090050000006b483045022100e32f6195c4437c4a3f0de88157989830c6c0effcecd093324b2dd33b81b9743902203e9bf7f36dc0a879de165c96b137ca163c3506fc5ac9db377650632e1e922e4f01210358e1623b2ffdf9b0bc135026a5e8fdd1625f61424937b7c1cb6e47af1f06bd0affffffff026ba91a00000000001976a914cc17bf00ffba667e4f8ff425500b83f3a863922788acf60b0300000000001976a914f73f6ea0a99cbcc985a0dae57b9938e0dfc245c088ac00000000");
            var tx2 =
                new Transaction(
                    "0100000001c3dd09422c44e8cab3065aac65f1cc7befce2a0ea5d309d8d213ec08877dbd4b000000006a473044022001ab7769a0d735bbe4756260c30ab8127f4282cdd00b66991ca6bfc383b5005c02203d29981127717946bf05fc15177f3042aa0b995db786a868de4cc67bfd88801d0121037df55814a04730433b1ee3bcc8f089eef346e556d222b13f1a57a355fd8d07f6ffffffff0120300500000000001976a914f55586866f28d6db41529b8bd85db09e88221a1388ac00000000");

            Assert.True(tracker.TrackedTransactions.TryAdd(new SmartTransaction(tx1, new Height(1))));
            Assert.True(tracker.TrackedTransactions.TryAdd(new SmartTransaction(tx2, new Height(1))));
            Assert.False(tracker.TrackedTransactions.TryAdd(new SmartTransaction(tx2, new Height(1))));

            HashSet <SmartTransaction> stx = new HashSet <SmartTransaction>();

            Assert.True(stx.Add(new SmartTransaction(tx1, new Height(1))));
            Assert.True(stx.Add(new SmartTransaction(tx2, new Height(2))));
            Assert.False(stx.Add(new SmartTransaction(tx2, new Height(3))));

            ConcurrentHashSet <SmartTransaction> stxchs = new ConcurrentHashSet <SmartTransaction>();

            Assert.True(stxchs.Add(new SmartTransaction(tx1, new Height(1))));
            Assert.True(stxchs.Add(new SmartTransaction(tx2, new Height(2))));
            Assert.False(stxchs.Add(new SmartTransaction(tx2, new Height(3))));

            ConcurrentObservableHashSet <SmartTransaction> stxcohs = new ConcurrentObservableHashSet <SmartTransaction>();

            Assert.True(stxcohs.TryAdd(new SmartTransaction(tx1, new Height(1))));
            Assert.True(stxcohs.TryAdd(new SmartTransaction(tx2, new Height(2))));
            Assert.False(stxcohs.TryAdd(new SmartTransaction(tx2, new Height(3))));
        }
Exemple #3
0
 private void ConditionalMute(ushort cl)
 {
     if (cl != LocalClientId && !_UnmutedClients.Contains(cl))
     {
         _MutedClients.Add(cl);
     }
 }
Exemple #4
0
        public static void AddEventServer(IEventServer eventServer)
        {
            lock (serviceLock)
            {
                var exposedTypes = Discovery.GetTypesFromAttribute(typeof(ServiceExposedAttribute));
                foreach (var type in exposedTypes)
                {
                    if (type.IsClass)
                    {
                        if (TypeAnalyzer.GetTypeDetail(type).Interfaces.Any(x => x == typeof(IEvent)))
                        {
                            var interfaceStack = ProviderLayers.GetProviderInterfaceStack();
                            var hasHandler     = Discovery.HasImplementationType(TypeAnalyzer.GetGenericType(typeof(IEventHandler <>), type), interfaceStack, interfaceStack.Length - 1);
                            if (hasHandler)
                            {
                                if (eventClients.Keys.Contains(type))
                                {
                                    throw new InvalidOperationException($"Cannot create loopback. Event Client already registered for type {type.GetNiceName()}");
                                }
                                if (!eventServerTypes.Contains(type))
                                {
                                    eventServerTypes.Add(type);
                                }
                                eventServer.RegisterEventType(type);
                            }
                        }
                    }
                }

                eventServer.SetHandler(HandleRemoteEventDispatchAsync);
                eventServers.Add(eventServer);
                eventServer.Open();
            }
        }
        public bool ToggleVerboseErrors(ulong guildId)
        {
            bool enabled;

            using (var uow = _db.UnitOfWork)
            {
                var gc = uow.GuildConfigs.For(guildId, set => set);

                enabled = gc.VerboseErrors = !gc.VerboseErrors;

                uow.Complete();

                if (gc.VerboseErrors)
                {
                    guildsEnabled.Add(guildId);
                }
                else
                {
                    guildsEnabled.TryRemove(guildId);
                }
            }

            if (enabled)
            {
                guildsEnabled.Add(guildId);
            }
            else
            {
                guildsEnabled.TryRemove(guildId);
            }

            return(enabled);
        }
Exemple #6
0
        public static void AddQueryServer(IQueryServer queryServer)
        {
            lock (serviceLock)
            {
                var exposedTypes = Discovery.GetTypesFromAttribute(typeof(ServiceExposedAttribute));
                foreach (var type in exposedTypes)
                {
                    if (type.IsInterface && TypeAnalyzer.GetTypeDetail(type).Interfaces.Any(x => x == typeof(IBaseProvider)))
                    {
                        var interfaceStack    = ProviderLayers.GetProviderInterfaceStack();
                        var hasImplementation = Discovery.HasImplementationType(type, interfaceStack, interfaceStack.Length - 1);
                        if (hasImplementation)
                        {
                            if (queryClients.Keys.Contains(type))
                            {
                                throw new InvalidOperationException($"Cannot create loopback. Query Client already registered for type {type.GetNiceName()}");
                            }
                            if (!queryServerTypes.Contains(type))
                            {
                                queryServerTypes.Add(type);
                            }
                            queryServer.RegisterInterfaceType(type);
                        }
                    }
                }

                queryServer.SetHandler(HandleRemoteQueryCallAsync);
                queryServers.Add(queryServer);
                queryServer.Open();
            }
        }
        public bool ToggleVerboseErrors(ulong guildId)
        {
            bool enabled;

            using (var uow = _db.GetDbContext())
            {
                var gc = uow.GuildConfigs.ForId(guildId, set => set);

                enabled = gc.VerboseErrors = !gc.VerboseErrors;

                uow.SaveChanges();

                if (gc.VerboseErrors)
                {
                    guildsEnabled.Add(guildId);
                }
                else
                {
                    guildsEnabled.TryRemove(guildId);
                }
            }

            if (enabled)
            {
                guildsEnabled.Add(guildId);
            }
            else
            {
                guildsEnabled.TryRemove(guildId);
            }

            return(enabled);
        }
Exemple #8
0
 internal void ClearCollected()
 {
     _collected.Clear();
     foreach (var e in _emojis)
     {
         _collected.Add(new PollEmoji(e));
     }
 }
Exemple #9
0
        public void ConstructorOverLoad_CustomComparer_WithInitialCapacity()
        {
            var threeCharSet = new ConcurrentHashSet <string>(5, 5, new ThreeCharEqualityComparer());

            threeCharSet.Add("string1");
            threeCharSet.Add("string2");
            Assert.AreEqual(1, threeCharSet.Count);
        }
Exemple #10
0
        public void ConstructorOverLoad_CustomCapacityAndConcurrency_WithCapacityLessThanConcurrency_DoesNotFail()
        {
            var hashSet = new ConcurrentHashSet <int>(8, 1);

            hashSet.Add(3);
            hashSet.Add(4);
            hashSet.Add(5);
            Assert.AreEqual(3, hashSet.Count);
        }
Exemple #11
0
        public async Task <string> PostAsync(TMRoom room)
        {
            room.MaxPlayerCount = 8;
            room.ClientInfos    = new List <TMClientInfoInRoom>();
            room.Status         = TMRoom.RoomStatus.Created;
            room.RoomContainer  = this;
            Rooms.Add(room);
            await room.SaveAsync();

            return(room.ObjectId);
        }
        public static void AddModelReference(this AppDomain appDomain, params string[] name)
        {
            var locations = AppDomain.CurrentDomain.GetAssemblies()
                            .Where(assembly => name.Contains(assembly.GetName().Name))
                            .Select(assembly => assembly.Location);

            foreach (var location in locations)
            {
                References.Add(location);
            }
        }
Exemple #13
0
        public SubscriptionToken SubscribeForMessage <T>(PID subscriber, RoutingFilter filter = null) where T : ActorMessage
        {
            var sub = GetSubscription <T>(subscriber);

            if (!_subscriptionCahce.Add(sub))
            {
                return(SubscriptionToken.Empty);
            }

            return(_eventAggregator.Subscribe <T>(message => _actorFactory.Context.Send(subscriber, message.Message), filter));
        }
Exemple #14
0
        public void ConstructorOverLoad_CustomCapacityAndConcurrency_DoesNotFail()
        {
            var hashSet = new ConcurrentHashSet <int>(5, 5);

            hashSet.Add(3);
            hashSet.Add(4);
            hashSet.Add(5);
            hashSet.Add(6);
            hashSet.Add(7);
            Assert.AreEqual(5, hashSet.Count);
        }
Exemple #15
0
 private void TryAdd(int id)
 {
     if (!Belongs(id))
     {
         return;
     }
     if (_ids.Add(id))
     {
         Interlocked.Increment(ref _entityCount);
     }
 }
Exemple #16
0
        public void Clear_RemovesAllItems()
        {
            var hashSet = new ConcurrentHashSet <int>();

            hashSet.Add(5);
            hashSet.Add(8);

            Assert.AreEqual(2, hashSet.Count);

            hashSet.Clear();
            Assert.AreEqual(0, hashSet.Count);
        }
Exemple #17
0
        private ICollection <CubePosition> DoCycles(ICollection <CubePosition> activeCubes,
                                                    bool includeW)
        {
            ICollection <CubePosition> newState  = new ConcurrentHashSet <CubePosition>();
            ICollection <CubePosition> mayActive = new ConcurrentHashSet <CubePosition>();

            activeCubes.AsParallel().ForAll(currentCube =>
            {
                int active = 0;

                foreach (var toCheckPos in GetNeighbors(currentCube, new CubePosition(), includeW))
                {
                    if (toCheckPos.Equals(currentCube))
                    {
                        continue;
                    }
                    if (activeCubes.Contains(toCheckPos))
                    {
                        active++;
                    }
                    else
                    {
                        mayActive.Add(new CubePosition
                        {
                            X = toCheckPos.X,
                            Y = toCheckPos.Y,
                            Z = toCheckPos.Z,
                            W = toCheckPos.W
                        });
                    }
                }

                if (active >= 2 && active <= 3)
                {
                    newState.Add(currentCube);
                }
            });

            mayActive.AsParallel().ForAll(currentCube =>
            {
                int active = GetNeighbors(currentCube, new CubePosition(), includeW)
                             .Where(toCheckPos => !toCheckPos.Equals(currentCube))
                             .Count(activeCubes.Contains);

                if (active == 3)
                {
                    newState.Add(currentCube);
                }
            });

            return(newState);
        }
Exemple #18
0
        public void CopyTo_OutOfRange_ThrowsException()
        {
            var hashSet = new ConcurrentHashSet <int>();

            hashSet.Add(5);
            hashSet.Add(8);

            Assert.Throws <ArgumentException>(() =>
            {
                var array = new int[2];
                ((ICollection <int>)hashSet).CopyTo(array, 4);
            });
        }
Exemple #19
0
        public void Add_MultipleTimes_AddsCorrectly()
        {
            var hashSet = new ConcurrentHashSet <int>();

            hashSet.Add(5);
            hashSet.Add(8);

            Assert.IsTrue(hashSet.Contains(5));
            Assert.IsTrue(hashSet.Contains(8));
            Assert.AreEqual(2, hashSet.Count);

            hashSet.Clear();
            Assert.AreEqual(0, hashSet.Count);
        }
Exemple #20
0
        public void CopyTo_MultipleTimes_AddsCorrectly()
        {
            var hashSet = new ConcurrentHashSet <int>();

            hashSet.Add(5);
            hashSet.Add(8);

            var array = new int[2];

            ((ICollection <int>)hashSet).CopyTo(array, 0);

            Assert.IsTrue(array.Contains(5));
            Assert.IsTrue(array.Contains(8));
        }
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="cacheKey">缓存键</param>
        /// <param name="cacheValue">缓存值</param>
        /// <param name="expiry">过期时间</param>
        public void Set <T>(string cacheKey, T cacheValue, TimeSpan expiry)
        {
            Check.NotNullOrEmpty(cacheKey, nameof(cacheKey));
            Check.NotNull(cacheValue, nameof(cacheValue));
            Check.NotNegativeOrZero(expiry, nameof(expiry));

            if (MaxRdSecond > 0)
            {
                var addSec = new Random().Next(1, MaxRdSecond);
                expiry.Add(new TimeSpan(0, 0, addSec));
            }

            _cache.Set(cacheKey, cacheValue, expiry);
            _cacheKeys.Add(cacheKey);
        }
Exemple #22
0
        public async Task HentaiBomb([Remainder] string tag = null)
        {
            if (!_hentaiBombBlacklist.Add(Context.User.Id))
            {
                return;
            }
            try
            {
                tag = tag?.Trim() ?? "";
                tag = "rating%3Aexplicit+" + tag;

                var links = await Task.WhenAll(GetGelbooruImageLink(tag),
                                               GetDanbooruImageLink(tag),
                                               GetKonachanImageLink(tag),
                                               GetYandereImageLink(tag)).ConfigureAwait(false);

                var linksEnum = links?.Where(l => l != null).ToArray();
                if (links == null || !linksEnum.Any())
                {
                    await ReplyErrorLocalized("not_found").ConfigureAwait(false);

                    return;
                }

                await Context.Channel.SendMessageAsync(string.Join("\n\n", linksEnum)).ConfigureAwait(false);
            }
            finally
            {
                await Task.Delay(5000).ConfigureAwait(false);

                _hentaiBombBlacklist.TryRemove(Context.User.Id);
            }
        }
Exemple #23
0
 public static void AddRange <T>(this ConcurrentHashSet <T> target, IEnumerable <T> elements) where T : class
 {
     foreach (var item in elements)
     {
         target.Add(item);
     }
 }
Exemple #24
0
 public static void AddMessageLogger(IMessageLogger messageLogger)
 {
     lock (serviceLock)
     {
         messageLoggers.Add(messageLogger);
     }
 }
        private Task HandleReaction(Cacheable <IUserMessage, ulong> msg,
                                    ISocketMessageChannel ch, SocketReaction r)
        {
            var _ = Task.Run(() =>
            {
                if (_emote.Name != r.Emote.Name)
                {
                    return;
                }
                var gu = (r.User.IsSpecified ? r.User.Value : null) as IGuildUser;
                if (gu == null || // no unknown users, as they could be bots, or alts
                    msg.Id != _msg.Id || // same message
                    gu.IsBot || // no bots
                    (DateTime.UtcNow - gu.CreatedAt).TotalDays <= 5 || // no recently created accounts
                    (_noRecentlyJoinedServer &&                                                     // if specified, no users who joined the server in the last 24h
                     (gu.JoinedAt == null || (DateTime.UtcNow - gu.JoinedAt.Value).TotalDays < 1))) // and no users for who we don't know when they joined
                {
                    return;
                }
                // there has to be money left in the pot
                // and the user wasn't rewarded
                if (_awardedUsers.Add(r.UserId) && TryTakeFromPot())
                {
                    _toAward.Enqueue(r.UserId);
                    if (_isPotLimited && PotSize < _amount)
                    {
                        PotEmptied = true;
                    }
                }
            });

            return(Task.CompletedTask);
        }
        public override void VisitNamespace(INamespaceSymbol symbol)
        {
            // Add to the namespace symbol cache
            string displayName = symbol.GetDisplayName();
            ConcurrentHashSet <INamespaceSymbol> symbols = _namespaceDisplayNameToSymbols.GetOrAdd(displayName, _ => new ConcurrentHashSet <INamespaceSymbol>());

            symbols.Add(symbol);

            // Create the document (but not if none of the members would be included)
            if (ShouldIncludeSymbol(symbol, x => _symbolPredicate == null || x.GetMembers().Any(m => _symbolPredicate(m, _compilation))))
            {
                _namespaceDisplayNameToDocument.AddOrUpdate(
                    displayName,
                    _ => AddNamespaceDocument(symbol, true),
                    (_, existing) =>
                {
                    // There's already a document for this symbol display name, add it to the symbol-to-document cache
                    _symbolToDocument.TryAdd(symbol, existing);
                    return(existing);
                });
            }

            // Descend if not finished, regardless if this namespace was included
            if (!_finished)
            {
                Parallel.ForEach(symbol.GetMembers(), s => s.Accept(this));
            }
        }
Exemple #27
0
        public async Task HentaiBomb([Remainder] string tag = null)
        {
            if (!_hentaiBombBlacklist.Add(Context.Guild?.Id ?? Context.User.Id))
            {
                return;
            }
            try
            {
                var images = await Task.WhenAll(Service.DapiSearch(tag, DapiSearchType.Gelbooru, Context.Guild?.Id, true),
                                                Service.DapiSearch(tag, DapiSearchType.Danbooru, Context.Guild?.Id, true),
                                                Service.DapiSearch(tag, DapiSearchType.Konachan, Context.Guild?.Id, true),
                                                Service.DapiSearch(tag, DapiSearchType.Yandere, Context.Guild?.Id, true)).ConfigureAwait(false);

                var linksEnum = images?.Where(l => l != null).ToArray();
                if (images == null || !linksEnum.Any())
                {
                    await ReplyErrorLocalized("not_found").ConfigureAwait(false);

                    return;
                }

                await Context.Channel.SendMessageAsync(string.Join("\n\n", linksEnum.Select(x => x.FileUrl))).ConfigureAwait(false);
            }
            finally
            {
                _hentaiBombBlacklist.TryRemove(Context.Guild?.Id ?? Context.User.Id);
            }
        }
        public ulong?ToggleGameVoiceChannel(ulong guildId, ulong vchId)
        {
            ulong?id;

            using (var uow = _db.UnitOfWork)
            {
                var gc = uow.GuildConfigs.For(guildId, set => set);

                if (gc.GameVoiceChannel == vchId)
                {
                    GameVoiceChannels.TryRemove(vchId);
                    id = gc.GameVoiceChannel = null;
                }
                else
                {
                    if (gc.GameVoiceChannel != null)
                    {
                        GameVoiceChannels.TryRemove(gc.GameVoiceChannel.Value);
                    }
                    GameVoiceChannels.Add(vchId);
                    id = gc.GameVoiceChannel = vchId;
                }

                uow.Complete();
            }
            return(id);
        }
        public bool ToggleCurrencyGeneration(ulong gid, ulong cid)
        {
            bool enabled;

            using (var uow = _db.UnitOfWork)
            {
                var guildConfig = uow.GuildConfigs.ForId(gid, set => set.Include(gc => gc.GenerateCurrencyChannelIds));

                var toAdd = new GCChannelId()
                {
                    ChannelId = cid
                };
                if (!guildConfig.GenerateCurrencyChannelIds.Contains(toAdd))
                {
                    guildConfig.GenerateCurrencyChannelIds.Add(toAdd);
                    _generationChannels.Add(cid);
                    enabled = true;
                }
                else
                {
                    var toDelete = guildConfig.GenerateCurrencyChannelIds.FirstOrDefault(x => x.Equals(toAdd));
                    if (toDelete != null)
                    {
                        uow._context.Remove(toDelete);
                    }
                    _generationChannels.TryRemove(cid);
                    enabled = false;
                }
                uow.Complete();
            }
            return(enabled);
        }
        private static void ExerciseFullApi(ConcurrentHashSet <int> hashSet, int[] numbersToAdd)
        {
            dynamic _;

            foreach (var number in numbersToAdd)
            {
                hashSet.Add(number);
            }

            var index             = 0;
            var genericEnumerator = hashSet.GetEnumerator();

            while (index < numbersToAdd.Length && genericEnumerator.MoveNext())
            {
                _ = genericEnumerator.Current;
            }

            index = 0;
            var nongenericEnumerator = ((IEnumerable)hashSet).GetEnumerator();

            while (index < numbersToAdd.Length && nongenericEnumerator.MoveNext())
            {
                _ = nongenericEnumerator.Current;
            }

            _ = hashSet.Count;
            var destinationArray = new int[500];

            hashSet.CopyTo(destinationArray, 0);
            _ = hashSet.Contains(numbersToAdd.First());
            hashSet.Remove(numbersToAdd.First());
            hashSet.Clear();
        }
 public async Task Scsc(IUserMessage msg)
 {
     var channel = (ITextChannel)msg.Channel;
     var token = new NadekoRandom().Next();
     var set = new ConcurrentHashSet<ITextChannel>();
     if (Subscribers.TryAdd(token, set))
     {
         set.Add(channel);
         await ((IGuildUser)msg.Author).SendMessageAsync("This is your CSC token:" + token.ToString()).ConfigureAwait(false);
     }
 }
        /// <summary>
        ///     Remove nodes that are to be omitted due to an #if !SharpNative or the else of an #if SharpNative
        /// </summary>
        /// <param name="tree"></param>
        /// <returns></returns>
        public static IEnumerable<SyntaxNode> DoNotWrite(SyntaxTree tree)
        {
            var triviaProcessed = new ConcurrentHashSet<SyntaxTrivia>();

            var skipCount = 0;
            //set to 1 if we encounter a #if !SharpNative directive (while it's 0).  Incremented for each #if that's started inside of that, and decremented for each #endif
            var elseCount = 0;
            //set to 1 if we encounter an #if SharpNative directive (while it's 0).  Incremented for each #if that's started inside of that, and decremented for each #endif

            var ret = new List<SyntaxNode>();

            Action<SyntaxNodeOrToken> recurse = null;
            recurse = node =>
            {
                Action<SyntaxTrivia> doTrivia = trivia =>
                {
                    if (!triviaProcessed.Add(trivia))
                        return;

                    if (trivia.RawKind == (decimal)SyntaxKind.EndIfDirectiveTrivia)
                    {
                        if (skipCount > 0)
                            skipCount--;
                        if (elseCount > 0)
                            elseCount--;
                    }
                    else if (trivia.RawKind == (decimal)SyntaxKind.IfDirectiveTrivia)
                    {
                        if (skipCount > 0)
                            skipCount++;
                        if (elseCount > 0)
                            elseCount++;

                        var cond = GetConditions(trivia, "#if ");

                        if (cond.Contains("!SharpNative") && skipCount == 0)
                            skipCount = 1;
                        else if (cond.Contains("SharpNative") && elseCount == 0)
                            elseCount = 1;
                    }
                    else if (trivia.RawKind == (decimal)SyntaxKind.ElseDirectiveTrivia)
                    {
                        if (elseCount == 1)
                        {
                            skipCount = 1;
                            elseCount = 0;
                        }
                    }
                };

                foreach (var trivia in node.GetLeadingTrivia())
                    doTrivia(trivia);

                if (skipCount > 0 && node.IsNode)
                    ret.Add(node.AsNode());

                foreach (var child in node.ChildNodesAndTokens())
                    recurse(child);

                foreach (var trivia in node.GetTrailingTrivia())
                    doTrivia(trivia);
            };

            var root = tree.GetRoot();
            recurse(root);

            return ret;
        }
        public void TestLockFreeHashSet_Guid()
        {
            ICollection<Guid> listTest = new ConcurrentHashSet<Guid>();

            Enumerable.Range(0, 50000)
                .ForEach(e => listTest.Add(Guid.NewGuid()));

        }
        public void TestLockFreeHashSet_Stream()
        {
            ICollection<Stream> listTest = new ConcurrentHashSet<Stream>();

            MemoryStream ms1 = new MemoryStream();
            MemoryStream ms2 = new MemoryStream();

            try
            {
                Enumerable.Range(0, 5000)
                    .Convert(i => new MemoryStream())
                    .InsertAtPosition(ms1, 455)
                    .ForEach(s => listTest.Add(s));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            Assert.IsTrue(listTest.Count == 5001);
            Assert.IsTrue(listTest.Contains(ms1));
            Assert.IsFalse(listTest.Contains(ms2));
        }
        public void TestLockFreeHashSet_Long()
        {
            ConcurrentHashSet<long> listTest = new ConcurrentHashSet<long>();

            listTest.Add(42);
            listTest.Add(22);
            listTest.Add(22);
            listTest.Add(64);
            listTest.Add(55);

            Assert.IsTrue(listTest.Count == 4);

            Assert.IsTrue(listTest.Contains(42));
            Assert.IsFalse(listTest.Contains(142));
            Assert.IsFalse(listTest.Contains(2));
            Assert.IsTrue(listTest.Contains(64));

            listTest.Remove(42);
            Assert.IsFalse(listTest.Contains(42));
            Assert.IsFalse(listTest.Remove(42));
            Assert.IsTrue(listTest.Count == 3);

            listTest.Add(42);
            listTest.Add(41);
            listTest.Add(0);

            Assert.IsTrue(listTest.Count == 6);

            listTest.Add(0);
            Assert.IsTrue(listTest.Count == 6);


            Assert.IsTrue(listTest.Contains(41));
            Assert.IsTrue(listTest.Contains(0));

            Assert.IsTrue(listTest.Remove(0));

            Assert.IsFalse(listTest.Contains(0));


            Assert.IsTrue(listTest.Remove(22));
            Assert.IsTrue(listTest.Remove(55));

            listTest.Add(1212);
            listTest.Add(323);
            listTest.Add(7567);
            listTest.Add(567);

            Assert.IsTrue(listTest.Count == 7);

        }