public CalcResponse Calc([FromBody] CalcRequest request)
        {
            _logger.LogInformation("Zeebe JobKey: {Value}", Request.Headers["X-Zeebe-Job-Key"]);
            _logger.LogInformation("Zeebe JobType: {Value}", Request.Headers["X-Zeebe-Job-Type"]);
            _logger.LogInformation("Zeebe ProcessInstanceKey: {Value}", Request.Headers["X-Zeebe-Process-Instance-Key"]);
            _logger.LogInformation("Zeebe BpmnProcessId: {Value}", Request.Headers["X-Zeebe-Bpmn-Process-Id"]);
            _logger.LogInformation("Zeebe ProcessDefinitionVersion: {Value}", Request.Headers["X-Zeebe-Process-Definition-Version"]);
            _logger.LogInformation("Zeebe ProcessDefinitionKey: {Value}", Request.Headers["X-Zeebe-Process-Definition-Key"]);
            _logger.LogInformation("Zeebe ElementId: {Value}", Request.Headers["X-Zeebe-Element-Id"]);
            _logger.LogInformation("Zeebe ElementInstanceKey: {Value}", Request.Headers["X-Zeebe-Element-Instance-Key"]);
            _logger.LogInformation("Zeebe Worker: {Value}", Request.Headers["X-Zeebe-Worker"]);
            _logger.LogInformation("Zeebe Retries: {Value}", Request.Headers["X-Zeebe-Retries"]);
            _logger.LogInformation("Zeebe Deadline: {Value}", Request.Headers["X-Zeebe-Deadline"]);
            _logger.LogInformation("Custom header func: {Value}", Request.Headers["X-Custom-Header-Func"]);

            var(@operator, firstOperand, secondOperand) = request;
            var first  = firstOperand.GetValueOrDefault();
            var second = secondOperand.GetValueOrDefault();

            return(new CalcResponse(@operator switch
            {
                "+" => first + second,
                "-" => first - second,
                "/" => first / second,
                "*" => first * second,
                _ => throw new InvalidOperationException($"Operator {@operator} isn't supported")
            }));
예제 #2
0
        public double[] Minus(double[] v1, double[] v2)
        {
            var request = CalcRequest.Minus(v1, v2);
            var res     = ExecuteRequest(request);

            return(res.Result);
        }
예제 #3
0
 public override Task <CalcResponse> Calculate(CalcRequest request, ServerCallContext context)
 {
     return(Task.FromResult(new CalcResponse()
     {
         Sum = request.A + request.B
     }));
 }
예제 #4
0
 public override Task <CalcResponse> Multiply(CalcRequest request, ServerCallContext context)
 {
     return(Task.FromResult(new CalcResponse
     {
         Result = request.FirstNumber * request.SecondNumber
     }));
 }
예제 #5
0
        public double ScalarMultiply(double[] v1, double[] v2)
        {
            var request = CalcRequest.ScalarMultiply(v1, v2);
            var res     = ExecuteRequest(request);

            return(res.Result[0]);
        }
 public override Task <CalcResult> Calc(CalcRequest request, ServerCallContext context)
 {
     return(Task.FromResult(new CalcResult()
     {
         Result = request.Number1 + request.Number2
     }));
 }
예제 #7
0
        public CalculationResult Post([FromBody] CalcRequest request)
        {
            var value  = _calculator.Calculate(request);
            var result = _postCalculationProcessor.Process(request.ResultType, value);

            return(result);
        }
        public string GetCalc(CalcRequest CalcRequestData)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://reservation.aeroflot.ru");

            req.Method            = "GET";
            req.Credentials       = CredentialCache.DefaultCredentials;
            req.AllowAutoRedirect = false;
            HttpWebResponse resp    = (HttpWebResponse)req.GetResponse();
            var             cookies = resp.Cookies;

            resp.Close();
            req = null;
            //ToDo:поправить на URL
            string url = string.Format("https://reservation.aeroflot.ru/SSW2010/7B47/webqtrip.html?searchType=NORMAL&journeySpan=RT&alternativeLandingPage=1&lang=ru&currency=RUB&cabinClass=ECONOMY&referrerCode=AFLBOOK&origin={0}&destination={1}&departureDate={2}&returnDate={3}&numAdults={4}&numChildren=0&numInfants=0&utm_source=&utm_campaign=&utm_medium=&utm_content=&utm_term=", CalcRequestData.origin, CalcRequestData.destination, CalcRequestData.departureDate.ToString("yyyy-MM-dd"), CalcRequestData.returnDate.ToString("yyyy-MM-dd"), CalcRequestData.numAdults.ToString());

            req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.CookieContainer = new CookieContainer();
            foreach (Cookie cookie in cookies)
            {
                req.CookieContainer.Add(cookie);
            }

            resp = (HttpWebResponse)req.GetResponse();
            string response = string.Empty;

            using (StreamReader stream = new StreamReader(resp.GetResponseStream(), Encoding.UTF8))
            {
                response = stream.ReadToEnd();
            }
            return(response);
        }
예제 #9
0
        private CalcResult ExecuteRequest(CalcRequest request)
        {
            CalcResult res = CalcResult.From(double.NaN);

            var sw = Stopwatch.StartNew();

            try
            {
                var client       = new TcpClient(HostIP, Port);
                var clientStream = client.GetStream();
                var bytes        = request.GetBytes();
                clientStream.Write(bytes, 0, bytes.Length);

                var buffer = new byte[client.ReceiveBufferSize];
                clientStream.Read(buffer, 0, client.ReceiveBufferSize);
                res = CalcResult.FromBytes(buffer);
                client.Close();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Failed to execute request");
            }
            sw.Stop();
            _logger.Info($"Request to {HostIP}:{Port} executed in {sw.ElapsedMilliseconds} ms");

            return(res);
        }
예제 #10
0
        /// <summary>
        /// performs simple binary calculations over 2 operands and 1 operator
        /// </summary>
        public virtual double Calculate(CalcRequest request)
        {
            //as my task is just to operate with 2 arguments and 1 operator
            //I implement simple and strait approach
            ValidateRequest(request);
            var operation = OperationsMap.GetOperation(request.Operators.First());
            var value     = operation.Execute(request.Operands[0], request.Operands[1]);

            return(value);
        }
예제 #11
0
        protected override void OnPaint(PaintEventArgs e)
        {
            var request = new CalcRequest(
                new Complex(-2.0, -1.25),
                new Complex(0.5, 1.25),
                e.ClipRectangle.Width,
                e.ClipRectangle.Height);

            var result = engine.Render(request);

            e.Graphics.DrawImage(result.Image, new Point(0, 0));
        }
예제 #12
0
        public static void DoSimpleCalc(CalcService.CalcServiceClient client, int number1, int number2)
        {
            var calcRequest = new CalcRequest()
            {
                Number1 = number1,
                Number2 = number2
            };

            var response = client.Calc(calcRequest);

            Console.WriteLine(response.Result);
        }
예제 #13
0
 public CalcResponse Divide(CalcRequest request)
 {
     try {
         return(new CalcResponse {
             Success = true, Value = request.a / request.b
         });
     } catch (Exception e) {
         return(new CalcResponse {
             Success = false, Error = e.Message
         });
     }
 }
예제 #14
0
        public void TestMust_ValidateRequestAndCreateCalcRequest()
        {
            //arrange
            ValidateCalcRequest validation = new ValidateCalcRequest("MOW", "LED", "01.08.2016", "01.09.2016");

            validation.NumAdults = 1;

            //act
            validation.Validate();
            CalcRequest request = validation.GetCalcRequest();

            //assert
            Assert.IsTrue(request.origin.Length > 0);
        }
예제 #15
0
        public CalcRequest GetCalcRequest()
        {
            CalcRequest request;

            if (RequestValidated)
            {
                request = new CalcRequest(originValidated, destinationValidated, departureDateValidated, returnDateValidated, numAdultsValidated);
            }
            else
            {
                throw new HttpRequestValidationException("Request parameters incorrect");
            }

            return(request);
        }
예제 #16
0
        protected virtual void ValidateRequest(CalcRequest request)
        {
            if (null == request)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (request.Operands.Length != 2)
            {
                throw new ArgumentException(Resources.InvalidOperandsCount);
            }

            if (request.Operators.Length != 1)
            {
                throw new ArgumentException(Resources.InvalidOperatorsCount);
            }
        }
예제 #17
0
        public override Task <CalcResponce> GetAnswer(CalcRequest request, ServerCallContext context)
        {
            Console.WriteLine("New request:");
            IRPN        manager    = new RPN();
            ICalculator calculator = new Calculator();

            var LFK = manager.LengyelFormaKonvertalas(request.Formula);

            Console.WriteLine(LFK);

            var result = calculator.Calculate(LFK);

            Console.WriteLine(result);

            return(Task.FromResult(new CalcResponce()
            {
                Answer = result
            }));
        }
예제 #18
0
        public void TestMust_ParseCalcResponseSuccess()
        {
            //arrange
            ValidateCalcRequest validation = new ValidateCalcRequest("MOW", "LED", "01.08.2016", "01.09.2016", "1");

            validation.Validate();
            CalcRequest request = validation.GetCalcRequest();

            //act
            //ISiteParser aeroflotParser = new FakeParser();
            ISiteRequests aeroflotRequests = new FakeRequests();
            SiteParser    parser           = new SiteParser(new AeroflotParser(), aeroflotRequests);

            parser.CalcRequestData = request;
            parser.GetCalc();
            CalcResponse response = parser.GetCalcResponse();

            //assert
            Assert.IsTrue(response != null);
        }
예제 #19
0
        private static void RunServer(object state)
        {
            var server = (BlockingTcpServer)state;

            while (server.IsStarted)
            {
                var    client       = server._listener.AcceptTcpClient();
                var    clientStream = client.GetStream();
                byte[] buffer       = new byte[client.ReceiveBufferSize];
                clientStream.Read(buffer, 0, client.ReceiveBufferSize);

                var        request = CalcRequest.FromBytes(buffer);
                CalcResult res;
                switch (request.Operation)
                {
                case Operation.Sum:
                    res = CalcResult.From(server._calculator.Sum(request.Vector1, request.Vector2));
                    break;

                case Operation.Minus:
                    res = CalcResult.From(server._calculator.Minus(request.Vector1, request.Vector2));
                    break;

                case Operation.ScalarMultiply:
                    res = CalcResult.From(server._calculator.ScalarMultiply(request.Vector1, request.Vector2));
                    break;

                default:
                    continue;
                }

                Thread.Sleep(250);

                var resBytes = res.GetBytes();
                clientStream.Write(resBytes, 0, resBytes.Length);

                client.Close();
            }
        }
예제 #20
0
        public CalcResponse Get(string origin, string destination, string departureDate, string returnDate, string numAdults)
        {
            CalcResponse        calcResponse = new CalcResponse();
            ValidateCalcRequest validation   = new ValidateCalcRequest(origin, destination, departureDate, returnDate, numAdults);

            validation.NumAdults = 1;
            string validateResult = validation.Validate();

            if (validation.RequestValidated)
            {
                CalcRequest   request          = validation.GetCalcRequest();
                ISiteRequests aeroflotRequests = new AeroflotRequests();
                SiteParser    parser           = new SiteParser(new AeroflotParser(), aeroflotRequests);
                parser.CalcRequestData = request;
                parser.GetCalc();
                calcResponse = parser.GetCalcResponse();
            }
            else
            {
                calcResponse.Error = validateResult;
            }
            return(calcResponse);
        }
예제 #21
0
 public string GetCalc(CalcRequest CalcRequestData)
 {
     return(FakeResponses.AeroflotCalc);
 }
예제 #22
0
        public ActionResult <string> Post([FromForm] CompanyFileMain model)
        {
            Company obj = new Company();
            Dictionary <string, string> dictCSharp = new Dictionary <string, string>();
            Dictionary <string, string> dictPython = new Dictionary <string, string>();
            // TextReader tr = new StreamReader(model.FileReport.OpenReadStream());
            Dictionary <string, string> values = JsonConvert.DeserializeObject <Dictionary <string, string> >(model.Data);

            // string line = tr.ReadLine();
            foreach (KeyValuePair <string, string> pair in values)
            {
                // var pair = line.Split('\t');
                string name  = pair.Key;
                string value = pair.Value;
                dictPython[name] = value;
                if (name.StartsWith("year_0_"))
                {
                    // Данные отчтетности за текущий год
                    var parts = name.Split('_');
                    dictCSharp[String.Join('_', "Code", parts[2])] = value;
                }
                else if (name.StartsWith("year_-1_") || Array.IndexOf(new[] { "year_-1", "year_0", "region" }, name) >= 0)
                {
                    // Данные отчетности за предыдущий год
                }
                else
                {
                    // Другие данные, например нефинансовые показатели
                    dictCSharp[name] = value;
                }
            }

            foreach (var prop in obj.GetType().GetProperties())
            {
                if (dictCSharp.TryGetValue(prop.Name, out var value))
                {
                    if (prop.PropertyType == typeof(float))
                    {
                        prop.SetValue(obj, float.Parse(value));
                    }
                    else if (prop.PropertyType == typeof(int))
                    {
                        prop.SetValue(obj, int.Parse(value));
                    }
                }
            }

            var borrower = new Borrower(obj);

            var request = new CalcRequest();

            request.Params.Add(dictPython);
            // request.INN = model.Inn ?? "";
            var reply      = _backend.Client.CalcProbability(request);
            var dictionary = new Dictionary <string, string>();

            foreach (KeyValuePair <string, float> pair in reply.Result)
            {
                dictionary[pair.Key] = pair.Value.ToString("P2");
            }

//            dictionary["Регрессия банка"] = borrower.CalcDefault().ToString("P2");
            return(Content(JsonConvert.SerializeObject(dictionary), "application/json", Encoding.UTF8));
        }
예제 #23
0
 public OElite.CalcResult PostViaJson([FromBody] CalcRequest request)
 {
     return(ReturnResult(request.Param1, request.Param2));
 }
예제 #24
0
 public int Add(CalcRequest request)
 {
     return(_servcie.Add(request.X, request.Y));
 }
예제 #25
0
 public async Task <CalcResultMessage> Post(CalcRequest request)
 {
     return(await WebApiApplication.ApiActor.Ask <CalcResultMessage>(new CalcMessage(request.JobId, request.LeftOperand, request.RightOperand)));
 }