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.CompressedSparseColumnFormatMatrix.java

/**
 * Construct from SparseCoordinateFormatMatrix type
 * @param m is a SparseCoordinateFormatMatrix
 *///  w  ww  . j  ava 2s  .  c om
public CompressedSparseColumnFormatMatrix(SparseCoordinateFormatMatrix m) {
    Validate.notNull(m);
    _els = m.getNumberOfElements();
    int[] colPtrTmp = new int[_els];
    int[] rowIdxTmp = new int[_els];
    double[] valuesTmp = new double[_els];
    double val;
    int ptr = 0, i;
    int localMaxEntrisInACol;
    _maxEntriesInAColumn = -1;
    for (i = 0; i < m.getNumberOfColumns(); i++) {
        colPtrTmp[i] = ptr;
        localMaxEntrisInACol = 0;
        for (int j = 0; j < m.getNumberOfRows(); j++) {
            val = m.getEntry(j, i);
            if (Double.doubleToLongBits(val) != 0L) {
                valuesTmp[ptr] = val;
                rowIdxTmp[ptr] = j;
                ptr++;
                localMaxEntrisInACol++;
            }
        }
        if (localMaxEntrisInACol > _maxEntriesInAColumn) {
            _maxEntriesInAColumn = localMaxEntrisInACol;
        }
    }
    colPtrTmp[i] = ptr; // adds in last entry to close access fields

    _values = Arrays.copyOfRange(valuesTmp, 0, ptr);
    _rowIdx = Arrays.copyOfRange(rowIdxTmp, 0, ptr);
    _colPtr = Arrays.copyOfRange(colPtrTmp, 0, i + 1); // yes, the +1 is correct!
    _rows = m.getNumberOfRows();
    _cols = m.getNumberOfColumns();
}

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

/**
 * Construct from SparseCoordinateFormatMatrix type
 * @param m is a SparseCoordinateFormatMatrix
 *//*  w w  w.jav a 2  s.c o m*/
public CompressedSparseRowFormatMatrix(SparseCoordinateFormatMatrix m) {
    Validate.notNull(m);
    _els = m.getNumberOfElements();
    int[] rowPtrTmp = new int[_els > 1 ? _els : 2];
    int localmaxEntriesInARow;
    _maxEntriesInARow = -1; // set max entries in a row negative, so that maximiser will work
    int ptr = 0;
    int i;
    for (i = 0; i < m.getNumberOfRows(); i++) {
        rowPtrTmp[i] = ptr;
        localmaxEntriesInARow = 0;
        for (int j = 0; j < m.getNumberOfColumns(); j++) {
            if (Double.doubleToLongBits(m.getEntry(i, j)) != 0L) {
                localmaxEntriesInARow++;
                ptr++;
            }
        }
        if (localmaxEntriesInARow > _maxEntriesInARow) { // is the number of entries on this row the largest?
            _maxEntriesInARow = localmaxEntriesInARow;
        }
    }
    rowPtrTmp[i] = ptr;
    _values = Arrays.copyOfRange(m.getNonZeroEntries(), 0, ptr);
    _colIdx = Arrays.copyOfRange(m.getColumnCoordinates(), 0, ptr);
    _rowPtr = Arrays.copyOfRange(rowPtrTmp, 0, i + 1); // yes, the +1 is correct!
    _rows = m.getNumberOfRows();
    _cols = m.getNumberOfColumns();
}

From source file:de.nx42.maps4cim.map.texture.osm.OsmHash.java

protected static String getQueryHashEntities(List<EntityDef> entities) {
    Hasher h = hf.newHasher();/* w w  w.  j a  va2s  .  c  om*/

    // add query
    for (EntityDef def : entities) {
        h.putInt(def.hashCode());
    }

    // get hash, cap length
    byte[] hash = h.hash().asBytes();
    if (hash.length > 4) {
        hash = Arrays.copyOfRange(hash, 0, 3);
    }

    // return hash, max 4 byte (6 chars)
    return Base64.encodeBase64URLSafeString(hash);
}

From source file:com.datatorrent.contrib.hdht.HDHTFileAccessTest.java

private void testSeqRead(long bucketKey, FileAccessFSImpl hfa, String fileName) throws IOException {
    FileAccess.FileReader in = hfa.getReader(bucketKey, fileName);
    Slice tkey = new Slice(null, 0, 0);
    Slice tvalue = new Slice(null, 0, 0);
    for (int i = 0; i < keys.length; i++) {
        assertTrue("If the cursor is currently not at the end. Next() method should return true ",
                in.next(tkey, tvalue));//from w  w w  .  ja  va2  s .  co  m
        assertArrayEquals("Key is not as expected", keys[i],
                Arrays.copyOfRange(tkey.buffer, tkey.offset, tkey.offset + tkey.length));
        assertArrayEquals("Value is not as expected", values[i].getBytes(),
                Arrays.copyOfRange(tvalue.buffer, tvalue.offset, tvalue.offset + tvalue.length));
    }
    assertFalse("Should return false because cursor is at the end", in.next(tkey, tvalue));
    in.close();
}

From source file:net.lethargiclion.informaban.InformaBanCommandExecutor.java

/**
 * Handles the /ban command.//from  w  w  w .j av  a 2  s.  co  m
 * 
 * @param sender
 *            The CommandSender executing this command.
 * @param args
 *            The command arguments.
 * @return False if a usage message should be displayed.
 */
private boolean commandBan(CommandSender sender, String[] args) {
    if (args.length == 1)
        sender.sendMessage(plugin.messages.getString("command.ban.reasonRequired"));
    if (args.length > 1) {
        Player victim = sender.getServer().getPlayer(args[0]);
        if (victim != null) {
            // Set up ban message
            String banReason = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), ' ');

            // Log ban to console
            plugin.getLogger().info(MessageFormat.format(plugin.messages.getString("command.ban.consoleLog"),
                    new Object[] { sender.getName(), victim.getName() }));

            // Do the ban and record it
            Ban b = new Ban();
            b.apply(plugin.messages, victim, sender, banReason, Ban.PERMANENT);
            plugin.getDatabase().insert(b); // Record the banning event
            plugin.getDatabase().insert(b.makeActiveEvent()); // Set the actual ban
        } else
            sender.sendMessage(plugin.messages.getString("error.playerNotFound"));
        return true;
    }
    return false;
}

From source file:edu.iu.daal_subgraph.Graph.java

/**
 * @brief get adj vertices by absolute v_id
 *
 * @param v/*from www .  ja v  a2 s  .c  o m*/
 *
 * @return 
 */
int[] adjacent_vertices_abs(int v) {
    //return (&adjacency_array[degree_list[v]]);
    //this doesn't return original array.
    //Be aware of the difference
    int local_id = this.vertex_local_ids[v];
    if (local_id >= 0)
        return Arrays.copyOfRange(adjacency_array, degree_list[local_id], degree_list[local_id + 1]);
    else
        return null;
}

From source file:com.facebook.presto.accumulo.tools.Main.java

@SuppressWarnings("unchecked")
@Override//  w w  w  . ja v  a  2s.  c  om
public int run(String[] args) throws Exception {
    // If no arguments, print help
    if (args.length == 0) {
        printTools();
        return 1;
    }

    // Get the tool name from the first argument
    String toolName = args[0];
    Task t = Main.getTask(toolName);
    if (t == null) {
        System.err.println(format("Unknown tool %s", toolName));
        printTools();
        return 1;
    }

    // Add the help option and all options for the tool
    Options opts = new Options();
    opts.addOption(HELP);
    opts.addOption(CONFIG);
    for (Option o : (Collection<Option>) t.getOptions().getOptions()) {
        opts.addOption(o);
    }

    // Parse command lines
    CommandLine cmd;
    try {
        cmd = new GnuParser().parse(opts, Arrays.copyOfRange(args, 1, args.length));
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        printHelp(t);
        return 1;
    }

    // Print help if the option is set
    if (cmd.hasOption(HELP.getLongOpt())) {
        printHelp(t);
        return 0;
    } else {
        AccumuloConfig config;
        if (cmd.hasOption(CONFIG.getLongOpt())) {
            config = fromFile(new File(cmd.getOptionValue(CONFIG.getLongOpt())));
        } else {
            // Validate PRESTO_HOME is set to pull accumulo properties from config path
            String prestoHome = System.getenv("PRESTO_HOME");
            if (prestoHome == null) {
                System.err.println(
                        "PRESTO_HOME is not set.  This is required to locate the etc/catalog/accumulo.properties file, or use --config option");
                System.exit(1);
            }

            // Create an AccumuloConfig from the accumulo properties file
            config = fromFile(new File(System.getenv("PRESTO_HOME"), "etc/catalog/accumulo.properties"));
        }

        // Run the tool and print help if anything bad happens
        int code = t.run(config, cmd);
        if (code != 0) {
            printHelp(t);
        }
        return code;
    }
}

From source file:org.apache.streams.data.util.JsonUtil.java

/**
 * Creates an empty array if missing/*from  w  w  w . j a v a  2  s  .  com*/
 * @param node objectnode to create the object within
 * @param field location to create the object
 * @return the Map representing the extensions property
 */
public static ObjectNode ensureObject(ObjectNode node, String field) {
    String[] path = Lists.newArrayList(Splitter.on('.').split(field)).toArray(new String[0]);
    ObjectNode current = node;
    ObjectNode result = null;
    for (int i = 0; i < path.length; i++) {
        if (node.get(field) == null)
            node.put(field, mapper.createObjectNode());
        current = (ObjectNode) node.get(field);
    }
    result = ensureObject((ObjectNode) node.get(path[path.length]),
            Joiner.on('.').join(Arrays.copyOfRange(path, 1, path.length)));
    return result;
}

From source file:ch.entwine.weblounge.kernel.command.SiteCommand.java

/**
 * Command signature that allows to do//from ww  w.ja v  a 2s  .  c  o m
 * <ul>
 * <li><code>site list</code></li>
 * <li><code>site &lt;id&gt; start</code></li>
 * <li><code>site &lt;id&gt; stop</code></li>
 * <li><code>site &lt;id&gt; restart</code></li>
 * <li><code>site &lt;id&gt; enable</code></li>
 * <li><code>site &lt;id&gt; disable</code></li>
 * <li><code>site &lt;id&gt; index</code></li>
 * <li><code>site &lt;id&gt; status</code></li>
 * <li><code>site &lt;id&gt; inspect &lt;url&gt;</code></li>
 * <li><code>site &lt;id&gt; search &lt;terms&gt;</code></li>
 * </ul>
 * 
 * @param args
 *          the list of arguments to this command
 */
public void site(String[] args) {
    if (args.length == 0) {
        list();
        return;
    } else if (args.length == 1) {
        if ("list".equals(args[0])) {
            list();
        } else {
            printUsage();
        }
    } else if (args.length > 1) {
        String id = args[0];

        // Look up the site
        Site site = getSite(id);
        if (site == null) {
            try {
                site = getSite(Integer.parseInt(id));
                if (site == null) {
                    System.out.println("Unknown site: " + id);
                    return;
                }
            } catch (NumberFormatException e) {
                System.out.println("Unknown site: " + id);
                return;
            }
        }

        // Process the command
        if ("start".equals(args[1]))
            start(site);
        else if ("stop".equals(args[1]))
            stop(site);
        else if ("restart".equals(args[1]))
            restart(site);
        else if ("index".equals(args[1]))
            index(site);
        else if ("status".equals(args[1]))
            status(site);
        else if ("inspect".equals(args[1]))
            inspect(site, Arrays.copyOfRange(args, 2, args.length));
        else if ("search".equals(args[1])) {
            search(site, Arrays.copyOfRange(args, 2, args.length));
        } else {
            System.out.println("Unknown command: " + args[1]);
            return;
        }
    } else {
        printUsage();
    }
}

From source file:hivemall.anomaly.SDAR2D.java

/**
 * @param x series of input in LIFO order
 * @param k AR window size/* www .j av a  2  s.c om*/
 * @return x_hat predicted x
 * @link https://en.wikipedia.org/wiki/Matrix_multiplication#Outer_product
 */
@Nonnull
public RealVector update(@Nonnull final ArrayRealVector[] x, final int k) {
    Preconditions.checkArgument(x.length >= 1, "x.length MUST be greater than 1: " + x.length);
    Preconditions.checkArgument(k >= 0, "k MUST be greater than or equals to 0: ", k);
    Preconditions.checkArgument(k < _C.length,
            "k MUST be less than |C| but " + "k=" + k + ", |C|=" + _C.length);

    final ArrayRealVector x_t = x[0];
    final int dims = x_t.getDimension();

    if (_initialized == false) {
        this._mu = x_t.copy();
        this._sigma = new BlockRealMatrix(dims, dims);
        assert (_sigma.isSquare());
        this._initialized = true;
        return new ArrayRealVector(dims);
    }
    Preconditions.checkArgument(k >= 1, "k MUST be greater than 0: ", k);

    // old parameters are accessible to compute the Hellinger distance
    this._muOld = _mu.copy();
    this._sigmaOld = _sigma.copy();

    // update mean vector
    // \hat{mu} := (1-r) \hat{} + r x_t
    this._mu = _mu.mapMultiply(1.d - _r).add(x_t.mapMultiply(_r));

    // compute residuals (x - \hat{})
    final RealVector[] xResidual = new RealVector[k + 1];
    for (int j = 0; j <= k; j++) {
        xResidual[j] = x[j].subtract(_mu);
    }

    // update covariance matrices
    // C_j := (1-r) C_j + r (x_t - \hat{}) (x_{t-j} - \hat{})'
    final RealMatrix[] C = this._C;
    final RealVector rxResidual0 = xResidual[0].mapMultiply(_r); // r (x_t - \hat{})
    for (int j = 0; j <= k; j++) {
        RealMatrix Cj = C[j];
        if (Cj == null) {
            C[j] = rxResidual0.outerProduct(x[j].subtract(_mu));
        } else {
            C[j] = Cj.scalarMultiply(1.d - _r).add(rxResidual0.outerProduct(x[j].subtract(_mu)));
        }
    }

    // solve A in the following Yule-Walker equation
    // C_j = _{i=1}^{k} A_i C_{j-i} where j = 1..k, C_{-i} = C_i'
    /*
     * /C_1\     /A_1\  /C_0     |C_1'    |C_2'    | .  .  .   |C_{k-1}' \
     * |---|     |---|  |--------+--------+--------+           +---------|
     * |C_2|     |A_2|  |C_1     |C_0     |C_1'    |               .     |
     * |---|     |---|  |--------+--------+--------+               .     |
     * |C_3|  =  |A_3|  |C_2     |C_1     |C_0     |               .     |
     * | . |     | . |  |--------+--------+--------+                     |
     * | . |     | . |  |   .                            .               |
     * | . |     | . |  |   .                            .               |
     * |---|     |---|  |--------+                              +--------|
     * \C_k/     \A_k/  \C_{k-1} | .  .  .                      |C_0     /
     */
    RealMatrix[][] rhs = MatrixUtils.toeplitz(C, k);
    RealMatrix[] lhs = Arrays.copyOfRange(C, 1, k + 1);
    RealMatrix R = MatrixUtils.combinedMatrices(rhs, dims);
    RealMatrix L = MatrixUtils.combinedMatrices(lhs);
    RealMatrix A = MatrixUtils.solve(L, R, false);

    // estimate x
    // \hat{x} = \hat{} + _{i=1}^k A_i (x_{t-i} - \hat{})
    RealVector x_hat = _mu.copy();
    for (int i = 0; i < k; i++) {
        int offset = i * dims;
        RealMatrix Ai = A.getSubMatrix(offset, offset + dims - 1, 0, dims - 1);
        x_hat = x_hat.add(Ai.operate(xResidual[i + 1]));
    }

    // update model covariance
    //  := (1-r)  + r (x - \hat{x}) (x - \hat{x})'
    RealVector xEstimateResidual = x_t.subtract(x_hat);
    this._sigma = _sigma.scalarMultiply(1.d - _r)
            .add(xEstimateResidual.mapMultiply(_r).outerProduct(xEstimateResidual));

    return x_hat;
}