Example #1
1
        void IDumpableAsText.DumpAsText(TextWriter writer)
        {
            var pbag = new List<KeyValuePair<String, String>>();
            Func<KeyValuePair<String, String>, String> fmt = kvp =>
            {
                var maxKey = pbag.Max(kvp1 => kvp1.Key.Length);
                return String.Format("    {0} : {1}", kvp.Key.PadRight(maxKey), kvp.Value);
            };

            Action<String> fillPbag = s =>
            {
                foreach (var line in s.SplitLines().Skip(1).SkipLast(1))
                {
                    var m = Regex.Match(line, "^(?<key>.*?):(?<value>.*)$");
                    var key = m.Result("${key}").Trim();
                    var value = m.Result("${value}").Trim();
                    pbag.Add(new KeyValuePair<String, String>(key, value));
                }
            };

            writer.WriteLine("Device #{0} \"{1}\" (/pci:{2}/dev:{3})", Index, Name, PciBusId, PciDeviceId);
            fillPbag(Simd.ToString());
            fillPbag(Clock.ToString());
            fillPbag(Memory.ToString());
            fillPbag(Caps.ToString());
            pbag.ForEach(kvp => writer.WriteLine(fmt(kvp)));
        }
Example #2
0
 private void DisplayWinner()
 {
     votes = new List<int>();
     votes.Add(toyStoryCount);
     votes.Add(starWarsCount);
     votes.Add(avengersCount);
     votes.Add(northCount);
     Console.WriteLine("");
     if (toyStoryCount == votes.Max())
     {
         Console.WriteLine("Toy Story wins with {0} votes", toyStoryCount);
     }
     else if (starWarsCount == votes.Max())
     {
         Console.WriteLine("Star Wars wins with {0} votes", starWarsCount);
     }
     else if (avengersCount == votes.Max())
     {
         Console.WriteLine("Avengers: Age of Ultron wins with {0} votes", avengersCount);
     }
     else if (northCount == votes.Max())
     {
         Console.WriteLine("North by Northwest wins with {0} votes", northCount);
     }
     else
     {
         Console.WriteLine("It's a tie");
     }
 }
Example #3
0
 private static TableLayoutPanel GetLayoutPanel(List<List<Control>> controls)
 {
     int columnCount = controls.Max(list => list.Count);
     var layoutPanel = new TableLayoutPanel
                                {
                                    ColumnCount = columnCount,
                                    RowCount = controls.Count,
                                    Dock = DockStyle.Fill,
                                    Location = new Point(0, 0),
                                    Name = "layoutPanel",
                                    BorderStyle =  BorderStyle.Fixed3D
                                };
     int horizontalMargin = layoutPanel.Margin.Horizontal;
     for (int columnIndex = 0; columnIndex < columnCount; columnIndex++)
     {
         int controlIndex = columnIndex;
         bool columnExists = controls.Count - 1 >= columnIndex;
         try
         {
             int columnWidth = !columnExists ? 0 : controls.Max(control => control.Count <= controlIndex || control[controlIndex] == null
                                                                             ? 0 : control[controlIndex].Width 
                                                                                   + control[controlIndex].Margin.Horizontal) 
                                                                                   + horizontalMargin;
             layoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, columnWidth));
         }
         catch (Exception e)
         {
             Console.WriteLine(e);
         }
     }
     return layoutPanel;
 }
Example #4
0
 private static Map ParseMap(string zone, string[] lines) {
     Map tmpMap = new Map();
     tmpMap.zone = zone;
     if (tmpMap.zone != "") {
         List<MapLineSegment> segmentList = new List<MapLineSegment>();
         foreach (string l in lines) {
             if (l[0] == 'L') {
                 segmentList.Add(ParseSegment(l));
             }
             else if (l[0] == 'P') {
                 //parse place
             }
         }
         //group up line segments according to color(RGB) value, then create one pen for each color used
         //this should greatly lower the overhead for creating brush and pen objects 
         //*edit* aparently not.
         List<MapLineSegment> distinctSegments = segmentList.Distinct(new MapLineSegmentColorComparer()).ToList();
         foreach (MapLineSegment colorSource in distinctSegments) {
             List<MapLineSegment> tmpSegmentList = segmentList.FindAll(x => x.color == colorSource.color);
             SolidColorBrush colorBrush = new SolidColorBrush(colorSource.color);
             Pen tmpPen = new Pen(colorBrush, 1.0);
             tmpMap.lineList.Add(new MapLine(tmpSegmentList, tmpPen));
         }
         if (segmentList.Count > 0) {
             tmpMap.maxX = Math.Max(segmentList.Max(x => x.aX), segmentList.Max(x => x.bX));
             tmpMap.maxY = Math.Max(segmentList.Max(x => x.aY), segmentList.Max(x => x.bY));
             tmpMap.minX = Math.Min(segmentList.Min(x => x.aX), segmentList.Min(x => x.bX));
             tmpMap.minY = Math.Min(segmentList.Min(x => x.aY), segmentList.Min(x => x.bY));
             tmpMap.width = tmpMap.maxX - tmpMap.minX;
             tmpMap.height = tmpMap.maxY - tmpMap.minY;
             tmpMap.depth = tmpMap.maxZ - tmpMap.minZ;
         }
     }
     return tmpMap;
 }
Example #5
0
    static void Main()
    {
        string input = Console.ReadLine();

        List<decimal> inputNums = new List<decimal>();
        List<decimal> oddNums = new List<decimal>();
        List<decimal> evenNums = new List<decimal>();

        string[] numbers = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (var num in numbers)
        {
            inputNums.Add(decimal.Parse(num));
        }

        int index = 1;

        for (int i = 0; i < inputNums.Count; i++)
        {

            if (index % 2 == 1)
            {
                oddNums.Add(inputNums[i]);
            }
            else
            {
                evenNums.Add(inputNums[i]);
            }

            index++;
        }

        if (inputNums.Count == 0)
        {
            Console.WriteLine("OddSum=No, OddMin=No, OddMax=No, EvenSum=No, EvenMin=No, EvenMax=No");
        }

        else if (inputNums.Count == 1)
        {
            double oddNumsSum = (double)oddNums.Sum();
            double oddNumsMin = (double)oddNums.Min();
            double oddNumsMax = (double)oddNums.Max();
            
            Console.WriteLine("OddSum={0:G0}, OddMin={1:G0}, OddMax={2:G0}, EvenSum=No, EvenMin=No, EvenMax=No",
                oddNumsSum, oddNumsMin, oddNumsMax);
        }

        else
        {
            double oddNumsSum = (double)oddNums.Sum();
            double oddNumsMin = (double)oddNums.Min();
            double oddNumsMax = (double)oddNums.Max();
            double evenNumsSum = (double)evenNums.Sum();
            double evenNumsMin = (double)evenNums.Min();
            double evenNumsMax = (double)evenNums.Max();

            Console.WriteLine("OddSum={0:G0}, OddMin={1:G0}, OddMax={2:G0}, EvenSum={3:G0}, EvenMin={4:G0}, EvenMax={5:G0}",  // {...:G0} Remove trailing zeros
                oddNumsSum, oddNumsMin, oddNumsMax, evenNumsSum, evenNumsMin, evenNumsMax);
        }
    }
Example #6
0
        internal static void Process()
        {
            Console.WriteLine("Day 2");
              int totPaper = 0;
              int totRibbon = 0;

              for (int i = 0; i < Day02.Input.Count; i++)
              {
            var inpLine = Day02.Input[i];
            int len = int.Parse(inpLine.Split('x')[0]);
            int width = int.Parse(inpLine.Split('x')[1]);
            int height = int.Parse(inpLine.Split('x')[2]);

            var lst = new List<int> { len, width, height };
            var smallest = lst.FindAll(d => d < lst.Max());

            if (smallest.Count == 1)
              smallest.Add(lst.Max());
            else if (smallest.Count == 0)
            {
              smallest.Add(lst.Max());
              smallest.Add(lst.Max());
            }

            totPaper += (2 * len * width) + (2 * width * height) + (2 * height * len) + ((int)smallest[0] * (int)smallest[1]);
            totRibbon += (2 * smallest[0]) + (2 * smallest[1]) + (len * width * height);
              }

              Console.WriteLine("  The elves should order " + totPaper + " sqft of wrapping-paper, and " + totRibbon + " feet of ribbon...");
        }
Example #7
0
        static void Main(string[] args)
        {
            int[] arr = new int[5];                                                 // array to keep numbers from user
            List<int> lista = new List<int>();                                      // list to keep all odd numbers from users numbers

            Console.WriteLine("Values for the array:");

            for (int i = 0; i < arr.Length; i++)                                    // loop taking numbers from user
            {
                Console.Write("Value for index {0}:", i);
                arr[i] = int.Parse(Console.ReadLine());
            }

            foreach (int x in arr)                                                  // loop adding all odd numbers(taken from arr[])
            {                                                                       // to lista (doasn't working on page if not x!=1)
                if (x % 2 != 0 & x != 1)
                    lista.Add(x);
            }

            for (int i = 0; i < arr.Length; i++)                                    // if we meet zero in lista, loop is looking for a max odd number from lista
            {                                                                       // and replace zero this number, next remove this number from lista
                if (arr[i] == 0 & lista.Count > 0)
                {
                    arr[i] = lista.Max();
                    lista.Remove(lista.Max());
                }
            }

            for (int i = 0; i < arr.Length; i++)
            {
                Console.WriteLine(arr[i]);
            }
        }
Example #8
0
        static void Main(string[] args)
        {
            var players = new List<Player>();
            var shaker = new DiceShaker();

            for (var i = 0; i < 100; i++)
            {
                var player = Factory.CreatePlayer(shaker);
                System.Console.WriteLine(string.Format("Player {0}:\r\nThrowing Power: {1}\r\nTAS: {2}:\r\nTAM: {3}",
                    i,
                    player.ThrowPower.GetValue<double>(),
                    player.ThrowAccuracyShort.GetValue<double>(),
                    player.ThrowAccuracyMid.GetValue<double>()));
                players.Add(player);
            }

            var maxPotential = players.Select(w => w.GetPotential()).Max();
            var bestPlayer = players.First(w => w.GetPotential() == maxPotential);

            var maxMidAcc = players.Max(w => w.ThrowAccuracyMid.GetValue<double>());

            bestPlayer = players.First(w => w.ThrowAccuracyMid.GetValue<double>() == maxMidAcc);

            var maxShortAcc = players.Max(w => w.ThrowAccuracyShort.GetValue<double>());

            bestPlayer = players.First(w => w.ThrowAccuracyShort.GetValue<double>() == maxShortAcc);

            if (bestPlayer != null)
            {

            }
        }
Example #9
0
    private void ShowSampleItems_Click(object sender, EventArgs e) {
      // create some sample items;

      MyMap.MapElements.Clear();
      MyMap.Layers.Clear();

      var bounds = new List<LocationRectangle>();
      foreach (var area in DataManager.SampleAreas) {
        var shape = new MapPolygon();
        foreach (var parts in area.Split(' ').Select(cord => cord.Split(','))) {
          shape.Path.Add(new GeoCoordinate(double.Parse(parts[1], ci), double.Parse(parts[0], ci)));
        }

        shape.StrokeThickness = 3;
        shape.StrokeColor = Colors.Blue;
        shape.FillColor = Color.FromArgb((byte)0x20, shape.StrokeColor.R, shape.StrokeColor.G, shape.StrokeColor.B);
        bounds.Add(LocationRectangle.CreateBoundingRectangle(shape.Path));
        MyMap.MapElements.Add(shape);
      }

      var rect = new LocationRectangle(bounds.Max(b => b.North), bounds.Min(b => b.West), bounds.Min(b => b.South), bounds.Max(b => b.East));
      MyMap.SetView(rect);

      // show all Items
      var itemsLayer = new MapLayer();
      foreach (var item in DataManager.SampleItems) {
        DrawItem(item, "Ulm", itemsLayer);
      }

      MyMap.Layers.Add(itemsLayer);
    }
Example #10
0
    static void Main()
    {
        var numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

        var odd = numbers.WhereNot(x => x % 2 == 0);
        Console.WriteLine(string.Join(" ", odd));

        var numbersBiggerThanTen = numbers.WhereNot(LessThanTen);
        Console.WriteLine(string.Join(" ", numbersBiggerThanTen));
        Console.WriteLine();

        var students = new List<Student>()
        {
            new Student("Stavri",5.5),
            new Student("Loshiq",2),
            new Student("Me4a", 3.50),
            new Student("Anatoli", 4.4),
            new Student("Rambo", 5.95)
        };

        Console.WriteLine(students.Max(student => student.Grade));
        Console.WriteLine(students.Min(Grade));

        Console.WriteLine();
        Console.WriteLine(students.Max(Name));
        Console.WriteLine(students.Min(student => student.Name));
    }
        //this method checks the rows
        private static string CheckHorizontals(string[,] theMatrix, int rows, int cols)
        {
            List<string> bestLine = new List<string>();

            for (int row = 0; row < rows; row++)
            {
                string nextLine = string.Empty;

                for (int col = 0; col < cols - 1; col++)
                {
                    if (col == 0)
                    {
                        nextLine += theMatrix[row, col] + ", ";
                    }

                    if (theMatrix[row, col + 1].Equals(theMatrix[row, col]))
                    {
                        nextLine += theMatrix[row, col + 1] + ", ";
                    }
                }

                bestLine.Add(nextLine);
            }

            if (bestLine.Count > 0)
            {
                return bestLine.Max().ToString().Substring(0, bestLine.Max().Length - 2);
            }
            else
            {
                return string.Empty;
            }
        }
Example #12
0
        public static Vector3 BestCircularFarmLocation(int radius, int range, int minMinions = 3)
        {
            var minions = EntityManager.MinionsAndMonsters.CombinedAttackable.Where(it => !it.IsDead && it.IsValidTarget(range));

            if (minions.Any() && minions.Count() == 1) return default(Vector3);

            var hitsperminion = new List<int>();
            int hits = new int();

            for (int i = 0; i < minions.Count(); i++)
            {
                hits = 1;

                for (int j = 0; j < minions.Count(); j++)
                {
                    if (j == i) continue;

                    if (minions.ElementAt(i).Distance(minions.ElementAt(j)) <= radius) hits++;
                }

                hitsperminion.Add(hits);
            }

            if (hitsperminion.Any() && hitsperminion.Max() > minMinions)
            {
                var pos = minions.ElementAt(hitsperminion.IndexOf(hitsperminion.Max())).ServerPosition;

                return pos;
            }

            return default(Vector3);
        }
        private void AddPlotSeries(List<Tuple<double, double>> ansv, double stepX, double stepY)
        {
            _stepX = stepX;
            _stepY = stepY;
            if (!_firstLoaded)
                DrawGrid(ansv.Min(item => item.Item1), ansv.Max(item => item.Item1), stepX,
                    ansv.Min(item => item.Item2), ansv.Max(item => item.Item2), stepY);

            MyCanvas.Children.Add(GenerateSeriesPath(ansv));
        }
 private static int[] ExtractOfMaxNumbers(List<int> list, int k)
 {
     List<int> maxNumbers = new List<int>();
     for (int i = 0; i < k; i++)
     {
         maxNumbers.Add(list.Max());
         list.Remove(list.Max());
     }
     return maxNumbers.ToArray();
 }
    static void Main()
    {
        string numbersString = Console.ReadLine();
        if (numbersString == "")
        {
            Console.WriteLine("OddSum=No, OddMin=No, OddMax=No, EvenSum=No, EvenMin=No, EvenMax=No");
        }

        else
        {
            decimal[] numbers = Array.ConvertAll(numbersString.Split(' '), decimal.Parse);


            List<decimal> odd = new List<decimal>();
            List<decimal> even = new List<decimal>();


            for (int i = 0; i < numbers.Length; i++)
            {
                if (i % 2 == 0)
                {
                    odd.Add(numbers[i]);

                }
                else
                {
                    even.Add(numbers[i]);
                }
            }
            if ((odd.Count == 0 && even.Count == 0) || numbersString == "")
            {
                Console.WriteLine("OddSum=No, OddMin=No, OddMax=No, EvenSum=No, EvenMin=No, EvenMax=No");
            }
            if (even.Count == 0)
            {
                decimal oddSum = odd.Sum();
                decimal oddMin = odd.Min();
                decimal oddMax = odd.Max();
                Console.WriteLine("OddSum={0:0.##}, OddMin={1:0.##}, OddMax={2:0.##}, EvenSum=No, EvenMin=No, EvenMax=No", oddSum, oddMin, oddMax);
            }
            else
            {
                decimal oddSum = odd.Sum();
                decimal oddMin = odd.Min();
                decimal oddMax = odd.Max();

                decimal evenSum = even.Sum();
                decimal evenMin = even.Min();
                decimal evenMax = even.Max();

                Console.WriteLine("OddSum={0:0.##}, OddMin={1:0.##}, OddMax={2:0.##}, EvenSum={3:0.##}, EvenMin={4:0.##}, EvenMax={5:0.##}"
                                            , oddSum, oddMin, oddMax, evenSum, evenMin, evenMax);
            }
        }    
    }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="table"></param>
        /// <param name="chart"></param>
        /// <param name="indexAxisX"></param>
        /// <param name="indexAxisY"></param>
        public void Plot(DataTable table, Chart chart, int indexAxisX, int indexAxisY)
        {
            if (HasNull(table))
            {
                MessageBox.Show(@"Iterate data first!");
            }
            else
            {
                try
                {
                    var xValue = new List<double>();
                    var yValue = new List<double>();

                    foreach (var series in chart.Series)
                    {
                        series.Points.Clear();
                    }

                    for (var i = 1; i < table.Columns.Count; i++)
                    {
                        xValue.Add(
                            Convert.ToDouble(table.Rows[indexAxisX][i].ToString()));
                        yValue.Add(
                            Convert.ToDouble(table.Rows[indexAxisY][i].ToString()));
                    }

                    if (Math.Abs(xValue.Min() - xValue.Max()) < 0.0000001 ||
                        Math.Abs(yValue.Min() - yValue.Max()) < 0.0000001)
                    {
                        MessageBox.Show(@"The selected data cannot be charted!");
                    }
                    else
                    {
                        chart.Series[0].Points.DataBindXY(xValue, yValue);
                        chart.Series[0].ChartType = SeriesChartType.FastLine;
                        chart.Series[0].Color = Color.Black;
                        chart.ChartAreas[0].AxisX.Maximum = xValue.Max();
                        chart.ChartAreas[0].AxisX.Minimum = xValue.Min();
                        chart.ChartAreas[0].AxisY.Maximum = yValue.Max();
                        chart.ChartAreas[0].AxisY.Minimum = yValue.Min();
                        chart.ChartAreas[0].AxisX.MajorGrid.Enabled = true;
                        chart.ChartAreas[0].AxisY.MajorGrid.Enabled = true;
                        chart.ChartAreas[0].AxisX.Title =
                            table.Rows[indexAxisX][0].ToString();
                        chart.ChartAreas[0].AxisY.Title =
                            table.Rows[indexAxisY][0].ToString();
                        chart.Series[0].IsVisibleInLegend = false;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(@"Chart error: " + ex.Message);
                }
            }
        }
Example #17
0
 public static Point MaxPoint( List<Point> points, Axis axis )
 {
     double max;
     if(axis == Axis.X)
     {
         max = points.Max(p => p.X);
         return points.FirstOrDefault(p => DoubleCompare(p.X, max));
     }
     max = points.Max(p => p.Y);
     return points.FirstOrDefault(p => DoubleCompare(p.Y, max));
 }
        public static IList<Player> CreatePlayerList(int goalkeepers, int defenders, int midfielders, int forwards, int startingId = 0)
        {
            var players = new List<Player>();

            players.AddRange(CreatePlayers(startingId, Position.Goalkeeper, goalkeepers));
            players.AddRange(CreatePlayers(players.Max(p => p.Id), Position.Defender, defenders));
            players.AddRange(CreatePlayers(players.Max(p => p.Id), Position.Midfielder, midfielders));
            players.AddRange(CreatePlayers(players.Max(p => p.Id), Position.Forward, forwards));

            return players;
        }
Example #19
0
		public VectorPath(List<VectorPathSegment> seg)
		{
			segments = seg;
			Length = segments.Sum(p => p.Length);

			float top = segments.Min(p => p.Boundings.Top);
			float bot = segments.Max(p => p.Boundings.Bottom);
			float lef = segments.Min(p => p.Boundings.Left);
			float rig = segments.Max(p => p.Boundings.Right);

			Boundings = new FRectangle(lef, top, rig-lef, bot-top);
		}
Example #20
0
        public Rectangle boundingRectangle(List<Point> points)
        {
            // Add checks here, if necessary, to make sure that points is not null,
            // and that it contains at least one (or perhaps two?) elements

            var minX = points.Min(p => p.X);
            var minY = points.Min(p => p.Y);
            var maxX = points.Max(p => p.X);
            var maxY = points.Max(p => p.Y);

            return new Rectangle(new Point(minX, minY), new Size(maxX - minX, maxY - minY));
        }
Example #21
0
        private List<int> GetYearsToQueryFor()
        {
            var latestSuperRugbyYear = Int32.Parse(ConfigurationManager.AppSettings["LatestSuperRugbyYear"]);
            var yearsToGet = new List<int>();
            yearsToGet.Add(2006);

            while (yearsToGet.Max() < latestSuperRugbyYear)
            {
                yearsToGet.Add(yearsToGet.Max() + 1);
            }

            return yearsToGet;
        }
Example #22
0
 public static void GetEnvelope(double lat, double lon, double dist, out double minLat, out double minLon, out double maxLat, out double maxLon)
 {
     var gc = new GeodeticCalculator();
     var endpoints = new List<GlobalCoordinates>();
     endpoints.Add(gc.CalculateEndingGlobalCoordinates(Ellipsoid.WGS84, new GlobalCoordinates(new Angle(lat), new Angle(lon)), new Angle(0), dist * 1000.0));
     endpoints.Add(gc.CalculateEndingGlobalCoordinates(Ellipsoid.WGS84, new GlobalCoordinates(new Angle(lat), new Angle(lon)), new Angle(90), dist * 1000.0));
     endpoints.Add(gc.CalculateEndingGlobalCoordinates(Ellipsoid.WGS84, new GlobalCoordinates(new Angle(lat), new Angle(lon)), new Angle(180), dist * 1000.0));
     endpoints.Add(gc.CalculateEndingGlobalCoordinates(Ellipsoid.WGS84, new GlobalCoordinates(new Angle(lat), new Angle(lon)), new Angle(270), dist * 1000.0));
     minLat = endpoints.Min(x => x.Latitude.Degrees);
     maxLat = endpoints.Max(x => x.Latitude.Degrees);
     minLon = endpoints.Min(x => x.Longitude.Degrees);
     maxLon = endpoints.Max(x => x.Longitude.Degrees);
 }
Example #23
0
    static int ReturnMaxAfterN(int N, params int[] arr)
    {
        //Make new array that contain all ints from "arr" after N
        List<int> arrSec = new List<int> { };
        for (int i = N, j = 0; i < arr.Length; i++, j++)
        {
            arrSec.Add(arr[i]);
        }
        int max = arrSec.Max();
        arrSec.Remove(arrSec.Max());

        return max;
    }
        public static DataClasses.CustomProgram GetCustomProgramRemotePB(int UserID)
        {
            DataClasses.GrucoxDataClassesRemoteDBDataContext dc = new DataClasses.GrucoxDataClassesRemoteDBDataContext();
            DataClasses.CustomProgram customProgramPB = new DataClasses.CustomProgram();
            List<DataClasses.GrucoxCustomProgramSession> ListcustomProgramPB = new List<DataClasses.GrucoxCustomProgramSession>();

            try
            {
                ListcustomProgramPB = (from sessions in dc.GetTable<DataClasses.GrucoxCustomProgramSession>()
                                       where sessions.LiveUserID == UserID
                                       select sessions).ToList<DataClasses.GrucoxCustomProgramSession>();
            }
            catch (Exception)
            {
                //For Diagnostics - Should be removed
                DataComms.CreateThreadInstance("DB Access during GetCustomProgramRemotePB");
            }
            finally
            {
                customProgramPB.LeftAvgConcP = ListcustomProgramPB.Max(z => z.LeftAvgConcP).HasValue ? (double)ListcustomProgramPB.Max(z => z.LeftAvgConcP) : 0.0;
                customProgramPB.LeftAvgEcceP = ListcustomProgramPB.Max(z => z.LeftAvgEcceP).HasValue ? (double)ListcustomProgramPB.Max(z => z.LeftAvgEcceP) : 0.0;
                customProgramPB.RightAvgConcP = ListcustomProgramPB.Max(z => z.RightAvgConcP).HasValue ? (double)ListcustomProgramPB.Max(z => z.RightAvgConcP) : 0.0;
                customProgramPB.RightAvgEcceP = ListcustomProgramPB.Max(z => z.RightAvgEcceP).HasValue ? (double)ListcustomProgramPB.Max(z => z.RightAvgEcceP) : 0.0;
            }
            return customProgramPB;
        }
Example #25
0
        public void Test()
        {
            Func<Entity, int> query = e => e.Count;

            var mockData = new List<Entity>
                {
                    new Entity() {Age = 20,Count = 1},
                    new Entity() {Age = 40,Count = 1},
                    new Entity() {Age = 60,Count = 1},
                };

            int a = mockData.Max(e => e.Count);
            int b = mockData.Max(query);
        }
Example #26
0
		public System.Drawing.Bitmap DrawBitmap(List<MazeImagePoint> labiryntImagePointCollection, int step)
		{
			int width = labiryntImagePointCollection.Max(obj => obj.X + 1) * step;
			int height = labiryntImagePointCollection.Max(obj => obj.Y + 1) * step;
			System.Drawing.Bitmap maze = new System.Drawing.Bitmap(width, height);
			int startX = 0;
			int endX = width - 1;
			int startY = 0;
			int endY = height - 1;

			using (var editor = System.Drawing.Graphics.FromImage(maze))
			{
				editor.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Black, 1), startX, startY, endX, endY);
			}

			foreach (MazeImagePoint labiryntImagePoint in labiryntImagePointCollection)
			{
				if (labiryntImagePoint.Operation == Operation.Nothing)
				{
					continue;
				}
				if (labiryntImagePoint.Operation == Operation.Right
					|| labiryntImagePoint.Operation == Operation.RightDown)
				{
					startX = labiryntImagePoint.X * step;
					endX = (labiryntImagePoint.X + 1) * step;
					startY = labiryntImagePoint.Y * step;
					endY = labiryntImagePoint.Y * step;
					using (var editor = System.Drawing.Graphics.FromImage(maze))
					{
						editor.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Black, 3), startX, startY, endX, endY);
					}
				}
				if (labiryntImagePoint.Operation == Operation.Down
					|| labiryntImagePoint.Operation == Operation.RightDown)
				{
					startX = labiryntImagePoint.X * step;
					endX = labiryntImagePoint.X * step;
					startY = labiryntImagePoint.Y * step;
					endY = (labiryntImagePoint.Y + 1) * step;
					using (var editor = System.Drawing.Graphics.FromImage(maze))
					{
						editor.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Black, 3), startX, startY, endX, endY);
					}
				}
			}
			return maze;
		}
 static void Main()
 {
     Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
     float[] allNumbers = Console.ReadLine().Split(' ').Select(float.Parse).ToArray();
     List<float> fpNumbers = new List<float> { };
     List<int> integerNumbers = new List<int> { };
     for (int index = 0; index < allNumbers.Length; index++)
     {
         if (allNumbers[index].ToString().Contains('.'))
         {
             fpNumbers.Add(allNumbers[index]);
         }
         else
         {
             integerNumbers.Add((int)allNumbers[index]);
         }
     }
     Console.WriteLine("[{0}] -> min: {1}, max: {2}, sum: {3}, avg: {4:f2}"
         , string.Join(", ", fpNumbers)
         , fpNumbers.Min()
         , fpNumbers.Max()
         , fpNumbers.Sum()
         , fpNumbers.Average());
     Console.WriteLine("[{0}] -> min: {1}, max: {2}, sum: {3}, avg: {4:f2}"
         , string.Join(", ", integerNumbers)
         , integerNumbers.Min()
         , integerNumbers.Max()
         , integerNumbers.Sum()
         , integerNumbers.Average());
 }
        public ActionResult Index(int id, List<int> grSel) {
            var db = new ZkDataContext();
            var post = db.ForumPosts.Find(id);

            string txt1;
            string txt2;

            if (grSel != null && grSel.Any())
            {
                if (grSel.Count > 1)
                {
                    txt1 = db.ForumPostEdits.Find(grSel.Min()).NewText;
                    txt2 = db.ForumPostEdits.Find(grSel.Max()).NewText;
                } else
                {
                    var edit = db.ForumPostEdits.Find(grSel.First());
                    txt1 = edit.OriginalText;
                    txt2 = edit.NewText;
                }

                var sd = new SideBySideDiffBuilder(new Differ());
                ViewBag.DiffModel = sd.BuildDiffModel(txt1, txt2);
            } else
            {
                var edit = post.ForumPostEdits.OrderByDescending(x => x.ForumPostEditID).FirstOrDefault();
                if (edit != null)
                {
                    var sd = new SideBySideDiffBuilder(new Differ());
                    ViewBag.DiffModel = sd.BuildDiffModel(edit.OriginalText, edit.NewText);
                }
            }


            return View("PostHistoryIndex", post);
        }
Example #29
0
        /*
         Write a program that finds the most frequent number in an array. Example:
	        {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3}  4 (5 times)
         */
        static void Main(string[] args)
        {
            int[] sequence = { 4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3 };

            List<int> sequenceWithNoRepeatings = new List<int>();
            List<int> occurences = new List<int>();

            int indexToAddAt = 0;
            for (int i = 0; i < sequence.Length; i++)
            {
                indexToAddAt = 0;

                if (!sequenceWithNoRepeatings.Contains(sequence[i]))
                {
                    sequenceWithNoRepeatings.Add(sequence[i]);
                    occurences.Add(1);
                }
                else
                {
                    indexToAddAt = sequenceWithNoRepeatings.IndexOf(sequence[i]);
                    occurences[indexToAddAt]++;
                }
            }

            int maxOccurence = occurences.Max();
            int postion = occurences.IndexOf(maxOccurence);

            Console.WriteLine("Sequence: " + String.Join(",", sequence));
            Console.WriteLine(sequenceWithNoRepeatings[postion] + " -> " + occurences[postion] + " times");
        }
Example #30
0
        static void Main(string[] args)
        {
            string[] numbers = Console.ReadLine().Split(' ');
            List<double> floatingNumbers = new List<double>();
            List<int> integerNumbers = new List<int>();
            foreach(string number in numbers)
            {
                if (number.Contains("."))
                {
                    double number2 = double.Parse(number);

                    if (number2 % 1 == 0)
                    {
                        integerNumbers.Add(Convert.ToInt32(number2));
                    }
                    else
                    {
                        floatingNumbers.Add(number2);
                    }
                }
                else
                {
                    integerNumbers.Add(int.Parse(number));
                }
            }
            string output = string.Join(", ", floatingNumbers);
            Console.WriteLine("{0} -> min: {1:f2}, max: {2:f2}, sum: {3:f2}, avg: {4:f2}", output, floatingNumbers.Min(), floatingNumbers.Max(),
                floatingNumbers.Sum(), floatingNumbers.Average());
            output = string.Join(", ", integerNumbers);
            Console.WriteLine("{0} -> min: {1}, max: {2}, sum: {3}, avg: {4:f2}", output, integerNumbers.Min(), integerNumbers.Max(),
                integerNumbers.Sum(), integerNumbers.Average());
        }
        public async Task <IHttpActionResult> Post(int id, UserRatingsModel userRatings)
        {
            try
            {
                //1. Validate Model State
                if (ModelState.IsValid)
                {
                    List <BeersReviewsModel> results   = new List <BeersReviewsModel>();
                    List <RatingsEntity>     dbRatings = null;

                    //2. Validate if beer exisis in Punk API
                    var beer = await _beerRepository.GetBeer(id);

                    if (beer == null)
                    {
                        return(NotFound());
                    }

                    //3. If ID exists in Punk API, add rating and save to database.json
                    if (beer.Any())
                    {
                        //4. Read Json and increment Rating Id
                        dbRatings = JsonConvert.DeserializeObject <List <RatingsEntity> >(_jsonUtility.Read("database.json", "Data"));
                        var count = dbRatings?.Max(x => x.Id);
                        count = count == null ? 1 : count + 1;

                        //5. Create Ratings Entity to be saved to json
                        //   Beer ID mapping to user rating request before saving to json
                        var ratings = new RatingsEntity
                        {
                            Id          = count.Value,
                            UserRatings = userRatings,
                            BeerId      = id
                        };

                        //6. Add to json entity
                        dbRatings.Add(ratings);

                        //7. Write and Save to database.json
                        string dbRatingsJson = JsonConvert.SerializeObject(dbRatings);
                        _jsonUtility.Write("database.json", "Data", dbRatingsJson);

                        //8. Return Success with rating info
                        return(Ok(ratings));
                    }
                }
            }
            catch (Exception ex)
            {
                //Return Internal Server Error for unhandled exceptions
                return(InternalServerError(ex));
            }

            //Return Bad Request with error messages for invalid inputs
            return(BadRequest(ModelState));
        }
        /// <summary>
        /// Computes AnalysisXResultCell aggregated results
        /// </summary>
        /// <param name="lstAnalysis">
        /// List of <see cref="AnalysisProcessingResultColumnValue"/>
        /// </param>
        /// <param name="aggregationType">
        /// <see cref="AnalysisAggregationType"/> object
        /// </param>
        /// <param name="column">
        /// <see cref="AnalysisColumn"/> object.
        /// </param>
        /// <returns>
        /// List of <see cref="AnalysisXResultCell"/>
        /// </returns>
        private static List <AnalysisXResultCell> GetAnalysisXResultCells(
            List <AnalysisProcessingResultColumnValue> lstAnalysis,
            AnalysisAggregationType aggregationType,
            AnalysisColumn column)
        {
            var xResultCells    = new List <AnalysisXResultCell>();
            var xCategoryValues = column.XCategoryValues;

            foreach (var xCategoryValue in xCategoryValues)
            {
                var result = 0.0;
                if (aggregationType.Sum)
                {
                    result = lstAnalysis?.Sum(x => x.ResultForXCategoryValueKey(xCategoryValue.Key)) ?? result;
                }
                else if (aggregationType.Min)
                {
                    if (lstAnalysis?.Any() == true)
                    {
                        result = lstAnalysis.Min(x => x.ResultForXCategoryValueKey(xCategoryValue.Key));
                    }
                }
                else if (aggregationType.Max)
                {
                    result = lstAnalysis?.Max(x => x.ResultForXCategoryValueKey(xCategoryValue.Key)) ?? result;
                }
                else
                {
                    var count        = 0;
                    var currentCount = 0;
                    if (lstAnalysis?.Any() == true)
                    {
                        foreach (var colVal in lstAnalysis)
                        {
                            currentCount = colVal.CountForXCategoryValueKey(xCategoryValue.Key);
                            if (currentCount > 0)
                            {
                                result += colVal.ResultForXCategoryValueKey(xCategoryValue.Key) * currentCount;
                                count  += currentCount;
                            }
                        }
                    }

                    result = count > 0
                        ? result / count
                        : 0;
                }

                xResultCells.Add(new AnalysisXResultCell(result, column.ResultColumn.DisplayStringFromNumber(result)));
            }

            return(xResultCells);
        }
Example #33
0
        private void DrawTopPoints()
        {
            var z = cubeElements?.Max(c => c.Point5.Z);

            if (z != null)
            {
                cubeElements.Where(e => e.ToEnumerable()
                                   .Any(p => p.Z == z))
                .ToList()
                .ForEach(c => c.ToEnumerable()
                         .Where(p => p.Z == z)
                         .ToList()
                         .ForEach(p => DrawSphere(p)));
            }
        }
Example #34
0
        public void Show()
        {
            string text = $"_barcode: '{_barcode}'{Environment.NewLine} ";

            if (_millisecondsList.Count > 0)
            {
                text +=
                    $"min: {_millisecondsList?.Min()}, {Environment.NewLine}" +
                    $"max: {_millisecondsList?.Max()}, {Environment.NewLine}" +
                    $"avg: {_millisecondsList?.Average()} " +
                    Environment.NewLine + $"{string.Join("," + Environment.NewLine, _millisecondsList)}";
            }
            MessageBox.Show(text);
            _lastPress        = null;
            _millisecondsList = new List <double>();
            _barcode          = "";
        }
Example #35
0
 public Restaurant Add(Restaurant newRestaurant)
 {
     restaurants.Add(newRestaurant);
     newRestaurant.Id = restaurants.Max(r => r.Id) + 1;
     return(newRestaurant);
 }
Example #36
0
        private void UpdateData()
        {
            try
            {
                this.TopLevelControl.Cursor = Cursors.WaitCursor;
                this.TopLevelControl.Text   = "Updating...";
                lblRetrieved.Text           = DateTime.Now.ToString("HH:mm:ss") + " Retrieving Positions...";
                Application.DoEvents();

                List <IncomingDeliveryOrderObject> newActivity = new List <IncomingDeliveryOrderObject>();

                dof.Load(newActivity, calc.MaxDtcId);

                lblRetrieved.Visible = true;
                lblRetrieved.Text    = DateTime.Now.ToString("HH:mm:ss") + " Retrieved " + newActivity.Count + " Positions";

                foreach (IncomingDeliveryOrderObject d in newActivity)
                {
                    DtcChannel.Instance.DtcMessageReceived(d);
                }

                /* commented out because g1 activity wasnt being used and it takes a long time
                 * List<G1RealTimeActivityObject> tmp = new List<G1RealTimeActivityObject>();
                 * g1f.LoadNewActivity(tmp, 5000, Settings.BookName, calc.MaxG1Id);
                 *
                 * foreach (G1RealTimeActivityObject g in tmp)
                 * {
                 *  DtcChannel.Instance.G1MessageReceived(g);
                 * }
                 */

                calc.UpdateConduitInfo(AllRealTimePositions);

                //calc.UpdateNpbInfo(AllRealTimePositions);

                //ALANDIAS--------------------------------------------------------------
                //if (Settings.Account == "269")
                {
                    List <IncomingPledgeOrderObject> ListPOF = new List <IncomingPledgeOrderObject>();
                    IncomingPledgeOrderParam         IP      = new IncomingPledgeOrderParam();
                    IP.Id.AddParamValue(MaxPledgeId, ">");
                    IP.StatusIndicator.AddParamValue("m");
                    IP.PledgorParticipantNum.AddParamValue(Settings.Account.PadLeft(8, '0'));
                    POF.Load(ListPOF, IP);

                    if (ListPOF.Count != 0)
                    {
                        MaxPledgeId = ListPOF.Max(x => x.Id);

                        foreach (RealTimePositionObject RTPO in AllRealTimePositions)
                        {
                            foreach (IncomingPledgeOrderObject IPOO in ListPOF)
                            {
                                if (RTPO.Cusip == IPOO.Cusip)
                                {
                                    int qty = Convert.ToInt32(IPOO.ShareQuantityNew);
                                    if (IPOO.ActivityCode == "051")
                                    {
                                        RTPO.DtcNonNpbActivityQuantity -= qty;
                                    }

                                    if (IPOO.ActivityCode == "056")
                                    {
                                        RTPO.DtcNonNpbActivityQuantity += qty;
                                    }
                                }
                            }
                        }
                    }
                }
                //--------------------------------------------------------------
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex, TraceEnum.LoggedError);
                MessageBox.Show(ex.ToString(), "Error");
            }
            finally
            {
                this.TopLevelControl.Cursor = Cursors.Default;
                this.TopLevelControl.Text   = "";

                for (int i = 0; i < 10; i++)
                {
                    this.TopLevelControl.Text += " " + Settings.Account + " ";
                }
            }
        }
Example #37
0
        static void Main(string[] args)
        {
            // Find the words in the collection that start with the letter 'L'
            List <string> fruits = new List <string>()
            {
                "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry"
            };

            IEnumerable <string> startsWithL = from f in fruits
                                               where f.StartsWith("L")
                                               select f;

            foreach (string f in startsWithL)
            {
                Console.WriteLine($"{f}");
            }



            // Which of the following numbers are multiples of 4 or 6
            List <int> numbers = new List <int>()
            {
                15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96
            };

            IEnumerable <int> fourSixMultiples = numbers.Where(number => number % 4 == 0 || number % 6 == 0);


            foreach (int number in fourSixMultiples)
            {
                Console.WriteLine($"{number}");
            }



            // Order these student names alphabetically, in descending order (Z to A)
            List <string> names = new List <string>()
            {
                "Heather", "James", "Xavier", "Michelle", "Brian", "Nina",
                "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice",
                "Theodora", "William", "Svetlana", "Charisse", "Yolanda",
                "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline",
                "Francisco", "Tre"
            };

            IEnumerable <string> decend = from name in names
                                          orderby name descending
                                          select name;

            foreach (string name in decend)
            {
                Console.WriteLine(name);
            }

            //List numbers in ascending order (Lowest to Highest)
            List <int> moreNumbers = new List <int>()
            {
                15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96
            };

            IEnumerable <int> sortedNums = from nums in moreNumbers
                                           orderby nums ascending
                                           select nums;

            foreach (int nums in sortedNums)
            {
                Console.WriteLine(nums);
            }


            // Output how many numbers are in this list
            List <int> numbers3 = new List <int>()
            {
                15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96
            };
            int howMany = numbers3.Count();

            Console.WriteLine(howMany);



            // How much money have we made?
            List <double> purchases = new List <double>()
            {
                2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65
            };
            double totalPurchases = purchases.Sum();

            Console.WriteLine($"The sum of all the purchases is ${totalPurchases}");

            // What is our most expensive product?
            List <double> prices = new List <double>()
            {
                879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76
            };
            double mostExpensive = prices.Max();

            Console.WriteLine($"The most expensive product is ${mostExpensive}");



            /*
             *  Store each number in the following List until a perfect square
             *  is detected.
             *
             *  Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx
             */
            List <int> wheresSquaredo = new List <int>()
            {
                66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14
            };

            IEnumerable <int> perfSquare = wheresSquaredo.TakeWhile(num => Math.Sqrt(num) % 1 != 0);


            foreach (int num in perfSquare)
            {
                Console.WriteLine($"{num} is not a perfect square");
            }

            //create new list of banks and their symbols
            List <Bank> banks = new List <Bank>()
            {
                new Bank()
                {
                    Name = "First Tennessee", Symbol = "FTB"
                },
                new Bank()
                {
                    Name = "Wells Fargo", Symbol = "WF"
                },
                new Bank()
                {
                    Name = "Bank of America", Symbol = "BOA"
                },
                new Bank()
                {
                    Name = "Citibank", Symbol = "CITI"
                },
            };

            //create new list of customers
            List <Customer> customers = new List <Customer>()
            {
                new Customer()
                {
                    Name = "Bob Lesman", Balance = 80345.66, Bank = "FTB"
                },
                new Customer()
                {
                    Name = "Joe Landy", Balance = 9284756.21, Bank = "WF"
                },
                new Customer()
                {
                    Name = "Meg Ford", Balance = 487233.01, Bank = "BOA"
                },
                new Customer()
                {
                    Name = "Peg Vale", Balance = 7001449.92, Bank = "BOA"
                },
                new Customer()
                {
                    Name = "Mike Johnson", Balance = 790872.12, Bank = "WF"
                },
                new Customer()
                {
                    Name = "Les Paul", Balance = 8374892.54, Bank = "WF"
                },
                new Customer()
                {
                    Name = "Big Ol Dick", Balance = 957436.39, Bank = "FTB"
                },
                new Customer()
                {
                    Name = "Sarah Ng", Balance = 56562389.85, Bank = "FTB"
                },
                new Customer()
                {
                    Name = "Tina Fey", Balance = 1000000.00, Bank = "CITI"
                },
                new Customer()
                {
                    Name = "Sid Brown", Balance = 49582.68, Bank = "CITI"
                }
            };

            //writes each customer and their balance and where their account is
            foreach (Customer cust in customers)
            {
                Console.WriteLine($"{cust.Name} has ${cust.Balance} in thier {cust.Bank} account");
            }


            //creates a list of banks
            var bankList = customers.GroupBy(x => x.Bank);

            foreach (var bankMills in bankList)
            {
                Console.WriteLine("{0} - {1}", bankMills.Key, bankMills.Count(x => x.Balance >= 1000000));
            }


            IEnumerable <Customer> millionairs =
                from customer in customers
                where customer.Balance >= 1000000
                select customer;

            foreach (Customer millionair in millionairs)
            {
                Console.WriteLine(millionair.Name);
            }



            var MillionairReport =
                from millionair in millionairs
                join bank in banks on millionair.Bank equals bank.Symbol
                select new { Millionair = millionair.Name, Bank = bank.Name };

            foreach (var ballers in MillionairReport)
            {
                Console.WriteLine(ballers.Millionair + " " + ballers.Bank);
            }
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Debug.Listeners.Clear();
            Debug.Listeners.Add(new RbsLogger.Logger("AreeRebarMark"));
            Debug.WriteLine("Start area rebar mark");
            double offset = 0; //мм

            //собираю все элементы армирования по площади и траектории
            Document doc = commandData.Application.ActiveUIDocument.Document;
            FilteredElementCollector areas = new FilteredElementCollector(doc)
                                             .OfClass(typeof(Autodesk.Revit.DB.Structure.AreaReinforcement))
                                             .WhereElementIsNotElementType();
            FilteredElementCollector paths = new FilteredElementCollector(doc)
                                             .OfClass(typeof(Autodesk.Revit.DB.Structure.PathReinforcement))
                                             .WhereElementIsNotElementType();
            List <Element> col   = areas.Concat(paths).ToList();
            int            count = 0;

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Area rebar mark");
                //и Path, и Area попытаюсь обрабатываю в одном цикле, чтобы компактнее было
                foreach (Element rebarAreaPath in col)
                {
                    //благодаря hashset можно собрать только уникальный марки стержней
                    HashSet <string> marks           = new HashSet <string>();
                    string           rebarSystemMark = "";

                    List <ElementId> rebarIds = null;
                    List <ElementId> curveIds = null;

                    double maxZ = 0;
                    double minZ = 0;

                    if (rebarAreaPath is AreaReinforcement)
                    {
                        AreaReinforcement ar = rebarAreaPath as AreaReinforcement;
                        rebarIds = ar.GetRebarInSystemIds().ToList();
                        curveIds = ar.GetBoundaryCurveIds().ToList();

                        //определяю нижнюю и верзнюю точку зоны
                        List <double> zs = new List <double>();
                        foreach (ElementId curveId in curveIds)
                        {
                            AreaReinforcementCurve curve =
                                doc.GetElement(curveId) as AreaReinforcementCurve;

                            XYZ    start = curve.Curve.GetEndPoint(0);
                            double z1    = start.Z;
                            zs.Add(z1);

                            XYZ    end = curve.Curve.GetEndPoint(1);
                            double z2  = end.Z;
                            zs.Add(z2);
                        }

                        maxZ  = zs.Max();
                        maxZ += offset / 304.8;
                        minZ  = zs.Min();
                        minZ += offset / 304.8;
                    }

                    if (rebarAreaPath is PathReinforcement)
                    {
                        PathReinforcement pr = rebarAreaPath as PathReinforcement;
                        rebarIds = pr.GetRebarInSystemIds().ToList();

                        maxZ = pr.get_BoundingBox(doc.ActiveView).Max.Z;
                        minZ = pr.get_BoundingBox(doc.ActiveView).Min.Z;
                    }

                    //получаю общие параметры, в которые буду записывать отметку верха и низа, они должны быть заранее добавлены
                    Parameter topelev = rebarAreaPath.LookupParameter("АрмПлощ.ОтмВерха");
                    Parameter botelev = rebarAreaPath.LookupParameter("АрмПлощ.ОтмНиза");

                    if (topelev == null)
                    {
                        topelev = rebarAreaPath.LookupParameter("Рзм.ОтмВерха");
                    }
                    if (botelev == null)
                    {
                        botelev = rebarAreaPath.LookupParameter("Рзм.ОтмНиза");
                    }

                    if (topelev != null && botelev != null)
                    {
                        topelev.Set(maxZ);
                        botelev.Set(minZ);
                    }

                    //еще хочу записать в зону длину самого длинного арматурного стержня в ней
                    double length = 0;

                    //обрабатываю арматурные стержни в составе зоны
                    foreach (ElementId rebarId in rebarIds)
                    {
                        Element rebar     = doc.GetElement(rebarId);
                        string  rebarMark = rebar.get_Parameter(BuiltInParameter.ALL_MODEL_MARK).AsString();
                        marks.Add(rebarMark);
                        double tempLength = rebar.get_Parameter(BuiltInParameter.REBAR_ELEM_LENGTH).AsDouble();
                        if (tempLength > length)
                        {
                            length = tempLength;
                        }
                    }

                    //сортирую марки и записываю через запятую
                    List <string> marksList = marks.ToList();
                    marksList.Sort();
                    for (int i = 0; i < marks.Count; i++)
                    {
                        rebarSystemMark += marksList[i];
                        if (i < marks.Count - 1)
                        {
                            rebarSystemMark += ", ";
                        }
                    }
                    rebarAreaPath.get_Parameter(BuiltInParameter.ALL_MODEL_MARK).Set(rebarSystemMark);

                    //записываю длину арматуры а зону
                    Parameter lengthParam = rebarAreaPath.LookupParameter("Рзм.Длина");
                    if (lengthParam != null)
                    {
                        lengthParam.Set(length);
                    }

                    count++;
                }
                t.Commit();
            }

            BalloonTip.Show("Успешно!", "Обработано зон: " + count.ToString());
            Debug.WriteLine("Success, elements: " + count.ToString());

            return(Result.Succeeded);
        }
Example #39
0
        public List <DivisionLotesentradaLinModel> CrearUnaNuevaLineaEntrada(DivisionLotessalidaLinModel first, List <DivisionLotesentradaLinModel> listadoEntrada, double?cantidad)
        {
            //CODE
            DivisionLotesentradaLinModel d1 = new DivisionLotesentradaLinModel();

            d1.Cantidad = 1;

            if (listadoEntrada?.Count == 0)
            {
                d1.Id = 1;
            }

            else
            {
                d1.Id = (listadoEntrada?.Max(l => l.Id) ?? 0) + 1;
            }

            //Obtenemos la familoa a la que pertenece ese articulo
            var familiaService = FService.Instance.GetService(typeof(FamiliasproductosModel), _context, _db);
            var familiaObj     = familiaService.get(ArticulosService.GetCodigoFamilia(first.Fkarticulos)) as FamiliasproductosModel;

            //Si es una tabla, son metros cuadrados y el lote es el mismo pero la tabla es el maximo de la BD + 1
            if (familiaObj.Tipofamilia == TipoFamilia.Tabla)
            {
                d1.Cantidad = cantidad;

                d1.Largo  = first.Largo / 2;
                d1.Ancho  = first.Ancho;
                d1.Grueso = first.Grueso;
                d1.Metros = d1.Ancho * d1.Largo * d1.Cantidad;

                d1.Lote           = first.Lote;
                d1.LoteAutomatico = false;

                d1.Decimalesmonedas = first.Decimalesmonedas;
                d1.Decimalesmedidas = first.Decimalesmedidas;
            }

            //Si es un bloque, metros 3 y el lote es automatico
            else if (familiaObj.Tipofamilia == TipoFamilia.Bloque)
            {
                d1.Cantidad = cantidad;

                d1.Largo  = first.Largo / 2;
                d1.Ancho  = first.Ancho;
                d1.Grueso = first.Grueso;
                d1.Metros = d1.Ancho * d1.Largo * d1.Grueso * d1.Cantidad;

                d1.Tabla          = 0;
                d1.Lote           = "Lote " + ((listadoEntrada?.Count() ?? 0) + 1).ToString();
                d1.LoteAutomatico = true;

                d1.Decimalesmonedas = first.Decimalesmonedas;
                d1.Decimalesmedidas = first.Decimalesmedidas;
            }

            //Si son losas
            else
            {
                d1.Cantidad = cantidad;

                d1.Largo  = first.Largo;
                d1.Ancho  = first.Ancho;
                d1.Grueso = first.Grueso;

                d1.Metros         = d1.Largo * d1.Ancho * d1.Cantidad;
                d1.Tabla          = 0;
                d1.Lote           = "Lote " + ((listadoEntrada?.Count() ?? 0) + 1).ToString();
                d1.LoteAutomatico = true;

                d1.Decimalesmonedas = first.Decimalesmonedas;
                d1.Decimalesmedidas = first.Decimalesmedidas;
            }

            d1.Fkarticulos       = first.Fkarticulos;
            d1.Descripcion       = first.Descripcion;
            d1.Tipodealmacenlote = first.Tipodealmacenlote;
            d1.Fkunidades        = first.Fkunidades;
            d1.Canal             = first.Canal;

            listadoEntrada.Add(d1);

            return(listadoEntrada);
        }
Example #40
0
        static void Main(string[] args)
        {
            // lambda with array

            int[] arr = { 0, -1, 4, 5, 6, 9, -2, 3, 2, 10 };
            foreach (var a in arr.Where(n => n > 5))
            {
                Console.WriteLine(a);
            }
            string[] cities = { "Mumbai", "Chennai ", " Bengaluru", "Pune", "Patna" };
            foreach (var c in cities.Where(g => g.StartsWith("P")))
            {
                Console.WriteLine(c);
            }

            foreach (var d in cities.Where(y => y.Contains("e")))
            {
                Console.WriteLine(d);
            }


            var result = cities.Where(x => x.Contains("e"));

            Console.WriteLine(result.Count());

            // Lambda with collection

            // 3.5 collection initialzier

            // adding to colletion without using add collection

            List <Employee> emp = new List <Employee>
            {
                new Employee
                {
                    EmpId = 100, Name = "Martin", Dept = "IT", Salary = 3500
                },
                new Employee
                {
                    EmpId = 101, Name = "Martin Luther", Dept = "IT", Salary = 35000
                },
                new Employee
                {
                    EmpId = 102, Name = "Martin Luther King", Dept = "ITIA", Salary = 350000
                },
                new Employee
                {
                    EmpId = 103, Name = "Martin Luther King Jr.", Dept = "ITIAM", Salary = 3500000
                }
            };

            // display all values

            foreach (var r in emp)
            {
                Console.WriteLine(r.EmpId + " " + " " + r.Name + " " + r.Dept + " " + r.Salary);
            }


            var data = emp.Where(x => x.EmpId == 100).SingleOrDefault();

            if (data == null)
            {
                Console.WriteLine("Invalid emp id");
            }
            else
            {
                Console.WriteLine(data.EmpId + " " + data.Name + " " + data.Dept + " " + data.Salary);
            }

            var dat = emp.Where(x => x.Dept == "IT");

            if (dat.Count() == 0)
            {
                Console.WriteLine("Invalid dept name");
            }

            else
            {
                foreach (var r in dat)
                {
                    Console.WriteLine(r.EmpId + " " + r.Name + " " + r.Dept);
                }
            }


            // SELECT NAME SORTED IN ASC/DESC ORDER OF NAME

            var data2 = emp.OrderBy(x => x.Name).Select(y => y.Name);

            foreach (var d in data2)
            {
                Console.Write(d);
            }

            var data3 = emp.OrderByDescending(x => x.Name).Select(y => y.Name);

            foreach (var d in data3)
            {
                Console.WriteLine(d);
            }

            // Select - selects one property or it will select all properties
            // to Select name nad salary we used - Anonymous property
            // new { EmpName = e.Name , EmpSalary = e.Salary}


            var data5 = emp.Select(x => new { EmpName = x.Name, EmpSalary = x.Salary });

            foreach (var d in data5)
            {
                Console.WriteLine(d.EmpName + " " + d.EmpSalary);
            }


            // SUMMARY - COUNT OF EMPLOYESS DEPT WISE AND SUM OF SALARY PAID DEPT WISE

            // column on which thae group by is provided
            var grp = emp.GroupBy(x => x.Dept).Select(x => new { DeptName = x.Key, EmpCount = x.Count(), sumSalary = x.Sum(y => y.Salary) });

            foreach (var g in grp)
            {
                Console.WriteLine(g.DeptName + "  " + g.EmpCount + "  " + g.sumSalary);
            }


            Console.WriteLine("Max salary : " + emp.Max(x => x.Salary));
            Console.WriteLine("Min salary : " + emp.Min(x => x.Salary));


            var maxsal = emp.Where(x => x.Salary == emp.Max(y => y.Salary));

            foreach (var d in maxsal)
            {
                Console.WriteLine(d.Name + " " + d.Salary);
            }
        }
 public Employee Add(Employee newEmployee)
 {
     newEmployee.Id = _employeeList.Max(e => e.Id) + 1;
     _employeeList.Add(newEmployee);
     return(newEmployee);
 }
Example #42
0
        static void Main(string[] args)
        {
            #region Application appearance

            Cabinet myCabinet = new Cabinet();
            Console.ForegroundColor = ConsoleColor.Cyan;

            Console.WriteLine(myCabinet.Name + "\n");
            myCabinet.GetDescription();
            Console.ForegroundColor = color;

            Console.WriteLine("The following commands are available:\n ");

            var column1 = new List <string>();
            var column2 = new List <string>();
            FileCabinetCommands.FillLists(column1, column2);

            var maxWidth     = column1.Max(s => s.Length);
            var formatString = string.Format("{{0, -{0}}} |{{1,{1}}}", maxWidth, 4);

            Console.WriteLine(formatString, "Request description: ", "Command:\n ");
            for (int i = 0; i < column1.Count; i++)
            {
                Console.Write(formatString, column1[i], column2[i]);
                Console.WriteLine();
            }

            Console.WriteLine("\n" + @"If you want to exit just type ""exit"".");

            #endregion

            MyCommands.FillDictionary();

            while (alive)
            {
                Console.WriteLine();
                try
                {
                    command = Console.ReadLine();

                    MyCommands.ParseInput(command);
                    if (MyCommands.del != null && attempsToUseDelegate == 1)
                    {
                        attempsToUseDelegate--;
                        MyCommands.del(myCabinet);
                    }
                }
                catch (InvalidNameException e)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(e.message);
                    Console.ForegroundColor = color;
                }
                catch (InvalidDayOfBirthException e)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(e.message);
                    Console.ForegroundColor = color;
                }
                catch (FileNotFoundException e)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(e.message);
                    Console.ForegroundColor = color;
                }
                catch (UserAlreadyExistsException e)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(e.message);
                    Console.ForegroundColor = color;
                }
                catch (UserNotExistsException e)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(e.message);
                    Console.ForegroundColor = color;
                }
            }
        }
Example #43
0
        private static void WriteOptions(RenderableComposer composer, CommandInfo?command)
        {
            // Collect all options into a single structure.
            var parameters = new List <HelpOption>
            {
                new HelpOption("h", "help", null, null, "Prints help information"),
            };

            parameters.AddRange(command?.Parameters?.OfType <CommandOption>()?.Select(o =>
                                                                                      new HelpOption(
                                                                                          o.ShortNames.FirstOrDefault(), o.LongNames.FirstOrDefault(),
                                                                                          o.ValueName, o.ValueIsOptional, o.Description))
                                ?? Array.Empty <HelpOption>());

            var options = parameters.ToArray();

            if (options.Length > 0)
            {
                composer.Color(ConsoleColor.Yellow, c => c.Text("OPTIONS:")).LineBreak();

                // Start with composing a list of lines.
                var result = new List <Tuple <string?, BlockElement> >();
                foreach (var option in options)
                {
                    var item = new BlockElement();
                    item.Append(new TabElement());

                    // Short
                    if (option.Short != null)
                    {
                        item.Append(new TextElement($"-{option.Short}"));
                        if (option.Long != null)
                        {
                            item.Append(new TextElement(","));
                        }
                    }
                    else
                    {
                        item.Append(new RepeatingElement(3, new TextElement(" ")));
                    }

                    // Long
                    if (option.Long != null)
                    {
                        item.Append(new TextElement(" "));
                        item.Append(new TextElement($"--{option.Long}"));
                    }

                    // Value
                    if (option.Value != null)
                    {
                        item.Append(new TextElement(" "));

                        if (option.ValueIsOptional ?? false)
                        {
                            item.Append(new ColorElement(ConsoleColor.Gray, new TextElement($"[{option.Value}]")));
                        }
                        else
                        {
                            item.Append(new ColorElement(ConsoleColor.Gray, new TextElement($"<{option.Value}>")));
                        }
                    }

                    result.Add(Tuple.Create(option.Description, item));
                }

                // Now add the descriptions to all lines.
                var maxLength = result.Max(x => x.Item2.Length);
                foreach (var item in result)
                {
                    var description = item.Item1;
                    var element     = item.Item2;

                    if (!string.IsNullOrWhiteSpace(description))
                    {
                        var neededSpaces = maxLength - element.Length;
                        if (neededSpaces > 0)
                        {
                            element.Append(new RepeatingElement(neededSpaces, new TextElement(" ")));
                        }

                        element.Append(new TabElement());
                        element.Append(new TextElement(description.TrimEnd('.').Trim()));
                    }

                    element.Append(new LineBreakElement());
                }

                // Append the items.
                composer.Append(result.Select(x => x.Item2));
                composer.LineBreak();
            }
        }
        static void Main(string[] args)
        {
            Parser           parser;
            List <Attribute> attributes;
            float            correctPredictions = 0;
            float            currAccuracy       = 0;
            List <int>       training           = null;
            List <int>       test = null;
            ID3          alg      = null;
            Node         tree     = null;
            int          maxDepth = 0;
            List <float> foldAccuracy;
            List <float> depthAvgAccuracy = new List <float>();


            /*******************************************************************************************
             ************************10-FOLD XVALIDATION FOR 23 DIFFERENT DEPTHS*************************
             ********************************************************************************************/
            for (int depth = 23; depth > 0; depth--)
            {
                foldAccuracy = new List <float>();

                // Dependency effect: parser must be created before attributes
                parser = new Parser("crossvalidationset.data");


                while (parser.NextSplit())
                {
                    attributes = new List <Attribute>()
                    {
                        new NumericalAttribute("Age", 0),
                        new DiscreteAttribute("Sex", 1, new List <float> {
                            -9, 0, 1
                        }),
                        new DiscreteAttribute("Chest Pain", 2, new List <float> {
                            -9, 1, 2, 3, 4
                        }),
                        new NumericalAttribute("trestBPS", 3),
                        new NumericalAttribute("Chol", 4),
                        new DiscreteAttribute("FBS", 5, new List <float> {
                            -9, 0, 1
                        }),
                        new DiscreteAttribute("restECG", 6, new List <float> {
                            -9, 0, 1, 2
                        }),
                        new NumericalAttribute("Talalch", 7),
                        new DiscreteAttribute("Exang", 8, new List <float> {
                            -9, 0, 1
                        }),
                        new NumericalAttribute("Oldpeak", 9),
                        new DiscreteAttribute("Slope", 10, new List <float> {
                            -9, 0, 1, 2, 3
                        }),
                        new DiscreteAttribute("Ca", 11, new List <float> {
                            -9, 0, 1, 2, 3
                        }),
                        new DiscreteAttribute("Thal", 12, new List <float> {
                            -9, 3, 6, 7
                        })
                    };

                    training = Enumerable.Range(0, Parser.TRAININGDATA.GetLength(0)).ToList();
                    alg      = new ID3(Parser.TRAININGDATA, depth);
                    tree     = alg.DecisionTreeLearning(training, attributes, new LeafNode(1), 0);

                    test = Enumerable.Range(0, Parser.TESTDATA.GetLength(0)).ToList();
                    foreach (int i in test)
                    {
                        correctPredictions += tree.CheckClassification(i);
                    }

                    currAccuracy = correctPredictions / Parser.TESTDATA.GetLength(0);
                    Console.WriteLine("Accuracy : {0}/{1} = {2} @ depth {3} ", correctPredictions, Parser.TESTDATA.GetLength(0), currAccuracy, depth);
                    foldAccuracy.Add(currAccuracy);

                    // Remove refs for GC
                    correctPredictions = 0;
                    training           = null;
                    test       = null;
                    alg        = null;
                    tree       = null;
                    attributes = null;
                }

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Average Accuracy: {0} @ depth {1}", foldAccuracy.Average(), depth);
                Console.ResetColor();

                depthAvgAccuracy.Add(foldAccuracy.Average());
                foldAccuracy = null;

                parser = null;
            }



            /*******************************************************************************************
             **************************************TRAINING+TEST*****************************************
             ********************************************************************************************/

            Console.ForegroundColor = ConsoleColor.Green;

            maxDepth = 23 - depthAvgAccuracy.IndexOf(depthAvgAccuracy.Max());

            parser = new Parser();
            parser.setTrainingData("crossvalidationset.data");

            attributes = new List <Attribute>()
            {
                new NumericalAttribute("Age", 0),
                new DiscreteAttribute("Sex", 1, new List <float> {
                    -9, 0, 1
                }),
                new DiscreteAttribute("Chest Pain", 2, new List <float> {
                    -9, 1, 2, 3, 4
                }),
                new NumericalAttribute("trestBPS", 3),
                new NumericalAttribute("Chol", 4),
                new DiscreteAttribute("FBS", 5, new List <float> {
                    -9, 0, 1
                }),
                new DiscreteAttribute("restECG", 6, new List <float> {
                    -9, 0, 1, 2
                }),
                new NumericalAttribute("Talalch", 7),
                new DiscreteAttribute("Exang", 8, new List <float> {
                    -9, 0, 1
                }),
                new NumericalAttribute("Oldpeak", 9),
                new DiscreteAttribute("Slope", 10, new List <float> {
                    -9, 0, 1, 2, 3
                }),
                new DiscreteAttribute("Ca", 11, new List <float> {
                    -9, 0, 1, 2, 3
                }),
                new DiscreteAttribute("Thal", 12, new List <float> {
                    -9, 3, 6, 7
                })
            };

            training = Enumerable.Range(0, Parser.TRAININGDATA.GetLength(0)).ToList();
            alg      = new ID3(Parser.TRAININGDATA, maxDepth);
            tree     = alg.DecisionTreeLearning(training, attributes, new LeafNode(1), 0);
            Console.WriteLine(tree);

            parser.setTestData("testset.data");
            test = Enumerable.Range(0, Parser.TESTDATA.GetLength(0)).ToList();

            foreach (int i in test)
            {
                correctPredictions += tree.CheckClassification(i);
            }

            currAccuracy = correctPredictions / Parser.TESTDATA.GetLength(0);

            Console.WriteLine("Accuracy : {0}/{1} = {2} @ depth {3} ", correctPredictions, Parser.TESTDATA.GetLength(0), currAccuracy, maxDepth);
            Console.ResetColor();

            Console.ReadLine();
        }
Example #45
0
        static void Main(string[] args)
        {
            // Restriction/Filtering Operations
            Console.WriteLine($@"
            Restriction/Filtering Operations
Find the words in the collection that start with the letter 'L'
");
            List <string> fruits = new List <string> ()
            {
                "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry"
            };

            IEnumerable <string> LFruits = fruits.Where(fruit => fruit.StartsWith("L"));

            foreach (string fruit in LFruits)
            {
                Console.WriteLine(fruit);
            }

            Console.WriteLine($@"
Which of the following numbers are multiples of 4 or 6
");
            List <int> numbers = new List <int> ()
            {
                15,
                8,
                21,
                24,
                32,
                13,
                30,
                12,
                7,
                54,
                48,
                4,
                49,
                96
            };

            IEnumerable <int> fourSixMultiples = numbers.Where(x => x % 4 == 0 && x % 6 == 0);

            foreach (int x in fourSixMultiples)
            {
                Console.WriteLine(x);
            }

            Console.WriteLine($@" 
            Ordering Operations
Order these student names alphabetically, in descending order (Z to A)
");
            List <string> names = new List <string> ()
            {
                "Heather",
                "James",
                "Xavier",
                "Michelle",
                "Brian",
                "Nina",
                "Kathleen",
                "Sophia",
                "Amir",
                "Douglas",
                "Zarley",
                "Beatrice",
                "Theodora",
                "William",
                "Svetlana",
                "Charisse",
                "Yolanda",
                "Gregorio",
                "Jean-Paul",
                "Evangelina",
                "Viktor",
                "Jacqueline",
                "Francisco",
                "Tre"
            };

            List <string> descend = (from x in names orderby x descending select x).ToList();

            foreach (string x in descend)
            {
                Console.WriteLine(x);
            }

            Console.WriteLine($@" 
Build a collection of these numbers sorted in ascending order
");
            List <int> numbers2 = new List <int> ()
            {
                15,
                8,
                21,
                24,
                32,
                13,
                30,
                12,
                7,
                54,
                48,
                4,
                49,
                96
            };

            List <int> ascend = (from n in numbers2 orderby n select n).ToList();

            foreach (int n in ascend)
            {
                Console.WriteLine(n);
            }

            Console.WriteLine($@" 
            Aggregate Operations
Output how many numbers are in this list
");
            List <int> numbers3 = new List <int> ()
            {
                15,
                8,
                21,
                24,
                32,
                13,
                30,
                12,
                7,
                54,
                48,
                4,
                49,
                96
            };

            Console.WriteLine($"Total {numbers3.Count()}");

            Console.WriteLine($@" 
How much money have we made?
");
            List <double> purchases = new List <double> ()
            {
                2340.29,
                745.31,
                21.76,
                34.03,
                4786.45,
                879.45,
                9442.85,
                2454.63,
                45.65
            };

            Console.WriteLine($"Total {purchases.Sum().ToString("C")}");

            Console.WriteLine($@" 
What is our most expensive product?
");
            List <double> prices = new List <double> ()
            {
                879.45,
                9442.85,
                2454.63,
                45.65,
                2340.29,
                34.03,
                4786.45,
                745.31,
                21.76
            };

            Console.WriteLine($"Most expensive: {purchases.Max().ToString("C")}");

            Console.WriteLine($@" 
            Partitioning Operations
Store each number in the following List until a perfect square is detected.
");
            List <int> wheresSquaredo = new List <int> ()
            {
                66,
                12,
                8,
                27,
                82,
                34,
                7,
                50,
                19,
                46,
                81,
                23,
                30,
                4,
                68,
                14
            };

            wheresSquaredo.ForEach(g => {
                if (Math.Sqrt(g) % 1 == 0)
                {
                    Console.WriteLine($"{g.ToString()} = {Math.Sqrt(g)}");
                }
            });

            Console.WriteLine($@" 
            Using Custom Types
Build a collection of customers who are millionaires.
");
Example #46
0
        public static Language AutoDetectLanguage(string[] words)
        {
            List <int> languageCount = new List <int>(new int[] { 0, 0, 0, 0, 0, 0, 0, 0 });
            int        index;

            foreach (string s in words)
            {
                if (Wordlist.English.WordExists(s, out index))
                {
                    //english is at 0
                    languageCount[0]++;
                }

                if (Wordlist.Japanese.WordExists(s, out index))
                {
                    //japanese is at 1
                    languageCount[1]++;
                }

                if (Wordlist.Spanish.WordExists(s, out index))
                {
                    //spanish is at 2
                    languageCount[2]++;
                }

                if (Wordlist.ChineseSimplified.WordExists(s, out index))
                {
                    //chinese simplified is at 3
                    languageCount[3]++;
                }

                if (Wordlist.ChineseTraditional.WordExists(s, out index) && !Wordlist.ChineseSimplified.WordExists(s, out index))
                {
                    //chinese traditional is at 4
                    languageCount[4]++;
                }
                if (Wordlist.French.WordExists(s, out index))
                {
                    languageCount[5]++;
                }

                if (Wordlist.PortugueseBrazil.WordExists(s, out index))
                {
                    //portuguese_brazil is at 6
                    languageCount[6]++;
                }

                if (Wordlist.Czech.WordExists(s, out index))
                {
                    //czech is at 7
                    languageCount[7]++;
                }
            }

            //no hits found for any language unknown
            if (languageCount.Max() == 0)
            {
                return(Language.Unknown);
            }

            if (languageCount.IndexOf(languageCount.Max()) == 0)
            {
                return(Language.English);
            }
            else if (languageCount.IndexOf(languageCount.Max()) == 1)
            {
                return(Language.Japanese);
            }
            else if (languageCount.IndexOf(languageCount.Max()) == 2)
            {
                return(Language.Spanish);
            }
            else if (languageCount.IndexOf(languageCount.Max()) == 3)
            {
                if (languageCount[4] > 0)
                {
                    //has traditional characters so not simplified but instead traditional
                    return(Language.ChineseTraditional);
                }

                return(Language.ChineseSimplified);
            }
            else if (languageCount.IndexOf(languageCount.Max()) == 4)
            {
                return(Language.ChineseTraditional);
            }
            else if (languageCount.IndexOf(languageCount.Max()) == 5)
            {
                return(Language.French);
            }
            else if (languageCount.IndexOf(languageCount.Max()) == 6)
            {
                return(Language.PortugueseBrazil);
            }
            else if (languageCount.IndexOf(languageCount.Max()) == 7)
            {
                return(Language.Czech);
            }
            return(Language.Unknown);
        }
        static void Main(string[] args)
        {
            //Criando as categorias
            Category c1 = new Category()
            {
                Id = 1, Name = "Eletronics", Type = 1
            };
            Category c2 = new Category()
            {
                Id = 2, Name = "Computers", Type = 1
            };
            Category c3 = new Category()
            {
                Id = 3, Name = "Furnitures", Type = 2
            };

            //Criando lista de produtos
            List <Product> products = new List <Product>()
            {
                new Product()
                {
                    Id    = 1, Name = "Laptop Dell",
                    Price = 1500.0, Category = c2
                },
                new Product()
                {
                    Id    = 2, Name = "Laptop HP",
                    Price = 900.0, Category = c2
                },
                new Product()
                {
                    Id    = 3, Name = "Mac Book",
                    Price = 20000.5, Category = c2
                },
                new Product()
                {
                    Id    = 4, Name = "Ipod",
                    Price = 2200.8, Category = c1
                },
                new Product()
                {
                    Id    = 5, Name = "Motorola G7 Top",
                    Price = 900.0, Category = c1
                },
                new Product()
                {
                    Id    = 6, Name = "Table",
                    Price = 50.0, Category = c3
                },
                new Product()
                {
                    Id    = 7, Name = "Nightstand",
                    Price = 30.0, Category = c3
                },
            };

            var specificProduct =
                products.Where(p => p.Price > 200.0);

            //Para cada item da minha lista filtrada specificProduct
            //foreach (Product item in specificProduct) {
            //Mostra os dados do item, que é um obj da classe Product
            //Console.WriteLine(item.ToString());
            //}

            Print("PRODUTOS COM PREÇO > $200", specificProduct);


            //var r1 = products.Where(p => p.Category.Type == 1
            //&& p.Price > 1500);

            var r1 = from p in products
                     where p.Category.Type == 1 &&
                     p.Price > 1500
                     select p;

            Print("PRODUTOS COM CATEGORIA DO TIPO 1 E VALOR " +
                  "MAIOR QUE 1500", r1);



            //Retorna apenas o valor do atributo e
            //não o objeto inteiro
            var r2 = products.Where(
                p => p.Category.Name == "Eletronics").
                     Select(p => p.Name);

            Print("NOMES DOS PRODUTOS DE ELETRONICOS", r2);

            //Utilização de objetos anônimos - Objeto de uma
            //classe inexistente
            //Note que CategoryName é uma apelino/alias para
            //p.Category.Name

            /*var r3 = products.Where(p => p.Name[0] == 'L').
             *  Select(p => new {
             *      p.Name, p.Price, CategoryName = p.Category.Name});*/

            var r3 = from p in products
                     where p.Name[0] == 'L'
                     select new {
                p.Name,
                p.Price,
                CategoryName = p.Category.Name
            };

            Print("PRODUTOS QUE COMEÇAM COM LETRA L", r3);

            var r4 = products.Where(p => p.Category.Type == 1).
                     OrderBy(p => p.Name);

            Print("Produtos da categoria do tipo 1," +
                  " ordenados pelo nome", r4);

            /*var r5 = products.Where(p => p.Category.Type == 1).
             *  OrderBy(p => p.Price).ThenBy(p => p.Name);*/

            var r5 = from p in products
                     where p.Category.Type == 1
                     orderby p.Price
                     orderby p.Name
                     select p;

            Print("Produtos da categoria do tipo 1," +
                  " ordenados pelo preço e então pelo nome", r5);

            var r6 = products.FirstOrDefault();

            Console.WriteLine("Primeiro produto da lista " + r6);

            var r7 = products.Where(p => p.Id == 1).
                     SingleOrDefault();

            Console.WriteLine("Apenas um produto \n" + r7);

            var r8 = products.Max(p => p.Price);

            Console.WriteLine("Maior valor - Produto mais caro:\n" + r8);

            var r9 = products.Min(p => p.Price);

            Console.WriteLine(
                "Menor valor - Produto mais barato:\n" + r9);

            var r10 = products.Where(p => p.Category.Id == 1).Sum(p => p.Price);

            Console.WriteLine(
                "A soma dos preços dos produtos da categoria 1:\n" + r10);

            var r11 = products.Where(p => p.Category.Id == 1).Average(p => p.Price);

            Console.WriteLine(
                "A média dos preços dos produtos da categoria 1:\n" + r11);

            var r12 = products.Where(p => p.Price > 50).Skip(2).Take(2);

            Print("Exemplo pula 2 e pega 2 ", r12);
        }
Example #48
0
 public float MaxRating()
 {
     return(ratings.Max());
 }
        static void Main(string[] args)
        {
            // This simulates text from a file; note that it must be flush to the left of the screen or else the extra spaces
            // add unneeded nodes to the lists that are generated; for simplicity of code, I chose not to implement clean-up of that and just
            // ensure that the string literal is not indented from the left of the Visual Studio screen.
            string text =
                @"/home
    /home/room1
    /home/room1/subroom
    /home/room2
    /home/room2/miniroom
    /home/room2/test/thetest
    /home/room2/bigroom
    /home/room2/hugeroom
    /home/room3";
            var possibleNodes = new List <List <string> >();
            var splitLines    = text
                                .Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                                .ToList();

            splitLines.ForEach(l =>
                               possibleNodes.Add(l
                                                 .Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
                                                 .ToList()
                                                 )
                               );
            var nodeDepth = possibleNodes.Max(n => n.Count);
            // Create the root node
            XDocument xDoc = new XDocument(new XElement(possibleNodes[0][0]));

            // We don't need it anymore
            possibleNodes.RemoveAt(0);
            // This gets us looping through the outer nodes
            for (var i = 1; i < possibleNodes.Count - 1; i++)
            {
                // Here we go "sideways" by going through each inner list (each broken down line of the text)
                for (var ii = 1; ii < nodeDepth; ii++)
                {
                    // Some lines have more depth than others, so we have to check this here since we are looping on the maximum
                    if (ii < possibleNodes[i].Count)
                    {
                        // Let's see if this node already exists
                        var existingNode = xDoc.Root.Descendants().FirstOrDefault(d => d.Name.LocalName == (possibleNodes[i][ii]));
                        // Let's also see if a parent node was created in the previous loop iteration.
                        // This will tell us whether to add the current node at the root level, or under another node
                        var parentNode = xDoc.Root.Descendants().FirstOrDefault(d => d.Name.LocalName == (possibleNodes[i][ii - 1]));
                        // If the current node has already been added, we do nothing (this if statement is not entered into)
                        // Otherwise, existingNode will be null and that means we need to add the current node
                        if (null == existingNode)
                        {
                            // Now, use parentNode to decide where to add the current node
                            if (null == parentNode)
                            {
                                // The parent node does not exist; therefore, the current node will be added to the root node.
                                xDoc.Root.Add(new XElement(possibleNodes[i][ii]));
                            }
                            else
                            {
                                // There IS a parent node for this node!
                                // Therefore, we must add the current node to the parent node
                                // (remember, parent node is the previous iteration of the inner for loop on nodeDepth )
                                var newNode = new XElement(possibleNodes[i][ii]);
                                parentNode.Add(newNode);
                                // Add "this is a" text (bonus!) -- only adding this text if the current node is the last one in the list.
                                if (possibleNodes[i].Count - 1 == ii)
                                {
                                    newNode.Add(new XText("This is a " + newNode.Name.LocalName));
                                }
                            }
                        }
                    }
                }
            }
            Console.Write(xDoc.ToString());
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            Category category1 = new Category()
            {
                Id = 1, Name = "Tools", Tier = 2
            };
            Category category2 = new Category()
            {
                Id = 2, Name = "Computers", Tier = 1
            };
            Category category3 = new Category()
            {
                Id = 3, Name = "Electronics", Tier = 1
            };

            List <Product> products = new List <Product>()
            {
                new Product()
                {
                    Id = 1, Name = "Computer", Price = 1100.0, Category = category2
                },
                new Product()
                {
                    Id = 2, Name = "Hammer", Price = 90.0, Category = category1
                },
                new Product()
                {
                    Id = 3, Name = "TV", Price = 1700.0, Category = category3
                },
                new Product()
                {
                    Id = 4, Name = "Notebook", Price = 1300.0, Category = category2
                },
                new Product()
                {
                    Id = 5, Name = "Saw", Price = 80.0, Category = category1
                },
                new Product()
                {
                    Id = 6, Name = "Tablet", Price = 700.0, Category = category2
                },
                new Product()
                {
                    Id = 7, Name = "Camera", Price = 700.0, Category = category3
                },
                new Product()
                {
                    Id = 8, Name = "Printer", Price = 350.0, Category = category3
                },
                new Product()
                {
                    Id = 9, Name = "Macbook", Price = 1800.0, Category = category2
                },
                new Product()
                {
                    Id = 10, Name = "Sound Bar", Price = 700.0, Category = category3
                },
                new Product()
                {
                    Id = 11, Name = "Level", Price = 70.0, Category = category1
                }
            };


            var query1 = products.Where(p => p.Category.Tier == 1 && p.Price < 900.0);

            Print("TIER 1 AND PRICE < 900: ", query1);

            var query2 = products.Where(p => p.Category.Name == "Tools").Select(p => p.Name);

            Print("NAMES OF PRODUCTS FROM TOOLS: ", query2);

            var query3 = products.Where(p => p.Name[0] == 'C').Select(p => new { p.Name, p.Price, CategoryName = p.Category.Name });

            Print("NAMES STARTED WITH 'C' AND ANONYMOUS OBJECT: ", query3);

            var query4 = products.Where(p => p.Category.Tier == 1).OrderBy(p => p.Price).ThenBy(p => p.Name);

            Print("TIER 1 ORDER BY PRICE THEN BY NAME: ", query4);

            var query5 = query4.Skip(2).Take(4);

            Print("TIER 1 ORDER BY PRICE THEN BY NAME SKIP 2 TAKE 4: ", query5);

            var query6 = products.First();

            Console.WriteLine("First test1: " + query6);

            //var query7 = products.Where(p => p.Price > 3000.0).First();
            // Se não existir um produto sob as condições pedidas se usarmos a query anterior é demostrada uma exceção.
            // Em vez de Firt(), utiliza-se FirstOrDefault() e retorna nulo
            var query7 = products.Where(p => p.Price > 3000.0).FirstOrDefault();

            Console.WriteLine("First test2: " + query7);
            Console.WriteLine();

            var query8 = products.Where(p => p.Id == 3).SingleOrDefault();

            Console.WriteLine("Single or default test1: " + query8);
            var query9 = products.Where(p => p.Id == 30).SingleOrDefault();

            Console.WriteLine("Single or default test2: " + query9);
            Console.WriteLine();

            var query10 = products.Max(p => p.Price);

            Console.WriteLine("Max Price: " + query10);
            var query11 = products.Min(p => p.Price);

            Console.WriteLine("Min Price: " + query11);
            var query12 = products.Where(p => p.Category.Id == 1).Sum(p => p.Price);

            Console.WriteLine("Category 1 Sum prices: " + query12);
            var query13 = products.Where(p => p.Category.Id == 1).Average(P => P.Price);

            Console.WriteLine("Category 1 Average prices: " + query13);
            var query14 = products.Where(p => p.Category.Id == 5).Select(p => p.Price).DefaultIfEmpty(0.0).Average();

            Console.WriteLine("Category 5 Average prices: " + query14);
            var query15 = products.Where(p => p.Category.Id == 1).Select(p => p.Price).Aggregate((x, y) => x + y);

            Console.WriteLine("Category 1 Aggregate sum: " + query15);
            var query16 = products.Where(p => p.Category.Id == 5).Select(p => p.Price).Aggregate(0.0, (x, y) => x + y);

            Console.WriteLine("Category 5 Aggregate sum: " + query16);
            Console.WriteLine();

            var query17 = products.GroupBy(p => p.Category);

            foreach (IGrouping <Category, Product> group in query17)
            {
                Console.WriteLine("Category " + group.Key.Name + ":");
                foreach (Product product in group)
                {
                    Console.WriteLine(product);
                }
                Console.WriteLine();
            }
        }
Example #51
0
        //  G L A V N A   F U N K C I J A

        public void Algoritam()
        {
            /*
             * Ova procedura inicijalizira algoritam praćenja rubova lima te ga vrti do kraja.
             * Tu se pozivaju sve prethodno definirane funkcije/procedure klase algoritmi.
             * Ideja je da se prije poziva ovog algoritma kamera pozicionira iznad nekog vrha lima
             * (npr. donjeg lijevog).
             */

            // centriranje kamere
            centriranje(posTol);

            // moguci smjerovi kretanja nakon centriranja - odabire se veci
            List <double> smjerovi = new List <double>();

            smjerovi = fSmjerovi(vidljiveTocke);
            double smjer;

            smjer = smjerovi.Max();

            double smjerProsli = double.NaN, maxDelta;
            int    index, counter = 0;

            // PETLJA ALGORITMA
            // -> tu se izmjenjuju pratiBrid i centriranje dok se ne ispuni trazeni broj vrhova
            while (true)
            {
                pratiBrid(smjer);
                //while (vidljiveTocke.Count==3)
                centriranje(posTol);

                // Prosli smjer treba promijeniti u suprotan jer je ce isti taj u analizi na
                // iducem vrhu biti suprotan u odnosu na analizu na proslom vrhu.
                if (smjer < Math.PI)
                {
                    smjerProsli = smjer + Math.PI;
                }
                if (smjer >= Math.PI)
                {
                    smjerProsli = smjer - Math.PI;
                }

                smjerovi = fSmjerovi(vidljiveTocke);

                // trazenje novog smjera
                index    = 0;
                maxDelta = Math.Abs(smjerovi.ElementAt(0) - smjerProsli);
                if (Math.Abs(smjerovi.ElementAt(1) - smjerProsli) > maxDelta)
                {
                    index = 1;
                }
                smjer = smjerovi.ElementAt(index);

                counter = counter + 1;

                // uvjet za prekid petlje, kraj algoritma
                if (counter == brojVrhova)
                {
                    break;
                }
            }
        }
Example #52
0
 public Task <Car> Add(Car car)
 {
     cars.Add(car);
     car.CarId = cars.Max(x => x.CarId) + 1;
     return(Task.FromResult(car));
 }
Example #53
0
 public Employee Post(Employee employee)
 {
     employee.Id = _employeeList.Max(e => e.Id) + 1;
     _employeeList.Add(employee);
     return(employee);
 }
Example #54
0
            public async Task <FilteredSearchDTO> Handle(Query request, CancellationToken cancellationToken)
            {
                List <FilteredDTO> result = null;
                var id = await dataContext.Advertise
                         .Where(x => x.UniqueId == request.AdvertiseId)
                         .AsNoTracking()
                         .Select(x => x.Id).FirstOrDefaultAsync();

                if (request.AdvertiseId is not null && request.Category is not null)
                {
                    if (id > 0)
                    {
                        result = await dataContext.UserAdvertise
                                 .Where(x => x.AdvertiseId > id &&
                                        x.Category.ToLower() == request.Category.ToLower())
                                 .Take(30).AsNoTracking().OrderByDescending(x => x.Advertise.PublishedAt)
                                 .Select(x => new FilteredDTO
                        {
                            Id               = x.AdvertiseId,
                            UniqueId         = x.Advertise.UniqueId,
                            City             = x.Advertise.City,
                            District         = x.Advertise.District,
                            Price            = x.Advertise.Price,
                            Title            = x.Advertise.Title,
                            ImageUrl         = x.AdvertisePhotos.First().Url,
                            AdvertiseInfoDTO = new HomeAdvertiseInfoDTO
                            {
                                Hint = x.Advertise.AdvertiseInfo.Advertise.AdvertiseInfo.Hint,
                            },
                            User = new AdvertiseUser
                            {
                                FirstName = x.AppUser.FirstName,
                                LastName  = x.AppUser.LastName,
                                UserName  = x.AppUser.UserName
                            }
                        })
                                 .ToListAsync();
                    }
                }

                if (request.Category is  null && request.AdvertiseId is  null)
                {
                    result = await dataContext.UserAdvertise

                             .Take(30).AsNoTracking().OrderByDescending(x => x.Advertise.PublishedAt)
                             .Select(x => new FilteredDTO
                    {
                        Id               = x.AdvertiseId,
                        UniqueId         = x.Advertise.UniqueId,
                        City             = x.Advertise.City,
                        District         = x.Advertise.District,
                        Price            = x.Advertise.Price,
                        Title            = x.Advertise.Title,
                        ImageUrl         = x.AdvertisePhotos.First().Url,
                        AdvertiseInfoDTO = new HomeAdvertiseInfoDTO
                        {
                            Hint = x.Advertise.AdvertiseInfo.Advertise.AdvertiseInfo.Hint,
                        },
                        User = new AdvertiseUser
                        {
                            FirstName = x.AppUser.FirstName,
                            LastName  = x.AppUser.LastName,
                            UserName  = x.AppUser.UserName
                        }
                    })
                             .ToListAsync();
                }


                if (request.AdvertiseId is not null && request.Category is null)
                {
                    result = await dataContext.UserAdvertise.Where(x => x.AdvertiseId > id)
                             .Take(30).AsNoTracking().OrderByDescending(x => x.Advertise.PublishedAt)
                             .Select(x => new FilteredDTO
                    {
                        Id               = x.AdvertiseId,
                        UniqueId         = x.Advertise.UniqueId,
                        City             = x.Advertise.City,
                        District         = x.Advertise.District,
                        Price            = x.Advertise.Price,
                        Title            = x.Advertise.Title,
                        ImageUrl         = x.AdvertisePhotos.First().Url,
                        AdvertiseInfoDTO = new HomeAdvertiseInfoDTO
                        {
                            Hint = x.Advertise.AdvertiseInfo.Advertise.AdvertiseInfo.Hint,
                        },
                        User = new AdvertiseUser
                        {
                            FirstName = x.AppUser.FirstName,
                            LastName  = x.AppUser.LastName,
                            UserName  = x.AppUser.UserName
                        }
                    }).ToListAsync();
                }

                if (request.AdvertiseId is null && request.Category is not null)
                {
                    result = await dataContext.UserAdvertise
                             .Where(x => x.Category.ToLower() == request.Category.ToLower())
                             .Take(30).AsNoTracking().OrderByDescending(x => x.Advertise.PublishedAt)
                             .Select(x => new FilteredDTO
                    {
                        Id               = x.AdvertiseId,
                        UniqueId         = x.Advertise.UniqueId,
                        City             = x.Advertise.City,
                        District         = x.Advertise.District,
                        Price            = x.Advertise.Price,
                        Title            = x.Advertise.Title,
                        ImageUrl         = x.AdvertisePhotos.First().Url,
                        AdvertiseInfoDTO = new HomeAdvertiseInfoDTO
                        {
                            Hint = x.Advertise.AdvertiseInfo.Advertise.AdvertiseInfo.Hint,
                        },
                        User = new AdvertiseUser
                        {
                            FirstName = x.AppUser.FirstName,
                            LastName  = x.AppUser.LastName,
                            UserName  = x.AppUser.UserName
                        }
                    })
                             .ToListAsync();
                }
                string last = null;

                if (result.Count > 0)
                {
                    last = result?.First(x => x?.Id == result?.Max(x => x?.Id))?.UniqueId ?? null;
                }
                return(new FilteredSearchDTO {
                    LastId = last,
                    FilteredDTO = result ?? null
                });

                throw new HttpContextException(HttpStatusCode.NotFound, new { Id = "Last id is not correct" });
            }
		protected override void OnCollectStateWorldOverlayDrawcalls(Canvas canvas)
		{
			base.OnCollectStateWorldOverlayDrawcalls(canvas);

			// Assure we know how to display the current selection
			this.ValidateSelectionStats();

			List<ObjectEditorSelObj> transformObjSel = this.allObjSel.Where(s => s.HasTransform).ToList();
			Point cursorPos = this.PointToClient(Cursor.Position);
			canvas.PushState();
			canvas.State.ZOffset = -1.0f;
			
			// Draw indirectly selected object overlay
			canvas.State.SetMaterial(new BatchInfo(DrawTechnique.Solid, ColorRgba.Lerp(this.FgColor, this.BgColor, 0.75f)));
			this.DrawSelectionMarkers(canvas, this.indirectObjSel);
			if (this.mouseoverObject != null && (this.mouseoverAction == ObjectEditorAction.RectSelect || this.mouseoverSelect) && !transformObjSel.Contains(this.mouseoverObject)) 
				this.DrawSelectionMarkers(canvas, new [] { this.mouseoverObject });

			// Draw selected object overlay
			canvas.State.SetMaterial(new BatchInfo(DrawTechnique.Solid, this.FgColor));
			this.DrawSelectionMarkers(canvas, transformObjSel);

			// Draw overall selection boundary
			if (transformObjSel.Count > 1)
			{
				float midZ = transformObjSel.Average(t => t.Pos.Z);
				float maxZDiff = transformObjSel.Max(t => MathF.Abs(t.Pos.Z - midZ));
				if (maxZDiff > 0.001f)
				{
					canvas.State.SetMaterial(new BatchInfo(DrawTechnique.Solid, ColorRgba.Lerp(this.FgColor, this.BgColor, 0.5f)));
					canvas.DrawSphere(
						this.selectionCenter.X, 
						this.selectionCenter.Y, 
						this.selectionCenter.Z, 
						this.selectionRadius);
				}
				else
				{
					canvas.State.SetMaterial(new BatchInfo(DrawTechnique.Solid, ColorRgba.Lerp(this.FgColor, this.BgColor, 0.5f)));
					canvas.DrawCircle(
						this.selectionCenter.X, 
						this.selectionCenter.Y, 
						this.selectionCenter.Z, 
						this.selectionRadius);
				}
			}

			// Draw scale action dots
			bool canMove = this.actionObjSel.Any(s => s.IsActionAvailable(ObjectEditorAction.Move));
			bool canScale = (canMove && this.actionObjSel.Count > 1) || this.actionObjSel.Any(s => s.IsActionAvailable(ObjectEditorAction.Scale));
			if (canScale)
			{
				float dotR = 3.0f / this.GetScaleAtZ(this.selectionCenter.Z);
				canvas.State.ZOffset -= 0.1f;
				canvas.State.SetMaterial(new BatchInfo(DrawTechnique.Solid, this.FgColor));
				canvas.FillCircle(
					this.selectionCenter.X + this.selectionRadius, 
					this.selectionCenter.Y, 
					this.selectionCenter.Z,
					dotR);
				canvas.FillCircle(
					this.selectionCenter.X - this.selectionRadius, 
					this.selectionCenter.Y, 
					this.selectionCenter.Z,
					dotR);
				canvas.FillCircle(
					this.selectionCenter.X, 
					this.selectionCenter.Y + this.selectionRadius, 
					this.selectionCenter.Z,
					dotR);
				canvas.FillCircle(
					this.selectionCenter.X, 
					this.selectionCenter.Y - this.selectionRadius, 
					this.selectionCenter.Z,
					dotR);
				canvas.State.ZOffset += 0.1f;
			}

			if (this.action != ObjectEditorAction.None)
			{
				// Draw action lock axes
				this.DrawLockedAxes(canvas, this.selectionCenter.X, this.selectionCenter.Y, this.selectionCenter.Z, this.selectionRadius * 4);
			}

			canvas.PopState();
		}
Example #56
0
        public void DisplayView()
        {
            int scrollVal = hScrollBar.Value;

            if (scrollVal < hScrollBar.Minimum)
            {
                scrollVal = hScrollBar.Minimum;
            }
            if (scrollVal > hScrollBar.Maximum)
            {
                scrollVal = hScrollBar.Maximum;
            }

            int trackView        = trackBar.Value;
            int displayItemCount = DisplayPointCount * trackView;

            List <T_ParkItemData> viewLists = null;
            int maxDisplayIndex             = 0;
            int minDisplayIndex             = 0;

            if (scrollVal == hScrollBar.Minimum)
            {
                int maxIndex = ChartData.Count > displayItemCount ? displayItemCount - 1 : ChartData.Count;
                if (displayItemCount > ChartData.Count)
                {
                    displayItemCount = ChartData.Count;
                }
                viewLists       = ChartData.GetRange(0, maxIndex);
                maxDisplayIndex = displayItemCount;
                minDisplayIndex = 0;
            }
            else if (scrollVal == hScrollBar.Maximum)
            {
                int minIndex = ChartData.Count < displayItemCount ? 0 : ChartData.Count - displayItemCount;
                if (displayItemCount > ChartData.Count)
                {
                    displayItemCount = ChartData.Count;
                }
                viewLists       = ChartData.GetRange(minIndex, ChartData.Count < displayItemCount ? ChartData.Count : displayItemCount);
                maxDisplayIndex = ChartData.Count;
                minDisplayIndex = minIndex;
            }
            else
            {
                int currentIndex = (scrollVal - 1) * displayItemCount;
                if (ChartData.Count < currentIndex + displayItemCount)
                {
                    displayItemCount = ChartData.Count - currentIndex;
                }

                viewLists = ChartData.GetRange(currentIndex, displayItemCount);

                maxDisplayIndex = currentIndex + displayItemCount;
                minDisplayIndex = currentIndex;
            }
            if (viewLists != null)
            {
                double maxPrice1 = viewLists.Max(m => m.HighPrice);
                double minPrice1 = viewLists.Min(m => m.LowPrice);
                double maxPrice2 = viewLists.Max(m => m.T_Psar);
                double minPrice2 = viewLists.Min(m => m.T_Psar);
                double maxPrice3 = viewLists.Max(m => m.T_Psar2);
                double minPrice3 = viewLists.Min(m => m.T_Psar2);
                double maxPrice  = maxPrice1 > maxPrice2 ? maxPrice1 : maxPrice2;
                double minPrice  = minPrice1 < minPrice2 ? minPrice1 : minPrice2;

                maxPrice = maxPrice > maxPrice3 ? maxPrice : maxPrice3;
                minPrice = minPrice < minPrice3 ? minPrice : minPrice3;
                maxPrice = maxPrice + SpaceMaxMin;
                minPrice = minPrice - SpaceMaxMin;
                chart.ChartAreas[0].AxisY2.Maximum = maxPrice;
                chart.ChartAreas[0].AxisY2.Minimum = minPrice;
                chart.ChartAreas[0].AxisX.Maximum  = maxDisplayIndex + 1;
                chart.ChartAreas[0].AxisX.Minimum  = minDisplayIndex - 1;

                DrawLines(viewLists);
            }

            chart.Update();
        }
Example #57
0
 public Employee  Add(Employee emp)
 {
     emp.Id = _employeeList.Max(e => e.Id) + 1;
     _employeeList.Add(emp);
     return(emp);
 }
Example #58
0
 internal void AddNotice(Notice notice)
 {
     notice.Id = (notices.Max(x => x.Id) + 1);
     notices.Add(notice);
 }
        public IHttpActionResult Register([FromBody] JObject parameters)
        {
            try
            {
                List <JProperty> properties = null;
                string           userName;
                string           password;
                string           code;

                try
                {
                    //Getting parameters values
                    properties = parameters.Children().Cast <JProperty>().ToList();
                    userName   = properties.Where(p => p.Name == "userName").FirstOrDefault()?.Value?.ToString();
                    password   = properties.Where(p => p.Name == "password").FirstOrDefault()?.Value?.ToString();
                    code       = properties.Where(p => p.Name == "code").FirstOrDefault()?.Value?.ToString();

                    //Checking if userName and password parameters are filled
                    if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
                    {
                        //returning error response
                        return(Content(HttpStatusCode.BadRequest, "You must fill username and password fields"));
                    }
                }
                catch
                {
                    return(Content(HttpStatusCode.BadRequest, "Invalid input parameters"));
                }

                //Checking if the entered code exists
                if (!codes.ContainsKey(code))
                {
                    //returning error response, because the entered code is not correct
                    return(Content(HttpStatusCode.BadRequest, "Wrong code"));
                }

                //Checking if the entered username already exists in the file
                if (users?.Where(u => u.Username == userName).Any() ?? false)
                {
                    //returning error response, because the username is already taken
                    return(Content(HttpStatusCode.BadRequest, "Username already exists"));
                }

                //Checking if the entered username is available in the VMS
                #region Check if user with this username already exists in the VMS
                if (configApiClient.GetChildItems("/" + ItemTypes.BasicUserFolder).Where(c => c.Properties.Where(p => p.Key == "Name" && p.Value == userName).FirstOrDefault() != null).FirstOrDefault() != null)
                {
                    //returning error response, because the username is not available in the VMS.
                    return(Content(HttpStatusCode.BadRequest, "Username already exists"));
                }
                #endregion

                //Creating new user object and setting it's parameters
                User tmpUser = new User()
                {
                    Id = (users?.Max(u => (int?)u.Id) ?? 0) + 1, Username = userName, Password = password, NumberOfCameras = codes[code], Cameras = new List <Camera>()
                };

                //Creating new empty Camera objects. The count depends on the entered code.
                for (int i = 0; i < tmpUser.NumberOfCameras; i++)
                {
                    tmpUser.Cameras.Add(new Camera());
                }

                #region Create User in VMS
                ConfigurationItem tmpConfigurationItem = configApiClient.InvokeMethod(configApiClient.GetItem("/" + ItemTypes.BasicUserFolder), "AddBasicUser");
                tmpConfigurationItem.Properties.Where(p => p.Key == "Name").FirstOrDefault().Value     = userName;
                tmpConfigurationItem.Properties.Where(p => p.Key == "Password").FirstOrDefault().Value = password;
                ConfigurationItem resultConfigurationItem = configApiClient.InvokeMethod(tmpConfigurationItem, "AddBasicUser");
                #endregion
                if (resultConfigurationItem.Properties.FirstOrDefault(p => p.Key == InvokeInfoProperty.State).Value == InvokeInfoStates.Success)
                {
                    string newUserSid = resultConfigurationItem.Properties.Where(p => p.Key == "Sid").FirstOrDefault().Value;
                    #region Create Role in VMS
                    tmpConfigurationItem = configApiClient.InvokeMethod(configApiClient.GetItem("/" + ItemTypes.RoleFolder), "AddRole");
                    tmpConfigurationItem.Properties.Where(p => p.Key == "Name").FirstOrDefault().Value = userName;
                    resultConfigurationItem = configApiClient.InvokeMethod(tmpConfigurationItem, "AddRole");
                    #endregion
                    if (resultConfigurationItem.Properties.FirstOrDefault(p => p.Key == InvokeInfoProperty.State).Value == InvokeInfoStates.Success)
                    {
                        #region Assign User to the Role
                        tmpConfigurationItem = configApiClient.InvokeMethod(configApiClient.GetChildItems(resultConfigurationItem.Path)[0], "AddRoleMember");
                        tmpConfigurationItem.Properties.Where(p => p.Key == "Sid").FirstOrDefault().Value = newUserSid;
                        resultConfigurationItem = configApiClient.InvokeMethod(tmpConfigurationItem, "AddRoleMember");
                        #endregion
                        if (resultConfigurationItem.Properties.FirstOrDefault(p => p.Key == InvokeInfoProperty.State).Value == InvokeInfoStates.Success)
                        {
                            if (users == null)
                            {
                                users = new List <User>();
                            }

                            //The user is successfully created and setted up in the VMS, so we are adding the User object to the collection and write it to the file.
                            users.Add(tmpUser);
                            File.WriteAllText(HttpContext.Current.Server.MapPath("~/data.txt"), JsonConvert.SerializeObject(users, new JsonSerializerSettings()
                            {
                                ContractResolver = new ExcludeCameraUsernameAndPasswordResolver()
                            }));

                            //returning success response
                            return(Ok(new LoginResult()
                            {
                                UserId = tmpUser.Id
                            }));
                        }
                        else
                        {
                            //returning error response
                            return(Content(HttpStatusCode.BadRequest, "Cannot add user to the role"));
                        }
                    }
                    else
                    {
                        //returning error response
                        return(Content(HttpStatusCode.BadRequest, "Cannot create the role"));
                    }
                }
                else
                {
                    //returning error response
                    return(Content(HttpStatusCode.BadRequest, "Cannot create the user"));
                }
            }
            catch (Exception)
            {
                //returning error response
                return(Content(HttpStatusCode.InternalServerError, "Unknown error"));
            }
        }
Example #60
0
    public Genome BestMember()
    {
        float max = members.Max(x => x.adjustedFitness);

        return(members.Where(x => x.adjustedFitness == max).FirstOrDefault());
    }