Example usage for java.util BitSet length

List of usage examples for java.util BitSet length

Introduction

In this page you can find the example usage for java.util BitSet length.

Prototype

public int length() 

Source Link

Document

Returns the "logical size" of this BitSet : the index of the highest set bit in the BitSet plus one.

Usage

From source file:no.ntnu.idi.socialhitchhiking.utility.ShareOnFacebook.java

@SuppressWarnings("deprecation")
@Override/*  w w w .  j ava  2  s  . c  o m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    currentRoute = getApp().getSelectedRoute();
    facebook = new Facebook(APP_ID);
    restoreCredentials(facebook);

    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.facebook_dialog);

    //Intitialize TripOption string values
    String formatedDate = formatDate(getApp().getSelectedJourney().getStart());
    String formatedTime = formatTime(getApp().getSelectedJourney().getStart());

    date = "Date: " + formatedDate;
    time = "Start time: " + formatedTime;
    seats = "Seats available: " + getApp().getSelectedJourney().getTripPreferences().getSeatsAvailable();
    //      String extras = "Extras: "+ getApp().getSelectedJourney().getTripPreferences().toString();
    BitSet sExtras = getApp().getSelectedJourney().getTripPreferences().getExtras();
    extras = "Preferences: ";
    String[] items = { "Music", "Animals", "Breaks", "Talking", "Smoking" };
    for (int i = 0; i < sExtras.length(); i++) {
        if (sExtras.get(i)) {
            if (i == sExtras.length() - 1)
                extras = extras + items[i] + ".";
            else {
                if (i == sExtras.length() - 2)
                    extras = extras + items[i] + " and ";
                else
                    extras = extras + items[i] + ", ";
            }
        }
    }
    String facebookMessage = "";
    isDriver = getIntent().getExtras().getBoolean("isDriver");
    if (isDriver) {
        facebookMessage = "I have created a new drive on FreeRider\n" + date + "\n" + time + "\n" + seats + "\n"
                + extras;
    } else {
        facebookMessage = "I am hitchhiking on a new ride on FreeRider\n" + date + "\n" + time + "\n" + seats
                + "\n" + extras;
        ;
    }
    messageToPost = facebookMessage;
}

From source file:org.ala.spatial.analysis.layers.SitesBySpeciesTabulated.java

/**
 * Generate and write the sites by species list.
 * <p/>//  w  w  w. j  a v  a  2s . c  o m
 * Output files have both .csv and .json decades, tabulation by decades
 * decadecounts, tabulation by (species in) sequential decades
 * bioregionName, tabulation by bioregions (from ssf or grid & gridColumns)
 *
 * @param records         all occurrence records for this density grid as Records.
 * @param outputDirectory path to the output directory.
 * @param region          area restriction, or null for everywhere the occurrences
 *                        appear, as SimpleRegion.
 * @param envelopeGrid    area restriction as an envelope grid, or null for
 *                        everywhere the occurrences appear, as Grid
 * @param bioregionName   null or output bioregion name.
 * @param ssf             null or bioregion as shape file with a single column as
 *                        SimpleRegion.
 * @param grid            null or bioregion as Grid. Must also have gridColumns.
 * @param gridColumns     null or grid bioregion category lookup values as
 *                        String [].
 * @param decade          true to generate decades and decadecounts output
 *                        tabulations.
 * @throws IOException
 */
public void write(Records records, String outputDirectory, SimpleRegion region, Grid envelopeGrid,
        String bioregionName, SimpleShapeFile ssf, Grid grid, String[] gridColumns, boolean decade)
        throws IOException {
    String[] columns = null;
    int[] gridIntersections = null;
    int numberOfBioregions = 0;
    // get columns for bioregion categories from ssf or gridColumns.
    if (ssf != null) {
        columns = ssf.getColumnLookup();
    } else if (grid != null) {
        columns = gridColumns;
        gridIntersections = new int[records.getRecordsSize()];
        double[][] points = new double[records.getRecordsSize()][2];
        for (int i = 0; i < records.getRecordsSize(); i++) {
            points[i][0] = records.getLongitude(i);
            points[i][1] = records.getLatitude(i);
        }
        float[] f = grid.getValues(points);
        for (int i = 0; i < f.length; i++) {
            gridIntersections[i] = (int) f[i];
            if (gridIntersections[i] < 0 || gridIntersections[i] >= gridColumns.length + 1) {
                gridIntersections[i] = -1;
            }
        }
        f = null;
        points = null;
    }
    if (columns != null) {
        numberOfBioregions = columns.length + 1;
    }

    int uniqueSpeciesCount = records.getSpeciesSize();

    short[] decadeIdx = getDecadeIdx(records);
    int numberOfDecades = decadeIdx[decadeIdx.length - 1] + 1;

    HashMap<Integer, Integer>[] bioMap = new HashMap[numberOfBioregions];
    HashMap<Integer, Integer>[] decMap = new HashMap[numberOfDecades];
    HashMap<Integer, Integer>[] decCountMap = new HashMap[numberOfDecades + 1];
    for (int i = 0; i < bioMap.length; i++) {
        bioMap[i] = new HashMap<Integer, Integer>();
    }
    for (int i = 0; i < decMap.length; i++) {
        decMap[i] = new HashMap<Integer, Integer>();
    }
    for (int i = 0; i < decCountMap.length; i++) {
        decCountMap[i] = new HashMap<Integer, Integer>();
    }

    records.sortedStarts(bbox[1], bbox[0], resolution);

    BitSet[] bsDecades = new BitSet[numberOfDecades];
    BitSet[] bsBioregions = new BitSet[numberOfBioregions];
    for (int j = 0; j < numberOfBioregions; j++) {
        bsBioregions[j] = new BitSet(uniqueSpeciesCount);
    }
    for (int j = 0; j < numberOfDecades; j++) {
        bsDecades[j] = new BitSet(uniqueSpeciesCount);
    }
    int[] decContinousCounts = new int[records.getSpeciesSize()];

    for (int pos = 0; pos < records.getRecordsSize();) {
        //find end pos
        int x = (int) ((records.getLongitude(pos) - bbox[0]) / resolution);
        int y = (int) ((records.getLatitude(pos) - bbox[1]) / resolution);
        int endPos = pos + 1;
        while (endPos < records.getRecordsSize()
                && x == (int) ((records.getLongitude(endPos) - bbox[0]) / resolution)
                && y == (int) ((records.getLatitude(pos) - bbox[1]) / resolution)) {
            endPos++;
        }

        double longitude = (x + 0.5) * resolution;
        double latitude = (y + 0.5) * resolution;
        if ((region == null || region.isWithin_EPSG900913(longitude, latitude)) && (envelopeGrid == null
                || envelopeGrid.getValues2(new double[][] { { longitude, latitude } })[0] > 0)) {
            //process this cell
            getNextIntArrayRow(records, pos, endPos, bsBioregions, bsDecades, ssf, gridIntersections,
                    decadeIdx);

            for (int j = 0; j < numberOfBioregions; j++) {
                int group = bsBioregions[j].cardinality();
                if (group > 0) {
                    Integer count = bioMap[j].get(group);
                    bioMap[j].put(group, count == null ? 1 : count + 1);
                }
            }
            for (int j = 0; j < numberOfDecades; j++) {
                int group = bsDecades[j].cardinality();
                if (group > 0) {
                    Integer count = decMap[j].get(group);
                    decMap[j].put(group, count == null ? 1 : count + 1);
                }
            }

            //reset
            for (int j = 0; j < decContinousCounts.length; j++) {
                decContinousCounts[j] = 0;
            }
            //sum
            for (int j = 0; j < numberOfDecades; j++) {
                BitSet bs = bsDecades[j];
                if (bs.cardinality() > 0) {
                    for (int k = 0; k < bs.length(); k++) {
                        if (bs.get(k)) {
                            decContinousCounts[k]++;
                        }
                    }
                }
            }
            //count
            java.util.Arrays.sort(decContinousCounts);
            int count = 1;
            for (int j = 1; j < decContinousCounts.length; j++) {
                if (decContinousCounts[j] == decContinousCounts[j - 1]) {
                    count++;
                } else {
                    Integer c = decCountMap[decContinousCounts[j - 1]].get(count);
                    decCountMap[decContinousCounts[j - 1]].put(count, c == null ? 1 : c + 1);
                    count = 1;
                }
            }
            Integer c = decCountMap[decContinousCounts[decContinousCounts.length - 1]].get(count);
            decCountMap[decContinousCounts[decContinousCounts.length - 1]].put(count, c == null ? 1 : c + 1);
        }

        pos = endPos;
    }

    if (numberOfBioregions > 0) {
        writeBioregions(bioregionName, outputDirectory, columns, bioMap);
    }
    writeDecades(outputDirectory, decadeIdx, decMap);
    writeDecadeCounts(outputDirectory, decCountMap);
}

From source file:edu.udo.scaffoldhunter.model.db.StringProperty.java

/**
 * This will generate a {@link PropertyType}.BitFingerprint.
 * /* w w w.j  a v a2s.c o  m*/
 * Precondition: Only for PropertyType BitFingerprint!
 * 
 * @param bits
 *            the bits in form of a {@link BitSet}
 * @param length
 *            the length as a {@link BitSet} does not save the exact length.
 */
public void setBitFingerprint(BitSet bits, short length) {
    checkBitFingerprint();
    Preconditions.checkArgument(length < Math.pow(2, 16), "length exceeds range");
    Preconditions.checkArgument(length > 0, "A length of zero is not supported");

    // + 1 not full block + 2 size block
    byte[] bitFingerprint = new byte[length / sizeofbyte + ((length % sizeofbyte) > 0 ? 1 : 0) + lengthbytes];

    // convert short to two bytes
    lenghtToBitFingerprint(length, bitFingerprint);

    // bits.lenght is faster because its the position of the highest on bit
    for (int i = 0; i < bits.length(); i++) {
        if (bits.get(i)) {
            // + 1 because the first char contains the size
            bitFingerprint[i / sizeofbyte + lengthbytes] |= 1 << (i % sizeofbyte);
        }
    }

    value = new String(Base64.encodeBase64String(bitFingerprint));
    lengthCache = length;
    bitsCache = (BitSet) bits.clone();
}

From source file:com.google.uzaygezen.core.LongArrayBitVector.java

@Override
public void copyFrom(BitSet from) {
    Preconditions.checkArgument(size >= from.length());
    clear();//www  .j av  a2 s.  co m
    for (int i = from.nextSetBit(0); i >= 0; i = from.nextSetBit(i + 1)) {
        set(i);
    }
    assert checkSanity();
}

From source file:org.lockss.util.NumberUtil.java

/**
 * Construct an alphabetical (base-26) sequence by incrementing the first
 * string alphabetically until it reaches the second string. The start string
 * is incremented by the given delta; if the delta does not divide into the
 * Levenstein distance between the start and end strings, an exception is
 * thrown. The strings must also be the same length.
 * <p>//from  w  w  w . j  a va2s .  co  m
 * The string is lower cased before the increment is applied, and then each
 * character position that was upper case in the original string is upper
 * cased in the resulting string. It is assumed that the two strings are
 * capitalised in the same pattern. An exception will be thrown if any
 * character is outside of a-z after lower casing.
 *
 * @param start an alphabetical string (case-insensitive)
 * @param end an alphabetical string (case-insensitive)
 * @param delta the increment between strings in the sequence; can be negative
 * @return a list of strings representing a sequence from <tt>start</tt> to <tt>end</tt>
 * @throws IllegalArgumentException if the delta does not divide into the gap or the strings are different lengths
 */
public static List<String> constructAlphabeticSequence(final String start, final String end, int delta)
        throws IllegalArgumentException {

    // Ensure the delta is positive
    if (delta == 0)
        throw new IllegalArgumentException("Delta cannot be 0.");

    // If the strings are equal, the sequence will be the single string
    if (start.equals(end))
        return new ArrayList<String>() {
            {
                add(start);
            }
        };

    // Check the string lengths are the same
    if (start.length() != end.length())
        throw new IllegalArgumentException(
                String.format("Start and end strings are different lengths: %s %s.", start, end));

    // Find the integer distance
    int distance = Math.abs(fromBase26(start) - fromBase26(end));
    //int distance = StringUtils.getLevenshteinDistance(start, end);
    // Check the delta divides into the gap
    if (distance % delta != 0) {
        throw new IllegalArgumentException(String.format(
                "The distance %s between start and end must be " + "divisible by delta %s.", distance, delta));
    }

    // Track the case of each character, so we can reset them before returning
    BitSet cases = new BitSet(start.length());
    for (int i = 0; i < start.length(); i++) {
        cases.set(i, Character.isUpperCase(start.charAt(i)));
    }

    // Increment alphabetically
    List<String> seq = new ArrayList<String>();
    int[] nums = constructSequence(fromBase26(start), fromBase26(end), delta);
    for (int i = 0; i < nums.length; i++) {
        String s = toBase26(nums[i]);
        // Pad the string to the correct length with 'a'
        s = StringUtils.leftPad(s, start.length(), 'a');
        // Re-case the chars
        char[] carr = s.toCharArray();
        for (int pos = 0; pos < cases.length(); pos++) {
            if (cases.get(pos))
                carr[pos] = Character.toUpperCase(carr[pos]);
        }
        seq.add(new String(carr));
    }
    return seq;
}

From source file:net.bioclipse.ds.sdk.pdewizard.DSTemplate.java

/**
 * This method duplicates the encoding in the CDKFingerPrintPropertyCalculator. 
 * This is required to read it back into 1024 bits.
 * @param value/*w w  w .  j a v  a  2s. co m*/
 * @return
 */
public String encodeFPBase64(Object value) {
    if (value instanceof String)
        return (String) value;
    BitSet val = (BitSet) value;
    byte[] bytes = new byte[val.length() / 8 + 1];
    for (int i = 0; i < val.length(); i++) {
        if (val.get(i)) {
            bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8);
        }
    }
    return new String(new Base64().encode(bytes));
}

From source file:edu.oregonstate.eecs.mcplan.util.Fn.java

/**
 * Convert a BitSet to a string in which each character represents
 * 'block_size' consecutive bits.//from   w  w w  .  ja v  a 2 s .c  o  m
 * @param bits
 * @param block_size Min 1, max 5
 * @return
 */
public static String toDigits(final BitSet bits, final int block_size) {
    assert (block_size >= 1);
    assert (block_size <= 5);
    final int radix = 1 << block_size;
    final StringBuffer sb = new StringBuffer();
    for (int i = 0; i < bits.length(); i += block_size) {
        int c = 0;
        for (int j = 0; j < block_size; ++j) {
            c |= (bits.get(i + j) ? 1 : 0) << j;
        }
        sb.append(Character.forDigit(c, radix));
    }
    return sb.reverse().toString();
}

From source file:com.google.uzaygezen.core.BitVectorTest.java

private void checkToBigEndianByteArrayAndCopyFromBigEndianAreInverse(Function<Integer, BitVector> factory) {
    Random random = new Random(TestUtils.SEED);
    for (int sizeUpperLimit = 0; sizeUpperLimit < 128; ++sizeUpperLimit) {
        byte[] array = new byte[sizeUpperLimit];
        random.nextBytes(array);/*  ww  w  .  jav  a 2  s .c o  m*/
        BitSet bs = BitSet.valueOf(array);
        ArrayUtils.reverse(array);
        int logicalSize = bs.length();
        int n = MathUtils.bitCountToByteCount(logicalSize);
        for (int i = 0; i < array.length - n; ++i) {
            assert array[i] == 0;
        }
        byte[] bigEndian = Arrays.copyOfRange(array, array.length - n, array.length);
        for (int size = logicalSize; size <= n << 3; ++size) {
            BitVector bv = factory.apply(size);
            bv.copyFromBigEndian(bigEndian);
            byte[] actual = bv.toBigEndianByteArray();
            assertArrayEquals(bigEndian, actual);
        }
    }
}

From source file:org.apache.fop.pdf.PDFFactory.java

private void buildCIDSet(PDFFontDescriptor descriptor, CIDFont cidFont) {
    BitSet cidSubset = cidFont.getCIDSubset().getGlyphIndexBitSet();
    PDFStream cidSet = makeStream(null, true);
    ByteArrayOutputStream baout = new ByteArrayOutputStream(cidSubset.length() / 8 + 1);
    int value = 0;
    for (int i = 0, c = cidSubset.length(); i < c; i++) {
        int shift = i % 8;
        boolean b = cidSubset.get(i);
        if (b) {//from  w w  w. ja  va 2 s . c o m
            value |= 1 << 7 - shift;
        }
        if (shift == 7) {
            baout.write(value);
            value = 0;
        }
    }
    baout.write(value);
    try {
        cidSet.setData(baout.toByteArray());
        descriptor.setCIDSet(cidSet);
    } catch (IOException ioe) {
        log.error("Failed to write CIDSet [" + cidFont + "] " + cidFont.getEmbedFontName(), ioe);
    }
}

From source file:org.apache.openjpa.kernel.StateManagerImpl.java

/**
 * Rollback state of the managed instance to the given savepoint.
 *///from w ww . j av  a2 s.co  m
void rollbackToSavepoint(SavepointFieldManager savepoint) {
    _state = savepoint.getPCState();
    BitSet loaded = savepoint.getLoaded();
    for (int i = 0, len = loaded.length(); i < len; i++) {
        if (loaded.get(i) && savepoint.restoreField(i)) {
            provideField(savepoint.getCopy(), savepoint, i);
            replaceField(_pc, savepoint, i);
        }
    }
    _loaded = loaded;
    _dirty = savepoint.getDirty();
    _flush = savepoint.getFlushed();
    _version = savepoint.getVersion();
    _loadVersion = savepoint.getLoadVersion();
}