Java Code Examples for org.apache.commons.lang3.ArrayUtils#reverse()

The following examples show how to use org.apache.commons.lang3.ArrayUtils#reverse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExpressionKeysTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testStandardTupleKeys() {
	TupleTypeInfo<Tuple7<String, String, String, String, String, String, String>> typeInfo = new TupleTypeInfo<>(
			BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,
			BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO);
	
	ExpressionKeys<Tuple7<String, String, String, String, String, String, String>> ek;
	
	for( int i = 1; i < 8; i++) {
		int[] ints = new int[i];
		for( int j = 0; j < i; j++) {
			ints[j] = j;
		}
		int[] inInts = Arrays.copyOf(ints, ints.length); // copy, just to make sure that the code is not cheating by changing the ints.
		ek = new ExpressionKeys<>(inInts, typeInfo);
		Assert.assertArrayEquals(ints, ek.computeLogicalKeyPositions());
		Assert.assertEquals(ints.length, ek.computeLogicalKeyPositions().length);
		
		ArrayUtils.reverse(ints);
		inInts = Arrays.copyOf(ints, ints.length);
		ek = new ExpressionKeys<>(inInts, typeInfo);
		Assert.assertArrayEquals(ints, ek.computeLogicalKeyPositions());
		Assert.assertEquals(ints.length, ek.computeLogicalKeyPositions().length);
	}
}
 
Example 2
Source File: ExpressionKeysTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Test
public void testStandardTupleKeys() {
	TupleTypeInfo<Tuple7<String, String, String, String, String, String, String>> typeInfo = new TupleTypeInfo<>(
			BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,
			BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO);
	
	ExpressionKeys<Tuple7<String, String, String, String, String, String, String>> ek;
	
	for( int i = 1; i < 8; i++) {
		int[] ints = new int[i];
		for( int j = 0; j < i; j++) {
			ints[j] = j;
		}
		int[] inInts = Arrays.copyOf(ints, ints.length); // copy, just to make sure that the code is not cheating by changing the ints.
		ek = new ExpressionKeys<>(inInts, typeInfo);
		Assert.assertArrayEquals(ints, ek.computeLogicalKeyPositions());
		Assert.assertEquals(ints.length, ek.computeLogicalKeyPositions().length);
		
		ArrayUtils.reverse(ints);
		inInts = Arrays.copyOf(ints, ints.length);
		ek = new ExpressionKeys<>(inInts, typeInfo);
		Assert.assertArrayEquals(ints, ek.computeLogicalKeyPositions());
		Assert.assertEquals(ints.length, ek.computeLogicalKeyPositions().length);
	}
}
 
Example 3
Source File: Utils.java    From jhdf with MIT License 5 votes vote down vote up
/**
 * This method is used when the length required is awkward i.e. no support
 * directly from {@link ByteBuffer}
 *
 * @param buffer to read from
 * @param length the number of bytes to read
 * @return the long value read from the buffer
 * @throws ArithmeticException if the data cannot be safely converted to an
 *                             unsigned long
 */
private static long readArbitraryLengthBytesAsUnsignedLong(ByteBuffer buffer, int length) {
	// Here we will use BigInteger to convert a byte array
	byte[] bytes = new byte[length];
	buffer.get(bytes);
	// BigInteger needs big endian so flip the order if needed
	if (buffer.order() == LITTLE_ENDIAN) {
		ArrayUtils.reverse(bytes);
	}
	// Convert to a unsigned long throws if it overflows
	return new BigInteger(1, bytes).longValueExact();
}
 
Example 4
Source File: PageRangeSetAdapterTest.java    From sejda with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void insertionOrder() {
    PageRange[] inputRanges = { new PageRange(4), new PageRange(6, 9), new PageRange(1, 2) };
    doTestInsertionOrder(inputRanges);
    ArrayUtils.reverse(inputRanges);
    doTestInsertionOrder(inputRanges);
}
 
Example 5
Source File: ArrayUtilsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenArrayUtilsClass_whenCalledreverse_thenCorrect() {
    int[] array1 = {1, 2, 3};
    int[] array2 = {3, 2, 1};
    ArrayUtils.reverse(array1);
    assertThat(array1).isEqualTo(array2);
}
 
Example 6
Source File: ArrayUtilsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenArray_whenReversingElementsWithinARange_thenCorrect() {
    int[] originalArray = { 1, 2, 3, 4, 5 };
    ArrayUtils.reverse(originalArray, 1, 4);
    int[] expectedArray = { 1, 4, 3, 2, 5 };
    assertArrayEquals(expectedArray, originalArray);
}
 
Example 7
Source File: GeoUtils.java    From vertexium with Apache License 2.0 5 votes vote down vote up
private static LinearRing toJtsLinearRing(List<GeoPoint> geoPoints, boolean counterClockwise, boolean lenient) {
    if (geoPoints.size() < 4) {
        throw new VertexiumInvalidShapeException("A polygon must specify at least 4 points for each boundary and hole.");
    }

    Coordinate[] shellCoordinates = geoPoints.stream()
        .map(geoPoint -> new Coordinate(geoPoint.getLongitude(), geoPoint.getLatitude()))
        .toArray(Coordinate[]::new);

    if (!shellCoordinates[0].equals(shellCoordinates[shellCoordinates.length - 1])) {
        if (lenient) {
            LOGGER.info("Closing an unclosed GeoShape by appending the beginning coordinate");
            shellCoordinates = org.apache.commons.lang3.ArrayUtils.add(shellCoordinates, shellCoordinates[0].copy());
        } else {
            throw new VertexiumInvalidShapeException("All polygon boundaries and holes must begin and end at the same point.");
        }
    }
    if (Orientation.isCCW(shellCoordinates) != counterClockwise) {
        if (lenient) {
            LOGGER.info("Reversing the coordinates of a ring that has a backwards orientation");
            ArrayUtils.reverse(shellCoordinates);
        } else {
            throw new VertexiumInvalidShapeException("The outer shell of a polygon must be specified in counter-clockwise " +
                "orientation and all holes must be specified in the clockwise direction.");
        }
    }
    return GEOMETRY_FACTORY.createLinearRing(shellCoordinates);
}
 
Example 8
Source File: AbstractMessages.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Nullable
protected String searchIncludes(Properties properties, String key, Locale locale, Locale truncatedLocale,
                                Set<String> passedPacks) {
    String includesProperty = properties.getProperty("@include");
    if (includesProperty != null) {
        // multiple includes separated by comma
        String[] includes = StringUtils.split(includesProperty, " ,");
        if (includes != null && includes.length > 0) {
            ArrayUtils.reverse(includes);
            for (String includePath : includes) {
                includePath = StringUtils.trimToNull(includePath);
                if (includePath != null) {
                    String message;
                    if (truncatedLocale == null) {
                        message = searchMessage(includePath, key, locale, messageTools.getDefaultLocale(), passedPacks);
                    } else {
                        message = searchMessage(includePath, key, locale, truncatedLocale, passedPacks);
                    }
                    if (message != null) {
                        return message;
                    }
                }
            }
        }
    }
    return null;
}
 
Example 9
Source File: NDCG.java    From pyramid with Apache License 2.0 5 votes vote down vote up
private static double idcg(double[] gradesInRankedList, int truncation){
    //should not sort the original one
    double[] sortedGrades = Arrays.copyOf(gradesInRankedList, gradesInRankedList.length);
    Arrays.sort(sortedGrades);
    ArrayUtils.reverse(sortedGrades);
    return dcg(sortedGrades,truncation);
}
 
Example 10
Source File: MedtronicCnlSession.java    From 600SeriesAndroidUploader with MIT License 5 votes vote down vote up
public byte[] getHMAC() throws NoSuchAlgorithmException {
    String shortSerial = this.stickSerial.replaceAll("\\d+-", "");
    byte[] message = (shortSerial + HMAC_PADDING).getBytes();
    byte[] numArray;

    MessageDigest instance = MessageDigest.getInstance("SHA-256");
    instance.update(message);

    numArray = instance.digest();
    ArrayUtils.reverse(numArray);

    return numArray;
}
 
Example 11
Source File: ArrayUtilsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenArray_whenReversingAllElements_thenCorrect() {
    int[] originalArray = { 1, 2, 3, 4, 5 };
    ArrayUtils.reverse(originalArray);
    int[] expectedArray = { 5, 4, 3, 2, 1 };
    assertArrayEquals(expectedArray, originalArray);
}
 
Example 12
Source File: Utils.java    From jhdf with MIT License 5 votes vote down vote up
/**
 * This method is used when the length required is awkward i.e. no support
 * directly from {@link ByteBuffer}
 *
 * @param buffer to read from
 * @param length the number of bytes to read
 * @return the long value read from the buffer
 * @throws ArithmeticException if the data cannot be safely converted to an
 *                             unsigned long
 */
private static int readArbitraryLengthBytesAsUnsignedInt(ByteBuffer buffer, int length) {
	// Here we will use BigInteger to convert a byte array
	byte[] bytes = new byte[length];
	buffer.get(bytes);
	// BigInteger needs big endian so flip the order if needed
	if (buffer.order() == LITTLE_ENDIAN) {
		ArrayUtils.reverse(bytes);
	}
	// Convert to a unsigned long throws if it overflows
	return new BigInteger(1, bytes).intValueExact();
}
 
Example 13
Source File: RuleMatcher.java    From public-suffix-list with Do What The F*ck You Want To Public License 5 votes vote down vote up
/**
 * Returns the matched public suffix.
 *
 * Matching is case insensitive.
 *
 * @param domain  the domain name, may be null
 * @return the matched public suffix or null
 */
String match(final String domain) {
    if (domain == null) {
        return null;

    }

    String[] reversedDomainLabels = DomainUtil.splitLabels(domain);
    ArrayUtils.reverse(reversedDomainLabels);
    if (reversedDomainLabels.length < reversedLabels.length) {
        return null;

    }

    String[] reversedMatchedLabels = new String[reversedLabels.length];
    for (int i = 0; i < reversedLabels.length; i++) {
        if (i > reversedDomainLabels.length) {
            return null;

        }
        String matchLabel = reversedLabels[i];
        String domainLabel = reversedDomainLabels[i];

        LabelMatcher matcher = new LabelMatcher(matchLabel);
        if (!matcher.isMatch(domainLabel)) {
            return null;

        }
        reversedMatchedLabels[i] = domainLabel;

    }
    ArrayUtils.reverse(reversedMatchedLabels);
    return DomainUtil.joinLabels(reversedMatchedLabels);
}
 
Example 14
Source File: ChecksumAlgorithm.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a long to a little-endian array.
 * 
 * @param l The long to convert.
 * @param numBytes The desired size of the resulting array.  Result is truncated or padded if 
 *                 numBytes is smaller or larger than size of long.
 * @return The little-endian array.
 */
public static byte[] toArray(long l, int numBytes) {
	ByteBuffer buffy = ByteBuffer.allocate(Long.BYTES);
	buffy.putLong(l);
	byte[] checksumArray = new byte[numBytes];
	int n = Math.min(Long.BYTES, numBytes);
	System.arraycopy(buffy.array(), Long.BYTES - n, checksumArray, numBytes - n, n);
	ArrayUtils.reverse(checksumArray);
	return checksumArray;
}
 
Example 15
Source File: StringUtils.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
public static byte[] intToByte(int v, boolean littleEndian) {
	byte[] bytes = new byte[4];
	for (int i = 0; i < 4; i++) {
		bytes[i] = (byte)(0xff & (v >> (i * 8)));
	}
	if (!littleEndian) {
		ArrayUtils.reverse(bytes);
	}
	return bytes;
}
 
Example 16
Source File: PhoenixResultSet.java    From phoenix with Apache License 2.0 4 votes vote down vote up
/**
 * Separate the actual cell data from the serialized list of dynamic column PColumns and
 * return the deserialized list of dynamic column PColumns for the current row
 * @return Deserialized list of dynamic column PColumns or null if there are no dynamic columns
 */
private List<PColumn> getDynColsListAndSeparateFromActualData() {
    Cell base = this.currentRow.getValue(0);
    final byte[] valueArray = CellUtil.cloneValue(base);
    // We inserted the known byte array before appending the serialized list of dynamic columns
    final byte[] anchor = Arrays.copyOf(DYN_COLS_METADATA_CELL_QUALIFIER,
            DYN_COLS_METADATA_CELL_QUALIFIER.length);
    // Reverse the arrays to find the last occurrence of the sub-array in the value array
    ArrayUtils.reverse(valueArray);
    ArrayUtils.reverse(anchor);
    final int pos = valueArray.length - Bytes.indexOf(valueArray, anchor);
    // There are no dynamic columns to process so return immediately
    if (pos >= valueArray.length) {
        return null;
    }
    ArrayUtils.reverse(valueArray);

    // Separate the serialized list of dynamic column PColumns from the actual cell data
    byte[] actualCellDataBytes = Arrays.copyOfRange(valueArray, 0,
            pos - DYN_COLS_METADATA_CELL_QUALIFIER.length);
    ImmutableBytesWritable actualCellData = new ImmutableBytesWritable(actualCellDataBytes);
    ImmutableBytesWritable key = new ImmutableBytesWritable();
    currentRow.getKey(key);
    // Store only the actual cell data as part of the current row
    this.currentRow = new TupleProjector.ProjectedValueTuple(key.get(), key.getOffset(),
            key.getLength(), base.getTimestamp(),
            actualCellData.get(), actualCellData.getOffset(), actualCellData.getLength(), 0);

    byte[] dynColsListBytes = Arrays.copyOfRange(valueArray, pos, valueArray.length);
    List<PColumn> dynCols = new ArrayList<>();
    try {
        List<PTableProtos.PColumn> dynColsProtos = DynamicColumnMetaDataProtos
                .DynamicColumnMetaData.parseFrom(dynColsListBytes).getDynamicColumnsList();
        for (PTableProtos.PColumn colProto : dynColsProtos) {
            dynCols.add(PColumnImpl.createFromProto(colProto));
        }
    } catch (InvalidProtocolBufferException e) {
        return null;
    }
    return dynCols;
}
 
Example 17
Source File: RuleMatcher.java    From public-suffix-list with Do What The F*ck You Want To Public License 4 votes vote down vote up
/**
 * Returns the rule pattern.
 *
 * @return the rule pattern, not null
 */
String getPattern() {
    String[] labels = reversedLabels.clone();
    ArrayUtils.reverse(labels);
    return DomainUtil.joinLabels(labels);
}
 
Example 18
Source File: LiftoverUtils.java    From picard with MIT License 4 votes vote down vote up
/**
 * method to swap the reference and alt alleles of a bi-allelic, SNP
 *
 * @param vc                   the {@link VariantContext} (bi-allelic SNP) that needs to have it's REF and ALT alleles swapped.
 * @param annotationsToReverse INFO field annotations (of double value) that will be reversed (x->1-x)
 * @param annotationsToDrop    INFO field annotations that will be dropped from the result since they are invalid when REF and ALT are swapped
 * @return a new {@link VariantContext} with alleles swapped, INFO fields modified and in the genotypes, GT, AD and PL corrected appropriately
 */
public static VariantContext swapRefAlt(final VariantContext vc, final Collection<String> annotationsToReverse, final Collection<String> annotationsToDrop) {

    if (!vc.isBiallelic() || !vc.isSNP()) {
        throw new IllegalArgumentException("swapRefAlt can only process biallelic, SNPS, found " + vc.toString());
    }

    final VariantContextBuilder swappedBuilder = new VariantContextBuilder(vc);

    swappedBuilder.attribute(SWAPPED_ALLELES, true);

    // Use getBaseString() (rather than the Allele itself) in order to create new Alleles with swapped
    // reference and non-variant attributes
    swappedBuilder.alleles(Arrays.asList(vc.getAlleles().get(1).getBaseString(), vc.getAlleles().get(0).getBaseString()));

    final Map<Allele, Allele> alleleMap = new HashMap<>();

    // A mapping from the old allele to the new allele, to be used when fixing the genotypes
    alleleMap.put(vc.getAlleles().get(0), swappedBuilder.getAlleles().get(1));
    alleleMap.put(vc.getAlleles().get(1), swappedBuilder.getAlleles().get(0));

    final GenotypesContext swappedGenotypes = GenotypesContext.create(vc.getGenotypes().size());
    for (final Genotype genotype : vc.getGenotypes()) {
        final List<Allele> swappedAlleles = new ArrayList<>();
        for (final Allele allele : genotype.getAlleles()) {
            if (allele.isNoCall()) {
                swappedAlleles.add(allele);
            } else {
                swappedAlleles.add(alleleMap.get(allele));
            }
        }
        // Flip AD
        final GenotypeBuilder builder = new GenotypeBuilder(genotype).alleles(swappedAlleles);
        if (genotype.hasAD() && genotype.getAD().length == 2) {
            final int[] ad = ArrayUtils.clone(genotype.getAD());
            ArrayUtils.reverse(ad);
            builder.AD(ad);
        } else {
            builder.noAD();
        }

        //Flip PL
        if (genotype.hasPL() && genotype.getPL().length == 3) {
            final int[] pl = ArrayUtils.clone(genotype.getPL());
            ArrayUtils.reverse(pl);
            builder.PL(pl);
        } else {
            builder.noPL();
        }
        swappedGenotypes.add(builder.make());
    }
    swappedBuilder.genotypes(swappedGenotypes);

    for (final String key : vc.getAttributes().keySet()) {
        if (annotationsToDrop.contains(key)) {
            swappedBuilder.rmAttribute(key);
        } else if (annotationsToReverse.contains(key) && !vc.getAttributeAsString(key, "").equals(VCFConstants.MISSING_VALUE_v4)) {
            final double attributeToReverse = vc.getAttributeAsDouble(key, -1);

            if (attributeToReverse < 0 || attributeToReverse > 1) {
                log.warn("Trying to reverse attribute " + key +
                        " but found value that isn't between 0 and 1: (" + attributeToReverse + ") in variant " + vc + ". Results might be wrong.");
            }
            swappedBuilder.attribute(key, 1 - attributeToReverse);
        }
    }

    return swappedBuilder.make();
}
 
Example 19
Source File: Utils.java    From api with Apache License 2.0 4 votes vote down vote up
public static byte[] toByteArrayLittleEndianUnsigned(BigInteger bi) {
    byte[] extractedBytes = toByteArrayUnsigned(bi);
    ArrayUtils.reverse(extractedBytes);
    //byte[] reversed = ByteUtils.reverseArray(extractedBytes);
    return extractedBytes;
}
 
Example 20
Source File: RuleMatcher.java    From public-suffix-list with Do What The F*ck You Want To Public License 2 votes vote down vote up
/**
 * Sets the rule labels.
 *
 * The labels are stored as a reversed copy in {@link #reversedLabels}.
 *
 * @param labels  the rule labels, not null
 */
RuleMatcher(final String[] labels) {
    this.reversedLabels = labels.clone();
    ArrayUtils.reverse(reversedLabels);
}