Example usage for java.util Collections reverseOrder

List of usage examples for java.util Collections reverseOrder

Introduction

In this page you can find the example usage for java.util Collections reverseOrder.

Prototype

@SuppressWarnings("unchecked")
public static <T> Comparator<T> reverseOrder() 

Source Link

Document

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Usage

From source file:com.farmerbb.notepad.fragment.NoteListFragment.java

private void listNotes() {
    // Get array of file names
    String[] listOfFiles = getActivity().getFilesDir().list();
    ArrayList<String> listOfNotes = new ArrayList<>();

    // Get number of files
    int numOfNotes = listOfFiles.length;

    // Remove any files from the list that aren't notes
    for (String listOfFile : listOfFiles) {
        if (NumberUtils.isCreatable(listOfFile))
            listOfNotes.add(listOfFile);
        else//from  w  ww. j a  v a2s. c o m
            numOfNotes--;
    }

    // Create arrays of note lists
    String[] listOfNotesByDate = new String[numOfNotes];
    String[] listOfNotesByName = new String[numOfNotes];

    NoteListItem[] listOfTitlesByDate = new NoteListItem[numOfNotes];
    NoteListItem[] listOfTitlesByName = new NoteListItem[numOfNotes];

    ArrayList<NoteListItem> list = new ArrayList<>(numOfNotes);

    for (int i = 0; i < numOfNotes; i++) {
        listOfNotesByDate[i] = listOfNotes.get(i);
    }

    // If sort-by is "by date", sort in reverse order
    if (sortBy.startsWith("date")) {
        Arrays.sort(listOfNotesByDate, Collections.reverseOrder());
        if (sortBy.endsWith("reversed"))
            ArrayUtils.reverse(listOfNotesByDate);
    }

    // Get array of first lines of each note
    for (int i = 0; i < numOfNotes; i++) {
        try {
            String title = listener.loadNoteTitle(listOfNotesByDate[i]);
            String date = listener.loadNoteDate(listOfNotesByDate[i]);
            listOfTitlesByDate[i] = new NoteListItem(title, date);
        } catch (IOException e) {
            showToast(R.string.error_loading_list);
        }
    }

    // If sort-by is "by name", sort alphabetically
    if (sortBy.startsWith("name")) {
        // Copy titles array
        System.arraycopy(listOfTitlesByDate, 0, listOfTitlesByName, 0, numOfNotes);

        // Sort titles
        Arrays.sort(listOfTitlesByName, NoteListItem.NoteComparatorTitle);
        if (sortBy.endsWith("reversed"))
            ArrayUtils.reverse(listOfTitlesByName);

        // Initialize notes array
        for (int i = 0; i < numOfNotes; i++)
            listOfNotesByName[i] = "new";

        // Copy filenames array with new sort order of titles and nullify date arrays
        for (int i = 0; i < numOfNotes; i++) {
            for (int j = 0; j < numOfNotes; j++) {
                if (listOfTitlesByName[i].getNote().equals(listOfTitlesByDate[j].getNote())
                        && listOfNotesByName[i].equals("new")) {
                    listOfNotesByName[i] = listOfNotesByDate[j];
                    listOfNotesByDate[j] = "";
                    listOfTitlesByDate[j] = new NoteListItem("", "");
                }
            }
        }

        // Populate ArrayList with notes, showing name as first line of the notes
        list.addAll(Arrays.asList(listOfTitlesByName));
    } else if (sortBy.startsWith("date"))
        list.addAll(Arrays.asList(listOfTitlesByDate));

    // Create the custom adapters to bind the array to the ListView
    final NoteListDateAdapter dateAdapter = new NoteListDateAdapter(getActivity(), list);
    final NoteListAdapter adapter = new NoteListAdapter(getActivity(), list);

    // Display the ListView
    if (showDate)
        listView.setAdapter(dateAdapter);
    else
        listView.setAdapter(adapter);

    listView.setSelection(ScrollPositions.getInstance().getPosition());

    // Finalize arrays to prepare for handling clicked items
    final String[] finalListByDate = listOfNotesByDate;
    final String[] finalListByName = listOfNotesByName;

    // Make ListView handle clicked items
    listView.setClickable(true);
    listView.setOnItemClickListener((arg0, arg1, position, arg3) -> {
        ScrollPositions.getInstance().setPosition(listView.getFirstVisiblePosition());

        if (sortBy.startsWith("date")) {
            if (directEdit)
                listener.editNote(finalListByDate[position]);
            else
                listener.viewNote(finalListByDate[position]);
        } else if (sortBy.startsWith("name")) {
            if (directEdit)
                listener.editNote(finalListByName[position]);
            else
                listener.viewNote(finalListByName[position]);
        }
    });

    // Make ListView handle contextual action bar
    final ArrayList<String> cab = listener.getCabArray();

    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // Respond to clicks on the actions in the CAB
            switch (item.getItemId()) {
            case R.id.action_select_all:
                cab.clear();

                for (int i = 0; i < listView.getAdapter().getCount(); i++) {
                    listView.setItemChecked(i, true);
                }
                return false;
            case R.id.action_export:
                if (cab.size() > 0) {
                    mode.finish(); // Action picked, so close the CAB
                    listener.exportNotes();
                    return true;
                } else {
                    showToast(R.string.no_notes_to_export);
                    return false;
                }
            case R.id.action_delete:
                if (cab.size() > 0) {
                    mode.finish(); // Action picked, so close the CAB
                    listener.deleteNotes();
                    return true;
                } else {
                    showToast(R.string.no_notes_to_delete);
                    return false;
                }
            default:
                return false;
            }
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            listener.hideFab();

            // Inflate the menu for the CAB
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.context_menu, menu);

            // Clear any old values from cab array
            cab.clear();

            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            listener.showFab();
        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            if (position > -1) {
                // Add/remove filenames to cab array as they are checked/unchecked
                if (checked) {
                    if (sortBy.startsWith("date"))
                        cab.add(finalListByDate[position]);
                    if (sortBy.startsWith("name"))
                        cab.add(finalListByName[position]);
                } else {
                    if (sortBy.startsWith("date"))
                        cab.remove(finalListByDate[position]);
                    if (sortBy.startsWith("name"))
                        cab.remove(finalListByName[position]);
                }

                listView.setItemChecked(-1, false);
            }

            // Update the title in CAB
            mode.setTitle(cab.size() + " " + listener.getCabString(cab.size()));
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }
    });

    if (cab.size() > 0) {
        List<String> cabClone = new ArrayList<>(cab);
        cab.clear();

        String[] array = null;
        if (sortBy.startsWith("date"))
            array = finalListByDate;
        if (sortBy.startsWith("name"))
            array = finalListByName;

        if (array != null) {
            for (String filename : cabClone) {
                for (int i = 0; i < array.length; i++) {
                    if (filename.equals(array[i]))
                        listView.setItemChecked(i, true);
                }
            }
        }
    }

    // If there are no saved notes, then display the empty view
    if (numOfNotes == 0) {
        TextView empty = getActivity().findViewById(R.id.empty);
        listView.setEmptyView(empty);
    }
}

From source file:org.arrowhead.wp5.market.impl.Market.java

private double findPrice(List<Bid> demList, List<Bid> supList, double[] solutionPoint) {
    List<Bid> demandList = new ArrayList<Bid>();
    demandList.addAll(demList);// w  w  w.j av  a  2  s. c  o m
    List<Bid> supplyList = new ArrayList<Bid>();
    supplyList.addAll(supList);

    Collections.sort(demandList, Collections.reverseOrder());
    Collections.sort(supplyList);

    Collections.reverse(demandList);
    long[] demandCum = cumulative(demandList);
    Collections.reverse(demandList);
    long[] supplyCum = cumulative(supplyList);

    logger.debug("sorted: {}", demandList);
    logger.debug("sorted: {}", supplyList);

    if (demandList.get(0).getPrice() < supplyList.get(0).getPrice()) {
        return supplyList.get(0).getPrice() - (supplyList.get(0).getPrice() - demandList.get(0).getPrice()) / 2;
    }

    int i = 0;
    int j = 0;
    long demQuantity = demandCum[i];
    long supQuantity = supplyCum[j];
    long curDemQuantity = demandList.get(i).getQuantity();
    long curSupQuantity = supplyList.get(j).getQuantity();
    while (i < demandList.size() && j < supplyList.size()
            && demandList.get(i).getPrice() > supplyList.get(j).getPrice()) {
        if (curDemQuantity > curSupQuantity) {
            demQuantity -= supQuantity;
            curDemQuantity -= curSupQuantity;
            demandList.get(i).incrWinQuantity(curSupQuantity);
            if (demQuantity == 0 && i < demandList.size()) {
                assert (false);
                demQuantity = demandCum[i];
            }
            supplyList.get(j).incrWinQuantity(curSupQuantity);
            j++;
            if (j < supplyList.size()) {
                supQuantity = supplyCum[j];
                curSupQuantity = supplyList.get(j).getQuantity();
            }
        } else {
            supQuantity -= demQuantity;
            curSupQuantity -= curDemQuantity;
            supplyList.get(j).incrWinQuantity(curDemQuantity);
            if (supQuantity == 0 && j < supplyList.size()) {
                assert (false);
                supQuantity = supplyCum[j];
            }
            demandList.get(i).incrWinQuantity(curDemQuantity);
            i++;
            if (i < demandList.size()) {
                demQuantity = demandCum[i];
                curDemQuantity = demandList.get(i).getQuantity();
            }
        }
    }

    if (i < demandList.size() && j < supplyList.size()) {
        if (curSupQuantity > curDemQuantity) {
            supplyList.get(j).incrWinQuantity(curDemQuantity);
            return demandList.get(i).getPrice();
        } else {
            demandList.get(i).incrWinQuantity(curSupQuantity);
            return supplyList.get(j).getPrice();
        }
    }

    i = Math.min(i, demandList.size() - 1);
    j = Math.min(j, supplyList.size() - 1);
    //      while (i < demandList.size() && j < supplyList.size()) {
    //         logger.debug("while: i: {} j: {} td: {} ts: {}", i, j, totalDemand, totalSupply);
    //         long demPrice = demandList.get(i).getPrice();
    //         long supPrice = supplyList.get(j).getPrice();
    //         if (demPrice > supPrice) {
    //            if (supQuantity<totalDemand && supQuantity<demQuantity) {
    //               totalDemand -= supQuantity;
    //               demQuantity -= supQuantity;
    //               j++;
    //               supQuantity = supplyList.get(j).getQuantity();
    //            } else {
    //               return supPrice;
    //            }
    //         } else {
    //            if (demQuantity<totalSupply && demQuantity<supQuantity) {
    //               totalSupply -= demQuantity;
    //               supQuantity -= demQuantity;
    //               i++;
    //               demQuantity = demandList.get(i).getQuantity();
    //            } else {
    //               return demPrice;
    //            }
    //         }
    //      }
    //      for (int i = 0; i < demandList.size()-1; i++) {
    //         for (int j = 0; j < supplyList.size()-1; j++) {
    //            if (demandList.get(i+1).getPrice() > supplyList.get(j).getPrice());
    //         }
    //      }
    return demandList.get(i).getPrice() < supplyList.get(j).getPrice() ? demandList.get(i).getPrice()
            : supplyList.get(j).getPrice();
}

From source file:com.atex.confluence.plugin.nexus.MavenInfoMacro.java

/**
 * This method gather all releases from the artifact and generate the code of a drop down field at front end.
 * @param model/* www.  j a v a2s . co m*/
 * @param selected 
 * @return
 */
private String getReleasesDropDown(ExtendedModel model, String selected) {
    StringBuilder builder = new StringBuilder();
    Set<String> versions = new TreeSet<String>(Collections.reverseOrder());
    for (Artifact a : model.getArtifacts()) {
        versions.add(a.getVersion());
    }
    builder.append(" {html}");
    builder.append("\n <select id=\"");
    builder.append(model.getArtifactId());
    builder.append("\"");
    builder.append(" class=\"selectRelease\"> \n");
    int count = 0;
    for (String version : versions) {
        builder.append("<option value=\"");
        builder.append(version);
        builder.append("\"");
        if (count == 0 && selected == null) {
            builder.append(" selected=\"selected\"");
        } else {
            if (version.equals(selected)) {
                builder.append(" selected=\"selected\"");
            }
        }
        count++;
        builder.append(">");
        builder.append(version);
        builder.append("</option> \n ");
    }
    builder.append("</select> \n");
    builder.append("{html} \n ");
    return builder.toString();
}

From source file:org.stockwatcher.data.cassandra.StockDAOImpl.java

@Override
public List<Stock> getMostWatchedStocks(StatementOptions options, int limit) {
    List<Stock> stocks = new ArrayList<Stock>(limit);
    try {/*from w  ww .  j  av  a  2 s  . c om*/
        BoundStatement bs = selectStockWatchCounts.bind();
        Map<Long, Set<String>> map = new TreeMap<Long, Set<String>>(Collections.reverseOrder());
        for (Row row : execute(bs, options)) {
            long watchCount = row.getLong("watch_count");
            if (watchCount > 0) {
                Set<String> values = map.get(watchCount);
                if (values == null) {
                    values = new HashSet<String>();
                    map.put(watchCount, values);
                }
                values.add(row.getString("stock_symbol"));
            }
        }
        int count = 0;
        List<ResultSetFuture> futures = new ArrayList<ResultSetFuture>(limit);
        for (long i : map.keySet()) {
            Iterator<String> iter = map.get(i).iterator();
            while (iter.hasNext() && count++ < limit) {
                bs = selectStockBySymbol.bind();
                bs.setString("stock_symbol", iter.next());
                futures.add(executeAsync(bs, options));
            }
        }
        for (ResultSetFuture future : futures) {
            stocks.add(createStock(future.getUninterruptibly().one()));
        }
    } catch (DriverException e) {
        throw new DAOException(e);
    }
    return stocks;
}

From source file:com.compomics.util.experiment.identification.psm_scoring.psm_scores.HyperScore.java

/**
 * Returns the interpolation values for the given score histogram in the
 * form {a, b}.//from   w w w. j  a  va 2s  .  c o m
 *
 * @param scoreHistogram the score histogram
 * @param useCache if true the interpolation values will be stored in the
 * histograms in cache
 *
 * @return the interpolation values for the given score histogram
 */
public double[] getInterpolationValues(HashMap<Integer, Integer> scoreHistogram, boolean useCache) {

    ArrayList<Integer> bins = new ArrayList<Integer>(scoreHistogram.keySet());
    Collections.sort(bins, Collections.reverseOrder());
    ArrayList<Double> evalueFunctionX = new ArrayList<Double>(scoreHistogram.size());
    ArrayList<Double> evalueFunctionY = new ArrayList<Double>(scoreHistogram.size());
    Integer currentSum = 0;
    for (Integer bin : bins) {
        Integer nInBin = scoreHistogram.get(bin);
        if (nInBin != null) {
            currentSum += nInBin;
        }
        if (currentSum > 0) {
            Double xValue = new Double(bin);
            xValue = FastMath.log10(xValue);
            evalueFunctionX.add(xValue);
            Double yValue = new Double(currentSum);
            yValue = FastMath.log10(yValue);
            evalueFunctionY.add(yValue);
        }
    }
    if (evalueFunctionX.size() <= 1) {
        return null;
    }
    RegressionStatistics regressionStatistics = LinearRegression.getSimpleLinearRegression(evalueFunctionX,
            evalueFunctionY);
    if (useCache) {
        Double roundedA = Util.roundDouble(regressionStatistics.a, 2);
        Double roundedB = Util.roundDouble(regressionStatistics.b, 2);
        Integer nA = as.get(roundedA);
        if (nA == null) {
            as.put(roundedA, 1);
        } else {
            as.put(roundedA, nA + 1);
        }
        Integer nB = bs.get(roundedB);
        if (nB == null) {
            bs.put(roundedB, 1);
        } else {
            bs.put(roundedB, nB + 1);
        }
    }
    return new double[] { regressionStatistics.a, regressionStatistics.b };
}

From source file:com.kurtraschke.nyctrtproxy.services.TripUpdateProcessor.java

public List<GtfsRealtime.TripUpdate> processFeed(Integer feedId, GtfsRealtime.FeedMessage fm,
        MatchMetrics totalMetrics) {/* ww w  .  j a  v  a 2 s . c  o m*/

    long timestamp = fm.getHeader().getTimestamp();

    MatchMetrics feedMetrics = new MatchMetrics();
    feedMetrics.reportLatency(timestamp);

    if (_latencyLimit > 0 && feedMetrics.getLatency() > _latencyLimit) {
        _log.info("Feed {} ignored, too high latency = {}", feedId, feedMetrics.getLatency());
        if (_listener != null)
            _listener.reportMatchesForSubwayFeed(feedId.toString(), feedMetrics, _cloudwatchNamespace);
        return Collections.emptyList();
    }

    final Map<String, String> realtimeToStaticRouteMap = _realtimeToStaticRouteMapByFeed.getOrDefault(feedId,
            Collections.emptyMap());

    int nExpiredTus = 0, nTotalRecords = 0;

    // Read in trip updates per route. Skip trip updates that have too stale of data.
    Multimap<String, GtfsRealtime.TripUpdate> tripUpdatesByRoute = ArrayListMultimap.create();
    for (GtfsRealtime.FeedEntity entity : fm.getEntityList()) {
        if (entity.hasTripUpdate()) {
            GtfsRealtime.TripUpdate tu = entity.getTripUpdate();
            if (expiredTripUpdate(tu, fm.getHeader().getTimestamp())) {
                nExpiredTus++;
            } else {
                String routeId = tu.getTrip().getRouteId();
                routeId = realtimeToStaticRouteMap.getOrDefault(routeId, routeId);
                tripUpdatesByRoute.put(routeId, tu);
            }
            nTotalRecords++;
        }
    }
    reportRecordsIn(nTotalRecords, nExpiredTus, totalMetrics, feedMetrics);

    List<GtfsRealtime.TripUpdate> ret = Lists.newArrayList();

    for (GtfsRealtimeNYCT.TripReplacementPeriod trp : fm.getHeader()
            .getExtension(GtfsRealtimeNYCT.nyctFeedHeader).getTripReplacementPeriodList()) {
        if (_routeBlacklistByFeed.getOrDefault(feedId, Collections.emptySet()).contains(trp.getRouteId()))
            continue;
        GtfsRealtime.TimeRange range = trp.getReplacementPeriod();

        Date start = range.hasStart() ? new Date(range.getStart() * 1000)
                : earliestTripStart(tripUpdatesByRoute.values());
        Date end = range.hasEnd() ? new Date(range.getEnd() * 1000)
                : new Date(fm.getHeader().getTimestamp() * 1000);

        // All route IDs in this trip replacement period
        Set<String> routeIds = Arrays.stream(trp.getRouteId().split(", ?"))
                .map(routeId -> realtimeToStaticRouteMap.getOrDefault(routeId, routeId))
                .collect(Collectors.toSet());

        for (String routeId : routeIds) {
            String newRouteId = _addToTripReplacementPeriodByRoute.get(routeId);
            if (newRouteId != null)
                routeIds.add(newRouteId);
        }

        // Kurt's trip matching algorithm (ActivatedTripMatcher) requires calculating currently-active static trips at this point.
        _tripMatcher.initForFeed(start, end, routeIds);

        for (String routeId : routeIds) {

            MatchMetrics routeMetrics = new MatchMetrics();

            Multimap<String, TripMatchResult> matchesByTrip = ArrayListMultimap.create();
            Collection<GtfsRealtime.TripUpdate> tripUpdates = tripUpdatesByRoute.get(routeId);
            routeMetrics.reportRecordsIn(tripUpdates.size());
            for (GtfsRealtime.TripUpdate tu : tripUpdates) {
                GtfsRealtime.TripUpdate.Builder tub = GtfsRealtime.TripUpdate.newBuilder(tu);
                GtfsRealtime.TripDescriptor.Builder tb = tub.getTripBuilder();

                // rewrite route ID for some routes
                tb.setRouteId(realtimeToStaticRouteMap.getOrDefault(tb.getRouteId(), tb.getRouteId()));

                // remove timepoints not in GTFS... in some cases this means there may be no STUs left (ex. H shuttle at H19S.)
                removeTimepoints(tub);

                // get ID which consists of route, direction, origin-departure time, possibly a path identifier (for feed 1.)
                NyctTripId rtid = NyctTripId.buildFromTripDescriptor(tb, _routesWithReverseRTDirections);

                // If we were able to parse the trip ID, there are various fixes
                // we may need to apply.
                if (rtid != null) {

                    // Fix stop IDs which don't include direction
                    tub.getStopTimeUpdateBuilderList().forEach(stub -> {
                        if (!(stub.getStopId().endsWith("N") || stub.getStopId().endsWith("S"))) {
                            stub.setStopId(stub.getStopId() + rtid.getDirection());
                        } else if (_routesWithReverseRTDirections.contains(tb.getRouteId())) {
                            String stopId = stub.getStopId();
                            stub.setStopId(stopId.substring(0, stopId.length() - 1) + rtid.getDirection());
                        }
                        if (_stopIdTransformStrategy != null) {
                            String stopId = stub.getStopId();
                            stopId = _stopIdTransformStrategy.transform(rtid.getRouteId(), rtid.getDirection(),
                                    stopId);
                            stub.setStopId(stopId);
                        }
                    });

                    // Re-set the trip ID to the parsed trip ID; coerces IDs to a uniform format.
                    // If the trip is matched, the ID will be rewritten again to the corresponding static trip ID below.
                    tb.setTripId(rtid.toString());
                } else {
                    _log.error("invalid trip_id={} train_id={}", tb.getTripId(),
                            tb.getExtension(GtfsRealtimeNYCT.nyctTripDescriptor).getTrainId());
                }

                // Some routes have start date set incorrectly
                if (tb.getStartDate().length() > 8) {
                    tb.setStartDate(fixedStartDate(tb));
                }

                TripMatchResult result = _tripMatcher.match(tub, rtid, fm.getHeader().getTimestamp());
                matchesByTrip.put(result.getTripId(), result);
            }

            // For TUs that match to same trip - possible they should be merged (route D has mid-line relief points where trip ID changes)
            // If they are NOT merged, then drop the matches for the worse ones
            for (Collection<TripMatchResult> matches : matchesByTrip.asMap().values()) {
                if (!tryMergeResult(matches) && matches.size() > 1 && !_allowDuplicates) {
                    List<TripMatchResult> dups = new ArrayList<>(matches);
                    dups.sort(Collections.reverseOrder());
                    TripMatchResult best = dups.get(0);
                    for (int i = 1; i < dups.size(); i++) {
                        TripMatchResult result = dups.get(i);
                        _log.debug(
                                "dropping duplicate in static trip={}, RT trip={} ({}). Better trip is {} ({})",
                                best.getTripId(), result.getRtTripId(), result.getStatus(), best.getRtTripId(),
                                best.getStatus());
                        result.setStatus(Status.NO_MATCH);
                        result.setResult(null);
                    }
                }
            }

            Set<String> matchedTripIds = new HashSet<>();
            // Read out results of matching. If there is a match, rewrite TU's trip ID. Add TU to return list.
            for (TripMatchResult result : matchesByTrip.values()) {
                if (!result.getStatus().equals(Status.MERGED)) {
                    GtfsRealtime.TripUpdate.Builder tub = result.getTripUpdateBuilder();
                    GtfsRealtime.TripDescriptor.Builder tb = tub.getTripBuilder();
                    if (result.hasResult() && (result.getTripUpdate().getStopTimeUpdateCount() == 0
                            || !result.stopsMatchToEnd())) {
                        _log.info("no stop match rt={} static={} {}",
                                result.getTripUpdate().getTrip().getTripId(),
                                result.getResult().getTrip().getId().getId(),
                                (result.getResult().getStopTimes().get(0).getDepartureTime() / 60) * 100);
                        result.setStatus(Status.NO_MATCH);
                        result.setResult(null);
                    }
                    if (result.hasResult()) {
                        ActivatedTrip at = result.getResult();
                        String staticTripId = at.getTrip().getId().getId();
                        _log.debug("matched {} -> {}", tb.getTripId(), staticTripId);
                        tb.setTripId(staticTripId);
                        removeTimepoints(at, tub);
                        matchedTripIds.add(staticTripId);
                    } else {
                        _log.debug("unmatched: {} due to {}", tub.getTrip().getTripId(), result.getStatus());
                        tb.setScheduleRelationship(GtfsRealtime.TripDescriptor.ScheduleRelationship.ADDED);
                        // ignore ADDED trips without stops
                        if (tub.getStopTimeUpdateCount() == 0)
                            continue;
                        // Trip Headsign and direction
                        String stopId = result.getRtLastStop();
                        String tripHeadsign = _tripActivator.getStopNameForId(stopId);
                        String nsDirection = NyctTripId
                                .buildFromTripDescriptor(tub.getTrip(), _routesWithReverseRTDirections)
                                .getDirection();
                        String tripDirection = "S".equals(nsDirection) ? "1" : "0";
                        GtfsRealtimeOneBusAway.OneBusAwayTripUpdate.Builder obaTripUpdate = GtfsRealtimeOneBusAway.OneBusAwayTripUpdate
                                .newBuilder();
                        if (StringUtils.isNotBlank(tripHeadsign)) {
                            obaTripUpdate.setTripHeadsign(tripHeadsign);
                            //Stop Headsign
                            if (_directionsService != null)
                                _directionsService.fillStopHeadSigns(tub.getStopTimeUpdateBuilderList());
                        }
                        obaTripUpdate.setTripDirection(tripDirection);
                        tub.setExtension(GtfsRealtimeOneBusAway.obaTripUpdate, obaTripUpdate.build());
                    }
                    tub.setTimestamp(timestamp);
                    TripUpdate tripUpdate = tub.build();
                    ret.add(tripUpdate);
                }

                routeMetrics.add(result);
                feedMetrics.add(result);
                totalMetrics.add(result);
            }

            if (_cancelUnmatchedTrips) {
                Iterator<ActivatedTrip> staticTrips = _tripActivator
                        .getTripsForRangeAndRoute(start, end, routeId).iterator();
                while (staticTrips.hasNext()) {
                    ActivatedTrip at = staticTrips.next();
                    if (!matchedTripIds.contains(at.getTrip().getId().getId())) {
                        long time = fm.getHeader().getTimestamp();
                        if (at.activeFor(trp, time)) {
                            TripUpdate.Builder tub = TripUpdate.newBuilder();
                            TripDescriptor.Builder tdb = tub.getTripBuilder();
                            tdb.setTripId(at.getTrip().getId().getId());
                            tdb.setRouteId(at.getTrip().getRoute().getId().getId());
                            tdb.setStartDate(at.getServiceDate().getAsString());
                            tdb.setScheduleRelationship(ScheduleRelationship.CANCELED);
                            ret.add(tub.build());

                            routeMetrics.addCancelled();
                            feedMetrics.addCancelled();
                            totalMetrics.addCancelled();
                        }
                    }
                }
            }

            if (_listener != null)
                _listener.reportMatchesForRoute(routeId, routeMetrics, _cloudwatchNamespace);
        }
    }

    if (_listener != null)
        _listener.reportMatchesForSubwayFeed(feedId.toString(), feedMetrics, _cloudwatchNamespace);

    _log.info("feed={}, expired TUs={}", feedId, nExpiredTus);
    return ret;
}

From source file:org.pentaho.ui.xul.swing.tags.SwingTree.java

public void removeTreeRows(int[] rows) {

    // sort the rows high to low
    ArrayList<Integer> rowArray = new ArrayList<Integer>();
    for (int i = 0; i < rows.length; i++) {
        rowArray.add(rows[i]);/*from  w  w w.j a v  a 2  s  . c  o  m*/
    }
    Collections.sort(rowArray, Collections.reverseOrder());

    // remove the items in that order
    for (int i = 0; i < rowArray.size(); i++) {
        int item = rowArray.get(i);
        if (item >= 0 && item < getRootChildren().getItemCount()) {
            getRootChildren().removeItem(item);
        }
    }

    table.updateUI();
    // treat as selection change.
    changeSupport.firePropertyChange("selectedRows", null, getSelectedRows()); //$NON-NLS-1$
    changeSupport.firePropertyChange("absoluteSelectedRows", null, getAbsoluteSelectedRows()); //$NON-NLS-1$
}

From source file:org.t3.metamediamanager.TheMovieDBProvider.java

private HashMap<String, String[]> getAllImages(String id, String language) {
    HashMap<String, String[]> res = new HashMap<String, String[]>(); //Final hashmap to be returned

    String query = String.format("http://api.themoviedb.org/3/movie/" + id + "/images?api_key=" + apiKey);

    try {//w  w  w  . j ava2s  .c  o  m
        URLConnection connection = new URL(query).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        InputStream response = connection.getInputStream();
        String rep = convertStreamToString(response);

        JSONObject json = convertStringToJSON(rep);

        String[] types = { "backdrops", "posters" };

        //We only select the 10 most voted images. We use this class to do the final sort
        class ImageInfo implements Comparable<ImageInfo> {
            String name;
            double priority;

            @Override
            public int compareTo(ImageInfo o) {
                return (int) (priority - o.priority);
            }
        }

        //Use of a temp hashmap with a list to be sorted
        HashMap<String, List<ImageInfo>> tmpRes = new HashMap<String, List<ImageInfo>>();

        //For each type of image (poster or backdrop)
        for (String type : types) {
            if (json.has(type)) {
                JSONArray typeJson = json.getJSONArray(type);

                List<ImageInfo> imgList = new ArrayList<ImageInfo>();

                tmpRes.put(type, imgList);

                int nbImages = typeJson.length();
                for (int i = 0; i < nbImages; i++) //For every image
                {
                    JSONObject imgObject = typeJson.getJSONObject(i);

                    if (imgObject.has("file_path") && imgObject.has("vote_average")
                            && imgObject.has("iso_639_1")) {
                        if (imgObject.isNull("iso_639_1")
                                || imgObject.getString("iso_639_1").equals(language)) {
                            ImageInfo ii = new ImageInfo();
                            ii.name = imgObject.getString("file_path");
                            ii.priority = imgObject.getDouble("vote_average");
                            imgList.add(ii);
                        }

                    }
                }

                //We sort by priority/vote
                Collections.sort(imgList, Collections.reverseOrder());

                int nbImagesFinal = (imgList.size() > 10) ? 10 : imgList.size();
                res.put(type, new String[nbImagesFinal]);
                for (int i = 0; i < nbImagesFinal; i++) {
                    res.get(type)[i] = createPicture(imgList.get(i).name); //Download the image, and keep the filename of the temp file
                }
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return res;
}

From source file:com.tilab.ca.sse.core.classify.Classifier.java

private List<ScoreDoc> sortByRank(Map<ScoreDoc, Integer> inputList) {
    LOG.debug("[sortByRank] - BEGIN");
    List<ScoreDoc> result = new ArrayList<>();
    LinkedMap apacheMap = new LinkedMap(inputList);
    for (int i = 0; i < apacheMap.size() - 1; i++) {
        Map<Float, ScoreDoc> treeMap = new TreeMap<>(Collections.reverseOrder());
        do {/*from  w  ww. j a  v a2  s  . co  m*/
            i++;
            treeMap.put(((ScoreDoc) apacheMap.get(i - 1)).score, (ScoreDoc) apacheMap.get(i - 1));
        } while (i < apacheMap.size() && apacheMap.getValue(i) == apacheMap.getValue(i - 1));
        i--;
        treeMap.keySet().stream().forEach((score) -> {
            result.add(treeMap.get(score));
        });
    }
    LOG.debug("[sortByRank] - END");
    return result;
}

From source file:org.fenixedu.ulisboa.specifications.ui.renderers.student.curriculum.StudentCurricularPlanLayout.java

/**
 * qubExtension, Curricular Years organization
 */// w w w.  j av  a2s  .c o m
protected void generateRowsForCurricularYearsOrganization(final HtmlTable mainTable) {
    final Map<String, Set<CurriculumLine>> collected = Maps.newTreeMap(Collections.reverseOrder());

    for (final CurriculumLine iter : getPlan().getAllCurriculumLines()) {
        if (isToShow(iter)) {

            final String key = iter instanceof Enrolment ? getCurricularPeriodLabel((Enrolment) iter)
                    : getCurricularPeriodLabel((Dismissal) iter);
            if (!Strings.isNullOrEmpty(key)) {

                Set<CurriculumLine> set = collected.get(key);
                if (set == null) {
                    set = Sets.newTreeSet(CurriculumLineServices.COMPARATOR);
                }
                set.add(iter);
                collected.put(key, set);
            }
        }
    }

    // qubExtension
    final int level = 1;
    generateGroupRowWithText(mainTable, getPresentationNameFor(getPlan().getRoot()), false, 0,
            (CurriculumGroup) null);

    for (final Entry<String, Set<CurriculumLine>> entry : collected.entrySet()) {
        if (!entry.getValue().isEmpty()) {

            generateGroupRowWithText(mainTable, entry.getKey(), true, level, (CurriculumGroup) null);

            for (final CurriculumLine iter : entry.getValue()) {
                if (iter instanceof Enrolment) {
                    generateEnrolmentRow(mainTable, (Enrolment) iter, level);
                }
                if (iter instanceof Dismissal) {
                    generateDismissalRow(mainTable, (Dismissal) iter, level);
                }
            }
        }
    }
}