Compute a patch between the given +expected+ output and the +actual+ output
 and return it as a string.
773350
def make_patch( expected, actual )
      diffs = Diff::LCS.sdiff( expected.split("\n"), actual.split("\n"),
        Diff::LCS::ContextDiffCallbacks )

      maxcol = diffs.flatten.
        collect {|d| [d.old_element.to_s.length, d.new_element.to_s.length ] }.
        flatten.max || 0
      maxcol += 4

      patch = "              %#{maxcol}s | %s\n" % [ "Expected", "Actual" ]
      patch << diffs.collect do |changeset|
        changeset.collect do |change|
          "%s [%03d, %03d]: %#{maxcol}s | %-#{maxcol}s" % [
            change.action,
            change.old_position,
            change.new_position,
            change.old_element.inspect,
            change.new_element.inspect,
          ]
        end.join("\n")
      end.join("\n---\n")
    end
139704
def patched(attrs, updates):
    """"""
    orig = patch(attrs, updates.items())
    try:
        yield orig
    finally:
        patch(attrs, orig.items())
366839
def tee_output_python():
    """"""
    buffer = StringIO()
    out = CapturedStdout(buffer)
    orig_stdout, orig_stderr = sys.stdout, sys.stderr
    flush()
    sys.stdout = TeeingStreamProxy(sys.stdout, buffer)
    sys.stderr = TeeingStreamProxy(sys.stderr, buffer)
    try:
        yield out
    finally:
        flush()
        out.finalize()
        sys.stdout, sys.stderr = orig_stdout, orig_stderr
1078018
def patches(self, dwn, install, comp_sum, uncomp_sum):
        
        dwnp, installp, comp_sump, uncomp_sump = ([] for i in range(4))
        for d, i, c, u in zip(dwn, install, comp_sum, uncomp_sum):
            if "_slack" + slack_ver() in i:
                dwnp.append(d)
                dwn.remove(d)
                installp.append(i)
                install.remove(i)
                comp_sump.append(c)
                comp_sum.remove(c)
                uncomp_sump.append(u)
                uncomp_sum.remove(u)
        if "--patches" in self.flag:
            return dwnp, installp, comp_sump, uncomp_sump
        return dwn, install, comp_sum, uncomp_sum
939859
function generatePatch(image) {

                    var totalPixels = image.pixels.length;
                    var patchData = new Uint8ClampedArray(totalPixels * 4);
                    for (var i = 0; i < totalPixels; i++) {
                        var pos = i * 4;
                        var colorIndex = image.pixels[i];
                        var color = image.colorTable[colorIndex];
                        patchData[pos] = color[0];
                        patchData[pos + 1] = color[1];
                        patchData[pos + 2] = color[2];
                        patchData[pos + 3] = colorIndex !== image.transparentIndex ? 255 : 0;
                    }

                    return patchData;
                }
1321742
function unifiedDiff (actual, expected, formatAdd, formatRem) {
  return [
    formatAdd('+ expected'),
    formatRem('- actual'),
    ''
  ]
    .concat(
      diff.createPatch('string', actual, expected)
        .split('\n')
        .slice(4)
        .filter(function (line) {
          return line[0] === '+' || line[0] === '-'
        })
        .map(function (line) {
          return line[0] === '+' ? formatAdd(line) : formatRem(line)
        })
    )
    .join('\n')
}
715739
def devaluate(actual, expected)
      expected = %r[#{Regexp.escape(expected)}] if expected.kind_of?(String)
      if actual.to_s =~ expected
        fail(expected_message(expected).not_to_match(actual))
      else
        pass(new_message.matches(expected))
      end
    end
1314890
def applied_patches_inverse
      result = {}
      applied_patches.each do |name, sig|
        raise DuplicateError, [result[sig], name] if result.key?(sig)
        result[sig] = name
      end
      result
    end
964940
function monkeypatch(content, next) {
        if (monkeyPatched(content)) return complete();

        _log('monkey patch %s', filePath);
        processor(content, next);
      }
443876
def patched_normalizeargs(sequence, output = None):
    
    if output is None:
        output = []

    if Broken in getattr(sequence, '__bases__', ()):
        return [sequence]

    cls = sequence.__class__
    if InterfaceClass in cls.__mro__ or zope.interface.declarations.Implements in cls.__mro__:
        output.append(sequence)
    else:
        for v in sequence:
            patched_normalizeargs(v, output)

    return output
355180
def stdout_to_results(s):
    """"""
    results = s.strip().split('\n')
    return [BenchmarkResult(*r.split()) for r in results]
156402
def patch_stream(self, instream, hunks):
    

    # todo: At the moment substituted lineends may not be the same
    #       at the start and at the end of patching. Also issue a
    #       warning/throw about mixed lineends (is it really needed?)

    hunks = iter(hunks)

    srclineno = 1

    lineends = {b'\n':0, b'\r\n':0, b'\r':0}
    def get_line():
      """
      local utility function - return line from source stream
      collecting line end statistics on the way
      """
      line = instream.readline()
        # 'U' mode works only with text files
      if line.endswith(b"\r\n"):
        lineends[b"\r\n"] += 1
      elif line.endswith(b"\n"):
        lineends[b"\n"] += 1
      elif line.endswith(b"\r"):
        lineends[b"\r"] += 1
      return line

    for hno, h in enumerate(hunks):
      debug("hunk %d" % (hno+1))
      # skip to line just before hunk starts
      while srclineno < h.startsrc:
        yield get_line()
        srclineno += 1

      for hline in h.text:
        # todo: check \ No newline at the end of file
        if hline.startswith(b"-") or hline.startswith(b"\\"):
          get_line()
          srclineno += 1
          continue
        else:
          if not hline.startswith(b"+"):
            get_line()
            srclineno += 1
          line2write = hline[1:]
          # detect if line ends are consistent in source file
          if sum([bool(lineends[x]) for x in lineends]) == 1:
            newline = [x for x in lineends if lineends[x] != 0][0]
            yield line2write.rstrip(b"\r\n")+newline
          else: # newlines are mixed
            yield line2write

    for line in instream:
      yield line
1243267
function applyPatch (oldStr, uniDiff) {
  var diffstr = uniDiff.split('\n');
  var diff = [];
  var remEOFNL = false,
      addEOFNL = false;

  // i = 4 in order to skip diff headers.
  for (var i = 4; i < diffstr.length; i++) {
    if(diffstr[i][0] === '@') {
      var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
      diff.unshift({
        start:meh[3],
        oldlength:meh[2],
        oldlines:[],
        newlength:meh[4],
        newlines:[]
      });
    } else if(diffstr[i][0] === '+') {
      diff[0].newlines.push(diffstr[i].substr(1));
    } else if(diffstr[i][0] === '-') {
      diff[0].oldlines.push(diffstr[i].substr(1));
    } else if(diffstr[i][0] === ' ') {
      diff[0].newlines.push(diffstr[i].substr(1));
      diff[0].oldlines.push(diffstr[i].substr(1));
    } else if(diffstr[i][0] === '\\') {
      if (diffstr[i-1][0] === '+') {
        remEOFNL = true;
      } else if(diffstr[i-1][0] === '-') {
        addEOFNL = true;
      }
    }
  }

  var str = oldStr.split('\n');
  for (i = diff.length - 1; i >= 0; i--) {
    var d = diff[i];
    for (var j = 0; j < d.oldlength; j++) {
      if(str[d.start-1+j] !== d.oldlines[j]) {
        return false;
      }
    }
    Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
  }

  if (remEOFNL) {
    while (!str[str.length-1]) {
      str.pop();
    }
  } else if (addEOFNL) {
    str.push('');
  }
  return str.join('\n');
}
88328
function compile(patch) {
  var code = "";
  patch.forEach(function(op) {
    var o = "";
    switch (op.op) {
      case "remove":
        o += "delete " + pathToStatement(op.path);
        break;
      case "add":
        o += pathToStatement(op.path) + " = " + JSON.stringify(op.value);
        break;
      case "replace":
        o += pathToStatement(op.path) + " = " + JSON.stringify(op.value);
        break;
      case "move":
        var from = pathToStatement(op.from);
        o += pathToStatement(op.path) + " = " + from + ";\n";
        o += "delete " + from;
        break;
      case "copy":
        o += pathToStatement(op.path) + " = " + from;
        break;
      case "test":
        o +=
          "if (!oo.equal(" +
          pathToStatement(op.path) +
          ", " +
          JSON.stringify(op.value) +
          ") throw new Error()";
        break;
    }
    code += o + ";\n";
  });
  return code;
}
453277
function _monkeypatch(filePath, monkeyPatched, processor, complete) {
  async.waterfall(
    [
      function read(next) {
        fs.readFile(filePath, 'utf8', next);
      },

      // TODO - need to parse gyp file - this is a bit hacker
      function monkeypatch(content, next) {
        if (monkeyPatched(content)) return complete();

        _log('monkey patch %s', filePath);
        processor(content, next);
      },

      function write(content, next) {
        fs.writeFile(filePath, content, 'utf8', function(err) {
          return next(err);
        });
      },
    ],
    complete,
  );
}
533254
private void error(String expected, String actual) {
        if (!recovering) {
            recovering = true;
            final String outputString = (EOF_STRING.equals(actual) || UNTERMINATED_COMMENT_STRING.equals(actual) || COMMENT_NOT_ALLOWED.equals(actual)) ? actual : "'"
                    + actual + "'";
            errors.add(SyntaxError._UnexpectedToken(expected, outputString,
                    lookahead(1).beginLine));
        }
    }
784209
def step_impl(context):
    """"""
    expected_lines = context.text.split('\n')
    assert len(expected_lines) == len(context.output)
    for expected, actual in zip(expected_lines, context.output):
        print('--\n\texpected: {}\n\tactual: {}'.format(expected, actual))
        assert expected == actual