Example usage for com.google.common.base Predicates not

List of usage examples for com.google.common.base Predicates not

Introduction

In this page you can find the example usage for com.google.common.base Predicates not.

Prototype

public static <T> Predicate<T> not(Predicate<T> predicate) 

Source Link

Document

Returns a predicate that evaluates to true if the given predicate evaluates to false .

Usage

From source file:com.datastax.driver.core.policies.HostFilterPolicy.java

/**
 * Create a new policy that wraps the provided child policy but only "forbids" hosts
 * whose DC belongs to the provided list.
 *
 * @param childPolicy the wrapped policy.
 * @param dcs         the DCs./*  w  ww.  j  a v a  2s  .c  o  m*/
 * @return the policy.
 */
public static HostFilterPolicy fromDCBlackList(LoadBalancingPolicy childPolicy, Iterable<String> dcs) {
    return new HostFilterPolicy(childPolicy, Predicates.not(hostDCPredicate(dcs, false)));
}

From source file:edu.mit.streamjit.impl.compiler.Schedule.java

private static <T> Schedule<T> schedule(ImmutableSet<T> things,
        ImmutableSet<ExecutionConstraint<T>> executionConstraints,
        ImmutableSet<BufferingConstraint<T>> bufferingConstraints, int multiplier, int fireCost,
        int excessBufferCost) {
    ILPSolver solver = new ILPSolver();
    //There's one variable for each thing, which represents the number of
    //times it fires.  This uses the default bounds.  (TODO: perhaps a bound
    //at 1 if we're steady-state scheduling, maybe by marking things as
    //must-fire and marking the bottommost thing?)
    ImmutableMap.Builder<T, ILPSolver.Variable> variablesBuilder = ImmutableMap.builder();
    for (T thing : things)
        variablesBuilder.put(thing, solver.newVariable(thing.toString()));
    ImmutableMap<T, ILPSolver.Variable> variables = variablesBuilder.build();

    for (ExecutionConstraint<T> constraint : executionConstraints)
        solver.constrainAtLeast(variables.get(constraint.thing).asLinearExpr(1), constraint.minExecutions);

    HashMap<ILPSolver.Variable, Integer> sumOfConstraints = new HashMap<>();
    for (ILPSolver.Variable v : variables.values())
        sumOfConstraints.put(v, 0);//from   www . ja  v  a  2  s  . c o m
    for (BufferingConstraint<T> constraint : bufferingConstraints) {
        ILPSolver.Variable upstreamVar = variables.get(constraint.upstream),
                downstreamVar = variables.get(constraint.downstream);
        ILPSolver.LinearExpr expr = upstreamVar.asLinearExpr(constraint.pushRate).minus(constraint.popRate,
                downstreamVar);
        switch (constraint.condition) {
        case LESS_THAN_EQUAL:
            solver.constrainAtMost(expr, constraint.bufferDelta);
            break;
        case EQUAL:
            solver.constrainEquals(expr, constraint.bufferDelta);
            break;
        case GREATER_THAN_EQUAL:
            solver.constrainAtLeast(expr, constraint.bufferDelta);
            break;
        default:
            throw new AssertionError(constraint.condition);
        }

        sumOfConstraints.put(upstreamVar, sumOfConstraints.get(upstreamVar) + constraint.pushRate);
        sumOfConstraints.put(downstreamVar, sumOfConstraints.get(downstreamVar) - constraint.popRate);
    }

    //Add a special constraint to ensure at least one filter fires.
    //TODO: in init schedules we might not always need this...
    Iterator<ILPSolver.Variable> variablesIter = variables.values().iterator();
    ILPSolver.LinearExpr totalFirings = variablesIter.next().asLinearExpr(1);
    while (variablesIter.hasNext())
        totalFirings = totalFirings.plus(1, variablesIter.next());
    solver.constrainAtLeast(totalFirings, 1);

    for (ILPSolver.Variable v : variables.values())
        sumOfConstraints.put(v, sumOfConstraints.get(v) * excessBufferCost + fireCost);
    ILPSolver.ObjectiveFunction objFn = solver.minimize(
            solver.newLinearExpr(Maps.filterValues(sumOfConstraints, Predicates.not(Predicates.equalTo(0)))));

    try {
        solver.solve();
    } catch (SolverException ex) {
        throw new ScheduleException(ex);
    }

    ImmutableMap.Builder<T, Integer> schedule = ImmutableMap.builder();
    for (Map.Entry<T, ILPSolver.Variable> e : variables.entrySet())
        schedule.put(e.getKey(), e.getValue().value() * multiplier);
    return new Schedule<>(things, bufferingConstraints, schedule.build());
}

From source file:eu.lp0.cursus.scoring.scores.impl.GenericOverallPositionData.java

@Override
protected LinkedListMultimap<Integer, Pilot> calculateOverallPositionsWithOrder() {
    // Invert race points with ordered lists of pilots
    Comparator<Pilot> racePlacings = new PilotRacePlacingComparator<T>(scores, placingMethod);
    Comparator<Pilot> fallbackOrdering = new PilotRaceNumberComparator();
    TreeMultimap<Integer, Pilot> invOverallPoints = TreeMultimap.create(Ordering.natural(),
            Ordering.from(racePlacings).compound(fallbackOrdering));
    Multimaps.invertFrom(Multimaps.forMap(scores.getOverallPoints()), invOverallPoints);

    // Calculate overall positions
    LinkedListMultimap<Integer, Pilot> overallPositions = LinkedListMultimap.create();
    List<Pilot> collectedPilots = new ArrayList<Pilot>(scores.getPilots().size());
    LinkedList<SortedSet<Pilot>> pilotPointsOrdering = new LinkedList<SortedSet<Pilot>>();
    int position = 1;

    if (allSimulatedToEnd) {
        final Map<Pilot, ? extends Set<Race>> simulatedPilotPoints = scores.getSimulatedPilotPoints();
        Predicate<Pilot> allSimulatedPilot = new Predicate<Pilot>() {
            private final int raceCount = scores.getRaces().size();

            @Override/*  w ww.  jav  a2s  . c  om*/
            public boolean apply(Pilot input) {
                return simulatedPilotPoints.get(input).size() == raceCount;
            }
        };

        for (Integer points : invOverallPoints.keySet()) {
            SortedSet<Pilot> pilots = Sets.filter(invOverallPoints.get(points),
                    Predicates.not(allSimulatedPilot));
            if (!pilots.isEmpty()) {
                pilotPointsOrdering.add(pilots);
            }
        }
        for (Integer points : invOverallPoints.keySet()) {
            SortedSet<Pilot> pilots = Sets.filter(invOverallPoints.get(points), allSimulatedPilot);
            if (!pilots.isEmpty()) {
                pilotPointsOrdering.add(pilots);
            }
        }
    } else {
        for (Integer points : invOverallPoints.keySet()) {
            pilotPointsOrdering.add(invOverallPoints.get(points));
        }
    }

    for (SortedSet<Pilot> pilots : pilotPointsOrdering) {
        switch (equalPositioning) {
        case ALWAYS:
            // Always put pilots with the same points in the same position
            overallPositions.putAll(position, pilots);
            position += pilots.size();
            break;

        case IF_REQUIRED:
            // Try to put pilots with the same points in separate positions
            PeekingIterator<Pilot> it = Iterators.peekingIterator(pilots.iterator());
            while (it.hasNext()) {
                Pilot pilot = it.next();
                collectedPilots.add(pilot);

                // If this pilot compares equally with the next pilot, add them too
                while (it.hasNext() && racePlacings.compare(it.peek(), pilot) == 0) {
                    collectedPilots.add(it.next());
                }

                // Sort them by an arbitrary order
                Collections.sort(collectedPilots, fallbackOrdering);

                // Add them all to this position
                overallPositions.putAll(position, collectedPilots);
                position += collectedPilots.size();

                collectedPilots.clear();
            }
            break;
        }
    }

    return overallPositions;
}

From source file:com.qcadoo.mes.productionPerShift.util.NonWorkingShiftsNotifier.java

private Iterable<ShiftAndDate> filterShiftsNotWorkingAtWeekday(final Iterable<ShiftAndDate> shiftsAndDates) {
    return Iterables.filter(shiftsAndDates, Predicates.not(IS_WORKING_AT_WEEKDAY));
}

From source file:org.lenskit.data.dao.EventCollectionDAO.java

@SuppressWarnings("unchecked")
@Override// w  w  w . ja  v  a  2 s  .  c  o  m
public <E extends Event> ObjectStream<E> streamEvents(Class<E> type, SortOrder order) {
    // We need to filter if there are any event types that are not subtypes of `type`.
    boolean needFilter = Iterables.any(types, Predicates.not(TypeUtils.subtypePredicate(type)));

    Comparator<Event> comp = order.getEventComparator();

    if (!needFilter) {
        // no need to filter - just wrap up our events and cast.
        if (comp == null) {
            return (ObjectStream<E>) ObjectStreams.wrap(events);
        } else {
            @SuppressWarnings("rawtypes")
            List evts = Lists.newArrayList(events);
            Collections.sort(evts, comp);
            return ObjectStreams.wrap(evts);
        }
    } else {
        // Now we must filter our events.
        if (comp == null) {
            return ObjectStreams.filter(streamEvents(), type);
        } else {
            List<E> filtered = Lists.newArrayList(Iterables.filter(events, type));
            Collections.sort(filtered, comp);
            return ObjectStreams.wrap(filtered);
        }
    }
}

From source file:org.sosy_lab.cpachecker.cfa.postprocessing.global.CFAReduction.java

public void removeIrrelevantForSpecification(final MutableCFA cfa) throws InterruptedException {
    Collection<CFANode> errorNodes = getErrorNodesWithCPA(cfa);

    if (errorNodes.isEmpty()) {
        // shortcut, all nodes are irrelevant
        cfa.clear();//  ww w . java 2  s  . c  om
        return;
    }

    Collection<CFANode> allNodes = cfa.getAllNodes();

    if (errorNodes.size() == allNodes.size()) {
        // shortcut, no node is irrelevant
        return;
    }

    CFATraversal.NodeCollectingCFAVisitor cfaVisitor = new CFATraversal.NodeCollectingCFAVisitor();
    CFATraversal traversal = CFATraversal.dfs().backwards();
    // backwards search to determine all relevant nodes
    for (CFANode n : errorNodes) {
        traversal.traverse(n, cfaVisitor);
    }
    Set<CFANode> relevantNodes = cfaVisitor.getVisitedNodes();

    assert allNodes.containsAll(relevantNodes) : "Inconsistent CFA";

    int numIrrelevantNodes = allNodes.size() - relevantNodes.size();

    logger.log(Level.INFO, "Detected", numIrrelevantNodes, "irrelevant CFA nodes.");

    if (numIrrelevantNodes == 0) {
        // shortcut, no node is irrelevant
        return;
    }

    Predicate<CFANode> irrelevantNode = Predicates.not(Predicates.in(relevantNodes));
    Collection<CFANode> removedNodes = ImmutableList.copyOf(Collections2.filter(allNodes, irrelevantNode));

    // now detach all the nodes not visited
    pruneIrrelevantNodes(cfa, removedNodes, errorNodes);
}

From source file:org.concord.energy3d.scene.CameraControl.java

public void setupMouseTriggers(final LogicalLayer layer, final boolean dragOnly) {
    // Mouse look
    final Predicate<TwoInputStates> someMouseDown = Predicates.or(TriggerConditions.leftButtonDown(),
            Predicates.or(TriggerConditions.rightButtonDown(), TriggerConditions.middleButtonDown()));
    final Predicate<TwoInputStates> dragged = Predicates.and(TriggerConditions.mouseMoved(),
            Predicates.and(someMouseDown, Predicates.not(new KeyHeldCondition(Key.LCONTROL))));
    final TriggerAction dragAction = new TriggerAction() {

        // Test boolean to allow us to ignore first mouse event. First event can wildly vary based on platform.
        private boolean firstPing = true;

        @Override/*from  ww w .  ja  v a  2  s .c  o  m*/
        public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
            if (!enabled || !mouseEnabled)
                return;
            final MouseState mouse = inputStates.getCurrent().getMouseState();
            if (mouse.getDx() != 0 || mouse.getDy() != 0) {
                if (!firstPing) {
                    final boolean left = leftMouseButtonEnabled
                            && mouse.getButtonState(MouseButton.LEFT) == ButtonState.DOWN;
                    final boolean right = rightMouseButtonEnabled
                            && mouse.getButtonState(MouseButton.RIGHT) == ButtonState.DOWN;
                    final boolean middle = mouse.getButtonState(MouseButton.MIDDLE) == ButtonState.DOWN;
                    if (left && leftButtonAction == ButtonAction.MOVE
                            || right && rightButtonAction == ButtonAction.MOVE) {
                        final double fac = Camera.getCurrentCamera().getLocation().length() * 150;
                        final double dx = -mouse.getDx() * fac / Camera.getCurrentCamera().getWidth();
                        final double dy = -mouse.getDy() * fac / Camera.getCurrentCamera().getHeight() / 4.0;
                        move(source.getCanvasRenderer().getCamera(), dx, dy);
                        SceneManager.getInstance().getCameraNode().updateFromCamera();
                        Scene.getInstance().updateEditShapes();
                    } else if (left && leftButtonAction == ButtonAction.ROTATE
                            || right && rightButtonAction == ButtonAction.ROTATE) {
                        rotate(source.getCanvasRenderer().getCamera(), -mouse.getDx(), -mouse.getDy());
                        SceneManager.getInstance().getCameraNode().updateFromCamera();
                        Scene.getInstance().updateEditShapes();
                    } else if (middle || left && leftButtonAction == ButtonAction.ZOOM
                            || right && rightButtonAction == ButtonAction.ZOOM) {
                        int dy = inputStates.getCurrent().getMouseState().getDy();
                        if (dy < -4)
                            dy = -4;
                        if (dy > 4)
                            dy = 4;
                        zoom(source, tpf, -dy / 1.0);
                    }
                } else {
                    firstPing = false;
                }
            }
        }
    };

    _mouseTrigger = new InputTrigger(dragOnly ? dragged : TriggerConditions.mouseMoved(), dragAction);
    layer.registerTrigger(_mouseTrigger);

    layer.registerTrigger(new InputTrigger(new MouseWheelMovedCondition(), new TriggerAction() {
        @Override
        public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
            zoom(source, tpf, inputStates.getCurrent().getMouseState().getDwheel());
        }
    }));
}

From source file:com.lithium.flow.config.repos.Repos.java

@Nonnull
public static Filer buildFiler(@Nonnull Config config, @Nonnull String url, @Nonnull Access access)
        throws IOException {
    checkNotNull(config);//from w ww . j av a2s  . com
    checkNotNull(url);
    checkNotNull(access);

    try {
        String host = URI.create(url).getHost();
        Login login = access.getLogin(host);
        SvnProvider svnProvider = new LoginSvnProvider(url, login);
        svnProvider = new PoolSvnProvider(svnProvider, config);

        boolean search = config.getList("configs.search", Configs.emptyList()).contains(url);
        Filer filer = new SvnFiler(svnProvider, search);
        filer = new CachedFiler(filer, config.prefix("configs"));
        filer = new CachedReadFiler(filer);
        if (config.containsKey("configs.exclude")) {
            Predicate<Record> predicate = Predicates
                    .not(new RegexPathPredicate(config.getList("configs.exclude")));
            filer = new FilteredFiler(filer, predicate);
        }
        return filer;
    } catch (SVNException e) {
        throw new IOException("failed to build filer: " + url, e);
    }
}

From source file:org.apache.brooklyn.util.collections.CollectionFunctionals.java

public static Predicate<Iterable<?>> notEmpty() {
    return Predicates.not(empty());
}

From source file:eu.lp0.cursus.scoring.scores.impl.AveragingRacePointsData.java

private Set<Race> getOtherRacesForPilot(Pilot pilot, Race race, boolean checkDiscards) {
    Set<Race> otherRaces = new HashSet<Race>(scores.getRaces().size() * 2);

    // Find other races where the pilot is not attending in a mandatory position
    for (Race otherRace : Iterables.filter(scores.getRaces(), Predicates.not(Predicates.equalTo(race)))) {
        if (!scores.hasSimulatedRacePoints(pilot, otherRace)) {
            otherRaces.add(otherRace);/*from   www.j ava 2 s. c o  m*/
        }
    }

    // If averaging should occur after discards, remove discards... unless that removes all races
    if (checkDiscards && !otherRaces.isEmpty() && method == AveragingMethod.AFTER_DISCARDS) {
        Set<Race> discardedRaces = scoresBeforeAveraging.getDiscardedRaces(pilot);
        if (!discardedRaces.containsAll(otherRaces)) {
            otherRaces.removeAll(discardedRaces);
        }
    }

    return otherRaces;
}