Java Code Examples for com.google.common.collect.Ordering

The following are top voted examples for showing how to use com.google.common.collect.Ordering. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ARCLib   File: HistoricStore.java   Source Code and License 6 votes vote down vote up
public List<Revision> getRevisions(String id, Params params) {

        AuditReader reader = getAuditReader();

        List<Number> revisionNumbers = reader.getRevisions(type, id);
        Map<Number, Revision> revisionMap = reader.findRevisions(Revision.class, asSet(revisionNumbers));
        Collection<Revision> revisions = revisionMap.values();

        Comparator<Revision> timestampComparator = Comparator.comparingLong(Revision::getTimestamp);
        Comparator<Revision> authorComparator = Comparator.comparing(Revision::getAuthor);

        Comparator<Revision> comparator;
        if (AUTHOR.equals(params.getSort())) {
            comparator = authorComparator;
        } else {
            comparator = timestampComparator;
        }

        if (params.getOrder() == Order.DESC) {
            comparator = comparator.reversed();
        }

        return Ordering.from(comparator)
                       .sortedCopy(revisions);
    }
 
Example 2
Project: CustomWorldGen   File: Loader.java   Source Code and License 6 votes vote down vote up
private void identifyDuplicates(List<ModContainer> mods)
{
    TreeMultimap<ModContainer, File> dupsearch = TreeMultimap.create(new ModIdComparator(), Ordering.arbitrary());
    for (ModContainer mc : mods)
    {
        if (mc.getSource() != null)
        {
            dupsearch.put(mc, mc.getSource());
        }
    }

    ImmutableMultiset<ModContainer> duplist = Multisets.copyHighestCountFirst(dupsearch.keys());
    SetMultimap<ModContainer, File> dupes = LinkedHashMultimap.create();
    for (Entry<ModContainer> e : duplist.entrySet())
    {
        if (e.getCount() > 1)
        {
            FMLLog.severe("Found a duplicate mod %s at %s", e.getElement().getModId(), dupsearch.get(e.getElement()));
            dupes.putAll(e.getElement(),dupsearch.get(e.getElement()));
        }
    }
    if (!dupes.isEmpty())
    {
        throw new DuplicateModsFoundException(dupes);
    }
}
 
Example 3
Project: cakes   File: TreeMultimapDemo.java   Source Code and License 6 votes vote down vote up
/**
 * 测试 TreeMultimap,自定义数据结构的排序
 */
@Test
public void testSelfDataOrdered() {
    // 创建TreeMultimap,使用Ordering.natural()指定自然排序,Ordering.from指定排序规则
    // Order4TreeMultimap::compareTo 是lambda的简写形式
    TreeMultimap<String, Order4TreeMultimap> treeMultimap = TreeMultimap
            .create(Ordering.natural(),
                    Ordering.from(Order4TreeMultimap::compareTo));

    // 列表2
    treeMultimap.put("order_list1", new Order4TreeMultimap(1, "haha1"));
    treeMultimap.put("order_list1", new Order4TreeMultimap(5, "haha2"));
    treeMultimap.put("order_list1", new Order4TreeMultimap(9, "haha3"));
    treeMultimap.put("order_list1", new Order4TreeMultimap(10, "haha3"));
    treeMultimap.put("order_list1", new Order4TreeMultimap(22, "haha4"));
    treeMultimap.put("order_list1", new Order4TreeMultimap(444, "haha5"));

    // 列表2
    treeMultimap.put("order_list2", new Order4TreeMultimap(1, "haha3"));
    treeMultimap.put("order_list2", new Order4TreeMultimap(3, "haha4"));
    treeMultimap.put("order_list3", new Order4TreeMultimap(2, "haha5"));

    // 输出
    treeMultimap.forEach((key, order) -> System.out.println("key=" + key + ",order=" + order));
}
 
Example 4
Project: HCFCore   File: ConquestTracker.java   Source Code and License 6 votes vote down vote up
/**
 * Sets the points a {@link PlayerFaction} has gained for this {@link ConquestTracker}.
 *
 * @param faction the faction to set for
 * @param amount  the amount to set
 * @return the new points of the {@link PlayerFaction}
 */
public int setPoints(PlayerFaction faction, int amount) {
    if (amount <= 0) return amount;

    synchronized (factionPointsMap) {
        factionPointsMap.put(faction, amount);
        List<Map.Entry<PlayerFaction, Integer>> entries = Ordering.from(POINTS_COMPARATOR).sortedCopy(factionPointsMap.entrySet());

        factionPointsMap.clear();
        for (Map.Entry<PlayerFaction, Integer> entry : entries) {
            factionPointsMap.put(entry.getKey(), entry.getValue());
        }
    }

    return amount;
}
 
Example 5
Project: n4js   File: OpenTypeSelectionDialog.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings({ "rawtypes", "unchecked", "static-access" })
protected Comparator getItemsComparator() {
	return Ordering.natural().nullsLast().from(new Comparator() {

		@Override
		public int compare(final Object o1, final Object o2) {
			if (o1 instanceof IEObjectDescription && o2 instanceof IEObjectDescription) {
				final IEObjectDescription d1 = (IEObjectDescription) o1;
				final IEObjectDescription d2 = (IEObjectDescription) o2;
				final QualifiedName fqn1 = d1.getQualifiedName();
				final QualifiedName fqn2 = d2.getQualifiedName();
				if (null != fqn1 && null != fqn2) {
					return nullToEmpty(fqn1.getLastSegment()).compareToIgnoreCase(
							nullToEmpty(fqn2.getLastSegment()));
				}
			}
			return Objects.hashCode(o1) - Objects.hashCode(o2);
		}
	});
}
 
Example 6
Project: Elasticsearch   File: OrderingByPosition.java   Source Code and License 6 votes vote down vote up
private OrderingByPosition (int position, boolean reverse, @Nullable Boolean nullFirst) {
    this.position = position;

    // note, that we are reverse for the queue so this conditional is by intent
    Ordering<Comparable> ordering;
    nullFirst = nullFirst != null ? !nullFirst : null; // swap because queue is reverse
    if (reverse) {
        ordering = Ordering.natural();
        if (nullFirst == null || !nullFirst) {
            ordering = ordering.nullsLast();
        } else {
            ordering = ordering.nullsFirst();
        }
    } else {
        ordering = Ordering.natural().reverse();
        if (nullFirst == null || nullFirst) {
            ordering = ordering.nullsFirst();
        } else {
            ordering = ordering.nullsLast();
        }
    }
    this.ordering = ordering;
}
 
Example 7
Project: java-monitoring-client-library   File: AbstractMetricSubject.java   Source Code and License 6 votes vote down vote up
/**
 * Asserts that the metric has no (non-default) values other than those about which an assertion
 * has already been made.
 */
public And<S> hasNoOtherValues() {
  for (MetricPoint<T> metricPoint : actual().getTimestampedValues()) {
    if (!expectedNondefaultLabelTuples.contains(metricPoint.labelValues())) {
      if (!hasDefaultValue(metricPoint)) {
        failWithBadResults(
            "has",
            "no other nondefault values",
            "has labeled values",
            Lists.transform(
                Ordering.<MetricPoint<T>>natural().sortedCopy(actual().getTimestampedValues()),
                metricPointConverter));
      }
      return andChainer();
    }
  }
  return andChainer();
}
 
Example 8
Project: tensorflow-spring-cloud-stream-app-starters   File: LabelImageTensorflowOutputConverter.java   Source Code and License 6 votes vote down vote up
private List<Integer> topKProbabilities(final float[] labelProbabilities, int k) {

		List<Integer> list = new ArrayList<>(labelProbabilities.length);
		for (int i = 0; i < labelProbabilities.length; i++) {
			list.add(i);
		}

		List<Integer> topK = new Ordering<Integer>() {
			@Override
			public int compare(Integer left, Integer right) {
				return Floats.compare(labelProbabilities[left], labelProbabilities[right]);
			}
		}.greatestOf(list, k);

		return topK;
	}
 
Example 9
Project: preDict   File: PreDict.java   Source Code and License 6 votes vote down vote up
private List<SuggestItem> pickSuggestions(String searchWord, int editDistanceMax, List<SuggestItem> suggestions) {
	int k = suggestions.size();
	if ((accuracyLevel == AccuracyLevel.topHit) && (suggestions.size() > 1))
		k = 1;
	else if (suggestions.size() > topK) {
		k = topK;
	}

	List<SuggestItem> returnSuggestions;
	if (k >= suggestions.size()) {
		returnSuggestions = suggestions;
	} else {
		returnSuggestions = Ordering.from(distanceCountComparator).leastOf(suggestions, k);
	}
	
	return customizing.adjustFinalResult(searchWord, returnSuggestions);
}
 
Example 10
Project: tac-kbp-eal   File: _CorpusQueryAssessments.java   Source Code and License 6 votes vote down vote up
public final CorpusQueryAssessments withNeutralizedJustifications() {
  return CorpusQueryAssessments.builder()
      .queryReponses(Iterables.transform(queryReponses(), neutralizeRealisFunction()))
      .queryResponsesToSystemIDs(
          copyWithTransformedKeys(queryResponsesToSystemIDs(), neutralizeRealisFunction()))
      .assessments(
          reduceToMap(
              transformKeys(assessments(), neutralizeRealisFunction()),
              // if multiple assessments on the same doc are collapsed together,
              // the ones higher in rank "trump" others
              maxFunction(Ordering.<QueryAssessment2016>natural())))
      // we arbitrarily take the first metadata, which is a bit of a hack
      .metadata(reduceToMap(transformKeys(metadata(), neutralizeRealisFunction()),
          _CorpusQueryAssessments.<String>getFirstFunction()))
      .build();
}
 
Example 11
Project: Elasticsearch   File: SortingTopNProjector.java   Source Code and License 6 votes vote down vote up
/**
 * @param inputs             contains output {@link io.crate.operation.Input}s and orderBy {@link io.crate.operation.Input}s
 * @param collectExpressions gathered from outputs and orderBy inputs
 * @param numOutputs         <code>inputs</code> contains this much output {@link io.crate.operation.Input}s starting form index 0
 * @param ordering           ordering that is used to compare the rows
 * @param limit              the number of rows to gather, pass to upStream
 * @param offset             the initial offset, this number of rows are skipped
 */
public SortingTopNProjector(Collection<? extends Input<?>> inputs,
                            Iterable<? extends CollectExpression<Row, ?>> collectExpressions,
                            int numOutputs,
                            Ordering<Object[]> ordering,
                            int limit,
                            int offset) {
    Preconditions.checkArgument(limit >= TopN.NO_LIMIT, "invalid limit");
    Preconditions.checkArgument(offset >= 0, "invalid offset");

    this.inputs = inputs;
    this.numOutputs = numOutputs;
    this.collectExpressions = collectExpressions;
    this.offset = offset;

    if (limit == TopN.NO_LIMIT) {
        limit = Constants.DEFAULT_SELECT_LIMIT;
    }
    int maxSize = this.offset + limit;
    pq = new RowPriorityQueue<>(maxSize, ordering);
}
 
Example 12
Project: googles-monorepo-demo   File: ElementOrderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void customComparable() {
  MutableGraph<ComparableSubClass> graph =
      GraphBuilder.undirected().nodeOrder(ElementOrder.<ComparableSubClass>natural()).build();

  ComparableSubClass node2 = new ComparableSubClass(2);
  ComparableSubClass node4 = new ComparableSubClass(4);
  ComparableSubClass node6 = new ComparableSubClass(6);
  ComparableSubClass node8 = new ComparableSubClass(8);

  graph.addNode(node4);
  graph.addNode(node2);
  graph.addNode(node6);
  graph.addNode(node8);

  assertThat(graph.nodeOrder().comparator()).isEqualTo(Ordering.natural());
  assertThat(graph.nodes()).containsExactly(node2, node4, node6, node8).inOrder();
}
 
Example 13
Project: QDrill   File: MapVector.java   Source Code and License 6 votes vote down vote up
@Override
public int getValueCapacity() {
  if (size() == 0) {
    return 0;
  }

  final Ordering<ValueVector> natural = new Ordering<ValueVector>() {
    @Override
    public int compare(@Nullable ValueVector left, @Nullable ValueVector right) {
      return Ints.compare(
          Preconditions.checkNotNull(left).getValueCapacity(),
          Preconditions.checkNotNull(right).getValueCapacity()
      );
    }
  };

  return natural.min(getChildren()).getValueCapacity();
}
 
Example 14
Project: tac-kbp-eal   File: BreakdownFunctions.java   Source Code and License 6 votes vote down vote up
/**
 * @return A mapping from each breakdown type to inner maps. These inner maps map from the
 * categories for that breakdown type to confusion matrices for only that category.
 */
public static <SignatureType, ProvenanceType>
ImmutableMap<String, BrokenDownProvenancedConfusionMatrix<SignatureType, ProvenanceType>>
computeBreakdowns(
    ProvenancedConfusionMatrix<ProvenanceType> corpusConfusionMatrix,
    Map<String, Function<? super ProvenanceType, SignatureType>> breakdowns,
    Ordering<SignatureType> resultKeyOrdering) {
  final ImmutableMap.Builder<String, BrokenDownProvenancedConfusionMatrix<SignatureType, ProvenanceType>>
      printModes =
      ImmutableMap.builder();

  for (final Map.Entry<String, Function<? super ProvenanceType, SignatureType>> breakdownEntry : breakdowns
      .entrySet()) {
    printModes.put(breakdownEntry.getKey(),
        corpusConfusionMatrix.breakdown(breakdownEntry.getValue(),
            resultKeyOrdering));
  }
  return printModes.build();
}
 
Example 15
Project: tac-kbp-eal   File: EAScoringObserver.java   Source Code and License 6 votes vote down vote up
public static ImmutableMap<String, BrokenDownSummaryConfusionMatrix<Symbol>> combineBreakdowns(
    Iterator<Map<String, BrokenDownSummaryConfusionMatrix<Symbol>>> breakdowns) {

  final Map<String, BrokenDownSummaryConfusionMatrix.Builder<Symbol>> ret = Maps.newHashMap();
  while (breakdowns.hasNext()) {
    final Map<String, BrokenDownSummaryConfusionMatrix<Symbol>> breakdown = breakdowns.next();
    for (final Map.Entry<String, BrokenDownSummaryConfusionMatrix<Symbol>> breakdownEntry : breakdown
        .entrySet()) {
      if (!ret.containsKey(breakdownEntry.getKey())) {
        ret.put(breakdownEntry.getKey(), BrokenDownSummaryConfusionMatrix.<Symbol>builder(
            Ordering.from(new SymbolUtils.ByString())));
      }
      ret.get(breakdownEntry.getKey()).combine(breakdownEntry.getValue());
    }
  }

  final ImmutableMap.Builder<String, BrokenDownSummaryConfusionMatrix<Symbol>> trueRet =
      ImmutableMap.builder();
  // return map in alphabetical order
  for (final String key : Ordering.natural().sortedCopy(ret.keySet())) {
    trueRet.put(key, ret.get(key).build());
  }
  return trueRet.build();
}
 
Example 16
Project: metanome-algorithms   File: DatatypeDate.java   Source Code and License 6 votes vote down vote up
public DatatypeDate(final Comparator<Date> comparator, final String dateFormat) {
  this.specificType = type.DATE;
  this.setDateFormat(dateFormat);

  if (comparator == null) {
    this.indexedComparator = new Comparator<RowIndexedDateValue>() {

      @Override
      public int compare(final RowIndexedDateValue o1, final RowIndexedDateValue o2) {
        return ComparisonChain.start()
            .compare(o1.value, o2.value, Ordering.natural().nullsFirst()).result();
      }

    };
  } else {
    this.indexedComparator = new Comparator<RowIndexedDateValue>() {

      @Override
      public int compare(final RowIndexedDateValue o1, final RowIndexedDateValue o2) {
        return ComparisonChain.start()
            .compare(o1.value, o2.value, Ordering.from(comparator).nullsFirst()).result();
      }

    };
  }
}
 
Example 17
Project: metanome-algorithms   File: DatatypeLong.java   Source Code and License 6 votes vote down vote up
public DatatypeLong(final Comparator<Long> comparator) {
  this.specificType = type.LONG;

  if (comparator == null) {
    this.indexedComparator = new Comparator<RowIndexedLongValue>() {

      @Override
      public int compare(final RowIndexedLongValue o1, final RowIndexedLongValue o2) {
        return ComparisonChain.start()
            .compare(o1.value, o2.value, Ordering.natural().nullsFirst()).result();
      }

    };
  } else {
    this.indexedComparator = new Comparator<RowIndexedLongValue>() {

      @Override
      public int compare(final RowIndexedLongValue o1, final RowIndexedLongValue o2) {
        return ComparisonChain.start()
            .compare(o1.value, o2.value, Ordering.from(comparator).nullsFirst()).result();
      }

    };
  }

}
 
Example 18
Project: jLZJD   File: LZJDf.java   Source Code and License 6 votes vote down vote up
/**
 * Obtains a min-hash set for the given input file
 * @param indx the unique index assigned for this file
 * @param x_file the file to get the LZJDf min-hash of
 * @param min_hash_size the max size for the min-hash
 * @return an int array of the min-hash values in sorted order
 * @throws IOException 
 */
protected static int[] getMinHash(int indx, File x_file, int min_hash_size) throws IOException
{
    int[] x_minset = min_hashes.get(indx);
    if(x_minset == null)
    {
        try(FileInputStream fis = new FileInputStream(x_file))
        {
            IntList hashes = LOCAL_INT_LIST.get();
            hashes.clear();
            getAllHashes(hashes, fis);

            List<Integer> sub_hashes = Ordering.natural().leastOf(hashes, Math.min(min_hash_size, hashes.size()));

            x_minset = new int[sub_hashes.size()];
            for(int i = 0; i < x_minset.length; i++)
                x_minset[i] = sub_hashes.get(i);
            Arrays.sort(x_minset);

            min_hashes.putIfAbsent(indx, x_minset);
        }
    }
    
    return x_minset;
}
 
Example 19
Project: guava-mock   File: StripedTest.java   Source Code and License 6 votes vote down vote up
public void testBulkGetReturnsSorted() {
  for (Striped<?> striped : allImplementations()) {
    Map<Object, Integer> indexByLock = Maps.newHashMap();
    for (int i = 0; i < striped.size(); i++) {
      indexByLock.put(striped.getAt(i), i);
    }

    // ensure that bulkGet returns locks in monotonically increasing order
    for (int objectsNum = 1; objectsNum <= striped.size() * 2; objectsNum++) {
      Set<Object> objects = Sets.newHashSetWithExpectedSize(objectsNum);
      for (int i = 0; i < objectsNum; i++) {
        objects.add(new Object());
      }

      Iterable<?> locks = striped.bulkGet(objects);
      assertTrue(Ordering.natural().onResultOf(Functions.forMap(indexByLock)).isOrdered(locks));

      // check idempotency
      Iterable<?> locks2 = striped.bulkGet(objects);
      assertEquals(Lists.newArrayList(locks), Lists.newArrayList(locks2));
    }
  }
}
 
Example 20
Project: HCFCore   File: ConquestTracker.java   Source Code and License 6 votes vote down vote up
/**
 * Sets the points a {@link PlayerFaction} has gained for this {@link ConquestTracker}.
 *
 * @param faction the faction to set for
 * @param amount  the amount to set
 * @return the new points of the {@link PlayerFaction}
 */
public int setPoints(PlayerFaction faction, int amount) {
    if (amount <= 0) return amount;

    synchronized (factionPointsMap) {
        factionPointsMap.put(faction, amount);
        List<Map.Entry<PlayerFaction, Integer>> entries = Ordering.from(POINTS_COMPARATOR).sortedCopy(factionPointsMap.entrySet());

        factionPointsMap.clear();
        for (Map.Entry<PlayerFaction, Integer> entry : entries) {
            factionPointsMap.put(entry.getKey(), entry.getValue());
        }
    }

    return amount;
}
 
Example 21
Project: guava-mock   File: ElementOrderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void nodeOrderUnorderedandEdgesSorted() {
  MutableNetwork<Integer, String> network =
      NetworkBuilder.directed()
          .nodeOrder(unordered())
          .edgeOrder(ElementOrder.sorted(Ordering.<String>natural().reverse()))
          .build();

  addEdges(network);

  assertThat(network.edgeOrder())
      .isEqualTo(ElementOrder.sorted(Ordering.<String>natural().reverse()));
  assertThat(network.edges()).containsExactly("p", "i", "e").inOrder();
  assertThat(network.nodeOrder()).isEqualTo(unordered());
  assertThat(network.nodes()).containsExactly(4, 1, 3);
}
 
Example 22
Project: ProjectAres   File: FeatureDefinitionContext.java   Source Code and License 6 votes vote down vote up
/**
 * Records are sorted by lexical position of their definition Element.
 * Records without an Element are ordered before those with an Element,
 * and two different records NEVER compare equal.
 */
@Override
public int compareTo(Record<?> that) {
    assertDefined();
    if(this == that) return 0;
    if(this.path == null) {
        if(that.path == null) {
            return Ordering.arbitrary().compare(this, that);
        } else {
            return -1;
        }
    } else {
        if(that.path == null) {
            return 1;
        } else {
            return ListUtils.lexicalCompare(this.path, that.path);
        }
    }
}
 
Example 23
Project: athena   File: PartitionsListCommand.java   Source Code and License 5 votes vote down vote up
/**
 * Displays partition client info as text.
 *
 * @param partitionClientInfo partition client information
 */
private void displayPartitionClients(List<PartitionClientInfo> partitionClientInfo) {
    if (partitionClientInfo.isEmpty()) {
        return;
    }
    ClusterService clusterService = get(ClusterService.class);
    print("-------------------------------------------------------------------");
    print(CLIENT_FMT, "Name", "SessionId", "Status", "Servers");
    print("-------------------------------------------------------------------");

    for (PartitionClientInfo info : partitionClientInfo) {
        boolean first = true;
        for (NodeId serverId : Ordering.natural().sortedCopy(info.servers())) {
            ControllerNode server = clusterService.getNode(serverId);
            String serverString = String.format("%s:%d", server.id(), server.tcpPort());
            if (first) {
                print(CLIENT_FMT, info.partitionId(), info.sessionId(),
                        info.status(), serverString);
                first = false;
            } else {
                print(CLIENT_FMT, "", "", "", serverString);
            }
        }
        if (!first) {
            print("-------------------------------------------------------------------");
        }
    }
}
 
Example 24
Project: googles-monorepo-demo   File: ServiceManager.java   Source Code and License 5 votes vote down vote up
ImmutableMap<Service, Long> startupTimes() {
  List<Entry<Service, Long>> loadTimes;
  monitor.enter();
  try {
    loadTimes = Lists.newArrayListWithCapacity(startupTimers.size());
    // N.B. There will only be an entry in the map if the service has started
    for (Entry<Service, Stopwatch> entry : startupTimers.entrySet()) {
      Service service = entry.getKey();
      Stopwatch stopWatch = entry.getValue();
      if (!stopWatch.isRunning() && !(service instanceof NoOpService)) {
        loadTimes.add(Maps.immutableEntry(service, stopWatch.elapsed(MILLISECONDS)));
      }
    }
  } finally {
    monitor.leave();
  }
  Collections.sort(
      loadTimes,
      Ordering.natural()
          .onResultOf(
              new Function<Entry<Service, Long>, Long>() {
                @Override
                public Long apply(Map.Entry<Service, Long> input) {
                  return input.getValue();
                }
              }));
  return ImmutableMap.copyOf(loadTimes);
}
 
Example 25
Project: andbg   File: EncodedValueWriter.java   Source Code and License 5 votes vote down vote up
public void writeAnnotation(TypeKey annotationType,
                            Collection<? extends AnnotationElement> elements) throws IOException {
    writer.writeEncodedValueHeader(ValueType.ANNOTATION, 0);
    writer.writeUleb128(typeSection.getItemIndex(annotationType));
    writer.writeUleb128(elements.size());

    Collection<? extends AnnotationElement> sortedElements = Ordering.from(BaseAnnotationElement.BY_NAME)
            .immutableSortedCopy(elements);

    for (AnnotationElement element: sortedElements) {
        writer.writeUleb128(stringSection.getItemIndex(annotationSection.getElementName(element)));
        writeEncodedValue(annotationSection.getElementValue(element));
    }
}
 
Example 26
Project: Reer   File: DefaultStructBindingsStore.java   Source Code and License 5 votes vote down vote up
private static void validateType(StructBindingValidationProblemCollector problems, Class<?> typeClass) {
    Constructor<?> customConstructor = findCustomConstructor(typeClass);
    if (customConstructor != null) {
        problems.add(customConstructor, "Custom constructors are not supported.");
    }

    ensureNoInstanceScopedFields(problems, typeClass);

    // sort for determinism
    Method[] methods = typeClass.getDeclaredMethods();
    Arrays.sort(methods, Ordering.usingToString());

    ensureNoProtectedOrPrivateMethods(problems, methods);
    ensureNoDefaultMethods(problems, typeClass, methods);
}
 
Example 27
Project: googles-monorepo-demo   File: TypeToken.java   Source Code and License 5 votes vote down vote up
private static <K, V> ImmutableList<K> sortKeysByValue(
    final Map<K, V> map, final Comparator<? super V> valueComparator) {
  Ordering<K> keyOrdering =
      new Ordering<K>() {
        @Override
        public int compare(K left, K right) {
          return valueComparator.compare(map.get(left), map.get(right));
        }
      };
  return keyOrdering.immutableSortedCopy(map.keySet());
}
 
Example 28
Project: Reer   File: ModelTypes.java   Source Code and License 5 votes vote down vote up
public static <T> Ordering<ModelType<? extends T>> displayOrder() {
    return new Ordering<ModelType<? extends T>>() {
        @Override
        public int compare(ModelType<? extends T> left, ModelType<? extends T> right) {
            return left.getDisplayName().compareTo(right.getDisplayName());
        }
    };
}
 
Example 29
Project: Reer   File: BuildInvocationsBuilder.java   Source Code and License 5 votes vote down vote up
@Override
@SuppressWarnings("StringEquality")
public DefaultBuildInvocations buildAll(String modelName, Project project) {
    if (!canBuild(modelName)) {
        throw new GradleException("Unknown model name " + modelName);
    }

    DefaultProjectIdentifier projectIdentifier = getProjectIdentifier(project);
    // construct task selectors
    List<LaunchableGradleTaskSelector> selectors = Lists.newArrayList();
    Map<String, LaunchableGradleTaskSelector> selectorsByName = Maps.newTreeMap(Ordering.natural());
    Set<String> visibleTasks = Sets.newLinkedHashSet();
    findTasks(project, selectorsByName, visibleTasks);
    for (String selectorName : selectorsByName.keySet()) {
        LaunchableGradleTaskSelector selector = selectorsByName.get(selectorName);
        selectors.add(selector.
                setName(selectorName).
                setTaskName(selectorName).
                setProjectIdentifier(projectIdentifier).
                setDisplayName(selectorName + " in " + project + " and subprojects.").
                setPublic(visibleTasks.contains(selectorName)));
    }

    // construct project tasks
    List<LaunchableGradleTask> projectTasks = tasks(project);

    // construct build invocations from task selectors and project tasks
    return new DefaultBuildInvocations()
        .setSelectors(selectors)
        .setTasks(projectTasks)
        .setProjectIdentifier(projectIdentifier);
}
 
Example 30
Project: Reer   File: VersionNumber.java   Source Code and License 5 votes vote down vote up
public int compareTo(VersionNumber other) {
    if (major != other.major) {
        return major - other.major;
    }
    if (minor != other.minor) {
        return minor - other.minor;
    }
    if (micro != other.micro) {
        return micro - other.micro;
    }
    if (patch != other.patch) {
        return patch - other.patch;
    }
    return Ordering.natural().nullsLast().compare(toLowerCase(qualifier), toLowerCase(other.qualifier));
}
 
Example 31
Project: BUILD_file_generator   File: JavaSourceFileParser.java   Source Code and License 5 votes vote down vote up
/** Create a cycle in 'graph' comprised of classes from 'classes'. */
private static void putOnCycle(Collection<String> classes, MutableGraph<String> graph) {
  if (classes.size() == 1) {
    return;
  }

  ImmutableList<String> sortedClasses = Ordering.natural().immutableSortedCopy(classes);

  for (int i = 1; i < sortedClasses.size(); i++) {
    graph.putEdge(sortedClasses.get(i - 1), sortedClasses.get(i));
  }
  graph.putEdge(getLast(sortedClasses), sortedClasses.get(0));
}
 
Example 32
Project: googles-monorepo-demo   File: ForwardingWrapperTesterTest.java   Source Code and License 5 votes vote down vote up
@Override public void foo(
    String s, Runnable r, Number n, Iterable<?> it, boolean b, Equivalence<String> eq,
    Exception e, InputStream in, Comparable<?> c, Ordering<Integer> ord,
    Charset charset, TimeUnit unit, Class<?> cls, Joiner joiner,
    Pattern pattern, UnsignedInteger ui, UnsignedLong ul, StringBuilder sb,
    Predicate<?> pred, Function<?, ?> func, Object obj) {
  delegate.foo(s,
      r, n, it, b, eq, e, in, c, ord, charset, unit, cls, joiner, pattern,
      ui, ul, sb, pred, func, obj);
}
 
Example 33
Project: googles-monorepo-demo   File: TypeToken.java   Source Code and License 5 votes vote down vote up
ImmutableList<K> collectTypes(Iterable<? extends K> types) {
  // type -> order number. 1 for Object, 2 for anything directly below, so on so forth.
  Map<K, Integer> map = Maps.newHashMap();
  for (K type : types) {
    collectTypes(type, map);
  }
  return sortKeysByValue(map, Ordering.natural().reverse());
}
 
Example 34
Project: CustomWorldGen   File: Clips.java   Source Code and License 5 votes vote down vote up
public Iterable<Event> pastEvents(float lastPollTime, float time)
{
    float clipLastPollTime = input.apply(lastPollTime);
    float clipTime = input.apply(time);
    return Iterables.mergeSorted(ImmutableSet.of(
        from.pastEvents(clipLastPollTime, clipTime),
        to.pastEvents(clipLastPollTime, clipTime)
    ), Ordering.<Event>natural());
}
 
Example 35
Project: Elasticsearch   File: FunctionIdent.java   Source Code and License 5 votes vote down vote up
@Override
public int compareTo(FunctionIdent o) {
    return ComparisonChain.start()
            .compare(name, o.name)
            .compare(argumentTypes, o.argumentTypes, Ordering.<DataType>natural().lexicographical())
            .result();
}
 
Example 36
Project: morf   File: TestViewChanges.java   Source Code and License 5 votes vote down vote up
/**
 * Test a simple configuration.
 */
@Test
public void testSimple() {
  ViewChanges c = new ViewChanges(
    ImmutableSet.of(
      view("A", "B", "C"),
      view("B", "C", "D"),
      view("C"),
      view("D")
    ),
    ImmutableSet.of(
      view("B")
    ),
    ImmutableSet.of(
      view("A"),
      view("B")
    ));

  assertEquals("Views to drop mismatch", ImmutableSet.of("B", "A"), nameSet(c.getViewsToDrop()));
  assertEquals("Views to deploy mismatch", ImmutableSet.of("A", "B"), nameSet(c.getViewsToDeploy()));

  Ordering<String> dropOrder = Ordering.explicit(nameList(c.getViewsToDrop()));
  assertTrue("Must drop A before B", dropOrder.compare("A", "B") < 0);

  Ordering<String> deployOrder = Ordering.explicit(nameList(c.getViewsToDeploy()));
  assertTrue("Must deploy B before A", deployOrder.compare("B", "A") < 0);
}
 
Example 37
Project: googles-monorepo-demo   File: SortedMapGenerators.java   Source Code and License 5 votes vote down vote up
@Override
public Iterable<Entry<String, Integer>> order(List<Entry<String, Integer>> insertionOrder) {
  return new Ordering<Entry<String, Integer>>() {
    @Override
    public int compare(Entry<String, Integer> left, Entry<String, Integer> right) {
      return left.getKey().compareTo(right.getKey());
    }
  }.sortedCopy(insertionOrder);
}
 
Example 38
Project: tac-kbp-eal   File: _Response.java   Source Code and License 5 votes vote down vote up
private HashCode computeSHA1Hash() {
  final Hasher hasher = SHA1_HASHER.newHasher()
      .putString(docID().toString(), Charsets.UTF_8)
      .putString(type().toString(), Charsets.UTF_8)
      .putString(role().toString(), Charsets.UTF_8)
      .putString(canonicalArgument().string(), Charsets.UTF_8)
      .putInt(canonicalArgument().charOffsetSpan().startInclusive())
      .putInt(canonicalArgument().charOffsetSpan().endInclusive())
      .putInt(baseFiller().startInclusive())
      .putInt(baseFiller().endInclusive());

  // we put PJ_CODE and AAJ_CODE into the hash because without them,
  // observe that shifting a second PJ element to being the first AAJ
  // element results in the same hash
  hasher.putInt(PJ_CODE);
  for (final CharOffsetSpan pj : Ordering.natural().sortedCopy(predicateJustifications())) {
    hasher.putInt(pj.startInclusive()).putInt(pj.endInclusive());
  }

  hasher.putInt(AAJ_CODE);
  for (final CharOffsetSpan aaj : Ordering.natural().sortedCopy(
      additionalArgumentJustifications())) {
    hasher.putInt(aaj.startInclusive()).putInt(aaj.endInclusive());
  }

  hasher.putInt(realis().ordinal());

  return hasher.hash();
}
 
Example 39
Project: tac-kbp-eal   File: _Response.java   Source Code and License 5 votes vote down vote up
@Override
public int compare(final Response left, final Response right) {
  return ComparisonChain.start()
      .compare(left.docID().toString(), right.docID().toString())
      .compare(
          Ordering.natural().sortedCopy(left.predicateJustifications()),
          Ordering.natural().sortedCopy(right.predicateJustifications()),
          Ordering.<CharOffsetSpan>natural().lexicographical())
      .compare(left.baseFiller(), right.baseFiller())
      .compare(left.canonicalArgument().charOffsetSpan(),
          right.canonicalArgument().charOffsetSpan())
      .compare(left.realis(), right.realis())
      .result();
}
 
Example 40
Project: businessworks   File: Errors.java   Source Code and License 5 votes vote down vote up
public List<Message> getMessages() {
  if (root.errors == null) {
    return ImmutableList.of();
  }

  return new Ordering<Message>() {
    @Override
    public int compare(Message a, Message b) {
      return a.getSource().compareTo(b.getSource());
    }
  }.sortedCopy(root.errors);
}
 
Example 41
Project: andbg   File: CollectionUtils.java   Source Code and License 5 votes vote down vote up
public static <T> boolean isNaturalSortedSet(@Nonnull Iterable<? extends T> it) {
    if (it instanceof SortedSet) {
        SortedSet<? extends T> sortedSet = (SortedSet<? extends T>)it;
        Comparator<?> comparator = sortedSet.comparator();
        return (comparator == null) || comparator.equals(Ordering.natural());
    }
    return false;
}
 
Example 42
Project: morf   File: ViewChanges.java   Source Code and License 5 votes vote down vote up
/**
 * @return sorted list of the views to deploy in the order they should be deployed.
 */
public List<View> getViewsToDeploy() {
  // Sort the list into creation order based on toposort result
  List<String> sortedViewNamesToDeploy = newArrayList(deploySet);
  Collections.sort(sortedViewNamesToDeploy, Ordering.explicit(viewCreationOrder));

  // Transform the sorted list back into a set of sorted views and return
  return Lists.transform(sortedViewNamesToDeploy, nameToView());
}
 
Example 43
Project: morf   File: DatabaseMetaDataProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Finds the primary keys for the {@code tableName}.
 *
 * @param tableName the table to query for.
 * @return a collection of the primary keys.
 */
protected List<String> getPrimaryKeys(String tableName) {
  List<PrimaryKeyColumn> columns = newArrayList();
  try {
    final DatabaseMetaData databaseMetaData = connection.getMetaData();

    ResultSet primaryKeyResults = databaseMetaData.getPrimaryKeys(null, schemaName, tableName);

    try {
      while (primaryKeyResults.next()) {
        columns.add(new PrimaryKeyColumn(primaryKeyResults.getShort(5), primaryKeyResults.getString(4)));
      }
    } finally {
      primaryKeyResults.close();
    }
  } catch (SQLException sqle) {
    throw new RuntimeSqlException("Error reading primary keys for table [" + tableName + "]", sqle);
  }

  List<PrimaryKeyColumn> sortedColumns = Ordering.from(new Comparator<PrimaryKeyColumn>() {
    @Override
    public int compare(PrimaryKeyColumn o1, PrimaryKeyColumn o2) {
      return o1.sequence.compareTo(o2.sequence);
    }
  }).sortedCopy(columns);

  // Convert to String before returning
  return transform(sortedColumns, new Function<PrimaryKeyColumn, String>() {
    @Override
    public String apply(PrimaryKeyColumn input) {
      return input.name;
    }
  });
}
 
Example 44
Project: tac-kbp-eal   File: _TypeRoleFillerRealis.java   Source Code and License 5 votes vote down vote up
public static Ordering<TypeRoleFillerRealis> byCAS() {
  return new Ordering<TypeRoleFillerRealis>() {
    @Override
    public int compare(final TypeRoleFillerRealis left, final TypeRoleFillerRealis right) {
      return left.argumentCanonicalString().string().compareTo(right.argumentCanonicalString().string());
    }
  };
}
 
Example 45
Project: tac-kbp-eal   File: _TypeRoleFillerRealis.java   Source Code and License 5 votes vote down vote up
public static Ordering<TypeRoleFillerRealis> byRealis() {
  return new Ordering<TypeRoleFillerRealis>() {
    @Override
    public int compare(final TypeRoleFillerRealis left, final TypeRoleFillerRealis right) {
      return left.realis().name().compareTo(right.realis().name());
    }
  };
}
 
Example 46
Project: tac-kbp-eal   File: SingleFileQueryStoreWriter.java   Source Code and License 5 votes vote down vote up
public void saveTo(final CorpusQueryAssessments store, final CharSink sink)
    throws IOException {
  final Writer out = sink.openStream();
  for (final QueryResponse2016 q : by2016Ordering().immutableSortedCopy(store.queryReponses())) {
    final Optional<String> metadata = Optional.fromNullable(store.metadata().get(q));
    if (metadata.isPresent()) {
      out.write("#" + metadata.get() + "\n");
    }
    final QueryAssessment2016 assessment =
        Optional.fromNullable(store.assessments().get(q)).or(QueryAssessment2016.UNASSESSED);

    final ImmutableList.Builder<String> pjStrings = ImmutableList.builder();
    for (final CharOffsetSpan pj : Ordering.natural()
        .immutableSortedCopy(q.predicateJustifications())) {
      pjStrings.add(dashJoiner.join(pj.startInclusive(), pj.endInclusive()));
    }
    final String pjString = commaJoiner.join(pjStrings.build());
    final String systemIDs = StringUtils.commaJoiner()
        .join(FluentIterable.from(store.queryResponsesToSystemIDs().get(q))
            .transform(SymbolUtils.desymbolizeFunction()).toSet());

    final String line =
        tabJoiner.join(q.queryID(), q.docID(), systemIDs, pjString, assessment.name());
    out.write(line + "\n");
  }
  out.close();
}
 
Example 47
Project: CustomWorldGen   File: Clips.java   Source Code and License 5 votes vote down vote up
public Iterable<Event> pastEvents(float lastPollTime, float time)
{
    if(parameter.apply(lastPollTime) < 0 && parameter.apply(time) >= 0)
    {
        return Iterables.mergeSorted(ImmutableSet.of(
            clip.pastEvents(lastPollTime, time),
            ImmutableSet.of(new Event(event, 0))
        ), Ordering.<Event>natural());
    }
    return clip.pastEvents(lastPollTime, time);
}
 
Example 48
Project: MinoanER   File: RelationsRank.java   Source Code and License 5 votes vote down vote up
public JavaPairRDD<String,Float> getSupportOfRelations(JavaPairRDD<String,List<Tuple2<Integer, Integer>>> relationIndex, long numEntititiesSquared, float minSupportThreshold) {
    JavaPairRDD<String, Float> unnormalizedSupports = relationIndex
            .mapValues(so -> (float)so.size() / numEntititiesSquared);
    unnormalizedSupports.setName("unnormalizedSupports").cache();        
    
    System.out.println(unnormalizedSupports.count()+" relations have been assigned a support value"); // dummy action to trigger execution
    float max_support = unnormalizedSupports.values().max(Ordering.natural());        
    return unnormalizedSupports
            .mapValues(x-> x/max_support)           //normalize the support values
            .filter(x-> x._2()> minSupportThreshold); //filter out relations below the min support threshold (infrequent relations)
}
 
Example 49
Project: Java-EX   File: StringUtil.java   Source Code and License 5 votes vote down vote up
public static int firstIndexOf(String str, String... ts) {
  return Stream.of(ts)
      .map(str::indexOf)
      .filter(i -> i != -1)
      .min(Ordering.natural())
      .orElse(-1);
}
 
Example 50
Project: Java-EX   File: StringUtil.java   Source Code and License 5 votes vote down vote up
public static int lastIndexOf(String str, String... ts) {
  return Stream.of(ts)
      .map(str::lastIndexOf)
      .filter(i -> i != -1)
      .max(Ordering.natural())
      .orElse(-1);
}
 
Example 51
Project: guava-mock   File: TypeToken.java   Source Code and License 5 votes vote down vote up
private static <K, V> ImmutableList<K> sortKeysByValue(
    final Map<K, V> map, final Comparator<? super V> valueComparator) {
  Ordering<K> keyOrdering =
      new Ordering<K>() {
        @Override
        public int compare(K left, K right) {
          return valueComparator.compare(map.get(left), map.get(right));
        }
      };
  return keyOrdering.immutableSortedCopy(map.keySet());
}
 
Example 52
Project: guava-mock   File: ServiceManager.java   Source Code and License 5 votes vote down vote up
ImmutableMap<Service, Long> startupTimes() {
  List<Entry<Service, Long>> loadTimes;
  monitor.enter();
  try {
    loadTimes = Lists.newArrayListWithCapacity(startupTimers.size());
    // N.B. There will only be an entry in the map if the service has started
    for (Entry<Service, Stopwatch> entry : startupTimers.entrySet()) {
      Service service = entry.getKey();
      Stopwatch stopWatch = entry.getValue();
      if (!stopWatch.isRunning() && !(service instanceof NoOpService)) {
        loadTimes.add(Maps.immutableEntry(service, stopWatch.elapsed(MILLISECONDS)));
      }
    }
  } finally {
    monitor.leave();
  }
  Collections.sort(
      loadTimes,
      Ordering.natural()
          .onResultOf(
              new Function<Entry<Service, Long>, Long>() {
                @Override
                public Long apply(Map.Entry<Service, Long> input) {
                  return input.getValue();
                }
              }));
  return ImmutableMap.copyOf(loadTimes);
}
 
Example 53
Project: ArchUnit   File: SliceCycleArchCondition.java   Source Code and License 5 votes vote down vote up
private Map<String, Edge<Slice, Dependency>> sortEdgesByDescription(Cycle<Slice, Dependency> cycle) {
    LinkedList<Edge<Slice, Dependency>> edges = new LinkedList<>(cycle.getEdges());
    Edge<Slice, Dependency> startEdge = Ordering.natural().onResultOf(GET_FROM_NODE_DESCRIPTION).min(edges);
    while (!edges.getFirst().equals(startEdge)) {
        edges.addLast(edges.pollFirst());
    }
    Map<String, Edge<Slice, Dependency>> descriptionToEdge = new LinkedHashMap<>();
    for (Edge<Slice, Dependency> edge : edges) {
        descriptionToEdge.put(edge.getFrom().getDescription(), edge);
    }
    return descriptionToEdge;
}
 
Example 54
Project: guava-mock   File: SetGenerators.java   Source Code and License 5 votes vote down vote up
private static Ordering<String> createExplicitComparator(String[] elements) {
  // Collapse equal elements, which Ordering.explicit() doesn't support, while
  // maintaining the ordering by first occurrence.
  Set<String> elementsPlus = Sets.newLinkedHashSet();
  elementsPlus.add(BEFORE_FIRST);
  elementsPlus.add(BEFORE_FIRST_2);
  elementsPlus.addAll(Arrays.asList(elements));
  elementsPlus.add(AFTER_LAST);
  elementsPlus.add(AFTER_LAST_2);
  return Ordering.explicit(Lists.newArrayList(elementsPlus));
}
 
Example 55
Project: guava-mock   File: SortedMapGenerators.java   Source Code and License 5 votes vote down vote up
@Override
public Iterable<Entry<String, Integer>> order(List<Entry<String, Integer>> insertionOrder) {
  return new Ordering<Entry<String, Integer>>() {
    @Override
    public int compare(Entry<String, Integer> left, Entry<String, Integer> right) {
      return left.getKey().compareTo(right.getKey());
    }
  }.sortedCopy(insertionOrder);
}
 
Example 56
Project: de.flapdoodle.solid   File: Blobs.java   Source Code and License 5 votes vote down vote up
public static Ordering<Blob> comparatorOf(ImmutableList<String> currentOrdering) {
	Preconditions.checkArgument(!currentOrdering.isEmpty(),"invalid ordering: %s",currentOrdering);
	
	ImmutableList<Ordering<Blob>> all = currentOrdering.stream()
		.map(p -> orderingFor(p))
		.collect(ImmutableList.toImmutableList());
	
	return Ordering.compound(all);
}
 
Example 57
Project: guava-mock   File: FreshValueGenerator.java   Source Code and License 5 votes vote down vote up
@Generates private <T> Ordering<T> generateOrdering() {
  return new Ordering<T>() {
    @Override public int compare(T left, T right) {
      return 0;
    }
    final String string = paramString(Ordering.class, generateInt());
    @Override public String toString() {
      return string;
    }
  };
}
 
Example 58
Project: graphiak   File: GraphiteMetric.java   Source Code and License 5 votes vote down vote up
@Override
public int compareTo(GraphiteMetric that) {
    return ComparisonChain.start()
            .compare(this.timestamp, that.timestamp,
                    Ordering.natural().reverse())
            .compare(this.path, that.path).compare(this.value, that.value)
            .result();
}
 
Example 59
Project: de.flapdoodle.solid   File: Blobs.java   Source Code and License 5 votes vote down vote up
private static Comparator<? super Entry<ImmutableMap<String, Object>, Collection<Blob>>> pathOrderingOf(ImmutableList<String> pathOrdering) {
	return (Entry<ImmutableMap<String, Object>, Collection<Blob>> l,Entry<ImmutableMap<String, Object>, Collection<Blob>> r) -> {
		for (String key : pathOrdering) {
			int ret=Objects.compare(asString(l.getKey().get(key)), asString(r.getKey().get(key)), Ordering.natural());
			if (ret!=0) {
				return ret;
			}
		}
		return 0;
	};
}
 
Example 60
Project: guava-mock   File: ForwardingWrapperTesterTest.java   Source Code and License 5 votes vote down vote up
@Override public void foo(
    String s, Runnable r, Number n, Iterable<?> it, boolean b, Equivalence<String> eq,
    Exception e, InputStream in, Comparable<?> c, Ordering<Integer> ord,
    Charset charset, TimeUnit unit, Class<?> cls, Joiner joiner,
    Pattern pattern, UnsignedInteger ui, UnsignedLong ul, StringBuilder sb,
    Predicate<?> pred, Function<?, ?> func, Object obj) {
  delegate.foo(s,
      r, n, it, b, eq, e, in, c, ord, charset, unit, cls, joiner, pattern,
      ui, ul, sb, pred, func, obj);
}