recursive diff (splits around longest substring and runs diff on head and tail remnants).\
  global_a_slice is used for recursion and should be left undefined in outer call.\
  returns a list of Delta tuples.
343364
def rediff(a,b,global_a_slice=None):
  ""
  if not (a or b): return []
  global_a_slice=global_a_slice or (0,len(a))
  csresult=contigsub(a,b)
  if not csresult: return (Delta(global_a_slice[0],global_a_slice[1],b),) # i.e. total replacement
  slicea,sliceb=csresult
  if slicea[0]==0 and sliceb[0]==0 and slicea[1]==len(a) and sliceb[1]==len(b): return [] # i.e. nochange
  head=rediff(a[:slicea[0]],b[:sliceb[0]],subslice(slicea,global_a_slice,'head'))
  tail=rediff(a[slicea[1]:],b[sliceb[1]:],subslice(slicea,global_a_slice,'tail'))
  return list(head)+list(tail)
1143571
function getDiffNodes(expected, actual) {
		//compute diff
		var diff = new diff_match_patch(),
			diffs = diff.diff_main(expected, actual),
			html = [],
			i,
			pre,
			nodes,
			actualNodes,
			x,
			op,
			data,
			text;
		
		diff.diff_cleanupSemantic(diffs);
		
		for (x = 0; x < diffs.length; x++) {
			op = diffs[x][0];    // Operation (insert, delete, equal)
			data = diffs[x][1];  // Text of change.
			text = data.replace(/&/g, "&amp;")
				.replace(/</g, "&lt;")
				.replace(/>/g, "&gt;")
				.replace(/\r\n/g, "&crarr;&para;<br />")
				.replace(/\r/g, "&crarr;<br />")
				.replace(/\n/g, "&para;<br />");
			
			switch (op) {
				case 1:
					html[x] = "<ins>" + text + "</ins>";
					break;
				case -1:
					html[x] = "<del>" + text + "</del>";
					break;
				case 0:
					html[x] = "<span>" + text + "</span>";
					break;
			}
			
			if (op !== -1) {
				i += data.length;
			}
		}
		
		html = html.join('');
		
		pre = doc.createElement("pre");
		pre.innerHTML = html;
		
		nodes = pre.cloneNode(true).children;
		actualNodes = [];
		for (i = 0; i < nodes.length; i++) {
			actualNodes[i] = nodes[i];
		}
		pre = null;
		return actualNodes;
	}
1064745
def diff_trees(left, right, diff_options=None, formatter=None):
    """"""
    if formatter is not None:
        formatter.prepare(left, right)
    if diff_options is None:
        diff_options = {}
    differ = diff.Differ(**diff_options)
    diffs = differ.diff(left, right)

    if formatter is None:
        return list(diffs)

    return formatter.format(diffs, left)
206935
def diff_cleanupSemanticLossless(self, diffs):
    

    def diff_cleanupSemanticScore(one, two):
      """Given two strings, compute a score representing whether the
      internal boundary falls on logical boundaries.
      Scores range from 6 (best) to 0 (worst).
      Closure, but does not reference any external variables.

      Args:
        one: First string.
        two: Second string.

      Returns:
        The score.
      """
      if not one or not two:
        # Edges are the best.
        return 6

      # Each port of this function behaves slightly differently due to
      # subtle differences in each language's definition of things like
      # 'whitespace'.  Since this function's purpose is largely cosmetic,
      # the choice has been made to use each language's native features
      # rather than force total conformity.
      char1 = one[-1]
      char2 = two[0]
      nonAlphaNumeric1 = not char1.isalnum()
      nonAlphaNumeric2 = not char2.isalnum()
      whitespace1 = nonAlphaNumeric1 and char1.isspace()
      whitespace2 = nonAlphaNumeric2 and char2.isspace()
      lineBreak1 = whitespace1 and (char1 == "\r" or char1 == "\n")
      lineBreak2 = whitespace2 and (char2 == "\r" or char2 == "\n")
      blankLine1 = lineBreak1 and self.BLANKLINEEND.search(one)
      blankLine2 = lineBreak2 and self.BLANKLINESTART.match(two)

      if blankLine1 or blankLine2:
        # Five points for blank lines.
        return 5
      elif lineBreak1 or lineBreak2:
        # Four points for line breaks.
        return 4
      elif nonAlphaNumeric1 and not whitespace1 and whitespace2:
        # Three points for end of sentences.
        return 3
      elif whitespace1 or whitespace2:
        # Two points for whitespace.
        return 2
      elif nonAlphaNumeric1 or nonAlphaNumeric2:
        # One point for non-alphanumeric.
        return 1
      return 0

    pointer = 1
    # Intentionally ignore the first and last element (don't need checking).
    while pointer < len(diffs) - 1:
      if (diffs[pointer - 1][0] == self.DIFF_EQUAL and
          diffs[pointer + 1][0] == self.DIFF_EQUAL):
        # This is a single edit surrounded by equalities.
        equality1 = diffs[pointer - 1][1]
        edit = diffs[pointer][1]
        equality2 = diffs[pointer + 1][1]

        # First, shift the edit as far left as possible.
        commonOffset = self.diff_commonSuffix(equality1, edit)
        if commonOffset:
          commonString = edit[-commonOffset:]
          equality1 = equality1[:-commonOffset]
          edit = commonString + edit[:-commonOffset]
          equality2 = commonString + equality2

        # Second, step character by character right, looking for the best fit.
        bestEquality1 = equality1
        bestEdit = edit
        bestEquality2 = equality2
        bestScore = (diff_cleanupSemanticScore(equality1, edit) +
            diff_cleanupSemanticScore(edit, equality2))
        while edit and equality2 and edit[0] == equality2[0]:
          equality1 += edit[0]
          edit = edit[1:] + equality2[0]
          equality2 = equality2[1:]
          score = (diff_cleanupSemanticScore(equality1, edit) +
              diff_cleanupSemanticScore(edit, equality2))
          # The >= encourages trailing rather than leading whitespace on edits.
          if score >= bestScore:
            bestScore = score
            bestEquality1 = equality1
            bestEdit = edit
            bestEquality2 = equality2

        if diffs[pointer - 1][1] != bestEquality1:
          # We have an improvement, save it back to the diff.
          if bestEquality1:
            diffs[pointer - 1] = (diffs[pointer - 1][0], bestEquality1)
          else:
            del diffs[pointer - 1]
            pointer -= 1
          diffs[pointer] = (diffs[pointer][0], bestEdit)
          if bestEquality2:
            diffs[pointer + 1] = (diffs[pointer + 1][0], bestEquality2)
          else:
            del diffs[pointer + 1]
            pointer -= 1
      pointer += 1
701201
function slice(v, start, end, step) {
  var r = [];
  var i = void 0;
  if (step > 0) {
    for (i = start; i < end; i += step) {
      r.push(v[i]);
    }
  } else {
    for (i = start; i > end; i += step) {
      r.push(v[i]);
    }
  }
  return r;
}
564365
function convertDiffToMessages(diff, actualOnly = false, includeTimeouts = false, timeout = undefined, comparisonLines = [], paths = []) {
    if (diff.tree && Object.keys(diff.tree).length > 0) {
        const keys = Object.keys(diff.tree);
        keys.forEach(key => {
            const _paths = [...paths];
            _paths.push(key);
            convertDiffToMessages(diff.tree[key], actualOnly, includeTimeouts, timeout, comparisonLines, _paths);
        });
    }
    else {
        let _paths = paths.join('');
        if (_paths.charAt(0) === '.') {
            _paths = _paths.substring(1);
        }
        const _actual = printValue(diff.actual);
        const _expected = printValue(diff.expected);
        let compareStr = '';
        if (actualOnly) {
            compareStr = (typeof diff.actual === 'undefined') ?
                '' : `{actual: <${_actual}>}\n`;
        }
        else {
            compareStr = (typeof diff.actual === 'undefined' && typeof diff.expected === 'undefined') ?
                '' : `{actual: <${_actual}>, expected: <${_expected}>}\n`;
        }
        const timeoutStr = (includeTimeouts) ? ` within ${timeout || diff.timeout}ms` : '';
        comparisonLines.push(`${diff.constructorName} at path '${_paths}'${timeoutStr}\n${compareStr}( ${diff.selector} )`);
    }
    return comparisonLines;
}
231717
def raw_diff(self):
        
        udiff_copy = self.copy_iterator()
        if self.__format == 'gitdiff':
            udiff_copy = self._parse_gitdiff(udiff_copy)
        return u''.join(udiff_copy)
971444
def diff_string_templates(string_a, string_b):
    
    s1 = string_a.strip().splitlines()
    s2 = string_b.strip().splitlines()
    diffs = unified_diff(s2, s1, fromfile='deployed', tofile='local', lineterm='')
    return '\n'.join(diffs)
106435
def palindromic_substrings_iter(s):
    
    if not s:
        yield []
        return
    for i in range(len(s), 0, -1):
        sub = s[:i]
        if sub == sub[::-1]:
            for rest in palindromic_substrings_iter(s[i:]):
                yield [sub] + rest
1220086
def _slice(expr, start=None, stop=None, step=None):
    

    return _string_op(expr, Slice, _start=start, _end=stop, _step=step)
638826
def __diff_obj(self, level, parents_ids=frozenset({}),
                   is_namedtuple=False):
        """"""
        try:
            if is_namedtuple:
                t1 = level.t1._asdict()
                t2 = level.t2._asdict()
            else:
                t1 = level.t1.__dict__
                t2 = level.t2.__dict__
        except AttributeError:
            try:
                t1 = self.__dict_from_slots(level.t1)
                t2 = self.__dict_from_slots(level.t2)
            except AttributeError:
                self.__report_result('unprocessed', level)
                return

        self.__diff_dict(
            level,
            parents_ids,
            print_as_attribute=True,
            override=True,
            override_t1=t1,
            override_t2=t2)
1163180
function recursiveDiff(vtree, elem) {
  var output = '';
  if (vtree == null && elem != null) {
    // If the VTree ran out but DOM still exists
    output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
  } else if (isVNode(vtree)) {
    if (!elem || elem.nodeType !== utils.NODE_TYPES.ELEMENT) {
      // If vtree is a VNode, but elem isn't an Element
      output += '<del>' + vNodeToString(vtree, true, false) + '</del>';
      if (elem) {
        output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
      }
    } else {
      // Diff elements and recurse
      output += diffElements(vtree, elem);
    }
  } else if (isVText(vtree)) {
    if (!elem || elem.nodeType !== utils.NODE_TYPES.TEXT) {
      // If vtree is a VText, but elem isn't a textNode
      output += '<del>' + escapeString(vtree.text) + '</del>';
      if (elem) {
        output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
      }
    } else {
      output += textDiff(vtree.text, elem.textContent);
    }
  } else if (isWidget(vtree)) {
    var widgetName;
    // Widgets are the construct that hold childViews
    if (vtree.constructor === HTMLCommentWidget) {
      // HTMLCommentWidget is a special case
      if (!elem || elem.nodeType !== utils.NODE_TYPES.COMMENT) {
        output += '<del>' + utils.getCommentString(escapeString(vtree.text), chars) + '</del>';
        if (elem) {
          output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
        }
      } else {
        output += utils.getCommentString(textDiff(escapeString(vtree.text), elem.textContent), chars);
      }
    } else if (vtree && vtree.view) {
      widgetName = vtree.view.getDebugName();
      if (typeof vtree.templateToString === 'function') {
        widgetName = vtree.templateToString(recursiveDiff);
      }
      if (vtree.view.el !== elem) {
        // If the view at this position isn't bound to elem, something has gone terribly wrong
        output += '<del><ins>' + widgetName + '</ins></del>';
      } else {
        output += widgetName;
      }
    } else if (vtree && typeof vtree.diff === 'function') {
      output += vtree.diff(elem, recursiveDiff);
    } else {
      output += '<del>[Uninitialized child view]</del>';
      output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
    }
  }
  return output;
}
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
203339
def get_substr_slices(umi_length, idx_size):
    '''
    
    '''
    cs, r = divmod(umi_length, idx_size)
    sub_sizes = [cs + 1] * r + [cs] * (idx_size - r)
    offset = 0
    slices = []
    for s in sub_sizes:
        slices.append((offset, offset + s))
        offset += s
    return slices
1288362
def _non_reducing_slice(slice_):
    
    # default to column slice, like DataFrame
    # ['A', 'B'] -> IndexSlices[:, ['A', 'B']]
    kinds = (ABCSeries, np.ndarray, Index, list, str)
    if isinstance(slice_, kinds):
        slice_ = IndexSlice[:, slice_]

    def pred(part):
        # true when slice does *not* reduce, False when part is a tuple,
        # i.e. MultiIndex slice
        return ((isinstance(part, slice) or is_list_like(part))
                and not isinstance(part, tuple))

    if not is_list_like(slice_):
        if not isinstance(slice_, slice):
            # a 1-d slice, like df.loc[1]
            slice_ = [[slice_]]
        else:
            # slice(a, b, c)
            slice_ = [slice_]  # to tuplize later
    else:
        slice_ = [part if pred(part) else [part] for part in slice_]
    return tuple(slice_)
948792
def malloc_diff(func):
    
    def _f(*args, **kwargs):
        print("\n<<<---")
        tracemalloc.start()
        snapshot1 = tracemalloc.take_snapshot()
        res = func(*args, **kwargs)
        snapshot2 = tracemalloc.take_snapshot()
        top_stats = snapshot2.compare_to(snapshot1, 'lineno')
        print("[ Top 10 differences]")
        for stat in top_stats[:10]:
            print(stat)
        print("--->>>\n")
        return res
    return _f
1129117
def get_diff(left, right):
    
    res = {'+': [], '-': []}

    def partition(objects):
        """Partition the passed object list."""
        res = {}
        for o in objects:
            t = type(o)
            if type(o) not in res:
                res[t] = []
            res[t].append(o)
        return res

    def get_not_included(foo, bar):
        """Compare objects from foo with objects defined in the values of
        bar (set of partitions).
        Returns a list of all objects included in list, but not dict values.
        """
        res = []
        for o in foo:
            if not compat.object_in_list(type(o), bar):
                res.append(o)
            elif not compat.object_in_list(o, bar[type(o)]):
                res.append(o)
        return res

    # Create partitions of both lists. This will reduce the time required for
    # the comparison
    left_objects = partition(left)
    right_objects = partition(right)
    # and then do the diff
    res['+'] = get_not_included(right, left_objects)
    res['-'] = get_not_included(left, right_objects)
    return res