Example #1
0
        static void Main(string[] args)
        {
            MyClass objectOne = new MyClass { Param = "Something", NonImportantParam = 10 };
            MyClass objectTwo = new MyClass { Param = "Something", NonImportantParam = 20 };

            Console.WriteLine("ObjectOne == objectTwo ? {0}", (objectOne == objectTwo).ToString());
            Console.WriteLine("ObjectOne equals to objectTwo ? {0}", (objectOne.Equals(objectTwo)).ToString());

            List<MyClass> myList = new List<MyClass>
            {
                new MyClass{ Param = "Something!", NonImportantParam = 10 },
                new MyClass{ Param = "Something", NonImportantParam = 20 }
            };

            List<MyClass> anotherList = new List<MyClass>
            {
                new MyClass{ Param = "!Something", NonImportantParam = 10 },
                new MyClass{ Param = "Something", NonImportantParam = 30 }
            };

            Console.WriteLine("objectOne in the list one at pos : {0}", myList.IndexOf(objectOne));
            Console.WriteLine("objectOne in the list two at pos : {0}", anotherList.IndexOf(objectOne));
            Console.WriteLine("Both list have in common:");
            foreach (var item in myList.Intersect(anotherList))
            {
                Console.WriteLine("\t {0}", item.Param);
            }
            // Using static methods.
            Console.WriteLine("O1 and P2 have same state: {0}", object.Equals(objectOne, objectTwo));
            Console.WriteLine("O1 and O2 are pointing to same object: {0}",
            object.ReferenceEquals(objectOne, objectTwo));
        }
Example #2
0
        public Intersect1()
        {
            IList<int> firstList = new List<int>
                                       {
                                           1,
                                           2,
                                           3,
                                           4,
                                           5
                                       };

            IList<int> secondList = new List<int>
                                        {
                                            1,
                                            3,
                                            5,
                                            7
                                        };

            var commonNumbers = firstList.Intersect(secondList);

            Console.WriteLine("Common numbers between two lists");

            foreach (int commonNumber in commonNumbers)
            {
                Console.WriteLine(commonNumber);
            }
        }
 public void Intersect()
 {
     var Orwells = new List<string> {"1984", "Animal Farm", "Homage to Catalonia", "Burmese Days"};
     var great_novels = new List<string> {"Hear of Darkness", "1984", "Animal Farm", "Ulysses"};
     var Orwells_great_novels = great_novels.Intersect(Orwells).ToList();
     Assert.Equal(Orwells_great_novels, FILL_ME_IN);
 }
Example #4
0
        public static bool IsConditionallyRemoved(InvocationExpression invocationExpression, IEntity entity)
 		{
            if (entity == null)
            {
                return false;
            }
 			var result = new List<string>();
 			foreach (var a in entity.Attributes)
 			{
 				var type = a.AttributeType.GetDefinition();
 				if (type != null && type.FullName.Equals("System.Diagnostics.ConditionalAttribute", StringComparison.Ordinal))
                {
 					if (a.PositionalArguments.Count > 0)
                    {
 						var symbol = a.PositionalArguments[0].ConstantValue as string;
                        if (symbol != null)
                        {
                            result.Add(symbol);
                        }
 					}
 				}
 			}

            if (result.Count > 0)
            {
                var syntaxTree = invocationExpression.GetParent<SyntaxTree>();
                if (syntaxTree != null)
                {
                    return !result.Intersect(syntaxTree.ConditionalSymbols).Any();    
                }
            }

 			return false;
 		}
        //2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
        //What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 12?
        public int FindLcm()
        {
            var twelves = new List<int>();
            var elevens = new List<int>();
            var tens = new List<int>();
            var nines = new List<int>();
            var eights = new List<int>();
            var sevens = new List<int>();
            var sixes = new List<int>();
            var fives = new List<int>();
            var fours = new List<int>();

            for (int i = 1; i <= 10000; i++)
            {
                twelves.Add(i * 12);
                elevens.Add(i * 11);
                tens.Add(i * 10);
                nines.Add(i * 9);
                eights.Add(i * 8);
                sevens.Add(i * 7);
                sixes.Add(i * 6);
                fives.Add(i * 5);
                fours.Add(i * 4);
            }

            var multiples =
                twelves.Intersect(elevens).
                Intersect(tens).Intersect(nines).
                Intersect(eights).Intersect(sevens)
                .Intersect(sixes).Intersect(fives).
                Intersect(fours).ToList();

            return multiples[0];
        }
 public static List<string> GetListOfAvailableUtilities(string path, List<string> utilitiesNames)
 {
     List<string> availableUtilities = new List<string>();
     try
     {
         //List<string> utilitiesInDirectory = Directory.GetFiles(path, "gdal*.exe").ToList<string>();
         List<string> utilitiesInDirectory = Directory.GetFiles(path, "*.exe").ToList<string>();
         if (utilitiesInDirectory.Count > 0)
         {
             for (int i = 0; i < utilitiesInDirectory.Count; i++)
             {
                 utilitiesInDirectory[i] =
                     Path.GetFileNameWithoutExtension(utilitiesInDirectory[i]);
             }
         }
         availableUtilities =
             utilitiesNames.Intersect(utilitiesInDirectory).ToList<string>();
     }
     catch (Exception e)
     {
         MessageBox.Show("Не удалось определить количество доступных утилит" +
             Environment.NewLine + e.Message);
     }
     return availableUtilities;
 }
        public List<PhonebookEntry> Find(string name, string town)
        {
            var listsNames = this.entriesByName.Values;
            var resultNames = new List<PhonebookEntry>();
            foreach (var list in listsNames)
            {
                if (list != null)
                {
                    if (list.Any(x => x.ToLower().Contains(name)))
                    {
                        resultNames.Add(
                            this.entriesByName.FirstOrDefault(x => x.Value.Any(y => y.ToLower().Contains(name))).Key);
                    }
                }
            }

            var listsTowns = this.entriesByTown.Values;
            var resultTowns = new List<PhonebookEntry>();
            foreach (var list in listsTowns)
            {
                if (list != null)
                {
                    if (list.Any(x => x.ToLower().Contains(town)))
                    {
                        resultTowns.Add(
                            this.entriesByTown.FirstOrDefault(x => x.Value.Any(y => y.ToLower().Contains(town))).Key);
                    }
                }
            }

            return resultNames.Intersect(resultTowns).ToList();
        }
Example #8
0
        private void button1_Click(object sender, EventArgs e)
        {
            int interval1 = int.Parse(textBox1.Text);
            int interval2 = int.Parse(textBox2.Text);
            int interval3 = int.Parse(textBox3.Text);
            int interval4 = int.Parse(textBox4.Text);

            List<int> niz1 = new List<int>();
            List<int> niz2 = new List<int>();

            for (int i =interval1; i <= interval2; i++)
            {
                niz1.Add(i);
            }
            for (int i = interval3; i <= interval4; i++)
            {
                niz2.Add(i);
            }

            IEnumerable<int> novi = niz1.Intersect(niz2);
            string rezultat="";

            foreach(int broj in novi)
            {
                rezultat+=broj.ToString()+", ";
            }
            MessageBox.Show(rezultat);
        }
Example #9
0
        static void Main(string[] args)
        {
            IDictionary<string, FileInfo> missingCarnets = new Dictionary<string, FileInfo>();
            GetCarnetNumbers().Apply(carnet => missingCarnets.Add(carnet, null));

            new DirectoryInfo(@"E:\ATIRS0V7\IRU_TO_ASSOCIATIONS\ATIRS_TO_ASSOCIATION_053\2012\2012-06").GetDirectories().Apply(folder =>
             {
                 folder.GetFiles("*.*").Apply(file =>
                 {
                     List<string> carnetsInFile = new List<string>();
                     Console.Out.Write("Parsing file {0}.", file.Name);
                     file.ProcessLines(line =>
                         {
                             int i = line.IndexOf(":+:TNO");
                             if (i > 0)
                             {
                                 string carnet = line.Substring(i + 8, 8);
                                 carnetsInFile.Add(carnet);
                             }
                         }, true);
                     Console.Out.WriteLine(" Found {0} carnets: []", carnetsInFile.Count); //, carnetsInFile.ToString(", ", true));
                     carnetsInFile.Intersect(missingCarnets.Keys).Apply(carnet => missingCarnets[carnet] = file);
                 });

                 /*new DirectoryInfo(@"E:\ATIRS0V7\IRU_TO_ASSOCIATIONS\ATIRS_TO_ASSOCIATION_053").GetSubDirectoryInfo("2012", "2012-06").GetFiles("*.*").Apply(file =>
                     {
                         List<string> carnetsInFile = new List<string>();
                         Console.Out.Write("Parsing file {0}.", file.Name);
                         file.ProcessLines(line =>
                             {
                                 int i = line.IndexOf(":+:TNO");
                                 if (i > 0)
                                 {
                                     string carnet = line.Substring(i + 8, 8);
                                     carnetsInFile.Add(carnet);
                                 }
                             }, true);
                         Console.Out.WriteLine(" Found {0} carnets: [{1}]", carnetsInFile.Count, carnetsInFile.ToString(", ", true));
                         carnetsInFile.Intersect(missingCarnets.Keys).Apply(carnet => missingCarnets[carnet] = file);
                     });*/
                 /*new LocalCARPaths().ARCHIVED_PROCESSED_SAFETIR_TERMINATION_FILES_FOLDER.GetFiles("C2I_*_201207*.*", "C2I_*_201208*.*").Apply(file =>
                             {
                                 List<string> carnetsInFile = new List<string>();
                                 Console.Out.Write("Parsing file {0}.", file.Name);
                                 file.ProcessLines(line =>
                                     {
                                         int i = line.IndexOf(":+:TNO");
                                         if (i > 0)
                                         {
                                             string carnet = line.Substring(i + 8, 8);
                                             carnetsInFile.Add(carnet);
                                         }
                                     }, true);
                                 Console.Out.WriteLine(" Found {0} carnets: []", carnetsInFile.Count); //, carnetsInFile.ToString(", ", true));
                                 carnetsInFile.Intersect(missingCarnets.Keys).Apply(carnet => missingCarnets[carnet] = file);
                             });*/

                 missingCarnets.Keys.Apply(carnet => Console.Out.WriteLine("Carnet {0} => {1}", carnet, missingCarnets[carnet] != null ? missingCarnets[carnet].Name : "Not found"));
             });
        }
        private async Task<List<BabyName>> GetNamesByCountryCode(IList<string> countryCodes)
        {
            var namesTotal = new List<BabyName>();

            foreach (string countryCode in countryCodes)
            {
                Country country = db.Countries.SingleOrDefault(x => x.CountryCode == countryCode);

                if(country == null)
                {
                    Trace.WriteLine($"The country with country code '{countryCode}' does not exist");
                    continue;
                }

                List<BabyName> namesFromCountry = await db.Names.Where(x => x.CountryId == country.Id).ToListAsync();

                if (namesTotal.Any())
                {
                    namesTotal = namesTotal.Intersect(namesFromCountry, new SimilarNameComparer()).ToList();
                }
                else
                {
                    namesTotal = namesFromCountry;
                }
            }

            return namesTotal.OrderBy(x => x.Name).ToList();
        }
Example #11
0
        public void Intersection()
        {
            var a = new List<Customer>
                {
                    new Customer { Id = 0, FirstName = "Adelia", LastName = "Kessler", Address = new Address { Street = "16256 Reichel Plains", City = "Ryanbury", State = "VA", Zip = "58851" }},
                    new Customer { Id = 1, FirstName = "Melissa", LastName = "Labadie", Address = new Address { Street = "4751 Johan Landing", City = "East Bettye", State = "SD", Zip = "54538" }},
                    new Customer { Id = 2, FirstName = "Gerard", LastName = "Gerhold", Address = new Address { Street = "242 Friesen Locks", City = "Jaylenhaven", State = "PR", Zip = "86606" }},
                };

            var b = new List<Customer>
                {
                    new Customer { Id = 0, FirstName = "Adelia", LastName = "Kessler", Address = new Address { Street = "16256 Reichel Plains", City = "Ryanbury", State = "VA", Zip = "58851" }},
                    new Customer { Id = 1, FirstName = "Melissa", LastName = "Labadie", Address = new Address { Street = "4751 Johan Landing", City = "East Bettye", State = "SD", Zip = "54538" }},
                    new Customer { Id = 2, FirstName = "Gerard", LastName = "Gerhold", Address = new Address { Street = "242 Friesen Locks", City = "Jaylenhaven", State = "PR", Zip = "86606" }},
                    new Customer { Id = 3, FirstName = "Clemens", LastName = "Kassulke", Address = new Address { Street = "0584 Leffler Garden", City = "East Cathy", State = "KY", Zip = "05828" }},
                    new Customer { Id = 4, FirstName = "Cloyd", LastName = "Heaney", Address = new Address { Street = "2486 Graham Junction", City = "New Pietro", State = "AE", Zip = "66483" }},
                };

            var results = a.Intersect(b).ToList();

            Assert.AreEqual(3, results.Count());
            Assert.AreEqual(0, results[0].Id);
            Assert.AreEqual(1, results[1].Id);
            Assert.AreEqual(2, results[2].Id);
        }
        private static bool ContainsAllItems(List<string> a, List<string> b)
        {

           if(a.Intersect(b).Count() > 0)
                return true;

           return false;
        }
        public static int GetLevelOfSimilarity(List<string> source, List<string> comparable)
        {
            var intersect = comparable.Intersect(source);
            var weight = 0;
            foreach (var word in intersect)
                weight += word.Length;

            return weight;
        }
Example #14
0
        /// <summary>Online evaluation for rankings of items</summary>
        /// <remarks>
        /// The evaluation protocol works as follows:
        /// For every test user, evaluate on the test items, and then add the those test items to the training set and perform an incremental update.
        /// The sequence of users is random.
        /// </remarks>
        /// <param name="recommender">the item recommender to be evaluated</param>
        /// <param name="test">test cases</param>
        /// <param name="training">training data (must be connected to the recommender's training data)</param>
        /// <param name="test_users">a list of all test user IDs</param>
        /// <param name="candidate_items">a list of all candidate item IDs</param>
        /// <param name="candidate_item_mode">the mode used to determine the candidate items</param>
        /// <returns>a dictionary containing the evaluation results (averaged by user)</returns>
        public static ItemRecommendationEvaluationResults EvaluateOnline(
			this IRecommender recommender,
			IPosOnlyFeedback test, IPosOnlyFeedback training,
			IList<int> test_users, IList<int> candidate_items,
			CandidateItems candidate_item_mode)
        {
            var incremental_recommender = recommender as IIncrementalItemRecommender;
            if (incremental_recommender == null)
                throw new ArgumentException("recommender must be of type IIncrementalItemRecommender");

            // prepare candidate items once to avoid recreating them
            switch (candidate_item_mode)
            {
                case CandidateItems.TRAINING: candidate_items = training.AllItems; break;
                case CandidateItems.TEST:     candidate_items = test.AllItems; break;
                case CandidateItems.OVERLAP:  candidate_items = new List<int>(test.AllItems.Intersect(training.AllItems)); break;
                case CandidateItems.UNION:    candidate_items = new List<int>(test.AllItems.Union(training.AllItems)); break;
            }

            test_users.Shuffle();
            var results_by_user = new Dictionary<int, ItemRecommendationEvaluationResults>();
            foreach (int user_id in test_users)
            {
                if (candidate_items.Intersect(test.ByUser[user_id]).Count() == 0)
                    continue;

                // prepare data
                var current_test_data = new PosOnlyFeedback<SparseBooleanMatrix>();
                foreach (int index in test.ByUser[user_id])
                    current_test_data.Add(user_id, test.Items[index]);
                // evaluate user
                var current_result = Items.Evaluate(recommender, current_test_data, training, current_test_data.AllUsers, candidate_items, CandidateItems.EXPLICIT);
                results_by_user[user_id] = current_result;

                // update recommender
                var tuples = new List<Tuple<int, int>>();
                foreach (int index in test.ByUser[user_id])
                    tuples.Add(Tuple.Create(user_id, test.Items[index]));
                incremental_recommender.AddFeedback(tuples);
            }

            var results = new ItemRecommendationEvaluationResults();

            foreach (int u in results_by_user.Keys)
                foreach (string measure in Items.Measures)
                    results[measure] += results_by_user[u][measure];

            foreach (string measure in Items.Measures)
                results[measure] /= results_by_user.Count;

            results["num_users"] = results_by_user.Count;
            results["num_items"] = candidate_items.Count;
            results["num_lists"] = results_by_user.Count;

            return results;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            List<string> lst1 = new List<string>() {"January","February","March"};
            List<string> lst2 = new List<string>() {"January", "April", "March" };
            List<string> lst3 = new List<string>() { "January", "April", "March", "May" };
            List<string> lst4 = new List<string>() { "Jan", "Feb", "Jan", "April", "Feb" };
            IEnumerable<string> lstNew = null;

            lstNew = lst1.Intersect(lst2, StringComparer.OrdinalIgnoreCase);
            PrintList(lstNew);
        }
Example #16
0
        public static object[] search(string phoneNumber)
        {
            List<ABPerson> singlePeople = new List<ABPerson> ();
            phoneNumber = Regex.Replace (phoneNumber, "[^0-9]", "");
            ABAddressBook ab = new ABAddressBook ();
            var people = ab.Where (x => x is ABPerson).Cast<ABPerson> ().Where (x => x.GetPhones ().Where (p => Regex.Replace (p.Value, "[^0-9]", "").Contains (phoneNumber) || phoneNumber.Contains (Regex.Replace (p.Value, "[^0-9]", ""))).Count () > 0).ToArray ();
            foreach (var person in people) {
                if (singlePeople.Intersect (person.GetRelatedNames ().Cast<ABPerson> ()).Count () <= 0)
                    singlePeople.Add (person);

            }
            return singlePeople.ToArray ();
        }
Example #17
0
 /// <summary>
 /// Create a new SmartObjectSelector with the given type, roles and isParticipant.
 /// </summary>
 /// <param name="type">The needed type of the object.</param>
 /// <param name="roles">The roles needed to be satisfied for the different indices.</param>
 /// <param name="isParticipant">Whether the object is a participant.</param>
 public SmartObjectSelector(Type type, IList<StateName>[] roles, bool isParticipant)
 {
     this.NeededType = type;
     this.Roles = roles;
     IEnumerable<StateName> minimalRoles = new List<StateName>(roles[0]);
     this.MatchingIndexes = new List<int>();
     for (int i = 0; i < roles.Length; i++)
     {
         minimalRoles = minimalRoles.Intersect(roles[i]);
         ((List<int>)this.MatchingIndexes).Add(i);
     }
     this.MinimalRoles = new List<StateName>(minimalRoles);
     this.IsParticipant = isParticipant;
 }
        /// <summary>
        /// Compares <paramref name="value1"/> to <paramref name="value2"/> and returns the result.
        /// </summary>
        /// <param name="value1">The value to compare.</param>
        /// <param name="value2">The value to compare against.</param>
        /// <param name="negated">When true the result is inversed.</param>
        /// <returns>The comparison result.</returns>
        public override bool Compare(List<string> value1, List<string> value2, bool negated)
        {
            if (value1.Count == 0 && value2.Count == 0)
            {
                return true ^ negated;
            }

            if (value1.Count == 0 || value2.Count == 0)
            {
                return false ^ negated;
            }

            return (value1.Intersect(value2).Count() == Math.Min(value1.Count, value2.Count)) ^ negated;
        }
Example #19
0
 //tries to add spells required for this stage
 //returns false if impossible
 //arguments are spells required and forbidden in other stages in current level segment
 public bool TrySpellset(ref List<Spell> AvailableSpells, ref List<Spell> RestrictedSpells)
 {
     Debug.Log("before/after");
     Debug.Log(AvailableSpells.Count);
     IEnumerable<Spell> list1 = AvailableSpells.Intersect(ForbiddenSpells);
     IEnumerable<Spell> list2 = RestrictedSpells.Intersect(AvailableSpells);
     Debug.Log(AvailableSpells.Count);
     if (list1.Count() > 0 || list2.Count() > 0) return false;
     AvailableSpells = AvailableSpells.Union(RequiredSpells).ToList();
     RestrictedSpells = RestrictedSpells.Union(ForbiddenSpells).ToList();
     Debug.Log("available");
     Debug.Log(RequiredSpells.Count);
     Debug.Log(AvailableSpells.Count);
     return true;
 }
Example #20
0
        private void test_Load(object sender, EventArgs e)
        {
            List<int> a = new List<int> { 1, 2, 3, 4 };
            List<int> b = new List<int> { 2, 3, 4, 5 };
            List<int> c = new List<int> { 3, 4, 5, 6 };
            List<int> res = a.Intersect(b).ToList<int>();//a.Except(b).Concat(b.Except(a)).ToList<int>();
            res = res.Intersect(c).ToList<int>();//a.Except(c).Concat(c.Except(a)).ToList<int>();
            a.Except(b).Concat(a.Except(b)).OrderBy(i => i).ToList().ForEach(i => Console.Write(i.ToString()));
            string abc = "";
            for (int i = 0;i<res.Count ;i++ )
            {
                abc += res[i];
            }

            this.textBox1.Text = abc;
        }
        static void Main(string[] args)
        {
            List<int> firstList = new List<int>();
            firstList.Add(1);
            firstList.Add(1);
            firstList.Add(1);
            firstList.Add(1);
            List<int> secondList = new List<int>();
            secondList.Add(1);
            secondList.Add(2);
            secondList.Add(2);
            secondList.Add(2);
            List<string> thirdList = new List<string>() { "bla", "bla" };
            List<int> resultIntersect = ArrayExtension.Intersect(firstList, secondList);
            List<int> resultUnion = ArrayExtension.UnionAll(firstList, secondList);
            List<int> resultConcat = ArrayExtension.Concat(firstList, secondList);
            string resultJoin = ArrayExtension.Join(thirdList);
            List<int> extensionIntersect = firstList.Intersect(secondList);

            Console.WriteLine("<-- Intersect Method -->");
            foreach (var item in resultIntersect)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("<-- Union Method  NO duplicates -->");
            foreach (var item in resultUnion)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("<-- Concat Method -->");
            foreach (var item in resultConcat)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("<-- Join Method -->");
            Console.WriteLine(resultJoin);

            Console.WriteLine("<--Extension Intersect Method-->");
            foreach (var item in extensionIntersect)
            {
                Console.WriteLine(item);
            }
        }
Example #22
0
        protected override long GetCalculationResult()
        {
            var tri = new List<double>();
            var pent = new List<double>();
            var hex = new List<double>();
            for (int n = 1; n < 1000000; n++)
            {
                tri.Add((double)n * (n + 1) / 2);
                pent.Add((double)n * ((3 * n) - 1) / 2);
                hex.Add((double)n * ((2 * n) - 1));
            }

            var res = tri.Intersect(pent).Intersect(hex);

            res.ToList().ForEach(n => Print("{0}", n));
            return 0;
        }
Example #23
0
        static void Main(string[] args)
        {
            List<int> numbers1 = new List<int>() { 1, 2, 3, 4, 5 };
            List<int> numbers2 = new List<int>() { 3, 4, 5, 6, 7 };

            List<int> intersected = new List<int>();
            intersected = numbers1.Intersect(numbers2);

            List<int> allUnioned = new List<int>();
            allUnioned = ArrayExtension.UnionAll(numbers1, numbers2);

            List<int> unionedWithoutDuplicates = new List<int>();
            unionedWithoutDuplicates = ArrayExtension.Union(numbers1, numbers2);

            char specialChar = ArrayExtension.GetReplacingValue;
            List<string> strings = new List<string>() { "I", "love", "fried", "potatoes" };
            string joined = ArrayExtension.Join(strings);

            foreach (var item in intersected)
            {
                Console.Write("{0} ", item);  // 3 4 5
            }

            Console.WriteLine();

            foreach (var item in allUnioned)
            {
                 Console.Write("{0} ", item);  // 1 2 3 4 5 3 4 5 6 7
            }

            Console.WriteLine();

            foreach (var item in unionedWithoutDuplicates)
            {
                Console.Write("{0} ", item);  // 1 2 3 4 5 6 7
            }

            Console.WriteLine();
            Console.WriteLine("Special replacing value: {0}\nJoined string: {1}", specialChar, joined);
            Console.WriteLine();
        }
Example #24
0
 public void CreateComparerTest()
 {
     List<int> list1 = new List<int>();
     for (int i = 0; i < 100; i++)
     {
         list1.Add(i);
     }
     List<int> list2 = new List<int>();
     for (int i = 50; i < 150; i++)
     {
         list2.Add(i);
     }
     IEqualityComparer<int> comparer = EqualityHelper<int>.CreateComparer(m => m);
     List<int> list3 = list1.Intersect(list2, comparer).ToList();
     Assert.Equal(50, list3.Count);
     Assert.Equal(50, list3.Min());
     Assert.Equal(99, list3.Max());
     List<int> list4 = list1.Except(list2, comparer).ToList();
     Assert.Equal(50, list4.Count);
     Assert.Equal(0, list4.Min());
     Assert.Equal(49, list4.Max());
 }
Example #25
0
 static void PowerModeChanged(Object sender, PowerModeChangedEventArgs e)
 {
     if (e.Mode == PowerModes.Suspend)
     {
         Console.WriteLine("PowerMode: suspend");
     }
     if (e.Mode == PowerModes.Resume)
     {
         Console.WriteLine("PowerMode: resume");
         // give it some time to connect. wasn't necessary for me, but might be for some configurations. adjust if needed.
         System.Threading.Thread.Sleep(500);
         var connectedSsids = new List<string>();
         foreach (WlanClient.WlanInterface wlanInterface in wlan.Interfaces)
         {
             if (wlanInterface.InterfaceState != Wlan.WlanInterfaceState.Connected)
             {
                 Console.WriteLine(wlanInterface.InterfaceName + " is not connected!");
             }
             else
             {
                 Wlan.Dot11Ssid ssid = wlanInterface.CurrentConnection.wlanAssociationAttributes.dot11Ssid;
                 connectedSsids.Add(new String(Encoding.ASCII.GetChars(ssid.SSID, 0, (int)ssid.SSIDLength)));
             }
         }
         Console.WriteLine("Connected SSIDs:");
         foreach (var ssid in connectedSsids)
             Console.WriteLine("\t" + ssid);
         if (connectedSsids.Intersect(safeSSIDs).Count() > 0)
         {
             Console.WriteLine("-> save");
         }
         else
         {
             Console.WriteLine("-> unsafe. Locking workstation now!");
             LockWorkStation();
         }
     }
 }
        private List<Constituent> GetConstituents(bool matchAllCriteria,params List<Constituent>[] constituentsWithMatch)
        {
            var resultList = new List<Constituent>();
            if (matchAllCriteria)
            {
                constituentsWithMatch.ForEach(list =>
                                                  {
                                                      if ( list!=null)
                                                      {
                                                          if(resultList.Count == 0)
                                                            resultList = list;
                                                          resultList = resultList.Intersect(list).ToList();
                                                      }

                                                  });
            }
            else
            {
                constituentsWithMatch.ForEach(list => { if(list!=null) resultList = resultList.Union(list).ToList(); });

            }
            return resultList.ToList();
        }
Example #27
0
         // GET: Training/Details/5
        public ActionResult Details(int id)
        {
            Training training = db.Trainings
                .Where(t => t.Id == id)
                .Include(t => t.SharedWith)
                .FirstOrDefault();
            if (training == null)
            {
                return HttpNotFound();
            }

            List<string> groupMembership = new List<string>();
            string userObjectId = (System.Security.Claims.ClaimsPrincipal.Current).
                FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            foreach (System.Security.Claims.Claim claim in (System.Security.Claims.ClaimsPrincipal.Current).FindAll("groups"))
                groupMembership.Add(claim.Value);

            List<string> sharedWith = training.SharedWith.Select(s => s.PrincipalId.ToString()).ToList();

            if (training.CreatedBy == userObjectId || groupMembership.Intersect(sharedWith).ToList().Count > 0)
                return View(training);
            else
                return new ViewResult { ViewName = "Error", ViewBag = { message = "Unauthorized - this training has not been shared with you." } };
        }
Example #28
0
        /// <summary>
        /// Modifies the features with a new selection based on the modifyMode.
        /// </summary>
        /// <param name="filterExpression">
        /// The string filter expression to use
        /// </param>
        /// <param name="modifyMode">
        /// Determines how the newly chosen features should interact with the existing
        ///  selection
        /// </param>
        public void SelectByAttribute(string filterExpression, ModifySelectionMode modifyMode)
        {
            if (!_drawnStatesNeeded && !_editMode)
            {
                AssignFastDrawnStates();
            }

            List<int> newSelection = DataSet.SelectIndexByAttribute(filterExpression);
            _selection.SuspendChanges();
            if (modifyMode == ModifySelectionMode.Replace)
            {
                _selection.Clear();
                Select(newSelection);
            }

            if (modifyMode == ModifySelectionMode.Append)
            {
                Select(newSelection);
            }

            if (modifyMode == ModifySelectionMode.SelectFrom)
            {
                List<int> cond = new List<int>();
                if (_editMode)
                {
                    IFeatureSelection fs = _selection as IFeatureSelection;
                    if (fs != null)
                    {
                        cond.AddRange(fs.Select(feature => DataSet.Features.IndexOf(feature)));
                    }
                }
                else
                {
                    IIndexSelection sel = _selection as IIndexSelection;
                    if (sel != null)
                    {
                        cond = sel.ToList();
                    }
                }

                IEnumerable<int> result = cond.Intersect(newSelection);
                _selection.Clear();
                Select(result);
            }

            if (modifyMode == ModifySelectionMode.Subtract)
            {
                UnSelect(newSelection);
            }

            _selection.ResumeChanges();
            OnItemChanged();
        }
Example #29
0
        public static List<Trade> Filter(List<Tag> selectedTags, List<Strategy> selectedStrategies, List<Instrument> selectedInstruments, IDBContext context, TradeFilterSettings settings)
        {
            if (context == null) throw new ArgumentNullException("context");

            //filter dates
            var trades = context
                .Trades
                .Include(x => x.Tags)
                .Include(x => x.Strategy)
                .Include(x => x.Orders)
                .Include(x => x.CashTransactions)
                .Where(x => x.DateClosed == null || x.DateClosed > settings.From)
                .Where(x => x.DateOpened < settings.To)
                .ToList();

            //filter open if required
            if (settings.ClosedTradesOnly)
            {
                trades = trades.Where(x => !x.Open).ToList();
            }

            //filter by strategy
            switch (settings.StrategyFilterMethod)
            {
                case FilterMethod.Any:
                    trades = trades.Where(x => selectedStrategies.Contains(x.Strategy)).ToList();
                    break;
                case FilterMethod.Exclude:
                    trades = trades.Where(x => !selectedStrategies.Contains(x.Strategy)).ToList();
                    break;
            }


            //filter by tags
            switch (settings.TagFilterMethod)
            {
                case FilterMethod.Any:
                    trades = trades.Where(x => selectedTags.Intersect(x.Tags).Any()).ToList();
                    break;
                case FilterMethod.All:
                    trades = trades.Where(x => selectedTags.Intersect(x.Tags).Count() == selectedTags.Count).ToList();
                    break;
                case FilterMethod.Exclude:
                    trades = trades.Where(x => !selectedTags.Intersect(x.Tags).Any()).ToList();
                    break;
            }

            List<int> selectedInstrumentIDs = selectedInstruments.Select(x => x.ID).ToList();

            //filter by instrument
            switch (settings.InstrumentFilterMethod)
            {
                case FilterMethod.Any:
                    trades = trades.Where(x => 
                        x.Orders.Select(y => y.InstrumentID).Intersect(selectedInstrumentIDs).Any() ||
                        x.CashTransactions.Where(y => y.InstrumentID.HasValue).Select(y => y.InstrumentID.Value).Intersect(selectedInstrumentIDs).Any())
                        .ToList();
                    break;

                case FilterMethod.All:
                    trades = trades.Where(x => 
                        x.Orders.Select(y => y.InstrumentID).Intersect(selectedInstrumentIDs).Union(
                        x.CashTransactions.Where(y => y.InstrumentID.HasValue).Select(y => y.InstrumentID.Value)).Count()
                            == selectedInstrumentIDs.Count)
                        .ToList();
                    break;

                case FilterMethod.Exclude:
                    trades = trades.Where(x => 
                        !x.Orders.Select(y => y.InstrumentID).Intersect(selectedInstrumentIDs).Any() &&
                        !x.CashTransactions.Where(y => y.InstrumentID.HasValue).Select(y => y.InstrumentID.Value).Intersect(selectedInstrumentIDs).Any())
                        .ToList();
                    break;
            }

            return trades.ToList();
        }
        public List<string> GetSelectableFields(List<string> KeyFields,List<string> SheetFields)
        {
            List<string> Result = new List<string>();

            if (KeyFields == null || SheetFields == null)
                return Result;

            Result = NotRequiredFields.Intersect(SheetFields).ToList();

            Result.Intersect(KeyFields).ToList().ForEach(x => Result.Remove(x));

            return Result;
        }