private void AddPlotSeries(List<Tuple<List<Tuple<double, double>>, double>> ansv, double stepX, double stepY)
 {
     _stepX = stepX;
     _stepY = stepY;
     if (!_firstLoaded)
     {
         DrawGrid(ansv.Min(item => item.Item1.Min(it => it.Item1)), ansv.Max(item => item.Item1.Max(it => it.Item1)), stepX,
             ansv.Min(item => item.Item1.Min(it => it.Item2)), ansv.Max(item => item.Item1.Max(it => it.Item2)), stepY);
         PopulateSlider(ansv.Min(it => it.Item2), ansv.Max(it => it.Item2),
             (from a in ansv from b in ansv let d = Math.Abs(a.Item2 - b.Item2) where a.Item1 != b.Item1 select d).Min());
     }
     _XandYandParam.Add(ansv);
     Redraw();
 }
 private void On_GetDelayedButton_Click(object sender, RoutedEventArgs e)
 {
     List<Data> data = Data.Get_All();
     if (data.Count == 0)
         MessageBox.Show("No Data!");
     else
     {
         List<TimeSpan> timeSpans = new List<TimeSpan>();
         for (int i = 0; i < data.Count - 1; i++)
             timeSpans.Add(data[i].LoggingOn - data[i + 1].LoggingOn);
         if (timeSpans.Count != 0)
         {
             TimeSpan acceptTimeSpan = timeSpans.Min<TimeSpan>().Add(new TimeSpan(0, 0, Int32.Parse(Mistake_TextBox.Text)));
             StringBuilder delayedStringBuilder = new StringBuilder();
             int delayCounter = 0;
             for (int i = 0; i < timeSpans.Count; i++)
             {
                 if (timeSpans[i] > acceptTimeSpan)
                 {
                     delayedStringBuilder.AppendFormat("{0} == ({1})", data[i + 1].ToString(), timeSpans[i].ToString());
                     delayedStringBuilder.AppendLine();
                     delayCounter++;
                 }
             }
             delayedStringBuilder.AppendLine((delayCounter * 1.0 / data.Count).ToString());
             Log_TextBox.Text = delayedStringBuilder.ToString();
         }
     }
 }
        public MainWindow()
        {
            InitializeComponent();

            int highestPrice = 65;
            List<int> vals = new List<int>() { 10, 20, 30, 40, 50 };
            int min = vals.Min();
            int max = vals.Max();
            max = highestPrice > max ? highestPrice : max;
            double range = max - min;

            // Draw max in red
            Color c = new Color() { ScA = 1, ScR = 1, ScG = 0, ScB = 0 };
            // y = 0 is at the top of the canvas
            var line = new Line() { X1 = 0, Y1 = 0, X2 = canvas.Width, Y2 = 0, Stroke = new SolidColorBrush(c), StrokeThickness = 2.0 };
            canvas.Children.Add(line);
            // Add txt so we can visualize better
            var txt = new TextBlock() { Text = max.ToString() };
            Canvas.SetLeft(txt, canvas.Width / 2);
            Canvas.SetTop(txt, 0 - 9);
            canvas.Children.Add(txt);

            foreach (int val in vals)
            {
                double percent = 1.0 - ((val - min) / range); // 0 is at the top, so invert it by doing 1.0 - xxx
                double y = percent * canvas.Height;
                // Draw line in a shade of blue/green
                c = new Color() { ScA = 1, ScR = 0, ScG = 0.5f, ScB = (float)percent };
                line = new Line() { X1 = 0, Y1 = y, X2 = canvas.Width, Y2 = y, Stroke = new SolidColorBrush(c), StrokeThickness = 2.0 };
                canvas.Children.Add(line);

                // Add txt so we can visualize better
                txt = new TextBlock() { Text = val.ToString() };
                Canvas.SetLeft(txt, canvas.Width / 2);
                Canvas.SetTop(txt, y - 9);
                canvas.Children.Add(txt);
            }
        }
Beispiel #4
0
        private void btn_simulate_Click(object sender, RoutedEventArgs e)
        {
            int nbrSim = Convert.ToInt32(txt_nbrsim.Text);
            double initWealth = Properties.Settings.Default.InitWealth;

            List<double> finalEarnings = new List<double>();
            List<int> counts = new List<int>();

            for (int i = 0; i < nbrSim; i++)
            {
                MartStrategy MStrat = new MartStrategy(5, 250, initWealth);
                double bid = MStrat.Bet();
                Number res;
                double payoff;
                int count = 0;
                while (bid <= MStrat.Wealth)
                {
                    MStrat.PlaceBet(bid);
                    res = _RGame.Play();
                    payoff = _RGame.GetPayoffColor(NumberColor.Red, bid, res);
                    MStrat.Setup(payoff);
                    bid = MStrat.Bet();
                    count++;
                }
                finalEarnings.Add(MStrat.Earnings-initWealth);
                counts.Add(count);
            }

            txt_earnings.Text = finalEarnings.Average().ToString();
            txt_plays.Text = counts.Average().ToString();
            txt_maxEarnings.Text = finalEarnings.Max().ToString();
            txt_maxLosses.Text = finalEarnings.Min().ToString();
            txt_totEarnings.Text = finalEarnings.Where(x => x > 0).Sum().ToString();
            txt_totLosses.Text = finalEarnings.Where(x => x < 0).Sum().ToString();
            txt_balance.Text = finalEarnings.Sum().ToString();
        }
            /// <summary>
            /// This takes in a list of distances, and returns a list of percents (the int just comes along for the ride)
            /// </summary>
            private static List<Tuple<int, double>> GetPercentOfWeight(List<Tuple<int, double>> distances, double searchRadiusMultiplier)
            {
                const double OFFSET = .1d;

                // Find the smallest distance in the list
                double min = distances.Min(o => o.Item2);

                // Figure out what the maximum possible distance would be
                double maxRange = (min * searchRadiusMultiplier) - min;

                // Figure out ratios based on distance
                double[] ratios = new double[distances.Count];
                for (int cntr = 0; cntr < ratios.Length; cntr++)
                {
                    // Normalize the distance
                    ratios[cntr] = UtilityCore.GetScaledValue_Capped(0d, 1d, 0d, maxRange, distances[cntr].Item2 - min);

                    // Run it through a function
                    ratios[cntr] = 1d / (ratios[cntr] + OFFSET);		// need to add an offset, because one of these will be zero
                }

                double total = ratios.Sum();

                // Turn those ratios into percents (normalizing the ratios)
                List<Tuple<int, double>> retVal = new List<Tuple<int, double>>();
                for (int cntr = 0; cntr < ratios.Length; cntr++)
                {
                    retVal.Add(new Tuple<int, double>(distances[cntr].Item1, ratios[cntr] / total));
                }

                // Exit Function
                return retVal;
            }
        /// <summary>
        ///  Make a move on the board
        /// </summary>
        /// <param name="board"></param>
        /// <param name="player"></param>
        /// <returns></returns>
        private Tuple<int, int[]> mmMove(TTTBoard board, Player player)
        {
            if ((int)board.CheckWin() == 1)
            {
                return new Tuple<int, int[]>(Score(board.CheckWin()), new int[] { -1, -1 });
            }
            else if ((board.GetEmptySquares()).Count == (board.Dim * board.Dim))
            {
                return new Tuple<int, int[]>(0, new int[] { rnd.Next(board.Dim), rnd.Next(board.Dim) });
            }
            else if (board.GetEmptySquares().Count == 0)
            {
                return new Tuple<int, int[]>(Score(board.CheckWin()), new int[] { -1, -1 });
            }

            List<int> listScore = new List<int>();
            List<int[]> listMove = new List<int[]>();
            Player newPlayer = player == Player.PLAYERO ? Player.PLAYERX : Player.PLAYERO;

            List<int[]> moves = board.GetEmptySquares();
            foreach (int[] move in moves)
            {
                TTTBoard newBoard = board.Clone();
                newBoard.Move(move[0], move[1], player);

                int newScore = mmMove(newBoard, newPlayer).Item1;
                listScore.Add(newScore);
                listMove.Add(move);

                if (player == Player.PLAYERX && newScore == 1) break;
                else if (player == Player.PLAYERO && newScore == -1) break;
            }
            int[] moveNew;
            int newScoreNew;
            if (player == Player.PLAYERX)
            {
                newScoreNew = listScore.Max();
                moveNew = listMove[listScore.IndexOf(newScoreNew)];
            }
            else
            {
                newScoreNew = listScore.Min();
                moveNew = listMove[listScore.IndexOf(newScoreNew)];
            }
            return new Tuple<int, int[]>(newScoreNew, moveNew);
        }
Beispiel #7
0
        //比分的小按钮事件
        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.

            Button button = sender as Button;
            SolidColorBrush b_Brush = (SolidColorBrush)(button.Background);
            int ColorCount = 0;

            if (b_Brush.Color.ToString() == "#FFFF0000")
            {
                foreach (StackPanel Stack in ((button.Parent as StackPanel).Parent as StackPanel).Children)
                {
                    foreach (Button button2 in Stack.Children)
                    {
                        SolidColorBrush b_Brush2 = (SolidColorBrush)(button2.Background);
                        if (b_Brush2.Color.ToString() == "#FFFF0000")
                        {
                            ColorCount++;
                        }
                    }
                }

                if (ColorCount > 1)
                {
                    button.Background = new SolidColorBrush(Colors.White);
                }
            }
            else
            {
                button.Background = new SolidColorBrush(Colors.Red);
            }

            double SumMinOdds = 0.00;//指数和 最小
            double SumMaxOdds = 0.00;//指数和 最大

            double ProductMinOdds = 1.00;//指数积 最小
            double ProductMaxOdds = 1.00;//指数积 最大

            int ZhuCount = 1;
            List<double> DoubleList = new List<double>();

            var selfcols = this.DataGrid1.Columns[0];

            foreach (var item in DataGrid1.ItemsSource)
            {
                //--对象所在的单元格
                var cells = selfcols.GetCellContent(item);
                if (cells != null)
                {
                    //--单元格所包含的元素
                    Grid grid = cells as Grid;

                    StackPanel Sp = grid.Children[0] as StackPanel;

                    StackPanel Sp1 = Sp.Children[1] as StackPanel;

                    foreach (StackPanel StackPanel in Sp1.Children)
                    {
                        foreach (Button button1 in StackPanel.Children)
                        {
                            SolidColorBrush b_Brush1 = (SolidColorBrush)(button1.Background);

                            if (b_Brush1.Color.ToString() == "#FFFF0000")
                            {
                                DoubleList.Add(Netball.RetuntDouble(ToolTipService.GetToolTip(button1).ToString()));
                            }
                        }
                    }

                    ZhuCount *= DoubleList.Count;

                    SumMinOdds += DoubleList.Min();
                    SumMaxOdds += DoubleList.Max();

                    ProductMinOdds *= DoubleList.Min();
                    ProductMaxOdds *= DoubleList.Max();
                }
                DoubleList.Clear();
            }

            this.tbSum.Text = string.Format("{0:f2}", SumMinOdds) + "~" + string.Format("{0:f2}", SumMaxOdds);
            this.tbProduct.Text = string.Format("{0:f2}", ProductMinOdds) + "~" + string.Format("{0:f2}", ProductMaxOdds);
            this.tbPremium.Text = string.Format("{0:f2}", ProductMinOdds * 2) + "~" + string.Format("{0:f2}", ProductMaxOdds * 2);
        }
        private static List<Skeleton> RemoveFrames(List<Skeleton> skels, int nFrames)
        {
            int diff = skels.Count - nFrames;
            List<Skeleton> result = new List<Skeleton>();

            List<double> dists = new List<double>();
            for (int i = 0; i < skels.Count - 1; i++)
            {
                dists.Add(GetDistBetweenFrames(skels.ElementAt(i), skels.ElementAt(i + 1)));
            }

            List<int> ignore = new List<int>();
            int j = 0;
            while (j < diff)
            {
                double min = dists.Min();
                int index = dists.IndexOf(min);
                if (index < skels.Count - 3)
                {
                    ignore.Add(index);
                    j++;
                }
                dists.RemoveAt(index);
            }

            for (int i = 0; i < skels.Count; i++)
            {
                if (ignore.Contains(i))
                {
                    continue;
                }

                result.Add(skels.ElementAt(i));
            }

            return AlignFrames(result, nFrames);
        }
        // Within the connection points with least number of connectors, get the one closest to the midpoint.
        private static ConnectionPoint GetConnectionPointForAutoConnect(List<ConnectionPoint> availableConnectionPoints)
        {
            int minConnectorCount = availableConnectionPoints.Min<ConnectionPoint>((p) =>
                {
                    return p.AttachedConnectors.Count;
                });

            List<ConnectionPoint> connectionPoints = new List<ConnectionPoint>(availableConnectionPoints.Where<ConnectionPoint>((p) =>
                {
                    return p.AttachedConnectors.Count == minConnectorCount;
                }));

            ConnectionPoint midPoint = availableConnectionPoints[availableConnectionPoints.Count / 2];
            if (connectionPoints.Contains(midPoint))
            {
                return midPoint;
            }
            double dist;
            return ConnectionPoint.GetClosestConnectionPoint(connectionPoints, midPoint.Location, out dist);
        }
        private void FrmChild_PassDataBetweenForm(object sender, PassDataWinFormEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(delegate {
                if (e.message == "文件读取成功")
                { Finished_File--; }

                win.FrontPage.Text += "\n" + e.Filename;
                win.FrontPage.Text += "文件状态:";
                win.FrontPage.Text += e.message;

                //结束读取数据后,将所有时间汇总,并统计到文件中^_^
                if (Finished_File == 0) {
                    win.Hide(); win.FrontPage.Text = "";
                    this.IsEnabled = true;
                    List<DateTime> All_File_Date = new List<DateTime>();
                    for (int i=0; i<Files.Count(); i++)
                    {
                        foreach(var date in Files[i].All_Date)
                        All_File_Date.Add(date);
                    }
                    start_time_calender.DisplayDateStart = All_File_Date.Min();
                    end_time_calender.DisplayDateStart = All_File_Date.Min();
                    start_time_calender.DisplayDateEnd = All_File_Date.Max();
                    end_time_calender.DisplayDateEnd = All_File_Date.Max();
                    start_time_calender.SelectedDate = All_File_Date.Min();
                    end_time_calender.SelectedDate = All_File_Date.Max();
                    output.IsEnabled = true;
                }
                win.scroll.ScrollToEnd();
            }));
        }
Beispiel #11
0
		public static Tuple<DesignItem, Rect> WrapItemsNewContainer(IEnumerable<DesignItem> items, Type containerType, bool doInsert = true)
		{
			var collection = items;
			
			var _context = collection.First().Context as XamlDesignContext;
			
			var container = collection.First().Parent;
			
			if (collection.Any(x => x.Parent != container))
				return null;

			//Change Code to use the Placment Operation!
			var placement = container.Extensions.OfType<IPlacementBehavior>().FirstOrDefault();
			if (placement == null)
				return null;

			var operation = PlacementOperation.Start(items.ToList(), PlacementType.Move);

			var newInstance = _context.Services.ExtensionManager.CreateInstanceWithCustomInstanceFactory(containerType, null);
			DesignItem newPanel = _context.Services.Component.RegisterComponentForDesigner(newInstance);
			
			List<ItemPos> itemList = new List<ItemPos>();
			
			foreach (var item in collection) {
				itemList.Add(GetItemPos(operation, item));
				//var pos = placement.GetPosition(null, item);
				if (container.Component is Canvas) {
					item.Properties.GetAttachedProperty(Canvas.RightProperty).Reset();
					item.Properties.GetAttachedProperty(Canvas.LeftProperty).Reset();
					item.Properties.GetAttachedProperty(Canvas.TopProperty).Reset();
					item.Properties.GetAttachedProperty(Canvas.BottomProperty).Reset();
				} else if (container.Component is Grid) {
					item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).Reset();
					item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).Reset();
					item.Properties.GetProperty(FrameworkElement.MarginProperty).Reset();
				}
				
				var parCol = item.ParentProperty.CollectionElements;
				parCol.Remove(item);
			}
			
			var xmin = itemList.Min(x => x.Xmin);
			var xmax = itemList.Max(x => x.Xmax);
			var ymin = itemList.Min(x => x.Ymin);
			var ymax = itemList.Max(x => x.Ymax);

			foreach (var item in itemList) {
				if (newPanel.Component is Canvas) {
					if (item.HorizontalAlignment == HorizontalAlignment.Right) {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(xmax - item.Xmax);
					} else {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(item.Xmin - xmin);
					}
					
					if (item.VerticalAlignment == VerticalAlignment.Bottom) {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(ymax - item.Ymax);
					} else {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(item.Ymin - ymin);
					}

					newPanel.ContentProperty.CollectionElements.Add(item.DesignItem);

				} else if (newPanel.Component is Grid) {
					Thickness thickness = new Thickness(0);
					if (item.HorizontalAlignment == HorizontalAlignment.Right) {
						item.DesignItem.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).SetValue(HorizontalAlignment.Right);
						thickness.Right = xmax - item.Xmax;
					} else {
						item.DesignItem.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).SetValue(HorizontalAlignment.Left);
						thickness.Left = item.Xmin - xmin;
					}
					
					if (item.VerticalAlignment == VerticalAlignment.Bottom) {
						item.DesignItem.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).SetValue(VerticalAlignment.Bottom);
						thickness.Bottom = ymax - item.Ymax;
					} else {
						item.DesignItem.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).SetValue(VerticalAlignment.Top);
						thickness.Top = item.Ymin - ymin;
					}
					
					item.DesignItem.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(thickness);

					newPanel.ContentProperty.CollectionElements.Add(item.DesignItem);

				} else if (newPanel.Component is Viewbox) {
					newPanel.ContentProperty.SetValue(item.DesignItem);
				}
			}

			if (doInsert)
			{
				PlacementOperation operation2 = PlacementOperation.TryStartInsertNewComponents(
					container,
					new[] {newPanel},
					new[] {new Rect(xmin, ymin, xmax - xmin, ymax - ymin).Round()},
					PlacementType.AddItem
				);

				operation2.Commit();

				_context.Services.Selection.SetSelectedComponents(new[] {newPanel});
			}

			operation.Commit();

			return new Tuple<DesignItem, Rect>(newPanel, new Rect(xmin, ymin, xmax - xmin, ymax - ymin).Round());
		}
Beispiel #12
0
		public static void WrapItemsNewContainer(IEnumerable<DesignItem> items, Type containerType)
		{
			var collection = items;
			
			var _context = collection.First().Context as XamlDesignContext;
			
			var oldContainer = collection.First().Parent;
			
			if (collection.Any(x => x.Parent != oldContainer))
				return;
			
			var newInstance = Activator.CreateInstance(containerType);
			DesignItem newPanel = _context.Services.Component.RegisterComponentForDesigner(newInstance);
			var changeGroup = newPanel.OpenGroup("Wrap in Container");
			
			List<ItemPos> itemList = new List<ItemPos>();
			
			foreach (var item in collection) {
				
				var itemPos = new ItemPos(){ DesignItem = item };
				itemList.Add(itemPos);
				
				if (oldContainer.Component is Canvas) {
					var canvas = oldContainer.View as Canvas;
					
					if (item.Properties.GetAttachedProperty(Canvas.RightProperty) != null && item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet) {
						itemPos.HorizontalAlignment = HorizontalAlignment.Right;
						itemPos.Xmax = canvas.ActualWidth - (double)item.Properties.GetAttachedProperty(Canvas.RightProperty).ValueOnInstance;
						itemPos.Xmin = itemPos.Xmax - ((FrameworkElement)item.View).ActualWidth;
					}
					else if (item.Properties.GetAttachedProperty(Canvas.LeftProperty) != null && item.Properties.GetAttachedProperty(Canvas.LeftProperty).IsSet) {
						itemPos.HorizontalAlignment = HorizontalAlignment.Left;
						itemPos.Xmin = (double)item.Properties.GetAttachedProperty(Canvas.LeftProperty).ValueOnInstance;
						itemPos.Xmax = itemPos.Xmin + ((FrameworkElement)item.View).ActualWidth;
					} else {
						itemPos.HorizontalAlignment = HorizontalAlignment.Left;
						itemPos.Xmax = itemPos.Xmin + ((FrameworkElement)item.View).ActualWidth;
					}
					
					if (item.Properties.GetAttachedProperty(Canvas.BottomProperty) != null && item.Properties.GetAttachedProperty(Canvas.BottomProperty).IsSet) {
						itemPos.VerticalAlignment = VerticalAlignment.Bottom;
						itemPos.Ymax = canvas.ActualHeight - (double)item.Properties.GetAttachedProperty(Canvas.BottomProperty).ValueOnInstance;
						itemPos.Ymin = itemPos.Ymax - ((FrameworkElement)item.View).ActualHeight;
					}
					else if (item.Properties.GetAttachedProperty(Canvas.TopProperty) != null && item.Properties.GetAttachedProperty(Canvas.TopProperty).IsSet) {
						itemPos.VerticalAlignment = VerticalAlignment.Top;
						itemPos.Ymin = (double)item.Properties.GetAttachedProperty(Canvas.TopProperty).ValueOnInstance;
						itemPos.Ymax = itemPos.Ymin + ((FrameworkElement)item.View).ActualHeight;
					} else {
						itemPos.VerticalAlignment = VerticalAlignment.Top;
						itemPos.Ymax = itemPos.Ymin + ((FrameworkElement)item.View).ActualHeight;
					}
					
					item.Properties.GetAttachedProperty(Canvas.RightProperty).Reset();
					item.Properties.GetAttachedProperty(Canvas.LeftProperty).Reset();
					item.Properties.GetAttachedProperty(Canvas.TopProperty).Reset();
					item.Properties.GetAttachedProperty(Canvas.BottomProperty).Reset();
				} else if (oldContainer.Component is Grid) {
					var grid = oldContainer.View as Grid;
					
					if ((HorizontalAlignment)item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).ValueOnInstance == HorizontalAlignment.Right) {
						itemPos.HorizontalAlignment = HorizontalAlignment.Right;
						itemPos.Xmax = grid.ActualWidth - ((Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance).Right;
						itemPos.Xmin = itemPos.Xmax - ((FrameworkElement)item.View).ActualWidth;
					} else {
						itemPos.HorizontalAlignment = HorizontalAlignment.Left;
						itemPos.Xmin = ((Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance).Left;
						itemPos.Xmax = itemPos.Xmin + ((FrameworkElement)item.View).ActualWidth;
					}
					
					if ((VerticalAlignment)item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).ValueOnInstance == VerticalAlignment.Bottom) {
						itemPos.VerticalAlignment = VerticalAlignment.Bottom;
						itemPos.Ymax = grid.ActualHeight - ((Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance).Bottom;
						itemPos.Ymin = itemPos.Ymax - ((FrameworkElement)item.View).ActualHeight;
					} else {
						itemPos.VerticalAlignment = VerticalAlignment.Top;
						itemPos.Ymin = ((Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance).Top;
						itemPos.Ymax = itemPos.Ymin + ((FrameworkElement)item.View).ActualHeight;
					}
					
					item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).Reset();
					item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).Reset();
					item.Properties.GetProperty(FrameworkElement.MarginProperty).Reset();
				}
				
				var parCol = item.ParentProperty.CollectionElements;
				parCol.Remove(item);
			}
			
			var xmin = itemList.Min(x => x.Xmin);
			var xmax = itemList.Max(x => x.Xmax);
			var ymin = itemList.Min(x => x.Ymin);
			var ymax = itemList.Max(x => x.Ymax);
			
			if (oldContainer.Component is Canvas) {
				newPanel.Properties.GetProperty(FrameworkElement.WidthProperty).SetValue(xmax - xmin);
				newPanel.Properties.GetProperty(FrameworkElement.HeightProperty).SetValue(ymax - ymin);
				newPanel.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(xmin);
				newPanel.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(ymin);
			} else if (oldContainer.Component is Grid) {
				newPanel.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).SetValue(HorizontalAlignment.Left);
				newPanel.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).SetValue(VerticalAlignment.Top);
				newPanel.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(new Thickness(xmin, ymin, 0, 0));
				newPanel.Properties.GetProperty(FrameworkElement.WidthProperty).SetValue(xmax - xmin);
				newPanel.Properties.GetProperty(FrameworkElement.HeightProperty).SetValue(ymax - ymin);
			}
			
			foreach (var item in itemList) {
				newPanel.ContentProperty.CollectionElements.Add(item.DesignItem);
				
				if (newPanel.Component is Canvas) {
					if (item.HorizontalAlignment == HorizontalAlignment.Right) {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(xmax - item.Xmax);
					} else {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(item.Xmin - xmin);
					}
					
					if (item.VerticalAlignment == VerticalAlignment.Bottom) {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(ymax - item.Ymax);
					} else {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(item.Ymin - ymin);
					}
				} else if (newPanel.Component is Grid) {
					Thickness thickness = new Thickness(0);
					if (item.HorizontalAlignment == HorizontalAlignment.Right) {
						item.DesignItem.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).SetValue(HorizontalAlignment.Right);
						thickness.Right = xmax - item.Xmax;
					} else {
						item.DesignItem.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).SetValue(HorizontalAlignment.Left);
						thickness.Left = item.Xmin - xmin;
					}
					
					if (item.VerticalAlignment == VerticalAlignment.Bottom) {
						item.DesignItem.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).SetValue(VerticalAlignment.Bottom);
						thickness.Bottom = ymax - item.Ymax;
					} else {
						item.DesignItem.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).SetValue(VerticalAlignment.Top);
						thickness.Top = item.Ymin - ymin;
					}
					
					item.DesignItem.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(thickness);
				}
			}
			
			oldContainer.ContentProperty.CollectionElements.Add(newPanel);
			
			changeGroup.Commit();
			
			_context.Services.Selection.SetSelectedComponents(new []{ newPanel });
		}
        private void buttonScalingScore_Click(object sender, RoutedEventArgs e)
        {
            int cols, rows;
            double horizLength, vertLength;
            if (!parseChessboardParameters(out cols, out rows, out horizLength, out vertLength))
            {
                return;
            }

            // 以下改造
            MotionDataHandler handler;
            string path;
            if (openMotionData(out handler, out path))
            {
                CvMat displayMat1 = null;
                CvMat displayMat3 = null;
                CvMat displayMat4 = null;
                CvMat gray = null;

                int length = handler.FrameCount;
                if (length == 0) { return; }

                CvSize boardSize = new CvSize(cols, rows);
                CvSize imageSize = new CvSize();
                List<Tuple<double, double>> pairs = new List<Tuple<double, double>>();
                CvPoint2D32f[] lastCorners = null;

                IEnumerable<CvMat> colorImages, depthImages;
                Utility.LoadImages(handler.GetColorImagePaths(), out colorImages);
                Utility.LoadImages(handler.GetDepthImagePaths(), out depthImages);
                var images = colorImages.Zip(depthImages, (first, second) => Tuple.Create(first, second));

                foreach (Tuple<CvMat, CvMat> imagePair in images)
                {
                    CvMat imageMat = imagePair.Item1;
                    CvMat depthMat = imagePair.Item2;
                    
                    if (displayMat4 == null)
                    {
                        displayMat4 = CvEx.InitCvMat(imageMat);
                    }

                    imageSize = new CvSize(imageMat.Cols, imageMat.Rows);
                    CvPoint2D32f[] corners;
                    int count;
                    CvEx.InitCvMat(ref gray, imageMat, MatrixType.U8C1);
                    imageMat.CvtColor(gray, ColorConversion.RgbToGray);
                    if (gray.FindChessboardCorners(boardSize, out corners, out count, ChessboardFlag.AdaptiveThresh))
                    {
                        CvEx.CloneCvMat(ref displayMat1, imageMat);
                        CvTermCriteria criteria = new CvTermCriteria(50, 0.01);
                        gray.FindCornerSubPix(corners, count, new CvSize(3, 3), new CvSize(-1, -1), criteria);
                        CvPoint3D32f?[] cornerPoints = new CvPoint3D32f?[corners.Length];
                        for (int j = 0; j < corners.Length; j++)
                        {
                            CvPoint2D32f corner = corners[j];
                            double? value = CalcEx.BilateralFilterDepthMatSinglePixel(corner, depthMat, 100, 4, 9);
                            if (value.HasValue)
                            {
                                cornerPoints[j] = new CvPoint3D32f(corner.X, corner.Y, value.Value);
                            }
                        }
                        for (int x = 0; x < cols; x++)
                        {
                            for (int y = 0; y < rows; y++)
                            {
                                if (!cornerPoints[x + y * cols].HasValue)
                                    continue;
                                CvPoint3D32f point1 = cornerPoints[x + y * cols].Value;
                                CvPoint3D64f undistortPoint1 = this.UndistortionData.GetRealFromScreenPos(point1, imageSize);
                                foreach (var offset in new[] { new { X = 1, Y = 0, D = horizLength }, new { X = 0, Y = 1, D = vertLength } })
                                {
                                    int dx = x + offset.X;
                                    int dy = y + offset.Y;
                                    if (dx >= cols || dy >= rows)
                                        continue;
                                    if (!cornerPoints[dx + dy * cols].HasValue)
                                        continue;

                                    CvPoint3D32f point2 = cornerPoints[dx + dy * cols].Value;
                                    CvPoint3D64f undistortPoint2 = this.UndistortionData.GetRealFromScreenPos(point2, imageSize);
                                    double distance = Math.Sqrt(CvEx.GetDistanceSq(undistortPoint1, undistortPoint2));
                                    double scale = distance / offset.D;
                                    CvColor color = CalcEx.HSVtoRGB(Math.Max(0, Math.Min(300, scale * 600 - 450)), scale, 2 - scale);
                                    displayMat4.DrawLine((int)point1.X, (int)point1.Y, (int)point2.X, (int)point2.Y, new CvScalar(color.R, color.G, color.B), 1, LineType.AntiAlias);
                                    pairs.Add(new Tuple<double, double>(distance, offset.D));
                                }
                            }
                        }
                        CvEx.DrawChessboardCornerFrame(displayMat1, boardSize, corners, new CvScalar(64, 128, 64));
                        displayMat1.DrawChessboardCorners(boardSize, corners, true);
                        lastCorners = corners;
                        putImage(displayMat1, PixelFormats.Rgb24);
                    }
                    else
                    {
                        CvEx.CloneCvMat(ref displayMat3, imageMat);
                        putImage(displayMat3, PixelFormats.Rgb24);
                    }
                }

                CvMat displayMat2 = CvEx.InitCvMat(displayMat1);
                displayMat1.Undistort2(displayMat2, this.UndistortionData.CameraStruct.CreateCvMat(), this.UndistortionData.DistortStruct.CreateCvMat(true));
                if (lastCorners != null)
                {
                    drawUndistortedCornerFrame(displayMat2, lastCorners, boardSize);
                }
                displayMat2.PutText(string.Format("Min: {0}", pairs.Min(x => x.Item1 / x.Item2)), new CvPoint(20, 20), new CvFont(FontFace.HersheyPlain, 1, 1), new CvScalar(255, 255, 255));
                displayMat2.PutText(string.Format("Max: {0}", pairs.Max(x => x.Item1 / x.Item2)), new CvPoint(20, 40), new CvFont(FontFace.HersheyPlain, 1, 1), new CvScalar(255, 255, 255));
                displayMat2.PutText(string.Format("Avg: {0}", pairs.Average(x => x.Item1 / x.Item2)), new CvPoint(20, 60), new CvFont(FontFace.HersheyPlain, 1, 1), new CvScalar(255, 255, 255));
                displayMat2.PutText(string.Format("Med: {0}", CalcEx.GetMedian(pairs.Select(x => x.Item1 / x.Item2).ToList())), new CvPoint(20, 80), new CvFont(FontFace.HersheyPlain, 1, 1), new CvScalar(255, 255, 255));
                putImage(displayMat4, PixelFormats.Rgb24);
                displayLabels();
            }

        }
Beispiel #14
0
        //初始化指数和、指数积、奖金的方法
        void Timer_Tick(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            string[] ZhuArr = null;
            string ButtonContext = string.Empty;
            int i = 0;

            double SumMinOdds = 0.00;//指数和 最小
            double SumMaxOdds = 0.00;//指数和 最大

            double ProductMinOdds = 1.00;//指数积 最小
            double ProductMaxOdds = 1.00;//指数积 最大

            List<double> DoubleList = new List<double>();

            var selfcols = this.DataGrid1.Columns[0];

            foreach (var item in DataGrid1.ItemsSource)
            {
                //--对象所在的单元格
                var cells = selfcols.GetCellContent(item);
                if (cells != null)
                {
                    //--单元格所包含的元素
                    Grid grid = cells as Grid;

                    StackPanel Sp = grid.Children[0] as StackPanel;

                    StackPanel Sp1 = Sp.Children[1] as StackPanel;

                    ZhuArr = GameNumber[i].Substring(GameNumber[i].IndexOf('(') + 1, GameNumber[i].LastIndexOf(')') - GameNumber[i].IndexOf('(') - 1).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (string s in ZhuArr)
                    {
                        Button b = ReturnShowNum(Sp1.Children[0] as StackPanel, s);

                        if (b == null)
                        {
                            b = ReturnShowNum(Sp1.Children[1] as StackPanel, s);
                            if (b == null)
                            {
                                b = ReturnShowNum(Sp1.Children[2] as StackPanel, s);
                            }
                        }

                        if (b != null)
                        {
                            b.Background = new SolidColorBrush(Colors.Red);//改变按钮颜色

                            DoubleList.Add(Netball.RetuntDouble(ToolTipService.GetToolTip(b).ToString()));
                        }
                    }

                    SumMinOdds += DoubleList.Min();
                    SumMaxOdds += DoubleList.Max();

                    ProductMinOdds *= DoubleList.Min();
                    ProductMaxOdds *= DoubleList.Max();
                }

                i++;
                DoubleList.Clear();

            }

            this.tbSum.Text = string.Format("{0:f2}", SumMinOdds) + "~" + string.Format("{0:f2}", SumMaxOdds);
            this.tbProduct.Text = string.Format("{0:f2}", ProductMinOdds) + "~" + string.Format("{0:f2}", ProductMaxOdds);
            this.tbPremium.Text = string.Format("{0:f2}", ProductMinOdds * 2) + "~" + string.Format("{0:f2}", ProductMaxOdds * 2);


            Timer.Stop();
        }
            private static List<Tuple<int, double>> GetPercentOfWeight_OLD(List<Tuple<int, double>> distances, double searchRadiusMultiplier)
            {
                const double AMOUNTATMAX = .01d;

                double min = distances.Min(o => o.Item2);
                double max = min * searchRadiusMultiplier * 10;		// making max greater so that there is more of a distance

                // The equation will be y=1/kx
                // Where x is the distance from center
                // So solving for k, k=1/xy
                double k = 1d / (max * AMOUNTATMAX);

                double[] scaled = distances.Select(o => 1d / (k * o.Item2)).ToArray();

                double total = scaled.Sum();

                List<Tuple<int, double>> retVal = new List<Tuple<int, double>>();
                for (int cntr = 0; cntr < distances.Count; cntr++)
                {
                    retVal.Add(new Tuple<int, double>(distances[cntr].Item1, scaled[cntr] / total));
                }

                // Exit Function
                return retVal;
            }
Beispiel #16
0
        //(公共方法)计算指数积、指数和、奖金的方法
        private void CountOdds()
        {
            double SumMinOdds = 0.00;//指数和 最小
            double SumMaxOdds = 0.00;//指数和 最大

            double ProductMinOdds = 1.00;//指数积 最小
            double ProductMaxOdds = 1.00;//指数积 最大

            List<double> DoubleList = new List<double>();

            var selfcols = this.DataGrid1.Columns[3];

            foreach (var item in DataGrid1.ItemsSource)
            {
                //--对象所在的单元格
                var cells = selfcols.GetCellContent(item);
                if (cells != null)
                {
                    //--单元格所包含的元素
                    Grid grid = cells as Grid;
                    foreach (Button button1 in grid.Children)
                    {
                        SolidColorBrush b_Brush1 = (SolidColorBrush)(button1.Background);

                        if (b_Brush1.Color.ToString() == "#FFFF0000")
                        {
                            DoubleList.Add(Netball.RetuntDouble(ToolTipService.GetToolTip(button1).ToString()));
                        }
                    }

                    SumMinOdds += DoubleList.Min();
                    SumMaxOdds += DoubleList.Max();

                    ProductMinOdds *= DoubleList.Min();
                    ProductMaxOdds *= DoubleList.Max();
                }
                DoubleList.Clear();
            }

            this.tbSum.Text = string.Format("{0:f2}", SumMinOdds) + "~" + string.Format("{0:f2}", SumMaxOdds);
            this.tbProduct.Text = string.Format("{0:f2}", ProductMinOdds) + "~" + string.Format("{0:f2}", ProductMaxOdds);
            this.tbPremium.Text = string.Format("{0:f2}", ProductMinOdds * 2) + "~" + string.Format("{0:f2}", ProductMaxOdds * 2);
        }
        private void CalculateBoundaries(List<SilverlightEdge> edges)
        {
            MaxX = edges.Max(x => x.Position.X);
            MinX = edges.Min(x => x.Position.X);
            LengthX = MaxX - MinX;
            MaxY = edges.Max(x => x.Position.Y);
            MinY = edges.Min(x => x.Position.Y);
            LengthY = MaxY-MinY;

            CenterPoint = new Point((MinX + MaxX) / 2, (MaxY + MinY) / 2);
        }
Beispiel #18
0
		public static void ArrangeItems(IEnumerable<DesignItem> items, ArrangeDirection arrangeDirection)
		{
			var collection = items;

			var _context = collection.First().Context as XamlDesignContext;

			var container = collection.First().Parent;

			if (collection.Any(x => x.Parent != container))
				return;

			var placement = container.Extensions.OfType<IPlacementBehavior>().FirstOrDefault();
			if (placement == null)
				return;

			var operation = PlacementOperation.Start(items.ToList(), PlacementType.Move);
			
			//var changeGroup = container.OpenGroup("Arrange Elements");

			List<ItemPos> itemList = new List<ItemPos>();
			foreach (var item in collection)
			{
				itemList.Add(GetItemPos(operation, item));
			}

			var xmin = itemList.Min(x => x.Xmin);
			var xmax = itemList.Max(x => x.Xmax);
			var mpos = (xmax - xmin) / 2 + xmin;
			var ymin = itemList.Min(x => x.Ymin);
			var ymax = itemList.Max(x => x.Ymax);
			var ympos = (ymax - ymin) / 2 + ymin;

			foreach (var item in collection)
			{
				switch (arrangeDirection)
				{
					case ArrangeDirection.Left:
						{
							if (container.Component is Canvas)
							{
								if (!item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet)
								{
									item.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(xmin);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualWidth - (xmin + (double) ((FrameworkElement) item.Component).ActualWidth);
									item.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(pos);
								}
							}
							else if (container.Component is Grid)
							{
								if ((HorizontalAlignment)item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).ValueOnInstance != HorizontalAlignment.Right)
								{
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Left = xmin;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualWidth - (xmin + (double)((FrameworkElement)item.Component).ActualWidth);
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Right = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
							}
						}
						break;
					case ArrangeDirection.HorizontalMiddle:
						{
							if (container.Component is Canvas)
							{
								if (!item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet)
								{
									if (!item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet)
									{
										item.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(mpos - (((FrameworkElement)item.Component).ActualWidth) / 2);
									}
									else
									{
										var pp = mpos - (((FrameworkElement)item.Component).ActualWidth) / 2;
										var pos = (double)((Panel)item.Parent.Component).ActualWidth - pp - (((FrameworkElement)item.Component).ActualWidth);
										item.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(pos);
									}
								}
							}
							else if (container.Component is Grid)
							{
								if ((HorizontalAlignment)item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).ValueOnInstance != HorizontalAlignment.Right)
								{
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Left = mpos - (((FrameworkElement)item.Component).ActualWidth) / 2;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
								else
								{
									var pp = mpos - (((FrameworkElement)item.Component).ActualWidth) / 2;
									var pos = (double)((Panel)item.Parent.Component).ActualWidth - pp - (((FrameworkElement)item.Component).ActualWidth);
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Right = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
							}
						}
						break;
					case ArrangeDirection.Right:
						{
							if (container.Component is Canvas)
							{
								if (!item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet)
								{
									var pos = xmax - (double)((FrameworkElement)item.Component).ActualWidth;
									item.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(pos);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualWidth - xmax;
									item.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(pos);
								}
							}
							else if (container.Component is Grid)
							{
								if ((HorizontalAlignment)item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).ValueOnInstance != HorizontalAlignment.Right)
								{
									var pos = xmax - (double)((FrameworkElement)item.Component).ActualWidth;
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Left = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualWidth - xmax;
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Right = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
							}
						}
						break;
					case ArrangeDirection.Top:
						{
							if (container.Component is Canvas)
							{
								if (!item.Properties.GetAttachedProperty(Canvas.BottomProperty).IsSet)
								{
									item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(ymin);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualHeight - (ymin + (double)((FrameworkElement)item.Component).ActualHeight);
									item.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(pos);
								}
							}
							else if (container.Component is Grid)
							{
								if ((VerticalAlignment)item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).ValueOnInstance != VerticalAlignment.Bottom)
								{
									item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(ymin);
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Top = ymin;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualHeight - (ymin + (double)((FrameworkElement)item.Component).ActualHeight);
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Bottom = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
							}
						}
						break;
					case ArrangeDirection.VerticalMiddle:
						{
							if (container.Component is Canvas)
							{
								if (!item.Properties.GetAttachedProperty(Canvas.BottomProperty).IsSet)
								{
									item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(ympos - (((FrameworkElement)item.Component).ActualHeight) / 2);
								}
								else
								{
									var pp = mpos - (((FrameworkElement)item.Component).ActualHeight) / 2;
									var pos = (double)((Panel)item.Parent.Component).ActualHeight - pp - (((FrameworkElement)item.Component).ActualHeight);
									item.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(pos);
								}
							}
							else if (container.Component is Grid)
							{
								if ((VerticalAlignment)item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).ValueOnInstance != VerticalAlignment.Bottom)
								{
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Top = ympos - (((FrameworkElement)item.Component).ActualHeight) / 2;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
								else
								{
									var pp = mpos - (((FrameworkElement)item.Component).ActualHeight) / 2;
									var pos = (double)((Panel)item.Parent.Component).ActualHeight - pp - (((FrameworkElement)item.Component).ActualHeight);
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Bottom = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
							}
						}
						break;
					case ArrangeDirection.Bottom:
						{
							if (container.Component is Canvas)
							{
								if (!item.Properties.GetAttachedProperty(Canvas.BottomProperty).IsSet)
								{
									var pos = ymax - (double)((FrameworkElement)item.Component).ActualHeight;
									item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(pos);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualHeight - ymax;
									item.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(pos);
								}
							}
							else if (container.Component is Grid)
							{
								if ((VerticalAlignment)item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).ValueOnInstance != VerticalAlignment.Bottom)
								{
									var pos = ymax - (double)((FrameworkElement)item.Component).ActualHeight;
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Top = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualHeight - ymax;
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Bottom = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
							}
						}
						break;
				}
			}

			operation.Commit();
		}
 void SetYAxisRange() {
   var points = new List<double>();
   StudyModels.ToList().ForEach( x => {
     points.AddRange( x.PointModels.Select( y => y.YAxisValue ) );
   } );
   YAxisMaxValue = points.Max();
   YAxisMinValue = points.Min();
 }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //LUCAS
            try
            {
                Random rand = new Random(42);
                List<int> numbers = new List<int>();
                ListDisjointSet<int> disjointSet;
                disjointSet = new ListDisjointSet<int>();

                Stopwatch iterationTimer = new Stopwatch();
                List<long> ticksList = new List<long>();
                for (int i = 0; i < 10000; i++)
                {
                    int n = rand.Next();
                    numbers.Add(n);
                    iterationTimer.Start();
                    disjointSet.MakeSet(n);
                    iterationTimer.Stop();
                    ticksList.Add(iterationTimer.ElapsedTicks);
                    iterationTimer.Reset();
                }
                mksetOne.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min());
                ticksList.Clear();

                for (int i = 0; i < numbers.Count * 3; i++)
                {
                    int lookup = numbers[rand.Next(numbers.Count)];
                    iterationTimer.Start();
                    disjointSet.Find(lookup);
                    iterationTimer.Stop();
                    ticksList.Add(iterationTimer.ElapsedTicks);
                    iterationTimer.Reset();
                }
                findOne.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min());
                ticksList.Clear();

                for (int i = 0; i < numbers.Count * 3; i++)
                {
                    int lookupA = numbers[rand.Next(numbers.Count)];
                    int lookupB = numbers[rand.Next(numbers.Count)];
                    iterationTimer.Start();
                    disjointSet.Union(disjointSet.Find(lookupA), disjointSet.Find(lookupB));
                    iterationTimer.Stop();
                    ticksList.Add(iterationTimer.ElapsedTicks);
                    iterationTimer.Reset();
                }
                unionOne.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min());
            }
            catch (Exception err)
            {
                Console.WriteLine(err.StackTrace);
            }

            //PAUL
            try
            {
                Random rand = new Random(42);
                List<int> numbers = new List<int>();
                DisjointDataSet<int> disjointSet;
                disjointSet = new DisjointDataSet<int>();

                Stopwatch iterationTimer = new Stopwatch();
                List<long> ticksList = new List<long>();
                for (int i = 0; i < 10000; i++)
                {
                    int n = rand.Next();
                    numbers.Add(n);
                    iterationTimer.Start();
                    disjointSet.MakeSet(n);
                    iterationTimer.Stop();
                    ticksList.Add(iterationTimer.ElapsedTicks);
                    iterationTimer.Reset();
                }
                mksetTwo.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min());
                ticksList.Clear();

                for (int i = 0; i < numbers.Count * 3; i++)
                {
                    int lookup = numbers[rand.Next(numbers.Count)];
                    iterationTimer.Start();
                    disjointSet.Find(lookup);
                    iterationTimer.Stop();
                    ticksList.Add(iterationTimer.ElapsedTicks);
                    iterationTimer.Reset();
                }
                findTwo.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min());
                ticksList.Clear();

                for (int i = 0; i < numbers.Count * 3; i++)
                {
                    int lookupA = numbers[rand.Next(numbers.Count)];
                    int lookupB = numbers[rand.Next(numbers.Count)];
                    iterationTimer.Start();
                    disjointSet.Union(lookupA, lookupB);
                    iterationTimer.Stop();
                    ticksList.Add(iterationTimer.ElapsedTicks);
                    iterationTimer.Reset();
                }
                unionTwo.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min());
            }
            catch (Exception err)
            {
                Console.WriteLine(err.StackTrace);
            }
        }
Beispiel #21
0
        private void AddFileView(FileItem file_item, VertexControl source, PocVertex source_vertex, List<int> lines = null)
        {
            if (!graph_provider.root_vertex.CtagsRun)
            {
                System.Windows.Forms.MessageBox.Show("Ctags is still running, so tags are not available.", "Ctags running", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
            }
            FileVertex new_vertex = graph_provider.AddFileView(file_item, source_vertex);
            VertexControl new_vertex_control = new VertexControl(new_vertex) { DataContext = new_vertex };
            try
            {
                graph_area.AddVertex(new_vertex, new_vertex_control);
            }
            catch (GraphX.GX_InvalidDataException)
            {
                new_vertex_control = graph_area.GetAllVertexControls().Where(c => c.Vertex == new_vertex).First();
            }

            PocEdge new_edge = new PocEdge(source_vertex, new_vertex);
            graph_area.InsertEdge(new_edge, new EdgeControl(source, new_vertex_control, new_edge));
            graph_area.RelayoutGraph(true);
            graph_area.UpdateLayout();
            centre_on_me = new_vertex_control;
            ICSharpCode.AvalonEdit.TextEditor editor = TreeHelpers.FindVisualChild<ICSharpCode.AvalonEdit.TextEditor>(new_vertex_control);
            if (editor != null && editor != NotesEditor)
            {
                editor.TextArea.TextView.MouseDown += TestEditor_MouseDown;
                editor.TextArea.SelectionChanged += TestEditor_SelectionChanged;
                if (graph_provider.root_vertex.CtagsRun) editor.TextArea.TextView.LineTransformers.Add(new UnderlineCtagsMatches(graph_provider.root_vertex.CtagsMatches.Keys.ToList()));
                if (lines != null)
                {
                    editor.TextArea.TextView.BackgroundRenderers.Add(new HighlightSearchLineBackgroundRenderer(editor, lines));
                    editor.ScrollToLine(lines.Min());
                }
                editor.Width = editor.ActualWidth;
            }
        }
        private static List<Skeleton> InterpolateFrames(List<Skeleton> skels, int nFrames)
        {
            int diff = nFrames - skels.Count;
            List<Skeleton> result = skels;

            List<double> dists = new List<double>();
            for (int i = 0; i < skels.Count - 1; i++)
            {
                dists.Add(GetDistBetweenFrames(skels.ElementAt(i), skels.ElementAt(i + 1)));
            }

            for (int i = 0; i < diff; i++)
            {
                if (dists.Count == 0)
                {
                    break;
                }
                double max = dists.Min();
                int index = dists.IndexOf(max);

                Skeleton insert = GetMidFrame(skels.ElementAt(index), skels.ElementAt(index + 1));
                result.Insert(index, insert);
                dists.RemoveAt(index);
            }

            return AlignFrames(result, nFrames);
        }
        public void Plot(double a, double b, double step, string function)
        {
            this.Plotter.Children.Clear();
            this.Plotter.Children.Add(this.xAxis);
            this.Plotter.Children.Add(this.yAxis);

            int aInt = (int)a;
            int bInt = (int)b;
            int stepInt = (int)step;

            double min = 0;
            double max = 0;
            List<double> fxDouble = new List<double>();

            if (function.Equals(availablePlots.Plot_Sen.ToString()))
            {
                double xAmplifier = 250 * step;

                for (double i = a; i <= b; i += step)
                {
                    Ellipse e = new Ellipse();
                    e.Height = 5;
                    e.Width = 5;
                    e.Fill = Brushes.Red;

                    Canvas.SetBottom(e, 300 + 300 * Math.Sin(i));
                    Canvas.SetLeft(e, 300 + xAmplifier * i);

                    this.Plotter.Children.Add(e);
                }
            }
            else if (function.Equals(availablePlots.Plot_Cos.ToString()))
            {
                double xAmplifier = 250 * step;

                for (double i = a; i <= b; i += step)
                {
                    Ellipse e = new Ellipse();
                    e.Height = 5;
                    e.Width = 5;
                    e.Fill = Brushes.Red;

                    Canvas.SetBottom(e, 300 + 300 * Math.Cos(i));
                    Canvas.SetLeft(e, 300 + xAmplifier * i);

                    this.Plotter.Children.Add(e);
                }
            }
            else if (function.Equals(availablePlots.Plot_Factorial.ToString()))
            {
                fxDouble.Clear();

                for (int i = aInt; i <= bInt; i += stepInt)
                {
                    fxDouble.Add(Herramientas.ComputeFactorial(i));
                }

                min = fxDouble.Min();
                max = fxDouble.Max();

                double xAmplifier = 25 * step;
                double yAmplifier = (300 / Math.Abs(max - min));

                for (int i = aInt; i <= bInt; i += stepInt)
                {
                    Ellipse e = new Ellipse();
                    e.Height = 5;
                    e.Width = 5;
                    e.Fill = Brushes.Red;

                    Canvas.SetBottom(e, 300 + yAmplifier * Herramientas.ComputeFactorial(i));
                    Canvas.SetLeft(e, 300 + xAmplifier * i);

                    this.Plotter.Children.Add(e);
                }
            }
            else if (function.Equals(availablePlots.Plot_Fibonacci.ToString()))
            {
                fxDouble.Clear();

                for (int i = aInt; i <= bInt; i += stepInt)
                {
                    fxDouble.Add(Herramientas.ComputeFactorial(i));
                }

                min = fxDouble.Min();
                max = fxDouble.Max();

                double xAmplifier = 25 * step;
                double yAmplifier = (300 / Math.Abs(max - min));

                for (int i = aInt; i <= bInt; i += stepInt)
                {
                    Ellipse e = new Ellipse();
                    e.Height = 5;
                    e.Width = 5;
                    e.Fill = Brushes.Red;

                    Canvas.SetBottom(e, 300 + yAmplifier * Herramientas.ComputeFibonacci(i));
                    Canvas.SetLeft(e, 300 + xAmplifier * i);

                    this.Plotter.Children.Add(e);
                }
            }

            this.Show();
        }
Beispiel #24
0
        private static void CalculateMaxAndMinZValueFromAllSeries(ref List<DataSeries> seriesList, out Double minimumZVal, out Double maximumZVal)
        {
            List<Double> minValues = new List<double>();
            List<Double> maxValues = new List<double>();
            
            minimumZVal = 0;
            maximumZVal = 1;

            foreach (DataSeries series in seriesList)
            {
                if (series.Enabled == false)
                    continue;
                
                CalculateMaxAndMinZValue(series, out minimumZVal, out maximumZVal);
                minValues.Add(minimumZVal);
                maxValues.Add(maximumZVal);
            }

            if (minValues.Count > 0)
                minimumZVal = minValues.Min();

            if (maxValues.Count > 0)
                maximumZVal = maxValues.Max();
        }
Beispiel #25
0
		private List<AxisItem> GetAxisItemsFromDoubleList(List<double> list, AxisType axisType, Point origin, double length, bool showMin = true, bool showMax = true)
		{
			if (list == null || list.Count <= 0)
			{
				return null;
			}
			List<AxisItem> items = new List<AxisItem>(list.Count);
			double markSize = 3;
			double max = list.Max();
			double min = list.Min();
			double unit = Math.Pow(10, Math.Floor(Math.Log10(max)) - 1);

			int maxMark = (int)Math.Floor(max / unit);
			int minMark = (int)Math.Floor(min / unit);
			int diff = maxMark - minMark;

			List<double> marks = new List<double>();
			if (showMin) marks.Add(min);
			if (diff <= 10)
			{
				for (int i = minMark; i <= maxMark; i++)
				{
					if (i % 2 == 0) marks.Add(i * unit);
				}
			}
			else if (diff <= 20)
			{
				for (int i = minMark; i <= maxMark; i++)
				{
					if (i % 5 == 0) marks.Add(i * unit);
				}
			}
			else if (diff <= 50)
			{
				for (int i = minMark; i <= maxMark; i++)
				{
					if (i % 10 == 0) marks.Add(i * unit);
				}
			}
			else if (diff <= 100)
			{
				for (int i = minMark; i <= maxMark; i++)
				{
					if (i % 20 == 0) marks.Add(i * unit);
				}
			}
			if(showMax) marks.Add(max);

			foreach (var mark in marks)
			{
				TextBlock tb = new TextBlock();
				Line ln = new Line();

				if (Math.Abs(mark - 0) < 1e-50 )
				{
					tb.Text = null;
				}
				else
				{
					tb.Text = mark.ToString();
				}

				tb.TextAlignment = TextAlignment.Right;
				ln.Stroke = new SolidColorBrush(Colors.Black);
				switch (axisType)
				{
					case AxisType.X:
						Canvas.SetBottom(tb, 0);
						Canvas.SetRight(tb, length - mark * length / max);

						ln.Y1 = origin.Y;
						ln.Y2 = origin.Y - markSize;
						ln.X1 = mark * length / max + origin.X;
						ln.X2 = ln.X1;
						break;
					case AxisType.Y:
						Canvas.SetTop(tb, length - mark * length / max);
						Canvas.SetLeft(tb, 0);

						ln.Y1 = origin.Y - mark * length / max;
						ln.Y2 = ln.Y1;
						ln.X1 = origin.X; 
						ln.X2 = origin.X + markSize;
						break;
					default:
						break;
				}

				items.Add(new AxisItem
					{
						Label = tb,
						Mark = ln
					}
				);
			}
			return items;
		}