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:net.lethargiclion.informaban.InformaBanCommandExecutor.java

/**
 * Handles the /kick command./*from   www .  ja v a2s.  c  o  m*/
 * 
 * @param sender
 *            The CommandSender executing this command.
 * @param args
 *            The command arguments.
 * @return False if a usage message should be displayed.
 */
private boolean commandKick(CommandSender sender, String[] args) {
    if (args.length == 1)
        sender.sendMessage(plugin.messages.getString("command.kick.reasonRequired"));
    if (args.length > 1) {
        Player victim = sender.getServer().getPlayer(args[0]);
        if (victim != null) {
            // Set up kick message
            String banReason = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), ' ');

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

            // Do the kick and record it
            Kick k = new Kick();
            k.apply(plugin.messages, victim, sender, banReason);
            plugin.getDatabase().insert(k);
        } else
            sender.sendMessage(plugin.messages.getString("error.playerNotFound"));
        return true;
    }
    return false;
}

From source file:cc.arduino.plugins.wifi101.flashers.java.NinaFlasher.java

@Override
public void updateFirmware(String port) throws Exception {
    FlasherSerialClient client = null;/*from   w  w  w. j  a  v  a2s. c  o m*/
    try {
        file = openFirmwareFile();
        progress(10, "Connecting to programmer...");
        client = new FlasherSerialClient();
        client.open(port, this.baudrate);
        client.hello();
        int maxPayload = client.getMaximumPayload();

        byte[] fwData = this.getData();
        int size = fwData.length;
        int address = 0x00000000;
        int written = 0;

        progress(20, "Erasing target...");

        client.eraseFlash(address, size);

        while (written < size) {
            progress(20 + written * 40 / size, "Programming " + size + " bytes ...");
            int len = maxPayload;
            if (written + len > size) {
                len = size - written;
            }
            client.writeFlash(address, Arrays.copyOfRange(fwData, written, written + len));
            written += len;
            address += len;
        }

        progress(55, "Verifying...");

        md5Checksum = getMD5Checksum(fwData);

        address = 0x00000000;
        byte[] md5rec = client.md5Flash(address, size);
        progress(75, "Verifying...");
        if (Arrays.equals(md5rec, md5Checksum)) {
            progress(100, "Done!");
        } else {
            throw new Exception("Error validating flashed firmware");
        }
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:com.itemanalysis.psychometrics.analysis.AbstractDiffFunction.java

/**
 * Numerically compute Hessian using a finite difference method. Override this
 * method when the analytic Hessian is available.
 *
 * @param x/*from   w  w w  .  j  a  v  a  2 s .  c o m*/
 * @return
 */
public RealMatrix hessianAt(double[] x) {
    int n = x.length;
    double[][] hessian = new double[n][n];
    double[] gradientAtXpls = null;
    double[] gradientAtX = gradient(x);
    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 = gradient(x_copy);
        x[j] = xtemp;
        for (int i = 0; i < n; i++) {
            hessian[i][j] = (gradientAtXpls[i] - gradientAtX[i]) / stepSize;
        }
    }
    RealMatrix m = new Array2DRowRealMatrix(hessian);
    return m;
}

From source file:com.continuuity.loom.common.queue.internal.ElementsTrackingQueueCliTool.java

public String configure(String args[]) throws ParseException {
    Preconditions.checkArgument(args.length >= 1, "Not enough arguments");
    boolean knownCommand = AVAILABLE_COMMANDS.contains(args[0]);
    Preconditions.checkArgument(knownCommand, "Unknown Command specified: " + args[0]);

    String sentCommand = args[0];

    CommandLineParser commandLineParser = new GnuParser();

    Options options = new Options();

    options.addOption("e", ARG_OPT_ELEMENT, true, "Element Id.");
    options.addOption("z", ARG_OPT_ZK_CONNECTION, true, "ZK Connection String.");
    options.addOption("q", ARG_OPT_QUEUE_NAME, true, "Queue Name.");

    CommandLine commandLine = null;/* w  ww  .ja v  a 2s.c o m*/

    commandLine = commandLineParser.parse(options, Arrays.copyOfRange(args, 1, args.length));

    //Check if the appropriate args are passed in for each of the commands
    if (CMD_HELP.equals(sentCommand)) {
        // NO params needed
        printHelp();
    }
    if (CMD_LIST.equals(sentCommand)) {
        // NO params needed
    }
    if (CMD_REMOVE_ALL.equals(sentCommand)) {
        // NO params needed
    }
    if (CMD_REMOVE.equals(sentCommand)) {
        Preconditions.checkArgument(commandLine.hasOption(ARG_OPT_ELEMENT),
                CMD_REMOVE + " command should have " + "element argument");
        this.elementId = commandLine.getOptionValue(ARG_OPT_ELEMENT);
    }
    if (CMD_PROMOTE.equals(sentCommand)) {
        Preconditions.checkArgument(commandLine.hasOption(ARG_OPT_ELEMENT),
                CMD_PROMOTE + " command should have " + "element argument");
        elementId = commandLine.getOptionValue(ARG_OPT_ELEMENT);
    }

    Preconditions.checkArgument(commandLine.hasOption(ARG_OPT_ZK_CONNECTION),
            ARG_OPT_ZK_CONNECTION + " must be specified");
    Preconditions.checkArgument(commandLine.hasOption(ARG_OPT_QUEUE_NAME),
            ARG_OPT_QUEUE_NAME + " must be specified");
    zkConnectionString = commandLine.getOptionValue(ARG_OPT_ZK_CONNECTION);
    queueName = commandLine.getOptionValue(ARG_OPT_QUEUE_NAME);

    command = sentCommand;

    return command;
}

From source file:com.kazuki43zoo.apistub.api.key.FixedLengthKeyExtractor.java

@Override
public List<Object> extract(HttpServletRequest request, byte[] requestBody, String... expressions) {
    if (requestBody == null || requestBody.length == 0) {
        return Collections.emptyList();
    }/*from  w  w  w.jav a  2  s .c  o m*/

    Charset defaultCharset = Optional.ofNullable(request.getContentType()).map(MediaType::parseMediaType)
            .map(MediaType::getCharset).orElse(StandardCharsets.UTF_8);

    return Stream.of(expressions).map(expression -> {
        String[] defines = StringUtils.splitByWholeSeparatorPreserveAllTokens(expression, ",");
        if (defines.length <= 2) {
            return null;
        }
        int offset = Integer.parseInt(defines[0].trim());
        int length = Integer.parseInt(defines[1].trim());
        String type = defines[2].trim().toLowerCase();
        final Charset charset;
        if (defines.length >= 4) {
            charset = Charset.forName(defines[3].trim());
        } else {
            charset = defaultCharset;
        }
        if (!(requestBody.length >= offset && requestBody.length >= offset + length)) {
            return null;
        }
        return Optional.ofNullable(FUNCTIONS.get(type)).orElseThrow(() -> new IllegalArgumentException(
                "A bad expression is detected. The specified type does not support. expression: '" + expression
                        + "', specified type: '" + type + "', allowing types: " + FUNCTIONS.keySet()))
                .apply(Arrays.copyOfRange(requestBody, offset, offset + length), charset);
    }).filter(Objects::nonNull).collect(Collectors.toList());
}

From source file:com.palantir.atlasdb.keyvalue.rocksdb.impl.RocksDbKeyValueServices.java

static Pair<Cell, Long> parseCellAndTs(byte[] key) {
    byte[] rowSizeBytes = new byte[2];
    rowSizeBytes[0] = key[key.length - 1];
    rowSizeBytes[1] = key[key.length - 2];

    int rowSize = (int) EncodingUtils.decodeVarLong(rowSizeBytes);
    int colEnd = key.length - 8 - EncodingUtils.sizeOfVarLong(rowSize);

    byte[] rowName = Arrays.copyOf(key, rowSize);
    byte[] colName = Arrays.copyOfRange(key, rowSize, colEnd);
    long ts = Longs.fromBytes(key[colEnd + 0], key[colEnd + 1], key[colEnd + 2], key[colEnd + 3],
            key[colEnd + 4], key[colEnd + 5], key[colEnd + 6], key[colEnd + 7]);

    return Pair.create(Cell.create(rowName, colName), ts);
}

From source file:uk.ac.ebi.eva.server.ws.VariantWSServer.java

@RequestMapping(value = "/{variantId}/info", method = RequestMethod.GET)
//    @ApiOperation(httpMethod = "GET", value = "Retrieves the information about a variant", response = QueryResponse.class)
public QueryResponse getVariantById(@PathVariable("variantId") String variantId,
        @RequestParam(name = "studies", required = false) List<String> studies,
        @RequestParam("species") String species, HttpServletResponse response)
        throws IllegalOpenCGACredentialsException, UnknownHostException, IOException {
    initializeQueryOptions();/*w  w w.  j  av  a2s . c  o m*/

    VariantDBAdaptor variantMongoDbAdaptor = DBAdaptorConnector.getVariantDBAdaptor(species);

    if (studies != null && !studies.isEmpty()) {
        queryOptions.put("studies", studies);
    }

    if (!variantId.contains(":")) { // Query by accession id
        return setQueryResponse(variantMongoDbAdaptor.getVariantById(variantId, queryOptions));
    } else { // Query by chr:pos:ref:alt
        String parts[] = variantId.split(":", -1);
        if (parts.length < 3) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return setQueryResponse(
                    "Invalid position and alleles combination, please use chr:pos:ref or chr:pos:ref:alt");
        }

        Region region = new Region(parts[0], Integer.parseInt(parts[1]), Integer.parseInt(parts[1]));
        queryOptions.put("reference", parts[2]);
        if (parts.length > 3) {
            queryOptions.put("alternate", String.join(":", Arrays.copyOfRange(parts, 3, parts.length)));
        }

        return setQueryResponse(variantMongoDbAdaptor.getAllVariantsByRegion(region, queryOptions));
    }
}

From source file:com.itemanalysis.psychometrics.analysis.AbstractMultivariateFunction.java

/**
 * Numerically compute Hessian using a finite difference method. Override this
 * method when the analytic Hessian is available.
 *
 * @param x//from ww w .j a  v a 2 s .com
 * @return
 */
public RealMatrix hessianAt(double[] x) {
    int n = x.length;
    double[][] hessian = new double[n][n];
    double[] gradientAtXpls = null;
    double[] gradientAtX = gradientAt(x);
    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 = gradientAt(x_copy);
        x[j] = xtemp;
        for (int i = 0; i < n; i++) {
            hessian[i][j] = (gradientAtXpls[i] - gradientAtX[i]) / stepSize;
        }
    }
    RealMatrix m = new Array2DRowRealMatrix(hessian);
    return m;
}

From source file:gobblin.runtime.cli.PublicMethodsCliObjectFactory.java

@Override
public T buildObject(String[] args, int offset, boolean printUsage, String usage) throws IOException {
    Options options = new Options();
    options.addOption(HELP);//from   w w  w .  jav a 2s  .  co m
    options.addOption(USE_LOG);
    for (Option opt : getOptions().getOptions()) {
        options.addOption(opt);
    }

    CommandLine cli;
    try {
        CommandLineParser parser = new DefaultParser();
        cli = parser.parse(options, Arrays.copyOfRange(args, offset, args.length));
    } catch (ParseException pe) {
        if (printUsage) {
            System.out.println("Command line parse exception: " + pe.getMessage());
            printUsage(usage, options);
        }
        throw new IOException(pe);
    }

    if (cli.hasOption(HELP.getOpt())) {
        if (printUsage) {
            printUsage(usage, options);
        }
        throw new HelpArgumentFound();
    }

    try {
        return buildObject(cli);
    } catch (Throwable t) {
        if (cli.hasOption(USE_LOG.getOpt())) {
            log.error("Failed to instantiate " + this.klazz.getName(), t);
        } else {
            System.out.println("Error: " + t.getMessage());
        }
        if (printUsage) {
            printUsage(usage, options);
        }
        throw new IOException(t);
    }
}

From source file:bb.mcmc.analysis.ConvergeStatUtils.java

protected static int[][] create2WaysContingencyTable(boolean[] testres, int newDim) {

    final boolean[] b1 = Arrays.copyOfRange(testres, 0, newDim - 1);
    final boolean[] b2 = Arrays.copyOfRange(testres, 1, newDim);

    final int table[][] = new int[][] { { 0, 0 }, { 0, 0 } };

    for (int i = 0; i < b1.length; i++) {
        if (b1[i] && b2[i]) {
            table[1][1] += 1;//from ww  w  .  j a v a  2  s . c om
        } else if (!b1[i] && b2[i]) {
            table[0][1] += 1;
        } else if (b1[i] && !b2[i]) {
            table[1][0] += 1;
        } else if (!b1[i] && !b2[i]) {
            table[0][0] += 1;
        }
    }
    return table;

}