项目:ARCLib
文件:HistoricStore.java
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);
}
项目:CustomWorldGen
文件:Loader.java
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);
}
}
项目:cakes
文件:TreeMultimapDemo.java
/**
* 测试 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,new Order4TreeMultimap(22,"haha4"));
treeMultimap.put("order_list1",new Order4TreeMultimap(444,"haha5"));
// 列表2
treeMultimap.put("order_list2","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));
}
项目:HCFCore
文件:ConquestTracker.java
/**
* 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;
}
项目:n4js
文件:OpenTypeSelectionDialog.java
@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);
}
});
}
项目:Elasticsearch
文件:OrderingByPosition.java
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;
}
项目:java-monitoring-client-library
文件:AbstractMetricSubject.java
/**
* 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();
}
项目:tensorflow-spring-cloud-stream-app-starters
文件:LabelImageTensorflowOutputConverter.java
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;
}
项目:preDict
文件:PreDict.java
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);
}
项目:tac-kbp-eal
文件:_CorpusQueryAssessments.java
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(),_CorpusQueryAssessments.<String>getFirstFunction()))
.build();
}
项目:Elasticsearch
文件:SortingTopNProjector.java
/**
* @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);
}
@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();
}
项目:QDrill
文件:MapVector.java
@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();
}
项目:tac-kbp-eal
文件:BreakdownFunctions.java
/**
* @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,ProvenanceType>>
printModes =
ImmutableMap.builder();
for (final Map.Entry<String,SignatureType>> breakdownEntry : breakdowns
.entrySet()) {
printModes.put(breakdownEntry.getKey(),corpusConfusionMatrix.breakdown(breakdownEntry.getValue(),resultKeyOrdering));
}
return printModes.build();
}
项目:tac-kbp-eal
文件:EAScoringObserver.java
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();
}
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,Ordering.from(comparator).nullsFirst()).result();
}
};
}
}
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,Ordering.natural().nullsFirst()).result();
}
};
} else {
this.indexedComparator = new Comparator<RowIndexedLongValue>() {
@Override
public int compare(final RowIndexedLongValue o1,Ordering.from(comparator).nullsFirst()).result();
}
};
}
}
项目:jLZJD
文件:LZJDf.java
/**
* 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;
}
项目:guava-mock
文件:StripedTest.java
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));
}
}
}
项目:guava-mock
文件:ElementOrderTest.java
@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);
}
/**
* 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);
}
}
}
项目:athena
文件:PartitionsListCommand.java
/**
* displays partition client info as text.
*
* @param partitionClientInfo partition client @R_470_4045@ion
*/
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("-------------------------------------------------------------------");
}
}
}
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);
}
项目:andbg
文件:EncodedValueWriter.java
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));
}
}
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);
}
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());
}
项目:Reer
文件:ModelTypes.java
项目:Reer
文件:BuildInvocationsBuilder.java
@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);
}
项目:Reer
文件:VersionNumber.java
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));
}
项目:BUILD_file_generator
文件:JavaSourceFileParser.java
/** 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));
}
@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);
}
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());
}
项目:CustomWorldGen
文件:Clips.java
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());
}
项目:Elasticsearch
文件:FunctionIdent.java
@Override
public int compareto(FunctionIdent o) {
return ComparisonChain.start()
.compare(name,o.name)
.compare(argumentTypes,o.argumentTypes,Ordering.<DataType>natural().lexicographical())
.result();
}
项目:morf
文件:TestViewChanges.java
/**
* 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);
}
@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);
}
项目:tac-kbp-eal
文件:_Response.java
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();
}
项目:tac-kbp-eal
文件:_Response.java
@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();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。