Example #1
1
  public SelectMany05Bean() {

    HobbitBean[] hobbits = {
      new HobbitBean("Bilbo", "Ring Finder"),
      new HobbitBean("Frodo", "Ring Bearer"),
      new HobbitBean("Merry", "Trouble Maker"),
      new HobbitBean("Pippin", "Trouble Maker")
    };

    Set<SelectItem> items = new LinkedHashSet<SelectItem>();
    for (HobbitBean hobbit : hobbits) {
      items.add(new SelectItem(hobbit.getName()));
    }
    hobbitCollection = new TreeSet<HobbitBean>();
    hobbitCollection.addAll(Arrays.asList(hobbits));
    possibleValues = Collections.unmodifiableSet(items);
    initialSortedSetValues = new TreeSet<String>(Collections.reverseOrder());
    initialSortedSetValues.add("Pippin");
    initialSortedSetValues.add("Frodo");
    initialCollectionValues = new LinkedHashSet<String>(2);
    initialCollectionValues.add("Bilbo");
    initialCollectionValues.add("Merry");
    initialSetValues = new CopyOnWriteArraySet<String>(); // not Cloneable
    initialSetValues.add("Frodo");
    initialListValues = new Vector<String>();
    initialListValues.add("Bilbo");
    initialListValues.add("Pippin");
    initialListValues.add("Merry");
    hobbitDataModel =
        new ListDataModel<HobbitBean>(new ArrayList<HobbitBean>(Arrays.asList(hobbits)));
  }
Example #2
0
 /**
  * Ranks the set of items by associated score.
  *
  * @param userItems map with scores for each item
  * @return the ranked list
  */
 protected List<Long> rankItems(Map<Long, Double> userItems) {
   List<Long> sortedItems = new ArrayList<Long>();
   if (userItems == null) {
     return sortedItems;
   }
   Map<Double, Set<Long>> itemsByRank = new HashMap<Double, Set<Long>>();
   for (Map.Entry<Long, Double> e : userItems.entrySet()) {
     long item = e.getKey();
     double pref = e.getValue();
     if (Double.isNaN(pref)) {
       // we ignore any preference assigned as NaN
       continue;
     }
     Set<Long> items = itemsByRank.get(pref);
     if (items == null) {
       items = new HashSet<Long>();
       itemsByRank.put(pref, items);
     }
     items.add(item);
   }
   List<Double> sortedScores = new ArrayList<Double>(itemsByRank.keySet());
   Collections.sort(sortedScores, Collections.reverseOrder());
   for (double pref : sortedScores) {
     List<Long> sortedPrefItems = new ArrayList<Long>(itemsByRank.get(pref));
     // deterministic output when ties in preferences: sort by item id
     Collections.sort(sortedPrefItems, Collections.reverseOrder());
     for (long itemID : sortedPrefItems) {
       sortedItems.add(itemID);
     }
   }
   return sortedItems;
 }
  public Map<Integer, Integer> withdrawAmount(int expectedAmount) throws NotEnoughMoneyException {
    Map<Integer, Integer> result = new TreeMap<>(Collections.reverseOrder());
    Map<Integer, Integer> temp = new TreeMap<>(Collections.reverseOrder());
    int n, rest = 0;

    for (Map.Entry<Integer, Integer> entry : denominations.entrySet()) {
      n = expectedAmount / entry.getKey();
      if (n != 0) {
        if (n > entry.getValue()) {
          rest = (n - entry.getValue()) * entry.getKey();
          n = entry.getValue();
        }
        result.put(entry.getKey(), n);
      }

      temp.put(entry.getKey(), entry.getValue() - n);
      expectedAmount = expectedAmount % entry.getKey() + rest;

      rest = 0;
    }

    if (expectedAmount != 0) {
      throw new NotEnoughMoneyException();
    }

    denominations.clear();
    denominations.putAll(temp);

    // ConsoleHelper.writeMessage("Withdrawal request was successfully processed");
    return result;
  }
Example #4
0
  public void testSortOrder() {
    Comparator<Long> comp = Collections.reverseOrder();
    assertSortOrder(
        new ReverseLexicoder<Long>(new LongLexicoder()),
        comp,
        Long.MIN_VALUE,
        0xff1234567890abcdl,
        0xffff1234567890abl,
        0xffffff567890abcdl,
        0xffffffff7890abcdl,
        0xffffffffff90abcdl,
        0xffffffffffffabcdl,
        0xffffffffffffffcdl,
        -1l,
        0l,
        0x01l,
        0x1234l,
        0x123456l,
        0x12345678l,
        0x1234567890l,
        0x1234567890abl,
        0x1234567890abcdl,
        0x1234567890abcdefl,
        Long.MAX_VALUE);

    Comparator<String> comp2 = Collections.reverseOrder();
    assertSortOrder(
        new ReverseLexicoder<String>(new StringLexicoder()), comp2, "a", "aa", "ab", "b", "aab");
  }
 @Test
 public void toSortedSet_with_comparator() {
   LazyIterable<Integer> integers = this.newWith(2, 4, 4, 2, 1, 4, 1, 3);
   MutableSortedSet<Integer> set = integers.toSortedSet(Collections.<Integer>reverseOrder());
   Verify.assertSortedSetsEqual(
       TreeSortedSet.newSetWith(Collections.<Integer>reverseOrder(), 1, 2, 3, 4), set);
 }
 @Test
 public void toSortedSet_with_comparator() {
   this.unmodifiableCollection = this.newWith("2", "4", "4", "2", "1", "4", "1", "3");
   MutableSortedSet<String> set =
       this.unmodifiableCollection.toSortedSet(Collections.<String>reverseOrder());
   Verify.assertSortedSetsEqual(
       TreeSortedSet.newSetWith(Collections.<String>reverseOrder(), "1", "2", "3", "4"), set);
 }
 @Override
 @Test
 public void toSortedBag_with_comparator() {
   RichIterable<Integer> integers = this.newWith(2, 4, 1, 3);
   MutableSortedBag<Integer> bag = integers.toSortedBag(Collections.<Integer>reverseOrder());
   Verify.assertSortedBagsEqual(
       TreeBag.newBagWith(Collections.<Integer>reverseOrder(), 4, 3, 2, 1), bag);
 }
 @Test
 public void toSortedList() {
   ImmutableBag<String> strings = this.newBag();
   MutableList<String> copy = FastList.newList(strings);
   MutableList<String> list = strings.toSortedList(Collections.<String>reverseOrder());
   Assert.assertEquals(copy.sortThis(Collections.<String>reverseOrder()), list);
   MutableList<String> list2 = strings.toSortedList();
   Assert.assertEquals(copy.sortThis(), list2);
 }
 @Test
 public void toSortedList() {
   ImmutableCollection<Integer> integers = this.classUnderTest();
   MutableList<Integer> copy = FastList.newList(integers);
   MutableList<Integer> list = integers.toSortedList(Collections.<Integer>reverseOrder());
   Assert.assertEquals(copy.sortThis(Collections.<Integer>reverseOrder()), list);
   MutableList<Integer> list2 = integers.toSortedList();
   Assert.assertEquals(copy.sortThis(), list2);
 }
 private void updateScores() {
   switch (selectedGame) {
     case "wordex":
       game = "ΛΕΞΟΜΑΝΤΕΙΑ";
       break;
     case "wordsearch":
       game = "ΚΡΥΠΤΟΛΕΞΟ";
       break;
     case "splitwords":
       game = "ΑΝΤΙΣΤΟΙΧΙΣΗ";
       break;
     case "wordsFromALetter":
       game = "ΛΕΞΕΙΣ ΑΠΟ ΓΡΑΜΜΑ";
       break;
     case "correctSpelling":
       game = "ΣΩΣΤΗ ΟΡΘΟΓΡΑΦΙΑ";
       break;
     case "correctSpelling2":
       game = "ΣΩΣΤΗ ΟΡΘΟΓΡΑΦΙΑ 2";
       break;
     case "namesAnimalsPlants":
       game = "ΟΝΟΜΑTA, ΖΩΑ, ΦΥΤΑ";
       break;
     case "coloredBoxes":
       game = "ΧΡΩΜΑΤΙΣΤΑ ΚΟΥΤΙΑ";
       break;
     case "matchCards":
       game = "ΤΑΙΡΙΑΞΕ ΚΑΡΤΕΣ";
       break;
     case "faceNameHouse":
       game = "Face Name House";
       break;
   }
   try {
     gameScores = db.getScores(game);
     gScoresContents = FXCollections.observableArrayList();
     Collections.sort(gameScores, Collections.reverseOrder());
     for (int i = 0; i < Math.min(gameScores.size(), 5); i++) {
       gScoresContents.add(gameScores.get(i));
     }
     gScores.setItems(gScoresContents);
     personalScores = db.getScores(player, game);
     pScoresContents = FXCollections.observableArrayList();
     Collections.sort(personalScores, Collections.reverseOrder());
     for (int i = 0; i < Math.min(personalScores.size(), 5); i++) {
       pScoresContents.add(personalScores.get(i));
     }
     pScores.setItems(pScoresContents);
   } catch (SQLException ex) {
     // TODO handle score exceptions
   }
 }
  @Override
  public void remove(final int removedIndex) {
    if (removedIndex < 0) {
      return;
    }
    super.remove(removedIndex);
    _rightClickActionListeners.remove(removedIndex);
    _doubleClickActionListeners.remove(removedIndex);

    // move all right click listeners for tabs above this index down
    {
      Set<Integer> keySet = new TreeSet<Integer>(Collections.reverseOrder());
      keySet.addAll(_rightClickActionListeners.keySet());
      for (Integer key : keySet) {
        int curIndex = key.intValue();
        if (curIndex > removedIndex) {
          ActionListener actionListener = _rightClickActionListeners.get(curIndex);
          _rightClickActionListeners.remove(curIndex);
          _rightClickActionListeners.put(curIndex - 1, actionListener);
        }
      }
    }

    // move all double click listeners for tabs above this index down
    {
      Set<Integer> keySet = new TreeSet<Integer>(Collections.reverseOrder());
      keySet.addAll(_doubleClickActionListeners.keySet());
      for (Integer key : keySet) {
        int curIndex = key.intValue();
        if (curIndex > removedIndex) {
          ActionListener actionListener = _doubleClickActionListeners.get(curIndex);
          _doubleClickActionListeners.remove(curIndex);
          _doubleClickActionListeners.put(curIndex - 1, actionListener);
        }
      }
    }

    // moved all the uncloseable tabs for tabs above this index down
    {
      for (ListIterator<Integer> it = _unclosables.listIterator(); it.hasNext(); ) {
        Integer tabIndex = it.next();
        int curIndex = tabIndex.intValue();
        if (curIndex == removedIndex) {
          it.remove();
        } else if (curIndex > removedIndex) {
          it.set(curIndex - 1);
        }
      }
    }
  }
 /** Sorts the wishlist based on wishlistSortType and wishlistSortOrder */
 private void sortWishlist() {
   /* If no sort type specified, return */
   if (wishlistSortType != SORT_TYPE_NONE) {
     if (wishlistSortOrder == ASCENDING) {
       switch (wishlistSortType) {
         case SORT_TYPE_CMC:
           Collections.sort(mCompressedWishlist, new WishlistComparatorCmc());
           break;
         case SORT_TYPE_COLOR:
           Collections.sort(mCompressedWishlist, new WishlistComparatorColor());
           break;
         case SORT_TYPE_NAME:
           Collections.sort(mCompressedWishlist, new WishlistComparatorName());
           break;
         case SORT_TYPE_PRICE:
           Collections.sort(mCompressedWishlist, new WishlistComparatorPrice(mPriceSetting));
           break;
         case SORT_TYPE_SET:
           Collections.sort(mCompressedWishlist, new WishlistComparatorSet());
           break;
       }
     } else {
       switch (wishlistSortType) {
         case SORT_TYPE_CMC:
           Collections.sort(
               mCompressedWishlist, Collections.reverseOrder(new WishlistComparatorCmc()));
           break;
         case SORT_TYPE_COLOR:
           Collections.sort(
               mCompressedWishlist, Collections.reverseOrder(new WishlistComparatorColor()));
           break;
         case SORT_TYPE_NAME:
           Collections.sort(
               mCompressedWishlist, Collections.reverseOrder(new WishlistComparatorName()));
           break;
         case SORT_TYPE_PRICE:
           Collections.sort(
               mCompressedWishlist,
               Collections.reverseOrder(new WishlistComparatorPrice(mPriceSetting)));
           break;
         case SORT_TYPE_SET:
           Collections.sort(
               mCompressedWishlist, Collections.reverseOrder(new WishlistComparatorSet()));
           break;
       }
     }
     mWishlistAdapter.notifyDataSetChanged();
   }
 }
  public void dump(PrintWriter out, WordPairStats wpStats, boolean reverse) {
    if (wpStats == null || !wpStats.hasStats()) {
      dump(out);
      return;
    }

    FullStatFig entropyFig = new FullStatFig();
    FullStatFig numTranslationsFig = new FullStatFig();
    FullStatFig sumFig = new FullStatFig();

    // Sort English words by decreasing frequency
    ArrayList<Pair<Double, String>> entries1 = new ArrayList<Pair<Double, String>>();
    for (String s : keySet()) {
      double count = wpStats.enCount(reverse, s);
      entries1.add(new Pair<Double, String>(count, s));
    }
    Collections.sort(
        entries1, Collections.reverseOrder(new Pair.FirstComparator<Double, String>()));

    for (Pair<Double, String> vs : entries1) {
      String s = vs.getSecond();
      StringDoubleMap m = getMap(s, false);

      FullStatFig fig = new FullStatFig(m.values());
      entropyFig.add(fig.entropy());
      numTranslationsFig.add(fig.size());
      sumFig.add(fig.total());

      out.printf(
          "%s\tentropy %s\tnTrans %d\tsum %f\tn %.0f\n",
          s, Fmt.D(fig.entropy()), fig.size(), fig.total(), vs.getFirst());

      ArrayList<StringDoubleMap.Entry> entries2 =
          new ArrayList<StringDoubleMap.Entry>(m.entrySet());
      Collections.sort(entries2, Collections.reverseOrder(m.entryValueComparator()));

      for (StringDoubleMap.Entry tv : entries2) {
        if (tv.getValue() < 1e-10) continue; // Skip zero entries
        String t = tv.getKey();
        double count = wpStats.frCount(reverse, t);
        double dice = wpStats.dice(reverse, s, t);
        out.printf("  %s: %f\tn %.0f, dice=%f\n", t, tv.getValue(), count, dice);
      }
    }

    out.println("# entropy = " + entropyFig);
    out.println("# sum = " + sumFig);
    out.println("# numTranslations = " + numTranslationsFig);
  }
Example #14
0
  public static void TopFilm() {

    Query query = JPA.em().createQuery("SELECT n FROM NoteMovie AS n");

    List<NoteMovie> topFilm = query.getResultList();
    List<NoteMovie> topFilm2 = new ArrayList<NoteMovie>();

    if (topFilm.size() > 0) {
      for (int i = 0; i < topFilm.size(); i++) {
        if (topFilm2.size() == 0)
          topFilm2.add(
              new NoteMovie(
                  (int) NoteMovies.moyenne(topFilm.get(i).Movie),
                  new User("1", "2", "3", "4", "5"),
                  topFilm.get(i).Movie));
        else {
          boolean deja = false;
          for (int j = 0; j < topFilm2.size(); j++) {
            if (topFilm2.get(j).Movie == topFilm.get(i).Movie) deja = true;
          }
          if (!deja)
            topFilm2.add(
                new NoteMovie(
                    (int) NoteMovies.moyenne(topFilm.get(i).Movie),
                    new User("1", "2", "3", "4", "5"),
                    topFilm.get(i).Movie));
        }
      }
    }
    Collections.sort(topFilm2, Collections.reverseOrder());

    render("Top/TopFilm.html", topFilm2);
  }
Example #15
0
  public void doIt() {
    Iterator iter;
    Collection ref;

    ref = new ArrayList();
    Populator.fillIt(ref);
    iter = ref.iterator();
    while (iter.hasNext()) {
      System.out.print(iter.next() + " ");
    } // end while loop
    System.out.println();

    Collections.reverse((List) ref);
    iter = ref.iterator();
    while (iter.hasNext()) {
      System.out.print(iter.next() + " ");
    } // end while loop
    System.out.println();

    Comparator aComparator = Collections.reverseOrder();
    Collections.sort((List) ref, aComparator);
    iter = ref.iterator();
    while (iter.hasNext()) {
      System.out.print(iter.next() + " ");
    } // end while loop
    System.out.println();
  } // end doIt()
Example #16
0
  public static void main(String[] args) {
    //		Sorting sr = new Sorting();
    //		int[] unSortedArray = {1, 4, 10, 0, 2, 9};
    // System.out.println(Arrays.toString(sr.swap(unSortedArray, 0, 4)));
    // sr.selectionSort(unSortedArray);
    //		int[] sortedArray = sr.bubbleSort(unSortedArray);
    //		System.out.println(Arrays.toString(sortedArray));

    // String result = (sr.binarySearch(sortedArray, 0,
    // sortedArray.length - 1, 11) != -1) ? "Match found" : "No Match";

    // System.out.println(result + " at " + sr.binarySearch(sortedArray, 0,
    // sortedArray.length - 1, 11) + "th position");
    //		System.out.println(sr.binarySearch(sortedArray, 0,
    //				sortedArray.length - 1, 8));

    Scanner scan = new Scanner(System.in);
    int len = scan.nextInt();

    Integer[] arrIn = new Integer[len];

    for (int i = 0; i < len; i++) {
      arrIn[i] = scan.nextInt();
    }

    System.out.println("Input: First Line: " + len + "--- Second Line: " + Arrays.toString(arrIn));

    Arrays.sort(arrIn, Collections.reverseOrder());
    System.out.println(Arrays.toString(arrIn));
    //		insertionSort1(len, arrIn);

  }
  @Override
  protected void executeCommand() {
    List<VM> vms = getVmDao().getAllRunningForVds(getVdsId());
    Collections.sort(vms, Collections.reverseOrder(new VmsComparer()));
    List<Guid> autoStartVmIdsToRerun = new ArrayList<>();
    for (VM vm : vms) {
      if (vm.isAutoStartup()) {
        autoStartVmIdsToRerun.add(vm.getId());
      }
      VDSReturnValue returnValue =
          runVdsCommand(
              VDSCommandType.SetVmStatus,
              new SetVmStatusVDSCommandParameters(vm.getId(), VMStatus.Down, VmExitStatus.Error));
      // Write that this VM was shut down by host reboot or manual fence
      if (returnValue != null && returnValue.getSucceeded()) {
        logSettingVmToDown(getVds().getId(), vm.getId());
      }

      runInternalActionWithTasksContext(
          VdcActionType.ProcessDownVm, new ProcessDownVmParameters(vm.getId(), true));
    }

    runVdsCommand(
        VDSCommandType.UpdateVdsVMsCleared,
        new UpdateVdsVMsClearedVDSCommandParameters(getVdsId()));
    if (!autoStartVmIdsToRerun.isEmpty()) {
      haAutoStartVmsRunner.addVmsToRun(autoStartVmIdsToRerun);
    }
    setSucceeded(true);
  }
  /**
   * this method finds out the minOccurrenc count to be one of the n best and deletes nodes with
   * lower support
   *
   * @param graph the graph
   * @param maxNumber the x most relevant semantic concepts
   */
  private void filterNMostOccurringNodes(WTPGraph graph, int maxNumber) {

    // to find out the minimal occurrence count to be under the n most occurring nodes (needed for
    // sorting)
    List<Integer> occurrencesCounts = new ArrayList<Integer>();

    // add each of the occurrences counters in the occurrencesCounts list
    for (String key : countOfNodeOccurrencesInPaths.keySet()) {
      Integer count = countOfNodeOccurrencesInPaths.get(key);
      if (count != null) occurrencesCounts.add(count);
    }

    // sorting
    Collections.sort(occurrencesCounts, Collections.reverseOrder());

    // int count = occurrencesCounts.size();

    // if something went wrong
    if (occurrencesCounts == null || occurrencesCounts.isEmpty()) return;
    // if there are already less than the n nodes that have to be filtered
    if (occurrencesCounts.size() <= maxNumber) {
      return;
    } else {
      Integer minOccurrences = occurrencesCounts.get(maxNumber - 1);
      removeNodesWithLessThanNOccurrences(graph, minOccurrences);
    }
  }
  public List<Integer> rankItems(Collection<Integer> users, Collection<Integer> items) {
    ItemRecommender item_recommender = (ItemRecommender) recommender;
    HashMap<Integer, Integer> user_weights = new HashMap<Integer, Integer>();
    for (int user_id : users) {
      user_weights.put(
          user_id, item_recommender.getFeedback().userMatrix().getEntriesByRow(user_id).size());
    }

    List<WeightedItem> average_scores = new ArrayList<WeightedItem>(items.size());

    for (int item_id : items) {
      WeightedItem weightedItem = new WeightedItem(item_id, 0.0);
      for (int user_id : users) {
        // TODO consider taking CanPredict into account
        weightedItem.weight += user_weights.get(user_id) * recommender.predict(user_id, item_id);
      }
      weightedItem.weight = weightedItem.weight / users.size();
      average_scores.add(item_id, weightedItem);
    }

    Collections.sort(average_scores, Collections.reverseOrder());
    List<Integer> ranked_items = new ArrayList<Integer>(average_scores.size());
    for (int i = 0; i < average_scores.size(); i++) {
      ranked_items.add(i, average_scores.get(i).item_id);
    }

    return ranked_items;
  }
Example #20
0
  public static void main(String[] args) {
    String[] newString = new String[args.length];
    int counter = 0;

    if (args[(args.length) - 1].equals("down")) {
      counter = 1;
    }

    for (int i = 0; i < args.length; i++) {
      if (System.getProperty(args[i]) == null) {
        newString[i] = "Error";
        continue;
      }

      newString[i] = System.getProperty(args[i]);
    }

    System.out.println("");
    if (counter == 1) {

      Arrays.sort(newString, Collections.reverseOrder()); // ,java.text.Collator.getInstance()
    } else {
      Arrays.sort(newString);
    }

    for (int i = 0; i < newString.length; i++) {
      if (newString[i].equals("Error")) {
        continue;
      }
      System.out.println(newString[i]);
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    BackgroundManager backgroundManager = BackgroundManager.getInstance(getActivity());
    backgroundManager.attach(getActivity().getWindow());
    mBackgroundTarget = new PicassoBackgroundManagerTarget(backgroundManager);

    mDefaultBackground = getResources().getDrawable(R.drawable.amphitheatre);

    mMetrics = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);

    Video video = (Video) getActivity().getIntent().getSerializableExtra(Constants.VIDEO);

    if (video.isMovie()) {
      new DetailRowBuilderTask(getActivity(), this).execute(video);
    } else {
      List<Video> videos =
          Select.from(Video.class)
              .where(Condition.prop("name").eq(video.getName()), Condition.prop("is_movie").eq(0))
              .list();

      Map<String, List<Video>> groups =
          new TreeMap<String, List<Video>>(Collections.reverseOrder());

      for (Video vid : videos) {
        // if an Episode item exists then categorize it
        // otherwise, add it to the uncategorized list
        if (vid.getTvShow() != null && vid.getTvShow().getEpisode() != null) {
          int seasonNumber = vid.getTvShow().getEpisode().getSeasonNumber();
          String key = String.format(getString(R.string.season_number), seasonNumber);

          if (groups.containsKey(key)) {
            List<Video> subVideos = groups.get(key);
            subVideos.add(vid);
          } else {
            List<Video> list = new ArrayList<Video>();
            list.add(vid);
            groups.put(key, list);
          }
        } else {
          String key = getString(R.string.uncategorized);

          if (groups.containsKey(key)) {
            groups.get(key).add(vid);
          } else {
            List<Video> list = new ArrayList<Video>();
            list.add(vid);
            groups.put(key, list);
          }
        }
      }

      new DetailRowBuilderTask(getActivity(), groups, this).execute(video);
    }

    setOnItemClickedListener(getDefaultItemClickedListener());
    updateBackground(video.getBackgroundImageUrl());
  }
  public int compare(T o1, T o2) {
    int treeComparatorResult = treeComparator.compare(o1, o2);
    if (treeComparatorResult == 0) {
      return 0;
    } else {
      List<Integer> sortedColumnIndexes = sortModel.getSortedColumnIndexes();
      if (sortedColumnIndexes != null && sortedColumnIndexes.size() > 0) {
        List<Comparator<T>> comparators = new ArrayList<Comparator<T>>();
        for (int sortedColumnIndex : sortedColumnIndexes) {
          // get comparator for column index... somehow
          List<Comparator> columnComparators =
              sortModel.getComparatorsForColumnIndex(sortedColumnIndex);

          if (columnComparators != null) {
            SortDirectionEnum sortDirection = sortModel.getSortDirection(sortedColumnIndex);
            for (Comparator columnComparator : columnComparators) {
              switch (sortDirection) {
                case ASC:
                  comparators.add(columnComparator);
                  break;
                case DESC:
                  comparators.add(Collections.reverseOrder(columnComparator));
                  break;
              }
            }
          }
        }
        return new ComparatorChain<T>(comparators).compare(o1, o2);
      } else {
        return treeComparatorResult;
      }
    }
  }
Example #23
0
  public static List<Star> findClosestKStars(int k, ObjectInputStream osin) {
    // maxHeap to store the closest k stars seen so far.
    PriorityQueue<Star> maxHeap = new PriorityQueue<>(k, Collections.reverseOrder());
    try {
      while (true) {
        // Add each star to the max-heap. If the max-heap size exceeds k,
        // remove the maximum element from the max-heap.
        Star star = (Star) osin.readObject();
        maxHeap.add(star);
        if (maxHeap.size() == k + 1) {
          maxHeap.remove();
        }
      }
    } catch (IOException e) {
      // Do nothing, read last element in stream.
    } catch (ClassNotFoundException e) {
      System.out.println("ClassNotFoundException: " + e.getMessage());
    }

    // We cannot go directly to an ArrayList from PriorityQueue, since
    // unlike LinkedList, it does not guarantee ordering of entries.
    List<Star> orderedStars = new ArrayList<Star>(maxHeap);
    // We need to reverse the orderedStars list since it goes from
    // largest to smallest because the PriorityQueue used the
    // Collections.reverse() comparator.
    Collections.reverse(orderedStars);
    return orderedStars;
  }
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n = scanner.nextInt();
    System.out.println("You entered integer " + n);

    List<BigDecimal> BD = new ArrayList<BigDecimal>();
    // System.out.println("Enter a string");
    // n = scanner.nextInt();
    /*  while(scanner.hasNext()){
    	  BD.add(new BigDecimal(scanner.next()));
    	  break;
    }

      for(BigDecimal bd :BD){
    	  System.out.println(bd);
    	  }  */

    for (int i = 0; i < n; i++) {
      BD.add(new BigDecimal(scanner.next()));
    }

    // Collections.reverse(BD);
    Collections.sort(BD, Collections.reverseOrder());
    for (BigDecimal bd : BD) {
      System.out.println(bd);
    }
  }
 @Test
 public void testCollection() {
   TreeBagMultimap<Integer, Integer> bagMultimap =
       TreeBagMultimap.newMultimap(Collections.reverseOrder());
   MutableSortedBag<Integer> collection = bagMultimap.createCollection();
   collection.addAll(FastList.newListWith(1, 4, 2, 3, 5, 5));
   Verify.assertSortedBagsEqual(
       TreeBag.newBagWith(Collections.reverseOrder(), 5, 5, 4, 3, 2, 1), collection);
   bagMultimap.putAll(1, collection);
   Verify.assertSortedBagsEqual(
       TreeBag.newBagWith(Collections.reverseOrder(), 5, 5, 4, 3, 2, 1), collection);
   bagMultimap.put(1, 0);
   Assert.assertEquals(Integer.valueOf(0), bagMultimap.get(1).getLast());
   bagMultimap.putAll(2, FastList.newListWith(0, 1, 2, 3, 4, 5, 5));
   Verify.assertSortedBagsEqual(bagMultimap.get(1), bagMultimap.get(2));
 }
Example #26
0
  public PriorityQueue<SelectDetailRow> transGroupValue(Doclist res, String[] fields)
      throws ParseException, IOException {

    long key = getkeyCrc();

    PriorityQueue<SelectDetailRow> topItems =
        new PriorityQueue<SelectDetailRow>(
            this.parse.limit_offset, Collections.reverseOrder(defcmp));
    for (int i = 0; i < res.index; i++) {
      int doc = res.list[i];
      SortGroupVal buff = new SortGroupVal();
      buff.groupbuff.append(String.valueOf(doc));
      buff.groupbuff.append(UniqConfig.GroupJoinString());
      buff.groupbuff.append(String.valueOf(key));

      for (int j = 0; j < fields.length; j++) {
        buff.groupbuff.append(UniqConfig.GroupJoinString());
        buff.groupbuff.append(EncodeUtils.encode("-"));
      }
      buff.sortString = "0";
      SelectDetailRow newrow = SelectDetailRow.INSTANCE(doc, doc);
      newrow.setKey(new ColumnKey(buff.groupbuff.toString()));
      newrow.colVal = buff.sortString;
      QueuePutUtils.put2QueueDetail(newrow, topItems, this.parse.limit_offset, defcmp);
    }
    return topItems;
  }
  @Test
  public void sortOnListWithLessThan10Elements() {
    ArrayList<Integer> integers = this.newArrayList(2, 3, 4, 1, 5, 7, 6, 9, 8);
    Verify.assertStartsWith(ArrayListIterate.sortThis(integers), 1, 2, 3, 4, 5, 6, 7, 8, 9);

    ArrayList<Integer> integers2 = this.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9);
    Verify.assertStartsWith(
        ArrayListIterate.sortThis(integers2, Collections.<Integer>reverseOrder()),
        9,
        8,
        7,
        6,
        5,
        4,
        3,
        2,
        1);

    ArrayList<Integer> integers3 = this.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9);
    Verify.assertStartsWith(ArrayListIterate.sortThis(integers3), 1, 2, 3, 4, 5, 6, 7, 8, 9);

    ArrayList<Integer> integers4 = this.newArrayList(9, 8, 7, 6, 5, 4, 3, 2, 1);
    Verify.assertStartsWith(ArrayListIterate.sortThis(integers4), 1, 2, 3, 4, 5, 6, 7, 8, 9);

    ThisIsNotAnArrayList<Integer> arrayListThatIsnt =
        new ThisIsNotAnArrayList<Integer>(FastList.newListWith(9, 8, 7, 6, 5, 4, 3, 2, 1));
    Verify.assertStartsWith(
        ArrayListIterate.sortThis(arrayListThatIsnt), 1, 2, 3, 4, 5, 6, 7, 8, 9);
  }
  public void dump(PrintWriter out) {
    FullStatFig entropyFig = new FullStatFig();
    FullStatFig numTranslationsFig = new FullStatFig();
    FullStatFig sumFig = new FullStatFig();

    for (Map.Entry<String, StringDoubleMap> e : entrySet()) {
      String s = e.getKey();
      StringDoubleMap m = e.getValue();

      FullStatFig fig = new FullStatFig(m.values());
      entropyFig.add(fig.entropy());
      numTranslationsFig.add(fig.size());
      sumFig.add(fig.total());

      out.printf(
          "%s\tentropy %s\tnTrans %d\tsum %f\n", s, Fmt.D(fig.entropy()), fig.size(), fig.total());

      ArrayList<StringDoubleMap.Entry> entries2 =
          new ArrayList<StringDoubleMap.Entry>(m.entrySet());
      Collections.sort(entries2, Collections.reverseOrder(m.entryValueComparator()));

      for (StringDoubleMap.Entry tv : entries2) {
        if (tv.getValue() < 1e-10) continue; // Skip zero entries
        String t = tv.getKey();
        out.printf("  %s: %f\n", t, tv.getValue());
      }
    }

    out.println("# entropy = " + entropyFig);
    out.println("# sum = " + sumFig);
    out.println("# numTranslations = " + numTranslationsFig);
  }
  @RequestMapping(value = "/classmates", method = RequestMethod.GET)
  public String getClassmates(Model model) {
    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    model.addAttribute("current_user", user);
    Student currentStudent = studentService.getOne(user.getId());

    if (user.getRole().equals(Role.ROLE_STUDENT))
      model.addAttribute("homework", currentStudent.getGroup().getHomeworks());

    TreeMap<Double, String> studentsMap = new TreeMap<>(Collections.reverseOrder());
    currentStudent
        .getGroup()
        .getStudents()
        .forEach(
            student ->
                studentsMap.put(
                    studentService.getAverageScore(student.getId()), student.getFullName()));

    LinkedHashMap<String, String> studentsMapForFreemarker = new LinkedHashMap<>();

    studentsMap
        .entrySet()
        .forEach(
            entry ->
                studentsMapForFreemarker.put(String.valueOf(entry.getKey()), entry.getValue()));

    model.addAttribute("studentsMap", studentsMapForFreemarker);
    return "student/classmates";
  }
Example #30
0
 private static double NDCG(Vector<Integer> dids, Map<Integer, Double> qr_graded, int K) {
   double DCG = 0.0;
   double IDCG = 0.0;
   double NDCG = 0.0;
   double rel = 0.0;
   Vector<Double> rels = new Vector<Double>();
   for (int i = 0; i < K; i++) {
     rel = 0.0;
     if (qr_graded.containsKey(dids.get(i)) != false) {
       rel = qr_graded.get(dids.get(i));
     }
     rels.add(rel);
     DCG += rel * Math.log(2) / Math.log((i + 1) + 1);
   }
   // calculate Ideal DCG (IDCG)
   Collections.sort(rels, Collections.reverseOrder());
   for (int i = 0; i < rels.size(); i++) {
     if (rels.get(i) == 0.0) {
       break;
     }
     IDCG += rels.get(i) * Math.log(2) / Math.log((i + 1) + 1);
   }
   // System.out.println("DCG: " + DCG + " IDCG: " + IDCG);
   NDCG = (IDCG == 0.0) ? 0 : DCG / IDCG;
   return NDCG;
 }