Example usage for java.util Queue isEmpty

List of usage examples for java.util Queue isEmpty

Introduction

In this page you can find the example usage for java.util Queue isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this collection contains no elements.

Usage

From source file:bwem.Graph.java

private int[] computeDistances(final ChokePoint start, final List<ChokePoint> targets) {
    final int[] distances = new int[targets.size()];

    TileImpl.getStaticMarkable().unmarkAll();

    final Queue<Pair<Integer, ChokePoint>> toVisit = new PriorityQueue<>(Comparator.comparingInt(a -> a.first));
    toVisit.offer(new Pair<>(0, start));

    int remainingTargets = targets.size();
    while (!toVisit.isEmpty()) {
        final Pair<Integer, ChokePoint> distanceAndChokePoint = toVisit.poll();
        final int currentDist = distanceAndChokePoint.first;
        final ChokePoint current = distanceAndChokePoint.second;
        final Tile currentTile = getMap().getData().getTile(current.getCenter().toTilePosition(),
                CheckMode.NO_CHECK);/*  w w w .  j  a v  a2 s .c o  m*/
        //            bwem_assert(currentTile.InternalData() == currentDist);
        if (!(((TileImpl) currentTile).getInternalData() == currentDist)) {
            throw new IllegalStateException();
        }
        ((TileImpl) currentTile).setInternalData(0); // resets Tile::m_internalData for future usage
        ((TileImpl) currentTile).getMarkable().setMarked();

        for (int i = 0; i < targets.size(); ++i) {
            if (current == targets.get(i)) {
                distances[i] = currentDist;
                --remainingTargets;
            }
        }
        if (remainingTargets == 0) {
            break;
        }

        if (current.isBlocked() && (!current.equals(start))) {
            continue;
        }

        for (final Area pArea : new Area[] { current.getAreas().getFirst(), current.getAreas().getSecond() }) {
            for (final ChokePoint next : pArea.getChokePoints()) {
                if (!next.equals(current)) {
                    final int newNextDist = currentDist + distance(current, next);
                    final Tile nextTile = getMap().getData().getTile(next.getCenter().toTilePosition(),
                            CheckMode.NO_CHECK);
                    if (!((TileImpl) nextTile).getMarkable().isMarked()) {
                        if (((TileImpl) nextTile).getInternalData() != 0) { // next already in toVisit
                            if (newNextDist < ((TileImpl) nextTile).getInternalData()) { // nextNewDist < nextOldDist
                                                                                         // To update next's distance, we need to remove-insert it from toVisit:
                                                                                         //                                    bwem_assert(iNext != range.second);
                                final boolean removed = toVisit
                                        .remove(new Pair<>(((TileImpl) nextTile).getInternalData(), next));
                                if (!removed) {
                                    throw new IllegalStateException();
                                }
                                ((TileImpl) nextTile).setInternalData(newNextDist);
                                ((ChokePointImpl) next).setPathBackTrace(current);
                                toVisit.offer(new Pair<>(newNextDist, next));
                            }
                        } else {
                            ((TileImpl) nextTile).setInternalData(newNextDist);
                            ((ChokePointImpl) next).setPathBackTrace(current);
                            toVisit.offer(new Pair<>(newNextDist, next));
                        }
                    }
                }
            }
        }
    }

    //    //   bwem_assert(!remainingTargets);
    //        if (!(remainingTargets == 0)) {
    //            throw new IllegalStateException();
    //        }

    // reset Tile::m_internalData for future usage
    for (Pair<Integer, ChokePoint> distanceToChokePoint : toVisit) {
        ((TileImpl) getMap().getData().getTile(distanceToChokePoint.second.getCenter().toTilePosition(),
                CheckMode.NO_CHECK)).setInternalData(0);
    }

    return distances;
}

From source file:org.shaman.terrain.polygonal.GraphToHeightmap.java

private void calculateBaseElevation() {
    //assign elevation to oceans
    for (Graph.Corner c : graph.corners) {
        if (c.ocean) {
            c.elevation = -1;//  w w  w.j  a  v a 2s. c  o m
        }
    }
    Queue<Graph.Corner> q = new ArrayDeque<>();
    for (Graph.Corner c : graph.corners) {
        if (c.coast) {
            q.add(c);
        }
    }
    while (!q.isEmpty()) {
        Graph.Corner c = q.poll();
        for (Graph.Corner r : c.adjacent) {
            float h = Math.max(-1, c.elevation - 0.2f);
            if (r.ocean && r.elevation < h) {
                r.elevation = h;
                q.add(r);
            }
        }
    }
    assignCenterElevations();
    //render
    Geometry geom = createElevationGeometry();
    Heightmap tmp = new Heightmap(size);
    render(tmp.getRawData(), geom, ColorRGBA.Black, -1, 1);
    //scale
    for (int x = 0; x < size; ++x) {
        for (int y = 0; y < size; ++y) {
            float h = tmp.getHeightAt(x, y);
            h = (float) (Math.signum(h) * Math.pow(Math.abs(h), HEIGHT_SCALING));
            tmp.setHeightAt(x, y, h);
        }
    }
    //distort
    Noise distortionNoise = new Noise(rand.nextLong());
    for (int x = 0; x < size; ++x) {
        for (int y = 0; y < size; ++y) {
            float s = x / (float) size;
            float t = y / (float) size;
            float ss = (float) (s + DISTORTION_AMPLITUDE * 2
                    * distortionNoise.noise(s * DISTORTION_FREQUENCY, t * DISTORTION_FREQUENCY, 0));
            float tt = (float) (t + DISTORTION_AMPLITUDE * 2
                    * distortionNoise.noise(s * DISTORTION_FREQUENCY, t * DISTORTION_FREQUENCY, 3.4));
            float v = tmp.getHeightInterpolating(ss * size, tt * size);
            heightmap.setHeightAt(x, y, v);
        }
    }
    //smooth
    for (int i = 0; i < SMOOTHING_STEPS; ++i) {
        smooth(heightmap);
    }
    //reset height
    for (Graph.Corner c : graph.corners) {
        if (c.ocean) {
            c.elevation = 0;
        }
    }
    assignCenterElevations();
    LOG.info("base elevation assigned");
}

From source file:org.squashtest.tm.service.internal.testcase.CustomTestCaseModificationServiceImpl.java

@Override
// TODO : secure this
public TestCase addNewTestCaseVersion(long originalTcId, TestCase newVersionData) {

    List<Long> milestoneIds = new ArrayList<>();

    Optional<Milestone> activeMilestone = activeMilestoneHolder.getActiveMilestone();
    if (activeMilestone.isPresent()) {
        milestoneIds.add(activeMilestone.get().getId());
    }//from  w  ww. j av  a 2s  .c  o  m

    // copy the core attributes
    TestCase orig = testCaseDao.findById(originalTcId);
    TestCase newTC = orig.createCopy();

    newTC.setName(newVersionData.getName());
    newTC.setReference(newVersionData.getReference());
    newTC.setDescription(newVersionData.getDescription());
    newTC.clearMilestones();

    // now we must inster that at the correct location
    TestCaseLibrary library = libraryService.findLibraryOfRootNodeIfExist(orig);
    if (library != null) {
        libraryService.addTestCaseToLibrary(library.getId(), newTC, null);
    } else {
        TestCaseFolder folder = libraryService.findParentIfExists(orig);
        libraryService.addTestCaseToFolder(folder.getId(), newTC, null);
    }

    // copy custom fields
    customFieldValuesService.copyCustomFieldValuesContent(orig, newTC);
    Queue<ActionTestStep> origSteps = new LinkedList<>(orig.getActionSteps());
    Queue<ActionTestStep> newSteps = new LinkedList<>(newTC.getActionSteps());
    while (!origSteps.isEmpty()) {
        ActionTestStep oStep = origSteps.remove();
        ActionTestStep nStep = newSteps.remove();
        customFieldValuesService.copyCustomFieldValuesContent(oStep, nStep);
    }

    // manage the milestones
    milestoneService.bindTestCaseToMilestones(newTC.getId(), milestoneIds);
    milestoneService.unbindTestCaseFromMilestones(originalTcId, milestoneIds);

    return newTC;
}

From source file:com.baifendian.swordfish.common.utils.graph.Graph.java

/**
 * ??, ???, // w  ww .j  a v a  2s  . com
 *
 * @return
 * @throws Exception
 */
public List<VK> broadFirstSearch() throws Exception {
    List<VK> visit = new ArrayList<>();
    Queue<VK> q = new LinkedList<>();
    Set<VK> hasVisited = new HashSet<>();

    synchronized (this) {
        // 
        for (VK key : getStartVertex()) {
            q.add(key);
            hasVisited.add(key);
            visit.add(key);
        }

        while (!q.isEmpty()) {
            VK key = q.poll();

            // ?
            for (VK postKey : getPostNode(key)) {
                if (!hasVisited.contains(postKey)) {
                    q.add(postKey);
                    hasVisited.add(postKey);
                    visit.add(postKey);
                }
            }
        }

        // ??
        if (visit.size() != getVertexNumber()) {
            throw new Exception("Broad first search can't search complete.");
        }
    }

    return visit;
}

From source file:it.geosolutions.geobatch.unredd.script.reprocess.ReprocessAction.java

/**
 * Main loop on input files. Single file processing is called on execute(File xmlFile)
 *///from w  w w  . j ava 2  s  .  c om
public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException {

    if (getTempDir() == null) {
        throw new IllegalStateException("temp dir has not been initialized");
    }
    if (!getTempDir().exists()) {
        throw new IllegalStateException("temp dir does not exist");
    }

    geoStoreUtil = new GeoStoreUtil(conf.getGeoStoreConfig(), getTempDir());

    //        initComponents(properties);

    final Queue<FileSystemEvent> ret = new LinkedList<FileSystemEvent>();

    while (!events.isEmpty()) {
        final FileSystemEvent ev = events.remove();

        try {
            if (ev != null) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Processing incoming event: " + ev.getSource());
                }
                File xmlFile = ev.getSource(); // this is the input xml file

                /**
                 * *************************
                 * The reprocessing flow will recompute statistics and charts. it is needed when data in the staging area are
                 * changed; i.e.: - vector data are edited; - chart scripts are modified or inserted; - new statistics are
                 * added. Each doXXX methos manages one of this case
                 */
                ReprocessRequest request = RequestReader.load(xmlFile);
                if (request == null) {
                    throw new ActionException(this, "Could not parse input file:" + xmlFile.getName());
                }

                if (request instanceof ReprocessLayerRequest) {
                    reprocessLayer((ReprocessLayerRequest) request);

                } else if (request instanceof ReprocessChartRequest) {
                    reprocessChart((ReprocessChartRequest) request);

                } else if (request instanceof ReprocessStatsRequest) {
                    reprocessStats((ReprocessStatsRequest) request);

                }

                ret.add(new FileSystemEvent(xmlFile, FileSystemEventType.FILE_ADDED));

            } else {
                LOGGER.error("Encountered a null event: skipping event");
                continue;
            }

        } catch (ActionException ex) {
            LOGGER.error(ex.getMessage());
            listenerForwarder.failed(ex);
            throw ex;

        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            listenerForwarder.failed(ex);
            throw new ActionException(this, ex.getMessage(), ex);
        }
    }

    return ret;
}

From source file:com.thoughtworks.go.server.service.dd.DependencyFanInNode.java

private Pair<StageIdentifier, List<FaninScmMaterial>> getRevisionNthFor(int n, FanInGraphContext context) {
    List<FaninScmMaterial> scmMaterials = new ArrayList<>();
    PipelineTimeline pipelineTimeline = context.pipelineTimeline;
    Queue<PipelineTimelineEntry.Revision> revisionQueue = new ConcurrentLinkedQueue<>();
    DependencyMaterialConfig dependencyMaterial = (DependencyMaterialConfig) materialConfig;
    PipelineTimelineEntry entry = pipelineTimeline.instanceFor(dependencyMaterial.getPipelineName(),
            totalInstanceCount - n);/*from   w ww .j av a 2 s. com*/

    Set<CaseInsensitiveString> visitedNodes = new HashSet<>();

    StageIdentifier dependentStageIdentifier = dependentStageIdentifier(context, entry,
            CaseInsensitiveString.str(dependencyMaterial.getStageName()));
    if (!StageIdentifier.NULL.equals(dependentStageIdentifier)) {
        addToRevisionQueue(entry, revisionQueue, scmMaterials, context, visitedNodes);
    } else {
        return null;
    }
    while (!revisionQueue.isEmpty()) {
        PipelineTimelineEntry.Revision revision = revisionQueue.poll();
        DependencyMaterialRevision dmr = DependencyMaterialRevision.create(revision.revision, null);
        PipelineTimelineEntry pte = pipelineTimeline
                .getEntryFor(new CaseInsensitiveString(dmr.getPipelineName()), dmr.getPipelineCounter());
        addToRevisionQueue(pte, revisionQueue, scmMaterials, context, visitedNodes);
    }

    return new Pair<>(dependentStageIdentifier, scmMaterials);
}

From source file:org.exoplatform.services.cms.webdav.WebDavServiceImpl.java

@DELETE
@Path("/{repoName}/{repoPath:.*}/")
public Response delete(@PathParam("repoName") String repoName, @PathParam("repoPath") String repoPath,
        @HeaderParam(ExtHttpHeaders.LOCKTOKEN) String lockTokenHeader,
        @HeaderParam(ExtHttpHeaders.IF) String ifHeader) {
    Item item = null;//from  w w w.  j a v a2 s . c  o m
    try {
        repoName = repositoryService.getCurrentRepository().getConfiguration().getName();
        repoPath = convertRepoPath(repoPath, false);

        try {
            item = nodeFinder.getItem(workspaceName(repoPath), path(normalizePath(repoPath)), true);
        } catch (PathNotFoundException e) {
            item = nodeFinder.getItem(workspaceName(repoPath), path(Text.escapeIllegalJcrChars(repoPath)),
                    true);
        }

    } catch (PathNotFoundException exc) {
        return Response.status(HTTPStatus.NOT_FOUND).entity(exc.getMessage()).build();
    } catch (NoSuchWorkspaceException exc) {
        return Response.status(HTTPStatus.NOT_FOUND).entity(exc.getMessage()).build();
    } catch (Exception e) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("Cannot find the item at " + repoName + "/" + repoPath, e);
        }
        return Response.serverError().build();
    }

    try {
        //Broadcast the event when user move node to Trash
        Node node = (Node) item;
        ListenerService listenerService = WCMCoreUtils.getService(ListenerService.class);
        ActivityCommonService activityService = WCMCoreUtils.getService(ActivityCommonService.class);
        Node parent = node.getParent();
        if (node.getPrimaryNodeType().getName().equals(NodetypeConstant.NT_FILE)) {
            if (activityService.isBroadcastNTFileEvents(node)) {
                listenerService.broadcast(ActivityCommonService.FILE_REMOVE_ACTIVITY, parent, node);
            }
        } else if (!WCMCoreUtils.isDocumentNodeType(node)) {
            Queue<Node> queue = new LinkedList<Node>();
            queue.add(node);

            //Broadcast event to remove file activities
            Node tempNode = null;
            try {
                while (!queue.isEmpty()) {
                    tempNode = queue.poll();
                    if (WCMCoreUtils.isDocumentNodeType(tempNode)
                            || tempNode.getPrimaryNodeType().getName().equals(NodetypeConstant.NT_FILE)) {
                        listenerService.broadcast(ActivityCommonService.FILE_REMOVE_ACTIVITY,
                                tempNode.getParent(), tempNode);
                    } else {
                        for (NodeIterator iter = tempNode.getNodes(); iter.hasNext();) {
                            Node childNode = iter.nextNode();
                            if (WCMCoreUtils.isDocumentNodeType(childNode)
                                    || childNode.isNodeType(NodetypeConstant.NT_UNSTRUCTURED)
                                    || childNode.isNodeType(NodetypeConstant.NT_FOLDER))
                                queue.add(childNode);
                        }
                    }
                }
            } catch (Exception e) {
                if (LOG.isWarnEnabled()) {
                    LOG.warn(e.getMessage());
                }
            }
        }
        //Remove the symlinks of deleted node. 
        Utils.removeSymlinks(node);
    } catch (Exception ex) {
        if (LOG.isWarnEnabled()) {
            LOG.warn(ex.getMessage());
        }
    }
    return super.delete(repoName, repoPath, lockTokenHeader, ifHeader);
}

From source file:edu.snu.leader.hidden.SimulationState.java

/**
 * Signals that the specified individual has canceled a group movement
 *
 * @param individual//from w w w . ja  va2  s . c o m
 */
public void cancelInitiation(SpatialIndividual individual) {
    if (_LOG.isDebugEnabled()) {
        _LOG.debug("Before cancel [" + individual.getID() + "]: eligibleInitiators=["
                + _eligibleInitiators.size() + "] remaining=[" + _remaining.size() + "] totalFollowers=["
                + individual.getTotalFollowerCount() + "]");
    }

    // Send it a signal so it can log some information
    individual.signalInitiationFailure(this);

    // We need to maintain a list of all the affected individuals
    List<SpatialIndividual> affected = new LinkedList<SpatialIndividual>();

    // Build the list starting with the initiator itself
    Queue<SpatialIndividual> indsToProcess = new LinkedList<SpatialIndividual>();
    indsToProcess.add(individual);
    while (!indsToProcess.isEmpty()) {
        // Get the first in the queue
        SpatialIndividual current = indsToProcess.remove();

        //            _LOG.debug( "Processing ["
        //                    + current.getID()
        //                    + "]" );

        // Add it to the list
        affected.add(current);

        // Add it's immediate followers to the queue for processing
        Iterator<Neighbor> followerIter = current.getFollowers().iterator();
        while (followerIter.hasNext()) {
            indsToProcess.add(followerIter.next().getIndividual());
        }
    }

    /* Iterate through all the affected individuals to change them from
     * departed to remaining and tell them to cancel */
    Iterator<SpatialIndividual> affectedIter = affected.iterator();
    while (affectedIter.hasNext()) {
        SpatialIndividual current = affectedIter.next();

        //            _LOG.debug( "Processing affected ["
        //                    + current.getID()
        //                    + "]" );

        // Remove the individual from the departed group
        _departed.remove(current.getID());

        // Add it to the remaining group
        _remaining.put(current.getID(), current);

        // Tell it to cancel
        current.cancel();

    }

    /* Iterate through the list again to see if they are eligible
     * initiators.  We couldn't do it during the last pass through since
     * we hadn't cleaned up all the groups yet. */
    //        affectedIter = affected.iterator();
    affectedIter = _remaining.values().iterator();
    while (affectedIter.hasNext()) {
        SpatialIndividual current = affectedIter.next();

        // Are any of the individual's neighbors initiators or followers?
        boolean eligible = true;
        Iterator<Neighbor> neighborIter = current.getNearestNeighbors().iterator();
        while (eligible && neighborIter.hasNext()) {
            // Can tell by looking at the group ID
            Neighbor neighbor = neighborIter.next();
            if (null != neighbor.getIndividual().getGroupID()) {
                /* The neighbor belongs to a group, the individual is NOT
                 * eligible. */
                eligible = false;
            }
        }

        // Is the individual eligible?
        if (eligible) {
            // Yup
            _eligibleInitiators.put(current.getID(), current);
        } else {
            // Nope, tell them who their first mover was
            // Iterate through the list of departed individuals and
            // find the first nearest neighbor
            Iterator<SpatialIndividual> departedIter = _departed.values().iterator();
            while (departedIter.hasNext()) {
                SpatialIndividual departedInd = departedIter.next();
                if (current.isNearestNeighbor(departedInd)) {
                    current.observeFirstMover(departedInd);
                    break;
                }
            }
        }

        /* Check all the individuals not yet departed to see if they
         * observed this individual as a first mover.  If so, reset their
         * first mover if no other neighbors have departed or if another
         * has departed, set it to that neighbor */
        Iterator<SpatialIndividual> remainingIter = _remaining.values().iterator();
        while (remainingIter.hasNext()) {
            SpatialIndividual currentRemaining = remainingIter.next();
            Neighbor firstMover = currentRemaining.getFirstMover();
            if ((null != firstMover) && (firstMover.getIndividual().getID().equals(current.getID()))) {
                // Reset the first mover
                currentRemaining.resetFirstMover();

                // See if they now have another first mover
                Iterator<SpatialIndividual> departedIter = _departed.values().iterator();
                while (departedIter.hasNext()) {
                    SpatialIndividual departedInd = departedIter.next();
                    if (currentRemaining.isNearestNeighbor(departedInd)) {
                        currentRemaining.observeFirstMover(departedInd);
                        break;
                    }
                }
            }
        }
    }

    _LOG.debug("After cancel: eligibleInitiators=[" + _eligibleInitiators.size() + "] remaining=["
            + _remaining.size() + "]");
}

From source file:edu.uci.ics.jung.algorithms.scoring.BetweennessCentrality.java

protected void computeBetweenness(Queue<V> queue, Transformer<E, ? extends Number> edge_weights) {
    for (V v : graph.getVertices()) {
        // initialize the betweenness data for this new vertex
        for (V s : graph.getVertices())
            this.vertex_data.put(s, new BetweennessData());

        //         if (v.equals(new Integer(0)))
        //            System.out.println("pause");

        vertex_data.get(v).numSPs = 1;//from   w ww. j  a v  a2s. c om
        vertex_data.get(v).distance = 0;

        Stack<V> stack = new Stack<V>();
        //            Buffer<V> queue = new UnboundedFifoBuffer<V>();
        //            queue.add(v);
        queue.offer(v);

        while (!queue.isEmpty()) {
            //                V w = queue.remove();
            V w = queue.poll();
            stack.push(w);
            BetweennessData w_data = vertex_data.get(w);

            for (E e : graph.getOutEdges(w)) {
                // TODO (jrtom): change this to getOtherVertices(w, e)
                V x = graph.getOpposite(w, e);
                if (x.equals(w))
                    continue;
                double wx_weight = edge_weights.transform(e).doubleValue();

                //                for(V x : graph.getSuccessors(w)) 
                //                {
                //                   if (x.equals(w))
                //                      continue;

                // FIXME: the other problem is that I need to 
                // keep putting the neighbors of things we've just 
                // discovered in the queue, if they're undiscovered or
                // at greater distance.

                // FIXME: this is the problem, right here, I think: 
                // need to update position in queue if distance changes
                // (which can only happen with weighted edges).
                // for each outgoing edge e from w, get other end x
                // if x not already visited (dist x < 0)
                //   set x's distance to w's dist + edge weight
                //   add x to queue; pri in queue is x's dist
                // if w's dist + edge weight < x's dist 
                //   update x's dist
                //   update x in queue (MapBinaryHeap)
                //   clear x's incoming edge list
                // if w's dist + edge weight = x's dist
                //   add e to x's incoming edge list

                BetweennessData x_data = vertex_data.get(x);
                double x_potential_dist = w_data.distance + wx_weight;

                if (x_data.distance < 0) {
                    //                        queue.add(x);
                    //                        vertex_data.get(x).distance = vertex_data.get(w).distance + 1;
                    x_data.distance = x_potential_dist;
                    queue.offer(x);
                }

                // note:
                // (1) this can only happen with weighted edges
                // (2) x's SP count and incoming edges are updated below 
                if (x_data.distance > x_potential_dist) {
                    x_data.distance = x_potential_dist;
                    // invalidate previously identified incoming edges
                    // (we have a new shortest path distance to x)
                    x_data.incomingEdges.clear();
                    // update x's position in queue
                    ((MapBinaryHeap<V>) queue).update(x);
                }
                //                  if (vertex_data.get(x).distance == vertex_data.get(w).distance + 1) 
                // 
                //                    if (x_data.distance == x_potential_dist) 
                //                    {
                //                        x_data.numSPs += w_data.numSPs;
                ////                        vertex_data.get(x).predecessors.add(w);
                //                        x_data.incomingEdges.add(e);
                //                    }
            }
            for (E e : graph.getOutEdges(w)) {
                V x = graph.getOpposite(w, e);
                if (x.equals(w))
                    continue;
                double e_weight = edge_weights.transform(e).doubleValue();
                BetweennessData x_data = vertex_data.get(x);
                double x_potential_dist = w_data.distance + e_weight;
                if (x_data.distance == x_potential_dist) {
                    x_data.numSPs += w_data.numSPs;
                    //                        vertex_data.get(x).predecessors.add(w);
                    x_data.incomingEdges.add(e);
                }
            }
        }
        while (!stack.isEmpty()) {
            V x = stack.pop();

            //              for (V w : vertex_data.get(x).predecessors) 
            for (E e : vertex_data.get(x).incomingEdges) {
                V w = graph.getOpposite(x, e);
                double partialDependency = vertex_data.get(w).numSPs / vertex_data.get(x).numSPs
                        * (1.0 + vertex_data.get(x).dependency);
                vertex_data.get(w).dependency += partialDependency;
                //                  E w_x = graph.findEdge(w, x);
                //                  double w_x_score = edge_scores.get(w_x).doubleValue();
                //                  w_x_score += partialDependency;
                //                  edge_scores.put(w_x, w_x_score);
                double e_score = edge_scores.get(e).doubleValue();
                edge_scores.put(e, e_score + partialDependency);
            }
            if (!x.equals(v)) {
                double x_score = vertex_scores.get(x).doubleValue();
                x_score += vertex_data.get(x).dependency;
                vertex_scores.put(x, x_score);
            }
        }
    }

    if (graph instanceof UndirectedGraph) {
        for (V v : graph.getVertices()) {
            double v_score = vertex_scores.get(v).doubleValue();
            v_score /= 2.0;
            vertex_scores.put(v, v_score);
        }
        for (E e : graph.getEdges()) {
            double e_score = edge_scores.get(e).doubleValue();
            e_score /= 2.0;
            edge_scores.put(e, e_score);
        }
    }

    vertex_data.clear();
}

From source file:gobblin.ingestion.google.webmaster.GoogleWebmasterDataFetcherImpl.java

/**
 * Get all pages in an async mode./*  w  w w. ja  v  a2s .  c om*/
 */
private Collection<String> getPages(String startDate, String endDate, List<Dimension> dimensions,
        ApiDimensionFilter countryFilter, Queue<Pair<String, FilterOperator>> toProcess) throws IOException {
    String country = GoogleWebmasterFilter.countryFilterToString(countryFilter);

    ConcurrentLinkedDeque<String> allPages = new ConcurrentLinkedDeque<>();
    int r = 0;
    while (r <= RETRY) {
        ++r;
        log.info(String.format("Get pages at round %d with size %d.", r, toProcess.size()));
        ConcurrentLinkedDeque<Pair<String, FilterOperator>> nextRound = new ConcurrentLinkedDeque<>();
        ExecutorService es = Executors.newFixedThreadPool(10, ExecutorsUtils
                .newDaemonThreadFactory(Optional.of(log), Optional.of(this.getClass().getSimpleName())));

        while (!toProcess.isEmpty()) {
            submitJob(toProcess.poll(), countryFilter, startDate, endDate, dimensions, es, allPages, nextRound);
        }
        //wait for jobs to finish and start next round if necessary.
        try {
            es.shutdown();
            boolean terminated = es.awaitTermination(5, TimeUnit.MINUTES);
            if (!terminated) {
                es.shutdownNow();
                log.warn(String.format(
                        "Timed out while getting all pages for country-%s at round %d. Next round now has size %d.",
                        country, r, nextRound.size()));
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        if (nextRound.isEmpty()) {
            break;
        }
        toProcess = nextRound;
    }
    if (r == RETRY) {
        throw new RuntimeException(String.format(
                "Getting all pages reaches the maximum number of retires %d. Date range: %s ~ %s. Country: %s.",
                RETRY, startDate, endDate, country));
    }
    return allPages;
}