Beispiel #1
0
        /// <summary>The compare pairs.</summary>
        /// <param name="player1Cards">The player 1 cards.</param>
        /// <param name="player2Cards">The player 2 cards.</param>
        /// <returns>The <see cref="int"/>.</returns>
        protected int ComparePairs(List<Card> player1Cards, List<Card> player2Cards)
        {
            int result = 0;

            while (player1Cards.Any(c => player1Cards.Count(x => x.Value == c.Value) == 2) && player2Cards.Any(c => player2Cards.Count(x => x.Value == c.Value) == 2) && result == 0)
            {
                int thisPairValue = player1Cards.Last(c => player1Cards.Count(x => x.Value == c.Value) == 2).Value;
                int otherPairValue = player2Cards.Last(c => player2Cards.Count(x => x.Value == c.Value) == 2).Value;

                if (thisPairValue == otherPairValue)
                {
                    player1Cards = player1Cards.Where(x => x.Value != thisPairValue).ToList();
                    player2Cards = player2Cards.Where(x => x.Value != otherPairValue).ToList();
                }
                else if (thisPairValue < otherPairValue)
                {
                    result = -1;
                }
                else
                {
                    result = 1;
                }
            }

            if (result == 0)
            {
                result = this.CompareHighestCards(player1Cards, player2Cards);
            }

            return result;
        }
 public MovingBlock(List<Block> list)
 {
     int x = 0;
     for (int i = 0; i < list.Count(); ++i)
     {
         Block block = list.ElementAt(i);
         if (block.type == "moving"&&!block.inlist)
         {
             x = block.cbox.X;
             this.cbox.X = block.cbox.X;
             this.cbox.Y = block.cbox.Y;
             blocks.Add(block);
             block.inlist = true;
             cbox = block.cbox;
             break;
         }
     }
     for (int j = 0; j < 10; ++j)
     {
         cbox.X = cbox.X + 48;
         for (int i = 0; i < list.Count(); ++i)
         {
             Block block = list.ElementAt(i);
             if (cbox.Intersects(block.cbox) &&block.type == "moving"&&!block.inlist)
             {
                 blocks.Add(block);
                 block.inlist = true;
             }
         }
     }
     this.cbox.Width = blocks.Count * 48;
     this.cbox.X = x;
     checkcbox = cbox;
 }
Beispiel #3
0
        private void IdName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string name = _tbIdName.Text;
                uint id = name.ToUInt32();
                uint ic = _tbIcon.Text.ToUInt32();
                uint at = _tbAttribute.Text.ToUInt32();

                _spellList = (from spell in DBC.Spell.Values

                            where ((id == 0 || spell.ID == id)

                                && (ic == 0 || spell.SpellIconID == ic)

                                && (at == 0 || (spell.Attributes    & at) != 0
                                            || (spell.AttributesEx  & at) != 0
                                            || (spell.AttributesEx2 & at) != 0
                                            || (spell.AttributesEx3 & at) != 0
                                            || (spell.AttributesEx4 & at) != 0
                                            || (spell.AttributesEx5 & at) != 0
                                            || (spell.AttributesEx6 & at) != 0
                                            || (spell.AttributesExG & at) != 0))

                                && (id != 0 || ic != 0 && at != 0) || spell.SpellName.ContainsText(name)

                            select spell).ToList();

                _lvSpellList.VirtualListSize = _spellList.Count();
                groupBox1.Text = "Spell Search count: " + _spellList.Count();

                if (_lvSpellList.SelectedIndices.Count > 0)
                    _lvSpellList.Items[_lvSpellList.SelectedIndices[0]].Selected = false;
            }
        }
Beispiel #4
0
        public static string GetArrayString(List<string> input,bool wrapInQuotes  )
        {
            if (input == null)
            {
                return string.Empty;
            }
            var output = new System.Text.StringBuilder();

            output.Append("[");

            for(int i=0; i<=input.Count()-1;i++)
            {
                if (i == input.Count() - 1)
                {
                    output.Append( checkWrapInQuotes(input[i],wrapInQuotes) );
                }
                else
                {
                    output.Append(checkWrapInQuotes(input[i],wrapInQuotes) + ",");
                }

            }

            output.Append("]");
            return output.ToString();
        }
Beispiel #5
0
		private static int[,] LcsInternal(List<JToken> left, List<JToken> right)
		{
			var arr = new int[left.Count() + 1, right.Count() + 1];

			for (int i = 0; i <= right.Count(); i++)
			{
				arr[0, i] = 0;
			}
			for (int i = 0; i <= left.Count(); i++)
			{
				arr[i, 0] = 0;
			}

			for (int i = 1; i <= left.Count(); i++)
			{
				for (int j = 1; j <= right.Count(); j++)
				{
					if (left[i - 1].Equals(right[j - 1]))
					{
						arr[i, j] = arr[i - 1, j - 1] + 1;
					}
					else
					{
						arr[i, j] = Math.Max(arr[i - 1, j], arr[i, j - 1]);
					}
				}
			}

			return arr;
		}
Beispiel #6
0
        public string GetRefreshRate()
        {
            if (CheatMode)
            {
                return("CM");
            }

            if (FixingBotch || (!RemoveingConditioning && ChangeType == TraitAlterType.UNSET))
            {
                var days = PS_ConditioningHelper.GetRefreshPerDay(StartingConditioning?.Count() ?? 0);
                return(DayToSafeTime(days));
            }
            else
            {
                var tempConCount = StartingConditioning?.Count() ?? 0;
                if (RemoveingConditioning)
                {
                    tempConCount--;
                }
                else if (ChangeType != TraitAlterType.UNSET)
                {
                    tempConCount++;
                }

                var days = PS_ConditioningHelper.GetRefreshPerDay(tempConCount);
                return(DayToSafeTime(days));
            }
        }
Beispiel #7
0
        public void Execute(List<Registry> registries, List<DefinitionSource> executionResult)
        {
            var summary = new
              {
            TotalTests = executionResult.Count(),
            TotalPassed = executionResult.Count(x => x.Enabled && x.RanSuccesfully),
            TotalFailed = executionResult.Count(x => x.Enabled && !x.RanSuccesfully),
            TotalPending = executionResult.Count(x => !x.Enabled),
            TotalSeconds = executionResult.Where(x => x.Enabled).Sum(x => (x.EndTime - x.StartTime).TotalSeconds)
              };

              if (summary.TotalPassed == summary.TotalTests)
              {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write("\n All tests passed! You rock!");
            Console.ForegroundColor = ConsoleColor.Gray;
              }

              Console.WriteLine("");
              executionResult.Where(x=>x.Enabled && !x.RanSuccesfully).Select((exception, index)=>new {exception=exception, index = index+1}).ToList().ForEach(x =>
              {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(" {0}) {1}, {2}",x.index, x.exception.Description, ConsoleReporter.CleanUpForConsole(x.exception.ExecutionResult.ToLower()));
              });

              Console.ForegroundColor = ConsoleColor.Gray;
              Console.WriteLine("\n {0} Total, {1} Passed, {2} Failed, {3} Pending ({4} secs)", summary.TotalTests, summary.TotalPassed,
            summary.TotalFailed, summary.TotalPending, summary.TotalSeconds);
        }
        public void TestGetRandomBetweenThree(double expectedSecondProbability, double expectedThirdProbability)
        {
            Random random = new Random();
            const int first = 1;
            const int second = 2;
            const int third = 3;
            const int count = 100;
            List<int> seq = new List<int>();
            for (int i = 0; i < count; i++)
            {
                seq.Add(random.GetRandomBetweenThree(first, second, third, expectedSecondProbability, expectedThirdProbability));
            }

            double secondProbability = (double)seq.Count(a => a == second) / count;
            double thirdProbability = (double)seq.Count(a => a == third) / count;
            bool eqaulWithInaccuracy = !expectedSecondProbability.Equals(0) && !expectedSecondProbability.Equals(1);
            if (eqaulWithInaccuracy)
            {
                const double inaccuracy = 0.15;
                Assert.Between(secondProbability, expectedSecondProbability - inaccuracy, expectedSecondProbability + inaccuracy);
                Assert.Between(thirdProbability, expectedThirdProbability - inaccuracy, expectedThirdProbability + inaccuracy);
            }
            else
            {
                Assert.AreEqual(expectedSecondProbability, secondProbability);
                Assert.AreEqual(expectedThirdProbability, thirdProbability);
            }
        }
 public static int GetHomeLosses(this TeamLeague teamLeague, List<Fixture> teamFixtures, bool includeForfeitedFixtures = true)
 {
     if(includeForfeitedFixtures)
         return teamFixtures.Count(f => (f.IsHomeTeam(teamLeague) && (!f.IsHomeWin() || f.IsHomeForfeit())));
     else
         return teamFixtures.Count(f => (f.IsHomeTeam(teamLeague) && !f.IsHomeWin() && !f.IsHomeForfeit()));
 }
Beispiel #10
0
        public static String CreateLinkString(Dictionary<String, String> parametersDic)
        {
            var keys = new List<string>(parametersDic.Keys);

              var paraSort = from objDic in parametersDic orderby objDic.Key ascending select objDic;
              var prestr = "";
              var i = 0;
              foreach (var kvp in paraSort)
              {
            if (i == keys.Count() - 1)
            {
              prestr = prestr + kvp.Key + "=" + kvp.Value;
            }
            else
            {
              prestr = prestr + kvp.Key + "=" + kvp.Value + "&";
            }
            i++;
            if (i == keys.Count())
            {
              break;
            }
              }

              return prestr;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="numberOfItemsToCreate">The number of test posts to create</param>
        /// <param name="commentLimit">The upper limit of the number of random comments to create per post</param>
        public static void Run(int numberOfItemsToCreate, int commentLimit)
        {
            Console.WriteLine(String.Format("InitializeDatabase"));

            List<Post> posts = new List<Post>();
            var repo = new MongoData();

            repo.Clean();

            for (int i = 0; i < numberOfItemsToCreate; i++)
            {
                var post = CreateTestPost("Discussion " + i, "email" + i + "@here.com", commentLimit);
                posts.Add(post);
            }

            Console.WriteLine(String.Format("\tTotal posts[{0}] and comments[{1}]",posts.Count(),posts.Sum(post => post.Comments.Count())));
            DateTime start = DateTime.Now;
            repo.SaveBatch(posts);
            //repo.Save(posts);
            DateTime end = DateTime.Now;

            Console.WriteLine(String.Format("\tTime to insert {0} items:{1} seconds. {2} per insert"
                                            , (posts.Count() + posts.Sum(post => post.Comments.Count()))
                                            , (end - start).TotalSeconds
                                            ,
                                            (end - start).TotalSeconds/
                                            (posts.Count() + posts.Sum(post => post.Comments.Count()))));

            Console.WriteLine(String.Format("\tCreated MongoDB {0} with {1} rows", MongoData.MongoDbName, numberOfItemsToCreate));

            repo.SaveManuscript(CreateTestWord());
            repo.SaveManuscript(CreateTestExcel());
        }
        public Double calculateOptimizedPercentage(IList<HistoricalModel> historicalData)
        {
            IList<Double> dailyChanges = new List<Double>();
            Double optimizedPercentage = 0.0;

            foreach(HistoricalModel h in historicalData)
            {
                Double dailyPercentageChange = ((h.Open-h.Close)/h.Open);
                dailyChanges.Add(dailyPercentageChange);
            }

            if (dailyChanges.Count() > 0)
            {
                Double sumPercentChanges = 0;
                foreach (Double percentChange in dailyChanges)
                {
                    sumPercentChanges = sumPercentChanges + percentChange;
                }

                optimizedPercentage = (sumPercentChanges / dailyChanges.Count()) * 100;

            }

            return optimizedPercentage;
        }
        private List<GroupCardModel> FindRecommendedGroups()
        {
           
            List<GroupCardModel> grpItems = new List<GroupCardModel>();

            if (CurrentMember != null)
            {
                
                String [] issues = new List<string>(CurrentMember.Children.Select(x => x.Issues.Select(k => k.Key.ToString("B").ToUpper())).SelectMany(x=>x)).ToArray();
                String[] grades = new List<string>(CurrentMember.Children.Select(x => x.Grades.Select(g => g.Key.ToString("B").ToUpper())).SelectMany(x => x)).ToArray() ;
                String[] topics = CurrentMember.Interests.Select(x => x.Key.ToString("B").ToUpper()).ToArray();
                String[] states = new string[] { CurrentMember.zipCodeToState() };
                String[] partners = new string[0]; //Partners not applicable to Member profile

                if(issues.Count()>0 && grades.Count()>0 && topics.Count() >0)
                {
                    litViewProfileLink1.Visible = false;
                }
                else if((issues.Count()>0 || grades.Count()>0) || topics.Count() >0)
                {
                    
                    //Set message to 
                    //"For better recommendations, complete your full profile (link to profile process)"
                    litViewProfileLink1.Visible = true;
                }

                return Groups.FindGroups(issues,topics,grades,states,partners).OrderByDescending(x=> x.NumOfMembers).ToList();
                
            }
            return grpItems;
           
        }
Beispiel #14
0
        public Card discardCard(PlayerState p, List<Card> hand)
        {
            for (int i = 0; i < hand.Count(); i++)
            {
                if (hand[i].getType() == 3)
                    return hand[i];
            }

            for (int i = 0; i < hand.Count(); i++)
            {
                if (hand[i].getType() == 4)
                    return hand[i];
            }

            for (int i = 0; i < hand.Count(); i++)
            {
                if ( hand[i].getType() == 1
                ||   hand[i].getType() == 2)
                    return hand[i];
            }

            Random r = new Random();
            int index = r.Next(0, hand.Count);
            return hand[index];
        }
        public static void ProcessDirectory(string targetDirectory, Dictionary<string, List<string>> myIndexDictionary, string textFilePath)
        {
            List<string> testFilePaths = new List<string>();
            string[] folders = targetDirectory.Split('\\');
            string currentFolder = folders[folders.Count() - 1];

            // Process the list of files found in the directory.
            string[] fileEntries = Directory.GetFiles(targetDirectory);
            foreach (string fileName in fileEntries)
            {
                if (Path.GetExtension(fileName) == ".jpg")
                {
                    testFilePaths.Add(fileName);
                    ProcessFile(fileName);
                }
            }

            //If the current jpeg list, for the given folder is not empty, add it to your dictionary
            if (testFilePaths.Count() > 0)
            {
                //Current Folder --> List of JPEG images of shred scans within that folder
                myIndexDictionary.Add(targetDirectory, testFilePaths);
                //Create an entry to the text file with our test collateral datta
                string textLine = currentFolder.PadRight(25) + testFilePaths.Count().ToString().PadLeft(5);
                //Add a line to the text file...The extra true paramters states that we want to append text to the end
                StreamWriter collateralFile = new StreamWriter(textFilePath, true);
                collateralFile.WriteLine(textLine);
                collateralFile.Close();
            }

            // Recurse into subdirectories of this directory.
            string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
            foreach (string subdirectory in subdirectoryEntries)
                ProcessDirectory(subdirectory, myIndexDictionary, textFilePath);
        }
Beispiel #16
0
        protected static bool PrintSummary(List<DiagnosticMessage> diagnostics, Stopwatch sw, bool success = true)
        {
            PrintDiagnostics(diagnostics);

            Reporter.Output.WriteLine();

            var errorCount = diagnostics.Count(d => d.Severity == DiagnosticMessageSeverity.Error);
            var warningCount = diagnostics.Count(d => d.Severity == DiagnosticMessageSeverity.Warning);

            if (errorCount > 0 || !success)
            {
                Reporter.Output.WriteLine("Compilation failed.".Red());
                success = false;
            }
            else
            {
                Reporter.Output.WriteLine("Compilation succeeded.".Green());
            }

            Reporter.Output.WriteLine($"    {warningCount} Warning(s)");
            Reporter.Output.WriteLine($"    {errorCount} Error(s)");

            Reporter.Output.WriteLine();

            Reporter.Output.WriteLine($"Time elapsed {sw.Elapsed}");

            return success;
        }
Beispiel #17
0
        public void Update(int right, GraphicsDeviceManager graphics, List<Platform> Plats)
        {
            if (right == 1)
                BackRect.X -= 3;
            if (right == 2)
                BackRect.X += 3;
            Vector2 velocity = new Vector2(0f, 0f);

            foreach (Platform plat in Plats)
            {
                if (BackRect.topOf(plat.PlatRec))
                {
                    velocity.Y = 0;
                }
            }

            int k = 0;
            for (int i1 = 0; i1 < Plats.Count(); i1++)
            {
                if (!BackRect.topOf(Plats[i1].PlatRec))
                    k++;
            }
            if ((k == Plats.Count()) && (BackRect.Bottom < graphics.PreferredBackBufferHeight))
            {
                velocity.Y += 5f;
                k = 0;
            }
            else
                velocity.Y = 0;
            position = new Vector2(BackRect.X, BackRect.Y) + velocity;

            BackRect = new Rectangle((int)position.X, (int)position.Y, BackgrText.Width, BackgrText.Height);
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            numbers = new List<List<int>>();
            numbers.Add(new List<int>() { 75 });
            numbers.Add(new List<int>() { 95, 64});
            numbers.Add(new List<int>() { 17, 47, 82 });
            numbers.Add(new List<int>() { 18, 35, 87, 10 });
            numbers.Add(new List<int>() { 20, 4, 82, 47, 65 });
            numbers.Add(new List<int>() { 19, 1, 23, 75, 3, 34 });
            numbers.Add(new List<int>() { 88, 2, 77, 73, 7, 63, 67 });
            numbers.Add(new List<int>() { 99, 65, 4, 28, 6, 16, 70, 92 });
            numbers.Add(new List<int>() { 41, 41, 26, 56, 83, 40, 80, 70, 33 });
            numbers.Add(new List<int>() { 41, 48, 72, 33, 47, 32, 37, 16, 94, 29 });
            numbers.Add(new List<int>() { 53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14 });
            numbers.Add(new List<int>() { 70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57 });
            numbers.Add(new List<int>() { 91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48 });
            numbers.Add(new List<int>() { 63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31 });
            numbers.Add(new List<int>() { 4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23 });

            numbers.Reverse();

            for(int i = 1; i < numbers.Count(); i++)
            {
                for(int j = 0; j < numbers[i].Count(); j++)
                {
                    numbers[i][j] = numbers[i][j] + Math.Max(numbers[i - 1][j], numbers[i - 1][j +1]);
                }
            }
            Console.WriteLine(numbers[numbers.Count() - 1][0]);
            Console.ReadLine();
        }
        private bool FindDefAndContentFileName(string dirPath, string xmlFileName, out XMLDefContentFileName xMLDefContent)
        {
            xMLDefContent = default;
            var xmlFile = XDocument.Load(dirPath + "\\" + xmlFileName);
            IEnumerable <XMLDefContentFileName> elems = new List <XMLDefContentFileName>();

            elems = from el in xmlFile.Descendants("ValidityFixed")?.Elements("NamesList")
                    select new XMLDefContentFileName
            {
                roots           = el.Attribute("Roots")?.Value.Replace(" ", string.Empty),
                defFileName     = xmlFileName,
                contentFileName = xmlFile.XPathSelectElement("IGE-XAO_DIAGRAM_DEFINITION/Diagram/ContentFile/Content")?.
                                  Attribute("FileName")?.Value.Replace(@".\", string.Empty)
            };

            if (elems?.Count() > 0)
            {
                xMLDefContent = elems.First();
                if (xMLDefContent.contentFileName == null)
                {
                    _errorMessages.Add($"Content file does not exist for definition file {xMLDefContent.defFileName}");
                    return(false);
                }
                if (elems?.Count() > 1)
                {
                    _errorMessages.Add($"For def file {xMLDefContent.defFileName} cannot be more than 1 element 'NameList'");
                    return(false);
                }
                return(true);
            }
            return(false);
        }
        /// <summary>
        /// Computes simple linear regression
        /// </summary>
        /// <param name="x">independent variable</param>
        /// <param name="y">dependent variable</param>
        /// <returns>regression results if x and y have elements, otherwise returns null</returns>
        /// <remarks>An ArgumentException will be thrown if x and y are of different size</remarks>
        /// <exception cref="ArgumentNullException">Either <paramref name="x" /> or <paramref name="y"/> is null.</exception>
        /// <exception cref="OverflowException">The number of elements in either <paramref name="x" /> or <paramref name="y"/> is larger than <see cref="F:System.Int32.MaxValue" />.</exception>
        /// <exception cref="ArgumentException">This method expects the x and y lists to be of equal size</exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="InvalidOperationException">Either <paramref name="x" /> or <paramref name="y" /> contains no elements.</exception>
        public static LinearRegressionResults LinearRegression(List<decimal> x, List<decimal> y)
        {
            if (x.Count() != y.Count())
                throw new ArgumentException("This method expects the x and y lists to be of equal size");
            if (!x.Any())
                return null;

            decimal sX = 0;
            decimal sXx = 0;
            decimal sY = 0;
            decimal sXy = 0;

            var n = x.Count();

            for (var i = 0; i < n; i++)
            {
                sX += x[i];
                sXx += x[i] * x[i];
                sY += y[i];
                sXy += x[i] * y[i];
            }

            var tmpLeft = ((decimal) 1/n);
            var tmpRight = ((decimal) 1/n);
            var b = (n * sXy - sX * sY) / (n * sXx - sX * sX);
            var a = tmpLeft * sY - b * tmpRight * sX;

            var predictedValues = new List<decimal>(n);

            predictedValues.AddRange(x.Select(c => a + b*c));

            var r = y.PearsonR(predictedValues);

            return new LinearRegressionResults(a, b, r);
        }
Beispiel #21
0
        /// <summary>
        ///  method to calculate maximum
        /// </summary>
        /// <param name="rounds"> list of rounds </param>
        /// <param name="factor"> change factor of value</param>
        public static double CalculateMaximum(List<IRound> rounds, double factor)
        {
            // check factor
            if (factor <= 0) throw new ArgumentNullException();

            // calculated maximum
            double result = 0;

            // round index
            double roundMuliplier = 1;

            // iteration over all rounds
            for (int index = rounds.Count() - 1; index >= 0; index--)
            {
                // add to result
                result += rounds[index].Points * roundMuliplier;

                // decrease round multiplier
                roundMuliplier -= factor;
            }

            // check count
            if (rounds.Count() > 0)
            {
                // divide through rounds count
                result /= rounds.Count();
            }

            // return maximum
            return result;
        }
        private int FindUserRoleIdInString(string articleBody, int startOfRoleSearchIndex, List<int> killIndexes)
        {
            string textToSearch;
            int nextIndex = killIndexes.IndexOf(startOfRoleSearchIndex) + 1;

            if (killIndexes.Count() == 1)
                textToSearch = articleBody;
            else if (nextIndex == killIndexes.Count())
                textToSearch = articleBody.Substring(startOfRoleSearchIndex);
            else
                textToSearch = articleBody.Substring(startOfRoleSearchIndex, killIndexes[nextIndex] - startOfRoleSearchIndex);

            foreach (Role role in Db.Roles.ToList())
            {
                if (textToSearch.Contains(role.Name.ToLower()))
                    return role.ID;

                if (role.Aliases.IsNotNullOrWhiteSpace())
                {
                    List<string> aliases = role.Aliases.Split(',').ToList();

                    foreach (string alias in aliases)
                    {
                        if (textToSearch.Contains(alias.ToLower()))
                            return role.ID;
                    }
                }
            }

            return 0;
        }
        public void drawTree(List<TVHS.ViewModels.ViewModelCategory> tree, int rootId, List<ViewModelCategory> result)
        {
            result.Add(tree[rootId]);
            int k = -1;
            for (int i = 0; i < tree.Count(); i++)
            {
                if (tree[i].ParentId == tree[rootId].Id)
                {
                    k = i;
                }
            }
            //leaf
            if(k == -1){

            }
            else{
                for (int i = 0; i < tree.Count(); i++)
                {
                    if (tree[i].ParentId == tree[rootId].Id)
                    {
                        drawTree(tree, i, result);
                    }
                }
            }
        }
Beispiel #24
0
        public HomeIndexViewModel(List<Item> items, List<WList> wlists, int currentListID, string index)
        {
            this.index = index;
            DateTime currentDate = wlists.First(x => x.wlistID == currentListID).sundayDate;
            this.currentListID = currentListID;
            this.items = items;
            this.wlists = wlists;
            int i,j;
            string template= "List ", generate="";

            //The sundays previous to the selected week are found
            prevDates = new DateTime[3] { currentDate.AddDays(-7),currentDate.AddDays(-14),
                                        currentDate.AddDays(-21)};
            //The sundays next to the selected week are found.
            nextDates = new DateTime[3]{currentDate.AddDays(21),currentDate.AddDays(14),
                                        currentDate.AddDays(7)};
            //The current date to be displayed.
            this.currentDate = currentDate;

            //Based on the amount of associated lists with the current week, it is
            //determined if the user has the options to add or remove lists.
            canAddList = (wlists.Count() < 8);
            canRemoveList = (wlists.Count() > 1);

            //The next avaliable name for a list name is found ("List 1", "List 2"...)
            for (i = 1; i < 9 && canAddList; i++) {
                generate = template + i.ToString();
                if (wlists.Where(x => x.name == generate).Count() == 0){
                    nextAvaliableName = generate;
                    break;
                }
            }
        }
        public ActionResult AjaxHandler( string sEchoParam, string iDisplayLength)
        {
            var listOfDinners =
                new List<NerdDinnerDomain.Dinner>()
                    {
                        new Dinner() {DinnerId = 1, Title = "dinner 1", Address="Somewhere one", Country = "USA", EventDate = DateTime.Parse("1/1/2012")},
                        new Dinner() {DinnerId = 2, Title = "dinner 2", Address="Somewhere two", Country = "England", EventDate = DateTime.Parse("1/1/2013")},
                        new Dinner() {DinnerId = 3, Title = "dinner 3", Address="Somewhere three", Country = "France", EventDate = DateTime.Parse("1/1/2014")},
                    };

            var result = from d in listOfDinners
                         select new []
                                    {
                                        Convert.ToString(d.DinnerId),
                                        d.Title,
                                        d.Address,
                                        d.Country,
                                        d.EventDate.ToShortDateString()
                                    };
            return Json(new
            {
                sEcho = string.IsNullOrEmpty(sEchoParam) ? "1": sEchoParam,
                iTotalRecords = listOfDinners.Count(),
                iTotalDisplayRecords = listOfDinners.Count(),
                aaData = result
            },JsonRequestBehavior.AllowGet);
        }
Beispiel #26
0
		public void addPages(string sLabelFormat, List<LabelInfo> lItems)
		{
			lFormats = new List<LabelEntryBase>();

			string[] sTextList = sLabelFormat.Split(new char[] { '~' });
			foreach (string sItem in sTextList)
			{
				if (sItem.Length > 0) lFormats.Add(LabelEntryBase.create(sItem));
			}

			if (lItems == null)
			{
				LabelPage lpNew = new LabelPage();
				lpNew.populate(lFormats);
				lPages.Add(lpNew);
			}
			else
			{
				if (lItems.Count() == 0) return;

				int iMaxRepeat = getMaxRepeat(lFormats);
				int iCount = (int)Math.Ceiling((decimal)lItems.Count() / iMaxRepeat);

				for (int iX = 0; iX < iCount; iX++)
				{
					LabelPage lpNew = new LabelPage();
					lpNew.populate(lFormats, lItems, iX * iMaxRepeat);
					lPages.Add(lpNew);
				}
			}
		}
Beispiel #27
0
 public GroupForces CalculateGroupForces(List<ActorAgent> neighbours)
 {
     if (neighbours != null && neighbours.Any())
     {
         var avoidSum = Vector3.zero;
         var cohesiveSum = Vector3.zero;
         var headingSum = Vector3.zero;
         foreach (var neighbour in neighbours)
         {
             if (neighbour != null && neighbour != agent)
             {
                 var neighbourVehicle = neighbour.GetVehicle();
                 if (neighbourVehicle != null)
                 {
                     var fromNeighbour = agent.GetVehicle().transform.position - neighbourVehicle.transform.position;
                     //if (fromNeighbour.sqrMagnitude < avoidDistance * avoidDistance)
                     avoidSum += fromNeighbour.normalized/fromNeighbour.magnitude;
                     cohesiveSum += neighbour.GetVehicle().transform.position;
                     headingSum += neighbour.Heading;
                 }
             }
         }
         return new GroupForces
         {
             SeparationForce = avoidSum,
             CohesiveForce = SeekForce(cohesiveSum / neighbours.Count()),
             AlignmentForce = (headingSum / neighbours.Count()).normalized
         };
     }
     return new GroupForces();
 }
Beispiel #28
0
        public new int CommitJournalEntries(string sDescription, List<QBJournalEntryLine> jelEntries)
        {
            if (jelEntries == null) return 0;
            if (jelEntries.Count() == 0) return 0;

            JournalEntryLine[] entries = new JournalEntryLine[jelEntries.Count()];

            for (int iX = 0; iX < jelEntries.Count(); iX++)
            {
                entries[iX] = TranslateJournalEntry(jelEntries[iX], jelEntries[iX].bCredit);
            }

            JournalEntry jeNew = new JournalEntry();

            JournalEntryHeader jeh = new JournalEntryHeader();
            jeh.Note = sDescription;

            jeNew.Header = jeh;
            jeNew.Line = entries;

            JournalEntry jeMade = getDataService().Add(jeNew) as JournalEntry;

            if (jeMade.Id.Value.ToInt() > 0 && jeMade.SyncToken.ToInt() > -1) return jeMade.Id.Value.ToInt();
            else return 0;
        }
Beispiel #29
0
        /// <summary>
        /// Shuffles the deck randomly.
        /// </summary>
        /// <returns> Returns the deck after shuffling. </returns>
        /// <param name="deck"> The deck that will be shuffled. </param>
        public static List<Card> Shuffle(List<Card> deck)
        {
            List<int> numsDone = new List<int>(); // A list of all the index values of cards done
            List<Card> shuffledDeck = new List<Card>(); // The new list of cards that will be return that is shuffled

            // Repeat until all cards in the deck has had its position chnaged
            for (int i = 0; i < deck.Count(); i++)
            {
                Random pickIndex = new Random(); // The random number generator that will pick a new index for the current card
                bool newIndex = false;
                int newPick = 0; // The new index it will be tacken from

                // While it hasn't found a new card
                while (!newIndex)
                {
                    newPick = pickIndex.Next(0, deck.Count()); // Picks a new number
                    newIndex = true; // Records that it has found a new card
                    // Checks that the new card hasn't already been picked, if it has been picked record it hasn't found a new card
                    foreach (int num in numsDone)
                    {
                        if (newPick == num)
                        {
                            newIndex = false;
                        }
                    }
                }

                numsDone.Add(newPick); // Adds the new index for the card to the list of picked index's
                shuffledDeck.Add(deck[newPick]); // Add the selected card to the new deck
            }

            return shuffledDeck; // Return the shuffled deck
        }
Beispiel #30
0
		/// <summary>
		/// Establishes if the given value is null, empty or the same as the default.  We look
		/// at the default value because if we're rendering the default we don't need to output
		/// the setting (as it's the default for the jQuery UI control) and thus we can reduce the
		/// JavaScript needed to initialise the control (which can be fairly big if you've got 20+ 
		/// options (never mind readability!))
		/// </summary>
		/// <param name="values">Options being set</param>
		/// <param name="defaultValues">Defaults for the option</param>
		/// <returns>
		/// Returns true if the value is null, empty or the same as the default
		/// Returns false otherwise
		/// </returns>
		public static bool IsNullEmptyOrDefault(List<string> values, List<string> defaultValues) {
			if (values == null || defaultValues == null)
				// can't be the same, remember "x != null", "null != x" and "null != null" !
				return false;

			if (values.Count() != defaultValues.Count()) 
				// not the same number of items => can't be the same
				return false;

			if (values == defaultValues)
				// same underlying object, so must be the same!
				return true;

			// otherwise look at each item in isolation
			for (int v=0; v < values.Count(); v++) {
				for (int d=0; d < defaultValues.Count(); d++) {
					if (values[v] != defaultValues[d]) {
						return false;
					}
				}
			}

			// all items in the list are the same, so the lists are the same
			return true;
		}
Beispiel #31
0
        //Place a random pawn on a random possible location (for the AI)
        //If placed on a barricade, it will place the barricade on a random field.
        public void automateTurn(int worp)
        {
            List<Pawn> pawnNoOption = new List<Pawn>();

            //Select a random pawn
            Pawn tempPawn = getRandomPawn();
            Model.Field[] possibleMoves = tempPawn.getPossibleMoves(worp).ToArray();
            while (possibleMoves.Count() == 0 && pawnNoOption.Count() < aPawns.Count())
            {
                if (!pawnNoOption.Contains(tempPawn))
                {
                    pawnNoOption.Add(tempPawn);
                }

                tempPawn = getRandomPawn();
                possibleMoves = tempPawn.getPossibleMoves(worp).ToArray();
            }

            if (pawnNoOption.Count() == aPawns.Count())
            {
                game.nextPlayer();
                return;
            }

            game.fieldClick(tempPawn.CurrentLocation);
            game.fieldClick(possibleMoves[random.Next(0, possibleMoves.Count())]);

            if (game.Barricade != null)
            {
                game.moveBarricadeRandom();
            }
        }
        public virtual ActionResult DataTables(DataTableCriteria searchCriteria)
        {
            // Generate Data
            List<DataTableRecord> allRecords = new List<DataTableRecord>();

            int idCount = 0;
            int cellCount = 0;

            for (int i = 0; i < 100; i++)
                allRecords.Add(new DataTableRecord() { Id = ++idCount, Column1 = "cell " + (++cellCount).ToString(), Column2 = "cell " + (++cellCount).ToString(), Column3 = "cell " + (++cellCount).ToString() });

            // Apply search criteria to data
            var filteredRecord = allRecords.ApplyCriteria(searchCriteria);

            // TODO: Apply searching in the ApplyCriteria function eventually...
            if(!string.IsNullOrWhiteSpace(searchCriteria.GlobalSearchText))
                filteredRecord = filteredRecord.Where(e => e.Column1.Contains(searchCriteria.GlobalSearchText) || e.Column2.Contains(searchCriteria.GlobalSearchText) || e.Column3.Contains(searchCriteria.GlobalSearchText)).ToList();


            // Create response
            var result = new DataGridResult<DataTableRecord>();

            result.Data = filteredRecord.ToList();
            result.DisplayedRecords = allRecords.Count();
            result.TotalRecords = allRecords.Count();

            return Json(result);
        }
Beispiel #33
0
 private void UpdateTotalInfo()
 {
     Invoke(new Action(() => {
         int totalBoxNum     = (int)currentBoxList?.Count(i => i.PACKRESULT == "S" && i.RESULT == "S").CastTo <int>(0);
         int totalNum        = (int)currentBoxList?.FindAll(i => i.PACKRESULT == "S" && i.RESULT == "S").Sum(j => j.Details?.Count);
         lblTotalBoxNum.Text = totalBoxNum.ToString();
         lblTotalNum.Text    = totalNum.ToString();
     }));
 }
Beispiel #34
0
 public int GetSlotTypeCountAll(SlotType slotType)
 {
     return((Head?.HasSlotTypeCount(slotType) ?? 0) +
            (Torso?.HasSlotTypeCount(slotType) ?? 0) +
            (Arm?.HasSlotTypeCount(slotType) ?? 0) +
            (Waist?.HasSlotTypeCount(slotType) ?? 0) +
            (Leg?.HasSlotTypeCount(slotType) ?? 0) +
            (_WeaponSlots?.Count(z => z.Type == slotType) ?? 0) +
            (Charm?.HasSlotTypeCount(slotType) ?? 0));
 }
Beispiel #35
0
 private void CounterBasket(object sender, EventArgs e)
 {
     if (basket?.Count() > 0)
     {
         for (int i = 0; i < basket.Count(); i++)
         {
             basket[i].id = i + 1;
         }
     }
 }
Beispiel #36
0
        public void Parse(NewTickPacket packet)
        {
            foreach (Status status in packet.Statuses)
            {
                var thing = Players.FirstOrDefault(x => x.PlayerData.OwnerObjectId == status.ObjectId);
                if (thing != null)
                {
                    thing.Parse(status);
                }
                Entity entity = Client.GetEntity(status.ObjectId);
                if (entity == null)
                {
                    continue;
                }
                if (!EntityPaths.ContainsKey(entity))
                {
                    EntityPaths[entity] = new List <Location>();
                }
                EntityPaths[entity].Add(status.Position);
                if (TargetEntityPathCopyThing != null && TargetEntity?.Status.ObjectId == entity.Status.ObjectId)
                {
                    TargetEntityPathCopyThing.Add(status.Position);
                }
            }

            if (TargetEntityPathCopyThing?.Count() > 0)
            {
                TargetLocation = TargetEntityPathCopyThing.First();
            }

            if (TargetLocation != null)
            {
                Location result = Lerp(Client.PlayerData.Pos, TargetLocation, Client.PlayerData.TilesPerTick());
                Client.SendGoto(result);
                if (result.ToString() == TargetLocation.ToString())
                {
                    TargetLocation = null;
                    if (TargetEntityPathCopyThing?.Count() > 0)
                    {
                        OnTargetReached();
                    }
                    else
                    {
                        TargetReached?.Invoke();
                    }
                }
            }
        }
        public IList <MailItem> FindMails(string search, bool showMail = false)
        {
            List <MailDetails> allMailsDetails      = ReturnAllMailsDetails();
            List <MailDetails> allFoundMailsDetails = ReturnAllFoundMailsDetails(allMailsDetails, search);

            IsMailFound = allFoundMailsDetails?.Count() > 0 ? true : false;
            MailItem        tmpMailItem;
            List <MailItem> foundMails = new List <MailItem>();

            foreach (var item in allFoundMailsDetails)
            {
                tmpMailItem = nameSpace.GetItemFromID(item.EntryID, item.FolderID) as MailItem;
                if (tmpMailItem != null)
                {
                    foundMails.Add(tmpMailItem);
                }
            }
            if (showMail)
            {
                foreach (MailItem item in foundMails)
                {
                    item.Display();
                }
            }
            return(foundMails);
        }
Beispiel #38
0
        public int PointBelongs(IIntersectable sender, Vector2 point)
        {
            counter++;
            int     p = boundary?.Count(tuple => IntersectLines(tuple.Item1, tuple.Item2, point)) ?? 0;
            Vector2 p1, p2;
            int     cnt     = poly.Count - 1;
            var     minSize = System.Math.Min(sender.FirstParamLimit, sender.SecondParamLimit) * 0.8;

            for (int i = 0; i < cnt; i++)
            {
                p1 = poly[i];
                p2 = poly[i + 1];
                if ((p1 - p2).Length() < minSize)
                {
                    if (IntersectLines(p1, p2, point))
                    {
                        p++;
                    }
                }
            }
            if (cyclic)
            {
                if ((poly[cnt] - poly[0]).Length() < minSize)
                {
                    if (IntersectLines(poly[cnt], poly[0], point))
                    {
                        p++;
                    }
                }
            }

            return(p);
        }
        private static Expression DefaultIDsInListExpression <TID>(List <TID> ids)
        {
            int cnt = ids?.Count() ?? 0;

            if (cnt == 0)
            {
                return(FalseExpression);
            }
            if (cnt == 1)
            {
                return(DefaultIDEqualsExpression(ids[0]));
            }

            Type listType = typeof(List <TID>),
                 idType   = typeof(TID);
            // Converting IList to List because it is difficult to get Contains method for arrays
            //List<TID> list = (ids is List<TID>) ? ids as List<TID> : ids.ToList();

            //            ConstantExpression idsParameter = Expression.Constant(list, listType);
            Expression <Func <List <TID> > > idsLambda = () => ids;
            Expression           convertExpression     = Expression.Convert(idMemberExpression, idType);
            MethodInfo           method             = listType.GetMethod("Contains", new[] { idType });
            MethodCallExpression containsExpression = Expression.Call(idsLambda.Body, method, convertExpression);

            return(containsExpression);
        }
Beispiel #40
0
        public override async Task <object> GetValue(int count)
        {
            string query =
                $"/query?q=SELECT \"currentValue\" FROM sensors_{SensorType} " +
                $"WHERE postgre_id=\'{PostgreSQLId}\' " +
                $"ORDER BY \"time\" DESC " +
                $"LIMIT {count}";

            string json = await influxDbClient.GetAsync(query);

            List <List <object> > resultCollection = InfluxDbJsonSerializer.Deserialize(json);

            if (resultCollection?.Count() > --count)
            {
                TimeStamp = DateTime.Parse(resultCollection[count][0].ToString()).ToUniversalTime();

                JsonElement stateJson = (JsonElement)resultCollection[count][1];
                bool        state     = JsonSerializer.Deserialize <bool>(stateJson.GetRawText());

                AlertState = Handle(state);

                return(state);
            }
            else
            {
                return(null);
            }
        }
        //public List<string> Logar(UsuarioViewModelLogin obj)
        //{
        //    List<string> errors = new List<string>();
        //    UsuarioViewModel usuarioViewModel = AutoMapper.Mapper.Map<UsuarioViewModelLogin, UsuarioViewModel>(obj);
        //    Usuario usuario = AutoMapper.Mapper.Map<UsuarioViewModel, Usuario>(usuarioViewModel);
        //    usuario = GetByName(usuario.email).First();
        //    try
        //    {
        //        if(usuario.password == obj.password && usuario.email == obj.email)
        //        {
        //            return errors;
        //        }
        //        else
        //        {
        //            errors.Add("Email ou senha incorretos");
        //            return errors;
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        Rollback();
        //        errors.Add("Ocorreu um erro no Login");
        //        return errors;
        //    }
        //}

        public List <string> Insert(UsuarioViewModel obj)
        {
            List <string> errors = new List <string>();

            try
            {
                Usuario usuario = AutoMapper.Mapper.Map <UsuarioViewModel, Usuario>(obj);
                if (errors?.Count > 0)
                {
                    return(errors);
                }
                else
                {
                    BeginTransaction();
                    errors = _usuarioService.Insert(usuario);
                    if (errors?.Count() == 0)
                    {
                        SaveChanges();
                        Commit();
                    }
                }
            }
            catch (Exception e)
            {
                Rollback();
                errors.Add("Ocorreu um erro no Cadastro");
            }
            return(errors);
        }
Beispiel #42
0
 bool HasProperty(string propName,
                  out List <dstu2.Hl7.Fhir.Introspection.PropertyMapping> dstu2,
                  out List <stu3.Hl7.Fhir.Introspection.PropertyMapping> stu3,
                  out List <r4.Hl7.Fhir.Introspection.PropertyMapping> r4)
 {
     if (_cm4 == null)
     {
         r4 = null;
     }
     else
     {
         r4 = _cm4.Select(t => t.FindMappedElementByName(propName)).Where(t => t != null && IsMatchingPropName(propName, t)).ToList();
     }
     if (_cm3 == null)
     {
         stu3 = null;
     }
     else
     {
         stu3 = _cm3.Select(t => t.FindMappedElementByName(propName)).Where(t => t != null && IsMatchingPropName(propName, t)).ToList();
     }
     if (_cm2 == null)
     {
         dstu2 = null;
     }
     else
     {
         dstu2 = _cm2.Select(t => t.FindMappedElementByName(propName)).Where(t => t != null && IsMatchingPropName(propName, t)).ToList();
     }
     return((dstu2?.Count() > 0) || (stu3?.Count() > 0) || (r4?.Count() > 0));
 }
Beispiel #43
0
        public override void Remove()
        {
            try
            {
                ResourceDictionary metroControls = (from d in Application.Current.Resources.MergedDictionaries
                                                    where d.Source != null && d.Source.OriginalString == "pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml"
                                                    select d).FirstOrDefault();
                ResourceDictionary metroFonts = (from d in Application.Current.Resources.MergedDictionaries
                                                 where d.Source != null && d.Source.OriginalString == "pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml"
                                                 select d).FirstOrDefault();
                List <ResourceDictionary> metroThemes = (from d in Application.Current.Resources.MergedDictionaries
                                                         where d.Source != null && d.Source.OriginalString.StartsWith("pack://application:,,,/MahApps.Metro;component/Styles/Themes/")
                                                         select d).ToList();
                if (metroControls != null)
                {
                    Application.Current.Resources.MergedDictionaries.Remove(metroControls);
                }

                if (metroFonts != null)
                {
                    Application.Current.Resources.MergedDictionaries.Remove(metroFonts);
                }

                if (metroThemes?.Count() > 0)
                {
                    foreach (ResourceDictionary dic in metroThemes)
                    {
                        Application.Current.Resources.MergedDictionaries.Remove(dic);
                    }
                }
                ThemeManager.CurrentTheme = null;
            }
            catch { App.Logger.Log("Could not clear theme"); }
        }
Beispiel #44
0
        private async Task RespondPowerVirtualAgentsBotReplyAsync(DirectLineClient client, RelayConversation currentConversation, ITurnContext <IMessageActivity> turnContext)
        {
            var retryMax = WaitForBotResponseMaxMilSec / PollForBotResponseIntervalMilSec;

            for (int retry = 0; retry < retryMax; retry++)
            {
                // Get bot response using directlineClient,
                // response contains whole conversation history including user & bot's message
                ActivitySet response = await client.Conversations.GetActivitiesAsync(currentConversation.ConversationtId, currentConversation.WaterMark);

                // Filter bot's reply message from response
                List <DirectLineActivity> botResponses = response?.Activities?.Where(x =>
                                                                                     x.Type == DirectLineActivityTypes.Message &&
                                                                                     string.Equals(x.From.Name, _botService.GetBotName(), StringComparison.Ordinal)).ToList();

                if (botResponses?.Count() > 0)
                {
                    if (int.Parse(response?.Watermark ?? "0") <= int.Parse(currentConversation.WaterMark ?? "0"))
                    {
                        // means user sends new message, should break previous response poll
                        return;
                    }

                    currentConversation.WaterMark = response.Watermark;
                    await turnContext.SendActivitiesAsync(_responseConverter.ConvertToBotSchemaActivities(botResponses).ToArray());
                }

                Thread.Sleep(PollForBotResponseIntervalMilSec);
            }
        }
Beispiel #45
0
    public bool Add(Item item)
    {
        if (item == null)
        {
            return(false);
        }

        if (items?.Count >= maxItems)
        {
            return(false);
        }

        if (item.MaxInInventory > 0 && items?.Count(x => x == item) >= item.MaxInInventory)
        {
            return(false);
        }

        if (items == null)
        {
            items = new List <Item>();
        }

        items.Add(item);
        onChanged.Invoke();

        return(true);
    }
        private async Task <ResultData <T> > GetIncrementalListData(int pageIndex)
        {
            IEnumerable <T> newList      = new List <T>();
            bool            HasMoreItems = false;

            try
            {
                newList = await GetList(pageIndex);

                HasMoreItems = newList?.Count() > 0;

                await RunOnUiThread(() =>
                {
                    if (pageIndex == DEFAULT_PAGE_INDEX)
                    {
                        DataList.Clear();
                    }

                    LoadMoreItemCompleted(newList, pageIndex);
                });
            }
            catch (Exception e)
            {
                var task = Logger.LogAsync(e);
            }
            return(new ResultData <T>()
            {
                Data = newList, HasMoreItems = HasMoreItems
            });
        }
        public static List <StudentSubjectMarksByDateDto> ToSetPositiveOrNegativeExtensionMarkDateValue(this List <StudentSubjectMarksByDateDto> list)
        {
            /*
             *  23   23 May
             *  2    24 May -21
             *  4    25     +2
             *
             */
            int totalItems = list?.Count() ?? 1;

            if (list == null || totalItems <= 1)
            {
                return(list);
            }

            list = list.OrderBy(c => c.Date).ToList();

            int index = 0;

            foreach (var mark in list)
            {
                if (index <= 0)
                {
                }
                else
                {
                    mark.ValueDifferenceFromPreviosMark = mark.Mark - (list[index - 1].Mark);
                }
                index++;
            }
            var ordr = list.OrderByDescending(c => c.Date).ToList();

            return(ordr);
        }
Beispiel #48
0
        private static int GetDangerLvlBuilding(Playfield p, int line)
        {
            List <BoardObj> enemyBuildings = p.enemyBuildings;

            if (enemyBuildings?.Count() > 0)
            {
                BoardObj bKT = enemyBuildings.FirstOrDefault(n => n.Line == line && n.IsPositionInArea(p, p.ownKingsTower.Position));

                BoardObj bPT;

                if (line == 1)
                {
                    bPT = enemyBuildings.FirstOrDefault(n => n.IsPositionInArea(p, p.ownPrincessTower1.Position));
                }
                else
                {
                    bPT = enemyBuildings.FirstOrDefault(n => n.IsPositionInArea(p, p.ownPrincessTower2.Position));
                }

                if (bKT != null || bPT != null)
                {
                    return(3);
                }
            }

            return(0);
        }
Beispiel #49
0
        public ActionResult Cart()
        {
            List <CartModel> list2 = null;

            if (TempData["cart"] != null)
            {
                double x = 0;
                list2 = JsonConvert.DeserializeObject <List <CartModel> >(TempData["cart"] as string);
                //list2 = ViewData["cart"] as List<CartModel>;
                foreach (var item in list2)
                {
                    x += item.TotalPrice;
                }
                if (list2?.Count() == 0)
                {
                    TempData.Remove("total");
                    TempData.Remove("item_count");
                }
                else
                {
                    TempData["total"]      = JsonConvert.SerializeObject(x);
                    TempData["item_count"] = JsonConvert.SerializeObject(list2.Count);
                }
            }
            TempData.Keep();
            return(View(list2));
        }
 /// <summary>
 /// Component to hold a 2D list of cards only showing the top card
 /// </summary>
 /// <param name="cards"></param>
 public HorizontalCardArrayComponent(List <List <ICard> > cards)
 {
     //Padding = 1;
     //Margin = 1;
     //MinimumHeightRequest = 100;
     RowDefinitions = new RowDefinitionCollection()
     {
         new RowDefinition()
         {
             Height = new GridLength(1, GridUnitType.Star)
         }
     };
     ColumnDefinitions = new ColumnDefinitionCollection();
     ColumnSpacing     = 1;
     RowSpacing        = 1;
     HorizontalOptions = LayoutOptions.FillAndExpand;
     VerticalOptions   = LayoutOptions.FillAndExpand;
     for (int i = 0; i < cards?.Count(); i++)
     {
         this.ColumnDefinitions.Add(new ColumnDefinition()
         {
             Width = new GridLength(1, GridUnitType.Star)
         });
         var lbl = new CardComponent(cards[i].LastOrDefault(), 0, i);
         this.Children.Add(lbl);
     }
 }
Beispiel #51
0
        private List <string> GetItems()
        {
            List <string> result = new List <string> {
                "Home"
            };

            try
            {
                var items = new List <string>();
                if (HttpContext.Request?.Path.HasValue == true)
                {
                    items = HttpContext.Request.Path.Value.Substring(1).Split("/").ToList();
                }
                if (items?.Count() > 0)
                {
                    for (int i = 0; i < items.Count() && i < 2; i++)
                    {
                        result.Add(items[i]);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error with get items in BreadcrumbsViewComponent.");
            }
            return(result);
        }
Beispiel #52
0
        public async Task <User> CreateUser(string email, string password, List <Claim> claims = null)
        {
            logger.ScopeTrace($"Creating user '{email}', Route '{RouteBinding.Route}'.");

            ValidateEmail(email);

            var user = new User {
                UserId = Guid.NewGuid().ToString()
            };
            await user.SetIdAsync(new User.IdKey {
                TenantName = RouteBinding.TenantName, TrackName = RouteBinding.TrackName, Email = email
            });

            await secretHashLogic.AddSecretHashAsync(user, password);

            if (claims?.Count() > 0)
            {
                user.Claims = claims.ToClaimAndValues();
            }

            await ThrowIfUserExists(email);
            await ValidatePasswordPolicy(email, password);

            await tenantRepository.CreateAsync(user);

            logger.ScopeTrace($"User '{email}' created, with user id '{user.UserId}'.");

            return(user);
        }
Beispiel #53
0
        public PartialViewResult PartialRequests()
        {
            try
            {
                List <Request> Result = null;
                if (LoggedIsSystemAdmin)
                {
                    Result = UnitOfWork.RequestsBL.GetAllRequests(r => r.Cycle.Department.IsActive == true)
                             .OrderByDescending(f => f.CreateDate)
                             .ToList();
                }
                else // normal user
                {
                    Result = UnitOfWork.RequestsBL
                             .GetAllRequests(f => f.CreatedById == LoggedUserId &&
                                             f.Cycle.DepartmentId == LoggedUserDepartmentId)
                             .OrderByDescending(f => f.CreateDate)
                             .ToList();
                }


                if (Result?.Count() != 0)
                {
                    return(PartialView("_PartialRequests", Result));
                }
                else
                {
                    return(PartialView("_PartialRequests", null));
                }
            }
            catch (Exception ex)
            {
                return(PartialView("_PartialRequests", ex));
            }
        }
Beispiel #54
0
        public ActionResult ExportToExcelUnion(List <int> leaguesId, int sortType, int seasonId)
        {
            leaguesId = (List <int>)Session["LeaguesIds"];
            var  xlsService = new ExcelGameService();
            bool isBasketBallOrWaterPolo = false;
            var  games = new List <ExcelGameDto>();

            foreach (var leagueId in leaguesId)
            {
                games.AddRange(xlsService.GetLeagueGames(leagueId, seasonId));
            }

            if (games?.Count() > 0)
            {
                isBasketBallOrWaterPolo = gamesRepo.IsBasketBallOrWaterPoloGameCycle(games[0].GameId);
            }

            if (sortType == 1)
            {
                games = games.OrderBy(x => x.Date).ToList();
            }
            if (sortType == 2)
            {
                games = games.OrderBy(x => x.Auditorium).ToList();
            }

            return(ToExcel(games, isBasketBallOrWaterPolo));
        }
Beispiel #55
0
        public static Output <List <object>, bool> Push(BHoMAdapter adapter, IEnumerable <object> objects, string tag = "",
                                                        PushType pushType = PushType.AdapterDefault, ActionConfig actionConfig = null,
                                                        bool active       = false)
        {
            var noOutput = BH.Engine.Reflection.Create.Output(new List <object>(), false);

            if (!active)
            {
                return(noOutput);
            }

            ActionConfig pushConfig = null;

            if (!adapter.SetupPushConfig(actionConfig, out pushConfig))
            {
                BH.Engine.Reflection.Compute.RecordError($"Invalid `{nameof(actionConfig)}` input.");
                return(noOutput);
            }

            PushType pt = pushType;

            if (!adapter.SetupPushType(pushType, out pt))
            {
                BH.Engine.Reflection.Compute.RecordError($"Invalid `{nameof(pushType)}` input.");
                return(noOutput);
            }

            List <object> result = adapter.Push(objects, tag, pt, pushConfig);

            return(BH.Engine.Reflection.Create.Output(result, objects?.Count() == result?.Count()));
        }
        private GoogleDriveItem _ToGoogleDriveItem(Google.Apis.Drive.v3.Data.File file)
        {
            List <string> metdata = file.Description?.ToLower().Split('|').ToList();

            string title = null;
            string tags  = null;
            string desc  = null;

            // parse title, tags, and description from description field

            if (metdata?.Count() > 1)
            {
                title = metdata?.Where(m => m.StartsWith("title")).FirstOrDefault().Split(':')[1];
                tags  = metdata?.Where(m => m.StartsWith("tags")).FirstOrDefault().Split(':')[1];
                desc  = metdata?.Where(m => m.StartsWith("description")).FirstOrDefault().Split(':')[1];
            }
            var googleDriveItem = new GoogleDriveItem
            {
                Id          = file.Id,
                Name        = file.Name,
                Title       = title ?? file.Name,
                Tags        = tags?.Split(',').Select(t => t),
                Description = desc ?? file.Description,
                Url         = file.WebViewLink,
                IsVideo     = file.MimeType.Contains("video"),
                IsFolder    = file.MimeType.Equals("application/vnd.google-apps.folder"),
                Parents     = file.Parents,
            };


            // googleDriveItem.Children = childFolders;

            return(googleDriveItem);
        }
Beispiel #57
0
        internal void pushN(List <object> vals, int n)
        {
            int nVals = vals?.Count() ?? 0;

            if (n < 0)
            {
                n = nVals;
            }

            for (int i = 0; i < n; i++)
            {
                push(i < nVals ? vals[i] : null);
            }

//            var nVals = vals.Length;
//            if (n < 0)
//            {
//                n = nVals;
//            }
//
//            for (var i = 0; i < n; i++)
//            {
//                if (i < nVals)
//                {
//                    push(vals[i]);
//                }
//                else
//                {
//                    push(null);
//                }
//            }
        }
        public async Task <ActionResult <IList <string> > > GetOptionals()
        {
            IList <string> result = new List <string>();

            foreach (var car in CarRepository.Cars)
            {
                foreach (var optional in car.Optionals)
                {
                    if (!result.Any(o => o.Equals(optional, StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Add(optional);
                    }
                }
            }

            Request.HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "X-Total-Count");
            Request.HttpContext.Response.Headers.Add("X-Total-Count", result?.Count().ToString());

            if (result == null || result.Count == 0)
            {
                return(await Task.FromResult <ActionResult>(this.Ok(result)));
            }
            else
            {
                return(await Task.FromResult <ActionResult>(this.Ok(result)));
            }
        }
Beispiel #59
0
 }                                     // Could be calculated from the others, but sometimes knowing if they don't add up means something
 public void RecalculateCounts()
 {
     tests    = testResults?.Count() ?? 0;
     failures = testResults?.Where(eachReport => { return(eachReport.finishState == UUnitFinishState.FAILED); }).Count() ?? 0;
     skipped  = testResults?.Where(eachReport => { return(eachReport.finishState == UUnitFinishState.SKIPPED); }).Count() ?? 0;
     passed   = testResults?.Where(eachReport => { return(eachReport.finishState == UUnitFinishState.PASSED); }).Count() ?? 0;
 }
Beispiel #60
0
        public static int GetStudents()
        {
            //DataSet ds = new DataSet();
            //DataTable dt = new DataTable();
            //ds.Tables.Add(dt);

            List <Student> students = new List <Student>();
            Student        st       = new Student();

            st.FirstName     = "Dirk";
            st.LastName      = "Strauss";
            st.JobTitle      = "";
            st.Age           = 19;
            st.StudentNumber = "20323742";
            students.Add(st);

            st.FirstName     = "Bob";
            st.LastName      = "Healey";
            st.JobTitle      = "Lab Assistant";
            st.Age           = 21;
            st.StudentNumber = "21457896";
            students.Add(st);

            students = null;

            return(students?.Count() ?? 0);
            //return students.Count();
        }