Exemplo n.º 1
0
        /// <summary>
        /// performs a google diff between stdin and the file identified by args[0] and outputs to stdout
        /// </summary>
        /// <param name="args"></param>
        private static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                throw new Exception("modified file path argument is required");
            }

            diff_match_patch googleDiff = new diff_match_patch();

            // read stdin raw, including separators
            string source = ReadStdin();
            string target;

            using (StreamReader streamReader = new StreamReader(args[0], Encoding.UTF8))
            {
                target = streamReader.ReadToEnd();
            }

            // NOTE: do our own diffs so we just do semantic cleanup. We don't want to optimize for efficiency.
            List <Diff> diffs;

            if (args.Length > 1 && args[1] == "--reverse")
            {
                diffs = googleDiff.diff_main(target, source);
            }
            else
            {
                diffs = googleDiff.diff_main(source, target);
            }

            googleDiff.diff_cleanupSemantic(diffs);
            List <Patch> patches = googleDiff.patch_make(diffs);

            Console.Write(googleDiff.patch_toText(patches));
        }
Exemplo n.º 2
0
        private async Task CompareAsync()
        {
            if (File1 == null || File2 == null)
            {
                return;
            }
            IsBusy = true;

            try
            {
                var file1Content = await FileIO.ReadTextAsync(File1, Windows.Storage.Streams.UnicodeEncoding.Utf8);

                var file2Content = await FileIO.ReadTextAsync(File2, Windows.Storage.Streams.UnicodeEncoding.Utf8);

                var diffs1 = _differ.diff_main(file1Content, file2Content);
                File1DiffHtml = diffs1.ToPrettyHtml(_darkThemeResolver.IsDarkMode());

                var diffs2 = _differ.diff_main(file2Content, file1Content);
                File2DiffHtml = diffs2.ToPrettyHtml(_darkThemeResolver.IsDarkMode());
            }
            catch (Exception exc)
            {
                await _dialogService.ShowError("Wrong File types.", "Oops", "Ok", null);
            }

            IsBusy = false;
        }
Exemplo n.º 3
0
        public List <string> Post([FromBody] JobModel jobList)//MAPPING CH PROBLEM
        {
            List <Diff>      diff   = new List <Diff>();
            List <string>    result = new List <string>();
            diff_match_patch dmp    = new diff_match_patch();

            string title    = jobList.JobClass[0].title;
            string newTitle = jobList.JobClass[1].title;

            string oldDescription = jobList.JobClass[0].description;
            string newDescription = jobList.JobClass[1].description;


            diff = dmp.diff_main(title, newTitle);
            dmp.diff_cleanupSemantic(diff);



            for (int j = 0; j < diff.Count; j++)
            {
                result.Add(diff[j].ToString());
            }

            //Compare description
            diff = dmp.diff_main(oldDescription, newDescription);
            dmp.diff_cleanupSemantic(diff);
            for (int j = 0; j < diff.Count; j++)
            {
                result.Add(diff[j].ToString());
            }

            return(result);
        }
Exemplo n.º 4
0
        /// <summary>
        /// View a specific Content Version
        /// </summary>
        /// <returns></returns>
        public ActionResult Version(int? contentId)
        {
            var version = _entities.ContentVersions.FirstOrDefault(v => v.Id == contentId);

            if (version == null)
            {
                return RedirectToRoute("ContentIndex");
            }

            var previousVersion = _entities.ContentVersions
                .Where(v => v.Version < version.Version && v.ContentId == version.ContentId)
                .OrderByDescending(v => v.Version)
                .FirstOrDefault();

            var model = new ContentVersionViewModel
            {
                CurrentVersion = version,
                PreviousVersion = previousVersion
            };

            if (previousVersion != null)
            {
                var dmp = new diff_match_patch();
                var diffsContent = dmp.diff_main(previousVersion.UnparsedContent, version.UnparsedContent);
                var diffsStylesheet = dmp.diff_main(previousVersion.StylesheetCode, version.StylesheetCode);

                model.ContentDiff = dmp.diff_prettyHtml(diffsContent);
                model.StylesheetDiff = dmp.diff_prettyHtml(diffsStylesheet);
            }

            return View("~/Areas/mitarbeit/Views/Content/Version.cshtml", model);
        }
Exemplo n.º 5
0
        public void changes()
        {
            while (true)
            {
                if (openDocument != null)
                {
                    List <Patch> patches;
                    Dictionary <int, List <Patch> > returnedPatches;
                    Object[] temp;

                    while (true)
                    {
                        try
                        {
                            if (hasLock == true)
                            {
                                Thread.Sleep(1000);
                                //Copies the document Textbox
                                // TextRange range = new TextRange(DocumentText.Document.ContentStart, DocumentText.Document.ContentEnd);
                                string myText2 = currentTextboxText;
                                patches = diffMatch.patch_make(diffMatch.diff_main(openDocument.FileContents, myText2));

                                temp = diffMatch.patch_apply(patches, openDocument.FileContents);

                                openDocument.FileContents = temp[0].ToString();

                                network.sendDocChanges(openDocument.FileName, patches, myInfo);
                                openDocument.SaveID = network.getLastPatchID(openDocument.FileName) + 1;
                            }
                            else
                            {
                                Thread.Sleep(1000);
                                returnedPatches = network.getDocChanges(openDocument.FileName, myInfo, openDocument.SaveID);

                                if (returnedPatches.Count > 0)
                                {
                                    foreach (List <Patch> item in returnedPatches.Values)
                                    {
                                        temp = diffMatch.patch_apply(item, openDocument.FileContents);

                                        openDocument.FileContents = temp[0].ToString();
                                        this.Dispatcher.Invoke(new Action(() => { DocumentText.Document.Blocks.Clear(); DocumentText.AppendText(openDocument.FileContents); }));
                                    }
                                    openDocument.SaveID = returnedPatches.Last().Key + 1;
                                }
                            }
                        }
                        catch (Exception)
                        {
                            //MessageBoxResult result = System.Windows.MessageBox.Show("Error: Connection to the server was lost. Would you like to reconnect?", "Error", MessageBoxButton.YesNo);
                            //if (result == MessageBoxResult.No)
                            //{
                            //    this.Close();
                            //    Environment.Exit(1);
                            //}
                        }
                    }
                }
            }
        }
Exemplo n.º 6
0
        private void cmdCompare_Click(object sender, RoutedEventArgs e)
        {
            List <DiffColor> diffColors = new List <DiffColor>();

            diff_match_patch comparer = new diff_match_patch();
            var result = comparer.diff_main(textEditorA.Text, textEditorB.Text);

            txtResult.Document.Text = "";
            foreach (var diff in result)
            {
                if (diff.operation == Operation.INSERT)
                {
                    diffColors.Add(new DiffColor()
                    {
                        Color = Brushes.Green, StartOffset = txtResult.Document.Text.Length, EndOffset = txtResult.Document.Text.Length + diff.text.Length
                    });
                }
                else if (diff.operation == Operation.DELETE)
                {
                    diffColors.Add(new DiffColor()
                    {
                        Color = Brushes.Red, StartOffset = txtResult.Document.Text.Length, EndOffset = txtResult.Document.Text.Length + diff.text.Length
                    });
                }
                txtResult.Document.Text += diff.text;
            }
            //txtResult.TextArea.TextView.LineTransformers.Clear();
            txtResult.TextArea.TextView.LineTransformers.Add(new DiffColorizer(diffColors));
        }
Exemplo n.º 7
0
 private static void Diff()
 {
     //var res = DiffUtiles.DiffText("abcbasdf sdfasdfasd", "abcdcb", true, true, false);
     var d    = new diff_match_patch();
     var res  = d.diff_main("abcabxyz bbb", "abcabxyz a bbb");
     var res2 = d.diff_prettyHtml(res);
 }
Exemplo n.º 8
0
        private static void ComparePDF(string source_file1, string source_file2, string destination_file)
        {
            //convert source files to plain text
            string source_file1_text = PDF2String(source_file1);
            string source_file2_text = PDF2String(source_file2);

            //backup
            if (source_file1_text == "")
            {
                source_file1_text = "This is a dog. Hint: your PDF file source 1 was not converted into text.....";
            }

            if (source_file2_text == "")
            {
                source_file2_text = "This is a cat. Hint: your PDF file source 2 was not converted into text.....";
            }

            //set up compare objects and perform compare
            diff_match_patch dmp  = new diff_match_patch();
            List <Diff>      diff = dmp.diff_main(source_file1_text, source_file2_text);

            //convert compare to HTML and output this file (saving) as HMTL file
            string _HTMLString = dmp.diff_prettyHtml(diff);

            _HTMLString = CleanUpHTMLstring(_HTMLString);



            ////write HTML file to disk
            //WriteHTMLFile(_HTMLString);

            WriteHTMLtoPDF(_HTMLString, destination_file);
        }
        public static List <Diferencia> sacarDiferencias(Informe informe)
        {
            List <Diferencia> diferenciasRelevantes = new List <Diferencia>();
            string            textoInicial          = PreprocemientoDeTexto.LimpiarTextoInicial(informe.CuerpoRealizaEnc);
            string            textoFinal            = PreprocemientoDeTexto.LimpiarTextoInicial(informe.CuerpoValidaEnc);

            Diff[] diferencias        = recolectorDeDiferencias.diff_main(textoInicial, textoFinal, true).ToArray();
            var    listaDeDiferencias = diferencias.ToList();

            recolectorDeDiferencias.diff_cleanupSemantic(listaDeDiferencias);
            diferencias = listaDeDiferencias.ToArray();
            for (int i = 0; i < diferencias.Count() - 1; i++)
            {
                if (EsRelevante(diferencias, i))
                {
                    Diferencia diferenciaRelevante = new Diferencia()
                    {
                        Tecnico          = informe.medicoinforma,
                        MedicoSupervisor = informe.medicorevisa,
                        CadenaInicial    = diferencias[i].text,
                        CadenaFinal      = diferencias[i + 1].text
                    };
                    diferenciasRelevantes.Add(diferenciaRelevante);
                }
            }
            return(diferenciasRelevantes);
        }
Exemplo n.º 10
0
        protected override void ProcessRecord()
        {
            diff_match_patch dmp  = new diff_match_patch();
            List <Diff>      diff = dmp.diff_main(LeftText, RightText);

            dmp.diff_cleanupSemantic(diff);
            var output = new CompareTextDiff();

            output.Diff = diff;
            var psObj = new PSObject(output);

            if (_leftFile != null)
            {
                psObj.Properties.Add(new PSNoteProperty("LeftFile", _leftFile));
            }

            if (_rightFile != null)
            {
                psObj.Properties.Add(new PSNoteProperty("RightFile", _rightFile));
            }

            if (View == CompareTextView.SideBySide)
            {
                psObj.TypeNames.Insert(0, "Microsoft.PowerShell.TextUtility.CompareTextDiff#SideBySide");
            }

            WriteObject(psObj);
        }
Exemplo n.º 11
0
        private static async Task Client_MessageUpdated(DiscordSocketClient client, Cacheable <IMessage, ulong> oldCache,
                                                        SocketMessage newMessage, ISocketMessageChannel channel)
        {
            if (newMessage.Author.IsBot)
            {
                return;
            }

            if (newMessage.Content == null)
            {
                return;
            }

            if (newMessage is IUserMessage userMessage)
            {
                var oldMessage = ToMessage(oldCache);

                var oldContent = oldMessage?.Content ?? string.Empty;
                var newContent = userMessage.Resolve();
                if (oldContent == newContent)
                {
                    return;
                }

                var diffMatchPatch = new diff_match_patch();
                var diffs          = diffMatchPatch.diff_main(oldContent, newContent);
                diffMatchPatch.diff_cleanupSemantic(diffs);

                var md = ToMarkdown(diffs);
                await PostEmbedAsync(client, "edited", new Color(0xF0E68C), userMessage.Author.Id, userMessage.Author,
                                     channel, md, oldMessage?.Attachment, userMessage.Id);
            }
        }
        public string GeneratePrettyHtmlDiff(string source, string target)
        {
            var dmp   = new diff_match_patch();
            var diffs = dmp.diff_main(source, target);

            return(dmp.diff_prettyHtml(diffs));
        }
        public Dictionary <LaboratoryWork, List <Similarity> > FindAndSaveSimilarities(LaboratoryWork laboratoryWork)
        {
            Dictionary <LaboratoryWork, List <Similarity> > laboratorySimilarities = new Dictionary <LaboratoryWork, List <Similarity> >();

            foreach (File sourceFile in laboratoryWork.Files)
            {
                var dmp = new diff_match_patch();
                foreach (LaboratoryWork anotherLaboratory in _context.LaboratoryWork.ToList())
                {
                    List <Similarity> similarities = new List <Similarity>();
                    foreach (File file in anotherLaboratory.Files)
                    {
                        var     diffs       = dmp.diff_main(file.Content, sourceFile.Content);
                        var     countEquals = CountEquals(diffs);
                        decimal similarity  = (countEquals / (decimal)Math.Max(sourceFile.Content.Length, file.Content.Length));
                        if (similarity >= (decimal)0.6)
                        {
                            Similarity s = new Similarity {
                                SimilarityToId = file.Id, Value = similarity, File = sourceFile
                            };
                            sourceFile.Similarities.Add(s);
                            similarities.Add(s);
                        }
                    }
                    if (!laboratorySimilarities.TryAdd(anotherLaboratory, similarities))
                    {
                        similarities.AddRange(laboratorySimilarities[anotherLaboratory]);
                        laboratorySimilarities[anotherLaboratory] = similarities;
                    }
                }
            }

            return(laboratorySimilarities);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Gets a list of the different words found under the "Different" operation.
        /// </summary>
        /// <param name="actual"></param>
        /// <param name="expected"></param>
        /// <returns></returns>
        private List <Diff> GetWrongWordsDifferentArray(string actual, string expected)
        {
            //Getting the original text string
            string originalText = expected;
            //Getting the ocr text string
            string           ocrText = actual;
            diff_match_patch diff_match_patchObject = new diff_match_patch();

            //Waits for comparison to finish without timeouts
            diff_match_patchObject.Diff_Timeout = 0;
            //Compares the original text of the txt file to the one produced by the OCR algorithm
            List <Diff> difference = diff_match_patchObject.diff_main(ocrText, originalText);

            //Deletes all the occurances that are the same so only the differences remain
            for (int i = 0; i < difference.Count; i++)
            {
                Diff diff = difference[i];
                difference[i].text = difference[i].text.Trim();
                if (diff.operation.Equals(Operation.EQUAL) || diff.text.Trim().Equals(""))
                {
                    difference.RemoveAt(i);
                }
            }
            return(difference);
        }
Exemplo n.º 15
0
        private void button1_Click(object sender, EventArgs e)
        {
            // Get inputLeft and inputRight
            string left  = inputLeft.Text;
            string right = inputRight.Text;

            // store differences in the displaytext, and line number
            string diffs = "";

            //            for (int line = 1; line <= left.Length; line++) {

            //            }

            diff_match_patch dmp = new diff_match_patch();

            List <Diff> diff = dmp.diff_main(left, right);

            dmp.diff_cleanupSemantic(diff);


            for (int i = 0; i < diff.Count; i++)
            {
                Console.WriteLine(diff[i]);
                diffs = diffs + diff[i] + Environment.NewLine;
            }



            // display in display box
            resultText.Text = diffs;
            Console.Read();
        }
Exemplo n.º 16
0
    void TestDiffMatchPatch()
    {
        var s1 = @"//.
using Au; using Au.Types; using System; using System.Collections.Generic;
class Script : AScript { [STAThread] static void Main(string[] a) => new Script(a); Script(string[] args) { //;;;
	
	var s=""one"";
";
        var s2 = @"/*/ role exeProgram;		outputPath %AFolders.Workspace%\bin; console true; /*/ //.
using Au; using Au.Types; using System; using System.Collections.Generic;
using My.NS1; //ąčę îôû
using My.NS2;
class Script : AScript { [STAThread] static void Main(string[] a) => new Script(a); Script(string[] args) { //;;;
	var i=2;
";

        var         dmp  = new diff_match_patch();
        List <Diff> diff = dmp.diff_main(s1, s2, true);

        dmp.diff_cleanupSemantic(diff);
        var delta = dmp.diff_toDelta(diff);

        AOutput.Write(delta);
        AOutput.Write("----");
        var d2 = dmp.diff_fromDelta(s1, delta);

        //AOutput.Write(d2);
        AOutput.Write(dmp.diff_text2(d2));
    }
Exemplo n.º 17
0
        private void getDiffInfo(FileHistoryDTO fileHistory, string newContent, string oldContent)
        {
            var dmp  = new diff_match_patch();
            var diff = dmp.diff_main(newContent, oldContent);

            dmp.diff_cleanupSemantic(diff);
            dmp.diff_prettyHtml(diff);

            var htmlContent    = new StringBuilder("");
            var linesIncreased = 0;
            var linesDecreased = 0;

            for (int i = 0; i < diff.Count; i++)
            {
                htmlContent.Append(diff[i]);
                if (diff[i].operation == Operation.DELETE)
                {
                    linesDecreased++;
                }
                if (diff[i].operation == Operation.INSERT)
                {
                    linesIncreased++;
                }
            }
            fileHistory.ContentDiffHtml = htmlContent.ToString();
            fileHistory.LinesDecreased  = linesDecreased;
            fileHistory.LinesIncreased  = linesIncreased;
            fileHistory.SizeDiff        = newContent.Length - oldContent.Length;
        }
Exemplo n.º 18
0
        private List <Patch> ProcessFile(string f)
        {
            string destinationContent = "";
            string sourceContent      = "";

            destinationContent = File.ReadAllText(f);

            //corresponding source path to destination file
            var sourcePath = f.Replace("\\destination\\", "\\source\\");

            if (!File.Exists(sourcePath))
            {
                patchResults.Add(new PatchResult {
                    DestinationFile = MakeRelativePath(f), SourceFile = MakeRelativePath(sourcePath), PatchResultType = PatchResultType.CopyFile
                });
                return(null);
            }

            //content of users original file
            sourceContent = File.ReadAllText(sourcePath);

            var dmp  = new diff_match_patch();
            var diff = dmp.diff_main(sourceContent, destinationContent);

            dmp.diff_cleanupSemantic(diff);

            var patchResult = dmp.patch_make(diff);

            patchResults.Add(new PatchResult {
                DestinationFile = MakeRelativePath(f), SourceFile = MakeRelativePath(sourcePath), PatchList = patchResult, PatchResultType = patchResult.Count > 0 ? PatchResultType.Patch : PatchResultType.Identical
            });

            return(patchResult);
        }
Exemplo n.º 19
0
        private void GetSummary()
        {
            _sheetDifferences.Clear();
            for (int i = 0; i < leftWorkbook.sheetNames.Count; i++)
            {
                string sheetName = leftWorkbook.sheetNames[i];
                if (rightWorkbook.sheetNames.Contains(sheetName))
                {
                    ExcelSheet leftExcelSheet  = leftWorkbook.LoadSheet(sheetName);
                    ExcelSheet rightExcelSheet = rightWorkbook.LoadSheet(sheetName);
                    int        columnCount     = Math.Max(leftExcelSheet.columnCount, rightExcelSheet.columnCount);
                    VSheet     leftSheet       = new VSheet(leftExcelSheet, columnCount);
                    VSheet     rightSheet      = new VSheet(rightExcelSheet, columnCount);

                    diff_match_patch comparer     = new diff_match_patch();
                    string           leftContent  = leftSheet.GetContent();
                    string           rightContent = rightSheet.GetContent();
                    List <Diff>      diffs        = comparer.diff_main(leftContent, rightContent, true);
                    comparer.diff_cleanupSemanticLossless(diffs);

                    bool isDifferent = false;
                    for (int diffIndex = 0; diffIndex < diffs.Count; diffIndex++)
                    {
                        if (diffs[diffIndex].operation != Operation.EQUAL)
                        {
                            isDifferent = true;
                            break;
                        }
                    }

                    _sheetDifferences.Add(sheetName, isDifferent);
                }
            }
        }
Exemplo n.º 20
0
        private void cmdCompare_Click(object sender, RoutedEventArgs e)
        {
            txtResult.TextArea.TextView.LineTransformers.Clear();

            var txt = "";
            diff_match_patch comparer = new diff_match_patch();
            var result = comparer.diff_main(textEditorA.Text, textEditorB.Text);

            txtResult.Document.Text = "";
            foreach (var diff in result)
            {
                if (diff.operation == Operation.INSERT)
                {
                    var st = txt.Length;
                    txt += diff.text;
                    var stp = txt.Length;

                    txtResult.TextArea.TextView.LineTransformers.Add(new TextColorizer(st, stp, Brushes.Green));
                }
                else if (diff.operation == Operation.DELETE)
                {
                    var st = txt.Length;
                    txt += diff.text;
                    var stp = txt.Length;

                    txtResult.TextArea.TextView.LineTransformers.Add(new TextColorizer(st, stp, Brushes.Red));
                }
                else
                {
                    txt += diff.text;
                }
            }
            txtResult.Document.Text = txt;
        }
        private static List <Diff> GetMinimalDifferences(List <string> list1, List <string> list2)
        {
            diff_match_patch match = new diff_match_patch
            {
                Diff_Timeout = ContentComparerHelper.Diff_Timeout
            };
            //match.Patch_Margin

            int         minDiff  = int.MaxValue;
            List <Diff> selected = null;

            foreach (string str1 in list1)
            {
                foreach (string str2 in list2)
                {
                    List <Diff> diff = match.diff_main(str1, str2, false);

                    IEnumerable <Diff> changes = diff.Where(d => d.operation != Operation.EQUAL);

                    int changesLength = changes.Any() ? changes.Sum(d => d.text.Length) : 0;

                    if (changesLength < minDiff)
                    {
                        minDiff  = changesLength;
                        selected = diff;
                    }
                }
            }

            return(selected);
        }
        protected override void Convert(PropertyInfo property, object newValue, object oldValue)
        {
            if (oldValue == null)
            {
                OldValue = "";
            }
            else
            {
                OldValue = AsString(property, oldValue);
            }

            if (newValue == null)
            {
                NewValue = "";
            }
            else
            {
                NewValue = AsString(property, newValue);
            }

            var diff   = new diff_match_patch();
            var diffs  = diff.diff_main(OldValue, NewValue);
            var asHtml = diffs.Select(ToHtml).ToArray();

            Message = $"$$$Изменено '{Name}'<br><div>{String.Join("", asHtml)}</div>";
        }
Exemplo n.º 23
0
        /// <summary>
        /// Compares two files to see its difference
        /// </summary>
        /// <param name="dmp">The diff match path utility</param>
        /// <param name="projectFilePath">The project copy file path</param>
        /// <param name="serverFilePath">The server copy file path</param>
        /// <returns>The file differences</returns>
        public static List <Diff> CompareFiles(this diff_match_patch dmp, String projectFilePath, String serverFilePath)
        {
            String projectFile = String.Join("\r\n", File.ReadAllLines(projectFilePath)),
                   serverFile  = String.Join("\r\n", File.ReadAllLines(serverFilePath));

            return(dmp.diff_main(serverFile, projectFile));
        }
Exemplo n.º 24
0
        public void StringDiffMatchPatch_Examples()
        {
            var originalText = "Hi, im a very long text";
            var editedText_1 = "Hi, i'm a very long text!";
            var editedText_2 = "Hi, im not such a long text";
            var expectedText = "Hi, i'm not such a long text!";

            var merge = MergeText.Merge(originalText, editedText_1, editedText_2);

            Assert.Equal(expectedText, merge.mergeResult);
            foreach (var patch in merge.patches)
            {
                Assert.True(patch.Value);
            }                                                                  // All patches were successful

            // diff_match_patch can also provide a detailed difference analysis:
            diff_match_patch dmp  = new diff_match_patch();
            List <Diff>      diff = dmp.diff_main(originalText, editedText_1);

            // The first section until the ' was unchanged:
            Assert.Equal("Hi, i", diff.First().text);
            Assert.Equal(Operation.EQUAL, diff.First().operation);
            // The last change was the insert of a !:
            Assert.Equal("!", diff.Last().text);
            Assert.Equal(Operation.INSERT, diff.Last().operation);
        }
Exemplo n.º 25
0
        public DiffView(string LocalOld, string LocalNew)
        {
            InitializeComponent();

            HandleTheme(newContent);
            HandleTheme(oldContent);

            this.Text = "Diff " + Path.GetFileNameWithoutExtension(LocalNew) + " -> " + Path.GetFileNameWithoutExtension(LocalOld);

            var dmp   = new diff_match_patch();
            var diffs = dmp.diff_main(File.ReadAllText(LocalNew), File.ReadAllText(LocalOld), false);

            foreach (Diff aDiff in diffs)
            {
                switch (aDiff.operation)
                {
                case Operation.INSERT:
                    AppendText(newContent, aDiff.text, Color.Green);
                    break;

                case Operation.DELETE:
                    AppendText(oldContent, aDiff.text, Color.Red);
                    break;

                case Operation.EQUAL:
                    AppendText(oldContent, aDiff.text, textColor);
                    AppendText(newContent, aDiff.text, textColor);
                    break;
                }
            }

            oldContent.SelectionStart = 0;
            newContent.SelectionStart = 0;
        }
Exemplo n.º 26
0
        public static void Main()
        {
            var dmp = new diff_match_patch();

            while (true)
            {
                Console.Clear();
                Console.WriteLine("Enter 2 texts seperated by enter");
                var input1 = Console.ReadLine().Trim().Replace(" ", "");

                var input2 = Console.ReadLine().Trim().Replace(" ", "");
                var diff   = dmp.diff_main(input1, input2);
                var result = dmp.diff_levenshtein(diff);

                Console.WriteLine("Result = " + result);
                double similarity = 100 - ((double)result / Math.Max(input1.Length, input2.Length) * 100);
                Console.WriteLine("Similarity = " + similarity);

                Console.WriteLine("Insert 'q' and then press enter to exit");
                var input3 = Console.ReadLine().Trim().Replace(" ", "");

                if (input3 == "q")
                {
                    break;
                }
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Compares two files to see if are equal
        /// </summary>
        /// <param name="dmp">The diff match path utility</param>
        /// <param name="projectFilePath">The project copy file path</param>
        /// <param name="serverFilePath">The server copy file path</param>
        /// <returns>True if the files are equals</returns>
        public static Boolean AreFilesEquals(this diff_match_patch dmp, String projectFilePath, String serverFilePath)
        {
            String projectFile = String.Join("\r\n", File.ReadAllLines(projectFilePath)),
                   serverFile  = String.Join("\r\n", File.ReadAllLines(serverFilePath));
            Boolean areEqual   = dmp.diff_main(serverFile, projectFile).Count(x => x.operation != Operation.EQUAL) == 0;

            return(areEqual);
        }
Exemplo n.º 28
0
        public void EvalDiffHtml(RCRunner runner, RCClosure closure, RCString left, RCString right)
        {
            diff_match_patch dmp    = new diff_match_patch();
            List <Diff>      diffs  = dmp.diff_main(left[0], right[0]);
            string           result = dmp.diff_prettyHtml(diffs);

            runner.Yield(closure, new RCString(result));
        }
Exemplo n.º 29
0
        public DiffResultScreen(string text1, string text2)
        {
            InitializeComponent();
            diffOperator = new diff_match_patch();
            List <Diff> diffs = diffOperator.diff_main(text1, text2);

            VisualizeDiff(diffs);
        }
        public IEnumerable <Diff> GetDiffBetween(string text1, string text2)
        {
            var         dmp  = new diff_match_patch();
            List <Diff> diff = dmp.diff_main(text1, text2);

            dmp.diff_cleanupSemantic(diff);
            return(diff);
        }
Exemplo n.º 31
0
        public void cargarDiff(byte[] a, byte[] b)
        {
            string TextoA = System.Text.Encoding.Default.GetString(a);
            string TextoB = System.Text.Encoding.Default.GetString(b);

            diff_match_patch dmp = new diff_match_patch();

            wbDiffViewer.DocumentText = dmp.diff_prettyHtml(dmp.diff_main(TextoA, TextoB));
        }
Exemplo n.º 32
0
        private static void updateContent(VisualDiffTextBlock textBlock)
        {
            textBlock.Inlines.Clear();

            if (textBlock.IsVisualDiffVisible)
            {
                var brushConverter = new BrushConverter();
                diff_match_patch dmp = new diff_match_patch();
                List<Diff> diffList = dmp.diff_main(
                    textBlock.PreviousText.Replace("\n", "\u00b6").Replace("\r", "").Replace(' ', '\u00B7'),
                    textBlock.CurrentText.Replace("\n", "\u00b6").Replace("\r", "").Replace(' ', '\u00B7'),
                    false);

                // Apply a clean up, the default value of this function is 4 chars.
                // To change the value, you'll need to do so inside the DiffMatchPatch.cs file.
                dmp.diff_cleanupEfficiency(diffList);

                foreach(Diff diffItem in diffList)
                {
                    switch(diffItem.operation)
                    {
                        case Operation.DELETE:
                            textBlock.Inlines.Add(new Run(diffItem.text) { Background = (Brush)brushConverter.ConvertFromString("#ff6a1010"), Foreground = (Brush)brushConverter.ConvertFromString("#ffdddddd"), TextDecorations = System.Windows.TextDecorations.Strikethrough });
                            break;
                        case Operation.EQUAL:
                            textBlock.Inlines.Add(new Run(diffItem.text.Replace("\u00b6", "\u00b6" + System.Environment.NewLine)));
                            break;
                        case Operation.INSERT:
                            textBlock.Inlines.Add(new Run(diffItem.text.Replace("\u00b6", "\u00b6" + System.Environment.NewLine)) { Background = (Brush)brushConverter.ConvertFromString("#ff005e41"), Foreground = (Brush)brushConverter.ConvertFromString("#ffdddddd") });
                            break;
                    }
                }
            }
            else
            {
                textBlock.Text = textBlock.CurrentText;
            }
        }
Exemplo n.º 33
0
        // GET: Topics/ViewHistory/5
        /// <summary>
        /// Zeigt die Änderungen, die an dem Thema vorgenommen wurden.
        /// </summary>
        /// <param name="id">Die TopicID</param>
        public ActionResult ViewHistory(int id)
        {
            Topic topic = db.Topics.Find(id);
            var history = db.TopicHistory.Where(th => th.TopicID == topic.ID).OrderBy(th => th.ValidFrom).ToList();

            if (history.Count == 0)
                return RedirectToAction("Details", new {id});

            history.Add(TopicHistory.FromTopic(topic, 0));

            var vm = new TopicHistoryViewModel
            {
                Usernames = db.Users.Where(u => u.IsActive).ToDictionary(u => u.ID, u => u.ShortName),
                SessionTypes = db.SessionTypes.ToDictionary(s => s.ID, s => s.Name),
                Current = topic,
                Initial = history[0]
            };

            var diff = new diff_match_patch
            {
                Diff_Timeout = 0.4f
            };

            // Anonyme Funktion, um die Biliothek diff_match_patch handlich zu verpacken.
            Func<string, string, List<Diff>> textDiff = (a, b) =>
            {
                var list = diff.diff_main(a, b);
                diff.diff_cleanupSemantic(list);
                return list;
            };

            foreach (var p in history.Pairwise())
            {
                vm.Differences.Add(new TopicHistoryDiff
                {
                    // Ein Eintrag entspricht später einer Box auf der Seite. Wenn keine Änderung existiert, sollte hier null gespeichert werden. Bei einer Änderung wird der NEUE Wert (der in Item2 enthalten ist) genommen.
                    // SimpleDiff ist eine kleine Helferfunktion, da die Zeilen sonst arg lang werden würden. Hier wird kein Text vergleichen - entweder hat sich alles geändert, oder gar nichts. (Daher "simple")
                    // textDiff ist komplexer, hier wird der Text analysiert und auf ähnliche Abschnitte hin untersucht.
                    Modified = p.Item1.ValidUntil,
                    Editor = vm.Usernames[p.Item1.EditorID],
                    SessionType = SimpleDiff(p.Item1.SessionTypeID, p.Item2.SessionTypeID, vm.SessionTypes),
                    TargetSessionType = SimpleDiff(p.Item1.TargetSessionTypeID, p.Item2.TargetSessionTypeID, vm.SessionTypes, "(kein)"),
                    Owner = SimpleDiff(p.Item1.OwnerID, p.Item2.OwnerID, vm.Usernames),
                    Priority = p.Item1.Priority == p.Item2.Priority ? null : p.Item2.Priority.DisplayName(),
                    Title = textDiff(p.Item1.Title, p.Item2.Title),
                    Time = p.Item1.Time == p.Item2.Time ? null : p.Item2.Time,
                    Description = textDiff(p.Item1.Description, p.Item2.Description),
                    Proposal = textDiff(p.Item1.Proposal, p.Item2.Proposal)
                });
            }

            return View(vm);
        }