public void linq_defers_execution()
        {
            var array = new[] {"a", "b", "a", "a"};

            var filteringValue = "a";
            var results1 = array.Where(x => x == filteringValue);

            filteringValue = "b";
            var results2 = array.Where(x => x == filteringValue);

            results1.Count().Should().Be(1);
            results2.Count().Should().Be(1);
        }
        public void SplitSupportedQuery()
        {
            IQueryable<string> queryRoot = new[] { "query", "root" }.AsQueryable();
            IQueryable<string> query = queryRoot.Where(s => true).Take(5);

            IQueryable supportedQuery;
            IQueryable unsupportedQuery;

            supportedQuery = QueryComposer.Split(query, out unsupportedQuery);

            MethodCallExpression mce = supportedQuery.Expression as MethodCallExpression;
            Assert.IsNotNull(mce,
                "The first supported expression should be a method call.");
            Assert.AreEqual("Take", mce.Method.Name,
                "The first supported expression should be a Take call.");
            Assert.AreEqual(2, mce.Arguments.Count,
                "The first supported expression should have 2 arguments.");

            MethodCallExpression mce2 = mce.Arguments[0] as MethodCallExpression;
            Assert.IsNotNull(mce2,
                "The second supported expression should be a method call.");
            Assert.AreEqual("Where", mce2.Method.Name,
                "The second supported expression should be a Where call.");
            Assert.AreEqual(2, mce2.Arguments.Count,
                "The second supported expression should have 2 arguments.");

            ConstantExpression ce = mce2.Arguments[0] as ConstantExpression;
            Assert.IsNotNull(ce,
                "The first argument in the second supported expression should be constant.");

            Assert.IsNull(unsupportedQuery,
                "The unsupported query should be null.");
        }
        public void correct_iquerable_should_be_returned()
        {
            var source = new[]
            {
                new DummyDocument
                {
                    Name = "First",
                },
                new DummyDocument
                {
                    Name = "Middle",
                },
                new DummyDocument
                {
                    Name = "Last",
                }
            }
            .AsQueryable();

            var sortedData = source.DynamicFiltering("name", "Last");

            var expectedSortedData = source.Where(document => document.Name == "Last");

            sortedData.SequenceEqual(expectedSortedData).Should().BeTrue();
        }
Exemplo n.º 4
0
        public void Foo()
        {
            // Single accepts a predicate - the Where is superfluous
               var stuff = new []{"Josh", "was", "here"};

               var less = stuff.Where(x => x.StartsWith("J")).Single();
        }
        /*begin*/
        public ActionResult GetItems(GridParams g, string[] selectedColumns, bool? choosingColumns)
        {
            //when setting columns from here we don't get the grid defaults, so we have to specify Sortable, Groupable etc.
            var columns = new[]
                              {
                                  new Column { Name = "Id", Width = 70, Order = 1 },
                                  new Column { Name = "Person", Sortable = true, Groupable = true, GroupRemovable = true, Order = 2 },
                                  new Column { Name = "Food", Sortable = true, Groupable = true, GroupRemovable = true, Order = 3 },
                                  new Column { Name = "Location", Sortable = true, Groupable = true, GroupRemovable = true, Order = 4 },
                                  new Column { Name = "Date", Sortable = true, Groupable = true, GroupRemovable = true, Width = 100, Order = 5 },
                                  new Column { Name = "Price", Sortable = true, Groupable = true, GroupRemovable = true, Width = 100, Order = 6 },
                              };

            var baseColumns = new[] { "Id", "Person" };

            //first load
            if (g.Columns.Length == 0)
            {
                g.Columns = columns;
            }

            if (choosingColumns.HasValue && selectedColumns == null)
            {
                selectedColumns = new string[] { };
            }

            if (selectedColumns != null)
            {
                //make sure we always have Id and Person columns
                selectedColumns = selectedColumns.Union(baseColumns).ToArray();

                var currectColumns = g.Columns.ToList();

                //remove unselected columns
                currectColumns = currectColumns.Where(o => selectedColumns.Contains(o.Name)).ToList();

                //add missing columns
                var missingColumns = selectedColumns.Except(currectColumns.Select(o => o.Name)).ToArray();

                currectColumns.AddRange(columns.Where(o => missingColumns.Contains(o.Name)));

                g.Columns = currectColumns.ToArray();
            }

            var gridModel = new GridModelBuilder<Lunch>(Db.Lunches.AsQueryable(), g).Build();

            // used to populate the checkboxlist
            gridModel.Tag =
                new
                    {
                        columns = columns.Select(o => o.Name).Except(baseColumns).ToArray(),
                        selectedColumns = g.Columns.Select(o => o.Name).Except(baseColumns).ToArray()
                    };

            return Json(gridModel);
        }
Exemplo n.º 6
0
        public override void Load()
        {
            var types = new[] {typeof (ILogInAccounts), typeof (LogInAccounts), GetType()}
                .Select(type => type.Assembly)
                .SelectMany(assembly => assembly.GetTypes())
                .ToArray();

            var services = types.Where(t => t.IsInterface && !t.IsGenericTypeDefinition);

            var implementations = types.Where(t => t.IsClass && !t.IsAbstract && !t.IsGenericTypeDefinition);

            services.SelectMany(t => implementations, (service, impl) => new {service, impl})
                    .Where(x => x.service.IsAssignableFrom(x.impl))
                    .GroupBy(x => x.service, x => x.impl)
                    .Where(g => g.Count() == 1)
                    .Select(g => new {service = g.Key, impl = g.Single()})
                    .ToList()
                    .ForEach(x => Kernel.Bind(x.service).To(x.impl).InRequestScope());
        }
        public override string[] Complete(Shell shell, string[] tokens)
        {
            var items = new[] {"users"};

            if (tokens.Length == 0)
            {
                return items;
            }

            return tokens.Length == 1 ? items.Where(x => x.StartsWith(tokens[0])).ToArray() : null;
        }
Exemplo n.º 8
0
        public void Switch()
        {
            var table = new[]
            {
                new { pre = ReelState.Stop, post = ReelState.Cycle },
                new { pre = ReelState.Cycle, post = ReelState.Stop },
            };

            State = table.Where(t => t.pre == State)
                         .First()
                         .post;
        }
        private void LoadLanguageList()
        {
            var settings = new[]
            {
                new DisplayLanguageSetting("en-US"),
                new DisplayLanguageSetting("fr-CA"),
                new DisplayLanguageSetting("sv-SV")
            };

            LanguageList.Items.AddRange(settings.Where(item => item.Exists).ToArray());
            LanguageList.DisplayMember = "Name";
        }
Exemplo n.º 10
0
        public void CanUsePredicates()
        {
            var source = new[] { 1, 2, 3, 4, 5 };

            var isEven = new Pred<int>(x => x%2 == 0);
            var isOdd = isEven.Invert();
            var isOddOr2 = isOdd.Or(x => x == 2);

            var count = source.Where(isOddOr2).Count();

            Assert.AreEqual(4, count);
        }
Exemplo n.º 11
0
        public void Syoka()
        {
            var table = new[]
            {
                new { pre = KakuhenMode.Normal, post = KakuhenMode.Kakuhen1 },
                new { pre = KakuhenMode.Kakuhen1, post = KakuhenMode.Kakuhen2 },
                new { pre = KakuhenMode.Kakuhen2, post = KakuhenMode.Kakuhen1 },
            };

            Mode = table.Where(t => t.pre == Mode)
                        .First()
                        .post;
        }
Exemplo n.º 12
0
        public override string ToString()
        {
            var result = new[] {
                                   VersionType.IsNullOrEmpty() ? "" : "\"_version_type\": " + VersionType.Quotate(),
                                   Version == null             ? "" : "\"_version\": " + Version.AsString(),
                                   Routing.IsNullOrEmpty()     ? "" : "\"_routing\": " + Routing.Quotate(),
                                   Percolate.IsNullOrEmpty()   ? "" : "\"_percolate\": " + Percolate.Quotate(),
                                   Parent.IsNullOrEmpty()      ? "" : "\"_parent\": " + Parent.Quotate(),
                                   Timestamp.IsNullOrEmpty()   ? "" : "\"_timestamp\": " + Timestamp.Quotate(),
                                   Ttl.IsNullOrEmpty()         ? "" : "\"_ttl\": " + Ttl.Quotate(),
                               };

            return result.Where(s => !s.IsNullOrEmpty()).JoinWithComma();
        }
        public void Rebase()
        {
            IQueryable<string> queryRoot = new[] { "query", "root" }.AsQueryable();
            IQueryable<string> query = queryRoot.Where(s => true);

            MethodCallExpression mce = query.Expression as MethodCallExpression;
            Assert.IsNotNull(mce,
                "Expression should be a method call.");
            Assert.AreEqual("Where", mce.Method.Name,
                "Expression should be a Where call.");
            Assert.AreEqual(2, mce.Arguments.Count,
                "Expression should have 2 arguments.");

            ConstantExpression ce = mce.Arguments[0] as ConstantExpression;
            Assert.IsNotNull(ce,
                "The first expression argument should be constant.");
            Assert.AreEqual(queryRoot, ce.Value,
                "The first expression argument should be the query root.");

            IQueryable<string> newQueryRoot = new[] { "new", "query", "root" }.AsQueryable();

            IQueryable rebasedQuery = QueryComposer.Compose(newQueryRoot, query);

            mce = rebasedQuery.Expression as MethodCallExpression;
            Assert.IsNotNull(mce,
                "Rebased expression should be a method call.");
            Assert.AreEqual("Where", mce.Method.Name,
                "Rebased expression should be a Where call.");
            Assert.AreEqual(2, mce.Arguments.Count,
                "Rebased expression should have 2 arguments.");

            ce = mce.Arguments[0] as ConstantExpression;
            Assert.IsNotNull(ce,
                "The first rebased expression argument should be constant.");
            Assert.AreEqual(newQueryRoot, ce.Value,
                "The first rebased expression argument should be the new query root.");
        }
        /// <summary>
        /// Checks that the API key passed looks like a GW2 API key (follows a length pattern between delimiters and is alpha numeric).
        /// </summary>
        /// <param name="possibleKey">
        /// The possible API key.
        /// </param>
        /// <returns>
        /// True if the possibleKey looks like a valid GW2 API key.
        /// </returns>
        public static bool LookLikeAValidGuildWarsTwoApiKey(string possibleKey)
        {
            const char Delimiter = '-';

            var expectedTokenLengths = new [] { 8, 4, 4, 4, 20, 4, 4, 4, 12 };

            var tokens = possibleKey.Split(Delimiter);

            var actualTokenLengths = tokens.Select(t => t.Length).ToArray();

            if (expectedTokenLengths.Length != actualTokenLengths.Length)
            {
                return false;
            }

            if (expectedTokenLengths.Where((t, index) => actualTokenLengths[index] != t).Any())
            {
                return false;
            }

            var allAlphaNumericChars = tokens.All(t => t.All(char.IsLetterOrDigit));

            return allAlphaNumericChars;
        }
Exemplo n.º 15
0
 public ActionResult PredictiveSearch(string keywordStartsWith)
 {
     var data = new[] { "London", "Manchester", "Manchester Airport", "London Kings Cross", "London Euston" };
     var results = data.Where(s => s.StartsWith(keywordStartsWith)).ToArray();
     return new JsonResult { ContentEncoding = Encoding.UTF8, Data = results, ContentType = "application/json", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
 }
Exemplo n.º 16
0
        public override void Execute()
        {
            if (!SpellManager.ShouldCast(false))
            {
                return;
            }

            const int range = 1100;
            const float hitchance = 56f;
            const float aoeratio = 0.2f;

            var enemies = EntityManager.Heroes.Enemies.Where(n => n.IsValidTarget(range));
            var selectedTarget = TargetSelector.GetTarget(range, DamageType.Magical);
            var allTargets =
                new[] {selectedTarget}.Concat(
                    enemies.Where(n => n.Index != selectedTarget.Index)
                        .OrderByDescending(n => Damage.TotalDamage(SpellSlot.Q, n)/n.Health)).Where(n => n.IsValidTarget() && !n.WillDie());

            if (selectedTarget == null && !enemies.Any())
            {
                return;
            }

            #region Killsteal logic

            var ksQ = Config.Menu["ksQ"].Cast<CheckBox>().CurrentValue &&
                      Player.CanUseSpell(SpellSlot.Q) == SpellState.Ready;
            var ksW = Config.Menu["ksW"].Cast<CheckBox>().CurrentValue &&
                      Player.CanUseSpell(SpellSlot.W) == SpellState.Ready;
            var ksE = Config.Menu["ksE"].Cast<CheckBox>().CurrentValue &&
                      Player.CanUseSpell(SpellSlot.E) == SpellState.Ready;
            var ksR = Config.Menu["ksR"].Cast<CheckBox>().CurrentValue &&
                      Player.CanUseSpell(SpellSlot.R) == SpellState.Ready;

            foreach (var enemy in allTargets)
            {
                if (ksE && Player.Instance.IsInRange(enemy, E.Range) && enemy.Killable(SpellSlot.E))
                {
                    E.Cast(enemy);
                    return;
                }

                if (ksW && Player.Instance.IsInRange(enemy, W.Range + W.Radius) && enemy.Killable(SpellSlot.W))
                {
                    var prediction = W.GetPrediction(enemy);

                    if (prediction.HitChancePercent >= hitchance)
                    {
                        W.Cast(prediction.CastPosition);
                        return;
                    }
                }

                if (ksQ && Player.Instance.IsInRange(enemy, Q.Range) && enemy.Killable(SpellSlot.Q))
                {
                    var prediction = Q.GetPrediction(enemy);

                    if (prediction.HitChancePercent >= hitchance)
                    {
                        Q.Cast(prediction.CastPosition);
                        return;
                    }
                }

                if (ksR && Player.Instance.IsInRange(enemy, R.Range) && enemy.Killable(SpellSlot.R))
                {
                    R.Cast(enemy);
                    return;
                }
            }

            #endregion

            #region Combo logic

            var useQ = Config.Menu["comboQ"].Cast<CheckBox>().CurrentValue &&
                       Player.CanUseSpell(SpellSlot.Q) == SpellState.Ready;
            var useW = Config.Menu["comboW"].Cast<CheckBox>().CurrentValue &&
                       Player.CanUseSpell(SpellSlot.W) == SpellState.Ready;
            var useE = Config.Menu["comboE"].Cast<CheckBox>().CurrentValue &&
                       Player.CanUseSpell(SpellSlot.E) == SpellState.Ready;
            var useR = Config.Menu["comboR"].Cast<CheckBox>().CurrentValue &&
                       Player.CanUseSpell(SpellSlot.R) == SpellState.Ready;

            // check for AOE then single target burst        
            // check W first
            if (enemies.Count() > 1)
            {
                if (useW)
                {
                    var aoePrediction =
                        Prediction.Position.PredictCircularMissileAoe(enemies.Cast<Obj_AI_Base>().ToArray(), W.Range,
                            W.Radius, W.CastDelay, W.Speed)
                            .OrderByDescending(r => r.GetCollisionObjects<Obj_AI_Minion>().Length)
                            .FirstOrDefault();

                    if (aoePrediction != null)
                    {
                        var predictedHeroes = aoePrediction.GetCollisionObjects<AIHeroClient>();

                        if (predictedHeroes.Length > 1 && (float) predictedHeroes.Length/enemies.Count() >= aoeratio)
                        {
                            W.Cast(aoePrediction.CastPosition);
                            return;
                        }
                    }
                }

                // check E next
                if (useE)
                {
                    var enemyE =
                        enemies.Where(n => n.IsValidTarget(E.Range) && n.IsBlazed())
                            .OrderByDescending(n => n.CountEnemiesInRange(SpellManager.ConflagrationSpreadRange))
                            .FirstOrDefault();

                    if (enemyE != null && enemyE.CountEnemiesInRange(SpellManager.ConflagrationSpreadRange) > 1)
                    {
                        E.Cast(enemyE);
                        return;
                    }
                }
            }

            // single target burst
            if (useE)
            {
                var targets = allTargets.Where(n => Player.Instance.IsInRange(n, E.Range));

                foreach (var target in targets)
                {
                    E.Cast(target);
                    return;
                }
            }

            if (useW)
            {
                foreach (var target in allTargets)
                {
                    if (W.Cast(target))
                    {
                        return;
                    }
                }
            }

            if (useQ)
            {
                foreach (var target in allTargets.Where(n => n.IsBlazed()))
                {
                    if (Q.Cast(target))
                    {
                        return;
                    }
                }
            }

            if (useR)
            {
                var bestTarget =
                    allTargets.Where(n => Player.Instance.IsInRange(n, R.Range))
                        .OrderByDescending(n => n.CountEnemiesInRange(SpellManager.PyroclasmSpreadRange))
                        .FirstOrDefault();

                if (bestTarget != null &&
                    bestTarget.CountEnemiesInRange(SpellManager.PyroclasmSpreadRange) >=
                    Config.Menu["minEnemiesR"].Cast<Slider>().CurrentValue)
                {
                    if ((!useW && !useE || bestTarget.IsBlazed()))
                    {
                        R.Cast(bestTarget);
                    }
                }
            }

            #endregion
        }
Exemplo n.º 17
0
        //public class A
        //{
        //    public string Name { get; set; }
        //}
        public static void Test(Assert assert)
        {
            assert.Expect(8);

            // TEST
            var numbers = new[] { 1, 3, 5, 7 };
            var numberPlusOne = (from n in numbers select n + 1).ToArray();
            assert.DeepEqual(numberPlusOne, new[] { 2, 4, 6, 8 }, "A sequence of ints one higher than the numbers[]");

            // TEST
            var persons = Person.GetPersons();
            var names = (from p in persons select p.Name).ToArray();
            assert.DeepEqual(names, new[] { "Frank", "Zeppa", "John", "Billy", "Dora", "Ian", "Mary", "Nemo" }, "Selects names as instance field");

            // TEST
            string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

            var textNumbers = (from n in numbers select strings[n]).ToArray();
            assert.DeepEqual(textNumbers, new[] { "one", "three", "five", "seven" }, "Selects names as items of another array");

            // TEST
            var anonimNames = (from p in persons select new { Name = p.Name }).ToArray();

            object[] anonimNamesToCompare = {
                                                new { Name = "Frank" }, new { Name = "Zeppa" }, new { Name = "John" },
                                                new { Name = "Billy" }, new { Name = "Dora" }, new { Name = "Ian" },
                                                new { Name = "Mary" }, new { Name = "Nemo" } };

            assert.DeepEqual(anonimNames, anonimNamesToCompare, "Selects names as an anonymous type");

            // TEST
            numbers = new[] { 0, 1, 3, 3 };

            var numberssInPlace = numbers
                                    .Select((n, index) => new
                                        {
                                            Number = n,
                                            IsIndex = n == index
                                        })
                                    .ToArray();

            object[] anonimNumbersToCompare = { new { Number = 0, IsIndex = true },
                                                  new { Number = 1, IsIndex = true },
                                                  new { Number = 3, IsIndex = false },
                                                  new { Number = 3, IsIndex = true }
                                              };

            assert.DeepEqual(numberssInPlace, anonimNumbersToCompare, "Selects numbers as an anonymous type");

            // TEST
            var numbersA = new[] { 1, 5, 2 };
            var numbersB = new[] { 3, 4, 2 };
            var simplePairs =
                (from a in numbersA
                 from b in numbersB
                 where a < b
                 select new { A = a, B = b }
                ).ToArray();

            object[] expectedSimplePairs = { new { A = 1, B = 3 }, new { A = 1, B = 4 }, new { A = 1, B = 2 }, new { A = 2, B = 3 }, new { A = 2, B = 4 } };

            assert.DeepEqual(simplePairs, expectedSimplePairs, "Join two numeric arrays with one where clause");

            // TEST
            numbersA = new[] { 1, 5, 2, 4, 3 };
            numbersB = new[] { 3, 4, 2, 5, 1 };

            var pairs =
                (from a in numbersA
                where a > 1
                from b in numbersB
                where b < 4 && a > b
                select new { Sum = a + b }
                ).ToArray();

            object[] expectedPairs = { new { Sum = 8}, new { Sum = 7}, new { Sum = 6}, new { Sum = 3},
                                     new { Sum = 7}, new { Sum = 6}, new { Sum = 5},
                                     new { Sum = 5}, new { Sum = 4},};

            assert.DeepEqual(pairs, expectedPairs, "Join two numeric arrays with two where clauses");

            // TEST
            numbersA = new[] { 1, 5, 2, 4, 3 };
            numbersB = new[] { 3, 4, 2, 5, 1 };

            var manyNumbers = numbersA
                .SelectMany((a, aIndex) => numbersB.Where(b => a == b && b > aIndex).Select(b => new { A = a, B = b, I = aIndex }))
                .ToArray();

            object[] expectedManyNumbers = { new { A = 1, B = 1, I = 0 },
                                           new { A = 5, B = 5, I = 1 },
                                           new { A = 4, B = 4, I = 3 }};

            assert.DeepEqual(manyNumbers, expectedManyNumbers, "SelectMany() two number arrays");
        }
        public void Where()
        {
            var source =
                new[]
                {
                    new TestObject {Id = 1}.ToSome(),
                    Maybe<TestObject>.None,
                    new TestObject {Id = 2}.ToSome(),
                    new TestObject {Id = 3}.ToSome()
                };

            var results = source.Where(x => x.Id >= 2).ToArray();

            CollectionAssert.AreEqual(new[] {source[2], source[3]}, results);
        }
Exemplo n.º 19
0
 public void Test()
 {
     string[] coll = new[] {"aaa", "bb"};
     string[] strings = coll.Where(s => s.Length == 2).ToArray();
 }