public async Task <List <Item> > Get(int userid)
        {
            using (TimeTrackingDBContext context = new TimeTrackingDBContext())
            {
                var result = new CalculationResult();

                // Get Calculation Config for Current User
                var config = await context.Calculation.Where(a => a.userId == userid).SingleOrDefaultAsync();

                var items = await context.Items.Where(i => i.userId == userid).ToListAsync();

                var fahrtkosten = await context.Items.Where(i => i.userId == userid).ToListAsync();


                result.inVoicedDays = items.Sum(a => a.hours) / 8;

                result.averageHourlyRate = 65;

                result.income = items.Sum(a => a.hours) * 65;

                result.investmentExpenses = result.income * config.investmentTax;

                result.adjustedIncome = result.income - result.investmentExpenses;

                result.employerExpenses = result.income * config.employerDuties;

                return(null);
            }
        }
Example #2
0
        private void AddTable(CalculationResult calculationResult)
        {
            PageBreak();
            var value = $@"Расчетный состав для {MainWindowViewModel.Instance.Calculation.CountConcrete} м³";

            AddTitle(value);

            var table = _document.AddTable(5, 2);

            table.Design    = TableDesign.TableGrid;
            table.Alignment = Alignment.center;
            table.SetColumnWidth(0, 5024);
            table.SetColumnWidth(1, 5024);

            table.Rows[0].Cells[0].Paragraphs[0].Append("Цемент").Font(_fontFamily.Source).FontSize(_fontSizeText);
            table.Rows[0].Cells[1].Paragraphs[0].Append($@"{calculationResult.CorrectedCementConsumption * MainWindowViewModel.Instance.Calculation.CountConcrete: .##} кг.").Font(_fontFamily.Source).FontSize(_fontSizeText);

            table.Rows[1].Cells[0].Paragraphs[0].Append("Вода").Font(_fontFamily.Source).FontSize(_fontSizeText);
            table.Rows[1].Cells[1].Paragraphs[0].Append($@"{calculationResult.WaterFlowWithRegardToAirContent * MainWindowViewModel.Instance.Calculation.CountConcrete: .##} л.").Font(_fontFamily.Source).FontSize(_fontSizeText);

            table.Rows[2].Cells[0].Paragraphs[0].Append("Песок").Font(_fontFamily.Source).FontSize(_fontSizeText);
            table.Rows[2].Cells[1].Paragraphs[0].Append($@"{calculationResult.TheAmountOfSandDry * MainWindowViewModel.Instance.Calculation.CountConcrete: .##} кг.").Font(_fontFamily.Source).FontSize(_fontSizeText);

            table.Rows[3].Cells[0].Paragraphs[0].Append("Крупный заполнитель").Font(_fontFamily.Source).FontSize(_fontSizeText);
            table.Rows[3].Cells[1].Paragraphs[0].Append($@"{calculationResult.NumberOfCoarseAggregate * MainWindowViewModel.Instance.Calculation.CountConcrete: .##}  кг.").Font(_fontFamily.Source).FontSize(_fontSizeText);

            table.Rows[4].Cells[0].Paragraphs[0].Append($@"Химическая добавка { MainWindowViewModel.Instance.Calculation.Admixtures.Name}").Font(_fontFamily.Source).FontSize(_fontSizeText);
            table.Rows[4].Cells[1].Paragraphs[0].Append($@"{calculationResult.ChemicalAdditive * MainWindowViewModel.Instance.Calculation.CountConcrete: .##}  кг.").Font(_fontFamily.Source).FontSize(_fontSizeText);
            _document.InsertTable(table);
        }
        public async Task <CalculationsCreateResponse> Handle(CalculationsCreateCommand request, CancellationToken cancellationToken)
        {
            var postalCodeEntity = await _dbContext.PostalCodes.FirstOrDefaultAsync(
                x => x.Code == request.PostalCode
                , cancellationToken);

            var calculationType =
                await _dbContext.CalculationRuleTypes.FirstOrDefaultAsync(
                    x => x.PostalCodeId == postalCodeEntity.Id,
                    cancellationToken : cancellationToken);

            var payableTax = calculationType.TaxCalculationTypeId switch
            {
                1 => CalculationBuilder.CalculateProgressive(request.AnnualIncome),
                2 => CalculationBuilder.CalculateFlatValue(request.AnnualIncome),
                3 => CalculationBuilder.CalculateFlatRate(request.AnnualIncome),
                _ => throw new NotImplementedException(),
            };

            var entity = new CalculationResult
            {
                AnnualIncome       = request.AnnualIncome,
                PostalCodeId       = postalCodeEntity.Id,
                TaxCalculationType = calculationType.Id,
                DateCreated        = DateTime.Now,
                TotalTax           = payableTax,
                NetPay             = request.AnnualIncome - payableTax
            };

            await _dbContext.CalculationResults.AddAsync(entity, cancellationToken);

            await _dbContext.SaveChangesAsync(cancellationToken);

            return(entity.ToCreateResponse());
        }
        public static void AssertAttribValue(this CalculationResult result, Campaigns.Model.Attribute attrib, int value)
        {
            var values = result.AttributeValues.Where(val => val.Attribute == attrib);

            Assert.IsTrue(values.Count() == 1);
            Assert.AreEqual(value, values.First().Value);
        }
Example #5
0
        public CalculationResult Process(File file)
        {
            //file parser manager is responsible to parse file and return workable data
            var calculationItemsResult = FileParserExecutionManager.Process(file);

            var applyNumber = calculationItemsResult.InitialNumber;

            //validated ready to use instructions
            foreach (var calculationItem in calculationItemsResult.Instructions)
            {
                // although there are simple math operations, it is good practice to separate operations
                // rather then doing it with in if else statements
                // this will help a lot if we need to extend operations or/and change something
                var operationManager = OperationFactory.Create(calculationItem.InstructionType);

                applyNumber = operationManager.Calculate(applyNumber, calculationItem.Number);
            }

            var result = new CalculationResult
            {
                Result = applyNumber
            };

            return(result);
        }
Example #6
0
        /// <summary>
        /// Calculate the basket value from the given input
        /// </summary>
        /// <param name="items">The items in string array form</param>
        /// <returns>The result of the calculation</returns>
        public CalculationResult Calculate(string[] items)
        {
            var basket = new Basket(items);
            var result = new CalculationResult();

            foreach (var kvp in basket)
            {
                result.Add(GetTotal(kvp.Key, kvp.Value));
            }

            // copy basket because we're taking stuff out
            // This is not strictly necessary but still a good idea for future
            // extensions, i.e. in case we need to list the initial basket
            var offerBasket = new Basket(basket);

            foreach (var offer in _config.Offers)
            {
                // How many times do the required items fit?
                int fitsTimes = offerBasket.FitsTimes(offer.Condition);
                if (fitsTimes > 0)
                {
                    // take items out and apply the offer
                    offerBasket.SubtractTimes(offer.Condition, fitsTimes);
                    result.AddOffer(offer, offer.PriceDelta * fitsTimes);
                }
            }

            return(result);
        }
Example #7
0
        /// <summary>
        /// Bedrijfsvoorheffing
        /// </summary>
        /// <param name="context"></param>
        /// <param name="componentContext"></param>
        /// <returns></returns>
        public async Task <List <CalculationResult> > Calculate(MuntContext context, ComponentContext componentContext)
        {
            var calculations = new List <CalculationResult>();

            var taxableWage = componentContext.AmountForCalculationArea;
            var payrollTax  = 0.0d;

            //Calculate annual bruto income
            var annualBrutoWage =
                CalculateLeastCommonDenominator(context, componentContext, taxableWage, 15.00d) * 12; //

            //Calculate worker taxes
            var workerTaxes = CalculateWorkerTaxes(context, componentContext, annualBrutoWage);

            //Netto annual wage = bruto - taxes
            var annualNettoWage = annualBrutoWage - workerTaxes;

            //Calculate basic taxes
            var basicTaxes = CalculateBasicTaxes(context, componentContext, annualNettoWage);

            //Calculate deductions on basic taxes
            var deductions = CalculateDeductions(context, componentContext);

            var annualTaxes = basicTaxes + deductions;

            payrollTax = annualTaxes / 12;

            calculations.Add(CalculationResult.New(componentContext.CalculationAreaOrder, componentContext.Order,
                                                   "BVH", "Bedrijfsvoorheffing", value: -payrollTax));

            return(calculations);
        }
Example #8
0
        public override GherkinParseResult Execute(ProviderResult providerResult, IEnumerable <ProviderSourceDataset> datasets)
        {
            CalculationResult calculationResult = providerResult.CalculationResults.SingleOrDefault(x => x.Calculation.Name.Equals(CalculationName, StringComparison.InvariantCultureIgnoreCase));

            object actualValue = GetActualValue(datasets, DatasetName, FieldName);

            if (actualValue != null)
            {
                object expectedValue = Convert.ChangeType(calculationResult.Value, actualValue.GetType());
                bool   logicResult   = TestLogic(actualValue, expectedValue, Operator);
                if (!logicResult)
                {
                    return(new GherkinParseResult(
                               $"{FieldName} in {DatasetName} - {actualValue} is not {Operator} {expectedValue}")
                    {
                        Dependencies = { new Dependency(DatasetName, FieldName, actualValue?.ToString()) }
                    });
                }
                return(new GherkinParseResult()
                {
                    Dependencies = { new Dependency(DatasetName, FieldName, actualValue?.ToString()) }
                });
            }
            return(new GherkinParseResult($"{FieldName} in {DatasetName} was not found")
            {
                Dependencies = { new Dependency(DatasetName, FieldName, actualValue?.ToString()) }
            });
        }
Example #9
0
        /// <summary>
        /// Berechnet den Abschreibungs- und Restbuchwert und rundet das Ergebnis entsprechend der Implementation.
        /// </summary>
        /// <param name="method">Das Verfahren für die Abschreibungsberechnung</param>
        /// <param name="data">Die Basis-Daten anhand derer der Abschreibungswert berechnet wird.</param>
        /// <param name="period">Das Abrechnungsjahr (beginnend bei 0 = keine Abschreibung)</param>
        /// <returns>Das Ergebnis der Berechnung und Rundung</returns>
        public CalculationResult Calculate(ICalculationMethod method, CalculationData data, int period)
        {
            if (period < 0 || period > data.DepreciationRange)
            {
                throw new ArgumentOutOfRangeException(nameof(period), "The period must be greater or equal than 0 and less than the value of depreciationRange.");
            }

            if (period == 0)
            {
                return(new CalculationResult(period, 0, data.AcquisitionValue));
            }

            var result = method.CalculateDepreciation(data, period);

            CalculationResult resultOld;

            if (period == 1)
            {
                // Nicht jede Berechnungsart funktioniert für period == 0!
                resultOld = new CalculationResult(0, 0, data.AcquisitionValue);
            }
            else
            {
                resultOld = method.CalculateDepreciation(data, period - 1);
            }

            var remainingValue    = Math.Round(result.RemainingValue, _decimals);
            var remainingValueOld = Math.Round(resultOld.RemainingValue, _decimals);

            return(new CalculationResult(period, remainingValueOld - remainingValue, remainingValue));
        }
        public async Task <IActionResult> HasCalculationResults(string calculationId)
        {
            Guard.IsNullOrWhiteSpace(calculationId, nameof(calculationId));

            Common.ApiClient.Calcs.Models.Calculation calculation = await _calculationsRepositoryPolicy.ExecuteAsync(() => _calculationRepository.GetCalculationById(calculationId));

            if (calculation == null)
            {
                _logger.Error($"Calculation could not be found for calculation id '{calculationId}'");

                return(new NotFoundObjectResult($"Calculation could not be found for calculation id '{calculationId}'"));
            }

            ProviderResult providerResult = await _resultsRepositoryPolicy.ExecuteAsync(() => _resultsRepository.GetSingleProviderResultBySpecificationId(calculation.SpecificationId));

            CalculationResult calculationResult = providerResult?
                                                  .CalculationResults?
                                                  .FirstOrDefault(m =>
                                                                  string.Equals(m.Calculation.Id,
                                                                                calculationId,
                                                                                StringComparison.InvariantCultureIgnoreCase));

            if (calculationResult != null)
            {
                return(new OkObjectResult(true));
            }

            return(new OkObjectResult(false));
        }
        public CalculationResult FunctionHandler(InputData input, ILambdaContext context)
        {
            _logger = new CloudWatchLogger(context);

            CalculationResult result = null;

            if (input == null)
            {
                _logger.LogError("Input data cannot be null.");
            }
            else
            {
                _logger.LogMessage(JsonConvert.SerializeObject(input));

                try
                {
                    result    = _calculator.Calculate(input.Height, input.Weight, input.Age);
                    result.Id = SaveInformations(input, result);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            }

            result = result ?? new CalculationResult
            {
                Description = CalculationDescription.NotCalculated.ToString()
            };

            _logger.LogMessage($"Calculation result: {result.BMI} - {result.Description}");

            return(result);
        }
Example #12
0
        public void ResultSerializationTests()
        {
            CalculationResult res1 = new CalculationResult(ar1, row, time1, id1);
            CalculationResult res2 = CalculationResult.GetFromBytes(CalculationResult.ToBytes(res1));

            Assert.AreEqual(res1, res2);
        }
Example #13
0
        private async Task <CalculationResult> CalculateResult(CalculationInput input, Func <Probability, Probability, Probability> calculation, string type)
        {
            var validationResult = _validator.Validate(input);

            if (!validationResult.IsValid)
            {
                return new CalculationResult {
                           Validation = validationResult
                }
            }
            ;

            var A = new Probability(input.A);
            var B = new Probability(input.B);

            var result = new CalculationResult
            {
                Validation        = validationResult,
                Result            = calculation(A, B).Value,
                CalculationDate   = DateTime.UtcNow,
                Inputs            = new[] { A, B },
                TypeOfCalculation = type
            };

            await _loggingService.LogAsync(result);

            return(result);
        }
    }
Example #14
0
        public CalculationResult CalculateLines()
        {
            var result = new CalculationResult();

            foreach (var line in _lines)
            {
                var lineType = _specification.GetCodeStringType(line);

                switch (lineType)
                {
                case CodeStringType.Empty:
                    result.EmptyLines++;
                    break;

                case CodeStringType.Code:
                    result.CodeLines++;
                    break;

                case CodeStringType.Comment:
                    result.CommentLines++;
                    break;

                case CodeStringType.Mixed:
                    result.HybridLines++;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            return(result);
        }
        public void Calculate_FailsValidation_ReturnsExpectedResult()
        {
            // Arrange
            var calculatorService = new CalculatorService(_logger.Object);
            var calculation       = new Mock <ICalculation <decimal> >(MockBehavior.Strict);

            var validationResult = new ValidationResult
            {
                IsValid = false,
                Errors  = new List <Error>
                {
                    new Error
                    {
                        ErrorCode = ErrorCode.InvalidParameters
                    }
                }
            };

            calculation.Setup(x => x.Validate()).Returns(validationResult);

            // Act
            var result = calculatorService.Calculate(calculation.Object);

            // Assert
            var expected = new CalculationResult <decimal> {
                Validation = validationResult
            };

            result.Should().BeEquivalentTo(expected);
            calculation.Verify(x => x.Validate(), Times.Once);
            _logger.VerifyNoOtherCalls();
        }
Example #16
0
        public CalculationResult Solve(Matrix matrix)
        {
            const int iterations = 20;

            CalculationResult result = new CalculationResult(matrix);

            double[] answers = new double[matrix.Size];

            for (int iter = 0; iter < iterations; iter++)
            {
                for (int i = 0; i < matrix.Size; i++)
                {
                    double sigma = 0;

                    for (int j = 0; j < matrix.Size; j++)
                    {
                        if (j != i)
                        {
                            sigma += matrix.Variables[i, j] * answers[j];
                        }
                    }

                    answers[i] = (matrix.Results[i] - sigma) / matrix.Variables[i, i];
                }
            }

            result.Answers = answers;
            return(result);
        }
Example #17
0
        public void OnGet()
        {
            if (!ModelState.IsValid)
            {
                return;
            }

            var input = new LoanCalculatorInput(Amount, TermYears * 12, InterestRate);

            CalculationResult <decimal> result = null;

            try
            {
                result = _loanCalculator.Calculate(input);
            }
            catch (ArgumentNullException)
            {
                OutputMessage = _localizer[LocalizationResourceKeys.LoanCalculatorErrorMessage];
            }

            if (result != null && result.Successful)
            {
                OutputMessage = string.Format(_localizer[LocalizationResourceKeys.LoanCalculatorResultMessage], Amount, TermYears, result.Value);
            }
        }
Example #18
0
        public async Task <List <CalculationResult> > Calculate(MuntContext context, ComponentContext componentContext)
        {
            var calculations = new List <CalculationResult>();

            var performanceCodes = context.PerformanceInformation.Performances.Select(p => p.Code).Distinct();

            foreach (var performanceCode in performanceCodes)
            {
                var performances = context.PerformanceInformation.Performances.Where(p => p.Code == performanceCode);

                var wage        = performances.FirstOrDefault()?.Value;
                var description = performances.FirstOrDefault()?.Description;
                var hours       = performances.Sum(p => p.Hours);
                var days        = performances.Sum(p => p.Days);
                var value       = hours * wage;

                //Add a calculation result for this area
                calculations.Add(CalculationResult.New(componentContext.CalculationAreaOrder, componentContext.Order,
                                                       performanceCode.ToString(), description,
                                                       days: days,
                                                       hours: hours,
                                                       value: value.HasValue ? value.Value : 0));
            }

            return(calculations);
        }
Example #19
0
        public void Run()
        {
            bool theEnd = false;

            Console.WriteLine("Receiver running...");

            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                CalculationResult result = CalculationResult.GetFromBytes(ea.Body);
                var props = ea.BasicProperties;
                var id    = props.CorrelationId;
                if (result.Row % 32 == 0)
                {
                    Console.WriteLine(string.Format("Received result, adding to assembly. Row: {0}", result.Row));
                }
                logger.LogWorkerTime(result);
                if (assembler.AddResult(result))
                {
                    channel.BasicPublish(exchange: "", routingKey: Queues.NotificationQueue, body: new byte[] { 1 });
                    theEnd = assembler.FinalAssembly;
                }

                channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
            };
            while (!theEnd)
            {
            }
            channel.BasicPublish(exchange: "", routingKey: Queues.NotificationQueue, body: new byte[] { 1 });
        }
Example #20
0
        internal static void ExportToCSV(CalculationResult result, string fileName, string info)
        {
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }
            File.AppendAllText(fileName, string.Format("Algorithm: {0}{2}Parameters: {1}{2};<INSTRUMENT>;<TIME>;<OPEN>;<HIGH>;<LOW>;<CLOSE>;<AMOUNT>;<BALANCE>;<RESULT>;;{3}{2}",
                                                       info, string.Join(",", result.Parameters), Environment.NewLine, result.AlgorithmData.Any() ? "<ALGORITHM DATA>" : string.Empty));
            var lines = result.Data.Select(o =>
                                           string.Format(";{0};{1};{2};{3};{4};{5};{6};{7};{8};",
                                                         Settings.Default.InsName,
                                                         o.Candle.TimeStamp,
                                                         o.Candle.Open,
                                                         o.Candle.High,
                                                         o.Candle.Low,
                                                         o.Candle.Close,
                                                         o.Amount,
                                                         o.Balance,
                                                         o.Amount > 0 ?
                                                         "LONG" : (o.Amount < 0 ?
                                                                   "SHORT" : "EXIT")
                                                         )
                                           ).Take(result.Data.Length - 1).ToArray();

            for (int li = 0; li < result.AlgorithmData.Length - 1; li++)
            {
                lines[lines.Length - li - 1] = string.Format("{0};{1};",
                                                             lines[lines.Length - li - 1],
                                                             string.Join(";", result.AlgorithmData[result.AlgorithmData.Length - li - 1]));
            }
            File.AppendAllLines(fileName, lines);
        }
Example #21
0
 public bool AddResult(CalculationResult result)
 {
     if (tempResult.Count() == 0)
     {
         isResult = false;
     }
     if (tempResult.Count() == container.Size - 1)
     {
         tempResult.Add(result.Row, result.Result);
         Assembly();
         isResult = true;
         if (intermediateResult)
         {
             container.SaveIntermediateMatrix(this.result);
             intermediateResult = false;
             tempResult.Clear();
             this.result.Clear();
         }
         else
         {
             container.SaveOutputMatrix(this.result);
             finalAssembly = true;
             this.result.Clear();
         }
         return(isResult);
     }
     tempResult.Add(result.Row, result.Result);
     return(isResult);
 }
        public void Calculate_PassesValidation_ReturnsExpectedResult()
        {
            // Arrange
            var calculatorService = new CalculatorService(_logger.Object);
            var calculation       = new Mock <ICalculation <decimal> >(MockBehavior.Strict);

            var validationResult = new ValidationResult {
                IsValid = true
            };

            calculation.Setup(x => x.Validate()).Returns(validationResult);
            calculation.Setup(x => x.Calculate()).Returns(0.55M);
            calculation.Setup(x => x.GetInputsForLogMessage()).Returns("SomeInputs");

            // Act
            var result = calculatorService.Calculate(calculation.Object);

            // Assert
            var expected = new CalculationResult <decimal>
            {
                Value      = 0.55M,
                Validation = validationResult
            };

            result.Should().BeEquivalentTo(expected);
            calculation.Verify(x => x.Validate(), Times.Once);
            calculation.Verify(x => x.Calculate(), Times.Once);
            _logger.VerifyInformationWasCalled("[CALCULATION] Type: ICalculation`1Proxy | Inputs: SomeInputs | Result: 0.55");
        }
Example #23
0
        /// <summary>
        /// Berechnet den Abschreibungs- und Restbuchwert und rundet das Ergebnis entsprechend der Implementation.
        /// </summary>
        /// <param name="method">Das Verfahren für die Abschreibungsberechnung</param>
        /// <param name="data">Die Basis-Daten anhand derer der Abschreibungswert berechnet wird.</param>
        /// <param name="period">Das Abrechnungsjahr (beginnend bei 0 = keine Abschreibung)</param>
        /// <returns>Das Ergebnis der Berechnung und Rundung</returns>
        public CalculationResult Calculate(ICalculationMethod method, CalculationData data, int period)
        {
            if (period < 0 || period > data.DepreciationRange)
                throw new ArgumentOutOfRangeException(nameof(period), "The period must be greater or equal than 0 and less than the value of depreciationRange.");

            if (period == 0)
                return new CalculationResult(period, 0, data.AcquisitionValue);

            var result = method.CalculateDepreciation(data, period);

            CalculationResult resultOld;
            if (period == 1)
            {
                // Nicht jede Berechnungsart funktioniert für period == 0!
                resultOld = new CalculationResult(0, 0, data.AcquisitionValue);
            }
            else
            {
                resultOld = method.CalculateDepreciation(data, period - 1);
            }

            var remainingValue = Math.Round(result.RemainingValue, _decimals);
            var remainingValueOld = Math.Round(resultOld.RemainingValue, _decimals);

            return new CalculationResult(period, remainingValueOld - remainingValue, remainingValue);
        }
Example #24
0
        public async Task Data_Put_With_Calculation()
        {
            string token = PrincipalUtil.GetToken(1337);

            TestDataUtil.PrepareInstance("tdd", "custom-validation", 1337, new Guid("182e053b-3c74-46d4-92ec-a2828289a877"));

            HttpClient client = SetupUtil.GetTestClient(_factory, "tdd", "custom-validation");

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "/tdd/custom-validation/instances/1337/182e053b-3c74-46d4-92ec-a2828289a877/data/7dfeffd1-1750-4e4a-8107-c6741e05d2a9")
            {
            };

            HttpResponseMessage response = await client.SendAsync(httpRequestMessage);

            string responseContent = await response.Content.ReadAsStringAsync();

            HttpRequestMessage putRequestMessage = new HttpRequestMessage(HttpMethod.Put, "/tdd/custom-validation/instances/1337/182e053b-3c74-46d4-92ec-a2828289a877/data/7dfeffd1-1750-4e4a-8107-c6741e05d2a9")
            {
                Content = new StringContent(responseContent, Encoding.UTF8, "application/json"),
            };

            response = await client.SendAsync(putRequestMessage);

            TestDataUtil.DeleteInstance("tdd", "custom-validation", 1337, new Guid("182e053b-3c74-46d4-92ec-a2828289a877"));
            responseContent = await response.Content.ReadAsStringAsync();

            CalculationResult calculationResult = JsonConvert.DeserializeObject <CalculationResult>(responseContent);

            Assert.Equal(HttpStatusCode.SeeOther, response.StatusCode);
            Assert.Contains(calculationResult.ChangedFields.Keys, k => k == "OpplysningerOmArbeidstakerengrp8819.Skjemainstansgrp8854.TestRepeatinggrp123[0].value");
            Assert.Equal(555, Convert.ToInt32(calculationResult.ChangedFields["OpplysningerOmArbeidstakerengrp8819.Skjemainstansgrp8854.TestRepeatinggrp123[0].value"]));
            Assert.Equal(1000, Convert.ToInt32(calculationResult.ChangedFields["OpplysningerOmArbeidstakerengrp8819.Skjemainstansgrp8854.Journalnummerdatadef33316.value"]));
            Assert.Null(calculationResult.ChangedFields["OpplysningerOmArbeidstakerengrp8819.Skjemainstansgrp8854.IdentifikasjonsnummerKravdatadef33317"]);
        }
Example #25
0
        public void ResultEqualityTests()
        {
            CalculationResult res1 = new CalculationResult(ar1, row, time1, id1);
            CalculationResult res2 = new CalculationResult(ar1, row, time1, id1);

            Assert.AreEqual(res1, res2);

            res1 = new CalculationResult(ar1, row, time1, id1);
            res2 = new CalculationResult(ar2, row, time1, id1);

            Assert.AreNotEqual(res1, res2);

            res1 = new CalculationResult(ar1, row, time1, id1);
            res2 = new CalculationResult(ar1, row, time2, id1);

            Assert.AreNotEqual(res1, res2);

            res1 = new CalculationResult(ar1, row, time1, id1);
            res2 = new CalculationResult(ar1, row, time1, id2);

            Assert.AreNotEqual(res1, res2);

            res1 = new CalculationResult(ar2, row, time1, id1);
            res2 = new CalculationResult(ar3, row, time1, id1);

            Assert.AreNotEqual(res1, res2);
        }
Example #26
0
        private void AddDetails(CalculationResult result)
        {
            Paragraph details = CreateParagraph();

            var value = $@"Полученный расход воды по Указаниям: {result.WaterFlowAccordingDirections : ##} л.";

            AddTextLineToParagraph(details, value);

            value = $@"Расход воды с учетом ОК: {result.WaterConsumptionIncludingOK: .##} л.";
            AddTextLineToParagraph(details, value);

            value = $@"Расход воды с учетом Воздухосодержания: {result.WaterFlowWithRegardToAirContent: .##} л.";
            AddTextLineToParagraph(details, value);

            value = $@"Расход воды с учетом влажности песка: {result.WaterConsumptionWithRegardToHumidityOfSand: .##} л.";
            AddTextLineToParagraph(details, value);

            value = $@"Количество цемента по расчету: {result.QuantityOfCementByCalculation: .##} кг.";
            AddTextLineToParagraph(details, value);

            value = $@"Полученное В/Ц из расчета: {result.WCByCalculation: .##}";
            AddTextLineToParagraph(details, value);

            value = $@"Максимально допустимое В/Ц по Указаниям: {result.MaximumPermissibleAccordingWCToInstructions: .##}";
            AddTextLineToParagraph(details, value);

            value = $@"В/Ц принимается минимальное из полученного и допустимого: {result.MinimumOfTheReceivedAndAdmissible: .##}";
            AddTextLineToParagraph(details, value);

            value = $@"Откорректированный расход цемента: {result.CorrectedCementConsumption: .##} кг.";
            AddTextLineToParagraph(details, value);

            value = $@"Объем заполнителей: {result.VolumeOfAggregates: .##} кг.";
            AddTextLineToParagraph(details, value);

            value = $@"Доля песка от общего кол-ва заполнит: {result.TheShareOfSandFromTheTotalNumberWillFill: .##} %";
            AddTextLineToParagraph(details, value);

            value = $@"Доля песка откорректированная  по Мк и В/Ц: {result.TheProportionOfSandCorrectedByMk: .##} %";
            AddTextLineToParagraph(details, value);

            value = $@"Доля песка откорректированная по крупному заполнителю: {result.ShareOfSandCorrectedForGravel} %";
            AddTextLineToParagraph(details, value);

            value = $@"Количество песка(сухого): {result.TheAmountOfSandDry: .##} кг.";
            AddTextLineToParagraph(details, value);

            value = $@"Количество песка(влажного): {result.TheAmountOfSandWet: .##} кг.";
            AddTextLineToParagraph(details, value);

            value = $@"Количество крупного заполнителя: {result.NumberOfCoarseAggregate: .##} кг.";
            AddTextLineToParagraph(details, value);

            value = $@"Химическая добавка: {result.ChemicalAdditive: .##} кг.";
            AddTextLineToParagraph(details, value);

            value = $@"В пересчете на 20% раствор: {result.InTermsOfSolution: .##} л.";
            AddTextLineToParagraph(details, value);
        }
Example #27
0
        public IActionResult Recalculate([FromBody] Recalculate obj)
        {
            // Get From DB
            if (obj == null)
            {
                return(BadRequest());
            }

            UtilitiesDAL utilDAL = new UtilitiesDAL(_db.ConnectionString);

            electrictyRate = utilDAL.GetElectricityRate(obj.Building);
            utilDAL        = new UtilitiesDAL(_db.ConnectionString);
            pvOutput       = utilDAL.GetPVOutput(obj.City);

            electrictyConsumptionPerMonth = Math.Round(obj.Bill / electrictyRate, 2);
            decimal electrictyConsumptionPerDay = Math.Round(electrictyConsumptionPerMonth / 30, 2);

            power = obj.Power;
            coveragePercentage = obj.Coverage / 100;

            decimal co2Reduction = 0.934M;

            averageCostperKWp = 15500000M;
            int yearInvestment = 25;

            CalculateSavings(yearInvestment);

            CalculationResult result = new CalculationResult();

            result.BuildingType           = obj.Building;
            result.MonthlyElectricityBill = obj.Bill;
            result.Power            = obj.Power;
            result.Coverage         = obj.Coverage;
            result.City             = obj.City;
            result.FirstYearSavings = savingList[0].SavingsValue;
            result.AnnualSavings    = averageSavings;
            if (savingList.Exists(x => x.AccumulatedSavings >= 0))
            {
                result.PaybackPeriod = savingList.FirstOrDefault(x => x.AccumulatedSavings >= 0).Year;
            }
            else
            {
                result.PaybackPeriod = 0;
            }
            result.SolarSystemCost           = costOfSystem;
            result.ReturnOnInvestment        = Math.Round((totalSavings - costOfSystem) / costOfSystem * 100, 2);
            result.SystemSize                = systemSize;
            result.MonthlyElectricityUse     = electrictyConsumptionPerMonth;
            result.MonthlySolarProduction    = Math.Round(powerList[0].EnergyOutput / 12, 0);
            result.LifetimeCO2Reduction      = Math.Round(totalEnergyOutput * co2Reduction, 2);
            result.NumberOfPanels            = Math.Round(systemSize / 0.3M, 0);
            result.AreaRequired              = Math.Round(result.NumberOfPanels * 1.5M, 0);
            result.CostOfSolarPerWatt        = Math.Round(costOfSystem / systemSize / 1000, 2);
            result.LifetimeCostOfElectricity = LCOE;
            result.LifetimeSavings           = totalSavings;
            result.ElectricityBillComparison = savingList;

            return(new ObjectResult(result));
        }
        public void Add_WithValue_AddsToSubTotalAndTotal()
        {
            var cResult = new CalculationResult();

            cResult.Add(12.34M);
            Assert.AreEqual(12.34M, cResult.SubTotal);
            Assert.AreEqual(12.34M, cResult.Total);
        }
        public void Ctor_WithNoParams_InitialisesWithExpectedValues()
        {
            var cResult = new CalculationResult();

            Assert.AreEqual(0.0M, cResult.SubTotal);
            Assert.AreEqual(0, cResult.Offers.Count);
            Assert.AreEqual(0.0M, cResult.Total);
        }
        public bool TryGetResult(out CalculationResult data)
        {
            var result = false;

            data = default(CalculationResult);

            return(result);
        }
        private async Task<ActionResult> PutFormData(string org, string app, Instance instance, Guid dataGuid, string dataType)
        {
            string classRef = _appResourcesService.GetClassRefForLogicDataType(dataType);
            Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]);
            
            ModelDeserializer deserializer = new ModelDeserializer(_logger, _altinnApp.GetAppModelType(classRef));
            object serviceModel = await deserializer.DeserializeAsync(Request.Body, Request.ContentType);

            if (!string.IsNullOrEmpty(deserializer.Error))
            {
                return BadRequest(deserializer.Error);
            }

            if (serviceModel == null)
            {
                return BadRequest("No data found in content");
            }

            string serviceModelJsonString = JsonSerializer.Serialize(serviceModel);

            // Trigger application business logic
            bool changedByCalculation = await _altinnApp.RunCalculation(serviceModel);

            int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId);

            // Save Formdata to database
            DataElement updatedDataElement = await _dataService.UpdateData(
                serviceModel,
                instanceGuid,
                _altinnApp.GetAppModelType(classRef),
                org,
                app,
                instanceOwnerPartyId,
                dataGuid);

            SelfLinkHelper.SetDataAppSelfLinks(instanceOwnerPartyId, instanceGuid, updatedDataElement, Request);

            string dataUrl = updatedDataElement.SelfLinks.Apps;

            if (changedByCalculation)
            {
                string updatedServiceModelString = JsonSerializer.Serialize(serviceModel);
                CalculationResult calculationResult = new CalculationResult(updatedDataElement);
                try
                {
                    Dictionary<string, object> changedFields = JsonHelper.FindChangedFields(serviceModelJsonString, updatedServiceModelString);
                    calculationResult.ChangedFields = changedFields;
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Unable to determine changed fields");
                }
                
                return StatusCode((int)HttpStatusCode.SeeOther, calculationResult);
            }

            return Created(dataUrl, updatedDataElement);
        }
Example #32
0
        public static bool Compare(CalculationResult actual, CalculationResult expected)
        {
            if ((actual == null) && (expected == null))
                return true;

            if ((actual == null) || (expected == null))
                return false;

            return actual.TotalAmount == expected.TotalAmount;
        }
Example #33
0
        public void CalculatorTest_SinglePoint_Success()
        {
            const int result = 10;
            var dataReader = Substitute.For<IDataReader>();
            var repository = Substitute.For<IRepository>();
            dataReader.ReadDataPoints("", 1).ReturnsForAnyArgs(info => new List<int> { result });

            CalculationResult expectedResult = new CalculationResult
            {
                TotalAmount = result
            };

            Calculator calc = new Calculator(dataReader, repository);
            var actualResult = calc.ProcessData(Arg.Any<string>(), 1);

            repository.Received().Save(actualResult);

            Assert.IsTrue(Comparer.Compare(actualResult, expectedResult));
        }
Example #34
0
        public ActionResult Calculate(string calculation)
        {
            dynamic response = new CalculationResult();
            Expression expression = new Expression(calculation);
            if (expression.HasErrors())
            {
                response.success = false;
                response.errors = expression.Error;
            }

            try
            {
               response.result = expression.Evaluate();
               response.success = true;
            }
            catch (Exception ex)
            {
                response.success = false;
                response.errors = ex.Message;
            }
            return Json(response);
        }
 private void TestResult(CalculationResult result, decimal expectedRemainingValue, decimal expectedDepreciation)
 {
     Assert.Equal(expectedRemainingValue, result.RemainingValue);
     Assert.Equal(expectedDepreciation, result.Depreciation);
 }
Example #36
0
        /// <summary>
        /// Build the result from the completed solver
        /// </summary>
        /// <param name="controller"></param>
        public void Build(SolverController controller)
        {
            map = controller.Map;

            // Build type strong info class
            info = new SolverResultInfo();
            info.TotalNodes = (int) controller.Stats.Nodes.ValueTotal;
            info.TotalSeconds = controller.Stats.EvaluationTime.ValueTotal;
            info.Machine = DebugHelper.GetCPUDescription();
            info.RatingScore = PuzzleAnalysis.CalcRating(map);
            foreach (Statistic stat in controller.Stats.Stats)
            {
                SolverLabel lb = stat.GetDisplayData();

                info.InfoValues.Add(new NameValuePair() {Name = lb.Name, Value = lb.Value});
            }

            // Build the exit status and summary
            if (HasSolution)
            {
                // General Sucess
                status = CalculationResult.SolutionFound;
                StringBuilder sb = new StringBuilder();
                if (solutions.Count == 1)
                {
                    sb.Append("Solution");
                }
                else
                {
                    sb.AppendFormat("{0} solutions", solutions.Count);
                }

                sb.AppendFormat(" in {0} and {1} nodes at {2:0} nodes/s (puzzle score {3})",
                                StringHelper.ToString(TimeSpan.FromSeconds(info.TotalSeconds)),
                                info.TotalNodes,
                                info.TotalNodes/info.TotalSeconds,
                                info.RatingScore);
                summary = sb.ToString();
            }
            else
            {
                if (exception != null)
                {
                    status = CalculationResult.Error;
                    summary = string.Format("Error ({0})", exception.Message);
                }
                else
                {
                    if (controllerResult == SolverController.States.Cancelled)
                    {
                        status = CalculationResult.Cancelled;
                        summary =
                            string.Format(" Cancelled after {0} sec and {1} nodes at {2:0} nodes/s (puzzle score {3})",
                                          StringHelper.ToString(TimeSpan.FromSeconds(info.TotalSeconds)),
                                          info.TotalNodes,
                                          info.TotalNodes/info.TotalSeconds,
                                          info.RatingScore);
                    }
                    else if (controllerResult == SolverController.States.CompleteNoSolution)
                    {
                        status = CalculationResult.NoSolution;
                        summary = "The puzzle does not have a solution";
                    }
                    else
                    {
                        status = CalculationResult.GaveUp;
                        summary = string.Format(
                                "The solver could not find a within the given constraints. Tried for {0} sec and {1} nodes at {2:0} nodes/s (puzzle score {3})",
                                StringHelper.ToString(TimeSpan.FromSeconds(info.TotalSeconds)),
                                info.TotalNodes,
                                info.TotalNodes/info.TotalSeconds,
                                info.RatingScore);
                    }
                }
            }
        }
Example #37
0
        private void bgCalculation_DoWork(object sender, DoWorkEventArgs e)
        {
            var mdf = (IMapDefinition)e.Argument;
            var resSvc = mdf.CurrentConnection.ResourceService;

            //Accumulate layers
            Dictionary<string, ILayerDefinition> layers = new Dictionary<string, ILayerDefinition>();
            foreach (var lyr in mdf.MapLayer)
            {
                if (!layers.ContainsKey(lyr.ResourceId))
                    layers.Add(lyr.ResourceId, (ILayerDefinition)resSvc.GetResource(lyr.ResourceId));
            }
            if (mdf.BaseMap != null)
            {
                foreach (var group in mdf.BaseMap.BaseMapLayerGroup)
                {
                    foreach (var layer in group.BaseMapLayer)
                    {
                        if (!layers.ContainsKey(layer.ResourceId))
                            layers.Add(layer.ResourceId, (ILayerDefinition)resSvc.GetResource(layer.ResourceId));
                    }
                }
            }

            Check.NotNull(layers, "layers");
            int processed = 0;

            //Begin
            foreach (var layer in layers.Values)
            {
                CalculationResult res = new CalculationResult();
                string wkt;
                var e1 = layer.GetSpatialExtent(true, out wkt);
                if (e1 != null)
                {
                    res.Extents = ExtentsToString(e1);
                }
                res.LayerDefinition = layer.ResourceID;
                res.CoordinateSystem = wkt;

                bool tx = false;
                if (wkt != mdf.CoordinateSystem)
                {
                    tx = true;
                    //Transform if not the same, otherwise assume either arbitrary or same as the map
                    if (!string.IsNullOrEmpty(wkt))
                    {
                        e1 = Utility.TransformEnvelope(e1, wkt, mdf.CoordinateSystem);
                        res.TransformedResult = e1;
                    }
                }
                else
                {
                    res.TransformedResult = e1;
                    res.Messages = Strings.NoTransformationRequired;
                }

                if (e1 != null)
                {
                    res.Status = TransformStatus.Pass;
                    if (tx)
                        res.TransformedExtents = ExtentsToString(e1);
                }
                else
                {
                    res.Status = TransformStatus.Fail;
                    res.Messages = string.Format(Strings.ExtentsTransformationFailed, layer.ResourceID);
                }

                processed++;
                bgCalculation.ReportProgress(processed, res);
            }
        }