public void TestMultiValueDictionary()
        {
            var dict = new MultiValueDictionary<int, int>();

            dict.Add(1, 1);
            dict.Add(1, 2);

            int val;

            Assert.IsTrue(dict.TryRemove(1, out val));
            Assert.AreEqual(2, val);

            Assert.IsTrue(dict.TryRemove(1, out val));
            Assert.AreEqual(1, val);

            Assert.IsFalse(dict.TryRemove(1, out val));

            dict.Add(2, 1);
            dict.Add(2, 2);
            dict.Remove(2, 3);
            dict.Remove(2, 2);

            Assert.IsTrue(dict.TryRemove(2, out val));
            Assert.AreEqual(1, val);
        }
        public void MultiValueDictionary_Add()
        {
            var mvd = new MultiValueDictionary<int, int>();
            mvd.Add(5, 42);
            mvd.Add(5, 42);
            mvd.Add(42, 42);

            Assert.AreEqual(2, mvd.Keys.Count);
            Assert.AreEqual(2, mvd[5].Count);
        }
 public static void ShouldNotGetValue()
 {
     var multiDict = new MultiValueDictionary<string, string>();
     multiDict.Add("key", "value");
     foreach(var value in values1)
     {
         multiDict.Add("key2", value);
     }
     IReadOnlyCollection<string> values;
     Assert.IsFalse(multiDict.TryGetValue("海亀", out values));
 }
        public static void ShouldAddAndTryGetValue()
        {
            var multiDict = new MultiValueDictionary<string, string>();
            multiDict.Add("key", "value");
            IReadOnlyCollection<string> values;

            Assert.IsTrue(multiDict.TryGetValue("key", out values));
            Assert.AreSame("value", values.First());

            foreach(var value in values1)
            {
                multiDict.Add("key2", value);
            }

            Assert.IsTrue(multiDict.TryGetValue("key2", out values));
            CollectionAssert.AreEqual(values1, values);
        }
Beispiel #5
0
 public void Add(int size)
 {
     MultiValueDictionary<int, int> dict = CreateMVD(size);
     foreach (var iteration in Benchmark.Iterations)
     {
         MultiValueDictionary<int, int> copyDict = new MultiValueDictionary<int, int>(dict);
         using (iteration.StartMeasurement())
             for (int i = 0; i <= 20000; i++)
             {
                 copyDict.Add(i * 10 + 1, 0); copyDict.Add(i * 10 + 2, 0); copyDict.Add(i * 10 + 3, 0);
                 copyDict.Add(i * 10 + 4, 0); copyDict.Add(i * 10 + 5, 0); copyDict.Add(i * 10 + 6, 0);
                 copyDict.Add(i * 10 + 7, 0); copyDict.Add(i * 10 + 8, 0); copyDict.Add(i * 10 + 9, 0);
             }
     }
 }
Beispiel #6
0
        public static MultiValueDictionary<int, int> CreateMVD(int size)
        {
            MultiValueDictionary<int, int> mvd = new MultiValueDictionary<int, int>();
            Random rand = new Random(11231992);

            while (mvd.Count < size)
                mvd.Add(rand.Next(), rand.Next());

            return mvd;
        }
 public static void ShouldClear()
 {
     var multiDict = new MultiValueDictionary<string, string>();
     multiDict.AddRange("key2", values2);
     multiDict.AddRange("key1", values1);
     multiDict.Add("key3", "海亀");
     multiDict.Clear();
     IReadOnlyCollection<string> values;
     Assert.IsFalse(multiDict.TryGetValue("海亀", out values));
     Assert.IsFalse(multiDict.TryGetValue("key1", out values));
     Assert.IsFalse(multiDict.TryGetValue("key2", out values));
     Assert.IsFalse(multiDict.TryGetValue("key3", out values));
 }
        public static void ShouldContainValue()
        {
            var multiDict = new MultiValueDictionary<int, string>();
            multiDict.AddRange(100, values2);
            multiDict.AddRange(-5, values1);
            multiDict.Add(1337, "海亀");

            Assert.IsTrue(multiDict.ContainsValue("dojpa2"));
            Assert.IsTrue(multiDict.ContainsValue("海亀"));
            Assert.IsTrue(multiDict.ContainsValue("test4"));
            Assert.IsTrue(multiDict.Contains("海亀"));
            Assert.IsTrue(multiDict.Contains("test1"));
            Assert.IsTrue(multiDict.Contains("dojpa4"));
        }
Beispiel #9
0
        public void Remove(int size)
        {
            MultiValueDictionary<int, int> dict = new MultiValueDictionary<int, int>();
            for (int i = 0; i < size; i++)
                for (int j = 0; j < 100; j++)
                    dict.Add(i, j);

            foreach (var iteration in Benchmark.Iterations)
            {
                MultiValueDictionary<int, int> copyDict = new MultiValueDictionary<int, int>(dict);
                using (iteration.StartMeasurement())
                    for (int i = 0; i <= size; i++)
                    {
                        copyDict.Remove(i);
                    }
            }
        }
        private void Log(EventWrittenEventArgs eventData)
        {
            NestedLoggerHandler?.Invoke(eventData);

            string s = FormattingEventListener.CreateFullMessageString(eventData, eventData.Level.ToString(), eventData.Message, m_baseTime, false);

            lock (m_logMessagesLock)
            {
                m_logMessages.Add(s);
                m_logMessagesPerEventId.Add(eventData.EventId, s);
            }

            if (m_logAction != null)
            {
                m_logAction(s);
            }
            else
            {
                Console.WriteLine(s);
            }

            // increase the use counter associated with the given event id.
            m_eventCounter.AddOrUpdate(eventData.EventId, 1, (k, v) => v + 1);

            // Increase per-path counters if applicable.
            string pathKey = TryGetPathKey(eventData.EventId, eventData.Payload);

            if (pathKey != null)
            {
                Dictionary <string, int> pathCounters = m_eventsByPathCounter.GetOrAdd(
                    eventData.EventId,
                    k => new Dictionary <string, int>(OperatingSystemHelper.PathComparer));

                lock (pathCounters)
                {
                    int existingCount;
                    pathCounters.TryGetValue(pathKey, out existingCount);
                    pathCounters[pathKey] = existingCount + 1;
                }
            }
        }
Beispiel #11
0
        public async Task Run_RemovesNotificationFromRepository()
        {
            var notificationsToRelease = new MultiValueDictionary <NotificationBuffer, BufferedNotification>();

            NotificationBuffer buffer1 = new NotificationBuffer(Guid.NewGuid(), bufferGovernor1.Id,
                                                                notificationPipeline1.Id);

            inMemoryCrudRepository.Attach(buffer1);
            BufferedNotification notification1 = new BufferedNotification(Guid.NewGuid(), "Notification1", "{}",
                                                                          buffer1, DateTime.Today);

            notificationsToRelease.Add(buffer1, notification1);
            inMemoryCrudRepository.Attach(notification1);

            bufferGovernor1.SelectNotificationsForReleaseAsync(inMemoryCrudRepository)
            .Returns(notificationsToRelease);

            await sut.Run();

            Assert.DoesNotContain(notification1, inMemoryCrudRepository.FindAll <BufferedNotification>());
        }
Beispiel #12
0
        private static int GetTreeNodeHeights(SyntaxNode root, MultiValueDictionary <int, SyntaxNode> heights)
        {
            bool isExpressionNode = root.GetAnnotations("Node").Any();
            int  thisHeight       = isExpressionNode ? 1 : 0;
            int  maxChildHeight   = 0;

            foreach (var node in root.ChildNodes())
            {
                int nodeHeight = GetTreeNodeHeights(node, heights);
                if (nodeHeight > maxChildHeight)
                {
                    maxChildHeight = nodeHeight;
                }
            }
            if (isExpressionNode)
            {
                heights.Add(thisHeight + maxChildHeight, root);
                //Console.WriteLine("Syntax: " + root + "; height=" + (thisHeight + maxChildHeight));
            }
            return(thisHeight + maxChildHeight);
        }
Beispiel #13
0
 private static void RefreshServices()
 {
     ServiceCacheLock.EnterWriteLock();
     ServiceCacheTime = DateTime.Now;
     ServiceCache.Clear();
     ServiceCacheByPID.Clear();
     foreach (ServiceController sc in ServiceController.GetServices())
     {
         ServiceInfo info = new ServiceInfo(sc);
         if (!ServiceCache.ContainsKey(sc.ServiceName)) // should not happen but in case
         {
             ServiceCache.Add(sc.ServiceName, info);
         }
         if (info.LastKnownPID != -1)
         {
             ServiceCacheByPID.Add(info.LastKnownPID, info);
         }
     }
     // this takes roughly 30 ms
     ServiceCacheLock.ExitWriteLock();
 }
Beispiel #14
0
        internal bool OnEvent(string eventType, Value128 id, out object data)
        {
            var contains = _eventsRaised.Contains(eventType, id);

            if (contains)
            {
                _eventsRaised.Remove(eventType, id);
                _eventsHandled.Remove(id, eventType);

                data = _eventData[id];
                if (data != null)
                {
                    _eventData.Remove(id);
                }
                return(true);
            }

            _eventsHandled.Add(id, eventType);
            data = default;
            return(false);
        }
        /** <inheritdoc /> */
        public void LocalListen <T>(IMessageListener <T> listener, object topic = null)
        {
            IgniteArgumentCheck.NotNull(listener, "filter");

            ResourceProcessor.Inject(listener, _ignite);

            lock (_funcMap)
            {
                var key = GetKey(listener, topic);

                MessageListenerHolder filter0 = MessageListenerHolder.CreateLocal(_ignite, listener);

                var filterHnd = _ignite.HandleRegistry.Allocate(filter0);

                filter0.DestroyAction = () =>
                {
                    lock (_funcMap)
                    {
                        _funcMap.Remove(key, filterHnd);
                    }
                };

                try
                {
                    DoOutOp((int)Op.LocalListen, writer =>
                    {
                        writer.WriteLong(filterHnd);
                        writer.Write(topic);
                    });
                }
                catch (Exception)
                {
                    _ignite.HandleRegistry.Release(filterHnd);

                    throw;
                }

                _funcMap.Add(key, filterHnd);
            }
        }
        public void Ctor_Comparer_SmokeAdd_ShouldSucceed()
        {
            // A mask value of -2 (0xFFFFFFFE) causes the lowest bit to be ignored,
            // such as treating 0 and 1 as same; 2 and 3, and so on.
            const int maskValue = -2;
            var       bmic      = new BitMaskedIntComparer(maskValue);
            var       mvdii     = new MultiValueDictionary <int, int>(bmic, bmic);

            mvdii.Add(0, 100);
            mvdii.Add(1, 101);
            mvdii.Add(1, 201);
            mvdii.Add(2, 102);
            mvdii.Add(3, 103);
            mvdii.Add(3, 203);
            Assert.Pass();
        }
        private MultiValueDictionary <string, string> GetHeaders(IEnumerator <string> enumerator)
        {
            var    headers    = new List <Header>();
            Header prevHeader = null;

            while (enumerator.MoveNext())
            {
                string line = enumerator.Current;
                if (string.IsNullOrEmpty(line))
                {
                    // no more headers (skip empty line)
                    break;
                }
                if (char.IsWhiteSpace(line[0]) && prevHeader != null)
                {
                    prevHeader.Value += " " + line.Trim();
                }
                else
                {
                    int splitPos = line.IndexOf(':');
                    if (splitPos < 0)
                    {
                        log.LogError("Invalid header line: {Line} Expected: {{key}}:{{value}}", line);
                    }
                    else
                    {
                        prevHeader = new Header(line.Substring(0, splitPos), line.Substring(splitPos + 1).Trim());
                        headers.Add(prevHeader);
                    }
                }
            }

            var dict = new MultiValueDictionary <string, string>();

            foreach (Header header in headers)
            {
                dict.Add(header.Key, header.Value);
            }
            return(dict);
        }
        public async Task HandleAsync_RemovesNotificationFromRepository()
        {
            var notificationsToRelease = new MultiValueDictionary <NotificationBuffer, BufferedNotification>();

            NotificationBuffer buffer1 = new NotificationBuffer(Guid.NewGuid(), bufferGovernor1.Id,
                                                                notificationPipeline1.Id);

            inMemoryCrudRepository.Attach(buffer1);
            BufferedNotification notification1 = new BufferedNotification(Guid.NewGuid(), "Notification1", "{}",
                                                                          buffer1, DateTime.Today);

            notificationsToRelease.Add(buffer1, notification1);
            inMemoryCrudRepository.Attach(notification1);

            bufferGovernor1.SelectNotificationsForReleaseAsync(inMemoryCrudRepository)
            .Returns(notificationsToRelease);

            var job = new ProcessBufferedNotificationsJob(Clock.Current.Now);
            await sut.HandleAsync(job, CancellationToken.None);

            Assert.DoesNotContain(notification1, inMemoryCrudRepository.FindAll <BufferedNotification>());
        }
Beispiel #19
0
        public void Remove(int size)
        {
            MultiValueDictionary <int, int> dict = new MultiValueDictionary <int, int>();

            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < 100; j++)
                {
                    dict.Add(i, j);
                }
            }

            foreach (var iteration in Benchmark.Iterations)
            {
                MultiValueDictionary <int, int> copyDict = new MultiValueDictionary <int, int>(dict);
                using (iteration.StartMeasurement())
                    for (int i = 0; i <= size; i++)
                    {
                        copyDict.Remove(i);
                    }
            }
        }
Beispiel #20
0
        protected virtual void HandleResponse(HttpWebResponse response)
        {
            string htmlString = DecompressHtml(response);

            jobStatus = JobStatus.HandlingResponse;
            if (htmlString != string.Empty)
            {
                MultiValueDictionary <string, ObjectId> links = new MultiValueDictionary <string, ObjectId>();
                foreach (HtmlResults feed in results.Values)
                {
                    HashSet <string> filteredLinks = feed.FilterByTags(htmlString, domain);
                    foreach (string link in filteredLinks)
                    {
                        links.Add(link, feed.resultsid);
                    }
                }

                jobStatus = JobStatus.LoadingPages;
                LoadChildPages(links);

                foreach (ChildPage page in childPages)
                {
                    foreach (ObjectId jobId in page.jobIds)
                    {
                        results[jobId].AddChildPage(page);
                    }
                }

                jobStatus = JobStatus.RankingPages;
                foreach (HtmlResults feed in results.Values)
                {
                    feed.ProcessKeywordScores();
                }

                jobStatus = JobStatus.Finished;
                timeStamp = DateTime.UtcNow;
                WebCrawler.Instance.EnqueueResult(this);
            }
        }
Beispiel #21
0
        private static MultiValueDictionary <string, FileInfo> matchIntoGroups(SearchOptions options, List <FileInfo> candidates, CancellationToken cancel)
        {
            switch (options.matcherType)
            {
            case MatcherType.Always:
            {
                var singleGroup = new MultiValueDictionary <string, FileInfo>();
                foreach (FileInfo file in candidates)
                {
                    singleGroup.Add("Any", file);
                }
                return(ComparisonUtils.removeOneElementGroups(singleGroup));
            }

            case MatcherType.Length:
            {
                return(LengthMatcher.matchByLength(candidates));
            }

            case MatcherType.LengthHash:
            {
                return(HashContentMatcher.matchByHashOrContent(candidates, options.matcherType, cancel));
            }

            case MatcherType.LengthHashContent:
            {
                return(HashContentMatcher.matchByHashOrContent(candidates, options.matcherType, cancel));
            }

            case MatcherType.Similarity:
            {
                return(SimilarityMatcher.matchBySimilarity(candidates, options.similarityMatcherThreshold, cancel));
            }

            default:
                throw new ArgumentException("Invalid MatcherType!");
            }
        }
Beispiel #22
0
        public void ContainsKey(int size)
        {
            MultiValueDictionary <int, int> dict = CreateMVD(size);

            // Setup
            Random rand = new Random(837322);
            int    key  = rand.Next(0, 400000);

            dict.Add(key, 12);

            // Actual perf testing
            foreach (var iteration in Benchmark.Iterations)
            {
                using (iteration.StartMeasurement())
                    for (int i = 0; i <= 10000; i++)
                    {
                        dict.ContainsKey(key); dict.ContainsKey(key); dict.ContainsKey(key);
                        dict.ContainsKey(key); dict.ContainsKey(key); dict.ContainsKey(key);
                        dict.ContainsKey(key); dict.ContainsKey(key); dict.ContainsKey(key);
                        dict.ContainsKey(key); dict.ContainsKey(key); dict.ContainsKey(key);
                    }
            }
        }
Beispiel #23
0
        public void TryGetValue(int size)
        {
            MultiValueDictionary <int, int> dict = CreateMVD(size);
            // Setup
            IReadOnlyCollection <int> retrieved;
            Random rand = new Random(837322);
            int    key  = rand.Next(0, 400000);

            dict.Add(key, 12);

            // Actual perf testing
            foreach (var iteration in Benchmark.Iterations)
            {
                using (iteration.StartMeasurement())
                    for (int i = 0; i <= 1000; i++)
                    {
                        dict.TryGetValue(key, out retrieved); dict.TryGetValue(key, out retrieved);
                        dict.TryGetValue(key, out retrieved); dict.TryGetValue(key, out retrieved);
                        dict.TryGetValue(key, out retrieved); dict.TryGetValue(key, out retrieved);
                        dict.TryGetValue(key, out retrieved); dict.TryGetValue(key, out retrieved);
                    }
            }
        }
Beispiel #24
0
        public bool FindQueryName(int processId, IPAddress remoteAddress, object target, Action <object, string, NameSources> setter)
        {
            Dictionary <IPAddress, Dictionary <string, DnsCacheEntry> > dnsCache;

            if (dnsQueryCache.TryGetValue(processId, out dnsCache))
            {
                Dictionary <string, DnsCacheEntry> cacheEntries;
                if (dnsCache.TryGetValue(remoteAddress, out cacheEntries) && cacheEntries.Count > 0)
                {
                    // we found an entry
                    setter(target, cacheEntries.Keys.First(), NameSources.CapturedQuery);
                    return(true);
                }
            }

            HostObserveJob job = new HostObserveJob()
            {
                target = new WeakReference(target), setter = setter, processId = processId, remoteAddress = remoteAddress, timeOut = MiscFunc.GetUTCTime() + 30
            };

            ObserverJobs.Add(remoteAddress, job);
            return(false);
        }
Beispiel #25
0
        public void MultiValueDictionaryValuesTest()
        {
            MultiValueDictionary <Int32, String> dictionary = new MultiValueDictionary <Int32, String>();

            foreach (KeyValuePair <Int32, List <String> > value in this.values)
            {
                dictionary.Add(value.Key, value.Value);
            }

            List <ICollection <String> > expected = new List <ICollection <String> >()
            {
                new List <String>()
                {
                    "1", "11"
                } as ICollection <String>,
                new List <String>()
                {
                    "2", "22"
                } as ICollection <String>
            };

            dictionary.Values.ShouldBe(expected);
        }
        internal void UpdateDataForDownloadData(DownloadData downloadData, FrontEndContext context = null)
        {
            context = context ?? m_context;
            Contract.Assert(context != null);

            var name = downloadData.Settings.ModuleName;

            var moduleId   = ModuleId.Create(context.StringTable, name);
            var descriptor = new ModuleDescriptor(moduleId, name, name, string.Empty, Kind, Name);

            var definition = ModuleDefinition.CreateModuleDefinitionWithImplicitReferences(
                descriptor,
                downloadData.ModuleRoot,
                downloadData.ModuleConfigFile,
                new[] { downloadData.ModuleSpecFile },
                allowedModuleDependencies: null,
                cyclicalFriendModules: null); // A Download package does not have any module dependency restrictions nor whitelists cycles

            m_descriptors.Add(descriptor);
            m_descriptorsByName.Add(name, descriptor);
            m_descriptorsBySpecPath.Add(downloadData.ModuleSpecFile, descriptor);
            m_definitions.Add(descriptor, definition);
        }
Beispiel #27
0
        private static MultiValueDictionary <string, string> GetMetaData(NzbParserContext context, XContainer nzbElement)
        {
            XElement headElement = nzbElement.Element(context.Namespace + NzbKeywords.Head);

            if (headElement == null)
            {
                return(null);
            }

            IEnumerable <Tuple <string, string> > headers =
                from metaElement in headElement.Elements(context.Namespace + NzbKeywords.Meta)
                let typeAttribute = metaElement.Attribute(NzbKeywords.Type)
                                    where typeAttribute != null
                                    select new Tuple <string, string>(typeAttribute.Value, metaElement.Value);

            var dict = new MultiValueDictionary <string, string>();

            foreach (Tuple <string, string> header in headers)
            {
                dict.Add(header.Item1, header.Item2);
            }
            return(dict);
        }
Beispiel #28
0
        public static ICollection <AnnotatedTransaction> TopologicalSort(this ICollection <AnnotatedTransaction> transactions)
        {
            var confirmed   = new MultiValueDictionary <int, AnnotatedTransaction>();
            var unconfirmed = new List <AnnotatedTransaction>();
            var result      = new List <AnnotatedTransaction>(transactions.Count);

            foreach (var tx in transactions)
            {
                if (tx.Height is int h)
                {
                    confirmed.Add(h, tx);
                }
                else
                {
                    unconfirmed.Add(tx);
                }
            }
            foreach (var tx in confirmed.OrderBy(o => o.Key))
            {
                if (tx.Value.Count == 1)
                {
                    result.Add(tx.Value.First());
                }
                else
                {
                    foreach (var tx2 in tx.Value.TopologicalSortCore())
                    {
                        result.Add(tx2);
                    }
                }
            }
            foreach (var tx in unconfirmed.TopologicalSortCore())
            {
                result.Add(tx);
            }
            return(result);
        }
Beispiel #29
0
        public void EnumeratorWithItems()
        {
            var originalPairs = new KeyValuePair <string, int>[] {
                new KeyValuePair <string, int>("first", 1),
                new KeyValuePair <string, int>("first", 2),
                new KeyValuePair <string, int>("first", 3),
                new KeyValuePair <string, int>("second", 4),
                new KeyValuePair <string, int>("second", 5),
                new KeyValuePair <string, int>("second", 6),
                new KeyValuePair <string, int>("third", 7),
            };

            var dict = new MultiValueDictionary <string, int>();

            for (int i = 0; i < originalPairs.Length; i++)
            {
                dict.Add(originalPairs[i].Key, originalPairs[i].Value);
            }

            var result = new List <KeyValuePair <string, int> >();

            foreach (var pair in dict)
            {
                result.Add(pair);
            }

            Assert.AreEqual(
                originalPairs.Length,
                result.Count,
                "Result is the expected length"
                );
            CollectionAssert.AreEquivalent(
                originalPairs,
                result,
                "Result contains the same pairs that were inserted"
                );
        }
Beispiel #30
0
        private void ConnectDecodedMethods(Assembly assembly)
        {
            foreach (var bridgeProcessorType in assembly.GetTypes().Where(x => typeof(BridgeCpu).IsAssignableFrom(x)))
            {
                object instance = null;

                foreach (var methodInfo in bridgeProcessorType.GetMethods(BindingFlags.Instance | BindingFlags.Public))
                {
                    var attribute = methodInfo.GetCustomAttribute <MethodInfoAttribute>();
                    if (attribute == null)
                    {
                        continue;
                    }

                    var mi = MethodInfoCollection.GetByIdOrNull(attribute.Id);
                    if (mi == null)
                    {
                        continue;
                    }

                    if (instance == null)
                    {
                        instance = Activator.CreateInstance(bridgeProcessorType, Implementation);
                        foreach (var pi in bridgeProcessorType.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(x => x.PropertyType == typeof(RawProgramMain)))
                        {
                            pi.SetValue(instance, this);
                        }
                    }

                    var fi = new MyMethodInfo();
                    fi.MethodInfo = mi;
                    fi.Action     = (Action)methodInfo.CreateDelegate(typeof(Action), instance);

                    MethodsByAddress.Add(mi.Address, fi);
                }
            }
        }
Beispiel #31
0
        private void AddCacheEntry(CloneableList <DnsCacheEntry> curEntries, DnsCacheEntry curEntry)
        {
            curEntries.Add(curEntry);

            if ((curEntry.RecordType == DnsApi.DnsRecordType.A || curEntry.RecordType == DnsApi.DnsRecordType.AAAA) && curEntry.Address != null)
            {
                if (curEntry.Address != null)
                {
                    cacheByIP.Add(curEntry.Address, curEntry);
                }
            }
            else if (curEntry.ResolvedString != null) // CNAME, SRV, MX, DNAME
            {
                if (curEntry.ResolvedString != null)
                {
                    cacheByStr.Add(curEntry.ResolvedString, curEntry);
                }
            }

            DnsCacheEvent?.Invoke(this, new DnsEvent()
            {
                Entry = curEntry
            });
        }
Beispiel #32
0
        public void MultiValueDictionaryRemoveTest()
        {
            MultiValueDictionary <Int32, String> dictionary = new MultiValueDictionary <Int32, String>();

            foreach (KeyValuePair <Int32, List <String> > value in this.values)
            {
                dictionary.Add(value.Key, value.Value);
            }

            dictionary.Remove(0, "0").ShouldBeFalse();
            dictionary.Remove(1, "1").ShouldBeTrue();
            dictionary.Remove(1, "1").ShouldBeFalse();
            dictionary.Remove(1, "11").ShouldBeTrue();
            dictionary.Remove(1, "11").ShouldBeFalse();

            dictionary = new MultiValueDictionary <Int32, String>();

            foreach (KeyValuePair <Int32, List <String> > value in this.values)
            {
                dictionary.Add(value.Key, value.Value);
            }

            dictionary.Remove(0).ShouldBeFalse();
            dictionary.Remove(1).ShouldBeTrue();
            dictionary.Remove(1).ShouldBeFalse();

            (dictionary as ICollection <KeyValuePair <Int32, ICollection <String> > >).Add(new KeyValuePair <Int32, ICollection <String> >(3, new List <String> {
                "3"
            } as ICollection <String>));
            (dictionary as ICollection <KeyValuePair <Int32, ICollection <String> > >).Remove(new KeyValuePair <Int32, ICollection <String> >(3, new List <String> {
                "3"
            } as ICollection <String>)).ShouldBeTrue();
            (dictionary as ICollection <KeyValuePair <Int32, ICollection <String> > >).Remove(new KeyValuePair <Int32, ICollection <String> >(3, new List <String> {
                "3"
            } as ICollection <String>)).ShouldBeFalse();
        }
Beispiel #33
0
        public void GetItem(int size)
        {
            MultiValueDictionary <int, int> dict = CreateMVD(size);

            // Setup
            IReadOnlyCollection <int> retrieved;

            for (int i = 1; i <= 9; i++)
            {
                dict.Add(i, 0);
            }

            // Actual perf testing
            foreach (var iteration in Benchmark.Iterations)
            {
                using (iteration.StartMeasurement())
                    for (int i = 0; i <= 10000; i++)
                    {
                        retrieved = dict[1]; retrieved = dict[2]; retrieved = dict[3];
                        retrieved = dict[4]; retrieved = dict[5]; retrieved = dict[6];
                        retrieved = dict[7]; retrieved = dict[8]; retrieved = dict[9];
                    }
            }
        }
        public void MultiValueDictionaryRemoveTest()
        {
            MultiValueDictionary <Int32, String> dictionary = new MultiValueDictionary <Int32, String>();

            foreach (KeyValuePair <Int32, List <String> > item in _items)
            {
                dictionary.Add(item.Key, item.Value);
            }

            Assert.AreEqual(false, dictionary.Remove(0, "0"));
            Assert.AreEqual(true, dictionary.Remove(1, "1"));
            Assert.AreEqual(false, dictionary.Remove(1, "1"));
            Assert.AreEqual(true, dictionary.Remove(1, "11"));
            Assert.AreEqual(false, dictionary.Remove(1, "11"));

            dictionary = new MultiValueDictionary <Int32, String>();

            foreach (KeyValuePair <Int32, List <String> > item in _items)
            {
                dictionary.Add(item.Key, item.Value);
            }

            Assert.AreEqual(false, dictionary.Remove(0));
            Assert.AreEqual(true, dictionary.Remove(1));
            Assert.AreEqual(false, dictionary.Remove(1));

            (dictionary as ICollection <KeyValuePair <Int32, ICollection <String> > >).Add(new KeyValuePair <Int32, ICollection <String> >(3, new List <String> {
                "3"
            } as ICollection <String>));
            Assert.AreEqual(true, (dictionary as ICollection <KeyValuePair <Int32, ICollection <String> > >).Remove(new KeyValuePair <Int32, ICollection <String> >(3, new List <String> {
                "3"
            } as ICollection <String>)));
            Assert.AreEqual(false, (dictionary as ICollection <KeyValuePair <Int32, ICollection <String> > >).Remove(new KeyValuePair <Int32, ICollection <String> >(3, new List <String> {
                "3"
            } as ICollection <String>)));
        }
Beispiel #35
0
        private void CreateMappingForOutputs(Process process, out MultiValueDictionary <AbsolutePath, ExpandedAbsolutePath> originalDirectories, out MultiValueDictionary <ExpandedAbsolutePath, ExpandedAbsolutePath> redirectedDirectories)
        {
            // Collect all predicted outputs (directories and files) for the given process
            var directories = CollectAllOutputDirectories(m_pathTable, process);

            // In order to keep the filter configuration to its minimum, let's remove directories that are nested within each other
            var dedupDirectories = AbsolutePathUtilities.CollapseDirectories(directories, m_pathTable, out var originalToCollapsedMapping);

            var stringTable            = m_pathTable.StringTable;
            var reserveFoldersResolver = new ReserveFoldersResolver(new object());

            originalDirectories   = new MultiValueDictionary <AbsolutePath, ExpandedAbsolutePath>(originalToCollapsedMapping.Count);
            redirectedDirectories = new MultiValueDictionary <ExpandedAbsolutePath, ExpandedAbsolutePath>(dedupDirectories.Count, ExpandedAbsolutePathEqualityComparer.Instance);

            // Map from original dedup directories to unique redirected directories
            var uniqueRedirectedDirectories = new Dictionary <AbsolutePath, ExpandedAbsolutePath>(dedupDirectories.Count);

            foreach (var kvp in originalToCollapsedMapping)
            {
                AbsolutePath originalDirectory          = kvp.Key;
                AbsolutePath originalCollapsedDirectory = kvp.Value;

                if (!uniqueRedirectedDirectories.TryGetValue(originalCollapsedDirectory, out var uniqueRedirectedDirectory))
                {
                    uniqueRedirectedDirectory = GetUniqueRedirectedDirectory(process, ref reserveFoldersResolver, originalCollapsedDirectory).Expand(m_pathTable);

                    uniqueRedirectedDirectories.Add(originalCollapsedDirectory, uniqueRedirectedDirectory);
                    redirectedDirectories.Add(uniqueRedirectedDirectory, originalCollapsedDirectory.Expand(m_pathTable));
                }

                // Let's reconstruct the redirected directory
                var redirectedDirectory = originalDirectory.Relocate(m_pathTable, originalCollapsedDirectory, uniqueRedirectedDirectory.Path);

                originalDirectories.Add(originalDirectory, redirectedDirectory.Expand(m_pathTable));
            }
        }
Beispiel #36
0
        public virtual void Serialization()
        {
            var items = Enumerable.Range(0, 100).Select(_ =>
            {
                var key    = NextKey();
                var values = Enumerable.Range(0, 100).Select(__ => NextValue()).ToArray();
                return(new KeyValuePair <TKey, TValue[]>(key, values));
            }).ToDictionary(kv => kv.Key, kv => kv.Value);
            var data0 = new MultiValueDictionary <TKey, TValue>();

            foreach (var kv in items)
            {
                data0.Add(kv.Key, kv.Value);
            }
            var binaryFormatter = new BinaryFormatter();

            byte[] bin;
            using (var buffer = new MemoryStream())
            {
                binaryFormatter.Serialize(buffer, data0);
                bin = buffer.ToArray();
            }
            MultiValueDictionary <TKey, TValue> data1;

            using (var buffer = new MemoryStream(bin, false))
            {
                data1 = (MultiValueDictionary <TKey, TValue>)binaryFormatter.Deserialize(buffer);
            }
            Assert.Equal(data0, data1);
            Assert.Equal(data0.GetHashCode(), data1.GetHashCode());
            var data2 = data0.Clone();

            Assert.True(((object)data0).Equals(data2));
            Assert.False(((object)data0).Equals(null));
            Assert.False(((object)data0).Equals(2));
        }
Beispiel #37
0
        public void ParamsArrayAdd()
        {
            var col = new MultiValueDictionary <string, string>();

            col.Add("A", "2");
            col.Add("B", "2", "1");
            col.Add("A", "1");
            col.Add("C", "2", "1", "3");
            col.Add("A", "3");
            col.Add("B", "3");

            // Added in different order to ensure not sorted and insert-order is preserved.
            Assert.Equal(3, col.Count);
            Assert.Equal(3, col.Values.Count());
            Assert.Equal(3, col.Keys.Count());
            Assert.Equal(3, col["A"].Count);
            Assert.Equal(3, col["B"].Count);
            Assert.Equal(3, col["C"].Count);
            Assert.Equal(@"A[2,1,3] | B[2,1,3] | C[2,1,3]", Print(col));
        }
Beispiel #38
0
 public void SubscribeMouseButton(MouseButton mouseButton, Action action)
 {
     _mouseButtonDictionary.Add(mouseButton, action);
 }
Beispiel #39
0
        private static List<WorkItem> Process(string targetPath)
        {
            var pullPath = Path.Combine(targetPath, "pulls.json");
            var rawPulls = File.ReadAllText(pullPath);
            var issuePath = Path.Combine(targetPath, "issues.json");
            var rawIssues = File.ReadAllText(issuePath);

            var pulls = JsonConvert.DeserializeObject(rawPulls) as JArray;
            var issues = JsonConvert.DeserializeObject(rawIssues) as JArray;

            var allItems = new List<WorkItem>(issues.Count);

            MultiValueDictionary<int, int> issueRelations = new MultiValueDictionary<int, int>();

            foreach (var issue in issues)
            {
                var id = issue.Value<int>("number");
                var rawRelatedItems = issue.Value<JArray>("relatedIssues");
                var relatedItems = rawRelatedItems.Count == 0 ? new List<int>() : rawRelatedItems.Select(n => n.Value<int>()).ToList();
                foreach (var relatedItem in relatedItems)
                {
                    issueRelations.Add(id, relatedItem);
                    issueRelations.Add(relatedItem, id);
                }

                var newItem = new WorkItem()
                {
                    Id = id,
                    Url = issue.Value<string>("htmlUrl"),
                    Title = issue.Value<string>("title"),
                    Body = issue.Value<string>("body"),
                    Author = issue.Value<string>("submitter"),
                    CreationDate = issue.Value<DateTime>("createdAt"),
                };
                allItems.Add(newItem);
            }

            foreach (var item in allItems)
            {
                IReadOnlyCollection<int> knownRelations;
                if (!issueRelations.TryGetValue(item.Id, out knownRelations))
                    continue;
                item.RelatedItems = knownRelations;
            }


            foreach (var pull in pulls)
            {
                var id = pull.Value<int>("number");

                var earliestCommit = DateTime.MaxValue;
                var latestCommit = DateTime.MinValue;
                var commits = new List<Commit>();
                foreach (var commit in pull["commits"] as JArray)
                {
                    var commitDate = commit.Value<DateTime>("createdAt");

                    if (commitDate < earliestCommit)
                        earliestCommit = commitDate;
                    if (commitDate > latestCommit)
                        latestCommit = commitDate;

                    var commitItem = new Commit()
                    {
                        Date = commitDate,
                        Sha = commit.Value<string>("sha"),
                        Message = commit.Value<string>("message"),
                        Author = commit.Value<string>("committer"),
                    };
                    commits.Add(commitItem);
                }

                var closedAtString = pull.Value<string>("closedAt");
                DateTime closedAt;
                if (!(DateTime.TryParse(closedAtString, out closedAt)))
                {
                    closedAt = default(DateTime);
                }

                var originalItem = allItems.Single(n => n.Id == id);
                var pullRequest = new PullRequest(originalItem, commits)
                {
                    FirstCommit = earliestCommit,
                    LastCommit = latestCommit,
                    CloseDate = closedAt,
                    Sha = pull.Value<string>("sha"),
                    Branch = pull.Value<string>("branch"),
                };
                allItems[allItems.IndexOf(originalItem)] = pullRequest;
            }
            return allItems;
        }
Beispiel #40
0
        public MultiValueDictionary<DateTime, ITable> getTableDateList(DbTabellen tblName)
        {
            #region tabellen-auswahl
            string operation;
            if (tblName == DbTabellen.Person)
            {
                operation = @"SELECT Person.ID, Person.Vorname, Person.Name, Veranstaltung.Beginn FROM Veranstaltung INNER JOIN (Person INNER JOIN Teilnahme ON Person.ID = Teilnahme.Person) ON Veranstaltung.ID = Teilnahme.Veranstaltung WHERE Person.[Name] IS NOT NULL AND Person.[Vorname] IS NOT NULL AND Person.[Geschlecht] IS NOT NULL AND Person.[ID] IS NOT NULL ORDER BY Veranstaltung.Beginn ASC;";
            }
            else if (tblName == DbTabellen.Institution)
            {
                operation = @"SELECT Institution.ID, Institution.Kurzname, Institution.Name, Veranstaltung.Beginn
            FROM Veranstaltung INNER JOIN ((Institution RIGHT JOIN Person ON Institution.ID = Person.Institution) INNER JOIN Teilnahme ON Person.ID = Teilnahme.Person) ON Veranstaltung.ID = Teilnahme.Veranstaltung WHERE Institution.ID IS NOT NULL ORDER BY Veranstaltung.Beginn ASC;";
            }
            else
            {
                throw new NotImplementedException();
            }
            #endregion

            var institList = new MultiValueDictionary<DateTime, ITable>();

            using (var connection = new OleDbConnection(_connectionString))
            {
                OleDbCommand command = new OleDbCommand(operation, connection);
                connection.Open();
                using (OleDbDataReader dataReader = command.ExecuteReader())
                {

                    while (dataReader != null && dataReader.Read())
                    {
                       var tableItem = TableItemFactory.CreateTableItem(tableName, dataReader.GetInt32(0), dataReader.GetString(1), dataReader.GetString(2));
                        institList.Add(dataReader.GetDateTime(3), tableItem);

                    }

                }
                connection.Close();
            }
            return institList;
        }
        public static void ShouldContainKey()
        {
            var multiDict = new MultiValueDictionary<string, string>();
            multiDict.AddRange("key2", values2);
            multiDict.AddRange("key1", values1);
            multiDict.Add("key3", "海亀");

            Assert.IsTrue(multiDict.ContainsKey("key1"));
            Assert.IsTrue(multiDict.ContainsKey("key3"));
            Assert.IsTrue(multiDict.ContainsKey("key2"));
            Assert.IsTrue(multiDict.Contains("key1"));
            Assert.IsTrue(multiDict.Contains("key2"));
            Assert.IsTrue(multiDict.Contains("key3"));
        }
Beispiel #42
0
 private void Persist(Block block)
 {
     MultiValueDictionary<UInt256, ushort> unspents = new MultiValueDictionary<UInt256, ushort>(p =>
     {
         Slice value = new byte[0];
         db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.IX_Unspent).Add(p), out value);
         return new HashSet<ushort>(value.ToArray().GetUInt16Array());
     });
     MultiValueDictionary<UInt256, ushort> unspent_antshares = new MultiValueDictionary<UInt256, ushort>(p =>
     {
         Slice value = new byte[0];
         db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.IX_AntShare).Add(p), out value);
         return new HashSet<ushort>(value.ToArray().GetUInt16Array());
     });
     MultiValueDictionary<UInt256, ushort> unspent_votes = new MultiValueDictionary<UInt256, ushort>(p =>
     {
         Slice value = new byte[0];
         db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.IX_Vote).Add(p), out value);
         return new HashSet<ushort>(value.ToArray().GetUInt16Array());
     });
     Dictionary<UInt256, Fixed8> quantities = new Dictionary<UInt256, Fixed8>();
     WriteBatch batch = new WriteBatch();
     batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Block).Add(block.Hash), block.Trim());
     foreach (Transaction tx in block.Transactions)
     {
         batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Transaction).Add(tx.Hash), tx.ToArray());
         switch (tx.Type)
         {
             case TransactionType.IssueTransaction:
                 foreach (TransactionResult result in tx.GetTransactionResults().Where(p => p.Amount < Fixed8.Zero))
                 {
                     if (quantities.ContainsKey(result.AssetId))
                     {
                         quantities[result.AssetId] -= result.Amount;
                     }
                     else
                     {
                         quantities.Add(result.AssetId, -result.Amount);
                     }
                 }
                 break;
             case TransactionType.EnrollmentTransaction:
                 {
                     EnrollmentTransaction enroll_tx = (EnrollmentTransaction)tx;
                     batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Enrollment).Add(tx.Hash), true);
                 }
                 break;
             case TransactionType.VotingTransaction:
                 unspent_votes.AddEmpty(tx.Hash);
                 for (ushort index = 0; index < tx.Outputs.Length; index++)
                 {
                     if (tx.Outputs[index].AssetId == AntShare.Hash)
                     {
                         unspent_votes.Add(tx.Hash, index);
                     }
                 }
                 break;
             case TransactionType.RegisterTransaction:
                 {
                     RegisterTransaction reg_tx = (RegisterTransaction)tx;
                     batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Asset).Add(reg_tx.Hash), true);
                 }
                 break;
         }
         unspents.AddEmpty(tx.Hash);
         unspent_antshares.AddEmpty(tx.Hash);
         for (ushort index = 0; index < tx.Outputs.Length; index++)
         {
             unspents.Add(tx.Hash, index);
             if (tx.Outputs[index].AssetId == AntShare.Hash)
             {
                 unspent_antshares.Add(tx.Hash, index);
             }
         }
     }
     foreach (TransactionInput input in block.Transactions.SelectMany(p => p.GetAllInputs()))
     {
         if (input.PrevIndex == 0)
         {
             batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Enrollment).Add(input.PrevHash));
         }
         unspents.Remove(input.PrevHash, input.PrevIndex);
         unspent_antshares.Remove(input.PrevHash, input.PrevIndex);
         unspent_votes.Remove(input.PrevHash, input.PrevIndex);
     }
     //统计AntCoin的发行量
     {
         Fixed8 amount_in = block.Transactions.SelectMany(p => p.References.Values.Where(o => o.AssetId == AntCoin.Hash)).Sum(p => p.Value);
         Fixed8 amount_out = block.Transactions.SelectMany(p => p.Outputs.Where(o => o.AssetId == AntCoin.Hash)).Sum(p => p.Value);
         if (amount_in != amount_out)
         {
             quantities.Add(AntCoin.Hash, amount_out - amount_in);
         }
     }
     foreach (var unspent in unspents)
     {
         if (unspent.Value.Count == 0)
         {
             batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Unspent).Add(unspent.Key));
         }
         else
         {
             batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Unspent).Add(unspent.Key), unspent.Value.ToByteArray());
         }
     }
     foreach (var unspent in unspent_antshares)
     {
         if (unspent.Value.Count == 0)
         {
             batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_AntShare).Add(unspent.Key));
         }
         else
         {
             batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_AntShare).Add(unspent.Key), unspent.Value.ToByteArray());
         }
     }
     foreach (var unspent in unspent_votes)
     {
         if (unspent.Value.Count == 0)
         {
             batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Vote).Add(unspent.Key));
         }
         else
         {
             batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Vote).Add(unspent.Key), unspent.Value.ToByteArray());
         }
     }
     foreach (var quantity in quantities)
     {
         batch.Put(SliceBuilder.Begin(DataEntryPrefix.ST_QuantityIssued).Add(quantity.Key), (GetQuantityIssued(quantity.Key) + quantity.Value).GetData());
     }
     current_block_hash = block.Hash;
     current_block_height = block.Hash == GenesisBlock.Hash ? 0 : current_block_height + 1;
     batch.Put(SliceBuilder.Begin(DataEntryPrefix.SYS_CurrentBlock), SliceBuilder.Begin().Add(block.Hash).Add(current_block_height));
     db.Write(WriteOptions.Default, batch);
 }
Beispiel #43
0
        public override bool VisitSubrutine([NotNull] injectionParser.SubrutineContext context)
        {
            subrutines.Add(context.GetSubrutineKey(), context);

            return(true);
        }
Beispiel #44
0
        public static Automaton NfaToDfa(Automaton nfa, out MultiValueDictionary<State, State> dfaStatesToNfa)
        {
            var dfa = new Automaton();
            dfa.CaptureNames = nfa.CaptureNames;
            var dfaStartState = dfa.AddState();
            dfa.StartState = dfaStartState;
            var nfaTransitionsToDfa = new MultiValueDictionary<Transition, Transition>();
            var transitionClasses = new List<Transition>();
            var mergeStates = new HashSet<State>();
            dfaStatesToNfa = new MultiValueDictionary<State, State>();
            dfaStatesToNfa.Add(dfaStartState, nfa.StartState);
            //不动点算法,不能使用 foreach!
            for(int i = 0; i < dfa.States.Count; ++i)
            {
                var curDfaState = dfa.States[i];
                var nfaStates = dfaStatesToNfa[curDfaState];
                foreach(var nfaState in nfaStates)
                {
                    foreach(var outTransition in nfaState.Output)
                    {
                        if (!nfaTransitionsToDfa.Values.SelectMany(transitions => transitions).Contains(outTransition))
                        {
                            transitionClasses.Add(outTransition);
                            nfaTransitionsToDfa.Add(outTransition, outTransition);
                        }
                    }
                }

                foreach(var transitionClass in transitionClasses)
                {
                    var nfaTransitions = nfaTransitionsToDfa[transitionClass];
                    foreach(var nfaTransition in nfaTransitions)
                    {
                        var state = nfaTransition.End;
                        if (!mergeStates.Contains(state))
                            mergeStates.Add(state);
                    }

                    mergeStates.OrderBy(state => state);

                    //mergeStates 是候选的一个 DFA 状态。在这之前,还需要判断:这个候选状态是否已经存在于 DFA 中了?
                    //var isContained = dfaStatesToNfa.Values.Contains((IReadOnlyCollection<State>)mergeStates);
                    State newDfaState = null;
                    foreach(var dfaState in dfaStatesToNfa.Keys)
                    {
                        var prevNfaStates = dfaStatesToNfa[dfaState];
                        if (prevNfaStates.Count == mergeStates.Count &&
                            prevNfaStates.SequenceEqual(mergeStates))
                        {
                            newDfaState = dfaState;
                            break;
                        }
                    }
                    if(newDfaState == null)
                    {
                        newDfaState = dfa.AddState();
                        dfaStatesToNfa.AddRange(newDfaState, mergeStates);
                        newDfaState.IsFinalState = mergeStates.Any(state => state.IsFinalState);
                    }

                    var dfaTransition = dfa.AddTransition(curDfaState, newDfaState, transitionClass.TransitionType);
                    dfaTransition.Capture = transitionClass.Capture;
                    dfaTransition.Range = transitionClass.Range;
                    dfaTransition.Index = transitionClass.Index;
                    mergeStates.Clear();
                }
                transitionClasses.Clear();
                nfaTransitionsToDfa.Clear();
            }

            return dfa;
        }