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

/**
 * Construct from DoubleMatrix2D type/*  w w w.j  a v  a2s .c  om*/
 * @param m is a DoubleMatrix2D
 */
public CompressedSparseRowFormatMatrix(DoubleMatrix2D m) {
    Validate.notNull(m);

    //get number of elements
    _els = m.getNumberOfElements();

    // tmp arrays, in case we get in a fully populated matrix, intelligent design upstream should ensure that this is overkill!
    double[] dataTmp = new double[_els];
    int[] colIndTmp = new int[_els];
    int[] rowPtrTmp = new int[_els + 1];

    // we need unwind the array m into coordinate form
    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++;
                colIndTmp[ptr] = j;
                dataTmp[ptr] = m.getEntry(i, j);
                ptr++;
            }
        }
        if (localmaxEntriesInARow > _maxEntriesInARow) { // is the number of entries on this row the largest?
            _maxEntriesInARow = localmaxEntriesInARow;
        }
    }
    rowPtrTmp[i] = ptr;

    // return correct 0 to correct length of the vector buffers
    _values = Arrays.copyOfRange(dataTmp, 0, ptr);
    _colIdx = Arrays.copyOfRange(colIndTmp, 0, ptr);
    _rowPtr = Arrays.copyOfRange(rowPtrTmp, 0, i + 1); // yes, the +1 is correct, it allows the computation of the number of elements in the final row!
    _rows = m.getNumberOfRows();
    _cols = m.getNumberOfColumns();
}

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

/**
 * Construct from DoubleMatrix2D type//  w  w w.  jav  a 2  s  . c om
 * @param aMatrix is a DoubleMatrix2D
 */
public SparseCoordinateFormatMatrix(final DoubleMatrix2D aMatrix) {
    Validate.notNull(aMatrix);

    //get number of elements
    _els = aMatrix.getNumberOfElements();

    // tmp arrays, in case we get in a fully populated matrix, intelligent design upstream should ensure that this is overkill!
    double[] valuesTmp = new double[_els];
    int[] xTmp = new int[_els];
    int[] yTmp = new int[_els];

    // we need unwind the array aMatrix into coordinate form
    int localmaxEntriesInARow;
    _maxEntriesInARow = -1; // set max entries in a column negative, so that maximiser will work
    int ptr = 0;
    for (int i = 0; i < aMatrix.getNumberOfRows(); i++) {
        localmaxEntriesInARow = 0;
        for (int j = 0; j < aMatrix.getNumberOfColumns(); j++) {
            if (Double.doubleToLongBits(aMatrix.getEntry(i, j)) != 0L) {
                xTmp[ptr] = j;
                yTmp[ptr] = i;
                valuesTmp[ptr] = aMatrix.getEntry(i, j);
                ptr++;
                localmaxEntriesInARow++;
            }
        }
        if (localmaxEntriesInARow > _maxEntriesInARow) {
            _maxEntriesInARow = localmaxEntriesInARow;
        }
    }

    _values = Arrays.copyOfRange(valuesTmp, 0, ptr);
    _x = Arrays.copyOfRange(xTmp, 0, ptr);
    _y = Arrays.copyOfRange(yTmp, 0, ptr);
    _rows = aMatrix.getNumberOfRows();
    _cols = aMatrix.getNumberOfColumns();
}

From source file:de.tudarmstadt.ukp.dkpro.spelling.detector.ngram.LMBasedDetector.java

protected double getSentenceProbability(List<String> words) throws AnalysisEngineProcessException {
    double sentenceProbability = 0.0;

    if (words.size() < 1) {
        return 0.0;
    }//from   ww w. j av a 2 s  . co  m

    long nrOfUnigrams;
    try {
        nrOfUnigrams = provider.getNrOfTokens();
    } catch (Exception e) {
        throw new AnalysisEngineProcessException(e);
    }

    List<String> trigrams = new ArrayList<String>();

    // in the google n-grams this is not represented (only single BOS markers)
    // but I leave it in place in case we add another n-gram provider
    trigrams.add(NGramDetectorUtils.getTrigram(BOS, BOS, words.get(0)));

    if (words.size() > 1) {
        trigrams.add(NGramDetectorUtils.getTrigram(BOS, words.get(0), words.get(1)));
    }

    for (String trigram : new NGramStringIterable(words, 3, 3)) {
        trigrams.add(trigram);
    }

    // FIXME - implement backoff or linear interpolation

    for (String trigram : trigrams) {
        long trigramFreq = getNGramCount(trigram);

        String[] parts = StringUtils.split(trigram, " ");

        String bigram = StringUtils.join(Arrays.copyOfRange(parts, 0, 2), " ");
        long bigramFreq = getNGramCount(bigram);

        String unigram = StringUtils.join(Arrays.copyOfRange(parts, 0, 1), " ");
        long unigramFreq = getNGramCount(unigram);

        if (trigramFreq < 1) {
            trigramFreq = 1;
        }
        if (bigramFreq < 1) {
            bigramFreq = 1;
        }
        if (unigramFreq < 1) {
            unigramFreq = 1;
        }

        double trigramProb = Math.log((double) trigramFreq / bigramFreq);
        double bigramProb = Math.log((double) bigramFreq / unigramFreq);
        double unigramProb = Math.log((double) unigramFreq / nrOfUnigrams);

        double interpolated = (trigramProb + bigramProb + unigramProb) / 3.0;

        sentenceProbability += interpolated;
    }

    return Math.exp(sentenceProbability);
}

From source file:com.cloudera.sqoop.tool.JobTool.java

/**
 * Given an array of strings, return the first instance
 * of "--" and all following elements.//  w w w  . j a  v  a 2  s .c o m
 * If no "--" exists, return null.
 */
private String[] getElementsAfterDoubleDash(String[] array) {
    String[] extraChildArgv = null;
    for (int i = 0; i < array.length; i++) {
        if ("--".equals(array[i])) {
            extraChildArgv = Arrays.copyOfRange(array, i, array.length);
            break;
        }
    }

    return extraChildArgv;
}

From source file:org.jenkinsci.plugins.codedx.AnalysisResultChecker.java

private String[] getSeverities(String minSeverity) {

    String[] possibleSeverities = { Filter.SEVERITY_INFO, Filter.SEVERITY_LOW, Filter.SEVERITY_MEDIUM,
            Filter.SEVERITY_HIGH, Filter.SEVERITY_UNSPECIFIED };

    for (int i = 0; i < possibleSeverities.length; i++) {

        if (possibleSeverities[i].equalsIgnoreCase(minSeverity)) {

            return Arrays.copyOfRange(possibleSeverities, i, possibleSeverities.length);
        }/* w w w.  jav a 2 s. c o m*/
    }

    return new String[] {};
}

From source file:fr.ortolang.diffusion.security.authentication.TicketHelper.java

public static Ticket decodeTicket(String ticket) {
    byte[] encryptedBytes = Base64.decodeBase64(ticket.getBytes());
    try {/* ww  w. ja  va  2s.c om*/
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        // Extract digest from decryptedBytes (MD5 length is 16 bytes)
        byte[] digest = Arrays.copyOfRange(decryptedBytes, decryptedBytes.length - 16, decryptedBytes.length);
        byte[] serializedMap = Arrays.copyOfRange(decryptedBytes, 0, decryptedBytes.length - 16);
        MessageDigest md = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM);
        if (!Arrays.equals(digest, md.digest(serializedMap))) {
            throw new DigestException();
        }
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(serializedMap));
        return (Ticket) ois.readObject();
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException
            | IllegalBlockSizeException | IOException | ClassNotFoundException | DigestException e) {
        LOGGER.log(Level.SEVERE, "Error when decoding ticket: " + e.getMessage());
    }
    return null;
}

From source file:com.palantir.stash.stashbot.servlet.BuildStatusReportingServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {/*  w w  w . j  a  v  a  2  s.  co m*/
        // Look at JenkinsManager class if you change this:
        // final two arguments could be empty...
        final String URL_FORMAT = "BASE_URL/REPO_ID_OR_SLUG/PULLREQUEST_ID]";
        final String pathInfo = req.getPathInfo();
        final String[] parts = pathInfo.split("/");

        // need at *least* 3 parts to be correct
        if (parts.length < 3) {
            throw new IllegalArgumentException("The format of the URL is " + URL_FORMAT);
        }

        // Last part is always the PR
        String pullRequestPart = parts[parts.length - 1];

        // First part is always empty because string starts with '/', last is pr, the rest is the slug
        String slugOrId = StringUtils.join(Arrays.copyOfRange(parts, 1, parts.length - 1), "/");

        Repository repo;
        try {
            int repoId = Integer.valueOf(slugOrId);
            repo = rs.getById(repoId);
            if (repo == null) {
                throw new IllegalArgumentException("Unable to find repository for repo id " + repoId);
            }
        } catch (NumberFormatException e) {
            // we have a slug, try to get a repo ID from that
            // slug should look like this: projects/PROJECT_KEY/repos/REPO_SLUG/pull-requests
            String[] newParts = slugOrId.split("/");

            if (newParts.length != 5) {
                throw new IllegalArgumentException(
                        "The format of the REPO_ID_OR_SLUG is an ID, or projects/PROJECT_KEY/repos/REPO_SLUG/pull-requests");
            }
            Project p = ps.getByKey(newParts[1]);
            if (p == null) {
                throw new IllegalArgumentException("Unable to find project for project key" + newParts[1]);
            }
            repo = rs.getBySlug(p.getKey(), newParts[3]);
            if (repo == null) {
                throw new IllegalArgumentException("Unable to find repository for project key" + newParts[1]
                        + " and repo slug " + newParts[3]);
            }
        }

        final long pullRequestId;
        final PullRequest pullRequest;

        try {
            pullRequestId = Long.parseLong(pullRequestPart);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Unable to parse pull request id " + parts[7], e);
        }
        pullRequest = prs.getById(repo.getId(), pullRequestId);
        if (pullRequest == null) {
            throw new IllegalArgumentException("Unable to find pull request for repo id "
                    + repo.getId().toString() + " pr id " + pullRequestId);
        }

        PullRequestMergeability canMerge = prs.canMerge(repo.getId(), pullRequestId);

        JSONObject output = new JSONObject();
        output.put("repoId", repo.getId());
        output.put("prId", pullRequestId);
        output.put("url", nb.repo(repo).pullRequest(pullRequest.getId()).buildAbsolute());
        output.put("canMerge", canMerge.canMerge());
        if (!canMerge.canMerge()) {
            JSONArray vetoes = new JSONArray();
            for (PullRequestMergeVeto prmv : canMerge.getVetos()) {
                JSONObject prmvjs = new JSONObject();
                prmvjs.put("summary", prmv.getSummaryMessage());
                prmvjs.put("details", prmv.getDetailedMessage());
                vetoes.put(prmvjs);
            }
            // You might expect a conflict would be included in the list of merge blockers.  You'd be mistaken.
            if (canMerge.isConflicted()) {
                JSONObject prmvjs = new JSONObject();
                prmvjs.put("summary", "This pull request is unmergeable due to conflicts.");
                prmvjs.put("details", "You will need to resolve conflicts to be able to merge.");
                vetoes.put(prmvjs);
            }
            output.put("vetoes", vetoes);
        }

        log.debug("Serving build status: " + output.toString());
        printOutput(output, req, res);
    } catch (Exception e) {
        res.reset();
        res.setStatus(500);
        res.setContentType("application/json");
        Writer w = res.getWriter();
        try {
            w.append(new JSONObject().put("error", e.getMessage()).toString());
        } catch (JSONException e1) {
            throw new RuntimeException("Errorception!", e1);
        }
        w.close();
    }
}

From source file:juicebox.tools.utils.juicer.arrowhead.BlockResults.java

/**
 * calculate D upstream, directionality index upstream
 *
 * @param observed//from w ww  .  j  av a2 s. c  o m
 * @param n
 * @param gap
 * @return dUpstream
 */
private RealMatrix calculateDirectionalityIndexUpstream(RealMatrix observed, int n, int gap) {

    RealMatrix dUpstream = MatrixTools.cleanArray2DMatrix(n);

    for (int i = 0; i < n; i++) {
        // choose smaller window of two: from 0 to (i-gap) or from (i+gap) to n
        int window = Math.min(n - (i + gap), i - gap);
        window = Math.min(window, n);

        if (window >= gap) {
            double[] row = observed.getRow(i);

            // in MATLAB second index inclusive, but for java need +1
            double[] A = Doubles
                    .toArray(Lists.reverse(Doubles.asList(Arrays.copyOfRange(row, i - window, i - gap + 1))));
            double[] B = Arrays.copyOfRange(row, i + gap, i + window + 1);

            double[] preference = new double[A.length];
            for (int j = 0; j < A.length; j++) {
                preference[j] = (A[j] - B[j]) / (A[j] + B[j]);
            }

            int index = 0;
            for (int j = i + gap; j < i + window + 1; j++) {
                dUpstream.setEntry(i, j, preference[index]);
                index++;
            }
        }
    }
    return dUpstream;
}

From source file:net.sf.dsp4j.octave.packages.signal_1_0_11.Freqz.java

public Freqz(double[] b, int n) {
    FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD);
    Complex[] hb = fft.transform(Arrays.copyOf(b, 2 * n), TransformType.FORWARD);

    H = Arrays.copyOfRange(hb, 0, n);
    w = new double[n];

    for (int i = 0; i < H.length; i++) {
        w[i] = Math.PI / n * i;// w ww. ja  va  2  s  .  c o  m
    }
}

From source file:com.googlesource.gerrit.plugins.hooks.workflow.action.AddVelocityComment.java

@Override
public void execute(String issue, ActionRequest actionRequest, Set<Property> properties) throws IOException {
    String template = null;/*  w  ww .j  a  v  a 2  s  .  c o m*/
    String templateName = actionRequest.getParameter(1);
    if ("inline".equals(templateName)) {
        String[] allParameters = actionRequest.getParameters();
        String[] templateParameters = Arrays.copyOfRange(allParameters, 1, allParameters.length);
        template = StringUtils.join(templateParameters, " ");
    } else {
        if (templateName.isEmpty()) {
            log.error("No template name given in " + actionRequest);
        } else {
            File templateFile = new File(sitePath, ITS_TEMPLATE_DIR + File.separator + templateName + ".vm");
            if (templateFile.canRead()) {
                template = FileUtils.readAllText(templateFile);
            } else {
                log.error("Cannot read template " + templateFile);
            }
        }
    }
    if (!Strings.isNullOrEmpty(template)) {
        String comment = velocify(template, properties);
        its.addComment(issue, comment);
    }
}