Read annotation file and store a list of namedtuples.
194763
def _init_associations(self, fin_gaf, hdr_only, prt, allow_missing_symbol):
        """"""
        ini = InitAssc()
        nts = ini.init_associations(fin_gaf, hdr_only, prt, allow_missing_symbol)
        self.hdr = ini.hdr
        return nts
936979
def get_annotations(cls, __fn):
        """"""
        if hasattr(__fn, '__func__'):
            __fn = __fn.__func__
        if hasattr(__fn, '__notes__'):
            return __fn.__notes__
        raise AttributeError('{!r} does not have annotations'.format(__fn))
937550
public static void writeJsonToFile(String filename,
      List<SemanticParserExampleLoss> losses, List<Map<String, Object>> annotations) {
    Preconditions.checkArgument(annotations.size() == losses.size());
    List<String> lines = Lists.newArrayList();
    for (int i = 0; i < losses.size(); i++) {
      lines.add(losses.get(i).toJson(annotations.get(i)));
    }
    IoUtils.writeLines(filename, lines);
  }
282524
def annotation_rows(prefix, annotations):
    
    ncol = len(annotations['Column Name'])
    return {name.replace(prefix, '', 1) : values + [''] * (ncol - len(values))
            for name, values in annotations.items() if name.startswith(prefix)}
197020
private Collection<AnnotationData> getAnnotationSet(final Collection<TagAndLength> pTags) {
		Collection<AnnotationData> ret = null;
		if (pTags != null) {
			Map<ITag, AnnotationData> data = AnnotationUtils.getInstance().getMap().get(getClass().getName());
			ret = new ArrayList<AnnotationData>(data.size());
			for (TagAndLength tal : pTags) {
				AnnotationData ann = data.get(tal.getTag());
				if (ann != null) {
					ann.setSize(tal.getLength() * BitUtils.BYTE_SIZE);
				} else {
					ann = new AnnotationData();
					ann.setSkip(true);
					ann.setSize(tal.getLength() * BitUtils.BYTE_SIZE);
				}
				ret.add(ann);
			}
		} else {
			ret = AnnotationUtils.getInstance().getMapSet().get(getClass().getName());
		}
		return ret;
	}
608750
def _extract_annotations_from_span(span):
    """"""
    if span.time_events is None:
        return []

    annotations = []
    for time_event in span.time_events:
        annotation = time_event.annotation
        if not annotation:
            continue

        event_timestamp_mus = timestamp_to_microseconds(time_event.timestamp)
        annotations.append({'timestamp': int(round(event_timestamp_mus)),
                            'value': annotation.description})

    return annotations
794258
def read_umi_tools(filename: PathLike, dtype: str='float32') -> AnnData:
    
    # import pandas for conversion of a dict of dicts into a matrix
    # import gzip to read a gzipped file :-)
    import gzip
    from pandas import DataFrame

    dod = {}  # this will contain basically everything
    fh = gzip.open(fspath(filename))
    header = fh.readline()  # read the first line

    for line in fh:
        t = line.decode('ascii').split('\t')  # gzip read bytes, hence the decoding
        try:
            dod[t[1]].update({t[0]:int(t[2])})
        except KeyError:
            dod[t[1]] = {t[0]:int(t[2])}

    df = DataFrame.from_dict(dod, orient='index')  # build the matrix
    df.fillna(value=0., inplace=True)  # many NaN, replace with zeros
    return AnnData(np.array(df), {'obs_names': df.index}, {'var_names': df.columns}, dtype=dtype)
1103216
def parse_hist_files(histf):
        """"""
        nameddata = dict()
        data = dict()
        try:
            for l in histf['f'].splitlines():
                s = l.split()
                if s:
                    if len(s) != 2:
                        raise RuntimeError("invalid format: " + str(len(s)) + " column(s) found in row. must be exactly 2.")
                    data[int(s[0])] = int(s[1])
        except Exception as err:
            log.warning("Error parsing %s. %s", histf['fn'], err)
            log.debug(traceback.format_exc())
        else:
            if data:
                nameddata[histf['s_name']] = data
            else:
                log.debug("%s is empty.", histf['fn'])
        finally:
            return nameddata
1308714
private AnnotationInfo readAnnotation() throws IOException {
        // Lcom/xyz/Annotation; -> Lcom.xyz.Annotation;
        final String annotationClassName = getConstantPoolClassDescriptor(
                inputStreamOrByteBuffer.readUnsignedShort());
        final int numElementValuePairs = inputStreamOrByteBuffer.readUnsignedShort();
        AnnotationParameterValueList paramVals = null;
        if (numElementValuePairs > 0) {
            paramVals = new AnnotationParameterValueList(numElementValuePairs);
            for (int i = 0; i < numElementValuePairs; i++) {
                final String paramName = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
                final Object paramValue = readAnnotationElementValue();
                paramVals.add(new AnnotationParameterValue(paramName, paramValue));
            }
        }
        return new AnnotationInfo(annotationClassName, paramVals);
    }
643951
def _OpenFilesForRead(self, metadata_value_pairs, token):
    """"""
    aff4_paths = [
        result.AFF4Path(metadata.client_urn)
        for metadata, result in metadata_value_pairs
    ]
    fds = aff4.FACTORY.MultiOpen(aff4_paths, mode="r", token=token)
    fds_dict = dict([(fd.urn, fd) for fd in fds])
    return fds_dict
492278
def load_annot(self):
        """"""
        if self.parent.info.filename is not None:
            filename = splitext(self.parent.info.filename)[0] + '_scores.xml'
        else:
            filename = None

        filename, _ = QFileDialog.getOpenFileName(self, 'Load annotation file',
                                                  filename,
                                                  'Annotation File (*.xml)')

        if filename == '':
            return

        try:
            self.update_notes(filename, False)
        except FileNotFoundError:
            msg = 'Annotation file not found'
            self.parent.statusBar().showMessage(msg)
            lg.info(msg)
363267
def _stream_annotation(file_name, pb_dir):
    
    # Full url of annotation file
    url = posixpath.join(config.db_index_url, pb_dir, file_name)

    # Get the content
    response = requests.get(url)
    # Raise HTTPError if invalid url
    response.raise_for_status()

    # Convert to numpy array
    ann_data = np.fromstring(response.content, dtype=np.dtype('<u1'))

    return ann_data
807576
public void accumulateAnnotations(List<String> annotations, AnnotationsAttribute annatt)
    {
        if (null == annatt)
        {
            return;
        }
        for (Annotation ann : annatt.getAnnotations())
        {
            annotations.add(ann.getTypeName());
        }
    }
1008090
def _annotate(args, setclus):
    """"""
    logger.info("Creating bed file")
    bedfile = generate_position_bed(setclus)
    a = pybedtools.BedTool(bedfile, from_string=True)
    beds = []
    logger.info("Annotating clusters")
    if hasattr(args, 'list_files'):
        beds = args.list_files.split(",")
        for filebed in beds:
            logger.info("Using %s " % filebed)
            db = os.path.basename(filebed)
            b = pybedtools.BedTool(filebed)
            c = a.intersect(b, wo=True)
            setclus = anncluster(c, setclus, db, args.type_ann, args.feature_id)
    return setclus
910560
def _read_file(self, filename):
        """"""
        result = []
        with open(filename, 'r') as f:
            lines = f.read().split('\n')
            for line in lines:
                nocomment = line.strip().split('#')[0].strip()
                if nocomment:
                    result.append(nocomment)
        return result
721910
def to_namedtuple(self):
        
        keys = filter(lambda x: not x.startswith("_"), self.__dict__)
        opt_nt = namedtuple(self.__class__.__name__, keys)
        filtered_dict = dict(map(lambda x: (x, self.__dict__[x]), keys))

        return opt_nt(**filtered_dict)
1059947
def reads(s, filename=None, loader=None, implicit_tuple=True, allow_errors=False):
  """"""
  return ast.reads(s,
      filename=filename or '<input>',
      loader=loader or default_loader,
      implicit_tuple=implicit_tuple,
      allow_errors=allow_errors)