Beispiel #1
0
        public void TokenFunctionTest(string equalsToken, string plusToken, int collectionSize)
        {
            var kvps = new KeyValuePair <string, string> [collectionSize];

            Random rand1 = new Random();

            for (int i = 0; i < collectionSize; i++)
            {
                kvps[i] = new KeyValuePair <string, string>($"key{i}", $"{Guid.NewGuid()}{Guid.NewGuid()}{Guid.NewGuid()}");
            }

            string value1 = kvps[rand1.Next(0, collectionSize - 1)].Value;
            string value2 = kvps[rand1.Next(0, collectionSize - 1)].Value;

            string queryString = $"value{equalsToken}{value1}{plusToken}{value2}";

            var sw         = Stopwatch.StartNew();
            var expression = ExpressionBuilder.BuildFunction <KeyValuePair <string, string> >(queryString);

            kvps.FirstOrDefault(expression).Should().NotBeNull().And
            .Should().BeAnyOf(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2));

            kvps.Where(expression).Should().NotBeNullOrEmpty().And
            .Contain(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2));

            kvps.Any(expression).Should().BeTrue();
            kvps.All(expression).Should().BeFalse();
            kvps.Count(expression).Should().Be(kvps.Count(q => q.Value == value1 || q.Value == value2));

            sw.Stop();
        }
Beispiel #2
0
        public void CopyTo_IndexZero_ValuesCopied()
        {
            Trie <string, char, int> trie = new Trie <string, char, int>();

            trie.Add("key1", 5);
            trie.Add("key2", 6);

            KeyValuePair <string, int>[] vals = new KeyValuePair <string, int> [4];
            trie.CopyTo(vals, 0);

            Assert.IsTrue(vals.Any(k => k.Key == "key1" && k.Value == 5));
            Assert.IsTrue(vals.Any(k => k.Key == "key2" && k.Value == 6));

            Assert.AreEqual(0, vals[2].Value);
            Assert.AreEqual(0, vals[3].Value);
        }
Beispiel #3
0
        public void IntTest(int collectionSize)
        {
            var kvps = new KeyValuePair <string, int> [collectionSize];

            Random rand1 = new Random();

            for (int i = 0; i < collectionSize; i++)
            {
                Random rand2 = new Random(rand1.Next(0, int.MaxValue));

                kvps[i] = new KeyValuePair <string, int>($"key{i}", rand2.Next(1, collectionSize));
            }

            int value1 = kvps[rand1.Next(0, collectionSize - 1)].Value;
            int value2 = kvps[rand1.Next(0, collectionSize - 1)].Value;

            string queryString = $"value={value1}%2B{value2}";

            var sw         = Stopwatch.StartNew();
            var expression = ExpressionBuilder.BuildFunction <KeyValuePair <string, int> >(queryString);

            kvps.FirstOrDefault(expression).Should().NotBeNull().And
            .Should().BeAnyOf(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2));

            kvps.Where(expression).Should().NotBeNullOrEmpty().And
            .Contain(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2));

            kvps.Any(expression).Should().BeTrue();
            kvps.All(expression).Should().BeFalse();
            kvps.Count(expression).Should().Be(kvps.Count(q => q.Value == value1 || q.Value == value2));

            sw.Stop();
        }
Beispiel #4
0
        public void DateTimeListTest(int collectionSize, int maxSubCollectionSize)
        {
            var kvps = new KeyValuePair <string, List <DateTime> > [collectionSize];

            int day   = 1;
            int month = 1;
            int year  = 2016;

            for (int i = 0; i < collectionSize; i++)
            {
                string key = $"key{i}";

                KeyValuePair <string, List <DateTime> > kvp = new KeyValuePair <string, List <DateTime> >(key, new List <DateTime>());

                for (int j = 0; j < maxSubCollectionSize; j++)
                {
                    kvp.Value.Add(new DateTime(year, month, day++));

                    if (day > 28)
                    {
                        day = 1;
                        month++;
                    }

                    if (month <= 12)
                    {
                        continue;
                    }

                    month = 1;
                    year++;
                }

                kvps[i] = kvp;
            }

            Random rand = new Random();

            DateTime value1 = kvps[rand.Next(0, collectionSize - 1)].Value[0];
            DateTime value2 = kvps[rand.Next(0, collectionSize - 1)].Value[0];

            string queryString = $"value={value1}%2B{value2}";

            var sw = Stopwatch.StartNew();

            var expression = ExpressionBuilder.BuildFunction <KeyValuePair <string, List <DateTime> > >(queryString);

            kvps.FirstOrDefault(expression).Should().NotBeNull().And
            .Should().BeAnyOf(kvps.Where(kvp => kvp.Value.Contains(value1) || kvp.Value.Contains(value2)));

            kvps.Where(expression).Should().NotBeNullOrEmpty().And
            .Contain(kvps.Where(kvp => kvp.Value.Contains(value1) || kvp.Value.Contains(value2)));

            kvps.Any(expression).Should().BeTrue();
            kvps.All(expression).Should().BeFalse();
            kvps.Count(expression).Should().Be(kvps.Count(q => q.Value.Contains(value1) || q.Value.Contains(value2)));

            sw.Stop();
        }
Beispiel #5
0
        public void CopyTo_ShouldCopy_AllUniqueByKey_ToTheGivenIndexOfTheArray()
        {
            // Arrange
            var       array  = new KeyValuePair <string, string> [10];
            const int index  = 1;
            var       kvp1   = new KeyValuePair <string, string>("key1", "value1");
            var       kvp2   = new KeyValuePair <string, string>("key2", "value2");
            var       kvp3   = new KeyValuePair <string, string>("key3", "value3");
            var       inner1 = new Dictionary <string, string>
            {
                [kvp1.Key] = kvp1.Value,
                [kvp2.Key] = kvp2.Value
            };

            var inner2 = new Dictionary <string, string>()
            {
                ["key1"]   = "moocakes",
                [kvp3.Key] = kvp3.Value
            };

            var sut = Create(inner1, inner2);

            // Pre-assert

            // Act
            sut.CopyTo(array, index);

            // Assert
            var defaultVal = default(KeyValuePair <string, string>);

            Expectations.Expect(array[0]).To.Equal(defaultVal);
            Expectations.Expect(array.Any(e => e.Equals(kvp1))).To.Be.True();
            Expectations.Expect(array.Any(e => e.Equals(kvp2))).To.Be.True();
            Expectations.Expect(array.Any(e => e.Equals(kvp3))).To.Be.True();
            PyLike.Range(4, 10).ForEach(i => Expectations.Expect(array[i]).To.Equal(defaultVal));
        }
Beispiel #6
0
        private static bool DoTestsMatchFilterRequest(string[] testTags, KeyValuePair<string, string>[] filterTags)
        {
            //If no tags were requested, then then it is a match
            if (!filterTags.Any())
            {
                return true;
            }

            var includeTags = filterTags.Where(t => t.Value.Equals("true", StringComparison.OrdinalIgnoreCase))
                                        .Select(t => t.Key)
                                        .ToArray();
            var excludeTags = filterTags.Where(t => t.Value.Equals("false", StringComparison.OrdinalIgnoreCase))
                                        .Select(t => t.Key)
                                        .ToArray();

            return !excludeTags.Intersect(testTags, StringComparer.OrdinalIgnoreCase).Any()  &&
                   includeTags.Intersect(testTags, StringComparer.OrdinalIgnoreCase).Count() == includeTags.Count();
        }
        private static IEnumerable<Interval> GenerateIntervals(DateTime start, KeyValuePair<DateTime, float>[] staffingPercentages)
        {
            if (!staffingPercentages.Any())
                throw new ApplicationException("Staffing percentages required");

            var lastEnd = start;
            foreach (var workforcePercentage in staffingPercentages)
            {
                var interval = new Interval()
                    {
                        Start = lastEnd,
                        End = workforcePercentage.Key,
                        StaffingPercentage = workforcePercentage.Value
                    };
                lastEnd = interval.End;
                yield return interval;
            }
        }
Beispiel #8
0
        public static void ShouldHaveHeaderValues(this HttpHeaderDictionary headers, string fieldName,
                                                  params string[] fieldValue)
        {
            var combinedFieldValues = string.Join(",", fieldValue);

            // indexer
            headers[fieldName].ShouldBe(combinedFieldValues);

            // singular
            headers.TryGetValue(fieldName, out var singular).ShouldBeTrue();
            singular.ShouldBe(combinedFieldValues);

            // multi
            headers.TryGetValues(fieldName, out var all).ShouldBeTrue();
            all.ShouldBe(fieldValue);

            // keys contain
            headers.Keys.ShouldContain(fieldName);
            headers.ContainsKey(fieldName).ShouldBeTrue();

            // values contain (why again, why?)
            headers.Values.ShouldContain(combinedFieldValues);


            foreach (var val in fieldValue)
            {
                headers.Contains(new KeyValuePair <string, string>(fieldName, val)).ShouldBeTrue();
            }

            // convert to dictionary
            new Dictionary <string, string>(headers)[fieldName].ShouldBe(combinedFieldValues);

            // copy to array (why why why?)
            var array = new KeyValuePair <string, string> [10];

            headers.CopyTo(array, 0);
            array.Any(item => item.Key == fieldName && item.Value == combinedFieldValues).ShouldBeTrue();
        }
Beispiel #9
0
        private async Task ShowUserInventory(IUser discordUser, MarbleBotUser marbleBotUser, int page = 1)
        {
            if (marbleBotUser.Items.Count == 0)
            {
                await SendErrorAsync($"**{Context.User.Username}**, you don't have any items!");

                return;
            }

            var itemOutput = new StringBuilder();

            KeyValuePair <int, int>[]? items = marbleBotUser.Items.Skip((page - 1) * 20).Take(20).ToArray();
            bool itemsPresent = items.Any();

            if (itemsPresent)
            {
                foreach ((int itemId, int noOwned) in items)
                {
                    if (noOwned > 0)
                    {
                        itemOutput.AppendLine($"`[{itemId:000}]` {Item.Find<Item>(itemId.ToString("000")).Name}: {noOwned}");
                    }
                }
            }
            else
            {
                itemOutput.Append($"**{Context.User.Username}**, there are no items on page **{page}**!");
            }

            await ReplyAsync(embed : new EmbedBuilder()
                             .WithAuthor(discordUser)
                             .WithColor(GetColor(Context))
                             .WithDescription(itemOutput.ToString())
                             .WithTitle(itemsPresent
                    ? $"Page **{page}** of **{(marbleBotUser.Items.Count - 1) / 20 + 1}**"
                    : "Invalid page")
                             .Build());
        }
Beispiel #10
0
    // Taken from https://stackoverflow.com/questions/1132494/string-escape-into-xml
    public static string XmlEscape(string escaped)
    {
        var replacements = new KeyValuePair <string, string>[]
        {
            new KeyValuePair <string, string>("&", "&amp;"),
            new KeyValuePair <string, string>("\"", "&quot;"),
            new KeyValuePair <string, string>("'", "&apos;"),
            new KeyValuePair <string, string>("<", "&lt;"),
            new KeyValuePair <string, string>(">", "&gt;"),
        };

        foreach (var pair in replacements)
        {
            foreach (var index in escaped.IndexesOf(pair.Key, 0).Reverse())
            {
                if (!replacements.Any(other => string.Compare(other.Value, 0, escaped, index, other.Value.Length, StringComparison.Ordinal) == 0))
                {
                    escaped = escaped.Substring(0, index) + pair.Value + escaped.Substring(index + 1, escaped.Length - index - 1);
                }
            }
        }
        return(escaped);
    }
Beispiel #11
0
        // Taken from https://stackoverflow.com/questions/1132494/string-escape-into-xml
        public static string XmlEscape(string escaped)
        {
            var replacements = new KeyValuePair<string, string>[]
            {
            new KeyValuePair<string,string>("&", "&amp;"),
            new KeyValuePair<string,string>("\"", "&quot;"),
            new KeyValuePair<string,string>("'", "&apos;"),
            new KeyValuePair<string,string>("<", "&lt;"),
            new KeyValuePair<string,string>(">", "&gt;"),
            };

            foreach (var pair in replacements)
                foreach (var index in escaped.IndexesOf(pair.Key, 0).Reverse())
                    if (!replacements.Any(other => string.Compare(other.Value, 0, escaped, index, other.Value.Length, StringComparison.Ordinal) == 0))
                    {
                        escaped = escaped.Substring(0, index) + pair.Value + escaped.Substring(index + 1, escaped.Length - index - 1);
                    }
            return escaped;
        }
Beispiel #12
0
        /// <summary>
        /// Initializes and decodes an IRC message, given the raw message from the server.
        /// </summary>
        public IrcMessage(string rawMessage)
        {
            RawMessage = rawMessage;
            Tags       = new KeyValuePair <string, string>[] { };

            if (rawMessage.StartsWith("@"))
            {
                var rawTags = rawMessage.Substring(1, rawMessage.IndexOf(' ') - 1);
                rawMessage = rawMessage.Substring(rawMessage.IndexOf(' ') + 1);

                // Parse tags as key value pairs
                var tags = new List <KeyValuePair <string, string> >();
                foreach (string rawTag in rawTags.Split(';'))
                {
                    var replacedTag = rawTag.Replace(@"\:", ";");
                    // The spec declares `@a=` as a tag with an empty value, while `@b;` as a tag with a null value
                    KeyValuePair <string, string> tag = new KeyValuePair <string, string>(replacedTag, null);

                    if (replacedTag.Contains("="))
                    {
                        string key   = replacedTag.Substring(0, replacedTag.IndexOf("="));
                        string value = replacedTag.Substring(replacedTag.IndexOf("=") + 1);
                        tag = new KeyValuePair <string, string>(key, value);
                    }

                    tags.Add(tag);
                }

                Tags = tags.ToArray();
            }

            if (rawMessage.StartsWith(":"))
            {
                Prefix     = rawMessage.Substring(1, rawMessage.IndexOf(' ') - 1);
                rawMessage = rawMessage.Substring(rawMessage.IndexOf(' ') + 1);
            }

            if (rawMessage.Contains(' '))
            {
                Command    = rawMessage.Remove(rawMessage.IndexOf(' '));
                rawMessage = rawMessage.Substring(rawMessage.IndexOf(' ') + 1);
                // Parse parameters
                var parameters = new List <string>();
                while (!string.IsNullOrEmpty(rawMessage))
                {
                    if (rawMessage.StartsWith(":"))
                    {
                        parameters.Add(rawMessage.Substring(1));
                        break;
                    }
                    if (!rawMessage.Contains(' '))
                    {
                        parameters.Add(rawMessage);
                        rawMessage = string.Empty;
                        break;
                    }
                    parameters.Add(rawMessage.Remove(rawMessage.IndexOf(' ')));
                    rawMessage = rawMessage.Substring(rawMessage.IndexOf(' ') + 1);
                }
                Parameters = parameters.ToArray();
            }
            else
            {
                // Violates RFC 1459, but we'll parse it anyway
                Command    = rawMessage;
                Parameters = new string[0];
            }

            // Parse server-time message tag.
            // Fallback to server-info if both znc.in/server-info and the former exists.
            //
            // znc.in/server-time tag
            if (Tags.Any(tag => tag.Key == "t"))
            {
                var tag = Tags.SingleOrDefault(x => x.Key == "t");
                Timestamp = new Timestamp(tag.Value, true);
            }
            // server-time tag
            else if (Tags.Any(tag => tag.Key == "time"))
            {
                var tag = Tags.SingleOrDefault(x => x.Key == "time");
                Timestamp = new Timestamp(tag.Value);
            }
        }
Beispiel #13
0
        public static Expression <Func <TScene, bool> > GetVerifyExpression <TScene>(this Pharos.Logic.Entity.ReturnRules entity, int providerId, Func <int, Expression, MemberExpression> memberExpression)
            where TScene : IScene, new()
        //注:此处Pharos.Logic.Entity.ReturnRules引用在下次底层数据访问重构时候,新建Dao进行解耦
        {
            var datetimeNow = DateTime.Now;

            switch (entity.AgingType)//时效匹配
            {
            case 1:
                var dayOfWeeks = new int[] {
                    !string.IsNullOrEmpty(entity.StartTime1)? Convert.ToInt32(entity.StartTime1):-1,
                    !string.IsNullOrEmpty(entity.StartTime2)? Convert.ToInt32(entity.StartTime2):-1,
                    !string.IsNullOrEmpty(entity.StartTime3)? Convert.ToInt32(entity.StartTime3):-1,
                    !string.IsNullOrEmpty(entity.EndTime1)? Convert.ToInt32(entity.EndTime1):-1,
                    !string.IsNullOrEmpty(entity.EndTime2)? Convert.ToInt32(entity.EndTime2):-1,
                    !string.IsNullOrEmpty(entity.EndTime3)? Convert.ToInt32(entity.EndTime3):-1,
                };
                if (!dayOfWeeks.Where(o => o != -1).Contains((int)datetimeNow.DayOfWeek))
                {
                    return(null);
                }
                break;

            case 2:

                var dayRanges = new KeyValuePair <DateTime, DateTime>[] {
                    string.IsNullOrEmpty(entity.StartTime1) || string.IsNullOrEmpty(entity.EndTime1)?
                    default(KeyValuePair <DateTime, DateTime>):
                    new KeyValuePair <DateTime, DateTime>(
                        Convert.ToDateTime(datetimeNow.ToString("yyyy-MM-dd") + " " + entity.StartTime1),
                        Convert.ToDateTime(datetimeNow.ToString("yyyy-MM-dd") + " " + entity.EndTime1)
                        ),
                    string.IsNullOrEmpty(entity.StartTime2) || string.IsNullOrEmpty(entity.EndTime2)?
                    default(KeyValuePair <DateTime, DateTime>):
                    new KeyValuePair <DateTime, DateTime>(
                        Convert.ToDateTime(datetimeNow.ToString("yyyy-MM-dd") + " " + entity.StartTime2),
                        Convert.ToDateTime(datetimeNow.ToString("yyyy-MM-dd") + " " + entity.EndTime2)
                        ),
                    string.IsNullOrEmpty(entity.StartTime3) || string.IsNullOrEmpty(entity.EndTime3)?
                    default(KeyValuePair <DateTime, DateTime>):
                    new KeyValuePair <DateTime, DateTime>(
                        Convert.ToDateTime(datetimeNow.ToString("yyyy-MM-dd") + " " + entity.StartTime3),
                        Convert.ToDateTime(datetimeNow.ToString("yyyy-MM-dd") + " " + entity.EndTime3)
                        ),
                };

                if (!dayRanges.Any(o => o.Key <= datetimeNow && o.Value >= datetimeNow))
                {
                    return(null);
                }
                break;
            }
            var p = Expression.Parameter(typeof(TScene), "p");
            MemberExpression propertyName = memberExpression(entity.Mode, p);
            Expression       body         = null;

            //计量范围
            Expression expression1 = GetLogicalOperationExpression(entity.LeftSign, entity.Number1, propertyName);

            if (entity.RightSign.HasValue && entity.Number2.HasValue)
            {
                var expression2 = GetLogicalOperationExpression(entity.RightSign.Value, entity.Number2.Value, propertyName);
                body = Expression.AndAlso(expression1, expression2);
            }
            else
            {
                body = expression1;
            }

            //限制规则提供程序
            var limitProvider   = Expression.Constant(entity.Adapters);
            var currentProvider = Expression.Constant(providerId);
            var ifEqualProvider = Expression.Equal(limitProvider, currentProvider);

            body = Expression.AndAlso(ifEqualProvider, body);
            //会员限定
            if (!string.IsNullOrEmpty(entity.MemberLevelId) && entity.MemberLevelId != "-1")
            {
                var level = Expression.Property(Expression.Property(p, "Member"), "MemberLevelId");
                body = Expression.AndAlso(body, Expression.Equal(Expression.Constant(entity.MemberLevelId), level));
            }
            return(Expression.Lambda <Func <TScene, bool> >(body, p));
        }
Beispiel #14
0
        /// <summary>
        /// Serializes the navigator popular rooms news.
        /// </summary>
        /// <param name="reply">The reply.</param>
        /// <param name="rooms">The rooms.</param>
        /// <param name="category">The category.</param>
        /// <param name="direct">if set to <c>true</c> [direct].</param>
        public void SerializeNavigatorPopularRoomsNews(ref ServerMessage reply, KeyValuePair<RoomData, uint>[] rooms,
                                                       int category, bool direct)
        {
            if (rooms == null || !rooms.Any())
            {
                reply.AppendInteger(0);
                return;
            }

            List<RoomData> roomsCategory = new List<RoomData>();
            foreach (KeyValuePair<RoomData, uint> pair in rooms.Where(pair => pair.Key.Category.Equals(category)))
            {
                roomsCategory.Add(pair.Key);
                if (roomsCategory.Count == (direct ? 40 : 8)) break;
            }
            reply.AppendInteger(roomsCategory.Count);
            foreach (RoomData data in roomsCategory) data.Serialize(reply, false);
        }
        private static string BuilCommandCall(string fullName, VariableParameter[] givenParameters, KeyValuePair<string, string>[] defaultedValues)
        {
            var result = new StringBuilder();

            result.Append(fullName);

            foreach (var parameter in givenParameters)
            {
                result.Append(" ");
                result.Append(parameter.Name);
                result.Append("=\"");
                result.Append(parameter.Value);
                result.Append("\"");
            }

            if (defaultedValues.Any())
            {
                result.Append("(with defaults:");

                foreach (var pair in defaultedValues)
                {
                    result.Append(" ");
                    result.Append(pair.Key);
                    result.Append("=\"");
                    result.Append(pair.Value);
                    result.Append("\"");
                }

                result.Append(")");
            }

            return result.ToString();
        }
        /// <summary>
        /// Realiza todas las realizaciones de una evidencia estocastica
        /// </summary>
        /// <param name="evidence"></param>
        /// <param name="realization"></param>
        /// <param name="pos"></param>
        /// <returns></returns>
        static IEnumerable<Tuple<KeyValuePair<BayesianNode, int>[],double>> EvidenceRealization(Evidence evidence, KeyValuePair<BayesianNode, int>[] realization, int pos,double probability=1.0)
        {
            if (pos == realization.Length)
            {
                if(realization.Any(x=>x.Value>=0))
                yield return new Tuple<KeyValuePair<BayesianNode, int>[], double>(realization,probability);
                
                yield break;
            }
            //en cada paso recursivo se escoge un nodo para su seleccion de estado
            //por cada probabilidad de estar en un estado de el nodo en la posicion pos
            bool outofevidence = true;
            for (int i = 0; i < evidence.EvidenceValues[pos].Length; i++)
            {
                
                if (evidence.EvidenceValues[pos][i] > 0)
                {
                    realization[pos] = new KeyValuePair<BayesianNode, int>(realization[pos].Key, i);
                    outofevidence = false;
                    var p = probability*evidence.EvidenceValues[pos][i];
                    foreach (var item in EvidenceRealization(evidence, realization, pos + 1,p))
                        yield return item;
                }
                
            }
            //si no esta en la evidencia entonces relization[pos]=bayesiannode,-1
            if(outofevidence)
                foreach (var item in EvidenceRealization(evidence, realization, pos + 1,probability))
                    yield return item;

        }
Beispiel #17
0
        public void CopyTo_IndexZero_ValuesCopied()
        {
            Trie<string, char, int> trie = new Trie<string, char, int>();

            trie.Add("key1", 5);
            trie.Add("key2", 6);

            KeyValuePair<string, int>[] vals = new KeyValuePair<string, int>[4];
            trie.CopyTo(vals, 0);

            Assert.IsTrue(vals.Any(k => k.Key == "key1" && k.Value == 5));
            Assert.IsTrue(vals.Any(k => k.Key == "key2" && k.Value == 6));

            Assert.AreEqual(0, vals[2].Value);
            Assert.AreEqual(0, vals[3].Value);
        }