Example usage for com.google.common.collect Iterables any

List of usage examples for com.google.common.collect Iterables any

Introduction

In this page you can find the example usage for com.google.common.collect Iterables any.

Prototype

public static <T> boolean any(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns true if any element in iterable satisfies the predicate.

Usage

From source file:com.isotrol.impe3.pms.core.dao.impl.DAOImpl.java

/**
 * @see com.isotrol.impe3.pms.core.dao.DAO#isUsed(java.util.UUID, com.isotrol.impe3.pms.model.Entity,
 * java.lang.Iterable)//from  w w w  .ja  va 2  s .  co  m
 */
public boolean isUsed(final UUID envId, final Entity entity, final Iterable<String> queries) {
    final Predicate<String> hasRows = new Predicate<String>() {
        public boolean apply(String input) {
            return hasRows(input, envId, entity);
        }
    };
    return Iterables.any(queries, hasRows);
}

From source file:com.twitter.aurora.scheduler.filter.SchedulingFilterImpl.java

private boolean isDedicated(final String slaveHost) {
    Iterable<Attribute> slaveAttributes = storage.weaklyConsistentRead(new Quiet<Iterable<Attribute>>() {
        @Override// www. ja v a  2s  . c o  m
        public Iterable<Attribute> apply(final StoreProvider storeProvider) {
            return AttributeStore.Util.attributesOrNone(storeProvider, slaveHost);
        }
    });

    return Iterables.any(slaveAttributes, new ConstraintFilter.NameFilter(DEDICATED_ATTRIBUTE));
}

From source file:org.trnltk.morphology.lexicon.ImmutableRootGenerator.java

private boolean hasVowel(String str) {
    return Iterables.any(Lists.newArrayList(ArrayUtils.toObject(str.toCharArray())),
            new Predicate<Character>() {
                @Override/*from w  ww.  j  av a 2s  .c om*/
                public boolean apply(Character input) {
                    return TurkishAlphabet.getLetter(input).isVowel();
                }
            });
}

From source file:uk.ac.stfc.isis.ibex.ui.configserver.dialogs.SaveConfigDialog.java

/**
 * @param name The config/component name
 * @return Whether an object already exists with this name
 *//*  w  w w. j ava 2s. c  o  m*/
private boolean isDuplicate(final String name) {
    List<String> prexisting = willBeComponent() ? existingComponents : existingConfigs;
    return Iterables.any(prexisting, new Predicate<String>() {
        @Override
        public boolean apply(String existing) {
            return compareIgnoringCase(existing, name);
        }
    });
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.operation.SynchronizeISequenceEventsSemanticOrderingOperation.java

private void applyCompoundReordering(EObject semanticElement, List<EventEnd> ends, List<EventEnd> compoundEnds,
        EventEnd startingEndPredecessor, EventEnd finishingEndPredecessor, ReorderTool reorderTool) {
    if (compoundEnds.isEmpty() || ends.size() != 2) {
        return;//from  w w  w  .  j  ava  2 s .c  o m
    }

    EventEnd startEventEnd = null;
    EventEnd endEventEnd = null;
    List<EObject> startSemanticEvents = Lists.newArrayList();

    // The main event has been reordered, the order of its ends might have
    // changed.
    for (EventEnd ee : ends) {
        SingleEventEnd see = EventEndHelper.getSingleEventEnd(ee, semanticElement);
        if (see.isStart()) {
            startEventEnd = ee;
            startSemanticEvents = EventEndHelper.getSemanticEvents(startEventEnd);
        } else {
            endEventEnd = ee;
        }
    }

    for (EventEnd ee : compoundEnds) {
        List<EObject> eeSemElts = EventEndHelper.getSemanticEvents(ee);
        EventEnd otherEnd = Iterables.any(eeSemElts, Predicates.in(startSemanticEvents)) ? startEventEnd
                : endEventEnd;
        EventEnd predecessor = Iterables.any(eeSemElts, Predicates.in(startSemanticEvents))
                ? startingEndPredecessor
                : finishingEndPredecessor;

        for (EObject elt : eeSemElts) {
            SingleEventEnd singleEventEnd = EventEndHelper.getSingleEventEnd(otherEnd, elt);
            ISequenceEvent ise = EventEndHelper.findISequenceEvent(singleEventEnd, diagram);
            if (!singleEventEnd.isStart()) {
                // SemanticEvent is before otherEnd
                applySemanticReordering(elt, predecessor, ee, reorderTool);
            } else {
                // SemanticEvent is after otherEnd
                applySemanticReordering(elt, predecessor, otherEnd, reorderTool);
            }
            reordered.add(ise);
        }
    }
}

From source file:org.sosy_lab.cpachecker.cpa.bam.BAMTransferRelation.java

private Collection<? extends AbstractState> doFixpointIterationForRecursion(
        final AbstractState pHeadOfMainFunctionState, final Precision pPrecision,
        final CFANode pHeadOfMainFunction) throws CPAException, InterruptedException {

    assert isHeadOfMainFunction(pHeadOfMainFunction) && stack.isEmpty();

    Collection<? extends AbstractState> resultStates;
    int iterationCounter = 0;
    while (true) { // fixpoint-iteration to handle recursive functions

        if (!targetFound) {
            // The target might be outside the recursive function.
            // If CEGAR removes the target through refinement,
            // we might miss the recursive function, if we reset the flags. So we do not reset them in that case.

            recursionSeen = false; // might be changed in recursive analysis
            resultStatesChanged = false; // might be changed in recursive analysis
            potentialRecursionUpdateStates.clear();
        }//  w  ww . j a  v a  2 s .co m

        logger.log(Level.FINE, "Starting recursive analysis of main-block");

        resultStates = doRecursiveAnalysis(pHeadOfMainFunctionState, pPrecision, pHeadOfMainFunction);

        logger.log(Level.FINE, "Finished recursive analysis of main-block");

        // EITHER: result is an target-state, return it 'as is' and let CEGAR-algorithm perform a refinement, if needed.
        // OR:     we have completely analyzed the main-block and have not found an target-state.
        //         now we check, if we need to unwind recursive calls further until a fixpoint is reached.

        targetFound = Iterables.any(resultStates, IS_TARGET_STATE);
        if (targetFound) {
            // not really a fixpoint, but we return and let CEGAR check the target-state
            logger.log(Level.INFO, "fixpoint-iteration aborted, because there was a target state.");
            break;
        }

        if (!resultStatesChanged) {
            logger.log(Level.INFO,
                    "fixpoint-iteration aborted, because we did not get new states (fixpoint reached).");
            break;
        }

        logger.log(Level.INFO, "fixpoint was not reached, starting new iteration", ++iterationCounter);

        reAddStatesForFixPointIteration(pHeadOfMainFunctionState);

        // continue;
    }

    return resultStates;
}

From source file:org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.table.TableContentMergeViewer.java

/**
 * {@inheritDoc}//w w  w . ja v a 2  s.com
 * 
 * @see org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.EMFCompareContentMergeViewer#paintCenter(org.eclipse.swt.widgets.Canvas,
 *      org.eclipse.swt.graphics.GC)
 */
@Override
protected void paintCenter(GC g) {
    TableMergeViewer leftMergeViewer = getLeftMergeViewer();
    TableMergeViewer rightMergeViewer = getRightMergeViewer();

    Table leftTable = leftMergeViewer.getStructuredViewer().getTable();
    Table rightTable = rightMergeViewer.getStructuredViewer().getTable();

    Rectangle leftClientArea = leftTable.getClientArea();
    Rectangle rightClientArea = rightTable.getClientArea();

    TableItem[] leftItems = leftTable.getItems();
    TableItem[] rightItems = rightTable.getItems();

    final ImmutableSet<TableItem> selection = ImmutableSet.copyOf(leftTable.getSelection());

    for (TableItem leftItem : leftItems) {
        final boolean selected = Iterables.any(selection, equalTo(leftItem));
        IMergeViewerItem leftData = (IMergeViewerItem) leftItem.getData();
        final Diff leftDiff = leftData.getDiff();
        if (leftDiff != null) {
            if (MergeViewerUtil.isVisibleInMergeViewer(leftDiff, getDifferenceGroupProvider(),
                    getDifferenceFilterPredicate())
                    && !MergeViewerUtil.isMarkAsMerged(leftDiff, leftData, getCompareConfiguration())) {
                TableItem rightItem = findRightTableItemFromLeftDiff(rightItems, leftDiff, leftData);

                if (rightItem != null) {
                    final Color strokeColor = getCompareColor().getStrokeColor(leftDiff, isThreeWay(), false,
                            selected);
                    g.setForeground(strokeColor);
                    drawCenterLine(g, leftClientArea, rightClientArea, leftItem, rightItem);
                }
            }
        }
    }
}

From source file:io.druid.indexing.overlord.autoscaling.SimpleWorkerResourceManagementStrategy.java

private void updateTargetWorkerCount(final WorkerBehaviorConfig workerConfig,
        final Collection<? extends TaskRunnerWorkItem> pendingTasks,
        final Collection<ImmutableWorkerInfo> zkWorkers) {
    synchronized (lock) {
        final Collection<ImmutableWorkerInfo> validWorkers = Collections2.filter(zkWorkers,
                ResourceManagementUtil.createValidWorkerPredicate(config));
        final Predicate<ImmutableWorkerInfo> isLazyWorker = ResourceManagementUtil
                .createLazyWorkerPredicate(config);
        final int minWorkerCount = workerConfig.getAutoScaler().getMinNumWorkers();
        final int maxWorkerCount = workerConfig.getAutoScaler().getMaxNumWorkers();

        if (minWorkerCount > maxWorkerCount) {
            log.error("Huh? minWorkerCount[%d] > maxWorkerCount[%d]. I give up!", minWorkerCount,
                    maxWorkerCount);/*  w ww .ja v a 2 s . c o m*/
            return;
        }

        if (targetWorkerCount < 0) {
            // Initialize to size of current worker pool, subject to pool size limits
            targetWorkerCount = Math.max(Math.min(zkWorkers.size(), maxWorkerCount), minWorkerCount);
            log.info("Starting with a target of %,d workers (current = %,d, min = %,d, max = %,d).",
                    targetWorkerCount, validWorkers.size(), minWorkerCount, maxWorkerCount);
        }

        final boolean notTakingActions = currentlyProvisioning.isEmpty() && currentlyTerminating.isEmpty();
        final boolean shouldScaleUp = notTakingActions && validWorkers.size() >= targetWorkerCount
                && targetWorkerCount < maxWorkerCount
                && (hasTaskPendingBeyondThreshold(pendingTasks) || targetWorkerCount < minWorkerCount);
        final boolean shouldScaleDown = notTakingActions && validWorkers.size() == targetWorkerCount
                && targetWorkerCount > minWorkerCount && Iterables.any(validWorkers, isLazyWorker);
        if (shouldScaleUp) {
            targetWorkerCount = Math.max(targetWorkerCount + 1, minWorkerCount);
            log.info("I think we should scale up to %,d workers (current = %,d, min = %,d, max = %,d).",
                    targetWorkerCount, validWorkers.size(), minWorkerCount, maxWorkerCount);
        } else if (shouldScaleDown) {
            targetWorkerCount = Math.min(targetWorkerCount - 1, maxWorkerCount);
            log.info("I think we should scale down to %,d workers (current = %,d, min = %,d, max = %,d).",
                    targetWorkerCount, validWorkers.size(), minWorkerCount, maxWorkerCount);
        } else {
            log.info("Our target is %,d workers, and I'm okay with that (current = %,d, min = %,d, max = %,d).",
                    targetWorkerCount, validWorkers.size(), minWorkerCount, maxWorkerCount);
        }
    }
}

From source file:org.jetbrains.kotlin.idea.internal.KotlinBytecodeToolWindow.java

private static boolean hasReifiedTypeParameters(CallableDescriptor descriptor) {
    return Iterables.any(descriptor.getTypeParameters(), new Predicate<TypeParameterDescriptor>() {
        @Override//from w  ww.j  a  v a 2s  .  co  m
        public boolean apply(TypeParameterDescriptor input) {
            return input.isReified();
        }
    });
}

From source file:edu.harvard.med.screensaver.ui.libraries.LibraryCopyPlateSearchResults.java

private void initialize(EntityDataFetcher<Plate, Integer> plateDataFetcher) {
    initialize(new InMemoryEntityDataModel<Plate, Integer, Plate>(plateDataFetcher) {
        private Predicate<TableColumn<Plate, ?>> isScreeningStatisticsColumnWithCriteria = new Predicate<TableColumn<Plate, ?>>() {
            @Override/*  w  w w. ja v  a2  s  .  c o m*/
            public boolean apply(TableColumn<Plate, ?> column) {
                return screeningStatisticColumns.contains(column) && column.hasCriteria();
            }
        };
        private Function<List<Plate>, Void> calculatePlateScreeningStatistics = new Function<List<Plate>, Void>() {
            @Override
            public Void apply(List<Plate> plates) {
                _librariesDao.calculatePlateScreeningStatistics(plates);
                return null;
            }
        };
        private Predicate<TableColumn<Plate, ?>> isVolumeStatisticsColumnWithCriteria = new Predicate<TableColumn<Plate, ?>>() {
            @Override
            public boolean apply(TableColumn<Plate, ?> column) {
                return volumeStatisticColumns.contains(column) && column.hasCriteria();
            }
        };
        private Function<List<Copy>, Void> calculateCopyScreeningStatistics = new Function<List<Copy>, Void>() {
            @Override
            public Void apply(List<Copy> copies) {
                _librariesDao.calculateCopyScreeningStatistics(copies);
                return null;
            }
        };

        @Override
        public void fetch(List<? extends TableColumn<Plate, ?>> columns) {
            // add fetch properties that are needed for review message generation
            if (columns.size() > 0) {
                ((HasFetchPaths<Plate>) columns.get(0)).addRelationshipPath(Plate.location);
                ((HasFetchPaths<Plate>) columns.get(0)).addRelationshipPath(Plate.copy.to(Copy.library));
            }
            ((HasFetchPaths<Plate>) columns.get(0))
                    .addRelationshipPath(RelationshipPath.from(Plate.class).to("updateActivities"));

            super.fetch(columns);
        }

        @Override
        public void filter(List<? extends TableColumn<Plate, ?>> columns) {
            if (_mode == Mode.ALL && !hasCriteriaDefined(getColumnManager().getAllColumns())) {
                setWrappedData(Collections.EMPTY_LIST); // for memory performance, initialize with an empty list.
            } else {
                boolean calcScreeningStatisticsBeforeFiltering = Iterables.any(columns,
                        isScreeningStatisticsColumnWithCriteria);
                boolean calcVolumeStatisticsBeforeFiltering = Iterables.any(columns,
                        isVolumeStatisticsColumnWithCriteria);
                if (calcScreeningStatisticsBeforeFiltering) {
                    calculateScreeningStatistics(_unfilteredData);
                }
                if (calcVolumeStatisticsBeforeFiltering) {
                    calculateVolumeStatistics(_unfilteredData);
                }

                super.filter(columns);

                if (!calcScreeningStatisticsBeforeFiltering) {
                    calculateScreeningStatistics(_unfilteredData);
                }
                if (!calcVolumeStatisticsBeforeFiltering) {
                    calculateVolumeStatistics(_unfilteredData);
                }
            }

            updateReviewMessage();
        }

        private boolean hasCriteriaDefined(List<? extends TableColumn<?, ?>> columns) {
            for (TableColumn<?, ?> column : columns) {
                if (column.hasCriteria())
                    return true;
            }
            return false;
        }

        private void calculateScreeningStatistics(Iterable<Plate> plates) {
            List<Plate> platesWithoutStatistics = Lists
                    .newArrayList(Iterables.filter(plates, PlateScreeningStatisticsNotInitialized));
            for (List<Plate> partition : Lists.partition(platesWithoutStatistics, 1024)) {
                _librariesDao.calculatePlateScreeningStatistics(partition);
            }
        }

        private void calculateVolumeStatistics(Iterable<Plate> plates) {
            List<Plate> platesWithoutStatistics = Lists
                    .newArrayList(Iterables.filter(plates, PlateVolumeStatisticsNotInitialized));
            for (List<Plate> partition : Lists.partition(platesWithoutStatistics, 1024)) {
                _librariesDao.calculatePlateVolumeStatistics(partition);
            }
        }
    });
    _libraryCopyPlateBatchEditor.initialize();
}