static void Main()
        {
            IEnumerable <int> intArr =new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            IEnumerable<double> dblArr =new[] { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 };

            Console.WriteLine("Sum of: ");
            Console.WriteLine("Integer array: {0}", intArr.Sum());
            Console.WriteLine("Double array: {0}", dblArr.Sum());

            Console.WriteLine();
            Console.WriteLine("Product of: ");
            Console.WriteLine("Integer array: {0}", intArr.Product());
            Console.WriteLine("Double array: {0}", dblArr.Product());

            Console.WriteLine();
            Console.WriteLine("Average of: ");
            Console.WriteLine("Integer array: {0}", intArr.Average());
            Console.WriteLine("Double array: {0}", dblArr.Average());

            Console.WriteLine();
            Console.WriteLine("Min of: ");
            Console.WriteLine("Integer array: {0}", intArr.Min());
            Console.WriteLine("Double array: {0}", dblArr.Min());

            Console.WriteLine();
            Console.WriteLine("Max of: ");
            Console.WriteLine("Integer array: {0}", intArr.Max());
            Console.WriteLine("Double array: {0}", dblArr.Max());
        }
Example #2
0
 public void List_Binds()
 {
     var values = new[] { 1, 2, 3, 4, };
     var list = new List<int>(values);
     var squares = list.Bind<int>(a => new List<int>(Helper(a))).Values.ToList();
     Assert.AreEqual(values.Sum(), squares.Count);
 }
        public void ForEach()
        {
            int[] numbers = new[] { 2, 3, 6, 7 };
            int sum = 0;

            numbers.ForEach(x => sum += x);
            Assert.Equal(sum, numbers.Sum());
        }
        public void ForEachFunc()
        {
            var @enum = new[] {1, 2, 3, 4}.AsEnumerable();
            var sum = 0;

            @enum.ForEach(n => sum += n);

            Assert.AreEqual(sum, @enum.Sum());
        }
Example #5
0
 public void TestInvokeInstanceMethod()
 {
     RunWith( ( object person ) =>
        {
            var elements = new[] { 1d, 2d, 3d, 4d, 5d };
            elements.ForEach( element => person.CallMethod( "Walk", element ) );
            Assert.AreEqual( elements.Sum(), person.GetFieldValue( "metersTravelled" ) );
        } );
 }
Example #6
0
        public HasVictim BanParser(bool wait = false)
        {
            var userHistory = Datastore.UserHistory(_message.SenderName) ?? new UserHistory { Nick = _message.SenderName }; // todo maKe this lazy

              var fullWidthCharacters = new[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'q', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'Q', 'X', 'Y', 'Z' };
              if (fullWidthCharacters.Sum(c => _originalText.Count(ot => ot == c)) > 5)
            return MuteAndIncrementHardCoded(userHistory, MagicStrings.FullWidth, "fullwidth text", wait);
              var spamCharacters = new[] { "▓", "▂", "♥", "ᴶ", "♠", "ᑫ", "ᴷ", "♦", "ᴬ", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹", "⁰", ":", "░", "═", "╔", "╗", "╚", "╝", "║", "─", "┐", "┌", "└", "╥", "┘", "╡", "▀", "▐", "▌", "█", "▄", "■", "▉", " ", "▒", " ", "̍", "̎", "̄", "̅", "̿", "̑", "̆", "̐", "͒", "͗", "͑", "̇", "̈", "̊", "͂", "̓", "̈́", "͊", "͋", "͌", "̃", "̂", "̌", "͐", "̀", "́", "̋", "̏", "̒", "̓", "̔", "̽", "̉", "ͣ", "ͤ", "ͥ", "ͦ", "ͧ", "ͨ", "ͩ", "ͪ", "ͫ", "ͬ", "ͭ", "ͮ", "ͯ", "̾", "͛", "͆", "̚", "̕", "̛", "̀", "́", "͘", "̡", "̢", "̧", "̨", "̴", "̵", "̶", "͏", "͜", "͝", "͞", "͟", "͠", "͢", "̸", "̷", "͡", "҉", "̖", "̗", "̘", "̙", "̜", "̝", "̞", "̟", "̠", "̤", "̥", "̦", "̩", "̪", "̫", "̬", "̭", "̮", "̯", "̰", "̱", "̲", "̳", "̹", "̺", "̻", "̼", "ͅ", "͇", "͈", "͉", "͍", "͎", "͓", "͔", "͕", "͖", "͙", "͚", "̣", "👎", "💉", "🔪", "🔫", "🚬", "👌", "ү", "f", "👀", "👎", "❌", "🚫", "ʳ", "ᶦ", "ᵍ", "ʰ", "ᵗ", "ᵉ", "✔", "ᵒ", "О", "O", "Н", "Ꮇ", "ƽ", "ԁ", "💯", " ", "▁", "▃", "▅", "▆", "✋", "🤔", "😏", "⎠", "⎝" };
              if (spamCharacters.Sum(c => _originalText.Count(ot => ot.ToString() == c)) > 20)
            return MuteAndIncrementHardCoded(userHistory, MagicStrings.SpamCharacters, "spam characters", wait);

              var unicode = new[] { '็', 'е', };
              var controlCharacters = new Regex(@"[\u0000-\u001F\u0080-\u009F\u007F-[\x0D\x0A\x09]]"); //http://stackoverflow.com/questions/3770117/what-is-the-range-of-unicode-printable-characters
              if (unicode.Sum(c => _originalText.Count(ot => ot == c)) >= 1 || controlCharacters.Match(_originalText).Success)
            return MuteAndIncrementHardCoded(userHistory, MagicStrings.Unicode, "unicode idiocy", wait);

              if (Datastore.EmoteRegex.Matches(_message.OriginalText).Count > 7)
            return MuteAndIncrementHardCoded(userHistory, MagicStrings.Facespam, "face spam", wait);

              var mutedWord = Datastore.MutedWords.Select(x => x.Key).FirstOrDefault(x => _originalText.Contains(x) || _text.Contains(x));
              var mute = DeterminesHasVictim(mutedWord, userHistory, MagicStrings.MutedWords, Datastore.MutedWords, new Mute(), wait);
              if (mute != null) return mute;

              var bannedWord = Datastore.BannedWords.Select(x => x.Key).FirstOrDefault(x => _originalText.Contains(x) || _text.Contains(x));
              var ban = DeterminesHasVictim(bannedWord, userHistory, MagicStrings.BannedWords, Datastore.BannedWords, new Ban(), wait);
              if (ban != null) return ban;

              var mutedRegex = Datastore.MutedRegex.Select(x => new Regex(x.Key)).FirstOrDefault(x => x.Match(_originalText).Success);
              if (mutedRegex != null) {
            var banR = DeterminesHasVictim(mutedRegex.ToString(), userHistory, MagicStrings.MutedRegex, Datastore.MutedRegex, new Mute(), wait);
            if (banR != null) return banR;
              }

              var bannedRegex = Datastore.BannedRegex.Select(x => new Regex(x.Key)).FirstOrDefault(x => x.Match(_originalText).Success);
              if (bannedRegex != null) {
            var banR = DeterminesHasVictim(bannedRegex.ToString(), userHistory, MagicStrings.BannedRegex, Datastore.BannedRegex, new Ban(), wait);
            if (banR != null) return banR;
              }

              var longSpam = LongSpam();
              if (longSpam != null) return longSpam;
              var selfSpam = SelfSpam();
              if (selfSpam != null) return selfSpam;
              var numberSpam = NumberSpam();
              if (numberSpam != null) return numberSpam;
              var repeatCharacterSpam = RepeatCharacterSpam();
              if (repeatCharacterSpam != null) return repeatCharacterSpam;
              //var lineSpam = LineSpam();
              //if (lineSpam != null) return lineSpam;

              foreach (var nuke in _messageProcessor.Nukes.Where(x => x.Predicate(_message.SanitizedText) || x.Predicate(_message.OriginalText))) {
            nuke.VictimList.Add(_message.SenderName);
            return new Mute(_message.SenderName, nuke.Duration, null);
              }
              return null;
        }
Example #7
0
 public void TestInvokeInstanceMethodViaMethodInfo()
 {
     RunWith( ( object person ) =>
        {
            var elements = new[] { 1d, 2d, 3d, 4d, 5d };
            var methodInfo = person.UnwrapIfWrapped().GetType().Method( "Walk", new [] { typeof(int) }, Flags.InstanceAnyVisibility );
            elements.ForEach( element => methodInfo.Call( person, element ) );
            Assert.AreEqual( elements.Sum(), person.GetFieldValue( "metersTravelled" ) );
        } );
 }
Example #8
0
 static void Main()
 {
     var elements = new[] {  "a",  "b" };
     Console.WriteLine(elements.Average());
     Console.WriteLine(elements.Min());
     Console.WriteLine(elements.Max());
     Console.WriteLine(elements.Sum());
     string a = "a";
     string b = "b";
     Console.WriteLine(a * b);
 }
Example #9
0
    static void Main()
    {
        var numbers = new[] { 3, 5, 12, 15, 30, 35 };

        Console.WriteLine("Sum: {0}", numbers.Sum());
        Console.WriteLine("Product: {0}", numbers.Product());
        Console.WriteLine("Min: {0}", numbers.Min());
        Console.WriteLine("Max: {0}", numbers.Max());
        Console.WriteLine("Average: {0}", numbers.Average());

        Console.WriteLine();
    }
        public void Mean()
        {
            var rnd  = new Random();
            var nums = new[] { rnd.NextDouble(), rnd.NextDouble(), rnd.NextDouble(), rnd.NextDouble(), rnd.NextDouble() };

            var res = API.Mean(nums);

            if (!string.IsNullOrWhiteSpace(res.Error))
            {
                Assert.Fail("The API call failed with the following internal error: " + res.Error);
            }

            Assert.AreEqual(nums.Sum() / nums.Count(), res.Result, 0.0000000001);
        }
Example #11
0
        public static void Main()
        {
            // products
            //int n = int.Parse(Console.ReadLine());
            var weight = new[] { 3, 8, 4, 1, 2, 8 };
            var cost = new[] { 2, 12, 5, 4, 3, 13 };
            var capacity = 10;

            Console.WriteLine("Max sum of weight: {0}", weight.Sum());
            Console.WriteLine("Max sum of value: {0}", cost.Sum());
            Console.WriteLine("Numbers: {0}", string.Join(", ", weight));
            Console.WriteLine("Costs: {0}", string.Join(", ", cost));

            Console.WriteLine("Capacity: {0}", capacity);
            Solve(weight, cost, capacity);
        }
Example #12
0
        public static int GetRandomInt()
        {
            var probabilities = new[] { 35, 35, 35, 35, 10 };
            var probabilitiesSum = probabilities.Sum();
            int tempRand = random.Next(0, probabilitiesSum);
            var currentSum = 0;
            for (int i = 0; i < probabilities.Length; i++)
            {
                currentSum += probabilities[i];
                if (tempRand < currentSum)
                {
                    return (i + 1);
                }
            }

            throw new InvalidOperationException();
        }
Example #13
0
        static void Main()
        {
            var items = new[]
            {
                1.2,
                2.3,
                3.4
            };

            Console.Write("Elements: ");
            foreach (var item in items)
            {
                Console.Write("{0} ", item);
            }
            Console.WriteLine();

            Console.WriteLine("Sum: " + items.Sum());
            Console.WriteLine("Product: " + items.Product());
            Console.WriteLine("Min: " + items.Min());
            Console.WriteLine("Max: " + items.Max());
            Console.WriteLine("Average: " + items.Average());
        }
Example #14
0
        /// <summary>
        /// Decodes an MPO file into jpeg images
        /// </summary>
        /// <remarks>
        /// An MPO file is a multi-jpeg container that can hold any number of jpeg files. The container itself contains no 
        /// extra data so jpeg images can be found and extracted using their start signature "0xFFD8FFE1" which represents
        /// the first EXIF tag
        /// </remarks>
        /// <param name="mpoFileName">The file name of the input mpo file</param>
        public static void DecodeMpo(string mpoFileName)
        {
            // The MPO file will contain N jpgs packed together. There is no extra information stored with the MPO.
            // JPEG images will be separated by the tag bytes FF D8 FF E1 (the start tags of the jpeg)
            var jpegHeaderStart = new[] { 0xFF, 0xD8, 0xFF, 0xE1 };

            // Start by reading the bytes
            var mpoData = File.ReadAllBytes(mpoFileName);

            // Find the location of the beginning of each image
            var indices = new List<int>();
            for (var i = 0; i < mpoData.Length - jpegHeaderStart.Length; i++)
            {
                // Use a mask to find the tag. ~A & A = 0 (this is a little screwy because we deal with FF here which matches everything)
                var j = 0;
                var maskResult = jpegHeaderStart.Sum(bt => ~mpoData[i + j++] & bt);

                // If the masking result is 0 then the right image start tag is found
                if (maskResult == 0)
                {
                    indices.Add(i);
                }
            }

            // For each found index, extract the jpeg
            for (var i = 0; i < indices.Count; i++)
            {
                // Create a temporary buffer to hold the image bytes
                // To do this, make a buffer with length equal to the difference between the start index of this image
                // and the start index of the next image. If there is no next image, use the end of the data instead.
                byte[] image = i + 1 == indices.Count ? new byte[mpoData.Length - indices[i]] : new byte[indices[i + 1] - indices[i]];

                // Copy the image data to a temporary file
                Array.Copy(mpoData, indices[i], image, 0, image.Length);

                // Write the image data to a file
                File.WriteAllBytes(i + ".jpg", image);
            }
        }
        /*2.	Implement a set of extension methods for IEnumerable<T> that implement the following group functions:
         * sum, product, min, max, average.*/
        static void Main()
        {
            List<int> listInt = new List<int> { 1, 2, 3, 4, 5 };
            double[] testDouble = new[] { 4.5, 6.0, 5.7, 34.7 }; //sum = 50.9

            Console.WriteLine("---list <int>---");
            Console.WriteLine("Sum: {0}", listInt.Sum());
            Console.WriteLine("Average: {0}", listInt.Average());
            Console.WriteLine("Product: {0}", listInt.Product());
            Console.WriteLine("Minimum: {0}", listInt.Min());
            Console.WriteLine("Minimum: {0}", listInt.Max());

            Console.WriteLine("---double---");
            Console.WriteLine("Sum: {0}", testDouble.Sum());
            Console.WriteLine("Average: {0}", testDouble.Average());
            Console.WriteLine("Product: {0}", testDouble.Product());
            Console.WriteLine("Minimum: {0}", testDouble.Min());
            Console.WriteLine("Minimum: {0}", testDouble.Max());

            List<int> testEmpty = new List<int>();
            Console.WriteLine(testEmpty.Sum()); //return error when enumaration is empty, does not work about array(return 0)
        }
        public void GetCalledFrequencyTest()
        {
            // Arrange
            var charges = new[]
            {
                new CallCharge(new TelephoneNumber("0123456789"), TimeSpan.FromSeconds(19), new Money(.19M)),
                new CallCharge(new TelephoneNumber("0123456789"), TimeSpan.FromSeconds(58), new Money(.58M)),
                new CallCharge(new TelephoneNumber("0123456789"), TimeSpan.FromSeconds(105), new Money(.05M)),
                new CallCharge(new TelephoneNumber("0123456789"), TimeSpan.FromSeconds(44), new Money(.44M)),
                new CallCharge(new TelephoneNumber("0781552266"), TimeSpan.FromSeconds(44), new Money(.44M))
            };
            var bill = new CallChargesBill(charges, charges.Sum());
            var stats = new CallChargesStatistics(bill);

            // Act
            var results = stats.GetCalledFrequency();

            // Assert
            Assert.AreEqual(2, results.Count());
            Assert.AreEqual(new TelephoneNumber("0123456789"), results.ElementAt(0).Number);
            Assert.AreEqual(new TelephoneNumber("0781552266"), results.ElementAt(1).Number);
            Assert.AreEqual(4, results.ElementAt(0).Frequency);
            Assert.AreEqual(1, results.ElementAt(1).Frequency);
        }
Example #17
0
 private static float TestSumSingleFunc(float a, float b, float c) {
     var array = new[] { a, b, c };
     return array.Sum();
 }
        public void Run()
        {
            //Setup FirebridSQL Server Connection Factory
			var dbFactory = new OrmLiteConnectionFactory(
				"User=SYSDBA;Password=masterkey;Database=ormlite-tests.fdb;DataSource=localhost;Dialect=3;charset=ISO8859_1;",
				FirebirdOrmLiteDialectProvider.Instance);

			
            IDbConnection db = dbFactory.OpenDbConnection();

            //Re-Create all table schemas:
            db.DropTable<OrderDetail>();
            db.DropTable<Order>();
            db.DropTable<Customer>();
            db.DropTable<Product>();
            db.DropTable<Employee>();

            db.CreateTable<Employee>();
            db.CreateTable<Product>();
            db.CreateTable<Customer>();
            db.CreateTable<Order>();
            db.CreateTable<OrderDetail>();

            db.Insert(new Employee { Id = 1, Name = "Employee 1" });
            db.Insert(new Employee { Id = 2, Name = "Employee 2" });
            var product1 = new Product { Id = 1, Name = "Product 1", UnitPrice = 10 };
            var product2 = new Product { Id = 2, Name = "Product 2", UnitPrice = 20 };
            db.Save(product1, product2);

            var customer = new Customer
            {
                FirstName = "Orm",
                LastName = "Lite",
                Email = "*****@*****.**",
                PhoneNumbers =
                    {
                        { PhoneType.Home, "555-1234" },
                        { PhoneType.Work, "1-800-1234" },
                        { PhoneType.Mobile, "818-123-4567" },
                    },
                Addresses =
                    {
                        { AddressType.Work, new Address { Line1 = "1 Street", Country = "US", State = "NY", City = "New York", ZipCode = "10101" } },
                    },
                Timestamp = DateTime.UtcNow,
            };
            db.Insert(customer);

            var customerId = db.LastInsertId(); //Get Auto Inserted Id
            customer = db.Single<Customer>(new { customer.Email }); //Query
            Assert.That(customer.Id, Is.EqualTo(customerId));

            //Direct access to System.Data.Transactions:
            using (var trans = db.BeginTransaction(IsolationLevel.ReadCommitted))
            {
                var order = new Order
                {
                    CustomerId = customer.Id,
                    EmployeeId = 1,
                    OrderDate = DateTime.UtcNow,
                    Freight = 10.50m,
                    ShippingAddress = new Address { Line1 = "3 Street", Country = "US", State = "NY", City = "New York", ZipCode = "12121" },
                };
                db.Save(order); //Inserts 1st time

                order.Id = (int)db.LastInsertId(); //Get Auto Inserted Id

                var orderDetails = new[] {
                    new OrderDetail
                    {
                        OrderId = order.Id,
                        ProductId = product1.Id,
                        Quantity = 2,
                        UnitPrice = product1.UnitPrice,
                    },
                    new OrderDetail
                    {
                        OrderId = order.Id,
                        ProductId = product2.Id,
                        Quantity = 2,
                        UnitPrice = product2.UnitPrice,
                        Discount = .15m,
                    }
                };

                db.Insert(orderDetails);

                order.Total = orderDetails.Sum(x => x.UnitPrice * x.Quantity * x.Discount) + order.Freight;

                db.Save(order); //Updates 2nd Time

                trans.Commit();
            }

            db.Dispose();
        }
		public void Sum ()
		{
			IEnumerable<uint> s = null;
			Assert.Throws<ArgumentNullException>(() => s.Sum ());

			s = new []{1U, 2U, 3U};
			Assert.AreEqual (6U, s.Sum ());
			Assert.AreEqual (6U, s.Sum (null));

			IEnumerable<SimpleNumber> s2 = new[]{
				new SimpleNumber (1),
				new SimpleNumber (2),
				new SimpleNumber (3),
			};
			Assert.AreEqual (new SimpleNumber (6), s2.Sum (new SimpleNumberMath ()));
		}
Example #20
0
 public void TestSumInt32() {
     Func<int, int, int, int> f = (a, b, c) => {
         var array = new[] { a, b, c };
         return array.Sum();
     };
     this.Test(f);
 }
Example #21
0
        private static List<int> GetLandsDistribution(IEnumerable<Card> noLandsDeck, int landCount)
        {
            var manaCounts = new[] {0, 0, 0, 0, 0};

              foreach (var card in noLandsDeck.Select(x => Cards.All[x.Name]))
              {
            foreach (var colorCount in card.ManaCost)
            {
              if (colorCount.Color.IsColorless)
            continue;

              foreach (var index in colorCount.Color.Indices)
              {
            manaCounts[index]++;
              }
            }
              }

              var totalManaCount = manaCounts.Sum();
              var distribution = manaCounts.Select(x => landCount*x/totalManaCount).ToList();
              var roundedCount = distribution.Sum();
              var roundingError = landCount - roundedCount;

              var i = 0;
              while (roundingError > 0)
              {
            var minLandCount = distribution.Where(x => x > 0).Min();

            for (var j = 0; j < distribution.Count; j++)
            {
              if (distribution[j] == minLandCount)
              {
            distribution[j]++;
            roundingError--;
            break;
              }
            }

            i++;
              }

              Asrt.True(distribution.Sum() == landCount, "Land distribution sum should equal land count.");
              return distribution;
        }
Example #22
0
 public void SumInt()
 {
     var ints = new[] { 1, 2, 3 };
     var sum = ints.Sum();
     AssertEquals(sum, 6);
 }
Example #23
0
        public void Matrix_Sum_Test()
        {
            Matrix one = new[,]
                {{1, 2, 3, 4},
                 {4, 5, 6, 5},
                 {7, 8, 9, 6}};

            Vector row = new[] { 12, 15, 18, 15 };
            Vector col = new[] { 10, 20, 30 };

            Assert.Equal(row, one.Sum(VectorType.Row));
            Assert.Equal(col, one.Sum(VectorType.Col));
            Assert.Equal(60, one.Sum());
        }
 public void UpdateTotalAmount(System.Collections.Generic.IEnumerable<BudgetItem> provider = null)
 {
     if (provider == null)
     {
         provider = this.BudgetItems;
     }
     if (provider.Count<BudgetItem>() == 0)
     {
         this.TotalAmount = this.amount;
     }
     else
     {
         this.TotalAmount = new decimal?(provider.Sum<BudgetItem>((System.Func<BudgetItem, Decimal>)(p => p.Amount)));
     }
     decimal? totalAmount = this.totalAmount;
     decimal? amount = this.amount;
     if ((totalAmount.GetValueOrDefault() > amount.GetValueOrDefault()) && (totalAmount.HasValue & amount.HasValue))
     {
         this.Amount = this.totalAmount;
     }
 }
Example #25
0
 public void TestSumInt64() {
     Func<long, long, long, long> f = (a, b, c) => {
         var array = new[] { a / 10000, b / 1000000, c / 100000000 };
         return array.Sum();
     };
     this.Test(f);
 }
        public void Run()
        {
            //Setup SQL Server Connection Factory
            var dbFactory = OrmLiteTestBase.CreateSqlServerDbFactory();

            //var dbFactory = new OrmLiteConnectionFactory(
            //    @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\App_Data\Database1.mdf;Integrated Security=True;User Instance=True",
            //    SqlServerOrmLiteDialectProvider.Instance);

            //Use in-memory Sqlite DB instead
            //var dbFactory = new OrmLiteConnectionFactory(
            //    ":memory:", false, SqliteOrmLiteDialectProvider.Instance);

            //Non-intrusive: All extension methods hang off System.Data.* interfaces
            using (IDbConnection db = dbFactory.OpenDbConnection())
            {
                //Re-Create all table schemas:
                db.DropTable<OrderDetail>();
                db.DropTable<Order>();
                db.DropTable<Customer>();
                db.DropTable<Product>();
                db.DropTable<Employee>();

                db.CreateTable<Employee>();
                db.CreateTable<Product>();
                db.CreateTable<Customer>();
                db.CreateTable<Order>();
                db.CreateTable<OrderDetail>();

                db.Insert(new Employee { Id = 1, Name = "Employee 1" });
                db.Insert(new Employee { Id = 2, Name = "Employee 2" });
                var product1 = new Product { Id = 1, Name = "Product 1", UnitPrice = 10 };
                var product2 = new Product { Id = 2, Name = "Product 2", UnitPrice = 20 };
                db.Save(product1, product2);

                var customer = new Customer {
                    FirstName = "Orm",
                    LastName = "Lite",
                    Email = "*****@*****.**",
                    PhoneNumbers =
                    {
                        { PhoneType.Home, "555-1234" },
                        { PhoneType.Work, "1-800-1234" },
                        { PhoneType.Mobile, "818-123-4567" },
                    },
                    Addresses =
                    {
                        { AddressType.Work, new Address { Line1 = "1 Street", Country = "US", State = "NY", City = "New York", ZipCode = "10101" } },
                    },
                    CreatedAt = DateTime.UtcNow,
                };
                db.Insert(customer);

                var customerId = db.GetLastInsertId(); //Get Auto Inserted Id
                customer = db.QuerySingle<Customer>(new { customer.Email }); //Query
                Assert.That(customer.Id, Is.EqualTo(customerId));

                //Direct access to System.Data.Transactions:
                using (IDbTransaction trans = db.OpenTransaction(IsolationLevel.ReadCommitted))
                {
                    var order = new Order {
                        CustomerId = customer.Id,
                        EmployeeId = 1,
                        OrderDate = DateTime.UtcNow,
                        Freight = 10.50m,
                        ShippingAddress = new Address { Line1 = "3 Street", Country = "US", State = "NY", City = "New York", ZipCode = "12121" },
                    };
                    db.Save(order); //Inserts 1st time

                    order.Id = (int)db.GetLastInsertId(); //Get Auto Inserted Id

                    var orderDetails = new[] {
                        new OrderDetail {
                            OrderId = order.Id,
                            ProductId = product1.Id,
                            Quantity = 2,
                            UnitPrice = product1.UnitPrice,
                        },
                        new OrderDetail {
                            OrderId = order.Id,
                            ProductId = product2.Id,
                            Quantity = 2,
                            UnitPrice = product2.UnitPrice,
                            Discount = .15m,
                        }
                    };

                    db.Insert(orderDetails);

                    order.Total = orderDetails.Sum(x => x.UnitPrice * x.Quantity * x.Discount) + order.Freight;

                    db.Save(order); //Updates 2nd Time

                    trans.Commit();
                }
            }
        }
        public ResponseSet UpdateResponseSetWithAnswers(System.Collections.Generic.IEnumerable<DataAccessModels.Category> categories, int responseSetID)
        {
            ResponseSet responseSet;
            using (var responseSetRepository = new ResponseSetRepository())
            {
                var answersToAdd = new List<Answer>();
                responseSet = responseSetRepository.GetResponseSetForUserByID(responseSetID);

                responseSet.IsCompleted = false;
                responseSet.DateModified = DateTime.Now;
                int incompletedAnswers = 0;
                int disabledQuestions = 0;

                foreach (var category in categories)
                    foreach (var question in category.Question)
                    {

                        var answer = responseSetRepository.GetQuestionAnswerByQuestionAndResponseSet(question.ID, responseSetID);


                        incompletedAnswers++;

                        if (question.Data.Validate())
                        {
                            incompletedAnswers--;
                            if (answer != null)
                                answer.AnswerText = question.Data.GetResult();
                            else
                            {
                                answer = new DataAccessModels.Answer
                                {
                                    AnswerText = question.Data.GetResult(),
                                    QuestionID = question.ID,
                                    ResponseSetID = responseSetID,
                                };
                                answersToAdd.Add(answer);
                            }
                        }
                        if (!question.Data.IsEnabled)
                            disabledQuestions++;
                    }

                responseSet.Progress = Math.Ceiling((1 - ((double)incompletedAnswers / (categories.Sum(c => c.Question.Count) - disabledQuestions))) * 100);
                responseSet.IsCompleted = incompletedAnswers == 0;
                responseSetRepository.AddAnswersToResponseSet(answersToAdd, responseSetID);

            }
            return responseSet;
        }
Example #28
0
 private static float TestSumSingleSelectorFunc(float a, float b, float c) {
     var array = new[] { a, b, c };
     return array.Sum(x => x * 2);
 }
Example #29
0
        private void LlenarVencimientos()
        {
            Cargando.Mostrar();

            DateTime dAhora = DateTime.Now;
            var oVentasC = Datos.GetListOf<VentasACreditoView>(c => dAhora > c.Vencimiento && c.Restante > 0).OrderBy(o => o.Cliente);
            this.dgvVencimientos.Rows.Clear();

            int iClienteID = 0;
            string sCliente = "";
            decimal mSem1, mSem2, mSem3, mSem4, mMes;
            mSem1 = mSem2 = mSem3 = mSem4 = mMes = 0;
            bool bPrimeraVuelta = true;
            foreach (var oVenta in oVentasC)
            {
                // Se verifica si es la primera vuelta, para no agregar nada pues falta ver si la siguiente es el mismo cliente
                if (bPrimeraVuelta)
                {
                    iClienteID = oVenta.ClienteID;
                    sCliente = oVenta.Cliente;
                    bPrimeraVuelta = false;
                }
                //
                if (oVenta.ClienteID != iClienteID)
                {
                    // Se agrega el cliente al grid
                    this.dgvVencimientos.Rows.Add(iClienteID, sCliente, (mSem1 + mSem2 + mSem3 + mSem4 + mMes), mSem1, mSem2, mSem3, mSem4, mMes);
                    // Se restauran los valores con el siguiente cliente
                    iClienteID = oVenta.ClienteID;
                    sCliente = oVenta.Cliente;
                    mSem1 = mSem2 = mSem3 = mSem4 = mMes = 0;
                }
                // Se calculan los importes de vencimiento por períodos de tiempo
                int iDiasVencido = (dAhora - oVenta.Vencimiento.Valor()).Days;
                if (iDiasVencido < 8)
                    mSem1 += oVenta.Restante;
                else if (iDiasVencido < 15)
                    mSem2 += oVenta.Restante;
                else if (iDiasVencido < 22)
                    mSem3 += oVenta.Restante;
                else if (iDiasVencido < 29)
                    mSem4 += oVenta.Restante;
                else
                    mMes += oVenta.Restante;
            }
            // Se agrega el último cliente, si aplica
            if (iClienteID > 0)
                this.dgvVencimientos.Rows.Add(iClienteID, sCliente, (mSem1 + mSem2 + mSem3 + mSem4 + mMes), mSem1, mSem2, mSem3, mSem4, mMes);

            // Se ordena según
            var oListaGrid = new[] { new { ClienteID = 1, Cliente = "uno", Vencido = 1.1
                , UnaSem = 1.1, DosSem = 1.1, TresSem = 1.1, CuatroSem = 1.1, MasMes = 1.1 } }.ToList();
            oListaGrid.Clear();
            foreach (DataGridViewRow oFila in this.dgvVencimientos.Rows)
                oListaGrid.Add(new
                {
                    ClienteID = Util.Entero(oFila.Cells["ClienteID"].Value),
                    Cliente = Util.Cadena(oFila.Cells["colCliente"].Value),
                    Vencido = Util.Doble(oFila.Cells["Vencido"].Value),
                    UnaSem = Util.Doble(oFila.Cells["UnaSem"].Value),
                    DosSem = Util.Doble(oFila.Cells["DosSem"].Value),
                    TresSem = Util.Doble(oFila.Cells["TresSem"].Value),
                    CuatroSem = Util.Doble(oFila.Cells["CuatroSem"].Value),
                    MasMes = Util.Doble(oFila.Cells["MasMes"].Value)
                });
            oListaGrid = oListaGrid.OrderByDescending(c => c.MasMes).ThenByDescending(c => c.CuatroSem).ThenByDescending(c => c.TresSem)
                .ThenByDescending(c => c.DosSem).ThenByDescending(c => c.UnaSem).ToList();

            // Se llenan los totales
            for (int iCol = 1; iCol < this.dgvVencimientosTotales.Columns.Count; iCol++)
                this.dgvVencimientosTotales[iCol, 0].Value = 0;
            if (oListaGrid.Count > 0)
            {
                this.dgvVencimientosTotales["tvVencido", 0].Value = oListaGrid.Sum(c => c.Vencido);
                this.dgvVencimientosTotales["tvUnaSem", 0].Value = oListaGrid.Sum(c => c.UnaSem);
                this.dgvVencimientosTotales["tvDosSem", 0].Value = oListaGrid.Sum(c => c.DosSem);
                this.dgvVencimientosTotales["tvTresSem", 0].Value = oListaGrid.Sum(c => c.TresSem);
                this.dgvVencimientosTotales["tvCuatroSem", 0].Value = oListaGrid.Sum(c => c.CuatroSem);
                this.dgvVencimientosTotales["tvMasMes", 0].Value = oListaGrid.Sum(c => c.MasMes);
            }

            // var oDatos = this.dgvVencimientos.ADataTable();
            this.dgvVencimientos.Rows.Clear();
            foreach (var oReg in oListaGrid)
            {
                this.dgvVencimientos.Rows.Add(oReg.ClienteID, oReg.Cliente, oReg.Vencido, oReg.UnaSem, oReg.DosSem, oReg.TresSem, oReg.CuatroSem, oReg.MasMes);
            }

            Cargando.Cerrar();
        }
Example #30
0
 public void TestSumDouble() {
     Func<double, double, double, double> f = (a, b, c) => {
         var array = new[] { a, b, c };
         return array.Sum();
     };
     this.Test(f);
 }