%prog overlap <a|a.fasta> <b|b.fasta>

    Check overlaps between two fasta records. The arguments can be genBank IDs
    instead of FASTA files. In case of IDs, the sequences will be downloaded
    first.
423050
def overlap(args):
    
    from jcvi.formats.blast import chain_HSPs

    p = OptionParser(overlap.__doc__)
    p.add_option("--dir", default=os.getcwd(),
            help="Download sequences to dir [default: %default]")
    p.add_option("--suffix", default="fasta",
            help="Suffix of the sequence file in dir [default: %default]")
    p.add_option("--qreverse", default=False, action="store_true",
            help="Reverse seq a [default: %default]")
    p.add_option("--nochain", default=False, action="store_true",
            help="Do not chain adjacent HSPs [default: chain HSPs]")
    p.set_align(pctid=GoodPct, hitlen=GoodOverlap, evalue=.01)
    p.set_outfile(outfile=None)
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    afasta, bfasta = args
    dir = opts.dir
    chain = not opts.nochain
    suffix = opts.suffix
    evalue = opts.evalue
    pctid = opts.pctid
    hitlen = opts.hitlen
    cutoff = Cutoff(pctid, hitlen)

    # Check first whether it is file or accession name
    if not op.exists(afasta):
        af = op.join(dir, ".".join((afasta, suffix)))
        if not op.exists(af):  # Check to avoid redownload
            entrez([afasta, "--skipcheck", "--outdir=" + dir])
        afasta = af

    if not op.exists(bfasta):
        bf = op.join(dir, ".".join((bfasta, suffix)))
        if not op.exists(bf):
            entrez([bfasta, "--skipcheck", "--outdir=" + dir])
        bfasta = bf

    assert op.exists(afasta) and op.exists(bfasta)

    cmd = "blastn -dust no"
    cmd += " -query {0} -subject {1}".format(afasta, bfasta)
    cmd += " -evalue {0} -outfmt 6 -perc_identity {1}".format(evalue, pctid)

    fp = popen(cmd)
    hsps = fp.readlines()

    hsps = [BlastLine(x) for x in hsps]
    hsps = [x for x in hsps if x.hitlen >= hitlen]
    if chain:
        logging.debug("Chain HSPs in the Blast output.")
        dist = 2 * hitlen  # Distance to chain the HSPs
        hsps = chain_HSPs(hsps, xdist=dist, ydist=dist)

    if len(hsps) == 0:
        print("No match found.", file=sys.stderr)
        return None

    besthsp = hsps[0]

    aid, asize = next(Fasta(afasta).itersizes())
    bid, bsize = next(Fasta(bfasta).itersizes())
    o = Overlap(besthsp, asize, bsize, cutoff, qreverse=opts.qreverse)
    o.print_graphic()

    if opts.outfile:
        fw = must_open(opts.outfile, "w")
        print(str(o), file=fw)
        fw.close()

    return o
1108002
def overlaps(self, contig, start, end, strand=None):
        
        return (
            self.can_overlap(contig, strand) and
            self.distance_to_interval(start, end) == 0)
1257561
def predicates_overlap(tags1: List[str], tags2: List[str]) -> bool:
    
    # Get predicate word indices from both predictions
    pred_ind1 = get_predicate_indices(tags1)
    pred_ind2 = get_predicate_indices(tags2)

    # Return if pred_ind1 pred_ind2 overlap
    return any(set.intersection(set(pred_ind1), set(pred_ind2)))
1199766
def merge(args):
    
    p = OptionParser(merge.__doc__)
    p.add_option("--seq", default=False, action="store_true",
                 help="Print FASTA sequences at the end")
    p.set_outfile()

    opts, args = p.parse_args(args)

    nargs = len(args)
    if nargs < 1:
        sys.exit(not p.print_help())

    if nargs == 1:
        listfile, = args
        fp = open(listfile)
        gffiles = [x.strip() for x in fp]
    else:
        gffiles = args

    outfile = opts.outfile

    deflines = set()
    fw = must_open(outfile, "w")
    fastarecs = {}
    for gffile in natsorted(gffiles, key=lambda x: op.basename(x)):
        logging.debug(gffile)
        fp = open(gffile)
        for row in fp:
            row = row.rstrip()
            if not row or row[0] == '#':
                if row == FastaTag:
                    break
                if row in deflines:
                    continue
                else:
                    deflines.add(row)

            print(row, file=fw)

        if not opts.seq:
            continue

        f = Fasta(gffile, lazy=True)
        for key, rec in f.iteritems_ordered():
            if key in fastarecs:
                continue
            fastarecs[key] = rec

    if opts.seq:
        print(FastaTag, file=fw)
        SeqIO.write(fastarecs.values(), fw, "fasta")

    fw.close()
437807
def wildcards_overlap(name1, name2):
    """"""
    if not name1 and not name2:
        return True
    if not name1 or not name2:
        return False
    for matched1, matched2 in _character_matches(name1, name2):
        if wildcards_overlap(name1[matched1:], name2[matched2:]):
            return True
    return False
460891
def _clashes(self, startTime, duration):
        
        return [m for m in self.activeMeasurements if m.overlapsWith(startTime, duration)]
834895
def _overlapping(files):
    
    segments = set()
    for path in files:
        seg = file_segment(path)
        for s in segments:
            if seg.intersects(s):
                return True
        segments.add(seg)
    return False
1104117
def overlap_add(blk_sig, size=None, hop=None, wnd=None, normalize=True):
  
  # Finds the size from data, if needed
  if size is None:
    blk_sig = Stream(blk_sig)
    size = len(blk_sig.peek())
  if hop is None:
    hop = size

  # Find the window to be applied, resulting on a list or None
  if wnd is not None:
    if callable(wnd) and not isinstance(wnd, Stream):
      wnd = wnd(size)
    if isinstance(wnd, Iterable):
      wnd = list(wnd)
    else:
      raise TypeError("Window should be an iterable or a callable")

  # Normalization to the [-1; 1] range
  if normalize:
    if wnd:
      steps = Stream(wnd).map(abs).blocks(hop).map(tuple)
      gain = max(xmap(sum, xzip(*steps)))
      if gain: # If gain is zero, normalization couldn't have any effect
        wnd[:] = (w / gain for w in wnd)
    else:
      wnd = [1 / ceil(size / hop)] * size

  # Window application
  if wnd:
    mul = operator.mul
    if len(wnd) != size:
      raise ValueError("Incompatible window size")
    wnd = wnd + [0.] # Allows detecting when block size is wrong
    blk_sig = (xmap(mul, wnd, blk) for blk in blk_sig)

  # Overlap-add algorithm
  add = operator.add
  mem = [0.] * size
  s_h = size - hop
  for blk in xmap(iter, blk_sig):
    mem[:s_h] = xmap(add, mem[hop:], blk)
    mem[s_h:] = blk # Remaining elements
    if len(mem) != size:
      raise ValueError("Wrong block size or declared")
    for el in mem[:hop]:
      yield el
  for el in mem[hop:]: # No more blocks, finish yielding the last one
    yield el
886330
def fasta(args):
    
    from jcvi.formats.sizes import Sizes

    p = OptionParser(fasta.__doc__)
    p.add_option("--extend", default=1000, type="int",
                 help="Extend seq flanking the gaps [default: %default]")
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    mapout, sfasta = args
    Flank = opts.extend
    pf = mapout.split(".")[0]
    mapbed = pf + ".bed"
    bm = BinMap(mapout)
    bm.print_to_bed(mapbed)

    bed = Bed(mapbed, sorted=False)
    markersbed = pf + ".markers.bed"
    fw = open(markersbed, "w")
    sizes = Sizes(sfasta).mapping
    for b in bed:
        accn = b.accn
        scf, pos = accn.split(".")
        pos = int(pos)
        start = max(0, pos - Flank)
        end = min(pos + Flank, sizes[scf])
        print("\t".join(str(x) for x in \
                    (scf, start, end, accn)), file=fw)

    fw.close()

    fastaFromBed(markersbed, sfasta, name=True)
231786
def gaps(args):
    
    from jcvi.formats.bed import uniq
    from jcvi.utils.iter import pairwise

    p = OptionParser(gaps.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    ombed, fastafile = args
    ombed = uniq([ombed])
    bed = Bed(ombed)

    for a, b in pairwise(bed):
        om_a = (a.seqid, a.start, a.end, "+")
        om_b = (b.seqid, b.start, b.end, "+")
        ch_a = range_parse(a.accn)
        ch_b = range_parse(b.accn)
        ch_a = (ch_a.seqid, ch_a.start, ch_a.end, "+")
        ch_b = (ch_b.seqid, ch_b.start, ch_b.end, "+")

        om_dist, x = range_distance(om_a, om_b, distmode="ee")
        ch_dist, x = range_distance(ch_a, ch_b, distmode="ee")

        if om_dist <= 0 and ch_dist <= 0:
            continue

        print(a)
        print(b)
        print(om_dist, ch_dist)
685023
public boolean overlaps(TimecodeRange that)
	{
		if (this.within(that.getStart()) || this.within(that.getEnd()))
		{
			return true; // we contain one of their timecodes
		}
		else if (that.within(this.getStart()) || that.within(this.getEnd()))
		{
			return true; // they contain one of our timecodes
		}
		else
		{
			return false;
		}
	}
777843
def overlapping(start1, end1, start2, end2):
    
    return not ((start1 <= start2 and start1 <= end2 and end1 <= end2 and end1 <= start2) or
                (start1 >= start2 and start1 >= end2 and end1 >= end2 and end1 >= start2))
75759
def check_overlapping_keys?(yaml_data, errors_array)
      overlap_detector = KeyOverlapDetector.new
      data = Psych.parser.parse(yaml_data)

      overlap_detector.parse(data)

      overlap_detector.overlapping_keys.each do |key|
        err_meg = "The same key is defined more than once: #{key.join('.')}"
        errors_array << err_meg
      end

      overlap_detector.overlapping_keys.empty?
    end
467170
def uniq(args):
    
    p = OptionParser(uniq.__doc__)
    p.add_option("--seq", default=False, action="store_true",
            help="Uniqify the sequences [default: %default]")
    p.add_option("-t", "--trimname", dest="trimname",
            action="store_true", default=False,
            help="turn on the defline trim to first space [default: %default]")

    opts, args = p.parse_args(args)
    if len(args) != 2:
        sys.exit(p.print_help())

    fastafile, uniqfastafile = args
    fw = must_open(uniqfastafile, "w")
    seq = opts.seq

    for rec in _uniq_rec(fastafile, seq=seq):
        if opts.trimname:
            rec.description = ""
        SeqIO.write([rec], fw, "fasta")
145612
def overlap(self, other):
        """"""
        if self._start < other.end and self._end > other.start:
            return True
        return False
522319
def overlapping(self, other):
        """"""
        return (
            other.start in self.ref_range) or (
            self.start in other.ref_range)
1013855
def get_sequences(options, fasta_file_contents):
    ''' 
    '''
    errors = []
    fasta_files_str = ", ".join(fasta_file_contents.keys())
    fasta_records = None
    reverse_mapping = {}

    try:
        fasta_records, reverse_mapping = parse_FASTA_files(options, fasta_file_contents)
        if not fasta_records:
            errors.append("No protein sequences found in the FASTA file(s) %s." % fasta_files_str)
    except Exception, e:
        e = '\n'.join([l for l in traceback.format_exc(), str('e') if l.strip()])
        errors.append("Error parsing FASTA file(s) %s:\n%s" % (fasta_files_str, str(e)))

    if not fasta_records:
        return None, {}, errors

    colorprinter.message('Found %d protein sequence(s).' % len(fasta_records))
    return fasta_records, reverse_mapping, errors