//gets the total value of all aircraft in fleet combined
 public static long GetFleetValue()
 {
     List<Int64> values = new List<Int64>();
     foreach(FleetAirliner airliner in GameObject.GetInstance().HumanAirline.Fleet)
     {
         values.Add(airliner.Airliner.Price);
     }
     return values.Sum();
 }
Ejemplo n.º 2
0
        //Entwickelt und kreuzt zwei Dots
        public bool DevelopNextGeneration()
        {
            List<double> listFitnessValues = new List<double>();
            double generalFitness = 0;
            Random rd = new Random();
            double tempRdValue = 0; //temp Random Value
            double tempInkValue = 0; //temp Inkrement Value
            try
            {
                //Puts the fitnessvalue of every dot in a list
                foreach (MyDot d in myDots)
                {
                    listFitnessValues.Add(d.Fitness);
                }
                //Divide all values through 0
                for (int i = 0; i < listFitnessValues.Count; i++)
                {
                    if (listFitnessValues[i] != 0)
                    {
                        listFitnessValues[i] = 1 / listFitnessValues[i];
                    }
                }

                generalFitness = listFitnessValues.Sum();
                tempRdValue = rd.NextDouble() * generalFitness;
                int k = 0;
                while (!((tempInkValue - listFitnessValues[k] < tempRdValue) && (tempInkValue + listFitnessValues[k+1] > tempRdValue)))
                {
                    tempInkValue += listFitnessValues[k];
                }
            }
            catch
            {
                return false;
            }

            return true;
        }
Ejemplo n.º 3
0
        private void btn_simulate_Click(object sender, RoutedEventArgs e)
        {
            int nbrSim = Convert.ToInt32(txt_nbrsim.Text);
            double initWealth = Properties.Settings.Default.InitWealth;

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

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

            txt_earnings.Text = finalEarnings.Average().ToString();
            txt_plays.Text = counts.Average().ToString();
            txt_maxEarnings.Text = finalEarnings.Max().ToString();
            txt_maxLosses.Text = finalEarnings.Min().ToString();
            txt_totEarnings.Text = finalEarnings.Where(x => x > 0).Sum().ToString();
            txt_totLosses.Text = finalEarnings.Where(x => x < 0).Sum().ToString();
            txt_balance.Text = finalEarnings.Sum().ToString();
        }
Ejemplo n.º 4
0
        private static int[] PruneAutosavesSprtGetDeletes(List<int>[] deletableSets, int numToDelete)
        {
            if (deletableSets.Sum(o => o.Count) == numToDelete)
            {
                // Everything in deletable sets needs to be deleted, so just return them all instead of taking the expense of load balancing
                return deletableSets.SelectMany(o => o).ToArray();
            }

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

            for (int cntr = 0; cntr < numToDelete; cntr++)
            {
                // Get the largest sets
                int maxSize = deletableSets.Max(o => o.Count);
                List<int>[] largest = deletableSets.Where(o => o.Count == maxSize).ToArray();

                // Pick a random set, and a random index within that set
                int setIndex = StaticRandom.Next(largest.Length);
                int innerIndex = StaticRandom.Next(largest[setIndex].Count);

                // Store the value pointed to
                retVal.Add(largest[setIndex][innerIndex]);

                // Now remove this from the set
                largest[setIndex].RemoveAt(innerIndex);
            }

            return retVal.ToArray();
        }
Ejemplo n.º 5
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

        }
Ejemplo n.º 6
0
 private byte[] Combine(List<  byte[] > arrays)
 {
     byte[] rv = new byte[arrays.Sum(a => a.Length)];
     int offset = 0;
     foreach (byte[] array in arrays)
     {
         System.Buffer.BlockCopy(array, 0, rv, offset, array.Length);
         offset += array.Length;
     }
     return rv;
 }
        private void OnModelChanged()
        {
            DateTime startDate;
            DateTime endDate;

            switch (this.Model.Grouping)
            {
                case Grouping.Day:
                    startDate = this.Model.StartDate;
                    endDate = this.Model.EndDate;
                    break;
                case Grouping.Week:
                    startDate = this.Model.StartDate.ToStartOfWeek();
                    endDate = this.Model.EndDate.ToEndOfWeek();
                    break;
                case Grouping.Month:
                    startDate = this.Model.StartDate.ToStartOfMonth();
                    endDate = this.Model.EndDate.ToEndOfMonth();
                    break;
                case Grouping.Year:
                    startDate = this.Model.StartDate.ToStartOfYear();
                    endDate = this.Model.EndDate.ToEndOfYear();
                    break;
                default:
                    throw new NotImplementedException();
            }

            var itemsSource = new List<InvoiceByGroupData>();

            var currentDate = startDate;

            while (currentDate.Date <= endDate)
            {
                var data = new InvoiceByGroupData();

                data.Start = currentDate;

                switch (this.Model.Grouping)
                {
                    case Grouping.Day:
                        data.Name = currentDate.Date.ToString("M/d");
                        data.End = currentDate.Date;
                        currentDate = currentDate.Date.AddDays(1);
                        break;
                    case Grouping.Week:
                        data.Name = currentDate.Date.ToString("M/d");
                        data.End = currentDate.ToEndOfWeek();
                        currentDate = currentDate.ToStartOfNextWeek();
                        break;
                    case Grouping.Month:
                        data.Name = currentDate.Date.ToString("M/yyyy");
                        data.End = currentDate.ToEndOfMonth();
                        currentDate = currentDate.ToStartOfNextMonth();
                        break;
                    case Grouping.Year:
                        data.Name = currentDate.Date.ToString("yyyy");
                        data.End = currentDate.ToEndOfYear();
                        currentDate = currentDate.ToStartOfNextYear();
                        break;
                    default:
                        break;
                }

                data.Amount = this.Model.FilteredInvoices
                    .Where(row => row.PreparedDate >= data.Start
                                  && row.PreparedDate <= data.End)
                    .Sum(row => row.Amount);

                itemsSource.Add(data);
            }

            this.Chart.Series.Clear();

            LineSeries series;

            series = new LineSeries();

            series.Title = "Invoices";
            series.DependentValuePath = "Amount";
            series.IndependentValuePath = "Name";
            series.ItemsSource = itemsSource;
            series.DataPointStyle = (Style)Application.Current.Resources["LineDataPointStyle"];

            this.Chart.Title = string.Format("Revenues ({0:N0})", itemsSource.Sum(row => row.Amount));

            this.Chart.Series.Add(series);
        }
Ejemplo n.º 8
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();
        }
Ejemplo n.º 9
0
 public void srv_GameRecord_GetReportDetailCompleted(object sender, GetReportDetailCompletedEventArgs e)
 {
     gridLoading.Visibility = Visibility.Collapsed;
     currentPos = 0;
     obReportDetail = e.Result.ToList();
     //obReportDetail.Add(DPageSum);
     //obReportDetail.Add(DTotalSum);
     if (e.Result.Count != 0)
     {
         DTotalSum = new ReportDetail();
         DTotalSum.RecordID = "总合计";
         DTotalSum.IsWin = -1;
         DTotalSum.Direction = -1;
         DTotalSum.ResultStatus = -1;
         DTotalSum.BetMoney = obReportDetail.Sum(p => p.BetMoney);
         DTotalSum.WinMoney = obReportDetail.Sum(p => p.WinMoney);
         if (e.Result.Count < 18)
         {
             obReportDetail = e.Result.ToList();
             DPageSum = new ReportDetail();
             DPageSum.RecordID = "本页合计";
             DPageSum.IsWin = -1;
             DPageSum.Direction = -1;
             DPageSum.ResultStatus = -1;
             DPageSum.BetMoney = obReportDetail.Take(18).Sum(p => p.BetMoney);
             DPageSum.WinMoney = obReportDetail.Take(18).Sum(p => p.WinMoney);
             obReportDetail.Add(DPageSum);
             obReportDetail.Add(DTotalSum);
             currentPos = 0;
             PagedCollectionView pageView = new PagedCollectionView(obReportDetail);
             pageView.PageSize = 20;
             dpRecord.PageSize = 20;
             dpRecord.Source = pageView;
             dgRecord.ItemsSource = pageView;
         }
         else
         {
             int page = int.Parse(Math.Ceiling(double.Parse(e.Result.Count.ToString()) / 18).ToString());
             for (int i = 0; i < page; i++)
             {
                 int stayNum = obReportDetail.Count - (i * 20);
                 if (stayNum > 18)
                 {
                     DPageSum = new ReportDetail();
                     DPageSum.RecordID = "本页合计";
                     DPageSum.IsWin = -1;
                     DPageSum.Direction = -1;
                     DPageSum.ResultStatus = -1;
                     //DPageSum.BetMoney = obReportDetail.Skip(i * 20).Take(18).Sum(p => p.BetMoney);
                     //DPageSum.WinMoney = obReportDetail.Skip(i * 20).Take(18).Sum(p => p.WinMoney);
                     DPageSum.BetMoney = obReportDetail.GetRange(i * 20, 18).Sum(p => p.BetMoney);
                     DPageSum.WinMoney = obReportDetail.GetRange(i * 20, 18).Sum(p => p.WinMoney);
                     obReportDetail.Insert(i * 20 + 18, DPageSum);
                     obReportDetail.Insert(i * 20 + 19, DTotalSum);
                 }
                 else
                 {
                     DPageSum = new ReportDetail();
                     DPageSum.RecordID = "本页合计";
                     DPageSum.IsWin = -1;
                     DPageSum.Direction = -1;
                     DPageSum.ResultStatus = -1;
                     //DPageSum.BetMoney = obReportDetail.Skip(i * 20).Take(stayNum).Sum(p => p.BetMoney);
                     //DPageSum.WinMoney = obReportDetail.Skip(i * 20).Take(stayNum).Sum(p => p.WinMoney);
                     DPageSum.BetMoney = obReportDetail.GetRange(i * 20, stayNum).Sum(p => p.BetMoney);
                     DPageSum.WinMoney = obReportDetail.GetRange(i * 20, stayNum).Sum(p => p.WinMoney);
                     obReportDetail.Insert(i * 20 + stayNum, DPageSum);
                     obReportDetail.Insert(i * 20 + stayNum + 1, DTotalSum);
                 }
             }
             currentPos = 0;
             PagedCollectionView pageView = new PagedCollectionView(obReportDetail);
             pageView.PageSize = 20;
             dpRecord.PageSize = 20;
             dpRecord.Source = pageView;
             dgRecord.ItemsSource = pageView;
         }
     }
     else
     {
         PagedCollectionView pageView = new PagedCollectionView(obReportDetail);
         pageView.PageSize = 20;
         dpRecord.PageSize = 20;
         dpRecord.Source = pageView;
         dgRecord.ItemsSource = pageView;
     }
     BindStatReportList(user.ID);
 }
        private void btnSellAircraft_Click(object sender, RoutedEventArgs e)
        {
            TrainingAircraft aircraft = (TrainingAircraft)((Button)sender).Tag;

            var aircrafts = new List<TrainingAircraft>(this.FlightSchool.Aircrafts);
            aircrafts.Remove(aircraft);

            Dictionary<TrainingAircraftType,int> types = this.FlightSchool.Aircrafts.GroupBy(a=>a.Type).
                     Select(group =>
                         new
                         {
                             Type = group.Key,
                             Count = group.Sum(g=>g.Type.MaxNumberOfStudents)
                         }).ToDictionary(g => g.Type, g => g.Count); ;

            foreach (PilotStudent student in this.FlightSchool.Students)
            {
                var firstAircraft = student.Rating.Aircrafts.OrderBy(a=>a.TypeLevel).First(a=>types.ContainsKey(a) && types[a] > 0);

                if (types.ContainsKey(firstAircraft))
                    types[firstAircraft]--;

            }

            Boolean canSellAircraft = aircrafts.Sum(a => a.Type.MaxNumberOfStudents) >= this.FlightSchool.Students.Count && types[aircraft.Type]>1;

            if (canSellAircraft)
            {
                WPFMessageBoxResult result = WPFMessageBox.Show(Translator.GetInstance().GetString("MessageBox", "2809"), Translator.GetInstance().GetString("MessageBox", "2809", "message"), WPFMessageBoxButtons.YesNo);

                if (result == WPFMessageBoxResult.Yes)
                {
                    this.FlightSchool.removeTrainingAircraft(aircraft);

                    double price = aircraft.Type.Price * 0.75;
                    AirlineHelpers.AddAirlineInvoice(GameObject.GetInstance().HumanAirline,GameObject.GetInstance().GameTime, Invoice.InvoiceType.Airline_Expenses, price);
                }
            }
            else
                WPFMessageBox.Show(Translator.GetInstance().GetString("MessageBox", "2810"), Translator.GetInstance().GetString("MessageBox", "2810", "message"), WPFMessageBoxButtons.Ok);
        }
        private void btnSellAircraft_Click(object sender, RoutedEventArgs e)
        {
            TrainingAircraft aircraft = (TrainingAircraft)((Button)sender).Tag;

            var aircrafts = new List<TrainingAircraft>(this.FlightSchool.Aircrafts);
            aircrafts.Remove(aircraft);

            Boolean canSellAircraft = aircrafts.Sum(a => a.Type.MaxNumberOfStudents) >= this.FlightSchool.Students.Count;

            if (canSellAircraft)
            {
                WPFMessageBoxResult result = WPFMessageBox.Show(Translator.GetInstance().GetString("MessageBox", "2809"), Translator.GetInstance().GetString("MessageBox", "2809", "message"), WPFMessageBoxButtons.YesNo);

                if (result == WPFMessageBoxResult.Yes)
                    this.FlightSchool.removeTrainingAircraft(aircraft);
            }
            else
                WPFMessageBox.Show(Translator.GetInstance().GetString("MessageBox", "2810"), Translator.GetInstance().GetString("MessageBox", "2810", "message"), WPFMessageBoxButtons.Ok);
        }
Ejemplo n.º 12
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))));
        }
Ejemplo n.º 13
0
        private void Calculate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                List<priceList> list = new List<priceList>();

                for (int i = 0; i < row; i++)
                {
                    var textbox = (TextBox)OrderItemGrid.Children.Cast<UIElement>().First(e1 => Grid.GetRow(e1) == i && Grid.GetColumn(e1) == 1);
                    var quantity = (TextBox)OrderItemGrid.Children.Cast<UIElement>().First(e1 => Grid.GetRow(e1) == i && Grid.GetColumn(e1) == 3);

                    int item;
                    int intquantity;

                    Int32.TryParse(textbox.Text.ToString(), out item);
                    Int32.TryParse(quantity.Text.ToString(), out intquantity);

                    if (item != 0 && intquantity != 0)
                    {
                        var t = list.Find(item1 => item1.id.Equals(item));
                        var priceTem = DataStore.Store.AllProduct.Find(item1 => item1.ID.Equals(item.ToString()));

                        if (t == null)
                        {
                            priceList pc = new priceList();
                            pc.id = item;
                            pc.quantity = intquantity;
                            pc.price = pc.quantity * Double.Parse(priceTem.Price);

                            list.Add(pc);
                        }
                        else
                        {
                            t.quantity += intquantity;
                            t.price = t.quantity * Double.Parse(priceTem.Price);
                        }
                    }
                }

                double fivePercent;
                double tenPercent;
                double fifteenPercent;
                double twentyPercent;

                double largest = 0;
                string reason = "";

                if (row == 0 || list.Count() == 0)
                    return;

                if (DiscountSchema.Content.Equals("Single Highest Schema"))
                {
                    //5% off if you buy 2 iphone 6 –“Iphone 6 Discount”
                    var temp = list.Find(item1 => item1.id.Equals(1));

                    if (temp.quantity == 2)
                    {
                        var priceTem = DataStore.Store.AllProduct.Find(item1 => item1.ID.Equals("1"));

                        fivePercent = (5 * temp.quantity * Int32.Parse(priceTem.Price)) / 100;
                        largest = fivePercent;
                        reason = "Iphone 6 Discount";
                    }

                    //10% off if its customers birthday on the day of ordering any product. – “Birthday Discount”

                    DateTime today = DateTime.Today;

                    int monthdiff = currentUser.Birthday.Month - today.Month;

                    int daydiff = currentUser.Birthday.Day - today.Day;

                    int yearDiff = currentUser.Birthday.Year - today.Year;

                    double sum = list.Sum(item => item.price);

                    if (monthdiff == 0 && daydiff == 0 && yearDiff != 0)
                    {
                        tenPercent = (10 * sum) / 100;

                        if (tenPercent > largest)
                        {
                            largest = tenPercent;
                            reason = "Birthday Discount";
                        }
                    }

                    //15% off if customer is more than 50 years old  - “Senior Citizen Discount”

                    if (yearDiff > 50)
                    {
                        fifteenPercent = (15 * sum) / 100;

                        if (fifteenPercent > largest)
                        {
                            largest = fifteenPercent;
                            reason = "Senior Citizen Discount";
                        }
                    }

                    //20% off if order total is more than £3000 – “High Value Order Discount”

                    if (sum > 3000)
                    {
                        twentyPercent = (20 * sum) / 100;

                        if (twentyPercent > largest)
                        {
                            largest = twentyPercent;
                            reason = "High Value Order Discount";
                        }
                    }

                    DisList.Text = reason + "\n " + "Single Highest Schema";
                    DisPrice.Text = (sum - largest).ToString();
                }
                else
                {
                    fifteenPercent = 0;
                    tenPercent = 0;
                    fivePercent = 0;
                    twentyPercent = 0;

                    //5% off if you buy 2 iphone 6 –“Iphone 6 Discount”
                    var temp = list.Find(item1 => item1.id.Equals(1));

                    if (temp.quantity == 2)
                    {
                        var priceTem = DataStore.Store.AllProduct.Find(item1 => item1.ID.Equals("1"));

                        fivePercent = (5 * temp.quantity * Int32.Parse(priceTem.Price)) / 100;
                        //largest = fivePercent;
                        reason = "Iphone 6 Discount";
                    }

                    //10% off if its customers birthday on the day of ordering any product. – “Birthday Discount”

                    DateTime today = DateTime.Today;

                    int monthdiff = currentUser.Birthday.Month - today.Month;

                    int daydiff = currentUser.Birthday.Day - today.Day;

                    int yearDiff = currentUser.Birthday.Year - today.Year;

                    double sum = list.Sum(item => item.price);

                    if (monthdiff == 0 && daydiff == 0 && yearDiff != 0)
                    {
                        tenPercent = (10 * sum) / 100;

                        reason += " \n Birthday Discount";
                    }

                    //15% off if customer is more than 50 years old  - “Senior Citizen Discount”

                    if (yearDiff > 50)
                    {
                        fifteenPercent = (15 * sum) / 100;

                        reason += " \n Senior Citizen Discount";
                    }

                    //20% off if order total is more than £3000 – “High Value Order Discount”

                    if (sum > 3000)
                    {
                        twentyPercent = (20 * sum) / 100;

                        reason += " \n High Value Order Discount";
                    }

                    DisList.Text = reason + "\n " + "Multiple Discount Schema";
                    DisPrice.Text = (sum - (fivePercent + tenPercent + fifteenPercent + twentyPercent)).ToString();
                }

                string originalPrice = "";

                foreach (priceList pl in list)
                {
                    originalPrice += "Item no " + pl.id + " cost is " + pl.price;
                }

                OriPrice.Text = originalPrice;
            }
            catch(Exception ex)
            {
                MessageBox.Show("Try Again");
            }
        }
Ejemplo n.º 14
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            label1.Content = "Drawing";
            UpdateLayout();
            using (FileStream writer = File.OpenRead(@"C:\Users\Bart\Desktop\KinectPackage\KrystianThird_Marek"))
            {
                IFormatter formatter = new BinaryFormatter();
                OpenedFrames = formatter.Deserialize(writer) as List<KinectLib.SkeletonFrame>;
            }

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

            foreach (var frame in OpenedFrames)
            {
                Point p = new Point();
                p.Y = frame.X;
                p.X = frame.Z;
                points.Add(p);
            }

            Matrix A = new Matrix();
            Vector X = new Vector();
            Vector B = new Vector();

            A.M11 = points.Count();
            A.M12 = points.Sum(o=> o.X);
            A.M21 = points.Sum(o => o.X);
            A.M22 = points.Sum(o => o.X * o.X);

            B.X = points.Sum(o => o.Y);
            B.Y = points.Sum(o => o.X * o.Y);

            A.Invert();

            X.X = A.M11 * B.X + A.M12 * B.Y;
            X.Y = A.M21 * B.X + A.M22 * B.Y;

            b = X.X;
            a = X.Y;
            slope = Math.Atan(a);
                        
            off_x = canvas1.Width / 2;
            off_y = canvas1.Height / 2;
            canvas1.Children.Clear();
            c_max = OpenedFrames.Select(o => Math.Sqrt((o.X * o.X) + (o.Y * o.Y) + (o.Z * o.Z)) ).Max();
            c_min = OpenedFrames.Select(o => Math.Sqrt((o.X * o.X) + (o.Y * o.Y) + (o.Z * o.Z))).Min();
            timer.Start();
             
            /*foreach (var frame in OpenedFrames)
            {
                canvas1.Children.Clear();
                Ellipse el = new Ellipse();
                el.Width = 10;
                el.Height = 10;
                el.Fill = new SolidColorBrush(Colors.Red);
                Canvas.SetLeft(el, off_x + off_x / 2 * frame.X / c_max);
                Canvas.SetTop(el, off_y + off_x / 2 * frame.Y / c_max);
                el.InvalidateVisual();
                canvas1.Children.Add(el);
                UpdateLayout();
            }

            label1.Content = "Done";*/
        }
		private HourlyDistribution GenerateRandomHourlyDistributionInfo(DateTime currentDate)
		{
            HourInfo hi;
            List<HourInfo> hiList = new List<HourInfo>();
            DateTime date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

            hi = new HourInfo(date.AddHours(0), 2 + random.NextDouble());
            hiList.Add(hi);
            for (int i = 1; i < 23; i++)
            {
                if (i <= 5)
                {
                    hi = new HourInfo(date.AddHours(i), 1 + random.NextDouble());
                    hiList.Add(hi);
                }
                else if (i == 6 || i == 7)
                {
                    hi = new HourInfo(date.AddHours(i), random.Next(2, 3) + random.NextDouble());
                    hiList.Add(hi);
                }
                else if (i == 8)
                {
                    hi = new HourInfo(date.AddHours(i), random.Next(4, 5) + random.NextDouble());
                    hiList.Add(hi);
                }
                else if (i == 9)
                {
                    hi = new HourInfo(date.AddHours(i), random.Next(5, 6) + random.NextDouble());
                    hiList.Add(hi);
                }
                else if ((i >= 10 && i <= 11) || i == 20)
                {
                    hi = new HourInfo(date.AddHours(i), random.Next(6, 7) + random.NextDouble());
                    hiList.Add(hi);
                }
                else if ((i >= 12 && i <= 13) || (i >= 21))
                {
                    hi = new HourInfo(date.AddHours(i), random.Next(4, 5) + random.NextDouble());
                    hiList.Add(hi);
                }
                else if (i >= 14 && i <= 19)
                {
                    hi = new HourInfo(date.AddHours(i), 6 + random.NextDouble());
                    hiList.Add(hi);
                }
            }

            double sumOfHourInfos = hiList.Sum(l => l.Distribution);
            hi = new HourInfo(date.AddHours(23), Math.Abs(100 - sumOfHourInfos));
            hiList.Add(hi);

            return new HourlyDistribution(currentDate, hiList);
        }
        public static String Proportionally(List<Decimal> ListOfSum, Decimal sumForDistribution)
        {
            Decimal sumOfList = ListOfSum.Sum();
            Decimal distributionCoefficient = sumForDistribution / sumOfList;

            for (Int32 nextSum = 0; nextSum < ListOfSum.Count; nextSum++)
            {
                ListOfSum[nextSum] = Math.Round(distributionCoefficient * ListOfSum[nextSum], 2);
            }
            return String.Join(";", ListOfSum.ToArray());
        }