Context:
# -*- coding: utf-8 -*-
"""Maximum flow algorithms test suite.
"""
from nose.tools import *

import networkx as nx
from networkx.algorithms.flow import build_flow_dict, build_residual_network
from networkx.algorithms.flow import (edmonds_karp, ford_fulkerson,
    preflow_push, shortest_augmenting_path)

flow_funcs = [edmonds_karp, ford_fulkerson, preflow_push,
              shortest_augmenting_path]
max_min_funcs = [nx.maximum_flow, nx.minimum_cut]
flow_value_funcs = [nx.maximum_flow_value, nx.minimum_cut_value]
interface_funcs = sum([max_min_funcs, flow_value_funcs], [])
all_funcs = sum([flow_funcs, interface_funcs], [])

msg = "Assertion failed in function: {0}"
msgi = "Assertion failed in function: {0} in interface {1}"

def compute_cutset(G, partition):
    reachable, non_reachable = partition
    cutset = set()
    for u, nbrs in ((n, G[n]) for n in reachable):
        cutset.update((u, v) for v in nbrs if v in non_reachable)
    return cutset

def validate_flows(G, s, t, flowDict, solnValue, capacity, flow_func):
    assert_equal(set(G), set(flowDict), msg=msg.format(flow_func.__name__))
    for u in G:
        assert_equal(set(G[u]), set(flowDict[u]),
                     msg=msg.format(flow_func.__name__))
    excess = dict((u, 0) for u in flowDict)
    for u in flowDict:
        for v, flow in flowDict[u].items():
            if capacity in G[u][v]:
                ok_(flow <= G[u][v][capacity])
            ok_(flow >= 0, msg=msg.format(flow_func.__name__))
            excess[u] -= flow
            excess[v] += flow
    for u, exc in excess.items():
        if u == s:
            assert_equal(exc, -solnValue, msg=msg.format(flow_func.__name__))
        elif u == t:
            assert_equal(exc, solnValue, msg=msg.format(flow_func.__name__))
        else:
            assert_equal(exc, 0, msg=msg.format(flow_func.__name__))

def validate_cuts(G, s, t, solnValue, partition, capacity, flow_func):
    assert_true(all(n in G for n in partition[0]),
                msg=msg.format(flow_func.__name__))
    assert_true(all(n in G for n in partition[1]),
                msg=msg.format(flow_func.__name__))
    cutset = compute_cutset(G, partition)
    assert_true(all(G.has_edge(u, v) for (u, v) in cutset),
                msg=msg.format(flow_func.__name__))
    assert_equal(solnValue, sum(G[u][v][capacity] for (u, v) in cutset),
                msg=msg.format(flow_func.__name__))
    H = G.copy()
    H.remove_edges_from(cutset)
    if not G.is_directed():
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
    else:
        assert_false(nx.is_strongly_connected(H),
                     msg=msg.format(flow_func.__name__))

def compare_flows_and_cuts(G, s, t, solnFlows, solnValue, capacity='capacity'):
    for flow_func in flow_funcs:
        R = flow_func(G, s, t, capacity)
        # Test both legacy and new implementations.
        legacy = R.graph.get('algorithm') == "ford_fulkerson_legacy"
        flow_value = R.graph['flow_value']
        if legacy:
            flow_dict = R.graph['flow_dict']
        else:
            flow_dict = build_flow_dict(G, R)
        assert_equal(flow_value, solnValue, msg=msg.format(flow_func.__name__))
        if legacy:
            assert_equal(flow_dict, solnFlows, msg=msg.format(flow_func.__name__))
        else:
            validate_flows(G, s, t, flow_dict, solnValue, capacity, flow_func)
        # Minimum cut
        if legacy:
            cut_value, partition = nx.minimum_cut(G, s, t,  capacity=capacity,
                                                  flow_func=ford_fulkerson)
        else:
            cut_value, partition = nx.minimum_cut(G, s, t, capacity=capacity,
                                                  flow_func=flow_func)
        validate_cuts(G, s, t, solnValue, partition, capacity, flow_func)

class TestMaxflowMinCutCommon:

    def test_graph1(self):
        # Trivial undirected graph
        G = nx.Graph()
        G.add_edge(1,2, capacity = 1.0)

        solnFlows = {1: {2: 1.0},
                     2: {1: 1.0}}

        compare_flows_and_cuts(G, 1, 2, solnFlows, 1.0)

    def test_graph2(self):
        # A more complex undirected graph
        # adapted from www.topcoder.com/tc?module=Statc&d1=tutorials&d2=maxFlow
        G = nx.Graph()
        G.add_edge('x','a', capacity = 3.0)
        G.add_edge('x','b', capacity = 1.0)
        G.add_edge('a','c', capacity = 3.0)
        G.add_edge('b','c', capacity = 5.0)
        G.add_edge('b','d', capacity = 4.0)
        G.add_edge('d','e', capacity = 2.0)
        G.add_edge('c','y', capacity = 2.0)
        G.add_edge('e','y', capacity = 3.0)

        H = {'x': {'a': 3, 'b': 1},
             'a': {'c': 3, 'x': 3},
             'b': {'c': 1, 'd': 2, 'x': 1},
             'c': {'a': 3, 'b': 1, 'y': 2},
             'd': {'b': 2, 'e': 2},
             'e': {'d': 2, 'y': 2},
             'y': {'c': 2, 'e': 2}}

        compare_flows_and_cuts(G, 'x', 'y', H, 4.0)

    def test_digraph1(self):
        # The classic directed graph example
        G = nx.DiGraph()
        G.add_edge('a','b', capacity = 1000.0)
        G.add_edge('a','c', capacity = 1000.0)
        G.add_edge('b','c', capacity = 1.0)
        G.add_edge('b','d', capacity = 1000.0)
        G.add_edge('c','d', capacity = 1000.0)

        H = {'a': {'b': 1000.0, 'c': 1000.0},
             'b': {'c': 0, 'd': 1000.0},
             'c': {'d': 1000.0},
             'd': {}}

        compare_flows_and_cuts(G, 'a', 'd', H, 2000.0)

    def test_digraph2(self):
        # An example in which some edges end up with zero flow.
        G = nx.DiGraph()
        G.add_edge('s', 'b', capacity = 2)
        G.add_edge('s', 'c', capacity = 1)
        G.add_edge('c', 'd', capacity = 1)
        G.add_edge('d', 'a', capacity = 1)
        G.add_edge('b', 'a', capacity = 2)
        G.add_edge('a', 't', capacity = 2)

        H = {'s': {'b': 2, 'c': 0},
             'c': {'d': 0},
             'd': {'a': 0},
             'b': {'a': 2},
             'a': {'t': 2},
             't': {}}

        compare_flows_and_cuts(G, 's', 't', H, 2)

    def test_digraph3(self):
        # A directed graph example from Cormen et al.
        G = nx.DiGraph()
        G.add_edge('s','v1', capacity = 16.0)
        G.add_edge('s','v2', capacity = 13.0)
        G.add_edge('v1','v2', capacity = 10.0)
        G.add_edge('v2','v1', capacity = 4.0)
        G.add_edge('v1','v3', capacity = 12.0)
        G.add_edge('v3','v2', capacity = 9.0)
        G.add_edge('v2','v4', capacity = 14.0)
        G.add_edge('v4','v3', capacity = 7.0)
        G.add_edge('v3','t', capacity = 20.0)
        G.add_edge('v4','t', capacity = 4.0)

        H = {'s': {'v1': 12.0, 'v2': 11.0},
             'v2': {'v1': 0, 'v4': 11.0},
             'v1': {'v2': 0, 'v3': 12.0},
             'v3': {'v2': 0, 't': 19.0},
             'v4': {'v3': 7.0, 't': 4.0},
             't': {}}

        compare_flows_and_cuts(G, 's', 't', H, 23.0)

    def test_digraph4(self):
        # A more complex directed graph
        # from www.topcoder.com/tc?module=Statc&d1=tutorials&d2=maxFlow
        G = nx.DiGraph()
        G.add_edge('x','a', capacity = 3.0)
        G.add_edge('x','b', capacity = 1.0)
        G.add_edge('a','c', capacity = 3.0)
        G.add_edge('b','c', capacity = 5.0)
        G.add_edge('b','d', capacity = 4.0)
        G.add_edge('d','e', capacity = 2.0)
        G.add_edge('c','y', capacity = 2.0)
        G.add_edge('e','y', capacity = 3.0)

        H = {'x': {'a': 2.0, 'b': 1.0},
             'a': {'c': 2.0},
             'b': {'c': 0, 'd': 1.0},
             'c': {'y': 2.0},
             'd': {'e': 1.0},
             'e': {'y': 1.0},
             'y': {}}

        compare_flows_and_cuts(G, 'x', 'y', H, 3.0)

    def test_optional_capacity(self):
        # Test optional capacity parameter.
        G = nx.DiGraph()
        G.add_edge('x','a', spam = 3.0)
        G.add_edge('x','b', spam = 1.0)
        G.add_edge('a','c', spam = 3.0)
        G.add_edge('b','c', spam = 5.0)
        G.add_edge('b','d', spam = 4.0)
        G.add_edge('d','e', spam = 2.0)
        G.add_edge('c','y', spam = 2.0)
        G.add_edge('e','y', spam = 3.0)

        solnFlows = {'x': {'a': 2.0, 'b': 1.0},
                     'a': {'c': 2.0},
                     'b': {'c': 0, 'd': 1.0},
                     'c': {'y': 2.0},
                     'd': {'e': 1.0},
                     'e': {'y': 1.0},
                     'y': {}}
        solnValue = 3.0
        s = 'x'
        t = 'y'

        compare_flows_and_cuts(G, s, t, solnFlows, solnValue, capacity = 'spam')

    def test_digraph_infcap_edges(self):
        # DiGraph with infinite capacity edges
        G = nx.DiGraph()
        G.add_edge('s', 'a')
        G.add_edge('s', 'b', capacity = 30)
        G.add_edge('a', 'c', capacity = 25)
        G.add_edge('b', 'c', capacity = 12)
        G.add_edge('a', 't', capacity = 60)
        G.add_edge('c', 't')

        H = {'s': {'a': 85, 'b': 12},
             'a': {'c': 25, 't': 60},
             'b': {'c': 12},
             'c': {'t': 37},
             't': {}}

        compare_flows_and_cuts(G, 's', 't', H, 97)

        # DiGraph with infinite capacity digon
        G = nx.DiGraph()
        G.add_edge('s', 'a', capacity = 85)
        G.add_edge('s', 'b', capacity = 30)
        G.add_edge('a', 'c')
        G.add_edge('c', 'a')
        G.add_edge('b', 'c', capacity = 12)
        G.add_edge('a', 't', capacity = 60)
        G.add_edge('c', 't', capacity = 37)

        H = {'s': {'a': 85, 'b': 12},
             'a': {'c': 25, 't': 60},
             'c': {'a': 0, 't': 37},
             'b': {'c': 12},
             't': {}}

        compare_flows_and_cuts(G, 's', 't', H, 97)

    def test_digraph_infcap_path(self):
        # Graph with infinite capacity (s, t)-path
        G = nx.DiGraph()
        G.add_edge('s', 'a')
        G.add_edge('s', 'b', capacity = 30)
        G.add_edge('a', 'c')
        G.add_edge('b', 'c', capacity = 12)
        G.add_edge('a', 't', capacity = 60)
        G.add_edge('c', 't')

        for flow_func in all_funcs:
            assert_raises(nx.NetworkXUnbounded,
                          flow_func, G, 's', 't')

    def test_graph_infcap_edges(self):
        # Undirected graph with infinite capacity edges
        G = nx.Graph()
        G.add_edge('s', 'a')
        G.add_edge('s', 'b', capacity = 30)
        G.add_edge('a', 'c', capacity = 25)
        G.add_edge('b', 'c', capacity = 12)
        G.add_edge('a', 't', capacity = 60)
        G.add_edge('c', 't')

        H = {'s': {'a': 85, 'b': 12},
             'a': {'c': 25, 's': 85, 't': 60},
             'b': {'c': 12, 's': 12},
             'c': {'a': 25, 'b': 12, 't': 37},
             't': {'a': 60, 'c': 37}}

        compare_flows_and_cuts(G, 's', 't', H, 97)

    def test_digraph4(self):
        # From ticket #429 by mfrasca.
        G = nx.DiGraph()
        G.add_edge('s', 'a', capacity = 2)
        G.add_edge('s', 'b', capacity = 2)
        G.add_edge('a', 'b', capacity = 5)
        G.add_edge('a', 't', capacity = 1)
        G.add_edge('b', 'a', capacity = 1)
        G.add_edge('b', 't', capacity = 3)
        flowSoln = {'a': {'b': 1, 't': 1},
                    'b': {'a': 0, 't': 3},
                    's': {'a': 2, 'b': 2},
                    't': {}}
        compare_flows_and_cuts(G, 's', 't', flowSoln, 4)

    def test_disconnected(self):
        G = nx.Graph()
        G.add_weighted_edges_from([(0,1,1),(1,2,1),(2,3,1)],weight='capacity')
        G.remove_node(1)
        assert_equal(nx.maximum_flow_value(G,0,3), 0)
        flowSoln = {0: {}, 2: {3: 0}, 3: {2: 0}}
        compare_flows_and_cuts(G, 0, 3, flowSoln, 0)

    def test_source_target_not_in_graph(self):
        G = nx.Graph()
        G.add_weighted_edges_from([(0,1,1),(1,2,1),(2,3,1)],weight='capacity')
        G.remove_node(0)
        for flow_func in all_funcs:
            assert_raises(nx.NetworkXError, flow_func, G, 0, 3)
        G.add_weighted_edges_from([(0,1,1),(1,2,1),(2,3,1)],weight='capacity')
        G.remove_node(3)
        for flow_func in all_funcs:
            assert_raises(nx.NetworkXError, flow_func, G, 0, 3)

    def test_source_target_coincide(self):
        G = nx.Graph()
        G.add_node(0)
        for flow_func in all_funcs:
            assert_raises(nx.NetworkXError, flow_func, G, 0, 0)

    def test_multigraphs_raise(self):
        G = nx.MultiGraph()
        M = nx.MultiDiGraph()
        G.add_edges_from([(0, 1), (1, 0)], capacity=True)
        for flow_func in all_funcs:
            assert_raises(nx.NetworkXError, flow_func, G, 0, 0)

class TestMaxFlowMinCutInterface:

    def setup(self):
        G = nx.DiGraph()
        G.add_edge('x','a', capacity = 3.0)
        G.add_edge('x','b', capacity = 1.0)

Answer: G.add_edge('a','c', capacity = 3.0)

<think>
In the TestMaxFlowMinCutInterface.setup method, they start building a directed graph by adding edges. After adding the edge ('x','b'), the next logical step is to continue defining the graph, matching the earlier example that includes edge ('a','c') with capacity 3.0. Therefore the next line should add that edge.
</think>
G.add_edge('a','c', capacity = 3.0)


Context:
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.rya.indexing.pcj.fluo.integration;

import static java.util.Objects.requireNonNull;
import static org.junit.Assert.assertEquals;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.rya.indexing.pcj.fluo.KafkaExportITBase;
import org.apache.rya.indexing.pcj.storage.accumulo.VariableOrder;
import org.apache.rya.indexing.pcj.storage.accumulo.VisibilityBindingSet;
import org.junit.Test;
import org.openrdf.model.Statement;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.model.vocabulary.XMLSchema;
import org.openrdf.query.BindingSet;
import org.openrdf.query.impl.MapBindingSet;

import com.google.common.collect.Sets;

/**
 * Performs integration tests over the Fluo application geared towards Kafka PCJ exporting.
 * <p>
 * These tests might be ignored so that they will not run as unit tests while building the application.
 * Run this test from Maven command line:
 * $ cd rya/extras/rya.pcj.fluo/pcj.fluo.integration
 * $ mvn surefire:test -Dtest=KafkaExportIT
 */
public class KafkaExportIT extends KafkaExportITBase {

    @Test
    public void newResultsExportedTest() throws Exception {
        final String sparql =
                "SELECT ?customer ?worker ?city { " +
                    "FILTER(?customer = <http://Alice>) " +
                    "FILTER(?city = <http://London>) " +
                    "?customer <http://talksTo> ?worker. " +
                    "?worker <http://livesIn> ?city. " +
                    "?worker <http://worksAt> <http://Chipotle>. " +
                "}";

        // Triples that will be streamed into Fluo after the PCJ has been created.
        final ValueFactory vf = new ValueFactoryImpl();
        final Collection<Statement> statements =
                Sets.newHashSet(
                        vf.createStatement(vf.createURI("http://Alice"), vf.createURI("http://talksTo"), vf.createURI("http://Bob")),
                        vf.createStatement(vf.createURI("http://Bob"), vf.createURI("http://livesIn"), vf.createURI("http://London")),
                        vf.createStatement(vf.createURI("http://Bob"), vf.createURI("http://worksAt"), vf.createURI("http://Chipotle")),
                        vf.createStatement(vf.createURI("http://Alice"), vf.createURI("http://talksTo"), vf.createURI("http://Charlie")),
                        vf.createStatement(vf.createURI("http://Charlie"), vf.createURI("http://livesIn"), vf.createURI("http://London")),
                        vf.createStatement(vf.createURI("http://Charlie"), vf.createURI("http://worksAt"), vf.createURI("http://Chipotle")),
                        vf.createStatement(vf.createURI("http://Alice"), vf.createURI("http://talksTo"), vf.createURI("http://David")),
                        vf.createStatement(vf.createURI("http://David"), vf.createURI("http://livesIn"), vf.createURI("http://London")),
                        vf.createStatement(vf.createURI("http://David"), vf.createURI("http://worksAt"), vf.createURI("http://Chipotle")),
                        vf.createStatement(vf.createURI("http://Alice"), vf.createURI("http://talksTo"), vf.createURI("http://Eve")),
                        vf.createStatement(vf.createURI("http://Eve"), vf.createURI("http://livesIn"), vf.createURI("http://Leeds")),
                        vf.createStatement(vf.createURI("http://Eve"), vf.createURI("http://worksAt"), vf.createURI("http://Chipotle")),
                        vf.createStatement(vf.createURI("http://Frank"), vf.createURI("http://talksTo"), vf.createURI("http://Alice")),
                        vf.createStatement(vf.createURI("http://Frank"), vf.createURI("http://livesIn"), vf.createURI("http://London")),
                        vf.createStatement(vf.createURI("http://Frank"), vf.createURI("http://worksAt"), vf.createURI("http://Chipotle")));

        // Create the PCJ in Fluo and load the statements into Rya.
        final String pcjId = loadData(sparql, statements);

        // The expected results of the SPARQL query once the PCJ has been computed.
        final Set<BindingSet> expectedResult = new HashSet<>();

        MapBindingSet bs = new MapBindingSet();
        bs.addBinding("customer", vf.createURI("http://Alice"));
        bs.addBinding("worker", vf.createURI("http://Bob"));
        bs.addBinding("city", vf.createURI("http://London"));
        expectedResult.add( new VisibilityBindingSet(bs) );

        bs = new MapBindingSet();
        bs.addBinding("customer", vf.createURI("http://Alice"));
        bs.addBinding("worker", vf.createURI("http://Charlie"));
        bs.addBinding("city", vf.createURI("http://London"));
        expectedResult.add( new VisibilityBindingSet(bs) );

        bs = new MapBindingSet();
        bs.addBinding("customer", vf.createURI("http://Alice"));
        bs.addBinding("worker", vf.createURI("http://David"));
        bs.addBinding("city", vf.createURI("http://London"));
        expectedResult.add( new VisibilityBindingSet(bs) );

        // Ensure the last result matches the expected result.
        final Set<VisibilityBindingSet> result = readAllResults(pcjId);
        assertEquals(expectedResult, result);
    }

    @Test
    public void min() throws Exception {
        // A query that finds the minimum price for an item within the inventory.
        final String sparql =
                "SELECT (min(?price) as ?minPrice) { " +
                    "?item <urn:price> ?price . " +
                "}";

        // Create the Statements that will be loaded into Rya.
        final ValueFactory vf = new ValueFactoryImpl();
        final Collection<Statement> statements = Sets.newHashSet(
                vf.createStatement(vf.createURI("urn:apple"), vf.createURI("urn:price"), vf.createLiteral(2.50)),
                vf.createStatement(vf.createURI("urn:gum"), vf.createURI("urn:price"), vf.createLiteral(0.99)),
                vf.createStatement(vf.createURI("urn:sandwich"), vf.createURI("urn:price"), vf.createLiteral(4.99)));

        // Create the PCJ in Fluo and load the statements into Rya.
        final String pcjId = loadData(sparql, statements);

        // Create the expected results of the SPARQL query once the PCJ has been computed.
        final MapBindingSet expectedResult = new MapBindingSet();
        expectedResult.addBinding("minPrice", vf.createLiteral(0.99));

        // Ensure the last result matches the expected result.
        final VisibilityBindingSet result = readLastResult(pcjId);
        assertEquals(expectedResult, result);
    }

    @Test
    public void max() throws Exception {
        // A query that finds the maximum price for an item within the inventory.
        final String sparql =
                "SELECT (max(?price) as ?maxPrice) { " +
                    "?item <urn:price> ?price . " +
                "}";

        // Create the Statements that will be loaded into Rya.
        final ValueFactory vf = new ValueFactoryImpl();
        final Collection<Statement> statements = Sets.newHashSet(
                vf.createStatement(vf.createURI("urn:apple"), vf.createURI("urn:price"), vf.createLiteral(2.50)),
                vf.createStatement(vf.createURI("urn:gum"), vf.createURI("urn:price"), vf.createLiteral(0.99)),
                vf.createStatement(vf.createURI("urn:sandwich"), vf.createURI("urn:price"), vf.createLiteral(4.99)));

        // Create the PCJ in Fluo and load the statements into Rya.
        final String pcjId = loadData(sparql, statements);

        // Create the expected results of the SPARQL query once the PCJ has been computed.
        final MapBindingSet expectedResult = new MapBindingSet();
        expectedResult.addBinding("maxPrice", vf.createLiteral(4.99));

        // Ensure the last result matches the expected result.
        final VisibilityBindingSet result = readLastResult(pcjId);
        assertEquals(expectedResult, result);
    }

    @Test
    public void count() throws Exception {
        // A query that counts the number of unique items that are in the inventory.
        final String sparql =
                "SELECT (count(?item) as ?itemCount) { " +
                    "?item <urn:id> ?id . " +
                "}";

        // Create the Statements that will be loaded into Rya.
        final ValueFactory vf = new ValueFactoryImpl();
        final Collection<Statement> statements = Sets.newHashSet(
                // Three that are part of the count.
                vf.createStatement(vf.createURI("urn:apple"), vf.createURI("urn:id"), vf.createLiteral(UUID.randomUUID().toString())),
                vf.createStatement(vf.createURI("urn:gum"), vf.createURI("urn:id"), vf.createLiteral(UUID.randomUUID().toString())),
                vf.createStatement(vf.createURI("urn:sandwich"), vf.createURI("urn:id"), vf.createLiteral(UUID.randomUUID().toString())),

                // One that is not.
                vf.createStatement(vf.createURI("urn:sandwich"), vf.createURI("urn:price"), vf.createLiteral(3.99)));

        // Create the PCJ in Fluo and load the statements into Rya.
        final String pcjId = loadData(sparql, statements);

        // Create the expected results of the SPARQL query once the PCJ has been computed.
        final MapBindingSet expectedResult = new MapBindingSet();
        expectedResult.addBinding("itemCount", vf.createLiteral("3", XMLSchema.INTEGER));

        // Ensure the last result matches the expected result.
        final VisibilityBindingSet result = readLastResult(pcjId);
        assertEquals(expectedResult, result);
    }

    @Test
    public void sum() throws Exception {
        // A query that sums the counts of all of the items that are in the inventory.
        final String sparql =
                "SELECT (sum(?count) as ?itemSum) { " +
                    "?item <urn:count> ?count . " +
                "}";

        // Create the Statements that will be loaded into Rya.
        final ValueFactory vf = new ValueFactoryImpl();
        final Collection<Statement> statements = Sets.newHashSet(
                vf.createStatement(vf.createURI("urn:apple"), vf.createURI("urn:count"), vf.createLiteral(5)),
                vf.createStatement(vf.createURI("urn:gum"), vf.createURI("urn:count"), vf.createLiteral(7)),
                vf.createStatement(vf.createURI("urn:sandwich"), vf.createURI("urn:count"), vf.createLiteral(2)));

        // Create the PCJ in Fluo and load the statements into Rya.
        final String pcjId = loadData(sparql, statements);

        // Create the expected results of the SPARQL query once the PCJ has been computed.
        final MapBindingSet expectedResult = new MapBindingSet();
        expectedResult.addBinding("itemSum", vf.createLiteral("14", XMLSchema.INTEGER));

        // Ensure the last result matches the expected result.
        final VisibilityBindingSet result = readLastResult(pcjId);
        assertEquals(expectedResult, result);
    }

    @Test
    public void average() throws Exception  {
        // A query that finds the average price for an item that is in the inventory.
        final String sparql =
                "SELECT (avg(?price) as ?averagePrice) { " +
                    "?item <urn:price> ?price . " +
                "}";

        // Create the Statements that will be loaded into Rya.
        final ValueFactory vf = new ValueFactoryImpl();
        final Collection<Statement> statements = Sets.newHashSet(
                vf.createStatement(vf.createURI("urn:apple"), vf.createURI("urn:price"), vf.createLiteral(3)),
                vf.createStatement(vf.createURI("urn:gum"), vf.createURI("urn:price"), vf.createLiteral(4)),
                vf.createStatement(vf.createURI("urn:sandwich"), vf.createURI("urn:price"), vf.createLiteral(8)));

        // Create the PCJ in Fluo and load the statements into Rya.
        final String pcjId = loadData(sparql, statements);

        // Create the expected results of the SPARQL query once the PCJ has been computed.
        final MapBindingSet expectedResult = new MapBindingSet();
        expectedResult.addBinding("averagePrice", vf.createLiteral("5", XMLSchema.DECIMAL));

        // Ensure the last result matches the expected result.
        final VisibilityBindingSet result = readLastResult(pcjId);
        assertEquals(expectedResult, result);
    }

    @Test
    public void aggregateWithFilter() throws Exception {
        // A query that filters results from a statement pattern before applying the aggregation function.
        final String sparql =
                "SELECT (min(?price) as ?minPrice) { " +
                    "FILTER(?price > 1.00) " +
                    "?item <urn:price> ?price . " +
                "}";

        // Create the Statements that will be loaded into Rya.
        final ValueFactory vf = new ValueFactoryImpl();
        final Collection<Statement> statements = Sets.newHashSet(
                vf.createStatement(vf.createURI("urn:apple"), vf.createURI("urn:price"), vf.createLiteral(2.50)),
                vf.createStatement(vf.createURI("urn:gum"), vf.createURI("urn:price"), vf.createLiteral(0.99)),
                vf.createStatement(vf.createURI("urn:sandwich"), vf.createURI("urn:price"), vf.createLiteral(4.99)));

        // Create the PCJ in Fluo and load the statements into Rya.
        final String pcjId = loadData(sparql, statements);

        // Create the expected results of the SPARQL query once the PCJ has been computed.
        final MapBindingSet expectedResult = new MapBindingSet();
        expectedResult.addBinding("minPrice", vf.createLiteral(2.50));

        // Ensure the last result matches the expected result.
        final VisibilityBindingSet result = readLastResult(pcjId);
        assertEquals(expectedResult, result);
    }

    @Test
    public void multipleAggregations() throws Exception {
        // A query that both counts the number of items being averaged and finds the average price.
        final String sparql =
                "SELECT (count(?item) as ?itemCount) (avg(?price) as ?averagePrice) {" +
                    "?item <urn:price> ?price . " +
                "}";

        // Create the Statements that will be loaded into Rya.
        final ValueFactory vf = new ValueFactoryImpl();

Answer: final Collection<Statement> statements = Sets.newHashSet(

<think>
The method is defining a test for multiple aggregations. Following the pattern of earlier tests, after creating the ValueFactory instance the next step is to define the collection of RDF statements to load. The code uses Guava's Sets.newHashSet to create the collection, so the next line should declare the statements variable with that call.
</think>
final Collection<Statement> statements = Sets.newHashSet(


Context:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;

namespace Microsoft.Azure.Management.Compute.Fluent
{
    /// <summary>
    /// Compute resource sku names.
    /// </summary>
    ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuQ29tcHV0ZVNrdU5hbWU=
    public partial class ComputeSkuName : ExpandableStringEnum<Microsoft.Azure.Management.Compute.Fluent.ComputeSkuName>, IBeta
    {
        /**
         * Static value Standard_F32s_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardF32sv2 = Parse("Standard_F32s_v2");
        /**
         * Static value Standard_DS2_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardDS2v2 = Parse("Standard_DS2_v2");
        /**
         * Static value Standard_H16r for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardH16r = Parse("Standard_H16r");
        /**
         * Static value Standard_H16m for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardH16m = Parse("Standard_H16m");
        /**
         * Static value Standard_D1 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD1 = Parse("Standard_D1");
        /**
         * Static value Standard_F16s_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardF16sv2 = Parse("Standard_F16s_v2");
        /**
         * Static value Standard_DS5_v2_Promo for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardDS5v2Promo = Parse("Standard_DS5_v2_Promo");
        /**
         * Static value Standard_E4s_v3 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardE4sv3 = Parse("Standard_E4s_v3");
        /**
         * Static value Standard_D1_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD1v2 = Parse("Standard_D1_v2");
        /**
         * Static value Standard_DS12_v2_Promo for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardDS12v2Promo = Parse("Standard_DS12_v2_Promo");
        /**
         * Static value Standard_D64s_v3 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD64sv3 = Parse("Standard_D64s_v3");
        /**
         * Static value Standard_M128-32ms for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardM128_32ms = Parse("Standard_M128-32ms");
        /**
         * Static value Standard_D4 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD4 = Parse("Standard_D4");
        /**
         * Static value Standard_D3 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD3 = Parse("Standard_D3");
        /**
         * Static value Standard_D2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD2 = Parse("Standard_D2");
        /**
         * Static value Standard_M128s for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardM128s = Parse("Standard_M128s");
        /**
         * Static value Standard_D4s_v3 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD4sv3 = Parse("Standard_D4s_v3");
        /**
         * Static value Standard_F2s_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardF2sv2 = Parse("Standard_F2s_v2");
        /**
         * Static value Standard_F1s for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardF1s = Parse("Standard_F1s");
        /**
         * Static value Standard_A8m_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardA8mv2 = Parse("Standard_A8m_v2");
        /**
         * Static value Standard_NC24 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardNC24 = Parse("Standard_NC24");
        /**
         * Static value Standard_B1s for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardB1s = Parse("Standard_B1s");
        /**
         * Static value Standard_E2s_v3 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardE2sv3 = Parse("Standard_E2s_v3");
        /**
         * Static value Standard_D8s_v3 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD8sv3 = Parse("Standard_D8s_v3");
        /**
         * Static value Standard_DS14_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardDS14v2 = Parse("Standard_DS14_v2");
        /**
         * Static value Standard_H16mr for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardH16mr = Parse("Standard_H16mr");
        /**
         * Static value Standard_DS13_v2_Promo for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardDS13v2Promo = Parse("Standard_DS13_v2_Promo");
        /**
         * Static value Standard_ND12s for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardND12s = Parse("Standard_ND12s");
        /**
         * Static value Standard_DS5_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardDS5v2 = Parse("Standard_DS5_v2");
        /**
         * Static value Standard_D15_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD15v2 = Parse("Standard_D15_v2");
        /**
         * Static value Standard_ND24s for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardND24s = Parse("Standard_ND24s");
        /**
         * Static value Standard_F4s_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardF4sv2 = Parse("Standard_F4s_v2");
        /**
         * Static value Standard_GS5-16 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardGS5_16 = Parse("Standard_GS5-16");
        /**
         * Static value Standard_F2s for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardF2s = Parse("Standard_F2s");
        /**
         * Static value Standard_B2ms for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardB2ms = Parse("Standard_B2ms");
        /**
         * Static value Standard_B2s for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardB2s = Parse("Standard_B2s");
        /**
         * Static value Standard_E2_v3 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardE2v3 = Parse("Standard_E2_v3");
        /**
         * Static value Standard_A4_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardA4v2 = Parse("Standard_A4_v2");
        /**
         * Static value Standard_DS4_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardDS4v2 = Parse("Standard_DS4_v2");
        /**
         * Static value Standard_F8s for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardF8s = Parse("Standard_F8s");
        /**
         * Static value Standard_D12_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD12v2 = Parse("Standard_D12_v2");
        /**
         * Static value Standard_A2m_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardA2mv2 = Parse("Standard_A2m_v2");
        /**
         * Static value Standard_DS13-4_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardDS13_4v2 = Parse("Standard_DS13-4_v2");
        /**
         * Static value Standard_M128ms for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardM128ms = Parse("Standard_M128ms");
        /**
         * Static value Standard_DS15_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardDS15v2 = Parse("Standard_DS15_v2");
        /**
         * Static value Standard_F2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardF2 = Parse("Standard_F2");
        /**
         * Static value Standard_F1 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardF1 = Parse("Standard_F1");
        /**
         * Static value Standard_DS14_v2_Promo for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardDS14v2Promo = Parse("Standard_DS14_v2_Promo");
        /**
         * Static value Standard_GS4-8 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardGS4_8 = Parse("Standard_GS4-8");
        /**
         * Static value Standard_E32-8s_v3 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardE32_8sv3 = Parse("Standard_E32-8s_v3");
        /**
         * Static value Standard_F8 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardF8 = Parse("Standard_F8");
        /**
         * Static value Standard_F16 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardF16 = Parse("Standard_F16");
        /**
         * Static value Standard_F4 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardF4 = Parse("Standard_F4");
        /**
         * Static value Standard_GS4-4 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardGS4_4 = Parse("Standard_GS4-4");
        /**
         * Static value Standard_F72s_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardF72sv2 = Parse("Standard_F72s_v2");
        /**
         * Static value Standard_D16s_v3 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD16sv3 = Parse("Standard_D16s_v3");
        /**
         * Static value Standard_D2_v2_Promo for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD2v2Promo = Parse("Standard_D2_v2_Promo");
        /**
         * Static value Standard_A1_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardA1v2 = Parse("Standard_A1_v2");
        /**
         * Static value Standard_NC6 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardNC6 = Parse("Standard_NC6");
        /**
         * Static value Standard_E16s_v3 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardE16sv3 = Parse("Standard_E16s_v3");
        /**
         * Static value Standard_A10 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardA10 = Parse("Standard_A10");
        /**
         * Static value Standard_A4m_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardA4mv2 = Parse("Standard_A4m_v2");
        /**
         * Static value Standard_A11 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardA11 = Parse("Standard_A11");
        /**
         * Static value Standard_DS12_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardDS12v2 = Parse("Standard_DS12_v2");
        /**
         * Static value Standard_E16_v3 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardE16v3 = Parse("Standard_E16_v3");
        /**
         * Static value Standard_D4_v3 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD4v3 = Parse("Standard_D4_v3");
        /**
         * Static value Standard_G4 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardG4 = Parse("Standard_G4");
        /**
         * Static value Standard_G3 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardG3 = Parse("Standard_G3");
        /**
         * Static value Standard_NC24s_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardNC24sv2 = Parse("Standard_NC24s_v2");
        /**
         * Static value Standard_G2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardG2 = Parse("Standard_G2");
        /**
         * Static value Classic for ComputeSkuName.
         */
        public static readonly ComputeSkuName Classic = Parse("Classic");
        /**
         * Static value Standard_D4_v2 for ComputeSkuName.
         */
        public static readonly ComputeSkuName StandardD4v2 = Parse("Standard_D4_v2");
        /**
         * Static value Standard_G1 for ComputeSkuName.
         */

Answer: public static readonly ComputeSkuName StandardG1 = Parse("Standard_G1");

<think>
The code defines a series of static readonly ComputeSkuName fields, each preceded by a comment describing the SKU. The pattern is a comment block, then a line like `public static readonly ComputeSkuName <Name> = Parse("<Name>");`. The last comment shown is for `Standard_G1`. Following the established pattern, the next line should declare the corresponding static field using Parse with the same string.
</think>
public static readonly ComputeSkuName StandardG1 = Parse("Standard_G1");


Context:
// Copyright 2017, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Generated code. DO NOT EDIT!

using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Google.Cloud.PubSub.V1.Snippets
{
    public class GeneratedPublisherClientSnippets
    {
        public async Task CreateTopicAsync()
        {
            // Snippet: CreateTopicAsync(TopicName,CallSettings)
            // Additional: CreateTopicAsync(TopicName,CancellationToken)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();
            // Initialize request argument(s)
            TopicName name = new TopicName("[PROJECT]", "[TOPIC]");
            // Make the request
            Topic response = await publisherClient.CreateTopicAsync(name);
            // End snippet
        }

        public void CreateTopic()
        {
            // Snippet: CreateTopic(TopicName,CallSettings)
            // Create client
            PublisherClient publisherClient = PublisherClient.Create();
            // Initialize request argument(s)
            TopicName name = new TopicName("[PROJECT]", "[TOPIC]");
            // Make the request
            Topic response = publisherClient.CreateTopic(name);
            // End snippet
        }

        public async Task CreateTopicAsync_RequestObject()
        {
            // Snippet: CreateTopicAsync(Topic,CallSettings)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();
            // Initialize request argument(s)
            Topic request = new Topic
            {
                TopicName = new TopicName("[PROJECT]", "[TOPIC]"),
            };
            // Make the request
            Topic response = await publisherClient.CreateTopicAsync(request);
            // End snippet
        }

        public void CreateTopic_RequestObject()
        {
            // Snippet: CreateTopic(Topic,CallSettings)
            // Create client
            PublisherClient publisherClient = PublisherClient.Create();
            // Initialize request argument(s)
            Topic request = new Topic
            {
                TopicName = new TopicName("[PROJECT]", "[TOPIC]"),
            };
            // Make the request
            Topic response = publisherClient.CreateTopic(request);
            // End snippet
        }

        public async Task PublishAsync()
        {
            // Snippet: PublishAsync(TopicName,IEnumerable<PubsubMessage>,CallSettings)
            // Additional: PublishAsync(TopicName,IEnumerable<PubsubMessage>,CancellationToken)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();
            // Initialize request argument(s)
            TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
            IEnumerable<PubsubMessage> messages = new[]
            {
                new PubsubMessage
                {
                    Data = ByteString.CopyFromUtf8(""),
                },
            };
            // Make the request
            PublishResponse response = await publisherClient.PublishAsync(topic, messages);
            // End snippet
        }

        public void Publish()
        {
            // Snippet: Publish(TopicName,IEnumerable<PubsubMessage>,CallSettings)
            // Create client
            PublisherClient publisherClient = PublisherClient.Create();
            // Initialize request argument(s)
            TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
            IEnumerable<PubsubMessage> messages = new[]
            {
                new PubsubMessage
                {
                    Data = ByteString.CopyFromUtf8(""),
                },
            };
            // Make the request
            PublishResponse response = publisherClient.Publish(topic, messages);
            // End snippet
        }

        public async Task PublishAsync_RequestObject()
        {
            // Snippet: PublishAsync(PublishRequest,CallSettings)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();
            // Initialize request argument(s)
            PublishRequest request = new PublishRequest
            {
                TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
                Messages = {
                               new PubsubMessage
                               {
                                   Data = ByteString.CopyFromUtf8(""),
                               },
                           },
            };
            // Make the request
            PublishResponse response = await publisherClient.PublishAsync(request);
            // End snippet
        }

        public void Publish_RequestObject()
        {
            // Snippet: Publish(PublishRequest,CallSettings)
            // Create client
            PublisherClient publisherClient = PublisherClient.Create();
            // Initialize request argument(s)
            PublishRequest request = new PublishRequest
            {
                TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
                Messages = {
                               new PubsubMessage
                               {
                                   Data = ByteString.CopyFromUtf8(""),
                               },
                           },
            };
            // Make the request
            PublishResponse response = publisherClient.Publish(request);
            // End snippet
        }

        public async Task GetTopicAsync()
        {
            // Snippet: GetTopicAsync(TopicName,CallSettings)
            // Additional: GetTopicAsync(TopicName,CancellationToken)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();
            // Initialize request argument(s)
            TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
            // Make the request
            Topic response = await publisherClient.GetTopicAsync(topic);
            // End snippet
        }

        public void GetTopic()
        {
            // Snippet: GetTopic(TopicName,CallSettings)
            // Create client
            PublisherClient publisherClient = PublisherClient.Create();
            // Initialize request argument(s)
            TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
            // Make the request
            Topic response = publisherClient.GetTopic(topic);
            // End snippet
        }

        public async Task GetTopicAsync_RequestObject()
        {
            // Snippet: GetTopicAsync(GetTopicRequest,CallSettings)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();
            // Initialize request argument(s)
            GetTopicRequest request = new GetTopicRequest
            {
                TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
            };
            // Make the request
            Topic response = await publisherClient.GetTopicAsync(request);
            // End snippet
        }

        public void GetTopic_RequestObject()
        {
            // Snippet: GetTopic(GetTopicRequest,CallSettings)
            // Create client
            PublisherClient publisherClient = PublisherClient.Create();
            // Initialize request argument(s)
            GetTopicRequest request = new GetTopicRequest
            {
                TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
            };
            // Make the request
            Topic response = publisherClient.GetTopic(request);
            // End snippet
        }

        public async Task ListTopicsAsync()
        {
            // Snippet: ListTopicsAsync(ProjectName,string,int?,CallSettings)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();
            // Initialize request argument(s)
            ProjectName project = new ProjectName("[PROJECT]");
            // Make the request
            PagedAsyncEnumerable<ListTopicsResponse, Topic> response =
                publisherClient.ListTopicsAsync(project);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((Topic item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListTopicsResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Topic item in page)
                {
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<Topic> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Topic item in singlePage)
            {
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }

        public void ListTopics()
        {
            // Snippet: ListTopics(ProjectName,string,int?,CallSettings)
            // Create client
            PublisherClient publisherClient = PublisherClient.Create();
            // Initialize request argument(s)
            ProjectName project = new ProjectName("[PROJECT]");
            // Make the request
            PagedEnumerable<ListTopicsResponse, Topic> response =
                publisherClient.ListTopics(project);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Topic item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListTopicsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Topic item in page)
                {
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;

Answer: Page<Topic> singlePage = response.ReadPage(pageSize);

<think>
The method ListTopics() mirrors the async version ListTopicsAsync(). After defining the pageSize variable, the next step is to retrieve a single page of results synchronously. In the async version they call response.ReadPageAsync(pageSize); the sync version uses response.ReadPage(pageSize). Therefore the next line is the synchronous page read statement.
</think>
Page<Topic> singlePage = response.ReadPage(pageSize);


Context:
/*
 * #%L
 * BroadleafCommerce Open Admin Platform
 * %%
 * Copyright (C) 2009 - 2013 Broadleaf Commerce
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

package org.broadleafcommerce.openadmin.web.form.entity;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.common.presentation.client.SupportedFieldType;
import org.broadleafcommerce.common.web.BroadleafRequestContext;
import org.broadleafcommerce.openadmin.dto.SectionCrumb;
import org.broadleafcommerce.openadmin.web.form.component.ListGrid;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;

public class EntityForm {

    protected static final Log LOG = LogFactory.getLog(EntityForm.class);

    public static final String HIDDEN_GROUP = "hiddenGroup";
    public static final String MAP_KEY_GROUP = "keyGroup";
    public static final String DEFAULT_GROUP_NAME = "Default";
    public static final Integer DEFAULT_GROUP_ORDER = 99999;
    public static final String DEFAULT_TAB_NAME = "General";
    public static final Integer DEFAULT_TAB_ORDER = 100;

    protected String id;
    protected String parentId;
    protected String idProperty = "id";
    protected String ceilingEntityClassname;
    protected String entityType;
    protected String mainEntityName;
    protected String sectionKey;
    protected Boolean readOnly = false;

    protected String translationCeilingEntity;
    protected String translationId;

    protected Set<Tab> tabs = new TreeSet<Tab>(new Comparator<Tab>() {
        @Override
        public int compare(Tab o1, Tab o2) {
            return new CompareToBuilder()
                    .append(o1.getOrder(), o2.getOrder())
                    .append(o1.getTitle(), o2.getTitle())
                    .toComparison();
        }
    });
    protected List<SectionCrumb> sectionCrumbs = new ArrayList<SectionCrumb>();

    // This is used to data-bind when this entity form is submitted
    protected Map<String, Field> fields = null;

    // This is used in cases where there is a sub-form on this page that is dynamically
    // rendered based on other values on this entity form. It is keyed by the name of the
    // property that drives the dynamic form.
    protected Map<String, EntityForm> dynamicForms = new LinkedHashMap<String, EntityForm>();

    // These values are used when dynamic forms are in play. They are not rendered to the client,
    // but they can be used when performing actions on the submit event
    protected Map<String, DynamicEntityFormInfo> dynamicFormInfos = new LinkedHashMap<String, DynamicEntityFormInfo>();

    protected List<EntityFormAction> actions = new ArrayList<EntityFormAction>();

    protected Map<String, Object> attributes = new HashMap<String, Object>();

    /**
     * @return a flattened, field name keyed representation of all of
     * the fields in all of the groups for this form. This set will also includes all of the dynamic form
     * fields.
     *
     * Note that if there collisions between the dynamic form fields and the fields on this form (meaning that they
     * have the same name), then the dynamic form field will be excluded from the map and the preference will be given
     * to first-level entities
     *
     * @see {@link #getFields(boolean)}
     */
    public Map<String, Field> getFields() {
        if (fields == null) {
            Map<String, Field> map = new LinkedHashMap<String, Field>();
            for (Tab tab : tabs) {
                for (FieldGroup group : tab.getFieldGroups()) {
                    for (Field field : group.getFields()) {
                        map.put(field.getName(), field);
                    }
                }
            }
            fields = map;
        }

        for (Entry<String, EntityForm> entry : dynamicForms.entrySet()) {
            Map<String, Field> dynamicFormFields = entry.getValue().getFields();
            for (Entry<String, Field> dynamicField : dynamicFormFields.entrySet()) {
                if (fields.containsKey(dynamicField.getKey())) {
                    LOG.info("Excluding dynamic field " + dynamicField.getKey() + " as there is already an occurrance in" +
                    		" this entityForm");
                } else {
                    fields.put(dynamicField.getKey(), dynamicField.getValue());
                }
            }
        }

        return fields;
    }

    /**
     * Clears out the cached 'fields' variable which is used to render the form on the frontend. Use this method
     * if you want to force the entityForm to rebuild itself based on the tabs and groups that have been assigned and
     * populated
     */
    public void clearFieldsMap() {
        fields = null;
    }

    public List<ListGrid> getAllListGrids() {
        List<ListGrid> list = new ArrayList<ListGrid>();
        for (Tab tab : tabs) {
            for (ListGrid lg : tab.getListGrids()) {
                list.add(lg);
            }
        }
        return list;
    }

    /**
     * Convenience method for grabbing a grid by its collection field name. This is very similar to {@link #findField(String)}
     * but differs in that this only searches through the sub collections for the current entity
     *
     * @param collectionFieldName the field name of the collection on the top-level entity
     * @return
     */
    public ListGrid findListGrid(String collectionFieldName) {
        for (ListGrid grid : getAllListGrids()) {
            if (grid.getSubCollectionFieldName().equals(collectionFieldName)) {
                return grid;
            }
        }
        return null;
    }

    public Tab findTab(String tabTitle) {
        for (Tab tab : tabs) {
            if (tab.getTitle() != null && tab.getTitle().equals(tabTitle)) {
                return tab;
            }
        }
        return null;
    }

    public Tab findTabForField(String fieldName) {
        fieldName = sanitizeFieldName(fieldName);
        for (Tab tab : tabs) {
            for (FieldGroup fieldGroup : tab.getFieldGroups()) {
                for (Field field : fieldGroup.getFields()) {
                    if (field.getName().equals(fieldName)) {
                        return tab;
                    }
                }
            }
        }
        return null;
    }

    public Field findField(String fieldName) {
        fieldName = sanitizeFieldName(fieldName);
        for (Tab tab : tabs) {
            for (FieldGroup fieldGroup : tab.getFieldGroups()) {
                for (Field field : fieldGroup.getFields()) {
                    if (field.getName().equals(fieldName)) {
                        return field;
                    }
                }
            }
        }
        return null;
    }

    /**
     * Since this field name could come from the frontend (where all fields are referenced like fields[name].value,
     * we need to strip that part out to look up the real field name in this entity
     * @param fieldName
     * @return
     */
    public String sanitizeFieldName(String fieldName) {
        if (fieldName.contains("[")) {
            fieldName = fieldName.substring(fieldName.indexOf('[') + 1, fieldName.indexOf(']'));
        }
        return fieldName;
    }

    public Field removeField(String fieldName) {
        Field fieldToRemove = null;
        FieldGroup containingGroup = null;

        findField: {
            for (Tab tab : tabs) {
                for (FieldGroup fieldGroup : tab.getFieldGroups()) {
                    for (Field field : fieldGroup.getFields()) {
                        if (field.getName().equals(fieldName)) {
                            fieldToRemove = field;
                            containingGroup = fieldGroup;
                            break findField;
                        }
                    }
                }
            }
        }

        if (fieldToRemove != null) {
            containingGroup.removeField(fieldToRemove);
        }

        if (fields != null) {
            fieldToRemove = fields.remove(fieldName);
        }

        return fieldToRemove;
    }

    public void removeTab(Tab tab) {
        tabs.remove(tab);
    }

    public void removeTab(String tabName) {
        if (tabs != null) {
            Iterator<Tab> tabIterator = tabs.iterator();
            while (tabIterator.hasNext()) {
                Tab currentTab = tabIterator.next();
                if (tabName.equals(currentTab.getTitle())) {
                    tabIterator.remove();
                }
            }
        }
    }
    public ListGrid removeListGrid(String subCollectionFieldName) {
        ListGrid lgToRemove = null;
        Tab containingTab = null;

        findLg: {
            for (Tab tab : tabs) {
                for (ListGrid lg : tab.getListGrids()) {
                    if (subCollectionFieldName.equals(lg.getSubCollectionFieldName())) {
                        lgToRemove = lg;
                        containingTab = tab;
                        break findLg;
                    }
                }
            }
        }

        if (lgToRemove != null) {
            containingTab.removeListGrid(lgToRemove);
        }

        if (containingTab.getListGrids().size() == 0 && containingTab.getFields().size() == 0) {
            removeTab(containingTab);
        }

        return lgToRemove;
    }

    public void addHiddenField(Field field) {
        if (StringUtils.isBlank(field.getFieldType())) {
            field.setFieldType(SupportedFieldType.HIDDEN.toString());
        }
        addField(field, HIDDEN_GROUP, DEFAULT_GROUP_ORDER, DEFAULT_TAB_NAME, DEFAULT_TAB_ORDER);
    }

    public void addField(Field field) {
        addField(field, DEFAULT_GROUP_NAME, DEFAULT_GROUP_ORDER, DEFAULT_TAB_NAME, DEFAULT_TAB_ORDER);
    }

    public void addMapKeyField(Field field) {
        addField(field, MAP_KEY_GROUP, 0, DEFAULT_TAB_NAME, DEFAULT_TAB_ORDER);
    }

    public void addField(Field field, String groupName, Integer groupOrder, String tabName, Integer tabOrder) {
        groupName = groupName == null ? DEFAULT_GROUP_NAME : groupName;
        groupOrder = groupOrder == null ? DEFAULT_GROUP_ORDER : groupOrder;
        tabName = tabName == null ? DEFAULT_TAB_NAME : tabName;
        tabOrder = tabOrder == null ? DEFAULT_TAB_ORDER : tabOrder;

        // Tabs and groups should be looked up by their display, translated name since 2 unique strings can display the same
        // thing when they are looked up in message bundles after display
        // When displayed on the form the duplicate groups and tabs look funny
        BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
        if (context != null && context.getMessageSource() != null) {
            groupName = context.getMessageSource().getMessage(groupName, null, groupName, context.getJavaLocale());
            tabName = context.getMessageSource().getMessage(tabName, null, tabName, context.getJavaLocale());
        }

        Tab tab = findTab(tabName);
        if (tab == null) {
            tab = new Tab();
            tab.setTitle(tabName);
            tab.setOrder(tabOrder);
            tabs.add(tab);
        }

        FieldGroup fieldGroup = tab.findGroup(groupName);
        if (fieldGroup == null) {
            fieldGroup = new FieldGroup();
            fieldGroup.setTitle(groupName);
            fieldGroup.setOrder(groupOrder);
            tab.getFieldGroups().add(fieldGroup);
        }

        fieldGroup.addField(field);
    }

    public void addListGrid(ListGrid listGrid, String tabName, Integer tabOrder) {
        // Tabs should be looked up and referenced by their display name
        BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
        if (context != null && context.getMessageSource() != null) {

Answer: tabName = context.getMessageSource().getMessage(tabName, null, tabName, context.getJavaLocale());

<think>
The method addListGrid mirrors addField: after obtaining the BroadleafRequestContext it checks for a message source and then translates the provided tabName using the message source. The next line inside the if‑block should perform that translation, assigning the possibly localized name back to tabName.
</think>
tabName = context.getMessageSource().getMessage(tabName, null, tabName, context.getJavaLocale());


Context:
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for tensorflow.ops.resource_variable_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import copy
import gc
import os
import pickle

import numpy as np

from tensorflow.core.framework import tensor_pb2
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import cpp_shape_inference_pb2
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import custom_gradient
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import list_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import momentum
from tensorflow.python.training import saver
from tensorflow.python.training import training_util
from tensorflow.python.util import compat

class ResourceVariableOpsTest(test_util.TensorFlowTestCase):

  def tearDown(self):
    gc.collect()
    # This will only contain uncollectable garbage, i.e. reference cycles
    # involving objects with __del__ defined.
    self.assertEqual(0, len(gc.garbage))

  @test_util.run_deprecated_v1
  def testHandleDtypeShapeMatch(self):
    with self.cached_session():
      handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[])
      with self.assertRaises(ValueError):
        resource_variable_ops.assign_variable_op(
            handle, constant_op.constant(0.0, dtype=dtypes.float32)).run()
      with self.assertRaises(ValueError):
        resource_variable_ops.assign_variable_op(handle,
                                                 constant_op.constant(
                                                     [0],
                                                     dtype=dtypes.int32)).run()
      resource_variable_ops.assign_variable_op(handle,
                                               constant_op.constant(
                                                   0,
                                                   dtype=dtypes.int32)).run()

  def testGPUInt64(self):
    if not context.context().num_gpus():
      return
    with context.eager_mode(), context.device("gpu:0"):
      v = resource_variable_ops.ResourceVariable(1, dtype=dtypes.int64)
      self.assertAllEqual(1, v.numpy())

  def testEagerNameNotIdentity(self):
    with context.eager_mode():
      v0 = resource_variable_ops.ResourceVariable(1.0, name="a")
      v1 = resource_variable_ops.ResourceVariable(2.0, name="a")
      self.assertAllEqual(v0.numpy(), 1.0)
      self.assertAllEqual(v1.numpy(), 2.0)

  def testEagerNameNotNeeded(self):
    with context.eager_mode():
      v0 = resource_variable_ops.ResourceVariable(1.0)
      self.assertAllEqual(v0.numpy(), 1.0)

  def testReadVariableDtypeMismatchEager(self):
    with context.eager_mode():
      handle = resource_variable_ops.var_handle_op(
          dtype=dtypes.int32, shape=[1], name="foo")
      resource_variable_ops.assign_variable_op(handle, 1)
      with self.assertRaisesRegexp(errors.InvalidArgumentError,
                                   "Trying to read variable with wrong dtype. "
                                   "Expected float got int32."):
        _ = resource_variable_ops.read_variable_op(handle, dtype=dtypes.float32)

  def testEagerInitializedValue(self):
    with context.eager_mode():
      variable = resource_variable_ops.ResourceVariable(1.0, name="eager-init")
      self.assertAllEqual(variable.numpy(), 1.0)
      self.assertAllEqual(variable.initialized_value().numpy(), 1.0)

  def testEagerBool(self):
    with context.eager_mode():
      v = resource_variable_ops.ResourceVariable(False, name="bool_test")
      self.assertAllEqual(bool(v), False)

  def testEagerDeepCopy(self):
    with context.eager_mode():
      init_value = np.ones((4, 4, 4))
      variable = resource_variable_ops.ResourceVariable(init_value,
                                                        name="init")

      copied_variable = copy.deepcopy(variable)
      copied_variable.assign(4 * np.ones((4, 4, 4)))

      # Copying the variable should create a new underlying tensor with distinct
      # values.
      self.assertFalse(np.allclose(variable.numpy(), copied_variable.numpy()))

  @test_util.run_deprecated_v1
  def testGraphDeepCopy(self):
    with self.cached_session():
      init_value = np.ones((4, 4, 4))
      variable = resource_variable_ops.ResourceVariable(init_value,
                                                        name="init")
      with self.assertRaises(NotImplementedError):
        copy.deepcopy(variable)

  @test_util.run_in_graph_and_eager_modes
  def testStridedSliceAssign(self):
    v = resource_variable_ops.ResourceVariable([1.0, 2.0])
    self.evaluate(variables.global_variables_initializer())
    self.evaluate(v[0].assign(2.0))
    self.assertAllEqual(self.evaluate(v), [2.0, 2.0])

  @test_util.run_in_graph_and_eager_modes
  def testVariableShape(self):
    v = resource_variable_ops.ResourceVariable([1., 1.])
    self.assertAllEqual(
        tensor_util.constant_value(
            resource_variable_ops.variable_shape(v.handle)),
        [2])

  @test_util.run_deprecated_v1
  def testDifferentAssignGraph(self):
    with ops.Graph().as_default():
      v = resource_variable_ops.ResourceVariable(1.0)
    ops.reset_default_graph()
    v.assign(2.0)  # Note: this fails if we run convert_to_tensor on not the
    # variable graph.

  @test_util.run_deprecated_v1
  def testFetchHandle(self):
    with self.cached_session():
      handle = resource_variable_ops.var_handle_op(
          dtype=dtypes.int32, shape=[1], name="foo")
      self.assertGreater(len(handle.eval()), 0)

  @test_util.run_deprecated_v1
  def testCachedValueReadBeforeWrite(self):
    with self.cached_session() as sess:
      v = resource_variable_ops.ResourceVariable(0.0, caching_device="cpu:0")
      self.evaluate(v.initializer)
      value, _ = sess.run([v, v.assign_add(1.0)])
      self.assertAllEqual(value, 0.0)

  def testAssignVariableDtypeMismatchEager(self):
    with context.eager_mode():
      handle = resource_variable_ops.var_handle_op(
          dtype=dtypes.int32, shape=[1], name="foo")
      resource_variable_ops.assign_variable_op(
          handle, constant_op.constant([1]))
      with self.assertRaisesRegexp(errors.InvalidArgumentError,
                                   "Trying to assign variable with wrong "
                                   "dtype. Expected int32 got float."):
        resource_variable_ops.assign_variable_op(
            handle, constant_op.constant([1.], dtype=dtypes.float32))

  def testUnprintableHandle(self):
    with context.eager_mode():
      handle = resource_variable_ops.var_handle_op(
          dtype=dtypes.int32, shape=[1], name="foo")
      self.assertIn("<unprintable>", str(handle))
      self.assertIn("<unprintable>", repr(handle))

  @test_util.run_in_graph_and_eager_modes
  def testDtypeSurvivesIdentity(self):
    handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[])
    id_handle = array_ops.identity(handle)
    self.evaluate(resource_variable_ops.assign_variable_op(
        id_handle, constant_op.constant(0, dtype=dtypes.int32)))

  def testUnreadOpName(self):
    v = resource_variable_ops.ResourceVariable(1.0)
    self.assertNotEqual(v.name, v.assign_add(1.0).name)

  @test_util.run_in_graph_and_eager_modes
  def testCreateRead(self):
    handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[])
    self.evaluate(resource_variable_ops.assign_variable_op(
        handle, constant_op.constant(1, dtype=dtypes.int32)))
    value = self.evaluate(
        resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32))
    self.assertAllEqual(1, value)

  @test_util.run_in_graph_and_eager_modes
  def testManyAssigns(self):
    handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[])
    create = resource_variable_ops.assign_variable_op(
        handle, constant_op.constant(1, dtype=dtypes.int32))
    with ops.control_dependencies([create]):
      first_read = resource_variable_ops.read_variable_op(
          handle, dtype=dtypes.int32)
    with ops.control_dependencies([first_read]):
      write = resource_variable_ops.assign_variable_op(
          handle, constant_op.constant(2, dtype=dtypes.int32))
    with ops.control_dependencies([write]):
      second_read = resource_variable_ops.read_variable_op(
          handle, dtype=dtypes.int32)
    f, s = self.evaluate([first_read, second_read])
    self.assertEqual(f, 1)
    self.assertEqual(s, 2)

  @test_util.run_in_graph_and_eager_modes
  def testAssignAdd(self):
    handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[])
    self.evaluate(resource_variable_ops.assign_variable_op(
        handle, constant_op.constant(1, dtype=dtypes.int32)))
    self.evaluate(resource_variable_ops.assign_add_variable_op(
        handle, constant_op.constant(1, dtype=dtypes.int32)))
    read = self.evaluate(
        resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32))
    self.assertEqual(read, 2)

  @test_util.run_in_graph_and_eager_modes
  def testScatterAdd(self):
    handle = resource_variable_ops.var_handle_op(
        dtype=dtypes.int32, shape=[1, 1])
    self.evaluate(
        resource_variable_ops.assign_variable_op(
            handle, constant_op.constant([[1]], dtype=dtypes.int32)))
    self.evaluate(
        resource_variable_ops.resource_scatter_add(
            handle, [0], constant_op.constant([[2]], dtype=dtypes.int32)))
    read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)
    self.assertEqual(self.evaluate(read), [[3]])

  @test_util.run_in_graph_and_eager_modes
  def testScatterSub(self):
    handle = resource_variable_ops.var_handle_op(
        dtype=dtypes.int32, shape=[1, 1])
    self.evaluate(
        resource_variable_ops.assign_variable_op(
            handle, constant_op.constant([[1]], dtype=dtypes.int32)))
    self.evaluate(
        resource_variable_ops.resource_scatter_sub(
            handle, [0], constant_op.constant([[2]], dtype=dtypes.int32)))
    read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)
    self.assertEqual(self.evaluate(read), [[-1]])

  @test_util.run_in_graph_and_eager_modes
  def testScatterMul(self):
    handle = resource_variable_ops.var_handle_op(
        dtype=dtypes.int32, shape=[1, 1])
    self.evaluate(
        resource_variable_ops.assign_variable_op(
            handle, constant_op.constant([[1]], dtype=dtypes.int32)))
    self.evaluate(
        resource_variable_ops.resource_scatter_mul(
            handle, [0], constant_op.constant([[5]], dtype=dtypes.int32)))
    read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)
    self.assertEqual(self.evaluate(read), [[5]])

  def testEagerPickle(self):
    with context.eager_mode():
      tmp_dir = self.get_temp_dir()
      fname = os.path.join(tmp_dir, "var.pickle")
      with open(fname, "wb") as f:
        v = resource_variable_ops.ResourceVariable(
            10.0,
            dtype=dtypes.float16,
            name="v")
        pickle.dump(v, f)

      with open(fname, "rb") as f:
        new_v = pickle.load(f)
        self.assertEqual(new_v.name, v.name)
        self.assertEqual(new_v.shape, v.shape)
        self.assertEqual(new_v.dtype, v.dtype)
        self.assertEqual(new_v.trainable, v.trainable)
        self.assertAllEqual(new_v.numpy(), v.numpy())

  @test_util.run_in_graph_and_eager_modes
  def testScatterDiv(self):
    handle = resource_variable_ops.var_handle_op(
        dtype=dtypes.int32, shape=[1, 1])
    self.evaluate(
        resource_variable_ops.assign_variable_op(
            handle, constant_op.constant([[6]], dtype=dtypes.int32)))
    self.evaluate(
        resource_variable_ops.resource_scatter_div(
            handle, [0], constant_op.constant([[3]], dtype=dtypes.int32)))
    read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)
    self.assertEqual(self.evaluate(read), [[2]])

  def testUseResource(self):
    v = variables.VariableV1(1.0, use_resource=True)
    self.assertTrue(isinstance(v, resource_variable_ops.ResourceVariable))

  def testEagerNoUseResource(self):
    with context.eager_mode():
      v = variables.Variable(1.0)
      self.assertTrue(isinstance(v, resource_variable_ops.ResourceVariable))

  @test_util.run_in_graph_and_eager_modes
  def testScatterMin(self):
    with ops.device("cpu:0"):
      handle = resource_variable_ops.var_handle_op(
          dtype=dtypes.int32, shape=[1, 1])
      self.evaluate(
          resource_variable_ops.assign_variable_op(handle,
                                                   constant_op.constant(
                                                       [[6]],
                                                       dtype=dtypes.int32)))
      self.evaluate(
          resource_variable_ops.resource_scatter_min(handle, [0],
                                                     constant_op.constant(
                                                         [[3]],
                                                         dtype=dtypes.int32)))
      read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)
      self.assertEqual(self.evaluate(read), [[3]])

  def testMetagraph(self):
    with ops.Graph().as_default():
      with variable_scope.variable_scope("foo", use_resource=True):
        a = variable_scope.get_variable("a", initializer=10.0)

      momentum.MomentumOptimizer(
          learning_rate=0.001, momentum=0.1).minimize(
              a,
              colocate_gradients_with_ops=True,
              global_step=training_util.get_or_create_global_step())

      graph = ops.get_default_graph()
      meta_graph_def = saver.export_meta_graph(graph=graph)

    with ops.Graph().as_default():
      saver.import_meta_graph(meta_graph_def, import_scope="")
      meta_graph_two = saver.export_meta_graph(graph=graph)
    self.assertEqual(meta_graph_def, meta_graph_two)

  @test_util.run_in_graph_and_eager_modes
  def testScatterMax(self):
    handle = resource_variable_ops.var_handle_op(
        dtype=dtypes.int32, shape=[1, 1])
    self.evaluate(
        resource_variable_ops.assign_variable_op(
            handle, constant_op.constant([[6]], dtype=dtypes.int32)))
    self.evaluate(
        resource_variable_ops.resource_scatter_max(
            handle, [0], constant_op.constant([[3]], dtype=dtypes.int32)))
    read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)
    self.assertEqual(self.evaluate(read), [[6]])

  @test_util.run_in_graph_and_eager_modes
  def testScatterAddScalar(self):
    handle = resource_variable_ops.var_handle_op(
        dtype=dtypes.int32, shape=[1, 1])
    self.evaluate(
        resource_variable_ops.assign_variable_op(
            handle, constant_op.constant([[1]], dtype=dtypes.int32)))
    self.evaluate(
        resource_variable_ops.resource_scatter_add(
            handle, [0], constant_op.constant(2, dtype=dtypes.int32)))
    read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)
    self.assertEqual(self.evaluate(read), [[3]])

  @test_util.run_in_graph_and_eager_modes
  def testScatterSubScalar(self):
    handle = resource_variable_ops.var_handle_op(
        dtype=dtypes.int32, shape=[1, 1])
    self.evaluate(
        resource_variable_ops.assign_variable_op(
            handle, constant_op.constant([[1]], dtype=dtypes.int32)))
    self.evaluate(
        resource_variable_ops.resource_scatter_sub(
            handle, [0], constant_op.constant(2, dtype=dtypes.int32)))
    read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)
    self.assertEqual(self.evaluate(read), [[-1]])

  @test_util.run_in_graph_and_eager_modes
  def testScatterMulScalar(self):
    handle = resource_variable_ops.var_handle_op(
        dtype=dtypes.int32, shape=[1, 1])
    self.evaluate(
        resource_variable_ops.assign_variable_op(

Answer: handle, constant_op.constant([[1]], dtype=dtypes.int32)))

<think>
The testScatterMulScalar method follows the pattern of other scalar scatter tests: it first assigns an initial value to the handle using assign_variable_op with a constant [[1]] of int32 type. The code snippet ends right after the opening of assign_variable_op, so the next line should provide the handle and constant arguments and close the parentheses.
</think>
handle, constant_op.constant([[1]], dtype=dtypes.int32)))


Context:
/*
 * Copyright 2014-2021 Lukas Krejci
 * and other contributors as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.revapi.configuration;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;

/**
 * {@link InputStream} implementation that reads a character stream from a {@link Reader} and transforms it to a byte
 * stream using a specified charset encoding. The stream is transformed using a {@link CharsetEncoder} object,
 * guaranteeing that all charset encodings supported by the JRE are handled correctly. In particular for charsets such
 * as UTF-16, the implementation ensures that one and only one byte order marker is produced.
 *
 *

 * Since in general it is not possible to predict the number of characters to be read from the {@link Reader} to satisfy
 * a read request on the {@link ReaderInputStream}, all reads from the {@link Reader} are buffered. There is therefore
 * no well defined correlation between the current position of the {@link Reader} and that of the
 * {@link ReaderInputStream}. This also implies that in general there is no need to wrap the underlying {@link Reader}
 * in a {@link java.io.BufferedReader}.
 *
 *

 * {@link ReaderInputStream} implements the inverse transformation of {@link java.io.InputStreamReader}; in the
 * following example, reading from <tt>in2</tt> would return the same byte sequence as reading from <tt>in</tt>
 * (provided that the initial byte sequence is legal with respect to the charset encoding):
 *
 *

 * InputStream in = ...
 * Charset cs = ...
 * InputStreamReader reader = new InputStreamReader(in, cs);
 * ReaderInputStream in2 = new ReaderInputStream(reader, cs);
 *

 *
 * {@link ReaderInputStream} implements the same transformation as {@link java.io.OutputStreamWriter}, except that the
 * control flow is reversed: both classes transform a character stream into a byte stream, but
 * {@link java.io.OutputStreamWriter} pushes data to the underlying stream, while {@link ReaderInputStream} pulls it
 * from the underlying stream.
 *
 * Note that while there are use cases where there is no alternative to using this class, very often the need to use
 * this class is an indication of a flaw in the design of the code. This class is typically used in situations where an
 * existing API only accepts an {@link InputStream}, but where the most natural way to produce the data is as a
 * character stream, i.e. by providing a {@link Reader} instance. An example of a situation where this problem may
 * appear is when implementing the {@link javax.activation.DataSource} interface from the Java Activation Framework.
 *
 * Given the fact that the {@link Reader} class doesn't provide any way to predict whether the next read operation will
 * block or not, it is not possible to provide a meaningful implementation of the {@link InputStream#available()}
 * method. A call to this method will always return 0. Also, this class doesn't support {@link InputStream#mark(int)}.
 *
 * Instances of {@link ReaderInputStream} are not thread safe.
 *
 * @see org.apache.commons.io.output.WriterOutputStream
 *
 * @since 2.0
 *
 * @deprecated remove this once {@link JSONUtil#stripComments(InputStream, Charset)} is removed.
 */
@Deprecated
final class ReaderInputStream extends InputStream {
    private static final int DEFAULT_BUFFER_SIZE = 1024;

    private final Reader reader;
    private final CharsetEncoder encoder;

    /**
     * CharBuffer used as input for the decoder. It should be reasonably large as we read data from the underlying
     * Reader into this buffer.
     */
    private final CharBuffer encoderIn;

    /**
     * ByteBuffer used as output for the decoder. This buffer can be small as it is only used to transfer data from the
     * decoder to the buffer provided by the caller.
     */
    private final ByteBuffer encoderOut;

    private CoderResult lastCoderResult;
    private boolean endOfInput;

    /**
     * Construct a new {@link ReaderInputStream}.
     *
     * @param reader
     *            the target {@link Reader}
     * @param encoder
     *            the charset encoder
     *
     * @since 2.1
     */
    public ReaderInputStream(final Reader reader, final CharsetEncoder encoder) {
        this(reader, encoder, DEFAULT_BUFFER_SIZE);
    }

    /**
     * Construct a new {@link ReaderInputStream}.
     *
     * @param reader
     *            the target {@link Reader}
     * @param encoder
     *            the charset encoder
     * @param bufferSize
     *            the size of the input buffer in number of characters
     *
     * @since 2.1
     */
    public ReaderInputStream(final Reader reader, final CharsetEncoder encoder, final int bufferSize) {
        this.reader = reader;
        this.encoder = encoder;
        this.encoderIn = CharBuffer.allocate(bufferSize);
        this.encoderIn.flip();
        this.encoderOut = ByteBuffer.allocate(128);
        this.encoderOut.flip();
    }

    /**
     * Construct a new {@link ReaderInputStream}.
     *
     * @param reader
     *            the target {@link Reader}
     * @param charset
     *            the charset encoding
     * @param bufferSize
     *            the size of the input buffer in number of characters
     */
    public ReaderInputStream(final Reader reader, final Charset charset, final int bufferSize) {
        this(reader, charset.newEncoder().onMalformedInput(CodingErrorAction.REPLACE)
                .onUnmappableCharacter(CodingErrorAction.REPLACE), bufferSize);
    }

    /**
     * Construct a new {@link ReaderInputStream} with a default input buffer size of 1024 characters.
     *
     * @param reader
     *            the target {@link Reader}
     * @param charset
     *            the charset encoding
     */
    public ReaderInputStream(final Reader reader, final Charset charset) {

Answer: this(reader, charset, DEFAULT_BUFFER_SIZE);

<think>
The class defines several overloaded constructors. The last one takes a Reader and a Charset and should delegate to the three-argument constructor that also accepts a buffer size, using the default buffer size constant. Therefore the next line inside the constructor body is a call to the other constructor with DEFAULT_BUFFER_SIZE.
</think>
this(reader, charset, DEFAULT_BUFFER_SIZE);