public ResultsWindow(Stats stat, List<Node> results, EightSquares eightPuzzle, int expanded, int total)
        {
            InitializeComponent();
            this.eightPuzzle = eightPuzzle;
            this.stat = stat;
            expandedCount.Text += expanded;
            genCount.Text += total;
            movesMade.Text += results.Last().gValue;
            avgBranchingFactor.Text += Math.Round((Double)total / expanded, 3);
            Double temp = (double)1 / (double)results.Last().gValue;
            effBranchingFactor.Text += Math.Round(Math.Pow(expanded, temp), 3);
            List<Data> source = new List<Data>();
            foreach (Node n in results)
            {
                source.Add(new Data()
                {
                    hValue = n.hValue,
                    gValue = n.gValue,
                    fValue = n.fValue,
                    action = n.action,
                    state = stringifyState(n),
                    thisNode = n
                });

                actionsToGoal.Text += (n.action != String.Empty && n.gValue != results.Count - 1) ? String.Format("{0}, ", n.action) : n.action;
            }
            grid.ItemsSource = source;
            //grid.DataContext = results[0];
        }
Example #2
0
        // takes list of participants sorted by place in age division, returns top 3..ish
        List<AgeChampion> CalcAgeChampions(List<AgeChampion> champions, List<Participant> participants, int place = 1)
        {
            Participant p = participants.First();
            participants.Remove(p);

            // no points scored, cannot be a champion
            if (ParticipantPoints(p) == 0)
                return champions;

            champions.Add(new AgeChampion(p, place, ParticipantPoints(p)));

            // no more possible champions
            if (participants.Count == 0)
                return champions;

            // if the same number of points, equal age champion w/ same place
            if (champions.Last().Points == ParticipantPoints(participants.First()))
                CalcAgeChampions(champions, participants, place);

            // room for more champions
            else if (champions.Count < 3)
                CalcAgeChampions(champions, participants, place + 1);

            return champions;
        }
        public static List<Fragment> FragmentData(Fragment data, int mtu, int header = 20)
        {
            var localData = new Fragment(data);
            var result = new List<Fragment>();
            while (localData.Length + header > mtu)
            {
                var temp = new Fragment(EightMultiple(mtu - header),
                                            true,
                                            localData.Offset);

                localData.Length -= temp.Length;
                localData.Offset = (temp.Length / 8) + ((result.Count > 0) ? result.Last().Offset : 0);
                result.Add(temp);
            }
            if (localData.Length != 0)
            {
                localData.Offset += (result.Count > 0) ? result.Last().Offset : 0;
                result.Add(localData);
            }

            return result;
        }
Example #4
0
        public void SetDataSource(List<Dictionary<string, object>> dataSource)
        {
            if (dataSource == null || dataSource.Count == 0)
            {
                return;
            }
            this.SearchChartView.ClearPoints();

            var entry0 = dataSource[0];
            var entryf = dataSource.Last();
            DateTime beginTime = DateTime.Parse((string)entry0["time"]);
            DateTime finalTime = DateTime.Parse((string)entryf["time"]);

            this.SearchChartView.UpdateTimeAxis(beginTime, finalTime, dataSource, dataSource.Count());
            this.SearchChartView.SetDataPoints(dataSource);
            /*
            foreach (var e in dataSource)
            {
                this.SearchChartView.AddCurvesDataPoint(e);
            }
            */
        }
Example #5
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            drawingContext.DrawLine(new Pen(Brushes.White, _firstThresholdThickness), new Point(-_firstThresholdThickness/2, 0), new Point(-_firstThresholdThickness/2, ActualHeight));
            var con = 17.817;
            List<double> points = new List<double>();
            double lasX = 0;

            for (int index = 0; index < NumberFrets; index++)
            {
                double x = lasX + (ActualWidth - lasX) / con;
                lasX = x;
                points.Add(x);
            }

            double scale = ActualWidth / points.Last();

            for (int index = 0; index < NumberFrets; index++)
            {
                Point strPoint = new Point(points[index]* scale, 0);
                Point endPoint = new Point(points[index]* scale, ActualHeight);
                drawingContext.DrawLine(new Pen(Brushes.Black, 2), strPoint, endPoint);
            }
        }
        public StartModelWindow()
        {
            InitializeComponent();

            environments = new List<EnvironmentPreset>(); //добавляем параметры для различных сред
            environments.Add(new EnvironmentPreset("H2O", 1, new Element[]{new Element(1, 20.4), new Element(16, 3.76)}, new int[]{2, 1}));
            environments.Add(new EnvironmentPreset("D2O", 1.11f, new Element[] { new Element(2, 3.39), new Element(16, 3.76) }, new int[] {2, 1}));
            environments.Add(new EnvironmentPreset("Be", 1.848f, new Element[]{new Element(9, 6.14)}, new int[]{1}));
            environments.Add(new EnvironmentPreset("BeO", 3.02f, new Element[] { new Element(9, 6.14), new Element(16, 3.76) }, new int[] {1, 1}));
            environments.Add(new EnvironmentPreset("C", 2.25f, new Element[] { new Element(12, 4.75) }, new int[] {1}));

            lstEnvironment.ItemsSource = environments;
            lstEnvironment.SelectedItem = environments.Last();

            this.position = new Vector3D(0, 0, 0); //координаты источника
            this.energy = 3; //начальная энергия (МэВ)
            this.count = 10; //число судеб для рассмотрения

            //по умолчанию среда - углерод
            this.env = ((EnvironmentPreset)lstEnvironment.SelectedItem);

            this.DataContext = this;
        }
Example #7
0
		public void SetParameter ()
			{
			if (m_Arguments.Count == 0)
				return;
			if (!File.Exists (m_Arguments ["P0"]))
				return;
#region Data for Root PreviewBeitrag

			m_TypeOfBeitrag = WMB.Basics.GetCommandLineContent (m_Arguments, CVM.CommonValues.WPMEDIA_TYPE_OF_BEITRAG);
			m_OrderNumber = WMB.Basics.GetCommandLineContent (m_Arguments, CVM.CommonValues.WPMEDIA_ORDER_NUMBER);
			m_BeitragsIDOfPreviewBeitrag = WMB.Basics.GetCommandLineContent (m_Arguments, WPMediaManagement.ManagedProgrammData.Param_VideoBeitragsID);
			m_ConnectedBeitragsID = WMB.Basics.GetCommandLineContent (m_Arguments, WPMediaManagement.ManagedProgrammData.Param_LogicallyConnectedBeitragsID);

			//m_FullBeitragToDisplay = new ArrayList ();
			//m_StartingTimesToDisplay = new ArrayList ();
			m_ProgrammManagement = new WPMediaManagement.ManagedProgrammManagement ();
			if (!m_ProgrammManagement.ProgrammData.FullBeitragList.ContainsKey (m_BeitragsIDOfPreviewBeitrag))
				{
				WMB.Basics.ReportErrorToEventViewer ("ProgrammPreview.SetParameter",
					"Für die ID \"" + m_BeitragsIDOfPreviewBeitrag + "\" gibt es keinen Eintrag");
				}
			m_BeitragsFullDataSetOfPreviewBeitrag = m_ProgrammManagement.ProgrammData.FullBeitragList [m_BeitragsIDOfPreviewBeitrag];
			DataRow [] BeitragsSchedulingRows = m_ProgrammManagement.ProgrammData.SchedulingDataSet.Tables ["Scheduling"].Select
				("OrderNumber = '" + m_OrderNumber + "'");
			if (BeitragsSchedulingRows.Length < 1)
				{
				WMB.Basics.ReportErrorToEventViewer ("ProgrammPreview.SetParameter",
					"Für die OrderNumber = \"" + m_OrderNumber + "\" gibt es keinen Eintrag");
				m_TypeOfBeitrag = String.Empty;
				return;
				}
			m_BeitragsSchedulingRow = BeitragsSchedulingRows [0];
			List<Slide> SlideList = new List<Slide> ();
#endregion
			if (m_TypeOfBeitrag == WPMediaManagement.ManagedProgrammData.BLOCK_PREVIEW)
				{
				Dictionary<String, List<String>> StartTimes = m_ProgrammManagement.ProgrammData.GetStartTimesForEachBeitragIDInThisBlock
					(m_BeitragsSchedulingRow ["ParentBlockOrderNumber"].ToString ());
				m_CompleteRunningTime = (m_HostCVM.TimeToStop - m_HostCVM.GetDateTimeNow).TotalSeconds;
				TimeSpan PictureIntervall = TimeSpan.FromSeconds(((m_CompleteRunningTime
												- CVM.CommonValues.DEFAULT_TIME_FOR_COMMON_OPEN_CHANNEL_INFO
												- CVM.CommonValues.DEFAULT_TIME_FOR_COMMON_BIETE_SUCHE_INFO
												- CVM.CommonValues.DEFAULT_TIME_FOR_COMMON_PREVIEW_INFO)
													/ StartTimes.Keys.Count));

				foreach (String BeitragID in StartTimes.Keys)
					{
					if (!m_ProgrammManagement.ProgrammData.FullBeitragList.ContainsKey(BeitragID))
						{
						WMB.Basics.ReportErrorToEventViewer("ProgrammPreview.CreateListOfDisplayableBeitraege",
							"Der Beitrag \"" + BeitragID + "\" ist nicht zugreifbar");
						continue;
						}

					SlideList.Add (new Slide ());
					SlideList.Last ().Content = new ProgrammEntryPreview (this, BeitragID, m_TypeOfBeitrag)
						{
						BeitragToPreviewFullDataSet = m_ProgrammManagement.ProgrammData.FullBeitragList [BeitragID],
						StartTimesForThisBeitragIDInThisBlock = (StartTimes [BeitragID])
						};
					SlideList.Last ().Options.DisplayDuration = PictureIntervall;
					}
				m_CompleteRunningTime = (m_HostCVM.TimeToStop - m_HostCVM.GetDateTimeNow).TotalSeconds;
				}
			else
				{
				TimeSpan PictureIntervall = m_ProgrammManagement.ProgrammData.GetDefinedDuration(m_BeitragsSchedulingRow);
				m_CompleteRunningTime = PictureIntervall.TotalSeconds;
				if (!m_ProgrammManagement.ProgrammData.FullBeitragList.ContainsKey (m_ConnectedBeitragsID))
					{
					WMB.Basics.ReportErrorToEventViewer ("ProgrammPreview.CreateListOfDisplayableBeitraege",
						"Der Beitrag \"" + m_ConnectedBeitragsID + "\" ist nicht zugreifbar");

					}
				else
					{
					SlideList.Add (new Slide ());
					SlideList.Last ().Content = new ProgrammEntryPreview (this, m_ConnectedBeitragsID, m_TypeOfBeitrag)
						{
						BeitragToPreviewFullDataSet = m_ProgrammManagement.ProgrammData.FullBeitragList [m_ConnectedBeitragsID]
						};
					SlideList.Last ().Options.DisplayDuration = PictureIntervall;
					}
				}
			SlideShow.Slides = SlideList.ToArray();
			SlideShow.TargetControl = TargetContent;

			}
Example #8
0
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            this.ManipulationStarted += new EventHandler<ManipulationStartedEventArgs>(_uppart_ManipulationStarted);
            this.ManipulationDelta += new EventHandler<ManipulationDeltaEventArgs>(_uppart_ManipulationDelta);
            this.ManipulationCompleted += new EventHandler<ManipulationCompletedEventArgs>(_uppart_ManipulationCompleted);

            _pageElements.Add(_border0);
            _pageElements.Add(_border2);
            _pageElements.Add(_border1);

            _pixellist = new PixelData[6];
            _bmps = new WriteableBitmap[6];
            for (int i = 0; i < _bmps.Length; ++i)
            {
                var bmp = new WriteableBitmap(480, 400);
                _bmps[i] = bmp;
                _pixellist[i].Pixels = bmp.Pixels;
            }

            _samplebitmaps = new List<WriteableBitmap>();
            string[] fn = new string[]
            {
                "img.jpg",
                "img01.jpg",
                "img02.jpg",
                "img03.jpg",
                "img04.jpg",
                "img05.jpg",
                "img06.jpg",
                "img07.jpg"
            };

            foreach (var f in fn)
            {
                var wbmp = BitmapFromResource(f);
                var wbmpout0 = new WriteableBitmap(480, 400);
                var wbmpout1 = new WriteableBitmap(480, 400);
                SplitBitmap(wbmp, wbmpout0, wbmpout1);

                _samplebitmaps.Add(wbmpout0);
                _samplebitmaps.Add(wbmpout1);
            }

            var firstpage = new FlipPage
            {
                Front = _samplebitmaps[0],
                Back = _samplebitmaps[0]
            };
            _pages.Add(firstpage);

            for (int i = 1; i < _samplebitmaps.Count - 1; i += 2)
            {
                var page = new FlipPage
                {
                    Front = _samplebitmaps[i],
                    Back = _samplebitmaps[i + 1]
                };
                _pages.Add(page);
            }

            var lastpage = new FlipPage
            {
                Front = _samplebitmaps.Last(),
                Back = _samplebitmaps.Last()
            };
            _pages.Add(lastpage);

            MovePageTo(0);

            const string XAML_MOVE_ANI = @"
            <Storyboard x:Name=""_sbCurrentPage""
xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
    xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
>
			<DoubleAnimation Duration=""0:0:0.4"" To=""0"" Storyboard.TargetProperty=""CurrentPageNum"">
				<DoubleAnimation.EasingFunction>
					<PowerEase EasingMode=""EaseOut""/>
				</DoubleAnimation.EasingFunction>
			</DoubleAnimation>
		</Storyboard>";

            _sbPageMove = XamlReader.Load(XAML_MOVE_ANI) as Storyboard;
            Storyboard.SetTarget(_sbPageMove, this);

        }
		void CalculateDrawingDetails(List<List<DrawingValues>> DrawingsGrid,
			DrawingStandards Standards, String PictureName)
			{
			Standards.UsedFrame = GetDrawingFrame(PictureName);

			Standards.TargetWidth = ((double)Standards.FullWidth * ((double)Standards.UsedFrame.PositionRight
							- (double)Standards.UsedFrame.PositionLeft)) / 100;
			double FullTargetHeight = ((double)Standards.FullHeight * ((double)Standards.UsedFrame.PositionBottom
							- (double)Standards.UsedFrame.PositionTop)) / 100;
			int NumberOfLines = DrawingsGrid.Count();
			if (PictureName.Contains("Sport"))
				{
				Standards.HeightUnit = FullTargetHeight / ((double)6 + 0.2);
				Standards.TargetHeight = Standards.HeightUnit*(NumberOfLines + 0.2);
				}
			else
				{
				Standards.HeightUnit = FullTargetHeight / ((double)11 + 0.2);
				Standards.TargetHeight = Standards.HeightUnit * (NumberOfLines + 0.2);
				}
			Standards.HeightUnit = Standards.TargetHeight/((double) NumberOfLines + 0.2);
			int NumberOfColumns = DrawingsGrid.Last().Count();
			Standards.WidthUnit = Standards.TargetWidth / ((double)NumberOfColumns + 4);
			Standards.RowStartings = new List<double>();
			Standards.ColumnStartings = new List<double>();
			double MarginXValue = 4;
			double MarginYValue = 4;
			int RunningIndex = 0;
			foreach (List<DrawingValues> drawingValueses in DrawingsGrid)
				{
				if (RunningIndex == 0)
					{
					Standards.RowStartings.Add(0);
					}
				else
				if (RunningIndex == 2)
					{
					Standards.RowStartings.Add(Standards.RowStartings.Last() + (Standards.HeightUnit * 1.2));
					}
				else
					Standards.RowStartings.Add(Standards.RowStartings.Last( ) + Standards.HeightUnit);

				if (RunningIndex > 0)
					{
					SetTop(drawingValueses, Standards.RowStartings.Last(), MarginYValue);
					if (RunningIndex == 1)
						SetBottom(drawingValueses, Standards.RowStartings.Last()
													+ (Standards.HeightUnit*1.2), MarginYValue);
					else
						SetBottom(drawingValueses, Standards.RowStartings.Last()
													+ Standards.HeightUnit, MarginYValue);
					}
				RunningIndex++;
				}
			RunningIndex = 0;
			foreach (DrawingValues drawingValues in DrawingsGrid.Last())
				{
				if (RunningIndex == 0)
					{
					Standards.ColumnStartings.Add(0);
					SetLeft(GetColumnDrawingValues(DrawingsGrid, RunningIndex), 0, MarginXValue);
					SetRight(GetColumnDrawingValues(DrawingsGrid, RunningIndex), (Standards.WidthUnit * 5), MarginXValue);
					RunningIndex++;
					continue;
					}
				if (RunningIndex == 1)
					{
					Standards.ColumnStartings.Add(Standards.ColumnStartings[0] + (Standards.WidthUnit * 5));
					SetLeft(GetColumnDrawingValues(DrawingsGrid, RunningIndex),
							Standards.ColumnStartings.Last(), MarginXValue);
					SetRight(GetColumnDrawingValues(DrawingsGrid, RunningIndex),
							Standards.ColumnStartings.Last() + (Standards.WidthUnit), MarginXValue);
					RunningIndex++;
					continue;
					}
				Standards.ColumnStartings.Add(Standards.ColumnStartings[RunningIndex - 1] + Standards.WidthUnit);
				SetLeft(GetColumnDrawingValues(DrawingsGrid, RunningIndex),
							Standards.ColumnStartings.Last(), MarginXValue);
				SetRight(GetColumnDrawingValues(DrawingsGrid, RunningIndex),
							Standards.ColumnStartings.Last() + (Standards.WidthUnit), MarginXValue);
				RunningIndex++;
				}
			DrawingsGrid[0][0].OuterTop = 0;
			DrawingsGrid[0][0].OuterLeft = 0;
			DrawingsGrid[0][0].OuterBottom = Standards.HeightUnit;
			DrawingsGrid[0][0].OuterRight = Standards.TargetWidth;
			DrawingsGrid[0][0].MarginTop = DrawingsGrid[0][0].OuterTop + MarginYValue;
			DrawingsGrid[0][0].MarginLeft = DrawingsGrid[0][0].OuterLeft + MarginXValue;
			DrawingsGrid[0][0].MarginBottom = DrawingsGrid[0][0].OuterBottom - MarginYValue;
			DrawingsGrid[0][0].MarginRight = DrawingsGrid[0][0].OuterRight - MarginXValue;

			}
        private void ListarUnidadeMedidas()
        {
            List<Contrato.UnidadeMedida> lstUnidadeMedidas = new List<Contrato.UnidadeMedida>();

            Contrato.EntradaUnidadeMedida entUnidadeMedida = new Contrato.EntradaUnidadeMedida();
            entUnidadeMedida.UsuarioLogado = Comum.Util.UsuarioLogado.Login;
            entUnidadeMedida.EmpresaLogada = Comum.Parametros.EmpresaProduto;
            entUnidadeMedida.Chave = Comum.Util.Chave;
            entUnidadeMedida.UnidadeMedida = new Contrato.UnidadeMedida() { Ativo = true };

            Servico.BrasilDidaticosClient servBrasilDidaticos = new Servico.BrasilDidaticosClient(Comum.Util.RecuperarNomeEndPoint());
            Contrato.RetornoUnidadeMedida retUnidadeMedida = servBrasilDidaticos.UnidadeMedidaListar(entUnidadeMedida);
            servBrasilDidaticos.Close();

            // Se encontrou unidades de medidas
            if (retUnidadeMedida.UnidadeMedidas != null)
                // Adiciona as unidades de medidas
                lstUnidadeMedidas.AddRange(retUnidadeMedida.UnidadeMedidas);

            if (lstUnidadeMedidas != null)
            {
                List<Objeto.UnidadeMedida> objUnidadeMedidas = null;

                if (_produto != null && _produto.UnidadeMedidas != null)
                {
                    objUnidadeMedidas = new List<Objeto.UnidadeMedida>();

                    foreach (Contrato.UnidadeMedida unidadeMedida in lstUnidadeMedidas)
                    {
                        if (unidadeMedida != null)
                        {
                            objUnidadeMedidas.Add(new Objeto.UnidadeMedida { Selecionado = false, Id = unidadeMedida.Id, Nome = unidadeMedida.Nome, Ativo = unidadeMedida.Ativo });
                            Contrato.UnidadeMedida objUnidadeMedida = (from ft in _produto.UnidadeMedidas where ft.Nome == unidadeMedida.Nome select ft).FirstOrDefault();

                            if (objUnidadeMedida != null)
                            {
                                objUnidadeMedidas.Last().Selecionado = true;
                                objUnidadeMedidas.Last().Quantidade = objUnidadeMedida.Quantidade;
                                objUnidadeMedidas.Last().QuantidadeItens = objUnidadeMedida.QuantidadeItens;
                            }
                        }
                    }
                }
                else
                    objUnidadeMedidas = (from t in lstUnidadeMedidas
                                         select new Objeto.UnidadeMedida { Selecionado = false, Id = t.Id, Nome = t.Nome, Quantidade = t.Quantidade, QuantidadeItens = t.QuantidadeItens, Ativo = t.Ativo }).ToList();

                dgUnidadeMedidas.ItemsSource = objUnidadeMedidas;
            }
        }
Example #11
0
        public void GetCrossSectionProfile(List<Point> list, string fileName, int TotalPoints, double fPointWidth)
        {
            BitmapImage myBitmapImage = GetImage(fileName);
            if (myBitmapImage == null)
            {
                return;
            }

            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
            newFormatedBitmapSource.BeginInit();
            newFormatedBitmapSource.Source = myBitmapImage;
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
            newFormatedBitmapSource.EndInit();

            int width = newFormatedBitmapSource.PixelWidth;

            int stride = width * 3;
            int size = newFormatedBitmapSource.PixelHeight * stride;
            byte[] pixels = new byte[size];
            Array.Clear(pixels, 0, size);
            newFormatedBitmapSource.CopyPixels(pixels, stride, 0);

            int x = 0;
            int y = 0;
            Point ptCenter = new Point();
            ptCenter.X = newFormatedBitmapSource.PixelWidth / 2;
            ptCenter.Y = newFormatedBitmapSource.PixelHeight / 2;
            int r_begin_min = (int)Math.Min(ptCenter.X, ptCenter.Y);

            ScaleTransform scaleTransform = new ScaleTransform(fPointWidth, fPointWidth);

            double delta = TotalPoints / 360;
            for (double angle = 0; angle < 360; angle += delta)
            {
                double rad_angle = Math.PI * angle / 180.0;
                int r_begin = (int)Math.Sqrt(2 * r_begin_min * r_begin_min);

                for (double r = r_begin; r > 0; r-=1)
                {
                    x = (int)(r * Math.Cos(rad_angle)) + (int)ptCenter.X;
                    y = (int)(r * Math.Sin(rad_angle)) + (int)ptCenter.Y;
                    if (x >= newFormatedBitmapSource.PixelWidth ||
                        y >= newFormatedBitmapSource.PixelHeight ||
                        x < 0 || y < 0)
                    {
                        continue;
                    }

                    int index = y * stride + 3 * x;
                    byte red = pixels[index];
                    byte green = pixels[index + 1];
                    byte blue = pixels[index + 2];

                    Color cur_col = Color.FromRgb(red, green, blue);
                    if (cur_col != Color.FromRgb(255, 255, 255))
                    {
                        int x_add = x - (int)ptCenter.X;
                        int y_add = y - (int)ptCenter.Y;
                        Point ptToAdd = new Point(x_add, y_add);

                        if (list.Count == 0 || list.Last() != ptToAdd)
                        {
                            list.Add(ptToAdd);
                            if (list.Count == 215)
                            {
                                int h = 0 + 4;
                            }
                        }

                        break;
                    }
                }
            }
            if (scaleTransform != null)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    list[i] = scaleTransform.Transform(list[i]);
                }

            }
        }
Example #12
0
        /// <summary>
        /// Arranges children giving them a proportional space according to their <see cref="SplitSize"/> attached property value
        /// </summary>
        /// <param name="finalSize"></param>
        /// <returns></returns>
        protected override Size ArrangeOverride(Size finalSize)
        {
            //Compute the list of visible children
            List<FrameworkElement> visibleChildren = new List<FrameworkElement>();
            for (int i = 0; i < VisualChildrenCount; i++)
            {
                FrameworkElement child = GetVisualChild(i) as FrameworkElement;

                IDockableControl dockableControl = child as IDockableControl;
                if (dockableControl != null &&
                    !dockableControl.IsDocked)
                {
                    child.Arrange(new Rect());

                    if (i == VisualChildrenCount - 1 &&
                        i > 0)
                    {
                        child = GetVisualChild(i - 1) as FrameworkElement;
                        Debug.Assert(child is ResizingPanelSplitter);

                        child.Arrange(new Rect());

                        if (visibleChildren.Count > 0)
                        {
                            Debug.Assert(visibleChildren[visibleChildren.Count - 1] is ResizingPanelSplitter);
                            visibleChildren[visibleChildren.Count - 1].Arrange(new Rect());
                            visibleChildren.RemoveAt(visibleChildren.Count - 1);
                        }

                    }
                    else if (i < VisualChildrenCount - 1)
                    {
                        i++;
                        child = GetVisualChild(i) as FrameworkElement;
                        child.Arrange(new Rect());
                        Debug.Assert(child is ResizingPanelSplitter);
                    }

                    continue;
                }

                visibleChildren.Add(child);
            }

            //with no children fill the space
            if (visibleChildren.Count == 0)
            {
                _childrenFinalSizes = new Size[] { };
                return new Size();
            }

            Debug.Assert(!(visibleChildren.Last<FrameworkElement>() is ResizingPanelSplitter));
                

            _childrenFinalSizes = new Size[visibleChildren.Count];

            var splitters = from FrameworkElement child in visibleChildren
                            where child is ResizingPanelSplitter
                            select child;
            var childStars = from FrameworkElement child in visibleChildren
                             where (!(child is ResizingPanelSplitter)) && child.IsStar()
                             select child;

            var childAbsolutes = from FrameworkElement child in visibleChildren
                                 where (!(child is ResizingPanelSplitter)) && child.IsAbsolute()
                                 select child;

            var childAutoSizes = from FrameworkElement child in visibleChildren
                                 where (!(child is ResizingPanelSplitter)) && child.IsAuto()
                                 select child;

            //calculate the size of the splitters
            Size splitterSize = new Size();
            foreach (ResizingPanelSplitter splitter in splitters)
            {
                splitterSize.Width += splitter.MinWidth;
                splitterSize.Height += splitter.MinHeight;
            }

            Size minimumSize = new Size(splitterSize.Width, splitterSize.Height);
            foreach (FrameworkElement child in childStars)
            {
                minimumSize.Width += child.MinWidth;
                minimumSize.Height += child.MinHeight;
            }
            foreach (FrameworkElement child in childAbsolutes)
            {
                minimumSize.Width += child.MinWidth;
                minimumSize.Height += child.MinHeight;
            }
            foreach (FrameworkElement child in childAutoSizes)
            {
                minimumSize.Width += child.MinWidth;
                minimumSize.Height += child.MinHeight;
            }


            Size minimumPrefferedSize = new Size(minimumSize.Width, minimumSize.Height);
            foreach (FrameworkElement child in childAbsolutes)
            {
                minimumPrefferedSize.Width += child.GetAbsoluteValue() - child.MinWidth;
                minimumPrefferedSize.Height += child.GetAbsoluteValue() - child.MinHeight;
            }
            foreach (FrameworkElement child in childAutoSizes)
            {
                minimumPrefferedSize.Width += child.DesiredSize.Width - child.MinWidth;
                minimumPrefferedSize.Height += child.DesiredSize.Height - child.MinHeight;
            }

            int iChild = 0;

            if (Orientation == Orientation.Horizontal)
            {
                #region Horizontal Orientation

                //if finalSize is not sufficient...
                if (minimumSize.Width >= finalSize.Width)
                {
                    foreach (FrameworkElement child in visibleChildren)
                    {
                        _childrenFinalSizes[iChild++] = new Size(child.MinWidth, finalSize.Height);
                    }
                }
                else if (minimumPrefferedSize.Width >= finalSize.Width)
                {
                    double delta = (minimumPrefferedSize.Width - finalSize.Width) / childAbsolutes.Count<FrameworkElement>();

                    foreach (FrameworkElement child in visibleChildren)
                    {
                        if (child is ResizingPanelSplitter)
                            _childrenFinalSizes[iChild++] = new Size(child.MinWidth, finalSize.Height);
                        else if (child.IsAbsolute())
                            _childrenFinalSizes[iChild++] = new Size(Math.Max(child.GetAbsoluteValue() - delta, 0.0), finalSize.Height);
                        else
                            _childrenFinalSizes[iChild++] = new Size(child.MinWidth, finalSize.Height);
                    }
                }
                else
                {
                    double starsSum = childStars.Sum<FrameworkElement>(v => v.GetStarValue());
                    double starsFinalWidth =
                        finalSize.Width -
                        splitters.Sum<FrameworkElement>(s => s.MinWidth) -
                        childAbsolutes.Sum<FrameworkElement>(a => a.GetAbsoluteValue()) -
                        childAutoSizes.Sum<FrameworkElement>(a => a.DesiredSize.Width);

                    foreach (FrameworkElement child in visibleChildren)
                    {
                        if (child is ResizingPanelSplitter)
                            _childrenFinalSizes[iChild++] = new Size(child.MinWidth, finalSize.Height);
                        else if (child.IsAbsolute())
                            _childrenFinalSizes[iChild++] = new Size(child.GetAbsoluteValue(), finalSize.Height);
                        else if (child.IsStar())
                            _childrenFinalSizes[iChild++] = new Size(child.GetStarValue() / starsSum * starsFinalWidth, finalSize.Height);
                        else
                            _childrenFinalSizes[iChild++] = new Size(child.DesiredSize.Width, finalSize.Height);
                    }

                }

                double offset = 0.0;

                for (int i = 0; i < visibleChildren.Count; i++)
                {
                    FrameworkElement child = visibleChildren[i] as FrameworkElement;
                    child.Arrange(new Rect(offset, 0.0, _childrenFinalSizes[i].Width, finalSize.Height));
                    offset += _childrenFinalSizes[i].Width;

                    SetEffectiveSize(child, new Size(_childrenFinalSizes[i].Width, finalSize.Height));
                }

                return new Size(offset, finalSize.Height);
                #endregion
            }
            else
            {
                #region Vertical Orientation

                //if finalSize is not sufficient...
                if (minimumSize.Height >= finalSize.Height)
                {
                    foreach (FrameworkElement child in visibleChildren)
                    {
                        _childrenFinalSizes[iChild++] = new Size(finalSize.Width, child.MinHeight);
                    }
                }
                else if (minimumPrefferedSize.Height >= finalSize.Height)
                {
                    double delta = (minimumPrefferedSize.Height - finalSize.Height) / childAbsolutes.Count<FrameworkElement>();

                    foreach (FrameworkElement child in visibleChildren)
                    {
                        if (child is ResizingPanelSplitter)
                            _childrenFinalSizes[iChild++] = new Size(finalSize.Width, child.MinHeight);
                        else if (child.IsAbsolute())
                            _childrenFinalSizes[iChild++] = new Size(finalSize.Width, Math.Max(child.GetAbsoluteValue() - delta, 0.0));
                        else
                            _childrenFinalSizes[iChild++] = new Size(finalSize.Width, child.MinHeight);
                    }
                }
                else
                {
                    double starsSum = childStars.Sum<FrameworkElement>(v => v.GetStarValue());
                    double starsFinalHeight =
                        finalSize.Height -
                        splitters.Sum<FrameworkElement>(s => s.MinHeight) -
                        childAbsolutes.Sum<FrameworkElement>(a => a.GetAbsoluteValue()) -
                        childAutoSizes.Sum<FrameworkElement>(a => a.DesiredSize.Height);

                    foreach (FrameworkElement child in visibleChildren)
                    {
                        if (child is ResizingPanelSplitter)
                            _childrenFinalSizes[iChild++] = new Size(finalSize.Width, child.MinHeight);
                        else if (child.IsAbsolute())
                            _childrenFinalSizes[iChild++] = new Size(finalSize.Width, child.GetAbsoluteValue());
                        else if (child.IsStar())
                            _childrenFinalSizes[iChild++] = new Size(finalSize.Width, child.GetStarValue() / starsSum * starsFinalHeight);
                        else
                            _childrenFinalSizes[iChild++] = new Size(finalSize.Width, child.DesiredSize.Height);
                    }

                }

                double offset = 0.0;

                for (int i = 0; i < visibleChildren.Count; i++)
                {
                    FrameworkElement child = visibleChildren[i] as FrameworkElement;
                    child.Arrange(new Rect(0.0, offset, finalSize.Width, _childrenFinalSizes[i].Height));
                    offset += _childrenFinalSizes[i].Height;
                    SetEffectiveSize(child, new Size(finalSize.Width, _childrenFinalSizes[i].Height));
                }

                return new Size(finalSize.Width, offset);
                #endregion
            }


        }
        static void HtmlDocSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var current = sender as RichTextBoxFromHtml;
            if (current == null)
                return; // throw exception

            HtmlDocument doc = e.NewValue as HtmlDocument;
            if (doc == null)
                return;
            Brush linkForeGround = Application.Current.Resources["DefaultGreenBrush"] as Brush;
            Brush linkMouseOverForeGround = Application.Current.Resources["DefaultBlueBrush"] as Brush;
            var p = new List<Inline>();
            foreach (var item in doc.DocumentNode.ChildNodes)
            {
                var r = new Run();
                switch (item.NodeType)
                {
                    case HtmlNodeType.Comment:
                        throw new NotImplementedException();
                    case HtmlNodeType.Document:
                        throw new NotImplementedException();
                    case HtmlNodeType.Element:
                        if (item.Name == "br")
                        {
                            if (p.Count == 0 || p.Last().GetType() != typeof(LineBreak))
                                p.Add(new LineBreak());
                            continue;
                        }
                        else if (item.Name == "blockquote")
                        {
                            // TODO: iterate into the element for one more level
                            r.Foreground = current.SubtleForeground;
                            r.Text = item.InnerText;
                        }
                        else if (item.Name == "img")
                        {

                            if (Microsoft.Phone.Info.DeviceStatus.DeviceTotalMemory / 1048576 < 256)
                            {
                                r.Foreground = current.Foreground;
                                r.Text = item.GetAttributeValue("src", "<有图片>");
                            }
                            else
                            {
                                Image MyImage = new Image();
                                var _imgsrc = new BitmapImage();
                                _imgsrc.CreateOptions = BitmapCreateOptions.BackgroundCreation | BitmapCreateOptions.DelayCreation;
                                _imgsrc.UriSource = new Uri(item.Attributes["src"].Value, UriKind.Absolute);
                                _imgsrc.ImageFailed += (ss, ee) =>
                            {
                                WebClient wc = new WebClient();
                                wc.Headers["Referer"] = "http://www.guokr.com";
                                wc.OpenReadCompleted += (s, eee) =>
                                    {
                                        try
                                        {
                                            _imgsrc.SetSource(eee.Result);
                                        }
                                        catch
                                        {

                                        }
                                    };
                                wc.OpenReadAsync(_imgsrc.UriSource);
                            };
                                MyImage.Source = _imgsrc;
                                InlineUIContainer MyUI = new InlineUIContainer();
                                MyImage.HorizontalAlignment = HorizontalAlignment.Left;
                                MyImage.MaxWidth = 300;
                                MyUI.Child = MyImage;
                                p.Add(MyUI);
                                continue;
                            }
                        }
                        else if (item.Name == "a")
                        {
                            var h = new Hyperlink();
                            h.Foreground = linkForeGround;
                            h.TextDecorations = null;
                            h.MouseOverForeground = linkMouseOverForeGround;
                            h.MouseOverTextDecorations = null;
                            h.Inlines.Add(HtmlEntity.DeEntitize(item.InnerText));
                            if (item.Attributes.Contains("href"))
                            {
                                string url = item.Attributes["href"].Value;
                                h.Click += (ss, ee) =>
                                {
                                    var t = new WebBrowserTask();
                                    t.Uri = new Uri(url, UriKind.Absolute);
                                    t.Show();
                                };
                            }
                            p.Add(h);
                            continue;
                        }
                        else if (item.Name == "b")
                        {
                            r.FontWeight = FontWeights.Bold;
                            r.Foreground = current.Foreground;
                            r.Text = HtmlEntity.DeEntitize(item.InnerText);
                        }
                        else if (item.Name == "i")
                        {
                            r.FontStyle = FontStyles.Italic;
                            r.Foreground = current.Foreground;
                            r.Text = HtmlEntity.DeEntitize(item.InnerText);
                        }
                        else
                        {
                            //throw new NotImplementedException();
                            r.Foreground = current.Foreground;
                            r.Text = item.InnerText;
                        }
                        break;
                    case HtmlNodeType.Text:
                        r.Foreground = current.Foreground;
                        r.Text = HtmlEntity.DeEntitize(item.InnerText);
                        while (r.Text.Length > 2000)
                        {
                            var rr = r;
                            rr.Foreground = r.Foreground;
                            rr.Text = r.Text.Substring(0, 2000);
                            p.Add(rr);
                            r.Text = r.Text.Substring(2000);
                        }
                        break;
                    default:
                        throw new NotImplementedException();
                }
                p.Add(r);
            }
            var rtb = current.InternalRTB;
            rtb.Blocks.Clear();
            rtb.Blocks.Add(new Paragraph());

            var sp = current.LayoutRoot;
            sp.Children.Clear();
            sp.Children.Add(rtb);

            foreach (var item in p)
            {
                if ((rtb.Blocks.Last() as Paragraph).Inlines.Count > 15)
                {
                    rtb = new RichTextBox();
                    rtb.Blocks.Add(new Paragraph());
                    sp.Children.Add(rtb);
                }

                (rtb.Blocks.Last() as Paragraph).Inlines.Add(item);
            }
        }
Example #14
0
        private void UpdatePage(DateTime date)
        {
            try
            {
                var ValuesList = new List<DateValues>();

                VentsTools.currentActionString = "Подключаюсь к Базе данных";
                _fndHwnd = GetCurrentThreadId();
                //запустим таймер с задержкой в 1с для отображения прогрессбара (бесячий кругалек, когда все зависло)
                ProgressBarPerform = new KeyValuePair<bool, int>(true, 1000);

                string ventName = (string)Dispatcher.Invoke(new Func<string>(() => (VentsListBox.SelectedItem as Vents).name)); // возвращает название выбранного вентилятора
                bool RDVres = _vt.ReadDayValuesFromDB(VentsConst.connectionString, VentsConst._DATAtb, ventName, date, ref ValuesList);
                if (!RDVres)
                    throw new Exception(String.Format("Не удалось получить ежедневные данные для {0} за {1}", (string)Dispatcher.Invoke(new Func<string>(delegate { return (VentsListBox.SelectedItem as Vents).descr; })), (string)Dispatcher.Invoke(new Func<string>(delegate { return (string)dateP.DisplayDate.ToString(); }))));

                //разобьем список на несколько по VentsConst._VALUE_ROWS_HOURTABLE итемов в каждом
                var parts = ValuesList.DivideByLenght(VentsConst._VALUE_ROWS_DAYTABLE);
                double cellWidth = (double)Dispatcher.Invoke(new Func<double>(() => workGrid.Width / VentsConst._MAXIMUM_COLUMNS_DAYTABLE));
                double cellHeight = (double)Dispatcher.Invoke(new Func<double>(() => workGrid.Height / VentsConst._MAXIMUM_ROWS_DAYTABLE));

                Dispatcher.Invoke(new Action(delegate { BuildDayTable(parts, cellWidth, cellHeight); }));  //построим таблицу

                #region autogenerated datagrid
                //Dispatcher.Invoke(new Action(delegate
                //{
                //    workGrid.Children.Clear();
                //    for (int i = 0; i < 3;i++ )
                //    {
                //        List<DateValues> listDV = parts[i];
                //        DataGrid dataGrid = new DataGrid();
                //        dataGrid.AutoGenerateColumns = true;
                //        dataGrid.MaxHeight = 380;
                //        //dataGrid.MaxWidth = 140;
                //        dataGrid.Width = 156;
                //        dataGrid.MaxWidth = 156;
                //        dataGrid.Margin = new Thickness(200 + dataGrid.Width * i, 59, 0, 0);
                //        dataGrid.RowHeight = 30;
                //        dataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                //        dataGrid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                //        dataGrid.CanUserAddRows = false;
                //        dataGrid.CanUserDeleteRows = false;
                //        dataGrid.CanUserReorderColumns = false;
                //        dataGrid.CanUserResizeColumns = false;
                //        dataGrid.CanUserResizeRows = false;
                //        dataGrid.CanUserSortColumns = false;
                //        dataGrid.IsReadOnly = true;
                //        dataGrid.IsHitTestVisible = false;
                //        dataGrid.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
                //        dataGrid.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
                //       // dataGrid.HorizontalGridLinesBrush = new SolidColorBrush(Color.FromRgb(255,255,255));
                //        dataGrid.ItemsSource = listDV;
                //        dataGrid.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(OnAutoGeneratingColumn);
                //        // var trtr = dataGrid.ColumnWidth;
                //        workGrid.Children.Add(dataGrid);
                //    }

                //}));
                #endregion

                //calculate monthly electric power expense
                int monthlyExpense = 0;
                if (date != _firstMonth)
                {
                    bool daylyRes = _vt.ReadMonthlyExpenseFromDB(VentsConst.connectionString, VentsConst._DATAtb, ventName, date, ref monthlyExpense);
                    if (!daylyRes)
                    {
                        throw new Exception(String.Format("Не удалось получить  данные для месячного расхода {0} за {1}", (string)Dispatcher.Invoke(new Func<string>(delegate { return (VentsListBox.SelectedItem as Vents).descr; })), (string)Dispatcher.Invoke(new Func<string>(delegate { return (string)dateP.DisplayDate.ToString(); }))));
                    }
                }
                else
                {
                    monthlyExpense = ValuesList.Last<DateValues>().value - ValuesList.First<DateValues>().value;
                }
                monthlyExpense = monthlyExpense * 100;
                Dispatcher.Invoke(new Action(delegate { totaltb.Text = String.Format("Расход {0} за {1} равен {2} кВтч", (VentsListBox.SelectedItem as Vents).descr, date.GetDateTimeFormats('O')[0].Substring(0, 8), monthlyExpense.ToString()); }));

                //generate current action string and update content of main window textbox
                string descr = (string)Dispatcher.Invoke(new Func<string>(delegate { return (VentsListBox.SelectedItem as Vents).descr; }));

                VentsTools.currentActionString = String.Format("Показания за  {0} {1}", date.Date.GetDateTimeFormats('D', CultureInfo.CreateSpecificCulture("ru-ru"))[0], descr);

                ProgressBarPerform = new KeyValuePair<bool, int>(false, 1000);
                _fndHwnd = IntPtr.Zero;

            }
            catch (Exception ex)
            {
                VentsTools.currentActionString = "Не удалось подключиться к базе данных";
                _log.Error(ex.Message);
                ProgressBarPerform = new KeyValuePair<bool, int>(false, 1000);
                _fndHwnd = IntPtr.Zero;
            }
        }
Example #15
0
        // SSL stripped
        private void SSLStrip_OnSSLStripped(string sourceIP, string destIP, List<string> changed)
        {
            Window.Dispatcher.BeginInvoke(new UI(delegate
            {
                // construct "changes"
                var changedText = string.Empty;

                foreach(var change in changed)
                {
                    if(change != changed.Last())
                    {
                        changedText += change + ", ";
                    } else {
                        changedText += change;
                    }
                }

                var text = string.Empty;

                // build whole output string
                if (sourceIP != string.Empty)
                {
                    text = "Stripped: »" + changedText + "« (" + sourceIP + " -> " + destIP + ")";
                } else
                {
                    text = "Information: »" + changedText + "«";
                }

                var resultText = new Run(text);
                resultText.Foreground = new SolidColorBrush(Window.ColorSSLStrip);

                var thickness = new Thickness(0, 0, 0, 5);
                var paragraph = new Paragraph(resultText);

                paragraph.Margin = thickness;

                // don't repeat the same entries
                if (lastSSLText != text)
                {
                    lastSSLText = text;

                    if(Window.TSSLText.Document.Blocks.Count > 0) {
                        Window.TSSLText.Document.Blocks.InsertBefore(Window.TSSLText.Document.Blocks.First(), paragraph);
                    } else {
                        Window.TSSLText.Document.Blocks.Add(paragraph);
                    }
                }
            }));
        }
Example #16
0
        private void btn_eval_click(object sender, RoutedEventArgs e)
        {
            var reader = new StreamReader(new FileStream(outputFile, FileMode.Open));

            var calculatedSequence = new List<string>();
            var calculatedLatency = new List<KeyValuePair<string,int>>();
            float countAll = 0;
            float countHit = 0;
            int latency = 0;

            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                if (line.Contains("==="))               
                {
                    calculatedSequence.Clear();
                    latency = 0;
                }

                if (line.Contains("%"))
                {
                    int sequenceHit = 0;
                    countAll++;

                    calculatedSequence.Add(line.Split('%')[0].Trim());

                    var originalLabel = line.Split('%')[1].Substring(1).Trim();

                    foreach (string lbl in calculatedSequence)
                    {
                        if (!lbl.Equals(originalLabel) && sequenceHit == 0)
                            latency++;
                        else
                            sequenceHit++;
                    }
                                                  
                    // EVALUATION: berechnete Werte entsprechen zu einem drittel des erwarteten Labels und das ziellabel ist mindestens einmal in den letzten 5 Frames enthalten
                    //var hit = sequenceHit >= calculatedSequence.Count*0.33 && calculatedSequence.GetRange(calculatedSequence.Count-6,5).Contains(originalLabel);
                    var hit = originalLabel == calculatedSequence.Last();
                    if (hit)
                        countHit++;
                    else
                        latency = -1;

                    calculatedLatency.Add(new KeyValuePair<string,int>(originalLabel,latency));
                }
                else
                {
                    if (!String.IsNullOrWhiteSpace(line))
                        calculatedSequence.Add(line.Trim());
                }
            }

            reader.Close();

            float q = countHit / countAll;
            double latOverall =  calculatedLatency.Sum(i => i.Value) / calculatedLatency.Count;

            box_eval.Document.Blocks.Add(new Paragraph(new Run(String.Format("Gesamt:\t{0}\nTreffer:\t{1}\nQuote:\t{2} %\n=================================\n",
                countAll, countHit, q * 100, latOverall*100))));

            var latencyOutput = "";
            var latencySum = 0.0;
            var latencyCount = 0;
            foreach (var lat in calculatedLatency)
            {                
                if (lat.Value >= 0)
                {
                    latencyOutput += String.Format("'{0}' erkannt nach {1} Frames. (= {2} ms)\n", lat.Key, lat.Value, lat.Value * 100);//100ms (3*33ms bei 30 fps)
                    latencySum += lat.Value;
                    latencyCount++;
                }
                else
                    latencyOutput += String.Format("'{0}' nicht erkannt!\n", lat.Key);
            }
            box_eval.Document.Blocks.Add(new Paragraph(new Run(String.Format("{0}\nDurchschnittliche Latenz aller erkannten Labels: {1:000.0} ms",latencyOutput, (latencySum/latencyCount)*100))));
        }
Example #17
0
        /// <summary>
        /// Calculate ControlPoints of a DataSeries
        /// </summary>
        /// <param name="chart">Chart</param>
        /// <param name="plotGroup">Corresponding plotGroup</param>
        /// <param name="dataPoints">List of DataPoints</param>
        /// <returns>ControlPoints</returns>
        internal static Point[] CalculateControlPointsOfADataSeries(Chart chart, PlotGroup plotGroup, List<DataPoint> dataPoints)
        {   
            List<Point> tempCPoints = new List<Point>();

            if (chart != null && chart.InternalSeries != null && plotGroup != null && dataPoints.Count > 0)
            {   
                Double minimumZVal, maximumZVal;

                List<DataSeries> seriesList = chart.InternalSeries;
                CalculateMaxAndMinZValueFromAllSeries(ref seriesList, out minimumZVal, out maximumZVal);

                Double tempAxisMinimum = plotGroup._initialAxisXMin;
                Double tempAxisMaximum = plotGroup._initialAxisXMax;

                dataPoints = dataPoints.OrderBy(a => a.ZValue).ToList();
                DataPoint dataPointHavingMaxZVal = dataPoints.Last();
                Double maxBubbleRadius = CalculateBubbleSize(dataPointHavingMaxZVal, minimumZVal, maximumZVal);

                foreach (DataPoint dataPoint in dataPoints)
                {   
                    // Double maxBubbleRadius = CalculateBubbleSize(dataPoint, minimumZVal, maximumZVal);
                    List<Point> controlPointsOfDp = CalculateControlPointsOfDataPoint(dataPoint, plotGroup, maxBubbleRadius, minimumZVal, maximumZVal, plotGroup.AxisX, plotGroup.AxisY);
                    tempCPoints.InsertRange(0, controlPointsOfDp);
                }

                if (tempCPoints.Count > 0)
                {   
                    tempCPoints = tempCPoints.OrderBy(x => x.X).ToList();
                }

                // tempCPoints.Clear();
            }

            return tempCPoints.ToArray();
        }
        public List<Contrato.Produto> LerProdutosArquivo()
        {
            // Lista com os produtos
            List<Contrato.Produto> produtos = new List<Contrato.Produto>();

            // Verifica se encontrou algum erro no arquivo
            bool encontrouErro = false;

            // Se o arquivo foi informado
            if (!string.IsNullOrWhiteSpace(txtCaminhoArquivo.Conteudo))
            {
                // Lê as linhas do arquivo
                string[] strLinhas = File.ReadAllLines(txtCaminhoArquivo.Conteudo, Encoding.Default);

                // Se existe linhas
                if (strLinhas.Length > 0)
                {
                    // Retorno
                    List<string> strLinhasRetorno = new List<string>();

                    // Para cada linha existente
                    foreach (string linha in strLinhas)
                    {
                        // Nova Linha
                        string novaLinha = string.Empty;

                        // Recupera os dados separados por ';'
                        string[] conteudo = linha.Split(';');

                        // Verifica se existe pelo menos '3' informações
                        if (conteudo.Length >= 3)
                        {
                            // Se a linha está válida
                            if (ValidarLinha(conteudo, linha, out novaLinha))
                            {
                                // Adiciona o produto a lista
                                produtos.Add(new Contrato.Produto
                                {
                                    CodigoFornecedor = conteudo[0].Trim(),
                                    Nome = conteudo[1].Trim(),
                                    ValorBase = decimal.Parse(conteudo[2].Trim()),
                                    Ativo = true
                                });

                                // Verifica se vai existir a coluna de NCM do produto
                                if (chkNCM.Selecionado != null && chkNCM.Selecionado == true)
                                    produtos.Last().Ncm = conteudo[3].Trim();
                            }
                            else
                                encontrouErro = true;
                        }
                        // Adiciona um nova linha no arquivo de retorno
                        strLinhasRetorno.Add(novaLinha);
                    }

                    // Verifica se algum erro foi encontrado
                    if (encontrouErro)
                    {
                        string nomeArquivo = txtCaminhoArquivo.Conteudo + ".LOG";

                        // Grava um arquivo de log
                        File.WriteAllLines(nomeArquivo, strLinhasRetorno);

                        // Mensagem de retorno
                        string msgErro = string.Format("Foram encontrados erros no arquivo '{0}'!\n Verifique no arquivo de log '{1}' as linhas com problemas.\nCaso elas não sejam corregidas, os produtos existentes nas mesmas não serão importados!", txtCaminhoArquivo.Conteudo, nomeArquivo);

                        // Exibi uma mensagem informando que foram encontrados erros no arquivo
                        MessageBox.Show(msgErro, "Fornecedor", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }

            return produtos;
        }
Example #19
0
        protected virtual List<Control> CreateGroupMenuItems(DataNew.Entities.Group def)
        {
            var tempActions = def.GroupActions.ToArray();
            int nGroupActions = def.GroupActions == null ? 0 : tempActions.Length;
            var items = new List<Control> {CreateGroupHeader()};
            for (int i = 0; i < nGroupActions; i++)
                items.Add(CreateGroupMenuItem(tempActions[i]));

            if (nGroupActions > 0)
                items.Add(new Separator());

            if (group.Controller != null)
                items.Add(CreateGroupPassToItem());
            if (group.Visibility != GroupVisibility.Undefined)
                items.Add(CreateVisibilityItem());
            MenuItem item = CreateLookAtCardsMenuItem();
            if (item != null)
                items.Add(item);
            if (def.Id == Program.GameEngine.Definition.Table.Id)
            {
                if (!(items.Last() is Separator))
                    items.Add(new Separator());
                var noteItem = new MenuItem() { Header = "Create Note" };
                noteItem.Click += NoteItemOnClick;
                items.Add(noteItem);
            }

            if (items.Last() is Separator)
                items.RemoveAt(items.Count - 1);

            return items;
        }
Example #20
0
		public void ProcessTrackCreation (Marker StartMarker)
			{
			if (StartMarker == null)
				{
				MessageBox.Show ("Es sind bei dem gewünschten DrawAbleTrack\r\n"
				                 + "kein Startpunkt und kein Endpunkt\r\n"
				                 + "in der Datenbasis eingetragen");
				return;
				}
			List<Marker> OrderedMarker = new List<Marker> ();
			int NumberOfMarkers = ActuellMarkers.Count;
			while (NumberOfMarkers > 0)
				{
				OrderedMarker.Add(NextNeighbour(StartMarker, ActuellMarkers));
				StartMarker = OrderedMarker.Last ();
				NumberOfMarkers = ActuellMarkers.Count;
				}
			ActuellMarkers.AddRange(OrderedMarker);
			}
Example #21
0
        /// <summary>
        /// Compute the desidered size of the panel
        /// </summary>
        /// <param name="availableSize"></param>
        /// <returns></returns>
        protected override Size MeasureOverride(Size availableSize)
        {
            SetupSplitters();

            CorrectSizes();

            //Compute the list of visible children
            List<FrameworkElement> visibleChildren = new List<FrameworkElement>();
            for (int i = 0; i < VisualChildrenCount; i++)
            {
                FrameworkElement child = GetVisualChild(i) as FrameworkElement;

                IDockableControl dockableControl = child as IDockableControl;
                if (dockableControl  != null &&
                    !dockableControl.IsDocked)
                {
                    child.Measure(Size.Empty);

                    if (i == VisualChildrenCount - 1 &&
                        i > 0)
                    {
                        child = GetVisualChild(i - 1) as FrameworkElement;
                        Debug.Assert(child is ResizingPanelSplitter);

                        child.Measure(Size.Empty);

                        if (visibleChildren.Count > 0)
                        {
                            Debug.Assert(visibleChildren[visibleChildren.Count - 1] is ResizingPanelSplitter);
                            visibleChildren[visibleChildren.Count - 1].Measure(Size.Empty);
                            visibleChildren.RemoveAt(visibleChildren.Count - 1);
                        }
                    }
                    else if (i < VisualChildrenCount - 1)
                    {
                        i++;
                        child = GetVisualChild(i) as FrameworkElement;
                        Debug.Assert(child is ResizingPanelSplitter);
                        child.Measure(Size.Empty);
                    }

                    continue;
                }

                visibleChildren.Add(child);
            }


            //with no children no space needed
            if (visibleChildren.Count == 0)
                return new Size();

            Debug.Assert(!(visibleChildren.Last<FrameworkElement>() is ResizingPanelSplitter));

            if (availableSize.Width == double.PositiveInfinity &&
                Orientation == Orientation.Horizontal)
            {
                Size newAvailSize = new Size();
                foreach (FrameworkElement child in visibleChildren)
                {
                    child.Measure(availableSize);
                    newAvailSize.Width += child.DesiredSize.Width;
                    newAvailSize.Height = Math.Max(child.DesiredSize.Height, newAvailSize.Height);
                }
                availableSize = newAvailSize;
            }
            //Thx to TMx
            else if (availableSize.Height == double.PositiveInfinity &&
                Orientation == Orientation.Vertical)
            {
                Size newAvailSize = new Size();
                foreach (FrameworkElement child in visibleChildren)
                {
                    child.Measure(newAvailSize);
                    newAvailSize.Width = Math.Max(child.DesiredSize.Width, newAvailSize.Width);
                    newAvailSize.Height += child.DesiredSize.Height;
                }
                availableSize = newAvailSize;
            }

            var splitters = from FrameworkElement child in visibleChildren
                            where child is ResizingPanelSplitter
                            select child;
            var childStars = from FrameworkElement child in visibleChildren
                             where (!(child is ResizingPanelSplitter)) && child.IsStar()
                             select child;

            var childAbsolutes = from FrameworkElement child in visibleChildren
                                 where (!(child is ResizingPanelSplitter)) && child.IsAbsolute()
                                 select child;

            var childAutoSizes = from FrameworkElement child in visibleChildren
                                 where (!(child is ResizingPanelSplitter)) && child.IsAuto()
                                 select child;

            //calculate the size of the splitters
            Size splitterSize = new Size();
            foreach (ResizingPanelSplitter splitter in splitters)
            {
                splitterSize.Width += splitter.MinWidth;
                splitterSize.Height += splitter.MinHeight;
            }

            Size minimumSize = new Size(splitterSize.Width, splitterSize.Height);
            foreach (FrameworkElement child in childStars)
            {
                minimumSize.Width += child.MinWidth;
                minimumSize.Height += child.MinHeight;
            }
            foreach (FrameworkElement child in childAbsolutes)
            {
                minimumSize.Width += child.MinWidth;
                minimumSize.Height += child.MinHeight;
            }
            foreach (FrameworkElement child in childAutoSizes)
            {
                minimumSize.Width += child.MinWidth;
                minimumSize.Height += child.MinHeight;
            }


            Size minimumPrefferedSize = new Size(minimumSize.Width, minimumSize.Height);
            foreach (FrameworkElement child in childAbsolutes)
            {
                minimumPrefferedSize.Width += child.GetAbsoluteValue() - child.MinWidth;
                minimumPrefferedSize.Height += child.GetAbsoluteValue() - child.MinHeight;
            }
            foreach (FrameworkElement child in childAutoSizes)
            {
                minimumPrefferedSize.Width += child.DesiredSize.Width - child.MinWidth;
                minimumPrefferedSize.Height += child.DesiredSize.Height - child.MinHeight;
            }

            if (Orientation == Orientation.Horizontal)
            {
                #region Horizontal Orientation

                //if finalSize is not sufficient...
                double offset = 0.0;
                double maxHeight = 0.0;
                if (minimumSize.Width >= availableSize.Width)
                {
                    foreach (FrameworkElement child in visibleChildren)
                    {
                        child.Measure(new Size(child.MinWidth, availableSize.Height));
                        maxHeight = Math.Max(child.DesiredSize.Height, maxHeight);
                        offset += child.MinWidth;
                    }
                }
                else if (minimumPrefferedSize.Width >= availableSize.Width)
                {
                    double delta = (minimumPrefferedSize.Width - availableSize.Width) / childAbsolutes.Count<FrameworkElement>();

                    foreach (FrameworkElement child in visibleChildren)
                    {
                        if (child is ResizingPanelSplitter)
                        {
                            child.Measure(new Size(child.MinWidth, availableSize.Height));
                            maxHeight = Math.Max(child.DesiredSize.Height, maxHeight);
                            offset += child.MinWidth;
                        }
                        else if (child.IsAbsolute())
                        {
                            child.Measure(new Size(Math.Max(child.GetAbsoluteValue() - delta, child.MinWidth), availableSize.Height));
                            maxHeight = Math.Max(child.DesiredSize.Height, maxHeight);
                            offset += child.GetAbsoluteValue() - delta;
                        }
                        else
                        {
                            child.Measure(new Size(child.MinWidth, availableSize.Height));
                            maxHeight = Math.Max(child.DesiredSize.Height, maxHeight);
                            offset += child.MinWidth;
                        }
                    }
                }
                else
                {
                    double starsSum = childStars.Sum<FrameworkElement>(v => v.GetStarValue());
                    double starsFinalWidth =
                        availableSize.Width -
                        splitters.Sum<FrameworkElement>(s => s.MinWidth) -
                        childAbsolutes.Sum<FrameworkElement>(a => a.GetAbsoluteValue()) -
                        childAutoSizes.Sum<FrameworkElement>(a => a.DesiredSize.Width);

                    foreach (FrameworkElement child in visibleChildren)
                    {
                        if (child is ResizingPanelSplitter)
                        {
                            child.Measure(new Size(child.MinWidth, availableSize.Height));
                            maxHeight = Math.Max(child.DesiredSize.Height, maxHeight);
                            offset += child.MinWidth;
                        }
                        else if (child.IsAbsolute())
                        {
                            child.Measure(new Size(child.GetAbsoluteValue(), availableSize.Height));
                            maxHeight = Math.Max(child.DesiredSize.Height, maxHeight);
                            offset += child.GetAbsoluteValue();
                        }
                        else if (child.IsStar())
                        {
                            double w = child.GetStarValue() / starsSum * starsFinalWidth;
                            child.Measure(new Size(w, availableSize.Height));
                            maxHeight = Math.Max(child.DesiredSize.Height, maxHeight);
                            offset += w;
                        }
                        else
                        {
                            child.Measure(new Size(child.DesiredSize.Width, availableSize.Height));
                            maxHeight = Math.Max(child.DesiredSize.Height, maxHeight);
                            offset += child.DesiredSize.Width;
                        }
                    }
                }

                return new Size(offset, maxHeight);

                #endregion
            }
            else
            {
                #region Vertical Orientation

                //if finalSize is not sufficient...
                double offset = 0.0;
                double maxWidth = 0.0;
                if (minimumSize.Height >= availableSize.Height)
                {
                    foreach (FrameworkElement child in visibleChildren)
                    {
                        child.Measure(new Size(availableSize.Width, child.MinHeight));
                        maxWidth = Math.Max(child.DesiredSize.Width, maxWidth);
                        offset += child.MinHeight;
                    }
                }
                else if (minimumPrefferedSize.Height >= availableSize.Height)
                {
                    double delta = (minimumPrefferedSize.Height - availableSize.Height) / childAbsolutes.Count<FrameworkElement>();

                    foreach (FrameworkElement child in visibleChildren)
                    {
                        if (child is ResizingPanelSplitter)
                        {
                            child.Measure(new Size(availableSize.Width, child.MinHeight));
                            maxWidth = Math.Max(child.DesiredSize.Width, maxWidth);
                            offset += child.MinHeight;
                        }
                        else if (child.IsAbsolute())
                        {
                            child.Measure(new Size(availableSize.Width, Math.Max(child.GetAbsoluteValue() - delta, child.MinHeight)));
                            maxWidth = Math.Max(child.DesiredSize.Width, maxWidth);
                            offset += child.GetAbsoluteValue() - delta;
                        }
                        else
                        {
                            child.Measure(new Size(availableSize.Width, child.MinHeight));
                            maxWidth = Math.Max(child.DesiredSize.Width, maxWidth);
                            offset += child.MinWidth;
                        }
                    }
                }
                else
                {
                    double starsSum = childStars.Sum<FrameworkElement>(v => v.GetStarValue());
                    double starsFinalHeight =
                        availableSize.Height -
                        splitters.Sum<FrameworkElement>(s => s.MinHeight) -
                        childAbsolutes.Sum<FrameworkElement>(a => a.GetAbsoluteValue()) -
                        childAutoSizes.Sum<FrameworkElement>(a => a.DesiredSize.Height);

                    foreach (FrameworkElement child in visibleChildren)
                    {
                        if (child is ResizingPanelSplitter)
                        {
                            child.Measure(new Size(availableSize.Width, child.MinHeight));
                            maxWidth = Math.Max(child.DesiredSize.Width, maxWidth);
                            offset += child.MinWidth;
                        }
                        else if (child.IsAbsolute())
                        {
                            child.Measure(new Size(availableSize.Width, child.GetAbsoluteValue()));
                            maxWidth = Math.Max(child.DesiredSize.Width, maxWidth);
                            offset += child.GetAbsoluteValue();
                        }
                        else if (child.IsStar())
                        {
                            double w = child.GetStarValue() / starsSum * starsFinalHeight;
                            child.Measure(new Size(availableSize.Width, w));
                            maxWidth = Math.Max(child.DesiredSize.Width, maxWidth);
                            offset += w;
                        }
                        else
                        {
                            child.Measure(new Size(availableSize.Width, child.DesiredSize.Height));
                            maxWidth = Math.Max(child.DesiredSize.Width, maxWidth);
                            offset += child.DesiredSize.Width;
                        }
                    }
                }

                return new Size(maxWidth, offset);

                #endregion

            }
        }
Example #22
0
        void splitter_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            HideResizerOverlayWindow();

            Resizer splitter = e.Source as Resizer;
            int i = 0;

            //Compute the list of visible children
            List<FrameworkElement> visibleChildren = new List<FrameworkElement>();
            for (i = 0; i < VisualChildrenCount; i++)
            {
                FrameworkElement child = GetVisualChild(i) as FrameworkElement;

                IDockableControl dockableControl = child as IDockableControl;
                if (dockableControl != null &&
                    !dockableControl.IsDocked)
                {
                    if (i == VisualChildrenCount - 1 &&
                        i > 0)
                    {
                        //remove the last splitter added
                        if (visibleChildren.Count > 0 &&
                            visibleChildren.Last<FrameworkElement>() is Resizer)
                            visibleChildren.RemoveAt(visibleChildren.Count - 1);
                    }
                    else if (i < VisualChildrenCount - 1)
                    {
                        //discard the next splitter
                        i++;
                    }

                    continue;
                }

                visibleChildren.Add(child);
            }

            if (visibleChildren.Count == 0)
                return;

            if (visibleChildren.Last<FrameworkElement>() is Resizer)
                visibleChildren.RemoveAt(visibleChildren.Count - 1);

            Size[] currentSizes = new Size[visibleChildren.Count];
            Window wnd = Window.GetWindow(this);
            if (wnd == null)
            {
                InvalidateMeasure();
                return;
            }
            var trToWnd = TransformToAncestor(wnd).Inverse;
            Vector transformedDelta = trToWnd.Transform(new Point(e.HorizontalChange, e.VerticalChange)) -
                trToWnd.Transform(new Point());
            double delta = Orientation == Orientation.Horizontal ? transformedDelta.X : transformedDelta.Y;

            if (_childrenFinalSizes == null)
                return;

            _childrenFinalSizes.CopyTo(currentSizes, 0);

            int iSplitter = visibleChildren.IndexOf(splitter);

            Debug.Assert(iSplitter > -1);

            List<FrameworkElement> prevChildren = new List<FrameworkElement>();
            for (i = iSplitter - 1; i >= 0; i--)
            {
                FrameworkElement child = visibleChildren[i] as FrameworkElement;
                if (child is Resizer)
                    continue;
                if (child.IsAbsolute() || child.IsAuto())
                {
                    if (prevChildren.Count == 0)
                    {
                        prevChildren.Add(child);
                    }
                    break;
                }
                if (child.IsStar())
                {
                    prevChildren.Add(child);
                }
            }

            List<FrameworkElement> nextChildren = new List<FrameworkElement>();

            for (i = iSplitter + 1; i < visibleChildren.Count; i++)
            {
                FrameworkElement child = visibleChildren[i] as FrameworkElement;
                if (child is Resizer)
                    continue;
                if (child.IsAbsolute() || child.IsAuto())
                {
                    if (nextChildren.Count == 0)
                        nextChildren.Add(child);
                    break;
                }
                if (child.IsStar())
                {
                    nextChildren.Add(child);
                }
            }

            double prevMinSize = prevChildren.Sum<FrameworkElement>(c => Orientation == Orientation.Horizontal ? c.MinWidth : c.MinHeight);
            double nextMinSize = nextChildren.Sum<FrameworkElement>(c => Orientation == Orientation.Horizontal ? c.MinWidth : c.MinHeight);
            double prevMaxSize = prevChildren.Sum<FrameworkElement>(c => Orientation == Orientation.Horizontal ? c.MaxWidth : c.MaxHeight);
            double nextMaxSize = nextChildren.Sum<FrameworkElement>(c => Orientation == Orientation.Horizontal ? c.MaxWidth : c.MaxHeight);

            double prevSize = prevChildren.Sum<FrameworkElement>(c => Orientation == Orientation.Horizontal ? currentSizes[visibleChildren.IndexOf(c)].Width : currentSizes[visibleChildren.IndexOf(c)].Height);
            double nextSize = nextChildren.Sum<FrameworkElement>(c => Orientation == Orientation.Horizontal ? currentSizes[visibleChildren.IndexOf(c)].Width : currentSizes[visibleChildren.IndexOf(c)].Height);

            if (prevSize + delta < prevMinSize)
                delta = prevMinSize - prevSize;
            if (nextSize - delta < nextMinSize)
                delta = -(nextMinSize - nextSize);

            double remDelta = delta * 2;

            while (!HelperFunc.AreClose(delta, 0.0))
            {
                int prevChildrenCountWithNoMinLen =
                    prevChildren.Count<FrameworkElement>(c => delta > 0 ? true : (Orientation == Orientation.Horizontal ? currentSizes[visibleChildren.IndexOf(c)].Width > c.MinWidth : currentSizes[visibleChildren.IndexOf(c)].Height > c.MinHeight));
                int nextChildrenCountWithNoMinLen =
                    nextChildren.Count<FrameworkElement>(c => delta < 0 ? true : (Orientation == Orientation.Horizontal ? currentSizes[visibleChildren.IndexOf(c)].Width > c.MinWidth : currentSizes[visibleChildren.IndexOf(c)].Height > c.MinHeight));

                delta = remDelta / 2.0;

                for (i = 0; i < currentSizes.Length; i++)
                {
                    FrameworkElement child = visibleChildren[i] as FrameworkElement;
                    if (child is Resizer)
                        continue;

                    if (Orientation == Orientation.Horizontal)
                    {
                        if (prevChildren.Contains(child) && prevChildrenCountWithNoMinLen > 0)
                        {
                            double s = delta / prevChildrenCountWithNoMinLen;
                            if (currentSizes[i].Width + s < child.MinWidth)
                                s = child.MinWidth - currentSizes[i].Width;

                            currentSizes[i].Width += s;
                            remDelta -= s;
                        }
                        if (nextChildren.Contains(child) && nextChildrenCountWithNoMinLen > 0)
                        {
                            double s = delta / nextChildrenCountWithNoMinLen;
                            if (currentSizes[i].Width - s < child.MinWidth)
                                s = currentSizes[i].Width - child.MinWidth;

                            currentSizes[i].Width -= s;
                            remDelta -= s;
                        }
                    }
                    else
                    {
                        if (prevChildren.Contains(child) && prevChildrenCountWithNoMinLen > 0)
                        {
                            double s = delta / prevChildrenCountWithNoMinLen;
                            if (currentSizes[i].Height + s < child.MinHeight)
                                s = child.MinHeight - currentSizes[i].Height;

                            currentSizes[i].Height += s;
                            remDelta -= s;
                        }
                        if (nextChildren.Contains(child) && nextChildrenCountWithNoMinLen > 0)
                        {
                            double s = delta / nextChildrenCountWithNoMinLen;
                            if (currentSizes[i].Height - s < child.MinHeight)
                                s = currentSizes[i].Height - child.MinHeight;

                            currentSizes[i].Height -= s;
                            remDelta -= s;
                        }
                    }
                }
            }

            Debug.Assert(HelperFunc.AreClose(delta, 0.0));

            double totalStartsSum = 0.0;
            double totalSizeForStarts = 0.0;

            for (i = 0; i < visibleChildren.Count; i++)
            {
                FrameworkElement child = visibleChildren[i] as FrameworkElement;
                if (child is Resizer)
                    continue;
                if (child.IsStar())
                {
                    totalStartsSum += child.GetStarValue();
                    totalSizeForStarts += Orientation == Orientation.Horizontal ? currentSizes[i].Width : currentSizes[i].Height;
                }
            }

            double starsScaleFactor = totalStartsSum / totalSizeForStarts;

            for (i = 0; i < currentSizes.Length; i++)
            {
                FrameworkElement child = visibleChildren[i] as FrameworkElement;

                if (child is Resizer)
                    continue;

                if (child.IsStar())
                {
                    if (Orientation == Orientation.Horizontal)
                    {
                        SetResizeWidth(child,
                            new GridLength(HelperFunc.MultiplyCheckNaN(currentSizes[i].Width, starsScaleFactor), GridUnitType.Star));
                    }
                    else
                    {
                        SetResizeHeight(child,
                            new GridLength(HelperFunc.MultiplyCheckNaN(currentSizes[i].Height, starsScaleFactor), GridUnitType.Star));
                    }
                }
                else if (child.IsAbsolute())
                {
                    if (Orientation == Orientation.Horizontal)
                    {
                        SetResizeWidth(child,
                            new GridLength(currentSizes[i].Width, GridUnitType.Pixel));
                    }
                    else
                    {
                        SetResizeHeight(child,
                            new GridLength(currentSizes[i].Height, GridUnitType.Pixel));
                    }
                }
            }

            InvalidateMeasure();
        }
Example #23
0
        /// <summary>
        /// This method is called by a splitter when it is dragged
        /// </summary>
        /// <param name="splitter">Dragged splitter</param>
        /// <param name="delta"></param>
        void splitter_DragDelta(object sender, DragDeltaEventArgs e)
        {
            ResizingPanelSplitter splitter = e.Source as ResizingPanelSplitter;
            int i = 0;

            //Compute the list of visible children
            List<FrameworkElement> visibleChildren = new List<FrameworkElement>();
            for (i = 0; i < VisualChildrenCount; i++)
            {
                FrameworkElement child = GetVisualChild(i) as FrameworkElement;

                IDockableControl dockableControl = child as IDockableControl;
                if (dockableControl != null &&
                    !dockableControl.IsDocked)
                {
                    if (i == VisualChildrenCount - 1 &&
                        i > 0)
                    {
                        //remove the last splitter added
                        if (visibleChildren.Count > 0 &&
                            visibleChildren.Last<FrameworkElement>() is ResizingPanelSplitter)
                            visibleChildren.RemoveAt(visibleChildren.Count - 1);
                    }
                    else if (i < VisualChildrenCount - 1)
                    {
                        //discard the next splitter
                        i++;
                    }

                    continue;
                }

                visibleChildren.Add(child);
            }

            if (visibleChildren.Count == 0)
                return;

            if (visibleChildren.Last<FrameworkElement>() is ResizingPanelSplitter)
                visibleChildren.RemoveAt(visibleChildren.Count - 1);

            Size[] currentSizes = new Size[visibleChildren.Count];
            double delta = Orientation == Orientation.Horizontal ? e.HorizontalChange : e.VerticalChange;

            if (_childrenFinalSizes == null)
                return;

            _childrenFinalSizes.CopyTo(currentSizes, 0);

            int iSplitter = visibleChildren.IndexOf(splitter);

            Debug.Assert(iSplitter > -1);

            List<FrameworkElement> prevChildren = new List<FrameworkElement>();
            for (i = iSplitter - 1; i >= 0; i--)
            {
                FrameworkElement child = visibleChildren[i] as FrameworkElement;
                if (child is ResizingPanelSplitter)
                    continue;
                if (child.IsAbsolute() || child.IsAuto())
                {
                    if (prevChildren.Count == 0)
                    {
                        prevChildren.Add(child);
                    }
                    break;
                }
                if (child.IsStar())
                {
                    prevChildren.Add(child);
                }
            }

            List<FrameworkElement> nextChildren = new List<FrameworkElement>();

            for (i = iSplitter + 1; i < visibleChildren.Count; i++)
            {
                FrameworkElement child = visibleChildren[i] as FrameworkElement;
                if (child is ResizingPanelSplitter)
                    continue;
                if (child.IsAbsolute() || child.IsAuto())
                {
                    if (nextChildren.Count == 0)
                        nextChildren.Add(child);
                    break;
                }
                if (child.IsStar())
                {
                    nextChildren.Add(child);
                }
            }


            double prevMinSize = prevChildren.Sum<FrameworkElement>(c => Orientation == Orientation.Horizontal ? c.MinWidth : c.MinHeight);
            double nextMinSize = nextChildren.Sum<FrameworkElement>(c => Orientation == Orientation.Horizontal ? c.MinWidth : c.MinHeight);
            double prevMaxSize = prevChildren.Sum<FrameworkElement>(c => Orientation == Orientation.Horizontal ? c.MaxWidth : c.MaxHeight);
            double nextMaxSize = nextChildren.Sum<FrameworkElement>(c => Orientation == Orientation.Horizontal ? c.MaxWidth : c.MaxHeight);

            double prevSize = prevChildren.Sum<FrameworkElement>(c => Orientation == Orientation.Horizontal ? currentSizes[visibleChildren.IndexOf(c)].Width : currentSizes[visibleChildren.IndexOf(c)].Height);
            double nextSize = nextChildren.Sum<FrameworkElement>(c => Orientation == Orientation.Horizontal ? currentSizes[visibleChildren.IndexOf(c)].Width : currentSizes[visibleChildren.IndexOf(c)].Height);

            if (prevSize + delta < prevMinSize)
                delta = prevMinSize - prevSize;
            if (nextSize - delta < nextMinSize)
                delta = -(nextMinSize - nextSize);

            double remDelta = delta * 2;

            while (!HelperFunc.AreClose(delta, 0.0))
            {
                int prevChildrenCountWithNoMinLen =
                    prevChildren.Count<FrameworkElement>(c => delta > 0 ? true : (Orientation == Orientation.Horizontal ? currentSizes[visibleChildren.IndexOf(c)].Width > c.MinWidth : currentSizes[visibleChildren.IndexOf(c)].Height > c.MinHeight));
                int nextChildrenCountWithNoMinLen =
                    nextChildren.Count<FrameworkElement>(c => delta < 0 ? true : (Orientation == Orientation.Horizontal ? currentSizes[visibleChildren.IndexOf(c)].Width > c.MinWidth : currentSizes[visibleChildren.IndexOf(c)].Height > c.MinHeight));
                
                delta = remDelta / 2.0;

                for (i = 0; i < currentSizes.Length; i++)
                {
                    FrameworkElement child = visibleChildren[i] as FrameworkElement;
                    if (child is ResizingPanelSplitter)
                        continue;

                    if (Orientation == Orientation.Horizontal)
                    {
                        if (prevChildren.Contains(child) && prevChildrenCountWithNoMinLen > 0)
                        {
                            double s = delta / prevChildrenCountWithNoMinLen;
                            if (currentSizes[i].Width + s < child.MinWidth)
                                s = child.MinWidth - currentSizes[i].Width;
                            
                            currentSizes[i].Width += s;
                            remDelta -= s;
                        }
                        if (nextChildren.Contains(child) && nextChildrenCountWithNoMinLen > 0)
                        {
                            double s = delta / nextChildrenCountWithNoMinLen;
                            if (currentSizes[i].Width - s < child.MinWidth)
                                s = currentSizes[i].Width - child.MinWidth;

                            currentSizes[i].Width -= s;
                            remDelta -= s;
                        }
                    }
                    else
                    {
                        if (prevChildren.Contains(child) && prevChildrenCountWithNoMinLen > 0)
                        {
                            double s = delta / prevChildrenCountWithNoMinLen;
                            if (currentSizes[i].Height + s < child.MinHeight)
                                s = child.MinHeight - currentSizes[i].Height;

                            currentSizes[i].Height += s;
                            remDelta -= s;
                        }
                        if (nextChildren.Contains(child) && nextChildrenCountWithNoMinLen > 0)
                        {
                            double s = delta / nextChildrenCountWithNoMinLen;
                            if (currentSizes[i].Height - s < child.MinHeight)
                                s = currentSizes[i].Height - child.MinHeight;

                            currentSizes[i].Height -= s;
                            remDelta -= s;
                        }
                    }
                }
            }

            Debug.Assert(HelperFunc.AreClose(delta, 0.0));

            double totalStartsSum = 0.0;
            double totalSizeForStarts = 0.0;

            for (i = 0; i < visibleChildren.Count; i++)
            { 
                FrameworkElement child = visibleChildren[i] as FrameworkElement;
                if (child is ResizingPanelSplitter)
                    continue;
                if (child.IsStar())
                {
                    totalStartsSum += child.GetStarValue();
                    totalSizeForStarts += Orientation == Orientation.Horizontal ? currentSizes[i].Width : currentSizes[i].Height;
                }
            }
                

            double starsScaleFactor = totalStartsSum / totalSizeForStarts;

            for (i = 0; i < currentSizes.Length; i++)
            {
                FrameworkElement child = visibleChildren[i] as FrameworkElement;

                if (child is ResizingPanelSplitter)
                    continue;

                if (child.IsStar())
                {
                    if (Orientation == Orientation.Horizontal)
                    {
                        SetResizeWidth(child,
                            new GridLength(HelperFunc.MultiplyCheckNaN(currentSizes[i].Width, starsScaleFactor), GridUnitType.Star));
                    }
                    else
                    {
                        SetResizeHeight(child,
                            new GridLength(HelperFunc.MultiplyCheckNaN(currentSizes[i].Height, starsScaleFactor), GridUnitType.Star));
                    }
                }
                else if (child.IsAbsolute())
                {
                    if (Orientation == Orientation.Horizontal)
                    {
                        SetResizeWidth(child,
                            new GridLength(currentSizes[i].Width, GridUnitType.Pixel));
                    }
                    else
                    {
                        SetResizeHeight(child,
                            new GridLength(currentSizes[i].Height, GridUnitType.Pixel)); 
                    }
                }
            }

            InvalidateMeasure();
            
            //ResizingPanelSplitter splitter = e.Source as ResizingPanelSplitter;
            //int iSplitter = Children.IndexOf(splitter);

            //UIElement childPrev = null;
            //UIElement childNext = null;

            ////int posInc = ResizingDirection == ResizingDirection.Direct ? 2 : -2;
            //int posInc = 2;// FlowDirection == FlowDirection.LeftToRight ? 2 : -2;
            //int negInc = -posInc;
            //int i = iSplitter;

            //while (i >= 0 ||
            //    i < Children.Count - 1)
            //{
            //    if (NextChildIsVisible(i))
            //    {
            //        //childNext = Children[ResizingDirection == ResizingDirection.Direct ? i + 1 : i - 1];
            //        childNext = Children[i + 1];//FlowDirection == FlowDirection.LeftToRight ? i + 1 : i - 1];
            //        break;
            //    }

            //    i += posInc;
            //}

            //i = iSplitter;

            //while (i >= 0 ||
            //        i < Children.Count - 1)
            //{
            //    if (PrevChildIsVisible(i))
            //    {
            //        //childPrev = Children[ResizingDirection == ResizingDirection.Direct ? i - 1 : i + 1];
            //        childPrev = Children[i - 1];//FlowDirection == FlowDirection.LeftToRight ? i - 1 : i + 1]; 
            //        break;
            //    }

            //    i -= posInc;
            //}

            //Size resExtPrev = new Size((double)childPrev.GetValue(ResizeWidthProperty), (double)childPrev.GetValue(ResizeHeightProperty));
            //Size resExtNext = new Size((double)childNext.GetValue(ResizeWidthProperty), (double)childNext.GetValue(ResizeHeightProperty));


            //#region Orientation == Horizontal
            //if (Orientation == Orientation.Horizontal)
            //{
            //    double delta = e.HorizontalChange;

            //    if (!double.IsPositiveInfinity(resExtPrev.Width) &&
            //        (resExtPrev.Width + delta < 0))
            //        delta = -resExtPrev.Width;

            //    if (!double.IsPositiveInfinity(resExtNext.Width) &&
            //        resExtNext.Width - delta < 0)
            //        delta = resExtNext.Width;


            //    if (!double.IsPositiveInfinity(resExtPrev.Width))
            //        childPrev.SetValue(ResizeWidthProperty, resExtPrev.Width + delta);
            //    if (!double.IsPositiveInfinity(resExtNext.Width))
            //        childNext.SetValue(ResizeWidthProperty, resExtNext.Width - delta);
            //}
            //#endregion
            //#region Orientation == Vertical
            //else //if (Orientation == Orientation.Vertical)
            //{
            //    double delta = e.VerticalChange;

            //    if (!double.IsPositiveInfinity(resExtPrev.Height) &&
            //        (resExtPrev.Height + delta < 0))
            //        delta = -resExtPrev.Height;

            //    if (!double.IsPositiveInfinity(resExtNext.Height) &&
            //        resExtNext.Height - delta < 0)
            //        delta = resExtNext.Height;


            //    if (!double.IsPositiveInfinity(resExtPrev.Height))
            //        childPrev.SetValue(ResizeHeightProperty, resExtPrev.Height + delta);

            //    if (!double.IsPositiveInfinity(resExtNext.Height))
            //        childNext.SetValue(ResizeHeightProperty, resExtNext.Height - delta);
            //}
            //#endregion

        }
        private void PreencherDadosTaxas()
        {
            Contrato.EntradaTaxa entTaxa = new Contrato.EntradaTaxa();
            entTaxa.UsuarioLogado = Comum.Util.UsuarioLogado.Login;
            entTaxa.Chave = Comum.Util.Chave;
            entTaxa.EmpresaLogada = Comum.Parametros.EmpresaProduto;
            entTaxa.Taxa = new Contrato.Taxa() { Ativo = true, Fornecedor = true };

            Servico.BrasilDidaticosClient servBrasilDidaticos = new Servico.BrasilDidaticosClient(Comum.Util.RecuperarNomeEndPoint());
            Contrato.RetornoTaxa retTaxa = servBrasilDidaticos.TaxaListar(entTaxa);
            servBrasilDidaticos.Close();

            if (retTaxa.Codigo != Contrato.Constantes.COD_RETORNO_VAZIO)
            {
                List<Objeto.Taxa> objTaxas = null;

                if (_fornecedor != null && _fornecedor.Taxas != null)
                {
                    objTaxas = new List<Objeto.Taxa>();

                    foreach (Contrato.Taxa taxa in retTaxa.Taxas)
                    {
                        objTaxas.Add(new Objeto.Taxa { Selecionado = false, Id = taxa.Id, Nome = taxa.Nome, Ativo = taxa.Ativo});
                        Contrato.Taxa objTaxa = (from ft in _fornecedor.Taxas where ft != null && ft.Nome == taxa.Nome select ft).FirstOrDefault();

                        if (objTaxa != null)
                        {
                            objTaxas.Last().Selecionado = true;
                            objTaxas.Last().Valor = objTaxa.Valor;
                            objTaxas.Last().Prioridade = objTaxa.Prioridade;
                        }
                    }
                }
                else
                    objTaxas = (from t in retTaxa.Taxas
                                select new Objeto.Taxa { Selecionado = false, Id = t.Id, Nome = t.Nome, Ativo = t.Ativo }).ToList();

                dgTaxas.ItemsSource = objTaxas;

            }
        }
        private void ListarTaxas()
        {
            List<Contrato.Taxa> lstTaxas = new List<Contrato.Taxa>();

            Contrato.EntradaTaxa entTaxa = new Contrato.EntradaTaxa();
            entTaxa.UsuarioLogado = Comum.Util.UsuarioLogado.Login;
            entTaxa.EmpresaLogada = Comum.Parametros.EmpresaProduto;
            entTaxa.Chave = Comum.Util.Chave;
            entTaxa.Taxa = new Contrato.Taxa() { Ativo = true, Produto = true };

            Servico.BrasilDidaticosClient servBrasilDidaticos = new Servico.BrasilDidaticosClient(Comum.Util.RecuperarNomeEndPoint());
            Contrato.RetornoTaxa retTaxa = servBrasilDidaticos.TaxaListar(entTaxa);
            servBrasilDidaticos.Close();

            // Se encontrou taxas
            if (retTaxa.Taxas != null)
                // Adiciona as taxas do Produto
                lstTaxas.AddRange(retTaxa.Taxas);

            if (cmbFornecedor.ValorSelecionado != null)
            {
                // Recupera as taxas do fornecedor
                List<Contrato.Taxa> taxas = (from f in _lstFornecedores
                                            where f.Id == ((Contrato.Fornecedor)cmbFornecedor.ValorSelecionado).Id
                                            select f).First().Taxas;

                // Se encontrou as taxas do fornecedor
                if (taxas != null)
                {
                    // Para cada taxa dentro da listagem de taxa do fornecedor
                    foreach (Contrato.Taxa tx in taxas)
                    {
                        if (tx != null)
                        {
                            Contrato.Taxa objTaxa = lstTaxas.Where(t => t.Nome == tx.Nome).FirstOrDefault();

                            if (objTaxa != null)
                            {
                                if (lstTaxas.RemoveAll(t => t.Nome == tx.Nome && (objTaxa.Valor != t.Valor || t.Valor == 0)) > 0)
                                    lstTaxas.Add(tx);
                            }
                            else
                                lstTaxas.Add(tx);
                        }
                    }
                }
            }

            if (lstTaxas != null)
            {
                List<Objeto.Taxa> objTaxas = null;

                if (_produto != null && _produto.Taxas != null)
                {
                    objTaxas = new List<Objeto.Taxa>();

                    // Para cada taxa existente
                    foreach (Contrato.Taxa taxa in lstTaxas)
                    {
                        // Verifica se a taxa não está vazia
                        if (taxa != null)
                        {
                            // Adiciona a taxa no objeto que popula o grid
                            objTaxas.Add(new Objeto.Taxa { Selecionado = false, Id = taxa.Id, Nome = taxa.Nome, Prioridade = taxa.Prioridade, Ativo = taxa.Ativo });
                            // Recupera a mesma taxa na lista de taxas do produto
                            Contrato.Taxa objTaxa = (from ft in _produto.Taxas where ft.Nome == taxa.Nome select ft).FirstOrDefault();
                            // Se a taxa existe para o produto
                            if (objTaxa != null)
                            {
                                // Atualiza a taxa com os valores do produto
                                objTaxas.Last().Selecionado = true;
                                objTaxas.Last().Valor = objTaxa.Valor;
                                objTaxas.Last().Prioridade = objTaxa.Prioridade;
                            }
                        }
                    }
                }
                else
                    objTaxas = (from t in lstTaxas
                                select new Objeto.Taxa { Selecionado = false, Id = t.Id, Nome = t.Nome, Valor = t.Valor, Prioridade = t.Prioridade, Ativo = t.Ativo }).ToList();

                dgTaxas.ItemsSource = objTaxas;
            }
        }
Example #26
0
        public void sharedMain(Option option, CompositionProvider compositionProvider, List<DataFeed> dataFeedList, List<Share> shareList, DateTime initialDate, double strike, DateTime maturity, int windowLength, int numberOfDaysPerYear, bool simulated)
        {
            PricingResults pricingResults = compositionProvider.getComposition(dataFeedList, initialDate, windowLength, numberOfDaysPerYear);
            HedgingPortfolio portfolio = createPortfolio(option, pricingResults, dataFeedList, initialDate);
            Dictionary<System.DateTime, ResultValue> plotResults = computeResults(option, portfolio, compositionProvider, dataFeedList, windowLength, numberOfDaysPerYear, !simulated);

            // Calcul du PayOff
            double payoff = option.GetPayoff(dataFeedList.Last().PriceList);

            Console.WriteLine(portfolio.Value);
            Console.WriteLine(payoff);

            // Création du graphique de résultats
            PlotModel = new PlotModel();
            SetUpModel();
            OptionDescription = "Underlying share: " + Utilities.shareListString(shareList.ToArray()) + "\n Strike: " + strike + "\n Start Date: " + initialDate + "\n Maturity: " + maturity;

            // Tracé du plot
            DrawPlot(plotResults, payoff);
        }
        private async Task<bool> ConnectToFirstWorking(List<IPEndPoint> endpoints)
        {
            bool connected = false;
            while (!connected && endpoints.Count > 0)
            {
                IPEndPoint endpoint = null;
                try
                {
                    endpoint = endpoints.Last();
                    _mainChannel = await _node.ConnectToServer(endpoint);
                    connected = true;
                }
                catch (Exception)
                {
                    endpoints.RemoveAt(endpoints.Count - 1);
                    MessageBox.Show("Can't connect to " + endpoint);
                }
            }

            return connected;
        }
Example #28
0
        private Dictionary<System.DateTime, ResultValue> computeResults(Option option, HedgingPortfolio portfolio, CompositionProvider compositionProvider, List<DataFeed> dataFeedList, int windowLength, int nbDaysYear, bool isSimulated)
        {
            Dictionary<System.DateTime, ResultValue> plotResults = new Dictionary<System.DateTime, ResultValue>();

            // Rebalancement du portfeuille au cours du temps
            double riskFreeRate = 0;
            for (int i = windowLength; i < dataFeedList.Count() - 2; i++)
            {
                // Calcul du taux sans risque proratisé
                riskFreeRate = Utilities.computeAccruedRiskFreeRate(dataFeedList[i].Date, dataFeedList[i + 1].Date, nbDaysYear, isSimulated);

                // Rebalancement et actualisation de la valeur du portefeuille
                PricingResults pricingResults = compositionProvider.getComposition(dataFeedList, dataFeedList[i].Date, windowLength, nbDaysYear);
                portfolio.update(dataFeedList[i].PriceList, pricingResults.Deltas, riskFreeRate);
                ResultValue curentValue = new ResultValue(pricingResults.Price, portfolio.Value);
                plotResults.Add(dataFeedList[i].Date, curentValue);
            }
            // Calcul du taux sans risque proratisé
            riskFreeRate = Utilities.computeAccruedRiskFreeRate(dataFeedList[dataFeedList.Count() - 2].Date, dataFeedList[dataFeedList.Count() - 1].Date, nbDaysYear, isSimulated);
            // Valeur finale du portefeuille
            portfolio.computeValue(dataFeedList[dataFeedList.Count() - 1].PriceList, riskFreeRate);
            ResultValue finalValue = new ResultValue(option.GetPayoff(dataFeedList.Last().PriceList), portfolio.Value);
            plotResults.Add(dataFeedList.Last().Date, finalValue);

            return plotResults;
        }
Example #29
0
        private void SourceFilters_Helper(bool Checked, bool Reset=false) {
            if (Reset) { Checked = true; }
            Character.IsLoading = true;
#if SILVERLIGHT
            List<object> sourceFiltersItems = FilterTree.Items.ToList();
#else
            List<object> sourceFiltersItems = new List<object>(FilterTree.Items.Cast<object>());
#endif
            object last = sourceFiltersItems.Last<object>();
            sourceFiltersItems.RemoveAt(sourceFiltersItems.Count-1);
            ItemFilterOther TheOtherOne = last as ItemFilterOther;
            foreach(ItemFilterRegex c in sourceFiltersItems) {
                if (c.Enabled != Checked) {
                    c.Enabled = Checked;
                }
                if (Reset && c.Name.Contains("Disable")) { c.Enabled = false; }
            }
            TheOtherOne.Enabled = Checked;
            // I think this will cut back substantially on the time to process Reset and other commands
            Character.IsLoading = false;
            Character.OnCalculationsInvalidated();
        }
Example #30
0
        private static List<Run> FormatArguments(IEnumerable<ClauseArgument> arguments)
        {
            var runsList = new List<Run>();

            foreach (var arg in arguments)
            {
                runsList.Add(NewRun(arg.Name, arg.IsAtom ? SyntaxColors.Atom : SyntaxColors.Arguments));
                runsList.Add(NewRun(", ", Colors.White));
            }

            runsList.Remove(runsList.Last());
            return runsList;
        }