Exemplo n.º 1
0
  public static <A, B> Stream<Pair<A, B>> zip(Stream<A> s1, Stream<B> s2, int size) {

    PairIterator<A, B, Pair<A, B>> itr =
        new PairIterator<>(s1.iterator(), s2.iterator(), Pair<A, B>::new);

    int characteristics = Spliterator.IMMUTABLE | Spliterator.NONNULL;

    if (size < 0) {
      return StreamSupport.stream(Spliterators.spliteratorUnknownSize(itr, characteristics), false);
    }

    return StreamSupport.stream(Spliterators.spliterator(itr, size, characteristics), false);
  }
Exemplo n.º 2
0
 public Boolean isCollectorFullBase() throws BotException {
   final int[] attackableElixirs = {0};
   final BufferedImage image = platform.screenshot(ENEMY_BASE);
   try {
     final URI uri = getClass().getResource("elixirs").toURI();
     Utils.withClasspathFolder(
         uri,
         (path) -> {
           final List<Rectangle> matchedElixirs = new ArrayList<>();
           try (Stream<Path> walk = Files.walk(path, 1)) {
             for (final Iterator<Path> it = walk.iterator(); it.hasNext(); ) {
               final Path next = it.next();
               if (Files.isDirectory(next)) {
                 continue;
               }
               final BufferedImage tar =
                   ImageIO.read(Files.newInputStream(next, StandardOpenOption.READ));
               final List<RegionMatch> doFindAll =
                   TemplateMatcher.findMatchesByGrayscaleAtOriginalResolution(image, tar, 7, 0.8);
               attackableElixirs[0] += countAttackableElixirs(doFindAll, matchedElixirs, next);
             }
           } catch (final IOException e) {
             logger.log(Level.SEVERE, e.getMessage(), e);
           }
         });
   } catch (final URISyntaxException e) {
     logger.log(Level.SEVERE, e.getMessage(), e);
   }
   return attackableElixirs[0] >= 0;
 }
Exemplo n.º 3
0
 /**
  * Returns whether the given {@link IntArrayND} equals the given object
  *
  * @param array The array
  * @param object The object
  * @return Whether the array equals the object
  */
 static boolean equals(IntArrayND array, Object object) {
   if (array == object) {
     return true;
   }
   if (object == null) {
     return false;
   }
   if (!(object instanceof IntArrayND)) {
     return false;
   }
   IntArrayND other = (IntArrayND) object;
   if (!array.getSize().equals(other.getSize())) {
     return false;
   }
   Stream<MutableIntTuple> coordinates =
       Coordinates.coordinates(array.getPreferredIterationOrder(), array.getSize());
   Iterable<MutableIntTuple> iterable = () -> coordinates.iterator();
   for (IntTuple coordinate : iterable) {
     int arrayValue = array.get(coordinate);
     int otherValue = other.get(coordinate);
     if (arrayValue != otherValue) {
       return false;
     }
   }
   return true;
 }
  public Stream<C> batchWhile(Predicate<? super T> predicate) {
    Iterator<T> it = stream.iterator();
    return StreamUtils.stream(
            new Iterator<C>() {
              T value = (T) UNSET;

              @Override
              public boolean hasNext() {
                return value != UNSET || it.hasNext();
              }

              @Override
              public C next() {

                C list = factory.get();
                if (value != UNSET) list.add(value);
                T value;

                label:
                while (it.hasNext()) {
                  value = it.next();
                  list.add(value);

                  if (!predicate.test(value)) {
                    value = (T) UNSET;
                    break label;
                  }
                  value = (T) UNSET;
                }
                return list;
              }
            })
        .filter(l -> l.size() > 0);
  }
 public ConsecutiveEventsSpliterator(
     final Stream<StreamBufferEvent> eventStream, final long currentVersion) {
   super(Long.MAX_VALUE, ORDERED);
   this.eventStream = eventStream;
   this.currentVersion = currentVersion;
   this.eventStreamIterator = eventStream.iterator();
 }
Exemplo n.º 6
0
 @Override
 public void run() {
   Instant now = Clock.systemUTC().instant();
   Optional<RetentionLevel> accessLevel =
       environment.retentions().findAccessLevelForMetric(metricName);
   if (accessLevel.isPresent()) {
     if (caches.get(accessLevel.get().name()).containsMetric(metricName)) {
       return;
     }
     Optional<RetentionLevel> highestLevel = accessLevel;
     while (highestLevel.isPresent() && highestLevel.get().next() != null) {
       highestLevel = environment.retentions().getNextLevel(highestLevel.get());
     }
     Optional<CachingLevel> cachingLevel =
         environment.cachingConfiguration().findLevelForLevelName(highestLevel.get().name());
     if (cachingLevel.isPresent()) {
       List<Future<?>> futures = new ArrayList<>();
       ArrayList<Metric> databaseMetricsList = new ArrayList<>();
       long intervalStart =
           now.minusSeconds(cachingLevel.get().cacheLineWidth() * highestLevel.get().frequency())
               .getEpochSecond();
       Interval interval = new Interval(intervalStart, now.getEpochSecond());
       Stream<Metric> databaseMetrics =
           environment.cassandraAccessLayer().loadMetrics(metricName, interval);
       Iterator<Metric> databaseMetricsIterator = databaseMetrics.iterator();
       while (databaseMetricsIterator.hasNext()) {
         Metric m = databaseMetricsIterator.next();
         databaseMetricsList.add(m);
       }
       while (accessLevel.isPresent()) {
         LoadMetrics loadMetrics =
             new LoadMetrics(accessLevel.get(), metricName, databaseMetricsList, interval);
         futures.add(loadMetricsThreadPool.submit(Executors.callable(loadMetrics)));
         accessLevel = environment.retentions().getNextLevel(accessLevel.get());
       }
       for (Future<?> f : futures) {
         try {
           f.get();
         } catch (InterruptedException | ExecutionException e) {
           log.warn("Exception while waiting for insertion of metrics into cache", e);
         }
       }
     }
   }
   log.trace("all new cache lines created for metric {}", metricName);
 }
Exemplo n.º 7
0
 @Test
 public void iso88599TOeuckr() throws IOException {
   Stream<Path> s = Files.list(new File(CrawlerUtils.getResourcePath("convert")).toPath());
   Iterator<Path> iter = s.iterator();
   while (iter.hasNext()) {
     Path p = iter.next();
     LOG.info(
         new String(p.getFileName().toString().getBytes("ISO-8859-1"), Charset.forName("euc-kr")));
     String newName =
         new String(p.getFileName().toString().getBytes("ISO-8859-1"), Charset.forName("euc-kr"));
     p.toFile().renameTo(p.getParent().resolve(newName).toFile());
   }
   s.close();
   LOG.info(
       new String(
           "/tmp/firefox-downloads/hello".getBytes("ISO-8859-1"), Charset.forName("euc-kr")));
 }
Exemplo n.º 8
0
  /**
   * Prints the list elements to the console, prepended by a number. Then, reads in a number from in
   * and returns the index of the element selected.
   */
  private int selectOptionFromList(Stream<String> list) {
    int i = 1;
    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
      this.out.printf("%d. %s\n", i, iterator.next());
      i++;
    }

    int option = -1;
    while (option <= 0 || option > i - 1) { // since i == numItems + 1
      try {
        option = this.scanner.nextInt();
      } catch (InputMismatchException e) {
        option = -1;
        this.scanner.next();
      }
    }
    return option - 1;
  }
  /**
   * get document and their corresponding length
   *
   * @param stemmedFile String stemmed file path
   * @return Map of Document -> Length
   * @throws IOException
   */
  private static Map<String, Long> getDocumentAndLength(String stemmedFile) throws IOException {
    HashMap<String, Long> documentLength = new HashMap<>();

    Stream<String> stemmed = FileUtils.readFiles(stemmedFile);
    Iterator<String> reader = stemmed.iterator();
    String lastDocId = null;
    while (reader.hasNext()) {
      String line = reader.next();
      if (isDocument(line)) {
        lastDocId = line.replace('#', ' ').trim();
        documentLength.put(lastDocId, 0L);
      } else {
        long length =
            Arrays.stream(line.split(SEPARATOR_SPACE)).filter(Indexer::isNotNumber).count();
        if (documentLength.containsKey(lastDocId)) {
          documentLength.put(lastDocId, documentLength.get(lastDocId) + length);
        } else {
          documentLength.put(lastDocId, length);
        }
      }
    }

    return documentLength;
  }
  /**
   * Loads a dictonary from a file named src/test/resources/dataDictionary.txt. TODO This should be
   * an externalised path.
   *
   * @throws IOException if the dictionary file cannot be opened.
   * @throws InvalidWordException if the dictionary file contains bad characters @see {@link
   *     DictionaryWord#pattern}.
   */
  protected void loadDictionary() throws IOException, InvalidWordException {
    Path path = FileSystems.getDefault().getPath("src/test/resources", "dataDictionary.txt");

    // load all lines as a Stream and iterate through them, creating a new
    // DictionaryWord as you go and adding to the map of anagrams.
    try (Stream<String> dictionaryWordStream = Files.lines(path, StandardCharsets.ISO_8859_1)) {
      for (Iterator<String> iterator = dictionaryWordStream.iterator(); iterator.hasNext(); ) {
        String word = (String) iterator.next();
        addWordToAnagramSet(new DictionaryWord(word));
      }
    }

    getAnagramsMap()
        .forEach(
            (k, v) -> {
              int numberOfAnagramWords = v.size();
              if (numberOfAnagramWords > 1) {
                totalAnagrams++;

                if (logger.isTraceEnabled()) {
                  logger.trace("anagram found: " + v);
                }
              }

              if (v.size() > longestGroupingOfAnagrams) {
                longestGroupingOfAnagrams = v.size();
                longestListOfAnagrams = v.toArray(longestListOfAnagrams);
              }
            });
    logger.info("Total anagrams = " + totalAnagrams);
    logger.info(
        "The largest number of anagrams in the set are: "
            + longestGroupingOfAnagrams
            + ". Its elements are: "
            + Arrays.toString(longestListOfAnagrams));
  }
Exemplo n.º 11
0
  public void read(Path path) throws IOException {

    try (Stream<String> lines = Files.lines(path, Charset.defaultCharset())) {

      Iterator<String> it = lines.iterator();
      String[] firstLine = it.next().split(" ");

      Problem problem = new Problem(Integer.parseInt(firstLine[0]), Integer.parseInt(firstLine[1]));

      int row = 0, colum = 0;
      while (it.hasNext()) {
        String line = it.next();
        colum = 0;

        for (char cell : line.toCharArray()) {
          if (cell == '#') {
            problem.paint(row, colum);
          }
          colum++;
        }
        row++;
      }
    }
  }
Exemplo n.º 12
0
  /**
   * Returns the encoded output stream of the underlying {@link Stream}'s encoder.
   *
   * @return the encoded output stream.
   */
  public Stream<int[]> getOutputStream() {
    if (isTerminal()) {
      throw new IllegalStateException("Stream is already \"terminal\" (operated upon or empty)");
    }

    final MultiEncoder encoder = (MultiEncoder) getEncoder();
    if (encoder == null) {
      throw new IllegalStateException(
          "setLocalParameters(Parameters) must be called before calling this method.");
    }

    // Protect outputStream formation and creation of "fan out" also make sure
    // that no other thread is trying to update the fan out lists
    Stream<int[]> retVal = null;
    try {
      criticalAccessLock.lock();

      final String[] fieldNames = getFieldNames();
      final FieldMetaType[] fieldTypes = getFieldTypes();

      if (outputStream == null) {
        if (indexFieldMap.isEmpty()) {
          for (int i = 0; i < fieldNames.length; i++) {
            indexFieldMap.put(fieldNames[i], i);
          }
        }

        // NOTE: The "inputMap" here is a special local implementation
        //       of the "Map" interface, overridden so that we can access
        //       the keys directly (without hashing). This map is only used
        //       for this use case so it is ok to use this optimization as
        //       a convenience.
        if (inputMap == null) {
          inputMap = new InputMap();
          inputMap.fTypes = fieldTypes;
        }

        final boolean isParallel = delegate.getInputStream().isParallel();

        output = new ArrayList<>();

        outputStream =
            delegate
                .getInputStream()
                .map(
                    l -> {
                      String[] arr = (String[]) l;
                      inputMap.arr = arr;
                      return input(arr, fieldNames, fieldTypes, output, isParallel);
                    });

        mainIterator = outputStream.iterator();
      }

      LinkedList<int[]> l = new LinkedList<int[]>();
      fanOuts.add(l);
      Copy copy = new Copy(l);

      retVal =
          StreamSupport.stream(
              Spliterators.spliteratorUnknownSize(
                  copy, Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.IMMUTABLE),
              false);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      criticalAccessLock.unlock();
    }

    return retVal;
  }
Exemplo n.º 13
0
 private <T extends Snippet> void identityMatch(Stream<T> got, T expected) {
   Iterator<T> it = got.iterator();
   assertTrue(it.hasNext(), "expected exactly one");
   assertTrue(expected == it.next(), "Identity must not change");
   assertFalse(it.hasNext(), "expected exactly one");
 }