Ejemplo n.º 1
0
 public void ReduceSum()
 {
     IExpression sum = new Sum(Money.Dollar(3), Money.Dollar(4));
     Bank bank = new Bank();
     Money result = bank.Reduce(sum, "USD");
     Assert.Equal(Money.Dollar(7), result);
 }
Ejemplo n.º 2
0
        public YangZhang(string name, int period)
            : base(name)
        {
            _period = period;
            MuClose = new SimpleMovingAverage("MuC", period);
            MuOpen = new SimpleMovingAverage("MuO", period);
            CloseVol = new Sum("CV", period);
            OpenVol = new Sum("OV", period);
            RSVol = new SimpleMovingAverage("OV", period);

            TradeBar previous = null;

            OcCp = new FunctionalIndicator<TradeBar>(name + "_e", currentBar =>
            {
                var nextValue = ComputeOcCp(previous, currentBar);
                previous = currentBar;
                return nextValue;
            }   // in our IsReady function we just need at least two sample
            , trueRangeIndicator => trueRangeIndicator.Samples >= _period
            );

            CcOc = new FunctionalIndicator<TradeBar>(name + "_", currentBar => ComputeCcOc(currentBar)
            , trueRangeIndicator => trueRangeIndicator.Samples >= _period);

            OHL = new FunctionalIndicator<TradeBar>(name + "_", currentBar => ComputeOHL(currentBar)
            , trueRangeIndicator => trueRangeIndicator.Samples >= _period);

        }
Ejemplo n.º 3
0
        /// <summary>
        /// Creates a new Stochastics Indicator from the specified periods.
        /// </summary>
        /// <param name="name">The name of this indicator.</param>
        /// <param name="period">The period given to calculate the Fast %K</param>
        /// <param name="kPeriod">The K period given to calculated the Slow %K</param>
        /// <param name="dPeriod">The D period given to calculated the Slow %D</param>
        public Stochastic(string name, int period, int kPeriod, int dPeriod)
            : base(name)
        {
            Maximum = new Maximum(name + "_Max", period);
            Mininum = new Minimum(name + "_Min", period);
            SumFastK = new Sum(name + "_SumFastK", kPeriod);
            SumSlowK = new Sum(name + "_SumD", dPeriod);

            FastStoch = new FunctionalIndicator<TradeBar>(name + "_FastStoch",
                input => ComputeFastStoch(period, input),
                fastStoch => Maximum.IsReady,
                () => Maximum.Reset()
                );

            StochK = new FunctionalIndicator<TradeBar>(name + "_StochK",
                input => ComputeStochK(period, kPeriod, input),
                stochK => Maximum.IsReady,
                () => Maximum.Reset()
                );

            StochD = new FunctionalIndicator<TradeBar>(name + "_StochD",
                input => ComputeStochD(period, kPeriod, dPeriod),
                stochD => Maximum.IsReady,
                () => Maximum.Reset()
                );
        }
        public void SumAddsTwoNumbers()
        {
            // Arrange
            var activity = new Sum();

            var host = WorkflowInvokerTest.Create(activity);

            // InArguments is a dynamic object of type Microsoft.Activities.WorkflowArguments
            host.InArguments.Num1 = 1;
            host.InArguments.Num2 = 2;

            try
            {
                // Act
                host.TestActivity();

                // Assert
                // Note: The host automatically captures the out arguments
                host.AssertOutArgument.AreEqual("Result", 3);

                Assert.AreEqual(3, host.OutArguments.Result);
            }
            finally
            {
                // Note: The host automatically captures tracking
                host.Tracking.Trace();
            }
        }
Ejemplo n.º 5
0
		/// <summary>
		/// To create the indicator <see cref="UltimateOscillator"/>.
		/// </summary>
		public UltimateOscillator()
		{
			_period7BpSum = new Sum { Length = _period7 };
			_period14BpSum = new Sum { Length = _period14 };
			_period28BpSum = new Sum { Length = _period28 };

			_period7TrSum = new Sum { Length = _period7 };
			_period14TrSum = new Sum { Length = _period14 };
			_period28TrSum = new Sum { Length = _period28 };
		}
Ejemplo n.º 6
0
        public void ComputesCorrectly() {
            var sum = new Sum(2);
            var time = DateTime.UtcNow;

            sum.Update(time.AddDays(1), 1m);
            sum.Update(time.AddDays(1), 2m);
            sum.Update(time.AddDays(1), 3m);

            Assert.AreEqual(sum.Current.Value, 2m + 3m);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UltimateOscillator"/> class using the specified parameters
 /// </summary>
 /// <param name="name">The name of this indicator</param>
 /// <param name="period1">The first period</param>
 /// <param name="period2">The second period</param>
 /// <param name="period3">The third period</param>
 public UltimateOscillator(string name, int period1, int period2, int period3)
     : base(name)
 {
     _period = Math.Max(Math.Max(period1, period2), period3);
     _trueRange = new TrueRange(name + "_TR");
     _sumBuyingPressure1 = new Sum(name + "_BP1", period1);
     _sumBuyingPressure2 = new Sum(name + "_BP2", period2);
     _sumBuyingPressure3 = new Sum(name + "_BP3", period3);
     _sumTrueRange1 = new Sum(name + "_TR1", period1);
     _sumTrueRange2 = new Sum(name + "_TR2", period2);
     _sumTrueRange3 = new Sum(name + "_TR3", period3);
 }
Ejemplo n.º 8
0
public static void Main()
{
Sum m = new Sum(10, 20);
Thread th = new Thread(new ThreadStart(m.Add));
th.Start();
for(int i= 0; i < 10; i++)
{
Thread.Sleep(500);
Console.Write(".");
}
th.Join();
Console.WriteLine("Main result is " + m.result);
}
        public void DelegatesCanBeAssignedToDelegateTypedVariable()
        {
            var add = new Add((left, right) => left + right);
            var sum = new Sum((left, right) => left + right);

            add += (left, right) => left + right;

            int[] a;
            int[] b;

            add.Invoke(1,1);

            Delegate dAdd = add;
            Delegate dSum = sum;
        }
Ejemplo n.º 10
0
        public void 三筆一組取Cost總和()
        {
            // Arrange
            var target = new Sum();
            var property = "Cost";
            var groupSize = 3;
            var products = this.getData();           

            // Act
            var actual = target.Add<Product>(groupSize, property, products);

            // Assert
            var expectedResult = new List<int> { 6, 15, 24, 21 };          
            CollectionAssert.AreEqual(expectedResult, actual);
        }
Ejemplo n.º 11
0
        public void 四筆一組取Revenue總和()
        {
            // Arrange
            var target = new Sum();
            var property = "Revenue";
            var groupSize = 4;
            var products = this.getData();

            // Act
            var actual = target.Add<Product>(groupSize, property, products);

            //assert  
            var expectedResult = new List<int> { 50, 66, 60 };
            CollectionAssert.AreEqual(expectedResult, actual);
        }
Ejemplo n.º 12
0
        public void ResetsCorrectly() {
            var sum = new Sum(2);
            var time = DateTime.UtcNow;

            sum.Update(time.AddDays(1), 1m);
            sum.Update(time.AddDays(1), 2m);
            sum.Update(time.AddDays(1), 3m);

            Assert.IsTrue(sum.IsReady);

            sum.Reset();

            TestHelper.AssertIndicatorIsInDefaultState(sum);
            Assert.AreEqual(sum.Current.Value, 0m);
            sum.Update(time.AddDays(1), 1);
            Assert.AreEqual(sum.Current.Value, 1m);
        }
Ejemplo n.º 13
0
 public void Visit(Sum sum)
 {
     // Nothing to do here...
 }
Ejemplo n.º 14
0
 public _IEnumerator_251(Sum _enclosing)
 {
     this._enclosing = _enclosing;
     this.i          = 0;
 }
Ejemplo n.º 15
0
 public void Visit(Sum sum)
 {
     ResultIsIntAndBothOperandsMustBeInt(sum);
 }
Ejemplo n.º 16
0
    public void OnDrag(PointerEventData eventData)
    {
        shouldMove = false;
        if (!hasBeenDragged)
        {
            return;
        }


        void move()
        {
            shouldMove = true;
        }

        previewState.Match(
            //should I stop?
            sum => sum.Match(forward => { move(); /*within one*/ }, backward =>
        {
            move();    /*paren changed*/

            void Fail()
            {
                backward.unHighlight();
                previewState = Sum <PreviewInfo, Unit> .Inr(new Unit());  // TODO verify
            }
            (var spawnTarget, var targets) = getTargets();
            FreshPreview(spawnTarget, targets).Match(preview => preview.Match(forward => Fail(), newBackward =>
            {
                if (newBackward.paren != backward.paren)
                {
                    Fail();
                }
                else
                {
                    backward.highlight();
                }
                //we'll wait a frame to re-highlight this way
            }, redundant => Fail()), _ => Fail());
        }, redundant =>
        {
            move();
            void Fail()
            {
                redundant.unhighlight();
                previewState = Sum <PreviewInfo, Unit> .Inr(new Unit());
            }

            (var spawnTarget, var targets) = getTargets();

            /* path has changed or index != 0 */
            FreshPreview(spawnTarget, targets).Match(preview => preview.Match(_ =>
            {
                print("forward");
                Fail();
            }, _ =>
            {
                print("backward");
                Fail();
            }, state =>
            {
                if (state.path.Count == redundant.path.Count && state.path.Select((x, i) => x == redundant.path[i]).All(x => x))
                {    //the path is the same
                    if (state.my_index == redundant.my_index)
                    {
                        print("same path");
                        /* do nothing */
                    }
                    else
                    {
                        print("path same length, but differs");
                        Fail();
                    }
                }
                else
                {
                    print("path is just different");
                    Fail();
                }
            }), _ => Fail());
        })
            , __ =>
        {
            //Should I start?
            var(spawnTarget, targets) = getTargets();
            previewState = FreshPreview(spawnTarget, targets);
            previewState.Match(sum => sum.Match(forward => { /* place*/ }, backward =>
            {
                /* highlight*/
                backward.highlight();
            }, redundant => { redundant.highlight(); }),
                               _ =>
            {     //no preview from last frame, no preview for next frame
                move();
            });
        });
    }
Ejemplo n.º 17
0
 public Decimal Sum(Sum sum)
 {
     return(_mongoContext.Total(sum));
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Подробное отображение объекта в UI.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            string capitalizationText = Сapitalization ? "с капитализацией" : "без капитализации";

            return($"{Sum.ToString("##,###")}$, {Percent * 100}%, {PeriodInMonth} месяцев {capitalizationText}, ожидаемая сумма: {CalcTotalSum().ToString("##,###")}$");
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Creates a default instance of the Average object using default instances of the
 /// Sum and Divide objects to calculate the average.
 /// </summary>
 internal Average()
 {
     DivideFunction = new Divide();
     SumFunction = new Sum();
 }
Ejemplo n.º 20
0
 public void RegisterHandler(Sum showSum)
 {
     ShowSum = showSum;
 }
Ejemplo n.º 21
0
        public MathTryParseResult TryParse(string expression, ICollection <Variable> variables = null)
        {
            var sum = new Sum()
            {
                Variables = variables
            };

            var balance = 0;
            var term    = "";
            var counter = 0;

            var mathTryParseResult = new MathTryParseResult()
            {
                ErrorMessage        = "This is not sum: " + expression,
                IsSuccessfulCreated = false
            };

            if (!expression.Contains("+") && !expression.Contains("-") ||
                (expression.Last() == '+' || expression.Last() == '-'))
            {
                return(mathTryParseResult);
            }

            foreach (var ch in expression)
            {
                counter++;
                if (ch == '(')
                {
                    balance--;
                }
                if (ch == ')')
                {
                    balance++;
                }

                if ((ch == '+' || ch == '-') && balance == 0 && counter != 1)
                {
                    var parseResult = _mathParser.TryParse(term, variables);

                    if (!parseResult.IsSuccessfulCreated)
                    {
                        return(parseResult);
                    }
                    sum.Terms.Add(parseResult.Expression);
                    term = ch == '-'? "-":"";
                    continue;
                }

                term += ch;
                if (counter == expression.Length)
                {
                    if (sum.Terms.Count == 0)
                    {
                        return(mathTryParseResult);
                    }

                    var parseResult = _mathParser.TryParse(term, variables);

                    if (!parseResult.IsSuccessfulCreated)
                    {
                        return(parseResult);
                    }
                    sum.Terms.Add(parseResult.Expression);
                }
            }

            if (sum.Terms.Count == 1)
            {
                return(mathTryParseResult);
            }

            return(new MathTryParseResult
            {
                IsSuccessfulCreated = true,
                Expression = sum
            });
        }
        public void GetMetricMeasurements_ReturnsExpected()
        {
            var opts          = new MetricsEndpointOptions();
            var stats         = new OpenCensusStats();
            var tagsComponent = new TagsComponent();
            var tagger        = tagsComponent.Tagger;
            var ep            = new MetricsEndpoint(opts, stats);

            IMeasureDouble testMeasure = MeasureDouble.Create("test.total", "test", MeasureUnit.Bytes);

            SetupTestView(stats, Sum.Create(), testMeasure, "test.test1");

            ITagContext context1 = tagger
                                   .EmptyBuilder
                                   .Put(TagKey.Create("a"), TagValue.Create("v1"))
                                   .Put(TagKey.Create("b"), TagValue.Create("v1"))
                                   .Put(TagKey.Create("c"), TagValue.Create("v1"))
                                   .Build();

            ITagContext context2 = tagger
                                   .EmptyBuilder
                                   .Put(TagKey.Create("a"), TagValue.Create("v1"))
                                   .Build();

            ITagContext context3 = tagger
                                   .EmptyBuilder
                                   .Put(TagKey.Create("b"), TagValue.Create("v1"))
                                   .Build();

            ITagContext context4 = tagger
                                   .EmptyBuilder
                                   .Put(TagKey.Create("c"), TagValue.Create("v1"))
                                   .Build();

            long allKeyssum = 0;

            for (int i = 0; i < 10; i++)
            {
                allKeyssum = allKeyssum + i;
                stats.StatsRecorder.NewMeasureMap().Put(testMeasure, i).Record(context1);
            }

            long asum = 0;

            for (int i = 0; i < 10; i++)
            {
                asum = asum + i;
                stats.StatsRecorder.NewMeasureMap().Put(testMeasure, i).Record(context2);
            }

            long bsum = 0;

            for (int i = 0; i < 10; i++)
            {
                bsum = bsum + i;
                stats.StatsRecorder.NewMeasureMap().Put(testMeasure, i).Record(context3);
            }

            long csum = 0;

            for (int i = 0; i < 10; i++)
            {
                csum = csum + i;
                stats.StatsRecorder.NewMeasureMap().Put(testMeasure, i).Record(context4);
            }

            var alltags = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("a", "v1"),
                new KeyValuePair <string, string>("b", "v1"),
                new KeyValuePair <string, string>("c", "v1")
            };

            var viewData = stats.ViewManager.GetView(ViewName.Create("test.test1"));
            var result   = ep.GetMetricMeasurements(viewData, alltags);

            Assert.NotNull(result);
            Assert.Single(result);
            var sample = result[0];

            Assert.Equal(allKeyssum, sample.Value);
            Assert.Equal(MetricStatistic.TOTAL, sample.Statistic);

            var atags = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("a", "v1"),
            };

            result = ep.GetMetricMeasurements(viewData, atags);
            Assert.NotNull(result);
            Assert.Single(result);
            sample = result[0];
            Assert.Equal(allKeyssum + asum, sample.Value);
            Assert.Equal(MetricStatistic.TOTAL, sample.Statistic);

            var btags = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("b", "v1"),
            };

            result = ep.GetMetricMeasurements(viewData, btags);
            Assert.NotNull(result);
            Assert.Single(result);
            sample = result[0];
            Assert.Equal(allKeyssum + bsum, sample.Value);
            Assert.Equal(MetricStatistic.TOTAL, sample.Statistic);

            var ctags = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("c", "v1"),
            };

            result = ep.GetMetricMeasurements(viewData, ctags);
            Assert.NotNull(result);
            Assert.Single(result);
            sample = result[0];
            Assert.Equal(allKeyssum + csum, sample.Value);
            Assert.Equal(MetricStatistic.TOTAL, sample.Statistic);

            var abtags = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("a", "v1"),
                new KeyValuePair <string, string>("b", "v1"),
            };

            result = ep.GetMetricMeasurements(viewData, abtags);
            Assert.NotNull(result);
            Assert.Single(result);
            sample = result[0];
            Assert.Equal(allKeyssum, sample.Value);
            Assert.Equal(MetricStatistic.TOTAL, sample.Statistic);

            var actags = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("a", "v1"),
                new KeyValuePair <string, string>("c", "v1"),
            };

            result = ep.GetMetricMeasurements(viewData, actags);
            Assert.NotNull(result);
            Assert.Single(result);
            sample = result[0];
            Assert.Equal(allKeyssum, sample.Value);
            Assert.Equal(MetricStatistic.TOTAL, sample.Statistic);

            var bctags = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("b", "v1"),
                new KeyValuePair <string, string>("c", "v1"),
            };

            result = ep.GetMetricMeasurements(viewData, bctags);
            Assert.NotNull(result);
            Assert.Single(result);
            sample = result[0];
            Assert.Equal(allKeyssum, sample.Value);
            Assert.Equal(MetricStatistic.TOTAL, sample.Statistic);
        }
Ejemplo n.º 23
0
        public void Main()
        {
            var statsComponent = new StatsComponent();
            var viewManager    = statsComponent.ViewManager;
            var statsRecorder  = statsComponent.StatsRecorder;
            var tagsComponent  = new TagsComponent();
            var tagger         = tagsComponent.Tagger;

            var FRONTEND_KEY            = TagKey.Create("my.org/keys/frontend");
            var FRONTEND_OS_KEY         = TagKey.Create("my.org/keys/frontend/os");
            var FRONTEND_OS_VERSION_KEY = TagKey.Create("my.org/keys/frontend/os/version");

            var VIDEO_SIZE = MeasureLong.Create("my.org/measure/video_size", "size of processed videos", "MBy");

            var VIDEO_SIZE_BY_FRONTEND_VIEW_NAME = ViewName.Create("my.org/views/video_size_byfrontend");
            var VIDEO_SIZE_BY_FRONTEND_VIEW      = View.Create(
                VIDEO_SIZE_BY_FRONTEND_VIEW_NAME,
                "processed video size over time",
                VIDEO_SIZE,
                Distribution.Create(BucketBoundaries.Create(new List <double>()
            {
                0.0, 256.0, 65536.0
            })),
                new List <TagKey>()
            {
                FRONTEND_KEY
            });

            var VIDEO_SIZE_ALL_VIEW_NAME = ViewName.Create("my.org/views/video_size_all");
            var VIDEO_SIZE_VIEW_ALL      = View.Create(
                VIDEO_SIZE_ALL_VIEW_NAME,
                "processed video size over time",
                VIDEO_SIZE,
                Distribution.Create(BucketBoundaries.Create(new List <double>()
            {
                0.0, 256.0, 65536.0
            })),
                new List <TagKey>()
            {
            });


            var VIDEO_SIZE_TOTAL_VIEW_NAME = ViewName.Create("my.org/views/video_size_total");
            var VIDEO_SIZE_TOTAL           = View.Create(
                VIDEO_SIZE_TOTAL_VIEW_NAME,
                "total video size over time",
                VIDEO_SIZE,
                Sum.Create(),
                new List <TagKey>()
            {
                FRONTEND_KEY
            });

            var VIDEOS_PROCESSED_VIEW_NAME = ViewName.Create("my.org/views/videos_processed");
            var VIDEOS_PROCESSED           = View.Create(
                VIDEOS_PROCESSED_VIEW_NAME,
                "total video processed",
                VIDEO_SIZE,
                Count.Create(),
                new List <TagKey>()
            {
                FRONTEND_KEY
            });

            viewManager.RegisterView(VIDEO_SIZE_VIEW_ALL);
            viewManager.RegisterView(VIDEO_SIZE_BY_FRONTEND_VIEW);
            viewManager.RegisterView(VIDEO_SIZE_TOTAL);
            viewManager.RegisterView(VIDEOS_PROCESSED);

            var context1 = tagger
                           .EmptyBuilder
                           .Put(FRONTEND_KEY, TagValue.Create("front1"))
                           .Build();
            var context2 = tagger
                           .EmptyBuilder
                           .Put(FRONTEND_KEY, TagValue.Create("front2"))
                           .Build();

            long sum = 0;

            for (var i = 0; i < 10; i++)
            {
                sum = sum + (25648 * i);
                if (i % 2 == 0)
                {
                    statsRecorder.NewMeasureMap().Put(VIDEO_SIZE, 25648 * i).Record(context1);
                }
                else
                {
                    statsRecorder.NewMeasureMap().Put(VIDEO_SIZE, 25648 * i).Record(context2);
                }
            }

            var viewDataByFrontend = viewManager.GetView(VIDEO_SIZE_BY_FRONTEND_VIEW_NAME);
            var viewDataAggMap     = viewDataByFrontend.AggregationMap.ToList();

            output.WriteLine(viewDataByFrontend.ToString());

            var viewDataAll       = viewManager.GetView(VIDEO_SIZE_ALL_VIEW_NAME);
            var viewDataAggMapAll = viewDataAll.AggregationMap.ToList();

            output.WriteLine(viewDataAll.ToString());

            var viewData1       = viewManager.GetView(VIDEO_SIZE_TOTAL_VIEW_NAME);
            var viewData1AggMap = viewData1.AggregationMap.ToList();

            output.WriteLine(viewData1.ToString());

            var viewData2       = viewManager.GetView(VIDEOS_PROCESSED_VIEW_NAME);
            var viewData2AggMap = viewData2.AggregationMap.ToList();

            output.WriteLine(viewData2.ToString());

            output.WriteLine(sum.ToString());
        }
        public void GetAvailableTags_ReturnsExpected()
        {
            var opts  = new MetricsEndpointOptions();
            var stats = new OpenCensusStats();
            var ep    = new MetricsEndpoint(opts, stats);

            SetupTestView(stats, Sum.Create(), null, "test.test1");
            var viewData = stats.ViewManager.GetView(ViewName.Create("test.test1"));

            var dict = new Dictionary <TagValues, IAggregationData>()
            {
                {
                    TagValues.Create(new List <ITagValue>()
                    {
                        TagValue.Create("v1"), TagValue.Create("v1"), TagValue.Create("v1")
                    }),
                    SumDataDouble.Create(1)
                },
                {
                    TagValues.Create(new List <ITagValue>()
                    {
                        TagValue.Create("v2"), TagValue.Create("v2"), TagValue.Create("v2")
                    }),
                    SumDataDouble.Create(1)
                }
            };

            var result = ep.GetAvailableTags(viewData.View.Columns, dict);

            Assert.NotNull(result);
            Assert.Equal(3, result.Count);

            var tag = result[0];

            Assert.Equal("a", tag.Tag);
            Assert.Contains("v1", tag.Values);
            Assert.Contains("v2", tag.Values);

            tag = result[1];
            Assert.Equal("b", tag.Tag);
            Assert.Contains("v1", tag.Values);
            Assert.Contains("v2", tag.Values);

            tag = result[2];
            Assert.Equal("c", tag.Tag);
            Assert.Contains("v1", tag.Values);
            Assert.Contains("v2", tag.Values);

            dict   = new Dictionary <TagValues, IAggregationData>();
            result = ep.GetAvailableTags(viewData.View.Columns, dict);
            Assert.NotNull(result);
            Assert.Equal(3, result.Count);

            tag = result[0];
            Assert.Equal("a", tag.Tag);
            Assert.Empty(tag.Values);

            tag = result[1];
            Assert.Equal("b", tag.Tag);
            Assert.Empty(tag.Values);

            tag = result[2];
            Assert.Equal("c", tag.Tag);
            Assert.Empty(tag.Values);
        }
        public void GetMetricSamples_ReturnsExpected()
        {
            var opts  = new MetricsEndpointOptions();
            var stats = new OpenCensusStats();
            var ep    = new MetricsEndpoint(opts, stats);

            SetupTestView(stats, Sum.Create(), null, "test.test1");
            var viewData             = stats.ViewManager.GetView(ViewName.Create("test.test1"));
            IAggregationData aggData = SumDataDouble.Create(100);

            Assert.NotNull(viewData);
            var result = ep.GetMetricSamples(aggData, viewData);

            Assert.NotNull(result);
            Assert.Single(result);
            var sample = result[0];

            Assert.Equal(100, sample.Value);
            Assert.Equal(MetricStatistic.TOTALTIME, sample.Statistic);

            SetupTestView(stats, Sum.Create(), null, "test.test2");
            viewData = stats.ViewManager.GetView(ViewName.Create("test.test2"));
            aggData  = SumDataLong.Create(100);

            Assert.NotNull(viewData);
            result = ep.GetMetricSamples(aggData, viewData);
            Assert.NotNull(result);
            Assert.Single(result);
            sample = result[0];
            Assert.Equal(100, sample.Value);
            Assert.Equal(MetricStatistic.TOTALTIME, sample.Statistic);

            SetupTestView(stats, Count.Create(), null, "test.test3");
            viewData = stats.ViewManager.GetView(ViewName.Create("test.test3"));
            aggData  = CountData.Create(100);

            Assert.NotNull(viewData);
            result = ep.GetMetricSamples(aggData, viewData);
            Assert.NotNull(result);
            Assert.Single(result);
            sample = result[0];
            Assert.Equal(100, sample.Value);
            Assert.Equal(MetricStatistic.COUNT, sample.Statistic);

            SetupTestView(stats, Mean.Create(), null, "test.test4");
            viewData = stats.ViewManager.GetView(ViewName.Create("test.test4"));
            aggData  = MeanData.Create(100, 50, 1, 500);

            Assert.NotNull(viewData);
            result = ep.GetMetricSamples(aggData, viewData);
            Assert.NotNull(result);
            Assert.Equal(2, result.Count);
            sample = result[0];
            Assert.Equal(50, sample.Value);
            Assert.Equal(MetricStatistic.COUNT, sample.Statistic);
            sample = result[1];
            Assert.Equal(100 * 50, sample.Value);
            Assert.Equal(MetricStatistic.TOTALTIME, sample.Statistic);

            SetupTestView(stats, Distribution.Create(BucketBoundaries.Create(new List <double>()
            {
                0.0, 10.0, 20.0
            })), null, "test.test5");
            viewData = stats.ViewManager.GetView(ViewName.Create("test.test5"));
            aggData  = DistributionData.Create(100, 50, 5, 200, 5, new List <long>()
            {
                10, 20, 20
            });

            Assert.NotNull(viewData);
            result = ep.GetMetricSamples(aggData, viewData);
            Assert.NotNull(result);
            Assert.Equal(3, result.Count);

            sample = result[0];
            Assert.Equal(50, sample.Value);
            Assert.Equal(MetricStatistic.COUNT, sample.Statistic);

            sample = result[1];
            Assert.Equal(200, sample.Value);
            Assert.Equal(MetricStatistic.MAX, sample.Statistic);

            sample = result[2];
            Assert.Equal(100 * 50, sample.Value);
            Assert.Equal(MetricStatistic.TOTALTIME, sample.Statistic);
        }
Ejemplo n.º 26
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            Sum s = new Sum(tbA.Text, tbB.Text);

            lbl.Content = s.summa();
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Creates an expression object from <see cref="FunctionToken"/>.
        /// </summary>
        /// <param name="token">The function token.</param>
        /// <returns>An expression.</returns>
        protected virtual IExpression CreateFunction(FunctionToken token)
        {
            IExpression exp;

            switch (token.Function)
            {
            case Functions.Add:
                exp = new Add(); break;

            case Functions.Sub:
                exp = new Sub(); break;

            case Functions.Mul:
                exp = new Mul(); break;

            case Functions.Div:
                exp = new Div(); break;

            case Functions.Pow:
                exp = new Pow(); break;

            case Functions.Absolute:
                exp = new Abs(); break;

            case Functions.Sine:
                exp = new Sin(); break;

            case Functions.Cosine:
                exp = new Cos(); break;

            case Functions.Tangent:
                exp = new Tan(); break;

            case Functions.Cotangent:
                exp = new Cot(); break;

            case Functions.Secant:
                exp = new Sec(); break;

            case Functions.Cosecant:
                exp = new Csc(); break;

            case Functions.Arcsine:
                exp = new Arcsin(); break;

            case Functions.Arccosine:
                exp = new Arccos(); break;

            case Functions.Arctangent:
                exp = new Arctan(); break;

            case Functions.Arccotangent:
                exp = new Arccot(); break;

            case Functions.Arcsecant:
                exp = new Arcsec(); break;

            case Functions.Arccosecant:
                exp = new Arccsc(); break;

            case Functions.Sqrt:
                exp = new Sqrt(); break;

            case Functions.Root:
                exp = new Root(); break;

            case Functions.Ln:
                exp = new Ln(); break;

            case Functions.Lg:
                exp = new Lg(); break;

            case Functions.Lb:
                exp = new Lb(); break;

            case Functions.Log:
                exp = new Log(); break;

            case Functions.Sineh:
                exp = new Sinh(); break;

            case Functions.Cosineh:
                exp = new Cosh(); break;

            case Functions.Tangenth:
                exp = new Tanh(); break;

            case Functions.Cotangenth:
                exp = new Coth(); break;

            case Functions.Secanth:
                exp = new Sech(); break;

            case Functions.Cosecanth:
                exp = new Csch(); break;

            case Functions.Arsineh:
                exp = new Arsinh(); break;

            case Functions.Arcosineh:
                exp = new Arcosh(); break;

            case Functions.Artangenth:
                exp = new Artanh(); break;

            case Functions.Arcotangenth:
                exp = new Arcoth(); break;

            case Functions.Arsecanth:
                exp = new Arsech(); break;

            case Functions.Arcosecanth:
                exp = new Arcsch(); break;

            case Functions.Exp:
                exp = new Exp(); break;

            case Functions.GCD:
                exp = new GCD(); break;

            case Functions.LCM:
                exp = new LCM(); break;

            case Functions.Factorial:
                exp = new Fact(); break;

            case Functions.Sum:
                exp = new Sum(); break;

            case Functions.Product:
                exp = new Product(); break;

            case Functions.Round:
                exp = new Round(); break;

            case Functions.Floor:
                exp = new Floor(); break;

            case Functions.Ceil:
                exp = new Ceil(); break;

            case Functions.Derivative:
                exp = new Derivative(); break;

            case Functions.Simplify:
                exp = new Simplify(); break;

            case Functions.Del:
                exp = new Del(); break;

            case Functions.Define:
                exp = new Define(); break;

            case Functions.Vector:
                exp = new Vector(); break;

            case Functions.Matrix:
                exp = new Matrix(); break;

            case Functions.Transpose:
                exp = new Transpose(); break;

            case Functions.Determinant:
                exp = new Determinant(); break;

            case Functions.Inverse:
                exp = new Inverse(); break;

            case Functions.If:
                exp = new If(); break;

            case Functions.For:
                exp = new For(); break;

            case Functions.While:
                exp = new While(); break;

            case Functions.Undefine:
                exp = new Undefine(); break;

            case Functions.Im:
                exp = new Im(); break;

            case Functions.Re:
                exp = new Re(); break;

            case Functions.Phase:
                exp = new Phase(); break;

            case Functions.Conjugate:
                exp = new Conjugate(); break;

            case Functions.Reciprocal:
                exp = new Reciprocal(); break;

            case Functions.Min:
                exp = new Min(); break;

            case Functions.Max:
                exp = new Max(); break;

            case Functions.Avg:
                exp = new Avg(); break;

            case Functions.Count:
                exp = new Count(); break;

            case Functions.Var:
                exp = new Var(); break;

            case Functions.Varp:
                exp = new Varp(); break;

            case Functions.Stdev:
                exp = new Stdev(); break;

            case Functions.Stdevp:
                exp = new Stdevp(); break;

            default:
                exp = null; break;
            }

            var diff = exp as DifferentParametersExpression;

            if (diff != null)
            {
                diff.ParametersCount = token.CountOfParams;
            }

            return(exp);
        }
Ejemplo n.º 28
0
 public void Visit(Sum node)
 {
     VisitChildren(node);
 }
Ejemplo n.º 29
0
 public static void AddValue(String element, Sum sum)
 {
     sum(element);
 }
Ejemplo n.º 30
0
 public void Visit(Sum sum)
 {
     Visit(sum, OpCodes.Add_Ovf); // With overflow check
 }
Ejemplo n.º 31
0
 public BuiltInFunctions()
 {
     // Text
     Functions["len"]         = new Len();
     Functions["lower"]       = new Lower();
     Functions["upper"]       = new Upper();
     Functions["left"]        = new Left();
     Functions["right"]       = new Right();
     Functions["mid"]         = new Mid();
     Functions["replace"]     = new Replace();
     Functions["rept"]        = new Rept();
     Functions["substitute"]  = new Substitute();
     Functions["concatenate"] = new Concatenate();
     Functions["char"]        = new CharFunction();
     Functions["exact"]       = new Exact();
     Functions["find"]        = new Find();
     Functions["fixed"]       = new Fixed();
     Functions["proper"]      = new Proper();
     Functions["search"]      = new Search();
     Functions["text"]        = new Text.Text();
     Functions["t"]           = new T();
     Functions["hyperlink"]   = new Hyperlink();
     Functions["value"]       = new Value();
     // Numbers
     Functions["int"] = new CInt();
     // Math
     Functions["abs"]         = new Abs();
     Functions["asin"]        = new Asin();
     Functions["asinh"]       = new Asinh();
     Functions["cos"]         = new Cos();
     Functions["cosh"]        = new Cosh();
     Functions["power"]       = new Power();
     Functions["sign"]        = new Sign();
     Functions["sqrt"]        = new Sqrt();
     Functions["sqrtpi"]      = new SqrtPi();
     Functions["pi"]          = new Pi();
     Functions["product"]     = new Product();
     Functions["ceiling"]     = new Ceiling();
     Functions["count"]       = new Count();
     Functions["counta"]      = new CountA();
     Functions["countblank"]  = new CountBlank();
     Functions["countif"]     = new CountIf();
     Functions["countifs"]    = new CountIfs();
     Functions["fact"]        = new Fact();
     Functions["floor"]       = new Floor();
     Functions["sin"]         = new Sin();
     Functions["sinh"]        = new Sinh();
     Functions["sum"]         = new Sum();
     Functions["sumif"]       = new SumIf();
     Functions["sumifs"]      = new SumIfs();
     Functions["sumproduct"]  = new SumProduct();
     Functions["sumsq"]       = new Sumsq();
     Functions["stdev"]       = new Stdev();
     Functions["stdevp"]      = new StdevP();
     Functions["stdev.s"]     = new Stdev();
     Functions["stdev.p"]     = new StdevP();
     Functions["subtotal"]    = new Subtotal();
     Functions["exp"]         = new Exp();
     Functions["log"]         = new Log();
     Functions["log10"]       = new Log10();
     Functions["ln"]          = new Ln();
     Functions["max"]         = new Max();
     Functions["maxa"]        = new Maxa();
     Functions["median"]      = new Median();
     Functions["min"]         = new Min();
     Functions["mina"]        = new Mina();
     Functions["mod"]         = new Mod();
     Functions["average"]     = new Average();
     Functions["averagea"]    = new AverageA();
     Functions["averageif"]   = new AverageIf();
     Functions["averageifs"]  = new AverageIfs();
     Functions["round"]       = new Round();
     Functions["rounddown"]   = new Rounddown();
     Functions["roundup"]     = new Roundup();
     Functions["rand"]        = new Rand();
     Functions["randbetween"] = new RandBetween();
     Functions["rank"]        = new Rank();
     Functions["rank.eq"]     = new Rank();
     Functions["rank.avg"]    = new Rank(true);
     Functions["quotient"]    = new Quotient();
     Functions["trunc"]       = new Trunc();
     Functions["tan"]         = new Tan();
     Functions["tanh"]        = new Tanh();
     Functions["atan"]        = new Atan();
     Functions["atan2"]       = new Atan2();
     Functions["atanh"]       = new Atanh();
     Functions["acos"]        = new Acos();
     Functions["acosh"]       = new Acosh();
     Functions["var"]         = new Var();
     Functions["varp"]        = new VarP();
     Functions["large"]       = new Large();
     Functions["small"]       = new Small();
     Functions["degrees"]     = new Degrees();
     // Information
     Functions["isblank"]    = new IsBlank();
     Functions["isnumber"]   = new IsNumber();
     Functions["istext"]     = new IsText();
     Functions["isnontext"]  = new IsNonText();
     Functions["iserror"]    = new IsError();
     Functions["iserr"]      = new IsErr();
     Functions["error.type"] = new ErrorType();
     Functions["iseven"]     = new IsEven();
     Functions["isodd"]      = new IsOdd();
     Functions["islogical"]  = new IsLogical();
     Functions["isna"]       = new IsNa();
     Functions["na"]         = new Na();
     Functions["n"]          = new N();
     // Logical
     Functions["if"]      = new If();
     Functions["iferror"] = new IfError();
     Functions["ifna"]    = new IfNa();
     Functions["not"]     = new Not();
     Functions["and"]     = new And();
     Functions["or"]      = new Or();
     Functions["true"]    = new True();
     Functions["false"]   = new False();
     // Reference and lookup
     Functions["address"] = new Address();
     Functions["hlookup"] = new HLookup();
     Functions["vlookup"] = new VLookup();
     Functions["lookup"]  = new Lookup();
     Functions["match"]   = new Match();
     Functions["row"]     = new Row()
     {
         SkipArgumentEvaluation = true
     };
     Functions["rows"] = new Rows()
     {
         SkipArgumentEvaluation = true
     };
     Functions["column"] = new Column()
     {
         SkipArgumentEvaluation = true
     };
     Functions["columns"] = new Columns()
     {
         SkipArgumentEvaluation = true
     };
     Functions["choose"]   = new Choose();
     Functions["index"]    = new Index();
     Functions["indirect"] = new Indirect();
     Functions["offset"]   = new Offset()
     {
         SkipArgumentEvaluation = true
     };
     // Date
     Functions["date"]             = new Date();
     Functions["today"]            = new Today();
     Functions["now"]              = new Now();
     Functions["day"]              = new Day();
     Functions["month"]            = new Month();
     Functions["year"]             = new Year();
     Functions["time"]             = new Time();
     Functions["hour"]             = new Hour();
     Functions["minute"]           = new Minute();
     Functions["second"]           = new Second();
     Functions["weeknum"]          = new Weeknum();
     Functions["weekday"]          = new Weekday();
     Functions["days360"]          = new Days360();
     Functions["yearfrac"]         = new Yearfrac();
     Functions["edate"]            = new Edate();
     Functions["eomonth"]          = new Eomonth();
     Functions["isoweeknum"]       = new IsoWeekNum();
     Functions["workday"]          = new Workday();
     Functions["networkdays"]      = new Networkdays();
     Functions["networkdays.intl"] = new NetworkdaysIntl();
     Functions["datevalue"]        = new DateValue();
     Functions["timevalue"]        = new TimeValue();
     // Database
     Functions["dget"]     = new Dget();
     Functions["dcount"]   = new Dcount();
     Functions["dcounta"]  = new DcountA();
     Functions["dmax"]     = new Dmax();
     Functions["dmin"]     = new Dmin();
     Functions["dsum"]     = new Dsum();
     Functions["daverage"] = new Daverage();
     Functions["dvar"]     = new Dvar();
     Functions["dvarp"]    = new Dvarp();
 }
Ejemplo n.º 32
0
        public virtual void modifySum(Node node)
        {
            Sum sumAdd = new Sum(this);

            this.addAllValuesGreater(node, sumAdd);
        }
Ejemplo n.º 33
0
 public void SumTimesTest()
 {
     IExpression fiveBucks = Money.Dollar(5);
     IExpression tenFrans = Money.Franc(10);
     Bank bank = new Bank();
     bank.AddRate("CHF", "USD", 2);
     IExpression sum = new Sum(fiveBucks, tenFrans).Times(2);
     Money result = bank.Reduce(sum, "USD");
     Assert.AreEqual(Money.Dollar(20), result);
 }
Ejemplo n.º 34
0
        static void Main()
        {
            Sum sum1 = (n) =>
            {
                double result = 0;
                for (int i = 1; i <= n; ++i)
                {
                    result += 1.0 / i;
                }
                return(result);
            };

            Sum doubleSum1 = (n) =>
            {
                double result = 0;
                for (int i = 1; i <= n; ++i)
                {
                    result += sum1(i);
                }
                return(result);
            };

            Sum sum2 = (n) =>
            {
                double result = 0;
                for (int i = 1; i <= n; ++i)
                {
                    result += 1.0 / Math.Pow(2, i);
                }
                return(result);
            };

            Sum doubleSum2 = (n) =>
            {
                double result = 0;
                for (int i = 1; i <= n; ++i)
                {
                    result += sum2(i);
                }
                return(result);
            };

            const int maxInput = 1000;

            do
            {
                Console.Clear();

                int n = InputChecker.InputVar <int>($"positive integer N (1 - {maxInput})", x => (x > 0) && (x <= maxInput));

                double sum1Check = 0;
                for (int i = 1; i <= n; ++i)
                {
                    for (int j = 1; j <= i; ++j)
                    {
                        sum1Check += 1.0 / j;
                    }
                }

                double sum2Check = 0;
                for (int i = 1; i <= n; ++i)
                {
                    for (int j = 1; j <= i; ++j)
                    {
                        sum2Check += 1.0 / Math.Pow(2, j);
                    }
                }

                Console.WriteLine($"Sum1 : {doubleSum1(n):F3}");
                Console.WriteLine($"Correct Sum1 : {sum1Check:F3}");
                Console.WriteLine($"Sum2 : {doubleSum2(n):F3}");
                Console.WriteLine($"Correct Sum2 : {sum2Check:F3}");

                Console.WriteLine("Press Esc to exit. Press any other key to continue.");
            } while (Console.ReadKey(true).Key != ConsoleKey.Escape);
        }
Ejemplo n.º 35
0
 public void DoSum(Sum sum, int a, int b)
 {
     Console.WriteLine(sum.Invoke(a, b));
 }
Ejemplo n.º 36
0
    private Sum <Action, PreviewInfo> MakeDrop(SpawnTarget spawnTarget, Transform target) //left is on failure, right is on success
    {
        var parenTracker = target.GetComponent <LayoutTracker>();

        List <int> index = parenTracker.index;

        var my_term = myCombinator == null
            ? Shrub <Sum <Combinator, Variable> > .Node(new List <Shrub <Sum <Combinator, Variable> > >())
            : Shrub <Sum <Combinator, Variable> > .Leaf(Sum <Combinator, Variable> .Inl(myCombinator));

        if (!target.GetComponentInParent <DraggableHolder>())
        {
            return(Sum <Action, PreviewInfo> .Inl(DestroyMe));
        }

        if (spawnTarget && !spawnTarget.NoBackApplication.val) //Back application
        {
            if (myCombinator == null)
            { //You are a parenthesis
                int my_index;
                for (my_index = 0; my_index < target.childCount; my_index++)
                {
                    if (transform.position.x < target.GetChild(my_index).position.x - target.GetChild(my_index).localScale.x / 4f)
                    {
                        break;
                    }
                }


                if (true /*my_index != target.childCount*/)
                {
                    return(Util.BackApplyParen(spawnTarget.goal, index.Skip(1).ToList(), my_index).Match(t =>
                    {
                        List <IHighlightable> selected = new List <IHighlightable>();
                        for (int i = 0; i < my_index; i++)
                        {
                            selected = selected.Concat(target.GetChild(i).GetComponentsInChildren <IHighlightable>()).ToList();
                        }
                        PreviewRedundantParenInfo prp = new PreviewRedundantParenInfo(index, my_index, () =>
                        {
                            spawnTarget.addParens(index.Skip(1).ToList(), my_index, GetComponent <LayoutTracker>(), t);

                            foreach (IHighlightable highlightable in selected)
                            {
                                highlightable.unselect();
                            }
                            PlaceMe();
                            myDraggableType = DraggableHolder.DraggableType.RedundantParens;
                        }, () =>
                        {
                            foreach (IHighlightable highlightable in selected)
                            {
                                highlightable.select();
                            }
                        }, () =>
                        {
                            foreach (IHighlightable highlightable in selected)
                            {
                                highlightable.unselect();
                            }
                        });
                        return Sum <Action, PreviewInfo> .Inr(PreviewInfo.In2(prp));
                    }, _ =>
                    {
                        return Sum <Action, PreviewInfo> .Inl(DestroyMe);
                    }));
                }
                else
                {
                    return(Sum <Action, PreviewInfo> .Inl(DestroyMe));
                }
            }
            else
            { //You not are a parenthesis
                HighlightParen hightligher = parenTracker.GetComponent <HighlightParen>();
                return(Util.BackApply(spawnTarget.goal, myCombinator, index.Skip(1).ToList()).Match(t =>

                                                                                                    Sum <Action, PreviewInfo> .Inr(PreviewInfo.In1(new PreviewBackCombinatorInfo(spawnTarget, parenTracker, index, () => {
                    pushUndoGoalTerm.Invoke(spawnTarget.goal);


                    spawnTarget.unApply(t, GetComponent <LayoutTracker>(), myCombinator, index.Skip(1).ToList());

                    PlaceMe();
                    hightligher.unselect();
                    myDraggableType = DraggableHolder.DraggableType.NoDragging;
                }, hightligher.select, hightligher.unselect)))

                                                                                                    , _ => Sum <Action, PreviewInfo> .Inl(DestroyMe)));
            }
        }
        else if (!spawnTarget && !NoForwardMode.val && target.GetComponentInParent <DraggableHolder>() && target.GetComponentInParent <DraggableHolder>().myType == DraggableHolder.DraggableType.Proposal) //forward application
        {
            if (evaluationMode.val)
            {
                return(Sum <Action, PreviewInfo> .Inl(DestroyMe));
            }

            int my_index;
            for (my_index = 0; my_index < target.childCount; my_index++)
            {
                if (transform.position.x < target.GetChild(my_index).position.x)
                {
                    break;
                }
            }
            var sm = target.GetComponentInParent <SymbolManager>();
            return(Sum <Action, PreviewInfo> .Inr(
                       PreviewInfo.In0(new PreviewForwardInfo(sm, index, target, my_index, () => {
                //if (pushUndoProposalTerm) {
                //	pushUndoProposalTerm.Invoke(sm.readTerm());
                //} else {
                //	Debug.LogError("pushUndoProposalTerm is null in DraggableSpell: " + this);
                //}
                sm.Insert(index.Skip(1).Append(my_index).ToList(), my_term);

                // paren = AccessTransfrom(topTracker, paren_index);

                transform.SetParent(target, true);
                transform.SetSiblingIndex(my_index);
                PlaceMe();
                myDraggableType = DraggableHolder.DraggableType.Proposal;
            }, UnPlace))
                       ));
        }
        return(Sum <Action, PreviewInfo> .Inl(DestroyMe));
    }
Ejemplo n.º 37
0
        public void BadOperationTest()
        {
            var math = new Sum();

            Assert.AreNotEqual(3, math.Operation(1, 1));
        }
Ejemplo n.º 38
0
        private static byte[] ProcessMergerClient(byte[] bytes)
        {
            try
            {
                // 1.获取合并包
                var client = Serializer.DeserializeFromBytes<MergePacket>(bytes);

                // 2.处理消息
                if (client.Type == MergePacket.MergeType.Sum)
                {
                    Sum sum = new Sum(client.TimeStamp, client.AppName);
                    double result = sum.Compute(Serializer.DeserializeFromBytes<double>(client.Data));
                    string flag = "sum_" + client.TimeStamp + "_" + client.AppName;
                    Logger.Info(flag + ",result is " + result);
                    sum.Remove(flag);
                    return Serializer.SerializeToBytes(result);
                }
                if (client.Type == MergePacket.MergeType.Average)
                {
                    Average average = new Average(client.TimeStamp, client.AppName);
                    double result = average.Compute(Serializer.DeserializeFromBytes<double>(client.Data));
                    string flag = "average_" + client.TimeStamp + "_" + client.AppName;
                    Logger.Info(flag + ",result is " + result);
                    average.Remove(flag);
                    return Serializer.SerializeToBytes(result);
                }

                if (client.Type == MergePacket.MergeType.Distinct)
                {
                    Distinct distinct = new Distinct(client.TimeStamp, client.AppName);
                    List<object> objects = distinct.Compute(Serializer.DeserializeFromBytes<List<object>>(client.Data));
                    string flag = "distinct_" + client.TimeStamp + "_" + client.AppName;
                    Logger.Info(flag + ", result count is " + objects.Count);
                    return Serializer.SerializeToBytes(objects);
                }

                if (client.Type == MergePacket.MergeType.CombineTable)
                {
                    CombineTable combineTable = new CombineTable(client.TimeStamp, client.AppName);
                    string flag = "combine_table_" + client.TimeStamp + "_" + client.AppName;
                    Logger.Info(flag + ", combine table.");
                    Hashtable objects = combineTable.Compute(Serializer.DeserializeFromBytes<Hashtable>(client.Data));
                    return Serializer.SerializeToBytes(objects);
                }

                if (client.Type == MergePacket.MergeType.CombineList)
                {
                    CombineList combineList = new CombineList(client.TimeStamp, client.AppName);
                    string flag = "combine_list_" + client.TimeStamp + "_" + client.AppName;
                    Logger.Info(flag + ", combine list.");
                    List<object> objects = combineList.Compute(Serializer.DeserializeFromBytes<List<object>>(client.Data));
                    return Serializer.SerializeToBytes(objects);
                }

                if (client.Type == MergePacket.MergeType.CombineSort)
                {
                    try
                    {
                        CombineSort combineSort = new CombineSort(client.TimeStamp, client.AppName);
                        string flag = "combine_sort_" + client.TimeStamp + "_" + client.AppName;
                        Logger.Info(flag + ", combine sort.");
                        object[] objects = combineSort.ArrayCompute(Serializer.DeserializeFromBytes(client.Data));
                        if (objects == null)
                        {
                            Logger.Warn("Result is null.");
                        }
                        else
                        {
                            Logger.Info("Result count is " + objects.Count());
                        }
                        return Serializer.SerializeToBytes(objects);
                    }
                    catch (Exception exception)
                    {
                        Logger.Error(exception);
                    }
                    object[] errorObjects = { -1 };
                    return Serializer.SerializeToBytes(errorObjects);

                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
            }
            return Serializer.SerializeToBytes(-1);
        }
Ejemplo n.º 39
0
 public void Visit(Sum sum)
 {
     sum.Left.Accept(this);
     _sb.Append("+");
     sum.Right.Accept(this);
 }
Ejemplo n.º 40
0
        public void OperationTest()
        {
            var math = new Sum();

            Assert.AreEqual(2, math.Operation(1, 1));
        }
Ejemplo n.º 41
0
 public void SumPlusMoney()
 {
     IExpression fiveBucks = Money.Dollar(5);
     IExpression tenFrancs = Money.Franc(10);
     Bank bank = new Bank();
     bank.AddRate("CHF", "USD", 2);
     IExpression sum = new Sum(fiveBucks, tenFrancs).Plus(fiveBucks);
     Money result = bank.Reduce(sum, "USD");
     Assert.Equal(Money.Dollar(15), result);
 }
 public int CompareTo(PowerConsumption other)
 {
     return(-Sum.CompareTo(other.Sum));
 }
Ejemplo n.º 43
0
 /// <summary>
 /// Initializes a new instance of the MoneyFlowIndex class
 /// </summary>
 /// <param name="name">The name of this indicator</param>
 /// <param name="period">The period of the negative and postive money flow</param>
 public MoneyFlowIndex(string name, int period)
     : base(name)
 {
     PositiveMoneyFlow = new Sum(name + "_PositiveMoneyFlow", period);
     NegativeMoneyFlow = new Sum(name + "_NegativeMoneyFlow", period);
 }
Ejemplo n.º 44
0
 public ParallelSummator()
 {
     res    = new Sum();
     Result = 0;
 }
Ejemplo n.º 45
0
 private Tail(Sum _enclosing, long n, long e)
 {
     this._enclosing = _enclosing;
     this.n          = n;
     this.e          = e;
 }
Ejemplo n.º 46
0
        private void SetPayload(FrameworkElement element, bool isFlippedHorizontally)
        {
            object simulinkNodeElement;
            Guid?  guid = GlobalVariableManager.LastSelectedElementIdentifer;

            switch (element.Name)
            {
            case "Constant":
            {
                Constant constant = (element as Constant);
                simulinkNodeElement = new InputElement(SimulinkInputType.Constant, guid);
                ((ISimulinkNodeElement <SimulinkInputType>)simulinkNodeElement).Properties.Add(nameof(constant.Value), constant.Value);
                ((ISimulinkNodeElement <SimulinkInputType>)simulinkNodeElement).Properties.Add("FlipHorizontally", isFlippedHorizontally);
            }
            break;

            case "Step":
            {
                Step step = (element as Step);
                simulinkNodeElement = new InputElement(SimulinkInputType.Step, guid);
                ((ISimulinkNodeElement <SimulinkInputType>)simulinkNodeElement).Properties.Add(nameof(step.StepTime), step.StepTime);
                ((ISimulinkNodeElement <SimulinkInputType>)simulinkNodeElement).Properties.Add(nameof(step.InitialValue), step.InitialValue);
                ((ISimulinkNodeElement <SimulinkInputType>)simulinkNodeElement).Properties.Add(nameof(step.FinalValue), step.FinalValue);
                ((ISimulinkNodeElement <SimulinkInputType>)simulinkNodeElement).Properties.Add(nameof(step.SampleTime), step.SampleTime);
                ((ISimulinkNodeElement <SimulinkInputType>)simulinkNodeElement).Properties.Add("FlipHorizontally", isFlippedHorizontally);
            }
            break;

            case "Ramp":
            {
                Ramp ramp = (element as Ramp);
                simulinkNodeElement = new InputElement(SimulinkInputType.Ramp, guid);
                ((ISimulinkNodeElement <SimulinkInputType>)simulinkNodeElement).Properties.Add(nameof(ramp.Slope), ramp.Slope);
                ((ISimulinkNodeElement <SimulinkInputType>)simulinkNodeElement).Properties.Add(nameof(ramp.StartTime), ramp.StartTime);
                ((ISimulinkNodeElement <SimulinkInputType>)simulinkNodeElement).Properties.Add(nameof(ramp.InitialOutput), ramp.InitialOutput);
                ((ISimulinkNodeElement <SimulinkInputType>)simulinkNodeElement).Properties.Add("FlipHorizontally", isFlippedHorizontally);
            }
            break;

            case "Scope":
                simulinkNodeElement = new OutputElement(SimulinkOutputType.Scope, guid);
                break;

            case "Display":
                simulinkNodeElement = new OutputElement(SimulinkOutputType.Display, guid);
                break;

            case "TransferFunction":
            {
                TransferFunction transferFunction = (element as TransferFunction);
                simulinkNodeElement = new InputOutputElement(SimulinkInputOutputType.TransferFunction, guid);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add(nameof(transferFunction.NumeratorCoefficients), transferFunction.NumeratorCoefficients);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add(nameof(transferFunction.DenominatorCoefficients), transferFunction.DenominatorCoefficients);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add("FlipHorizontally", isFlippedHorizontally);
            }
            break;

            case "PidController":
            {
                PidController pidController = (element as PidController);
                simulinkNodeElement = new InputOutputElement(SimulinkInputOutputType.PidController, guid);
                // Selected Controller
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add(nameof(pidController.SelectedPidController), pidController.SelectedPidController);
                // Controller Parameters
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add(nameof(pidController.Proportional), pidController.Proportional);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add(nameof(pidController.Integral), pidController.Integral);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add(nameof(pidController.Derivative), pidController.Derivative);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add(nameof(pidController.FilterCoefficient), pidController.FilterCoefficient);
                // Controller Initial Conditions
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add(nameof(pidController.Integrator), pidController.Integrator);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add(nameof(pidController.Filter), pidController.Filter);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add("FlipHorizontally", isFlippedHorizontally);
            }
            break;

            case "Integrator":
            {
                Integrator integrator = (element as Integrator);
                simulinkNodeElement = new InputOutputElement(SimulinkInputOutputType.Integrator, guid);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add(nameof(integrator.InitialCondition), integrator.InitialCondition);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add("FlipHorizontally", isFlippedHorizontally);
            }
            break;

            case "Sum":
            {
                Sum sum = (element as Sum);
                simulinkNodeElement = new InputOutputElement(SimulinkInputOutputType.Sum, guid);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).NumberOfInputs = sum.Signs.CountNonEmpty();
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add(nameof(sum.Signs), sum.Signs);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add("FlipHorizontally", isFlippedHorizontally);
            }
            break;

            case "Gain":
            {
                Gain gain = (element as Gain);
                simulinkNodeElement = new InputOutputElement(SimulinkInputOutputType.Gain, guid);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add(nameof(gain.Value), gain.Value);
                ((ISimulinkNodeElement <SimulinkInputOutputType>)simulinkNodeElement).Properties.Add("FlipHorizontally", isFlippedHorizontally);
            }
            break;

            default:
                throw new InvalidOperationException();
            }

            SimulinkNodeElement = simulinkNodeElement;
        }
Ejemplo n.º 47
0
        public void TwoNumbersTest()
        {
            var sum = new Sum(new[] { new Number(1), new Number(2) }, 2);

            Assert.Equal(3.0, sum.Execute());
        }
Ejemplo n.º 48
0
        static void Main(string[] args)
        {
            Sum ob = new Sum();

            Console.WriteLine(ob.sumByRecursion(343));
        }
Ejemplo n.º 49
0
        public static MathObject IsolateVariableEq(this Equation eq, Symbol sym)
        {
            if (eq.Operator == Equation.Operators.NotEqual) return eq;

            if (eq.FreeOf(sym)) return eq;

            // sin(x) / cos(x) == y   ->   tan(x) == y

            if (eq.a is Product && (eq.a as Product).elts.Any(elt => elt == new Sin(sym)) &&
                eq.a is Product && (eq.a as Product).elts.Any(elt => elt == 1 / new Cos(sym)))
                return
                    (eq.a / new Sin(sym) * new Cos(sym) * new Tan(sym) == eq.b).IsolateVariableEq(sym);

            // A sin(x)^2 == B sin(x) cos(x)   ->   A sin(x)^2 / (B sin(x) cos(x)) == 1

            if (
                eq.a is Product &&
                (eq.a as Product).elts.Any(elt =>
                    (elt == new Sin(sym)) ||
                    ((elt is Power) && (elt as Power).bas == new Sin(sym) && (elt as Power).exp is Number)) &&

                eq.b is Product &&
                (eq.b as Product).elts.Any(elt =>
                    (elt == new Sin(sym)) ||
                    ((elt is Power) && (elt as Power).bas == new Sin(sym) && (elt as Power).exp is Number))
                )
                return
                    (eq.a / eq.b == 1).IsolateVariableEq(sym);

            if (eq.b.Has(sym)) return IsolateVariableEq(new Equation(eq.a - eq.b, 0), sym);

            if (eq.a == sym) return eq;

            // (a x^2 + c) / x == - b

            if (eq.a is Product &&
                (eq.a as Product).elts.Any(
                    elt =>
                        elt is Power &&
                        (elt as Power).bas == sym &&
                        (elt as Power).exp == -1))
                return IsolateVariableEq(eq.a * sym == eq.b * sym, sym);

            //if (eq.a is Product &&
            //    (eq.a as Product).elts.Any(
            //        elt =>
            //            elt is Power &&
            //            (elt as Power).bas == sym &&
            //            (elt as Power).exp is Integer &&
            //            ((elt as Power).exp as Integer).val < 0))
            //    return IsolateVariableEq(eq.a * sym == eq.b * sym, sym);

            // if (eq.a.Denominator() is Product &&
            //     (eq.a.Denominator() as Product).Any(elt => elt.Base() == sym)
            //
            //

            // (x + y)^(1/2) == z
            //
            // x == -y + z^2   &&   z >= 0

            if (eq.a is Power && (eq.a as Power).exp == new Integer(1) / 2)
                return IsolateVariableEq((eq.a ^ 2) == (eq.b ^ 2), sym);

            // 1 / sqrt(x) == y

            if (eq.a is Power && (eq.a as Power).exp == -new Integer(1) / 2)
                return (eq.a / eq.a == eq.b / eq.a).IsolateVariable(sym);

            // x ^ 2 == y
            // x ^ 2 - y == 0

            if (eq.a.AlgebraicExpand().DegreeGpe(new List<MathObject>() { sym }) == 2 &&
                eq.b != 0)
            {
                return
                    (eq.a - eq.b == 0).IsolateVariable(sym);
            }

            // a x^2 + b x + c == 0

            if (eq.a.AlgebraicExpand().DegreeGpe(new List<MathObject>() { sym }) == 2)
            {
                var a = eq.a.AlgebraicExpand().CoefficientGpe(sym, 2);
                var b = eq.a.AlgebraicExpand().CoefficientGpe(sym, 1);
                var c = eq.a.AlgebraicExpand().CoefficientGpe(sym, 0);

                if (a == null || b == null || c == null) return eq;

                return new Or(

                    new And(
                        sym == (-b + (((b ^ 2) - 4 * a * c) ^ (new Integer(1) / 2))) / (2 * a),
                        (a != 0).Simplify()
                        ).Simplify(),

                    new And(
                        sym == (-b - (((b ^ 2) - 4 * a * c) ^ (new Integer(1) / 2))) / (2 * a),
                        (a != 0).Simplify()
                        ).Simplify(),

                    new And(sym == -c / b, a == 0, (b != 0).Simplify()).Simplify(),

                    new And(
                        (a == 0).Simplify(),
                        (b == 0).Simplify(),
                        (c == 0).Simplify()
                        ).Simplify()

                ).Simplify();
            }

            // (x + y == z).IsolateVariable(x)

            if (eq.a is Sum && (eq.a as Sum).elts.Any(elt => elt.FreeOf(sym)))
            {
                var items = ((Sum)eq.a).elts.FindAll(elt => elt.FreeOf(sym));

                //return IsolateVariable(
                //    new Equation(
                //        eq.a - new Sum() { elts = items }.Simplify(),
                //        eq.b - new Sum() { elts = items }.Simplify()),
                //    sym);

                //var new_a = eq.a; items.ForEach(elt => new_a = new_a - elt);
                //var new_b = eq.b; items.ForEach(elt => new_b = new_b - elt);

                var new_a = new Sum() { elts = (eq.a as Sum).elts.Where(elt => items.Contains(elt) == false).ToList() }.Simplify();
                var new_b = eq.b; items.ForEach(elt => new_b = new_b - elt);

                // (new_a as Sum).Where(elt => items.Contains(elt) == false)

                return IsolateVariableEq(new Equation(new_a, new_b), sym);

                //return IsolateVariable(
                //    new Equation(
                //        eq.a + new Sum() { elts = items.ConvertAll(elt => elt * -1) }.Simplify(),
                //        eq.b - new Sum() { elts = items }.Simplify()),
                //    sym);
            }

            // a b + a c == d

            // a + a c == d

            if (eq.a is Sum && (eq.a as Sum).elts.All(elt => elt.DegreeGpe(new List<MathObject>() { sym }) == 1))
            {
                //return
                //    (new Sum() { elts = (eq.a as Sum).elts.Select(elt => elt / sym).ToList() }.Simplify() == eq.b / sym)
                //    .IsolateVariable(sym);

                return
                    (sym * new Sum() { elts = (eq.a as Sum).elts.Select(elt => elt / sym).ToList() }.Simplify() == eq.b)
                    .IsolateVariable(sym);
            }

            // -sqrt(x) + z * x == y

            if (eq.a is Sum && eq.a.Has(sym ^ (new Integer(1) / 2))) return eq;

            // sqrt(a + x) - z * x == -y

            if (eq.a is Sum && eq.a.Has(elt => elt is Power && (elt as Power).exp == new Integer(1) / 2 && (elt as Power).bas.Has(sym)))
                return eq;

            if (eq.a is Sum && eq.AlgebraicExpand().Equals(eq)) return eq;

            if (eq.a is Sum) return eq.AlgebraicExpand().IsolateVariable(sym);

            // (x + 1) / (x + 2) == 3

            if (eq.a.Numerator().Has(sym) && eq.a.Denominator().Has(sym))
            {
                return IsolateVariableEq(eq.a * eq.a.Denominator() == eq.b * eq.a.Denominator(), sym);
            }

            // sqrt(2 + x) * sqrt(3 + x) == y

            if (eq.a is Product && (eq.a as Product).elts.All(elt => elt.Has(sym))) return eq;

            if (eq.a is Product)
            {
                var items = ((Product)eq.a).elts.FindAll(elt => elt.FreeOf(sym));

                return IsolateVariableEq(
                    new Equation(
                        eq.a / new Product() { elts = items }.Simplify(),
                        eq.b / new Product() { elts = items }.Simplify()),
                    sym);
            }

            // x ^ -2 == y

            if (eq.a is Power &&
                (eq.a as Power).bas == sym &&
                (eq.a as Power).exp is Integer &&
                ((eq.a as Power).exp as Integer).val < 0)
                return (eq.a / eq.a == eq.b / eq.a).IsolateVariableEq(sym);

            if (eq.a is Power) return eq;

            // sin(x) == y

            // Or(x == asin(y), x  == Pi - asin(y))

            if (eq.a is Sin)
                return
                    new Or(
                        (eq.a as Sin).args[0] == new Asin(eq.b),
                        (eq.a as Sin).args[0] == new Symbol("Pi") - new Asin(eq.b))
                        .IsolateVariable(sym);

            // tan(x) == y

            // x == atan(t)

            if (eq.a is Tan)
                return
                    ((eq.a as Tan).args[0] == new Atan(eq.b))
                    .IsolateVariable(sym);

            // asin(x) == y
            //
            // x == sin(y)

            if (eq.a is Asin)
                return
                    ((eq.a as Asin).args[0] == new Sin(eq.b))
                    .IsolateVariable(sym);

            throw new Exception();
        }
Ejemplo n.º 50
0
        public void OneNumberTest()
        {
            var sum = new Sum(new[] { new Number(2) }, 1);

            Assert.Equal(2.0, sum.Execute());
        }
Ejemplo n.º 51
0
        public void VectorTest()
        {
            var sum = new Sum(new[] { new Vector(new[] { new Number(1), new Number(2) }) }, 1);

            Assert.Equal(3.0, sum.Execute());
        }
Ejemplo n.º 52
0
 // Start is called before the first frame update
 void Awake()
 {
     e.AddRemovableListener(x => args = Sum <T, Unit> .Inl(x), this);
 }