Example usage for java.util Arrays copyOfRange

List of usage examples for java.util Arrays copyOfRange

Introduction

In this page you can find the example usage for java.util Arrays copyOfRange.

Prototype

public static boolean[] copyOfRange(boolean[] original, int from, int to) 

Source Link

Document

Copies the specified range of the specified array into a new array.

Usage

From source file:com.opengamma.maths.lowlevelapi.datatypes.primitive.SparseCoordinateFormatMatrix.java

/**
 * Construct from vectors of coordinates with corresponding values
 * @param x x-coordinates of data points (column number)
 * @param y y-coordinates of data points (row number)
 * @param values value of data points (value)
 * @param m the number of rows to implement in the instantiated matrix
 * @param n the number of columns to implement in the instantiated matrix
 *//*from   ww w . j a v  a  2  s .c  o  m*/
public SparseCoordinateFormatMatrix(int[] x, int[] y, double[] values, int m, int n) {
    Validate.notNull(x);
    Validate.notNull(y);
    Validate.notNull(values);
    Validate.isTrue(x.length == y.length,
            "Vector lengths do not match, therefore one to one coordinate pairings do not exist");
    Validate.isTrue(x.length == values.length,
            "Vector lengths do not match, therefore one to one coordinate pairings do not exist");
    Validate.isTrue(m >= 1, "m (number of rows) must be greater than or equal to one");
    Validate.isTrue(n >= 1, "n (number of columns) must be greater than or equal to one");
    Validate.isTrue(Max.value(y) <= m - 1,
            "Number of rows requested (m) is less than the most positive row coordinate");
    Validate.isTrue(Max.value(x) <= n - 1,
            "Number of columns requested (n) is less than the most positive column coordinate");
    _els = x.length;
    // twiddle rows into ascending order
    int[] rowPerm = Sort.getIndex(y);
    int[] localRSx = Permute.stateless(x, rowPerm); // local row sorted X
    int[] localRSy = Permute.stateless(y, rowPerm); // local row sorted Y
    double[] localRSv = Permute.stateless(values, rowPerm); // local row sorted values

    // temp storage
    int[] yTmp = new int[_els];
    int[] xTmp = new int[_els];
    double[] valuesTmp = new double[_els];

    // unique rows and sort (should be sorted anyway)
    int[] yU = Unique.bitwise(localRSy); // unique row indexes
    Sort.valuesInplace(yU, direction.ascend);

    // walk vectors permute as needed assign to tmp Storage
    _maxEntriesInARow = -1;
    int ptr = 0;
    for (int i = 0; i < yU.length; i++) {

        int[] indexesOfXOnThisRow = Find.indexes(localRSy, condition.eq, yU[i]);

        int[] xlocaltmp = View.byIndex(localRSx, indexesOfXOnThisRow);
        int[] xlocaltmpsortedindex = Sort.getIndex(xlocaltmp);
        xlocaltmp = Permute.stateless(xlocaltmp, xlocaltmpsortedindex);
        double[] vlocaltmp = Permute.stateless(View.byIndex(localRSv, indexesOfXOnThisRow),
                xlocaltmpsortedindex);
        Validate.notNull(indexesOfXOnThisRow,
                "Y coordinate given with no corresponding X coordinate, this should never happen");
        for (int j = 0; j < indexesOfXOnThisRow.length; j++) {
            yTmp[ptr] = yU[i];
            xTmp[ptr] = xlocaltmp[j];
            valuesTmp[ptr] = vlocaltmp[j];
            ptr++;
        }
        if (indexesOfXOnThisRow.length > _maxEntriesInARow) {
            _maxEntriesInARow = indexesOfXOnThisRow.length;
        }
    }

    _values = Arrays.copyOfRange(valuesTmp, 0, ptr);
    _x = Arrays.copyOfRange(xTmp, 0, ptr);
    _y = Arrays.copyOfRange(yTmp, 0, ptr);
    _rows = m;
    _cols = n;

}

From source file:com.goncalomb.bukkit.bkglib.bkgcommand.BKgSubCommand.java

List<String> tabComplete(CommandSender sender, String[] args, int argsIndex) {
    // Find sub-command.
    if (argsIndex < args.length) {
        BKgSubCommand subCommand = _subCommands.get(args[argsIndex].toLowerCase());
        if (subCommand != null) {
            return subCommand.tabComplete(sender, args, argsIndex + 1);
        }/*w  ww  .  j  a  v  a  2 s  .  c o  m*/
    }
    // Sub-command not found or no more arguments, let's try to run this one.
    int argsLeft = args.length - argsIndex;
    if (_tabMethod != null) {
        if (argsLeft >= _minArgs && argsLeft <= _maxArgs && _type.isValidSender(sender)
                && sender.hasPermission(_perm)) {
            return invokeTabMethod(sender, Arrays.copyOfRange(args, argsIndex, args.length));
        }
        return null;
    }
    // Tab completion not found, send all sub-commands.
    if (argsLeft == 1) {
        ArrayList<String> allowedCommands = new ArrayList<String>();
        String arg = args[args.length - 1].toLowerCase();
        for (Entry<String, BKgSubCommand> command : _subCommands.entrySet()) {
            String name = command.getKey();
            if (name.startsWith(arg) && command.getValue()._type.isValidSender(sender)) {
                allowedCommands.add(name);
            }
        }
        return allowedCommands;
    }
    return null;
}

From source file:com.jillesvangurp.geo.GeoGeometry.java

/**
 * Points in a cloud are supposed to be close together. Sometimes bad data causes a handful of points out of
 * thousands to be way off. This method filters those out by sorting the coordinates and then discarding the
 * specified percentage.//from   ww w  .  ja v a2s. c om
 *
 * @param points 2d array of points
 * @param percentage percentage of points to discard
 * @return sorted array of points with the specified percentage of elements at the beginning and end of the array removed.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static double[][] filterNoiseFromPointCloud(double[][] points, float percentage) {
    Arrays.sort(points, new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            double[] p1 = (double[]) o1;
            double[] p2 = (double[]) o2;
            if (p1[0] == p2[0]) {
                if (p1[1] > p2[1]) {
                    return 1;
                } else if (p1[1] == p2[1]) {
                    return 0;
                } else {
                    return -1;
                }
            } else if (p1[0] > p2[0]) {
                return 1;
            }
            if (p1[0] == p2[0]) {
                return 0;
            } else {
                return -1;
            }
        }
    });
    int discard = (int) (points.length * percentage / 2);

    return Arrays.copyOfRange(points, discard, points.length - discard);
}

From source file:com.luthfihm.virtualtour.ar.GyroscopeOrientation.java

private void getRotationVectorFromGyro() {
    // Calculate the angular speed of the sample
    float magnitude = (float) Math
            .sqrt(Math.pow(vGyroscope[0], 2) + Math.pow(vGyroscope[1], 2) + Math.pow(vGyroscope[2], 2));

    // Normalize the rotation vector if it's big enough to get the axis
    if (magnitude > EPSILON) {
        vGyroscope[0] /= magnitude;/*  ww  w .j ava 2s . c o m*/
        vGyroscope[1] /= magnitude;
        vGyroscope[2] /= magnitude;
    }

    // Integrate around this axis with the angular speed by the timestep
    // in order to get a delta rotation from this sample over the timestep
    // We will convert this axis-angle representation of the delta rotation
    // into a quaternion before turning it into the rotation matrix.
    float thetaOverTwo = magnitude * dT / 2.0f;
    float sinThetaOverTwo = (float) Math.sin(thetaOverTwo);
    float cosThetaOverTwo = (float) Math.cos(thetaOverTwo);

    deltaVGyroscope[0] = sinThetaOverTwo * vGyroscope[0];
    deltaVGyroscope[1] = sinThetaOverTwo * vGyroscope[1];
    deltaVGyroscope[2] = sinThetaOverTwo * vGyroscope[2];
    deltaVGyroscope[3] = cosThetaOverTwo;

    // Create a new quaternion object base on the latest rotation
    // measurements...
    qGyroscopeDelta = new Quaternion(deltaVGyroscope[3], Arrays.copyOfRange(deltaVGyroscope, 0, 3));

    // Since it is a unit quaternion, we can just multiply the old rotation
    // by the new rotation delta to integrate the rotation.
    qGyroscope = qGyroscope.multiply(qGyroscopeDelta);
}

From source file:com.megster.cordova.rfduino.Peripheral.java

private String getAdvertisingValue(byte[] scanRecord) {

    String advertising = "";

    int i = 0;//w  w w  .  jav a  2 s.c  o  m
    while (i < scanRecord.length) {
        int length = scanRecord[i] & 0xFF;
        if (length == 0) {
            break;
        } // will this really happen?
        i++;
        int type = scanRecord[i] & 0xFF;
        if (type == 0xFF) { // manufacturer data
            // skip the first 2 char (because that's what the rfduino iOS code does)
            byte[] bytes = Arrays.copyOfRange(scanRecord, i + 3, i + length);
            try {
                advertising = new String(bytes, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                advertising = "error";
            }
            break;
        } else {
            i += length;
        }
    }
    return advertising;
}

From source file:net.fenyo.mail4hotspot.dns.Msg.java

public byte[] read(final int pos, final int size) throws GeneralException {
    synchronized (output_buffer) {
        last_use = System.currentTimeMillis();

        if (size == 0 || pos + size > this.output_size)
            throw new GeneralException("output buffer too short");
        return Arrays.copyOfRange(output_buffer, pos, pos + size);
    }//  ww  w .j  ava  2  s.  co m
}

From source file:ch.ethz.matsim.ivt_baseline.counts.StreetCountsLinkIdentification.java

private static List<CountInput> readCountInputs(String pathToCountsInput) {
    List<CountInput> countInputs = new ArrayList<>();
    BufferedReader reader = IOUtils.getBufferedReader(pathToCountsInput, Charset.forName("UTF-8"));
    try {//from  w  w  w . j ava2s .c o m
        reader.readLine(); // read header:
        // countStationID   xCoord_CountStation   yCoord_CountStation   direction   longDirection   latDirection
        String line = reader.readLine();
        while (line != null) {
            String[] lineElements = line.split("\t");
            if (lineElements.length > 6) {
                String[] firstDirection = Arrays.copyOfRange(lineElements, 0, 6);
                countInputs.add(getCountInput(firstDirection));
                String[] secondDirection = ArrayUtils.addAll(Arrays.copyOfRange(lineElements, 0, 3),
                        Arrays.copyOfRange(lineElements, 6, 9));
                countInputs.add(getCountInput(secondDirection));
            } else {
                countInputs.add(getCountInput(lineElements));
            }
            line = reader.readLine();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return countInputs;
}

From source file:ezbake.amino.cli.Main.java

public Main(String[] args) {

    this.cmdLineParser = new CmdLineParser(this);
    if (args.length == 0) {
        // no point in loading the rest, to be faster for the user.
        this.properties = null;
        this.pool = null;
        this.client = null;
        return;/*from  w ww  . j  a  v  a2s  .co m*/
    }

    try {
        int splitAt = getArgumentsOfAt(args);
        if (splitAt == -1) {
            throw new CmdLineException(cmdLineParser, "Command-name required");
        }
        commandName = args[splitAt];
        arguments = ImmutableList.copyOf(Arrays.copyOfRange(args, splitAt + 1, args.length));
        cmdLineParser.parseArgument(ImmutableList.copyOf(Arrays.copyOf(args, splitAt)));
    } catch (CmdLineException e) {
        System.out.println(e.getMessage());
        this.properties = null;
        this.pool = null;
        this.client = null;
        return;
    }

    this.properties = createEzConf();
    this.pool = new ThriftClientPool(properties);
    try {
        logger.info("Getting Thrift client from pool for amino:amino");
        this.client = pool.getClient("amino", "amino", AminoService.Client.class);
    } catch (final TException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.asakusafw.runtime.io.text.directio.AbstractTextStreamFormatTest.java

/**
 * input - w/ header./*from  w w w  .  j  av  a 2  s .  c om*/
 * @throws Exception if failed
 */
@Test
public void input_hedaer_split_rest() throws Exception {
    MockFormat format = format(3, HeaderType.FORCE).withInputSplitter(InputSplitters.byLineFeed());
    String[][] data = { { "A", "B", "C", }, { "D", "E", "F", }, { "G", "H", "I", }, };
    try (ModelInput<String[]> in = format.createInput(String[].class, "dummy", input(data), 1,
            Long.MAX_VALUE)) {
        String[][] result = collect(3, in);
        assertThat(result, is(Arrays.copyOfRange(data, 1, 3)));
    }
}

From source file:com.itemanalysis.psychometrics.irt.estimation.ItemLogLikelihood.java

/**
 * This numeric calculation of the Hessian is used to compute standard errors for the
 * item parameter estimates. It uses the analytic derivatives in the calculation.
 *
 * @param x item parameter array/*from   ww w.j  a  va2  s .c o m*/
 * @return
 */
private double[][] numericHessian(double[] x) {
    //        double EPSILON = 1e-8;
    int n = x.length;
    double[][] hessian = new double[n][n];
    double[] gradientAtXpls = null;
    double[] gradientAtX = derivativeAt(x);//analytic derivative
    double xtemp = 0.0;
    double stepSize = 0.0001;

    for (int j = 0; j < n; j++) {
        stepSize = Math.sqrt(EPSILON) * (Math.abs(x[j]) + 1.0);//from SAS manual on nlp procedure
        xtemp = x[j];
        x[j] = xtemp + stepSize;
        double[] x_copy = Arrays.copyOfRange(x, 0, x.length);
        gradientAtXpls = derivativeAt(x_copy);//analytic derivative
        x[j] = xtemp;
        for (int i = 0; i < n; i++) {
            hessian[i][j] = (gradientAtXpls[i] - gradientAtX[i]) / stepSize;
        }
    }
    return hessian;
}