python类Differ()的实例源码

differ.py 文件源码 项目:chalktalk_docs 作者: loremIpsum1771 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def __init__(self, source, proposal):
        proposal = htmlescape(proposal)

        differ = Differ()
        self.diff = list(differ.compare(source.splitlines(1),
                                        proposal.splitlines(1)))
image_differ.py 文件源码 项目:satori 作者: operatorequals 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def contentDiff( f1, f2 ) :
    if 'text' in enabledModes :
        differ = difflib.Differ()
        f1_lines = f1['content'].decode('base64').splitlines()
        f2_lines = f2['content'].decode('base64').splitlines()
        diff = differ.compare( f1_lines, f2_lines )
        __logger.info( '\n'.join( diff ) )
test_difflib.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_added_tab_hint(self):
        # Check fix for bug #1488943
        diff = list(difflib.Differ().compare(["\tI am a buggy"],["\t\tI am a bug"]))
        self.assertEqual("- \tI am a buggy", diff[0])
        self.assertEqual("?            --\n", diff[1])
        self.assertEqual("+ \t\tI am a bug", diff[2])
        self.assertEqual("? +\n", diff[3])
differ.py 文件源码 项目:sphinxcontrib-websupport 作者: sphinx-doc 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self, source, proposal):
        proposal = htmlescape(proposal)

        differ = Differ()
        self.diff = list(differ.compare(source.splitlines(1),
                                        proposal.splitlines(1)))
netbase.py 文件源码 项目:deep-prior-pp 作者: moberweger 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def load(self, filename):
        """
        Load the parameters for this network from disk.
        :param filename: Load the parameters of this network from a pickle file at the named path. If this name ends in
               ".gz" then the input will automatically be gunzipped; otherwise the input will be treated as a "raw" pickle.
        :return: None
        """
        if filename is None:
            return

        opener = gzip.open if filename.lower().endswith('.gz') else open
        handle = opener(filename, 'rb')
        saved = cPickle.load(handle)
        handle.close()
        if saved['network'] != self.__str__():
            print "Possibly not matching network configuration!"
            differences = list(difflib.Differ().compare(saved['network'].splitlines(), self.__str__().splitlines()))
            print "Differences are:"
            print "\n".join(differences)
        for layer in self.layers:
            if (len(layer.params) + len(layer.params_nontrained)) != len(saved['{}-values'.format(layer.layerNum)]):
                print "Warning: Layer parameters for layer {} do not match. Trying to fit on shape!".format(layer.layerNum)
                n_assigned = 0
                for p in layer.params + layer.params_nontrained:
                    for v in saved['{}-values'.format(layer.layerNum)]:
                        if p.get_value().shape == v.shape:
                            p.set_value(v)
                            n_assigned += 1

                if n_assigned != (len(layer.params) + len(layer.params_nontrained)):
                    raise ImportError("Could not load all necessary variables!")
                else:
                    print "Found fitting parameters!"
            else:
                for p, v in zip(layer.params + layer.params_nontrained, saved['{}-values'.format(layer.layerNum)]):
                    if p.get_value().shape == v.shape:
                        p.set_value(v)
                    else:
                        print "WARNING: Skipping parameter for {}! Shape {} does not fit {}.".format(p.name, p.get_value().shape, v.shape)
        print 'Loaded model parameters from {}'.format(filename)
test_mdvl.py 文件源码 项目:mdvl 作者: axiros 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def c(s, md, testcase, **kw):
        print('\n\n%s\n' % ('=' * 40))
        print('Testcase: %s' % testcase)
        print('\n\n%s\n' % ('=' * 40))
        md = dedent(md)
        print('source (spaces as dots):')
        print(md.replace(' ', '.'))
        mdr, f = mdvl.main(md, no_print=True, **kw)
        print('result:')
        print(mdr)
        if inspect:
            return
        fn = pth + '/tests/results/' + testcase
        if record:
            print ('recording %s' % testcase)
            with open(fn, 'w') as fd:
                fd.write(mdr)
            return
        with open(fn) as fd:
            exp = fd.read()
            if exp == mdr:
                return
            import difflib
            d = difflib.Differ()
            diff = d.compare(exp.splitlines(), mdr.splitlines())
            print ('\n'.join(diff))
            raise Exception('compare failed')
test_difflib.py 文件源码 项目:pefile.pypy 作者: cloudtracer 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_added_tab_hint(self):
        # Check fix for bug #1488943
        diff = list(difflib.Differ().compare(["\tI am a buggy"],["\t\tI am a bug"]))
        self.assertEqual("- \tI am a buggy", diff[0])
        self.assertEqual("?            --\n", diff[1])
        self.assertEqual("+ \t\tI am a bug", diff[2])
        self.assertEqual("? +\n", diff[3])
test_difflib.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_added_tab_hint(self):
        # Check fix for bug #1488943
        diff = list(difflib.Differ().compare(["\tI am a buggy"],["\t\tI am a bug"]))
        self.assertEqual("- \tI am a buggy", diff[0])
        self.assertEqual("?            --\n", diff[1])
        self.assertEqual("+ \t\tI am a bug", diff[2])
        self.assertEqual("? +\n", diff[3])
test_difflib.py 文件源码 项目:ndk-python 作者: gittor 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_added_tab_hint(self):
        # Check fix for bug #1488943
        diff = list(difflib.Differ().compare(["\tI am a buggy"],["\t\tI am a bug"]))
        self.assertEqual("- \tI am a buggy", diff[0])
        self.assertEqual("?            --\n", diff[1])
        self.assertEqual("+ \t\tI am a bug", diff[2])
        self.assertEqual("? +\n", diff[3])
diff.py 文件源码 项目:website 作者: hackerspace-ntnu 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def simple_merge(txt1, txt2):
    """Merges two texts"""
    differ = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
    diff = differ.compare(txt1.splitlines(1), txt2.splitlines(1))

    content = "".join([l[2:] for l in diff])

    return content
subscribe.py 文件源码 项目:yui 作者: item4 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def run(bot, sess):
    subs = sess.query(SiteSub).all()
    for sub in subs:  # type: SiteSub
        async with aiohttp.ClientSession() as session:
            try:
                async with session.get(sub.url) as res:
                    new_body: str = await res.text()
                    if sub.body != new_body:
                        old_body_lines = sub.body.splitlines(keepends=True)
                        new_body_lines = new_body.splitlines(keepends=True)
                        d = Differ()
                        diff = [
                            SPACE_RE.sub(' ', x).rstrip() for x in d.compare(
                                old_body_lines,
                                new_body_lines
                            )
                            if x[0] not in [' ', '?']
                        ]
                        await bot.say(
                            sub.user,
                            '`{}` ?? ??? ?????!\n```\n{}\n```'.format(
                                sub.url,
                                '\n'.join(diff),
                            )
                        )
                        sub.body = new_body
                        with sess.begin():
                            sess.add(sub)
            except aiohttp.client_exceptions.ClientConnectorError:
                await bot.say(
                    sub.user,
                    f'`{sub.url}` ? ??? ? ???!'
                )
merge_pyi.py 文件源码 项目:merge_pyi 作者: google 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_diff(a, b):
    import difflib
    a, b = a.split('\n'), b.split('\n')

    diff = difflib.Differ().compare(a, b)
    return '\n'.join(diff)
test_merge_pyi.py 文件源码 项目:merge_pyi 作者: google 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _get_diff(a, b):
    a, b = a.split('\n'), b.split('\n')

    diff = difflib.Differ().compare(a, b)
    return '\n'.join(diff)
pycore.py 文件源码 项目:blackmamba 作者: zrzka 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _set_diffs(self):
        differ = difflib.Differ()
        self.lines = []
        lineno = 0
        for line in differ.compare(self.old.splitlines(True),
                                   self.new.splitlines(True)):
            if line.startswith(' '):
                lineno += 1
            elif line.startswith('-'):
                lineno += 1
                self.lines.append(lineno)
test_difflib.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_added_tab_hint(self):
        # Check fix for bug #1488943
        diff = list(difflib.Differ().compare(["\tI am a buggy"],["\t\tI am a bug"]))
        self.assertEqual("- \tI am a buggy", diff[0])
        self.assertEqual("?            --\n", diff[1])
        self.assertEqual("+ \t\tI am a bug", diff[2])
        self.assertEqual("? +\n", diff[3])
utils.py 文件源码 项目:audio-visualizer-screenlet 作者: ninlith 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def highlight_changes(s1, s2):
    """Highlight words that are changed."""
    # pylint: disable=invalid-name
    l1 = s1.split(' ')
    l2 = s2.split(' ')
    dif = list(Differ().compare(l1, l2))
    return " ".join(["\033[1m" + i[2:] + "\033[0m" if i[:1] == "+" else i[2:]
                     for i in dif if not i[:1] in "-?"])
pycore.py 文件源码 项目:wuye.vim 作者: zhaoyingnan911 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def _set_diffs(self):
        differ = difflib.Differ()
        self.lines = []
        lineno = 0
        for line in differ.compare(self.old.splitlines(True),
                                   self.new.splitlines(True)):
            if line.startswith(' '):
                lineno += 1
            elif line.startswith('-'):
                lineno += 1
                self.lines.append(lineno)
pycore.py 文件源码 项目:wuye.vim 作者: zhaoyingnan911 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _set_diffs(self):
        differ = difflib.Differ()
        self.lines = []
        lineno = 0
        for line in differ.compare(self.old.splitlines(True),
                                   self.new.splitlines(True)):
            if line.startswith(' '):
                lineno += 1
            elif line.startswith('-'):
                lineno += 1
                self.lines.append(lineno)
utils.py 文件源码 项目:meta-swupd 作者: pohly 项目源码 文件源码 阅读 47 收藏 0 点赞 0 评论 0
def unique_contents(base_manifest_fn, image_manifest_fn):
    """
    Get a list of files unique to the bundle image

    Compare the bundle image manifest to the base image manifest and return
    a list of files unique to the bundle image.

    base_manifest_fn -- the base image manifest
    image_manifest_fn -- the bundle image manifest
    """
    import difflib
    differ = difflib.Differ()

    base_manifest_list = []
    with open(base_manifest_fn) as base:
        base_manifest_list = base.read().splitlines()

    image_manifest_list = []
    with open(image_manifest_fn) as image:
        image_manifest_list = image.read().splitlines()

    delta = list(differ.compare(base_manifest_list, image_manifest_list))

    return delta_contents(delta)


# FIXME: Mariano proposed a similar method to OE-Core for package_manager
doctest.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def output_difference(self, example, got, optionflags):
        """
        Return a string describing the differences between the
        expected output for a given example (`example`) and the actual
        output (`got`).  `optionflags` is the set of option flags used
        to compare `want` and `got`.
        """
        want = example.want
        # If <BLANKLINE>s are being used, then replace blank lines
        # with <BLANKLINE> in the actual output string.
        if not (optionflags & DONT_ACCEPT_BLANKLINE):
            got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)

        # Check if we should use diff.
        if self._do_a_fancy_diff(want, got, optionflags):
            # Split want & got into lines.
            want_lines = want.splitlines(True)  # True == keep line ends
            got_lines = got.splitlines(True)
            # Use difflib to find their differences.
            if optionflags & REPORT_UDIFF:
                diff = difflib.unified_diff(want_lines, got_lines, n=2)
                diff = list(diff)[2:] # strip the diff header
                kind = 'unified diff with -expected +actual'
            elif optionflags & REPORT_CDIFF:
                diff = difflib.context_diff(want_lines, got_lines, n=2)
                diff = list(diff)[2:] # strip the diff header
                kind = 'context diff with expected followed by actual'
            elif optionflags & REPORT_NDIFF:
                engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
                diff = list(engine.compare(want_lines, got_lines))
                kind = 'ndiff with -expected +actual'
            else:
                assert 0, 'Bad diff option'
            # Remove trailing whitespace on diff output.
            diff = [line.rstrip() + '\n' for line in diff]
            return 'Differences (%s):\n' % kind + _indent(''.join(diff))

        # If we're not using diff, then simply list the expected
        # output followed by the actual output.
        if want and got:
            return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
        elif want:
            return 'Expected:\n%sGot nothing\n' % _indent(want)
        elif got:
            return 'Expected nothing\nGot:\n%s' % _indent(got)
        else:
            return 'Expected nothing\nGot nothing\n'


问题


面经


文章

微信
公众号

扫码关注公众号