예제 #1
0
        public ActionResult RateUser(string userId, int rateValue)
        {
            var raterId = this.User.Identity.GetUserId();
            var rate = this.rates
                .GetAll()
                .Where(x => x.RaterId == raterId &&
                            x.RatedId == userId)
                .FirstOrDefault();

            if (rate != null)
            {
                rate.Value = rateValue;
                this.rates.Update(rate);

                return this.Json(new { VoteValue = rate.Value });
            }
            else
            {
                var rateToAdd = new Rate()
                {
                    RaterId = this.User.Identity.GetUserId(),
                    RatedId = userId,
                    Value = rateValue
                };

                this.rates.Create(rateToAdd);
                var ratedUser = this.users.GetById(userId);
                ratedUser.Rates.Add(rateToAdd);
                this.users.Update(ratedUser);

                return this.Json(new { VoteValue = rateToAdd.Value });
            }
        }
 public FirstOrderHistory(Timestamp initialTime, decimal initialValue, Rate initialRate)
 {
     Moments = new SortedList<Timestamp, Snapshot>
     {
         { initialTime, new Snapshot(initialTime, initialValue, initialRate) }
     };
 }
        protected void InsertRate()
        {
            #region Rate
            Rate _Rate = new Rate();
            _Rate.Style_ID = int.Parse(ddlStyle.SelectedValue);
            _Rate.Size_ID = int.Parse(ddlSize.SelectedValue);
            _Rate.Standard_Value = float.Parse(txtStandardValue.Text);
            if (txtCuttingRate.Text != "")
                _Rate.Cutting_Rate = float.Parse(txtCuttingRate.Text);
            if (txtElasticStitchingRate.Text != "")
                _Rate.Elastic_Stitching = float.Parse(txtElasticStitchingRate.Text);
            if (txtOverlock.Text != "")
                _Rate.OverLock = float.Parse(txtOverlock.Text);
            if (txtContractorCommision.Text != "")
                _Rate.Contractor_Commission = float.Parse(txtContractorCommision.Text);
            if (txtbindingrate.Text != "")
                _Rate.BindingRate = float.Parse(txtbindingrate.Text);
            if (txtGloveStitchingRate.Text != "")
                _Rate.GloveStitchingRate = float.Parse(txtGloveStitchingRate.Text);

            _Rate.IsDeleted = false;
            #endregion

            lblMessage.Text = Rate_DA.InsertRate(_Rate);

            lblMessage.ForeColor = System.Drawing.Color.Green;
        }
 protected void AddRate(Rate rate)
 {
     if (Shipment.RateAdjusters != null)
     {
         rate = Shipment.RateAdjusters.Aggregate(rate, (current, adjuster) => adjuster.AdjustRate(current));
     }
     Shipment.rates.Add(rate);
 }
예제 #5
0
        public void RateUser(string userId, int value)
        {
            var newRating = new Rate()
            {
                UserId = userId,
                Value = value
            };

            this.rates.Add(newRating);
            this.rates.SaveChanges();
        }
예제 #6
0
        public bool AddRate(Rate rate)
        {
            Console.WriteLine("\r\n{0} - Adding Rate", DateTime.Now);
            using(RatesDBContext context = new RatesDBContext())
            {
                context.Rates.Add(new Rate() { Value = rate.Value, RateDescription = rate.RateDescription });
                context.SaveChanges();
                Console.WriteLine("{0} Rate Value : {1}",rate.RateDescription, rate.Value.ToString());

                return true;
            }
        }
예제 #7
0
        public void Rate_ReadXml_CorrectInput()
        {
            string xmlString = @"<?xml version=""1.0"" encoding=""utf-8""?><Rate Symbol=""USDUKP""><Bid>1.045</Bid><Ask>1.34</Ask><High>1.44</High><Low>1.04</Low><Direction>-1</Direction><Last>08:24:30</Last></Rate>";
            //
            DateTime tickerDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 17, 26, 34);
            Rate expected = new Rate("EURUSD", 1.28669, 1.28699, 1.28807, 1.28598, RateDirection.Up, tickerDate);
            byte[] bytes = Encoding.ASCII.GetBytes(xmlString);
            MemoryStream stream = new MemoryStream(bytes);

            XmlReader reader = XmlReader.Create(stream);
            Rate actual = new Rate(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//fxRate.txt");

            Assert.That(actual, Is.EqualTo(expected));
        }
예제 #8
0
        private void ParseXml(string url)
        {
            Stream xmlStream = GetStream(url);
            XmlReader xmlReader = XmlReader.Create(xmlStream);

            xmlReader.Read(); //move to first element in xml
            xmlReader.Read(); //move to whitespace
            xmlReader.Read(); //move to "Rates"
            xmlReader.Read(); //reads "Rates" move to whitespace
            while (xmlReader.Read()) //read whitespace and move to "Rate"
            {
                if (xmlReader.Name == "Rates") { break; }
                Rate rate = new Rate(xmlReader);
                rates.Add(rate);
            }
        }
예제 #9
0
        public static void AddVote(Rate item)
        {
            RateDataSource rateDS = new RateDataSource();
            DatasetInfoDataSource datasetInfoDS = new DatasetInfoDataSource();

            rateDS.AddVote(new RateEntry()
            {
                RowKey = Guid.NewGuid().ToString(),
                ItemKey = item.ItemKey,
                PartitionKey = "rates",
                RateDate = item.RateDate,
                RateValue = item.RateValue,
                User = item.User,
            });

            datasetInfoDS.IncrementVote(item.ItemKey, item.RateValue);
        }
 protected static Rate createNewRate(Currency baseCurrency = Currency.USD, DateTime? date = null)
 {
     var rate = new Rate
     {
         BaseCurrency = baseCurrency,
         Date = date ?? DateTime.Today,
         Holiday = false,
         Rates = new Dictionary<Currency, decimal>
         {
             {Currency.USD, 1.0m},
             {Currency.RUB, 52.35m},
             {Currency.EUR, 0.80199m},
             {Currency.GBP, 0.63574m},
             {Currency.JPY, 118.39m}
         }
     };
     return rate;
 }
        private async void MenuItemClickHandler(object sender, EventArgs e)
        {
            ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;

            currentCurrencyLabel.Text = clickedItem.Text;
            string prefCurrency = currentCurrency;

            currentCurrency        = clickedItem.Text;
            currentPriceLabel.Text = "Current\nPrice\n(" + currentCurrency + ")";
            if (tlp.RowCount > 0)
            {
                progressSpinner.Visible = true;
                ShowStatusMessage("Changing currency...\n(Speed depends on server traffic)");
                currencyDropDown.Enabled = false;
                List <CryptoTicker> tickers = await FetchCryptoTicker(currentCurrency);

                Rate rate = await FetchRate(currentCurrency, prefCurrency);

                currencyDropDown.Enabled = true;
                for (int i = 0; i < tlp.RowCount - 1; i++)
                {
                    Control priceControl = tlp.GetControlFromPosition(3, i);
                    Control labelControl = tlp.GetControlFromPosition(1, i);
                    Control fiatControl  = tlp.GetControlFromPosition(2, i);
                    for (int j = 0; j < tickers.Count; j++)
                    {
                        if (tickers[j].name == labelControl.Text)
                        {
                            priceControl.Text = Round(tickers[j].price_cur, 4);
                            fiatControl.Text  = GetCurrencyFromRate(rate, FixDecimalDo(fiatControl.Text).ToString());
                        }
                    }
                }
                CalculateProfit();
                CalculateTotalProfit();
                WriteToFile();
                progressSpinner.Visible = false;
                HideStatusMessage();
            }
        }
예제 #12
0
        public async Task CalculatePrices()
        {
            using (var repository = new EntityRepository(new BaitkmDbContext(new DbContextOptions <BaitkmDbContext>())))
            {
                IEnumerable <Rate>     rates      = repository.Filter <Rate>(r => !r.IsDeleted);
                IEnumerable <Currency> currencies = repository.Filter <Currency>(c => c.Id != 1 && !c.IsDeleted);
                foreach (Currency c in currencies)
                {
                    using (var client = new HttpClient())
                    {
                        try
                        {
                            var response       = client.GetAsync($"https://itfllc.am/api/rate/exchange?from={1}&to={c.RequestId}&value={1}").Result;
                            var responseResult = JsonConvert.DeserializeObject <BaseExchangeResponseModel>(response.Content.ReadAsStringAsync().Result);

                            if (rates.Count() < 1)
                            {
                                repository.Create <Rate>(new Rate
                                {
                                    CurrencyId  = c.Id,
                                    CurrentRate = Math.Round(responseResult.Data.Result, 3, MidpointRounding.ToEven)
                                });
                            }
                            else
                            {
                                Rate rate = await repository.Filter <Rate>(r => r.CurrencyId == c.Id).FirstOrDefaultAsync();

                                rate.CurrentRate = Math.Round(responseResult.Data.Result, 3, MidpointRounding.ToEven);
                                repository.Update(rate);
                            }
                        }
                        catch (Exception e)
                        {
                            throw new Exception(e.Message);
                        }
                    }
                }
                repository.SaveChanges();
            }
        }
예제 #13
0
        public void LoadData()
        {
            // create and execute query
            t = new DataTable();
            t.Columns.Add(new DataColumn("Select", typeof(bool)));
            t.Columns.Add("id");
            t.Columns.Add("Employee");
            t.Columns.Add("Amount");
            t.Columns.Add("Unit");
            t.Columns.Add("Max");
            t.Columns.Add("Created");
            t.Columns.Add(new DataColumn("Delete", typeof(Image)));//1
            t.Columns.Add("userID");

            //  t.Columns.Add(new DataColumn("Delete", typeof(Image)));

            Image delete = new Bitmap(Properties.Resources.Server_Delete_16);

            foreach (Rate c in Rate.List())
            {
                string user = "";
                try { user = GenericCollection.users.Where(r => r.Id == c.UserID).First().Name; } catch { }
                try
                {
                    t.Rows.Add(new object[] { "false", c.Id, user, c.Amount, c.Units, c.Period, c.Created, delete, c.UserID });
                }
                catch (Exception m)
                {
                    MessageBox.Show("" + m.Message);
                    Helper.Exceptions(m.Message, "Viewing customer {each customer list }" + user);
                }
            }

            dtGrid.DataSource         = t;
            dtGrid.AllowUserToAddRows = false;
            // dtGrid.Columns["Amount"].DefaultCellStyle.BackColor = Color.LightGreen;
            // dtGrid.Columns["Unit"].DefaultCellStyle.BackColor = Color.LightGray;
            dtGrid.Columns["id"].Visible     = false;
            dtGrid.Columns["userID"].Visible = false;
        }
예제 #14
0
파일: Program.cs 프로젝트: adriansi7/dotnet
        private static void SearchRoom()
        {
            if (Program.hotels.Count < 1)
            {
                DisplayResult("There are no hotels to search for");
                return;
            }

            string output = "";

            Console.WriteLine("How many days?");
            int days = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("What is your budget?");
            int budget = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("How many rooms?");
            int numberOfRooms = Convert.ToInt32(Console.ReadLine());

            int resultsFound = 0;

            foreach (var hotel in Program.hotels)
            {
                Rate hotelPrice = hotel.GetPriceForNumberOfRooms(numberOfRooms) * days;

                if (hotelPrice.Amount <= budget)
                {
                    output += "Hotel " + hotel.Name + " in " + hotel.City + " with a total price of " + hotelPrice.Amount + " " + hotelPrice.Currency + System.Environment.NewLine;
                    resultsFound++;
                }
            }

            if (resultsFound == 0)
            {
                output += "No rooms found for the search criteria";
            }


            DisplayResult(output);
        }
예제 #15
0
        public ActionResult Create(Rate rate)
        {
            //SelectList operators = new SelectList(db.Operators, "Id", "Name");
            //SelectList rateTypes = new SelectList(db.RateTypes, "Id", "Name");

            //ViewData["Operator"] = operators;
            //ViewData["RateType"] = rateTypes;
            //Param item = rate.Params.Find(x => x.ParamType.ParamDataType == ParamDataType.Bool);
            //if (!item.Equals(null))
            //{

            //}

            if (ModelState.IsValid)
            {
                db.Rates.Add(rate);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(rate));
        }
예제 #16
0
        public void Init(Rate r)
        {
            this.comboTyp.SelectedItem = r.Type;
            this.txtBoxRef.Text        = r.Name;
            this.txtTer.Text           = r.Duration.ToString();
            this.comboTer.SelectedItem = r.TimeUnit;
            String CurCode = (CachedData.CachedCurrencyDic.ContainsKey(r.IdCcy)
                                                                ? CachedData.CachedCurrencyDic[r.IdCcy].Code
                                                                : "");

            this.comboCur.SelectedItem = CurCode;
            //this.comboMar.SelectedItem = r.FixingPlace;

            this.txtBoxFda.Text        = r.SettlementDays.ToString();
            this.comboBas.SelectedItem = (CachedData.CachedDayCounterDic.ContainsKey(r.BasisId)
                                                                ? CachedData.CachedDayCounterDic[r.BasisId].Name
                                                                : "");
            this.comboMod.SelectedItem = r.Compounding;
            this.comboFre.SelectedItem = r.Frequency;
            this.comboBus.SelectedItem = r.BusinessDayConvention.ToString();
            this.textBoxSpread.Text    = r.Spread.ToString();
        }
예제 #17
0
        private static async Task <List <Rate> > ReadRatingsAsync(DbDataReader reader)
        {
            var ratings = new List <Rate>();

            await using (reader)
            {
                while (await reader.ReadAsync())
                {
                    var rate = new Rate
                    {
                        Id     = reader.GetInt32(0),
                        Rating = reader.GetInt32(1),
                        UserId = reader.GetInt32(2),
                        BookId = reader.GetInt32(3),
                    };

                    ratings.Add(rate);
                }
            }

            return(ratings);
        }
예제 #18
0
        public void Save(Rate rate)
        {
            List <Rate> dbRecords      = _db.Rate.ToList();
            var         equalItemIndex = dbRecords.FindIndex(
                item => (item.Date == rate.Date &&
                         item.Code == rate.Code &&
                         item.Value == rate.Value &&
                         item.ServiceId == rate.ServiceId));

            if (equalItemIndex != -1)
            {
                dbRecords[equalItemIndex].Code      = rate.Code;
                dbRecords[equalItemIndex].Date      = rate.Date;
                dbRecords[equalItemIndex].Value     = rate.Value;
                dbRecords[equalItemIndex].ServiceId = rate.ServiceId;
            }
            else
            {
                _db.Rate.Add(rate);
            }
            _db.SaveChanges();
        }
예제 #19
0
        static void Main(string[] args)
        {
            string      XMLText = File.ReadAllText(FILENAME);
            List <Rate> myRates = new List <Rate>();

            using (XmlReader reader = XmlReader.Create(new StringReader(XMLText)))
            {
                while (!reader.EOF)
                {
                    if (reader.Name != "rate")
                    {
                        reader.ReadToFollowing("rate");
                    }
                    if (!reader.EOF)
                    {
                        XElement xRate = (XElement)XElement.ReadFrom(reader);
                        Rate     rate  = new Rate();
                        rate.Category = xRate.Attribute("category").Value;      //text of current Node   : Catagory
                        DateTime myDate;
                        if (DateTime.TryParse(xRate.Attribute("date").Value, out myDate))
                        {
                            rate.Date = myDate;
                        }
                        Console.WriteLine("value Element=" + xRate.Element("value").Value);     //test: reader.Value does not the data
                        decimal myValue;
                        if (Decimal.TryParse(xRate.Element("value").Value, out myValue))
                        {
                            rate.Value = myValue;
                        }
                        else
                        {
                            rate.Value = -1;       // this is what happens because reader.value == ""
                        }
                        //return collection with result
                        myRates.Add(rate);
                    }
                }
            }
        }
예제 #20
0
        /// <summary>
        /// Method, that fills the US-Dollar Rate List with data from server
        /// </summary>
        private void FillUsdRateList()
        {
            string response = "";

            try
            {
                response = CAC.StartClient("OE<EOF>");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Der opstod en fejl under forsøg på at hente valutalister\n" + ex.ToString(), "Hent valutalister", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            if (response.Length >= 1)
            {
                UsdRateList = new List <Rate>();
                string[] responseData = response.Split(';');
                if (responseData.Count() > 2 && responseData.Count() % 2 != 0)
                {
                    responseData = responseData.Where(w => w != responseData[responseData.Count() - 1]).ToArray();

                    for (int i = 0; i < responseData.Length; i++)
                    {
                        Rate tempRate = new Rate(responseData[i], responseData[i + 1]);
                        UsdRateList.Add(tempRate);
                        i++;
                        i++;
                    }
                }
                else if (responseData.Count() > 2 && responseData.Count() % 2 == 0)
                {
                    for (int i = 0; i < responseData.Length; i++)
                    {
                        Rate tempRate = new Rate(responseData[i], responseData[i + 1]);
                        UsdRateList.Add(tempRate);
                        i++;
                    }
                }
            }
        }
예제 #21
0
        public JSONResult <string> UpdateRate(RateJSON rate)
        {
            try
            {
                var customer = AuthoriseRequest();

                Rate entityRate = rate.ToRate();
                m_service.UpdateRate(customer.Name, entityRate);

                return(new JSONResult <string>()
                {
                    Success = true, Result = entityRate.ID
                });
            }
            catch (Exception excp)
            {
                return(new JSONResult <string>()
                {
                    Success = false, Error = excp.Message
                });
            }
        }
예제 #22
0
        public async Task <ActionResult <Rate> > CreateRate(RateVm rateVm)
        {
            var x = await _context.Rates.Where(x => x.ProductId == rateVm.ProductId).FirstOrDefaultAsync();

            var nRating = new Rate
            {
                Star = rateVm.Star,

                UserId    = rateVm.UserId,
                ProductId = rateVm.ProductId
            };

            _context.Rates.Add(nRating);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetAllRate",
                                   new { id = nRating.Id },
                                   new RateVm
            {
                Star = nRating.Star,
            }));
        }
예제 #23
0
        public EditRateForm(Carrier carrier, Rate rateToEdit)
        {
            InitializeComponent();
            _carrier    = carrier;
            _rateToEdit = rateToEdit;

            _originalOriginRegionShortName      = _rateToEdit.OriginRegionShortName;
            _originalOriginDestinationShortName = _rateToEdit.DestinationRegionShortName;

            costTextBox.KeyPress += Utility.TextBox_KeyPress_Filte_Positive_Number_Only;

            foreach (var item in RMA.Model.Region.Store.Items)
            {
                originComboBox.Items.Add(item.ShortName);
                destinationComboBox.Items.Add(item.ShortName);
            }

            originComboBox.SelectedItem      = _rateToEdit.OriginRegionShortName;
            destinationComboBox.SelectedItem = _rateToEdit.DestinationRegionShortName;


            typeComboBox.Items.Add(RateType.Flat.ToString());
            typeComboBox.Items.Add(RateType.Increase.ToString());

            if (_rateToEdit is FlatRate)
            {
                typeComboBox.SelectedIndex = 0;
                costTextBox.Text           = (_rateToEdit as FlatRate).Totalcost.ToString();
            }
            else if (_rateToEdit is IncreaseRate)
            {
                typeComboBox.SelectedIndex = 1;
                costTextBox.Text           = (_rateToEdit as IncreaseRate).CostPerMile.ToString();
            }
            else
            {
                throw new Exception("fatal error");
            }
        }
예제 #24
0
        public void Execute(RateDto request, int id)
        {
            var userPost = _context.Rates.Where(x => x.IdPost == request.IdPost).Select(x => x.IdUser);

            if (request.Number > 5)
            {
                throw new ArgumentException("Number must be under 6");
            }
            if (userPost.Contains(_actor.Id))
            {
                throw new ArgumentException("Voted");
            }
            var rate = new Rate
            {
                Number = request.Number,
                IdUser = _actor.Id,
                IdPost = id
            };

            _context.Rates.Add(rate);
            _context.SaveChanges();
        }
예제 #25
0
    private double ScoreBarUserByUser(Bar bar)
    {
        var    users = UserTagsMatrix.GetSimilarUsers(5, this, Engine.Users);
        int    cnt   = 0;
        double score = 0;

        for (int i = 0; i < 5; i++)
        {
            User user = Engine.GetUserByUserID(users[i]);
            Rate rate = user.GetRateFromUser(bar);
            if (rate != null)
            {
                cnt++;
                score += user.CalculateScoreForBar(bar, rate);
            }
        }
        if (cnt > 0)
        {
            return(score / cnt);
        }
        return(0);
    }
예제 #26
0
        //Parses the per-second rate for a resource and converts it into a Rate object
        public static Rate ParseRate(string input)
        {
            Rate rate = new Rate();

            if (input.Contains('+'))
            {
                rate.Positive = true;
            }
            else if (input.Contains('-'))
            {
                rate.Positive = false;
            }
            else
            {
                rate.Positive = null;
            }
            if (rate.Positive != null)
            {
                rate.Delta = double.Parse(rateRegex.Match(input).ToString());
            }
            return(rate);
        }
예제 #27
0
        public static void Insert(Rate rate)
        {
            var sscsb = new SqlConnectionStringBuilder(Helper.GetConnectionString())
            {
                ConnectTimeout = 5
            };

            using (var sqlConnection = new SqlConnection(sscsb.ConnectionString))
            {
                using (var cmd = sqlConnection.CreateCommand())
                {
                    sqlConnection.Open();
                    cmd.CommandText = @"INSERT INTO Rates (Amount, StartDate, Service)
                    VALUES (@Amount, @StartDate, @Service)";
                    cmd.Parameters.Add("@Amount", SqlDbType.Decimal).Value     = rate.Amount;
                    cmd.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = rate.StartDate;
                    cmd.Parameters.Add("@Service", SqlDbType.Int).Value        = rate.Service.Id;

                    cmd.ExecuteReader();
                }
            }
        }
예제 #28
0
        private void ReadSettings(bool bindControl = true)
        {
            Algorithm   = BotSetting.AlgorithmList.Where(x => x.Id == Settings.Default.algorithm).First();
            CandleType  = new CandleType(Settings.Default.candleType);
            Fee         = Settings.Default.fee;
            TradeRate   = Settings.Default.tradeRate;
            Coin        = BotSetting.CoinList.Where(x => x.Ticker.Equals(Settings.Default.coin)).FirstOrDefault();
            Interval    = Convert.ToInt32(Settings.Default.interval);
            Rate        = Convert.ToDouble(Settings.Default.rate);
            CandleCount = Convert.ToInt32(Settings.Default.candleCount);

            cmbAlgorithm.SelectedItem = Algorithm;
            cmbCandle.SelectedItem    = CandleType;
            txtFee.Text          = Fee.ToString();
            txtTradeRate.Text    = TradeRate.ToString();
            cmbCoin.SelectedItem = Coin;
            txtInterval.Text     = Interval.ToString();
            txtRate.Text         = Rate.ToString();


            txtCandleCount.Text = Fee.ToString();
        }
예제 #29
0
        public static Booking CreateNew(
            string accountNumber,
            DateTime arriveDate,
            DateTime departureDate,
            bool isComplimentary,
            Rate rate,
            int allotmentQty,
            decimal room,
            decimal service,
            decimal tax,
            decimal extraBed,
            decimal extraBedService,
            decimal extraBedTax,
            decimal lunch,
            decimal dinner,
            decimal discount,
            decimal abf)
        {
            var obj = new Booking
            {
                AccountNumber   = accountNumber,
                ArriveDate      = arriveDate,
                DepartureDate   = departureDate,
                IsComplimentary = isComplimentary,
                Rate            = rate,
                AllotmentQty    = allotmentQty,
                Service         = service,
                Tax             = tax,
                ExtraBed        = extraBed,
                ExtraBedService = extraBedService,
                ExtraBedTax     = extraBedTax,
                Lunch           = lunch,
                Dinner          = dinner,
                Discount        = discount,
                Abf             = abf
            };

            return(obj);
        }
      public async Task <IActionResult> PutAsync(int id, [FromBody] Rate resource)
      {          // if Model is invalid show error message by using ModelState
          if (!ModelState.IsValid)
          {
              return(BadRequest(ModelState.GetErrorMessages()));
          }
          //get data form EmployeeAttendenceResource by id using AutoMapper
          //var rate=_mapper.Map<SaveRateResource,Rate>(resource);
          //update data by id
          var result = await _rateService.UpdateAsync(id, resource);

          //if updated data is null
          if (result == null)
          {
              return(BadRequest(result));
          }
          //get result data from SaveEmployeeResource after update data using automapper
          var rateResource = _mapper.Map <Rate, RateResource>(result.Rate);

          //show data
          return(Ok(rateResource));
      }
예제 #31
0
    private double ScoreBarItemByItem(Bar bar)
    {
        var    bars  = BarsTagsMatrix.GetSimilarBars(5, bar, Engine.Bars);
        int    cnt   = 0;
        double score = 0;

        for (int i = 0; i < 5; i++)
        {
            Bar  newBar = Engine.GetBarByBarID(bars[i]);
            Rate rate   = GetRateFromUser(newBar);
            if (rate != null)
            {
                cnt++;
                score += CalculateScoreForBar(newBar, rate);
            }
        }
        if (cnt > 0)
        {
            return(score / cnt);
        }
        return(0);
    }
        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return(false);
            }

            if (obj == this)
            {
                return(true);
            }

            return(obj is V1PaymentSurcharge other &&
                   ((Name == null && other.Name == null) || (Name?.Equals(other.Name) == true)) &&
                   ((AppliedMoney == null && other.AppliedMoney == null) || (AppliedMoney?.Equals(other.AppliedMoney) == true)) &&
                   ((Rate == null && other.Rate == null) || (Rate?.Equals(other.Rate) == true)) &&
                   ((AmountMoney == null && other.AmountMoney == null) || (AmountMoney?.Equals(other.AmountMoney) == true)) &&
                   ((Type == null && other.Type == null) || (Type?.Equals(other.Type) == true)) &&
                   ((Taxable == null && other.Taxable == null) || (Taxable?.Equals(other.Taxable) == true)) &&
                   ((Taxes == null && other.Taxes == null) || (Taxes?.Equals(other.Taxes) == true)) &&
                   ((SurchargeId == null && other.SurchargeId == null) || (SurchargeId?.Equals(other.SurchargeId) == true)));
        }
예제 #33
0
        public IHttpActionResult PostRate(Rate rate)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Customer customer = db.Customer.Find(rate.CustomerId);
            Product  product  = db.Products.Find(rate.ProductId);

            if (customer == null && product == null)
            {
                return(BadRequest("product or customer deos not exist"));
            }

            db.Rates.Add(rate);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException)
            {
                if (db.Rates.Where(i => i.CustomerId == rate.CustomerId && i.ProductId == rate.ProductId).FirstOrDefault() != null)
                {
                    //return Conflict();
                    return(ResponseMessage(Request.CreateResponse(HttpStatusCode.Conflict, "rate already Exist")));
                }
                else
                {
                    throw;
                }
            }
            var addMess = new { message = "Success", data = db.Rates.Where(i => i.ProductId == rate.ProductId && i.CustomerId == rate.CustomerId) };

            return(Ok(addMess));
            //return CreatedAtRoute("DefaultApi", new { id = rate.ProductId }, rate);
        }
예제 #34
0
        static void Main(string[] args)
        {
            BillingSystem          BS  = new BillingSystem();
            AutomaticPhoneExchange ATE = new AutomaticPhoneExchange(BS);
            var lite   = new Rate("Lite", 4, 2);
            var short2 = new Rate("Short", 0, 6);

            ATE.AddNewRate(lite);
            ATE.AddNewRate(short2);
            Terminal t1 = ATE.ConcludeContract("Mihail", "01", 20, lite);
            Terminal t2 = ATE.ConcludeContract("Igor", "02", 30, lite);
            Terminal t3 = ATE.ConcludeContract("Oksana", "03", 25, short2);

            t1.TurnOn();
            t2.TurnOn();
            t3.TurnOn();
            t1.Call("02");
            Thread.Sleep(2000);
            t3.Call("01");
            Thread.Sleep(2000);
            t2.TurnOff();
            Thread.Sleep(2000);
            t1.Call("02");
            Thread.Sleep(2000);
            t1.Call("03");
            Thread.Sleep(2000);
            t1.EndCall();
            Thread.Sleep(2000);
            t1.GetCallsHistory();
            Thread.Sleep(2000);
            t1.GetRateInfo();
            Thread.Sleep(2000);
            t1.ChangeRate("short");
            Thread.Sleep(2000);
            t1.GetCallsHistoryByCost(4);

            Console.ReadLine();
        }
        public void GetRateTest_ChecksTheRateForTheGivenCurrencyPairAfterSubmittingDepthLevels_ChecksTheRateReturnedToVerify()
        {
            MarketController marketController = (MarketController)_applicationContext["MarketController"];
            BBOMemoryImage   bboMemoryImage   = (BBOMemoryImage)_applicationContext["BBOMemoryImage"];

            DepthLevel bidLevel1 = new DepthLevel(new Price(491));
            DepthLevel bidLevel2 = new DepthLevel(new Price(492));
            DepthLevel bidLevel3 = new DepthLevel(new Price(493));

            DepthLevel askLevel1 = new DepthLevel(new Price(494));
            DepthLevel askLevel2 = new DepthLevel(new Price(495));
            DepthLevel askLevel3 = new DepthLevel(new Price(496));

            bboMemoryImage.OnBBOArrived("XBT/USD", bidLevel1, askLevel1);
            IHttpActionResult httpActionResult = marketController.GetRate("XBT/USD");

            OkNegotiatedContentResult <Rate> returnedOkRate = (OkNegotiatedContentResult <Rate>)httpActionResult;
            Rate rate = returnedOkRate.Content;

            Assert.AreEqual("XBT/USD", rate.CurrencyPair);
            Assert.AreEqual(492.5, rate.RateValue); // MidPoint of bidLevel1 = 491 & askLevel1 = 494

            bboMemoryImage.OnBBOArrived("XBT/USD", bidLevel2, askLevel2);
            httpActionResult = marketController.GetRate("XBT/USD");
            returnedOkRate   = (OkNegotiatedContentResult <Rate>)httpActionResult;
            rate             = returnedOkRate.Content;

            Assert.AreEqual("XBT/USD", rate.CurrencyPair);
            Assert.AreEqual(493.5, rate.RateValue); // MidPoint of bidLevel2 = 492 & askLevel2 = 495

            bboMemoryImage.OnBBOArrived("XBT/USD", bidLevel3, askLevel3);
            httpActionResult = marketController.GetRate("XBT/USD");
            returnedOkRate   = (OkNegotiatedContentResult <Rate>)httpActionResult;
            rate             = returnedOkRate.Content;

            Assert.AreEqual("XBT/USD", rate.CurrencyPair);
            Assert.AreEqual(494.5, rate.RateValue); // MidPoint of bidLevel3 = 493 & askLevel3 = 496
        }
예제 #36
0
    private void Start()
    {
        rb        = GetComponent <Rigidbody>();
        col       = GetComponent <Collider>();
        mesh      = GetComponent <MeshFilter>();
        colliding = col.enabled;

        FiringMode = (Rate)Mathf.Clamp(
            Mathf.RoundToInt(Random.Range(-0.5f, 2.5f)),
            0,
            2
            );

        if (FiringMode == Rate.Semi)
        {
            this.gameObject.name = "Pistol";
            mesh.mesh            = gunMeshes[0];
            damage   = Random.Range(3, 6);
            fireRate = Random.Range(0.2f, 0.8f);
        }
        else if (FiringMode == Rate.Auto)
        {
            this.gameObject.name = "Uzi";
            mesh.mesh            = gunMeshes[1];
            damage   = Random.Range(1, 3);
            fireRate = Random.Range(0.1f, 0.3f);
        }
        else if (FiringMode == Rate.Burst)
        {
            this.gameObject.name = "Shotgun";
            mesh.mesh            = gunMeshes[2];
            damage      = Random.Range(1, 3);
            fireRate    = Random.Range(2, 4);
            projectiles = Random.Range(4, 8);
        }

        Invoke("StopTheErrors", 1.0f);
    }
예제 #37
0
        public async Task <IActionResult> add(int book_id, int star, string review)
        {
            try {
                Book book = await _bookRepository.Get(book_id);

                if (book == null)
                {
                    return(NotFound(new Respone(404, "Not Found", null)));
                }

                var  username = User.FindFirst(ClaimTypes.NameIdentifier).Value;
                User user     = await _userRepository.FindByUsername(username);

                if (user == null)
                {
                    return(NotFound(new Respone(404, "Not Found", null)));
                }

                if (await _rateRepository.isRated(book_id, user.user_id))
                {
                    return(BadRequest(new Respone(400, "Rated", null)));
                }

                Rate rate = new Rate
                {
                    book_id = book.book_id,
                    star    = star,
                    review  = review,
                    user_id = user.user_id
                };

                await _rateRepository.Add(rate);

                return(Ok(new Respone(200, "ok", null)));
            } catch (Exception e) {
                return(BadRequest(new Respone(400, "Failed", null)));
            }
        }
예제 #38
0
        public ActionResult SubmitStar(string rateStar, string param)
        {
            if (ModelState.IsValid)
            {
                //Guid paramId = new Guid(id);

                decimal backlinkRate;
                if (!rateStar.Any(char.IsDigit))
                {
                    backlinkRate = ReturnRate(rateStar);
                }
                else
                {
                    backlinkRate = Convert.ToDecimal(rateStar.Replace('.', '/'));
                }

                Guid textId   = new Guid("4c7ef240-8d78-4bdc-b332-3303608c9c7a");
                Text backLink = db.Texts.Find(textId);
                backLink.AverageRate = (backLink.AverageRate + backlinkRate) / 2;

                Rate rate = new Rate();
                rate.Id           = Guid.NewGuid();
                rate.EntityId     = textId;
                rate.CreationDate = DateTime.Now;
                rate.IsDeleted    = false;
                rate.IP           = Request.UserHostAddress;
                rate.StarRate     = backlinkRate;
                rate.Type         = 1;
                db.Rates.Add(rate);
                db.SaveChanges();

                return(Json("true", JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json("false", JsonRequestBehavior.AllowGet));
            }
        }
예제 #39
0
        public async void CreateDataAr()
        {
            var items = await App.Database.GetItemsAsync();

            var item = items.Where(x => x.lang == "ar").FirstOrDefault();

            if (item != null)
            {
                Rate rate = new Rate
                {
                    ID     = item.ID,
                    q1     = q1.Text,
                    q2     = q2.Text,
                    q3     = q3.Text,
                    q4     = q4.Text,
                    left   = left.Text,
                    center = center.Text,
                    right  = right.Text,
                    lang   = "ar"
                };
                var res = await App.Database.UpdateItems(rate);
            }
            else
            {
                Rate rate = new Rate
                {
                    q1     = q1.Text,
                    q2     = q2.Text,
                    q3     = q3.Text,
                    q4     = q4.Text,
                    left   = left.Text,
                    center = center.Text,
                    right  = right.Text,
                    lang   = "ar"
                };
                var res = await App.Database.SaveItemAsync(rate);
            }
        }
예제 #40
0
        public void Execute(RateDto request, int id)
        {
            var userRateArticle = _context.Rates.Where(x => x.ArticleId == request.ArticleId).Select(s => s.UserId);


            if (request.RateNumber > 5)
            {
                throw new ArgumentException("Number must be under 6");
            }
            if (userRateArticle.Contains(_actor.Id))
            {
                throw new ArgumentException("You already vote");
            }
            var rate = new Rate
            {
                RateNumber = request.RateNumber,
                UserId     = _actor.Id,
                ArticleId  = id
            };

            _context.Rates.Add(rate);
            _context.SaveChanges();
        }
예제 #41
0
        private void ParseXml(string url)
        {
            Stream xmlStream = GetStream(url);
            XmlReader xmlReader = XmlReader.Create(xmlStream);

            xmlReader.Read(); //move to first element in xml
            xmlReader.Read(); //move to whitespace
            xmlReader.Read(); //move to "Rates"
            xmlReader.Read(); //reads "Rates" move to whitespace
            while (xmlReader.Read()) //read whitespace and move to "Rate"
            {
                if (xmlReader.Name == "Rates") { break; }
                Rate rate = new Rate(xmlReader);
                if (timeSeries.ContainsKey(rate.Symbol))
                {
                    timeSeries[rate.Symbol].Add(rate.Data[0]);
                }
                else
                {
                    timeSeries.Add(rate.Symbol, new List<RateData>() { rate.Data[0] });
                }
            }
        }
예제 #42
0
 public ICollection<Rate> Rates()
 {
     Console.WriteLine("\r\n{0} - Getting Rates", DateTime.Now);
     ICollection<Rate> Rate = new List<Rate>();
     using (RatesDBContext context = new RatesDBContext())
     {
         foreach (Rate rate in context.Rates)
         {
             Rate r = new Rate();
             r.RateID = rate.RateID;
             r.RateDescription = rate.RateDescription;
             r.Value = rate.Value;
             Rate.Add(r);
             Console.WriteLine("Rate Value : {0}", r.Value.ToString());
         }
         return Rate;
     }
 }
예제 #43
0
        public bool UpdateRate(Rate rate)
        {
            Console.WriteLine("\r\n{0} - Updating Rate", DateTime.Now);
            using (RatesDBContext context = new RatesDBContext())
            {
                Rate rateRecord = context.Rates.Where(r => r.RateID == rate.RateID).FirstOrDefault<Rate>();

                if (rateRecord != null)
                {
                    rateRecord.RateDescription = rate.RateDescription;
                    rateRecord.Value = rate.Value;
                    context.SaveChanges();
                    Console.WriteLine("{0} Rate Value : {1}", rate.RateDescription, rate.Value.ToString());
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
 private async Task<int> SaveOneRateAsync(IDbConnection connection, Rate rate)
 {
     try
     {
         return await connection.ExecuteAsync(
             "insert into Rates (BaseCurrency,Date,Holiday,SerializedRates) values (@BaseCurrency,@Date,@Holiday,@SerializedRates)",
             RateDatabaseModel.FromRate(rate));
     }
     catch (Exception ex)
     {
         _logger.Error(ex, "Failed to insert new exchange rate to database. Rate: {0}", JsonConvert.SerializeObject(rate));
         /*
            if repository can't save one rate - it will try to save other rates.
            a new rate can't be inserted, if the same data already inserted in other session
         */
     }
     return 0;
 }
예제 #45
0
 public void Update(Rate rate)
 {
     this.rates.Save();
 }
예제 #46
0
 public void Create(Rate rate)
 {
     this.rates.Add(rate);
     this.rates.Save();
 }
 public Snapshot(Timestamp time, decimal val, Rate r)
 {
     Time = time;
     Value = val;
     rateOfChange = r;
 }
 public void Delete(Rate rate)
 {
     StaffingResource.DeleteRate(rate);
 }
예제 #49
0
파일: RateBlock.cs 프로젝트: andgein/uLearn
		public void RateSlide(Rate rate)
		{
			buttons[rate].Click();
		}
예제 #50
0
파일: Rate.cs 프로젝트: anagri/sharekhan
 public bool Equals(Rate other)
 {
     if (ReferenceEquals(null, other)) return false;
     if (ReferenceEquals(this, other)) return true;
     return other.Value == Value;
 }
예제 #51
0
 protected virtual Booking ActuallyCreateBooking(DateTime date, Rate rate, List<AdditionalEquipment> eqs, string contactId, List<Room> rooms, Product product, IDocumentSession session)
 {
     var booking = string.IsNullOrEmpty(BookingId) ? new Booking() : session.Load<Booking>(BookingId);
     booking.Date = date == DateTime.MinValue ? Date : date;
     booking.MainContactId = contactId;
     booking.StartTime = TimePart.FromString(StartTime);
     booking.Length = TimePart.Duration(StartTime, EndTime);
     booking.Rooms = rooms;
     booking.OneOffCharge = OneOffCharge;
     booking.Rate = rate;
     booking.Product = product;
     booking.Notes = new List<Note>
                         {
                             new Note
                                 {
                                     Content = Notes
                                 }
                         };
     booking.AdditionalEquipment = eqs;
     return booking;
 }
예제 #52
0
            /// <summary>
            /// Initializes a new instance of the <see cref="Address"/> class.
            /// </summary>
            /// <param name="f_id">The f_id.</param>
            /// <param name="f_firstName">Name of the f_first.</param>
            /// <param name="f_lastName">Name of the f_last.</param>
            /// <param name="f_address1">The f_address1.</param>
            /// <param name="f_address2">The f_address2.</param>
            /// <param name="f_city">The f_city.</param>
            /// <param name="f_state">The f_state.</param>
            /// <param name="f_zip">The f_zip.</param>
            /// <param name="f_country">The f_country.</param>
            /// <param name="f_homePhone">The f_home phone.</param>
            /// <param name="f_workPhone">The f_work phone.</param>
            /// <param name="f_email">The f_email.</param>
            /// <param name="f_specialInstructions">The f_special instructions.</param>
            /// <param name="f_comments">The f_comments.</param>
            /// <param name="f_sendshipmentupdates">if set to <c>true</c> [f_sendshipmentupdates].</param>
            /// <param name="f_emailAds">if set to <c>true</c> [f_email ads].</param>
            /// <param name="f_rate">The f_rate.</param>
            /// <param name="f_dateCreated">The f_date created.</param>
            /// <param name="f_company">The f_company.</param>
            public Address(
				Guid f_id, string f_firstName, string f_lastName, string f_address1, string f_address2, string f_city,
				string f_state, string f_zip, string f_country, string f_homePhone, string f_workPhone, string f_email, string f_specialInstructions,
				string f_comments, bool f_sendshipmentupdates, bool f_emailAds, Rate f_rate, DateTime f_dateCreated, string f_company )
            {
                this.Rates = new List<Rate>();
                EstShippingCost = 0;
                Id = f_id;
                FirstName = f_firstName;
                LastName = f_lastName;
                Address1 = f_address1;
                Address2 = f_address2;
                City = f_city;
                State = f_state;
                Zip = f_zip;
                Country = f_country;
                HomePhone = f_homePhone;
                WorkPhone = f_workPhone;
                Email = f_email;
                SpecialInstructions = f_specialInstructions;
                Comments = f_comments;
                SendShipmentUpdates = f_sendshipmentupdates;
                EmailAds = f_emailAds;
                Rate = f_rate;
                DateCreated = f_dateCreated;
                Company = f_company;
            }
 public Rate AdjustRate(Rate rate)
 {
     rate.TotalCharges = rate.TotalCharges * _amount;
     return rate;
 }
예제 #54
0
파일: Form1.cs 프로젝트: duwke/SharpTemp
 private void SetAlarm(int index, double? temp)
 {
     if (this.InvokeRequired)
     {
         MyHttpServer.AlarmChangeHandler stc = new MyHttpServer.AlarmChangeHandler(SetAlarm);
         this.Invoke(stc, new object[] { index, temp });
     }
     else
     {
         if (index == 0)
         {
             _t0AlarmTemp = temp;
             if (temp.HasValue)
             {
                 btnAlarm1.BackColor = Color.Red;
                 if (_lastT0 < _t0AlarmTemp)
                 {
                     _t0Rate = Rate.RISING;
                 }
                 else
                 {
                     _t0Rate = Rate.FALLING;
                 }
                 SharpTemp.Properties.Settings.Default.T0Alarm = temp.Value;
                 textBox1.Text = temp.Value.ToString();
             }
             else
             {
                 btnAlarm1.BackColor = Color.White;
                 textBox1.Text = "";
             }
         }
         else if (index == 1)
         {
             _t1AlarmTemp = temp;
             if (temp.HasValue)
             {
                 btnAlarm2.BackColor = Color.Red;
                 if (_lastT1 < _t1AlarmTemp)
                 {
                     _t1Rate = Rate.RISING;
                 }
                 else
                 {
                     _t1Rate = Rate.FALLING;
                 }
                 SharpTemp.Properties.Settings.Default.T1Alarm = temp.Value;
                 textBox2.Text = temp.Value.ToString();
             }
             else
             {
                 btnAlarm2.BackColor = Color.White;
                 textBox2.Text = "";
             }
         }
     }
 }
 private string GenerateRateKey(Rate rate)
 {
     return GenerateRateKey(rate.BaseCurrency, rate.Date);
 }
 public void Update(Timestamp t, Rate r)
 {
     Sanitize(t);
     var value = Latest.Project(t - Latest.Time);
     Update(t, value, r);
 }
예제 #57
0
        public ActionResult Rate(int eventid)
        {
            //int currentId = CurrentUser.ID;
            //var agenda = service.GetMyAgenda(eventid, currentId);// CurrentUser.ID);
            var sessions = service.GetSessions(eventid);
            var timeSlots = service.GetTimeslots(eventid);
            //ViewBag.Agenda = agenda;
            ViewBag.Sessions = sessions;
            ViewBag.TimeSlots = timeSlots;
            Rate model = new Rate();
            //List<int> timeSlotIDs = new List<int> { 22, 23, 24, 26, 27, 28, 29 };
            foreach (var timeSlot in timeSlots)
            {
                RateSession rs = new RateSession
                {
                    TimeSlotID = timeSlot.ID
                };
                model.RateSessions.Add(rs);
            }

            return View(model);
        }
예제 #58
0
파일: RateBlock.cs 프로젝트: andgein/uLearn
		public bool IsActive(Rate rate)
		{
			return buttons[rate].isActive;
		}
 public void Update(Timestamp t, decimal value, Rate r)
 {
     Sanitize(t, false);
     Moments.Add(t, new Snapshot(t, value, r));
     OnPropertyChanged("Latest");
 }
예제 #60
0
 public ImportAction(Timestamp t, Rate rate, Resource r)
 {
     At = t;
     Rate = rate;
     Resource = r;
 }