protected List<String> serviceNamesNotFoundInZipkin(List<io.zipkin.Span> spans) {
   List<String> serviceNamesFoundInAnnotations =
       spans
           .stream()
           .filter(span -> span.annotations != null)
           .map(span -> span.annotations)
           .flatMap(Collection::stream)
           .filter(span -> span.endpoint != null)
           .map(annotation -> annotation.endpoint)
           .map(endpoint -> endpoint.serviceName)
           .distinct()
           .collect(Collectors.toList());
   List<String> serviceNamesFoundInBinaryAnnotations =
       spans
           .stream()
           .filter(span -> span.binaryAnnotations != null)
           .map(span -> span.binaryAnnotations)
           .flatMap(Collection::stream)
           .filter(span -> span.endpoint != null)
           .map(annotation -> annotation.endpoint)
           .map(endpoint -> endpoint.serviceName)
           .distinct()
           .collect(Collectors.toList());
   List<String> names = new ArrayList<>();
   names.addAll(serviceNamesFoundInAnnotations);
   names.addAll(serviceNamesFoundInBinaryAnnotations);
   return names.contains(getAppName()) ? Collections.emptyList() : names;
 }
Пример #2
1
  public static void main(String... args) {

    List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
    numbers.stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);

    numbers.stream().limit(20).forEach(System.out::println);
  }
Пример #3
1
  public static void main(String[] args) {
    List<Person> persons = new LinkedList<>();
    persons.add(new Person("Bob", 19));
    persons.add(new Person("Bob", 65));
    persons.add(new Person("Arne", 32));
    persons.add(new Person("Arne", 10));
    persons.add(new Person("Arne", 40));
    persons.add(new Person("Kari", 27));
    persons.add(new Person("Gunvor", 90));
    persons.add(new Person("Kjell", 90));
    persons.add(new Person("Bob", 5));
    persons.add(new Person("Bob", 15));

    long nameCount = persons.stream().map(Person::getName).distinct().count();

    System.out.println("There are " + nameCount + " different names");

    int totalAge = persons.stream().mapToInt(Person::getAge).sum();

    System.out.println("The total age is " + totalAge);

    System.out.println("The following persons are of age:");
    persons
        .stream()
        .filter(p -> p.getAge() >= 18)
        .forEach(
            p -> {
              System.out.println("- " + p.getName());
            });
  }
 private void initializeExplicitConstructor(
     TurinTypeContructorDefinitionNode constructor, SymbolResolver resolver) {
   List<? extends FormalParameter> allParams = constructor.getParameters();
   List<FormalParameter> paramsWithoutDefaultValues =
       allParams
           .stream()
           .filter((p) -> !p.hasDefaultValue())
           .collect(Collectors.<FormalParameter>toList());
   List<String> paramSignatures =
       paramsWithoutDefaultValues
           .stream()
           .map((p) -> p.getType().jvmType().getSignature())
           .collect(Collectors.toList());
   boolean hasDefaultParameters =
       allParams.stream().filter((p) -> p.hasDefaultValue()).findFirst().isPresent();
   if (hasDefaultParameters) {
     paramSignatures.add("Ljava/util/Map;");
   }
   JvmConstructorDefinition constructorDefinition =
       new JvmConstructorDefinition(
           jvmType().getInternalName(), "(" + String.join("", paramSignatures) + ")V");
   constructors.add(
       new InternalConstructorDefinition(
           new ReferenceTypeUsage(this), allParams, constructorDefinition));
 }
  /**
   * Test {@link FileUtilities#generateSaveSetContent(SaveSetData)} and {@link
   * FileUtilities#readFromSaveSet(java.io.InputStream)}.
   *
   * @throws IOException
   */
  @Test
  public void testSaveSetData() throws IOException {
    SaveSet set =
        new SaveSet(
            new Branch(), Optional.empty(), new String[] {"first", "second", "third"}, "someId");
    SaveSetData bsd =
        new SaveSetData(
            set,
            Arrays.asList(
                new SaveSetEntry("pv1", "rb1", "d1", true),
                new SaveSetEntry("pv2", "rb2", "Math.pow(x,3)", false)),
            "some description");
    String content = FileUtilities.generateSaveSetContent(bsd);
    assertEquals(
        "# Description:\n# some description\n#\nPV,READBACK,DELTA,READ_ONLY\npv1,rb1,d1,true\npv2,rb2,\"Math.pow(x,3)\",false\n",
        content);

    SaveSetContent bsc =
        FileUtilities.readFromSaveSet(
            new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
    assertEquals("some description", bsc.getDescription());
    List<SaveSetEntry> entries = bsc.getEntries();
    assertArrayEquals(
        new String[] {"pv1", "pv2"},
        entries.stream().map(e -> e.getPVName()).toArray(String[]::new));
    assertArrayEquals(
        new String[] {"rb1", "rb2"},
        entries.stream().map(e -> e.getReadback()).toArray(String[]::new));
    assertArrayEquals(
        new String[] {"d1", "Math.pow(x,3)"},
        entries.stream().map(e -> e.getDelta()).toArray(String[]::new));
    assertArrayEquals(
        new Boolean[] {true, false},
        entries.stream().map(e -> e.isReadOnly()).toArray(Boolean[]::new));
  }
Пример #6
0
  public void calTrendMaMonitor(String code, List<Indicator> indicatorList) {
    List<ProdIndex> prodIndexList = prodIndexBuss.queryAscByCode(code);

    indicatorList
        .stream()
        .forEach(
            indicator -> {
              TrendMaMonitor trendMaMonitor1 =
                  trendMaMonitorRepos.findByCodeAndTrend(code, indicator.getName());
              TrendMaMonitor trendMaMonitor2 = new TrendMaMonitor();
              trendMaMonitor2.setTrend(indicator.getName());
              trendMaMonitor2.setCode(code);
              TrendMaMonitor trendMaMonitor =
                  trendMaMonitor1 == null ? trendMaMonitor2 : trendMaMonitor1;
              prodIndexList
                  .stream()
                  .forEach(
                      prodIndex -> {
                        indicator.push(prodIndex.getDt(), prodIndex.getPrice());
                        if (indicator.getLine().isEmpty()) {
                          return;
                        }
                        Price maPrice = indicator.getLine().get(indicator.getLine().size() - 1);
                        calTrendMaMonitor(
                            trendMaMonitor,
                            prodIndex.getDt(),
                            prodIndex.getPrice(),
                            maPrice.getP());
                      });
              trendMaMonitorRepos.save(trendMaMonitor);
            });
    trendMaMonitorRepos.flush();
  }
  @GET
  @Path("/{name}/{version}")
  @ApiOperation(
      value = "Documents by name and version",
      notes = "Documents always have a name and a version",
      response = DocumentDTO.class,
      responseContainer = "List")
  public List<DocumentDTO> documentByNameAndVersion(
      @ApiParam(value = "Name of documents to fetch", required = true) @PathParam("name")
          String name,
      @ApiParam(value = "Version of named documents", required = true) @PathParam("version")
          String version,
      @ApiParam(value = "Whether to re-index document", required = false, defaultValue = "false")
          @DefaultValue("false")
          @QueryParam("reindex")
          boolean reindex) {

    List<Document> documents = documentRepository.findDocumentsByNameAndVersion(name, version);

    if (reindex) {
      documents.stream().forEach(document -> documentationService.reindexDocument(document));
    }

    return documents
        .stream()
        .map(Transformations::convertDocumentToDTO)
        .collect(Collectors.toList());
  }
Пример #8
0
  public static void createPackageJar(List<Member> members, PackageVersion version) {

    // These members should be collect before insert memberships, Right now
    // we don't need UploadedPackageMember
    InvocationContext context = InvocationContext.get();
    List<Instance> packageMembers = context.getDbChanges().getAdded();

    List<UploadedPackageMember> uploadMemberships =
        members
            .stream()
            // Prepare UploadedPackageMember from package's component
            .map(m -> createUploadedMembership(m.getClonedComponent(), m.getMembership(), version))
            // Collect to list
            .collect(Collectors.toList());

    List<UploadedPackageMember> createUploadPackageMembers =
        createUploadPackageMembers(UploadingPackage.getMembers(), version);

    uploadMemberships.addAll(createUploadPackageMembers);

    // Save Uploaded Package Membership
    context.getDatabase().upsert(uploadMemberships, DMLOperationType.THROW_ERRORS);

    List<Instance> allInstances =
        uploadMemberships.stream().map(m -> m.getComponent()).collect(Collectors.toList());
    prepareJAR(version, allInstances);

    prepatePackageData(version, packageMembers);
  }
  @Test
  public void testGetPaymentsAmortizedFully() {

    AmortizationAttributes amAttrs = generateAmortizationAttributesObjectTemplate();
    MonetaryAmount loanAmount = ofUSD(10000);
    amAttrs.setLoanAmount(loanAmount);
    amAttrs.setInterestRateAsPercent(7.);
    amAttrs.setInterestOnly(false);
    amAttrs.setPaymentFrequency(TimePeriod.Monthly.getPeriodsPerYear());
    int termInMonths = 12;
    amAttrs.setTermInMonths(termInMonths);
    amAttrs.setAmortizationPeriodInMonths(12);
    amAttrs.setCompoundingPeriodsPerYear(2);
    amAttrs.setRegularPayment(AmortizationCalculator.getPeriodicPayment(amAttrs));

    List<ScheduledPayment> schedule = AmortizationCalculator.generateSchedule(amAttrs);

    MonetaryAmount interestTotal =
        schedule.stream().map(payment -> payment.getInterest()).reduce((a, b) -> a.add(b)).get();

    assertEquals("Amortized Interest total", ofUSD(377.67), interestTotal);

    MonetaryAmount principalTotal =
        schedule.stream().map(payment -> payment.getPrincipal()).reduce((a, b) -> a.add(b)).get();

    assertEquals("Amortized Principal fully paid", loanAmount, principalTotal);
  }
  @Override
  @Async(value = "gpThreadPoolTaskExecutor")
  public Future<Boolean> async(IMissioneNotificationMessage theMissioneNotificationMessage)
      throws Exception {
    logger.debug(
        "@@@@@@@@@@@@@@@@@@@@@@@@@@ {} start Notification " + "Task {}\n",
        Thread.currentThread().getName(),
        getAsyncTaskType());
    List<IMissioniMessagePreparator> missioniMessagePreparator = null;

    try {
      missioniMessagePreparator = prepareMessage(theMissioneNotificationMessage);
      missioniMessagePreparator
          .stream()
          .forEach(m -> this.gpMailSpringSender.send(m.getMimeMessagePreparator()));
    } catch (Exception ex) {
      logger.error("####################MAIL_ASYNC_TASK_EXCEPTION : {}\n", ex.getMessage());
      ex.printStackTrace();
      return new AsyncResult<>(Boolean.FALSE);
    } finally {
      if ((missioniMessagePreparator != null) && (!missioniMessagePreparator.isEmpty())) {
        missioniMessagePreparator.stream().forEach(m -> m.deleteAttachments());
      }
    }

    logger.debug(
        "@@@@@@@@@@@@@@@@@@@@@@@@@@ {} end Notification " + "Task {}\n",
        Thread.currentThread().getName(),
        getAsyncTaskType());
    return new AsyncResult<>(Boolean.TRUE);
  }
Пример #11
0
  /**
   * Evaluates the given learner on the given dataset using the given evaluators.
   *
   * @param maxDesiredSize See maxDesiredSize in SupervisedLearner.predictScoredList.
   * @param learnerUseFilter This tells the learner that it needs to apply its filter to the given
   *     inputs and labels when making predictions. In this case the filter will also be used in
   *     reverse to unfilter the learner's predictions before passing them to the evaluator. The
   *     only reason this should be false is if the inputs and labels are pre-filterd, such as in
   *     SupervisedLearner.innerTrain.
   */
  public static Evaluation runEvaluators(
      Matrix inputs,
      Matrix labels,
      SupervisedLearner learner,
      boolean learnerUseFilter,
      List<Evaluator> evaluators) {
    if (inputs.rows() != labels.rows()) throw new IllegalArgumentException();

    evaluators.stream().forEach(evaluator -> evaluator.startBatch(labels));
    int maxDesiredSize =
        evaluators.stream().mapToInt(evaluator -> evaluator.getMaxDesiredSize()).max().getAsInt();

    for (int r : new Range(inputs.rows())) {
      List<Vector> predictions =
          learner.predictScoredList(inputs.row(r), maxDesiredSize, learnerUseFilter);
      for (Evaluator evaluator : evaluators) {
        evaluator.evaluate(labels.row(r), predictions);
      }
    }

    Evaluation evaluation = new Evaluation();
    for (Evaluator evaluator : evaluators) {
      evaluation.putScores(evaluator.getClass(), evaluator.calcScores());
      evaluation.putConfusions(evaluator.getClass(), evaluator.calcConfusions());
    }

    return evaluation;
  }
Пример #12
0
  static Runnable fromParameters(String[] args) {
    Map<String, Opts> commands = new HashMap<>();

    commands.put("serve", new Serve());
    commands.put("check", new Check());
    commands.put("build", new Build());
    commands.put("help", new Help());
    commands.put("new", new New());

    List<String> params =
        new ArrayList<>(args.length == 0 ? Arrays.asList("build") : Arrays.asList(args));
    params
        .stream()
        .findFirst()
        .ifPresent(
            command -> {
              if (!commands.containsKey(command)) {
                params.add(0, "build");
              }
            });

    Opts command = commands.get(params.get(0));

    OptionSet parsed =
        command
            .getOptionParser()
            .parse(params.stream().skip(1).collect(Collectors.toList()).toArray(new String[] {}));
    command.assign(parsed);
    return command;
  }
  @Test
  public void testFindAllByIds() {

    List<TestEntity> values =
        Arrays.asList(1, 2)
            .stream()
            .map(
                v -> {
                  TestEntity t = new TestEntity();
                  t.setStringProperty(String.format("Hello %s time(s)", v));
                  return t;
                })
            .collect(Collectors.toList());
    repository.save(values);

    List<TestEntity> actual =
        (List<TestEntity>)
            repository.findAll(values.stream().map(TestEntity::getId).collect(Collectors.toList()));

    assertNotNull("Checking that the result is not null.", actual);
    assertEquals(2, actual.size());

    Map<String, TestEntity> expected =
        values.stream().collect(toMap(TestEntity::getId, Function.identity()));
    actual.forEach(
        testEntity ->
            assertEquals(
                expected.get(testEntity.getId()).getStringProperty(),
                testEntity.getStringProperty()));
  }
Пример #14
0
  /**
   * Selects a unit from the entries in the table that pass the filter
   *
   * @param filter - the function that determines which units are permitted; if null, no filter is
   *     applied.
   * @return - the selected unit, or null if no units pass the filter.
   */
  public MechSummary generateUnit(UnitFilter filter) {
    int roll = Compute.randomInt(100);
    if (roll < salvagePct) {
      MechSummary ms = generateSalvage(filter);
      if (ms != null) {
        return ms;
      }
    }
    List<TableEntry> useUnitList = unitTable;
    int unitMapSize = unitTotal;
    if (filter != null) {
      useUnitList =
          unitTable
              .stream()
              .filter(te -> filter.include(te.getUnitEntry()))
              .collect(Collectors.toList());
      unitMapSize = useUnitList.stream().mapToInt(te -> te.weight).sum();
    }

    if (unitMapSize > 0) {
      roll = Compute.randomInt(unitMapSize);
      for (TableEntry te : useUnitList) {
        if (roll < te.weight) {
          return te.getUnitEntry();
        }
        roll -= te.weight;
      }
    }
    assert (unitMapSize == 0);
    return null;
  }
Пример #15
0
  public IResult getStatus(String name) {
    List<Attack> attacks;
    List<SpellCast> spellCasts;
    Person person = personService.find(name, false);
    if (person == null) {
      return new ErrorResult("Person " + name + " not found");
    }
    attacks = attackService.findByPerson(person);
    spellCasts = spellService.findByCasterAndTarget(person, person.getProvince());

    List<String> messages = new ArrayList<>();
    messages.add("Status for " + person.getName());
    messages.add("Armies out:");
    // @formatter:off
    messages.addAll(
        attacks
            .stream()
            .sorted((left, right) -> left.getReturnDate().compareTo(right.getReturnDate()))
            .map(attack -> attack.toString(false))
            .collect(Collectors.toList()));
    // @formatter:on
    messages.add("Active spells:");
    messages.addAll(spellCasts.stream().map(this::toMessage).collect(Collectors.toList()));
    return new MultiReplyResult(messages);
  }
Пример #16
0
  private boolean checkAndHandleIfVisibleDsSwitchesFromCompleteToIncomplete(
      final List<DistributionSetUpdateEvent> events,
      final List<DistributionSetIdName> visibleItemIds) {
    final List<DistributionSet> setsThatAreVisibleButNotCompleteAnymore =
        events
            .stream()
            .map(event -> event.getEntity())
            .filter(set -> !set.isComplete())
            .filter(set -> visibleItemIds.contains(DistributionSetIdName.generate(set)))
            .collect(Collectors.toList());

    if (!setsThatAreVisibleButNotCompleteAnymore.isEmpty()) {
      refreshDistributions();

      if (setsThatAreVisibleButNotCompleteAnymore
          .stream()
          .anyMatch(
              set -> set.getId().equals(managementUIState.getLastSelectedDsIdName().getId()))) {
        managementUIState.setLastSelectedDistribution(null);
        managementUIState.setLastSelectedEntity(null);
      }

      return true;
    }

    return false;
  }
Пример #17
0
  public static Settings readFile() {
    try {
      List<String> set = Files.readAllLines(Paths.get(filename));
      Optional<String> hasHost = set.stream().filter(s -> s.contains("HOST")).findFirst();
      Optional<String> hasPort = set.stream().filter(s -> s.contains("PORT")).findFirst();
      Optional<String> hasDbName = set.stream().filter(s -> s.contains("DB_NAME")).findFirst();
      Optional<String> hasUser = set.stream().filter(s -> s.contains("USER")).findFirst();
      Optional<String> hasPass = set.stream().filter(s -> s.contains("PASSWORD")).findFirst();

      //            Stream.of("HOST", "PORT", "DB_NAME", "USER", "PASSWORD").(e -> {
      //                set.stream().filter(s -> s.contains(e)).findFirst();
      //            });
      Settings settings = null;

      if (hasHost.isPresent()
          && hasPort.isPresent()
          && hasDbName.isPresent()
          && hasUser.isPresent()
          && hasPass.isPresent()) {
        settings = new Settings();
        settings.setHOST(hasHost.get().split(":")[1]);
        settings.setPORT(hasPort.get().split(":")[1]);
        settings.setDATABASE_NAME(hasDbName.get().split(":")[1]);
        settings.setUSER(hasUser.get().split(":")[1]);
        settings.setPASSWORD(hasPass.get().split(":")[1]);

      } else {
      }
      return settings;
    } catch (IOException ex) {
      JOptionPane.showMessageDialog(null, "Nie mo¿na zapisaæ do pliku!");
      logger.log(Level.WARNING, "read from file goes wrong");
    }
    return null;
  }
Пример #18
0
 @Override
 public String toString() {
   depositsString = "";
   checkOutsString = "";
   deposits
       .stream()
       .forEach(
           (deposit) -> {
             depositsString += deposit.toString();
           });
   checkOuts
       .stream()
       .forEach(
           (checkOut) -> {
             checkOutsString += checkOut.toString();
           });
   return "\nAccount: "
       + accountId
       + ", "
       + creationDate
       + ", "
       + money
       + ", "
       + accountStatus
       + depositsString
       + checkOutsString;
 }
Пример #19
0
  public Opml export(User user) {
    Opml opml = new Opml();
    opml.setFeedType("opml_1.1");
    opml.setTitle(String.format("%s subscriptions in CommaFeed", user.getName()));
    opml.setCreated(new Date());

    List<FeedCategory> categories = feedCategoryDAO.findAll(user);
    Collections.sort(
        categories,
        (e1, e2) ->
            MoreObjects.firstNonNull(e1.getPosition(), 0)
                - MoreObjects.firstNonNull(e2.getPosition(), 0));

    List<FeedSubscription> subscriptions = feedSubscriptionDAO.findAll(user);
    Collections.sort(
        subscriptions,
        (e1, e2) ->
            MoreObjects.firstNonNull(e1.getPosition(), 0)
                - MoreObjects.firstNonNull(e2.getPosition(), 0));

    // export root categories
    for (FeedCategory cat :
        categories.stream().filter(c -> c.getParent() == null).collect(Collectors.toList())) {
      opml.getOutlines().add(buildCategoryOutline(cat, categories, subscriptions));
    }

    // export root subscriptions
    for (FeedSubscription sub :
        subscriptions.stream().filter(s -> s.getCategory() == null).collect(Collectors.toList())) {
      opml.getOutlines().add(buildSubscriptionOutline(sub));
    }

    return opml;
  }
  private static List<AnaphorWithReferent> parseText(InputText text) {
    Annotation annotatedText = new Annotation(text.toString());
    Container.getStanfordCoreNLP().annotate(annotatedText);
    List<CoreMap> coreMapSentences = annotatedText.get(CoreAnnotations.SentencesAnnotation.class);
    List<Tree> trees =
        coreMapSentences
            .stream()
            .map(s -> s.get(TreeCoreAnnotations.TreeAnnotation.class))
            .collect(Collectors.toList());

    List<Sentence> allSentences =
        IntStream.range(0, trees.size())
            .mapToObj(
                id ->
                    new Sentence(
                        id,
                        trees.get(id),
                        Container.getNPsFromParseTreeExtractor().extract(trees.get(id))))
            .collect(Collectors.toList());
    List<AnaphorWithReferent> anaphoraWithReferentFromAllSentences =
        allSentences
            .stream()
            .map(s -> Container.getAllAnaphorWithReferentPerSentenceFinder().find(s, allSentences))
            .flatMap(a -> a.stream())
            .collect(Collectors.toList());

    return anaphoraWithReferentFromAllSentences;
  }
Пример #21
0
  public static void main(String[] args) {
    List<Person> people = createPeople();

    // print all males, but with name in uppercase
    people
        .stream()
        .filter(person -> person.getGender() == Gender.MALE)
        .map(
            person ->
                new Person(person.getName().toUpperCase(), person.getGender(), person.getAge()))
        .forEach(System.out::println);

    // the original list is still intact
    System.out.println(people);

    // Map (aka Convert) People to Birds
    people
        .stream()
        .filter(person -> person.getGender() == Gender.MALE)
        .map(
            person -> new Bird(person.getName().toUpperCase(), person.getGender(), person.getAge()))
        .forEach(System.out::println);

    // the original list is still intact
    System.out.println(people);
  }
  private List<ReportEntry> fillForEmptyPeriods(
      List<ReportEntry> inputEntries, Pair<LocalDate, LocalDate> interval) {
    Optional<String> aRosterTypeCode =
        inputEntries.stream().map(ReportEntry::getRosterTypeCode).findAny();

    if (!aRosterTypeCode.isPresent()) {
      return inputEntries;
    }
    List<ReportEntry> result = inputEntries.stream().collect(Collectors.toList());

    for (LocalDate period = interval.getLeft();
        period.isBefore(interval.getRight());
        period = period.plusMonths(1)) {
      result.add(
          new ReportEntry(
              beneficiary,
              aRosterTypeCode.get(),
              AmountType.PAYMENT,
              YearMonth.from(period),
              BigDecimal.ZERO));
      result.add(
          new ReportEntry(
              beneficiary, "UNKNOWN", AmountType.REFUND, YearMonth.from(period), BigDecimal.ZERO));
    }
    return result;
  }
Пример #23
0
  public Theme(
      String name,
      List<String> cssRelativePaths,
      List<String> headJsRelativePaths,
      List<String> bodyJsRelativePaths) {
    this.name = name;

    String uriPrefix = UriUtils.getPublicUri(this) + "/";
    this.cssTagSuffixes =
        cssRelativePaths
            .stream()
            .map(
                relativePath ->
                    uriPrefix + relativePath + "\" rel=\"stylesheet\" type=\"text/css\" />")
            .collect(Collectors.toList());
    this.headJsTagSuffixes =
        headJsRelativePaths
            .stream()
            .map(relativePath -> uriPrefix + relativePath + "\" type=\"text/javascript\"></script>")
            .collect(Collectors.toList());
    this.bodyJsTagSuffixes =
        bodyJsRelativePaths
            .stream()
            .map(relativePath -> uriPrefix + relativePath + "\" type=\"text/javascript\"></script>")
            .collect(Collectors.toList());
  }
Пример #24
0
  public Computation compute(TypeManager types, SerializedValueVisitor<Computation> compiler) {
    Class<?> clazz = constructorParams.getType();
    List<String> statements = new ArrayList<>();

    List<Computation> computedParams =
        constructorParams
            .getValues()
            .stream()
            .map(value -> value.accept(compiler))
            .collect(toList());

    statements.addAll(
        computedParams
            .stream()
            .flatMap(computation -> computation.getStatements().stream())
            .collect(toList()));

    String[] params =
        computedParams.stream().map(computation -> computation.getValue()).toArray(String[]::new);

    String bean = newObject(types.getBestName(clazz), params);
    String constructorStatement =
        assignLocalVariableStatement(types.getSimpleName(clazz), name, bean);
    statements.add(constructorStatement);

    for (SetterParam param : setterParams) {
      Computation fieldComputation = param.computeValue().accept(compiler);
      statements.addAll(fieldComputation.getStatements());

      String setStatement = callMethodStatement(name, param.getName(), fieldComputation.getValue());
      statements.add(setStatement);
    }

    return new Computation(name, true, statements);
  }
Пример #25
0
 @Test
 public void testOnlyOne() {
   List<Integer> ints = IntStreamEx.rangeClosed(1, 100).boxed().toList();
   checkShortCircuitCollector("One", Optional.empty(), 2, ints::stream, MoreCollectors.onlyOne());
   checkShortCircuitCollector(
       "FilterSeveral",
       Optional.empty(),
       2,
       () -> ints.stream().filter(x -> x % 20 == 0),
       MoreCollectors.onlyOne());
   checkShortCircuitCollector(
       "FilterSeveral2",
       Optional.empty(),
       40,
       ints::stream,
       MoreCollectors.filtering(x -> x % 20 == 0, MoreCollectors.onlyOne()));
   checkShortCircuitCollector(
       "FilterOne",
       Optional.of(60),
       1,
       () -> ints.stream().filter(x -> x % 60 == 0),
       MoreCollectors.onlyOne());
   checkShortCircuitCollector(
       "FilterNone",
       Optional.empty(),
       0,
       () -> ints.stream().filter(x -> x % 110 == 0),
       MoreCollectors.onlyOne());
 }
Пример #26
0
  /**
   * Program entry point
   *
   * @param args command line args
   */
  public static void main(String[] args) {
    // initialize game objects and print their status
    List<GameObject> objects = new ArrayList<>();
    objects.add(new FlamingAsteroid(0, 0, 5, 5));
    objects.add(new SpaceStationMir(1, 1, 2, 2));
    objects.add(new Meteoroid(10, 10, 15, 15));
    objects.add(new SpaceStationIss(12, 12, 14, 14));
    objects.stream().forEach(o -> LOGGER.info(o.toString()));
    LOGGER.info("");

    // collision check
    objects
        .stream()
        .forEach(
            o1 ->
                objects
                    .stream()
                    .forEach(
                        o2 -> {
                          if (o1 != o2 && o1.intersectsWith(o2)) {
                            o1.collision(o2);
                          }
                        }));
    LOGGER.info("");

    // output eventual object statuses
    objects.stream().forEach(o -> LOGGER.info(o.toString()));
    LOGGER.info("");
  }
Пример #27
0
  private TeamResult readTeamResultXml(
      final List<MatchInfo> matchCache,
      final List<TeamInfo> teamCache,
      final List<Category> categories,
      final Element resultElm)
      throws Exception {
    /*  example team result XML file content
    <result matchNumber="1" teamNumber="1" cat1="-1" cat2="-1" cat3="-1" ... >
        Specific notes about this team and this match
    </result>
    */

    // Process <result> XML element
    int theMatchNumber = resultElm.getAttribute("matchNumber").getIntValue();
    MatchInfo match =
        matchCache.stream().filter(m -> m.getMatchNumber() == theMatchNumber).findFirst().get();

    int theTeamNumber = resultElm.getAttribute("teamNumber").getIntValue();
    TeamInfo team =
        teamCache.stream().filter(t -> t.getTeamNumber() == theTeamNumber).findFirst().get();

    Map<Category, Integer> scores = new HashMap<>();
    for (Category c : categories) {
      String score = resultElm.getAttributeValue(c.getName());
      if ((score != null) && (score.length() > 0)) {
        scores.put(c, Integer.valueOf(score));
      }
    }

    TeamResult tr = new TeamResult(match, team, scores);
    tr.setNotes(resultElm.getTextNormalize());

    return tr;
  }
  public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    list.add("1");
    list.add("2");
    list.add("3");
    list.add("5");
    list.add("4");
    list.stream().filter(s -> Integer.valueOf(s) < 3).forEach(s -> System.out.print(s));

    List<String> list2 = new ArrayList<String>();
    list2.add("1");
    list2.add("2");
    list2.add("3");
    list2.add("5");
    list2.add("4");
    List<String> list3 =
        list2.stream().filter(s -> Integer.valueOf(s) < 3).collect(Collectors.toList());
    list3.add("7");
    list3.forEach(s -> System.out.print(s));

    List<String> list4 = new ArrayList<String>();
    list4.add("1");
    list4.add("2");
    list4.add("3");
    list4.add("5");
    list4.add("4");
    System.out.println(list4.stream().mapToInt(s -> Integer.valueOf(s)).sum());
    System.out.println(
        list4
            .stream()
            .filter(s -> Integer.valueOf(s) < 3)
            .mapToInt(s -> Integer.valueOf(s))
            .average()
            .getAsDouble());
  }
Пример #29
0
  public static void main(String[] args) {
    List<Employee> list = EmployeeFactory.getEmpList();

    Predicate<Employee> averageSal = e -> e.getSalary() < 6000;
    Predicate<Employee> itOnly = e -> e.getDepartment().equals(IT);
    Consumer<Employee> printConsumer =
        e ->
            LOGGER.info(
                "{}, {}, Age: {}, Salary: {} - {}",
                e.getName(),
                e.getGender(),
                e.getAge(),
                e.getSalary(),
                e.getDepartment());

    // display it employees before salary raise
    list.stream().filter(itOnly).filter(Employee::isFemale).forEach(printConsumer);
    Consumer<Employee> salaryRaise = e -> e.setSalary(e.getSalary() + 200);
    list.stream().filter(itOnly).filter(Employee::isFemale).forEach(salaryRaise);
    LOGGER.info("");
    LOGGER.info("=== Raise ===");
    LOGGER.info("");
    // output after sal raise
    list.stream().filter(itOnly).filter(Employee::isFemale).forEach(printConsumer);
  }
Пример #30
0
  // Adds any missing device ports.
  private void addMissingPorts(Device device) {
    try {
      List<Port> ports = deviceService.getPorts(device.id());
      Set<ConnectPoint> existing =
          ports
              .stream()
              .map(p -> new ConnectPoint(device.id(), p.number()))
              .collect(Collectors.toSet());
      Set<ConnectPoint> missing =
          connectPoints
              .stream()
              .filter(cp -> cp.deviceId().equals(device.id()))
              .filter(cp -> !existing.contains(cp))
              .collect(Collectors.toSet());

      if (!missing.isEmpty()) {
        List<PortDescription> newPorts =
            Stream.concat(
                    ports.stream().map(this::description), missing.stream().map(this::description))
                .collect(Collectors.toList());
        deviceProviderService.updatePorts(device.id(), newPorts);
      }
    } catch (IllegalArgumentException e) {
      log.warn("Error pushing ports: {}", e.getMessage());
    }
  }