// Arg(ControllerName),Param(..),.. -> Arg(ControllerName),Arg('Index'),...
        public static IList<Token> Rewrite(IList<Token> tokens)
        {
            //"--command"
            if (tokens.Count() >= 2
                && tokens[0].TokenType==TokenType.Argument
                && tokens[0].Value.EqualsIC("help")
                && tokens[1].TokenType==TokenType.Argument)
            {
                tokens[1] = new Token(tokens[1].Value,TokenType.ParameterValue,tokens[1].Index);
                tokens.Insert(1,new Token("command",TokenType.Parameter,1));
                //index:2
                if (tokens.Count() >= 4) { tokens[3] = new Token(tokens[3].Value, TokenType.ParameterValue, tokens[1].Index); }
                tokens.Insert(3, new Token("action", TokenType.Parameter, 2));
            }
            //help maps to index (should have routing here)
            if (tokens.Count() == 0)
            {
                tokens.Add(new Token("help",TokenType.Argument,0));
            }

            //Index rewrite:
            var indexToken= new Token("Index", TokenType.Argument,1);
            if (tokens.Count()>=2
                && tokens[1].TokenType!=TokenType.Argument
                && tokens[0].TokenType==TokenType.Argument)
            {
                tokens.Insert(1,indexToken);
            }
            else if (tokens.Count()==1
                && tokens[0].TokenType==TokenType.Argument)
            {
                tokens.Add(indexToken);
            }
            return tokens;
        }
Example #2
1
        /// <summary>
        /// Convert numbers to spark chart strings.
        /// </summary>
        /// <param name="data">List or Array of numbers</param>
        /// <returns>empty string if <paramref name="data"/>is <code>null</code> or empty.</returns>
        public static String Render(IList<double> data)
        {
            var ticks = TickProvider.Ticks;

            if (data == null || data.Count == 0)
                return string.Empty;

            char[] res = new char[data.Count()];

            double min = data.Min();
            double max = data.Max();
            double step = (max - min) / (ticks.Length - 1);
            if (step.Equals(0d)) step = 1;

            for (var i = 0; i < data.Count(); i++)
            {
                var val = data[i];
                double d = (val - min)/step;

                // if it's 10^-10 close to its rounded, round; floor otherwise
                int tick = (int) ((Math.Abs(Math.Round(d) - d) < 1e-10) ? Math.Round(d) : Math.Floor((val - min) / step));
                res[i] = ticks[tick];
            }
            return new string(res);
        }
Example #3
1
        private int[,] BuildMatrix(IList<Drop> goblet, int blocksCount, int chunkSize)
        {
            var rowsCount = goblet.Count() * chunkSize;
            var columnsCount = (blocksCount * chunkSize) + 1;
            var matrix = new int[rowsCount, columnsCount];

            for (int dropIdx = 0; dropIdx < goblet.Count(); dropIdx++)
            {
                var drop = goblet[dropIdx];

                for (int i = 0; i < chunkSize; i++)
                {
                    var row = (dropIdx * chunkSize) + i;
                    matrix[row, columnsCount - 1] = drop.Data[i];

                    foreach (var part in drop.SelectedParts)
                    {
                        var col = (part * chunkSize) + i;
                        matrix[row, col] = 1;
                    }
                }
            }

            return matrix;
        }
Example #4
1
        /// <summary>
        /// Initialises a new instance of the <see cref="TableInfo"/> class.
        /// </summary>
        /// <param name="columns">The columns that are mapped for the table.</param>
        /// <param name="identifierStrategy">The identifier strategy used by the table.</param>
        /// <param name="name">The name of the table.</param>
        /// <param name="schema">The database schema the table exists within (e.g. 'dbo'); otherwise null.</param>
        /// <exception cref="ArgumentNullException">Thrown if columns or name are null.</exception>
        /// <exception cref="MappingException">Thrown if no there is a problem with the column mappings.</exception>
        public TableInfo(
            IList<ColumnInfo> columns,
            IdentifierStrategy identifierStrategy,
            string name,
            string schema)
        {
            if (columns == null)
            {
                throw new ArgumentNullException("columns");
            }

            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            this.columns = new ReadOnlyCollection<ColumnInfo>(columns);
            this.identifierStrategy = identifierStrategy;
            this.name = name;
            this.schema = schema;

            this.identifierColumn = columns.FirstOrDefault(c => c.IsIdentifier);

            this.insertColumnCount = columns.Count(c => c.AllowInsert);
            this.updateColumnCount = columns.Count(c => c.AllowUpdate);

            this.ValidateColumns();
        }
 private int SolveFive(BombSettings settings, IList<Color> colors)
 {
     if (settings.SerialLastDigit == Parity.NotSet)
     {
         throw new NeedSerialLastDigitException();
     }
     // If the last wire is black and the last digit of the serial number is odd, cut the fourth wire.
     else if (colors.Last() == Color.Black && settings.SerialLastDigit == Parity.Odd)
     {
         return 4;
     }
     // Otherwise, if there is exactly one red wire and there is more than one yellow wire, cut the first wire.
     else if (colors.Count(c => c == Color.Red) == 1 && colors.Count(c => c == Color.Yellow) > 1)
     {
         return 1;
     }
     // Otherwise, if there are no black wires, cut the second wire.
     else if (colors.Count(c => c == Color.Black) == 0)
     {
         return 2;
     }
     // Otherwise, cut the first wire.
     else
     {
         return 1;
     }
 }
Example #6
1
 /// <summary>
 /// The cross product of two double vectors, A and B, which are of length, 2.
 /// In actuality, there is no cross-product for 2D. This is shorthand for 2D systems 
 /// that are really simplifications of 3D. The returned scalar is actually the value in 
 /// the third (read: z) direction.
 /// </summary>
 /// <param name = "A">1D double Array, A</param>
 /// <param name = "B">1D double Array, B</param>
 /// <returns></returns>
 public static double crossProduct2(IList<double> A, IList<double> B)
 {
     if (((A.Count() == 2) && (B.Count() == 2))
         || ((A.Count() == 3) && (B.Count() == 3) && A[2] == 0.0 && B[2] == 0.0))
         return A[0] * B[1] - B[0] * A[1];
     throw new Exception("This cross product \"shortcut\" is only used with 2D vectors to get the single value in the,"
                         + "would be, Z-direction.");
 }
Example #7
1
        public override void HandleCommand(IList<string> paramList, IrcUser user, bool isIngameCommand)
        {
            int num;
            if (paramList.Count() == 1)
            {
                // display random quote
                Connection.GetData(Data.UrlQuote, "get", jObject =>
                {
                    if ((bool)jObject["success"])
                    {
                        Utils.SendChannel((string)jObject["result"].SelectToken("id") + ": " +
                                          (string)jObject["result"].SelectToken("quote"));
                    }
                    else
                    {
                        Utils.SendChannel("No quotes found.");
                    }
                }, Utils.HandleException);
            }
            else if (paramList[1] == "add")
            {
                if (isIngameCommand == false)
                {
                    var quote = "";
                    for (var l = 2; l < paramList.Count(); l++)
                    {
                        quote = quote + paramList[l] + " ";
                    }

                    Connection.GetData(string.Format(Data.UrlQuoteAdd, user.Nick, user.Hostmask, quote.Trim()),
                        "get", jObject => Utils.SendChannel(string.Format("Quote #{0} has been added.", jObject["result"].SelectToken("id"))), Utils.HandleException);
                }
                else
                {
                    Utils.SendChannel("This command is restricted to the IRC channel only.");
                }
            }
            else if (int.TryParse(paramList[1], out num))
            {
                Connection.GetData(string.Format(Data.UrlQuoteSpecific, num), "get", jObject =>
                {
                    if ((bool)jObject["success"])
                    {
                        Utils.SendChannel((string)jObject["result"].SelectToken("quote"));
                    }
                    else
                    {
                        Utils.SendChannel("Specific quote not found.");
                    }
                }, Utils.HandleException);
            }
            else
            {
                Utils.SendChannel("Usage: !quote add <message>");
            }
        }
Example #8
1
        public virtual void PrintReportFooter(StreamWriter streamWriter, IList<AllItem> allItems)
        {
            int drCount = allItems.Count(ai => ai.Classification == "Dr");
            int crCount = allItems.Count(ai => ai.Classification == "Cr");

            decimal drAmount = allItems.Where(ai => ai.Classification == "Dr").Sum(ai => ai.Amount);
            decimal crAmount = allItems.Where(ai => ai.Classification == "Cr").Sum(ai => ai.Amount);

            streamWriter.WriteLine(string.Format(this.reportFooterFormat, drCount, drAmount, crCount, crAmount));
        }
 public static DailyBuildSummary Create(DateTime date, IList<BuildDetails> dailyBuilds)
 {
     return new DailyBuildSummary()
     {
         Date = date,
         FailedBuilds = dailyBuilds.Count(b => b.Status == BuildState.Broken),
         TotalBuilds = dailyBuilds.Count(),
         NumberChangedFiles = dailyBuilds.Sum(b => b.NumberChangedFiles)
     };
 }
        public IList<CurveSegment> GenerateCurveSegments(IList<DataPoint> dataPoints)
        {
            var numDataPoints = dataPoints.Count();

            if (numDataPoints < 3) throw new ArgumentException("Not enough data points");

            var lastKnownSlope = 0.0;
            var lastKnownSlopeMagnitude = 0.0;

            var listOfCurveSegments = new List<CurveSegment>();

            var listOfCurrentPoints = new List<DataPoint>();
            listOfCurrentPoints.Add(dataPoints.First());

            for (var i = 1; i < dataPoints.Count(); i++)
            {
                var lastDataPoint = dataPoints[i - 1];
                var currentDataPoint = dataPoints[i];

                var discoveredSlope = currentDataPoint.YCoordinate - currentDataPoint.YCoordinate;
                var discoveredSlopeMagnitude = Math.Abs(discoveredSlope);
                /*
                 * Test discovered slope value. There's only three possibilities:
                 * 1. The discovered slope is "zero", which means it's still a part of the current segment
                 * 2. The discovered slope is positive
                 * 3. The discovered slope is negative
                 *
                 * Compare with the previous slope, which can be:
                 * 1. Positive
                 * 2. Negative
                 * 3. "Zero"
                 */

                /*
                 * If the last known slope is zero or if the previous slope was negative and the current slope is positive
                 * or if the previous slope was positive and the current slope is negative, seal the current segment and
                 * create a new one
                 */
                if ((lastKnownSlopeMagnitude < Limits.MaxPrecision && discoveredSlopeMagnitude > Limits.MaxPrecision) ||
                    (lastKnownSlope < 0 && discoveredSlope > 0) ||
                    (lastKnownSlope > 0 && discoveredSlope < 0))
                {
                    listOfCurveSegments.Add(new CurveSegment(listOfCurrentPoints));

                    listOfCurrentPoints = new List<DataPoint>();
                }

                //The slopes are the same polarity
                listOfCurrentPoints.Add(currentDataPoint);
                lastKnownSlope = discoveredSlope;
                lastKnownSlopeMagnitude = discoveredSlopeMagnitude;
            }

            return listOfCurveSegments;
        }
Example #11
1
        private static int GetResult(IList<Tree> list)
        {
            var total = 0;

            for (var i = 0; i < list.Count(); i++)
            {
                total += list[i].Age;
            }

            return total/list.Count();
        }
Example #12
1
        public static double Length(IList<IGeoLocation> cities)
        {
            var length = 0d;
            for (var i = 0; i < cities.Count() - 1; i++)
            {
                length = length + Distance(cities[i], cities[i + 1]);
            }

            length = length + Distance(cities[cities.Count() - 1], cities[0]);
            return length;
        }
        public void should_parse_objects_symbols_and_properties_when_parsing_more_complex_xml_content()
        {
            Lexemes = Parser.Parse(ComplexXml);

            Lexemes.Count.ShouldBe(136);
            Lexemes.Count(lx => lx.Type == LexemType.Comment).ShouldBe(6);
        }
        private static IList<ulong> GetFibLikeSequence(IList<ulong> seedSequence, int length)
        {
            IList<ulong> sequence = new List<ulong>();

            int count = seedSequence.Count();

            if (length <= count)
            {
                sequence = seedSequence.Take((int)length).ToList();
            }
            else
            {
                sequence = seedSequence;

                for (int i = count; i < length; i++)
                {
                    ulong num = 0;

                    for (int j = 0; j < count; j++)
                    {
                        num += sequence[sequence.Count - 1 - j];
                    }

                    sequence.Add(num);
                }
            }

            return sequence;
        }
Example #15
1
        public static string FindPositionPart(IList<string> parts, int cursorPosition, out int foundPartsIndex, out int cursorInPartPosition)
        {
            cursorInPartPosition = 0;
              var partsComplete = parts.Aggregate(String.Empty, (aggr, s) => aggr + s);
              for (int i = 0; i < parts.Count(); i++) {
            var partsLower = parts.Take(i).Aggregate(String.Empty, (aggr, s) => aggr + s);
            var partsUpper = parts.Take(i + 1).Aggregate(String.Empty, (aggr, s) => aggr + s);

            var b = partsLower.Length;
            var t = partsUpper.Length;

            if ((cursorPosition >= b && cursorPosition < t) || partsUpper == partsComplete) {
              if (parts[i] == WorkDayParser.itemSeparator.ToString() || parts[i] == WorkDayParser.hourProjectInfoSeparator.ToString()) {
            // cursor left of separator
            foundPartsIndex = i - 1;
            var prevPart = parts.ElementAt(foundPartsIndex);
            // find out where in the found part the cursor is, need to use prevpart an its length
            cursorInPartPosition = prevPart.Length;
            return prevPart;
              } else {
            // find out where in the found part the cursor is
            cursorInPartPosition = cursorPosition - b;
            foundPartsIndex = i;
            return parts.ElementAt(i);
              }
            }
              }
              // not found
              foundPartsIndex = -1;
              return String.Empty;
        }
Example #16
0
        public override void HandleCommand(IList<string> paramList, IrcUser user, bool isIngameCommand)
        {
            if (Utils.IsOp(user.Nick))
            {
                if (paramList.Count() == 1)
                {
                    Utils.SendNotice("Usage: !mcb <name> <optional:number>", user.Nick);
                }
                else
                {
                    Connection.GetPlayerLookup(paramList[1], bans =>
                    {
                        if (bans.Local != null && bans.Local.Any())
                        {
                            var limit = 1;
                            int i;
                            if (paramList.Count() == 3 && Int32.TryParse(paramList[2], out i))
                            {
                                // a count is given
                                limit = int.Parse(paramList[2]);
                            }

                            for (var j = 0; j < limit; j++)
                            {
                                var localBan =
                                    bans.Local[j].Replace("\r\n", "")
                                        .Replace("\r", "")
                                        .Replace("\n", "")
                                        .Replace("\0", "")
                                        .Split(' ');

                                var banReason = "";
                                for (var k = 4; k < localBan.Count(); k++)
                                {
                                    banReason += localBan[k] + " ";
                                }

                                Utils.SendNotice(
                                    string.Concat("Server: ", localBan[2], ", Reason: ",
                                        Utils.Truncate(banReason.Trim(), 25), " URL: ", "http://www.mcbans.com/ban/" + localBan[1]), user.Nick);
                            }
                        }
                        else
                        {
                            Utils.SendNotice("This player does not have any local bans.", user.Nick);
                        }
                    }, Utils.HandleException);
                }
            }
            else
            {
                Utils.SendChannel(Data.MessageRestricted);
            }
        }
Example #17
0
        public override ISet<CreatureCard> ChooseAttackers(IList<CreatureCard> possibleAttackers)
        {
            if (possibleAttackers.Count() == 0)
                return null;

            var chosenSet = new HashSet<CreatureCard>();
            PrintPossibleAttackers(possibleAttackers);
            Console.WriteLine ();

            while(true)
            {
                Console.Write("mla> ");
                string input = Console.In.ReadLine().Trim();

                // if user simply presses enter or white space, repeat list of possible attackers and chosen attackers
                if(String.IsNullOrEmpty(input))
                {
                    PrintPossibleAttackers(possibleAttackers);
                    PrintChosenCreatures(chosenSet);
                    continue;
                }

                // attempt to parse as a number.  If is a number in range, add to set
                int chosen;
                if(Int32.TryParse(input,out chosen))
                {
                    if(chosen == -1)
                        break;

                    // if the chosen number is in range, add it to the set
                    // if not in the set already, or remove it if it is in the set.
                    // otherwise, tsk-tsk the user
                    if(chosen >= 0 && chosen < possibleAttackers.Count())
                    {
                        bool added = chosenSet.Add(possibleAttackers[chosen]);
                        if(!added)
                            chosenSet.Remove(possibleAttackers[chosen]);
                    }
                    else
                    {
                        Console.Write("Select a number from -1 to ");
                        Console.WriteLine(possibleAttackers.Count() - 1);
                    }
                    PrintChosenCreatures(chosenSet);
                    continue;
                }

                ParseCommands(input);
            }

            return chosenSet;
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 public TestClassTableEntry(
     TestClass testClass,
     bool emphasized,
     IList<TestResult> testResults,
     Func<TestResult, string> testUrlBuilder)
 {
     Name = GetColoredText("black", testClass.DisplayName, emphasized, preventWrapping: true);
     PassCount = testResults.Count(result => result.Succeeded);
     FailCount = testResults.Count(result => !result.Succeeded);
     TotalCount = testResults.Count;
     TestResults = testResults.Select
     (
         result => new TestResultTableEntry(result, testUrlBuilder)
     ).ToList();
 }
Example #19
0
        public void FancyTable(IList<string> headers)
        {
            SetFillColor(255, 0, 0);
            SetTextColor(255);
            SetDrawColor(128, 0, 0);
            SetLineWidth(0.3);
            SetFont("", "B");

            int[] w = { 40, 35, 40, 45 };
            for (int i = 0; i < headers.Count(); i++)
            {
                Cell(w[i], 7, headers[i], "1", 0, AlignEnum.Center, true);
            }
            Ln();
            SetFillColor(224, 235, 255);
            SetTextColor(0);
            SetFont("");

            bool fill = false;
            foreach (var row in Data)
            {
                Cell(w[0], 6, row[0], "LR", 0, AlignEnum.Left, fill);
                Cell(w[1], 6, row[1], "LR", 0, AlignEnum.Left, fill);
                Cell(w[2], 6, string.Format("{0:N0}", Convert.ToInt32(row[2])), "LR", 0, AlignEnum.Right, fill);
                Cell(w[3], 6, string.Format("{0:N0}", Convert.ToInt32(row[3])), "LR", 0, AlignEnum.Right, fill);
                Ln();
                fill = !fill;
            }
            Cell(w.Sum(), 0, "", "T");
        }
Example #20
0
        public override void HandleCommand(IList<string> paramList, IrcUser user, bool isIngameCommand)
        {
            int i;
            // check if the params number 4, that the number/sides are integers, and that number and sides are both greater than 0
            if (paramList.Count() == 3 && Int32.TryParse(paramList[1], out i) && Int32.TryParse(paramList[2], out i) &&
                (Int32.Parse(paramList[1]) > 0) && (Int32.Parse(paramList[2]) > 0) && (Int32.Parse(paramList[1]) <= 4) &&
                (Int32.Parse(paramList[2]) <= 100))
            {
                var dice = Int32.Parse(paramList[1]);
                var sides = Int32.Parse(paramList[2]);
                var random = new Random();

                var diceList = new List<int>();
                for (var j = 0; j < dice; j++)
                {
                    diceList.Add(random.Next(1, sides));
                }

                var outputString = String.Format("Rolling a {0} sided die, {1} time{2}: {3}", sides, dice,
                    (dice > 1) ? "s" : "", diceList.Aggregate("", (current, roll) => current + roll + " ").Trim());
                Utils.SendChannel(outputString);
            }
            else
            {
                Utils.SendChannel("Usage: !dice <number 1-4 > <sides 1 - 100>");
            }
        }
Example #21
0
        /// <summary>
        /// Given an input feature, a feature space and its associated labels, and a positive integer 'k',
        /// Determines the 'k' nearest neighbor label for the input feature. The 'k' value corresponds
        /// to the number of nearest neighbors to use in the voting process.
        /// 
        /// <remarks> 
        /// "When I have this grid of data points, and I provide one additional example row, find the 'k' number
        /// of rows that are most similar, count up the number of occurrences of each label for each row (1 to 'k'), 
        /// and choose the label with the highest occurrence."
        /// </remarks> 
        /// <see href="http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm" />
        /// </summary>
        /// <param name="distanceType">The type of equation to use when measuring the distance between each data point</param>
        /// <param name="input">The matrix row to input; must have the same number of columns as the feature space</param>
        /// <param name="featureSpace">The feature space matrix; everything we know</param>
        /// <param name="labels">The results for each feature space row; what we call each collection of data points</param>
        /// <param name="k">The number of nearest neighbors to include in the voting; the label with the most occurrences in 'k' neighbors wins</param>
        /// <returns></returns>
        public static string Classify(DistanceType distanceType, Number[] input, Matrix featureSpace, IList<string> labels, int k)
        {
            if (labels.Count() != featureSpace.Rows)
            {
                throw new ArgumentException("The number of labels must match the number of rows of data in the feature space", "labels");
            }

            var distances = CalculateDistances(distanceType, featureSpace, input);

            var nearestNeighbors = distances.OrderByDescending(d => d.Value).Take(k);

            var votes = new Dictionary<string, int>(k);

            foreach (var label in nearestNeighbors.Select(neighbor => labels[neighbor.Key]))
            {
                if (votes.ContainsKey(label))
                {
                    votes[label]++;
                }
                else
                {
                    votes.Add(label, 1);
                }
            }

            var nearest = votes.OrderByDescending(v => v.Value).First().Key;

            return nearest;
        }
        private static int CalculateTotalFromTokens(IList<string> tokens)
        {
            var total = int.Parse(tokens[0]);
            for (var i = 1; (i + 1) < tokens.Count(); i += 2)
            {
                var right = int.Parse(tokens[i + 1]);

                switch (tokens[i])
                {
                    case "a" :
                        total += right;
                        break;
                    case "b" :
                        total -= right;
                        break;
                    case "c" :
                        total *= right;
                        break;
                    case "d" :
                        total /= right;
                        break;
                }
            }
            return total;
        }
        public bool Start(HostControl hostControl)
        {
            _log.InfoFormat("Starting Subscriber Activity Service");

            var started = new List<ServiceControl>();

            try
            {
                _services = _serviceBootstrappers.Select(x => x.CreateService()).ToList();

                _log.InfoFormat("Starting {0} services", _services.Count());

                foreach (ServiceControl activityService in _services)
                {
                    hostControl.RequestAdditionalTime(TimeSpan.FromMinutes(1));
                    StartService(hostControl, activityService);

                    started.Add(activityService);
                }

                return true;
            }
            catch (Exception ex)
            {
                _log.Error("Service failed to start", ex);

                Parallel.ForEach(started, service =>
                    {
                        hostControl.RequestAdditionalTime(TimeSpan.FromMinutes(1));
                        StopService(hostControl, service);
                    });

                throw;
            }
        }
Example #24
0
        public IList<TreeNode> BuidTree(IList<TreeNode> treeList, IList<Resource> list, IList<Resource> listall)
        {
            foreach (var li in list)
            {

                var count = listall.Count(r => r.F_ResourceID.Equals(li.ResourceID));
                if (count == 0)
                {
                    TreeFile treeFile = new TreeFile();
                    treeFile.text = li.ResourcName;
                    treeFile.id = li.ResourceID;
                    treeFile.url = li.URL;
                    treeList.Add(treeFile);
                }
                else
                {
                    TreeFolder treefolder = new TreeFolder();
                    var TempList = listall.Where(s => s.F_ResourceID.Equals(li.ResourceID));
                    treefolder.id = li.ResourceID;
                    treefolder.url = li.URL;
                    treefolder.text = li.ResourcName;
                    IList<TreeNode> listchild = new List<TreeNode>();
                    treefolder.children = BuidTree(listchild, TempList.ToList(), listall);
                    treeList.Add(treefolder);
                }

            }
            return treeList;
        }
Example #25
0
        /// <summary>
        /// Orders selected point list as a square matrix
        /// </summary>
        /// <param name="selectedPoints">Selected points list</param>
        /// <returns>Ordered in matrix order list</returns>
        protected virtual IList<SelectedPoint> OrderAsMatrix(IList<SelectedPoint> selectedPoints)
        {
            var sortedList = new List<SelectedPoint>();
            var selected = selectedPoints.Select(x => x).ToList();

            var matrixDimension = (int)Math.Sqrt(selectedPoints.Count());

            if (matrixDimension * matrixDimension != selected.Count)
            {
                return selectedPoints;
            }

            for (int i = 0; i < matrixDimension; i++)
            {
                //take each sqrt(elementCount) topmost elements from original list, order them by X coordinate,
                //add to new list and remove from original
                sortedList.AddRange(
                    selected
                    .OrderBy(point => point.Location.Y)
                    .Take(matrixDimension)
                    .OrderBy(point => point.Location.X));

                foreach (var item in sortedList)
                {
                    selected.Remove(item);
                }
            }

            return sortedList;
        }
Example #26
0
        private void Init(IList<Point> vertices )
        {
            if (vertices == null || vertices.Count() < 2)
                throw new ArgumentException("vertices being passed to create line is not valid.");

            Vertices = new List<Point>(vertices);
        }
Example #27
0
        public InterlockDataAdapter(OleDbDataReader dr ,IList<string> dynamicList, int startColumn)
        {
            ControlSystemName = string.Empty;
            InterlockTypeName =
            Number = string.Empty;
            Cause = string.Empty;
            Description = string.Empty;

            ControlSystemName = dr.SafeString((int)InterlockColumn.ControlSystemName).Trim();
            InterlockTypeName = dr.SafeString((int)InterlockColumn.InterlockType).Trim();
            Number = dr.SafeString((int)InterlockColumn.Number).Trim();
            Cause = dr.SafeString((int)InterlockColumn.Cause).Trim();
            Description = dr.SafeString((int)InterlockColumn.Description).Trim();

            DynamicProperties = new List<DynamicProperty>();

            if (dynamicList != null && dynamicList.Any())
            {
                for (int d = 0; d < dynamicList.Count(); d++)
                {
                    string p = dynamicList[d];

                    DynamicProperty property = new DynamicProperty();

                    property.PropertyName = p;
                    property.PropertyValue = dr.SafeString(startColumn + d);

                    DynamicProperties.Add(property);
                }
            }
        }
Example #28
0
		public static Schedule Empty = new Schedule(); // Null object pattern

		/// <summary>
		/// Creates an instance of <see cref="Schedule"/> from carrier mouvements.
		/// </summary>
		/// <param name="carrierMovements"></param>
		public Schedule(IList<CarrierMovement> carrierMovements)
		{
			// check if not null
			if (carrierMovements == null)
				throw new ArgumentNullException("carrierMovements");    

			// no null elements
			if (carrierMovements.Count() > 0 && carrierMovements.ToList().Exists(carrierMovement => carrierMovement == null))
				throw new ArgumentException("carrierMovements contains null elements.");

			// no elements
			if (carrierMovements.Count() == 0)
				throw new ArgumentException("carrierMovements has no elements.");

			_carrierMouvements = carrierMovements;
		}
Example #29
0
        /// <summary>
        /// Joins the specified lists.
        /// </summary>
        /// <param name="xList">The list with the propertie x active.</param>
        /// <param name="yList">The list with the propertie y active.</param>
        /// <param name="group">The group aplicable to each element.</param>
        /// <returns>The joined list</returns>
        private static IEnumerable<OutputClass> Join(IList<InputClass> xList, IList<InputClass> yList, string group)
        {
            var outputObject = new OutputClass()
            {
                ClassAB = group,
                Y = 0,
                X = 0
            };

            var countX = xList.Count();

            var countY = yList.Count();

            var count = countY > countX ? countY : countX;

            var array = Enumerable.Repeat(outputObject, count).ToArray();

            var iteratorX = new Iterator(xList);
            var iteratorY = new Iterator(yList);

            foreach (var outputClass in array)
            {
                outputClass.X = iteratorX.Next().Codigo;
                outputClass.Y = iteratorY.Next().Codigo;
                outputClass.ClassAB = group;
            }

            return array;
        }
Example #30
0
        /// <summary>
        /// Retrives the width columns.
        /// </summary>
        /// <param name="columns">The columns.</param>
        /// <returns>Dictionary{System.StringSystem.Int32}.</returns>
        private static Dictionary<string, int> RetriveWidthColumns(IList<string> columns)
        {
            var columnWidthList = new Dictionary<string, int>();

            if (columns != null && columns.Any())
            {
                if (columns[0].Contains(Constants.SplitVerticalBar))
                {
                    for (var i = 0; i < columns.Count(); i++)
                    {
                        var column = columns[i].Split(Constants.SplitVerticalBar);

                        var columnUniqName = !string.IsNullOrEmpty(column[0]) ? column[0] : string.Empty;

                        var columnWidth = 0;
                        try
                        {
                            columnWidth = !string.IsNullOrEmpty(column[1]) && column[1].Length > 1 ? Convert.ToInt32(column[1], CultureInfo.InvariantCulture) : 0;
                        }
                        catch
                        {
                        }

                        columnWidthList[columnUniqName.Trim()] = columnWidth;
                    }
                }
            }

            return columnWidthList;
        }