Example usage for java.util Arrays binarySearch

List of usage examples for java.util Arrays binarySearch

Introduction

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

Prototype

public static int binarySearch(Object[] a, Object key) 

Source Link

Document

Searches the specified array for the specified object using the binary search algorithm.

Usage

From source file:edu.cornell.med.icb.goby.alignments.AlignmentReaderImpl.java

/**
 * Calculate the offset (in bytes) in the compact entries file for a specific targetIndex and position.
 * Entries that can be read after this position are guaranteed to have targetIndex larger or equal to targetIndex
 * and positions larger or equal to position.
 * The parameter chunkOffset can be used to iterate through successive protocol buffer compressed chunks.
 * A typical usage is to call getByteOffset with startReference and startPosition. A second call to getByteOffset
 * with endReference and endPosition with chunkOffset=0 will return an end position. If the end and start positions
 * are the same, both start and end locations are in the same chunk. In this case, it is necessary to extend the end
 * byte position to include the entire chunk. This can be achieved by calling getByteOffset with  endReference and endPosition
 * and a chunkOffset of 1. Because it is possible that the next chunk also contains only entries with the same position,
 * one must/*from  ww  w.  jav a2s  .  c  om*/
 * use 0, 1,2, etc until the returned offset differs allows to make sure the indexed position is at the start of a new chunk.
 *
 * @param targetIndex Index of a reference sequence.
 * @param position    Position along the reference sequence.
 * @param chunkOffset Offset used to iterate through successive PB chunks.
 * @return the largest position in byte in the entries file that occur before the location (targetIndex, position) or
 *         Long.MIN_VALUE if the offset cannot be determined (e.g., alignment is empty).
 */
protected long getByteOffset(final int targetIndex, final int position, final int chunkOffset) {

    if (targetIndex >= targetPositionOffsets.length)
        return Long.MAX_VALUE;

    final long absolutePosition = recodePosition(targetIndex, position);
    int offsetIndex = Arrays.binarySearch(indexAbsolutePositions.elements(), absolutePosition);
    offsetIndex = offsetIndex < 0 ? -1 - offsetIndex : offsetIndex;
    offsetIndex = offsetIndex >= indexOffsets.size() ? indexOffsets.size() - 1 : offsetIndex - 1;
    if (offsetIndex + chunkOffset < 0) {
        // empty alignment.
        return Long.MIN_VALUE;
    }

    if (offsetIndex + chunkOffset < indexOffsets.size()) {
        final long byteOffset = indexOffsets.getLong(offsetIndex + chunkOffset);
        return byteOffset;
    } else {
        // return an end-offset past the beginning of the last chunk:
        return indexOffsets.getLong(offsetIndex) + 10;
    }

}

From source file:com.opengamma.analytics.math.cube.InterpolatedFromSurfacesDoublesCube.java

@Override
public Double getValue(final Double x, final Double y, final Double z) {
    Validate.notNull(x, "x");
    Validate.notNull(y, "y");
    Validate.notNull(z, "z");
    final double[] values = new double[_nSurfaces];
    int i = 0;/*from   ww w  .j  a  va2s. com*/
    double x1, y1, z1;
    switch (_plane) {
    case XY:
        x1 = x;
        y1 = y;
        z1 = z;
        break;
    case XZ:
        x1 = x;
        y1 = z;
        z1 = y;
        break;
    case YZ:
        x1 = y;
        y1 = z;
        z1 = x;
        break;
    default:
        throw new IllegalArgumentException("Cannot handle type " + _plane);
    }
    final int index = Arrays.binarySearch(_points, z1);
    if (index < 0) {
        for (final Surface<Double, Double, Double> surface : _surfaces) {
            values[i++] = surface.getZValue(x1, y1);
        }
        return InterpolatedDoublesCurve.fromSorted(_points, values, _interpolator).getYValue(z1);
    }
    return _surfaces[index].getZValue(x1, y1);
}

From source file:com.digium.respokesdk.RespokeSignalingChannel.java

private void sendEvent(final String httpMethod, final JSONArray array, final Integer attempt,
        final RESTListener completionListener, long delayMillis) {
    // Queue the request with the socket workerThread
    workerThread.postTaskDelayed(new Runnable() {
        @Override//from   w  w  w .  j a va2 s. c  o  m
        public void run() {
            if (connected) {
                final CountDownLatch asyncTaskSignal = new CountDownLatch(1);

                client.emit(httpMethod, array, new Acknowledge() {
                    @Override
                    public void acknowledge(JSONArray arguments) {
                        // There should only ever be one element in this array. Anything else is ignored for the time being.
                        if ((arguments != null) && (arguments.length() > 0)) {
                            try {
                                Object responseObject = arguments.get(0);
                                JSONObject jsonResponse = null;
                                Object responseBody = null;
                                String errorMessage = null;
                                boolean rateLimitErrorPresent = false;
                                Integer rateLimitDelay = 1000; // 1 second unless specified otherwise

                                if (responseObject instanceof JSONObject) {
                                    jsonResponse = (JSONObject) responseObject;
                                } else {
                                    errorMessage = "Unexpected response received";
                                }

                                // If the response contained json, parse it for error messages
                                if (null != jsonResponse) {
                                    try {
                                        int statusCode = jsonResponse.getInt("statusCode");
                                        int[] validCodes = { 200, 204, 205, 302, 401, 403, 404, 418, 429 };
                                        if (Arrays.binarySearch(validCodes, statusCode) < 0) {
                                            errorMessage = "An unknown error occurred";
                                        } else if (429 == statusCode) {
                                            // The request was rejected due to a rate limit error
                                            rateLimitErrorPresent = true;

                                            // If there was a rate limit error, extract the limit info from the headers
                                            try {
                                                JSONObject headers = jsonResponse.getJSONObject("headers");
                                                Integer limit = headers.getInt("RateLimit-Limit");
                                                rateLimitDelay = 1000 / limit;
                                            } catch (JSONException e) {
                                                // If the limit info could not be found, use the default
                                            }
                                        }
                                    } catch (JSONException e) {
                                        // If there was no status code, then assume the operation was successful
                                    }

                                    responseBody = jsonResponse.get("body");

                                    if (responseBody instanceof String) {
                                        String responseString = (String) responseBody;

                                        if (responseString.equals("null")) {
                                            responseBody = null;
                                        } else {
                                            try {
                                                responseBody = new JSONObject(responseString);
                                            } catch (JSONException e) {
                                                // It's not a jsonobject. Pass the data to the calling object as is
                                            }
                                        }
                                    }

                                    if (responseBody instanceof JSONObject) {
                                        // The body of the response was decoded into JSON. Look for error messages
                                        // If there was a server error, there will be a key named 'error' or 'status'
                                        try {
                                            errorMessage = ((JSONObject) responseBody).getString("error");
                                            String details = ((JSONObject) responseBody).getString("details");
                                            errorMessage = errorMessage + " (" + details + ")";
                                        } catch (JSONException e) {
                                            // If there was no 'error' key, then assume the operation was successful
                                        }
                                    }
                                }

                                if (rateLimitErrorPresent) {
                                    if (attempt < 3) {
                                        Log.d(TAG, "Performing rate-limited retry " + attempt + 1);
                                        sendEvent(httpMethod, array, attempt + 1, completionListener,
                                                rateLimitDelay);
                                    } else {
                                        completionListener.onError("API rate limit was exceeded");
                                    }
                                } else {
                                    if (null == errorMessage) {
                                        completionListener.onSuccess(responseBody);
                                    } else {
                                        completionListener.onError(errorMessage);
                                    }
                                }
                            } catch (JSONException e) {
                                completionListener.onError("Unexpected response from server");
                            }
                        } else {
                            completionListener.onError("Unexpected response from server");
                        }

                        // Signal that processing is complete and the next task in the worker thread may proceed
                        asyncTaskSignal.countDown();
                    }
                });

                try {
                    // Wait for the previous task to complete before moving to the next item in the worker thread queue. This is to avoid multiple socket requests from occurring simultaneously which causes instability in the socket.io library
                    asyncTaskSignal.await(REST_TASK_TIMEOUT, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                completionListener.onError("Can't complete request when not connected. Please reconnect!");
            }
        }
    }, delayMillis);
}

From source file:net.sf.click.jquery.behavior.JQBehavior.java

/**
 * Returns the <tt>Locale</tt> that should be used in this behavior. The
 * returned locale must be present in the list of {@link #SUPPORTED_LANGUAGES}.
 * <p/>// ww  w . j  a  va2s.co m
 * If a locale is not currently supported you can set the
 * {@link #SUPPORTED_LANGUAGES} manually.
 *
 * @return the locale that should be used in this behavior
 */
protected Locale getLocale() {
    Locale locale = null;

    locale = getContext().getLocale();
    String lang = locale.getLanguage();
    if (Arrays.binarySearch(SUPPORTED_LANGUAGES, lang) >= 0) {
        return locale;
    }

    locale = Locale.getDefault();
    lang = locale.getLanguage();
    if (Arrays.binarySearch(SUPPORTED_LANGUAGES, lang) >= 0) {
        return locale;
    }

    return Locale.ENGLISH;
}

From source file:org.fhcrc.cpl.viewer.quant.gui.PanelWithSpectrumChart.java

License:asdf

/**
 * Create a 3D plot for a quantitative event
 * @param scanValuesPadded/*w  w w.j  ava  2 s.c  o  m*/
 * @param mzValues
 * @param intensityValuesPadded
 */
protected void generate3DPlot(double[] scanValuesPadded, double[] mzValues, double[][] intensityValuesPadded) {
    _log.debug("Generating R contour plot...");

    //float[][] intensityValuesPaddedAsFloat = new float[intensityValuesPadded.length][intensityValuesPadded[0].length];
    //for (int i=0; i<intensityValuesPadded.length; i++)
    //    for (int j=0; j<intensityValuesPadded[0].length; j++)
    //       intensityValuesPaddedAsFloat[i][j] = (float) intensityValuesPadded[i][j];
    //
    //JFrame frame = SurfaceFrame.ShowSurfaceFrame(intensityValuesPaddedAsFloat);
    //frame.setVisible(true);

    contourPlot = new PanelWithRPerspectivePlot();
    contourPlot.setName("3D");
    contourPlot.setRotationAngle(contourPlotRotationAngle);
    contourPlot.setTiltAngle(contourPlotTiltAngle);
    contourPlot.setChartWidth(contourPlotWidth);
    contourPlot.setChartHeight(contourPlotHeight);
    contourPlot.setUseGradientForColor(true);
    contourPlot.setShowBorders(false);
    contourPlot.setShowBox(contourPlotShowAxes);

    //contourPlot.setTiltAngles(Arrays.asList(new Integer[] { 82, 76, 70, 66, 60, 54, 49, 45, 41, 38, 35, 32, 30, 28, 27, 26, 25, 24, 23 }));
    // contourPlot.setRotationAngles(Arrays.asList(new Integer[] {0, 5, 10, 15, 20, 25, 30, 35, 40, 45,
    //                    50, 55, 60, 65, 70, 75, 80, 85, 85}));

    double[] twoZeroes = new double[] { 0, 0 };
    if (lightFirstScanLine > 0) {
        double[] line1XValues = new double[] { lightFirstScanLine, lightFirstScanLine };
        double[] line1YValues = new double[] { minMz, lightMz };
        contourPlot.addLine(line1XValues, line1YValues, twoZeroes, "red",
                PanelWithRPerspectivePlot.LINE_STYLE_DASHED);
    }
    if (lightLastScanLine > 0) {
        double[] line2XValues = new double[] { lightLastScanLine, lightLastScanLine };
        double[] line2YValues = new double[] { minMz, lightMz };
        contourPlot.addLine(line2XValues, line2YValues, twoZeroes, "red",
                PanelWithRPerspectivePlot.LINE_STYLE_DASHED);
    }
    if (heavyFirstScanLine > 0) {
        double[] line1XValues = new double[] { heavyFirstScanLine, heavyFirstScanLine };
        double[] line1YValues = new double[] { heavyMz, maxMz };
        contourPlot.addLine(line1XValues, line1YValues, twoZeroes, "red",
                PanelWithRPerspectivePlot.LINE_STYLE_DASHED);
    }
    if (heavyLastScanLine > 0) {
        double[] line2XValues = new double[] { heavyLastScanLine, heavyLastScanLine };
        double[] line2YValues = new double[] { heavyMz, maxMz };
        contourPlot.addLine(line2XValues, line2YValues, twoZeroes, "red",
                PanelWithRPerspectivePlot.LINE_STYLE_DASHED);
    }
    //draw a little X on the MS/MS event
    if (idEventScan > 0 && idEventMz > 0) {
        drawContourCrossForEvent(idEventScan, idEventMz, "blue");
    }
    if (otherEventScans != null && !otherEventScans.isEmpty()) {
        for (int i = 0; i < otherEventScans.size(); i++)
            drawContourCrossForEvent(otherEventScans.get(i), otherEventMZs.get(i), "yellow");
    }

    double closestLightMz = mzValues[Math.abs(Arrays.binarySearch(mzValues, lightMz))];
    double closestHeavyMz = mzValues[Math.abs(Arrays.binarySearch(mzValues, heavyMz))];

    //light and heavy monoisotopes
    double[] tickXValues = new double[] { minScan - 1, maxScan + 1 };

    double[] lightTickYValues = new double[] { closestLightMz, closestLightMz };
    double[] heavyTickYValues = new double[] { closestHeavyMz, closestHeavyMz };

    contourPlot.addLine(tickXValues, lightTickYValues, twoZeroes, "red");
    contourPlot.addLine(tickXValues, heavyTickYValues, twoZeroes, "red");

    contourPlot.plot(scanValuesPadded, mzValues, intensityValuesPadded);
    _log.debug("Generated R contour plot.");
}

From source file:com.celements.web.plugin.CelementsWebPlugin.java

boolean arrayContains(String[] array, String value) {
    Arrays.sort(array);
    return (Arrays.binarySearch(array, value) >= 0);
}

From source file:org.fhcrc.cpl.viewer.quant.gui.PanelWithSpectrumChart.java

License:asdf

protected void drawHeatmapCrossForEvent(double[] scanValuesPadded, double[] mzValues,
        double[][] intensityValuesPadded, int scan, float mz, float intensityForIdCross) {
    //cross for ID event
    if (scan > 0 && mz > 0) {
        int closestEventMzIndex = Math.abs(Arrays.binarySearch(mzValues, mz));
        int closestEventScanIndex = Math.abs(Arrays.binarySearch(scanValuesPadded, scan));

        conditionallySetValueAt(intensityValuesPadded, closestEventScanIndex, closestEventMzIndex,
                intensityForIdCross);//from   w w  w  .ja va 2 s .  c o  m
        conditionallySetValueAt(intensityValuesPadded, closestEventScanIndex - 1, closestEventMzIndex - 1,
                intensityForIdCross);
        conditionallySetValueAt(intensityValuesPadded, closestEventScanIndex + 1, closestEventMzIndex + 1,
                intensityForIdCross);
        conditionallySetValueAt(intensityValuesPadded, closestEventScanIndex - 1, closestEventMzIndex + 1,
                intensityForIdCross);
        conditionallySetValueAt(intensityValuesPadded, closestEventScanIndex + 1, closestEventMzIndex - 1,
                intensityForIdCross);

    }
}

From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java

/**
 * Perform a selection query that retrieves all points in the given range.
 * The range is specified in the two-dimensional array positions. 
 * @param in/*w  w  w . j  av a2 s.c  om*/
 * @param query_mbr
 * @return
 * @throws IOException
 */
public static Node aggregateQuery(FSDataInputStream in, Rectangle query_mbr) throws IOException {
    long treeStartPosition = in.getPos();
    Node result = new Node();
    int numOfSelectedRecords = 0;
    int resolution = in.readInt();
    short fillValue = in.readShort();
    int cardinality = in.readInt();
    final Vector<Integer> selectedNodesPos = new Vector<Integer>();
    final Vector<Integer> selectedStarts = new Vector<Integer>();
    final Vector<Integer> selectedEnds = new Vector<Integer>();
    StockQuadTree stockQuadTree = getOrCreateStockQuadTree(resolution);
    // Nodes to be searched. Contains node positions in the array of nodes
    Stack<Integer> nodes_2b_searched = new Stack<Integer>();
    nodes_2b_searched.add(0); // Root node (ID=1)
    Rectangle node_mbr = new Rectangle();
    while (!nodes_2b_searched.isEmpty()) {
        int node_pos = nodes_2b_searched.pop();
        stockQuadTree.getNodeMBR(node_pos, node_mbr);
        if (query_mbr.contains(node_mbr)) {
            // Add this node to the selection list and stop this branch
            selectedNodesPos.add(node_pos);
        } else if (query_mbr.intersects(node_mbr)) {
            int first_child_id = stockQuadTree.nodesID[node_pos] * 4 + 0;
            int first_child_pos = Arrays.binarySearch(stockQuadTree.nodesID, first_child_id);
            if (first_child_pos < 0) {
                // No children. Hit a leaf node
                // Scan and add matching points only
                java.awt.Point record_coords = new Point();
                for (int record_pos = stockQuadTree.nodesStartPosition[node_pos]; record_pos < stockQuadTree.nodesEndPosition[node_pos]; record_pos++) {
                    stockQuadTree.getRecordCoords(record_pos, record_coords);
                    if (query_mbr.contains(record_coords)) {
                        // matched a record.
                        if (!selectedEnds.isEmpty() && selectedEnds.lastElement() == record_pos) {
                            // Merge with an adjacent range
                            selectedEnds.set(selectedEnds.size() - 1, record_pos + 1);
                        } else {
                            // Add a new range of unit width
                            selectedStarts.add(record_pos);
                            selectedEnds.add(record_pos + 1);
                        }
                        numOfSelectedRecords++;
                    }
                }
            } else {
                // Non-leaf node. Add all children to the list of nodes to search
                // Add in reverse order to the stack so that results come in sorted order
                nodes_2b_searched.add(first_child_pos + 3);
                nodes_2b_searched.add(first_child_pos + 2);
                nodes_2b_searched.add(first_child_pos + 1);
                nodes_2b_searched.add(first_child_pos + 0);
            }
        }
    }
    // Result 1: Accumulate all values
    // Sort disk offsets to eliminate backward seeks
    if (!selectedStarts.isEmpty()) {
        LOG.debug("Aggregate query selected " + selectedNodesPos.size() + " nodes and " + numOfSelectedRecords
                + " records");

        final IndexedSortable sortable = new IndexedSortable() {
            @Override
            public int compare(int i, int j) {
                return selectedStarts.get(i) - selectedStarts.get(j);
            }

            @Override
            public void swap(int i, int j) {
                int temp = selectedStarts.get(i);
                selectedStarts.set(i, selectedStarts.get(j));
                selectedStarts.set(j, temp);

                temp = selectedEnds.get(i);
                selectedEnds.set(i, selectedEnds.get(j));
                selectedEnds.set(j, temp);
            }
        };
        new QuickSort().sort(sortable, 0, selectedStarts.size());

        long dataStartPosition = getValuesStartOffset(cardinality);
        Point resultCoords = new Point();
        // Return all values in the selected ranges
        for (int iRange = 0; iRange < selectedStarts.size(); iRange++) {
            int treeStart = selectedStarts.get(iRange);
            int treeEnd = selectedEnds.get(iRange);
            long startPosition = dataStartPosition + selectedStarts.get(iRange) * cardinality * 2;
            in.seek(startPosition);
            for (int treePos = treeStart; treePos < treeEnd; treePos++) {
                // Retrieve the coords for the point at treePos
                stockQuadTree.getRecordCoords(treePos, resultCoords);
                // Read all entries at current position
                for (int iValue = 0; iValue < cardinality; iValue++) {
                    short value = in.readShort();
                    if (value != fillValue)
                        result.accumulate(value);
                }
            }
        }

    }

    // Result 2: Accumulate all nodes
    if (!selectedNodesPos.isEmpty()) {
        long nodesStartPosition = treeStartPosition + getNodesStartOffset(resolution, cardinality);
        // Sort node positions to eliminate backward seeks
        IndexedSortable nodeSortable = new IndexedSortable() {
            @Override
            public int compare(int i, int j) {
                return selectedNodesPos.get(i) - selectedNodesPos.get(j);
            }

            @Override
            public void swap(int i, int j) {
                int temp = selectedNodesPos.get(i);
                selectedNodesPos.set(i, selectedNodesPos.get(j));
                selectedNodesPos.set(j, temp);
            }
        };
        new QuickSort().sort(nodeSortable, 0, selectedNodesPos.size());

        Node selectedNode = new Node();
        for (int node_pos : selectedNodesPos) {
            long nodePosition = nodesStartPosition + node_pos * NodeSize;
            in.seek(nodePosition);
            selectedNode.readFields(in);
            result.accumulate(selectedNode);
        }
    }
    return result;
}

From source file:ca.oson.json.util.ObjectUtil.java

public static boolean inArray(String name, String[] names) {
    if (name == null || names == null) {
        return false;
    }//w  w w.  ja va  2  s  .com

    return Arrays.binarySearch(names, name) >= 0;
}

From source file:org.apache.mahout.freqtermsets.fpgrowth.FPGrowth.java

private static FrequentPatternMaxHeap growth(FPTree tree, MutableLong minSupportMutable, int k,
        FPTreeDepthCache treeCache, int level, int currentAttribute, StatusUpdater updater) {

    int i = Arrays.binarySearch(tree.getHeaderTableAttributes(), currentAttribute);
    if (i < 0) {
        return new FrequentPatternMaxHeap(k, true); // frequentPatterns;
    }/*  w w  w  .ja va2  s .co  m*/

    int headerTableCount = tree.getHeaderTableCount();

    //    // YA: The frequent pattern returned should be k PER item.. so the total
    // size of the heap should be k * number of items (headerTableCount - i)
    FrequentPatternMaxHeap frequentPatterns = new FrequentPatternMaxHeap(k * (headerTableCount - i), true);
    //    FrequentPatternMaxHeap frequentPatterns = new FrequentPatternMaxHeap(k,true);

    while (i < headerTableCount) {
        int attribute = tree.getAttributeAtIndex(i);
        long count = tree.getHeaderSupportCount(attribute);
        if (count < minSupportMutable.longValue()) {
            i++;
            continue;
        }
        updater.update("FPGrowth Algorithm for a given feature: " + attribute);
        FPTree conditionalTree = treeCache.getFirstLevelTree(attribute);
        if (conditionalTree.isEmpty()) {
            traverseAndBuildConditionalFPTreeData(tree.getHeaderNext(attribute), minSupportMutable.longValue(),
                    conditionalTree, tree);
            // printTree(conditionalTree);

        }

        FrequentPatternMaxHeap returnedPatterns;
        if (attribute == currentAttribute) {

            returnedPatterns = growthTopDown(conditionalTree, minSupportMutable, k, treeCache, level + 1, true,
                    currentAttribute, updater);

            frequentPatterns = mergeHeap(frequentPatterns, returnedPatterns, attribute, count, true);
        } else {
            returnedPatterns = growthTopDown(conditionalTree, minSupportMutable, k, treeCache, level + 1, false,
                    currentAttribute, updater);
            frequentPatterns = mergeHeap(frequentPatterns, returnedPatterns, attribute, count, false);
        }
        if (frequentPatterns.isFull() && minSupportMutable.longValue() < frequentPatterns.leastSupport()) {
            minSupportMutable.setValue(frequentPatterns.leastSupport());
        }
        i++;
    }

    return frequentPatterns;
}