public int CalculateDamage(int power) { double damage = (((2.0 * User.Stats.Level / 5.0) + 2.0) * power * User.Stats.Atk / Target.Stats.Def / 50.0) + 2.0; // Critical hits add 1.5x damage if (IsCritical) { damage *= 1.5; } // Randomize the damage between 0.85x and 100x damage *= NumberUtilities.GetRandomInteger(85, 100) / 100.0; // Apply STAB damage *= StabMultiplier; // Apply type matchup bonus damage *= MatchupMultiplier; return((int)damage); }
public async Task <IActionResult> Create(CategoryViewModel model) { if (ModelState.IsValid) { var vm = new Category { Id = NumberUtilities.GetUniqueNumber(), Name = model.Category.Name, ParentId = model.Category.ParentId }; await _context.Categories.AddAsync(vm); if (model.Category.ParentId != null) { var cat = await _context.Categories.AsNoTracking().FirstOrDefaultAsync(x => x.Id == model.Category.ParentId); cat.IsParent = true; } await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View()); }
private async void CalculatePrimes_Click(object sender, RoutedEventArgs e) { int min = int.Parse(txtPrimeBegin.Text); int max = int.Parse(txtPrimeEnd.Text); this.ViewModel.PrimeNumbers = await NumberUtilities.CalculatePrimesAsync(min, max); }
private async Task _generateOpponentAsync() { // Pick a random species from the same zone as the player's gotchi. List <ISpecies> species_list = new List <ISpecies>(); foreach (ISpeciesZoneInfo zone in await database.GetZonesAsync(await database.GetSpeciesAsync(player1.Gotchi.Gotchi.SpeciesId))) { species_list.AddRange((await database.GetSpeciesAsync(zone.Zone)).Where(x => !x.Status.IsExinct)); } player2 = new PlayerState(); if (species_list.Count() > 0) { player2.Gotchi = await database.GenerateGotchiAsync(new GotchiGenerationParameters { Base = player1.Gotchi.Gotchi, Species = species_list[NumberUtilities.GetRandomInteger(species_list.Count())], MinLevel = player1.Gotchi.Stats.Level - 3, MaxLevel = player1.Gotchi.Stats.Level + 3, GenerateMoveset = true, GenerateStats = true }); } // Set the opponent. if (player2.Gotchi != null) { player2.Gotchi.Gotchi.OwnerId = WildGotchiUserId; player2.Gotchi.Gotchi.Id = WildGotchiId; } }
static void Main(string[] args) { #region Number to Words var numberToWords = NumberUtilities.ToWords(1234); #endregion #region Twilio Sms SmsUtilities.ConfigureService(container => { container.Add("twilio", new TwilioSmsService("+10000000000", "sid", "token")); }); var text = "Test Sms!"; SmsUtilities.SendSms(text, "+8801815000000", "t"); #endregion #region Encription/Decryption SecurityUtilities.ConfigureOptions(x => { x.Key = ""; x.Secret = ""; }); string str = "Normal String"; string encryptedString = str.Encrypt(); #endregion #region Dynamic Search var users = new List <User> { new User { Id = 1, Name = "A" }, new User { Id = 2, Name = "B" }, new User { Id = 3, Name = "B" }, }.AsQueryable(); var searchOptions = new SearchOptions { Search = new string[] { "name eq B" } }; var result = users.ApplySearch(searchOptions).ToList(); #endregion Console.ReadLine(); }
public void ThenResultIs785Minutes() { string result = null; Given(new SimpleTestStep("desc of given", () => Console.WriteLine("This is Given."))); When(new SimpleTestStep("desc of when", () => result = NumberUtilities.ConvertTimeToMinutes("13:05"))); Then(new SimpleTestStep("", () => Assert.That(result, Is.EqualTo("785")))); }
public void Test_SortNumbers1() { int[] inputs = { -38, 190, 180, 170, 160, 150, 140, 130, 120, 110 }; int[] output = NumberUtilities.SortArray(inputs); string result = String.Join(" ", output); Trace.Write("'" + result + "'"); Assert.That(result, Is.EqualTo("-38 110 120 130 140 150 160 170 180 190")); }
public void Test_AddingTimes() { string input1 = "00:01:00"; string input2 = "00:10:00"; var result = NumberUtilities.AddDateTimes(input1, input2); string expected = "00:11:00"; Assert.That(result.TimeOfDay.ToString(), Is.EqualTo(expected)); }
public async Task <IActionResult> Create([Bind("Id,Division,Name")] District district) { if (ModelState.IsValid) { district.Id = NumberUtilities.GetUniqueNumber(); _context.Add(district); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(district)); }
public IActionResult AgentRequest(Agent agent) { if (!ModelState.IsValid) { return(View(agent)); } agent.Id = NumberUtilities.GetUniqueNumber(); _context.Agents.Add(agent); _context.SaveChanges(); return(RedirectToAction("Index", "Agents")); }
public async Task <IActionResult> AddProduct(IFormFile file, ProductViewModel vm) { if (ModelState.IsValid) { var Seller = _context.Sellers.Where(s => s.Email.Contains(User.Identity.Name)); if (Seller.SingleOrDefault() == null) { return(RedirectToAction("RequestForSell", "Products")); } ImgUploader img = new ImgUploader(environment); var imgPath = img.ImageUrl(file); //function working here var products = new Product { Id = NumberUtilities.GetUniqueNumber(), Title = vm.Product.Title, Description = vm.Product.Description, Price = vm.Product.Price, SellerId = 1, //manually value. Next time it will be from Session User Value CategoryId = vm.Product.CategoryId, DistrictId = vm.Product.DistrictId, IsPublished = vm.Product.IsPublished, //manually valuess Unit = vm.Product.Unit, ItemInStock = vm.Product.ItemInStock, UpdatedAt = DateTime.Now, //manually valuess OfferExpireDate = DateTime.Now, //manually valuess ImagePath = imgPath, OfferPrice = vm.Product.OfferPrice, }; await _context.AddAsync(products); await _context.SaveChangesAsync(); long id = products.Id; } else { var viewmodel = _productService.GetProductViewModelAsync(); ViewBag.error = "You Cannot ignore required fields"; return(View("AddProduct", viewmodel)); } return(RedirectToAction("AddProduct", "Products")); }
public async Task <IActionResult> Create([Bind("Id,Title,SellerId,Price,Description,Unit,IsPublished,ItemInStock,DistrictId,CategoryId,ImagePath,OfferPrice,OfferExpireDate,CreatedAt,UpdatedAt")] Product product) { if (ModelState.IsValid) { product.Id = NumberUtilities.GetUniqueNumber(); _context.Add(product); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["CategoryId"] = new SelectList(_context.Categories, "Id", "Domain", product.CategoryId); ViewData["DistrictId"] = new SelectList(_context.Districts, "Id", "Division", product.DistrictId); ViewData["SellerId"] = new SelectList(_context.Sellers, "Id", "Email", product.SellerId); return(View(product)); }
static void Main() { int[] elements = { 1, 2, 3 }; Console.WriteLine("Max element: {0}\n", ArrayUtilities.FindMax(elements)); /* --------------------------------------- */ object number = 12.3456; NumberUtilities.PrintAsPercent(number); NumberUtilities.PrintWithFixedPoint(number); NumberUtilities.PrintWithRightAlignment(number); /* --------------------------------------- */ var digit = 9; Console.WriteLine("\nDigit name of {0} is '{1}'", digit, NumberUtilities.GetDigitName(digit)); /* --------------------------------------- */ var a = 3.1; var b = 4.2; var c = 5.3; var triangleArea = ShapeUtilities.CalculateTriangleArea(a, b, c); Console.WriteLine("\nTriangle area: {0}\n", triangleArea); /* --------------------------------------- */ var p1 = new Point(-7, 13); var p2 = new Point(-9, 13); Console.WriteLine(p1); Console.WriteLine(p2); var distanceBetweenTwoPoints = ShapeUtilities.CalculateDistanceBetweenTwoPoints(p1, p2); Console.WriteLine("\nDistance between two points: {0}", distanceBetweenTwoPoints); var areTwoPointsHorizontal = ShapeUtilities.AreTwoPointsHorizontal(p1, p2); Console.WriteLine("Are two points horizontal: {0}", areTwoPointsHorizontal); var areTwoPointsVertical = ShapeUtilities.AreTwoPointsVertical(p1, p2); Console.WriteLine("Are two points vertical: {0}\n", areTwoPointsVertical); }
private string GenerateSubstringBasedName(ICreator owner, ISpecies species) { IEnumerable <string> substrings = GetSubstrings(species.GetName()); string result = substrings.Random(); // Perform random modifications to the output string. if (NumberUtilities.GetRandomBoolean()) { result = result.Substring(0, result.Length - 1); // cut off the last vowel if (NumberUtilities.GetRandomBoolean()) { result += new[] { 'a', 'i', 'o', 'u' } }
private Tuple <PlayerState, PlayerState> _getTurnOrder() { /* Determine which player gets to move first at the start of the turn. * * Move priority is considered first, followed by speed, and then random selection. * * */ PlayerState first, second; if (player1.SelectedMove.Priority > player2.SelectedMove.Priority) { first = player1; second = player2; } else if (player2.SelectedMove.Priority > player1.SelectedMove.Priority) { first = player2; second = player1; } else if (player1.Gotchi.Stats.Spd > player2.Gotchi.Stats.Spd) { first = player1; second = player2; } else if (player2.Gotchi.Stats.Spd > player1.Gotchi.Stats.Spd) { first = player2; second = player1; } else { if (NumberUtilities.GetRandomInteger(0, 2) == 0) { first = player1; second = player2; } else { first = player2; second = player1; } } return(new Tuple <PlayerState, PlayerState>(first, second)); }
public async Task Roll(int min, int max) { if (min < 0 || max < 0) { await ReplyErrorAsync("Values must be greater than 1."); } else if (min > max + 1) { await ReplyErrorAsync("Minimum value must be less than or equal to the maximum value."); } else { int result = NumberUtilities.GetRandomInteger(min, max + 1); await ReplyAsync(result.ToString()); } }
public static void InitializeLuaContext(Script script) { if (!_registered_assembly) { UserData.RegisterAssembly(); _registered_assembly = true; } script.Globals["Console"] = (Action <string>)((string x) => Console.WriteLine(x)); script.Globals["Rand"] = (Func <int, int, int>)((int min, int max) => NumberUtilities.GetRandomInteger(min, max)); script.Globals["Chance"] = (Func <int, bool>)((int chance) => NumberUtilities.GetRandomInteger(0, chance) == 0); script.Globals["Min"] = (Func <int, int, int>)((int a, int b) => Math.Min(a, b)); script.Globals["Max"] = (Func <int, int, int>)((int a, int b) => Math.Max(a, b)); script.Globals["Swap"] = (Action <object, object>)((object a, object b) => GeneralUtilities.Swap(ref a, ref b)); script.Globals["NewRequirements"] = (Func <GotchiRequirements>)(() => LuaFunctions.NewRequirements()); }
public Document Upload(IFormFile file) { if (file == null || file.Length == 0) { return(null); } //DRILL ORIGINAL NAME var originalName = GetDocumentName(file); //DRILL EXTENSION var extension = Path.GetExtension(file.FileName).ToLower(); //GENERATE UNIQUE NAME var currentName = _encryptionService.GetUniqueKey(20); //ROOT PATH string rootPath = _env.ContentRootPath; //APPLICATION LOCAL DIRECTORY PATH string localDirectory = $"/StaticFiles/Images/"; //FILE PATH string imagePath = $"{rootPath}{localDirectory}{currentName}{extension}"; //SAVE STREAM using (var stream = new FileStream(imagePath, FileMode.Create)) { file.CopyTo(stream); stream.Dispose(); } return(new Document { Id = NumberUtilities.GetUniqueNumber(), OriginalName = originalName, Name = currentName, CreatedAt = DateTime.UtcNow, Extension = extension, Path = Path.Combine(localDirectory, (currentName + extension)), Type = FileUtilities.GetType(extension) }); }
public async Task <IActionResult> ApproveSeller(string email) { var requestedSeller = _context.SellerRequests .Where(s => s.Email.Contains(email)) .FirstOrDefault(); if (requestedSeller == null) { return(NotFound()); } var sellers = _context.Sellers.Include(x => x.User).ThenInclude(x => x.District); if (!sellers.Any(x => x.Email == email)) { var seller = new Seller { Id = NumberUtilities.GetUniqueNumber(), Name = requestedSeller.SellerName, Email = email, CompanyName = requestedSeller.CompanyName, Phone = requestedSeller.Phone, DateOfBirth = requestedSeller.DateOfBirth }; await _context.Sellers.AddAsync(seller); var appUserr = _context.Users.Where(x => x.Email == email).FirstOrDefault(); if (appUserr != null) { seller.UserId = appUserr.Id; } await _context.SaveChangesAsync(); } //REMOVE PREVIOUS SELLER REQUEST var del = _context.SellerRequests.Find(requestedSeller.Id); _context.SellerRequests.Remove(del); await _context.SaveChangesAsync(); return(RedirectToAction("RequestIndex")); } //REQUEST SECTION END
public async override Task ApplyAsync(ISearchContext context, ISearchResult result) { if (int.TryParse(Value, out int count) && count > 0) { IEnumerable <ISpecies> results = await result.GetResultsAsync(); // Take N random IDs from the results. IEnumerable <long> randomIds = results .Where(species => species.Id.HasValue) .OrderBy(species => NumberUtilities.GetRandomInteger(int.MaxValue)) .Take(count) .Select(species => (long)species.Id) .ToArray(); // Filter all but those results. await result.FilterByAsync(async (species) => await Task.FromResult(!randomIds.Any(id => id == species.Id)), Invert); } }
public void Test_FindMissingNumber(string input, int expected) { var result = NumberUtilities.FindMissingNumber(input); Assert.That(result, Is.EqualTo(expected)); var query = input .Split(' ') .Select(Int32.Parse) .GroupBy(s => s) .OrderBy(s => s.Count()) .Select(x => new { Number = x.Key, RepetitionCount = x.Count() }); foreach (var item in query) { Console.WriteLine($"Number: {item.Number}, repetitionCount: {item.RepetitionCount}"); } }
public GotchiMove GetRandomMove() { // Select randomly from all moves that currently have PP. List <GotchiMove> options = new List <GotchiMove>(); foreach (GotchiMove move in Moves) { if (move.PP > 0) { options.Add(move); } } if (options.Count() > 0) { return(options[NumberUtilities.GetRandomInteger(options.Count())]); } else { return(null); } }
// GET api/<controller>/5 public string Get(int id) { return(NumberUtilities.IsPrime(id).ToString()); }
public static async Task <BattleGotchi> GenerateGotchiAsync(this SQLiteDatabase database, GotchiGenerationParameters parameters) { BattleGotchi result = new BattleGotchi(); if (!(parameters.Base is null)) { // If a base gotchi was provided, copy over some of its characteristics. result.Gotchi.BornTimestamp = parameters.Base.BornTimestamp; result.Gotchi.DiedTimestamp = parameters.Base.DiedTimestamp; result.Gotchi.EvolvedTimestamp = parameters.Base.EvolvedTimestamp; result.Gotchi.FedTimestamp = parameters.Base.FedTimestamp; } // Select a random base species to start with. ISpecies species = parameters.Species; if (species is null) { IEnumerable <ISpecies> base_species_list = await database.GetBaseSpeciesAsync(); if (base_species_list.Count() > 0) { species = base_species_list.ElementAt(NumberUtilities.GetRandomInteger(0, base_species_list.Count())); } } if (species != null) { result.Gotchi.SpeciesId = (long)species.Id; } // Evolve it the given number of times. for (int i = 0; i < parameters.MaxEvolutions; ++i) { if (!await database.EvolveAndUpdateGotchiAsync(result.Gotchi)) { break; } } // Generate stats (if applicable). if (parameters.GenerateStats) { result.Gotchi.Experience = GotchiExperienceCalculator.ExperienceToLevel(result.Stats.ExperienceGroup, NumberUtilities.GetRandomInteger(parameters.MinLevel, parameters.MaxLevel + 1)); result.Stats = await new GotchiStatsCalculator(database, Global.GotchiContext).GetStatsAsync(result.Gotchi); } // Generate moveset (if applicable). if (parameters.GenerateMoveset) { result.Moves = await Global.GotchiContext.MoveRegistry.GetMoveSetAsync(database, result.Gotchi); } // Generate types. result.Types = await Global.GotchiContext.TypeRegistry.GetTypesAsync(database, result.Gotchi); // Generate a name for the gotchi. result.Gotchi.Name = (species is null ? "Wild Gotchi" : species.GetShortName()) + string.Format(" (Lv. {0})", result.Stats is null ? 1 : result.Stats.Level); return(result); }
public async Task <ActionResult> Checkout(OrderViewModel ovModel) { if (SessionHelper.GetObjectFromJson <List <CartItem> >(HttpContext.Session, "cart") == null) { return(RedirectToAction("Index", "Products")); } Customer customer = new Customer(); var customerExisted = _context.Customers.Where(c => c.Email == ovModel.Order.Email).AsNoTracking().FirstOrDefault(); if (customerExisted == null) { //nw user var user = new AppUser { Email = ovModel.Order.Email, UserName = ovModel.Order.Email }; var res = await _userManager.CreateAsync(user); if (res.Succeeded) { var cust = new Customer { Id = NumberUtilities.GetUniqueNumber(), Name = ovModel.Order.Name, Email = ovModel.Order.Email, Phone = ovModel.Customer.Phone, UserId = user.Id }; await _context.Customers.AddAsync(cust); await _context.SaveChangesAsync(); customer = cust; } } else { customer = _context.Customers.Find(ovModel.Customer.Id); } var order = new Order { Id = NumberUtilities.GetUniqueNumber(), Name = customer.Name, Email = customer.Email, //fixed portion ShippingAddress = ovModel.Order.ShippingAddress, PostalCode = ovModel.Order.PostalCode, StreetNo = ovModel.Order.StreetNo, CustomerId = customer.Id, TotalPrice = ovModel.TotalPrice, OrderDate = DateTime.Now, AccountNo = ovModel.Order.AccountNo, TransactionId = ovModel.Order.TransactionId }; _context.Orders.Add(order); _context.SaveChanges(); var cartList = SessionHelper.GetObjectFromJson <List <CartItem> >(HttpContext.Session, "cart"); ViewBag.total = cartList.Sum(c => c.Product.Price * c.Quantity); foreach (var item in cartList) { var order_product = new ProductOrder { Id = NumberUtilities.GetUniqueNumber(), OrderId = order.Id, ProductId = item.Product.Id, NumberOfProduct = item.Quantity }; _context.ProductOrders.Add(order_product); _context.SaveChanges(); var quantity = _context.Products.Where(c => c.Id == item.Product.Id).SingleOrDefault(); if (quantity != null) { var pro = _context.Products.Find(item.Product.Id); pro.ItemInStock = pro.ItemInStock - order_product.NumberOfProduct; _context.Products.Update(pro); _context.SaveChanges(); } } //clear the session now HttpContext.Session.Clear(); var agents = _context.Agents.Where(c => c.User.DistrictId == customer.User.DistrictId).ToList(); var random = new Random(); var index = random.Next(0, agents.Count); var agent = agents[index]; var agentorder = new AgentOrder { Id = NumberUtilities.GetUniqueNumber(), AgentId = agent.Id, OrderId = order.Id, IsPaid = false, IsOnRoute = false, IsFullyCompleted = false }; _context.AgentOrders.Add(agentorder); _context.SaveChanges(); TempData["orderSuccess"] = "Your order has been placed successfully!"; return(RedirectToAction("Checkout")); }
private void button7_Click(object sender, EventArgs e) { Mail mail = new Mail(); mail.From = txtDe.Text; mail.To = txtPara.Text; //mail.Bcc = "*****@*****.**"; mail.Subject = txtAssunto.Text; mail.Body = txtCorpo.Text; //mail.AttachmentList.Add(@"D:\desenvolvimento_old\analise de sistemas\nfe\documentacao\NT_2016_002_v1.51.pdf"); //KhronusReturn ret = MailUtilities.send("smtp.gmail.com", "*****@*****.**", "fev@030277@", 587, true, mail); KhronusReturn ret = MailUtilities.send(txtSmtp.Text, txtUsuario.Text, txtSenha.Text, NumberUtilities.parseInt(txtPorta.Text), chkSsl.Checked, mail); MessageBox.Show(ret.Status + " " + ret.Message); }
private void pd_PrintPage2(object sender, PrintPageEventArgs ev) { float linesPerPage = 0; int yPos = 0; int count = 1; int leftMargin = 3; // ev.MarginBounds.Left; int topMargin = 3; // ev.MarginBounds.Top; string line = null; //Font printFont = new Font("Lucida Console", 7); //printFont = new Font("Letter Gothic Std", 7); //Font printFont = new Font("MS Gothic", 8); Font printFont = new Font("MS Gothic", 8); // Calculate the number of lines per page. //linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics); //Impressao do logo // // //count = 5; //yPos = topMargin + (count * printFont.GetHeight(ev.Graphics)); // Print each line of the file. while (((line = streamToPrint.ReadLine()) != null)) { //yPos = topMargin + (count * printFont.GetHeight(ev.Graphics)); //RectangleF rect = new RectangleF(leftMargin, yPos, 280f, 100f); if (line.StartsWith("{LOGO}")) { //Bitmap logo = (Bitmap)Image.FromFile(@"C:\prosis\img\logo-refriauto.png"); //ev.Graphics.DrawImage(logo, leftMargin+5, yPos+11, 50, 25); } else if (line.StartsWith("{128CODE}")) { BarcodeLib.Barcode barcode = new BarcodeLib.Barcode(); Bitmap bitmap = (Bitmap)barcode.Encode(BarcodeLib.TYPE.CODE128, "35170910292626000172590001709212247548880575", Color.Black, Color.White, 280, 30); ev.Graphics.DrawImage(bitmap, new Rectangle(leftMargin, yPos, 280, 30)); } else if (line.StartsWith("{QRCODE}")) { //var bw = new ZXing.BarcodeWriter(); //var encOptions = new ZXing.Common.EncodingOptions() { Width = 150, Height = 150, Margin = 0 }; //bw.Options = encOptions; //bw.Format = ZXing.BarcodeFormat.QR_CODE; //Bitmap imageQrCode = new Bitmap(bw.Write("https://www.homologacao.nfce.fazenda.sp.gov.br/NFCeConsultaPublica/Paginas/ConsultaQRCode.aspx?chNFe=35160207209613000182650010000000191000000190&nVersao=100&tpAmb=2&dhEmi=323031362d30322d32305431303a33353a35302d30323a3030&vNF=100.00&vICMS=0.00&digVal=55586c7938373833637672394551445570353332776d76336c58303d&cIdToken=000003&cHashQRCode=eebc9c3b9009688a8f668ec5deafd769af7d643b")); //ev.Graphics.DrawImage(imageQrCode, new Rectangle(70, yPos, 150, 150)); QRCodeEncoder qrCodecEncoder = new QRCodeEncoder(); qrCodecEncoder.QRCodeBackgroundColor = System.Drawing.Color.White; qrCodecEncoder.QRCodeForegroundColor = System.Drawing.Color.Black; //qrCodecEncoder.CharacterSet = "UTF-8"; qrCodecEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; qrCodecEncoder.QRCodeScale = 6; qrCodecEncoder.QRCodeVersion = 0; qrCodecEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q; Image imageQRCode; //string a ser gerada String dados = "35170910292626000172590001709212247548880575"; imageQRCode = qrCodecEncoder.Encode(dados); //picQrCode.Image = imageQRCode; //ev.Graphics.DrawImage(imageQRCode, new Rectangle(leftMargin, yPos, (int)convertCmToPoint(0.5), (int)convertCmToPoint(0.5))); ev.Graphics.DrawImage(imageQRCode, new Rectangle(leftMargin + 80, yPos, 100, 100)); } else { //String s0 = StringUtilities.subString(line, 0, 4).Replace("{", "").Replace("}", ""); //String n = s0 //String s1 = StringUtilities.subString(line, 4); //if (line.StartsWith("{B8}")) //{ // printFont = new Font("MS Gothic", 8, FontStyle.Bold); //} //else //{ // printFont = new Font("MS Gothic", 8, FontStyle.Regular); //} //line = line.Replace("{B}", ""); StringFormat format = new StringFormat(); if (line.StartsWith("{")) { int pos = line.IndexOf("}"); String ini0 = line.Substring(0, pos + 1); String ini1 = ini0.Replace("{", "").Replace("}", ""); String[] ini2 = ini1.Split(','); String style = ini2[0]; int size = NumberUtilities.parseInt(ini2[1]); String align = ini2[2]; if (style.Equals("B")) { printFont = new Font("MS Gothic", size, FontStyle.Bold); } else { printFont = new Font("MS Gothic", size, FontStyle.Regular); } StringAlignment a; if (align.Equals("C")) { a = StringAlignment.Center; } else if (align.Equals("L")) { a = StringAlignment.Near; } else { a = StringAlignment.Far; } format.LineAlignment = a; format.Alignment = a; line = line.Replace(ini0, ""); //yPos = topMargin + (count * printFont.GetHeight(ev.Graphics)); Rectangle rect = new Rectangle(leftMargin, yPos, 280, 12); //ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat()); ev.Graphics.DrawString(line, printFont, Brushes.Black, rect, format); } else { //yPos = topMargin + (count * printFont.GetHeight(ev.Graphics)); Rectangle rect = new Rectangle(leftMargin, yPos, 280, 12); //ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat()); ev.Graphics.DrawString(line, printFont, Brushes.Black, rect, new StringFormat()); } //ev.Graphics.DrawString( // line, // printFont, // Brushes.Black, // rect, // new StringFormat()); } count++; //yPos = topMargin + (count * printFont.GetHeight(ev.Graphics)); //yPos = rect.Height + (count * printFont.GetHeight(ev.Graphics)); yPos += 12; // (int)printFont.GetHeight(ev.Graphics); } //count++; //yPos = topMargin + (count * printFont.GetHeight(ev.Graphics)); //ev.Graphics.DrawString( // "# | COD | DESC | QTD | UN | VL UN R$ | (VL TR R$)*| VL ITEM R$", // printFont, // Brushes.Black, // new RectangleF(leftMargin, yPos, 200f, 100f), // new StringFormat()); // If more lines exist, print another page. /* * if (line != null) * ev.HasMorePages = true; * else * ev.HasMorePages = false; */ }
public void Test_ConvertTimeToMinutes(string input, string expected) { var result = NumberUtilities.ConvertTimeToMinutes(input); Assert.That(result, Is.EqualTo(expected)); }
private void button2_Click(object sender, EventArgs e) { decimal value = 10M; MessageBox.Show(NumberUtilities.format(value)); }
public static async Task <bool> EvolveAndUpdateGotchiAsync(this SQLiteDatabase database, Gotchi gotchi, string desiredEvo) { bool evolved = false; if (string.IsNullOrEmpty(desiredEvo)) { // Find all descendatants of this species. using (SQLiteCommand cmd = new SQLiteCommand("SELECT species_id FROM Ancestors WHERE ancestor_id=$ancestor_id;")) { List <long> descendant_ids = new List <long>(); cmd.Parameters.AddWithValue("$ancestor_id", gotchi.SpeciesId); foreach (DataRow row in await database.GetRowsAsync(cmd)) { descendant_ids.Add(row.Field <long>("species_id")); } // Pick an ID at random. if (descendant_ids.Count > 0) { gotchi.SpeciesId = descendant_ids[NumberUtilities.GetRandomInteger(descendant_ids.Count)]; evolved = true; } } } else { // Get the desired evo. IEnumerable <ISpecies> sp = await database.GetSpeciesAsync(desiredEvo); if (sp is null || sp.Count() != 1) { return(false); } // Ensure that the species evolves into the desired evo. using (SQLiteCommand cmd = new SQLiteCommand("SELECT COUNT(*) FROM Ancestors WHERE ancestor_id = $ancestor_id AND species_id = $species_id")) { cmd.Parameters.AddWithValue("$ancestor_id", gotchi.SpeciesId); cmd.Parameters.AddWithValue("$species_id", sp.First().Id); if (await database.GetScalarAsync <long>(cmd) <= 0) { return(false); } gotchi.SpeciesId = (long)sp.First().Id; evolved = true; } } // Update the gotchi in the database. if (evolved) { using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Gotchi SET species_id=$species_id, evolved_ts=$evolved_ts WHERE id=$id;")) { cmd.Parameters.AddWithValue("$species_id", gotchi.SpeciesId); // The "last evolved" timestamp is now only updated in the event the gotchi evolves (in order to make the "IsEvolved" check work correctly). // Note that this means that the background service will attempt to evolve the gotchi at every iteration (unless it evolves by leveling). cmd.Parameters.AddWithValue("$evolved_ts", DateTimeOffset.UtcNow.ToUnixTimeSeconds()); cmd.Parameters.AddWithValue("$id", gotchi.Id); await database.ExecuteNonQueryAsync(cmd); } } return(evolved); }