Search in sources :

Example 6 with UnaryOperator

use of java.util.function.UnaryOperator in project grakn by graknlabs.

the class QueryVisitor method visitPropHas.

@Override
public UnaryOperator<VarPattern> visitPropHas(GraqlParser.PropHasContext ctx) {
    Label type = visitLabel(ctx.label());
    VarPattern relation = Optional.ofNullable(ctx.relation).map(this::getVariable).orElseGet(Graql::var);
    VarPattern resource = Optional.ofNullable(ctx.resource).map(this::getVariable).orElseGet(Graql::var);
    if (ctx.predicate() != null) {
        resource = resource.val(visitPredicate(ctx.predicate()));
    }
    VarPattern finalResource = resource;
    return var -> var.has(type, finalResource, relation);
}
Also used : VarPattern(ai.grakn.graql.VarPattern) Token(org.antlr.v4.runtime.Token) Graql(ai.grakn.graql.Graql) ConnectedComponentQuery(ai.grakn.graql.analytics.ConnectedComponentQuery) UnaryOperator(java.util.function.UnaryOperator) Label(ai.grakn.concept.Label) Map(java.util.Map) ComputeQuery(ai.grakn.graql.ComputeQuery) ConceptId(ai.grakn.concept.ConceptId) Aggregate(ai.grakn.graql.Aggregate) MinQuery(ai.grakn.graql.analytics.MinQuery) Collectors.toSet(java.util.stream.Collectors.toSet) QueryBuilder(ai.grakn.graql.QueryBuilder) MaxQuery(ai.grakn.graql.analytics.MaxQuery) ImmutableSet(com.google.common.collect.ImmutableSet) AggregateQuery(ai.grakn.graql.AggregateQuery) ImmutableMap(com.google.common.collect.ImmutableMap) Graql.eq(ai.grakn.graql.Graql.eq) Collection(java.util.Collection) StringUtil(ai.grakn.util.StringUtil) Set(java.util.Set) ValuePredicate(ai.grakn.graql.ValuePredicate) TerminalNode(org.antlr.v4.runtime.tree.TerminalNode) Match(ai.grakn.graql.Match) List(java.util.List) GraqlParser(ai.grakn.graql.internal.antlr.GraqlParser) Stream(java.util.stream.Stream) LocalDate(java.time.LocalDate) Var(ai.grakn.graql.Var) DefineQuery(ai.grakn.graql.DefineQuery) Optional(java.util.Optional) ParserRuleContext(org.antlr.v4.runtime.ParserRuleContext) DegreeQuery(ai.grakn.graql.analytics.DegreeQuery) DeleteQuery(ai.grakn.graql.DeleteQuery) GraqlBaseVisitor(ai.grakn.graql.internal.antlr.GraqlBaseVisitor) StdQuery(ai.grakn.graql.analytics.StdQuery) InsertQuery(ai.grakn.graql.InsertQuery) LocalDateTime(java.time.LocalDateTime) Function(java.util.function.Function) PathQuery(ai.grakn.graql.analytics.PathQuery) AttributeType(ai.grakn.concept.AttributeType) MeanQuery(ai.grakn.graql.analytics.MeanQuery) CommonUtil(ai.grakn.util.CommonUtil) SumQuery(ai.grakn.graql.analytics.SumQuery) GraqlQueryException(ai.grakn.exception.GraqlQueryException) Graql.label(ai.grakn.graql.Graql.label) GetQuery(ai.grakn.graql.GetQuery) Query(ai.grakn.graql.Query) MedianQuery(ai.grakn.graql.analytics.MedianQuery) Graql.and(ai.grakn.graql.Graql.and) Collectors.toList(java.util.stream.Collectors.toList) Order(ai.grakn.graql.Order) NamedAggregate(ai.grakn.graql.NamedAggregate) DateTimeFormatter(java.time.format.DateTimeFormatter) CountQuery(ai.grakn.graql.analytics.CountQuery) PathsQuery(ai.grakn.graql.analytics.PathsQuery) Pattern(ai.grakn.graql.Pattern) Label(ai.grakn.concept.Label) VarPattern(ai.grakn.graql.VarPattern) Graql(ai.grakn.graql.Graql)

Example 7 with UnaryOperator

use of java.util.function.UnaryOperator in project jdk8u_jdk by JetBrains.

the class SequentialOpTest method testLazy.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class, groups = { "serialization-hostile" })
public void testLazy(String name, TestData.OfRef<Integer> data) {
    Function<Integer, Integer> id = LambdaTestHelpers.identity();
    AtomicInteger counter = new AtomicInteger();
    Supplier<Stream<Integer>>[] suppliers = new Supplier[] { () -> data.stream(), () -> data.parallelStream() };
    UnaryOperator<Stream<Integer>>[] configs = new UnaryOperator[] { (UnaryOperator<Stream<Integer>>) s -> s.peek(e -> {
        counter.incrementAndGet();
    }), (UnaryOperator<Stream<Integer>>) s -> s.map(id).peek(e -> {
        counter.incrementAndGet();
    }).sequential().map(id), (UnaryOperator<Stream<Integer>>) s -> s.map(id).peek(e -> {
        counter.incrementAndGet();
    }).parallel().map(id), (UnaryOperator<Stream<Integer>>) s -> s.sequential().map(id).peek(e -> {
        counter.incrementAndGet();
    }).map(id), (UnaryOperator<Stream<Integer>>) s -> s.parallel().map(id).peek(e -> {
        counter.incrementAndGet();
    }).map(id) };
    for (int i = 0; i < suppliers.length; i++) {
        setContext("supplierIndex", i);
        Supplier<Stream<Integer>> supp = suppliers[i];
        for (int j = 0; j < configs.length; j++) {
            setContext("configIndex", j);
            UnaryOperator<Stream<Integer>> config = configs[j];
            counter.set(0);
            Stream<Integer> stream = config.apply(supp.get());
            assertEquals(0, counter.get());
            Iterator<Integer> iterator = stream.iterator();
            assertEquals(0, counter.get());
            if (iterator.hasNext())
                iterator.next();
            assertTrue(data.size() == 0 || counter.get() > 0);
            counter.set(0);
            stream = config.apply(supp.get());
            Spliterator<Integer> spliterator = stream.spliterator();
            assertEquals(0, counter.get());
            spliterator.forEachRemaining(e -> {
            });
            assertTrue(data.size() == 0 || counter.get() > 0);
        }
    }
}
Also used : Iterator(java.util.Iterator) TestData(java.util.stream.TestData) StreamTestDataProvider(java.util.stream.StreamTestDataProvider) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) UnaryOperator(java.util.function.UnaryOperator) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Stream(java.util.stream.Stream) LambdaTestHelpers(java.util.stream.LambdaTestHelpers) OpTestCase(java.util.stream.OpTestCase) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Assert.assertTrue(org.testng.Assert.assertTrue) Comparator(java.util.Comparator) Spliterator(java.util.Spliterator) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Supplier(java.util.function.Supplier) Stream(java.util.stream.Stream) UnaryOperator(java.util.function.UnaryOperator) Test(org.testng.annotations.Test)

Example 8 with UnaryOperator

use of java.util.function.UnaryOperator in project lucene-solr by apache.

the class JsonLoaderTest method testFewParentsJsonDoc.

public void testFewParentsJsonDoc() throws Exception {
    String json = PARENT_TWO_CHILDREN_JSON;
    SolrQueryRequest req;
    SolrQueryResponse rsp;
    BufferingRequestProcessor p;
    JsonLoader loader;
    {
        //multichild test case
        final boolean array = random().nextBoolean();
        StringBuilder b = new StringBuilder();
        if (array) {
            b.append("[");
        }
        final int passes = atLeast(2);
        for (int i = 1; i <= passes; i++) {
            b.append(json.replace("1", "" + i));
            if (array) {
                b.append(i < passes ? "," : "]");
            }
        }
        req = req(PARENT_TWO_CHILDREN_PARAMS);
        req.getContext().put("path", "/update/json/docs");
        rsp = new SolrQueryResponse();
        p = new BufferingRequestProcessor(null);
        loader = new JsonLoader();
        loader.load(req, rsp, new ContentStreamBase.StringStream(b.toString()), p);
        for (int i = 1; i <= passes; i++) {
            final int ii = i;
            UnaryOperator<String> s = (v) -> v.replace("1", "" + ii);
            final SolrInputDocument parent = p.addCommands.get(i - 1).solrDoc;
            assertOnlyValue(s.apply("1"), parent, "id");
            assertOnlyValue("i am the parent", parent, "name");
            assertOnlyValue("parent", parent, "cat");
            assertEquals(2, parent.getChildDocuments().size());
            {
                final SolrInputDocument child1 = parent.getChildDocuments().get(0);
                assertOnlyValue(s.apply("1.1"), child1, "id");
                assertOnlyValue(s.apply("i am the 1st child"), child1, "name");
                assertOnlyValue("child", child1, "cat");
            }
            {
                final SolrInputDocument child2 = parent.getChildDocuments().get(1);
                assertOnlyValue(s.apply("1.2"), child2, "id");
                assertOnlyValue("i am the 2nd child", child2, "name");
                assertOnlyValue("child", child2, "cat");
                assertEquals(1, child2.getChildDocuments().size());
                final SolrInputDocument grandChild = child2.getChildDocuments().get(0);
                assertOnlyValue(s.apply("1.2.1"), grandChild, "id");
                assertOnlyValue("i am the grandchild", grandChild, "name");
                assertOnlyValue("grandchild", grandChild, "cat");
            }
        }
    }
}
Also used : SolrQueryRequest(org.apache.solr.request.SolrQueryRequest) SolrQueryResponse(org.apache.solr.response.SolrQueryResponse) SolrInputDocument(org.apache.solr.common.SolrInputDocument) BufferingRequestProcessor(org.apache.solr.update.processor.BufferingRequestProcessor) JsonLoader(org.apache.solr.handler.loader.JsonLoader) UnaryOperator(java.util.function.UnaryOperator)

Example 9 with UnaryOperator

use of java.util.function.UnaryOperator in project trex-stateless-gui by cisco-system-traffic-generator.

the class MultiplierOption method buildUI.

/**
     * Build multiplier view UI
     *
     * @param title
     * @param group
     */
private void buildUI(String title, ToggleGroup group) {
    // add radio button
    selection = new RadioButton(title);
    selection.setToggleGroup(group);
    selection.selectedProperty().addListener((ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
        if (newValue) {
            multiplierSelectionEvent.onMultiplierSelect(type);
        }
        value.setDisable(!newValue);
    });
    setTooltip();
    getChildren().add(selection);
    MultiplierOption.setTopAnchor(selection, 15d);
    MultiplierOption.setLeftAnchor(selection, 0d);
    // text field
    value = new TextField();
    value.setPrefSize(120, 22);
    value.setDisable(true);
    value.addEventFilter(KeyEvent.KEY_RELEASED, multiplierSelectionEvent.validateInput());
    String regex = unitRegex();
    final UnaryOperator<TextFormatter.Change> keyPressFilter = c -> {
        String text = c.getControlNewText();
        if (text.matches(regex)) {
            return c;
        } else {
            return null;
        }
    };
    value.setTextFormatter(new TextFormatter<>(keyPressFilter));
    getChildren().add(value);
    MultiplierOption.setTopAnchor(value, 43d);
    MultiplierOption.setLeftAnchor(value, 0d);
    MultiplierOption.setBottomAnchor(value, 15d);
}
Also used : TextField(javafx.scene.control.TextField) MultiplierType(com.exalttech.trex.ui.MultiplierType) Util(com.exalttech.trex.util.Util) UnaryOperator(java.util.function.UnaryOperator) KeyEvent(javafx.scene.input.KeyEvent) TextFormatter(javafx.scene.control.TextFormatter) Logger(org.apache.log4j.Logger) ToggleGroup(javafx.scene.control.ToggleGroup) AnchorPane(javafx.scene.layout.AnchorPane) RadioButton(javafx.scene.control.RadioButton) ObservableValue(javafx.beans.value.ObservableValue) MultiplierSelectionEvent(com.exalttech.trex.ui.components.events.MultiplierSelectionEvent) Tooltip(javafx.scene.control.Tooltip) ObservableValue(javafx.beans.value.ObservableValue) TextField(javafx.scene.control.TextField) RadioButton(javafx.scene.control.RadioButton)

Example 10 with UnaryOperator

use of java.util.function.UnaryOperator in project algorithms by Iurii-Dziuban.

the class DefaultAndStaticInInterface method testDatePlusStream.

// --- End of Question 17.
// Java 8 certification Question 18.
/**
 * Which of the following statements can fill in the blank to make the code compile successfully? (Choose all that apply.)
 *
 *     Set[? extends RuntimeException] set = VALUE
 *
 *     A. new HashSet[? extends RuntimeException]();
 *     B. new HashSet<Exception>();
 *     C. new TreeSet<RuntimeException>();
 *     D. new TreeSet<NullPointerException>();
 *     E. None of the above
 *
 *     Answer: C,D . A is not possible on the right side of expression.
 *     B is not possible, cause Exception is higher in hierarchy
 */
// --- End of Question 18.
// Java 8 certification Question 19.
/**
 * Which of the following position a ResultSet cursor to a location immediately before the
 *     first row? (Choose all that apply.)
 *     A. rs.absolute(-1)
 *     B. rs.absolute(0)
 *     C. rs.absolute(1)
 *     D. rs.beforeFirst()
 *     E. rs.first()
 *     F. rs.next()
 *
 *     Answer: B, D. On scrollable ResultSet absolute -1 -> end row, 0 -> before first row, 1 -> the first row
 *     beforeFirst() is equivalent method
 */
// --- End of Question 19.
// Java 8 certification Question 20.
/**
 * Assume that today is June 1, 2016. What is the result of the following?
 */
@Test
public void testDatePlusStream() {
    LocalDate localDate = LocalDate.of(2016, 6, 1);
    Stream<LocalDate> s = Stream.of(localDate);
    UnaryOperator<LocalDate> u = l -> l;
    s.filter(l -> l != null).map(u).peek(System.out::println);
    assertThat(Stream.of(localDate).filter(l -> l != null).map(u).collect(Collectors.toList()).get(0)).isEqualTo(localDate);
}
Also used : NoSuchFileException(java.nio.file.NoSuchFileException) Arrays(java.util.Arrays) BufferedInputStream(java.io.BufferedInputStream) Connection(java.sql.Connection) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ObjectInputStream(java.io.ObjectInputStream) UnaryOperator(java.util.function.UnaryOperator) Function(java.util.function.Function) ArrayList(java.util.ArrayList) SQLException(java.sql.SQLException) Duration(java.time.Duration) Console(java.io.Console) Path(java.nio.file.Path) Period(java.time.Period) Files(java.nio.file.Files) Predicate(java.util.function.Predicate) Set(java.util.Set) Test(org.junit.Test) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Collectors(java.util.stream.Collectors) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) Serializable(java.io.Serializable) List(java.util.List) IntToLongFunction(java.util.function.IntToLongFunction) Stream(java.util.stream.Stream) ConcurrentSkipListSet(java.util.concurrent.ConcurrentSkipListSet) Paths(java.nio.file.Paths) LocalDate(java.time.LocalDate) Statement(java.sql.Statement) Optional(java.util.Optional) Comparator(java.util.Comparator) Collections(java.util.Collections) ConcurrentModificationException(java.util.ConcurrentModificationException) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) LocalDate(java.time.LocalDate) Test(org.junit.Test)

Aggregations

UnaryOperator (java.util.function.UnaryOperator)10 List (java.util.List)6 Function (java.util.function.Function)6 Stream (java.util.stream.Stream)6 Arrays (java.util.Arrays)5 Comparator (java.util.Comparator)5 Spliterator (java.util.Spliterator)4 Set (java.util.Set)3 Consumer (java.util.function.Consumer)3 DoubleConsumer (java.util.function.DoubleConsumer)3 IntConsumer (java.util.function.IntConsumer)3 LongConsumer (java.util.function.LongConsumer)3 DoubleStream (java.util.stream.DoubleStream)3 DoubleStreamTestDataProvider (java.util.stream.DoubleStreamTestDataProvider)3 IntStream (java.util.stream.IntStream)3 IntStreamTestDataProvider (java.util.stream.IntStreamTestDataProvider)3 LambdaTestHelpers (java.util.stream.LambdaTestHelpers)3 LambdaTestHelpers.countTo (java.util.stream.LambdaTestHelpers.countTo)3 LambdaTestHelpers.dpEven (java.util.stream.LambdaTestHelpers.dpEven)3 LambdaTestHelpers.ipEven (java.util.stream.LambdaTestHelpers.ipEven)3