from "hb-ot-shape-complex-indic-table.cc"
322952
public static function indic_get_categories ($u) {
  if (0x0900 <= $u && $u <= 0x0DFF) return self::$indic_table[$u - 0x0900 + 0];	// offset 0 for Most "indic"
  if (0x1CD0 <= $u && $u <= 0x1D00) return self::$indic_table[$u - 0x1CD0 + 1152];	// offset for Vedic extensions
  if (0x1780 <= $u && $u <= 0x17FF) return self::$khmer_table[$u - 0x1780];		// Khmer
  if ($u == 0x00A0) return 3851;	// (ISC_CP | (IMC_x << 8))
  if ($u == 0x25CC) return 3851;	// (ISC_CP | (IMC_x << 8))
  return 3840;	// (ISC_x | (IMC_x << 8))
}
850483
def structure(table_toplevels):
    

    table_toplevels = tuple(table_toplevels)
    obj = NamedDict()

    last_array_of_tables = None         # The Name of the last array-of-tables header

    for toplevel in table_toplevels:

        if isinstance(toplevel, toplevels.AnonymousTable):
            obj[''] = toplevel.table_element

        elif isinstance(toplevel, toplevels.Table):
            if last_array_of_tables and toplevel.name.is_prefixed_with(last_array_of_tables):
                seq = obj[last_array_of_tables]
                unprefixed_name = toplevel.name.without_prefix(last_array_of_tables)

                seq[-1] = CascadeDict(seq[-1], NamedDict({unprefixed_name: toplevel.table_element}))
            else:
                obj[toplevel.name] = toplevel.table_element
        else:    # It's an ArrayOfTables

            if last_array_of_tables and toplevel.name != last_array_of_tables and \
                    toplevel.name.is_prefixed_with(last_array_of_tables):

                seq = obj[last_array_of_tables]
                unprefixed_name = toplevel.name.without_prefix(last_array_of_tables)

                if unprefixed_name in seq[-1]:
                    seq[-1][unprefixed_name].append(toplevel.table_element)
                else:
                    cascaded_with = NamedDict({unprefixed_name: [toplevel.table_element]})
                    seq[-1] = CascadeDict(seq[-1], cascaded_with)

            else:
                obj.append(toplevel.name, toplevel.table_element)
                last_array_of_tables = toplevel.name

    return obj
879079
function() {
            while (i < tb.seqCount) {
                var ns = ba[p];
                if (p + ns + 2 + (tb.version == 0 ? 4 : 8) >= ba.length) {
                    headerBlocksFetched += headerBlockSize;
                    headerBlockSize = Math.max(HEADER_BLOCK_SIZE,Math.floor(headerBlocksFetched*tb.seqCount/i));
                    return tb.data.slice(o + p, headerBlockSize).fetch(function (r) {
                        o += p;
                        p = 0;
                        ba = new Uint8Array(r);
                        parseSeqInfo();
                    });
                } else {
                    ++p;
                    var name = '';
                    for (var j = 1; j <= ns; ++j) {
                        name += String.fromCharCode(ba[p++]);
                    }
                    if (tb.version == 0) {
                        var offset = tb.readInt(ba, p);
                        p += 4;
                    } else {
                        var offset = tb.readInt64(ba, p);
                        p += 8;
                    }
                    tb.seqDict[name] = new TwoBitSeq(tb, offset);
                    ++i;
                }
            }
            return cnt(tb);
        }
106345
def prokka_table(self):
        

        # Specify the order of the different possible categories
        headers = OrderedDict()
        headers['organism'] = {
                'title': 'Organism',
                'description': 'Organism name',
        }
        headers['contigs'] = {
                'title': '# contigs',
                'description': 'Number of contigs in assembly',
                'format': '{:i}',
        }
        headers['bases'] = {
                'title': '# bases',
                'description': 'Number of nucleotide bases in assembly',
                'format': '{:i}',
        }
        headers['CDS'] = {
                'title': '# CDS',
                'description': 'Number of annotated CDS',
                'format': '{:i}',
        }
        headers['rRNA'] = {
                'title': '# rRNA',
                'description': 'Number of annotated rRNA',
                'format': '{:i}',
        }
        headers['tRNA'] = {
                'title': '# tRNA',
                'description': 'Number of annotated tRNA',
                'format': '{:i}',
        }
        headers['tmRNA'] = {
                'title': '# tmRNA',
                'description': 'Number of annotated tmRNA',
                'format': '{:i}',
        }
        headers['misc_RNA'] = {
                'title': '# misc RNA',
                'description': 'Number of annotated misc. RNA',
                'format': '{:i}',
        }
        headers['sig_peptide'] = {
                'title': '# sig_peptide',
                'description': 'Number of annotated sig_peptide',
                'format': '{:i}',
        }
        headers['repeat_region'] = {
                'title': '# CRISPR arrays',
                'description': 'Number of annotated CRSIPR arrays',
                'format': '{:i}',
        }
        table_config = {
            'namespace': 'prokka',
            'min': 0,
        }

        return table.plot(self.prokka, headers, table_config)
944213
def GetRosettaResidueMap(self, ConvertMSEToAtom = False, RemoveIncompleteFinalResidues = False, RemoveIncompleteResidues = False):
        ''''''
        raise Exception('This code looks to be deprecated. Use construct_pdb_to_rosetta_residue_map instead.')
        chain = None
        sequences = {}
        residue_map = {}
        resid_set = set()
        resid_list = []

        DNA_residues = set([' DA', ' DC', ' DG', ' DT'])
        chains = []
        self.RAW_ATOM_SEQUENCE = []
        essential_atoms_1 = set(['CA', 'C', 'N'])#, 'O'])
        essential_atoms_2 = set(['CA', 'C', 'N'])#, 'OG'])
        current_atoms = set()
        atoms_read = {}
        oldchainID = None
        removed_residue = {}
        for line in self.lines:
            if line[0:4] == 'ATOM' or (ConvertMSEToAtom and (line[0:6] == 'HETATM') and (line[17:20] == 'MSE')):
                chainID = line[21]
                if missing_chain_ids.get(self.pdb_id):
                    chainID = missing_chain_ids[self.pdb_id]
                if chainID not in chains:
                    chains.append(chainID)
                residue_longname = line[17:20]
                if residue_longname in DNA_residues:
                    # Skip DNA
                    continue
                if residue_longname == 'UNK':
                    # Skip unknown residues
                    continue
                if residue_longname not in allowed_PDB_residues_types and not(ConvertMSEToAtom and residue_longname == 'MSE'):
                    if not self.strict:
                        # Skip unknown residues
                        continue
                    else:
                        raise NonCanonicalResidueException("Residue %s encountered: %s" % (line[17:20], line))
                else:
                    resid = line[21:27]
                    #print(chainID, residue_longname, resid)
                    #print(line)
                    #print(resid_list)
                    if resid not in resid_set:
                        removed_residue[chainID] = False
                        add_residue = True
                        if current_atoms:
                            if RemoveIncompleteResidues and essential_atoms_1.intersection(current_atoms) != essential_atoms_1 and essential_atoms_2.intersection(current_atoms) != essential_atoms_2:
                                oldChain = resid_list[-1][0]
                                oldResidueID = resid_list[-1][1:]
                                print("The last residue '%s', %s, in chain %s is missing these atoms: %s." % (resid_list[-1], residue_longname, oldChain, essential_atoms_1.difference(current_atoms) or essential_atoms_2.difference(current_atoms)))
                                resid_set.remove(resid_list[-1])
                                #print("".join(resid_list))
                                resid_list = resid_list[:-1]
                                if oldchainID:
                                    removed_residue[oldchainID] = True
                                #print("".join(resid_list))
                                #print(sequences[oldChain])
                                if sequences.get(oldChain):
                                    sequences[oldChain] = sequences[oldChain][:-1]

                                if residue_map.get(oldChain):
                                    residue_map[oldChain] = residue_map[oldChain][:-1]

                                #print(sequences[oldChain]
                        else:
                            assert(not(resid_set))
                        current_atoms = set()
                        atoms_read[chainID] = set()
                        atoms_read[chainID].add(line[12:15].strip())
                        resid_set.add(resid)
                        resid_list.append(resid)
                        chainID = line[21]

                        sequences[chainID] = sequences.get(chainID, [])
                        if residue_longname in non_canonical_amino_acids:
                            sequences[chainID].append(non_canonical_amino_acids[residue_longname])
                        else:
                            sequences[chainID].append(residue_type_3to1_map[residue_longname])

                        residue_map[chainID] = residue_map.get(chainID, [])
                        if residue_longname in non_canonical_amino_acids:
                            residue_map[chainID].append((resid, non_canonical_amino_acids[residue_longname]))
                        else:
                            residue_map[chainID].append((resid, residue_type_3to1_map[residue_longname]))

                        oldchainID = chainID
                    else:
                        #atoms_read[chainID] = atoms_read.get(chainID, set())
                        atoms_read[chainID].add(line[12:15].strip())
                    current_atoms.add(line[12:15].strip())
        if RemoveIncompleteFinalResidues:
            # These are (probably) necessary for Rosetta to keep the residue. Rosetta does throw away residues where only the N atom is present if that residue is at the end of a chain.
            for chainID, sequence_list in sequences.iteritems():
                if not(removed_residue[chainID]):
                    if essential_atoms_1.intersection(atoms_read[chainID]) != essential_atoms_1 and essential_atoms_2.intersection(atoms_read[chainID]) != essential_atoms_2:
                        print("The last residue %s of chain %s is missing these atoms: %s." % (sequence_list[-1], chainID, essential_atoms_1.difference(atoms_read[chainID]) or essential_atoms_2.difference(atoms_read[chainID])))
                        oldResidueID = sequence_list[-1][1:]
                        residue_map[chainID] = residue_map[chainID][0:-1]
                        sequences[chainID] = sequence_list[0:-1]


        for chainID, sequence_list in sequences.iteritems():
            sequences[chainID] = "".join(sequence_list)
            assert(sequences[chainID] == "".join([res_details[1] for res_details in residue_map[chainID]]))
        for chainID in chains:
            for a_acid in sequences.get(chainID, ""):
                self.RAW_ATOM_SEQUENCE.append((chainID, a_acid))

        residue_objects = {}
        for chainID in residue_map.keys():
            residue_objects[chainID] = []
        for chainID, residue_list in residue_map.iteritems():
            for res_pair in residue_list:
                resid = res_pair[0]
                resaa = res_pair[1]
                assert(resid[0] == chainID)
                residue_objects[chainID].append((resid[1:].strip(), resaa))

        return sequences, residue_objects
1334718
def _build_unicode_character_database(self):
        
        filename = "UnicodeData.txt"
        current_dir = os.path.abspath(os.path.dirname(__file__))
        tag = re.compile(r"<\w+?>")
        with codecs.open(os.path.join(current_dir, filename), mode="r", encoding="utf-8") as fp:
            for line in fp:
                if not line.strip():
                    continue
                data = line.strip().split(";")
                # Replace the start/end range markers with their proper derived names.
                if data[1].endswith((u"First>", u"Last>")) and _is_derived(int(data[0], 16)):
                    data[1] = _get_nr_prefix(int(data[0], 16))
                    if data[1].startswith("HANGUL SYLLABLE"):  # For Hangul syllables, use naming rule NR1
                        data[1] += _get_hangul_syllable_name(int(data[0], 16))
                    else:  # Others should use naming rule NR2
                        data[1] += data[0]
                data[3] = int(data[3])  # Convert the Canonical Combining Class value into an int.
                if data[5]:  # Convert the contents of the decomposition into characters, preserving tag info.
                    data[5] = u" ".join([_hexstr_to_unichr(s) if not tag.match(s) else s for s in data[5].split()])
                for i in [6, 7, 8]:  # Convert the decimal, digit and numeric fields to either ints or fractions.
                    if data[i]:
                        if "/" in data[i]:
                            data[i] = Fraction(data[i])
                        else:
                            data[i] = int(data[i])
                for i in [12, 13, 14]:  # Convert the uppercase, lowercase and titlecase fields to characters.
                    if data[i]:
                        data[i] = _hexstr_to_unichr(data[i])
                lookup_name = _uax44lm2transform(data[1])
                uc_data = UnicodeCharacter(u"U+" + data[0], *data[1:])
                self._unicode_character_database[int(data[0], 16)] = uc_data
                self._name_database[lookup_name] = uc_data
        # Fill out the "compressed" ranges of UnicodeData.txt i.e. fill out the remaining characters per the Name
        # Derivation Rules.  See the Unicode Standard, ch. 4, section 4.8, Unicode Name Property
        for lookup_range, prefix_string in _nr_prefix_strings.items():
            exemplar = self._unicode_character_database.__getitem__(lookup_range[0])
            for item in lookup_range:
                hex_code = _padded_hex(item)
                new_name = prefix_string
                if prefix_string.startswith("HANGUL SYLLABLE"):  # For Hangul, use naming rule NR1
                    new_name += _get_hangul_syllable_name(item)
                else:  # Everything else uses naming rule NR2
                    new_name += hex_code
                uc_data = exemplar._replace(code=u"U+" + hex_code, name=new_name)
                self._unicode_character_database[item] = uc_data
                self._name_database[_uax44lm2transform(new_name)] = uc_data
479264
def is_indiclang_char(c,lang): 
    
    o=get_offset(c,lang)
    return (o>=0 and o<=0x7f) or ord(c)==DANDA or ord(c)==DOUBLE_DANDA
1207942
function parse_BrtRowHdr(data, length) {
	var z = ({});
	var tgt = data.l + length;
	z.r = data.read_shift(4);
	data.l += 4; // TODO: ixfe
	var miyRw = data.read_shift(2);
	data.l += 1; // TODO: top/bot padding
	var flags = data.read_shift(1);
	data.l = tgt;
	if(flags & 0x07) z.level = flags & 0x07;
	if(flags & 0x10) z.hidden = true;
	if(flags & 0x20) z.hpt = miyRw / 20;
	return z;
}
801956
@SuppressWarnings("unchecked")
    String getFormattedTabularData(TabularData td, String indent) {
        StringBuilder sb = new StringBuilder();
        indent += INDENT;

        sb.append("{");
        Collection<CompositeData> values = (Collection<CompositeData>) td.values();
        int valuesRemaining = values.size();
        for (CompositeData cd : values) {
            sb.append(getFormattedCompositeData(cd, indent));
            if (--valuesRemaining > 0) {
                sb.append("\n").append(indent).append("}, {");
            }
        }
        sb.append("}");

        return String.valueOf(sb);
    }
291673
private void tred2()
    {
        for(int j = 0; j < n; j++)
            d[j] = V.get(n-1, j);

        // Householder reduction to tridiagonal form.

        for (int i = n - 1; i > 0; i--)
        {

            // Scale to avoid under/overflow.

            double scale = 0.0;
            double h = 0.0;
            for (int k = 0; k < i; k++)
            {
                scale = scale + abs(d[k]);
            }
            if (scale == 0.0)
            {
                e[i] = d[i - 1];
                for (int j = 0; j < i; j++)
                {
                    d[j] = V.get(i-1, j);
                    V.set(i, j, 0.0);
                    V.set(j, i, 0.0);
                }
            }
            else
            {

                // Generate Householder vector.

                for (int k = 0; k < i; k++)
                {
                    d[k] /= scale;
                    h += d[k] * d[k];
                }
                double f = d[i - 1];
                double g = sqrt(h);
                if (f > 0)
                    g = -g;
                e[i] = scale * g;
                h -= f * g;
                d[i - 1] = f - g;
                Arrays.fill(e, 0, i, 0.0);

                // Apply similarity transformation to remaining columns.

                for (int j = 0; j < i; j++)
                {
                    f = d[j];
                    V.set(j, i, f);
                    g = e[j] + V.get(j, j) * f;
                    for (int k = j + 1; k <= i - 1; k++)
                    {
                        g += V.get(k,j) * d[k];
                        e[k] += V.get(k, j) * f;
                    }
                    e[j] = g;
                }
                f = 0.0;
                for (int j = 0; j < i; j++)
                {
                    e[j] /= h;
                    f += e[j] * d[j];
                }
                double hh = f / (h + h);
                for (int j = 0; j < i; j++)
                {
                    e[j] -= hh * d[j];
                }
                for (int j = 0; j < i; j++)
                {
                    f = d[j];
                    g = e[j];
                    
                    for (int k = j; k <= i - 1; k++)
                    {
                        V.increment(k, j, -(f * e[k] + g * d[k]));
                    }
                    d[j] = V.get(i-1, j);
                    V.set(i, j, 0.0);
                }
            }
            d[i] = h;
        }


        // Accumulate transformations.

        for (int i = 0; i < n - 1; i++)
        {
            V.set(n-1, i, V.get(i, i));
            V.set(i, i, 1.0);
            double h = d[i + 1];
            if (h != 0.0)
            {
                for (int k = 0; k <= i; k++)
                {
                    d[k] = V.get(k, i+1) / h;
                }
                for (int j = 0; j <= i; j++)
                {
                    double g = 0.0;
                    for (int k = 0; k <= i; k++)
                    {
                        g += V.get(k, i+1) * V.get(k, j);
                    }
                    
                    RowColumnOps.addMultCol(V, j, 0, i+1, -g, d);
                }
            }

            RowColumnOps.fillCol(V, i+1, 0, i+1, 0.0);
            
        }
        for (int j = 0; j < n; j++)
        {
            d[j] = V.get(n-1, j);
            V.set(n-1, j, 0.0);
        }
        V.set(n-1, n-1, 1.0);
        e[0] = 0.0;
    }
759632
def parse_ggKbase_tables(tables, id_type):
    
    g2info = {}
    for table in tables:
        for line in open(table):
            line = line.strip().split('\t')
            if line[0].startswith('name'):
                header = line
                header[4] = 'genome size (bp)'
                header[12] = '#SCGs'
                header[13] = '#SCG duplicates'
                continue
            name, code, info = line[0], line[1], line
            info = [to_int(i) for i in info]
            if id_type is False: # try to use name and code ID
                if 'UNK' in code or 'unknown' in code:
                    code = name
                if (name != code) and (name and code in g2info):
                    print('# duplicate name or code in table(s)', file=sys.stderr)
                    print('# %s and/or %s' % (name, code), file=sys.stderr)
                    exit()
                if name not in g2info:
                    g2info[name] = {item:stat for item, stat in zip(header, info)}
                if code not in g2info:
                    g2info[code] = {item:stat for item, stat in zip(header, info)}
            else:
                if id_type == 'name':
                    ID = name
                elif id_type == 'code':
                    ID = code
                else:
                    print('# specify name or code column using -id', file=sys.stderr)
                    exit()
                ID = ID.replace(' ', '')
                g2info[ID] = {item:stat for item, stat in zip(header, info)}
                if g2info[ID]['genome size (bp)'] == '':
                    g2info[ID]['genome size (bp)'] = 0
    return g2info
288926
private static String calculateMolecularFormula(List<AbstractMolecule> molecules) throws BuilderMoleculeException, CTKException, ChemistryException {
    Map<String, Integer> atomNumberMap = new TreeMap<String, Integer>();
    for (AbstractMolecule molecule : molecules) {
      LOG.info(molecule.getMolecule().toString());
      atomNumberMap = generateAtomNumberMap(molecule, atomNumberMap);
    }
    LOG.info("GET map");
    StringBuilder sb = new StringBuilder();
    Set<String> atoms = atomNumberMap.keySet();
    for (Iterator<String> i = atoms.iterator(); i.hasNext();) {
      String atom = i.next();
      String num = atomNumberMap.get(atom).toString();
      if (num.equals("1")) {
        num = "";
      }
      sb.append(atom);
      sb.append(num.toString());
    }
    return sb.toString();
  }
944429
def get_chr2idx(self):
        """"""
        return {chr(ascii_int):idx for idx, ascii_int in enumerate(self.all_chrints)}
733385
def std_table(rows):
    """"""

    result = ""
    if len(rows) > 1:
        headers = rows[0]._fields
        lens = []
        for i in range(len(rows[0])):
            lens.append(len(max([x[i] for x in rows] + [headers[i]],
                                key=lambda x: len(str(x)))))
        formats = []
        hformats = []
        for i in range(len(rows[0])):
            if isinstance(rows[0][i], int):
                formats.append("%%%dd" % lens[i])
            else:
                formats.append("%%-%ds" % lens[i])
            hformats.append("%%-%ds" % lens[i])
        pattern = " | ".join(formats)
        hpattern = " | ".join(hformats)
        separator = "-+-".join(['-' * n for n in lens])
        result += hpattern % tuple(headers) + " \n"
        result += separator + "\n"

        for line in rows:
            result += pattern % tuple(t for t in line) + "\n"
    elif len(rows) == 1:
        row = rows[0]
        hwidth = len(max(row._fields, key=lambda x: len(x)))
        for i in range(len(row)):
            result += "%*s = %s" % (hwidth, row._fields[i], row[i]) + "\n"

    return result
1200416
def get_bound_form(self, noun, gender):
        """"""
        syllables = self.syllabifier.syllabify(noun)
        stem = self.stemmer.get_stem(noun, gender)
        cv_pattern = self.cv_patterner.get_cv_pattern(stem)
        # Based on Huehnergard Appendix 6.C.1: base in -VC
        if [letter[0] for letter in cv_pattern[-2:]] == ['V', 'C'] or stem in ['nakr']:
            # a. 2-syllable
            if len(syllables) > 2:
                # awīlum > awīl, nakrum > naker
                if stem in ['nakr']:
                    return 'naker'
                else:
                    return stem
            # b. 1-syllable
            elif len(syllables) > 1:
                # bēlum > bēl
                return stem
            # c. abum, aḫum
            if stem in ['ab', 'aḫ']:
                return stem + 'i'
        # Appendix 6.C.2: base in -C₁C₁
        if cv_pattern[-1][:2] == cv_pattern[-2][:2]:
            # a. 1-syllable
            if 3 > len(syllables) > 1:
                return stem + 'i'
            # b. 2-syllable, -tt
            if len(syllables) > 2 and cv_pattern[-1][2] + cv_pattern[-2][2] == 'tt':
                return stem + 'i'
            # c. 2-syllable, other
            if len(syllables) > 2:
                return stem[:-1]
        # Appendix 6.C.3: base in -C₁C₂, C₂ ≠ t, i.e. pVrs
        if cv_pattern[-1][0] == cv_pattern[-2][0] and cv_pattern[-1][1] != cv_pattern[-2][1]:
            return stem[:-1] + stem[1] + stem[-1]
        # Appendix 6.C.4: base in -Ct (fem.)
        if cv_pattern[-1][2] == 't' and cv_pattern[-2][0] == 'C':
            if len(syllables) > 2:
                return stem + 'i'
            # Need to deal with fem. Ptcpl. māḫirtum -> māḫirat
            if len(syllables) > 1:
                # These are case by case
                if stem in ['qīšt']:
                    return stem + 'i'
                if stem in ['mārt']:
                    return stem[:-1] + stem[1] + stem[-1]
152323
public static int cusparseScsr2hyb(
        cusparseHandle handle, 
        int m, 
        int n, 
        cusparseMatDescr descrA, 
        Pointer csrSortedValA, 
        Pointer csrSortedRowPtrA, 
        Pointer csrSortedColIndA, 
        cusparseHybMat hybA, 
        int userEllWidth, 
        int partitionType)
    {
        return checkResult(cusparseScsr2hybNative(handle, m, n, descrA, csrSortedValA, csrSortedRowPtrA, csrSortedColIndA, hybA, userEllWidth, partitionType));
    }
530464
private static Table getTable(char t) {
    switch (t) {
      case 'L':
        return Table.LOWER;
      case 'P':
        return Table.PUNCT;
      case 'M':
        return Table.MIXED;
      case 'D':
        return Table.DIGIT;
      case 'B':
        return Table.BINARY;
      case 'U':
      default:
        return Table.UPPER;
    }
  }