Example #1
1
 /**
  * Creates a Tree of the given elements.
  *
  * @param <T> Component type of the List.
  * @param values Zero or more values.
  * @return A Tree containing the given values.
  * @throws NullPointerException if {@code values} is null
  */
 @SuppressWarnings("varargs")
 @SafeVarargs
 static <T> Tree<T> of(T... values) {
   Objects.requireNonNull(values, "values is null");
   List<T> list = List.of(values);
   return list.isEmpty() ? Empty.instance() : new Node<>(list.head(), list.tail().map(Tree::of));
 }
Example #2
1
 /**
  * Creates a Tree of the given elements.
  *
  * <p>If the given iterable is a tree, it is returned as result. if the iteration order of the
  * elements is stable.
  *
  * @param <T> Component type of the List.
  * @param iterable An Iterable of elements.
  * @return A list containing the given elements in the same order.
  * @throws NullPointerException if {@code elements} is null
  */
 @SuppressWarnings("unchecked")
 static <T> Tree<T> ofAll(Iterable<? extends T> iterable) {
   Objects.requireNonNull(iterable, "iterable is null");
   if (iterable instanceof Tree) {
     return (Tree<T>) iterable;
   } else {
     final List<T> list = List.ofAll(iterable);
     return list.isEmpty() ? Empty.instance() : new Node<>(list.head(), list.tail().map(Tree::of));
   }
 }
Example #3
1
 @Override
 protected PriorityQueue<Byte> ofAll(byte[] array) {
   return PriorityQueue.ofAll(List.ofAll(array));
 }
Example #4
1
 @Override
 protected PriorityQueue<Character> ofAll(char[] array) {
   return PriorityQueue.ofAll(List.ofAll(array));
 }
Example #5
1
 @Override
 protected PriorityQueue<Double> ofAll(double[] array) {
   return PriorityQueue.ofAll(List.ofAll(array));
 }
Example #6
1
 @Override
 protected PriorityQueue<Float> ofAll(float[] array) {
   return PriorityQueue.ofAll(List.ofAll(array));
 }
Example #7
1
 @Override
 protected PriorityQueue<Integer> ofAll(int[] array) {
   return PriorityQueue.ofAll(List.ofAll(array));
 }
Example #8
1
 @Override
 public <U> Array<U> scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation) {
   Objects.requireNonNull(operation, "operation is null");
   return Collections.scanRight(
       this, zero, operation, List.empty(), List::prepend, list -> Array.wrap(list.toJavaArray()));
 }
Example #9
1
 @Override
 protected PriorityQueue<Long> ofAll(long[] array) {
   return PriorityQueue.ofAll(List.ofAll(array));
 }
Example #10
1
 @Override
 protected PriorityQueue<Short> ofAll(short[] array) {
   return PriorityQueue.ofAll(List.ofAll(array));
 }
Example #11
1
 @Override
 default <U> Seq<U> scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation) {
   Objects.requireNonNull(operation, "operation is null");
   return Collections.scanRight(
       this, zero, operation, List.empty(), List::prepend, Function.identity());
 }
Example #12
1
 /**
  * Returns a new Node containing the given value and having no children.
  *
  * @param value A value
  * @param <T> Value type
  * @return A new Node instance.
  */
 static <T> Node<T> of(T value) {
   return new Node<>(value, List.empty());
 }
Example #13
1
 @Override
 protected PriorityQueue<Boolean> ofAll(boolean[] array) {
   return PriorityQueue.ofAll(List.ofAll(array));
 }
Example #14
1
 /**
  * Returns a new Node containing the given value and having the given children.
  *
  * @param value A value
  * @param children The child nodes, possibly empty
  * @param <T> Value type
  * @return A new Node instance.
  */
 static <T> Node<T> of(T value, Iterable<Node<T>> children) {
   Objects.requireNonNull(children, "children is null");
   return new Node<>(value, List.ofAll(children));
 }
Example #15
0
  public void clearMessages() {
    messages.clear();
    getRootStyleNode().removeChildrenAll();

    rootMessageStyleNodes.clear();

    endMarginNode = null;
    newMessageSeparatorNode = null;
  }
Example #16
0
 public List<AnalyzedMessage> getMessages(int offset, int length) {
   List<AnalyzedMessage> list = new ArrayList<>();
   for (int i = 0; i < rootMessageStyleNodes.size(); i++) {
     StyleNode node = rootMessageStyleNodes.get(i);
     if (JUtils.intersects(offset, length, node.getOffset(), node.getLength())) {
       list.add(messages.get(i));
     }
   }
   return list;
 }
Example #17
0
 protected Supplier<List<Person>> scrumMasterSupplier() {
   return () -> {
     Skill smSkill = organisationProperty().get().getSmSkill();
     Person currentProductOwner = productOwnerProperty().get();
     List<Person> currentDevTeam = devTeamProperty().get();
     // person has sm skill and does not currently have any other role in the team
     return teamMembersProperty()
         .get()
         .stream()
         .filter(
             person ->
                 person.observableSkills().contains(smSkill)
                     && !person.equals(currentProductOwner)
                     && !currentDevTeam.contains(person))
         .collect(Collectors.toList());
   };
 }
Example #18
0
 @Override
 public void setTypeVariables(List<TypeVariable> typeVariables) {
   declaration.setTypeParameters(
       typeVariables
           .stream()
           .map(getContext()::unresolveTypeVariable)
           .collect(Collectors.toList()));
 }
Example #19
0
  public void allRayIntersections(Vec raypt, Vec rayNormalizedDir, Consumer<Tp> cons) {
    if (!intersectsWithRay(raypt, rayNormalizedDir)) return;

    container.forEach(cons);
    forAllSubtree(
        (i, j, k) -> {
          if (subtree[i][j][k] != null)
            subtree[i][j][k].allRayIntersections(raypt, rayNormalizedDir, cons);
        });
  }
Example #20
0
  static void graphsToFile(List<Triplet<FooGraph, List<Integer>, FooGraph>> l, String name) {
    try {
      PrintWriter writer = new PrintWriter(name, "UTF-8");
      writer.println("graph G {");
      int offset = 0;
      for (Triplet<FooGraph, List<Integer>, FooGraph> t : l) {
        FooGraph g = t.getValue0();
        List<Integer> markedNodes = t.getValue1();
        FooGraph markedEdges = t.getValue2();

        for (int i = 0; i < g.numVertices(); i++) {
          String vertex = "" + (offset + i);
          if (markedNodes != null && markedNodes.contains(i)) {
            vertex += " [fillcolor = red, style=filled]";
          }
          writer.println(vertex);
        }
        for (int i = 0; i < g.numVertices(); i++) {
          for (int j = i + 1; j < g.numVertices(); j++) {
            if (g.adj[i][j]) {
              String edge = (offset + i) + " -- " + (offset + j);
              if (markedEdges != null && markedEdges.adj[i][j]) {
                edge += " [color = red, penwidth=6.0]";
              }
              writer.println(edge);
            }
          }
        }
        writer.println("");
        offset += g.numVertices();
      }
      writer.println("}");
      writer.close();

    } catch (IOException e) {
      System.err.println("Caught IOException: " + e.getMessage());
    }
  }
Example #21
0
  public void add(Tp obj, int maxDepth) {
    if (!in(0, 0, 0, 2, obj)) throw new RuntimeException("Object is out of octree");

    if (maxDepth != 0) {
      for (int i = 0; i < 2; ++i)
        for (int j = 0; j < 2; ++j)
          for (int k = 0; k < 2; ++k)
            if (in(i, j, k, 1, obj)) {
              if (subtree[i][j][k] == null)
                subtree[i][j][k] = new Octree(xc[i], xc[i + 1], yc[j], yc[j + 1], zc[k], zc[k + 1]);
              subtree[i][j][k].add(obj, maxDepth - 1);
              return;
            }
    }
    // Gstate.counter++;
    container.add(obj);
    //        System.out.println("gstate counter:" + Gstate.counter);
  }
Example #22
0
 @Override
 @SuppressWarnings("unchecked")
 protected final <T> PriorityQueue<T> of(T... elements) {
   return PriorityQueue.ofAll(toStringComparator(), List.of(elements));
 }
Example #23
0
 /**
  * Returns a new Node containing the given value and having the given children.
  *
  * @param value A value
  * @param children The child nodes, possibly empty
  * @param <T> Value type
  * @return A new Node instance.
  */
 @SuppressWarnings("varargs")
 @SafeVarargs
 static <T> Node<T> of(T value, Node<T>... children) {
   Objects.requireNonNull(children, "children is null");
   return new Node<>(value, List.of(children));
 }
Example #24
0
  public void appendMessages(List<AnalyzedMessage> newMessages) {
    if (newMessages.size() == 0) return;

    List<AnalyzedMessage> oldMessages = new ArrayList<>(messages);

    if (messageFilter != null) newMessages = CUtils.filter(newMessages, messageFilter);

    messages.addAll(newMessages);

    List<StyleNode> msgNodes =
        CUtils.map(
            newMessages,
            m -> {
              StyleNode n = builder.buildMessage(m);
              n.updateTree(NStyleUtils.getTemplateManager());
              return n;
            });
    rootMessageStyleNodes.addAll(msgNodes);

    List<StyleNode> appendNodes = new ArrayList<>();
    List<StyleNode> removeNodes = new ArrayList<>();

    if (oldMessages.size() > 0) {
      appendNodes.add(builder.buildTemplate("message_separator"));

      if (newMessages.size() > 0) {
        if (newMessageSeparatorNode != null) removeNodes.add(newMessageSeparatorNode);
        newMessageSeparatorNode = builder.buildTemplate("new_message_separator");
        if (newMessageSeparatorNode != null) appendNodes.add(newMessageSeparatorNode);
      }
    }

    for (int i = 0; i < msgNodes.size(); i++) {
      StyleNode n = msgNodes.get(i);
      appendNodes.add(n);

      if (i < msgNodes.size() - 1) appendNodes.add(builder.buildTemplate("message_separator"));
    }

    if (endMarginTemplateId != null) {
      if (endMarginNode != null) removeNodes.add(endMarginNode);
      endMarginNode = builder.buildTemplate(endMarginTemplateId);
      appendNodes.add(endMarginNode);
    }

    runWithNoRedraw(
        () -> {
          CUtils.forEach(removeNodes, node -> node.getParent().removeChild(node));

          getRootStyleNode().addChildAll(appendNodes);

          try {
            getRootStyleNode().updateTree(NStyleUtils.getTemplateManager());
          } catch (RuntimeException e) {
            DialogUtils.openError(null, "Script error", e.toString());
          }
        });
  }
Example #25
0
  public TeamViewModel() {
    createValidators();

    ListProperty<Person> peopleInOrganisation = new SimpleListProperty<>();
    peopleInOrganisation.bind(
        Bindings.createObjectBinding(
            () -> {
              if (organisationProperty().get() != null) {
                return organisationProperty().get().getPeople();
              } else {
                return FXCollections.observableArrayList();
              }
            },
            organisationProperty()));

    ListProperty<Team> teamsInOrganisation = new SimpleListProperty<>();
    teamsInOrganisation.bind(
        Bindings.createObjectBinding(
            () -> {
              if (organisationProperty().get() != null) {
                return organisationProperty().get().getTeams();
              } else {
                return FXCollections.observableArrayList();
              }
            },
            organisationProperty()));

    ListProperty<Person> peopleInTeams = new SimpleListProperty<>();
    peopleInTeams.bind(
        Bindings.createObjectBinding(
            () -> {
              return teamsInOrganisation
                  .stream()
                  .flatMap(team -> team.observableTeamMembers().stream()) // TODO listen
                  .collect(GoatCollectors.toObservableList());
            },
            teamsInOrganisation));

    eligibleTeamMembers = new SimpleListProperty<>();
    eligibleTeamMembers.bind(
        Bindings.createObjectBinding(
            () -> {
              return peopleInOrganisation
                  .stream()
                  .filter(
                      person ->
                          !peopleInTeams.contains(person) // no team in model
                              || person.getTeam() == modelWrapper.get()) // this team in model
                  .collect(GoatCollectors.toObservableList());
            },
            peopleInOrganisation,
            peopleInTeams));

    eligibleDevs = new SimpleListProperty<>();
    eligibleDevs.bind(
        Bindings.createObjectBinding(
            () -> {
              return teamMembersProperty()
                  .get()
                  .stream() // is in team
                  .filter(
                      person ->
                          !person.equals(productOwnerProperty().get()) // not PO
                              && !person.equals(scrumMasterProperty().get())) // not SM
                  .collect(GoatCollectors.toObservableList());
            },
            teamMembersProperty(),
            productOwnerProperty(),
            scrumMasterProperty()));

    teamMembersProperty()
        .addListener(
            (ListChangeListener.Change<? extends Person> change) -> {
              change.next();
              List<? extends Person> removed = change.getRemoved();
              devTeamProperty().removeAll(removed);
              if (removed.contains(productOwnerProperty().get())) {
                productOwnerProperty().set(null);
              }
              if (removed.contains(scrumMasterProperty().get())) {
                scrumMasterProperty().set(null);
              }
            });
  }
Example #26
0
 public List<Answer> classicFind(Predicate<Answer> pred) {
   List<Answer> results = new ArrayList<Answer>();
   for (Answer answer : answers.values()) if (pred.test(answer)) results.add(answer);
   return results;
 }
Example #27
0
 private List<Annotation> getAnnotationsInternal(List<AnnotationExpr> l) {
   return l.stream()
       .map(AnnotationParser::annotationFromAnnotationExpr)
       .collect(Collectors.toList());
 }
Example #28
0
 @Test
 public void toListIsSortedAccordingToComparator() {
   final Comparator<Integer> comparator = composedComparator();
   final PriorityQueue<Integer> queue = PriorityQueue.ofAll(comparator, values);
   assertThat(queue.toList()).isEqualTo(values.sorted(comparator));
 }
Example #29
0
public class PriorityQueueTest extends AbstractTraversableTest {
  private final List<Integer> values =
      List.of(
          3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4, 6, 2, 6, 4, 3, 3, 8, 3, 2, 7,
          9, 5, 0, 2, 8, 8, 4, 1, 9, 7, 1, 6, 9, 3, 9, 9, 3, 7, 5, 1, 0);

  @Override
  protected <T> Collector<T, ArrayList<T>, PriorityQueue<T>> collector() {
    return PriorityQueue.collector();
  }

  @Override
  protected <T> PriorityQueue<T> empty() {
    return PriorityQueue.empty(toStringComparator());
  }

  @Override
  protected <T> PriorityQueue<T> of(T element) {
    return PriorityQueue.ofAll(toStringComparator(), List.of(element));
  }

  @Override
  @SuppressWarnings("unchecked")
  protected final <T> PriorityQueue<T> of(T... elements) {
    return PriorityQueue.ofAll(toStringComparator(), List.of(elements));
  }

  @Override
  protected <T> PriorityQueue<T> ofAll(Iterable<? extends T> elements) {
    return PriorityQueue.ofAll(toStringComparator(), elements);
  }

  @Override
  protected <T> Traversable<T> ofJavaStream(Stream<? extends T> javaStream) {
    return PriorityQueue.ofAll(toStringComparator(), javaStream);
  }

  @Override
  protected PriorityQueue<Boolean> ofAll(boolean[] array) {
    return PriorityQueue.ofAll(List.ofAll(array));
  }

  @Override
  protected PriorityQueue<Byte> ofAll(byte[] array) {
    return PriorityQueue.ofAll(List.ofAll(array));
  }

  @Override
  protected PriorityQueue<Character> ofAll(char[] array) {
    return PriorityQueue.ofAll(List.ofAll(array));
  }

  @Override
  protected PriorityQueue<Double> ofAll(double[] array) {
    return PriorityQueue.ofAll(List.ofAll(array));
  }

  @Override
  protected PriorityQueue<Float> ofAll(float[] array) {
    return PriorityQueue.ofAll(List.ofAll(array));
  }

  @Override
  protected PriorityQueue<Integer> ofAll(int[] array) {
    return PriorityQueue.ofAll(List.ofAll(array));
  }

  @Override
  protected PriorityQueue<Long> ofAll(long[] array) {
    return PriorityQueue.ofAll(List.ofAll(array));
  }

  @Override
  protected PriorityQueue<Short> ofAll(short[] array) {
    return PriorityQueue.ofAll(List.ofAll(array));
  }

  @Override
  protected <T> PriorityQueue<T> tabulate(int n, Function<? super Integer, ? extends T> f) {
    return PriorityQueue.tabulate(n, f);
  }

  @Override
  protected <T> PriorityQueue<T> fill(int n, Supplier<? extends T> s) {
    return PriorityQueue.fill(n, s);
  }

  @Override
  protected boolean useIsEqualToInsteadOfIsSameAs() {
    return true;
  }

  @Override
  protected int getPeekNonNilPerformingAnAction() {
    return 1;
  }

  @Override
  protected boolean emptyShouldBeSingleton() {
    return false;
  }

  @Override
  protected boolean isOrdered() {
    return true;
  }

  private static SerializableComparator<Object> toStringComparator() {
    return (o1, o2) -> String.valueOf(o1).compareTo(String.valueOf(o2));
  }

  private static Comparator<Integer> composedComparator() {
    final Comparator<Integer> bitCountComparator =
        (o1, o2) -> Integer.compare(bitCount(o1), bitCount(o2));
    return bitCountComparator.thenComparing(naturalComparator());
  }

  @Test
  @Override
  public void shouldScanLeftWithNonComparable() {
    // The resulting type would need a comparator
  }

  @Test
  @Override
  public void shouldScanRightWithNonComparable() {
    // The resulting type would need a comparator
  }

  @Override
  public void shouldPreserveSingletonInstanceOnDeserialization() {
    // The empty PriorityQueue encapsulates a comparator and therefore cannot be a singleton
  }

  // -- static narrow

  @Test
  public void shouldNarrowQueue() {
    final PriorityQueue<Double> doubles = of(1.0d);
    final PriorityQueue<Number> numbers = PriorityQueue.narrow(doubles);
    final int actual = numbers.enqueue(new BigDecimal("2.0")).sum().intValue();
    assertThat(actual).isEqualTo(3);
  }

  // -- toList

  @Test
  public void toListIsSortedAccordingToComparator() {
    final Comparator<Integer> comparator = composedComparator();
    final PriorityQueue<Integer> queue = PriorityQueue.ofAll(comparator, values);
    assertThat(queue.toList()).isEqualTo(values.sorted(comparator));
  }

  // -- merge

  @Test
  public void shouldMergeTwoPriorityQueues() {
    final PriorityQueue<Integer> source = of(3, 1, 4, 1, 5);
    final PriorityQueue<Integer> target = of(9, 2, 6, 5, 3);
    assertThat(source.merge(target)).isEqualTo(of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3));

    assertThat(PriorityQueue.of(3).merge(PriorityQueue.of(toStringComparator(), 1)))
        .isEqualTo(of(3, 1));
  }

  // -- distinct

  @Test
  public void shouldComputeDistinctOfNonEmptyTraversableUsingKeyExtractor() {
    final Comparator<String> comparator = (o1, o2) -> Integer.compare(o1.charAt(1), o2.charAt(1));
    assertThat(
            PriorityQueue.of(comparator, "5c", "1a", "3a", "1a", "2a", "4b", "3b")
                .distinct()
                .map(s -> s.substring(1)))
        .isEqualTo(of("a", "b", "c"));
  }

  // -- removeAll

  @Test
  public void shouldRemoveAllElements() {
    assertThat(of(3, 1, 4, 1, 5, 9, 2, 6).removeAll(of(1, 9, 1, 2))).isEqualTo(of(3, 4, 5, 6));
  }

  // -- enqueueAll

  @Test
  public void shouldEnqueueAllElements() {
    assertThat(of(3, 1, 4).enqueueAll(of(1, 5, 9, 2))).isEqualTo(of(3, 1, 4, 1, 5, 9, 2));
  }

  // -- peek

  @Test(expected = NoSuchElementException.class)
  public void shouldFailPeekOfEmpty() {
    empty().peek();
  }

  // -- dequeue

  @Test
  public void shouldDeque() {
    assertThat(of(3, 1, 4, 1, 5).dequeue()).isEqualTo(Tuple.of(1, of(3, 4, 1, 5)));
  }

  @Test(expected = NoSuchElementException.class)
  public void shouldFailDequeueOfEmpty() {
    empty().dequeue();
  }

  // -- toPriorityQueue

  @Test
  public void shouldKeepInstanceOfPriorityQueue() {
    final PriorityQueue<Integer> queue = PriorityQueue.of(1, 3, 2);
    assertThat(queue.toPriorityQueue()).isSameAs(queue);
  }

  // -- property based tests

  @Test
  public void shouldBehaveExactlyLikeAnotherPriorityQueue() {
    for (int i = 0; i < 10; i++) {
      final Random random = getRandom(-1);

      final java.util.PriorityQueue<Integer> mutablePriorityQueue = new java.util.PriorityQueue<>();
      javaslang.collection.PriorityQueue<Integer> functionalPriorityQueue =
          javaslang.collection.PriorityQueue.empty();

      final int size = 100_000;
      for (int j = 0; j < size; j++) {
        /* Insert */
        if (random.nextInt() % 3 == 0) {
          assertMinimumsAreEqual(mutablePriorityQueue, functionalPriorityQueue);

          final int value = random.nextInt(size) - (size / 2);
          mutablePriorityQueue.add(value);
          functionalPriorityQueue = functionalPriorityQueue.enqueue(value);
        }

        assertMinimumsAreEqual(mutablePriorityQueue, functionalPriorityQueue);

        /* Delete */
        if (random.nextInt() % 5 == 0) {
          if (!mutablePriorityQueue.isEmpty()) {
            mutablePriorityQueue.poll();
          }
          if (!functionalPriorityQueue.isEmpty()) {
            functionalPriorityQueue = functionalPriorityQueue.tail();
          }

          assertMinimumsAreEqual(mutablePriorityQueue, functionalPriorityQueue);
        }
      }

      final Collection<Integer> oldValues =
          mutablePriorityQueue.stream().sorted().collect(toList());
      final Collection<Integer> newValues = functionalPriorityQueue.toJavaList();
      assertThat(oldValues).isEqualTo(newValues);
    }
  }

  private void assertMinimumsAreEqual(
      java.util.PriorityQueue<Integer> oldQueue, PriorityQueue<Integer> newQueue) {
    assertThat(oldQueue.isEmpty()).isEqualTo(newQueue.isEmpty());
    if (!newQueue.isEmpty()) {
      assertThat(oldQueue.peek()).isEqualTo(newQueue.head());
    }
  }
}
Example #30
0
 @Override
 protected <T> PriorityQueue<T> of(T element) {
   return PriorityQueue.ofAll(toStringComparator(), List.of(element));
 }