//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 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 #3
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));
        }
 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;
 }
Example #5
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;
 		}
Example #6
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"));
             });
        }
Example #7
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);
        }
        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 #9
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);
        }
Example #10
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 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();
        }
        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
        public CompanyFlatDTO[] GetByAdvancedFilter(CompanyAdvancedFilterDTO filter)
        {
            List <int> result = null;

            if (!string.IsNullOrEmpty(filter.firstName) || !string.IsNullOrEmpty(filter.lastName) || !string.IsNullOrEmpty(filter.email))
            {
                var userCompanyIds = UserModel.GetCompanyIdsByUsersProperties(filter.firstName, filter.lastName, filter.email).ToList();
                result = userCompanyIds;
            }

            if (!string.IsNullOrEmpty(filter.acServer))
            {
                var serverCompanyIds = CompanyAcServerModel.GetCompaniesByServerName(filter.acServer).Select(c => c.Company.Id).ToList();
                result = result?.Intersect(serverCompanyIds).ToList() ?? serverCompanyIds;
            }

            if (!string.IsNullOrEmpty(filter.companyName))
            {
                var comapniesByName = CompanyModel.GetCompaniesFlatByName(filter.companyName).Select(c => c.id).ToList();
                result = result?.Intersect(comapniesByName).ToList() ?? comapniesByName;
            }

            if (!string.IsNullOrEmpty(filter.consumerKey))
            {
                var lmsCompany             = LmsCompanyModel.GetOneByConsumerKey(filter.consumerKey).Value;
                var companiesByConsumerKey = lmsCompany == null
                                                ? new List <int>()
                                                : new List <int> {
                    lmsCompany.CompanyId
                };

                result = result?.Intersect(companiesByConsumerKey).ToList() ?? companiesByConsumerKey;
            }

            return(this.CompanyModel.GetCompaniesFlatByIds(result).ToArray());
        }
Example #21
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;
        }
Example #22
0
        private static void BuildValidFormats()
        {
            if (s_ValidTextureFormats != null)
            {
                return;
            }

            s_ValidTextureFormats        = new Dictionary <TextureTypeAndBuildTarget, Value>();
            s_ValidDefaultTextureFormats = new Dictionary <TextureImporterType, Value>();

            foreach (var textureTypeName in Enum.GetNames(typeof(TextureImporterType)))
            {
                var textureTypeField = typeof(TextureImporterType).GetField(textureTypeName);
                if (textureTypeField.IsDefined(typeof(ObsoleteAttribute), false))
                {
                    continue;
                }

                var textureType = (TextureImporterType)Enum.Parse(typeof(TextureImporterType), textureTypeName);

                List <int> defaultFormats = null;

                foreach (var targetName in Enum.GetNames(typeof(BuildTarget)))
                {
                    var targetField = typeof(BuildTarget).GetField(targetName);
                    if (targetField.IsDefined(typeof(ObsoleteAttribute), false))
                    {
                        continue;
                    }

                    var target = (BuildTarget)Enum.Parse(typeof(BuildTarget), targetName);

                    var Key = new TextureTypeAndBuildTarget(textureType, target);

                    var validFormats = Array.ConvertAll(TextureImporter.RecommendedFormatsFromTextureTypeAndPlatform(textureType, target), value => (int)value);

                    s_ValidTextureFormats.Add(Key, new Value(validFormats, BuildTextureStrings(validFormats)));

                    defaultFormats = defaultFormats?.Intersect(validFormats).ToList() ?? validFormats.ToList();
                }

                // need "Auto" as the first entry for defaults
                defaultFormats.Insert(0, -1);
                var defaultFormatsArray = defaultFormats.ToArray();
                s_ValidDefaultTextureFormats[textureType] = new Value(defaultFormatsArray, BuildTextureStrings(defaultFormatsArray));
            }
        }
Example #23
0
        public static WcfServicePayload <List <TEntity> > CombinedQuery <TEntity, TPropertyMap>(ISession hSession,
                                                                                                Dictionary <ErpPropertyInfo, string> criteria, bool containsEndDate = false)
            where TEntity : BusinessEntity, new() where TPropertyMap : PropertyEntityMapBase, new()

        {
            string businessEntityName = typeof(TEntity).Name;

            var type = EntityStructureApi.GetStructureByTypeName(businessEntityName);

            if (type == null)
            {
                return(new WcfServicePayload <List <TEntity> >(WcfError.UnknownError, "TypeError:No type " + businessEntityName));
            }

            //对每个condition都找出所有满足条件的id,然后做join
            //HQL不支持对没有标记one to many的表做join,因此目前只能先全部查询一遍,然后在代码里做join
            //TODO:这里是日后优化的目标
            List <int> intersectKeys = null;

            foreach (var conEntry in criteria)
            {
                var query =
                    hSession.CreateQuery("from " + type.PropertyMapType +
                                         " where value = ? and PropertyId =" +
                                         conEntry.Key.PropertyId + (containsEndDate? "":" and end_date is null"));
                query.SetString(0, PropertyHelper.ParseValue(conEntry.Key, conEntry.Value));

                List <int> keys = query.List <TPropertyMap>().Select(q => q.EntityId).ToList();
                intersectKeys = intersectKeys?.Intersect(keys).ToList() ?? keys;
                if (intersectKeys.Count == 0)
                {
                    break;
                }
            }

            if (intersectKeys != null && intersectKeys.Count != 0)
            {
                List <TEntity> entries =
                    intersectKeys.Select(key => hSession.Get <TEntity>(key)).ToList();
                return(new WcfServicePayload <List <TEntity> >(entries));
            }
            else
            {
                return(new WcfServicePayload <List <TEntity> >(new List <TEntity>()));
            }
        }
        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 #25
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 #26
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 #27
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 #28
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 #30
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." } };
        }
        private static void UpdateContentType(Web web, Microsoft.SharePoint.Client.ContentType existingContentType, ContentType templateContentType, TokenParser parser, PnPMonitoredScope scope, bool isNoScriptSite = false)
        {
            var isDirty = false;

            if (existingContentType.Hidden != templateContentType.Hidden)
            {
                scope.LogPropertyUpdate("Hidden");
                existingContentType.Hidden = templateContentType.Hidden;
                isDirty = true;
            }
            if (existingContentType.ReadOnly != templateContentType.ReadOnly)
            {
                scope.LogPropertyUpdate("ReadOnly");
                existingContentType.ReadOnly = templateContentType.ReadOnly;
                isDirty = true;
            }
            if (existingContentType.Sealed != templateContentType.Sealed)
            {
                scope.LogPropertyUpdate("Sealed");
                existingContentType.Sealed = templateContentType.Sealed;
                isDirty = true;
            }
            if (templateContentType.Description != null && existingContentType.Description != parser.ParseString(templateContentType.Description))
            {
                scope.LogPropertyUpdate("Description");
                existingContentType.Description = parser.ParseString(templateContentType.Description);
                isDirty = true;
            }
            if (templateContentType.DocumentTemplate != null && existingContentType.DocumentTemplate != parser.ParseString(templateContentType.DocumentTemplate))
            {
                scope.LogPropertyUpdate("DocumentTemplate");
                existingContentType.DocumentTemplate = parser.ParseString(templateContentType.DocumentTemplate);
                isDirty = true;
            }
            if (existingContentType.Name != parser.ParseString(templateContentType.Name))
            {
                scope.LogPropertyUpdate("Name");
                existingContentType.Name = parser.ParseString(templateContentType.Name);
                isDirty = true;
                // CT is being renamed, add an extra token to the tokenparser
                parser.AddToken(new ContentTypeIdToken(web, existingContentType.Name, existingContentType.StringId));
            }
            if (templateContentType.Group != null && existingContentType.Group != parser.ParseString(templateContentType.Group))
            {
                scope.LogPropertyUpdate("Group");
                existingContentType.Group = parser.ParseString(templateContentType.Group);
                isDirty = true;
            }
            if (!isNoScriptSite)
            {
                if (templateContentType.DisplayFormUrl != null && existingContentType.DisplayFormUrl != parser.ParseString(templateContentType.DisplayFormUrl))
                {
                    scope.LogPropertyUpdate("DisplayFormUrl");
                    existingContentType.DisplayFormUrl = parser.ParseString(templateContentType.DisplayFormUrl);
                    isDirty = true;
                }
                if (templateContentType.EditFormUrl != null && existingContentType.EditFormUrl != parser.ParseString(templateContentType.EditFormUrl))
                {
                    scope.LogPropertyUpdate("EditFormUrl");
                    existingContentType.EditFormUrl = parser.ParseString(templateContentType.EditFormUrl);
                    isDirty = true;
                }
                if (templateContentType.NewFormUrl != null && existingContentType.NewFormUrl != parser.ParseString(templateContentType.NewFormUrl))
                {
                    scope.LogPropertyUpdate("NewFormUrl");
                    existingContentType.NewFormUrl = parser.ParseString(templateContentType.NewFormUrl);
                    isDirty = true;
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(parser.ParseString(templateContentType.DisplayFormUrl)) ||
                    !String.IsNullOrEmpty(parser.ParseString(templateContentType.EditFormUrl)) ||
                    !String.IsNullOrEmpty(parser.ParseString(templateContentType.NewFormUrl)))
                {
                    // log message
                    scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ContentTypes_SkipCustomFormUrls, existingContentType.Name);
                }
            }

#if !SP2013
            if (templateContentType.Name.ContainsResourceToken())
            {
                existingContentType.NameResource.SetUserResourceValue(templateContentType.Name, parser);
                isDirty = true;
            }
            if (templateContentType.Description.ContainsResourceToken())
            {
                existingContentType.DescriptionResource.SetUserResourceValue(templateContentType.Description, parser);
                isDirty = true;
            }
#endif
            if (isDirty)
            {
                existingContentType.Update(true);
                web.Context.ExecuteQueryRetry();
            }
            // Delta handling
            existingContentType.EnsureProperty(c => c.FieldLinks);
            List <Guid> targetIds = existingContentType.FieldLinks.AsEnumerable().Select(c1 => c1.Id).ToList();
            List <Guid> sourceIds = templateContentType.FieldRefs.Select(c1 => c1.Id).ToList();

            var fieldsNotPresentInTarget = sourceIds.Except(targetIds).ToArray();

            if (fieldsNotPresentInTarget.Any())
            {
                foreach (var fieldId in fieldsNotPresentInTarget)
                {
                    var fieldRef = templateContentType.FieldRefs.Find(fr => fr.Id == fieldId);
                    var field    = web.Fields.GetById(fieldId);
                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ContentTypes_Adding_field__0__to_content_type, fieldId);
                    web.AddFieldToContentType(existingContentType, field, fieldRef.Required, fieldRef.Hidden);
                }
            }

            isDirty = false;
            foreach (var fieldId in targetIds.Intersect(sourceIds))
            {
                var fieldLink = existingContentType.FieldLinks.FirstOrDefault(fl => fl.Id == fieldId);
                var fieldRef  = templateContentType.FieldRefs.Find(fr => fr.Id == fieldId);
                if (fieldRef != null)
                {
                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ContentTypes_Field__0__exists_in_content_type, fieldId);
                    if (fieldLink.Required != fieldRef.Required)
                    {
                        scope.LogPropertyUpdate("Required");
                        fieldLink.Required = fieldRef.Required;
                        isDirty            = true;
                    }
                    if (fieldLink.Hidden != fieldRef.Hidden)
                    {
                        scope.LogPropertyUpdate("Hidden");
                        fieldLink.Hidden = fieldRef.Hidden;
                        isDirty          = true;
                    }
                }
            }

            // The new CT is a DocumentSet, and the target should be, as well
            if (templateContentType.DocumentSetTemplate != null)
            {
                if (!Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.IsChildOfDocumentSetContentType(web.Context, existingContentType).Value)
                {
                    scope.LogError(CoreResources.Provisioning_ObjectHandlers_ContentTypes_InvalidDocumentSet_Update_Request, existingContentType.Id, existingContentType.Name);
                }
                else
                {
                    Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate templateToUpdate =
                        Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.GetDocumentSetTemplate(web.Context, existingContentType);

                    // TODO: Implement Delta Handling
                    scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ContentTypes_DocumentSet_DeltaHandling_OnHold, existingContentType.Id, existingContentType.Name);
                }
            }

            if (isDirty)
            {
                existingContentType.Update(true);
                web.Context.ExecuteQueryRetry();
            }
        }
Example #32
0
        //Räknar antalet matchningar
        private static int MatchingIngredients(List <string> recipe, List <string> ingredients)
        {
            var qtyMatch = recipe.Intersect(ingredients);

            return(qtyMatch.Count());
        }
Example #33
0
        public bool IsInState(Board board, Color color)
        {
            /*
             * On construit des groupes de règles spéciales qui ne tienne pas compte
             * de celle de la mise en echec
             */
            Board        tempBoard = new Board(board);
            List <IRule> queenMovementCheckRules = new List <IRule> {
                new QueenMovementRule(), new CanOnlyTakeEnnemyRule()
            };

            List <IRule> pawnMovementCheckRules = new List <IRule> {
                new PawnMovementRule(), new CanOnlyTakeEnnemyRule()
            };

            List <IRule> kingMovementCheckRules = new List <IRule> {
                new KingMovementRule(), new CanOnlyTakeEnnemyRule(), new CastlingRule()
            };

            List <IRule> knightMovementCheckRules = new List <IRule>
            {
                new KnightMovementRule(),
                new CanOnlyTakeEnnemyRule()
            };

            List <IRule> rookMovementCheckRules = new List <IRule> {
                new CanOnlyTakeEnnemyRule(), new RookMovementRule()
            };

            List <IRule> bishopMovementCheckRules = new List <IRule>
            {
                new CanOnlyTakeEnnemyRule(),
                new BishopMovementRule()
            };

            Dictionary <Type, List <IRule> > rulesGroup = new Dictionary <Type, List <IRule> >
            {
                { Type.Queen, queenMovementCheckRules },
                { Type.Pawn, pawnMovementCheckRules },
                { Type.Knight, knightMovementCheckRules },
                { Type.Rook, rookMovementCheckRules },
                { Type.Bishop, bishopMovementCheckRules },
                { Type.King, kingMovementCheckRules }
            };


            // On cherche le roi
            Piece concernedKing = tempBoard.Squares.OfType <Square>()
                                  .First(x => (x?.Piece?.Type == Type.King) && (x?.Piece?.Color == color)).Piece;

            bool res = false;

            foreach (KeyValuePair <Type, List <IRule> > rules in rulesGroup)
            {
                List <Square> possibleMoves = new List <Square>();
                concernedKing.Type = rules.Key;
                possibleMoves      = possibleMoves.Concat(rules.Value.First().PossibleMoves(concernedKing)).ToList();
                rules.Value.ForEach(
                    x => possibleMoves = possibleMoves.Intersect(x.PossibleMoves(concernedKing)).ToList());

                if (possibleMoves.Any(x => x?.Piece?.Type == rules.Key))
                {
                    // Vérifier si il ne faut pas être d'une couleur différente
                    res = true;
                }
            }
            concernedKing.Type = Type.King;
            return(res);
        }
Example #34
0
        /// <summary>
        /// Worker to query one aggregate of a topology
        /// </summary>
        /// <param name="aggregateIndex">The aggregation view to update by the worker</param>
        /// <param name="token">CancellationToken</param>
        public async Task Worker(int aggregateIndex, CancellationToken token)
        {
            RDXOpcUaQueries  opcUaQueries  = new RDXOpcUaQueries(token);
            RDXOeeKpiQueries oeeKpiQueries = new RDXOeeKpiQueries(opcUaQueries, token);

            RDXTrace.TraceInformation("RDX Worker {0} started", aggregateIndex);

            // give app some time to start before updating queries
            await Task.Delay(10000 *(aggregateIndex + 1));

            while (!token.IsCancellationRequested)
            {
                Stopwatch stopWatch         = new Stopwatch();
                DateTime  nextUpdate        = DateTime.MaxValue;
                bool      resetStartDelayed = false;

                stopWatch.Start();

                Interlocked.Increment(ref _busyWorkers);

                // the station and node list is updated, other workers are delayed
                while (_workerStartDelayed != 0)
                {
                    RDXTrace.TraceInformation("RDX Worker {0} delayed", aggregateIndex);
                    await Task.Delay(1000);
                }

                try
                {
                    List <Task>         tasks    = new List <Task>();
                    ContosoTopologyNode rootNode = _topology.GetRootNode();
                    ContosoAggregatedOeeKpiHistogram aggregatedTimeSpan = rootNode[aggregateIndex];
                    DateTimeRange searchSpan = RDXUtils.TotalSearchRangeFromNow(aggregatedTimeSpan);

                    RDXTrace.TraceInformation("RDX Worker {0} updating Range {1} to {2}",
                                              aggregateIndex, searchSpan.From, searchSpan.To);

                    // calc next update. To time is already rounded for update time span.
                    nextUpdate = searchSpan.To + rootNode[aggregateIndex].UpdateTimeSpan;

                    // query all stations in topology and find all active servers in timespan
                    Task <StringDimensionResult> aggServerTask = opcUaQueries.AggregateServers(searchSpan);

                    // always get an aggregate of all activity for the latest interval, use it as a cache
                    TimeSpan                 intervalTimeSpan = aggregatedTimeSpan[0].IntervalTimeSpan;
                    DateTimeRange            aggregateSpan    = RDXUtils.CalcAggregationRange(aggregatedTimeSpan, searchSpan.To);
                    RDXCachedAggregatedQuery fullQuery        = new RDXCachedAggregatedQuery(opcUaQueries);
                    Task aggServerAndNodesTask = fullQuery.Execute(aggregateSpan);

                    // wait for all outstanding aggregates
                    tasks.Add(aggServerTask);
                    tasks.Add(aggServerAndNodesTask);
                    await RDXUtils.WhenAllTasks("Aggregates", tasks, stopWatch);

                    List <string> topologyStations = _topology.GetAllChildren(_tree.TopologyRoot.Key, typeof(Station));
                    List <string> opcUaServers     = await aggServerTask;

                    // intersect list of active servers and schedule all queries
                    tasks.Clear();
                    List <string> opcUaServersToQuery = opcUaServers.Intersect(topologyStations, StringComparer.InvariantCultureIgnoreCase).ToList();
                    await oeeKpiQueries.ScheduleAllOeeKpiQueries(searchSpan, _topology, fullQuery, opcUaServersToQuery, tasks, aggregateIndex);

                    // wait for all outstanding queries
                    await RDXUtils.WhenAllTasks("Queries", tasks, stopWatch);

                    // Update the topology Oee and KPI values
                    _topology.UpdateAllKPIAndOEEValues(aggregateIndex);

                    // one worker issues the Browser update
                    if (aggregatedTimeSpan.UpdateBrowser)
                    {
                        // Push updates to dashboard
                        BrowserUpdate();
                        RDXTrace.TraceInformation("BrowserUpdate finished after {0}ms",
                                                  stopWatch.ElapsedMilliseconds);
                    }

                    // add new stations and nodes to topology
                    if (aggregatedTimeSpan.UpdateTopology)
                    {
                        // delay other workers
                        Interlocked.Exchange(ref _workerStartDelayed, 1);
                        resetStartDelayed = true;
                        // only add stations and nodes if no other worker is busy yet
                        if (Interlocked.Increment(ref _busyWorkers) == 2)
                        {
                            AddNewServers(fullQuery, topologyStations);
                            await AddNewNodes(fullQuery, topologyStations);

                            RDXTrace.TraceInformation("Add New Server and Nodes finished after {0}ms",
                                                      stopWatch.ElapsedMilliseconds);
                        }
                    }
                }
                catch (Exception e)
                {
                    RDXTrace.TraceError("Exception {0} in Worker after {1}ms",
                                        e.Message, stopWatch.ElapsedMilliseconds);
                }
                finally
                {
                    Interlocked.Decrement(ref _busyWorkers);
                    if (resetStartDelayed)
                    {
                        Interlocked.Decrement(ref _busyWorkers);
                        Interlocked.Exchange(ref _workerStartDelayed, 0);
                    }
                }

                RDXTrace.TraceInformation("RDX Worker {0} schedule next update for {1}",
                                          aggregateIndex, nextUpdate);

                TimeSpan delay = nextUpdate.Subtract(DateTime.UtcNow);
                if (delay.TotalMilliseconds > 0)
                {
                    await Task.Delay(delay, token);
                }
            }
        }
Example #35
0
        private void DisplayData()
        {
            string[] telas           = { "16", "18", "20", "25" };
            string   _numeroContrato = string.Empty;

            contratos = new List <string>();
            FileInfo fileInfo = null;

            listContratosValidos = new ContratosPdf();
            try
            {
                SetLoading(true);

                Invoke((MethodInvoker) delegate { lblSetLoad.Text = "Validando Ponteiro VS Arquivos..."; });
                ponteiro = new List <string>();
                ponteiro = GetPonteiroExcel();

                IEnumerable <string> arquivos = null;
                foreach (string itemTela in telas)
                {
                    arquivos = Directory.EnumerateFiles(textBoxOrigem.Text, $"*_{itemTela}.pdf", System.IO.SearchOption.AllDirectories);

                    if (arquivos.Count() == 0)
                    {
                        continue;
                    }

                    foreach (string item in arquivos)
                    {
                        fileInfo        = new FileInfo(item);
                        _numeroContrato = fileInfo.Name.Split('_')[0].Trim();

                        if (itemTela.Equals("16"))
                        {
                            listContratosValidos.Tela16.Add(new KeyValuePair <string, string>(_numeroContrato, item));
                            contratos.Add(_numeroContrato);
                            continue;
                        }
                        if (itemTela.Equals("18"))
                        {
                            listContratosValidos.Tela18.Add(new KeyValuePair <string, string>(_numeroContrato, item));
                            continue;
                        }
                        if (itemTela.Equals("20"))
                        {
                            listContratosValidos.Tela20.Add(new KeyValuePair <string, string>(_numeroContrato, item));
                            continue;
                        }
                        if (itemTela.Equals("25"))
                        {
                            listContratosValidos.Tela25.Add(new KeyValuePair <string, string>(_numeroContrato, item));
                            continue;
                        }
                        if (itemTela.Equals("34"))
                        {
                            listContratosValidos.Tela34.Add(new KeyValuePair <string, string>(_numeroContrato, item));
                            continue;
                        }
                        _numeroContrato = string.Empty;
                        fileInfo        = null;
                    }
                }

                fileInfo  = null;
                ponteiro  = ponteiro.Intersect(contratos).ToList();
                contratos = contratos.Except(ponteiro).ToList();

                contratos.ForEach(c =>
                {
                    listContratosValidos.Tela16.RemoveAll(r => r.Key.Equals(c));
                    listContratosValidos.Tela18.RemoveAll(r => r.Key.Equals(c));
                    listContratosValidos.Tela20.RemoveAll(r => r.Key.Equals(c));
                    listContratosValidos.Tela25.RemoveAll(r => r.Key.Equals(c));
                    listContratosValidos.Tela34.RemoveAll(r => r.Key.Equals(c));
                });


                SetLoading(false);
                ZiparContratos();


                System.Diagnostics.Process.Start("explorer.exe", textBoxDestino.Text);
                Application.Exit();
                MessageBox.Show("Processo Finalizado com sucesso", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception exLoad)
            {
                MessageBox.Show($"Erro ao carregar contratos\n{exLoad.Message}", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #36
0
    IEnumerator ClearAndCollapseRoutine(List <GamePiece> gamePieces)
    {
        //need to create bombs during collapse in this section
        //check the entire board for matches call DropBomb method

        List <GamePiece> movingPieces = new List <GamePiece>();
        List <GamePiece> matches      = new List <GamePiece>();

        //HighlightPieces(gamePieces);
        yield return(new WaitForSeconds(0.2f));

        bool isFinished = false;

        while (!isFinished)
        {
            //find pieces hit by bomb
            List <GamePiece> bombedPieces = GetBombedPieces(gamePieces);
            gamePieces = gamePieces.Union(bombedPieces).ToList();

            //bombs hit by other bombs
            bombedPieces = GetBombedPieces(gamePieces);
            gamePieces   = gamePieces.Union(bombedPieces).ToList();

            //collectible pieces that have hit the bottom of the board
            List <GamePiece> collectedPieces = FindCollectiblesAt(0, true);

            //find blockers destroyed by bombs
            List <GamePiece> allCollectibles = FindAllCollectibles();
            List <GamePiece> blockers        = gamePieces.Intersect(allCollectibles).ToList();
            //add blockers to list of collected pieces
            collectedPieces = collectedPieces.Union(blockers).ToList();
            //decrement cleared collectibles/blockers
            collectibleCount -= collectedPieces.Count;
            //add these collectibles to the list of game pieces to clear
            gamePieces = gamePieces.Union(collectedPieces).ToList();

            //fix for null reference error in GetColumns
            List <int> columnsToCollapse = GetColumns(gamePieces);

            ClearPiecesAt(gamePieces, bombedPieces);
            BreakTilesAt(gamePieces);

            for (int i = 0; i < spawnedPieces.Count; i++)
            {
                ActivateBomb(spawnedPieces[i]);
            }
            spawnedPieces.Clear();

            yield return(new WaitForSeconds(0.1f));

            movingPieces = StartCollapse(columnsToCollapse);
            while (!FinishedCollapsing(movingPieces))
            {
                yield return(null);              // wait to respawn
            }
            yield return(new WaitForSeconds(0.1f));

            //check for extra matches as result of collapse
            matches = FindMatchesWith(movingPieces);

            collectedPieces = FindCollectiblesAt(0, true);
            matches         = matches.Union(collectedPieces).ToList();

            if ((matches.Count == 0))
            {
                isFinished = true;
                break;
            }
            else
            {
                m_scoreMultiplier++;
                if (SoundManager.Instance != null)
                {
                    SoundManager.Instance.PlayBonusSound();
                }
                yield return(StartCoroutine(ClearAndCollapseRoutine(matches)));
            }
        }
        yield return(null);
    }
Example #37
0
        static void Main(string[] args)
        {
            List <string> results = new List <string>();

            //using (StreamReader inputFile = new StreamReader(@"..\..\inputs\A-example-practice.in"))
            using (StreamReader inputFile = new StreamReader(@"..\..\inputs\A-small-attempt1.in"))
            //using (StreamReader inputFile = new StreamReader(@"..\..\inputs\A-large.in"))
            {
                int numberOfTestCases = Convert.ToInt32(inputFile.ReadLine());
                for (int i = 0; i < numberOfTestCases; i++)
                {
                    int      answer1 = Convert.ToInt32(inputFile.ReadLine());
                    string[] rows1   = new string[4];
                    rows1[0] = inputFile.ReadLine();
                    rows1[1] = inputFile.ReadLine();
                    rows1[2] = inputFile.ReadLine();
                    rows1[3] = inputFile.ReadLine();

                    List <int> targetRow1Numbers = new List <int>();
                    string[]   targetRow1        = rows1[answer1 - 1].Split(' ');
                    foreach (string number in targetRow1)
                    {
                        targetRow1Numbers.Add(Convert.ToInt32(number));
                    }


                    int      answer2 = Convert.ToInt32(inputFile.ReadLine());
                    string[] rows2   = new string[4];
                    rows2[0] = inputFile.ReadLine();
                    rows2[1] = inputFile.ReadLine();
                    rows2[2] = inputFile.ReadLine();
                    rows2[3] = inputFile.ReadLine();

                    List <int> targetRow2Numbers = new List <int>();
                    string[]   targetRow2        = rows2[answer2 - 1].Split(' ');
                    foreach (string number in targetRow2)
                    {
                        targetRow2Numbers.Add(Convert.ToInt32(number));
                    }

                    List <int> result = targetRow1Numbers.Intersect(targetRow2Numbers).ToList <int>();

                    if (1 == result.Count)
                    {
                        results.Add(result.FirstOrDefault().ToString());
                    }
                    else if (result.Count > 1)
                    {
                        results.Add("Bad magician!");
                    }
                    else
                    {
                        results.Add("Volunteer cheated!");
                    }
                }
            }

            //using (StreamWriter outputFile = new StreamWriter(@"..\..\outputs\A-example-practice.out"))
            using (StreamWriter outputFile = new StreamWriter(@"..\..\outputs\A-small-attempt1.out"))
            //using (StreamWriter outputFile = new StreamWriter(@"..\..\outputs\A-large.out"))
            {
                //Console.WriteLine(numberOfIntersectionPoints);
                int i = 1;
                foreach (string result in results)
                {
                    outputFile.WriteLine("Case #{0}: {1}", i++, result);
                }
            }
        }
        static void Main(string[] args)
        {
            //LAMBDAS
            doubleIt dblIt = x => x * 2;

            Console.WriteLine($"5 * 2 = {dblIt(5)}");


            //get even numbers
            List <int> numList = new List <int> {
                1, 9, 2, 6, 3
            };
            var evenList = numList.Where(a => a % 2 == 0).ToList();

            foreach (var j in evenList)
            {
                Console.Write(j + " ");
            }
            Console.WriteLine();

            //get range
            var rangeList = numList.Where(x => (x > 2) && (x < 9)).ToList();

            foreach (var j in rangeList)
            {
                Console.Write(j + " ");
            }
            Console.WriteLine();

            //Find number of heads and tails flipped randomly
            List <int> flipList = new List <int>();
            int        i        = 0;
            Random     rnd      = new Random();

            while (i < 100)
            {
                flipList.Add(rnd.Next(1, 3));
                i++;
            }
            Console.WriteLine("Heads : {0}", flipList.Where(a => a == 1).ToList().Count());
            Console.WriteLine("Tails : {0}", flipList.Where(a => a == 2).ToList().Count());

            //Find all names that start with a specific letter
            var nameList = new List <string> {
                "Doug", "Sally", "Sue"
            };
            var sNameList = nameList.Where(x => x.StartsWith("S"));

            foreach (var j in sNameList)
            {
                Console.Write(j + " ");
            }
            Console.WriteLine();

            //SELECT
            var oneTo10 = new List <int>();

            oneTo10.AddRange(Enumerable.Range(1, 10));

            var squares = oneTo10.Select(x => x * x);

            foreach (var j in squares)
            {
                Console.Write(j + " ");
            }
            Console.WriteLine();

            //ZIP
            var listOne = new List <int>(new int[] { 1, 3, 4 });
            var listTwo = new List <int>(new int[] { 4, 6, 8 });
            var sumList = listOne.Zip(listTwo, (x, y) => x * 10 + y).ToList();

            foreach (var j in sumList)
            {
                Console.Write(j + " ");
            }
            Console.WriteLine();

            //Aggregate
            var numList2 = new List <int> {
                1, 2, 3, 4, 5
            };

            Console.WriteLine("Sum : {0}", numList2.Aggregate((a, b) => a + b));

            //Average
            Console.WriteLine("Avg: {0}", numList2.AsQueryable().Average());

            //All
            Console.WriteLine("All > 3: {0}", numList2.All(x => x > 3));

            //Distinct
            var numList3 = new List <int> {
                1, 2, 3, 2, 3
            };

            Console.WriteLine("Distint : {0}", string.Join(",", numList3.Distinct()));

            //Except - takes two lists and returns values that aren't found in the second list
            var numList4 = new List <int> {
                3
            };

            Console.WriteLine("Except : {0}", string.Join(",", numList3.Except(numList4)));

            //Intersect - returns values found in both lists
            Console.WriteLine("Intersect : {0}", string.Join(",", numList3.Intersect(numList4)));
        }
        private void Display()
        {
            //DONT turn on sorting in the future, thats not how it works.  You click and drag to sort manually since it gives you
            // the order of recipies.

            List <Tuple <Recipes.Recipe, int> > wantedList = null;

            System.Diagnostics.Trace.WriteLine(BaseUtils.AppTicks.TickCountLap(this, true) + " EN " + displaynumber + " Begin Display");

            if (last_he != null)
            {
                List <MaterialCommodities> mcl = last_he.MaterialCommodity.Sort(false);

                int fdrow = dataGridViewEngineering.FirstDisplayedScrollingRowIndex;      // remember where we were displaying

                MaterialCommoditiesRecipe.ResetUsed(mcl);

                wantedList = new List <Tuple <Recipes.Recipe, int> >();

                string        engineers = SQLiteDBClass.GetSettingString(DbEngFilterSave, "All");
                List <string> engList   = engineers.Split(';').ToList <string>();
                string        modules   = SQLiteDBClass.GetSettingString(DbModFilterSave, "All");
                List <string> modList   = modules.Split(';').ToList <string>();
                string        levels    = SQLiteDBClass.GetSettingString(DbLevelFilterSave, "All");
                string[]      lvlArray  = (levels == "All" || levels == "None") ? new string[0] : levels.Split(';');
                string        upgrades  = SQLiteDBClass.GetSettingString(DbUpgradeFilterSave, "All");
                string[]      upgArray  = upgrades.Split(';');
                string        materials = SQLiteDBClass.GetSettingString(DbMaterialFilterSave, "All");
                List <string> matList;
                if (materials == "All" || materials == "None")
                {
                    matList = new List <string>();
                }
                else
                {
                    matList = materials.Split(';').Where(x => !string.IsNullOrEmpty(x) && matLookUp.ContainsKey(x)).Select(m => matLookUp[m]).ToList();
                }

                for (int i = 0; i < Recipes.EngineeringRecipes.Count; i++)
                {
                    int rno = (int)dataGridViewEngineering.Rows[i].Tag;
                    dataGridViewEngineering[MaxCol.Index, i].Value = MaterialCommoditiesRecipe.HowManyLeft(mcl, Recipes.EngineeringRecipes[rno]).Item1.ToStringInvariant();
                    bool visible = true;

                    if (engineers == "All" && modules == "All" && levels == "All" && upgrades == "All" && materials == "All")
                    {
                        visible = true;
                    }
                    else
                    {
                        visible = false;
                        if (engineers == "All")
                        {
                            visible = true;
                        }
                        else
                        {
                            var included = engList.Intersect <string>(Recipes.EngineeringRecipes[rno].engineers.ToList <string>());
                            visible = included.Count() > 0;
                        }
                        if (modules == "All")
                        {
                            visible = visible && true;
                        }
                        else
                        {
                            var included = modList.Intersect <string>(Recipes.EngineeringRecipes[rno].modules.ToList <string>());
                            visible = visible && included.Count() > 0;
                        }
                        if (levels == "All")
                        {
                            visible = visible && true;
                        }
                        else
                        {
                            visible = visible && lvlArray.Contains(Recipes.EngineeringRecipes[rno].level);
                        }
                        if (upgrades == "All")
                        {
                            visible = visible && true;
                        }
                        else
                        {
                            visible = visible && upgArray.Contains(Recipes.EngineeringRecipes[rno].name);
                        }
                        if (materials == "All")
                        {
                            visible = visible && true;
                        }
                        else
                        {
                            var included = matList.Intersect <string>(Recipes.EngineeringRecipes[rno].ingredients.ToList <string>());
                            visible = visible && included.Count() > 0;
                        }
                    }

                    dataGridViewEngineering.Rows[i].Visible = visible;

                    if (visible)
                    {
                        Tuple <int, int, string, string> res = MaterialCommoditiesRecipe.HowManyLeft(mcl, Recipes.EngineeringRecipes[rno], Wanted[rno]);
                        //System.Diagnostics.Debug.WriteLine("{0} Recipe {1} executed {2} {3} ", i, rno, Wanted[rno], res.Item2);

                        dataGridViewEngineering[WantedCol.Index, i].Value      = Wanted[rno].ToStringInvariant();
                        dataGridViewEngineering[AvailableCol.Index, i].Value   = res.Item2.ToStringInvariant();
                        dataGridViewEngineering[NotesCol.Index, i].Value       = res.Item3;
                        dataGridViewEngineering[NotesCol.Index, i].ToolTipText = res.Item4;
                    }
                    if (Wanted[rno] > 0 && (visible || isEmbedded))      // embedded, need to
                    {
                        wantedList.Add(new Tuple <Recipes.Recipe, int>(Recipes.EngineeringRecipes[rno], Wanted[rno]));
                    }
                }

                if (!isEmbedded)
                {
                    MaterialCommoditiesRecipe.ResetUsed(mcl);
                    List <MaterialCommodities> shoppinglist = MaterialCommoditiesRecipe.GetShoppingList(wantedList, mcl);
                    dataGridViewEngineering.RowCount = Recipes.EngineeringRecipes.Count;             // truncate previous shopping list..
                    foreach (MaterialCommodities c in shoppinglist.OrderBy(mat => mat.Details.Name)) // and add new..
                    {
                        int rn = dataGridViewEngineering.Rows.Add();

                        foreach (var cell in dataGridViewEngineering.Rows[rn].Cells.OfType <DataGridViewCell>())
                        {
                            if (cell.OwningColumn == UpgradeCol)
                            {
                                cell.Value = c.Details.Name;
                            }
                            else if (cell.OwningColumn == WantedCol)
                            {
                                cell.Value = c.scratchpad.ToStringInvariant();
                            }
                            else if (cell.OwningColumn == NotesCol)
                            {
                                cell.Value = c.Details.Shortname;
                            }
                            else if (cell.ValueType == null || cell.ValueType.IsAssignableFrom(typeof(string)))
                            {
                                cell.Value = string.Empty;
                            }
                        }
                        dataGridViewEngineering.Rows[rn].ReadOnly = true;   // disable editing wanted..
                    }
                }

                if (fdrow >= 0 && dataGridViewEngineering.Rows[fdrow].Visible)        // better check visible, may have changed..
                {
                    dataGridViewEngineering.FirstDisplayedScrollingRowIndex = fdrow;
                }
            }

            if (OnDisplayComplete != null)
            {
                OnDisplayComplete(wantedList);
            }

            System.Diagnostics.Trace.WriteLine(BaseUtils.AppTicks.TickCountLap(this) + " EN " + displaynumber + " Load Finished");
        }
Example #40
0
        public static bool IsCouponValidForCheckout(Coupon coupon, CheckoutOrderInfo checkoutOrderInfo, out CouponStatus couponStatus)
        {
            couponStatus = CouponStatus.NotFound;

            //Coupon coupon = Coupon.GetCoupon(couponCode, storeId);
            if (coupon != null)
            {
                //--- "Active" status?
                if (!coupon.IsActive.Value)
                {
                    couponStatus = CouponStatus.NotActive;
                    return(false);
                }

                //--- Active Dates?
                if (coupon.ValidFromDate.HasValue)
                {
                    if (DateTime.Today < coupon.ValidFromDate.Value)
                    {
                        couponStatus = CouponStatus.ActiveDateInvalidFrom;
                        return(false);
                    }
                }
                if (coupon.ValidToDate.HasValue)
                {
                    if (DateTime.Today > coupon.ValidToDate.Value)
                    {
                        couponStatus = CouponStatus.ActiveDateInvalidTo;
                        return(false);
                    }
                }

                List <CheckoutCouponInfo> checkoutCouponInfos = checkoutOrderInfo.GetAppliedCoupons();
                //--- already been applied?
                if (checkoutCouponInfos.Exists(c => c.CouponCode == coupon.Code))
                {
                    couponStatus = CouponStatus.AlreadyApplied;
                    return(false);
                }
                //--- combinable?
                if (!coupon.IsCombinable.Value && checkoutCouponInfos.Count > 0)
                {
                    // this coupon is not combinable and user is trying to combine it
                    couponStatus = CouponStatus.NotCombinable;
                    return(false);
                }
                if (checkoutCouponInfos.Count > 1 && checkoutCouponInfos.Exists(cc => cc.IsCombinable == false))
                {
                    // there's multiple coupons applied but at least 1 of them is NOT combinable
                    couponStatus = CouponStatus.NonCombinableCouponAlreadyInUse;
                    return(false);
                }

                CouponDiscountType discountType = coupon.DiscountTypeName;
                //--- Applies to products?
                if (discountType == CouponDiscountType.Product)
                {
                    // make sure the Product(s) the coupon applies to are in the User's Cart
                    List <int> couponProductIds = coupon.GetProductIds().ConvertAll(s => Convert.ToInt32(s));
                    List <int> cartProductIds   = checkoutOrderInfo.Cart.GetCartProducts().ToList().ConvertAll(p => p.Id.Value);

                    // 'cartProductIds' must contain at least 1 of the 'couponProductIds'
                    List <int> intersectedIds = cartProductIds.Intersect(couponProductIds).ToList();
                    if (intersectedIds.Count == 0)
                    {
                        couponStatus = CouponStatus.NoEligibleProduct;
                        return(false);
                    }
                }

                //--- Applies to shipping?
                if (discountType == CouponDiscountType.Shipping)
                {
                    // make sure one of the Shipping Option(s) the coupon applies to has been selected by the User
                    if (checkoutOrderInfo.ShippingProvider != ShippingProviderType.UNKNOWN)
                    {
                        if (!coupon.GetShippingRateTypes().Contains(checkoutOrderInfo.ShippingRate.ServiceType))
                        {
                            couponStatus = CouponStatus.NoEligibleShipping;
                            return(false);
                        }
                    }
                }

                //--- min. cart total
                if (coupon.MinOrderAmount.HasValue && (checkoutOrderInfo.Total < coupon.MinOrderAmount.Value))
                {
                    couponStatus = CouponStatus.MinOrderAmountNotReached;
                    return(false);
                }

                // TODO - Max # redemptions per user
                // Probably need to implement some kind of "User GUID" cookie value at the store level to track unique users/visitors
                // since we can't reliably use UserId (won't work for anonymous checkout) or IP address (different users behind same IP)

                //--- max. # redemptions - lifetime
                if (coupon.MaxUsesLifetime.HasValue)
                {
                    int numLifetimeRedemptions = coupon.GetNumberOfRedemptions();
                    if (numLifetimeRedemptions >= coupon.MaxUsesLifetime.Value)
                    {
                        couponStatus = CouponStatus.ExceededMaxLifetimeRedemptions;
                        return(false);
                    }
                }

                couponStatus = CouponStatus.Valid;
                return(true);
            }
            return(false);
        }
Example #41
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();
        }
Example #42
0
        static void Main(string[] args)
        {
            Console.WriteLine();
            for (int i = 0; i < args.Length; i++)
            {
                Console.WriteLine($"Arg {i}: {args[i]}");
            }

            string[] myArgs = Environment.GetCommandLineArgs();
            Console.WriteLine(string.Join(", ", myArgs));
            //SayHallo();

            bool canIVote = true;

            Console.WriteLine($"Biggest Integer: {int.MaxValue}");
            Console.WriteLine($"Smallest Integer: {int.MinValue}");
            Console.WriteLine($"Biggest Double: {double.MaxValue.ToString("#")}");
            decimal  decPiVal    = 3.1315926535897932384626433832M;
            bool     boolFromStr = bool.Parse("true");
            int      intFromStr  = int.Parse("10");
            DateTime awesomeDate = new DateTime(1986, 3, 2);

            Console.WriteLine($"Day of Week: {awesomeDate.DayOfWeek}");
            awesomeDate = awesomeDate.AddDays(4);
            awesomeDate = awesomeDate.AddMonths(1);
            awesomeDate = awesomeDate.AddYears(2);
            Console.WriteLine($"New date: {awesomeDate.Date}");
            TimeSpan lunchTime = new TimeSpan(12, 30, 0);

            lunchTime = lunchTime.Subtract(new TimeSpan(0, 15, 0));
            lunchTime = lunchTime.Add(new TimeSpan(1, 0, 0));
            Console.WriteLine($"New Time: {lunchTime.ToString()}");

            BigInteger big = BigInteger.Parse("1234132432543253242342342314122412");

            Console.WriteLine($"Big Num * 2 = {big * 2}");
            Console.WriteLine("Currency: {0:c}", 23.455);
            Console.WriteLine("Pad with 0s: {0:d4}", 23);
            Console.WriteLine("3 Decimals: {0:f3}", 23.4555);
            Console.WriteLine("Commas: {0:n4}", 2300);

            string randString = "This is a string";

            Console.WriteLine("String Length: {0}", randString.Length);
            Console.WriteLine("String Contains is: {0}", randString.Contains("is"));
            Console.WriteLine("Index of is: {0}", randString.IndexOf("is"));
            Console.WriteLine("Remove String: {0}", randString.Remove(0, 6));
            Console.WriteLine("Insert String: {0}", randString.Insert(10, "short "));
            Console.WriteLine("Replace String: {0}", randString.Replace("string", "sentence"));
            Console.WriteLine("Compare A to B: {0}", String.Compare("A", "B", StringComparison.OrdinalIgnoreCase));
            Console.WriteLine("A = a: {0}", String.Equals("A", "a", StringComparison.OrdinalIgnoreCase));
            Console.WriteLine("Pad Left: {0}", randString.PadLeft(20, '.'));
            Console.WriteLine("Pad Right: {0}", randString.PadRight(20, '.'));
            Console.WriteLine("Trim(): {0}", randString.Trim());
            Console.WriteLine("Uppercase: {0}", randString.ToUpper());
            Console.WriteLine("Lowercase: {0}", randString.ToLower());

            string newString = String.Format("{0} saw a {1} {2} in the {3}", "Paul", "rabbit", "eating", "field");

            Console.WriteLine(newString);
            Console.WriteLine(@"Exactly what I Typed ' \");

            // Classes
            Shape[] shapes = { new Circle(5), new Rectangle(4, 5) };
            foreach (Shape s in shapes)
            {
                s.GetInfo();
                Console.WriteLine("{0} Area: {1:f2}", s.Name, s.Area());
                Circle testCirc = s as Circle;
                if (testCirc == null)
                {
                    Console.WriteLine("This isn't a Circle");
                }

                if (s is Circle)
                {
                    Console.WriteLine("This isn't a Rectangle");
                }
            }
            object circ1 = new Circle(4);
            Circle circ2 = (Circle)circ1;

            Console.WriteLine("The {0} Area is {1:f2}", circ2.Name, circ2.Area());

            // Interfaces
            Vehicle buick = new Vehicle("Buick", 4, 160);

            if (buick is IDrivable)
            {
                buick.Move();
                buick.Stop();
            }
            else
            {
                Console.WriteLine("The {0} can't be driven", buick.Brand);
            }
            IElectronicDevice TV     = TVRemote.GetDevice();
            PowerButton       powBut = new PowerButton(TV);

            powBut.Execute();
            powBut.Undo();

            // Collections
            collectionFunctions();

            // Generics
            //List<int> numList = new List<int>();
            List <Animal> animalList = new List <Animal>();

            animalList.Add(new Animal()
            {
                Name = "Doug"
            });
            animalList.Add(new Animal()
            {
                Name = "Paul"
            });
            animalList.Add(new Animal()
            {
                Name = "Sally"
            });
            animalList.Insert(1, new Animal()
            {
                Name = "Steve"
            });
            animalList.RemoveAt(1);
            Console.WriteLine("Num of Animals: {0}", animalList.Count());
            foreach (Animal a in animalList)
            {
                Console.WriteLine(a.Name);
            }
            int x = 5, y = 4;

            Animal.GetSum(ref x, ref y);
            string strX = "4", strY = "3";

            Animal.GetSum(ref strX, ref strY);
            Rectangle <int> rec1 = new Rectangle <int>(20, 50);

            Console.WriteLine(rec1.GetArea());
            Rectangle <string> rec2 = new Rectangle <string>("20", "50");

            Console.WriteLine(rec2.GetArea());

            // Delegates
            Arithmetic add, sub, addSub;

            add    = new Arithmetic(Add);
            sub    = new Arithmetic(Subtract);
            addSub = add + sub;
            Console.WriteLine("Add 6 & 10");
            add(6, 10);
            Console.WriteLine("Add & Subtract 10 & 4");
            addSub(10, 4);

            // Manipulating list
            doubleIt dlIt = z => z * 2;

            Console.WriteLine($"5 + 2 = {dlIt(5)}");
            List <int> numList = new List <int> {
                1, 9, 2, 6, 3
            };
            var evenList = numList.Where(a => a % 2 == 0).ToList();

            foreach (var j in evenList)
            {
                Console.WriteLine(j);
            }
            var rangeList = numList.Where(a => (a > 2) && (a < 9)).ToList();

            foreach (var j in rangeList)
            {
                Console.WriteLine(j);
            }
            List <int> flipList = new List <int>();
            int        k        = 0;
            Random     rnd      = new Random();

            while (k < 100)
            {
                flipList.Add(rnd.Next(1, 3));
                k++;
            }
            Console.WriteLine("Heads: {0}", flipList.Where(a => a == 1).ToList().Count);
            Console.WriteLine("Tails: {0}", flipList.Where(a => a == 2).ToList().Count);

            var nameList = new List <string> {
                "Doug", "Sally", "Sue"
            };
            var sNameList = nameList.Where(a => a.StartsWith("S"));

            foreach (var m in sNameList)
            {
                Console.WriteLine(m);
            }
            var oneTo10 = new List <int>();

            oneTo10.AddRange(Enumerable.Range(1, 10));
            var squares = oneTo10.Select(a => a * a);

            foreach (var l in squares)
            {
                Console.WriteLine(l);
            }
            var listOne = new List <int>(new int[] { 1, 3, 4 });
            var listTwo = new List <int>(new int[] { 4, 6, 8 });
            var sumList = listOne.Zip(listTwo, (a, b) => a + b).ToList();

            foreach (var n in sumList)
            {
                Console.WriteLine(n);
            }
            var numList2 = new List <int>()
            {
                1, 2, 3, 4, 5, 6
            };

            Console.WriteLine("Sum: {0}", numList2.Aggregate((a, b) => a + b));
            Console.WriteLine("Average: {0}", numList2.AsQueryable().Average());
            Console.WriteLine("All > 3: {0}", numList2.All(a => a > 3));
            Console.WriteLine("Any > 3: {0}", numList2.Any(a => a > 3));
            var numList3 = new List <int>()
            {
                1, 2, 3, 2, 3
            };

            Console.WriteLine("Distinct: {0}", string.Join(", ", numList3.Distinct()));
            var numList4 = new List <int>()
            {
                3
            };

            Console.WriteLine("Except: {0}", string.Join(", ", numList3.Except(numList4)));
            Console.WriteLine("Intersect: {0}", string.Join(", ", numList3.Intersect(numList4)));

            // Overloading and enumaration
            AnimalFarm myAnimals = new AnimalFarm();

            myAnimals[0] = new Animal("Wilbur");
            myAnimals[1] = new Animal("Templeton");
            myAnimals[2] = new Animal("Gander");
            myAnimals[3] = new Animal("Charlotte");
            foreach (Animal i in myAnimals)
            {
                Console.WriteLine(i.Name);
            }
            Box box1 = new Box(2, 3, 4);
            Box box2 = new Box(5, 6, 7);
            Box box3 = box1 + box2;

            Console.WriteLine($"Box 3: {box3}");
            Console.WriteLine($"Box Int: {(int)box3}");
            Box box4 = (Box)4;

            Console.WriteLine($"Box 4: {box4}");
            var shopkins = new
            {
                Name  = "Shopkins",
                Price = 4.99
            };

            Console.WriteLine("{0} cost ${1}", shopkins.Name, shopkins.Price);
            var toyArray = new[] {
                new { Name = "Yo-Kai Pack", Price = 4.99 },
                new { Name = "Legos", Price = 9.99 }
            };

            foreach (var item in toyArray)
            {
                Console.WriteLine("{0} costs ${1}", item.Name, item.Price);
            }
            Console.ReadLine();
        }
Example #43
0
 private static IEnumerable <int> Intersect(List <int> a, List <int> b)
 {
     return(a.Intersect(b));
 }
Example #44
0
        //Retorna um PATH, representado por um caminho de Edge
        //Utilizado em ROUTE
        public static Path find_best_route_Dijkstra(Graph graph, Node A, Node B)
        {
            //Para o Path resultado
            var nodes_resultado = new List <Node>();
            var edges_resultado = new List <Edge>();

            //Antes de comecar o Dijkstra, eu preciso considerar somentes todo e qualquer node que:
            //Tem caminho ate A & Tem caminho ate B

            //Para tanto, eu faco um greedy, a partir do node A, e outro, a partir do node B.
            //Com isso, levanto tos os nodes do grafo que sao acessiveis para A, e depois para B.
            //Faco a uniao desse conjunto, tendo entao os nodes interessantes para o Dijkstra

            //ATENCAAAO!
            //Antes de calcular o reachables do B, ver se o B esta nos reachables do A
            //Esse check é importante, pq se nao tiver, ja pode parar o algortimo.

            //Depois eu pego a interseção, pq isso vai deixar o Dijsktra muito mais rapido, sem necessidade de calcular uma porrada de node...

            //Usando avoid, evito varios pontos sem necessidae... pq faco um greed de todos os pontos a partir de B sem passar por A.
            //E todos os pontos a partir de A sem passar por B. A intereseçao é todos os pontos dos caminhos possiveis entre A e B.

            //EDIT:
            //Pensei que isso me retornaria todos os PATHS, mas estava errado!!
            //http://stackoverflow.com/questions/9535819/find-all-paths-between-two-graph-nodes


            //EDIT: So existe uma situação onde a interseção abaixo nao vai retornar nada erronemanente. É quando tiver um caminho direto entre A e B.
            var unico_edge = graph.Edges.Where(e => (e.nA == A && e.nB == B) || (e.nA == B && e.nB == A)).FirstOrDefault();

            if (unico_edge != null)
            {
                nodes_resultado.Add(unico_edge.nA);
                nodes_resultado.Add(unico_edge.nB);
                edges_resultado.Add(unico_edge);
                return(new Path(nodes_resultado, edges_resultado));
            }

            //DEIXEI O AVOID, pois traz uma melhoria minima... vai que a partir de B tem alguns nodes, nao precisa ver pro lado de la ou pro lado de ca...
            var avoid = new List <Node>();

            avoid.Add(A); //COMENTADO
            avoid.Add(B);

            List <Node> todos_os_nodes_acessiveis_por_A = reachable_nodes_greedy(graph, A, avoid);
            List <Node> todos_os_nodes_acessiveis_por_B = reachable_nodes_greedy(graph, B, avoid); //COMENTADO

            //Se ao interceder nao retornar nenhum node, entao nao existe caminho possivel... //COMENTADO
            List <Node> nodes_Problema = todos_os_nodes_acessiveis_por_A.Intersect <Node>(todos_os_nodes_acessiveis_por_B).ToList(); //COMENTADO

            //A checagem podia ser assim:
            //if (!todos_os_nodes_acessiveis_por_A.Contains(B)) return null; //Deixei a checagem mesmo, que é o mais importante ...

            //Mas deixei assim:
            if (nodes_Problema.Count == 0)
            {
                return(null);                           //Nao existe path possivel...
            }
            //Adicionando manualmente o node A e B, pq os codigos acima nao adicionam A e B...
            nodes_Problema.Add(A);
            nodes_Problema.Add(B);

            //Transformando os nodes em rotulos de Dijkstra
            var rotulos = new Dictionary <Node, Dijkstra_Rotulo>();

            //Preciso tambem dos edges do problema, para saber todos os nodes vizinhos de outro...
            List <Edge> edges_Problema = graph.Edges.Where(e => nodes_Problema.Contains(e.nA) || nodes_Problema.Contains(e.nB)).ToList();

            //Criando rotulos para todos os nodes, inclusive B
            foreach (Node n in nodes_Problema)
            {
                rotulos.Add(n, new Dijkstra_Rotulo {
                    node = n
                });                                                                              //Ja é, por default, pemamnente facil, u null e pred null
            }
            rotulos[A].permanente = true;
            rotulos[A].u          = 0;

            //RODANDO DIJKSTRA:
            Node atual = A;

            while (atual != null)
            {
                //DEBUG - Analisar com breakpoint
                //var vizinhos = edges_Problema.Where(e => e.nA == atual || e.nB == atual).Select(e => (e.nA == atual) ? e.nB : e.nA).ToList();

                //Marcando os vizinhos do atual
                foreach (var vizinho in edges_Problema.Where(e => e.nA == atual || e.nB == atual).Select(e => (e.nA == atual) ? e.nB : e.nA))
                {
                    //E pra pegar um vizinho somente se ele for node do problema... se nao num tem necessidade...
                    if (!nodes_Problema.Contains(vizinho))
                    {
                        continue;
                    }

                    //Somando a distancia do vizinho ao rotulo atual
                    var u_candidato = rotulos[atual].u + Math.Pow(Math.Pow(atual.x - vizinho.x, 2) + Math.Pow(atual.y - vizinho.y, 2), 0.5);

                    //O u sendo null é minha versao de infinito... se for, qualquer coisa é melhor..
                    if (rotulos[vizinho].u == null || u_candidato < rotulos[vizinho].u)
                    {
                        rotulos[vizinho].u    = u_candidato;
                        rotulos[vizinho].pred = atual;
                    }
                }

                //DEBUG - Analisar com breakpoint
                //var nao_permanentes = rotulos.Where(kvp => kvp.Value.permanente == false && kvp.Value.u != null).ToList();

                //Procurando agora o no, temporario, de menor u. Ele vira permanente e passa a ser o atual.
                //No momento que nao houver temporarios, acabar o loop

                atual = null;
                foreach (var kvp in rotulos.Where(kvp => kvp.Value.permanente == false && kvp.Value.u != null)) //Nao pode ser infinito, um infinito nunca vai ser o atual... pq os vizinhos sempre tem u...
                {
                    if (atual == null)
                    {
                        atual = kvp.Key;
                    }
                    else
                    {
                        if (kvp.Value.u < rotulos[atual].u)
                        {
                            atual = kvp.Key;                                 //Escolhendo o node com menor u
                        }
                    }
                }

                if (atual != null)
                {
                    rotulos[atual].permanente = true;                //Tornando o atual permanente!
                }
                //Se passar daqui, entao é pq nao achou nenhum temporario. Assim, vai null para o while, e ele sai...
            }

            //Calculando o PathN resultado.

            //Agora, de traz pra frente, vai montando o PathN...

            var node_final = B; //Vai começar pelo B, o final

            //Agora vai inserir B e pegar o predecessor. Quando o predecessor for o A, parar
            while (true)
            {
                nodes_resultado.Insert(0, node_final); //Mantendo a ordem... vai empurrando pra frente os que foram adicionado primeiro
                edges_resultado.Insert(0, edges_Problema.Where(e => (e.nA == node_final && e.nB == rotulos[node_final].pred) || (e.nB == node_final && e.nA == rotulos[node_final].pred)).First());

                if (rotulos[node_final].pred == A)
                {
                    break;
                }

                node_final = rotulos[node_final].pred;
            }

            nodes_resultado.Insert(0, A); //Inserir o A manualmente

            return(new Path(nodes_resultado, edges_resultado));
        }
Example #45
0
        static void Main()
        {
            IList <string> iListOfString = new List <string> {
                "1st", "2nd", "3rd"
            };
            IEnumerable <string> iEnumerableOfString = iListOfString.AsEnumerable();

            Dictionary <string, IList <string> > dictionaryOfIList = new Dictionary <string, IList <string> >
            {
                { "1st", new List <string> {
                      "1st", "2nd", "3rd"
                  } },
                { "2nd", new List <string> {
                      "1st", "2nd", "3rd"
                  } },
                { "3rd", new List <string> {
                      "1st", "2nd", "3rd"
                  } }
            };

            Dictionary <string, IEnumerable <string> >
            dictionaryOfIEnumerable1 = dictionaryOfIList
                                       .Select(item => new { item.Key, Value = item.Value.Cast <string>() })
                                       .ToDictionary(item => item.Key, item => item.Value),
                dictionaryOfIEnumerable2 = dictionaryOfIList
                                           .Select(item => new { item.Key, Value = item.Value.OfType <string>() })
                                           .ToDictionary(item => item.Key, item => item.Value),
                dictionaryOfIEnumerable3 = dictionaryOfIList
                                           .Select(item => new { item.Key, Value = item.Value.AsEnumerable() })
                                           .ToDictionary(item => item.Key, item => item.Value);

            var listOfString = new List <string> {
                "1st", "2nd", "3rd"
            };

            var tmpString = "/3rd";
            var tmpBool   = listOfString.Any(item => tmpString.StartsWith($"/{item}"));

            tmpBool   = listOfString.All(item => !tmpString.StartsWith($"/{item}"));
            tmpString = "/4th";
            tmpBool   = listOfString.Any(item => tmpString.StartsWith($"/{item}"));
            tmpBool   = listOfString.All(item => !tmpString.StartsWith($"/{item}"));

            var listOfClassWithNullable = new List <ClassWithNullable>
            {
                new ClassWithNullable {
                    Id = 1
                },
                new ClassWithNullable {
                    Id = 2, FDateTime1 = new DateTime(1974, 1, 5)
                },
                new ClassWithNullable {
                    Id = 2, FDateTime2 = new DateTime(2000, 11, 22)
                },
                new ClassWithNullable {
                    Id = 2, FDateTime1 = new DateTime(1974, 1, 5), FDateTime2 = new DateTime(2000, 11, 22)
                }
            };

            var classWithNullable = new ClassWithNullable();
            var resultFromListOfClassWithNullable = listOfClassWithNullable.Where(item => item.FDateTime1 == classWithNullable.FDateTime1 && item.FDateTime2 == classWithNullable.FDateTime2).ToList();

            classWithNullable = new ClassWithNullable {
                FDateTime1 = new DateTime(1974, 1, 5)
            };
            resultFromListOfClassWithNullable = listOfClassWithNullable.Where(item => item.FDateTime1 == classWithNullable.FDateTime1 && item.FDateTime2 == classWithNullable.FDateTime2).ToList();

            classWithNullable = new ClassWithNullable {
                FDateTime2 = new DateTime(2000, 11, 22)
            };
            resultFromListOfClassWithNullable = listOfClassWithNullable.Where(item => item.FDateTime1 == classWithNullable.FDateTime1 && item.FDateTime2 == classWithNullable.FDateTime2).ToList();

            classWithNullable = new ClassWithNullable {
                FDateTime1 = new DateTime(1974, 1, 5), FDateTime2 = new DateTime(2000, 11, 22)
            };
            resultFromListOfClassWithNullable = listOfClassWithNullable.Where(item => item.FDateTime1 == classWithNullable.FDateTime1 && item.FDateTime2 == classWithNullable.FDateTime2).ToList();

            var listOfD = new List <D>
            {
                new D {
                    PString = "[1]", PInt = 1, LD = new List <D> {
                        new D {
                            PString = "[1][1]", PInt = 11, LD = new List <D> {
                                new D {
                                    PString = "[1][1][1]", PInt = 111, PBool1 = false, PBool2 = false
                                }, new D {
                                    PString = "[1][1][2]", PInt = 112, PBool1 = false, PBool2 = true
                                }, new D {
                                    PString = "[1][1][3]", PInt = 113, PBool1 = true, PBool2 = false
                                }, new D {
                                    PString = "[1][1][4]", PInt = 114, PBool1 = true, PBool2 = true
                                }
                            }
                        }, new D {
                            PString = "[1][2]", PInt = 12
                        }, new D {
                            PString = "[1][3]", PInt = 13
                        }
                    }
                },
                new D {
                    PString = "[2]", PInt = 2, LD = new List <D> {
                        new D {
                            PString = "[2][1]", PInt = 21, LD = new List <D> {
                                new D {
                                    PString = "[2][1][1]", PInt = 211, PBool1 = false, PBool2 = false
                                }, new D {
                                    PString = "[2][1][2]", PInt = 212, PBool1 = false, PBool2 = false
                                }, new D {
                                    PString = "[2][1][3]", PInt = 213, PBool1 = false, PBool2 = false
                                }, new D {
                                    PString = "[2][1][4]", PInt = 214, PBool1 = false, PBool2 = false
                                }
                            }
                        }, new D {
                            PString = "[2][2]", PInt = 22
                        }, new D {
                            PString = "[2][3]", PInt = 23
                        }
                    }
                },
                new D {
                    PString = "[3]", PInt = 3, LD = new List <D> {
                        new D {
                            PString = "[3][1]", PInt = 31, LD = new List <D> {
                                new D {
                                    PString = "[3][1][1]", PInt = 311, PBool1 = false, PBool2 = false
                                }, new D {
                                    PString = "[3][1][2]", PInt = 312, PBool1 = false, PBool2 = true
                                }, new D {
                                    PString = "[3][1][3]", PInt = 313, PBool1 = true, PBool2 = false
                                }, new D {
                                    PString = "[3][1][4]", PInt = 314, PBool1 = true, PBool2 = true
                                }
                            }
                        }, new D {
                            PString = "[3][2]", PInt = 32
                        }, new D {
                            PString = "[3][3]", PInt = 33
                        }
                    }
                },
                new D {
                    PString = "[4]", PInt = 4, LD = new List <D> {
                        new D {
                            PString = "[4][1]", PInt = 41, LD = new List <D> {
                                new D {
                                    PString = "[4][1][1]", PInt = 411, PBool1 = false, PBool2 = false
                                }, new D {
                                    PString = "[4][1][2]", PInt = 412, PBool1 = false, PBool2 = false
                                }, new D {
                                    PString = "[4][1][3]", PInt = 413, PBool1 = false, PBool2 = false
                                }, new D {
                                    PString = "[4][1][4]", PInt = 414, PBool1 = false, PBool2 = false
                                }
                            }
                        }, new D {
                            PString = "[4][2]", PInt = 42
                        }, new D {
                            PString = "[4][3]", PInt = 43
                        }
                    }
                }
            };

            var subListOfD = listOfD.Where(outer => outer.LD.All(inner => inner.PInt != 11) && outer.LD.All(inner => inner.PInt != 41)).ToList();

            subListOfD = (from outer in listOfD
                          let inner = outer.LD
                                      where inner.All(item => item.PInt != 11) && inner.All(item => item.PInt != 41)
                                      select outer).ToList();

            subListOfD = listOfD
                         .Select(outer => new { outer, outer.LD })
                         .Where(tmpAkaLet => tmpAkaLet.LD.All(inner => inner.PInt != 11) && tmpAkaLet.LD.All(inner => inner.PInt != 41)).Select(tmpAkaLet => tmpAkaLet.outer).ToList();


            listOfD = new List <D>
            {
                new D {
                    PString = "q", PInt = 10
                },
                new D {
                    PString = "я", PInt = 10
                },
                new D {
                    PString = "й", PInt = 2
                },
                new D {
                    PString = "f", PInt = 3
                }
            };

            foreach (var item in listOfD.OfType <D>().OrderBy(i => i.PInt).ThenBy(i => i.PString))
            {
                Debug.WriteLine($"{{PInt:{item.PInt}, PString:\"{item.PString}\"}}");
            }
            //foreach (var item in listOfD.OfType<D>().OrderBy(i => new {i.PInt, i.PString})) // System.ArgumentException "По крайней мере в одном объекте должен быть реализован интерфейс IComparable."
            //    Debug.WriteLine($"{{PInt:{item.PInt}, PString:\"{item.PString}\"}}");
            foreach (var item in listOfD.OfType <D>().OrderBy(i => i.PInt.ToString() + i.PString))
            {
                Debug.WriteLine($"{{PInt:{item.PInt}, PString:\"{item.PString}\"}}");
            }

            var test0 = listOfD.SelectMany(level1 => level1.LD).SelectMany(level2 => level2.LD).ToList();
            var test1 = listOfD.Where(level1 => level1.LD.Any(level2 => level2.LD.Any(level3 => level3.PBool2))).ToList();
            var test2 = listOfD.Where(level1 => level1.LD.SelectMany(level2 => level2.LD).Any(level3 => level3.PBool2)).ToList();

            List <int>
            listOfInt = new List <int> {
                1, 2, 3, 4, 5
            },
                listOfIntII = new List <int> {
                2, 3
            },
                listOfIntIII;

            tmpString = listOfInt.Aggregate("", (str, next) => $"{str} , {next.ToString()}");

            listOfIntIII = (from i in listOfInt
                            where
                            listOfIntII.Contains(i)
                            select i).ToList();

            listOfIntIII = listOfInt.Where(i => listOfIntII.Contains(i)).ToList();
            listOfIntIII = listOfInt.Intersect(listOfIntII).ToList();
            listOfIntIII = listOfIntII.Intersect(listOfInt).ToList();

            List <A> listOfA = new List <A>
            {
                new A {
                    FA = 1, FB = true
                },
                new A {
                    FA = 1, FB = true
                },
                new A {
                    FA = 2
                },
                new A {
                    FA = 2
                }
            };

            var doubles = listOfA.GroupBy(item => new { item.FA, item.FB });
            var keys    = doubles.Select(g => g.Key);
            int tmpInt  = keys.Count();

            listOfA.Add(new A {
                FA = 1
            });
            doubles = listOfA.GroupBy(item => new { item.FA, item.FB });
            keys    = doubles.Select(g => g.Key);
            tmpInt  = keys.Count();

            var doublesII = listOfA.GroupBy(a => a.FA).Where(ga => ga.GroupBy(b => b.FB).Select(gb => gb.Key).Count() > 1);

            foreach (IGrouping <int, A> g in doublesII)
            {
                foreach (A a in g)
                {
                    Debug.WriteLine(a);
                }
            }

            doublesII = listOfA.GroupBy(a => a.FA).Where(ga => ga.GroupBy(b => b.FB).Select(gb => gb.Key).Count() > 1);
            foreach (A a in doublesII.SelectMany(g => g))
            {
                Debug.WriteLine(a);
            }

            List <bool> listOfBool = new List <bool> {
                true, true, true
            };

            tmpBool    = listOfBool.Aggregate(true, (val, next) => { return(val && next); });
            listOfBool = new List <bool> {
                true, false, true
            };
            tmpBool = listOfBool.Aggregate(true, (val, next) => { return(val && next); });

            List <ClassWithNullableValues> listOfClassWithNullableValues = new List <ClassWithNullableValues>
            {
                new ClassWithNullableValues {
                    fDateTime = null, fLong = null
                },
                new ClassWithNullableValues {
                    fDateTime = DateTime.Now.Date, fLong = null
                },
                new ClassWithNullableValues {
                    fDateTime = null, fLong = 9L
                },
                new ClassWithNullableValues {
                    fDateTime = DateTime.Now.Date, fLong = 13L
                },
            };

            var testNullable = listOfClassWithNullableValues.Where(item => item.fDateTime == DateTime.Now.Date).ToArray();

            testNullable = listOfClassWithNullableValues.Where(item => item.fLong == 13L).ToArray();

            Dictionary <int, List <A> > dictionaryIntListOfA = new Dictionary <int, List <A> >
            {
                { 1, new List <A> {
                      new A {
                          FA = 1
                      }
                  } },
                { 2, new List <A> {
                      new A {
                          FA = 1
                      }, new A {
                          FA = 2
                      }
                  } },
                { 3, new List <A> {
                      new A {
                          FA = 1
                      }, new A {
                          FA = 2
                      }, new A {
                          FA = 3
                      }
                  } },
                { 4, new List <A> {
                      new A {
                          FA = 1
                      }, new A {
                          FA = 1
                      }, new A {
                          FA = 2
                      }
                  } },
                { 5, new List <A> {
                      new A {
                          FA = 1
                      }, new A {
                          FA = 2
                      }, new A {
                          FA = 2
                      }
                  } },
                { 6, new List <A> {
                      new A {
                          FA = 1
                      }, new A {
                          FA = 1
                      }, new A {
                          FA = 2
                      }, new A {
                          FA = 2
                      }
                  } }
            };

            var _doubles = dictionaryIntListOfA.SelectMany(item => item.Value).GroupBy(item => new { item.FA, item.FB }).Where(g => g.Count() > 1).SelectMany(g => g).ToList();

            foreach (var dd in _doubles)
            {
                Console.WriteLine(dd);
            }

            var _equalsValues = dictionaryIntListOfA[4].GroupBy(a => a.FA).Where(g => g.Count() > 1).Select(g => g.ToList());

            foreach (List <A> _tmpA_ in _equalsValues)
            {
                Console.WriteLine(_tmpA_.Count());
            }

            _equalsValues = dictionaryIntListOfA[6].GroupBy(a => a.FA).Where(g => g.Count() > 1).Select(g => g.ToList());

            foreach (List <A> _tmpA_ in _equalsValues)
            {
                Console.WriteLine(_tmpA_.Count());
            }

            //var _equalsNodes = dictionaryIntListOfA.Where(item => item.Value.GroupBy(a => a.FA).Where(g => g.Count() > 1).Count() > 0);
            //var _equalsNodes = dictionaryIntListOfA.Where(item => item.Value.GroupBy(a => a.FA).Where(g => g.Count() > 1).Any());
            var _equalsNodes = dictionaryIntListOfA.Where(item => item.Value.GroupBy(a => a.FA).Any(g => g.Count() > 1));

            int[] tmpInts = null;

            try
            {
                tmpInt = tmpInts.First(); // ArgumentNullException "Value cannot be null.\r\nParameter name: source"
                //tmpInt = tmpInts.FirstOrDefault(); // ArgumentNullException "Value cannot be null.\r\nParameter name: source"
            }
            catch (ArgumentNullException eException)
            {
                Debug.WriteLine("{0}: \"{1}\"", eException.GetType().FullName, eException.Message);
            }

            tmpInts = new int[0];

            try
            {
                tmpInt = tmpInts.First(); // InvalidOperationException "Sequence contains no elements"
                //tmpInt = tmpInts.FirstOrDefault(); // ok
            }
            catch (InvalidOperationException eException)
            {
                Debug.WriteLine("{0}: \"{1}\"", eException.GetType().FullName, eException.Message);
            }

            City[] cities =
            {
                new City {
                    CityCode = "0771", CityName = "Raipur", CityPopulation = "BIG"
                },
                new City {
                    CityCode = "0751", CityName = "Gwalior", CityPopulation = "MEDIUM"
                },
                new City {
                    CityCode = "0755", CityName = "Bhopal", CityPopulation = "BIG"
                },
                new City {
                    CityCode = "022", CityName = "Mumbai", CityPopulation = "BIG"
                },
            };

            CityPlace[] places =
            {
                new CityPlace {
                    CityCode = "0771", Place = "Shankar Nagar"
                },
                new CityPlace {
                    CityCode = "0771", Place = "Pandari"
                },
                new CityPlace {
                    CityCode = "0771", Place = "Energy Park"
                },

                new CityPlace {
                    CityCode = "0751", Place = "Baadaa"
                },
                new CityPlace {
                    CityCode = "0751", Place = "Nai Sadak"
                },
                new CityPlace {
                    CityCode = "0751", Place = "Jayendraganj"
                },
                new CityPlace {
                    CityCode = "0751", Place = "Vinay Nagar"
                },

                new CityPlace {
                    CityCode = "0755", Place = "Idgah Hills"
                },

                new CityPlace {
                    CityCode = "022", Place = "Parel"
                },
                new CityPlace {
                    CityCode = "022", Place = "Haaji Ali"
                },
                new CityPlace {
                    CityCode = "022", Place = "Girgaon Beach"
                },

                new CityPlace {
                    CityCode = "0783", Place = "Railway Station"
                }
            };

            var placesDoubles = places.GroupBy(item => item.CityCode).Where(g => g.Count() > 1).ToDictionary(g => g.Key, g => g.ToList());

            var query = places.GroupJoin(cities, place => place.CityCode, city => city.CityCode, (place, matchingCities) => new { place, matchingCities }).SelectMany(groupJoinItem => groupJoinItem.matchingCities.DefaultIfEmpty(new City {
                CityName = "NO NAME"
            }), (groupJoinItem, city) => new { Place = groupJoinItem.place, City = city });

            foreach (var pair in query)
            {
                Console.WriteLine(pair.Place.Place + ": " + pair.City.CityName);
            }

            listOfA = new List <A>(new[]
            {
                new A {
                    FA = 1
                },
                new A {
                    FA = 2
                },
                new A {
                    FA = 3
                }
            });

            List <A>
            listOfAII = new List <A>(new[]
            {
                new A()
                {
                    FA = 1
                },
                new A()
                {
                    FA = 3
                }
            });

            var joinResult = listOfA.Join(listOfAII, outerKeySelector => outerKeySelector.FA, innerKeySelector => innerKeySelector.FA, (outerList, innerList) => new { OuterListFA = outerList.FA, InnerListFA = innerList.FA }).ToList();

            var leftJoinResult = listOfA.GroupJoin(listOfAII, outerKeySelector => outerKeySelector.FA, innerKeySelector => innerKeySelector.FA, (outerList, innerList) => new { OuterList = outerList.FA, InnerList = innerList.Select(a => a.FA) }).SelectMany(groupJoinItem => groupJoinItem.InnerList.DefaultIfEmpty(), (groupJoinItem, innerFA) => new { groupJoinItem.OuterList, innerFA }).ToList();

            tmpInts = new[] { 1, 1, 1, 1, 1 };

            int[]
            tmpIntsII;

            tmpBool = tmpInts.Any(itemOuter => tmpInts.Any(itemInner => itemInner != itemOuter));
            tmpBool = tmpInts.Distinct().Count() != 1;
            tmpInts = new[] { 1, 2, 3, 4, 5 };
            tmpBool = tmpInts.Any(itemOuter => tmpInts.Any(itemInner => itemInner != itemOuter));
            tmpBool = tmpInts.Distinct().Count() != 1;

            A
                tmpA = new A()
            {
                FA = 1, FB = false, FC = false
            },
                tmpAII = new A()
            {
                FA = 2, FB = false, FC = false
            },
                tmpAIII = new A()
            {
                FA = 3, FB = false, FC = false
            };

            listOfA   = new List <A>(new[] { tmpA, tmpAII, tmpAIII });
            listOfAII = new List <A>(new[] { tmpA, tmpAII, tmpAIII });

            Console.WriteLine("{0}listOfA.SequenceEqual(listOfAII)", !listOfA.SequenceEqual(listOfAII) ? "!" : string.Empty);
            Console.WriteLine("{0}listOfA.SequenceEqual(listOfAII, new AComparer())", !listOfA.SequenceEqual(listOfAII, new AComparer()) ? "!" : string.Empty);

            listOfAII = new List <A>(new[]
            {
                new A()
                {
                    FA = 1, FB = false, FC = false
                },
                new A()
                {
                    FA = 2, FB = false, FC = false
                },
                new A()
                {
                    FA = 3, FB = false, FC = false
                }
            });

            Console.WriteLine("{0}listOfA.SequenceEqual(listOfAII)", !listOfA.SequenceEqual(listOfAII) ? "!" : string.Empty);
            Console.WriteLine("{0}listOfA.SequenceEqual(listOfAII, new AComparer())", !listOfA.SequenceEqual(listOfAII, new AComparer()) ? "!" : string.Empty);

            listOfAII = new List <A>(new[]
            {
                new A()
                {
                    FA = 1, FB = false, FC = false
                },
                new A()
                {
                    FA = 2, FB = false, FC = false
                },
                new A()
                {
                    FA = 2, FB = true, FC = false
                },
                new A()
                {
                    FA = 3, FB = false, FC = false
                },
                new A()
                {
                    FA = 3, FB = true, FC = false
                },
                new A()
                {
                    FA = 3, FB = true, FC = true
                }
            });

            var groupsOfA = listOfAII.GroupBy(a => a.FA);

            foreach (var group in groupsOfA)
            {
                WriteLine("{0} {1} {2}", group.Key, group.Count(), group.Select(a => a.FB).Distinct().Aggregate(string.Empty, (str, next) => { if (!string.IsNullOrWhiteSpace(str))
                                                                                                                                               {
                                                                                                                                                   str += ", ";
                                                                                                                                               }
                                                                                                                                               return(str + next.ToString()); }));
            }

            var groupsOfAB = listOfAII.GroupBy(a => new { a.FA, a.FB });

            foreach (var group in groupsOfAB)
            {
                WriteLine($"{group.Key} {group.Count()}");
            }

            tmpInt = listOfA.Select(item => item.FB).Distinct().Count();

            tmpInts = new [] { 1, 3, 5, 3 };

            listOfString = tmpInts.OfType <string>().ToList(); // listOfString.Count == 0
            listOfString = tmpInts.Select(item => item.ToString(CultureInfo.InvariantCulture)).ToList();

            var groups = tmpInts.GroupBy(x => x).Where(g => g.Count() > 1);

            tmpInt = tmpInts.GroupBy(x => x).Where(g => g.Count() > 1).Count();

            List <object>
            listOfObjectsI = new List <object>(new[] { (object)1, 3, 5.5 });

            List <int>
            listOfIntsI;

            listOfIntsI = listOfObjectsI.OfType <int>().Distinct().ToList();

            tmpInts   = new [] { 1, 3, 5 };
            tmpIntsII = new[] { 2, 4, 5 };

            int[]
            tmpIntsIII;

            tmpIntsIII = tmpInts.Except(tmpIntsII).ToArray();                 // { 1, 3 }
            tmpIntsIII = tmpIntsII.Except(tmpInts).ToArray();                 // { 2, 4 }
            tmpIntsIII = tmpInts.Concat(tmpIntsII).ToArray();                 // { 1, 3, 5, 2, 4, 5 }
            tmpIntsIII = tmpInts.Concat(tmpIntsII).Distinct().ToArray();      // { 1, 3, 5, 2, 4 }
            tmpIntsIII = tmpInts.Concat(tmpIntsII.Except(tmpInts)).ToArray(); // { 1, 3, 5, 2, 4 }
            tmpIntsIII = tmpInts.Intersect(tmpIntsII).ToArray();              // { 5 }
            tmpIntsIII = tmpIntsII.Intersect(tmpInts).ToArray();              // { 5 }

            tmpIntsII  = new int[0];
            tmpIntsIII = tmpInts.Intersect(tmpIntsII).ToArray(); // { }
            tmpIntsIII = tmpIntsII.Intersect(tmpInts).ToArray(); // { }
            tmpIntsIII = tmpInts.Except(tmpIntsII).ToArray();    // { 1, 3, 5 }
            tmpIntsIII = tmpIntsII.Except(tmpInts).ToArray();    // { }

            tmpInts    = new[] { 1, 3, 5, 3, 1 };
            tmpIntsII  = new[] { 3, 4, 5 };
            tmpIntsIII = tmpInts.Intersect(tmpIntsII).ToArray(); // { 3, 5 }
            tmpIntsIII = tmpIntsII.Intersect(tmpInts).ToArray(); // { 3, 5 }

            tmpIntsII  = new[] { 3, 4, 3 };
            tmpIntsIII = tmpInts.Intersect(tmpIntsII).ToArray(); // { 3 }
            tmpIntsIII = tmpIntsII.Intersect(tmpInts).ToArray(); // { 3 }

            string[]
            tmpStrings = { "рАз", "ДвА", "тРи" },
            tmpStringsII = { "РаЗ", "дВа", "ТрИ" },
            tmpStringsIII;

            tmpStringsIII = tmpStrings.Intersect(tmpStringsII).ToArray();
            tmpStringsIII = tmpStrings.Intersect(tmpStringsII, StringComparer.CurrentCultureIgnoreCase).ToArray();

            listOfA = new List <A>();

            tmpBool = listOfA.All(a => !a.FB); // true
            tmpBool = listOfA.Any(a => !a.FB); //false

            List <List <A> >
            listOfListOfA = new List <List <A> >();

            tmpBool = listOfListOfA.Any(list => list.LongCount(a => a.FA == 11) > 0);

            listOfListOfA = new List <List <A> >(new List <A>[]
            {
                new List <A>(),
                new List <A>(),
                new List <A>()
            });

            tmpBool = listOfListOfA.Any(list => list.LongCount(a => a.FA == 11) > 0);

            listOfListOfA = new List <List <A> >(new List <A>[]
            {
                new List <A>(new A[] { new A()
                                       {
                                           FA = 1
                                       }, new A()
                                       {
                                           FA = 2
                                       }, new A()
                                       {
                                           FA = 3
                                       } }),
                new List <A>(new A[] { new A()
                                       {
                                           FA = 1
                                       }, new A()
                                       {
                                           FA = 2
                                       }, new A()
                                       {
                                           FA = 3
                                       } }),
                new List <A>(new A[] { new A()
                                       {
                                           FA = 1
                                       }, new A()
                                       {
                                           FA = 2
                                       }, new A()
                                       {
                                           FA = 3
                                       } })
            });

            listOfA = listOfListOfA.SelectMany(list => list.Where(item => item.FA == 2)).ToList();

            long
                tmpLong = listOfListOfA[0].LongCount(a => a.FA == 1);

            tmpBool = listOfListOfA.Any(list => list.LongCount(a => a.FA == 11) > 0);
            tmpBool = listOfListOfA.Any(list => list.LongCount(a => a.FA == 1) > 0);

            List <AA>
            listOfAASrc    = new List <AA>(new AA[] { new AA(), new BB(), new CC() }),
                listOfAA   = new List <AA>(new AA[] { new AA(1), new BB(2), new CC(3) }),
                listOfAAII = new List <AA>(new AA[] { new AA(1), new BB(3), new CC(5) }),
                tmpListOfAA;

            tmpListOfAA = listOfAA.Intersect(listOfAAII).ToList();
            tmpListOfAA = listOfAA.Except(listOfAAII).ToList();

            List <BB>
            listOfBB       = new List <BB>(new BB[] { new BB(1), new BB(2), new CC(3) }),
                listOfBBII = new List <BB>(new BB[] { new BB(5), new BB(3), new CC(1) }),
                tmpListOfBB,
                listOfBBCast,
                listOfBBOfType = listOfAASrc.OfType <BB>().ToList();

            tmpListOfBB = listOfBB.Intersect(listOfBBII).ToList();
            tmpListOfBB = listOfBB.Except(listOfBBII).ToList();
            tmpListOfBB = listOfBBII.OrderBy(i => i).ToList();

            try
            {
                listOfBBCast = listOfAASrc.Cast <BB>().ToList();
            }
            catch (InvalidCastException eException)
            {
                Console.WriteLine(eException.Message);
            }

            List <CC>
            listOfCCCast,
                listOfCCOfType = listOfAASrc.OfType <CC>().ToList();

            try
            {
                listOfCCCast = listOfAASrc.Cast <CC>().ToList();
            }
            catch (InvalidCastException eException)
            {
                Console.WriteLine(eException.Message);
            }

            listOfAASrc    = new List <AA>();
            listOfCCOfType = listOfAASrc.OfType <CC>().Where(c => c.FAA == 1).ToList();

            tmpInt = listOfAASrc.OfType <CC>().Count(c => c.FAA == 1);

            try
            {
                tmpInt = listOfAASrc.OfType <CC>().Max(c => c.FCC);
            }
            catch (InvalidOperationException eException)
            {
                Console.WriteLine(eException.Message);
            }

            tmpString  = "1st 2nd 3rd 4th 5th";
            tmpStrings = tmpString.Split(' ');
            tmpString  = tmpStrings.Aggregate((str, next) => {
                if (!string.IsNullOrEmpty(str))
                {
                    str += ", ";
                }
                return(str += next);
            });

            tmpInts   = new[] { 1, 2, 3, 4, 5 };
            tmpIntsII = new[] { 1, 2, 3, 4, 5 };

            tmpString = tmpInts.Aggregate(string.Empty, (str, next) => {
                if (!string.IsNullOrEmpty(str))
                {
                    str += ", ";
                }
                return(str += next);
            });

            tmpIntsIII = (
                from i in tmpInts
                where i <= 2
                select i
                ).ToArray();

            tmpIntsIII = (
                from i in tmpInts
                where i <= 2
                select i
                ).Union(
                from i in tmpIntsII
                where i > 2
                select i
                ).ToArray();

            tmpIntsIII = (
                from i in tmpInts
                where i <= 4
                select i
                ).Union(
                from i in tmpIntsII
                where i > 2
                select i
                ).ToArray();

            tmpInt = tmpInts.Aggregate((sum, i) => sum + i);
            tmpInt = tmpInts.Aggregate(0, (total, next) => {
                Console.WriteLine("total: {0} next: {1}", total, next);
                return(next % 2 == 0 ? total + 1 : total);
            });
            tmpInt = tmpInts.Aggregate(3, (biggest, i) => {
                Console.WriteLine("biggest: {0} i: {1}", biggest, i);
                return(biggest > i ? biggest : i);
            }, b => {
                Console.WriteLine("b: {0}", b);
                return(b * 10);
            });

            listOfA = new List <A>(new[]
            {
                new A {
                    FA = 1, FB = true, FC = false
                },
                new A {
                    FA = 2, FB = true, FC = true
                },
                new A {
                    FA = 3, FB = true, FC = false
                },
                new A {
                    FA = 4, FB = true, FC = false
                }
            });

            listOfAII = new List <A>(new[]
            {
                new A {
                    FA = 1, FB = true, FC = false
                },
                new A {
                    FA = 3, FB = true, FC = false
                }
            });

            List <A>
            tmpListOfA;

            tmpListOfA = listOfA.Where(a => a.FA == 5).Where(a => a.FB).ToList();

            AComparer
                aComparer = new AComparer();

            tmpListOfA = listOfA.Intersect(listOfAII, aComparer).ToList();
            tmpListOfA = listOfA.Except(listOfAII, aComparer).ToList();

            Dictionary <int, bool>
            dictionaryOfA = listOfA.Select(e => new KeyValuePair <int, bool>(e.FA, e.FB)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            foreach (KeyValuePair <int, bool> kvp in dictionaryOfA)
            {
                Console.WriteLine(string.Format("dictionaryOfA[{0}]=\"{1}\"", kvp.Key, kvp.Value));
            }

            dictionaryOfA = (from e in listOfA select new { e.FA, e.FB }).ToDictionary(o => o.FA, o => o.FB);
            foreach (KeyValuePair <int, bool> kvp in dictionaryOfA)
            {
                Console.WriteLine(string.Format("dictionaryOfA[{0}]=\"{1}\"", kvp.Key, kvp.Value));
            }

            dictionaryOfA = listOfA.Select(e => new { e.FA, e.FB }).ToDictionary(o => o.FA, o => o.FB);
            foreach (KeyValuePair <int, bool> kvp in dictionaryOfA)
            {
                Console.WriteLine(string.Format("dictionaryOfA[{0}]=\"{1}\"", kvp.Key, kvp.Value));
            }

            tmpA = default(A);
            tmpA = listOfA.SingleOrDefault(i => i.FA == 3);
            tmpA = listOfA.SingleOrDefault(i => i.FA == 13);
            if (tmpA == default(A))
            {
                Console.WriteLine("default(A)");
            }

            listOfIntII = new List <int>(/*new int[] { -1, 0, 1}*/);
            tmpIntsIII  = listOfIntII.ToArray();
            tmpBool     = tmpIntsIII.All(i => i > 0);
            tmpBool     = tmpIntsIII.Any(i => i == 0);
            tmpBool     = listOfA.All(i => i.FB);
            tmpBool     = listOfA.All(i => i.FC);
            tmpBool     = listOfA.Any();
            tmpBool     = listOfA.Any(i => i.FA > 13);

            tmpListOfA = listOfA.Take(2).ToList();

            tmpInt = listOfA.Count();
            tmpInt = listOfA.Count(i => !i.FC);
            tmpInt = listOfA.Where(i => i.FC).Select(i => i.FA).FirstOrDefault();

            listOfA = new List <A>(new A[]
            {
                new A {
                    FA = 1, FB = true, FC = false
                },
                new A {
                    FA = 2, FB = true, FC = true
                },
                new A {
                    FA = 3, FB = true, FC = false
                },
                new A {
                    FA = 4, FB = true, FC = false
                }
            });

            List <B>
            listOfB = new List <B>();

            listOfB.Add(new B(listOfA));
            listOfB.Add(new B(listOfA));
            listOfB.Add(new B(listOfA));

            listOfInt = listOfB.SelectMany(i => i.LA).Where(i => i.FC).Select(i => i.FA).ToList();

            var tmp = listOfB.SelectMany(i => i.LA).Select(ii => ii.FA);

            List <C>
            listOfC = new List <C>();

            listOfC.Add(new C(1, listOfA));
            listOfC.Add(new C(2, listOfA));
            listOfC.Add(new C(3, listOfA));
            listOfC.Add(new C(4, listOfA));

            var
                tmpList = from c in listOfC
                          select
                          new
            {
                c.FI,
                IsSelected = c.LA.Any(a => a.FC)
            };

            tmpListOfA = listOfA.Where(r => r.FC).ToList();

            var itemsOfA = from itemOfC in listOfC where itemOfC.FI == 1 from itemOfA in itemOfC.LA select itemOfA;

            DateTime
                tmpDateTimeI  = new DateTime(2017, 1, 1),
                tmpDateTimeII = new DateTime(2017, 1, 5);

            IEnumerable <DateTime>
            tmpListOfDateTime = Enumerable.Range(0, (int)(tmpDateTimeII - tmpDateTimeI).TotalDays + 1).Select(x => tmpDateTimeI.AddDays(x)).ToList();

            IEnumerable <int>
            tmpListOfInt = Enumerable.Range(0, 10);     // [0,1,2,3,4,5,6,7,8,9]

            IEnumerable <IEnumerable <int> >
            tmpListOfListOfInt = Enumerable.Repeat(tmpListOfInt, 100); // [[0,1,2,3,4,5,6,7,8,9],...,[0,1,2,3,4,5,6,7,8,9]]

            tmpListOfInt = tmpListOfListOfInt.SelectMany(x => x);      // [0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,...,0,1,2,3,4,5,6,7,8,9] // 2D -> 1D

            IEnumerable <string>
            tmpListOfString = tmpListOfInt.Select(x => x.ToString());     // ["0","1","2","3","4","5","6","7","8","9",...,"0","1","2","3","4","5","6","7","8","9"]

            tmpString = tmpListOfString.ToString();
            tmpString = tmpListOfString.Aggregate((a, b) => a + b); // "01234566789...01234566789"

            tmpString = Enumerable.Repeat(Enumerable.Range(0, 10), 100).SelectMany(x => x).Select(x => x.ToString()).Aggregate((a, b) => a + b);

            tmpInts    = new int[] { 1, 2, 3, 4, 5 };
            tmpIntsII  = new int[] { 1, 2, 3, 4, 5 };
            tmpIntsIII = tmpInts.Zip(tmpIntsII, (first, second) => first * second).ToArray();

            List <DateTime>
            listOfDateTime =
                new List <DateTime>(new[]
            {
                new DateTime(2013, 1, 15), new DateTime(2013, 1, 5),
                new DateTime(2013, 1, 14)
            });

            var _orderBy_ = listOfDateTime.OrderBy(x => x);
            var _select_  = _orderBy_.Select(x => x.ToShortDateString());
            // if list is empty System.InvalidOperationException is occured
            var _aggregate_ = _select_.Aggregate((str, next) =>
            {
                if (!string.IsNullOrEmpty(str))
                {
                    str += "-";
                }

                return(str + next);
            });

            var __aggregate__ = _select_.Aggregate("", (str, next) =>
            {
                if (!string.IsNullOrEmpty(str))
                {
                    str += "-";
                }

                return(str + next);
            });

            tmpString = listOfDateTime.OrderBy(x => x).Select(x => x.ToShortDateString()).Aggregate("", (str, next) =>
            {
                if (!string.IsNullOrEmpty(str))
                {
                    str += "-";
                }

                return(str + next);
            });

            tmpString = listOfDateTime.OrderBy(x => x).Select(x => x.ToShortDateString()).Aggregate("", (str, next) =>
            {
                if (!string.IsNullOrEmpty(str))
                {
                    str += "-";
                }

                return(str + next);
            },
                                                                                                    str =>
            {
                return(str.Replace("-", "~"));
            });

            var listOfClassForTestAggregate = new List <ClassForTestAggregate>
            {
                new ClassForTestAggregate("1st"),
                new ClassForTestAggregate("2nd"),
                new ClassForTestAggregate("3rd"),
                new ClassForTestAggregate("4th")
            };

            tmpString = listOfClassForTestAggregate.Aggregate("", (str, next) =>
            {
                if (string.IsNullOrWhiteSpace(next.FString))
                {
                    return(str);
                }

                if (next.FString[0] - '0' > 2)
                {
                    return(str);
                }

                return(str += next.FString);
            });

            Console.WriteLine(tmpString);

            var xmlTree = XElement.Parse(
                @"<Root>
    <Child>aaa<GrandChild anAttribute='xyz'>Text</GrandChild>
        <!--a comment-->
        <?xml-stylesheet type='text/xsl' href='test.xsl'?>
    </Child>
    <Child>ccc<GrandChild>Text</GrandChild>ddd</Child>
</Root>");
            var nodes =
                from node in xmlTree.Elements("Child").DescendantNodes()
                select node;

            foreach (var node in nodes)
            {
                switch (node.NodeType)
                {
                case XmlNodeType.Element:
                    Console.WriteLine("Element: {0}", ((XElement)node).Name);
                    break;

                case XmlNodeType.Text:
                    Console.WriteLine("Text: {0}", ((XText)node).Value);
                    break;

                case XmlNodeType.Comment:
                    Console.WriteLine("Comment: {0}", ((XComment)node).Value);
                    break;

                case XmlNodeType.ProcessingInstruction:
                    Console.WriteLine("PI: {0}", ((XProcessingInstruction)node).Data);
                    break;
                }
            }
        }
Example #46
0
 /// <summary>
 /// Returns the set-intersection of this and the specified list of names (case insensitive).
 /// </summary>
 /// <param name="pOther"></param>
 /// <returns></returns>
 public cHeaderFieldNameList Intersect(cHeaderFieldNameList pOther) => new cHeaderFieldNameList(mNames.Intersect(pOther.mNames, StringComparer.InvariantCultureIgnoreCase), true);
    static void Main()
    {
        #region TribonacciDealing

        BigInteger firstTribonacci  = BigInteger.Parse(Console.ReadLine());
        BigInteger secondTribonacci = BigInteger.Parse(Console.ReadLine());
        BigInteger thirdTribonacci  = BigInteger.Parse(Console.ReadLine());

        BigInteger firstSpiralMemb = BigInteger.Parse(Console.ReadLine());
        int        stepSpiral      = int.Parse(Console.ReadLine());

        List <BigInteger> TribonacciList = new List <BigInteger>();
        TribonacciList.Add(firstTribonacci);
        TribonacciList.Add(secondTribonacci);
        TribonacciList.Add(thirdTribonacci);

        BigInteger fourthTribonacci = firstTribonacci + secondTribonacci + thirdTribonacci;
        TribonacciList.Add(fourthTribonacci);
        BigInteger memberTribonacci = 0;
        BigInteger a = 0;
        a = secondTribonacci;
        BigInteger b = 0;
        b = thirdTribonacci;
        BigInteger c = 0;
        c = fourthTribonacci;
        for (int i = (int)0; i <= 100; i++)
        {
            memberTribonacci = a + b + c;
            TribonacciList.Add(memberTribonacci);
            a = b;
            b = c;
            c = memberTribonacci;
        }

        #endregion

        #region SpiralNumbers

        List <BigInteger> spiralMembers = new List <BigInteger>();
        spiralMembers.Add(firstSpiralMemb);

        BigInteger secondSpiralMemb = firstSpiralMemb + stepSpiral;
        spiralMembers.Add(secondSpiralMemb);

        BigInteger thirdSpitalMemb = secondSpiralMemb + stepSpiral;
        spiralMembers.Add(thirdSpitalMemb);

        BigInteger third = 0;
        third = thirdSpitalMemb;

        BigInteger fourthSpiralMemb = 0;
        BigInteger nextSpiralMemb   = 0;

        if (stepSpiral == 1)
        {
            for (int i = 2; i < 100; i += 2)
            {
                for (int j = i; j < 100; j += 2)
                {
                    fourthSpiralMemb = third + i * stepSpiral;
                    spiralMembers.Add(fourthSpiralMemb);
                    third = fourthSpiralMemb;

                    nextSpiralMemb = third + j * stepSpiral;
                    spiralMembers.Add(nextSpiralMemb);
                    third = nextSpiralMemb;
                    break;
                }
            }
        }
        else
        {
            for (int i = 2; i < 100; i++)
            {
                for (int j = i; j < 100; j++)
                {
                    fourthSpiralMemb = third + i * stepSpiral;
                    spiralMembers.Add(fourthSpiralMemb);
                    third = fourthSpiralMemb;

                    nextSpiralMemb = third + j * stepSpiral;
                    spiralMembers.Add(nextSpiralMemb);
                    third = nextSpiralMemb;
                    break;
                }
            }
        }
        #endregion

        #region SearchForTheFirstMatch
        BigInteger matchNumb = 0;


        var matchList             = spiralMembers.Intersect(TribonacciList);
        List <BigInteger> matches = new List <BigInteger>();

        foreach (var match in matchList)
        {
            matches.Add(match);
        }
        bool isEmpty = !matches.Any();
        if (!isEmpty)
        {
            BigInteger minMatch = (BigInteger)matchList.Min();
            Console.WriteLine(minMatch);
        }
        if (isEmpty)
        {
            Console.WriteLine("No.");
        }
        #endregion
    }
Example #48
0
        private void cmdUnion_Click(object sender, EventArgs e)
        {
            int N = 3; //Levenshtein Comparator Threshold
            LevenshteinDistanceStringComparer lev_comparator = new LevenshteinDistanceStringComparer(N);

            this.Cursor = Cursors.WaitCursor;

            if (lstHeaders.SelectedIndex == -1)
            {
                MessageBox.Show("You must select a 'Shared Header' to perform the intersection on.");
                return;
            }

            string match_header        = (string)lstHeaders.SelectedItem;
            List <FileStructure> files = listBox1.Items.Cast <FileStructure>().ToList();
            //List<string> headers = FileOperations.ReadHeadersCSV(files[0].FilePath);
            List <string> intersects = new List <string>();

            bool first_pass = true;

            foreach (FileStructure f_struct in files)
            {
                #region Retrieve data in column that matches header selected to intersect against

                //Get Index Match

                int index_header = 0;
                for (int i = 0; i < f_struct.Headers.Count; i++)
                {
                    FieldHeaderComparer comparer = new FieldHeaderComparer();

                    if (comparer.Equals(f_struct.Headers[i], match_header))
                    {
                        index_header = i;
                        break;
                    }
                }

                //Get Column Data From Matching Header
                List <string[]> entries     = FileOperations.ReadCSV(f_struct.FilePath);
                List <string>   data_column = new List <string>();
                foreach (string[] entry in entries)
                {
                    data_column.Add(entry[index_header].Trim());
                }

                #endregion

                #region Perform Intersect Operation

                if (!first_pass)
                {
                    //1 -> 256 Matches
                    //2 -> 253 Matches
                    //3 -> 242 Matches
                    //4 -> 223 Matches
                    //5 -> 208 Matches
                    //6 -> 195 Matches
                    intersects = intersects.Intersect(data_column, lev_comparator).ToList();
                }
                else
                {
                    intersects = data_column;
                    first_pass = false;
                }

                #endregion
            }

            //Find Largest DB File

            FileStructure output_db = files.OrderByDescending(x => x.Filesize).First();

            //Match Intersects with rows in file
            List <string[]> input_entries  = FileOperations.ReadCSV(output_db.FilePath);
            List <string[]> output_matches = new List <string[]>();

            int output_index_header = 0;
            for (int i = 0; i < output_db.Headers.Count; i++)
            {
                FieldHeaderComparer comparer = new FieldHeaderComparer();

                if (comparer.Equals(output_db.Headers[i], match_header))
                {
                    output_index_header = i;
                    break;
                }
            }

            foreach (string[] entry in input_entries)
            {
                bool is_match = false;
                foreach (string intersect_match in intersects)
                {
                    if (lev_comparator.Equals(entry[output_index_header], intersect_match))
                    {
                        is_match = true;
                        break;
                    }
                }

                if (is_match)
                {
                    output_matches.Add(entry);
                }
            }

            //Eliminate Empties and Duplicates

            List <string[]> output_matches_new = new List <string[]>();
            foreach (string[] entry in output_matches)
            {
                if (string.IsNullOrWhiteSpace(entry[output_index_header]))
                {
                    continue;
                }

                bool duplicate = false;
                foreach (string[] new_entry in output_matches_new)
                {
                    if (new_entry[output_index_header] == entry[output_index_header])
                    {
                        duplicate = true;
                        break;
                    }
                }

                if (!duplicate)
                {
                    output_matches_new.Add(entry);
                }
            }


            //Write Out

            using (StreamWriter writer = new StreamWriter(FilePath + "\\intersection.csv", false))
            {
                foreach (string[] entry in output_matches_new)
                {
                    StringBuilder builder = new StringBuilder();
                    foreach (string field in entry)
                    {
                        builder.Append(field + ",");
                    }
                    //builder.Remove(builder.Length - 1, 1);
                    writer.WriteLine(builder.ToString());
                }
            }

            this.Cursor = Cursors.Default;
        }
Example #49
0
        public static bool OpenPorts(List <TankiPort> portsList)
        {
            List <string> ports = portsList.Where(x => x.isOpen == false).Select(x => x.port.ToString()).ToList();

            if (ports.Count == 0)
            {
                return(false);
            }
            else
            {
                INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(
                    Type.GetTypeFromProgID("HNetCfg.FwMgr", false));
                if (!mgr.LocalPolicy.CurrentProfile.FirewallEnabled)
                {
                    return(false);
                }

                INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.
                                          CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2", false));

                List <INetFwRule> _rules = new List <INetFwRule>();
                foreach (INetFwRule rule in fwPolicy2.Rules)
                {
                    _rules.Add(rule);
                }

                var Rules = _rules.Where(x =>
                                         x.Action == NET_FW_ACTION_.NET_FW_ACTION_BLOCK &&
                                         x.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT &&
                                         x.Enabled == true).ToList();
                if (Rules.Count == 0)
                {
                    return(false);
                }


                foreach (INetFwRule rule in Rules)
                {
                    var tList       = rule.RemotePorts.Split(',').ToList();
                    var remotePorts = new List <string>();

                    foreach (var item in tList)
                    {
                        if (item.Contains('-'))
                        {
                            var t = item.Split('-').ToList().ConvertAll(x => Convert.ToInt32(x));
                            for (int i = t.First(); i <= t.Last(); i++)
                            {
                                remotePorts.Add(i.ToString());
                            }
                        }
                        else
                        {
                            remotePorts.Add(item);
                        }
                    }

                    var intersection = remotePorts.Intersect(ports).ToList();
                    if (intersection.Count == 0)
                    {
                        continue;
                    }
                    if (intersection.Count == remotePorts.Count)
                    {
                        rule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
                    }
                    else
                    {
                        rule.RemotePorts = String.Join(",", remotePorts.Except(intersection));
                        string query = "netsh advfirewall firewall add rule name=\"OpenTankiPorts\"" +
                                       " dir=out action=allow protocol=TCP remoteport=" + string.Join(",", intersection);
                        Util.ExecuteInHidedMode(query);
                    }
                }
                return(true);
            }
        }
Example #50
0
        public override bool Evaluate(CubeState state)
        {
            object[] values = this.Children.Select(n => n.Evaluate(state)).ToArray();
            switch (this.Function)
            {
            case PropositionFunction.ContainsAtLeast:
                int?tCount = values[1] as int?;
                if (tCount is null)
                {
                    throw new Exception("Tried to pass Non-Numeric as second argument to ContainsAtLeast");
                }
                int count = (int)tCount;
                if (values[0] is Node <List <PackCard> > board)
                {
                    return(board.Evaluate(state).Count >= count);
                }
                IList value = values[0] as IList;
                if (value is null)
                {
                    throw new Exception("Tried to pass Non-Enumerable as first argument to ContainsAtLeast");
                }
                return(value.Count >= count);

            case PropositionFunction.ContainsExact:
                int?tCount2 = values[1] as int?;
                if (tCount2 is null)
                {
                    throw new Exception("Tried to pass Non-Numeric as second argument to ContainsExact");
                }
                int count2 = (int)tCount2;
                if (values[0] is Node <List <PackCard> > board2)
                {
                    return(board2.Evaluate(state).Count == count2);
                }
                IList value2 = values[0] as IList;
                if (value2 is null)
                {
                    throw new Exception("Tried to pass Non-Enumerable as first argument to ContainsExact");
                }
                return(value2.Count == count2);

            case PropositionFunction.Contains:
                if (values[0] is Node <List <PackCard> > board3)
                {
                    return(board3.Evaluate(state).Contains(values[1]));
                }
                IList value3 = values[0] as IList;
                if (value3 is null)
                {
                    throw new Exception("Tried to pass Non-Enumerable as first argument to Contains");
                }
                return(value3.Contains(values[1]));

            case PropositionFunction.Intersects:
                if (values[0] is Node <List <PackCard> > lBoard && values[1] is Node <List <PackCard> > rBoard)
                {
                    return(lBoard.Evaluate(state).Intersect(rBoard.Evaluate(state)).Count() > 0);
                }
                IEnumerable left = values[0] as IEnumerable;
                if (left is null)
                {
                    throw new Exception("Tried to pass Non-Enumerable as first argument to Intersects");
                }
                IList right = values[1] as IList;
                if (right is null)
                {
                    throw new Exception("Tried to pass Non-Enumerable as second argument to Intersects");
                }
                return(left.Cast <object>().Intersect(right.Cast <object>()).Count() > 0);

            case PropositionFunction.Subset:
                if (values[0] is Node <List <PackCard> > lBoard2 && values[1] is Node <List <PackCard> > rBoard2)
                {
                    List <PackCard> lCards = lBoard2.Evaluate(state);
                    return(lCards.Intersect(rBoard2.Evaluate(state)).Count() > lCards.Count);
                }
                IList left1 = values[0] as IList;
                if (left1 is null)
                {
                    throw new Exception("Tried to pass Non-Enumerable as first argument to Subset");
                }
                IList right1 = values[1] as IList;
                if (right1 is null)
                {
                    throw new Exception("Tried to pass Non-Enumerable as second argument to Subset");
                }
                return(left1.Cast <object>().Intersect(right1.Cast <object>()).Count() == left1.Count);

            case PropositionFunction.Equals:
                return(values[0] == values[1]);
            }
            throw new NotImplementedException();
        }
Example #51
0
        public static List <int> Run(List <int> R, List <int> P, List <int> X)
        {
            if (!P.Any() && !X.Any() && R.Count() > 1)
            {
                foreach (var item in R)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                if (R == P)
                {
                    return(R);
                }
            }
            else
            {
                List <int> nodesCopy = new List <int>();
                foreach (var elem in P)
                {
                    nodesCopy.Add(elem);
                }

                foreach (var v in nodesCopy)
                {
                    List <int> GrafV = new List <int>();
                    GrafV.Add(v);

                    List <int> neighborGraph = new List <int>();
                    foreach (var elem in Graf.VerticesEdges)
                    {
                        if (elem.Source.Id == v)
                        {
                            neighborGraph.Add(elem.Destination.Id);
                        }
                        else if (elem.Destination.Id == v)
                        {
                            neighborGraph.Add(elem.Source.Id);
                        }
                    }

                    Run(R.Union(GrafV).ToList(), P.Intersect(neighborGraph).ToList(), X.Intersect(neighborGraph).ToList());

                    P.Remove(v);
                    X.Add(v);
                }
                ;
            }
            return(R);
        }
Example #52
0
        public static decimal CalculateDiscountAmount(Coupon coupon, CheckoutOrderInfo checkoutOrderInfo)
        {
            // we're assuming it's a valid coupon when this is called, maybe not a good idea??

            decimal discountAmount = 0.0m;

            CouponDiscountType discountType = coupon.DiscountTypeName;

            if (discountType == CouponDiscountType.SubTotal)
            {
                if (coupon.IsAmountOff)
                {
                    discountAmount = coupon.AmountOff.Value;
                }
                else if (coupon.IsPercentOff)
                {
                    discountAmount = coupon.PercentOffDecimal * checkoutOrderInfo.SubTotal;
                }
            }
            else if (discountType == CouponDiscountType.Product)
            {
                List <int> couponProductIds = coupon.GetProductIds().ConvertAll(s => Convert.ToInt32(s));
                List <vCartItemProductInfo> cartProductInfos = checkoutOrderInfo.Cart.GetCartItemsWithProductInfo();
                List <int> cartProductIds = cartProductInfos.ConvertAll(p => p.ProductId.Value);

                List <int> intersectedProductIds = cartProductIds.Intersect(couponProductIds).ToList();
                foreach (int productIdToDiscount in intersectedProductIds)
                {
                    vCartItemProductInfo cartItem = cartProductInfos.Find(pi => pi.ProductId.Value == productIdToDiscount);
                    if (cartItem != null)
                    {
                        if (coupon.IsAmountOff)
                        {
                            discountAmount += (coupon.AmountOff.Value * cartItem.Quantity.Value);
                        }
                        else if (coupon.IsPercentOff)
                        {
                            discountAmount += (coupon.PercentOffDecimal * cartItem.GetPriceForQuantity());
                        }
                    }
                }
            }
            else if (discountType == CouponDiscountType.Shipping)
            {
                if (coupon.IsAmountOff)
                {
                    discountAmount = coupon.AmountOff.Value;
                }
                else if (coupon.IsPercentOff)
                {
                    discountAmount = coupon.PercentOffDecimal * checkoutOrderInfo.ShippingRate.Rate;
                }
            }
            else if (discountType == CouponDiscountType.SubTotalAndShipping)
            {
                if (coupon.IsAmountOff)
                {
                    discountAmount = coupon.AmountOff.Value;
                }
                else if (coupon.IsPercentOff)
                {
                    discountAmount = coupon.PercentOffDecimal * (checkoutOrderInfo.SubTotal + checkoutOrderInfo.ShippingRate.Rate);
                }
            }
            else
            {
                throw new NotImplementedException(string.Format(@"""{0}"" is an unknown CouponDiscountType", discountType));
            }

            //--- check we didn't exceed the "Max Discount Amount Per Order"
            if (coupon.MaxDiscountAmountPerOrder.HasValue && (discountAmount > coupon.MaxDiscountAmountPerOrder.Value))
            {
                discountAmount = coupon.MaxDiscountAmountPerOrder.Value;
            }

            return(discountAmount.RoundForMoney());
        }
Example #53
0
        /// <summary>
        /// 根据规则组获取Sql语句并更新规则详情列表
        /// </summary>
        /// <param name="conditionList"></param>
        /// <param name="type">
        /// 用于标记来源是筛选器还是设定循环任务
        /// </param>
        /// <returns></returns>
        public static string GetWhereStrByCondition(List <FilterCondition> conditionList, int type, string verifId)
        {
            StringBuilder strWhere = new StringBuilder();
            //用于取交的AccId字典
            Dictionary <string, List <int> > accIdDic = new Dictionary <string, List <int> >();

            #region 更新规则详情列表
            //更新出错只记录日志
            if (RuleListBLL.AddNewRule(conditionList, type, verifId) == 0)
            {
                Logger.Info("在筛选操作中添加规则详情出错!");
            }
            #endregion

            #region 根据表名做分区
            //穷举涉及的表名
            List <string> tabNameList = new List <string>()
            {
                "i200.dbo.T_Account",
                "i200.dbo.T_OrderInfo",
                "i200.dbo.T_Business",
                "i200.dbo.T_LOG",
                "sys_i200.dbo.Sys_TagNexus",
                "sys_i200.dbo.SysRpt_ShopInfo",
                "sys_i200.dbo.SysRpt_ShopDayInfo"   //添加每日店铺汇总
            };

            foreach (var str in tabNameList)
            {
                List <FilterCondition> tempConditionList = conditionList.FindAll(x => x.TableName == str);

                if (tempConditionList != null && tempConditionList.Count > 0)
                {
                    accIdDic[str] = new List <int>();
                    StringBuilder strTemp = new StringBuilder();

                    //每日汇总表的特殊处理
                    StringBuilder strGroupBy = new StringBuilder();
                    strGroupBy.Append(" group by accountid,");

                    StringBuilder strHaving = new StringBuilder();
                    strHaving.Append(" having ");

                    switch (str)
                    {
                    case "i200.dbo.T_Account":
                        strTemp.Append("select ID from " + str + " where state=1 and ");
                        break;

                    case "i200.dbo.T_OrderInfo":
                        strTemp.Append("select accId from " + str + " where (orderstatus=2 or (orderstatus=1 and orderTypeId=2)) and ");
                        break;

                    case "i200.dbo.T_Business":
                    case "sys_i200.dbo.SysRpt_ShopInfo":
                        strTemp.Append("select isnull(accountid,0) accountid from " + str + " where ");
                        break;

                    case "sys_i200.dbo.Sys_TagNexus":
                        strTemp.Append("select acc_id from " + str + " where ");
                        break;

                    case "i200.dbo.T_LOG":
                        strTemp.Append("select accountid from i200.dbo.T_Log lt left join i200.dbo.T_Token_Api ta on lt.accountid=ta.accId where ");
                        break;

                    case "sys_i200.dbo.SysRpt_ShopDayInfo":
                        strTemp.Append("select accountid from " + str + " where ");
                        break;

                    default:
                        break;
                    }

                    //strTemp.Append(" and ");
                    //针对单表拼装SQL
                    #region 拼接SQL语句

                    foreach (var conditionItem in tempConditionList)
                    {
                        switch (conditionItem.ConditionType)
                        {
                        case "StrPair":
                        case "TimePair":
                            if (!string.IsNullOrEmpty(conditionItem.DataRange.Min.ToString()) && conditionItem.DataRange.Min.ToString() != "null")
                            {
                                strTemp.Append(" (" + conditionItem.ColName + " >= '" +
                                               conditionItem.DataRange.Min + "') and ");
                            }
                            if (!string.IsNullOrEmpty(conditionItem.DataRange.Max.ToString()) && conditionItem.DataRange.Max.ToString() != "null")
                            {
                                if (conditionItem.ConditionType == "TimePair")
                                {
                                    DateTime dt = Convert.ToDateTime(conditionItem.DataRange.Max);

                                    strTemp.Append(" (" + conditionItem.ColName + " <= '" + dt.AddDays(1) +
                                                   "') and ");
                                }
                                else
                                {
                                    strTemp.Append(" (" + conditionItem.ColName + " <= '" + conditionItem.DataRange.Max +
                                                   "') and ");
                                }
                            }
                            //strTemp.Append(" (" + conditionItem.ColName + " between '" +
                            //               conditionItem.DataRange.Min + "' and '" + conditionItem.DataRange.Max +
                            //               "') and ");
                            break;

                        case "IntPair":
                            if (conditionItem.ColName.Contains("sum("))     //包含数据的处理
                            {
                                string colName = conditionItem.ColName.Substring(
                                    conditionItem.ColName.IndexOf('(') + 1, conditionItem.ColName.IndexOf(')') - conditionItem.ColName.IndexOf('(') - 1);

                                strGroupBy.Append(colName + ", ");

                                if (conditionItem.DataRange.Min.ToString() != "null")
                                {
                                    strHaving.Append(" (" + conditionItem.ColName + " >= " +
                                                     Convert.ToInt32(conditionItem.DataRange.Min) +
                                                     ") and ");
                                }
                                if (conditionItem.DataRange.Max.ToString() != "null")
                                {
                                    strHaving.Append(" (" + conditionItem.ColName + " <= " +
                                                     Convert.ToInt32(conditionItem.DataRange.Max) +
                                                     ") and ");
                                }
                            }
                            else
                            {
                                if (conditionItem.DataRange.Min.ToString() != "null")
                                {
                                    strTemp.Append(" (" + conditionItem.ColName + " >= " +
                                                   Convert.ToInt32(conditionItem.DataRange.Min) +
                                                   ") and ");
                                }
                                if (conditionItem.DataRange.Max.ToString() != "null")
                                {
                                    strTemp.Append(" (" + conditionItem.ColName + " <= " +
                                                   Convert.ToInt32(conditionItem.DataRange.Max) +
                                                   ") and ");
                                }
                                //特殊条件组合下的字段处理
                                switch (conditionItem.ColName)
                                {
                                //连续天数附加LoginType条件
                                case "ContinuousDay":
                                    strTemp.Append(" loginType=1 and ");
                                    break;
                                }
                                //strTemp.Append(" (" + conditionItem.ColName + " between " +
                                //               Convert.ToInt32(conditionItem.DataRange.Max) + " and " +
                                //               Convert.ToInt32(conditionItem.DataRange.Min) +
                                //               ") and ");
                            }
                            break;

                        case "IntRange":
                            string intList = "";

                            //前台登录库记录方式的不统一,导致登录相关的问题需要分端处理
                            //构建分析库、或者前台重构
                            //处理移动端分端登录的相关信息(移动端分端需要重构)
                            if (conditionItem.ColName == "LogMode")
                            {
                                string mobileStr = "";

                                foreach (var intItem in conditionItem.DataRange.Range)
                                {
                                    int label = Convert.ToInt32(intItem);
                                    switch (label)
                                    {
                                    case 1:
                                    case 0:
                                    case 3:
                                        intList += intItem + ",";
                                        break;

                                    //移动端登录的特殊处理
                                    case 4:
                                        mobileStr += " ta.AppKey='iPhoneHT5I0O4HDN65' or ";
                                        intList   += "4,";
                                        break;

                                    case 5:
                                        mobileStr += " ta.AppKey='iPadMaO8VUvVH0eBss' or ";
                                        intList   += "4,";
                                        break;

                                    case 6:
                                        mobileStr += " ta.AppKey='AndroidYnHWyROQosO' or ";
                                        intList   += "4,";
                                        break;

                                    default:
                                        break;
                                    }
                                }

                                if (!string.IsNullOrEmpty(intList))
                                {
                                    intList = intList.Substring(0, intList.LastIndexOf(','));

                                    strTemp.Append(" (lt.LogMode in (" + intList + ")) and ");
                                }
                                if (!string.IsNullOrEmpty(mobileStr))
                                {
                                    mobileStr = mobileStr.Substring(0, mobileStr.LastIndexOf('o'));

                                    strTemp.Append(" (" + mobileStr + ") and ");
                                }
                            }
                            //只在某端登录的逻辑
                            //else if (conditionItem.ColName == "LogModeAlone")
                            //{

                            //}
                            else
                            {
                                foreach (var intItem in conditionItem.DataRange.Range)
                                {
                                    intList += intItem + ",";
                                }
                                intList = intList.Substring(0, intList.LastIndexOf(','));

                                strTemp.Append(" (" + conditionItem.ColName + " in (" + intList + ")) and ");
                            }

                            break;

                        case "StrRange":
                            string strList = "";
                            foreach (var intItem in conditionItem.DataRange.Range)
                            {
                                strList += "'" + intItem + "',";
                            }
                            intList = strList.Substring(0, strList.LastIndexOf(','));

                            strTemp.Append(" (" + conditionItem.ColName + " in (" + intList + ")) and ");
                            break;

                        default:
                            break;
                        }
                    }
                    #endregion

                    string sql = "";

                    if (str == "i200.dbo.T_LOG")
                    {
                        sql = strTemp.ToString().Substring(0, strTemp.ToString().LastIndexOf('a')) +
                              " group by accountid";
                    }
                    else if (str == "sys_i200.dbo.SysRpt_ShopDayInfo") //如果是每日店铺汇总表则组合三段Sql
                    {
                        sql = strTemp.ToString().Substring(0, strTemp.ToString().LastIndexOf('a')) +
                              strGroupBy.ToString().Substring(0, strGroupBy.ToString().LastIndexOf(',')) +
                              strHaving.ToString().Substring(0, strHaving.ToString().LastIndexOf('a'));
                    }
                    else
                    {
                        sql = strTemp.ToString().Substring(0, strTemp.ToString().LastIndexOf('a'));
                    }

                    accIdDic[str] = RuleListBLL.GetAccIdByStr(sql);

                    //判断是否存在时间类型
                    if (sql.IndexOf('/') > 0)
                    {
                        RuleListBLL.AddSqlRecord(sql, verifId, 1, tempConditionList[0].ConditionGroup);
                    }
                    else
                    {
                        RuleListBLL.AddSqlRecord(sql, verifId, 0, tempConditionList[0].ConditionGroup);
                    }
                }
            }
            #endregion

            #region 特殊自定义类、由于库不统一导致的独立条件的单独处理模块
            //建立包含的店铺集合
            if (conditionList.Exists(x => x.ColName == "specificAccId"))
            {
                string jsonList = conditionList.Find(x => x.ColName == "specificAccId").DataRange.Range.ToString();

                List <int> listSpec =
                    CommonLib.Helper.JsonDeserializeObject <List <int> >(jsonList);
                accIdDic["specific"] = listSpec;
            }

            //建立排除的店铺集合
            if (conditionList.Exists(x => x.ColName == "specificEx"))
            {
                string jsonList = conditionList.Find(x => x.ColName == "specificEx").DataRange.Range.ToString();

                List <int> listSpec =
                    CommonLib.Helper.JsonDeserializeObject <List <int> >(jsonList);
                accIdDic["specificEx"] = listSpec;
            }

            //根据地区筛选
            if (conditionList.Exists(x => x.ColName == "areaQuery"))
            {
                string jsonList = conditionList.Find(x => x.ColName == "areaQuery").DataRange.Range.ToString();

                List <string> listSpec =
                    CommonLib.Helper.JsonDeserializeObject <List <string> >(jsonList);

                StringBuilder strArea = new StringBuilder();
                strArea.Append("select accid from [Sys_I200].[dbo].[Sys_Account] where 1=1 and ");


                string areaCondition = "";
                foreach (var item in listSpec)
                {
                    areaCondition += " sysAddress like '%" + item + "%' or ";
                }
                areaCondition = areaCondition.Substring(0, areaCondition.LastIndexOf('o'));
                strArea.Append(areaCondition);

                try
                {
                    accIdDic["areaQuery"] = RuleListBLL.GetAccIdByStr(strArea.ToString());
                    RuleListBLL.AddSqlRecord(strArea.ToString(), verifId, 0, 7);
                }
                catch (Exception ex)
                {
                    Logger.Error("获取用户地区筛选数据出错!", ex);
                    accIdDic["areaQuery"] = null;
                }
            }


            //只在移动端、PC端或者Web端登录的用户
            //属于需要添加到
            if (conditionList.Exists(x => x.ColName == "LogModeAlone"))
            {
                FilterCondition conditionModel = conditionList.Find(x => x.ColName == "LogModeAlone");
                string          data           = conditionList.Find(x => x.ColName == "LogModeAlone").DataRange.Range.ToString();
                List <int>      listSpec       =
                    CommonLib.Helper.JsonDeserializeObject <List <int> >(data);

                StringBuilder strSpecSql = new StringBuilder();
                //获取所有登录用户和分组
                strSpecSql.Append(
                    "select Accountid,LogMode into #logMode from i200.dbo.T_LOG group by Accountid,LogMode ;");

                strSpecSql.Append("select Accountid from #logMode ");

                switch (listSpec[0])
                {
                case 4:    //移动端
                    strSpecSql.Append(
                        " where LogMode=4 and Accountid not in (select Accountid from #logMode " +
                        " where left(LogMode,1) in ('0','1','3')) group by Accountid ;");
                    break;

                case 0:    //网页端
                    strSpecSql.Append(
                        " where left(LogMode,1) in ('0','1') and Accountid not in (select Accountid from #logMode " +
                        " where left(LogMode,1) in ('4','3')) group by Accountid ;");
                    break;

                case 3:    //PC端
                    strSpecSql.Append(
                        " where left(LogMode,1) in ('3') and Accountid not in (select Accountid from #logMode " +
                        " where left(LogMode,1) in ('4','0','1')) group by Accountid ;");
                    break;
                }

                strSpecSql.Append("drop table #logMode;");

                //获取用户集
                accIdDic["LogModeAlone"] = RuleListBLL.GetAccIdByStr(strSpecSql.ToString());
                RuleListBLL.AddSqlRecord(strSpecSql.ToString(), verifId, 0, conditionModel.ConditionGroup);
            }

            //获取用户历史活跃状态
            if (conditionList.Exists(x => x.ColName == "activeEver"))
            {
                string     jsonList = conditionList.Find(x => x.ColName == "activeEver").DataRange.Range.ToString();
                List <int> listSpec =
                    CommonLib.Helper.JsonDeserializeObject <List <int> >(jsonList);

                StringBuilder strEverActive = new StringBuilder();

                //拼接选择条件
                string where = "(";
                foreach (var intItem in listSpec)
                {
                    where += intItem + ",";
                }
                where = where.Substring(0, where.LastIndexOf(',')) + ") ";

                strEverActive.Append("select accid from Sys_I200.dbo.SysRpt_ShopActive where active in " + where +
                                     " and stateVal=1 group by accid");


                accIdDic["activeEver"] = RuleListBLL.GetAccIdByStr(strEverActive.ToString());
                RuleListBLL.AddSqlRecord(strEverActive.ToString(), verifId, 0, 7);
            }

            //获取用户行业
            if (conditionList.Exists(x => x.ColName == "industry"))
            {
                string     jsonList = conditionList.Find(x => x.ColName == "industry").DataRange.Range.ToString();
                List <int> listSpec =
                    CommonLib.Helper.JsonDeserializeObject <List <int> >(jsonList);

                StringBuilder strIndustry = new StringBuilder();

                string strList = "";
                foreach (var intItem in listSpec)
                {
                    strList += intItem + ",";
                }
                strList = strList.Substring(0, strList.LastIndexOf(','));

                strIndustry.Append("select accid,Eindustry_1 m1,Eindustry_2 m2,Sindustry_1 s1,Sindustry_2 s2,0 industryId into #list from sys_i200.dbo.SysStat_IndustryFilter;");
                strIndustry.Append("update #list set s1=m1 where m1 is not null;  ");
                strIndustry.Append("update #list set s2=m2 where m2 is not null;   ");
                strIndustry.Append("update #list set #list.industryId=i.IndustryId from sys_i200.dbo.SysStat_IndustryFilterDic i  ");
                strIndustry.Append("where #list.s1=i.Industry_1 and #list.s2=i.[Industry_2];");

                strIndustry.Append("select accid from #list left join sys_i200.dbo.SysStat_IndustryFilterDic i " +
                                   "on #list.industryId=i.IndustryId where i.IndustryId in (" + strList + ");");
                strIndustry.Append("drop table #list;");

                accIdDic["industry"] = RuleListBLL.GetAccIdByStr(strIndustry.ToString());
                //暂时屏蔽记录插入
                //RuleListBLL.AddSqlRecord(strIndustry.ToString(), verifId, 0, 7);
            }
            #endregion

            #region 处理产生的集合并合并

            if (accIdDic.Count <= 0)
            {
                return("");
            }
            else
            {
                List <int> temp = accIdDic.First().Value;
                foreach (var item in accIdDic)
                {
                    if (item.Key != "specificEx" && item.Key != null)
                    {
                        temp = temp.Intersect(item.Value).ToList();
                    }
                }

                if (accIdDic.ContainsKey("specificEx"))
                {
                    temp = temp.Except(accIdDic["specificEx"]).ToList();
                }

                string where = " and accountid in (";

                foreach (var intItem in temp)
                {
                    where += intItem + ",";
                }

                if (where.LastIndexOf(',') <= 0)
                {
                    return("");
                }
                else
                {
                    where = where.Substring(0, where.LastIndexOf(',')) + ") ";

                    return(where);
                }
            }
            #endregion
        }
Example #54
0
        public async void Simulate(string path)
        {
            _InterruptSimulation = false;

            //Get devices
            List <IoTDevice> iotDevices = await _iotDeviceHelper.GetAllInputDevices();

            if (iotDevices == null || iotDevices.Count == 0)
            {
                ConsoleHelper.WriteWarning($"No devices found! Make sure to run '1. Setup list of devices' first.");
                _InterruptSimulation = true;
                return;
            }

            //Get story messages and validation
            List <StoryMessage> storyMessages = GetSimulationStory(path);

            if (storyMessages == null || storyMessages.Count == 0)
            {
                ConsoleHelper.WriteWarning($"No story message found! Choose a valid csv file.");
                _InterruptSimulation = true;
                return;
            }

            List <string> deviceIds = storyMessages.GroupBy(p => p.DeviceId).Select(p => p.Key).ToList();

            if (deviceIds.Intersect(iotDevices.Select(p => p.DeviceId)).Count() != deviceIds.Count())
            {
                ConsoleHelper.WriteWarning($"Some devices in the story aren't properly set in IoT Hub. Please run the sensors csv file.");
                _InterruptSimulation = true;
                return;
            }

            int          elapsedTime = 0;
            IoTDevice    device      = null;
            StoryMessage storyLog    = null;

            for (int i = 0; i < storyMessages.Count; i++)
            {
                StoryMessage storyMessage = storyMessages[i];
                if (_InterruptSimulation)
                {
                    return;
                }

                if (storyMessage.Timestamp - elapsedTime > 0)
                {
                    await Task.Delay(storyMessage.Timestamp - elapsedTime);

                    elapsedTime += storyMessage.Timestamp - elapsedTime;
                }

                if (_InterruptSimulation)
                {
                    return;
                }

                device = iotDevices.Find(p => p.DeviceId == storyMessage.DeviceId);

                object messageObj = new ButtonSensorMessage();
                if (device.DeviceType == "SoundSensor")
                {
                    messageObj = new SoundSensorMessage()
                    {
                        Decibel = GetSoundMetadata()
                    };
                }
                await _iotDeviceHelper.SendMessage(device, storyMessage.EventType, messageObj);

                i++;

                int start = i > (SIMULATION_WINDOW_SIZE - 1) ? i - (SIMULATION_WINDOW_SIZE - 1) : 0;
                ConsoleHelper.ClearConsole();
                ConsoleHelper.WriteInfo("Press Escape when you want to end the simulation.");
                ConsoleHelper.WriteInfo("");
                ConsoleHelper.WriteHighlight($"{i} messages sent from {(deviceIds.Count)} demo device(s).");
                ConsoleHelper.WriteInfo("");
                ConsoleHelper.WriteInfo($"=================================");
                for (int j = start; j < start + SIMULATION_WINDOW_SIZE; j++)
                {
                    storyLog = storyMessages[j];
                    if (j < i)
                    {
                        ConsoleHelper.WriteInfo($"--{storyLog.Timestamp}-{storyLog.DeviceId}");
                    }
                    else if (j > i)
                    {
                        ConsoleHelper.WriteInfo($"");
                    }
                    else
                    {
                        ConsoleHelper.WriteHighlight($"--{storyLog.Timestamp}-{storyLog.DeviceId}");
                    }
                }
                ConsoleHelper.WriteInfo($"=================================");
            }
            ConsoleHelper.WriteInfo("");
            ConsoleHelper.WriteHighlight("Done!");

            await Task.Delay(5000);
        }
Example #55
0
        public IActionResult ShowRooms(KursViewModel kursViewModel)
        {
            if (kursViewModel.Days != null)
            {
                kursViewModel.Roomlist = new List <DayAndRooms>();
                List <DateTime> datelist = new List <DateTime>();
                List <Room>     allRooms = _databaseHandler.GetAllRooms();

                foreach (var day in kursViewModel.Days)
                {
                    DateTime    dayformatted = DateTime.ParseExact(day, "dd-MM-yyyy HH:mm", CultureInfo.InvariantCulture);
                    DayAndRooms dayAndRooms  = new DayAndRooms()
                    {
                        Date  = dayformatted,
                        Rooms = allRooms,
                        block =
                            Array.FindIndex(Data.BlockStartArray,
                                            s => s.Equals(dayformatted.Hour + ":" + dayformatted.Minute)) + 1
                    };
                    kursViewModel.Roomlist.Add(dayAndRooms);
                }

                DateTime dateStart = kursViewModel.start;
                DateTime dateEnd   = kursViewModel.end;
                while (dateStart <= dateEnd)                               //für den ganzen zeitraum
                {
                    for (var x = 0; x < kursViewModel.Roomlist.Count; x++) //für jede tag/block Komponente
                    {
                        DayAndRooms day  = kursViewModel.Roomlist[x];
                        DateTime    date = new DateTime();
                        if (dateStart.DayOfWeek <= day.Date.DayOfWeek)
                        {
                            if (!(dateStart.AddDays(day.Date.DayOfWeek - dateStart.DayOfWeek) > dateEnd))
                            {
                                date = dateStart.AddDays(day.Date.DayOfWeek - dateStart.DayOfWeek);
                            }
                        }
                        else
                        {
                            if (!(dateStart.AddDays(7 + (dateStart.DayOfWeek - day.Date.DayOfWeek)) > dateEnd))
                            {
                                date = dateStart.AddDays(7 + (dateStart.DayOfWeek - day.Date.DayOfWeek));
                            }
                        }
                        List <Room> resultrooms    = new List <Room>();
                        List <Room> availableRooms = _databaseHandler.GetFreeRoomsOnDateAndBlock(date, day.block);
                        resultrooms = availableRooms.Intersect(day.Rooms).ToList();

                        var roomlistobject = kursViewModel.Roomlist[x];
                        roomlistobject.Rooms      = resultrooms;
                        kursViewModel.Roomlist[x] = roomlistobject;



                        //kursViewModel.Roomlist[x].Rooms.Clear();
                        //kursViewModel.Roomlist[x].Rooms.AddRange(resultrooms);
                        datelist.Add(kursViewModel.Roomlist[x].Date);
                    }

                    dateStart = dateStart.AddDays(7);
                }


                HttpContext.Session.SetObjectAsJson("datelist", datelist);

                return(View(kursViewModel));
            }
            else
            {
                ViewData["ErrorTagauswahl"] = "Es wurden keine Tage ausgewählt!";
                return(View("CourseDays", kursViewModel));
            }
        }
        public List <string> CheckScriptedInstallersIntegrity(IModProfile p_impFrom, IModProfile p_impTo)
        {
            List <string> lstConflicts = new List <string>();
            string        strToPath    = GetCurrentProfileScriptedLogPath(p_impTo);

            if (!Directory.Exists(strToPath))
            {
                return(null);
            }

            if (p_impFrom == null)
            {
                List <string> lstTo = new List <string>();
                lstTo = Directory.GetFiles(strToPath, "*.xml", SearchOption.TopDirectoryOnly).ToList();
                if ((lstTo != null) && (lstTo.Count > 0))
                {
                    lstTo = lstTo.Select(x => Path.GetFileName(x)).ToList();

                    foreach (string File in lstTo)
                    {
                        IVirtualModInfo modMod = VirtualModActivator.VirtualMods.Find(x => Path.GetFileNameWithoutExtension(x.ModFileName).Equals(Path.GetFileNameWithoutExtension(File), StringComparison.CurrentCultureIgnoreCase));
                        if (modMod != null)
                        {
                            lstConflicts.Add(Path.GetFileName(modMod.ModFileName));
                        }
                    }
                }
            }
            else
            {
                string strFromPath = GetCurrentProfileScriptedLogPath(p_impFrom);
                if (!Directory.Exists(strFromPath))
                {
                    return(null);
                }

                List <string> lstFrom      = new List <string>();
                List <string> lstTo        = new List <string>();
                List <string> lstCommon    = new List <string>();
                Int32         intConflicts = 0;

                try
                {
                    lstFrom = Directory.GetFiles(strFromPath, "*.xml", SearchOption.TopDirectoryOnly).ToList();
                    lstTo   = Directory.GetFiles(strToPath, "*.xml", SearchOption.TopDirectoryOnly).ToList();

                    if ((lstFrom != null) && (lstFrom.Count > 0))
                    {
                        lstFrom = lstFrom.Select(x => Path.GetFileName(x)).ToList();
                    }
                    else
                    {
                        return(lstConflicts);
                    }

                    if ((lstTo != null) && (lstTo.Count > 0))
                    {
                        lstTo = lstTo.Select(x => Path.GetFileName(x)).ToList();
                    }
                    else
                    {
                        return(lstConflicts);
                    }

                    lstCommon = lstFrom.Intersect(lstTo, StringComparer.CurrentCultureIgnoreCase).ToList();

                    foreach (string File in lstCommon)
                    {
                        intConflicts = 0;
                        List <KeyValuePair <string, string> > dicFrom = LoadXMLModFilesToInstall(Path.Combine(strFromPath, File));
                        List <KeyValuePair <string, string> > dicTo   = LoadXMLModFilesToInstall(Path.Combine(strToPath, File));

                        intConflicts += dicFrom.Where(x => !dicTo.Contains(x, StringComparer.CurrentCultureIgnoreCase)).Count();
                        if (intConflicts <= 0)
                        {
                            intConflicts += dicTo.Where(x => !dicFrom.Contains(x, StringComparer.CurrentCultureIgnoreCase)).Count();
                        }

                        if (intConflicts > 0)
                        {
                            IVirtualModInfo modMod = VirtualModActivator.VirtualMods.Find(x => Path.GetFileNameWithoutExtension(x.ModFileName).Equals(Path.GetFileNameWithoutExtension(File), StringComparison.CurrentCultureIgnoreCase));
                            if (modMod != null)
                            {
                                lstConflicts.Add(Path.GetFileName(modMod.ModFileName));
                            }
                        }
                    }
                }
                catch
                { }
            }

            return(lstConflicts);
        }
        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;
        }
    private IEnumerator Play()
    {
        var myUnits = _cellGrid.Units.FindAll(u => u.PlayerNumber.Equals(PlayerNumber)).ToList();

        foreach (var unit in myUnits.OrderByDescending(u => u.Cell.GetNeighbours(_cellGrid.Cells).FindAll(u.IsCellTraversable).Count))
        {
            var enemyUnits   = _cellGrid.Units.Except(myUnits).ToList();
            var unitsInRange = new List <Unit>();
            foreach (var enemyUnit in enemyUnits)
            {
                if (unit.IsUnitAttackable(enemyUnit, unit.Cell))
                {
                    unitsInRange.Add(enemyUnit);
                }
            }//Looking for enemies that are in attack range.
            if (unitsInRange.Count != 0)
            {
                int index = _rnd.Next(0, unitsInRange.Count);
                unit.GetComponent <Unit> ().UnitAttack();
                unit.DealDamage(unitsInRange[index]);
                yield return(new WaitForSeconds(0.5f));

                continue;
            }//If there is an enemy in range, attack it.

            List <Cell> potentialDestinations = new List <Cell>();

            foreach (var enemyUnit in enemyUnits)
            {
                potentialDestinations.AddRange(_cellGrid.Cells.FindAll(c => unit.IsCellMovableTo(c) && unit.IsUnitAttackable(enemyUnit, c)));
            }//Making a list of cells that the unit can attack from.

            var notInRange = potentialDestinations.FindAll(c => c.GetDistance(unit.Cell) > unit.MovementPoints);
            potentialDestinations = potentialDestinations.Except(notInRange).ToList();

            if (potentialDestinations.Count == 0 && notInRange.Count != 0)
            {
                potentialDestinations.Add(notInRange.ElementAt(_rnd.Next(0, notInRange.Count - 1)));
            }

            potentialDestinations = potentialDestinations.OrderBy(h => _rnd.Next()).ToList();
            List <Cell> shortestPath = null;
            foreach (var potentialDestination in potentialDestinations)
            {
                var path = unit.FindPath(_cellGrid.Cells, potentialDestination);
                if ((shortestPath == null && path.Sum(h => h.MovementCost) > 0) || shortestPath != null && (path.Sum(h => h.MovementCost) < shortestPath.Sum(h => h.MovementCost) && path.Sum(h => h.MovementCost) > 0))
                {
                    shortestPath = path;
                }

                var pathCost = path.Sum(h => h.MovementCost);
                if (pathCost > 0 && pathCost <= unit.MovementPoints)
                {
                    unit.moveOn = true;
                    unit.Move(potentialDestination, path);
                    while (unit.isMoving)
                    {
                        yield return(0);
                    }
                    shortestPath = null;
                    break;
                }
                yield return(0);
            }//If there is a path to any cell that the unit can attack from, move there.

            if (shortestPath != null)
            {
                foreach (var potentialDestination in shortestPath.Intersect(unit.GetAvailableDestinations(_cellGrid.Cells)).OrderByDescending(h => h.GetDistance(unit.Cell)))
                {
                    var path     = unit.FindPath(_cellGrid.Cells, potentialDestination);
                    var pathCost = path.Sum(h => h.MovementCost);
                    if (pathCost > 0 && pathCost <= unit.MovementPoints)
                    {
                        unit.moveOn = true;
                        unit.Move(potentialDestination, path);
                        while (unit.isMoving)
                        {
                            yield return(0);
                        }
                        break;
                    }
                    yield return(0);
                }
            }//If the path cost is greater than unit movement points, move as far as possible.

            foreach (var enemyUnit in enemyUnits)
            {
                var enemyCell = enemyUnit.Cell;
                if (unit.IsUnitAttackable(enemyUnit, unit.Cell))
                {
                    unit.GetComponent <Unit> ().UnitAttack();
                    unit.DealDamage(enemyUnit);
                    yield return(new WaitForSeconds(0.5f));

                    break;
                }
            }//Look for enemies in range and attack.
        }
        _cellGrid.EndTurn();
    }
Example #59
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 #60
0
        private string StageAnalysisInfo()
        {
            try
            {
                lock (stageGroups)
                {
                    double cores = Environment.ProcessorCount;
                    Dictionary <string, double> cpuPerRequest       = new Dictionary <string, double>(); // CPU time per request for each stage
                    Dictionary <string, double> wallClockPerRequest = new Dictionary <string, double>(); // Wallclock time per request for each stage
                    Dictionary <string, double> numberOfRequests    = new Dictionary <string, double>(); // Number of requests for each stage
                    foreach (var keyVal in stageGroups)
                    {
                        string name = keyVal.Key;
                        if (GetNumberOfRequests(name) > 0)
                        {
                            cpuPerRequest.Add(name, GetCpuPerStagePerRequest(name));
                            wallClockPerRequest.Add(name, GetWallClockPerStagePerRequest(name));
                            numberOfRequests.Add(name, GetNumberOfRequests(name));
                        }
                    }
                    cpuPerRequest.Add("Untracked.ThreadPoolThread", GetCpuPerStagePerRequest("Untracked.ThreadPoolThread"));
                    numberOfRequests.Add("Untracked.ThreadPoolThread", GetNumberOfRequests("Untracked.ThreadPoolThread"));

                    double elapsedWallClock = GetMaxWallClock();
                    double elapsedCPUClock  = GetTotalCPU();

                    // Idle time estimation
                    double untrackedProportionTime = 1 - elapsedCPUClock / (cores * elapsedWallClock);

                    // Ratio of wall clock per cpu time calculation
                    double sum = 0;
                    double num = 0;
                    foreach (var stage in wallClockPerRequest.Keys)
                    {
                        if (!waitingStages.Contains(stage))
                        {
                            double ratio = wallClockPerRequest[stage] / cpuPerRequest[stage] - 1;
                            sum += ratio * numberOfRequests[stage];
                            num += numberOfRequests[stage];
                        }
                    }
                    double avgRatio = sum / num;

                    // Wait time estimation - implementation of strategy 2 from the "local-throughput.pdf" "Coping with Practical Measurements".
                    var waitTimes = new Dictionary <string, double>(); // Wait time per request for each stage
                    foreach (var stage in wallClockPerRequest.Keys)
                    {
                        waitTimes.Add(stage,
                                      waitingStages.Contains(stage)
                                ? Math.Max(wallClockPerRequest[stage] - avgRatio * cpuPerRequest[stage] - cpuPerRequest[stage], 0)
                                : 0);
                    }

                    // CPU sum for denominator of final equation
                    double cpuSum = 0;
                    foreach (var stage in cpuPerRequest.Keys)
                    {
                        cpuSum += cpuPerRequest[stage] * numberOfRequests[stage];
                    }

                    // beta and lambda values
                    var beta   = new Dictionary <string, double>();
                    var s      = new Dictionary <string, double>();
                    var lambda = new Dictionary <string, double>();
                    foreach (var stage in wallClockPerRequest.Keys)
                    {
                        beta.Add(stage, cpuPerRequest[stage] / (cpuPerRequest[stage] + waitTimes[stage]));
                        s.Add(stage, 1000.0 / (cpuPerRequest[stage] + waitTimes[stage]));
                        lambda.Add(stage, 1000.0 * numberOfRequests[stage] / elapsedWallClock);
                    }

                    // Final equation thread allocation - implementation of theorem 2 from the "local-throughput.pdf" "Incorporating Ready Time".
                    var throughputThreadAllocation = new Dictionary <string, double>(); // Thread allocation suggestion for each stage
                    foreach (var stage in wallClockPerRequest.Keys)
                    {
                        // cores is p
                        // numberOfRequests is q
                        // cpuPerRequest is x
                        // stableReadyTimeProportion is alpha
                        // waitTimes is w
                        throughputThreadAllocation.Add(stage, cores * numberOfRequests[stage] * (cpuPerRequest[stage] * (1 + stableReadyTimeProportion) + waitTimes[stage]) / cpuSum);
                    }



                    double sum1 = 0;
                    foreach (var stage in s.Keys)
                    {
                        sum1 += lambda[stage] * beta[stage] / s[stage];
                    }

                    double sum2 = 0;
                    foreach (var stage in s.Keys)
                    {
                        sum2 += Math.Sqrt(lambda[stage] * beta[stage] / s[stage]);
                    }

                    var latencyThreadAllocation = new Dictionary <string, double>(); // Latency thread allocation suggestion for each stage
                    foreach (var stage in wallClockPerRequest.Keys)
                    {
                        latencyThreadAllocation.Add(stage, lambda[stage] / s[stage] + Math.Sqrt(lambda[stage]) * (cores - sum1) / (Math.Sqrt(s[stage] * beta[stage]) * sum2));
                    }

                    var latencyPenalizedThreadAllocationConst = new Dictionary <string, double>();
                    var latencyPenalizedThreadAllocationCoef  = new Dictionary <string, double>();

                    foreach (var stage in wallClockPerRequest.Keys)
                    {
                        latencyPenalizedThreadAllocationConst.Add(stage, lambda[stage] / s[stage]);
                        latencyPenalizedThreadAllocationCoef.Add(stage, Math.Sqrt(lambda[stage] / (lambda[firstStage] * s[stage])));
                    }

                    double sum3 = 0;
                    foreach (var stage in s.Keys)
                    {
                        sum3 += beta[stage] * Math.Sqrt(lambda[stage] / s[stage]);
                    }

                    double zeta = Math.Pow(sum3 / (cores - sum1), 2) / lambda[firstStage];

                    var sb = new StringBuilder();
                    sb.AppendLine();
                    sb.AppendLine();
                    sb.AppendLine("zeta:   " + zeta);
                    sb.AppendLine();
                    foreach (var stage in stages.Intersect(wallClockPerRequest.Keys))
                    {
                        sb.AppendLine("Stage: " + stage);
                        sb.AppendLine("  Measured average CPU per request:        " + cpuPerRequest[stage].ToString("F3") + " ms");
                        sb.AppendLine("  Measured average Wall-clock per request: " + wallClockPerRequest[stage].ToString("F3") + " ms");
                        sb.AppendLine("  Measured number of requests:             " + numberOfRequests[stage].ToString("F0") + " requests");
                        sb.AppendLine("  lambda:                                  " + lambda[stage].ToString("F3") + " arrival rate requests/sec");
                        sb.AppendLine("  s:                                       " + s[stage].ToString("F3") + " per thread service rate requests/sec");
                        sb.AppendLine("  beta:                                    " + beta[stage].ToString("F3") + " per thread CPU usage");
                        sb.AppendLine("  Estimated wait time:                     " + waitTimes[stage].ToString("F3") + " ms");
                        sb.AppendLine("  Throughput thread allocation:            " + Math.Ceiling(throughputThreadAllocation[stage]) + " threads  (rounded up from " + throughputThreadAllocation[stage].ToString("F3") + ")");
                        sb.AppendLine("  Latency thread allocation:               " + Math.Ceiling(latencyThreadAllocation[stage]) + " threads  (rounded up from " + latencyThreadAllocation[stage].ToString("F3") + ")");
                        sb.AppendLine("  Regularlized latency thread allocation:  " + latencyPenalizedThreadAllocationConst[stage].ToString("F3") + " + " + latencyPenalizedThreadAllocationCoef[stage].ToString("F3") + " / sqrt(eta) threads  (rounded this value up)");
                    }

                    var cpuBreakdown = new Dictionary <string, double>();
                    foreach (var stage in cpuPerRequest.Keys)
                    {
                        double val = (numberOfRequests[stage] * cpuPerRequest[stage]) / (cores * elapsedWallClock);
                        cpuBreakdown.Add(stage == "ThreadPoolThread" ? "ThreadPoolThread.AsynchronousReceive" : stage, val);
                    }
                    cpuBreakdown.Add("Untracked", untrackedProportionTime);

                    sb.AppendLine();
                    sb.AppendLine("CPU usage by thread type:");
                    foreach (var v in cpuBreakdown.OrderBy(key => (-1 * key.Value)))
                    {
                        sb.AppendLine("  " + v.Value.ToString("F3") + ", " + v.Key);
                    }

                    sb.AppendLine();
                    sb.Append("EndStageAnalysis");
                    return(sb.ToString());
                }
            }
            catch (Exception e)
            {
                return(e + Environment.NewLine + e.StackTrace);
            }
        }