static void Main(string[] args) { string pathfileA = @"C:\xcmpdata\trunk\lineTypeCodeListing.txt"; string pathfileB = @"C:\xcmpdata\branch\lineTypeCodeListing.txt"; FileInfo a = new FileInfo(pathfileA); FileInfo b = new FileInfo(pathfileB); //string s1 = "hello, world - parag,"; //string s2 = "hello, WXld - parag."; StreamReader sra = null; StreamReader srb = null; try { //Open Text files for Reading sra = a.OpenText(); string sa = sra.ReadToEnd(); srb = b.OpenText(); string sb = srb.ReadToEnd(); //Pass the strings to be matched for Diff DiffMatchPatch.diff_match_patch xdiff = new diff_match_patch(); List<DiffMatchPatch.Diff> diffs = xdiff.diff_main(sa, sb, true); //Print the Diff with content string html = xdiff.diff_prettyHtml(diffs); string diffFileURI = @"C:\xcmpdata\results\diff.html"; StreamWriter diffFile = null; try { diffFile = new StreamWriter(diffFileURI); diffFile.Write(html); } catch (Exception e) { Console.Write("Exception occurred: " + e.InnerException); } finally { diffFile.Close(); } } catch (FileNotFoundException fnf) { Console.WriteLine("File Not found at given location:" + fnf.Message); } catch (DirectoryNotFoundException dnf) { Console.WriteLine("Directory Not found at given location:" + dnf.Message); } Console.WriteLine("xcmp completed finding differences in the given files, Results are available at designated location."); Console.ReadKey(); }
public static void BaseSentencesCheck(List<Sentence> target, List<Sentence> sample, List<string> errors) { if (target.Count != sample.Count) { errors.Add("В файлах для сравнения содержится разное количество предложений"); } else { var diffEngine = new diff_match_patch(); for (var i = 0; i < target.Count; ++i) { var targetSentece = target[i].Text.ToLower(); var sampleSentence = sample[i].Text.ToLower(); var diff = diffEngine.diff_main(targetSentece, sampleSentence); if (_isDiffMatters(diff, sampleSentence)) { errors.Add( String.Format( "Расхождение в данных (существенное расхождение в {0}-ом по счету предложении). В целевых данных: '{1}', в эталонных данных '{2}'", i, target[i].Text.ToLower(), sample[i].Text.ToLower())); } } } }
private string DiffToHtml(string s1, string s2) { var dmp = new diff_match_patch(); var diffs = dmp.diff_main(s1 ?? string.Empty, s2 ?? string.Empty); dmp.diff_cleanupSemantic(diffs); return dmp.diff_prettyHtml(diffs); }
public void Diff(string Text1, string Text2) { this.Text1 = Text1; this.Text2 = Text2; var dmp = new diff_match_patch(); var diffs = dmp.diff_main(Text1, Text2); Html = dmp.diff_prettyHtml(diffs); InsertCount = 0; InsertLength = 0; DeleteCount = 0; DeleteLength = 0; foreach (var d in diffs) { if (d.operation == Operation.INSERT) { InsertCount++; InsertLength += d.text.Length; } if (d.operation == Operation.DELETE) { DeleteCount++; DeleteLength += d.text.Length; } } }
public static void Main(string[] args) { string text1 = System.IO.File.ReadAllText("Speedtest1.txt"); string text2 = System.IO.File.ReadAllText("Speedtest2.txt"); diff_match_patch dmp = new diff_match_patch(); dmp.Diff_Timeout = 0; // Execute one reverse diff as a warmup. dmp.diff_main(text2, text1); GC.Collect(); GC.WaitForPendingFinalizers(); DateTime ms_start = DateTime.Now; dmp.diff_main(text1, text2); DateTime ms_end = DateTime.Now; Console.WriteLine("Elapsed time: " + (ms_end - ms_start)); }
static IEnumerable<Span> DiffInline(ILine originalLine, ILine modifiedLine) { var dmp = new diff_match_patch(); var diffs = dmp.diff_main(originalLine.Value, modifiedLine.Value); dmp.diff_cleanupSemantic(diffs); return diffs .Select(x => new Span(x.text, OperationToKind(x.operation))) .ToArray(); }
protected void Page_Load(object sender, EventArgs e) { var text1 = "In the demo they cross out the words that are different and that is what I am trying to achieve."; var text2 = "In the they demo cross out the words that are different and that is what I am trying to achieve."; var dmp = new diff_match_patch(); var diffs = dmp.diff_main(text1, text2); var html = dmp.diff_prettyHtml(diffs); foreach (var d in diffs) { Result.Text += d.operation.ToString() + ";" + d.text.ToString() + "</br>"; } //Result.Text = html; }
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)); }
public void ShowDifferenceBetweenTwoFile() { diff_match_patch DIFF = new diff_match_patch(); List<Chunk> chunklist1; List<Chunk> chunklist2; diffs = DIFF.diff_main(richTextBoxCurrentVersion.Text, richTextBoxLastVersion.Text); DIFF.diff_cleanupEfficiency(diffs); chunklist1 = collectChunks(richTextBoxCurrentVersion); chunklist2 = collectChunks(richTextBoxLastVersion); paintChunks(richTextBoxCurrentVersion, chunklist1); paintChunks(richTextBoxLastVersion, chunklist2); richTextBoxCurrentVersion.SelectionLength = 0; richTextBoxLastVersion.SelectionLength = 0; }
private static void Go() { using (var process = new Process { StartInfo = new ProcessStartInfo { WorkingDirectory = Directory.GetCurrentDirectory(), UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden, FileName = _Runner, Arguments = string.Format("{0} /nologo /output={1} /run={2}", _Assembly, _Output, _Run) } }) { process.Start(); process.WaitForExit(); Console.WriteLine("process.ExitCode: {0}", process.ExitCode); var xml = File.ReadAllText(_Output); var highest = XDocument .Parse(xml) .XPathSelectElements("//test-case") .Where(n => n.Attribute("time") != null) .Select(n => new { Name = n.Attribute("name").Value, Time = (int)(decimal.Parse(n.Attribute("time").Value) * 1000) }) .OrderByDescending(i => i.Time) .Take(10) .Select(i => string.Format("{0} : {1}", i.Time, string.Join(".", i.Name.Split('.').Reverse().Take(2).Reverse().ToArray()))) .ToArray(); Array.ForEach(highest, Console.WriteLine); var times = XDocument .Parse(xml) .XPathSelectElements("//test-case") .Where(n => n.Attribute("time") != null) .Select(n => decimal.Parse(n.Attribute("time").Value)) .Select(n => (int)(n * 1000)) .OrderBy(d => d) .ToArray(); var buckets = new[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; foreach (var t in times) if (t >= 1000) ++buckets[19]; else if (t == 0) ++buckets[0]; else if (t >= 100) { var idx = t / 100; ++buckets[idx + 9]; } else { var idx = t / 10; ++buckets[idx]; } var names = "0-9|10-19|20-29|30-39|40-49|50-59|60-69|70-79|80-89|90-99|100-199|200-299|300-399|400-499|500-599|600-699|700-799|800-899|900-999|1000+".Split('|'); for (var x = 0; x < names.Length; x++) Console.WriteLine("{0,10}: {1}", names[x], Enumerable.Range(0, buckets[x]).Aggregate("", (c, i) => c + "*")); var _CurCount = XDocument .Parse(xml) .XPathSelectElements("//test-case") .Count(); var delta = _CurCount - _PreviousCount; Console.ForegroundColor = delta == 0 ? ConsoleColor.Yellow : delta < 0 ? ConsoleColor.Red : ConsoleColor.Green; Console.WriteLine("Count Delta: {0}", delta); Console.ResetColor(); _PreviousCount = _CurCount; var counts = XDocument .Parse(xml) .XPathSelectElements("//test-case") .Select(n => n.Attribute("result").Value) .GroupBy(s => s, s => s); foreach (var ctype in counts) { Console.ForegroundColor = ctype.Key == "Success" ? ConsoleColor.Green : ConsoleColor.Red; Console.WriteLine("{0}: {1}", ctype.Key, ctype.Count()); Console.ResetColor(); } var messages = XDocument .Parse(xml) .XPathSelectElements("//test-case") .Where(n => n.Attribute("result") != null) .Where(n => n.Attribute("result").Value == "Failure") .Select(n => n.XPathSelectElement("./failure/message").Value) .Where(s => s.Contains("\"actual\":") && s.Contains("\"expected\":")) .Select(s => new { actual = s.Split(new[] {"\"expected\":"}, StringSplitOptions.None)[0], expected = s.Split(new[] {"\"expected\":"}, StringSplitOptions.None)[1] }) .Select(i => new { actual = i.actual.Split(new[] {"\"actual\":"}, StringSplitOptions.None)[1].TrimEnd(','), expected = i.expected.Substring(0, i.expected.LastIndexOf('}')) }) .ToArray(); var differ = new diff_match_patch(); foreach (var msg in messages) { Console.WriteLine("------- ***** -------"); var diffs = differ.diff_main(msg.actual, msg.expected); foreach (var diff in diffs) { switch (diff.operation) { case Operation.EQUAL: break; case Operation.INSERT: Console.ForegroundColor = ConsoleColor.Green; break; case Operation.DELETE: Console.ForegroundColor = ConsoleColor.Red; break; } Console.Write(diff.text); Console.ResetColor(); } Console.WriteLine("------- ***** -------"); } //Console.WriteLine(messages[0].actual); //Console.WriteLine("---"); //Console.WriteLine(messages[0].expected); } }
private void lstBlocks_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (lstBlocks.SelectedItem != null) { var blk1 = ((S7FunctionBlock)fld1.GetBlock(lstBlocks.SelectedItem.ToString())).ToString(false); var blk2 = ((S7FunctionBlock)fld2.GetBlock(lstBlocks.SelectedItem.ToString())).ToString(false); txtResult.TextArea.TextView.LineTransformers.Clear(); var txt = ""; diff_match_patch comparer = new diff_match_patch(); var result = comparer.diff_main(blk1, blk2); 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; } }
public double CalculatePercentChanged() { string page1 = _cache; string page2 = Helpers.WebHelper.DownloadWebPage(_url); if (page2 == "") { Error(); return -1.0; } diff_match_patch difflib = new diff_match_patch(); List<Diff> list = difflib.diff_main(page1, page2); double levenshtein = difflib.diff_levenshtein(list); double length = (page1.Length > page2.Length) ? page1.Length : page2.Length; double percentDifferent = levenshtein / length * 100; return percentDifferent; }
public static string GetDiffHtml(string text1, string text2) { diff_match_patch dmp = new diff_match_patch(); dmp.Diff_Timeout = 0; var diffs = dmp.diff_main(text1, text2); var html = dmp.diff_prettyHtml(diffs); return html; }
private static BlameResult GetBlameOutput(string repositoryPath, string fileName, string blameCommitId, string[] currentLines) { BlameResult blameResult; using (var repo = new Repository(repositoryPath)) { // try to determine if the remote URL is plausibly a github.com or GitHub Enterprise URL Uri webRootUrl = repo.Network.Remotes .OrderBy(x => x.Name == "origin" ? 0 : 1) .ThenBy(x => x.Name) .Select(x => { Match m = Regex.Match(x.Url, @"^(git@(?'host'[^:]+):(?'user'[^/]+)/(?'repo'[^/]+)\.git|(git|https?)://(?'host'[^/]+)/(?'user'[^/]+)/(?'repo'[^/]+)\.git)$", RegexOptions.ExplicitCapture); if (m.Success) { string host = m.Groups["host"].Value; return new Uri(string.Format("http{0}://{1}/{2}/{3}/", host == "github.com" ? "s" : "", host, m.Groups["user"].Value, m.Groups["repo"].Value)); } else { return null; } }).FirstOrDefault(x => x != null); var loadingPerson = new Person("Loading…", "loading"); var commit = new Commit(UncommittedChangesCommitId, loadingPerson, DateTimeOffset.Now, loadingPerson, DateTimeOffset.Now, "", null, null); // create a fake blame result that assigns all the code to the HEAD revision blameResult = new BlameResult(webRootUrl, new[] { new Block(1, currentLines.Length, commit, fileName, 1) }.AsReadOnly(), currentLines.Select((l, n) => new Line(n + 1, l, true)).ToList(), new Dictionary<string, Commit> { { commit.Id, commit } }); } Task.Run(() => { // run "git blame" ExternalProcess git = new ExternalProcess(GetGitPath(), Path.GetDirectoryName(repositoryPath)); List<string> arguments = new List<string> { "blame", "--incremental", "--encoding=utf-8" }; if (blameCommitId != null) arguments.Add(blameCommitId); arguments.AddRange(new[] { "--", fileName }); var results = git.Run(new ProcessRunSettings(arguments.ToArray())); if (results.ExitCode != 0) return; // parse output List<Block> blocks = new List<Block>(); Dictionary<string, Commit> commits = new Dictionary<string, Commit>(); ParseBlameOutput(results.Output, blocks, commits); // allocate a (1-based) array for all lines in the file int lineCount = blocks.Sum(b => b.LineCount); Invariant.Assert(lineCount == currentLines.Length, "Unexpected number of lines in file."); // initialize all lines from current version Line[] lines = currentLines .Select((l, n) => new Line(n + 1, l, false)) .ToArray(); blameResult.SetData(blocks, lines, commits); Dictionary<string, Task<string>> getFileContentTasks = CreateGetFileContentTasks(repositoryPath, blocks, commits, currentLines); // process the blocks for each unique commit foreach (var groupLoopVariable in blocks.OrderBy(b => b.StartLine).GroupBy(b => b.Commit)) { // check if this commit modifies a previous one var group = groupLoopVariable; Commit commit = group.Key; string commitId = commit.Id; string previousCommitId = commit.PreviousCommitId; if (previousCommitId != null) { // diff the old and new file contents when they become available Task<string> getOldFileContentTask = getFileContentTasks[previousCommitId]; Task<string> getNewFileContentTask = getFileContentTasks[commitId]; Task.Factory.ContinueWhenAll(new[] { getOldFileContentTask, getNewFileContentTask }, tasks => { // diff the two versions var oldFileContents = tasks[0].Result; var newFileContents = tasks[1].Result; // diff_match_patch can generate incorrect output if there are more than 65536 lines being diffed var checkLines = GetLineCount(oldFileContents) < 65000 && GetLineCount(newFileContents) < 65000; var diff = new diff_match_patch { Diff_Timeout = 10 }; var diffs = diff.diff_main(oldFileContents, newFileContents, checkLines); diff.diff_cleanupSemantic(diffs); // process all the lines in the diff output, matching them to blocks using (IEnumerator<Line> lineEnumerator = ParseDiffOutput(diffs).GetEnumerator()) { // move to first line (which is expected to always be present) Invariant.Assert(lineEnumerator.MoveNext(), "Expected at least one line from diff output."); Line line = lineEnumerator.Current; // process all the blocks, finding the corresponding lines from the diff for each one foreach (Block block in group) { // skip all lines that occurred before the start of this block while (line.LineNumber < block.OriginalStartLine) { Invariant.Assert(lineEnumerator.MoveNext(), "diff does not contain the expected number of lines."); line = lineEnumerator.Current; } // process all lines in the current block while (line.LineNumber >= block.OriginalStartLine && line.LineNumber < block.OriginalStartLine + block.LineCount) { // assign this line to the correct index in the blamed version of the file blameResult.SetLine(line.LineNumber - block.OriginalStartLine + block.StartLine, line); // move to the next line (if available) if (lineEnumerator.MoveNext()) line = lineEnumerator.Current; else break; } } } }); } else { // this is the initial commit (but has not been modified since); grab its lines from the current version of the file foreach (Block block in group) for (int lineNumber = block.StartLine; lineNumber < block.StartLine + block.LineCount; lineNumber++) blameResult.SetLine(lineNumber, new Line(lineNumber, currentLines[lineNumber - 1], true)); } } }); return blameResult; }
//File Comparison static void FileCompare(FileInfo a, FileInfo b, string diffFileURI) { StreamReader sra = null; StreamReader srb = null; try { //Open Text files for Reading sra = a.OpenText(); string sa = sra.ReadToEnd(); srb = b.OpenText(); string sb = srb.ReadToEnd(); //Pass the strings to be matched for Diff DiffMatchPatch.diff_match_patch xdiff = new diff_match_patch(); List<DiffMatchPatch.Diff> diffs = xdiff.diff_main(sa, sb, true); //Print the Diff with content StringBuilder html = new StringBuilder(); html.Append("<strong>" + a.DirectoryName + "\\" + a.Name + " compared to " + b.DirectoryName + "\\" + b.Name + "</strong>\n"); html.Append(xdiff.diff_prettyHtml(diffs)); StreamWriter diffFile = null; try { diffFile = File.AppendText(diffFileURI); diffFile.Write(html.ToString()); } catch (Exception e) { Console.Write("Exception occurred: " + e.InnerException); } finally { diffFile.Close(); } } catch (FileNotFoundException fnf) { Console.WriteLine("File Not found at given location:" + fnf.Message); } catch (DirectoryNotFoundException dnf) { Console.WriteLine("Directory Not found at given location:" + dnf.Message); } }
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 void MakeContentDiffs(Dictionary<int, DiffLine[]> addDeletePairs) { addDeletePairs.Values .Where(x => x.All(y => y != null)) .ForEach(p => { var deleteLine = p[0]; var addLine = p[1]; var deleteContent = deleteLine.Content; var addContent = addLine.Content; var dmp = new diff_match_patch(); var diffs = dmp.diff_main(deleteContent, addContent); dmp.diff_cleanupSemantic(diffs); var deleteIndex = 0; var addIndex = 0; var deleteContentDiffs = new List<DiffLine.ContentDiff>(); var addContentDiffs = new List<DiffLine.ContentDiff>(); diffs.ForEach(d => { var diffTextLength = d.text.Length; switch (d.operation) { case Operation.DELETE: deleteContentDiffs.Add(new DiffLine.ContentDiff { StartIndex = deleteIndex, EndIndex = deleteIndex + diffTextLength }); deleteIndex += diffTextLength; break; case Operation.INSERT: addContentDiffs.Add(new DiffLine.ContentDiff { StartIndex = addIndex, EndIndex = addIndex + diffTextLength }); addIndex += diffTextLength; break; case Operation.EQUAL: deleteIndex += diffTextLength; addIndex += diffTextLength; break; } }); if (deleteContentDiffs.Any()) deleteLine.ContentDiffs = deleteContentDiffs.ToArray(); if (addContentDiffs.Any()) addLine.ContentDiffs = addContentDiffs.ToArray(); }); }