Example usage for java.util HashSet remove

List of usage examples for java.util HashSet remove

Introduction

In this page you can find the example usage for java.util HashSet remove.

Prototype

public boolean remove(Object o) 

Source Link

Document

Removes the specified element from this set if it is present.

Usage

From source file:biomine.bmvis2.pipeline.SizeSliderOperation.java

public void updateSizeSlider(VisualGraph visualGraph) {
    int minCount = targetSize;
    HashSet<VisualGroupNode> closedGroups = new HashSet<VisualGroupNode>();
    HashSet<VisualGroupNode> openGroups = new HashSet<VisualGroupNode>();
    for (VisualNode n : visualGraph.getNodes()) {
        if (n instanceof VisualGroupNode) {
            closedGroups.add((VisualGroupNode) n);
        }//  w  w w.  j  ava 2 s.  c  o  m
        VisualGroupNode p = n.getParent();
        if (p != null && p.getParent() != null) {

            openGroups.add(p);
            openGroups.remove(p.getParent());
        }
    }
    int curCount = visualGraph.getNodes().size();
    final int order = 1;
    final double depthMult = 0.01;
    System.out.println("openGroups.size() = " + openGroups.size());
    if (curCount > minCount) {
        // close as many open groups as possible while not going
        // under minCount nodes

        // start with nodes with most depth
        ArrayList<VisualGroupNode> groups = new ArrayList<VisualGroupNode>(openGroups);
        Collections.sort(groups, new Comparator<VisualGroupNode>() {
            public int compare(VisualGroupNode o1, VisualGroupNode o2) {
                return Double.compare((o2.getDepth() - o1.getDepth()) * depthMult
                // + hider.getNodeGoodness(o1)
                // - hider.getNodeGoodness(o2)
                , 0) * order;
            }
        });

        for (VisualGroupNode toClose : groups) {
            System.out.println("closing " + toClose);
            int s = toClose.getChildren().size();
            if (curCount - s >= minCount) {
                toClose.setOpen(false);
                curCount -= s;
            }

        }
    } else {

        ArrayList<VisualGroupNode> groups = new ArrayList<VisualGroupNode>(closedGroups);
        Collections.sort(groups, new Comparator<VisualGroupNode>() {
            public int compare(VisualGroupNode o1, VisualGroupNode o2) {
                return Double.compare((o2.getDepth() - o1.getDepth()) * depthMult
                // + hider.getNodeGoodness(o1)
                // - hider.getNodeGoodness(o2),
                , 0)

                        * order * -1;
            }
        });
        for (VisualGroupNode toOpen : groups) {
            System.out.println("opening " + toOpen);
            int s = toOpen.getChildren().size();

            toOpen.setOpen(true);
            for (VisualNode n : toOpen.getChildren())
                if (n instanceof VisualGroupNode)
                    ((VisualGroupNode) n).setOpen(false);
            curCount += s;

            if (curCount + s >= minCount)
                break;
        }

    }
}

From source file:org.apache.samza.test.framework.TestRunner.java

/**
 * Gets the contents of the output stream represented by {@code outputDescriptor} after {@link TestRunner#run(Duration)}
 * has completed/*from   w w w  .  j  av  a  2 s.  c  o  m*/
 *
 * @param outputDescriptor describes the stream to be consumed
 * @param timeout timeout for consumption of stream in Ms
 * @param <StreamMessageType> type of message
 *
 * @return a map whose key is {@code partitionId} and value is messages in partition
 * @throws SamzaException Thrown when a poll is incomplete
 */
public static <StreamMessageType> Map<Integer, List<StreamMessageType>> consumeStream(
        InMemoryOutputDescriptor outputDescriptor, Duration timeout) throws SamzaException {
    Preconditions.checkNotNull(outputDescriptor);
    String streamId = outputDescriptor.getStreamId();
    String systemName = outputDescriptor.getSystemName();
    Set<SystemStreamPartition> ssps = new HashSet<>();
    Set<String> streamIds = new HashSet<>();
    streamIds.add(streamId);
    SystemFactory factory = new InMemorySystemFactory();
    Config config = new MapConfig(outputDescriptor.toConfig(),
            outputDescriptor.getSystemDescriptor().toConfig());
    Map<String, SystemStreamMetadata> metadata = factory.getAdmin(systemName, config)
            .getSystemStreamMetadata(streamIds);
    SystemConsumer consumer = factory.getConsumer(systemName, config, null);
    String name = (String) outputDescriptor.getPhysicalName().orElse(streamId);
    metadata.get(name).getSystemStreamPartitionMetadata().keySet().forEach(partition -> {
        SystemStreamPartition temp = new SystemStreamPartition(systemName, streamId, partition);
        ssps.add(temp);
        consumer.register(temp, "0");
    });

    long t = System.currentTimeMillis();
    Map<SystemStreamPartition, List<IncomingMessageEnvelope>> output = new HashMap<>();
    HashSet<SystemStreamPartition> didNotReachEndOfStream = new HashSet<>(ssps);
    while (System.currentTimeMillis() < t + timeout.toMillis()) {
        Map<SystemStreamPartition, List<IncomingMessageEnvelope>> currentState = null;
        try {
            currentState = consumer.poll(ssps, 10);
        } catch (InterruptedException e) {
            throw new SamzaException("Timed out while consuming stream \n" + e.getMessage());
        }
        for (Map.Entry<SystemStreamPartition, List<IncomingMessageEnvelope>> entry : currentState.entrySet()) {
            SystemStreamPartition ssp = entry.getKey();
            output.computeIfAbsent(ssp, k -> new LinkedList<IncomingMessageEnvelope>());
            List<IncomingMessageEnvelope> currentBuffer = entry.getValue();
            Integer totalMessagesToFetch = Integer.valueOf(metadata.get(outputDescriptor.getStreamId())
                    .getSystemStreamPartitionMetadata().get(ssp.getPartition()).getNewestOffset());
            if (output.get(ssp).size() + currentBuffer.size() == totalMessagesToFetch) {
                didNotReachEndOfStream.remove(entry.getKey());
                ssps.remove(entry.getKey());
            }
            output.get(ssp).addAll(currentBuffer);
        }
        if (didNotReachEndOfStream.isEmpty()) {
            break;
        }
    }

    if (!didNotReachEndOfStream.isEmpty()) {
        throw new IllegalStateException("Could not poll for all system stream partitions");
    }

    return output.entrySet().stream().collect(
            Collectors.toMap(entry -> entry.getKey().getPartition().getPartitionId(), entry -> entry.getValue()
                    .stream().map(e -> (StreamMessageType) e.getMessage()).collect(Collectors.toList())));
}

From source file:com.predic8.membrane.core.cloud.etcd.EtcdBasedConfigurator.java

private void cleanUpNotRunningNodes(HashSet<EtcdNodeInformation> newRunningNodes) {
    HashSet<EtcdNodeInformation> currentlyRunningNodes = new HashSet<EtcdNodeInformation>();
    for (String module : runningNodesForModule.keySet()) {
        currentlyRunningNodes.addAll(runningNodesForModule.get(module));
    }//from   w  w  w .  j  a  v  a 2 s .c  o  m
    for (EtcdNodeInformation node : newRunningNodes) {
        currentlyRunningNodes.remove(node);
    }
    for (EtcdNodeInformation node : currentlyRunningNodes) {
        shutdownRunningClusterNode(node);
    }

    HashSet<String> modules = new HashSet<String>();
    for (String module : runningNodesForModule.keySet()) {
        modules.add(module);
    }
    for (String module : modules) {
        if (runningNodesForModule.get(module).size() == 0) {
            runningNodesForModule.remove(module);
            shutDownRunningModuleServiceProxy(module);
        }
    }
}

From source file:org.fusesource.mop.support.Database.java

public TreeSet<String> uninstall(final String mainArtifact) throws IOException {
    assertOpen();// w  w  w  . ja v a  2  s . co m
    return pageFile.tx().execute(new Transaction.CallableClosure<TreeSet<String>, IOException>() {
        public TreeSet<String> execute(Transaction tx) throws IOException {
            RootEntity root = RootEntity.load(tx);
            BTreeIndex<String, HashSet<String>> artifacts = root.artifacts.get(tx);
            BTreeIndex<String, HashSet<String>> artifactIdIndex = root.artifactIdIndex.get(tx);
            BTreeIndex<String, HashSet<String>> typeIndex = root.typeIndex.get(tx);
            BTreeIndex<String, HashSet<String>> explicityInstalledArtifacts = root.explicityInstalledArtifacts
                    .get(tx);

            TreeSet<String> unused = new TreeSet<String>();
            HashSet<String> artifiactIds = explicityInstalledArtifacts.remove(tx, mainArtifact);
            for (String id : artifiactIds) {
                ArtifactId a = ArtifactId.strictParse(id);
                if (id == null) {
                    throw new IOException("Invalid artifact id: " + id);
                }
                HashSet<String> rc = artifacts.get(tx, id);
                rc.remove(mainArtifact);
                if (rc.isEmpty()) {
                    unused.add(id);
                    artifacts.remove(tx, id);
                    indexRemove(tx, artifactIdIndex, id, a.getArtifactId());
                    indexRemove(tx, typeIndex, id, a.getType());
                } else {
                    artifacts.put(tx, id, rc);
                }
            }

            root.tx_sequence++;
            root.store(tx);
            return unused;
        }
    });
}

From source file:abs.backend.erlang.ClassGenerator.java

private void generateExports() {
    ecs.println("-export([get_val_internal/2,set_val_internal/3,init_internal/0,get_all_state/1]).");
    ecs.println("-compile(export_all).");
    ecs.println();//from   ww  w .jav  a 2  s .  c om

    HashSet<MethodSig> callable_sigs = new HashSet<MethodSig>();
    HashSet<InterfaceDecl> visited = new HashSet<InterfaceDecl>();
    for (InterfaceTypeUse i : classDecl.getImplementedInterfaceUseList()) {
        visited.add((InterfaceDecl) i.getDecl());
    }

    while (!visited.isEmpty()) {
        InterfaceDecl id = visited.iterator().next();
        visited.remove(id);
        for (MethodSig ms : id.getBodyList()) {
            if (ms.isHTTPCallable()) {
                callable_sigs.add(ms);
            }
        }
        for (InterfaceTypeUse i : id.getExtendedInterfaceUseList()) {
            visited.add((InterfaceDecl) i.getDecl());
        }
    }

    ecs.print("exported() -> #{ ");
    boolean first = true;
    for (MethodSig ms : callable_sigs) {
        if (ms.isHTTPCallable()) {
            if (!first)
                ecs.print(", ");
            first = false;
            ecs.print("<<\"" + ms.getName() + "\">> => { ");
            ecs.print("'m_" + ms.getName() + "'");
            ecs.print(", ");
            ecs.print("<<\"" + ms.getReturnType().getType().getQualifiedName() + "\">>");
            ecs.print(", ");
            ecs.print("[ ");
            boolean innerfirst = true;
            for (ParamDecl p : ms.getParamList()) {
                if (!innerfirst)
                    ecs.print(", ");
                innerfirst = false;
                ecs.print("{ ");
                ecs.print("<<\"" + p.getName() + "\">>");
                ecs.print(", ");
                ecs.print("<<\"" + p.getAccess().getType().getQualifiedName() + "\">>");
                ecs.print(" }");
            }
            ecs.print("] ");
            ecs.print("}");
        }
    }
    ecs.println(" }.");
    ecs.println();
}

From source file:org.structnetalign.merge.DistanceClusterer.java

/**
 *
 * @param graph//from  w ww .  j  av a 2  s  .c  o m
 * @param roots
 * @return For each root, the set of other roots that are easily reachable, including the parent root
 */
public final Map<V, Set<V>> transform(Graph<V, E> graph, Collection<V> roots) {

    Map<V, Set<V>> reachableMap = new HashMap<V, Set<V>>();

    for (V root : roots) {

        Set<V> reachable = new HashSet<>();
        HashSet<V> unvisited = new HashSet<V>(graph.getVertices());

        // a map from every vertex to the edge used to get to it
        // works because only visit a vertex once
        HashMap<V, E> edgesTaken = new HashMap<V, E>();

        Deque<V> queue = new LinkedList<V>();
        queue.add(root);
        reachable.add(root);

        while (!queue.isEmpty()) {

            V vertex = queue.remove();
            E edge = edgesTaken.get(vertex);
            unvisited.remove(vertex);

            // stop traversing if we're too far
            if (!isWithinRange(root, vertex))
                continue;

            reachable.add(vertex); // not that this is AFTER the within-range check

            if (edge != null)
                visit(vertex, edge); // this is the ONLY place where we "officially" VISIT a vertex

            Collection<V> neighbors = graph.getNeighbors(vertex);
            for (V neighbor : neighbors) {
                if (unvisited.contains(neighbor)) {
                    queue.add(neighbor);
                    E edgeToNeighbor = graph.findEdge(vertex, neighbor);
                    edgesTaken.put(neighbor, edgeToNeighbor);
                }
            }

            unvisit(vertex, edge); // this is the ONLY place where we "officially" UNVISIT a vertex

        }

        reachableMap.put(root, reachable);

    }

    return reachableMap;
}

From source file:thingynet.hierarchy.HierarchyTest.java

@Test
public void getDescendantsShouldReturnExpectedHierarchies() {
    Hierarchy parent = hierarchyService.createRoot(PARENT, null);
    Hierarchy child = hierarchyService.createChild(parent, CHILD, null);
    Hierarchy sibling = hierarchyService.createChild(parent, SIBLING, null);
    Hierarchy grandChild = hierarchyService.createChild(child, GRAND_CHILD, null);
    Hierarchy greatGrandChild = hierarchyService.createChild(grandChild, GREAT_GRAND_CHILD, null);

    Hierarchy other = hierarchyService.createRoot(OTHER, null);
    hierarchyService.createChild(other, CHILD, null);

    HashSet<String> expectedIds = new HashSet<>();
    expectedIds.add(child.getPath());/*from   w w w .j  a v a2  s  . co  m*/
    expectedIds.add(sibling.getPath());
    expectedIds.add(grandChild.getPath());
    expectedIds.add(greatGrandChild.getPath());

    Iterable<Hierarchy> actual = hierarchyService.getDescendants(parent);
    while (actual.iterator().hasNext()) {
        Hierarchy descendant = actual.iterator().next();
        assertThat(expectedIds.remove(descendant.getPath()), is(true));
    }
    assertThat(expectedIds.size(), is(0));
}

From source file:org.zaproxy.zap.extension.multiFuzz.CharTypes.java

public NFA(ParseTree t) {
    NFA f;/*from   ww w . j  ava 2  s  .c  o  m*/
    NFA s;
    State b;
    State e;
    switch (t.getLabel()) {
    case 0: // START
        b = new State();
        states = new ArrayList<>();
        states.add(b);
        end = 0;
        break;
    case 1: // UNION
        f = new NFA(t.getChildren().get(0));
        s = new NFA(t.getChildren().get(1));
        b = new State();
        e = new State();
        b.empty.add(f.states.get(0));
        b.empty.add(s.states.get(0));
        f.states.get(f.end).empty.add(e);
        s.states.get(s.end).empty.add(e);
        states.add(b);
        states.addAll(f.states);
        states.addAll(s.states);
        states.add(e);
        this.end = states.size() - 1;
        break;
    case 2: // CONCAT
        f = new NFA(t.getChildren().get(0));
        s = new NFA(t.getChildren().get(1));
        states.addAll(f.states);
        State rem = s.states.get(0);
        State rep = states.get(f.end);
        rep.out.putAll(rem.out);
        rep.empty.addAll(rem.empty);

        for (State p : s.states) {
            if (p.empty.contains(rem)) {
                p.empty.remove(rem);
                p.empty.add(rep);
            }
            for (HashSet<State> target : p.out.values()) {
                if (target.contains(rem)) {
                    target.remove(rem);
                    target.add(rep);
                }
            }
        }
        s.states.remove(rem);
        states.addAll(s.states);
        end = states.size() - 1;
        break;
    case 3: // QUEST
        f = new NFA(t.getChildren().get(0));
        states.addAll(f.states);
        end = states.size() - 1;
        states.get(0).addTransition(states.get(end), null);
        break;
    case 4: // STAR
        f = new NFA(t.getChildren().get(0));
        states.addAll(f.states);
        end = states.size() - 1;
        states.get(end).addTransition(states.get(0), null);
        states.get(0).addTransition(states.get(end), null);
        break;
    case 5: // PLUS
        f = new NFA(t.getChildren().get(0));
        s = new NFA(t.getChildren().get(0));
        states.addAll(f.states);
        states.get(f.end).out.putAll(s.states.get(0).out);
        states.get(f.end).empty.addAll(s.states.get(0).empty);
        s.states.remove(0);
        states.addAll(s.states);
        end = states.size() - 1;
        states.get(f.end).addTransition(states.get(end), null);
        states.get(end).addTransition(states.get(f.end), null);
        break;
    case 6: // CHARCLASS
        b = new State();
        e = new State();
        for (Character c : t.getValue()) {
            b.addTransition(e, c);
        }
        states = new ArrayList<>();
        states.add(b);
        states.add(e);
        end = 1;
        break;
    case 7: // LIT
        b = new State();
        e = new State();
        b.addTransition(e, t.getValue().get(0));
        states = new ArrayList<>();
        states.add(b);
        states.add(e);
        end = 1;
        break;
    }
}

From source file:org.abs_models.backend.erlang.ClassGenerator.java

private void generateExports() {
    ecs.println(// ww w.  j  a  v a 2s . com
            "-export([get_val_internal/2,set_val_internal/3,init_internal/0,get_state_for_modelapi/1,implemented_interfaces/0,exported/0]).");
    ecs.println("-compile(export_all).");
    ecs.println();

    HashSet<MethodSig> callable_sigs = new HashSet<>();
    HashSet<InterfaceDecl> visited = new HashSet<>();
    for (InterfaceTypeUse i : classDecl.getImplementedInterfaceUseList()) {
        visited.add((InterfaceDecl) i.getDecl());
    }

    while (!visited.isEmpty()) {
        InterfaceDecl id = visited.iterator().next();
        visited.remove(id);
        for (MethodSig ms : id.getBodyList()) {
            if (ms.isHTTPCallable()) {
                callable_sigs.add(ms);
            }
        }
        for (InterfaceTypeUse i : id.getExtendedInterfaceUseList()) {
            visited.add((InterfaceDecl) i.getDecl());
        }
    }

    ecs.print("implemented_interfaces() -> [ ");
    String separator = "";
    for (InterfaceDecl i : classDecl.getSuperTypes()) {
        ecs.format("%s<<\"%s\">>", separator, i.getName());
        separator = ", ";
    }
    ecs.println(" ].");
    ecs.println();

    ecs.print("exported() -> #{ ");
    boolean first = true;
    for (MethodSig ms : callable_sigs) {
        if (ms.isHTTPCallable()) {
            if (!first)
                ecs.print(", ");
            first = false;
            ecs.print("<<\"" + ms.getName() + "\">> => { ");
            ecs.print("'m_" + ms.getName() + "'");
            ecs.print(", ");
            ecs.print("<<\"" + ms.getReturnType().getType().toString() + "\">>");
            ecs.print(", ");
            ecs.print("[ ");
            boolean innerfirst = true;
            for (ParamDecl p : ms.getParamList()) {
                // For each parameter, we need name, human-readable type,
                // ABS type, and ABS type arguments (if present)
                if (!innerfirst)
                    ecs.print(", ");
                innerfirst = false;
                ecs.print("{ ");
                ecs.print("<<\"" + p.getName() + "\">>, ");
                ecs.print("<<\"" + p.getType().toString() + "\">>, ");
                generateParameterDescription(p.getType());
                ecs.print(" }");
            }
            ecs.print("] ");
            ecs.print("}");
        }
    }
    ecs.println(" }.");
    ecs.println();
}

From source file:com.hadoopvietnam.cache.memcached.MemcachedCache.java

/**
 * {@inheritDoc}/*  ww w.  ja v a  2s .c o m*/
 */
public void removeFromSet(final String inKey, final Long inValue) {
    if (log.isTraceEnabled()) {
        log.trace("Removing from set '" + inKey + "', value: " + inValue);
    }
    CASMutation<Object> mutation = new CASMutation<Object>() {
        // This is only invoked when a set already exists.
        @SuppressWarnings("unchecked")
        public Object getNewValue(final Object current) {
            Set<Long> set = (Set<Long>) current;
            HashSet<Long> hashSet = new HashSet<Long>(set);
            hashSet.remove(inValue);
            return hashSet;
        }
    };

    SerializingTranscoder transcoder = new SerializingTranscoder();
    CASMutator<Object> mutator = new CASMutator<Object>(client, transcoder);

    // This returns whatever value was successfully stored within the cache,
    // either the
    // initial set or a mutated existing one
    try {
        mutator.cas(inKey, new HashSet<Long>(), MAX_EXPIRATION_TIME, mutation);
    } catch (Exception e) {
        log.error("Nothing to delete from memcached for key - " + inKey, e);
    }
}