Beispiel #1
0
        internal static Tuple <MethodInfo, MethodDeclaration>[]? FilterTestMethods(MethodInfo method, Tuple <MethodInfo, MethodDeclaration>[]?testMethodsWithDeclaration)
        {
            if (method.DeclaringType == null ||
                testMethodsWithDeclaration == null ||
                testMethodsWithDeclaration.Length == 0)
            {
                return(null);
            }

            Tuple <MethodInfo, MethodDeclaration>[] tuples;
            if (method.HasDeclaringTypeValidationAttributes())
            {
                tuples = testMethodsWithDeclaration
                         .Where(x => x.Item1.DeclaringType != null &&
                                x.Item1.DeclaringType.Name.EndsWith("AttributesTests", StringComparison.Ordinal))
                         .ToArray();
            }
            else
            {
                var mn = method.DeclaringType.BeautifyName().Replace("<T>", string.Empty, StringComparison.Ordinal);
                tuples = testMethodsWithDeclaration
                         .Where(x => x.Item1.DeclaringType != null &&
                                x.Item1.DeclaringType.Name.StartsWith(mn, StringComparison.Ordinal))
                         .ToArray();
            }

            return(tuples);
        }
        /// <summary>
        /// Splits slash-separated strings into a submenu tree
        /// </summary>
        /// <param name="menu"></param>
        /// <param name="items"></param>
        private void AddMenuItems(ItemsControl menu, Tuple<KeyValuePair<int, string>, string[]>[] items)
        {
            foreach (var group in items.Where(x => x.Item2.Length > 1).GroupBy(x => x.Item2.First()))
            {
                var menuItem = new MenuItem { Command = null, CommandParameter = null, Header = group.Key };
                menu.Items.Add(menuItem);
                var subItems = group.Select(x => Tuple.Create(x.Item1, x.Item2.Skip(1).ToArray())).ToArray();
                AddMenuItems(menuItem, subItems);
            }

            foreach (var item in items.Where(x => x.Item2.Length == 1))
            {
                menu.Items.Add(new MenuItem { Command = SelectOptionCommand, CommandParameter = item.Item1, Header = item.Item2.Last() });
            }
        }
        public void TestExpertProbabilities()
        {
            var input =
                @"declare obstacle [ test ]
                    probability [ expert1 ] .01
                    probability [ expert2 ] .02
                  end
                  declare expert [ expert1 ] end
                  declare expert [ expert2 ] end";

            var expected = new Tuple <string, double>[] {
                new Tuple <string, double> ("expert1", .01),
                new Tuple <string, double> ("expert2", .02)
            };

            var model = parser.Parse(input);

            var srs = model.satisfactionRateRepository.GetObstacleSatisfactionRates("test");

            foreach (var sr in srs)
            {
                Assert.IsInstanceOf(typeof(DoubleSatisfactionRate), sr);

                var dsr           = (DoubleSatisfactionRate)sr;
                var expected_item = expected.Where(t => t.Item1 == dsr.ExpertIdentifier && t.Item2 == dsr.SatisfactionRate);
            }
        }
 private Point[] GetGhostMove()
 {
     Point[] move = new Point[4];
     for (int i = 0; i < 4; i++)
     {
         List <Point> points = new List <Point>();
         checkGhostPoint(points, i, -1, 0);
         checkGhostPoint(points, i, 1, 0);
         checkGhostPoint(points, i, 0, -1);
         checkGhostPoint(points, i, 0, 1);
         if (points.Count == 1)
         {
             move[i] = points[0];
         }
         else if (points.Count > 0)
         {
             Tuple <int, int>[] values = new Tuple <int, int> [points.Count];
             for (int j = 0; j < values.Length; j++)
             {
                 values[j] = Tuple.Create(shortestPathToPacman(points[j]), j);
             }
             Array.Sort(values, (a, b) => a.Item1 - b.Item1);
             int good = values[0].Item1;
             values  = values.Where(t => t.Item1 == good).ToArray();
             move[i] = points[values[_rnd.Next(values.Length)].Item2];
         }
         else
         {
             move[i] = Settings.GhostPosition[i]; // Shouldn't happen as we will lose
         }
     }
     return(move);
 }
Beispiel #5
0
        public void Rank_CoordinatesNullPerfectTermMatch_ReturnsExpectedCertainty()
        {
            //verify that whitespaces are trimmed and certainty is calculated accurately
            //entries contains a Name that matches searchTerm exactly, so max(Certainty) for matching term should == 100%
            var entries = new Tuple <GeoDataEntry, double>[]
            {
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Test"
                }, 1.0),                                                                  //full match
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Test 2 "
                }, .6666),                                                                     //whitespaces should be trimmed
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Test 3 xx"
                }, .4444),
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Something"
                }, 0)                                                                       //doesn't start with searchTerm
            };


            foreach (RankingResult result in Target.Rank(entries.Select(e => e.Item1), "test", null))
            {
                Assert.AreEqual(Rounder.Round(entries.Where(e => e.Item1.Equals(result.Entry)).Single().Item2), result.Certainty);
            }
        }
Beispiel #6
0
        public void Rank_CoordinatesNullPartialTermMatch_ReturnsExpectedCertainty()
        {
            //vverify that in the case of only partial matches, results are still offset/normalized to 100%
            var entries = new Tuple <GeoDataEntry, double>[]
            {
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Test"
                }, 1.0),                                                                  //full match
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Test 2 "
                }, .67),                                                                     //whitespaces should be trimmed
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Test 3 xx"
                }, .44),
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Something"
                }, 0)                                                                       //doesn't start with searchTerm
            };


            foreach (RankingResult result in Target.Rank(entries.Select(e => e.Item1), "te", null))
            {
                Assert.AreEqual(Rounder.Round(entries.Where(e => e.Item1.Equals(result.Entry)).Single().Item2), result.Certainty);
            }
        }
Beispiel #7
0
 public static int Count <T1, T2, T3, T4, T5, T6, T7>(this Tuple <T1, T2, T3, T4, T5, T6, T7> value,
                                                      Func <object, Boolean> predicate)
 {
     Contract.Requires <ArgumentNullException>(value != null);
     Contract.Requires <ArgumentNullException>(predicate != null);
     return(value.Where(predicate).Count());
 }
Beispiel #8
0
        public PocoData(Type pocoType, string tableName, string keyspaceName, LookupKeyedCollection<string, PocoColumn> columns,
                        string[] partitionkeys, Tuple<string, SortOrder>[] clusteringKeys, bool caseSensitive, bool compact, bool allowFiltering)
        {
            if (pocoType == null) throw new ArgumentNullException("pocoType");
            if (tableName == null) throw new ArgumentNullException("tableName");
            if (columns == null) throw new ArgumentNullException("columns");
            if (partitionkeys == null) throw new ArgumentNullException("partitionkeys");
            if (clusteringKeys == null) throw new ArgumentNullException("clusteringKeys");
            PocoType = pocoType;
            TableName = tableName;
            Columns = columns;
            CaseSensitive = caseSensitive;
            CompactStorage = compact;
            AllowFiltering = allowFiltering;
            KeyspaceName = keyspaceName;
            _columnsByMemberName = columns.ToDictionary(c => c.MemberInfo.Name, c => c);
            PartitionKeys = partitionkeys.Where(columns.Contains).Select(key => columns[key]).ToList();
            ClusteringKeys = clusteringKeys.Where(c => columns.Contains(c.Item1)).Select(c => Tuple.Create(columns[c.Item1], c.Item2)).ToList();
            _primaryKeys = new HashSet<string>(PartitionKeys.Select(p => p.ColumnName).Concat(ClusteringKeys.Select(c => c.Item1.ColumnName)));

            MissingPrimaryKeyColumns = new List<string>();
            if (PartitionKeys.Count != partitionkeys.Length)
            {
                MissingPrimaryKeyColumns.AddRange(partitionkeys.Where(k => !columns.Contains(k)));
            }
            if (ClusteringKeys.Count != clusteringKeys.Length)
            {
                MissingPrimaryKeyColumns.AddRange(partitionkeys.Where(k => !columns.Contains(k)));
            }
        }
Beispiel #9
0
        private void filterButton_Click(object sender, EventArgs e) // вызывается когда нажали кнопку фильтрации
        {
            Tuple <object, string>[] values = new Tuple <object, string>[] {
                new Tuple <object, string>(nameField, dbFields[1]),
                new Tuple <object, string>(visitorsAmountField, dbFields[2]),
                new Tuple <object, string>(costPerVisitorField, dbFields[3]),
                new Tuple <object, string>(equipmentEntertainmentCostsField, dbFields[4]),
                new Tuple <object, string>(rentPriceField, dbFields[5])
            };
            Tuple <object, string>[] dates = new Tuple <object, string>[]
            {
                new Tuple <object, string>(startDateTimePicker, dbFields[6]),
                new Tuple <object, string>(endDateTimePicker, dbFields[7])
            };

            var filterFields = values.Where(v => (v.Item1 as TextBox)?.Text.Length != 0)
                               .Concat(dates.Where(v => (v.Item1 as DateTimePicker)?.Text.Length != 1));

            if (!isFormValid(values.Concat(dates).Except(filterFields).Select(v => v.Item1).ToArray()))
            {
                return;
            }
            var filteredResultFields = filterFields
                                       .Select(v => $"[{v.Item2}]{filterTypeComboBox.SelectedItem}{(v.Item1 as TextBox)?.Text ?? (v.Item1 as DateTimePicker).Value.ToOADate().ToString()}");

            filterCommand = "WHERE " + string.Join($" AND ", filteredResultFields);
            Update(sortFieldComboBox.Text, isFiltered: true);
        }
Beispiel #10
0
        private static Tuple <int, int> FindClosestReachableTargetPosition(
            Creature creature, char[,] map, List <Creature> creatures, int[,] ranges)
        {
            var targets         = creatures.Where(c => c.IsElf != creature.IsElf);
            var otherCreatures  = creatures.Where(c => c.ID != creature.ID);
            var targetPositions = targets.SelectMany(t => {
                var possibleTargetPositions = new Tuple <int, int>[4] {
                    new Tuple <int, int>(t.X - 1, t.Y),
                    new Tuple <int, int>(t.X + 1, t.Y),
                    new Tuple <int, int>(t.X, t.Y - 1),
                    new Tuple <int, int>(t.X, t.Y + 1)
                };

                return(possibleTargetPositions.Where(pt =>
                                                     map[pt.Item1, pt.Item2] == '.' &&
                                                     !otherCreatures.Any(c => c.X == pt.Item1 && c.Y == pt.Item2)));
            }).ToList();

            if (targetPositions.Count == 0)
            {
                return(null);
            }

            var positionsByDistance = targetPositions.GroupBy(tp => ranges[tp.Item1, tp.Item2]).OrderBy(g => g.Key).ToList();

            if (positionsByDistance.First().Key == int.MaxValue)
            {
                return(null);
            }

            var closestPosition = positionsByDistance.First().OrderBy(tp => tp.Item2).ThenBy(tp => tp.Item1).First();

            return(closestPosition);
        }
        private List <DBTableInfo> GetTableInfoListHasGetFieldInfo(DataTable dt, IDbConnection con)
        {
            string    queryIndexSqlStr = this.GetQueryIndexSql(null);
            DataTable dtIndex          = base.PrimitiveQueryDataToDataTable(con, queryIndexSqlStr);
            var       indexTupleRowArr = new Tuple <string, DataRow> [dtIndex.Rows.Count];

            for (int i = 0; i < dtIndex.Rows.Count; i++)
            {
                indexTupleRowArr[i] = new Tuple <string, DataRow>(DBAccessEx.ConvertObject <string>(dtIndex.Rows[i]["TABLE_NAME"]), dtIndex.Rows[i]);
            }

            DataRow[]             indexArr;
            var                   tableInfoList = new List <DBTableInfo>();
            string                tableName;
            DBIndexInfoCollection indexInfoCollection = null;

            foreach (DataRow row in dt.Rows)
            {
                tableName           = row[0].ToString();
                indexArr            = indexTupleRowArr.Where(t => { return(string.Equals(t.Item1, tableName)); }).Select(t => { return(t.Item2); }).ToArray();
                indexInfoCollection = this.ConvertTableIndexs(tableName, dtIndex.Columns, indexArr);
                tableInfoList.Add(this.OracleGetTableInfoByName(con, tableName, true, indexInfoCollection, row));
            }

            return(tableInfoList);
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            var _ = Console.ReadLine().Split();
            var n = int.Parse(_[0]);
            var t = int.Parse(_[1]);

            var ary = new Tuple <int, int> [n];

            for (var i = 0; i < n; i++)
            {
                var __ = Console.ReadLine().Split();
                var ci = int.Parse(__[0]);
                var ti = int.Parse(__[1]);
                ary[i] = Tuple.Create(ci, ti);
            }
            var minv = ary.Where(x => x.Item2 <= t);

            if (minv.Any())
            {
                var m = minv.OrderBy(x => x.Item1).First();
                Console.WriteLine(m.Item1);
            }
            else
            {
                Console.WriteLine("TLE");
            }
        }
Beispiel #13
0
 private void shortGhosts()
 {
     for (int i = 0; i < 4; i++)
     {
         List <MapPoint> points = new List <MapPoint>();
         checkGhostPoint(points, i, -1, 0);
         checkGhostPoint(points, i, 1, 0);
         checkGhostPoint(points, i, 0, -1);
         checkGhostPoint(points, i, 0, 1);
         if (points.Count == 1)
         {
             _game.Ghost[i] = points[0];
         }
         else if (points.Count > 0)
         {
             Tuple <int, int>[] values = new Tuple <int, int> [points.Count];
             for (int j = 0; j < values.Length; j++)
             {
                 values[j] = Tuple.Create(shortestPathToPacman(points[j]), j);
             }
             Array.Sort(values, (a, b) => a.Item1 - b.Item1);
             int good = values[0].Item1;
             values         = values.Where(t => t.Item1 == good).ToArray();
             _game.Ghost[i] = points[values[_rnd.Next(values.Length)].Item2];
         }
         else
         {
             _game.Ghost[i] = _game.Trail[i];
         }
     }
 }
Beispiel #14
0
        /// <summary>
        /// Converts the input array into a string of date time strings
        ///
        /// Making it easier to parse but runs in O(n^2) time.
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        private Tuple <DateTime, int>[] convertAllToString(Array array)
        {
            Tuple <DateTime, int>[] resualt = new Tuple <DateTime, int> [array.Length + 1];

            int indexCounter = 0;

            for (int i = 1; i <= array.Length; i++, indexCounter++)
            {
                if (array.GetValue(i, 1) == null)
                {
                    indexCounter--;
                }
                else if (array.GetValue(i, 1) is double)
                {
                    DateTime dateToAdd = DateTime.FromOADate((double)array.GetValue(i, 1));
                    resualt[indexCounter] = Tuple.Create(dateToAdd, i);
                }
                else
                {
                    DateTime temp;
                    if (DateTime.TryParse(((string)array.GetValue(i, 1)), out temp))
                    {
                        resualt[indexCounter] = Tuple.Create(Convert.ToDateTime(array.GetValue(i, 1)), i);
                    }
                    else
                    {
                        indexCounter--;
                    }
                }
            }
            return(resualt = resualt.Where(x => x != null).ToArray());
        }
Beispiel #15
0
        /// <summary>
        /// Read the data from the excel file and return a tuble of tasts and row numbers
        /// </summary>
        /// <param name="ExSheet"></param>
        /// <param name="startingIndex"></param>
        /// <param name="endingIndex"></param>
        /// <returns></returns>
        private Tuple <string, string>[] dataFromFile(Excel.Worksheet ExSheet, int startingIndex, int endingIndex)
        {
            Excel.Range eventRange    = ExSheet.get_Range("B" + startingIndex, "B" + endingIndex);
            Excel.Range buildingRange = ExSheet.get_Range("E" + startingIndex, "E" + endingIndex);

            System.Array eventArray    = (System.Array)eventRange.Cells.Value2;
            System.Array buildingArray = (System.Array)buildingRange.Cells.Value2;

            Tuple <string, string>[] data = new Tuple <string, string> [eventArray.Length];

            int dataCount = 0;

            for (int i = 1; i <= eventArray.GetUpperBound(0); i++)
            {
                if (eventArray.GetValue(i, 1) != null || buildingArray.GetValue(i, 1) != null)
                {
                    data[dataCount] = new Tuple <string, string>(eventArray.GetValue(i, 1).ToString(), buildingArray.GetValue(i, 1).ToString());
                    dataCount++;
                }
            }

            eventRange    = null;
            buildingRange = null;
            return(data = data.Where(x => x != null).ToArray());
        }
        private static ContoursPerSlice GenerateContoursPerSlice(
            Volume3D <byte> volume,
            bool fillContours,
            byte foregroundId,
            SliceType sliceType,
            bool filterEmptyContours,
            Region3D <int> regionOfInterest,
            ContourSmoothingType axialSmoothingType)
        {
            var region = regionOfInterest ?? new Region3D <int>(0, 0, 0, volume.DimX - 1, volume.DimY - 1, volume.DimZ - 1);

            int startPoint;
            int endPoint;

            // Only smooth the output on the axial slices
            var smoothingType = axialSmoothingType;

            switch (sliceType)
            {
            case SliceType.Axial:
                startPoint = region.MinimumZ;
                endPoint   = region.MaximumZ;
                break;

            case SliceType.Coronal:
                startPoint    = region.MinimumY;
                endPoint      = region.MaximumY;
                smoothingType = ContourSmoothingType.None;
                break;

            case SliceType.Sagittal:
                startPoint    = region.MinimumX;
                endPoint      = region.MaximumX;
                smoothingType = ContourSmoothingType.None;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(sliceType), sliceType, null);
            }

            var numberOfSlices  = endPoint - startPoint + 1;
            var arrayOfContours = new Tuple <int, IReadOnlyList <ContourPolygon> > [numberOfSlices];

            for (var i = 0; i < arrayOfContours.Length; i++)
            {
                var z        = startPoint + i;
                var volume2D = ExtractSlice.Slice(volume, sliceType, z);
                var contours = fillContours ?
                               ContoursFilled(volume2D, foregroundId, smoothingType):
                               ContoursWithHoles(volume2D, foregroundId, smoothingType);

                arrayOfContours[i] = Tuple.Create(z, contours);
            }

            return(new ContoursPerSlice(
                       arrayOfContours
                       .Where(x => !filterEmptyContours || x.Item2.Count > 0)
                       .ToDictionary(x => x.Item1, x => x.Item2)));
        }
Beispiel #17
0
 private static double[] DoPla(double[] w, Tuple<double[], double>[] classified)
 {
     var misclassified = classified.Where(t => GetY(w, t.Item1) != t.Item2).ToArray();
       //Console.WriteLine("{0} misclassified.", misclassified.Length);
       //Console.Write(".");
       if (misclassified.Length == 0)
     return w;
       else
     return DoPla(NextW(w, misclassified[R.Next(misclassified.Length)]), classified);
 }
Beispiel #18
0
        public static Func <A, R> MemoizeLast <A, R, K>(this Func <A, R> f, Func <A, K> key, Predicate <R> result)
        {
            var cache = new Tuple <K, R> [0];

            return(a => {
                K k = key(a);
                var r = cache.Where(t => result(t.Item2) && EqualityComparer <K> .Default.Equals(t.Item1, k)).ToArray();
                if (r.Length == 0)
                {
                    r = cache = new[] { Tuple.Create(k, f(a)) }
                }
                ;
                return r[0].Item2;
            });
        }
Beispiel #19
0
        private bool CheckKnight(IBoard board, Side opponentSide, int x, int y)
        {
            var knightMoves = new Tuple <int, int> [8];

            knightMoves[0] = new Tuple <int, int>(x + 1, y + 2);
            knightMoves[1] = new Tuple <int, int>(x + 1, y + -2);
            knightMoves[2] = new Tuple <int, int>(x + -1, y + 2);
            knightMoves[3] = new Tuple <int, int>(x + -1, y + -2);
            knightMoves[4] = new Tuple <int, int>(x + 2, y + 1);
            knightMoves[5] = new Tuple <int, int>(x + 2, y + -1);
            knightMoves[6] = new Tuple <int, int>(x + -2, y + 1);
            knightMoves[7] = new Tuple <int, int>(x + -2, y + -1);

            return(knightMoves.Where(move => (move.Item1 > 0 && move.Item2 > 0 && move.Item1 < 8 && move.Item2 < 8)).Select(move => board.GetPeice(move.Item1, move.Item2)).Any(
                       possibleKnight => possibleKnight != null && !possibleKnight.Side.Equals(opponentSide) &&
                       possibleKnight.Type.Equals(PeiceType.Knight)));
        }
Beispiel #20
0
 private void proxyGhosts()
 {
     for (int i = 0; i < 4; i++)
     {
         List <MapPoint> points = new List <MapPoint>();
         checkGhostPoint(points, i, -1, 0);
         checkGhostPoint(points, i, 1, 0);
         checkGhostPoint(points, i, 0, -1);
         checkGhostPoint(points, i, 0, 1);
         if (points.Count == 1)
         {
             _game.Ghost[i] = points[0];
         }
         else if (points.Count > 2)
         {
             _game.Ghost[i] = points[_rnd.Next(points.Count)];
         }
         else if (points.Count > 0)
         {
             Tuple <int, int>[] values = new Tuple <int, int> [points.Count];
             for (int j = 0; j < values.Length; j++)
             {
                 int v = 0;
                 if ((points[j].Row - _map.Ghost[i].Row) * (_map.Pacman.Row - _map.Ghost[i].Row) > 0)
                 {
                     v++;
                 }
                 if ((points[j].Col - _map.Ghost[i].Col) * (_map.Pacman.Col - _map.Ghost[i].Col) > 0)
                 {
                     v++;
                 }
                 values[j] = Tuple.Create(v, j);
             }
             Array.Sort(values, (a, b) => b.Item1 - a.Item1);
             int good = values[0].Item1;
             values         = values.Where(t => t.Item1 == good).ToArray();
             _game.Ghost[i] = points[values[_rnd.Next(values.Length)].Item2];
         }
         else
         {
             _game.Ghost[i] = _game.Trail[i];
         }
     }
 }
Beispiel #21
0
        internal Point GetModeLocation(Gamemode mode, OWEvent owevent) // Gets the location of a gamemode in Settings/Modes
        {
            // Ordered by how the gamemodes are listed in Overwatch at Settings/Modes
            var gamemodes = new Tuple <Gamemode, OWEvent>[]
            {
                // Default modes are listed first in alphabetical order.
                new Tuple <Gamemode, OWEvent>(Gamemode.Assault, OWEvent.None),
                new Tuple <Gamemode, OWEvent>(Gamemode.AssaultEscort, OWEvent.None),
                new Tuple <Gamemode, OWEvent>(Gamemode.Control, OWEvent.None),
                new Tuple <Gamemode, OWEvent>(Gamemode.Escort, OWEvent.None),

                // Followed by Mei's Snowball Offensive, which goes against the normal order for some reason.
                new Tuple <Gamemode, OWEvent>(Gamemode.MeisSnowballOffensive, OWEvent.WinterWonderland),

                // Then the rest in alphabetical order, except for skirmish.
                new Tuple <Gamemode, OWEvent>(Gamemode.CaptureTheFlag, OWEvent.None),
                new Tuple <Gamemode, OWEvent>(Gamemode.Deathmatch, OWEvent.None),
                new Tuple <Gamemode, OWEvent>(Gamemode.Elimination, OWEvent.None),
                new Tuple <Gamemode, OWEvent>(Gamemode.JunkensteinsRevenge, OWEvent.HalloweenTerror),
                new Tuple <Gamemode, OWEvent>(Gamemode.Lucioball, OWEvent.SummerGames),
                new Tuple <Gamemode, OWEvent>(Gamemode.TeamDeathmatch, OWEvent.None),
                new Tuple <Gamemode, OWEvent>(Gamemode.YetiHunter, OWEvent.WinterWonderland),

                // Skirmish is always last.
                new Tuple <Gamemode, OWEvent>(Gamemode.Skirmish, OWEvent.None)
            };

            int modeIndex = Array.IndexOf(gamemodes
                                          .Where(m => m.Item2 == OWEvent.None || m.Item2 == owevent)
                                          .Select(m => m.Item1)
                                          .ToArray()
                                          , mode) + 1;

            if (modeIndex == 0)
            {
                return(Point.Empty);
            }

            int[] columns = new int[] { 83, 227, 370, 515 };

            return(new Point(columns[modeIndex % 4], 129 + modeIndex / 4 * 107));
        }
Beispiel #22
0
        private IEnumerable <ChessPosition> getStandardDrawPositions(ChessPosition position)
        {
            // get positions next to the current position of the king (all permutations of { -1, 0, +1 }^2 except (0, 0))
            var coords = new Tuple <int, int>[]
            {
                new Tuple <int, int>(position.Row - 1, position.Column - 1),
                new Tuple <int, int>(position.Row - 1, position.Column),
                new Tuple <int, int>(position.Row - 1, position.Column + 1),
                new Tuple <int, int>(position.Row, position.Column - 1),
                new Tuple <int, int>(position.Row, position.Column + 1),
                new Tuple <int, int>(position.Row + 1, position.Column - 1),
                new Tuple <int, int>(position.Row + 1, position.Column),
                new Tuple <int, int>(position.Row + 1, position.Column + 1),
            };

            // only retrieve positions that are actually onto the chess board (and not off scale)
            var positions = coords.Where(x => ChessPosition.AreCoordsValid(x)).Select(x => new ChessPosition(x.Item1, x.Item2));

            return(positions);
        }
Beispiel #23
0
        /// <summary>
        /// Compute the field positions that can be captured by the given chess piece.
        /// </summary>
        /// <param name="board">The chess board representing the game situation</param>
        /// <param name="drawingPiecePosition">The chess position of the chess piece to be drawn</param>
        /// <param name="precedingEnemyDraw">The last draw made by the opponent</param>
        /// <param name="analyzeDrawIntoCheck">Indicates whether drawing into a check situation should be analyzed</param>
        /// <returns>a list of all possible chess draws</returns>
        public IEnumerable <ChessDraw> GetDraws(IChessBoard board, ChessPosition drawingPiecePosition, ChessDraw?precedingEnemyDraw = null, bool analyzeDrawIntoCheck = false)
        {
            var piece = board.GetPieceAt(drawingPiecePosition);

            // make sure the chess piece is a knight
            if (piece.Type != ChessPieceType.Knight)
            {
                throw new InvalidOperationException("The chess piece is not a knight.");
            }

            // get positions next to the current position of the king (all permutations of { -1, 0, +1 }^2 except (0, 0))
            var coords = new Tuple <int, int>[]
            {
                new Tuple <int, int>(drawingPiecePosition.Row - 2, drawingPiecePosition.Column - 1),
                new Tuple <int, int>(drawingPiecePosition.Row - 2, drawingPiecePosition.Column + 1),
                new Tuple <int, int>(drawingPiecePosition.Row - 1, drawingPiecePosition.Column - 2),
                new Tuple <int, int>(drawingPiecePosition.Row - 1, drawingPiecePosition.Column + 2),
                new Tuple <int, int>(drawingPiecePosition.Row + 1, drawingPiecePosition.Column - 2),
                new Tuple <int, int>(drawingPiecePosition.Row + 1, drawingPiecePosition.Column + 2),
                new Tuple <int, int>(drawingPiecePosition.Row + 2, drawingPiecePosition.Column - 1),
                new Tuple <int, int>(drawingPiecePosition.Row + 2, drawingPiecePosition.Column + 1),
            };

            // only retrieve positions that are actually onto the chess board (and not off scale)
            var positions = coords.Where(x => ChessPosition.AreCoordsValid(x)).Select(x => new ChessPosition(x));

            // do not draw into positions captured by allied chess pieces
            positions = positions.Where(x => !board.IsCapturedAt(x) || board.GetPieceAt(x).Color != piece.Color);

            // transform positions to chess draws
            var draws = positions.Select(newPos => new ChessDraw(board, drawingPiecePosition, newPos));

            if (analyzeDrawIntoCheck && draws?.Count() > 0)
            {
                // remove draws that would draw into a check situation
                draws = draws.Where(x => !ChessDrawSimulator.Instance.IsDrawIntoCheck(board, x));
            }

            return(draws);
        }
Beispiel #24
0
    static long Solve()
    {
        int n = int.Parse(Console.ReadLine());

        Tuple <long, long>[] cost = new Tuple <long, long>[]
        {
            new Tuple <long, long>(-1, 0),
            new Tuple <long, long>(-1, 0),
            new Tuple <long, long>(-1, 0)
        };
        for (int i = 0; i < n; i++)
        {
            var ab = Console.ReadLine().Split().Select(int.Parse).ToArray();
            Tuple <long, long>[] newcost = new Tuple <long, long> [3];
            for (int j = 0; j < 3; j++)
            {
                newcost[j] = new Tuple <long, long>(ab[0] + j, cost.Where(x => x.Item1 != ab[0] + j).Min(x => x.Item2) + ab[1] * j);
            }
            cost = newcost;
        }
        return(cost.Min(x => x.Item2));
    }
Beispiel #25
0
        //return Tuple<double, double, double> for each box start m/z, end m/z, m/z length
        public static void GenerateDynamicBoxes_BU(List <IsoEnvelop> isoEnvelops, Parameters parameters, List <List <Tuple <double, double, double> > > boxes)
        {
            //var thred = isoEnvelops.OrderByDescending(p => p.IntensityRatio).First().IntensityRatio / 20;
            var mzs = isoEnvelops.Where(p => p.Mz > parameters.BoxCarScanSetting.BoxCarMzRangeLowBound &&
                                        p.Mz < parameters.BoxCarScanSetting.BoxCarMzRangeHighBound).OrderBy(p => p.TotalIntensity).Take(30).Select(p => p.ExperimentIsoEnvelop.First().Mz).OrderBy(p => p).ToArray();

            Tuple <double, double, double>[] ranges = new Tuple <double, double, double> [mzs.Length + 1];

            ranges[0] = new Tuple <double, double, double>(parameters.BoxCarScanSetting.BoxCarMzRangeLowBound, mzs[0], mzs[0] - parameters.BoxCarScanSetting.BoxCarMzRangeLowBound);
            for (int i = 1; i < mzs.Length; i++)
            {
                ranges[i] = new Tuple <double, double, double>(mzs[i - 1], mzs[i], mzs[i] - mzs[i - 1]);
            }

            ranges[mzs.Length] = new Tuple <double, double, double>(mzs.Last(), parameters.BoxCarScanSetting.BoxCarMzRangeHighBound, parameters.BoxCarScanSetting.BoxCarMzRangeHighBound - mzs.Last());

            for (int i = 0; i < parameters.BoxCarScanSetting.NumberOfBoxCarScans; i++)
            {
                var tuples = new List <Tuple <double, double, double> >();
                boxes.Add(tuples);
            }


            int j = 0;

            foreach (var r in ranges.Where(p => p.Item3 > 3)) //If the range is too small, say 5, there is no need to place a box between.
            {
                if (j <= parameters.BoxCarScanSetting.NumberOfBoxCarScans - 1)
                {
                    boxes[j].Add(r);
                    j++;
                }
                else
                {
                    j = 0;
                }
            }
        }
                private static List<Tuple<Point, Point>> StitchSegmentsSprtCleanup_EXTENDCOLINEAR(Tuple<Point, Point>[] lineSegments)
                {
                    // Remove single vertex matches
                    var deduped = lineSegments.Where(o => !Math2D.IsNearValue(o.Item1, o.Item2)).ToList();



                    // Remove double T joints (happens when two polygons are butted up next to each other.  Need to get rid of that middle segment)



                    // Removing colinear should be optional, it's an expense that may not be desired
                    bool merged = false;
                    do
                    {
                        // Find segment pairs that are colienar, and convert to a single segment (but only if they have no other segments using the point
                        // to be deleted)






                    } while (merged);









                    return null;

                }
 private static void AssertReceivedTimes(Tuple<string, TimeSpan>[] changes, string id, int[] expectedReceivedSeconds)
 {
     var seconds = changes.Where(t => t.Item1 == id)
         .Select(t => (int)Math.Floor(t.Item2.TotalSeconds)).ToArray();
     seconds.ShouldAllBeEquivalentTo(expectedReceivedSeconds);
 }
Beispiel #28
0
 public static long LongCount <T1>(this Tuple <T1> value, Func <object, Boolean> predicate)
 {
     Contract.Requires <ArgumentNullException>(value != null);
     Contract.Requires <ArgumentNullException>(predicate != null);
     return(value.Where(predicate).LongCount());
 }
 private static string[] getLocationsOfObjectsThatBelongToCategory(Dictionary<string, Category> categoriesToTransfer, Tuple<string, List<Category>, List<MediaContent>>[] locationCategoriesTuplesWithMedia)
 {
     var resultLocations = locationCategoriesTuplesWithMedia.Where(tuple => tuple.Item2.Any(cat => categoriesToTransfer.ContainsKey(cat.ID)))
                                                 .SelectMany(tuple =>
                                                     {
                                                         List<string> joiningValues = new List<string>();
                                                         joiningValues.Add(tuple.Item1);
                                                         joiningValues.AddRange(tuple.Item3.Select(mc => mc.RelativeLocation));
                                                         return joiningValues.ToArray();
                                                     }).ToArray();
     return resultLocations;
 }
            /// <summary>
            /// This adds ioIndex to one of finalLinks
            /// </summary>
            /// <param name="closestBrainIndex">Index of the brain that is closest to the IO.  There is no extra burden for linking to this one</param>
            /// <param name="brainBrainBurdens">
            /// Item1=Index of other brain
            /// Item2=Link resistance (burden) between closestBrainIndex and this brain
            /// </param>
            private static void AddIOLink(BrainBurden[] finalLinks, int ioIndex, double ioSize, int closestBrainIndex, Tuple<int, double>[] brainBrainBurdens)
            {
                // Figure out the cost of adding the link to the various brains
                Tuple<int, double>[] burdens = new Tuple<int, double>[finalLinks.Length];

                for (int cntr = 0; cntr < finalLinks.Length; cntr++)
                {
                    int brainIndex = finalLinks[cntr].Index;        // this is likely always the same as cntr, but since that object has brainIndex as a property, I feel safer using it

                    // Adding to the closest brain has no exta cost.  Adding to any other brain has a cost based on the
                    // distance between the closest brain and that other brain
                    double linkCost = 0d;
                    if (brainIndex != closestBrainIndex)
                    {
                        //TODO: Link every brain to every other brain, then get rid of this if statement
                        var matchingBrain = brainBrainBurdens.FirstOrDefault(o => o.Item1 == brainIndex);
                        if (matchingBrain == null)
                        {
                            continue;
                        }

                        linkCost = matchingBrain.Item2;
                    }

                    // LinkCost + IOStorageCost
                    burdens[cntr] = Tuple.Create(cntr, linkCost + BrainBurden.CalculateBurden(finalLinks[cntr].IOSize + ioSize, finalLinks[cntr].Size));
                }

                int cheapestIndex = burdens.
                    Where(o => o != null).
                    OrderBy(o => o.Item2).First().Item1;

                finalLinks[cheapestIndex].AddIOLink(ioIndex);
            }
Beispiel #31
0
		private IEnumerable<Tuple<IndexToWorkOn, IndexingBatch>> FilterIndexes(IList<IndexToWorkOn> indexesToWorkOn, JsonDocument[] jsonDocs)
		{
			var last = jsonDocs.Last();

			Debug.Assert(last.Etag != null);
			Debug.Assert(last.LastModified != null);

			var lastEtag = last.Etag.Value;
			var lastModified = last.LastModified.Value;

			var lastIndexedEtag = new ComparableByteArray(lastEtag.ToByteArray());

			var documentRetriever = new DocumentRetriever(null, context.ReadTriggers);

			var filteredDocs =
				BackgroundTaskExecuter.Instance.Apply(context, jsonDocs, doc =>
				{
					var filteredDoc = documentRetriever.ExecuteReadTriggers(doc, null, ReadOperation.Index);
					return filteredDoc == null ? new
					{
						Doc = doc,
						Json = (object)new FilteredDocument(doc)
					} : new
					{
						Doc = filteredDoc,
						Json = JsonToExpando.Convert(doc.ToJson())
					};
				});

			Log.Debug("After read triggers executed, {0} documents remained", filteredDocs.Count);

			var results = new Tuple<IndexToWorkOn, IndexingBatch>[indexesToWorkOn.Count];
			var actions = new Action<IStorageActionsAccessor>[indexesToWorkOn.Count];

			BackgroundTaskExecuter.Instance.ExecuteAll(context, indexesToWorkOn, (indexToWorkOn, i) =>
			{
				var indexLastInedexEtag = new ComparableByteArray(indexToWorkOn.LastIndexedEtag.ToByteArray());
				if (indexLastInedexEtag.CompareTo(lastIndexedEtag) >= 0)
					return;

				var indexName = indexToWorkOn.IndexName;
				var viewGenerator = context.IndexDefinitionStorage.GetViewGenerator(indexName);
				if (viewGenerator == null)
					return; // probably deleted

				var batch = new IndexingBatch();

				foreach (var item in filteredDocs)
				{
					if (FilterDocuments(item.Doc))
						continue;

					// did we already indexed this document in this index?
					var etag = item.Doc.Etag;
					if (etag == null)
						continue;

					if (indexLastInedexEtag.CompareTo(new ComparableByteArray(etag.Value.ToByteArray())) >= 0)
						continue;


					// is the Raven-Entity-Name a match for the things the index executes on?
					if (viewGenerator.ForEntityNames.Count != 0 &&
						viewGenerator.ForEntityNames.Contains(item.Doc.Metadata.Value<string>(Constants.RavenEntityName)) == false)
					{
						continue;
					}

					batch.Add(item.Doc, item.Json);

					if (batch.DateTime == null)
						batch.DateTime = item.Doc.LastModified;
					else
						batch.DateTime = batch.DateTime > item.Doc.LastModified
											? item.Doc.LastModified
											: batch.DateTime;
				}

				if (batch.Docs.Count == 0)
				{
					Log.Debug("All documents have been filtered for {0}, no indexing will be performed, updating to {1}, {2}", indexName,
						lastEtag, lastModified);
					// we use it this way to batch all the updates together
					actions[i] = accessor => accessor.Indexing.UpdateLastIndexed(indexName, lastEtag, lastModified);
					return;
				}
				if (Log.IsDebugEnabled)
				{
					Log.Debug("Going to index {0} documents in {1}: ({2})", batch.Ids.Count, indexToWorkOn, string.Join(", ", batch.Ids));
				}
				results[i] = Tuple.Create(indexToWorkOn, batch);

			});

			transactionalStorage.Batch(actionsAccessor =>
			{
				foreach (var action in actions)
				{
					if (action != null)
						action(actionsAccessor);
				}
			});

			return results.Where(x => x != null);
		}
Beispiel #32
0
        public Searchspace GenerateSolution(SolutionParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            var result = new Searchspace(new Vector2(parameters.Width, parameters.Height));

            var buildings = parameters.BuildingPositions.Select((kvp) => new ProductionBuilding(kvp.Key.Recipe, kvp.Key.Amount, kvp.Key.Building, kvp.Value.Item1, kvp.Value.Item2));

            foreach (var building in buildings)
            {
                result = result.AddComponent(building);
            }

            var belts = new Dictionary <Item, List <RoutingCoordinate> >();
            List <Tuple <IStep, Item, bool> > todo = parameters.Connections.ToList();

            while (todo.Count != 0)
            {
                Preview = result;

                var connection = todo[0];
                todo.RemoveAt(0);

                var isDestination = connection.Item3;

                var prev = result;

                if (belts.ContainsKey(connection.Item2))
                {
                    IEnumerable <RoutingCoordinate> sources      = new RoutingCoordinate[] { };
                    IEnumerable <RoutingCoordinate> destinations = new RoutingCoordinate[] { };

                    //TODO: fix itemAmount
                    //TODO: fix fluids
                    if (connection.Item2.ItemType == ItemType.Solid)
                    {
                        if (isDestination)
                        {
                            sources      = belts[connection.Item2];
                            destinations = BuildingToPlaceables(connection.Item1, parameters);
                        }
                        else
                        {
                            sources      = BuildingToPlaceables(connection.Item1, parameters);
                            destinations = belts[connection.Item2];
                        }

                        result = SolidRouter.Route(new ItemAmount(connection.Item2, 1), result, sources, destinations);
                    }
                }
                else
                {
                    var firstMatching = todo.Where((t) => t.Item2 == connection.Item2 && t.Item3 != connection.Item3).First();
                    todo.Remove(firstMatching);
                    var both = new Tuple <IStep, Item, bool>[] { connection, firstMatching };

                    var source      = both.Where((c) => c.Item3 == false).First();
                    var destination = both.Where((c) => c.Item3 == true).First();

                    if (connection.Item2.ItemType == ItemType.Solid)
                    {
                        var sources      = BuildingToPlaceables(source.Item1, parameters);
                        var destinations = BuildingToPlaceables(destination.Item1, parameters);
                        result = SolidRouter.Route(new ItemAmount(connection.Item2, 1), result, sources, destinations);
                    }

                    if (connection.Item2.ItemType == ItemType.Fluid)
                    {
                        var sources      = BuildingToPipes(source.Item1, parameters, connection.Item2);
                        var destinations = BuildingToPipes(destination.Item1, parameters, connection.Item2);
                        result = FluidRouter.Route(new ItemAmount(connection.Item2, 1), result, sources, destinations);
                    }
                }

                if (!belts.ContainsKey(connection.Item2))
                {
                    belts[connection.Item2] = new List <RoutingCoordinate>();
                }
                belts[connection.Item2].AddRange(RoutesToCoords(prev, result));
            }

            return(result);
        }
Beispiel #33
0
        private void SetEntityState(EntityState newState, Tuple<IProperty, object>[] generatedValues)
        {
            // The entity state can be Modified even if some properties are not modified so always
            // set all properties to modified if the entity state is explicitly set to Modified.
            if (newState == EntityState.Modified)
            {
                _stateData.SetAllPropertiesModified(_entityType.Properties.Count(), isModified: true);

                // Assuming key properties are not modified
                foreach (var keyProperty in EntityType.GetKey().Properties)
                {
                    _stateData.SetPropertyModified(keyProperty.Index, isModified: false);
                }
            }
            else if (newState == EntityState.Unchanged)
            {
                _stateData.SetAllPropertiesModified(_entityType.Properties.Count(), isModified: false);
            }

            var oldState = _stateData.EntityState;
            if (oldState == newState)
            {
                return;
            }

            // An Added entity does not yet exist in the database. If it is then marked as deleted there is
            // nothing to delete because it was not yet inserted, so just make sure it doesn't get inserted.
            if (oldState == EntityState.Added
                && newState == EntityState.Deleted)
            {
                newState = EntityState.Unknown;
            }

            _configuration.Services.StateEntryNotifier.StateChanging(this, newState);

            if (newState == EntityState.Added)
            {
                foreach (var generatedValue in generatedValues.Where(v => v != null && v.Item2 != null))
                {
                    this[generatedValue.Item1] = generatedValue.Item2;
                }
            }
            else
            {
                Contract.Assert(generatedValues == null);
            }

            _stateData.EntityState = newState;

            if (oldState == EntityState.Unknown)
            {
                _configuration.StateManager.StartTracking(this);
            }
            else if (newState == EntityState.Unknown)
            {
                // TODO: Does changing to Unknown really mean stop tracking?
                _configuration.StateManager.StopTracking(this);
            }

            _configuration.Services.StateEntryNotifier.StateChanged(this, oldState);
        }
        private void btnPolyUnionTest4_Click(object sender, RoutedEventArgs e)
        {

            // The main problem is that lines are slicing through the entire polygon.  Need to detect that, also get rid of colinear points

            try
            {
                ClearAllVisuals();

                Point3D[][] initial3D = new Point3D[3][];

                initial3D[0] = new Point3D[] {
                    new Point3D(-16.1947246550931,-0.9149519332283,2.55976103387392),
                    new Point3D(-17.1107881600685,0.515445435128346,3.40133335668073),
                    new Point3D(-17.3596515210729,-0.829632679480615,4.42103762371103),
                    new Point3D(-17.3450427909807,-2.19357445878095,5.01957844043668),
                    new Point3D(-17.3283385073944,-2.17500700982897,4.98385833288751) };

                initial3D[1] = new Point3D[] {
                    new Point3D(-16.1947246550931,-0.914951933228302,2.55976103387392),
                    new Point3D(-17.3283385073944,-2.17500700982897,4.9838583328875),
                    new Point3D(-17.3450427909807,-2.19357445878095,5.01957844043668),
                    new Point3D(-17.341448388578,-2.52916527179157,5.16684630945675),
                    new Point3D(-15.3066235822732,-2.3016870563904,1.74387733292857) };

                initial3D[2] = new Point3D[] {
                    new Point3D(-17.3204018787836,-4.49416933689273,6.02915227870288),
                    new Point3D(-16.4203453178512,-4.5492595275131,4.58613381891047),
                    new Point3D(-14.928909934653,-2.89147215820253,1.39687808008519),
                    new Point3D(-15.3066235822732,-2.3016870563904,1.74387733292857),
                    new Point3D(-17.341448388578,-2.52916527179157,5.16684630945675) };

                // Create some random triangles
                Point[][] initialPolys = new Point[3][];

                initialPolys[0] = new Point[] {
                    new Point(-1.70753174254516,-10.6978382660948),
                    new Point(-0.726945738693094,-12.3201526746214),
                    new Point(-2.36588629353582,-12.7943243278674),
                    new Point(-3.85545055921974,-12.7943243278674),
                    new Point(-3.82425967044327,-12.7638803171038) };

                initialPolys[1] = new Point[] {
                    new Point(-1.70753174254517,-10.6978382660948),
                    new Point(-3.82425967044327,-12.7638803171038),
                    new Point(-3.85545055921974,-12.7943243278674),
                    new Point(-4.22195013459667,-12.7943243278674),
                    new Point(-2.65818579358351,-9.1250442852861) };

                initialPolys[2] = new Point[] {
                    new Point(-6.36793604229414,-12.7943243278674),
                    new Point(-5.84736974693176,-11.1743089731826),
                    new Point(-3.06250352298613,-8.45612745855601),
                    new Point(-2.65818579358351,-9.1250442852861),
                    new Point(-4.22195013459667,-12.7943243278674) };



                var feedsIntermediate = new Tuple<double, double, double, double>[]
                {
                    Tuple.Create(-1.70753174254516, -10.6978382660948, -0.726945738693094, -12.3201526746214),      //0
                    Tuple.Create(-0.726945738693094, -12.3201526746214, -2.36588629353582, -12.7943243278674),      //1
                    Tuple.Create(-2.36588629353582, -12.7943243278674, -3.85545055921974, -12.7943243278674),       //2
                    Tuple.Create(-3.85545055921974, -12.7943243278674, -3.82425967044327, -12.7638803171038),       //3
                    Tuple.Create(-3.82425967044327, -12.7638803171038, -1.70753174254516, -10.6978382660948),       //4
                    Tuple.Create(-1.70753174254517, -10.6978382660948, -3.82425967044327, -12.7638803171038),       //5
                    Tuple.Create(-3.82425967044327, -12.7638803171038, -3.85545055921974, -12.7943243278674),       //6
                    Tuple.Create(-3.85545055921974, -12.7943243278674, -4.22195013459667, -12.7943243278674),       //7
                    Tuple.Create(-4.22195013459667, -12.7943243278674, -2.65818579358351, -9.1250442852861),       //8
                    Tuple.Create(-2.65818579358351, -9.1250442852861, -1.70753174254517, -10.6978382660948),       //9
                    Tuple.Create(-6.36793604229414, -12.7943243278674, -5.84736974693176, -11.1743089731826),       //10
                    Tuple.Create(-5.84736974693176, -11.1743089731826, -3.06250352298613, -8.45612745855601),       //11
                    Tuple.Create(-3.06250352298613, -8.45612745855601, -2.65818579358351, -9.1250442852861),       //12
                    Tuple.Create(-2.65818579358351, -9.1250442852861, -4.22195013459667, -12.7943243278674),       //13
                    Tuple.Create(-4.22195013459667, -12.7943243278674, -6.36793604229414, -12.7943243278674)       //14
                }.Select(o => Tuple.Create(new Point(o.Item1, o.Item2), new Point(o.Item3, o.Item4))).ToArray();

                #region feeds intermediate dupes

                // Simplify duplication chains:
                //      Any point should only have one other match in the list
                //      If there is more than one match, the list should be able to be simplified

                List<Point> uniquePoints = new List<Point>();
                foreach (Point point in UtilityCore.Iterate(feedsIntermediate.Select(o => o.Item1), feedsIntermediate.Select(o => o.Item2)))
                {
                    if (!uniquePoints.Any(o => Math2D.IsNearValue(point, o)))
                    {
                        uniquePoints.Add(point);
                    }
                }

                var matchAttempt = uniquePoints
                    .Select(o => new { Point = o, Matches = feedsIntermediate.Where(p => Math2D.IsNearValue(o, p.Item1) || Math2D.IsNearValue(o, p.Item2)).ToArray() }).
                    OrderByDescending(o => o.Matches.Length).
                    ToArray();


                Tuple<Point, Point>[] feeds2 = feedsIntermediate.Select(o => o.Item1.X < o.Item2.X ? o : Tuple.Create(o.Item2, o.Item1)).ToArray();

                List<Tuple<Point, Point>> feeds3 = new List<Tuple<Point, Point>>();
                foreach (var feed in feeds2)
                {
                    if (!feeds3.Any(o => Math2D.IsNearValue(feed.Item1, o.Item1) && Math2D.IsNearValue(feed.Item2, o.Item2)))
                    {
                        feeds3.Add(feed);
                    }
                }


                var matchAttempt2 = uniquePoints
                    .Select(o => new { Point = o, Matches = feeds3.Where(p => Math2D.IsNearValue(o, p.Item1) || Math2D.IsNearValue(o, p.Item2)).ToArray() }).
                    OrderByDescending(o => o.Matches.Length).
                    ToArray();


                #endregion

                // This is what StitchSegments generates (should have just come up with one poly)
                Point[][] intermediate = new Point[1][];

                intermediate[0] = new Point[] {
                    new Point(-1.70753174254516,-10.6978382660948),     //0
                    new Point(-0.726945738693094,-12.3201526746214),        //1
                    new Point(-2.36588629353582,-12.7943243278674),     //2
                    new Point(-3.85545055921974,-12.7943243278674),     //3
                    new Point(-3.82425967044327,-12.7638803171038),     //4
                    new Point(-1.70753174254517,-10.6978382660948),     //5
                    new Point(-3.82425967044327,-12.7638803171038),     //6
                    new Point(-3.85545055921974,-12.7943243278674),     //7
                    new Point(-4.22195013459667,-12.7943243278674),     //8
                    new Point(-2.65818579358351,-9.1250442852861) };        //9

                //intermediate[1] = new Point[] {
                //    new Point(-6.36793604229414,-12.7943243278674),
                //    new Point(-5.84736974693176,-11.1743089731826),
                //    new Point(-3.06250352298613,-8.45612745855601),
                //    new Point(-2.65818579358351,-9.1250442852861),
                //    new Point(-4.22195013459667,-12.7943243278674) };

                #region intermediate distances

                List<Tuple<int, int, double, bool>> distances = new List<Tuple<int, int, double, bool>>();
                for (int outer = 0; outer < intermediate[0].Length - 1; outer++)
                {
                    for (int inner = outer + 1; inner < intermediate[0].Length; inner++)
                    {
                        double distance = (intermediate[0][outer] - intermediate[0][inner]).Length;

                        distances.Add(Tuple.Create(outer, inner, distance, Math1D.IsNearZero(distance)));
                    }
                }

                distances = distances.OrderBy(o => o.Item3).ToList();

                #endregion

                // Separate into islands
                Polygon2D[] finalPolys = null;
                try
                {
                    finalPolys = GetPolyUnion(initialPolys);
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
                    finalPolys = new Polygon2D[0];
                }

                #region Draw

                Visual3D visual;

                // Lines
                foreach (Point[] polygon in initialPolys)
                {
                    visual = GetVisual_PolygonLines(polygon.Select(o => o.ToPoint3D(-2)).ToArray(), Colors.Gray, 1);
                    _debugVisuals.Add(visual);
                    _viewport.Children.Add(visual);
                }


                foreach (Point[] polygon in intermediate)
                {
                    visual = GetVisual_PolygonLines(polygon.Select(o => o.ToPoint3D(0)).ToArray(), Colors.Gray, 2);
                    _debugVisuals.Add(visual);
                    _viewport.Children.Add(visual);
                }


                for (int cntr = 0; cntr < intermediate[0].Length; cntr++)
                {
                    visual = GetVisual_Dot(intermediate[0][cntr].ToPoint3D(2), .02 + (cntr * .01), UtilityWPF.GetColorEGA(64, cntr));
                    _debugVisuals.Add(visual);
                    _viewport.Children.Add(visual);
                }


                //foreach (Point3D[] poly in initial3D)
                //{
                //    visual = GetPolygonLinesVisual(poly, Colors.Black, 1);
                //    _debugVisuals.Add(visual);
                //    _viewport.Children.Add(visual);
                //}


                foreach (Polygon2D polygon in finalPolys)
                {
                    visual = GetVisual_PolygonLines(polygon.Polygon.Select(o => o.ToPoint3D(2)).ToArray(), Colors.Black, 2);
                    _debugVisuals.Add(visual);
                    _viewport.Children.Add(visual);

                    foreach (Point[] hole in polygon.Holes)
                    {
                        visual = GetVisual_PolygonLines(hole.Select(o => o.ToPoint3D(2)).ToArray(), Colors.Red, 2);
                        _debugVisuals.Add(visual);
                        _viewport.Children.Add(visual);
                    }
                }

                // Polygons
                //foreach (Point[] polygon in finalPolys)       // can't do these, they are concave
                //foreach (Point[] polygon in initialPolys)
                for (int cntr = 0; cntr < initialPolys.Length; cntr++)
                {
                    Color color = UtilityWPF.GetColorEGA(10, cntr);
                    //Color color = Color.FromArgb(10, Convert.ToByte(StaticRandom.Next(256)), Convert.ToByte(StaticRandom.Next(256)), Convert.ToByte(StaticRandom.Next(256)));

                    visual = GetVisual_Polygon_Convex(initialPolys[cntr].Select(o => o.ToPoint3D()).ToArray(), color);
                    _debugVisuals.Add(visual);
                    _viewport.Children.Add(visual);
                }

                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
 private static List<Tuple<Point, Point>> StitchSegmentsSprtCleanup(Tuple<Point, Point>[] lineSegments)
 {
     // Remove single vertex matches
     return lineSegments.Where(o => !Math2D.IsNearValue(o.Item1, o.Item2)).ToList();
 }
Beispiel #36
0
 private IValueProvider[] TrySelectDefault(Tuple<IValueProvider, IProbe>[] itemsWithHighestScore, int max)
 {
     var defaultValueProviders = itemsWithHighestScore.Where(x => x.Item2.ExplicitPositiveReferencesCount == 0 && x.Item2.ReferencesCount == 0).Select(x => x.Item1).ToArray();
     if (defaultValueProviders.Count() == 1)
     {
         return new[] { defaultValueProviders.Single()};
     }
     throw new ItemsWithConflictingHighestScoreException(itemsWithHighestScore, max);
 }
            private static Point[] StitchSegments(Tuple<Point, Point>[] lineSegments)
            {
                // Need to remove single vertex matches, or the loop below will have problems
                var fixedSegments = lineSegments.Where(o => !Math2D.IsNearValue(o.Item1, o.Item2)).ToList();
                if (fixedSegments.Count == 0)
                {
                    return null;
                }

                List<Point> retVal = new List<Point>();

                // Stitch the segments together into a polygon
                retVal.Add(fixedSegments[0].Item1);
                Point currentPoint = fixedSegments[0].Item2;
                fixedSegments.RemoveAt(0);

                while (fixedSegments.Count > 0)
                {
                    var match = FindAndRemoveMatchingSegment(fixedSegments, currentPoint);
                    if (match == null)
                    {
                        //TODO: If this becomes an issue, make a method that builds fragments, then the final polygon will hop from fragment to fragment
                        //TODO: Or, use Math2D.GetConvexHull - make an overload that rotates the points into the xy plane
                        //throw new ApplicationException("The hull passed in has holes in it");
                        return null;
                    }

                    retVal.Add(match.Item1);
                    currentPoint = match.Item2;
                }

                if (!Math2D.IsNearValue(retVal[0], currentPoint))
                {
                    //throw new ApplicationException("The hull passed in has holes in it");
                    return null;
                }

                if (retVal.Count < 3)
                {
                    return null;
                }

                // Exit Function
                return retVal.ToArray();
            }
        private IEnumerable <Tuple <IndexToWorkOn, IndexingBatch> > FilterIndexes(IList <IndexToWorkOn> indexesToWorkOn, JsonDocument[] jsonDocs)
        {
            var last = jsonDocs.Last();

            Debug.Assert(last.Etag != null);
            Debug.Assert(last.LastModified != null);

            var lastEtag     = last.Etag.Value;
            var lastModified = last.LastModified.Value;

            var lastIndexedEtag = new ComparableByteArray(lastEtag.ToByteArray());

            var documentRetriever = new DocumentRetriever(null, context.ReadTriggers);

            var filteredDocs =
                BackgroundTaskExecuter.Instance.Apply(jsonDocs, doc =>
            {
                doc = documentRetriever.ExecuteReadTriggers(doc, null, ReadOperation.Index);
                return(doc == null ? null : new { Doc = doc, Json = JsonToExpando.Convert(doc.ToJson()) });
            });

            log.Debug("After read triggers executed, {0} documents remained", filteredDocs.Count);

            var results = new Tuple <IndexToWorkOn, IndexingBatch> [indexesToWorkOn.Count];
            var actions = new Action <IStorageActionsAccessor> [indexesToWorkOn.Count];

            BackgroundTaskExecuter.Instance.ExecuteAll(context.Configuration, scheduler, indexesToWorkOn, (indexToWorkOn, i) =>
            {
                var indexLastInedexEtag = new ComparableByteArray(indexToWorkOn.LastIndexedEtag.ToByteArray());
                if (indexLastInedexEtag.CompareTo(lastIndexedEtag) >= 0)
                {
                    return;
                }

                var indexName     = indexToWorkOn.IndexName;
                var viewGenerator = context.IndexDefinitionStorage.GetViewGenerator(indexName);
                if (viewGenerator == null)
                {
                    return;                     // probably deleted
                }
                var batch = new IndexingBatch();

                foreach (var item in filteredDocs)
                {
                    // did we already indexed this document in this index?
                    if (indexLastInedexEtag.CompareTo(new ComparableByteArray(item.Doc.Etag.Value.ToByteArray())) >= 0)
                    {
                        continue;
                    }


                    // is the Raven-Entity-Name a match for the things the index executes on?
                    if (viewGenerator.ForEntityNames.Count != 0 &&
                        viewGenerator.ForEntityNames.Contains(item.Doc.Metadata.Value <string>(Constants.RavenEntityName)) == false)
                    {
                        continue;
                    }

                    batch.Add(item.Doc, item.Json);

                    if (batch.DateTime == null)
                    {
                        batch.DateTime = item.Doc.LastModified;
                    }
                    else
                    {
                        batch.DateTime = batch.DateTime > item.Doc.LastModified
                                                                        ? item.Doc.LastModified
                                                                        : batch.DateTime;
                    }
                }

                if (batch.Docs.Count == 0)
                {
                    log.Debug("All documents have been filtered for {0}, no indexing will be performed, updating to {1}, {2}", indexName,
                              lastEtag, lastModified);
                    // we use it this way to batch all the updates together
                    actions[i] = accessor => accessor.Indexing.UpdateLastIndexed(indexName, lastEtag, lastModified);
                    return;
                }
                log.Debug("Going to index {0} documents in {1}", batch.Ids.Count, indexToWorkOn);
                results[i] = Tuple.Create(indexToWorkOn, batch);
            });

            transactionalStorage.Batch(actionsAccessor =>
            {
                foreach (var action in actions)
                {
                    if (action != null)
                    {
                        action(actionsAccessor);
                    }
                }
            });

            return(results.Where(x => x != null));
        }
        private void ExecuteReloadConfig(Tuple<string, Action<bool>>[] items)
        {
            List<string> requestTypes;
            List<string> distinctRequestsTypes;

            DataSet configuration = null;
            bool systemConfigurationLoaded = false;

            requestTypes = items
                .Select(tuple => tuple.Item1)
                .ToList();

            distinctRequestsTypes = requestTypes
                .Distinct()
                .OrderBy(type => requestTypes.LastIndexOf(type))
                .ToList();

            foreach (string type in distinctRequestsTypes)
            {
                string typeInner = type;

                if (type == m_configurationType.ToString())
                {
                    DisplayStatusMessage("Loading system configuration...", UpdateType.Information);
                    configuration = GetConfigurationDataSet();

                    // Update data source on all adapters in all collections
                    if ((object)configuration != null)
                        PropagateDataSource(configuration);
                }
                else if (type == "Augmented")
                {
                    DisplayStatusMessage("Augmenting current system configuration...", UpdateType.Information);
                    configuration = AugmentConfigurationDataSet(DataSource);

                    // Update data source on all adapters in all collections
                    if ((object)configuration != null)
                        PropagateDataSource(configuration);
                }
                else if (type == "BinaryCache")
                {
                    DisplayStatusMessage("Loading binary cached configuration...", UpdateType.Information);
                    configuration = GetBinaryCachedConfigurationDataSet();

                    // Update data source on all adapters in all collections
                    if ((object)configuration != null)
                        PropagateDataSource(configuration);
                }
                else if (type == "XmlCache")
                {
                    DisplayStatusMessage("Loading XML cached configuration...", UpdateType.Information);
                    configuration = GetXMLCachedConfigurationDataSet();

                    // Update data source on all adapters in all collections
                    if ((object)configuration != null)
                        PropagateDataSource(configuration);
                }
                else if (type == "Startup")
                {
                    systemConfigurationLoaded = LoadStartupConfiguration();
                }
                else
                {
                    // No specific reload command was issued;
                    // load system configuration as normal
                    systemConfigurationLoaded = LoadSystemConfiguration();
                }

                foreach (Action<bool> callback in items.Where(tuple => tuple.Item1 == typeInner).Select(tuple => tuple.Item2))
                {
                    try
                    {
                        callback(systemConfigurationLoaded || (object)configuration != null);
                    }
                    catch (Exception ex)
                    {
                        DisplayStatusMessage("Failed to execute callback for ReloadConfig request of type {0}: {1}", UpdateType.Alarm, type, ex.Message);
                        LogException(ex);
                    }
                }

                // Spawn routing table calculation updates
                m_iaonSession.RecalculateRoutingTables();
            }
        }
Beispiel #40
0
        private JsBlockStatement InitializeConstructor(INamedTypeSymbol type, string constructorName, Tuple<string, IParameterSymbol>[] parameters)
        {
            var block = new JsBlockStatement();
            block.Assign(GetFromPrototype(constructorName).Member(SpecialNames.TypeField), Js.Reference(SpecialNames.TypeInitializerTypeFunction));

            var parameterNames = parameters.Select(x => x.Item1);
            JsExpression[] arguments;
            if (!type.IsBuiltIn())
            {
                block.Assign(GetFromPrototype(constructorName).Member(SpecialNames.New), 
                    Js.Function().Body(Js.New(Js.Reference(SpecialNames.TypeInitializerTypeFunction), Js.This(), Js.Reference("arguments")).Return()));
            }
            else
            {
                arguments = parameters.Where(x => x.Item2 != null && x.Item2.IsBuiltIn()).Select(x => Js.Reference(x.Item1)).ToArray();
                block.Assign(GetFromPrototype(constructorName).Member(SpecialNames.New), 
                    Js.Function(parameterNames.Select(x => Js.Parameter(x)).ToArray())
                        .Body(Js.New(GetFromPrototype(constructorName).Member(SpecialNames.TypeField), Js.Array(arguments)).Return()));
            }

            return block;
        }
Beispiel #41
0
        public static void MoveLegalityCheck(PBESpecies species, byte level, IEnumerable <PBEMove> moves, PBESettings settings)
        {
            // Validate basic move rules first
            if (moves == null || moves.Count() != settings.NumMoves)
            {
                throw new ArgumentOutOfRangeException(nameof(moves), $"A Pokémon must have exactly {settings.NumMoves} moves.");
            }
            if (moves.Any(m => moves.Count(m2 => m != PBEMove.None && m == m2) > 1))
            {
                throw new ArgumentOutOfRangeException(nameof(moves), $"A Pokémon cannot have duplicate moves other than {PBEMove.None}.");
            }
            if (moves.All(m => m == PBEMove.None))
            {
                throw new ArgumentOutOfRangeException(nameof(moves), $"A Pokémon must have at least one move other than {PBEMove.None}.");
            }
            if (species == PBESpecies.Keldeo_Resolute && !moves.Contains(PBEMove.SecretSword))
            {
                throw new ArgumentOutOfRangeException(nameof(moves), $"{species} must have {PBEMove.SecretSword}.");
            }

            // Combine all moves from pre-evolutions
            IEnumerable <PBESpecies> evolutionChain = PBEPokemonData.Data[species].PreEvolutions.Concat(new[] { species });

            IEnumerable <Tuple <PBEMove, byte, PBEMoveObtainMethod> > levelUp = new Tuple <PBEMove, byte, PBEMoveObtainMethod> [0];
            IEnumerable <Tuple <PBEMove, PBEMoveObtainMethod> >       other   = new Tuple <PBEMove, PBEMoveObtainMethod> [0];

            foreach (PBESpecies pkmn in evolutionChain)
            {
                PBEPokemonData pData = PBEPokemonData.Data[pkmn];
                levelUp = levelUp.Union(pData.LevelUpMoves.Where(t => t.Item2 <= level));
                other   = other.Union(pData.OtherMoves);
            }
            // TODO:
            IEnumerable <PBEMove> allAsMoves = GetLegalMoves(species, level);

            // Check if there's a move it cannot possibly learn
            foreach (PBEMove m in moves)
            {
                if (m != PBEMove.None && !allAsMoves.Contains(m))
                {
                    throw new ArgumentOutOfRangeException(nameof(moves), $"{species} cannot learn {m}.");
                }
            }

            // Check generational rules
            bool HasGen3Method(PBEMoveObtainMethod method)
            {
                return(method.HasFlag(PBEMoveObtainMethod.LevelUp_RS) ||
                       method.HasFlag(PBEMoveObtainMethod.LevelUp_FR) ||
                       method.HasFlag(PBEMoveObtainMethod.LevelUp_LG) ||
                       method.HasFlag(PBEMoveObtainMethod.LevelUp_E) ||
                       method.HasFlag(PBEMoveObtainMethod.LevelUp_Colo) ||
                       method.HasFlag(PBEMoveObtainMethod.LevelUp_XD) ||
                       method.HasFlag(PBEMoveObtainMethod.TM_RSFRLGE) ||
                       method.HasFlag(PBEMoveObtainMethod.HM_RSFRLGE) ||
                       method.HasFlag(PBEMoveObtainMethod.MoveTutor_FRLG) ||
                       method.HasFlag(PBEMoveObtainMethod.MoveTutor_E) ||
                       method.HasFlag(PBEMoveObtainMethod.MoveTutor_XD) ||
                       method.HasFlag(PBEMoveObtainMethod.EggMove_RSFRLG) ||
                       method.HasFlag(PBEMoveObtainMethod.EggMove_E));
            }

            bool HasGen4Method(PBEMoveObtainMethod method)
            {
                return(method.HasFlag(PBEMoveObtainMethod.LevelUp_DP) ||
                       method.HasFlag(PBEMoveObtainMethod.LevelUp_Pt) ||
                       method.HasFlag(PBEMoveObtainMethod.LevelUp_HGSS) ||
                       method.HasFlag(PBEMoveObtainMethod.TM_DPPtHGSS) ||
                       method.HasFlag(PBEMoveObtainMethod.HM_DPPt) ||
                       method.HasFlag(PBEMoveObtainMethod.HM_HGSS) ||
                       method.HasFlag(PBEMoveObtainMethod.MoveTutor_DP) ||
                       method.HasFlag(PBEMoveObtainMethod.MoveTutor_Pt) ||
                       method.HasFlag(PBEMoveObtainMethod.MoveTutor_HGSS) ||
                       method.HasFlag(PBEMoveObtainMethod.EggMove_DPPt) ||
                       method.HasFlag(PBEMoveObtainMethod.EggMove_HGSS));
            }

            bool HasGen5Method(PBEMoveObtainMethod method)
            {
                return(method.HasFlag(PBEMoveObtainMethod.LevelUp_BW) ||
                       method.HasFlag(PBEMoveObtainMethod.LevelUp_B2W2) ||
                       method.HasFlag(PBEMoveObtainMethod.TM_BW) ||
                       method.HasFlag(PBEMoveObtainMethod.TM_B2W2) ||
                       method.HasFlag(PBEMoveObtainMethod.HM_BWB2W2) ||
                       method.HasFlag(PBEMoveObtainMethod.MoveTutor_BW) ||
                       method.HasFlag(PBEMoveObtainMethod.MoveTutor_B2W2) ||
                       method.HasFlag(PBEMoveObtainMethod.EggMove_BWB2W2));
            }

            IEnumerable <Tuple <PBEMove, PBEMoveObtainMethod> > movesAsObtainMethods = levelUp.Where(t => moves.Contains(t.Item1)).Select(t => Tuple.Create(t.Item1, t.Item3)).Union(other.Where(t => moves.Contains(t.Item1)));

            // Check to see where the Pokémon DEFINITELY has been
            bool definitelyBeenInGeneration3 = false,
                 definitelyBeenInGeneration4 = false,
                 definitelyBeenInGeneration5 = false;

            foreach (Tuple <PBEMove, PBEMoveObtainMethod> m in movesAsObtainMethods)
            {
                bool gen3 = HasGen3Method(m.Item2),
                                                          gen4 = HasGen4Method(m.Item2),
                                                          gen5 = HasGen5Method(m.Item2);
                if (gen3 && !gen4 && !gen5)
                {
                    definitelyBeenInGeneration3 = true;
                }
                else if (!gen3 && gen4 && !gen5)
                {
                    definitelyBeenInGeneration4 = true;
                }
                else if (!gen3 && !gen4 && gen5)
                {
                    definitelyBeenInGeneration5 = true;
                }
            }

            // TODO: Check where the species was born
            // TODO: Check if moves make sense (example: learns a move in gen4 but was born in gen5/caught in dreamworld/is gen5 event)
            // TODO: Check if HMs were transferred
            // TODO: Check events for moves
            ;
        }
                private static List<Tuple<Point, Point>> StitchSegmentsSprtCleanup_TOOMUCH(Tuple<Point, Point>[] lineSegments)
                {
                    Tuple<Point, Point>[] cleaned = lineSegments.
                        Where(o => !Math2D.IsNearValue(o.Item1, o.Item2)).     // Remove single vertex matches
                        Select(o => o.Item1.X < o.Item2.X ? o : Tuple.Create(o.Item2, o.Item1)).     // Put the smaller x as item1
                        ToArray();

                    // Only return distinct segments
                    List<Tuple<Point, Point>> retVal = new List<Tuple<Point, Point>>();
                    foreach (var segment in cleaned)
                    {
                        if (!retVal.Any(o => Math2D.IsNearValue(segment.Item1, o.Item1) && Math2D.IsNearValue(segment.Item2, o.Item2)))
                        {
                            retVal.Add(segment);
                        }
                    }

                    // Exit Function
                    return retVal;
                }
Beispiel #43
0
        private void ProcessSoulBags(Random rand, Tuple<Player, int>[] dat)
        {
            var items = new Dictionary<Player, HashSet<Item>>();
            foreach (var i in dat)
                items.Add(i.Item1, new HashSet<Item>());

            foreach (var i in SoulBag)
            {
                var eligiblePlayers = dat
                    .Where(_ => _.Item2 > i.Item1)
                    .OrderByDescending(_ => _.Item2)
                    .ToArray();

                var lootCount = i.Item2.BaseLootCount + i.Item2.PersonMultiplier*eligiblePlayers.Length;

                var loots = new List<Item>();
                for (var j = 0;
                    (j < lootCount || loots.Count < i.Item2.MinLootCount) &&
                    loots.Count < i.Item2.MaxLootCount;
                    j++)
                {
                    var loot = i.Item2.GetRandomLoot(rand);
                    if (loot != null) loots.Add(loot);
                }
                int idx = 0, q = -1;
                for (var j = 0; j < loots.Count;) //Give loots rounds
                {
                    if (items[eligiblePlayers[idx].Item1].Add(loots[j]) ||
                        idx == q)
                    {
                        j++;
                        q = -1;
                    }
                    else if (q == -1)
                        q = idx;

                    idx++;
                    if (idx == eligiblePlayers.Length) idx = 0;
                }
            }
            foreach (var i in items)
                if (i.Value.Count > 0)
                    ShowBags(rand, i.Value, i.Key);
        }
Beispiel #44
0
        static void Main(string[] args)
        {
            int    a = 10;
            string b = "Hello";
            float  c = 2.32f;
            char   d = 'd';
            bool   e = true;

            int[] f = new int[6] {
                1, 2, 3, 4, 5, 6
            };
            ArrayList Array1 = new ArrayList();
            ArrayList Array2 = new ArrayList()
            {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10
            };

            Array1.Add(a);
            Array1.Add(b);
            Array1.Add(c);
            Array1.Add(d);
            Array1.Add(e);
            Array1.Add(f);
            Array1.Add("bcd");

            var dcd = Array1[6];     //Just for the sake of explicit typecasting

            Array1.Insert(0, a * 2); //inserting value a*2 at 0 index
            //by inserting every value will be pushed forward to the next location.

            Array1.AddRange(Array2);//adding another array list at the end of the first array list

            for (int i = 0; i < Array1.Count; i++)
            {
                Console.WriteLine("Value from {0} index ", i);
                Console.WriteLine(Array1[i]);
            }
            Console.WriteLine("\n Ended The array List Now moving towards next Collection \n\n\n");


            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


            //Code for Sorted List (Non generic)
            Console.WriteLine("From Sorted List Nongeneric");
            int        j       = 0;
            SortedList myNames = new SortedList();

            myNames.Add(j, a);
            j++;
            myNames.Add(j, b);
            j++;
            myNames.Add(j, c);
            j++;
            myNames.Add(j, d);
            j++;
            myNames.Add(j, e);
            j++;
            myNames.Add(j, f);
            j++;

            Console.WriteLine("Before removing an element");
            foreach (DictionaryEntry variable in myNames)
            {
                Console.WriteLine("{0} {1}", variable.Key, variable.Value);
            }

            myNames.RemoveAt(0);
            Console.WriteLine("After removing an element");
            foreach (DictionaryEntry variable in myNames)
            {
                Console.WriteLine("{0} {1}", variable.Key, variable.Value);
            }



            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            //Code for Sorted List (Generic)
            Console.WriteLine("\n\n\n From Sorted List Generic");
            j = 0;
            SortedList <int, string> myNames1 = new SortedList <int, string>();

            myNames1.Add(j, "a");
            j++;
            myNames1.Add(j, "b");
            j++;
            myNames1.Add(j, "c");
            j++;
            myNames1.Add(j, "d");
            j++;
            myNames1.Add(j, "e");
            j++;
            myNames1.Add(j, "f");
            j++;

            myNames1.Remove(1);
            foreach (var variable in myNames1)
            {
                Console.WriteLine("The value against key {0} is {1}", variable.Key, variable.Value);
            }

            Console.WriteLine("\n\n\n Using KeyValuePair Property");

            foreach (KeyValuePair <int, string> obj in myNames1)
            {
                Console.WriteLine("{0} {1}", obj.Key, obj.Value);
            }
            string result;

            if (myNames1.TryGetValue(2, out result))
            {
                Console.WriteLine("true {0}", result);
            }
            //Console.WriteLine(myNames1[0]);



            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            //Code for Dictionary implementation starts here
            Console.WriteLine("\n\n\n From Dictionary");

            Dictionary <char, string> dict = new Dictionary <char, string>();

            dict.Add('a', "Ali");
            dict.Add('b', "Batman");
            dict.Add('c', "Cat");
            dict.Add('d', "Dog");
            dict.Add('e', "Elephant");
            dict.Add('f', "Frog");
            foreach (Object obj in dict)
            {
                Console.WriteLine(obj);
            }

            dict.Add('g', "Goose");
            dict.Remove('a');

            Console.WriteLine("\n\n From Dictionary Generic Printing Count of objects");
            Console.WriteLine(dict.Count);

            Console.WriteLine("\n\n\n From Dictionary Generic using Object");
            foreach (Object obj in dict)
            {
                Console.WriteLine(obj);
            }
            Console.WriteLine("\n\n\n From Dictionary Generic using KeyValuePair");
            foreach (KeyValuePair <char, string> obj in dict)
            {
                Console.WriteLine("{0} {1}", obj.Key, obj.Value);
            }



            //Code for HashTable implementation starts here
            Console.WriteLine("\n\n\n From Hashtable");

            Hashtable hash = new Hashtable();

            hash.Add(1, a);
            hash.Add('a', b);
            hash.Add('b', b);
            hash.Add('d', b);
            foreach (DictionaryEntry obj in hash)
            {
                Console.WriteLine("{0} {1}", obj.Key, obj.Value);
            }
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


            //Code for List implementation starts here
            Console.WriteLine("\n\n\n From List generic");

            List <int> myList = new List <int>();

            myList.Add(1);
            myList.Add(21);
            myList.Add(2);
            myList.Add(0);
            myList.Sort();
            for (int i = 0; i < myList.Count; i++)
            {
                Console.WriteLine(myList[i]);
            }
            myList.RemoveAt(0);
            myList.Insert(0, 20);
            myList.Sort();
            for (int i = 0; i < myList.Count; i++)
            {
                Console.WriteLine(myList[i]);
            }


            List <ArrayList> myCollector = new List <ArrayList>();

            myCollector.Add(Array1);
            myCollector.Add(Array2);
            Console.WriteLine("\n\n" + myCollector[0].ToArray().Length);


            //Adding dummy student data into the list of students


            int                age;
            float              cgpa;
            string             name;
            string             email;
            string             address;
            string             contactNumber;
            List <StudentInfo> myClass = new List <StudentInfo>();
            StudentInfo        bacs    = new StudentInfo();

            myClass.Add(bacs);
            myClass.Add(bacs);
            for (int i = 0; i < 0; i++)
            {
                Console.WriteLine("Write the age of {0} student", i + 1);
                age = int.Parse(Console.ReadLine());
                Console.WriteLine("Write the cgpa of {0} student", i + 1);
                cgpa = float.Parse(Console.ReadLine());
                Console.WriteLine("Write the name of {0} student", i + 1);
                name = Console.ReadLine();
                Console.WriteLine("Write the email of {0} student", i + 1);
                email = Console.ReadLine();
                Console.WriteLine("Write the address of {0} student", i + 1);
                address = Console.ReadLine();
                Console.WriteLine("Write the contactNumber of {0} student", i + 1);
                contactNumber = Console.ReadLine();

                myClass.Add(new StudentInfo(age, cgpa, name, email, address, contactNumber));
            }
            foreach (StudentInfo s in myClass)
            {
                if (s.AGE >= 18)
                {
                    Console.WriteLine("The student details are as follow");
                    Console.WriteLine("The Name of the student is {0}", s.NAME);
                    Console.WriteLine("The Age of the student is {0}", s.AGE);
                    Console.WriteLine("The Cgpa of the student is {0}", s.CGPA);
                    Console.WriteLine("The Email of the student is {0}", s.EMAIL);
                    Console.WriteLine("The Address of the student is {0}", s.ADDRESS);
                    Console.WriteLine("The Contact Number of the student is {0}", s.CONTACTNUMBER);
                }
            }
            var results = from StudentInfo in myClass
                          where StudentInfo.AGE >= 12
                          select StudentInfo;

            Console.WriteLine("Student with age greater then 12 are as follow");

            foreach (StudentInfo s in results)
            {
                Console.WriteLine(s.AGE);
            }

            /*
             * myClass.Select(x=>new object { name=x.Total})
             *
             * var results = from s in myClass
             *            select s;
             *
             * foreach(StudentInfo info in myClass)
             *  {
             * Console.WriteLine(results[0]);*/


            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            ///


            //Code for Stack implementation starts here
            Console.WriteLine("\n\n\n Implementation of Stack starts from here \n");
            Stack <int> myStack = new Stack <int>(f);


            Console.WriteLine("\nStack after entering values using array \n");
            foreach (int variable in myStack)
            {
                Console.Write(variable + ",");
            }
            Console.WriteLine();


            Console.WriteLine("\nStack after entering Value using push \n");
            myStack.Push(20);
            foreach (int variable in myStack)
            {
                Console.Write(variable + ",");
            }


            Console.WriteLine("\nStack after Peeking from it \n");
            Console.WriteLine(myStack.Peek());
            foreach (int variable in myStack)
            {
                Console.Write(variable + ",");
            }


            Console.WriteLine("\nStack after popping element from it \n");
            Console.WriteLine(myStack.Pop());
            foreach (int variable in myStack)
            {
                Console.Write(variable + ",");
            }
            Console.WriteLine();
            int check = 24;

            if (myStack.Contains(check))
            {
                Console.WriteLine("true the stack contains the value {0}", check);
            }
            else
            {
                Console.WriteLine("False the stack doesnot contains the value {0}", check);
            }


            //Iplementation of queue starts from here
            Queue <int> myQueue = new Queue <int>(f);

            Console.WriteLine("\nQueue after entering values from array");
            foreach (int variable in myQueue)
            {
                Console.Write(variable + ",");
            }

            myQueue.Enqueue(20);
            Console.WriteLine("\n\nQueue after using enqueue");
            foreach (int variable in myQueue)
            {
                Console.Write(variable + ",");
            }



            Console.WriteLine("\n\nQueue after Dequeue method");
            Console.WriteLine("The value returned from the dequeue method is " + myQueue.Dequeue());
            foreach (int variable in myQueue)
            {
                Console.Write(variable + ",");
            }


            Console.WriteLine("\n\nPrinting the count of elements in the queue \n" + myQueue.Count());

            Console.WriteLine("\nQueue after Peeking from it");
            Console.WriteLine("Value returned from peek method is " + myQueue.Peek());
            foreach (int variable in myQueue)
            {
                Console.Write(variable + ",");
            }

            Console.WriteLine();

            ///////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////
            ///////////////////////////////////////////////////////////////
            //File Hanlding
            string path1 = @"C:\Users\Lenovo\source\repos\Collections\Collections\bin\Debug\netcoreapp3.1/DummyData1.txt";
            string path2 = @"C:\Users\Lenovo\source\repos\Collections\Collections\bin\Debug\netcoreapp3.1/DummyData2.txt";
            string path3 = @"C:\Users\Lenovo\source\repos\Collections\Collections\bin\Debug\netcoreapp3.1/DummyData3.txt";

            string Abc  = "Hello from the file1";
            string Abcd = "Hello from the file2";

            /*File.WriteAllText(path1,Abc);
             * File.WriteAllText(path2, Abcd);
             */
            string DataRead = File.ReadAllText(path1);

            Console.WriteLine(DataRead);

            //This block is used to to auto close the file after the use
            //the file will open at the start of the using block and
            //At the end of the block the file is automatically closed.

            /*using (StreamWriter sw = File.AppendText(path1))
             * {
             *  sw.WriteLine("\nHello once again using Stream Writer");
             * }
             *
             * using (StreamReader sr = File.OpenText(path2))
             * {
             *  string readed = "";
             *  while ((readed = sr.ReadLine()) != null)
             *  {
             *      Console.WriteLine(readed);
             *  }
             * } */

            DataRead = File.ReadAllText(path1);
            Console.WriteLine("\n\n" + DataRead + "\n\n");

            DataRead = File.ReadAllText(path2);
            Console.WriteLine("\n\n" + DataRead + "\n\n");


            /*FileStream file = new FileStream(path3, FileMode.OpenOrCreate , FileAccess.ReadWrite);
             * //file.Write("Hello")
             * file.WriteByte(66);
             * file.Close();
             */
            using (FileStream file1 = new FileStream(path3, FileMode.Append, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(file1, Encoding.UTF8))
                {
                    int[] arrays = new int[10] {
                        1, 2, 3, 4, 5, 6, 7, 8, 9, 10
                    };
                    foreach (int num in arrays)
                    {
                        sw.Write(num + " ");
                    }

                    sw.WriteLine("\nHelpppp");
                }
            }


            using (FileStream file1 = new FileStream(path3, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(file1))
                {
                    string line = sr.ReadLine();
                    while (line != null)
                    {
                        Console.WriteLine(line);
                        line = sr.ReadLine();
                    }
                }
            }



            //Exception Handling Code
            int[] except = new int[3] {
                1, 2, 3
            };
            try
            {
                Console.WriteLine(except[10]);
            }
            catch (Exception error)
            {
                Console.WriteLine(error.Message);
            }
            finally
            {
                Console.WriteLine("The try catch Block has ended");
            }

            /*using (FileStream fs = new FileStream(path1, FileMode.Open, FileAccess.Read))
             * {
             *  using(StreamWriter stw = new StreamWriter(fs))
             *  {
             *
             *  }
             *
             *  using(StreamReader str = new StreamReader(fs))
             *  {
             *
             *  }
             *
             * }*/



            //Manipulating the tuples in the form of an array
            Tuple <int, float, double, char, string>[] studentTuples = new Tuple <int, float, double, char, string> [2];

/*            Tuple<int, float, double, char, string>[] studentFiltered = new Tuple< int, float, double, char, string>[2];
 */
            for (int i = 0; i < 2; i++)
            {
                studentTuples[i] = new Tuple <int, float, double, char, string>(1, 2.2f, 3.3, 'a', "abcd");
            }

            /*int iterator=0;*/
            foreach (Tuple <int, float, double, char, string> tp in studentTuples)
            {
                /*if (tp.Item5.Length >= 3)
                 * {
                 *  studentFiltered[iterator] = tp;
                 *  iterator++;
                 * }*/
                Console.Write(tp.Item1 + " , ");
                Console.Write(tp.Item2 + " , ");
                Console.Write(tp.Item3 + " , ");
                Console.Write(tp.Item4 + " , ");
                Console.WriteLine(tp.Item5);
            }
            //var v1 = new Tuple.Create(1,2);



            //Manilulating with the string array using LINQ queries
            string[] myNamesArray = new string[22] {
                "Ali", "Yar", "Wamik", "Afaq", "Salal", "Daniel", "June", "Juliet",
                "danyyal", "Yousuf", "Bukht", "Yar", "Arshad", "Kainat", "aiman", "sidra",
                "Tooba", "zeeshan", "Hyper", "Don", "Chaudary", "Muaaz"
            };
            var MyQueryResult = from names in myNamesArray
                                where names.Length >= 3
                                select names;

            Console.WriteLine("name---first2letters--Caps--length");
            foreach (var names in MyQueryResult)
            {
                Console.Write(names + " ");
                Console.Write(names.Substring(0, 2) + " ");
                Console.Write(names.ToUpper() + " ");
                Console.WriteLine(names.ToUpper().Length);
            }



            //Maipulatin with Tuple array using the LINQ queries
            var myTupleResults = studentTuples.Where(tuples => tuples.Item5.Substring(0, 2) == "ab" && tuples.Item5.Contains('b') && tuples.Item1 == 1);


            //We can write queries in Two ways

            /*from tuples in studentTuples
             * where tuples.Item5.Substring(0, 2) == "ab" && tuples.Item5.Contains('b') && tuples.Item1==12
             * select tuples;*/

            //Getting array in the resul of LINQ Queries
            var myTupleResultsArray = studentTuples.Where(tuples => tuples.Item5.Substring(0, 2) == "ab" && tuples.Item5.Contains('b') && tuples.Item1 == 1).ToArray();

            Console.WriteLine(myTupleResultsArray[0]);



            Console.WriteLine("\n\n From Tuples results\nName---first2letters--Caps--length");
            foreach (var tuples in myTupleResults)
            {
                Console.Write(tuples.Item1 + " ");
                Console.Write(tuples.Item2 + " ");
                Console.Write(tuples.Item3 + " ");
                Console.Write(tuples.Item4.ToString() + " ");
                Console.WriteLine(tuples.Item5.Substring(0));
            }
            Program pg = new Program();

            MakeNoise mk = new MakeNoise(pg.Noise);

            mk(10);
        }