public VisualizationDataSource(string parameterName, object data, Algorithms algorithm, DataType dataType, bool isDynamic)
        {
            this.guid = Guid.NewGuid();

            this.parameterName = parameterName;
            this.data = data;
            this.algorithm = algorithm;

            List<string> availibleAlgorithms = new List<string>();
            switch (dataType)
            {
                case DataType.ScalarData:
                    availibleAlgorithms.Add(GetAlgorithmName(Algorithms.ColorMap));
                    availibleAlgorithms.Add(GetAlgorithmName(Algorithms.IsolineMap));
                    availibleAlgorithms.Add(GetAlgorithmName(Algorithms.Probes));
                    break;
                case DataType.VectorData:
                    availibleAlgorithms.Add(GetAlgorithmName(Algorithms.VectorMarkers));
                    break;
                case DataType.PointSet:
                    availibleAlgorithms.Add(GetAlgorithmName(Algorithms.Probes));
                    availibleAlgorithms.Add(GetAlgorithmName(Algorithms.Trajectories));
                    break;
                default: break;
            }

            this.IsDynamic = isDynamic;
        }
Example #2
0
        /// <summary>
        /// Suck in some more changes from an XmlNode.  Handy for config file parenting.
        /// </summary>
        /// <param name="node">The node to read from</param>
        public void AddSettings(XmlNode node)
        {
            if (node == null)
                return;

            if (node.Attributes != null)
            {
                var preferredAlgorithm = node.Attributes["preferredAlgorithm"];
                if (preferredAlgorithm != null)
                {
                    try
                    {
                        _preferredAlgorithm = (Algorithms)Enum.Parse(typeof(Algorithms), preferredAlgorithm.Value, true);
                    }
                    catch (ArgumentException) { }
                }
            }

            if (node.Attributes != null)
            {
                var compressionLevel = node.Attributes["compressionLevel"];
                if (compressionLevel != null)
                {
                    try
                    {
                        _compressionLevel = (CompressionLevels)Enum.Parse(typeof(CompressionLevels), compressionLevel.Value, true);
                    }
                    catch (ArgumentException) { }
                }
            }

            ParseExcludedTypes(node.SelectSingleNode("excludedMimeTypes"));
            ParseExcludedPaths(node.SelectSingleNode("excludedPaths"));

        }
Example #3
0
 private Settings()
 {
     _preferredAlgorithm = Algorithms.Default;
     _compressionLevel = CompressionLevels.Default;
     _excludedTypes = new StringCollection();
     _excludedPaths = new StringCollection();
     InitTypes();
 }
Example #4
0
 private Settings()
 {
     _preferredAlgorithm = Algorithms.None;
     _compressionLevel = CompressionLevels.None;
     _excludedTypes = new StringCollection();
     _excludedPaths = new StringCollection();
     _whitespace = false;
 }
        public SyndicationCompressionSettings(XmlNode node)
            : this()
        {
            if(node == null)
            {
                return;
            }

            _type = (Algorithms)RetrieveEnumFromAttribute(node.Attributes["type"], typeof(Algorithms));
            _level = (CompressionLevels)RetrieveEnumFromAttribute(node.Attributes["level"], typeof(CompressionLevels));
        }
Example #6
0
 private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
 {
     individualsNo.Text = "0";
     algorithm = Algorithms.None;
     if (AlgorithmsSelect.Items.Count > 0)
     {
         AlgorithmsSelect.SelectedIndex = 0;
     }
     form.Text = "BIA - " + comboBox1.SelectedItem.ToString();
     PrintGraph();
 }
Example #7
0
 /// <summary>
 /// Gets the percentage of sameness that the actual text is from the expected text
 /// Comparison is performed on a word level by first tokenizing the string values
 /// </summary>
 /// <param name="expectedText">The expected text</param>
 /// <param name="actualText">The actual text</param>
 /// <param name="algorithm">The type of algorithm to use when calculating the edit distance</param>
 /// <returns>The percentage that the actual text is the same as the expected text</returns>
 public static decimal PhraseAccuracyPercentage(string expectedText, string actualText, Algorithms algorithm = Algorithms.Levenshtein)
 {
     return(100m - PhraseErrorPercentage(expectedText, actualText, algorithm));
 }
Example #8
0
        /// <summary>
        /// Gets the percentage of difference that the actual text is from the expected text
        /// Comparison is performed on a word level by first tokenizing the string values
        /// </summary>
        /// <param name="expectedText">The expected text</param>
        /// <param name="actualText">The actual text</param>
        /// <param name="algorithm">The type of algorithm to use when calculating the edit distance</param>
        /// <returns>The percentage that the actual text is different from the expected text</returns>
        public static decimal PhraseErrorPercentage(string expectedText, string actualText, Algorithms algorithm = Algorithms.Levenshtein)
        {
            IEnumerable <string> tokens1 = expectedText.Tokenize();
            IEnumerable <string> tokens2 = actualText.Tokenize();

            return(PhraseErrorPercentage(tokens1, tokens2, algorithm));
        }
Example #9
0
        /// <summary>
        /// Gets the Minimum Edit distance using the algorithm specified.
        /// Comparison is performed on a string level, treating each string in the IEnumerables seperately
        /// This method allow gettings the edit distance using your own tokenizer
        /// </summary>
        /// <param name="tokens1">The first of 2 IEnumerable&lt;string&gt; to compare to each other</param>
        /// <param name="tokens2">The second of 2 IEnumerable&lt;string&gt; to compare to each other</param>
        /// <param name="algorithm">The type of algorithm to use to calculate the edit distance</param>
        /// <returns>The minimum edit distance of the 2 values using the specified algorithm</returns>
        public static int PhraseEditDistance(IEnumerable <string> tokens1, IEnumerable <string> tokens2, Algorithms algorithm = Algorithms.Levenshtein)
        {
            switch (algorithm)
            {
            case Algorithms.None:
                return(StringDistance(tokens1, tokens2));

            case Algorithms.Hamming:
                return(ModHammingDistance(tokens1, tokens2, 1));

            case Algorithms.DemerauLevenshtein:
                return(DemerauLevenshteinDistance(tokens1, tokens2, 1, 1));

            default:
            case Algorithms.Levenshtein:
                return(LevenshteinDistance(tokens1, tokens2, 1, 1));
            }
        }
        //*************************************************************************
        //  Method: TryCalculateGraphMetrics()
        //
        /// <summary>
        /// Attempts to calculate a set of one or more related metrics.
        /// </summary>
        ///
        /// <param name="graph">
        /// The graph to calculate metrics for.  The graph may contain duplicate
        /// edges and self-loops.
        /// </param>
        ///
        /// <param name="calculateGraphMetricsContext">
        /// Provides access to objects needed for calculating graph metrics.
        /// </param>
        ///
        /// <param name="oneDoubleGraphMetricCalculator">
        /// Graph metric calculator in the Algorithms namespace that calculates
        /// one graph metric of type Double.
        /// </param>
        ///
        /// <param name="calculateGraphMetric">
        /// true to calculate the graph metric, false to skip it.
        /// </param>
        ///
        /// <param name="columnName">
        /// Name of the column to write to in the vertex table.
        /// </param>
        ///
        /// <param name="columnWidthChars">
        /// Width of the column, in characters, or <see
        /// cref="Microsoft.Research.CommunityTechnologies.AppLib.ExcelUtil.
        /// AutoColumnWidth" /> to set the width automatically.
        /// </param>
        ///
        /// <param name="style">
        /// Style of the column, or null to apply Excel's normal style.  Sample:
        /// "Bad".
        /// </param>
        ///
        /// <param name="graphMetricColumns">
        /// Where an array of GraphMetricColumn objects gets stored if true is
        /// returned, one for each related metric calculated by this method.
        /// </param>
        ///
        /// <returns>
        /// true if the graph metrics were calculated or don't need to be
        /// calculated, false if the user wants to cancel.
        /// </returns>
        ///
        /// <remarks>
        /// This method periodically checks BackgroundWorker.<see
        /// cref="BackgroundWorker.CancellationPending" />.  If true, the method
        /// immediately returns false.
        ///
        /// <para>
        /// It also periodically reports progress by calling the
        /// BackgroundWorker.<see
        /// cref="BackgroundWorker.ReportProgress(Int32, Object)" /> method.  The
        /// userState argument is a <see cref="GraphMetricProgress" /> object.
        /// </para>
        ///
        /// <para>
        /// Calculated metrics for hidden rows are ignored by the caller, because
        /// Excel misbehaves when values are written to hidden cells.
        /// </para>
        ///
        /// </remarks>
        //*************************************************************************
        protected Boolean TryCalculateGraphMetrics(
            IGraph graph,
            CalculateGraphMetricsContext calculateGraphMetricsContext,
            
            Algorithms.OneDoubleGraphMetricCalculatorBase
            oneDoubleGraphMetricCalculator,
            
            Boolean calculateGraphMetric,
            String columnName,
            Double columnWidthChars,
            String style,
            out GraphMetricColumn [] graphMetricColumns
            )
        {
            Debug.Assert(graph != null);
            Debug.Assert(calculateGraphMetricsContext != null);
            Debug.Assert(oneDoubleGraphMetricCalculator != null);
            Debug.Assert( !String.IsNullOrEmpty(columnName) );

            Debug.Assert(columnWidthChars == ExcelUtil.AutoColumnWidth ||
            columnWidthChars > 0);

            AssertValid();

            graphMetricColumns = new GraphMetricColumn[0];

            if (!calculateGraphMetric)
            {
            return (true);
            }

            // Calculate the graph metrics for each vertex using the
            // OneDoubleGraphMetricCalculatorBase object, which knows nothing about
            // Excel.

            Dictionary<Int32, Double> oGraphMetrics;

            if ( !oneDoubleGraphMetricCalculator.TryCalculateGraphMetrics(graph,
            calculateGraphMetricsContext.BackgroundWorker, out oGraphMetrics) )
            {
            // The user cancelled.

            return (false);
            }

            // Transfer the graph metrics to an array of GraphMetricValue objects.

            List<GraphMetricValueWithID> oGraphMetricValues =
            new List<GraphMetricValueWithID>();

            foreach (IVertex oVertex in graph.Vertices)
            {
            // Try to get the row ID stored in the worksheet.

            Int32 iRowID;

            if ( TryGetRowID(oVertex, out iRowID) )
            {
                oGraphMetricValues.Add( new GraphMetricValueWithID(
                    iRowID, oGraphMetrics[oVertex.ID] ) );
            }
            }

            graphMetricColumns = new GraphMetricColumn [] {
            new GraphMetricColumnWithID( WorksheetNames.Vertices,
                TableNames.Vertices, columnName, columnWidthChars,
                NumericFormat, style, oGraphMetricValues.ToArray()
                ) };

            return (true);
        }
        /// <summary>
        /// Finds the index of the last item, in the range of items extending from the beginning
        /// of the list to <paramref name="index"/>, that is equal to <paramref name="item"/>.
        /// </summary>
        /// <remarks>The default implementation of equality for type T is used in the search. This is the
        /// equality defined by IComparable&lt;T&gt; or object.Equals.</remarks>
        /// <param name="item">The item to search fror.</param>
        /// <param name="index">The ending index of the range to check.</param>
        /// <returns>The index of the last item in the given range that that is equal to <paramref name="item"/>.  If no item is equal
        /// to <paramref name="item"/>, -1 is returned.</returns>
        public virtual int LastIndexOf(T item, int index)
        {
            int foundIndex = Algorithms.LastIndexOf(Range(0, index + 1), item, EqualityComparer <T> .Default);

            return(foundIndex);
        }
Example #12
0
 private void RadioButton_Checked_2(object sender, RoutedEventArgs e)
 {
     algs = Algorithms.FullSearch2;
 }
Example #13
0
 public Pathing(Dungeon dungeon, Algorithms.IPathFinder pathFinding)
 {
     this.pathFinding = pathFinding;
     this.dungeon = dungeon;
 }
Example #14
0
 public static void InsertNumber_NotValidIorJ_Exception(int numberSource, int numberIn, int i, int j) =>
 Assert.Throws <ArgumentException>(() => Algorithms.InsertNumber(numberSource, numberIn, i, j));
Example #15
0
 public static int InsertNumber_ValidCases(int numberSource, int numberIn, int i, int j)
 => Algorithms.InsertNumber(numberSource, numberIn, i, j);
Example #16
0
        ////////////////////////////////////////////////////////////////////////////////
        //
        // Function Name: IVA_Classification_Segmentation
        //
        // Description  : Segments the classification image
        //
        // Parameters   : image                 - Input Image
        //                imageMask             - Segmented image
        //                roi                   - Region of Interest
        //                preprocessingOptions  - Preprocessing options
        //
        // Return Value : None
        //
        ////////////////////////////////////////////////////////////////////////////////
        public static void IVA_Classification_Segmentation(VisionImage image, VisionImage imageMask, Roi roi, ParticleClassifierPreprocessingOptions preprocessingOptions)
        {
            int useExpandedROI = 0;
            RectangleContour boundingBox = roi.GetBoundingRectangle(), expandedBox = roi.GetBoundingRectangle(), reducedBox = roi.GetBoundingRectangle();

            // Local Threshold method uses a kernel size, and the ROI must be larger than the kernel size for the function to work
            // Take care of making the ROI to extract larger if needed for the local threshold case
            if (preprocessingOptions.ThresholdType == ThresholdType.Local)
            {
                // Get the image size
                int xRes, yRes;
                xRes        = image.Width;
                yRes        = image.Height;
                boundingBox = roi.GetBoundingRectangle();

                // Take into account clipping of ROI. Just get ROI that's within bounds of image.
                if (Math.Min(xRes, (boundingBox.Left + boundingBox.Width)) - Math.Max(0, boundingBox.Left) < preprocessingOptions.LocalThresholdOptions.WindowWidth || Math.Min(yRes, (boundingBox.Top + boundingBox.Height)) - Math.Max(0, boundingBox.Top) < preprocessingOptions.LocalThresholdOptions.WindowHeight)
                {
                    // The ROI is smaller than the kernel. Try to expand the kernel in the directions needed to meet the minimum size required by the kernel.


                    int expandX     = (int)(preprocessingOptions.LocalThresholdOptions.WindowWidth / 2);
                    int expandY     = (int)(preprocessingOptions.LocalThresholdOptions.WindowHeight / 2);
                    int leftExpand  = expandX;
                    int rightExpand = expandX;
                    int leftSlack   = (int)boundingBox.Left;
                    int rightSlack  = (int)(xRes - (boundingBox.Left + boundingBox.Width));

                    if (leftExpand > leftSlack)
                    {
                        rightExpand += (leftExpand - leftSlack);
                    }

                    if (rightExpand > rightSlack)
                    {
                        leftExpand += (rightExpand - rightSlack);
                    }

                    int leftOut = (int)boundingBox.Left - leftExpand;
                    if (leftOut < 0)
                    {
                        leftOut = 0;
                    }
                    int rightOut = (int)(boundingBox.Left + boundingBox.Width + rightExpand);
                    if (rightOut > xRes)
                    {
                        rightOut = xRes;
                    }

                    int topExpand    = expandY;
                    int bottomExpand = expandY;
                    int topSlack     = (int)boundingBox.Top;
                    int bottomSlack  = (int)(yRes - (boundingBox.Top + boundingBox.Height));
                    if (topExpand > topSlack)
                    {
                        bottomExpand += (topExpand - topSlack);
                    }
                    if (bottomExpand > bottomSlack)
                    {
                        topExpand += (bottomExpand - bottomSlack);
                    }
                    int topOut = (int)(boundingBox.Top - topExpand);
                    if (topOut < 0)
                    {
                        topOut = 0;
                    }
                    int bottomOut = (int)(boundingBox.Top + boundingBox.Height + bottomExpand);
                    if (bottomOut > yRes)
                    {
                        bottomOut = yRes;
                    }
                    expandedBox.Initialize(leftOut, topOut, rightOut - leftOut, bottomOut - topOut);

                    // Create the reduced Rect so after performing the local threshold, we can reduce the size back to the original ROI dimensions.
                    reducedBox.Initialize(Math.Max(boundingBox.Left - leftOut, 0), Math.Max(boundingBox.Top - topOut, 0), boundingBox.Width + Math.Min(boundingBox.Left, 0), boundingBox.Height + Math.Min(boundingBox.Top, 0));

                    // Set this flag so the image can be reduced after performing the local threshold.
                    useExpandedROI = 1;
                }
            }

            // if Expanded Box hasn't been updated, use the boundingBox passed in to extract.
            if (useExpandedROI == 0)
            {
                expandedBox = boundingBox;
            }


            // Extract the region of interest into the mask image.
            Algorithms.Extract(image, imageMask, expandedBox, 1, 1);

            // Create a temporary ROI that will be used to mask the extracted image, to get rid of
            // the pixels outside of the rotated rectangle.
            Roi tmpROI = new Roi(roi);

            // If the ROI is a rotated rectangle, then compute the new location of the search ROI.
            if ((roi[0].Type == ContourType.RotatedRectangle) && (((RotatedRectangleContour)roi[0].Shape).Angle > 0.01))
            {
                CoordinateSystem baseSystem = new CoordinateSystem();
                baseSystem.Origin.X        = (roi.GetBoundingRectangle().Left < 0 ? 0 : roi.GetBoundingRectangle().Left);
                baseSystem.Origin.Y        = (roi.GetBoundingRectangle().Top < 0 ? 0 : roi.GetBoundingRectangle().Top);
                baseSystem.Angle           = 0;
                baseSystem.AxisOrientation = AxisOrientation.Direct;

                CoordinateSystem newSystem = new CoordinateSystem(new PointContour(0, 0), 0, AxisOrientation.Direct);

                CoordinateTransform transform = new CoordinateTransform(baseSystem, newSystem);

                Algorithms.TransformRoi(tmpROI, transform);
            }

            // Create a temporary image.
            using (VisionImage tmpImageMask = new VisionImage(ImageType.U8, 7))
            {
                double thresholdMin;
                double thresholdMax;

                switch (preprocessingOptions.ThresholdType)
                {
                case ThresholdType.Manual:
                    thresholdMin = preprocessingOptions.ManualThresholdRange.Minimum;
                    thresholdMax = preprocessingOptions.ManualThresholdRange.Maximum;
                    Algorithms.Threshold(imageMask, imageMask, new Range(thresholdMin, thresholdMax), true, 1);
                    break;

                case ThresholdType.Auto:
                    Collection <ThresholdData> thresholdData;
                    thresholdData = Algorithms.AutoThreshold(image, tmpImageMask, 2, preprocessingOptions.AutoThresholdOptions.Method);

                    if (preprocessingOptions.AutoThresholdOptions.ParticleType == ParticleType.Bright)
                    {
                        thresholdMin = (thresholdData[0].Range.Maximum > preprocessingOptions.AutoThresholdOptions.Limits.Minimum ?
                                        thresholdData[0].Range.Maximum : preprocessingOptions.AutoThresholdOptions.Limits.Minimum);
                        thresholdMax = 255;
                    }
                    else
                    {
                        thresholdMin = 0;
                        thresholdMax = (thresholdData[0].Range.Maximum < preprocessingOptions.AutoThresholdOptions.Limits.Maximum ?
                                        thresholdData[0].Range.Maximum : preprocessingOptions.AutoThresholdOptions.Limits.Maximum);
                    }
                    Algorithms.Threshold(imageMask, imageMask, new Range(thresholdMin, thresholdMax), true, 1);
                    break;

                case ThresholdType.Local:
                    LocalThresholdOptions Options = new LocalThresholdOptions(preprocessingOptions.LocalThresholdOptions.ParticleType, preprocessingOptions.LocalThresholdOptions.Method, 1.0, preprocessingOptions.LocalThresholdOptions.WindowWidth, preprocessingOptions.LocalThresholdOptions.WindowHeight);
                    Options.DeviationWeight = preprocessingOptions.LocalThresholdOptions.DeviationWeight;
                    Algorithms.LocalThreshold(imageMask, imageMask, Options);
                    break;

                default:
                    break;
                }

                /// If the expanded ROI was used, reduce it so no particles are found outside requested ROI.
                if (useExpandedROI == 1)
                {
                    Algorithms.Extract(imageMask, imageMask, reducedBox, 1, 1);
                }

                // Cast the image to 8 bit.
                imageMask.Type = ImageType.U8;

                // Eliminates particles that touch the border of the image.
                if (preprocessingOptions.RejectBorder)
                {
                    if ((roi[0].Type == ContourType.RotatedRectangle) && (((RotatedRectangleContour)roi[0].Shape).Angle > 0.01))
                    {
                        // Special case for the rotated rectangle.
                        Algorithms.Label(imageMask, imageMask, Connectivity.Connectivity8);

                        Collection <short> lookupTable = new Collection <short>();
                        lookupTable.Add(0);
                        for (int i = 1; i < 256; i++)
                        {
                            lookupTable.Add(1);
                        }

                        RoiProfileReport roiProfile = Algorithms.RoiProfile(imageMask, tmpROI);

                        for (int i = 0; i < roiProfile.Report.ProfileData.Count; i++)
                        {
                            lookupTable[0] = (short)roiProfile.Report.ProfileData[i];
                        }

                        Algorithms.UserLookup(imageMask, imageMask, lookupTable);
                    }
                    else
                    {
                        Algorithms.RejectBorder(imageMask, imageMask, Connectivity.Connectivity8);
                    }
                }

                // Remove small particles.
                if (preprocessingOptions.NumberOfErosions > 0)
                {
                    Algorithms.RemoveParticle(imageMask, imageMask, preprocessingOptions.NumberOfErosions, SizeToKeep.KeepLarge);
                }

                // If the rectangle is rotated, mask out the areas of the image that are not in the ROI.
                if ((roi[0].Type == ContourType.RotatedRectangle) && (((RotatedRectangleContour)roi[0].Shape).Angle > 0.01))
                {
                    // Perform the mask
                    Algorithms.RoiToMask(tmpImageMask, tmpROI, new PixelValue(255));
                    Algorithms.And(imageMask, tmpImageMask, imageMask);
                }

                // Sets the mask offset.
                imageMask.MaskOffset.X = Math.Max(0, roi.GetBoundingRectangle().Left);
                imageMask.MaskOffset.Y = Math.Max(0, roi.GetBoundingRectangle().Top);
            }
            tmpROI.Dispose();
        }
Example #17
0
 public IList <TileInfo> Get(ITileSchema schema, Extent extent, string levelId)
 {
     return(schema.GetTileInfos(extent, levelId).OrderBy(
                t => Algorithms.Distance(extent.CenterX, extent.CenterY, t.Extent.CenterX, t.Extent.CenterY)).ToList());
 }
Example #18
0
        public SplashScreen()
            : base(80, 23)
        {
            IsVisible = false;
            //effectsManager = new EffectsManager(this.TextSurface);
            // Setup the console text background
            string textTemplate = "sole SadCon";

            System.Text.StringBuilder text = new System.Text.StringBuilder(2200);

            for (int i = 0; i < Width * Height; i++)
            {
                text.Append(textTemplate);
            }
            Print(0, 0, text.ToString(), Color.Black, Color.Transparent);

            // Load the logo
            System.IO.Stream imageStream = Microsoft.Xna.Framework.TitleContainer.OpenStream("sad.png");
            var image = Texture2D.FromStream(Global.GraphicsDevice, imageStream);

            imageStream.Dispose();

            // Configure the logo
            _consoleImage         = image.ToSurface(Global.FontDefault, false);
            _consoleImagePosition = new Point(Width / 2 - _consoleImage.Width / 2, -1);
            _consoleImage.Tint    = Color.Black;

            // Configure the animations
            _animation = new InstructionSet();
            _animation.Instructions.AddLast(new Wait()
            {
                Duration = 0.3f
            });

            // Animation to move the angled gradient spotlight effect.
            var moveGradientInstruction = new CodeInstruction();

            moveGradientInstruction.CodeCallback = (inst) =>
            {
                _x += 1;

                if (_x > Width + 50)
                {
                    inst.IsFinished = true;
                }

                Color[] colors     = new Color[] { Color.Black, Color.Blue, Color.White, Color.Blue, Color.Black };
                float[] colorStops = new float[] { 0f, 0.2f, 0.5f, 0.8f, 1f };

                Algorithms.GradientFill(Font.Size, new Point(_x, 12), 10, 45, new Rectangle(0, 0, Width, Height), new ColorGradient(colors, colorStops), SetForeground);
            };
            _animation.Instructions.AddLast(moveGradientInstruction);

            // Animation to clear the SadConsole text.
            _animation.Instructions.AddLast(new CodeInstruction()
            {
                CodeCallback = (i) => { Fill(Color.Black, Color.Transparent, 0, null); i.IsFinished = true; }
            });

            // Animation for the logo text.
            var logoText = new ColorGradient(new Color[] { Color.Magenta, Color.Yellow }, new float[] { 0.0f, 1f }).ToColoredString("[| Powered by SadConsole |]");

            logoText.SetEffect(new SadConsole.Effects.Fade()
            {
                DestinationForeground = Color.Blue, FadeForeground = true, FadeDuration = 1f, Repeat = false, RemoveOnFinished = true, Permanent = true, CloneOnApply = true
            });
            _animation.Instructions.AddLast(new DrawString(this)
            {
                Position = new Point(26, this.Height - 1), Text = logoText, TotalTimeToPrint = 1f
            });

            // Animation for fading in the logo picture.
            _animation.Instructions.AddLast(new FadeTextSurfaceTint(_consoleImage, new ColorGradient(Color.Black, Color.Transparent), new TimeSpan(0, 0, 0, 0, 2000)));

            // Animation to blink SadConsole in the logo text
            _animation.Instructions.AddLast(new CodeInstruction()
            {
                CodeCallback = (i) =>
                {
                    SadConsole.Effects.Fade fadeEffect = new SadConsole.Effects.Fade();
                    fadeEffect.AutoReverse             = true;
                    fadeEffect.DestinationForeground   = new ColorGradient(Color.Blue, Color.Yellow);
                    fadeEffect.FadeForeground          = true;
                    fadeEffect.UseCellForeground       = false;
                    fadeEffect.Repeat           = true;
                    fadeEffect.FadeDuration     = 0.7f;
                    fadeEffect.RemoveOnFinished = true;

                    List <Cell> cells = new List <Cell>();
                    for (int index = 0; index < 10; index++)
                    {
                        var point = new Point(26, this.Height - 1).ToIndex(this.Width) + 14 + index;
                        cells.Add(Cells[point]);
                        cellindexes.Add(point);
                    }

                    SetEffect(cells, fadeEffect);
                    i.IsFinished = true;
                }
            });

            // Animation to delay, keeping the logo and all on there for 2 seconds, then destroy itself.
            _animation.Instructions.AddLast(new Wait()
            {
                Duration = 2.5f
            });
            _animation.Instructions.AddLast(new FadeTextSurfaceTint(_consoleImage, new ColorGradient(Color.Transparent, Color.Black), new TimeSpan(0, 0, 0, 0, 2000)));
            _animation.Instructions.AddLast(new CodeInstruction()
            {
                CodeCallback = (i) =>
                {
                    SplashCompleted?.Invoke();

                    i.IsFinished = true;
                }
            });
        }
Example #19
0
 public AlgorithmContainer GetMostProfitableAlgorithmContainer()
 {
     return(Algorithms.FirstOrDefault(a => a.AlgorithmStringID == MostProfitableAlgorithmStringID));
 }
Example #20
0
 /// <summary>
 /// Algorimo de 50-61 numeros
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void RadioButton_Checked_Big(object sender, RoutedEventArgs e)
 {
     if (Lotto == null)
         return;
     Algorithm = Algorithms.AlgorithmBig;
     AutoEvaluation_Click(sender, e);
     radioalgmagi.IsChecked = false;
 }
Example #21
0
        /// <summary>
        /// Gets the percentage that the actual text is different from the expected text
        /// The comparison is performed on a character level
        /// </summary>
        /// <param name="expectedText">The expected text</param>
        /// <param name="actualText">The actual text</param>
        /// <param name="algorithm">The type of algorithm to use to calculate the edit distance</param>
        /// <returns>The percentage that the actual text is different from the expected text</returns>
        public static decimal ErrorPercentage(string expectedText, string actualText, Algorithms algorithm = Algorithms.Levenshtein)
        {
            decimal difference = MinEditDistance(expectedText, actualText, algorithm);
            decimal length     = expectedText.Length;

            return((difference / length) * 100m);
        }
Example #22
0
 private void RadioButton_Checked_3(object sender, RoutedEventArgs e)
 {
     algs = Algorithms.GreedySearch;
 }
Example #23
0
 public int[] FilterDigit_ValidCases_ArrayOnlyWithDigit(int[] a) =>
 Algorithms.Filter(a, Algorithms.ContainsDigit).ToArray();
Example #24
0
        /// <summary>
        /// Algoritmo de 20 magicos
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RadioButton_Checked_3(object sender, RoutedEventArgs e)
        {
            if (Lotto == null)
                return;
            Algorithm = Algorithms.AlgorithmMagic;
            AutoEvaluation_Click(sender, e);
            radioalg1.IsChecked = false;
            radioalg2.IsChecked = false;

            //#region Tabulaciones algoritmo 50 (si descomento esto tengo que descomentar #region AutoTestAfter)

            //radioalg3.IsChecked = false;

            //#endregion
        }
Example #25
0
 public void FilterDigit_NotValidCases(int[] a) =>
 Assert.Throws <ArgumentNullException>(() => Algorithms.Filter(a, Algorithms.ContainsDigit));
 /// <summary>
 /// Finds the index of the last item in the list that is equal to <paramref name="item"/>.
 /// </summary>
 /// <remarks>The default implementation of equality for type T is used in the search. This is the
 /// equality defined by IComparable&lt;T&gt; or object.Equals.</remarks>
 /// <param name="item">The item to search fror.</param>
 /// <returns>The index of the last item in the list that that is equal to <paramref name="item"/>.  If no item is equal
 /// to <paramref name="item"/>, -1 is returned.</returns>
 public virtual int LastIndexOf(T item)
 {
     return(Algorithms.LastIndexOf(this, item, EqualityComparer <T> .Default));
 }
 public List <TextChoice> GetClosestOptions(int count)
 {
     return(Algorithms.Closest(Choices, WorldStateProvider.State, count));
 }
 /// <summary>
 /// Returns a view onto a sub-range of this list. Items are not copied; the
 /// returned IList&lt;T&gt; is simply a different view onto the same underlying items. Changes to this list
 /// are reflected in the view, and vice versa. Insertions and deletions in the view change the size of the
 /// view, but insertions and deletions in the underlying list do not.
 /// </summary>
 /// <remarks>
 /// <para>This method can be used to apply an algorithm to a portion of a list. For example:</para>
 /// <code>Algorithms.ReverseInPlace(deque.Range(3, 6))</code>
 /// will reverse the 6 items beginning at index 3.</remarks>
 /// <param name="start">The starting index of the view.</param>
 /// <param name="count">The number of items in the view.</param>
 /// <returns>A list that is a view onto the given sub-part of this list. </returns>
 /// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> or <paramref name="count"/> is negative.</exception>
 /// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> + <paramref name="count"/> is greater than the
 /// size of the list.</exception>
 public virtual IList <T> Range(int start, int count)
 {
     return(Algorithms.Range(this, start, count));
 }
Example #29
0
    private static void test01()
    //****************************************************************************80
    //
    //  Purpose:
    //
    //    TEST01 tests RCONT.
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    28 January 2008
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        const int NROW = 5;
        const int NCOL = 5;

        int ifault = 0;

        int[] matrix = new int[NROW * NCOL];
        int[] ncolt  =
        {
            2, 2, 2, 2, 1
        };
        int[] nrowt =
        {
            3, 2, 2, 1, 1
        };
        int[]     nsubt = new int[NCOL];
        int       test;
        const int test_num = 10;

        Console.WriteLine("");
        Console.WriteLine("TEST01");
        Console.WriteLine("  RCONT constructs a random matrix with");
        Console.WriteLine("  given row and column sums.");

        typeMethods.i4vec_print(NROW, nrowt, "  The rowsum vector:");
        typeMethods.i4vec_print(NCOL, ncolt, "  The columnsum vector: ");

        bool key = false;

        Algorithms.RContData data = new();

        for (test = 1; test <= test_num; test++)
        {
            Algorithms.rcont(ref data, NROW, NCOL, nrowt, ncolt, ref nsubt, ref matrix, ref key, ref ifault);

            if (ifault != 0)
            {
                Console.WriteLine("");
                Console.WriteLine("  RCONT returned IFAULT = " + ifault + "");
                return;
            }

            typeMethods.i4mat_print(NROW, NCOL, matrix, "  The rowcolsum matrix:");
        }
    }
Example #30
0
 /// <summary>
 /// Gets the Minimum Edit distance using the algorithm specified.
 /// Comparison is performed on a word level by first tokenizing the string values using the Tokenize extension method
 /// </summary>
 /// <param name="text1">The first of 2 strings to compare to each other</param>
 /// <param name="text2">The second of 2 strings to compare to each other</param>
 /// <param name="algorithm">The type of algorithm to use to calculate the edit distance</param>
 /// <returns>The minimum edit distance of the 2 strings using the specified algorithm</returns>
 public static int PhraseEditDistance(string text1, string text2, Algorithms algorithm = Algorithms.Levenshtein)
 {
     return(PhraseEditDistance(text1.Tokenize(), text2.Tokenize(), algorithm));
 }
Example #31
0
        public void GetFibonacciNumbers_Count0_ReturnsEmptyIEnumerable()
        {
            var result = Algorithms.GetFibonacciNumbers(-1);

            Assert.That(result.Any(), Is.EqualTo(false));
        }
Example #32
0
        /// <summary>
        /// Gets the percentage that the 2 sets of strings are similar to each other
        /// Comparison is performed on a string level allowing you to perform your own tokenization
        /// </summary>
        /// <param name="tokens1">The first of 2 IEnumerable&lt;string&gt; values to compare to each other</param>
        /// <param name="tokens2">The second of 2 IEnumerable&lt;string&gt; values to compare to each other</param>
        /// <param name="algorithm">The type of algorithm to use to calculate the edit distance</param>
        /// <returns>The percentage that the 2 values are similar to each other</returns>
        public static decimal PhraseSimilarityPercentage(IEnumerable <string> tokens1, IEnumerable <string> tokens2, Algorithms algorithm = Algorithms.Levenshtein)
        {
            decimal difference = PhraseEditDistance(tokens1, tokens2, algorithm);
            decimal length     = Math.Max(tokens1.Count(), tokens2.Count());

            return((1m - (difference / length)) * 100m);
        }
Example #33
0
 /// <summary>
 /// Provides a read-only view of this collection. The returned ICollection&lt;T&gt; provides
 /// a view of the collection that prevents modifications to the collection. Use the method to provide
 /// access to the collection without allowing changes. Since the returned object is just a view,
 /// changes to the collection will be reflected in the view.
 /// </summary>
 /// <returns>An ICollection&lt;T&gt; that provides read-only access to the collection.</returns>
 public virtual ICollection <T> AsReadOnly()
 {
     return(Algorithms.ReadOnly(this));
 }
Example #34
0
        /// <summary>
        /// Gets the percentage of difference that the actual tokens are from the expected tokens
        /// Comparison is performed on a string level allowing custom tokenization
        /// </summary>
        /// <param name="expectedTokens">The expected tokens</param>
        /// <param name="actualTokens">The actual tokens</param>
        /// <param name="algorithm">The type of algorithm to use when calculating the edit distance</param>
        /// <returns>The percentage that the actual tokens are different from the expected tokens</returns>
        public static decimal PhraseErrorPercentage(IEnumerable <string> expectedTokens, IEnumerable <string> actualTokens, Algorithms algorithm = Algorithms.Levenshtein)
        {
            decimal difference = PhraseEditDistance(expectedTokens, actualTokens, algorithm);
            decimal length     = expectedTokens.Count();

            return((difference / length) * 100m);
        }
Example #35
0
 /// <summary>
 /// Shows the string representation of the collection. The string representation contains
 /// a list of the items in the collection. Contained collections (except string) are expanded
 /// recursively.
 /// </summary>
 /// <returns>The string representation of the collection.</returns>
 public override string ToString()
 {
     return(Algorithms.ToString(this));
 }
Example #36
0
 /// <summary>
 /// Gets the percentage of sameness that the actual tokens are from the expected tokens
 /// Comparison is performed on a string level allowing custom tokenization
 /// </summary>
 /// <param name="expectedTokens">The expected tokens</param>
 /// <param name="actualTokens">The actual tokens</param>
 /// <param name="algorithm">The type of algorithm to use when calculating the edit distance</param>
 /// <returns>The percentage that the actual tokens are the same as the expected tokens</returns>
 public static decimal PhraseAccuracyPercentage(IEnumerable <string> expectedTokens, IEnumerable <string> actualTokens, Algorithms algorithm = Algorithms.Levenshtein)
 {
     return(100m - PhraseErrorPercentage(expectedTokens, actualTokens, algorithm));
 }
 private SyndicationCompressionSettings()
 {
     _type = Algorithms.Deflate;
     _level = CompressionLevels.Normal;
 }
Example #38
0
    private static void test12()
    //****************************************************************************80
    //
    //  Purpose:
    //
    //    TEST12 tests R8_UNI.
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    08 July 2008
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        int    i;
        double r;

        Console.WriteLine("");
        Console.WriteLine("TEST12");
        Console.WriteLine("  Show how the seeds used by R8_UNI,");
        Console.WriteLine("  which change on each step, can be reset to");
        Console.WriteLine("  restore any part of the sequence.");

        int s1_save = 12345;
        int s2_save = 34567;

        int s1 = s1_save;
        int s2 = s2_save;

        Console.WriteLine("");
        Console.WriteLine("  Begin sequence with following seeds");
        Console.WriteLine("");
        Console.WriteLine("  S1 = " + s1 + "");
        Console.WriteLine("  S2 = " + s2 + "");
        Console.WriteLine("");
        Console.WriteLine("         I      R                     S1            S2");
        Console.WriteLine("");

        for (i = 1; i <= 10; i++)
        {
            r = Algorithms.r8_uni(ref s1, ref s2);
            Console.WriteLine("  " + i.ToString().PadLeft(8)
                              + "  " + r.ToString(CultureInfo.InvariantCulture).PadLeft(14)
                              + "  " + s1.ToString().PadLeft(12)
                              + "  " + s2.ToString().PadLeft(12) + "");

            switch (i)
            {
            case 5:
                s1_save = s1;
                s2_save = s2;
                break;
            }
        }

        s1 = s1_save;
        s2 = s2_save;

        Console.WriteLine("");
        Console.WriteLine("  Restart the sequence, using the seeds");
        Console.WriteLine("  produced after step 5:");
        Console.WriteLine("");
        Console.WriteLine("  S1 = " + s1 + "");
        Console.WriteLine("  S2 = " + s2 + "");
        Console.WriteLine("");
        Console.WriteLine("         I      R                     S1            S2");
        Console.WriteLine("");

        for (i = 1; i <= 10; i++)
        {
            r = Algorithms.r8_uni(ref s1, ref s2);
            Console.WriteLine("  " + i.ToString().PadLeft(8)
                              + "  " + r.ToString(CultureInfo.InvariantCulture).PadLeft(14)
                              + "  " + s1.ToString().PadLeft(12)
                              + "  " + s2.ToString().PadLeft(12) + "");
        }
    }
Example #39
0
        public MainWindow()
        {
            InitializeComponent();

            //Para que los tooltips no se quiten
            ToolTipService.ShowDurationProperty.OverrideMetadata(
                typeof (DependencyObject), new FrameworkPropertyMetadata(Int32.MaxValue));

            DateDesde = Util.DoDateTime(desdeDate.Text, true);
            DateHasta = Util.DoDateTime(hastaDate.Text, false);

            TextCopied = "";
            var start = new Start();
            start.Show();

            Lotto = new LottoData();
            Lotto.Initialize(1);
            Update_DigitsPosition();

            Algorithm = Lotto.DefaultAlgorithm;
            Lotto.LoadFileColumn();

            textBoxWrite1.Text = Lotto.DataColumn1;
            textBoxWrite2.Text = Lotto.DataColumn2;

            //#region Tabulaciones Estadística

            //DataSet ds = new DataSet();

            //var tabla = ConvertListToDataTable(Lotto.FrecuencyNumber);

            //ds.Tables.Add(tabla);
            //DataDatagrid.ItemsSource = ds.Tables[0].DefaultView;

            //var listProm = Lotto.DoPromedio();
            //var listMed = Lotto.DoMediana();
            //var listMod = Lotto.DoModa();
            //tabla.Columns.Add("Promedio");
            //tabla.Columns.Add("Mediana");
            //tabla.Columns.Add("Moda");
            //tabla.Columns.Add("Números");
            //for (int i = 0; i < 100; i++)
            //{
            //    tabla.Rows[i]["Promedio"] = listProm[i];
            //    tabla.Rows[i]["Mediana"] = listMed[i];
            //    tabla.Rows[i]["Moda"] = listMod[i];
            //    tabla.Rows[i]["Números"] = i.ToString();
            //}

            //#endregion

            computerData = new ComputerData();
            var temp = new List<string>();
            foreach (var n in Lotto.L())
            {
                temp.Add(n.Corrido1);
            }
            computerData.L = temp;

            Verify();

            Lotto.Main = this;
            DataContext = Lotto;
            Lotto.DateSelect = new Date(DateTime.Today);
            calendar.SelectedDate = Lotto.LastDay;

            comboBox.SelectedIndex = Lotto.LastDay.Month - 1;

            moveIndex = 0;
            //_timer = new Timer();
            //_timer.Elapsed += new ElapsedEventHandler(ThreadMove);
            //_timer.Interval = 15000;
            //_timer.Enabled = true;
            //_timer.AutoReset = true;
            //_timer.Start();

            //Desactivar la copia desde los textbox
            DataObject.AddCopyingHandler(textBoxWrite1, OnCancelCommand);
            DataObject.AddCopyingHandler(textBoxWrite2, OnCancelCommand);

            //#region Extras

            //ComboBoxsLoaded();
            //Search3();

            //#endregion

            //#region Fantasy5

            //var tempdate = Lotto.LastDayF5.AddDays(1);
            //entryF5.Text = tempdate.Day > 9 ? tempdate.Day.ToString() : ("0" + tempdate.Day.ToString()) + "/";
            //entryF5.Text += tempdate.Month > 9
            //                    ? tempdate.Month.ToString()
            //                    : ("0" + tempdate.Month.ToString()) + "/" + tempdate.Year.ToString() +
            //                      "/";

            //#endregion

            start.Close();

        }
Example #40
0
        public void Set(float min, float max, int numberOfIndividuals, bool onlyIntegers, Algorithms algorithm, MethodInfo methodInfo, float ymin = 0, float ymax = 0)
        {
            newYmin = newXmin = Min = YMin = min;
            newYmax = newXmax = Max = YMax = max;

            if (ymin != 0 && ymax != 0)
            {
                YMin = ymin;
                YMax = ymax;
            }

            MethodInfo = methodInfo;
            NumberOfIndividuals = numberOfIndividuals;
            OnlyIntegers = onlyIntegers;
            Algorithm = algorithm;
        }
Example #41
0
 private void SetAlg()
 {
     algorithm = (Algorithms)Enum.Parse(typeof(Algorithms), AlgorithmsSelect.SelectedItem.ToString());
 }
 /// <summary>
 /// Provides a read-only view of this list. The returned IList&lt;T&gt; provides
 /// a view of the list that prevents modifications to the list. Use the method to provide
 /// access to the list without allowing changes. Since the returned object is just a view,
 /// changes to the list will be reflected in the view.
 /// </summary>
 /// <returns>An IList&lt;T&gt; that provides read-only access to the list.</returns>
 public virtual new IList <T> AsReadOnly()
 {
     return(Algorithms.ReadOnly(this));
 }
Example #43
0
        /// <summary>
        /// Algorimo de prueba
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RadioButton_Checked_Test(object sender, RoutedEventArgs e)
        {
            if (Lotto == null)
                return;
            Algorithm = Algorithms.AlgorithmTest;
            AutoEvaluation_Click(sender, e);

            //#region Tabulaciones algoritmo 50

            //radioalg3.IsChecked = false;

            //#endregion
        }
 /// <summary>
 /// Finds the last item in the list that satisfies the condition
 /// defined by <paramref name="predicate"/>. If no item matches the condition, than
 /// the default value for T (null or all-zero) is returned.
 /// </summary>
 /// <remarks>If the default value for T (null or all-zero) matches the condition defined by <paramref name="predicate"/>,
 /// and the list might contain the default value, then it is impossible to distinguish the different between finding
 /// the default value and not finding any item. To distinguish these cases, use <see cref="TryFindLast"/>.</remarks>
 /// <param name="predicate">A delegate that defined the condition to check for.</param>
 /// <returns>The last item that satisfies the condition <paramref name="predicate"/>. If no item satisfies that
 /// condition, the default value for T is returned.</returns>
 /// <seealso cref="TryFindLast"/>
 public virtual T FindLast(Predicate <T> predicate)
 {
     return(Algorithms.FindLastWhere(this, predicate));
 }
 /// <summary>
 /// Finds the last item in the list that satisfies the condition
 /// defined by <paramref name="predicate"/>.
 /// </summary>
 /// <param name="predicate">A delegate that defines the condition to check for.</param>
 /// <param name="foundItem">If true is returned, this parameter receives the last item in the list
 /// that satifies the condition defined by <paramref name="predicate"/>.</param>
 /// <returns>True if an item that  satisfies the condition <paramref name="predicate"/> was found. False
 /// if no item in the list satisfies that condition.</returns>
 public virtual bool TryFindLast(Predicate <T> predicate, out T foundItem)
 {
     return(Algorithms.TryFindLastWhere(this, predicate, out foundItem));
 }
 private string GetAlgorithmName(Algorithms algorithm)
 {
     switch (algorithm)
     {
         case Algorithms.ColorMap: return "Color Map";
         case Algorithms.IsolineMap: return "Isoline Map";
         case Algorithms.Probes: return "Probes";
         case Algorithms.VectorMarkers: return "Vector Markers";
         case Algorithms.Trajectories: return "Trajectories";
         default: break;
     }
     throw new Exception("Something strange has happened");
 }
 /// <summary>
 /// Finds the index of the last item in the list that satisfies the condition
 /// defined by <paramref name="predicate"/>. If no item matches the condition, -1 is returned.
 /// </summary>
 /// <param name="predicate">A delegate that defined the condition to check for.</param>
 /// <returns>The index of the last item that satisfies the condition <paramref name="predicate"/>. If no item satisfies that
 /// condition, -1 is returned.</returns>
 public virtual int FindLastIndex(Predicate <T> predicate)
 {
     return(Algorithms.FindLastIndexWhere(this, predicate));
 }
Example #48
0
 private void button1_Click(object sender, EventArgs e)
 {
     algorithm = Algorithms.None;
     PrintGraph();
 }
 /// <summary>
 /// Finds the index of the last item, in the range of items extending from the beginning
 /// of the list to <paramref name="index"/>, that satisfies the condition
 /// defined by <paramref name="predicate"/>. If no item matches the condition, -1 is returned.
 /// </summary>
 /// <param name="predicate">A delegate that defined the condition to check for.</param>
 /// <param name="index">The ending index of the range to check.</param>
 /// <returns>The index of the last item in the given range that satisfies the condition <paramref name="predicate"/>. If no item satisfies that
 /// condition, -1 is returned.</returns>
 public virtual int FindLastIndex(int index, Predicate <T> predicate)
 {
     return(Algorithms.FindLastIndexWhere(Range(0, index + 1), predicate));
 }
Example #50
0
 private Settings()
 {
     _preferredAlgorithm = Algorithms.None;
     _excludedPaths = new StringCollection();
     _whitespace = false;
 }
        private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (AlgorithmSelector.SelectedIndex == 0)
            {
                RUpDown.IsEnabled = true;
                GUpDown.IsEnabled = true;
                BUpDown.IsEnabled = true;
                ColorsCountUpDown.IsEnabled = false;

                SelectedAlgorithm = Algorithms.UniformQuantization;
            }
            else
            {
                RUpDown.IsEnabled = false;
                GUpDown.IsEnabled = false;
                BUpDown.IsEnabled = false;
                ColorsCountUpDown.IsEnabled = true;

                SelectedAlgorithm = AlgorithmSelector.SelectedIndex == 1 ? Algorithms.PopularityQuantization : Algorithms.OctreeQuantization;
            }
        }