/**
   * Initiates the dereferencing process of some of the URIs identified in the dataset, chosen in
   * accordance with a statistical sampling method, in order to compute the estimated
   * dereferenceability of the whole dataset
   *
   * @return estimated dereferencibility, computed as aforementioned
   */
  @Override
  public double metricValue() {

    if (!this.metricCalculated) {
      uriSet.addAll(this.fqurisReservoir.getItems());
      double uriSize = (double) uriSet.size();

      // Process
      this.httpRetreiver.addListOfResourceToQueue(this.fqurisReservoir.getItems());
      this.httpRetreiver.start(true);

      do {
        this.checkForForwardLinking();
        uriSet.clear();
        uriSet.addAll(this.notFetchedQueue);
        this.notFetchedQueue.clear();
      } while (!this.uriSet.isEmpty());

      this.metricCalculated = true;
      httpRetreiver.stop();
      // End Process

      metricValue = (totalDerefDataWithSub == 0.0) ? 0.0 : (double) totalDerefDataWithSub / uriSize;

      statsLogger.info(
          "Estimated Dereferencable Forward Links Metric: Dataset: {} - Total # Forward Links URIs {}; Total URIs : {}",
          EnvironmentProperties.getInstance().getDatasetURI(),
          totalDerefDataWithSub,
          uriSize);
    }

    return this.metricValue;
  }
 private boolean roleSettingOperation(
     TestPlanEntity testPlan, Host tester, List<Engine> idleEngines, List<Engine> engineOnTester) {
   Queue<Engine> engineQ = new ArrayDeque<>();
   engineQ.addAll(engineOnTester);
   boolean finished = setUpRemoteEngines(testPlan, engineQ);
   if (!finished) {
     if (engineQ.isEmpty()) {
       engineQ.addAll(idleEngines);
       finished = setUpRemoteEngines(testPlan, engineQ);
       if (!finished) {
         _logger.error(
             String.format(
                 "Testplan: %d can't init. Too many engine role faults", testPlan.getId()));
         return true;
       }
     } else {
       _logger.error(
           String.format(
               "Testplan: %d can't init. Not enough available engines", testPlan.getId()));
       return true;
     }
   } else {
     if (!engineQ.isEmpty()) {
       List<Engine> enginesToBeKicked = engineQ.stream().collect(Collectors.toList());
       _logger.warn(
           String.format("Host: %d has to many engines, should kickout some.", tester.getId()));
       if (!hostService.kickEnginesToRandomHost(enginesToBeKicked, tester)) {
         _logger.warn(String.format("Host: %d kick out failed. please retry", tester.getId()));
         return true;
       }
     }
   }
   return false;
 }
Esempio n. 3
0
  public static ImmutableSet<TypeDescriptor> reachableFrom(
      ImmutableCollection<DeclaredClass> values,
      Map<ClassTypeDescriptor, DeclaredClass> knownClasses) {
    Queue<DeclaredClass> toCheck = new LinkedList<>(values);

    Set<ClassTypeDescriptor> reachable = Sets.newHashSet();

    while (!toCheck.isEmpty()) {
      DeclaredClass current = toCheck.remove();

      if (!reachable.add(current.className())) {
        continue;
      }

      toCheck.addAll(
          current
              .parents()
              .stream()
              .map(knownClasses::get)
              .filter(declaredClass -> declaredClass != null)
              .collect(toList()));

      toCheck.addAll(
          current
              .loadedClasses()
              .stream()
              .map(knownClasses::get)
              .filter(declaredClass -> declaredClass != null)
              .collect(toList()));

      toCheck.addAll(
          current
              .methods()
              .values()
              .stream()
              .flatMap(declaredMethod -> declaredMethod.methodCalls().stream())
              .map(CalledMethod::owner)
              .filter(typeDescriptor -> !reachable.contains(typeDescriptor))
              .map(knownClasses::get)
              .filter(declaredClass -> declaredClass != null)
              .collect(toList()));

      toCheck.addAll(
          current
              .methods()
              .values()
              .stream()
              .flatMap(declaredMethod -> declaredMethod.fieldAccesses().stream())
              .map(AccessedField::owner)
              .filter(typeDescriptor -> !reachable.contains(typeDescriptor))
              .map(knownClasses::get)
              .filter(declaredClass -> declaredClass != null)
              .collect(toList()));
    }

    return ImmutableSet.copyOf(reachable);
  }
 private static void playerWin(
     final Queue<Card> deckPlayer,
     final Queue<Card> cardsToWinPlayer1,
     final Queue<Card> cardsToWinPlayer2) {
   deckPlayer.addAll(cardsToWinPlayer1);
   cardsToWinPlayer1.clear();
   deckPlayer.addAll(cardsToWinPlayer2);
   cardsToWinPlayer2.clear();
 }
  public void process(
      @NotNull TopDownAnalysisContext c,
      @NotNull JetScope outerScope,
      @NotNull PackageLikeBuilder owner,
      @NotNull Collection<? extends PsiElement> declarations) {

    {
      // TODO: Very temp code - main goal is to remove recursion from
      // collectPackageFragmentsAndClassifiers
      Queue<JetDeclarationContainer> forDeferredResolve = new LinkedList<JetDeclarationContainer>();
      forDeferredResolve.addAll(
          collectPackageFragmentsAndClassifiers(c, outerScope, owner, declarations));

      while (!forDeferredResolve.isEmpty()) {
        JetDeclarationContainer declarationContainer = forDeferredResolve.poll();
        assert declarationContainer != null;

        DeclarationDescriptor descriptorForDeferredResolve =
            c.forDeferredResolver.get(declarationContainer);
        JetScope scope = c.normalScope.get(declarationContainer);

        // Even more temp code
        if (descriptorForDeferredResolve instanceof MutableClassDescriptorLite) {
          forDeferredResolve.addAll(
              collectPackageFragmentsAndClassifiers(
                  c,
                  scope,
                  ((MutableClassDescriptorLite) descriptorForDeferredResolve).getBuilder(),
                  declarationContainer.getDeclarations()));
        } else if (descriptorForDeferredResolve instanceof MutablePackageFragmentDescriptor) {
          forDeferredResolve.addAll(
              collectPackageFragmentsAndClassifiers(
                  c,
                  scope,
                  ((MutablePackageFragmentDescriptor) descriptorForDeferredResolve).getBuilder(),
                  declarationContainer.getDeclarations()));
        } else {
          assert false;
        }
      }
    }

    importsResolver.processTypeImports(c);

    createTypeConstructors(
        c); // create type constructors for classes and generic parameters, supertypes are not
            // filled in
    resolveTypesInClassHeaders(
        c); // Generic bounds and types in supertype lists (no expressions or constructor
            // resolution)

    c.setClassesTopologicalOrder(topologicallySortClassesAndObjects(c));

    // Detect and disconnect all loops in the hierarchy
    detectAndDisconnectLoops(c);
  }
Esempio n. 6
0
 /**
  * Returns a new collection holding references to all {@link EObject}s of the given elements. That
  * is, the tree of elements is flattened into one collection. The elements, however, are not
  * modified.
  *
  * @param elements A collection of {@link EObject}s.
  * @return A new, flat list of all elements.
  */
 public static List<? extends EObject> flattenEObjects(Collection<? extends EObject> elements) {
   final ArrayList<EObject> result = new ArrayList<EObject>();
   final Queue<EObject> queue = new LinkedList<EObject>();
   queue.addAll(elements);
   while (!queue.isEmpty()) {
     final EObject obj = queue.poll();
     result.add(obj);
     queue.addAll(obj.eContents());
   }
   return result;
 }
 private static List<DescriptorProtos.DescriptorProto> getAllMessageTypesInDescriptorProto(
     DescriptorProtos.FileDescriptorProto fileDescriptorProto) {
   Queue<DescriptorProtos.DescriptorProto> queue = new LinkedList<>();
   queue.addAll(fileDescriptorProto.getMessageTypeList());
   List<DescriptorProtos.DescriptorProto> result = new ArrayList<>();
   while (!queue.isEmpty()) {
     DescriptorProtos.DescriptorProto descriptorProto = queue.poll();
     queue.addAll(descriptorProto.getNestedTypeList());
     result.add(descriptorProto);
   }
   return result;
 }
 /**
  * Add the following notifications to the list to be processed at the next asynchronous
  * opportunity. Returns true if any of the notifications could remove, add, or change any
  * violations.
  *
  * @param notifications
  * @return boolean
  */
 public final boolean enqueue(List<Notification> notifications) {
   Boolean isPaused = null;
   List<Notification> filtered = new ArrayList<Notification>();
   for (Notification notification : notifications) {
     if (notification.getEventType() == Notification.RESOLVE) {
       continue;
     } else if (notification.getEventType() == ControlNotification.PAUSE) {
       isPaused = true;
       continue;
     } else if (notification.getEventType() == ControlNotification.RESUME) {
       isPaused = false;
       filtered.add(notification);
       continue;
     }
     if (isImportant(notification)) {
       filtered.add(notification);
     }
   }
   if (filtered.isEmpty() && (isPaused == null || !isPaused)) {
     return false;
   }
   synchronized (queueLock) {
     if (isPaused != null) {
       paused = isPaused;
     }
     queuedNotifications.addAll(filtered);
     queueLock.notify();
   }
   return !paused;
 }
Esempio n. 9
0
  /**
   * Finds the shortest possible path, measured in number of edges traversed, between two vertices,
   * a and b, in a graph, and returns this distance. The distance between a vertex and itself is
   * zero. Throws NoPathFoundException if there does not exist a path between a and b.
   *
   * @param graph the graph which contains vertices a and b
   * @param a the starting vertex contained in the graph
   * @param b the vertex to be traveled to (end vertex), contained in the same graph as a
   * @return the number of edges traversed to get from a to b along the shortest path
   * @throws NoPathFoundException if there does not exist a path from a to b
   */
  public static int shortestDistance(Graph graph, Vertex a, Vertex b) throws NoPathFoundException {

    Queue<Vertex> nextVertexQueue = new LinkedList<Vertex>();
    HashSet<Vertex> scheduledSet = new HashSet<Vertex>();

    nextVertexQueue.addAll(graph.getDownstreamNeighbors(a));
    scheduledSet.addAll(graph.getDownstreamNeighbors(a));

    int depth = 1;
    while (!nextVertexQueue.isEmpty()) {
      Queue<Vertex> currentVertexQueue = new LinkedList<Vertex>(nextVertexQueue);
      nextVertexQueue = new LinkedList<>();
      while (!currentVertexQueue.isEmpty()) {
        Vertex currentRoot = currentVertexQueue.poll();
        if (currentRoot.equals(b)) return depth;
        else {
          for (Vertex each_child : graph.getDownstreamNeighbors(currentRoot)) {
            if (!scheduledSet.contains(each_child)) {
              nextVertexQueue.add(each_child);
              scheduledSet.add(each_child);
            }
          }
        }
      }
      depth++;
    }
    throw new NoPathFoundException();
  }
Esempio n. 10
0
  /**
   * returns a set of lists that represent all possible breadth-first traversals of the graph. Each
   * traversal is always the shortest possible way to traverse the graph from a starting index. The
   * number of lists in the set represents the possible number of starting vertices.
   *
   * @param graph the graph to be traversed
   * @return Set<List<Vertex>> the set of lists of all possible ways to traverse the graph
   */
  public static Set<List<Vertex>> breadthFirstSearch(Graph graph) {
    // TODO: Representation safety required
    Set<List<Vertex>> result = new HashSet<List<Vertex>>();
    for (Vertex a : graph.getVertices()) {

      Queue<Vertex> nextVertexQueue = new LinkedList<Vertex>();
      HashSet<Vertex> scheduledSet = new HashSet<Vertex>();

      // initialize the first root queue
      nextVertexQueue.addAll(graph.getDownstreamNeighbors(a));
      scheduledSet.addAll(graph.getDownstreamNeighbors(a));

      // one traversal of the graph starting at a vertex a
      List<Vertex> traversal = new LinkedList<Vertex>();
      traversal.add(a);
      // loop until run out of new vertexes to visit
      while (!nextVertexQueue.isEmpty()) {

        // add the current vertex to the traversal
        Vertex currentRoot = nextVertexQueue.poll();
        traversal.add(currentRoot);

        // add children if they aren't already scheduled
        for (Vertex each_child : graph.getDownstreamNeighbors(currentRoot)) {
          if (!scheduledSet.contains(each_child)) {
            nextVertexQueue.add(each_child);
            scheduledSet.add(each_child);
          }
        }
      }

      result.add(traversal);
    }
    return result;
  }
Esempio n. 11
0
  /**
   * Finds an annotation in an Annotated, taking stereo types into account
   *
   * @param beanManager the current bean manager
   * @param annotated the Annotated in which to search
   * @param annotationType the type of the annotation to search for
   * @return An Optional that contains an instance of annotation type for which was searched if the
   *     annotated contained this.
   */
  public static <A extends Annotation> Optional<A> getAnnotation(
      BeanManager beanManager, Annotated annotated, Class<A> annotationType) {

    annotated.getAnnotation(annotationType);

    if (annotated.getAnnotations().isEmpty()) {
      return empty();
    }

    if (annotated.isAnnotationPresent(annotationType)) {
      return Optional.of(annotated.getAnnotation(annotationType));
    }

    Queue<Annotation> annotations = new LinkedList<>(annotated.getAnnotations());

    while (!annotations.isEmpty()) {
      Annotation annotation = annotations.remove();

      if (annotation.annotationType().equals(annotationType)) {
        return Optional.of(annotationType.cast(annotation));
      }

      if (beanManager.isStereotype(annotation.annotationType())) {
        annotations.addAll(beanManager.getStereotypeDefinition(annotation.annotationType()));
      }
    }

    return empty();
  }
  /** Copies all entries under the file path. */
  private void copyFileEntries(
      File baseDir, String entryRoot, Set<String> entries, JarOutputStream jarOut)
      throws IOException {
    URI baseUri = baseDir.toURI();
    File packageFile = new File(baseDir, entryRoot);
    Queue<File> queue = Lists.newLinkedList();
    queue.add(packageFile);
    while (!queue.isEmpty()) {
      File file = queue.remove();

      String entry = baseUri.relativize(file.toURI()).getPath();
      if (entries.add(entry)) {
        jarOut.putNextEntry(new JarEntry(entry));
        if (file.isFile()) {
          Files.copy(file, jarOut);
        }
        jarOut.closeEntry();
      }

      if (file.isDirectory()) {
        File[] files = file.listFiles();
        if (files != null) {
          queue.addAll(Arrays.asList(files));
        }
      }
    }
  }
Esempio n. 13
0
 /**
  * Put all the pool groups into the priority queue sorted by a comparator
  *
  * @param comparator the comparator to sort all the pool groups in the queue
  * @return the queue of the pool groups sorted by a comparator
  */
 private Queue<PoolGroupSchedulable> createPoolGroupQueue(ScheduleComparator comparator) {
   int initCapacity = snapshotPoolGroups.size() == 0 ? 1 : snapshotPoolGroups.size();
   Queue<PoolGroupSchedulable> poolGroupQueue =
       new PriorityQueue<PoolGroupSchedulable>(initCapacity, comparator);
   poolGroupQueue.addAll(snapshotPoolGroups);
   return poolGroupQueue;
 }
Esempio n. 14
0
 public void recursiveCompare() {
   Queue<ComparePair> compares = new LinkedList<ComparePair>();
   compares.add(this);
   while (!compares.isEmpty()) {
     compares.addAll(compares.poll().compare());
   }
 }
 private boolean setUpRemoteEngines(TestPlanEntity testPlan, Queue<Engine> engineQ) {
   List<EngineRole> engineRoles = testPlan.getTestTenant().getEngineList();
   Queue<EngineRole> engineRoleQ = new ArrayDeque<>();
   engineRoleQ.addAll(engineRoles);
   while (!engineRoleQ.isEmpty()) {
     EngineRole role = engineRoleQ.remove();
     if (engineQ.size() < engineRoles.size()) {
       _logger.error(
           String.format(
               "Testplan: %d can't init. Not enough available engines", testPlan.getId()));
       return true;
     }
     while (true) {
       Engine e = engineQ.remove();
       if (engineService.setRemoteEngineRole(e, role)) {
         break;
       }
       if (engineQ.isEmpty()) {
         _logger.error(
             String.format(
                 "Testplan: %d can't init. Not enough available engines", testPlan.getId()));
         return true;
       }
     }
   }
   return false;
 }
Esempio n. 16
0
  private static PencilPosition findShortestRoute(int[][] maze) {
    // all found solutions to the maze
    PriorityQueue<PencilPosition> solutions =
        new PriorityQueue<PencilPosition>(5, new PencilPositionComparator());
    // bread-first search queue
    Queue<PencilPosition> routes = new LinkedList<PencilPosition>();
    // set of already visited positions
    Set<PencilPosition> visitedPositions = new HashSet<PencilPosition>();

    // add the starting positions, which is always (0,0)
    routes.add(new PencilPosition(0, 0, false, null));

    while (!routes.isEmpty()) {
      PencilPosition position = routes.poll();

      // if this is the destinations position then we've found a solution
      if (0 == maze[position.row][position.column]) {
        solutions.add(position);
        continue;
      }

      // if we haven't already visited this position
      if (!visitedPositions.contains(position)) {
        routes.addAll(findPossibleRoutes(position, maze));
        visitedPositions.add(position);
      }
    }

    return solutions.poll();
  }
Esempio n. 17
0
  /**
   * Walk behaves more like pyhton's os.walk than the walker I built around it again this was
   * laziness. Is a breadth first search modifications could include max depth
   *
   * @return File[] containing files that fit the filter
   */
  public File[] walk() {
    DirectoryFilter df = new DirectoryFilter();
    Queue<File> dirQueue = new LinkedBlockingQueue<File>();
    dirQueue.addAll(Arrays.asList(m_topLevel.listFiles(df)));
    m_fileStructure.addDirs(m_topLevel.listFiles(df));
    m_fileStructure.addFiles(walkFiles(m_topLevel));

    while (!dirQueue.isEmpty()) {
      File d = dirQueue.poll();
      dirQueue.addAll(Arrays.asList(d.listFiles(df)));
      m_fileStructure.addDirs(d.listFiles(df));
      m_fileStructure.addFiles(walkFiles(d));
    }

    return m_fileStructure.getFiles();
  }
Esempio n. 18
0
 public static long[] routing(boolean[][] grid, int L, int C) {
   Queue<Loc> queue = new LinkedList<Loc>();
   long[][] routingMap = new long[L][C];
   routingMap[0][0] = 1;
   queue.add(new Loc(0, 0));
   long level = 0;
   Loc endLoc = new Loc(L - 1, C - 1);
   while (!queue.isEmpty()) {
     Set<Loc> prepareSet = new HashSet<Loc>();
     while (!queue.isEmpty()) {
       Loc poll = queue.poll();
       for (int[] o : offsets) {
         int tx = poll.x + o[0];
         int ty = poll.y + o[1];
         if (0 > tx || tx >= L || 0 > ty || ty >= C || !grid[tx][ty]) continue;
         Loc tLoc = new Loc(tx, ty);
         if (routingMap[tx][ty] == 0) prepareSet.add(tLoc);
         if (prepareSet.contains(tLoc)) {
           routingMap[tx][ty] += routingMap[poll.x][poll.y];
           routingMap[tx][ty] %= 1E9 + 7;
         }
       }
     }
     level++;
     if (prepareSet.contains(endLoc)) break;
     queue.addAll(prepareSet);
     prepareSet.clear();
   }
   if (routingMap[L - 1][C - 1] == 0) level = -1;
   return new long[] {routingMap[L - 1][C - 1], level};
 }
Esempio n. 19
0
  /**
   * Read input commands and execute transactions
   *
   * @throws Exception
   * @author Deepti Verma
   */
  public void run() throws Exception {
    String line = null;
    // Read and execute input operations
    while ((line = br.readLine()) != null) {
      line = line.trim();
      if (!(line.startsWith("\\")
          || line.isEmpty())) { // Ignore a line that starts with \\ then it is comment or is empty
        String[] operations = line.split(";");
        for (int i = 0; i < operations.length; i++) {
          operations[i] = operations[i].trim();
          doOperation(operations[i]);
        }
      }

      // Check for transactions waiting to be executed
      Queue<Transaction> tempQueue = new ArrayDeque<>();
      while (!transactionWaitingList.isEmpty()) {
        Transaction tr = transactionWaitingList.poll();
        if (tr.isWaiting && !tempQueue.contains(tr)) {
          if (!doOperation(tr.operationWaiting)) {
            anyTransactionsWaiting = true;
            tempQueue.add(tr);
          } else {
            tr.isWaiting = false;
          }
        }
      }
      if (!tempQueue.isEmpty()) transactionWaitingList.addAll(tempQueue);
      currentTimeStamp++;
    }
    bw.flush();
  }
Esempio n. 20
0
  /**
   * Given a configuration file, load the rooms, spawn points and players.
   *
   * @param filename - name of configuration file
   */
  public void loadRooms(String filename) {

    rooms.clear();
    // System.out.println("Loading level");
    try {
      Scanner sc;

      if (StealthGame.EXPORT) sc = new Scanner(ResourceLoader.load(filename));
      else sc = new Scanner(new File(filename));

      // int roomNum = 0;

      // Load rooms
      while (sc.hasNext()) {
        String roomFile = sc.nextLine();
        rooms.add(new Room("res/levels/" + roomFile));
      }

      sc.close();
    } catch (IOException e) {
      System.out.println("Level - Error loading file - IOException : " + e.getMessage());
    }

    // Initilise door destinations
    for (Room r : rooms) {
      r.initilizeDoors(rooms);
      spawns.addAll(r.getSpawns());
    }

    System.out.println("*** Done Loading level ***");
  }
 @Deprecated
 private void initTestShortCut(TestPlanEntity tp) {
   List<Engine> totest = engineService.getAllEngines().subList(0, tp.getEngineNumber());
   List<EngineRole> engineRoles = tp.getTestTenant().getEngineList();
   Queue<Engine> engineQ = new ArrayDeque<>();
   engineQ.addAll(totest);
   setUpRemoteEngines(tp, engineQ);
 }
Esempio n. 22
0
 public static void compareOrig(Object origObj, Object newObj, Class objClass) {
   ComparePair compare = new ComparePair(origObj, newObj, objClass);
   Queue<ComparePair> compares = new LinkedList<ComparePair>();
   compares.add(compare);
   while (!compares.isEmpty()) {
     compares.addAll(compares.poll().compare());
   }
 }
Esempio n. 23
0
  /**
   * @Title: disableSpot @Description: swith to on demand mode
   *
   * @throws
   */
  public synchronized void disableSpot() {
    isSpotEnabled = false;
    for (Set<InstanceStatus> temp : spotGroups.values()) {
      orphans.addAll(temp);
    }

    spotGroups.clear();
  }
Esempio n. 24
0
  public String ToDot() {
    String r = "";
    Set<SemiTagNode> visited = new HashSet<SemiTagNode>();
    Queue<SemiTagNode> worklist = new LinkedList<SemiTagNode>();
    worklist.addAll(heads);
    visited.addAll(heads);
    StringBuilder b = new StringBuilder("digraph HtmlTree {\n");
    b.append("  rankdir = LR;\n");
    int count = 0;
    for (SemiTagNode node : allnodes) {
      SemiTagNode current = node;
      String tagname = "\"" + "" + current.getId() + current.toString() + "\"";
      b.append("  ").append(tagname);
      b.append("[shape=box];\n");
      for (SemiTagEdge e : current.outegdes) {
        SemiTagNode suc = e.target;
        b.append("  ");
        // System.out.println(tagname);
        b.append(tagname + " -> \"" + "" + suc.getId() + suc.toString() + "\"");
        String cutmethodsig;
        if (e.methodsig.length() > 26) cutmethodsig = e.methodsig.substring(16, 25);
        else cutmethodsig = e.methodsig;
        b.append("[label = \"" + cutmethodsig + "\"]");
        // b.append("  ").append(current.Value.getFiniteStrings());

      }
    }
    /*while(!worklist.isEmpty())
    {

    	SemiTagNode current=worklist.poll();
    	String tagname="\""+""+current.getId()+current.toString()+"\"";
    	b.append("  ").append(tagname);
    	b.append("[shape=box];\n");
    	for (SemiTagEdge e : current.outegdes) {
    		SemiTagNode suc=e.target;
    		if(!visited.contains(suc))
    		{
    			visited.add(suc);
    			worklist.add(suc);
    		}
    		b.append("  ");
    		//System.out.println(tagname);
    		b.append(tagname+" -> \""+""+suc.getId()+suc.toString()+"\"");
    		String cutmethodsig;
    		if(e.methodsig.length()>26)
    			cutmethodsig=e.methodsig.substring(16, 25);
    		else
    			cutmethodsig=e.methodsig;
    		b.append("[label = \""+cutmethodsig+"\"]");
    		//b.append("  ").append(current.Value.getFiniteStrings());


    	}
    	count++;
    }*/
    return b.append("}\n").toString();
  }
  public Message<URI> receive() {
    if (toBeReceived.isEmpty()) {
      Collection<ChangedDocument> changedDocuments = couchDbChangesOperations.pollForChanges();
      toBeReceived.addAll(changedDocuments);
    }

    ChangedDocument changedDocument = toBeReceived.poll();
    return prepareMessage(changedDocument);
  }
 @VisibleForTesting
 protected void flushCallbacks() {
   Queue<QueuedCallback> queue = new ArrayDeque<>();
   queue.addAll(mCallbackQueue);
   for (QueuedCallback callback : queue) {
     if (callback.shouldRun()) {
       callback.run();
       mCallbackQueue.remove(callback);
     }
   }
 }
    /** @param nodes Nodes. */
    private Queue<ClusterNode> fallbacks(Collection<ClusterNode> nodes) {
      Queue<ClusterNode> fallbacks = new LinkedList<>();

      ClusterNode node = F.first(F.view(nodes, IS_LOC_NODE));

      if (node != null) fallbacks.add(node);

      fallbacks.addAll(node != null ? F.view(nodes, F.not(IS_LOC_NODE)) : nodes);

      return fallbacks;
    }
 @Override
 public void setup(Context.OperatorContext context) {
   if (context != null) {
     spinningTime = context.getValue(Context.OperatorContext.SPIN_MILLIS);
   }
   execute = true;
   cause = new AtomicReference<Throwable>();
   waitingTuples.addAll(committedTuples);
   executorService =
       Executors.newSingleThreadExecutor(new NameableThreadFactory("Reconciler-Helper"));
   executorService.submit(processEnqueuedData());
 }
 @Override
 public void committed(long l) {
   logger.debug(" current committed window {}", l);
   if (currentWindows.isEmpty()) {
     return;
   }
   long processedWindowId = currentWindows.peek();
   while (processedWindowId <= l) {
     List<QUEUETUPLE> outputDataList = currentWindowTuples.get(processedWindowId);
     if (outputDataList != null && !outputDataList.isEmpty()) {
       committedTuples.addAll(outputDataList);
       waitingTuples.addAll(outputDataList);
     }
     currentWindows.remove();
     currentWindowTuples.remove(processedWindowId);
     if (currentWindows.isEmpty()) {
       return;
     }
     processedWindowId = currentWindows.peek();
   }
 }
Esempio n. 30
0
  public DBPediaSpreadVector(final SailConnection sailConnection, final Resource... seeds) {
    this.sailConnection = sailConnection;
    this.vector = new WeightedVector<Resource>();
    this.seeds = seeds;

    curGen = new LinkedList<Resource>();
    curGen.addAll(Arrays.asList(seeds));

    nextGen = new LinkedList<Resource>();

    weight = 1.0;
  }