Пример #1
0
        public override void ContextualRunInit(CalculationContext context)
        {
            MajorUsage = new double[context.Combinations.Count][];
            MinorUsage = new double[context.Combinations.Count][];

            switch (SectionClassification)
            {
            // Eq 6.13
            case 1:
            case 2:
                MajorMomentResistance =
                    CrossSection.MajorPlasticSectionModulus * Material.YieldStrength / FactorSafety;
                MinorMomentResistance =
                    CrossSection.MinorPlasticSectionModulus * Material.YieldStrength / FactorSafety;
                break;

            // Eq 6.14
            case 3:
                MajorMomentResistance =
                    CrossSection.MajorElasticSectionModulus * Material.YieldStrength / FactorSafety;
                MinorMomentResistance =
                    CrossSection.MinorElasticSectionModulus * Material.YieldStrength / FactorSafety;
                break;

            case 4:
                throw new NotImplementedException();
            }
        }
 public CalculationResult CalculateComplexResult(CalculationContext context)
 {
     return(new CalculationResult
     {
         Result = context.A + context.B + 1
     });
 }
Пример #3
0
        TreeNode LinkUndefinedVariable(UndefinedVariableTreeNode vTree, CalculationContext context, string[] parameterNames)
        {
            for (int i = 0; i < parameterNames.Length; ++i)
            {
                if (vTree.Name == parameterNames[i])
                {
                    return(new FunctionParameterTreeNode(i));
                }
            }

            if (context.VariableTable.IsIdentifierDefined(vTree.Name))
            {
                // can't optimize to ternary expression, idk why
                if (InsertVariableValuesDirectly)
                {
                    return(new NumberTreeNode(context.VariableTable[vTree.Name], vTree.Parent));
                }
                else
                {
                    return(new VariableIndexTreeNode(context.VariableTable.GetIndex(vTree.Name), vTree.Parent));
                }
            }

            throw new Exception(String.Format("Variable \"{0}\" is not defined", vTree.Name));
        }
Пример #4
0
        public static CalculationContext GenerateStandardContext()
        {
            CalculationContext context = new CalculationContext();

            context.VariableTable.AssignNewItem("pi", Math.PI);
            context.VariableTable.AssignNewItem("e", Math.E);
            context.VariableTable.AssignNewItem("phi", (Math.Sqrt(5) + 1.0) / 2);

            AssignFunction(context, UnaryOperation.Sign);
            AssignFunction(context, UnaryOperation.AbsoluteValue);

            AssignFunction(context, UnaryOperation.Sine);
            AssignFunction(context, UnaryOperation.Cosine);
            AssignFunction(context, UnaryOperation.Tangent);
            AssignFunction(context, UnaryOperation.Cotangent);
            AssignFunction(context, UnaryOperation.Secant);
            AssignFunction(context, UnaryOperation.Cosecant);

            AssignFunction(context, UnaryOperation.Exponent);
            AssignFunction(context, UnaryOperation.NaturalLogarithm);
            AssignFunction(context, BinaryOperation.Logarithm);

            AssignFunction(context, UnaryOperation.SquareRoot);
            AssignFunction(context, UnaryOperation.CubeRoot);
            AssignFunction(context, BinaryOperation.NthRoot);

            return(context);
        }
 public void Execute(CalculationContext context)
 {
     foreach (var webshop in context.Project.Webshops)
     {
         context.RequiredServersCapacity += (BusinessConstants.RequiredServerCapacityPerUser * webshop.UserCount);
     }
 }
Пример #6
0
        public Grid Solve(Grid source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            CalculationContextFactory calculationContextFactory = new CalculationContextFactory();
            Calculator             calculator         = new Calculator();
            Predictor              predictor          = new Predictor();
            Stack <PredictContext> predictionStack    = new Stack <PredictContext>();
            CalculationContext     calculationContext = calculationContextFactory.Create(source);
            CalculationResultData  calculationResult  = calculator.Process(calculationContext);

            while (calculationResult.Result != CalculationResult.Finish)
            {
                switch (calculationResult.Result)
                {
                case CalculationResult.NeedPrediction:
                    calculationContext = calculationContextFactory.Create(predictor.CreatePrediction(predictionStack, calculationContext));
                    break;

                case CalculationResult.Stop:
                    calculationContext = calculationContextFactory.Create(predictor.ApplyNextPrediction(predictionStack));
                    break;

                default:
                    throw new InvalidOperationException();
                }
                calculationResult = calculator.Process(calculationContext);
            }
            return(calculationResult.Context.Grid);
        }
Пример #7
0
 private static void ApplyMigrations(CalculationContext context)
 {
     if (context.Database.GetPendingMigrations().Any())
     {
         context.Database.Migrate();
     }
 }
        public async Task Calc(CalculationContext context)
        {
            var input = await _inputService.GetInput();

            while (input != null)
            {
                try
                {
                    context.Execute(input);
                }
                catch (ParameterCountNotMatchExceptions e)
                {
                    await _outputService.Output(e.Message);
                }
                catch (InvalidOperationException invalidOperation)
                {
                    await _outputService.Output(invalidOperation.Message);
                }
                catch (Exception unExpectedException)
                {
                    if (IsDebugEnable)
                    {
                        await _outputService.Output(unExpectedException.ToString());
                    }
                    else
                    {
                        await _outputService.Output("system err");
                    }
                }

                await _outputService.Output(ViewModelBuilder.PresentStack(context.CalculationData));

                input = await _inputService.GetInput();
            }
        }
Пример #9
0
 public void Execute(CalculationContext context)
 {
     foreach (var webshop in context.Project.Webshops)
     {
         ExecutePerWebshop(webshop, context);
     }
 }
 public void Execute(CalculationContext context)
 {
     if (context.RequiredServersCapacity > context.ServersCapacity)
     {
         context.Feedback.Add(string.Format("You do not have enough active servers. Only {0}% users will be handled.", Math.Ceiling((context.ServersCapacity / context.RequiredServersCapacity) * 100)));
     }
 }
Пример #11
0
        public async Task Endpoint(HttpContext context,
                                   CalculationContext dataContext)
        {
            int  count = int.Parse((string)context.Request.RouteValues["count"]);
            long total = dataContext.Calculations
                         .FirstOrDefault(c => c.Count == count)?.Result ?? 0;

            if (total == 0)
            {
                for (int i = 1; i <= count; i++)
                {
                    total += i;
                }
                dataContext.Calculations !
                .Add(new Calculaton()
                {
                    Count = count, Result = total
                });
                await dataContext.SaveChangesAsync();
            }
            string totalString = $"({ DateTime.Now.ToLongTimeString() }) {total}";
            await context.Response.WriteAsync(
                $"({DateTime.Now.ToLongTimeString()}) Total for {count}"
                + $" values:\n{totalString}\n");
        }
Пример #12
0
 /// <inheritdoc/>
 public override void ContextualRunInit(CalculationContext context)
 {
     base.ContextualRunInit(context);
     Moment.CrossSection = CrossSection;
     Moment.Material     = Material;
     Axial.CrossSection  = CrossSection;
     Axial.Material      = Material;
 }
Пример #13
0
        public void ExecutePerWebshop(Webshop webshop, CalculationContext context)
        {
            var increaseRate = context.FeaturesWithImpact
                               .Where(f => f.WebshopId == webshop.Id)
                               .Sum(f => (f.Definition.AverageOrderAmountIncreaseRate ?? 0) / 100m);

            webshop.LatestChangeSet.AverageOrderAmountIncreaseRate = increaseRate;
        }
Пример #14
0
 public override void ContextualRunInit(CalculationContext context)
 {
     CombinedUsage = new double[context.Combinations.Count][];
     if (SectionClassification > 3)
     {
         throw new NotImplementedException();
     }
 }
Пример #15
0
        public void Execute(CalculationContext context)
        {
            var featuresWithImpact = context.Project.Webshops.SelectMany(w => w.Features)
                                     .Where(f => (f.Definition.IsFunctionality && f.Implemented && f.LastUpdatedIteration == context.IterationNumber - 1) ||
                                            (f.Definition.IsAction && f.AddedOnIteration + f.Definition.Duration >= context.IterationNumber))
                                     .ToList();

            context.FeaturesWithImpact = featuresWithImpact;
        }
Пример #16
0
        static void CalculateInput(string expressionInput, CalculationContext context)
        {
            Token[]          tokens   = lexer.Tokenize(expressionInput);
            TreeNode         tree     = parser.Construct(tokens);
            FinishedFunction function = linker.BuildFunction(tree, context, new string[0]);
            double           value    = treeCalculator.Calculate(function);

            Console.WriteLine(String.Format(" = {0}", value.ToString("G", System.Globalization.CultureInfo.InvariantCulture)));
        }
Пример #17
0
        public void ExistingGroundRequired()
        {
            NHBC2020FoundationDepth calc = new NHBC2020FoundationDepth();

            CalculationContext context = new CalculationContext();

            Assert.Throws(typeof(ArgumentNullException), () => calc.Run(new OutputBuilder()));
            Assert.IsFalse(calc.Calculated, "Calculation should not have completed");
        }
Пример #18
0
        public IValue Eval(CalculationContext context, IValue[] operands)
        {
            if (this.lastContext == null || !this.lastContext.Equals(context))
            {
                this.lastValue = new LazyValue(this.expression, context);
            }

            return(this.lastValue);
        }
        public void ExecutePerWebshop(Webshop webshop, CalculationContext context)
        {
            var activeUsersCount = webshop.UserCount;
            if (context.RequiredServersCapacity > context.ServersCapacity)
                activeUsersCount *= (context.ServersCapacity / context.RequiredServersCapacity);

            var income = Math.Ceiling(webshop.AverageOrderAmount * activeUsersCount);
            webshop.LatestChangeSet.Income = income;
        }
Пример #20
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Start your calculation journey!");

            var calculationContext      = new CalculationContext();
            ICalculationService service = new CalculationService(new InputFormatService(new InputService()), new OutputService());
            await service.Calc(calculationContext);

            Console.Read();
        }
Пример #21
0
 public HomeController(
     IMqttClientService mqttClient,
     CalculationContext dbContext,
     SortSourceByQueryParameterHelper <Message> sortJobsByQueryParameter
     )
 {
     _mqttClient = mqttClient;
     _dbContext  = dbContext;
     _sortJobsByQueryParameter = sortJobsByQueryParameter;
 }
Пример #22
0
        public void ExecutePerWebshop(Webshop webshop, CalculationContext context)
        {
            webshop.LatestChangeSet.NewUsersCount = context.FeaturesWithImpact.Where(f => f.WebshopId == webshop.Id)
                                                    .Sum(f => (f.Definition.NewOnlineUsersAmount ?? 0) / 100 * webshop.UserCount);

            var conversionRate = context.FeaturesWithImpact.Where(f => f.WebshopId == webshop.Id)
                                 .Sum(f => (f.Definition.OfflineUsersConversionRate ?? 0) / 100m);

            webshop.LatestChangeSet.ConvertedUsersCount = Math.Min(Math.Ceiling(conversionRate * webshop.OfflineUsersCount), webshop.OfflineUsersCount - webshop.ConvertedUsersCount);
        }
        public override void ContextualRunInit(CalculationContext context)
        {
            base.ContextualRunInit(context);
            foreach (BoltRow boltRow in BoltRows)
            {
                boltRow.Run(context.Output);
            }

            //Set up supporting member
            _supportingColumn.Run(context);
        }
Пример #24
0
        public void Execute(CalculationContext context)
        {
            var developersCost = context.Project.Developers.Sum(d => d.Definition.Cost);

            if (context.Project.Cash < developersCost)
            {
                throw new CalculationException(Name, "You do not have enough cash to pay for developers.");
            }

            context.Project.LatestChangeSet.Cost += developersCost;
        }
Пример #25
0
        public void Test_Invalid_Input()
        {
            var context = new CalculationContext();
            var list    = new List <InputDto>();

            list.Add(new InputDto("5", 0));
            list.Add(new InputDto("2", 3));
            list.Add(new InputDto("-", 5));
            list.Add(new InputDto("invalid", 7));

            Assert.Throws <InvalidOperationException>(() => context.Execute(list));
        }
        public CalculationViewModel(Calculation calc)
        {
            Calcuation = calc;
            Context    = new CalculationContext();
            Context.Combinations.Add(new Combination()
            {
                Name = "1"
            });

            GetInputs();
            GetOutputs();
        }
 public MqttClientService(
     IManagedMqttClientOptions options,
     CalculationContext dbContext,
     HttpTransportService httpClient
     )
 {
     _options    = options;
     _dbContext  = dbContext;
     _httpClient = httpClient;
     _mqttClient = new MqttFactory().CreateManagedMqttClient();
     ConfigureMqttClient();
 }
Пример #28
0
        static void OptimizeInput(string input, CalculationContext context)
        {
            string           funcName    = input.Substring(10).Trim(' ');
            FinishedFunction unoptimized = context.FunctionTable[funcName];
            FinishedFunction optimized   = optimizer.OptimizeWithTable(unoptimized);

            Console.WriteLine("Unoptimized: ");
            Console.WriteLine(unoptimized.TopNode);
            visualizer.VisualizeAsTree(unoptimized.TopNode, context);
            Console.WriteLine("Optimized: ");
            Console.WriteLine(optimized.TopNode);
            visualizer.VisualizeAsTree(optimized.TopNode, context);
        }
Пример #29
0
        static void TestInput(string input, CalculationContext context)
        {
            string           funcName        = input.Substring(6).Trim(' ');
            FinishedFunction function        = context.FunctionTable[funcName];
            PostfixFunction  postfixFunction = translator.Convert(function);

            Console.WriteLine("Testing functionality: ");
            TestCalculator(postfixCalculator, postfixFunction, context.VariableTable, function.ParameterCount, 10, 1, true);
            TestCalculator(treeCalculator, function, context.VariableTable, function.ParameterCount, 10, 1, true);
            Console.WriteLine("Testing speed: ");
            TestCalculator(postfixCalculator, postfixFunction, context.VariableTable, function.ParameterCount, 100000, 100, false);
            TestCalculator(treeCalculator, function, context.VariableTable, function.ParameterCount, 100000, 100, false);
        }
        public void Execute(CalculationContext context)
        {
            context.ActiveServers = new List <Server>(context.Project.Servers.Select(ps => ps.Definition));
            while (context.ActiveServers.Any() && context.ActiveServers.Sum(s => s.Cost) > context.Project.Cash)
            {
                context.ActiveServers.RemoveAt(0);
            }

            if (context.ActiveServers.Count != context.Project.Servers.Count())
            {
                context.Feedback.Add("You don't have enough money to pay for all your servers.");
            }
        }