Write events to Annotations file.
        
        Parameters
        ----------
        annot : instance of Annotations
            Annotations file
        name : str
            name for the event type
348509
def to_annot(self, annot, name=None, chan=None):
        
        annot.add_events(self.events, name=name, chan=chan)
300116
def annotate(self, annotation: Any) -> None:
        
        if isinstance(annotation, list):
            self._annotations += annotation
        else:
            self._annotations.append(annotation)
730884
function annotate(fn) {
  var matched = /function +[^\(]*\(([^\)]*)\).*/.exec(fn.toString());
  var names = _.reject(matched[1].split(',') || [], _.isEmpty);

  return _.map(names, function(name) {
    return name.replace(/\s+/g, '');
  });
}
407991
def highlight_event(self, annot):
        
        beg = annot.marker.x()
        end = beg + annot.marker.width()
        window_start = self.parent.value('window_start')
        window_length = self.parent.value('window_length')
        events = self.parent.notes.get_selected_events((window_start, 
                                                window_start + window_length))
        ev = [x for x in events if (x['start'] == annot.marker.x() or \
                                    x['end'] == annot.marker.y())]
        
        if ev:
            annot_name = ev[0]['name']
            
            msg = "Event of type '{}' from {} to {}".format(
                    annot_name, beg, end)
            self.current_etype = self.parent.notes.idx_eventtype.currentText()
            self.parent.notes.idx_eventtype.setCurrentText(annot_name)
            self.current_event = ev[0]
        else:
            msg = "Marker from {} to {}".format(beg, end)
        self.parent.statusBar().showMessage(msg)
            
        highlight = self.highlight = RectMarker(annot.marker.x(),
                                               annot.marker.y(),
                                               annot.marker.width(),
                                               annot.marker.height(),
                                               zvalue=-5,
                                               color=QColor(255, 255, 51))
        self.scene.addItem(highlight)
        self.event_sel = annot
577104
def write_events(stream, events):
    '''
    
    '''
    for event in events:
        data = event.SerializeToString()
        len_field = struct.pack('<Q', len(data))
        len_crc = struct.pack('<I', masked_crc(len_field))
        data_crc = struct.pack('<I', masked_crc(data))
        stream.write(len_field)
        stream.write(len_crc)
        stream.write(data)
        stream.write(data_crc)
242298
def _generate_struct_class_custom_annotations(self, ns, data_type):
        
        self.emit('def _process_custom_annotations(self, annotation_type, field_path, processor):')

        with self.indent(), emit_pass_if_nothing_emitted(self):
            self.emit(
                (
                    'super({}, self)._process_custom_annotations(annotation_type, field_path, '
                    'processor)'
                ).format(class_name_for_data_type(data_type))
            )
            self.emit()

            for field in data_type.fields:
                field_name = fmt_var(field.name, check_reserved=True)
                for annotation_type, processor in self._generate_custom_annotation_processors(
                        ns, field.data_type, field.custom_annotations):
                    annotation_class = class_name_for_annotation_type(annotation_type, ns)
                    self.emit('if annotation_type is {}:'.format(annotation_class))
                    with self.indent():
                        self.emit('self.{} = {}'.format(
                            field_name,
                            generate_func_call(
                                processor,
                                args=[
                                    "'{{}}.{}'.format(field_path)".format(field_name),
                                    'self.{}'.format(field_name),
                                ])
                        ))
                    self.emit()
142319
def markers_to_events(self, keep_name=False):
        
        markers = self.parent.info.markers
        
        if markers is None:
            self.parent.statusBar.showMessage('No markers in dataset.')
            return
        
        if not keep_name:
            name, ok = self.new_eventtype()            
            if not ok:
                return            
        else:
            name = None
                
        self.annot.add_events(markers, name=name, chan='')
        
        if keep_name:
            self.display_eventtype()
            n_eventtype = self.idx_eventtype.count()
            self.idx_eventtype.setCurrentIndex(n_eventtype - 1)
        
        self.update_annotations()
661011
def annotation(args):
    
    from jcvi.formats.base import DictFile

    p = OptionParser(annotation.__doc__)
    p.add_option("--queryids", help="Query IDS file to switch [default: %default]")
    p.add_option("--subjectids", help="Subject IDS file to switch [default: %default]")
    opts, args = p.parse_args(args)

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

    blastfile, = args

    d = "\t"
    qids = DictFile(opts.queryids, delimiter=d) if opts.queryids else None
    sids = DictFile(opts.subjectids, delimiter=d) if opts.subjectids else None
    blast = Blast(blastfile)
    for b in blast:
        query, subject = b.query, b.subject
        if qids:
            query = qids[query]
        if sids:
            subject = sids[subject]
        print("\t".join((query, subject)))
296308
def annotate(results, settings):
    ''''''
    annotations = (generate_annotation(result, setting)
                   for result, setting in zip(results, settings))
    return '\n'.join(annot for annot in annotations if annot)
182535
def _write(self, session, openFile, replaceParamFile=None):
        
        openFile.write(
            text(
                yaml.dump([evt.as_yml() for evt in
                           self.events.order_by(ProjectFileEvent.name,
                           ProjectFileEvent.subfolder)]
                          )
            )
        )
548317
def write_events(self, outname):
        
        self.make_output_dir(outname)

        if '.hdf' in outname:
            self.write_to_hdf(outname)
        else:
            raise ValueError('Cannot write to this format')
213923
def dump_annotations(type_info, files):
    
    with open(type_info) as f:
        data = json.load(f)
    for item in data:
        path, line, func_name = item['path'], item['line'], item['func_name']
        if files and path not in files:
            for f in files:
                if path.startswith(os.path.join(f, '')):
                    break
            else:
                continue  # Outer loop
        print("%s:%d: in %s:" % (path, line, func_name))
        type_comments = item['type_comments']
        signature = unify_type_comments(type_comments)
        arg_types = signature['arg_types']
        return_type = signature['return_type']
        print("    # type: (%s) -> %s" % (", ".join(arg_types), return_type))
734674
def add_event(self, func: Callable, event: str) -> None:
        
        self._events[event].add(func)
156961
def event_emitter(cls_=None, *, events=('*', )):
    

    # create a dictionary from items in the 'events' parameter and with empty
    # lists as values
    event_dict = dict.fromkeys(events, [])

    # if '*' was in the events tuple - then pop it out of the event_dict
    # and store the fact that we may allow any event name to be added to the
    # event emitter.
    allow_any_eventname = event_dict.pop('*', False) == []

    def _event_emitter(cls):

        def on(self, name, callback):
            """
            Add a callback to the event named 'name'. Returns the object for
            chained 'on' calls.
            """
            if not (callable(callback) or isawaitable(callback)):
                raise ValueError("Callback not callable: %r" % callback)

            try:
                event_dict[name].append(callback)
            except KeyError:
                if allow_any_eventname:
                    event_dict[name] = [callback]
                else:
                    msg = "Event Emitter has no event {!r}".format(name)
                    raise KeyError(msg)

            return self

        async def emit(self, name):
            """
            Coroutine which executes each of the callbacks added to the event
            identified by 'name'
            """
            for cb in event_dict[name]:
                if isawaitable(cb):
                    await cb
                else:
                    cb()

        cls.on = on
        cls.emit = emit

        return cls

    if cls_ is None:
        return _event_emitter
    else:
        return _event_emitter(cls_)
844711
def _generate_struct_or_union_class_custom_annotations(self):
        
        self.emit('def _process_custom_annotations(')
        with self.indent():
            self.emit('self,')
            self.emit('annotation_type: Type[T],')
            self.emit('field_path: Text,')
            self.emit('processor: Callable[[T, U], U],')
            self.import_tracker._register_typing_import('Type')
            self.import_tracker._register_typing_import('Text')
            self.import_tracker._register_typing_import('Callable')
        self.emit(') -> None: ...')
        self.emit()
1168346
def new_annot(self):
        """"""
        if self.parent.info.filename is None:
            msg = 'No dataset loaded'
            self.parent.statusBar().showMessage(msg)
            lg.debug(msg)
            return

        filename = splitext(self.parent.info.filename)[0] + '_scores.xml'
        filename, _ = QFileDialog.getSaveFileName(self, 'Create annotation file',
                                                  filename,
                                                  'Annotation File (*.xml)')
        if filename == '':
            return

        self.update_notes(filename, True)
1354718
def decorate_set_on_listener(prototype):
    
    # noinspection PyDictCreation,PyProtectedMember
    def add_annotation(method):
        method._event_info = {}
        method._event_info['name'] = method.__name__
        method._event_info['prototype'] = prototype
        return method

    return add_annotation