code: def merge_close(events, min_interval, merge_to_longer=False):
      
      half_iv = min_interval / 2
      merged = []
  
      for higher in events:
  
          if not merged:
              merged.append(higher)
  
          else:
              lower = merged[-1]
  
              if higher['start'] - half_iv <= lower['end'] + half_iv:
  
                  if merge_to_longer and (higher['end'] - higher['start'] >
                  lower['end'] - lower['start']):
                      start = min(lower['start'], higher['start'])
                      higher.update({'start': start})
                      merged[-1] = higher
  
                  else:
                      end = max(lower['end'], higher['end'])
                      merged[-1].update({'end': end})
  
              else:
                  merged.append(higher)
  
      return merged
docs: Merge events that are separated by a less than a minimum interval.
  
      Parameters
      ----------
      events : list of dict
          events with 'start' and 'end' times, from one or several channels.
          **Events must be sorted by their start time.**
      min_interval : float
          minimum delay between consecutive events, in seconds
      merge_to_longer : bool (default: False)
          If True, info (chan, peak, etc.) from the longer of the 2 events is
          kept. Otherwise, info from the earlier onset spindle is kept.
  
      Returns
      -------
      list of dict
          original events list with close events merged.