This function compares two csv files
423407
def compare_csv_decimal_files(file1, file2, header=True, timeseries=False):
    
    # CHECK NUM LINES
    with open_csv(file1) as fh1, \
            open_csv(file2) as fh2:
        assert sum(1 for _ in fh1) == sum(1 for _ in fh2)

    with open_csv(file1) as fh1, \
            open_csv(file2) as fh2:
        csv1 = csv.reader(fh1)
        csv2 = csv.reader(fh2)

        if header:
            assert next(csv1) == next(csv2)  # header

        while True:
            try:
                row1 = next(csv1)
                row2 = next(csv2)
                compare_start_index = 0
                if timeseries:
                    assert row1[0] == row2[0]  # check dates
                    compare_start_index = 1

                assert_almost_equal(
                    np_array(row1[compare_start_index:], dtype=np_float32),
                    np_array(row2[compare_start_index:], dtype=np_float32),
                    decimal=2)
            except StopIteration:
                break
    return True
978806
def compare(ver1, ver2):
    ''''''
    if ver1 == ver2:
        return 0
    ver1 = _cut(ver1)
    ver2 = _cut(ver2)
    # magic multiplier
    m = 1
    # if the first one is shorter, replace them
    if len(ver1) < len(ver2):
        ver1, ver2 = ver2, ver1
        # and reverse magic multiplier
        m = -1
    # compare all items that both have
    for i, part in enumerate(ver2):
        if ver1[i] > ver2[i]:
            return m * 1
        if ver1[i] < ver2[i]:
            return m * -1
    # if the first "extra" item is not negative, it's bigger
    if ver1[len(ver2)] >= 0:
        return m * 1
    else:
        return m * -1
1048167
def sort_csv(in_file):
    
    out_file = "%s.sort" % in_file
    if not (os.path.exists(out_file) and os.path.getsize(out_file) > 0):
        cl = ["sort", "-k", "1,1", in_file]
        with open(out_file, "w") as out_handle:
            child = subprocess.Popen(cl, stdout=out_handle)
            child.wait()
    return out_file
936961
def compareValues(self, a, b):
        
        values = self.values()
        try:
            return cmp(values.index(a), values.index(b))
        except ValueError:
            return cmp(a, b)
1352589
def compare(self, other, base=None):
        
        if self.__class__ != other.__class__:
            return False, ''

        names = self._field_names_

        def cmp_func(name, s, o):
            # special case for string types
            if isinstance(s, six.string_types) and isinstance(o, six.string_types):
                return s == o, name

            if s.__class__ != o.__class__:
                return False, name

            if isinstance(s, BaseObj):
                if not isinstance(s, weakref.ProxyTypes):
                    return s.compare(o, name)
            elif isinstance(s, list):
                for i, v in zip(range(len(s)), s):
                    same, n = cmp_func(jp_compose(str(i), name), v, o[i])
                    if not same:
                        return same, n
            elif isinstance(s, dict):
                # compare if any key diff
                diff = list(set(s.keys()) - set(o.keys()))
                if diff:
                    return False, jp_compose(str(diff[0]), name)
                diff = list(set(o.keys()) - set(s.keys()))
                if diff:
                    return False, jp_compose(str(diff[0]), name)

                for k, v in six.iteritems(s):
                    same, n = cmp_func(jp_compose(k, name), v, o[k])
                    if not same:
                        return same, n
            else:
                return s == o, name

            return True, name

        for n in names:
            same, n = cmp_func(jp_compose(n, base), getattr(self, n), getattr(other, n))
            if not same:
                return same, n

        return True, ''
1248701
function compareBufferArrays(buffArray1, buffArray2) {
  assert(Array.isArray(buffArray1), 'We only accept arrays.');
  assert(Array.isArray(buffArray2), 'We only accept arrays.');
  if (buffArray1.length !== buffArray2.length) {
    return false;
  }
  for (var i = 0; i < buffArray1.length; ++i) {
    var buff1 = buffArray1[i];
    assert(Buffer.isBuffer(buff1), 'Only buffers allowed in 1');
    var buff2 = buffArray2[i];
    assert(Buffer.isBuffer(buff2), 'Only buffers allowed in 2');
    if (Buffer.compare(buff1, buff2) !== 0) {
      return false;
    }
  }
  return true;
}
311855
def is_same_file (filename1, filename2):
    
    if filename1 == filename2:
        return True
    if os.name == 'posix':
        return os.path.samefile(filename1, filename2)
    return is_same_filename(filename1, filename2)
559617
function sortFiles (a, b) {
  if (a.type === b.type) {
    if (a.file === b.file) {
      var ai = a.start || a.mtime || a.index
      var bi = b.start || b.mtime || b.index
      if (sort === 'desc') {
        return parseFloat(bi) - parseFloat(ai)
      } else {
        return parseFloat(ai) - parseFloat(bi)
      }
    } else {
      var ai = a.mtime || a.index
      var bi = b.mtime || b.index
      if (sort === 'desc') {
        return parseFloat(bi) - parseFloat(ai)
      } else {
        return parseFloat(ai) - parseFloat(bi)
      }
    }
  } else {
    var order = [1, 2, 0]
    return order[b.type] - order[a.type]
  }
}
450673
def compare(what, imt, calc_ids, files, samplesites=100, rtol=.1, atol=1E-4):
    
    sids, imtls, poes, arrays = getdata(what, calc_ids, samplesites)
    try:
        levels = imtls[imt]
    except KeyError:
        sys.exit(
            '%s not found. The available IMTs are %s' % (imt, list(imtls)))
    imt2idx = {imt: i for i, imt in enumerate(imtls)}
    head = ['site_id'] if files else ['site_id', 'calc_id']
    if what == 'hcurves':
        array_imt = arrays[:, :, imtls(imt)]
        header = head + ['%.5f' % lvl for lvl in levels]
    else:  # hmaps
        array_imt = arrays[:, :, imt2idx[imt]]
        header = head + [str(poe) for poe in poes]
    rows = collections.defaultdict(list)
    diff_idxs = get_diff_idxs(array_imt, rtol, atol)
    if len(diff_idxs) == 0:
        print('There are no differences within the tolerance of %d%%' %
              (rtol * 100))
        return
    arr = array_imt.transpose(1, 0, 2)  # shape (N, C, L)
    for sid, array in sorted(zip(sids[diff_idxs], arr[diff_idxs])):
        for calc_id, cols in zip(calc_ids, array):
            if files:
                rows[calc_id].append([sid] + list(cols))
            else:
                rows['all'].append([sid, calc_id] + list(cols))
    if files:
        fdict = {calc_id: open('%s.txt' % calc_id, 'w')
                 for calc_id in calc_ids}
        for calc_id, f in fdict.items():
            f.write(views.rst_table(rows[calc_id], header))
            print('Generated %s' % f.name)
    else:
        print(views.rst_table(rows['all'], header))
137013
public int compare(final FeatureFile ff1, final FeatureFile ff2) {
		if (ff1 != null && ff2 != null) {
			return ff1.getName().compareTo(ff2.getName());
		} else {
			return -1;
		}
	}
590291
def compare_dicts(d1, d2):
    
    a = json.dumps(d1, indent=4, sort_keys=True)
    b = json.dumps(d2, indent=4, sort_keys=True)
    # stolen from cpython
    # https://github.com/python/cpython/blob/01fd68752e2d2d0a5f90ae8944ca35df0a5ddeaa/Lib/unittest/case.py#L1091
    diff = ('\n' + '\n'.join(difflib.ndiff(
                   a.splitlines(),
                   b.splitlines())))
    return diff
125053
def compare(node1, node2):
    """"""
    if not os.path.isdir("a"):
        print("error: comparison feature not initialized", file=sys.stderr)
        sys.exit(4)

    print("=" * 80)
    print("WERKZEUG INTERNAL BENCHMARK -- COMPARE MODE".center(80))
    print("-" * 80)

    def _hg_update(repo, node):
        def hg(*x):
            return subprocess.call(
                ["hg"] + list(x), cwd=repo, stdout=null_out, stderr=null_out
            )

        hg("revert", "-a", "--no-backup")
        client = subprocess.Popen(
            ["hg", "status", "--unknown", "-n", "-0"], stdout=subprocess.PIPE, cwd=repo
        )
        unknown = client.communicate()[0]
        if unknown:
            client = subprocess.Popen(
                ["xargs", "-0", "rm", "-f"],
                cwd=repo,
                stdout=null_out,
                stdin=subprocess.PIPE,
            )
            client.communicate(unknown)
        hg("pull", "../..")
        hg("update", node)
        if node == "tip":
            diff = subprocess.Popen(
                ["hg", "diff"], cwd="..", stdout=subprocess.PIPE
            ).communicate()[0]
            if diff:
                client = subprocess.Popen(
                    ["hg", "import", "--no-commit", "-"],
                    cwd=repo,
                    stdout=null_out,
                    stdin=subprocess.PIPE,
                )
                client.communicate(diff)

    _hg_update("a", node1)
    _hg_update("b", node2)
    d1 = run("a", no_header=True)
    d2 = run("b", no_header=True)

    print("DIRECT COMPARISON".center(80))
    print("-" * 80)
    for key in sorted(d1):
        delta = d1[key] - d2[key]
        if abs(1 - d1[key] / d2[key]) < TOLERANCE or abs(delta) < MIN_RESOLUTION:
            delta = "=="
        else:
            delta = "%+.4f (%+d%%)" % (delta, round(d2[key] / d1[key] * 100 - 100))
        print("%36s   %.4f    %.4f    %s" % (format_func(key), d1[key], d2[key], delta))
    print("-" * 80)
591956
def max_diff(dset1,dset2):
    ''''''
    for dset in [dset1,dset2]:
        if not os.path.exists(dset):
            nl.notify('Error: Could not find file: %s' % dset,level=nl.level.error)
            return float('inf')
    try:
        dset1_d = nib.load(dset1)
        dset2_d = nib.load(dset2)
        dset1_data = dset1_d.get_data()
        dset2_data = dset2_d.get_data()
    except IOError:
        nl.notify('Error: Could not read files %s and %s' % (dset1,dset2),level=nl.level.error)
        return float('inf')
    try:
        old_err = np.seterr(divide='ignore',invalid='ignore')
        max_val = 100*np.max(np.ma.masked_invalid(np.double(dset1_data - dset2_data) / ((dset1_data+dset2_data)/2)))
        np.seterr(**old_err)
        return max_val
    except ValueError:
        return float('inf')
1319437
public static float compare(final int numOfBits, final byte[] data1,
            final byte[] data2) {
        if (data1.length != data2.length) {
            return 0;
        }
        final int count = countSameBits(data1, data2);
        return (float) count / (float) numOfBits;
    }
247656
private static boolean confirmNoFileConflicts(Set<UpdatedFile> updatedFiles1, Set<UpdatedFile> updatedFiles2) {

        for (Iterator<UpdatedFile> iter1 = updatedFiles1.iterator(); iter1.hasNext();) {
            UpdatedFile currFile1 = iter1.next();
            for (Iterator<UpdatedFile> iter2 = updatedFiles2.iterator(); iter2.hasNext();) {
                UpdatedFile currFile2 = iter2.next();
                if (currFile1.getId().equals(currFile2.getId())) {
                    return false;
                }
            }
        }
        return true;
    }
165981
def is_csv_file(inputfile):
    
    try:
        stream = open(inputfile)
        row = stream.readline()
    except (IOError, UnicodeDecodeError):  # pragma: no cover
        return False
    finally:
        stream.close()
    content = row.strip().split(',')
    return inputfile.endswith('.csv') and len(content) >= 4
17943
def dicom_diff(file1, file2):
    

    datasets = compressed_dicom.read_file(file1), compressed_dicom.read_file(file2)

    rep = []

    for dataset in datasets:
        lines = (str(dataset.file_meta)+"\n"+str(dataset)).split('\n')
        lines = [line + '\n' for line in lines]  # add the newline to the end
        rep.append(lines)

    diff = difflib.Differ()
    for line in diff.compare(rep[0], rep[1]):
        if (line[0] == '+') or (line[0] == '-'):
            sys.stdout.write(line)