Esempio n. 1
0
 private Polynomial(IEnumerable<KeyValuePair<int, Expression>> Coefficients, Expression Variable)
 {
     coefficients = new DefaultDictionary<int,Expression>(0);
     foreach (KeyValuePair<int, Expression> i in Coefficients)
         coefficients.Add(i.Key, i.Value);
     variable = Variable;
 }
Esempio n. 2
0
        public void TestCtor_DefaultCtor_UsesDictionary()
        {
            DefaultDictionary <int, int> dictionary = new DefaultDictionary <int, int>();

            Assert.IsInstanceOfType(dictionary.Dictionary, typeof(Dictionary <int, int>), "The internal dictionary was the wrong type.");
            Assert.AreEqual(0, dictionary.DefaultGenerator(0), "The wrong generator was set.");
        }
Esempio n. 3
0
        public static IDictionary <string, string> GetCookies(this IMessage message)
        {
            var cookies = new DefaultDictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            var cookieHeaders = message.Headers["Cookie"];

            if (cookieHeaders == null)
            {
                return(cookies);
            }

            foreach (var cookieHeader in cookieHeaders)
            {
                foreach (var cookieString in cookieHeader.Replace(" ", "").Split(';'))
                {
                    var equalsPos = cookieString.IndexOf('=');
                    if (equalsPos > 0)
                    {
                        string name  = cookieString.Substring(0, equalsPos);
                        string value = cookieString.Substring(equalsPos + 1);
                        cookies[name] = value;
                    }
                }
            }

            return(cookies);
        }
Esempio n. 4
0
        public async Task <double> GetWeightAsync(Submission firstSubmission, Submission secondSubmission)
        {
            logger.Information($"Вычисляю коэффициент похожести решения #{firstSubmission.Id} и #{secondSubmission.Id}");
            var maxSnippetsCount      = configuration.PlagiarismDetector.CountOfColdestSnippetsUsedToSecondSearch;
            var authorsCountThreshold = configuration.PlagiarismDetector.SnippetAuthorsCountThreshold;
            var snippetsOccurrencesOfFirstSubmission = await snippetsRepo.GetSnippetsOccurencesForSubmissionAsync(firstSubmission, maxSnippetsCount, 0, authorsCountThreshold).ConfigureAwait(false);

            logger.Debug($"Сниппеты первого решения: [{string.Join(", ", snippetsOccurrencesOfFirstSubmission)}]");
            var snippetsOccurrencesOfSecondSubmission = await snippetsRepo.GetSnippetsOccurencesForSubmissionAsync(secondSubmission, maxSnippetsCount, 0, authorsCountThreshold).ConfigureAwait(false);

            logger.Debug($"Сниппеты второго решения: [{string.Join(", ", snippetsOccurrencesOfSecondSubmission)}]");

            /* Group by snippets from the second submissions by snippetId for fast searching */
            var snippetsOccurrencesOfSecondSubmissionBySnippet = snippetsOccurrencesOfSecondSubmission
                                                                 .GroupBy(o => o.SnippetId)
                                                                 .ToDictionary(g => g.Key, g => g.ToList())
                                                                 .ToDefaultDictionary();

            var tokensMatchedInFirstSubmission  = new DefaultDictionary <SnippetType, HashSet <int> >();
            var tokensMatchedInSecondSubmission = new DefaultDictionary <SnippetType, HashSet <int> >();

            foreach (var snippetOccurence in snippetsOccurrencesOfFirstSubmission)
            {
                var snippet = snippetOccurence.Snippet;
                foreach (var otherOccurence in snippetsOccurrencesOfSecondSubmissionBySnippet[snippet.Id])
                {
                    logger.Debug($"Нашёл совпадающий сниппет в обоих решениях: {snippet}");
                    for (var i = 0; i < snippet.TokensCount; i++)
                    {
                        tokensMatchedInFirstSubmission[snippet.SnippetType].Add(snippetOccurence.FirstTokenIndex + i);
                        tokensMatchedInSecondSubmission[snippet.SnippetType].Add(otherOccurence.FirstTokenIndex + i);
                    }
                }
            }
            logger.Debug("Закончил поиск совпадающих сниппетов");

            var unionLength     = 0;
            var allSnippetTypes = GetAllSnippetTypes();

            foreach (var snippetType in allSnippetTypes)
            {
                if (!tokensMatchedInFirstSubmission.ContainsKey(snippetType))
                {
                    continue;
                }

                unionLength += tokensMatchedInFirstSubmission[snippetType].Count;
                unionLength += tokensMatchedInSecondSubmission[snippetType].Count;
            }

            var totalLength = GetTokensCountFromSnippetOccurrences(snippetsOccurrencesOfFirstSubmission) +
                              GetTokensCountFromSnippetOccurrences(snippetsOccurrencesOfSecondSubmission);
            var weight = totalLength == 0 ? 0 : ((double)unionLength) / totalLength;

            /* Normalize weight */
            weight /= allSnippetTypes.Count;

            logger.Information($"Совпавших токенов {unionLength}, всего токенов {totalLength}, итоговый коэффициент {weight}");
            return(weight);
        }
Esempio n. 5
0
        public static Polynomial Divide(Polynomial N, Polynomial D, out Polynomial R)
        {
            if (!Equals(N.Variable, D.Variable))
            {
                throw new ArgumentException("Polynomials must be of the same variable.", "N/D");
            }

            DefaultDictionary <int, Expression> q = new DefaultDictionary <int, Expression>(0);
            DefaultDictionary <int, Expression> r = new DefaultDictionary <int, Expression>(0);

            foreach (KeyValuePair <int, Expression> i in N.Coefficients)
            {
                r.Add(i.Key, i.Value);
            }

            while (r.Any() && !r[0].Equals(0) && r.Keys.Max() + 1 >= D.Degree)
            {
                int        rd = r.Keys.Max() + 1;
                int        dd = D.Degree;
                Expression t  = r[rd] / D[dd];
                int        td = rd - dd;

                // Compute q += t
                q[td] += t;

                // Compute r -= d * t
                for (int i = 0; i <= dd; ++i)
                {
                    r[i + td] -= -D[i] * t;
                }
            }
            R = new Polynomial(r, N.Variable);
            return(new Polynomial(q, N.Variable));
        }
Esempio n. 6
0
        public Expression Factor()
        {
            // Check if there is a simple factor of x.
            if (this[0].EqualsZero())
            {
                return(Product.New(variable, new Polynomial(Coefficients.Where(i => i.Key != 0).ToDictionary(i => i.Key - 1, i => i.Value), variable).Factor()).Evaluate());
            }

            DefaultDictionary <Expression, int> factors = new DefaultDictionary <Expression, int>(0);

            switch (Degree)
            {
            //case 2:
            //    Expression a = this[2];
            //    Expression b = this[1];
            //    Expression c = this[0];

            //    // D = b^2 - 4*a*c
            //    Expression D = Add.New(Multiply.New(b, b), Multiply.New(-4, a, c));
            //    factors[Binary.Divide(Add.New(Unary.Negate(b), Call.Sqrt(D)), Multiply.New(2, a))] += 1;
            //    factors[Binary.Divide(Add.New(Unary.Negate(b), Call.Sqrt(D)), Multiply.New(2, a))] += 1;
            //    break;
            default:
                return(this);
            }

            // Assemble expression from factors.
            //return Multiply.New(factors.Select(i => Power.New(Binary.Subtract(x, i.Key), i.Value)));
        }
Esempio n. 7
0
        public override object CalculateResult()
        {
            DefaultDictionary<char, HashSet<char>> lefts = new DefaultDictionary<char, HashSet<char>>(c => new HashSet<char>());
            foreach (char[] code in GetText()
                    .Split(new[] { '\n' })
                    .Select(l => l.Trim())
                    .Where(l => l != string.Empty)
                    .Select(l => l.ToCharArray()))
            {
                for (int i = 0; i < code.Length; i++)
                {
                    lefts[code[i]].UnionWith(code.Take(i));
                }
            }

            List<char> password = new List<char>();
            while (lefts.Count > 0)
            {
                char c = lefts
                    .Where(p => p.Value.Count == 0)
                    .Select(p => p.Key)
                    .First();

                password.Add(c);
                lefts.Remove(c);
                foreach (var p in lefts)
                {
                    p.Value.Remove(c);
                }
            }
            return new string(password.ToArray());
        }
Esempio n. 8
0
        public void TestDefaulted_WithDictionary_CreatesDefaultDictionary()
        {
            IDictionary <int, int>       dictionary = new Dictionary <int, int>();
            DefaultDictionary <int, int> defaulted  = dictionary.Defaulted();

            Assert.AreSame(dictionary, defaulted.Dictionary, "The dictionary was not set in the backing field.");
        }
Esempio n. 9
0
        // Will aggregate metrics for a single tag of a single template
        IEnumerable <Metric> AggregateTag(IEnumerable <Metric> metrics, IEnumerable <string> targetMetricNames, string targetTag, IAggregator aggregator)
        {
            var aggregateValues = new DefaultDictionary <AggregateMetric, IAggregator>(_ => aggregator.New());

            foreach (Metric metric in metrics)
            {
                // if metric is the aggregation target and it has a tag that should be aggregated
                if (targetMetricNames.Contains(metric.Name) && metric.Tags.ContainsKey(targetTag))
                {
                    var aggregateMetric = new AggregateMetric(metric, targetTag);
                    aggregateValues[aggregateMetric].PutValue(metric.Value);
                }
                else
                {
                    yield return(metric);
                }
            }

            // aggregate all and construct new metrics from result
            foreach (var aggregatePair in aggregateValues)
            {
                double aggregatedValue = aggregatePair.Value.GetAggregate();
                yield return(aggregatePair.Key.ToMetric(aggregatedValue));
            }
        }
Esempio n. 10
0
        public void TestCtor_WithDefaultGenerator_SetsGenerator()
        {
            Func <int, int> generator = i => i;
            DefaultDictionary <int, int> dictionary = new DefaultDictionary <int, int>(generator);

            Assert.IsInstanceOfType(dictionary.Dictionary, typeof(Dictionary <int, int>), "The internal dictionary was the wrong type.");
            Assert.AreSame(generator, dictionary.DefaultGenerator, "The wrong generator was set.");
        }
Esempio n. 11
0
 /// <summary>
 ///  Reads a Radius response packet from the given input stream and
 ///  creates an appropiate RadiusPacket descendant object.
 ///  Reads in all attributes and returns the object.
 ///  Checks the packet authenticator.
 ///  @param sharedSecret shared secret to be used to decode this packet
 ///  @param request Radius request packet
 ///  @return new RadiusPacket object
 ///  @exception IOException IO error
 ///  @exception RadiusException malformed packet
 /// </summary>
 public static RadiusPacket DecodeResponsePacket(Stream @in, String sharedSecret, RadiusPacket request)
 {
     if (request == null)
     {
         throw new ArgumentNullException("request", "request may not be null");
     }
     return(DecodePacket(DefaultDictionary.GetDefaultDictionary(), @in, sharedSecret, request));
 }
Esempio n. 12
0
 public OrbitMap(IList <string> orbits)
 {
     Map = new DefaultDictionary <string, Body>(key => new Body(key));
     foreach (var orbit in orbits)
     {
         AddOrbit(orbit);
     }
 }
Esempio n. 13
0
 public UserModel(UserRolesInfo userRoles)
 {
     UserName        = userRoles.UserName;
     UserId          = userRoles.UserId;
     UserVisibleName = userRoles.UserVisibleName;
     CourseAccesses  = new DefaultDictionary <string, Dictionary <CourseAccessType, CourseAccessModel> >();
     SystemAccesses  = new Dictionary <SystemAccessType, SystemAccessModel>();
 }
Esempio n. 14
0
        public void NotNullDictionary_DoesForEach()
        {
            var result = 0;

            DefaultDictionary.ForEach((key, value) => result += key * 2);

            Assert.AreEqual(DefaultDictionary.Sum(y => y.Key * 2), result);
        }
Esempio n. 15
0
        public void UnaryIncrement_OnDictionaryValue_Works()
        {
            var dict = new DefaultDictionary <int, int>(_ => 0);

            dict[0]++;

            dict[0].Should().Be(1);
        }
Esempio n. 16
0
        public void UpdateByNdimNewton()
        {
            var r      = Days.Select(rr => rr.R).ToList();
            var sigma2 = ComputeSigma2();
            var h      = Hessian(Days, sigma2);
            var g      = Gradient(r, Days, sigma2);

            var a = new DefaultDictionary <int, double?>(null);
            var d = new DefaultDictionary <int, double?>(null)
            {
                { 0, h[0][0] }
            };
            var b = new DefaultDictionary <int, double?>(null)
            {
                { 0, h[0][1] }
            };
            var n = r.Count();

            for (int i = 1; i < n; i++)
            {
                a[i] = h[i][i - 1] / d[i - 1];
                d[i] = h[i][i] - a[i] * b[i - 1];
                b[i] = h[i][i + 1];
            }

            var y = new DefaultDictionary <int, double?>(null)
            {
                { 0, g[0] }
            };

            for (int i = 1; i < n; i++)
            {
                y[i] = g[i] - a[i] * y[i - 1];
            }

            var x = new DefaultDictionary <int, double?>(null);

            x[n - 1] = y[n - 1] / d[n - 1];
            for (int i = n - 2; i >= 0; i--)
            {
                x[i] = (y[i] - b[i] * x[i + 1]) / d[i];
            }

            var newR = r.Zip(x, (ri, xi) => ri - xi.Value);

            foreach (var nr in newR)
            {
                if (nr > 650)
                {
                    // Somerthing's Wrong.
                }
            }

            for (int idx = 0; idx < Days.Count(); idx++)
            {
                Days[idx].R = Days[idx].R - x[idx].Value;
            }
        }
Esempio n. 17
0
 private EntryInfo()
 {
     CourseToEntries =
         new DefaultDictionary <CourseModel, ISet <ISQEntryModel> >(() => new HashSet <ISQEntryModel>());
     ProfessorToEntries =
         new DefaultDictionary <ProfessorModel, ISet <ISQEntryModel> >(() => new HashSet <ISQEntryModel>());
     Entries = new HashSet <ISQEntryModel>();
     Lock    = new ReadWriteLock();
 }
Esempio n. 18
0
 private Polynomial(IEnumerable <KeyValuePair <int, Expression> > Coefficients, Expression Variable)
 {
     coefficients = new DefaultDictionary <int, Expression>(0);
     foreach (KeyValuePair <int, Expression> i in Coefficients)
     {
         coefficients.Add(i.Key, i.Value);
     }
     variable = Variable;
 }
Esempio n. 19
0
        public override long RunPart1(Dictionary <string, Reaction> input)
        {
            var chemicals = new DefaultDictionary <string, long> {
                { "ORE", long.MaxValue }
            };

            Consume("FUEL", 1, chemicals, input);
            return(long.MaxValue - chemicals["ORE"]);
        }
Esempio n. 20
0
        public void TestDefaulted_WithDefaultGenerator_CreatesDefaultDictionary()
        {
            IDictionary <int, int>       dictionary       = new Dictionary <int, int>();
            Func <int, int>              defaultGenerator = i => 0;
            DefaultDictionary <int, int> defaulted        = dictionary.Defaulted(defaultGenerator);

            Assert.AreSame(dictionary, defaulted.Dictionary, "The dictionary was not set in the backing field.");
            Assert.AreSame(defaultGenerator, defaulted.DefaultGenerator, "The default generator was not set in the backing field.");
        }
Esempio n. 21
0
        public void TestCtor_WithComparer_SetsComparer()
        {
            IEqualityComparer <int>      comparer   = EqualityComparer <int> .Default;
            DefaultDictionary <int, int> dictionary = new DefaultDictionary <int, int>(comparer);

            Assert.IsInstanceOfType(dictionary.Dictionary, typeof(Dictionary <int, int>), "The internal dictionary was the wrong type.");
            Assert.AreEqual(0, dictionary.DefaultGenerator(0), "The wrong generator was set.");
            Assert.AreSame(comparer, ((Dictionary <int, int>)dictionary.Dictionary).Comparer, "The comparer was not set.");
        }
Esempio n. 22
0
        public void TestCtor_SetsDictionaryAndGenerator()
        {
            IDictionary <int, int>       dictionary        = new Dictionary <int, int>();
            Func <int, int>              generator         = i => 0;
            DefaultDictionary <int, int> defaultDictionary = new DefaultDictionary <int, int>(dictionary, generator);

            Assert.AreSame(dictionary, defaultDictionary.Dictionary, "The dictionary was not set.");
            Assert.AreSame(generator, defaultDictionary.DefaultGenerator, "The generator was not set.");
        }
Esempio n. 23
0
        public void TestCtor_SetsDictionary()
        {
            IDictionary <int, int>       dictionary        = new Dictionary <int, int>();
            DefaultDictionary <int, int> defaultDictionary = new DefaultDictionary <int, int>(dictionary);

            Assert.AreSame(dictionary, defaultDictionary.Dictionary, "The dictionary was not set.");
            Assert.AreEqual(default(int), defaultDictionary.DefaultGenerator(0), "The default generator generated the wrong value.");
            Assert.AreEqual(dictionary.IsReadOnly, ((IDictionary <int, int>)defaultDictionary).IsReadOnly, "The read-only property not the same.");
        }
Esempio n. 24
0
        protected CommentResponse BuildCommentResponse(
            Comment comment,
            bool canUserSeeNotApprovedComments, DefaultDictionary <int, List <Comment> > replies, DefaultDictionary <int, int> commentLikesCount, HashSet <int> likedByUserCommentsIds,
            [CanBeNull] Dictionary <string, List <Group> > authorId2Groups, [CanBeNull] HashSet <string> authorsWithPassed, [CanBeNull] HashSet <int> userAvailableGroups,
            bool canViewAllGroupMembers, bool addCourseIdAndSlideId, bool addParentCommentId, bool addReplies
            )
        {
            var commentInfo = new CommentResponse
            {
                Id           = comment.Id,
                Text         = comment.Text,
                RenderedText = CommentTextHelper.RenderCommentTextToHtml(comment.Text),
                Author       = BuildShortUserInfo(comment.Author),
                PublishTime  = comment.PublishTime,
                IsApproved   = comment.IsApproved,
                IsLiked      = likedByUserCommentsIds.Contains(comment.Id),
                LikesCount   = commentLikesCount[comment.Id],
                IsPassed     = authorsWithPassed?.Contains(comment.AuthorId) ?? false,
                Replies      = new List <CommentResponse>()
            };

            if (authorId2Groups != null && userAvailableGroups != null && authorId2Groups.ContainsKey(comment.Author.Id))
            {
                commentInfo.AuthorGroups = authorId2Groups[comment.AuthorId]
                                           .Where(g => canViewAllGroupMembers || userAvailableGroups.Contains(g.Id))
                                           .Select(BuildShortGroupInfo)
                                           .ToList().NullIfEmpty();
            }

            if (addCourseIdAndSlideId)
            {
                commentInfo.CourseId = comment.CourseId;
                commentInfo.SlideId  = comment.SlideId;
            }

            if (addParentCommentId && !comment.IsTopLevel)
            {
                commentInfo.ParentCommentId = comment.ParentCommentId;
            }

            if (!comment.IsTopLevel)
            {
                commentInfo.IsCorrectAnswer = comment.IsCorrectAnswer;
                return(commentInfo);
            }

            commentInfo.IsPinnedToTop = comment.IsPinnedToTop;
            if (addReplies)
            {
                var commentReplies = FilterVisibleComments(replies[comment.Id], canUserSeeNotApprovedComments);
                commentInfo.Replies = BuildCommentsListResponse(commentReplies, canUserSeeNotApprovedComments, null, commentLikesCount, likedByUserCommentsIds,
                                                                authorId2Groups, authorsWithPassed, userAvailableGroups, canViewAllGroupMembers, addCourseIdAndSlideId, addParentCommentId, addReplies);
            }

            return(commentInfo);
        }
Esempio n. 25
0
 public QuizBlockData(QuizModel model, int index, QuizState quizState, DefaultDictionary <string, int> questionAnswersFrequency = null, bool isInstructor = false, bool debugView = false, bool isCourseAdmin = false)
 {
     QuizModel  = model;
     BlockIndex = index;
     QuizState  = quizState;
     QuestionAnswersFrequency = questionAnswersFrequency ?? new DefaultDictionary <string, int>();
     IsCourseAdmin            = isCourseAdmin;
     IsInstructor             = isInstructor;
     DebugView = debugView;
 }
Esempio n. 26
0
        public void Test_DefaultDictExample()
        {
            var dict1 = new DefaultDictionary <string, int>();

            Assert.AreEqual(dict1["apple"], 0);
            dict1["banana"] += 10;
            Assert.AreEqual(dict1["banana"], 10);
            dict1["apple"] += 3;
            Assert.AreEqual(dict1["apple"], 3);
        }
Esempio n. 27
0
        private void Research(GameProcess game)
        {
            ModuleAddress fmodPatchAddress = new DefaultDictionary <GameVersion, ModuleAddress>(game.Version)
            {
                [GameVersion.Alpha]  = ModuleAddress.FromImageAddress(game.ModuleContext, 0x140DA75),
                [GameVersion.Latest] = ModuleAddress.FromImageAddress(game.ModuleContext, 0xFAA9E5)
            };

            game.Memory.WriteByte(fmodPatchAddress, 0x2);
        }
Esempio n. 28
0
        public override void PerformAction(
            IRuleExecutionContext requestInfo,
            IRuleResult ruleResult,
            out bool stopProcessing,
            out bool endRequest)
        {
            switch (_scope)
            {
            case Scope.Header:
                foreach (var header in requestInfo.GetHeaderNames())
                {
                    if (!_scopeIndex.Contains(header.ToLower()))
                    {
                        requestInfo.SetHeader(header, null);
                    }
                }
                break;

            case Scope.Parameter:
                var parameters = new DefaultDictionary <string, IList <string> >(StringComparer.OrdinalIgnoreCase);
                foreach (var parameterName in _scopeIndex)
                {
                    IList <string> parameterValue;
                    if (requestInfo.NewParameters.TryGetValue(parameterName, out parameterValue))
                    {
                        if (parameterValue != null && parameterValue.Count > 0)
                        {
                            parameters[parameterName] = parameterValue;
                        }
                    }
                }
                requestInfo.NewParameters = parameters;
                break;

            case Scope.PathElement:
                // Note that _scopeIndexValue is sorted into ascending order and always includes 0
                var newPath = _scopeIndexValue
                              .Where(i => i >= 0 && i < requestInfo.NewPath.Count)
                              .Select(index => requestInfo.NewPath[index])
                              .ToList();
                if (newPath.Count < 2)
                {
                    newPath.Add(string.Empty);
                }
                requestInfo.NewPath = newPath;
                break;

            case Scope.HostElement:
                // TODO: but only if this makes any sense
                break;
            }

            stopProcessing = _stopProcessing;
            endRequest     = _endRequest;
        }
        public void Instance_ShouldAppearToBeCaseInsensitive()
        {
            // Arrange
            var dict = new DefaultDictionary <string, object>();
            // Pre-Assert
            // Act
            var result = dict.GetPropertyValue("Comparer");

            // Assert
            Expect(result).To.Equal(StringComparer.OrdinalIgnoreCase);
        }
Esempio n. 30
0
    private long Part1(int preamble, string rawData)
    {
        int oldest = 0;

        long[] numbers = new long[preamble];

        var input = rawData.Lines().Select(x => long.Parse(x)).GetEnumerator();

        while (oldest < preamble)
        {
            input.MoveNext();
            numbers[oldest++] = input.Current;
        }
        oldest = 0;

        var sums = new DefaultDictionary <long, long>();

        for (int i = 0; i < preamble - 1; i++)
        {
            for (int j = 0; j < preamble; j++)
            {
                sums[numbers[i] + numbers[j]]++;
            }
        }

        while (input.MoveNext())
        {
            if (sums[input.Current] == 0)
            {
                return(input.Current);
            }
            long oldestValue = numbers[oldest];
            for (int i = 0; i < preamble; i++)
            {
                if (i != oldest)
                {
                    sums[numbers[i] + oldestValue]--;
                }
            }
            numbers[oldest] = input.Current;

            for (int i = 0; i < preamble; i++)
            {
                if (i != oldest)
                {
                    sums[numbers[i] + input.Current]++;
                }
            }

            oldest = (oldest + 1) % preamble;
        }

        return(0);
    }
Esempio n. 31
0
    public static IEnumerable <T> Mode <T>(this IEnumerable <T> n) where T : notnull
    {
        var count = new DefaultDictionary <T, int>();

        foreach (var item in n)
        {
            count[item]++;
        }
        var max = count.Values.Max();

        return(count.Keys.Where(x => count[x] == max));
    }
Esempio n. 32
0
        // Combine like terms and multiply constants.
        protected override Expression VisitProduct(Product M)
        {
            // Map terms to exponents.
            DefaultDictionary <Expression, Real> terms = new DefaultDictionary <Expression, Real>(0);

            // Accumulate constants and sum exponent of each term.
            Real C = 1;

            foreach (Expression i in M.Terms.SelectMany(i => Product.TermsOf(Visit(i))))
            {
                if (i is Constant)
                {
                    Real Ci = (Real)i;
                    // Early exit if 0.
                    if (Ci.EqualsZero())
                    {
                        return(0);
                    }
                    C *= Ci;
                }
                else
                {
                    Power Pi = i as Power;
                    if (!ReferenceEquals(Pi, null) && Pi.Right is Constant)
                    {
                        terms[Pi.Left] += (Real)Pi.Right;
                    }
                    else
                    {
                        terms[i] += 1;
                    }
                }
            }

            // Build a new expression with the accumulated terms.
            if (!C.EqualsOne())
            {
                // Find a sum term that has a constant term to distribute into.
                KeyValuePair <Expression, Real> A = terms.FirstOrDefault(i => Real.Abs(i.Value).EqualsOne() && i.Key is Sum);
                if (!ReferenceEquals(A.Key, null))
                {
                    terms.Remove(A.Key);
                    terms[ExpandExtension.Distribute(C ^ A.Value, A.Key)] += A.Value;
                }
                else
                {
                    terms.Add(C, 1);
                }
            }
            return(Product.New(terms
                               .Where(i => !i.Value.EqualsZero())
                               .Select(i => !i.Value.EqualsOne() ? Power.New(i.Key, Constant.New(i.Value)) : i.Key)));
        }
        static void AuthClient_UpdateCacheEvent()
        {
            var overrides = Server.Return((IPropertyAuthServer s) => s.OverridenProperties());

            propertyRules = new DefaultDictionary<PropertyRoute, PropertyAllowed>
                (pr =>
                {
                    if (!BasicPermission.AutomaticUpgradeOfProperties.IsAuthorized())
                        return TypeAuthClient.GetDefaultAllowed() ? PropertyAllowed.Modify : PropertyAllowed.None;

                    return TypeAuthClient.GetAllowed(pr.RootType).MaxUI().ToPropertyAllowed();

                }, overrides);
        }
Esempio n. 34
0
        public static Mock<IAggregatorProvider> GetAggregatorProviderMock(params LazyAggregator[] aggregators)
        {
            var storage = new DefaultDictionary<Type, DefaultDictionary<Id, LazyAggregator>>(()=>new DefaultDictionary<Id, LazyAggregator>());
            foreach(var aggregator in aggregators)
            {
                storage[aggregator.GetType()][aggregator.Id] = aggregator;
            }
            var mock = new Mock<IAggregatorProvider>();

            mock.Setup(x => x.Get(It.IsAny<Type>(), It.IsAny<Id>()))
                .Returns((Type aggType, Id id) =>
                    storage[aggType][id]);

            mock.Setup(x => x.Save(It.IsAny<LazyAggregator>()))
                .Callback((LazyAggregator agg) =>
                    storage[agg.GetType()][agg.Id] = agg);

            return mock;
        }
Esempio n. 35
0
 public override object CalculateResult()
 {
     var _digitCache = new DefaultDictionary<int, int[]>(n => MathUtilities.ToDigits(n, true));
     return new Range(7, 10, true)
         .GetPermutations()
         .Select(o => o.PrependItem(6).ToArray())
         .SelectMany(o => new Range(1, 5, true)
             .GetPermutations()
             .Select(i => new[] { new[] { o[0], i[0], i[1] }, new[] { o[1], i[1], i[2] }, new[] { o[2], i[2], i[3] }, new[] { o[3], i[3], i[4] }, new[] { o[4], i[4], i[0] } }))
         .Where(z => {
             int value = z[0].Sum();
             return z.Skip(1).All(x => x.Sum() == value);
         })
         .Select(z => z
             .SelectMany(x => x.SelectMany(y => _digitCache[y]))
             .ToArray())
         .Where(x => x.Length == 16)
         .Aggregate((a, b) => a.SequenceCompare(b) > 0 ? a : b)
         .StringJoin(string.Empty);
 }
Esempio n. 36
0
 public BaseChip()
 {
     Connections = new DefaultDictionary<string, RW>(() => new NullRW());
 }
Esempio n. 37
0
		internal static void TranslateFieldsToLocalAccess(List<ILNode> newBody, Dictionary<FieldDefinition, ILVariable> fieldToParameterMap)
		{
			var fieldToLocalMap = new DefaultDictionary<FieldDefinition, ILVariable>(f => new ILVariable { Name = f.Name, Type = f.FieldType });
			foreach (ILNode node in newBody) {
				foreach (ILExpression expr in node.GetSelfAndChildrenRecursive<ILExpression>()) {
					FieldDefinition field = GetFieldDefinition(expr.Operand as FieldReference);
					if (field != null) {
						switch (expr.Code) {
							case ILCode.Ldfld:
								if (expr.Arguments[0].MatchThis()) {
									expr.Code = ILCode.Ldloc;
									if (fieldToParameterMap.ContainsKey(field)) {
										expr.Operand = fieldToParameterMap[field];
									} else {
										expr.Operand = fieldToLocalMap[field];
									}
									expr.Arguments.Clear();
								}
								break;
							case ILCode.Stfld:
								if (expr.Arguments[0].MatchThis()) {
									expr.Code = ILCode.Stloc;
									if (fieldToParameterMap.ContainsKey(field)) {
										expr.Operand = fieldToParameterMap[field];
									} else {
										expr.Operand = fieldToLocalMap[field];
									}
									expr.Arguments.RemoveAt(0);
								}
								break;
							case ILCode.Ldflda:
								if (expr.Arguments[0].MatchThis()) {
									expr.Code = ILCode.Ldloca;
									if (fieldToParameterMap.ContainsKey(field)) {
										expr.Operand = fieldToParameterMap[field];
									} else {
										expr.Operand = fieldToLocalMap[field];
									}
									expr.Arguments.Clear();
								}
								break;
						}
					}
				}
			}
		}
Esempio n. 38
0
 static void AuthClient_UpdateCacheEvent()
 {
     typeRules = Server.Return((ITypeAuthServer s) => s.AuthorizedTypes());
 }
Esempio n. 39
0
        public static Polynomial Divide(Polynomial N, Polynomial D, out Polynomial R)
        {
            if (!Equals(N.Variable, D.Variable))
                throw new ArgumentException("Polynomials must be of the same variable.", "N/D");

            DefaultDictionary<int, Expression> q = new DefaultDictionary<int, Expression>(0);
            DefaultDictionary<int, Expression> r = new DefaultDictionary<int, Expression>(0);
            foreach (KeyValuePair<int, Expression> i in N.Coefficients)
                r.Add(i.Key, i.Value);

            while (r.Any() && !r[0].Equals(0) && r.Keys.Max() + 1 >= D.Degree)
            {
                int rd = r.Keys.Max() + 1;
                int dd = D.Degree;
                Expression t = r[rd] / D[dd];
                int td = rd - dd;

                // Compute q += t
                q[td] += t;

                // Compute r -= d * t
                for (int i = 0; i <= dd; ++i)
                    r[i + td] -= -D[i] * t;
            }
            R = new Polynomial(r, N.Variable);
            return new Polynomial(q, N.Variable);
        }
Esempio n. 40
0
        public override object CalculateResult()
        {
            return new Range(NumGames)
                .AsParallel()
                .Select(x =>
                {
                    Random random = MathUtilities.CreateRandom();
                    var communityChestCards = new[]
                        {
                            CommunityChestCard.AdvanceToGo,
                            CommunityChestCard.GoToJail,
                            CommunityChestCard.Other,
                            CommunityChestCard.Other,
                            CommunityChestCard.Other,
                            CommunityChestCard.Other,
                            CommunityChestCard.Other,
                            CommunityChestCard.Other,
                            CommunityChestCard.Other,
                            CommunityChestCard.Other,
                            CommunityChestCard.Other,
                            CommunityChestCard.Other,
                            CommunityChestCard.Other,
                            CommunityChestCard.Other,
                            CommunityChestCard.Other,
                            CommunityChestCard.Other,
                        }
                        .Shuffle(random)
                        .ToQueue();
                    var chanceCards = new[]
                        {
                            ChanceCard.AdvanceToGo,
                            ChanceCard.GoToJail,
                            ChanceCard.GoToC1,
                            ChanceCard.GoToE3,
                            ChanceCard.GoToH2,
                            ChanceCard.GoToRailroad1,
                            ChanceCard.GoToNextRailroad,
                            ChanceCard.GoToNextRailroad,
                            ChanceCard.GoToNextUtility,
                            ChanceCard.GoBackThreeSquares,
                            ChanceCard.Other,
                            ChanceCard.Other,
                            ChanceCard.Other,
                            ChanceCard.Other,
                            ChanceCard.Other,
                            ChanceCard.Other,
                        }
                        .Shuffle(random)
                        .ToQueue();
                    Square currentPosition = Square.Go;
                    Action refixPosition = () =>
                    {
                        while (currentPosition < Square.Go)
                        {
                            currentPosition += BoardSize;
                        }
                        while (currentPosition > Square.H2)
                        {
                            currentPosition -= BoardSize;
                        }
                    };
                    DefaultDictionary<Square, int> landings = new DefaultDictionary<Square, int>(s => 0);
                    for (int i = 0; i < NumTurnsPerGame; i++)
                    {
                        int numDoubles = 0;
                        int die1 = random.Next(1, 1 + DieSize);
                        int die2 = random.Next(1, 1 + DieSize);
                        if (die1 == die2)
                        {
                            numDoubles++;
                        }
                        else
                        {
                            numDoubles = 0;
                        }
                        if (numDoubles == 3)
                        {
                            numDoubles = 0;
                            currentPosition = Square.Jail;
                        }
                        else
                        {
                            currentPosition += die1 + die2;
                            refixPosition();

                        checkPosition:
                            if (currentPosition == Square.GoToJail)
                            {
                                currentPosition = Square.Jail;
                            }
                            else if (Chances.Contains(currentPosition))
                            {
                                ChanceCard card = chanceCards.Dequeue();
                                chanceCards.Enqueue(card);

                                switch (card)
                                {
                                    case ChanceCard.AdvanceToGo:
                                        currentPosition = Square.Go;
                                        break;
                                    case ChanceCard.GoToJail:
                                        currentPosition = Square.GoToJail;
                                        break;
                                    case ChanceCard.GoToC1:
                                        currentPosition = Square.C1;
                                        break;
                                    case ChanceCard.GoToE3:
                                        currentPosition = Square.E3;
                                        break;
                                    case ChanceCard.GoToH2:
                                        currentPosition = Square.H2;
                                        break;
                                    case ChanceCard.GoToRailroad1:
                                        currentPosition = Square.Railroad1;
                                        break;
                                    case ChanceCard.GoToNextRailroad:
                                        while (!Railroads.Contains(currentPosition))
                                        {
                                            currentPosition++;
                                            refixPosition();
                                        }
                                        break;
                                    case ChanceCard.GoToNextUtility:
                                        while (!Utilities.Contains(currentPosition))
                                        {
                                            currentPosition++;
                                            refixPosition();
                                        }
                                        break;
                                    case ChanceCard.GoBackThreeSquares:
                                        currentPosition -= 3;
                                        refixPosition();

                                        goto checkPosition; // I hate gotos, but it's the cleanest way in this case.
                                }
                            }
                            else if (CommunityChests.Contains(currentPosition))
                            {
                                CommunityChestCard card = communityChestCards.Dequeue();
                                communityChestCards.Enqueue(card);

                                switch (card)
                                {
                                    case CommunityChestCard.AdvanceToGo:
                                        currentPosition = Square.Go;
                                        break;
                                    case CommunityChestCard.GoToJail:
                                        currentPosition = Square.Jail;
                                        break;
                                }
                            }
                        }
                        landings[currentPosition]++;
                    }
                    return landings;
                })
                .Aggregate((a, b) => {
                    foreach (var pair in b)
                    {
                        if (!a.ContainsKey(pair.Key))
                        {
                            a[pair.Key] = 0;
                        }
                        a[pair.Key] += pair.Value;
                    }
                    return a;
                })
                .OrderByDescending(p => p.Value)
                .Select(p => p.Key)
                .Take(3)
                .Select(s => ((int)s).ToString("00"))
                .StringJoin(string.Empty);
        }
Esempio n. 41
0
        public static Polynomial Add(Polynomial L, Polynomial R)
        {
            if (!Equals(L.Variable, R.Variable))
                throw new ArgumentException("Polynomials must be of the same variable.", "L+R");

            DefaultDictionary<int, Expression> P = new DefaultDictionary<int, Expression>(0);
            int D = Math.Max(L.Degree, R.Degree);
            for (int i = 0; i <= D; ++i)
                P[i] = L[i] + R[i];

            return new Polynomial(P, L.Variable);
        }
Esempio n. 42
0
        /// <summary>
        /// Analyse the instructions in the method code and convert them to a ByteCode list.
        /// </summary>
        private List<ByteCode> StackAnalysis()
        {
            // Map from instruction to bytecode.
            var instrToByteCode = new Dictionary<Instruction, ByteCode>();

            // Create temporary structure for the stack analysis
            var body = new List<ByteCode>(codeAttr.Code.Length);
            foreach (var inst in codeAttr.Instructions)
            {
                var first = true;
                foreach (var byteCode in Create(inst, module))
                {
                    if (first)
                    {
                        instrToByteCode[inst] = byteCode;
                        first = false;
                    }
                    body.Add(byteCode);
                }
            }
            // Connect bytecodes to the next
            for (var i = 0; i < body.Count - 1; i++)
            {
                body[i].Next = body[i + 1];
            }

            var agenda = new Stack<ByteCode>();
            var localVarsCount = codeAttr.MaxLocals; // methodDef.GetParametersLocalVariableSlots();

            // All bytecodes that are the start of an exception handler.
            var exceptionHandlerStarts = new HashSet<ByteCode>(validExceptionHandlers.Select(eh => instrToByteCode[eh.Handler]));
            var exceptionTryStarts = new DefaultDictionary<ByteCode, List<ExceptionHandler>>(x => new List<ExceptionHandler>());
            foreach (var eh in validExceptionHandlers)
            {
                exceptionTryStarts[instrToByteCode[eh.Start]].Add(eh);
            }

            // Add known states
            var ldExceptionByHandlerPc = new Dictionary<int, ByteCode>();
            foreach (var ex in validExceptionHandlers)
            {
                ByteCode ldexception;
                if (ldExceptionByHandlerPc.TryGetValue(ex.HandlerPc, out ldexception))
                {
                    // Re-use ldexception (that we've created for the same handler PC for another exception handler before)
                }
                else
                {
                    // No handler at handlerPc processed before, do that now
                    var handlerStart = instrToByteCode[ex.Handler];
                    handlerStart.StackBefore = new StackSlot[0];
                    handlerStart.VariablesBefore = VariableSlot.MakeUnknownState(localVarsCount);
                    {
                        // Catch handlers start with the exeption on the stack
                        ldexception = new ByteCode {
                            Code = AstCode.Ldexception,
                            Operand = ex.CatchType,
                            PopCount = 0,
                            PushCount = 1,
                            Offset = handlerStart.Offset,
                            Next = handlerStart,
                            StackBefore = new StackSlot[0],
                            VariablesBefore = handlerStart.VariablesBefore
                        };
                        handlerStart.StackBefore = new[] { new StackSlot(new[] { ldexception }, null) };
                    }
                    ldExceptionByHandlerPc[ex.HandlerPc] = ldexception;
                    agenda.Push(handlerStart);
                }
                // Store ldexception by exception handler
                ldexceptions[ex] = ldexception;
            }

            // At the start of the method the stack is empty and all local variables have unknown state
            body[0].StackBefore = new StackSlot[0];
            body[0].VariablesBefore = VariableSlot.MakeUnknownState(localVarsCount);
            agenda.Push(body[0]);

            // Process agenda
            while (agenda.Count > 0)
            {
                var byteCode = agenda.Pop();

                // Calculate new stack
                var newStack = byteCode.CreateNewStack();

                // Calculate new variable state
                var newVariableState = VariableSlot.CloneVariableState(byteCode.VariablesBefore);
                if (byteCode.IsVariableDefinition)
                {
                    newVariableState[((LocalVariableReference)byteCode.Operand).Index] = new VariableSlot(new[] { byteCode }, false);
                }

                // After the leave, finally block might have touched the variables
                if (byteCode.Code == AstCode.Leave)
                {
                    newVariableState = VariableSlot.MakeUnknownState(localVarsCount);
                }

                // Find all successors
                var branchTargets = FindBranchTargets(byteCode, instrToByteCode, exceptionHandlerStarts);

                // Apply the state to successors
                foreach (var branchTarget in branchTargets)
                {
                    UpdateBranchTarget(byteCode, branchTarget, (branchTargets.Count == 1), newStack, newVariableState, agenda);
                }

                // Apply state to handlers when a branch target is the start of an exception handler
                foreach (var branchTarget in branchTargets.Where(exceptionTryStarts.ContainsKey))
                {
                    // The branch target is the start of a try block.
                    UpdateTryStartBranchTarget(branchTarget, exceptionTryStarts[branchTarget], instrToByteCode, newVariableState, agenda);
                }
            }

            // Occasionally the compilers or obfuscators generate unreachable code (which might be intentonally invalid)
            // I believe it is safe to just remove it
            body.RemoveAll(b => b.StackBefore == null);

            // Generate temporary variables to replace stack
            foreach (var byteCode in body)
            {
                var argIdx = 0;
                var popCount = byteCode.PopCount ?? byteCode.StackBefore.Length;
                for (var i = byteCode.StackBefore.Length - popCount; i < byteCode.StackBefore.Length; i++)
                {
                    var tmpVar = new AstGeneratedVariable(string.Format("arg_{0:X2}_{1}", byteCode.Offset, argIdx), null);
                    byteCode.StackBefore[i] = new StackSlot(byteCode.StackBefore[i].Definitions, tmpVar);
                    foreach (var pushedBy in byteCode.StackBefore[i].Definitions)
                    {
                        if (pushedBy.StoreTo == null)
                        {
                            pushedBy.StoreTo = new List<AstVariable>(1);
                        }
                        pushedBy.StoreTo.Add(tmpVar);
                    }
                    argIdx++;
                }
            }

            // Try to use single temporary variable insted of several if possible (especially useful for dup)
            // This has to be done after all temporary variables are assigned so we know about all loads
            foreach (var byteCode in body)
            {
                if ((byteCode.StoreTo == null) || (byteCode.StoreTo.Count <= 1)) 
                    continue;

                var locVars = byteCode.StoreTo;
                // For each of the variables, find the location where it is loaded - there should be preciesly one
                var loadedBy = locVars.Select(locVar => body.SelectMany(bc => bc.StackBefore).Single(s => s.LoadFrom == locVar)).ToList();
                // We now know that all the variables have a single load,
                // Let's make sure that they have also a single store - us
                if (loadedBy.All(slot => (slot.Definitions.Length == 1) && (slot.Definitions[0] == byteCode)))
                {
                    // Great - we can reduce everything into single variable
                    var tmpVar = new AstGeneratedVariable(string.Format("expr_{0:X2}", byteCode.Offset), locVars.Select(x => x.OriginalName).FirstOrDefault());
                    byteCode.StoreTo = new List<AstVariable> { tmpVar };
                    foreach (var bc in body)
                    {
                        for (var i = 0; i < bc.StackBefore.Length; i++)
                        {
                            // Is it one of the variable to be merged?
                            if (locVars.Contains(bc.StackBefore[i].LoadFrom))
                            {
                                // Replace with the new temp variable
                                bc.StackBefore[i] = new StackSlot(bc.StackBefore[i].Definitions, tmpVar);
                            }
                        }
                    }
                }
            }

            // Split and convert the normal local variables
            ConvertLocalVariables(body);

            // Convert branch targets to labels
            foreach (var byteCode in body)
            {
                if (byteCode.Operand is Instruction[])
                {
                    byteCode.Operand = (from target in (Instruction[])byteCode.Operand select instrToByteCode[target].Label(true)).ToArray();
                }
                else if (byteCode.Operand is Instruction)
                {
                    byteCode.Operand = instrToByteCode[(Instruction)byteCode.Operand].Label(true);
                }
                else if (byteCode.Operand is LookupSwitchData)
                {
                    var data = (LookupSwitchData) byteCode.Operand;
                    byteCode.Operand = data.Pairs.Select(x => new AstLabelKeyPair(instrToByteCode[x.Target].Label(true), x.Match)).ToArray();
                }
            }

            // Convert parameters to ILVariables
            ConvertParameters(body);

            // Replace temporary opcodes
            foreach (var byteCode in body)
            {
                switch (byteCode.Code)
                {
                    case AstCode.Dup_x1:
                    case AstCode.Dup_x2:
                    case AstCode.Dup2:
                    case AstCode.Dup2_x1:
                    case AstCode.Dup2_x2:
                    case AstCode.Swap:
                        byteCode.Code = AstCode.Dup;
                        break;
                    case AstCode.Pop2:
                        byteCode.Code = AstCode.Pop;
                        break;
                }
            }

            return body;
        }
Esempio n. 43
0
 private Polynomial(DefaultDictionary<int, Expression> Coefficients, Expression Variable)
 {
     coefficients = Coefficients;
     variable = Variable;
 }
Esempio n. 44
0
        public Expression Factor()
        {
            // Check if there is a simple factor of x.
            if (this[0].EqualsZero())
                return Product.New(variable, new Polynomial(Coefficients.Where(i => i.Key != 0).ToDictionary(i => i.Key - 1, i => i.Value), variable).Factor()).Evaluate();

            DefaultDictionary<Expression, int> factors = new DefaultDictionary<Expression, int>(0);
            switch (Degree)
            {
                //case 2:
                //    Expression a = this[2];
                //    Expression b = this[1];
                //    Expression c = this[0];

                //    // D = b^2 - 4*a*c
                //    Expression D = Add.New(Multiply.New(b, b), Multiply.New(-4, a, c));
                //    factors[Binary.Divide(Add.New(Unary.Negate(b), Call.Sqrt(D)), Multiply.New(2, a))] += 1;
                //    factors[Binary.Divide(Add.New(Unary.Negate(b), Call.Sqrt(D)), Multiply.New(2, a))] += 1;
                //    break;
                default:
                    return this;
            }

            // Assemble expression from factors.
            //return Multiply.New(factors.Select(i => Power.New(Binary.Subtract(x, i.Key), i.Value)));
        }
Esempio n. 45
0
 private void Research(GameProcess game)
 {
     var fmodPatchAddress = new DefaultDictionary<GameVersion, uint>(game.Version)
     {
         [GameVersion.Alpha] = ModuleAddress.FromImageAddress(game.ModuleContext, 0x140DA75),
         [GameVersion.Latest] = ModuleAddress.FromImageAddress(game.ModuleContext, 0xFAA9E5)
     };
     game.Memory.WriteByte(fmodPatchAddress, 0x2);
 }
Esempio n. 46
0
        private static MethodInfo GetCommand(Type type, string cmdName, CommandType cType)
        {
            if (!ircCommands.ContainsKey(type))
            {
                lock (ircCommands)
                {
                    if (!ircCommands.ContainsKey(type))
                    {
                        var dict = new DefaultDictionary<string, MethodInfo>();
                        var methods = from mi in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod)
                                      from attr in mi.GetCustomAttributes(typeof(IrcCommandAttribute), true).Cast<IrcCommandAttribute>()
                                      select new { Method = mi, Name = attr.Name };
                        foreach (var m in methods)
                        {
                            if (m.Name != "_Default")
                                dict[m.Name] = m.Method;
                            else
                                dict.Default = m.Method;
                        }
                        ircCommands.Add(type, dict);

                        dict = new DefaultDictionary<string, MethodInfo>();
                        methods = from mi in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod)
                                  from attr in mi.GetCustomAttributes(typeof(IrcClientCommandAttribute), true).Cast<IrcClientCommandAttribute>()
                                  select new { Method = mi, Name = attr.Name };
                        foreach (var m in methods)
                        {
                            if (m.Name != "_Default")
                                dict[m.Name] = m.Method;
                            else
                                dict.Default = m.Method;
                        }
                        clientCommands.Add(type, dict);
                    }
                }
            }
            if (cType == CommandType.Default)
                return ircCommands[type][cmdName];
            else if (cType == CommandType.Client)
                return clientCommands[type][cmdName];
            throw new ArgumentException("Unknown CommandType", "cType");
        }
Esempio n. 47
0
        /// <summary>
        /// Construct a polynomial of x from f(x).
        /// </summary>
        /// <param name="f"></param>
        /// <param name="x"></param>
        /// <returns></returns>
        public static Polynomial New(Expression f, Expression x)
        {
            // Match each term to A*x^N where A is constant with respect to x, and N is an integer.
            Variable A = PatternVariable.New("A", i => !i.DependsOn(x));
            Variable N = PatternVariable.New("N", i => i.IsInteger());
            Expression TermPattern = Product.New(A, Power.New(x, N));

            DefaultDictionary<int, Expression> P = new DefaultDictionary<int, Expression>(0);

            foreach (Expression i in Sum.TermsOf(f))
            {
                MatchContext Matched = TermPattern.Matches(i, Arrow.New(x, x));
                if (Matched == null)
                    throw new ArgumentException("f is not a polynomial of x.");

                int n = (int)Matched[N];
                P[n] += Matched[A];
            }

            return new Polynomial(P, x);
        }
Esempio n. 48
0
		/// <summary>
		/// Initializes the state range logic:
		/// Clears 'ranges' and sets 'ranges[entryPoint]' to the full range (int.MinValue to int.MaxValue)
		/// </summary>
		void InitStateRanges(ILNode entryPoint)
		{
			ranges = new DefaultDictionary<ILNode, StateRange>(n => new StateRange());
			ranges[entryPoint] = new StateRange(int.MinValue, int.MaxValue);
			rangeAnalysisStateVariable = null;
		}
Esempio n. 49
0
        public static Expression EvaluateSum(IEnumerable<Expression> Terms)
        {
            // Map terms to their coefficients.
            DefaultDictionary<Expression, Real> terms = new DefaultDictionary<Expression, Real>(0);

            // Accumulate constants and sum coefficient of each term.
            Real C = 0;
            foreach (Expression i in Terms)
            {
                if (i is Constant)
                {
                    C += (Real)i;
                }
                else
                {
                    // Find constant term.
                    Constant coeff = Product.TermsOf(i).OfType<Constant>().FirstOrDefault();
                    if (!ReferenceEquals(coeff, null))
                        terms[Product.New(Product.TermsOf(i).ExceptUnique(coeff, Expression.RefComparer))] += (Real)coeff;
                    else
                        terms[i] += 1;
                }
            }

            // Build a new expression with the accumulated terms.
            if (!C.EqualsZero())
                terms.Add(Constant.New(C), (Real)1);
            return Sum.New(terms
                .Where(i => !i.Value.EqualsZero())
                .Select(i => !i.Value.EqualsOne() ? Product.New(i.Key, Constant.New(i.Value)) : i.Key));
        }
Esempio n. 50
0
        // Combine like terms and multiply constants.
        protected override Expression VisitProduct(Product M)
        {
            // Map terms to exponents.
            DefaultDictionary<Expression, Real> terms = new DefaultDictionary<Expression, Real>(0);

            // Accumulate constants and sum exponent of each term.
            Real C = 1;
            foreach (Expression i in M.Terms.SelectMany(i => Product.TermsOf(Visit(i))))
            {
                if (i is Constant)
                {
                    Real Ci = (Real)i;
                    // Early exit if 0.
                    if (Ci.EqualsZero())
                        return 0;
                    C *= Ci;
                }
                else
                {
                    Power Pi = i as Power;
                    if (!ReferenceEquals(Pi, null) && Pi.Right is Constant)
                        terms[Pi.Left] += (Real)Pi.Right;
                    else
                        terms[i] += 1;
                }
            }

            // Build a new expression with the accumulated terms.
            if (!C.EqualsOne())
            {
                // Find a sum term that has a constant term to distribute into.
                KeyValuePair<Expression, Real> A = terms.FirstOrDefault(i => Real.Abs(i.Value).EqualsOne() && i.Key is Sum);
                if (!ReferenceEquals(A.Key, null))
                {
                    terms.Remove(A.Key);
                    terms[ExpandExtension.Distribute(C ^ A.Value, A.Key)] += A.Value;
                }
                else
                {
                    terms.Add(C, 1);
                }
            }
            return Product.New(terms
                .Where(i => !i.Value.EqualsZero())
                .Select(i => !i.Value.EqualsOne() ? Power.New(i.Key, Constant.New(i.Value)) : i.Key));
        }
 static void AuthClient_UpdateCacheEvent()
 {
     permissionRules = Server.Return((IPermissionAuthServer s) => s.PermissionRules());
 }