auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public static void run(String username, String password, String account, String label, String product) throws InterruptedException { <END> BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000); BasicAuth auth = new BasicAuth(username, password); EnterpriseStreamingEndpoint endpoint = new EnterpriseStreamingEndpoint(account, product, label); Client client = new ClientBuilder() .name("PowerTrackClient-01") .hosts(Constants.ENTERPRISE_STREAM_HOST) .endpoint(endpoint) .authentication(auth) .processor(new SimpleStringProcessor(queue)) .build(); client.connect(); for (int msgRead = 0; msgRead < 1000; msgRead++) { String msg = queue.take(); System.out.println(msg); } client.stop(); }</code><technical_language>break long line</technical_language>

Target:
public static void run(String username, String password, String account, String label, String product) throws InterruptedException { BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000); BasicAuth auth = new BasicAuth(username, password); RealTimeEnterpriseStreamingEndpoint endpoint = new RealTimeEnterpriseStreamingEndpoint(account, product, label); Client client = new ClientBuilder() .name("PowerTrackClient-01") .hosts(Constants.ENTERPRISE_STREAM_HOST) .endpoint(endpoint) .authentication(auth) .processor(new LineStringProcessor(queue)) .build(); client.connect(); for (int msgRead = 0; msgRead < 1000; msgRead++) { String msg = queue.take(); System.out.println(msg); } client.stop(); }
Source:
<code>private static boolean hasHeader(TagNode node) { if (node.getChildren().stream().anyMatch(TableWithoutHeaderCheck::isTableHeader)) { return true; } else { return node.getChildren().stream().filter(child -> !isTable(child)).anyMatch(TableWithoutHeaderCheck::hasHeader); <START> } <END> }</code><technical_language>shortcircuit evaluation avoid if-else block here: return node.getChildren().stream().anyMatch(TableWithoutHeaderCheck::isTableHeader) || node.getChildren().stream().filter(child -> !isTable(child)).anyMatch(TableWithoutHeaderCheck::hasHeader);</technical_language>

Target:
private static boolean hasHeader(TagNode node) { return node.getChildren().stream().anyMatch(TableWithoutHeaderCheck::isTableHeader) || node.getChildren().stream().filter(child -> !isTable(child)).anyMatch(TableWithoutHeaderCheck::hasHeader); }
Source:
<code>public void run() { log.info("Running job {}", getClass().getSimpleName()); for (final String account : allAccountIds.get()) { for (final String region : jobsProperties.getWhitelistedRegions()) { try { log.info("Scanning public EC2 instances for {}/{}", account, region); final AmazonEC2Client ec2Client = clientProvider.getClient( AmazonEC2Client.class, account, getRegion(fromName(region))); Optional<String> nextToken = empty(); do { final DescribeInstancesRequest request = new DescribeInstancesRequest(); if (nextToken.isPresent()) { <START> request.setNextToken(nextToken.get()); <END> } else { request.withFilters( new Filter("ip-address").withValues("*"), new Filter("instance-state-name").withValues("running")); } final DescribeInstancesResult result = ec2Client.describeInstances(request); nextToken = Optional.ofNullable(result.getNextToken()); for (final Reservation reservation : result.getReservations()) { for (final Instance instance : reservation.getInstances()) { processInstance(account, region, instance); } } } while (nextToken.isPresent()); } catch (final AmazonServiceException a) { if (a.getErrorCode().equals("RequestLimitExceeded")) { log.warn("RequestLimitExceeded for account: {}", account); } else { log.error(a.getMessage(), a); } } } } }</code><technical_language>in this case setNextToken()</technical_language>

Target:
public void run() { log.info("Running job {}", getClass().getSimpleName()); for (final String account : allAccountIds.get()) { for (final String region : jobsProperties.getWhitelistedRegions()) { try { log.info("Scanning public EC2 instances for {}/{}", account, region); final AmazonEC2Client ec2Client = clientProvider.getClient( AmazonEC2Client.class, account, getRegion(fromName(region))); Optional<String> nextToken = empty(); do { final DescribeInstancesRequest request = new DescribeInstancesRequest(); if (nextToken.isPresent()) { request.setNextToken(nextToken.get()); } else { request.withFilters( new Filter("ip-address").withValues("*"), new Filter("instance-state-name").withValues("running")); } final DescribeInstancesResult result = ec2Client.describeInstances(request); nextToken = Optional.ofNullable(trimToNull(result.getNextToken())); for (final Reservation reservation : result.getReservations()) { for (final Instance instance : reservation.getInstances()) { processInstance(account, region, instance); } } } while (nextToken.isPresent()); } catch (final AmazonServiceException a) { if (a.getErrorCode().equals("RequestLimitExceeded")) { log.warn("RequestLimitExceeded for account: {}", account); } else { log.error(a.getMessage(), a); } } } } }
Source:
<code>private void recordValues() { FateMetricValues measurement = metricValues.get(); currentFateOps.set(measurement.getCurrentFateOps()); zkChildFateOpsTotal.set(measurement.getZkFateChildOpsTotal()); zkConnectionErrorsTotal.set(measurement.getZkConnectionErrors()); Map<String,Long> states = measurement.getTxStateCounters(); states.forEach((key, value) -> { MutableGaugeLong v = fateTypeCounts.get(key); if (v != null) { v.set(value); } else { v = super.getRegistry().newGauge(metricNameHelper(FATE_TX_STATE_METRIC_PREFIX, key), "By transaction state count for " + key, value); fateTypeCounts.put(key, v); } }); fateOpCounts.forEach((key, value) -> value.set(0)); Map<String,Long> opTypes = measurement.getOpTypeCounters(); opTypes.forEach((key, value) -> { <START> MutableGaugeLong g = fateOpCounts.get(key); if (g != null) { g.set(value); } else { g = super.getRegistry().newGauge(metricNameHelper(FATE_OP_TYPE_METRIC_PREFIX, key), "By transaction op type count for " + key, value); } fateOpCounts.put(key, g); <END> }); }</code><technical_language>do fateOpCounts.put(key, g) in case exist in map? In case g is null gauge is created, do g.set(value)? If gauge set, code puts exists. java opTypes.forEach((key, value) -> { fateOpCounts.computeIfAbsent(key, ik -> super.getRegistry().newGauge(metricNameHelper(FATE_OP_TYPE_METRIC_PREFIX, ik), "By transaction op type count for " + ik, value)) .set(value); });</technical_language>

Target:
private void recordValues() { currentFateOps.set(metricValues.getCurrentFateOps()); zkChildFateOpsTotal.set(metricValues.getZkFateChildOpsTotal()); zkConnectionErrorsTotal.set(metricValues.getZkConnectionErrors()); Map<String,Long> states = metricValues.getTxStateCounters(); states.forEach((key, value) -> { MutableGaugeLong v = fateTypeCounts.get(key); if (v != null) { v.set(value); } else { v = super.getRegistry().newGauge(metricNameHelper(FATE_TX_STATE_METRIC_PREFIX, key), "By transaction state count for " + key, value); fateTypeCounts.put(key, v); } }); fateOpCounts.forEach((key, value) -> value.set(0)); Map<String,Long> opTypes = metricValues.getOpTypeCounters(); log.info("OP Counts Before: prev {}, updates {}", fateOpCounts, opTypes); opTypes.forEach((key, value) -> { MutableGaugeLong g = fateOpCounts.get(key); if (g != null) { g.set(value); } else { g = super.getRegistry().newGauge(metricNameHelper(FATE_OP_TYPE_METRIC_PREFIX, key), "By transaction op type count for " + key, value); fateOpCounts.put(key, g); } }); log.info("OP Counts After: prev {}, updates {}", fateOpCounts, opTypes); }
Source:
<code>private void waitForTable(int nbOfRows) { SWTBotUtils.waitUntil(expected -> { UIThreadRunnable.syncExec(() -> { fTableViewer.refresh(); }); return fTableBot.rowCount() == expected; }, nbOfRows, "Unable to refresh the table"); <START> } <END></code><technical_language>rework a bit</technical_language>

Target:
private void waitForTable(int nbOfRows) { SWTBotUtils.waitUntil(tableBot -> { UIThreadRunnable.syncExec(() -> { fTableViewer.refresh(); }); return tableBot.rowCount() == nbOfRows; }, fTableBot, "Unable to refresh the table"); }
Source:
<code>public ByteBufferImpl(byte[] buf, int offset, int length) { <START> this.buf = buf; <END> this.offset = offset; this.length = length; }</code><technical_language>do a defensive copy</technical_language>

Target:
public ByteBufferImpl(byte[] buf, int offset, int length) { if (buf == null) throw new IllegalArgumentException("Null buff not allowed!"); if (buf.length < offset + length) throw new IllegalArgumentException("Incorrect arguments: buff.length" + buf.length + ", offset=" + offset +", length="+ length); this.buf = buf; this.offset = offset; this.length = length; }
Source:
<code>public void registerCacheEntryListener(CacheEntryListenerConfiguration<K, V> cacheEntryListenerConfiguration, boolean addToConfig) { ensureOpen(); if (cacheEntryListenerConfiguration == null) { throw new NullPointerException("CacheEntryListenerConfiguration can't be null"); } CacheEventListenerAdaptor<K, V> adaptor = new CacheEventListenerAdaptor<>(this, cacheEntryListenerConfiguration, getSerializationService()); EventHandler handler = createHandler(adaptor); UUID regId = getContext().getListenerService().registerListener(createCacheEntryListenerCodec(nameWithPrefix), handler); if (addToConfig) { cacheConfig.addCacheEntryListenerConfiguration(cacheEntryListenerConfiguration); } addListenerLocally(regId, cacheEntryListenerConfiguration, adaptor); <START> if (addToConfig) { <END> updateCacheListenerConfigOnOtherNodes(cacheEntryListenerConfiguration, true); } }</code><technical_language>Is supposed regId != null time</technical_language>

Target:
public void registerCacheEntryListener(CacheEntryListenerConfiguration<K, V> cacheEntryListenerConfiguration, boolean addToConfig) { ensureOpen(); if (cacheEntryListenerConfiguration == null) { throw new NullPointerException("CacheEntryListenerConfiguration can't be null"); } CacheEventListenerAdaptor<K, V> adaptor = new CacheEventListenerAdaptor<>(this, cacheEntryListenerConfiguration, getSerializationService()); UUID regId = getContext().getListenerService() .registerListener(createCacheEntryListenerCodec(nameWithPrefix), createHandler(adaptor)); if (addToConfig) { cacheConfig.addCacheEntryListenerConfiguration(cacheEntryListenerConfiguration); } addListenerLocally(regId, cacheEntryListenerConfiguration, adaptor); if (addToConfig) { updateCacheListenerConfigOnOtherNodes(cacheEntryListenerConfiguration, true); } }
Source:
<code>public void unlockSettingsCodeSnippet() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); END: com.azure.data.applicationconfig.configurationclient.clearReadOnly#string-string ConfigurationSetting resultSetting = configurationClient .setReadOnly(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); END: com.azure.data.applicationconfig.configurationclient.clearReadOnly#ConfigurationSetting Response<ConfigurationSetting> responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), new Context(key2, value2)); System.out <START> .printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); <END> END: com.azure.data.applicationconfig.configurationclient.clearReadOnlyWithResponse#ConfigurationSetting-Context }</code><technical_language>Same. This line break is odd</technical_language>

Target:
public void unlockSettingsCodeSnippet() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); END: com.azure.data.applicationconfig.configurationclient.clearReadOnly#string-string ConfigurationSetting resultSetting = configurationClient.setReadOnlyWithResponse( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), Context.NONE).getValue(); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); END: com.azure.data.applicationconfig.configurationclient.clearReadOnly#ConfigurationSetting Response<ConfigurationSetting> responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), false, new Context(key2, value2)); System.out.printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); END: com.azure.data.applicationconfig.configurationclient.clearReadOnlyWithResponse#ConfigurationSetting-Context }
Source:
<code>private ClientMessage createAuthenticationMessage(HazelcastInstance hz, String clientName) { return ClientAuthenticationCodec.encodeRequest(hz.getConfig().getClusterName(), null, null, UUID.randomUUID(), "FOO", <START> (byte) 1, clientName, "xxx", new ArrayList<>(), -1, null); <END> }</code><technical_language>emptyList() instead new ArrayList<>()</technical_language>

Target:
private ClientMessage createAuthenticationMessage(HazelcastInstance hz, String clientName) { return ClientAuthenticationCodec.encodeRequest(hz.getConfig().getClusterName(), null, null, UUID.randomUUID(), "FOO", (byte) 1, clientName, "xxx", emptyList(), -1, null); }
Source:
<code>public AmazonS3Client getS3Client() { if (s3Client == null) { clientConfig = new ClientConfiguration(); clientConfig.setMaxErrorRetry(3); <START> s3Client = new AmazonS3Client(new AnonymousAWSCredentials()); <END> } return s3Client; }</code><technical_language>I figure this out, I asked @senderista in <LINK_0></technical_language>

Target:
public AmazonS3Client getS3Client() { if (s3Client == null) { clientConfig = new ClientConfiguration(); clientConfig.setMaxErrorRetry(3); s3Client = new AmazonS3Client(new DefaultAWSCredentialsProviderChain()); } return s3Client; }
Source:
<code>public int compare(SingleBenchmarkResult a, SingleBenchmarkResult b) { return new CompareToBuilder() .append(b.isFailure(), a.isFailure()) .append(b.getAverageUninitializedVariableCount(), a.getAverageUninitializedVariableCount()) <START> .append(a.getAverageScore(), b.getAverageScore(), resilientScoreComparator) <END> .toComparison(); }</code><technical_language>upgrade recipe need note of this (as [MINOR]), some users a custom Ranking implementation</technical_language>

Target:
public int compare(SingleBenchmarkResult a, SingleBenchmarkResult b) { return new CompareToBuilder() .append(b.hasAnyFailure(), a.hasAnyFailure()) .append(b.getAverageUninitializedVariableCount(), a.getAverageUninitializedVariableCount()) .append(a.getAverageScore(), b.getAverageScore(), resilientScoreComparator) .toComparison(); }
Source:
<code>public String getSampleType() { <START> return sampleType; <END> }</code><technical_language>add "this" qualifier</technical_language>

Target:
public String getSampleType() { return this.sampleType; }
Source:
<code><START> public void setDbxState(DbxState dbxState) { <END> editorState.setStateDbxState(dbxState); }</code><technical_language>of getters/setters removed. editorState getter/setter exposed other class wants modify state editor state getter/setter</technical_language>

Target:
public void setDbxState(DbxState dbxState) { this.dbxState = dbxState; }
Source:
<code>public static Properties defaultProperties() { final Properties properties = AzureManagementApiMetadata.defaultProperties(); properties.setProperty(OPERATION_TIMEOUT, "60000"); properties.setProperty(OPERATION_POLL_INITIAL_PERIOD, "5"); properties.setProperty(OPERATION_POLL_MAX_PERIOD, "15"); properties.setProperty(TCP_RULE_FORMAT, "tcp_%s-%s"); properties.setProperty(TCP_RULE_REGEXP, "tcp_\\d{1,5}-\\d{1,5}"); properties.put("oauth.endpoint", "<LINK_0>"); properties.put(JWS_ALG, "RS256"); <START> properties.put(AUDIENCE, "<LINK_0>"); <END> properties.put(RESOURCE, "<LINK_1>"); properties.put(CREDENTIAL_TYPE, CLIENT_CREDENTIALS_SECRET.toString()); return properties; }</code><technical_language>OAuth changes, properties required anymore, specific JWT token flow in Google Compute Engine specific</technical_language>

Target:
public static Properties defaultProperties() { final Properties properties = AzureManagementApiMetadata.defaultProperties(); properties.setProperty(OPERATION_TIMEOUT, "60000"); properties.setProperty(OPERATION_POLL_INITIAL_PERIOD, "5"); properties.setProperty(OPERATION_POLL_MAX_PERIOD, "15"); properties.setProperty(TCP_RULE_FORMAT, "tcp_%s-%s"); properties.setProperty(TCP_RULE_REGEXP, "tcp_\\d{1,5}-\\d{1,5}"); properties.put("oauth.endpoint", "<LINK_0>"); properties.put(RESOURCE, "<LINK_1>"); properties.put(CREDENTIAL_TYPE, CLIENT_CREDENTIALS_SECRET.toString()); return properties; }
Source:
<code>public GitHubSCMBuilder(@NonNull GitHubSCMSource source, @NonNull SCMHead head, @CheckForNull SCMRevision revision) { super(head, revision, guessRemote(source), source.getCredentialsId()); this.context = source.getOwner(); apiUri = StringUtils.defaultIfBlank(source.getApiUri(), GitHubServerConfig.GITHUB_URL); GitHubSCMSourceHelper helper = GitHubSCMSourceHelper.build(source); repoOwner = StringUtils.defaultIfBlank(source.getRepoOwner(), helper.owner); repository = StringUtils.defaultIfBlank(source.getRepository(), helper.repoName); <START> repositoryUrl = source.getRepositoryUrl()!=null?source.getRepositoryUrl() : helper.url; <END> withoutRefSpecs(); String repoUrl; if (head instanceof PullRequestSCMHead) { PullRequestSCMHead h = (PullRequestSCMHead) head; withRefSpec("+refs/pull/" + h.getId() + "/head:refs/remotes/@{remote}/" + head .getName()); repoUrl = repositoryUrl(h.getSourceOwner(), h.getSourceRepo()); } else if (head instanceof TagSCMHead) { withRefSpec("+refs/tags/" + head.getName() + ":refs/tags/" + head.getName()); repoUrl = repositoryUrl(repoOwner, repository); } else { withRefSpec("+refs/heads/" + head.getName() + ":refs/remotes/@{remote}/" + head.getName()); repoUrl = repositoryUrl(repoOwner, repository); } if (repoUrl != null) { withBrowser(new GithubWeb(repoUrl)); } withCredentials(credentialsId(), null); }</code><technical_language>lines able ignorant of helper, changes, right (and if not, I change implementations lines need change)? able this: repoOwner = source.getRepoOwner(); repository = source.getRepository(); repositoryUrl = source.getRepositoryUrl();</technical_language>

Target:
public GitHubSCMBuilder(@NonNull GitHubSCMSource source, @NonNull SCMHead head, @CheckForNull SCMRevision revision) { super(head, revision, guessRemote(source), source.getCredentialsId()); this.context = source.getOwner(); apiUri = StringUtils.defaultIfBlank(source.getApiUri(), GitHubServerConfig.GITHUB_URL); repoOwner = source.getRepoOwner(); repository = source.getRepository(); repositoryUrl = source.getRepositoryUrl(); withoutRefSpecs(); String repoUrl; if (head instanceof PullRequestSCMHead) { PullRequestSCMHead h = (PullRequestSCMHead) head; withRefSpec("+refs/pull/" + h.getId() + "/head:refs/remotes/@{remote}/" + head .getName()); repoUrl = repositoryUrl(h.getSourceOwner(), h.getSourceRepo()); } else if (head instanceof TagSCMHead) { withRefSpec("+refs/tags/" + head.getName() + ":refs/tags/" + head.getName()); repoUrl = repositoryUrl(repoOwner, repository); } else { withRefSpec("+refs/heads/" + head.getName() + ":refs/remotes/@{remote}/" + head.getName()); repoUrl = repositoryUrl(repoOwner, repository); } if (repoUrl != null) { withBrowser(new GithubWeb(repoUrl)); } withCredentials(credentialsId(), null); }
Source:
<code>public static ColumnResolver getResolverForCompiledDerivedTable(PhoenixConnection connection, TableRef tableRef, RowProjector projector) throws SQLException { List<PColumn> projectedColumns = new ArrayList<PColumn>(); List<Expression> sourceExpressions = new ArrayList<Expression>(); PTable table = tableRef.getTable(); for (PColumn column : table.getColumns()) { Expression sourceExpression = projector.getColumnProjector(column.getPosition()).getExpression(); PColumnImpl projectedColumn = new PColumnImpl(column.getName(), column.getFamilyName(), sourceExpression.getDataType(), sourceExpression.getMaxLength(), sourceExpression.getScale(), sourceExpression.isNullable(), <START> column.getPosition(), sourceExpression.getSortOrder(), column.getArraySize(), column.getViewConstant(), column.isViewReferenced(), null); <END> projectedColumns.add(projectedColumn); sourceExpressions.add(sourceExpression); } PTable t = PTableImpl.makePTable(table, projectedColumns); return new SingleTableColumnResolver(connection, new TableRef(tableRef.getTableAlias(), t, tableRef.getLowerBoundTimeStamp(), tableRef.hasDynamicCols())); }</code><technical_language>This is a copy constructor, instead of null for new arg, column.getExpressionStr()</technical_language>

Target:
public static ColumnResolver getResolverForCompiledDerivedTable(PhoenixConnection connection, TableRef tableRef, RowProjector projector) throws SQLException { List<PColumn> projectedColumns = new ArrayList<PColumn>(); List<Expression> sourceExpressions = new ArrayList<Expression>(); PTable table = tableRef.getTable(); for (PColumn column : table.getColumns()) { Expression sourceExpression = projector.getColumnProjector(column.getPosition()).getExpression(); PColumnImpl projectedColumn = new PColumnImpl(column.getName(), column.getFamilyName(), sourceExpression.getDataType(), sourceExpression.getMaxLength(), sourceExpression.getScale(), sourceExpression.isNullable(), column.getPosition(), sourceExpression.getSortOrder(), column.getArraySize(), column.getViewConstant(), column.isViewReferenced(), column.getExpressionStr()); projectedColumns.add(projectedColumn); sourceExpressions.add(sourceExpression); } PTable t = PTableImpl.makePTable(table, projectedColumns); return new SingleTableColumnResolver(connection, new TableRef(tableRef.getTableAlias(), t, tableRef.getLowerBoundTimeStamp(), tableRef.hasDynamicCols())); }
Source:
<code>public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { <START> checkQueue(); <END> return super.invokeAll(tasks); }</code><technical_language>pass size of list? checkQueue assumes add 1 item. I checkQueue(tasks.size())</technical_language>

Target:
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { checkQueue(tasks.size()); return super.invokeAll(tasks); }
Source:
<code>private String locateTool(String tool) { <START> String[] roots = { "/usr/bin/", "/usr/local/bin/", "/Users/christian/.nvm/versions/node/v6.6.0/bin/" }; <END> for (String root : roots) { if (new File(root + tool).exists()) { return root + tool; } } return null; }</code><technical_language>need a reference nodes setup</technical_language>

Target:
private String locateTool(String tool) { String[] roots = { "/usr/bin/", "/usr/local/bin/" }; for (String root : roots) { if (new File(root + tool).exists()) { return root + tool; } } return null; }
Source:
<code><START> List<JournalEntry> getAllEntries() { <END> List<JournalEntry> result = new ArrayList<>(); Offset lastOffset = getLastOffset(); if (lastOffset != null) { NavigableMap<Offset, StoreKey> journalView = journal.headMap(lastOffset, true); for (Map.Entry<Offset, StoreKey> entry : journalView.entrySet()) { result.add(new JournalEntry(entry.getKey(), entry.getValue())); } } return result; }</code><technical_language>i a concerned this is invoked. a huge waste of result thrown away</technical_language>

Target:
List<JournalEntry> getAllEntries() { List<JournalEntry> result = new ArrayList<>(); Offset lastOffset = getLastOffset(); journal.entrySet(); if (lastOffset != null) { NavigableMap<Offset, StoreKey> journalView = journal.headMap(lastOffset, true); for (Map.Entry<Offset, StoreKey> entry : journalView.entrySet()) { result.add(new JournalEntry(entry.getKey(), entry.getValue())); } } return result; }
Source:
<code>private void checkStatusCode(HttpURLConnection connection) throws Exception{ try { int responseCode = connection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { switch (responseCode) { case 401: case 403: throw new RCException(RCClient.ErrorCodes.ERROR_DEVICE_PUSH_NOTIFICATION_AUTHENTICATION_FORBIDDEN); case 404: throw new RCException(RCClient.ErrorCodes.ERROR_DEVICE_PUSH_NOTIFICATION_HTTP_NOT_FOUND); case 408: throw new RCException(RCClient.ErrorCodes.ERROR_DEVICE_PUSH_NOTIFICATION_TIMED_OUT); default: throw new RCException(RCClient.ErrorCodes.ERROR_DEVICE_PUSH_NOTIFICATION_UNKNOWN_ERROR); } } <START> } catch (Exception e) { <END> throw e; } }</code><technical_language>do need catch re-throw? throws Exception cover for IOException RCException</technical_language>

Target:
private void checkStatusCode(HttpURLConnection connection) throws Exception{ int responseCode = connection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { switch (responseCode) { case 401: case 403: throw new RCException(RCClient.ErrorCodes.ERROR_DEVICE_PUSH_NOTIFICATION_AUTHENTICATION_FORBIDDEN); case 404: throw new RCException(RCClient.ErrorCodes.ERROR_DEVICE_PUSH_NOTIFICATION_HTTP_NOT_FOUND); case 408: throw new RCException(RCClient.ErrorCodes.ERROR_DEVICE_PUSH_NOTIFICATION_TIMED_OUT); default: throw new RCException(RCClient.ErrorCodes.ERROR_DEVICE_PUSH_NOTIFICATION_UNKNOWN_ERROR); } } }
Source:
<code>public Authenticated authenticate(AuthenticationScheme authenticationScheme, Credentials credentials) throws ContextAuthenticationException { <START> if (log.isDebugEnabled()) { <END> log.debug("Authenticating with sheme: " + credentials.getAuthenticationScheme()); } Authenticated authenticated = null; try { authenticated = authenticationScheme.authenticate(credentials); this.user = authenticated.getUser(); notifyUserSessionListener(this.user, Event.LOGIN, Status.SUCCESS); } catch(ContextAuthenticationException e) { User loggingInUser = new User(); loggingInUser.setUsername(credentials.getClientName()); notifyUserSessionListener(loggingInUser, Event.LOGIN, Status.FAIL); throw e; } setUserLocation(); if (log.isDebugEnabled()) { log.debug("Authenticated as: " + this.user); } return authenticated; }</code><technical_language>Do want log client name</technical_language>

Target:
public Authenticated authenticate(AuthenticationScheme authenticationScheme, Credentials credentials) throws ContextAuthenticationException { if (log.isDebugEnabled()) { log.debug("Authenticating client '" + credentials.getClientName() + "' with sheme: " + credentials.getAuthenticationScheme()); } Authenticated authenticated = null; try { authenticated = authenticationScheme.authenticate(credentials); this.user = authenticated.getUser(); notifyUserSessionListener(this.user, Event.LOGIN, Status.SUCCESS); } catch(ContextAuthenticationException e) { User loggingInUser = new User(); loggingInUser.setUsername(credentials.getClientName()); notifyUserSessionListener(loggingInUser, Event.LOGIN, Status.FAIL); throw e; } setUserLocation(); if (log.isDebugEnabled()) { log.debug("Authenticated as: " + this.user); } return authenticated; }
Source:
<code>public void clickOnAdImage(String slotName){ <START> wait.forElementVisible(By.cssSelector(AdsContent.getSlotSelector(slotName))); <END> driver.findElement(By.cssSelector(AdsContent.getSlotSelector(slotName))).click(); PageObjectLogging.log("clickOnAdImage", slotName + " is clicked", true); }</code><technical_language>This test works selenium driver is clicking TOP_LEADERBOARD point clicks is a video trigger. a selector represents "click through" background of VUAP? If not, leave is. highly probable test campaign</technical_language>

Target:
public void clickOnAdImage(String slotName){ adSelector(slotName); adSelector(slotName).click(); PageObjectLogging.log("clickOnAdImage", slotName + " is clicked", true); }
Source:
<code>private JsonNode asJson(Object target) throws AccessException { if (target instanceof ContainerNode) { return (ContainerNode<?>) target; } else if (target instanceof JsonNodeWrapper && ((JsonNodeWrapper) target).getTarget() instanceof JsonNode) { JsonNodeWrapper wrapper = (JsonNodeWrapper) target; return assertContainerNode((JsonNode) wrapper.getTarget()); } <START> else if (target instanceof String) { <END> try { JsonNode json = this.objectMapper.readTree((String) target); return assertContainerNode(json); } catch (JsonProcessingException e) { throw new AccessException("Exception while trying to deserialize String", e); } } else { throw new IllegalStateException("Can't happen. Check SUPPORTED_CLASSES"); } }</code><technical_language>need assertion all. if (index != null && container.has(index)) { return typedValue(container.get(index)); } So, good deal JsonNode get. previous Jackson version different, is a bit easier avoid extra checks</technical_language>

Target:
private JsonNode asJson(Object target) throws AccessException { if (target instanceof ContainerNode) { return (ContainerNode<?>) target; } else if (target instanceof JsonNodeWrapper && ((JsonNodeWrapper<?>) target).getRealNode() instanceof JsonNode) { return ((JsonNodeWrapper<?>) target).getRealNode(); } else if (target instanceof String) { try { return this.objectMapper.readTree((String) target); } catch (JsonProcessingException e) { throw new AccessException("Exception while trying to deserialize String", e); } } else { throw new IllegalStateException("Can't happen. Check SUPPORTED_CLASSES"); } }
Source:
<code>private IFrameDMContext createFrameContext(IExecutionDMContext execCtx, String frameNum) { assert execCtx != null && frameNum != null; if (execCtx == null || frameNum == null) {return null;} int intFrameNum = 0; try { intFrameNum = Integer.parseInt(frameNum); } catch (NumberFormatException e){ GdbPlugin.log(e); } <START> return ((MIStack)(stackService)).createFrameDMContext(execCtx, intFrameNum); <END> }</code><technical_language>This cast remove if stackService is of type MIStack</technical_language>

Target:
private IFrameDMContext createFrameContext(IExecutionDMContext execCtx, String frameNum) { assert execCtx != null && frameNum != null; if (execCtx == null || frameNum == null) { return null; } int intFrameNum = 0; try { intFrameNum = Integer.parseInt(frameNum); } catch (NumberFormatException e){ GdbPlugin.log(e); } return fStackService.createFrameDMContext(execCtx, intFrameNum); }
Source:
<code>private Set<GlusterVolumeEntity> getExistingSessionSlaveVolumes() { Set<GlusterVolumeEntity> volumesAlreadySlaveOfGeoRepSessions = new HashSet<GlusterVolumeEntity>(); for(GlusterGeoRepSession session : getDbFacade().getGlusterGeoRepDao().getAllSessions()) { String slaveVolumeName = session.getSlaveVolumeName(); String slaveHostName = session.getSlaveHostName(); <START> GlusterVolumeEntity slaveVolume = getGlusterVolumeDao().getByName(getVdsDao().getByName(slaveHostName).getVdsGroupId(), slaveVolumeName); <END> volumesAlreadySlaveOfGeoRepSessions.add(slaveVolume); } return volumesAlreadySlaveOfGeoRepSessions; }</code><technical_language>NPE here. I session.getSlaveVolumeId() instead. If slaveVolume exists in DB, this field populated</technical_language>

Target:
private Set<GlusterVolumeEntity> getExistingSessionSlaveVolumes() { Set<GlusterVolumeEntity> volumesAlreadySlaveOfGeoRepSessions = new HashSet<GlusterVolumeEntity>(); for(GlusterGeoRepSession session : getDbFacade().getGlusterGeoRepDao().getAllSessions()) { Guid slaveVolumeId = session.getSlaveVolumeId(); if(slaveVolumeId != null) { GlusterVolumeEntity slaveVolume = getGlusterVolumeDao().getById(slaveVolumeId); volumesAlreadySlaveOfGeoRepSessions.add(slaveVolume); } } return volumesAlreadySlaveOfGeoRepSessions; }
Source:
<code>public void basicCancel(final String consumerTag) throws IOException { final Consumer originalConsumer = _consumers.get(consumerTag); if (originalConsumer == null) throw new IOException("Unknown consumerTag"); BlockingRpcContinuation<Consumer> k = new BlockingRpcContinuation<Consumer>() { @Override public Consumer transformReply(AMQCommand replyCommand) { <START> ((Basic.CancelOk) replyCommand.getMethod()).getConsumerTag(); END> _consumers.remove(consumerTag); dispatcher.handleCancelOk(originalConsumer, consumerTag); return originalConsumer; } }; final Method m = new Basic.Cancel(consumerTag, false); rpc(m, k); try { if(_rpcTimeout == NO_RPC_TIMEOUT) { k.getReply(); } else { try { k.getReply(_rpcTimeout); } catch (TimeoutException e) { throw wrapTimeoutException(m, e); } } } catch(ShutdownSignalException ex) { throw wrap(ex); } metricsCollector.basicCancel(this, consumerTag); }</code><technical_language>OK, want trigger "unsynchronized" RPC responses problem here, right? If so, wrap in try/catch block log exception a warning, avoid changing behavior much. Thanks</technical_language>

Target:
public void basicCancel(final String consumerTag) throws IOException { final Consumer originalConsumer = _consumers.get(consumerTag); if (originalConsumer == null) throw new IOException("Unknown consumerTag"); BlockingRpcContinuation<Consumer> k = new BlockingRpcContinuation<Consumer>() { @Override public Consumer transformReply(AMQCommand replyCommand) { if (!(replyCommand.getMethod() instanceof Basic.CancelOk)) LOGGER.warn("Received reply was not of expected method Basic.CancelOk", replyCommand.getMethod()); _consumers.remove(consumerTag); dispatcher.handleCancelOk(originalConsumer, consumerTag); return originalConsumer; } }; final Method m = new Basic.Cancel(consumerTag, false); rpc(m, k); try { if(_rpcTimeout == NO_RPC_TIMEOUT) { k.getReply(); } else { try { k.getReply(_rpcTimeout); } catch (TimeoutException e) { throw wrapTimeoutException(m, e); } } } catch(ShutdownSignalException ex) { throw wrap(ex); } metricsCollector.basicCancel(this, consumerTag); }
Source:
<code>public ModifiableRealmIdentity getRealmIdentityForUpdate(Principal principal) throws RealmUnavailableException { removeFromCache(principal); <START> return getModifiableSecurityRealm().getRealmIdentityForUpdate(principal); <END> }</code><technical_language>inherent race here, if sequence occurs: 1. Thread A: getRealmIdentityForUpdate 2. Thread A: removeFromCache 3. Thread B: getRealmIdentity 4. Thread A: modify credentials 5. Thread B: authenticate wrong credentials, cached entry removed cache *after* modifications occur, i.e. ModifiableRealmIdentity wrapped I tell</technical_language>

Target:
public ModifiableRealmIdentity getRealmIdentityForUpdate(Principal principal) throws RealmUnavailableException { return wrap(getModifiableSecurityRealm().getRealmIdentityForUpdate(principal)); }
Source:
<code>private void fetchRemoteData() { WordPress.getRestClientUtils().getGeneralSettings( String.valueOf(mBlog.getRemoteBlogId()), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { <START> handleResponseToGeneralSettingsRequest(response); <END> } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { AppLog.w(AppLog.T.API, "Error GETing site settings: " + error); if (isAdded()) { ToastUtils.showToast(getActivity(), getString(R.string.error_fetch_remote_site_settings)); getActivity().finish(); } } }); }</code><technical_language>I isAdded() check is needed here</technical_language>

Target:
private void fetchRemoteData() { if (mBlog.isDotcomFlag()) { WordPress.getRestClientUtils().getGeneralSettings( String.valueOf(mBlog.getRemoteBlogId()), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { if (isAdded()) { handleResponseToWPComSettingsRequest(response); } } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { handleSettingsFetchError(error.toString()); } }); } else { Object[] params = { mBlog.getRemoteBlogId(), mBlog.getUsername(), mBlog.getPassword() }; instantiateInterface().callAsync(mXmlRpcFetchCallback, ApiHelper.Methods.GET_OPTIONS, params); } }
Source:
<code>public Optional<Group> getGroupById(long id) { GroupsRecord r = dslContext.fetchOne(GROUPS, GROUPS.ID.eq(Math.toIntExact(id))); if (r != null) { <START> return Optional.of(r.map(new GroupMapper())); <END> } return Optional.empty(); }</code><technical_language>Optional.map</technical_language>

Target:
public Optional<Group> getGroupById(long id) { GroupsRecord r = dslContext.fetchOne(GROUPS, GROUPS.ID.eq(Math.toIntExact(id))); return Optional.ofNullable(r).map( (rec) -> rec.map(new GroupMapper())); }
Source:
<code>public void create(final Scenario scenario) { try { verifyPreCondition(scenario); resetMail(); RpslObject objectForScenario = objectForScenario(scenario); logEvent("Creating", objectForScenario); <START> WhoisResources whoisResourcesResp = RestTest.target(context.getRestPort(), <END> "whois/test/mntner?password=123") .request() .post(Entity.entity(context.getWhoisObjectMapper().mapRpslObjects(FormattedClientAttributeMapper.class, objectForScenario), MediaType.APPLICATION_XML), WhoisResources.class); logEvent("Created", whoisResourcesResp); RpslObject resp = context.getWhoisObjectMapper().map(whoisResourcesResp.getWhoisObjects().get(0), FormattedClientAttributeMapper.class); verifyPostCondition(scenario, resp, Scenario.Result.SUCCESS); verifyNotificationEmail(scenario); } catch (ClientErrorException exc) { logEvent("Create", exc.getResponse().readEntity(WhoisResources.class)); verifyPostCondition(scenario, Scenario.Result.FAILURE); verifyNotificationEmail(scenario); } }</code><technical_language>"whoisResources" is clearer (or full word "Resp", i.e. "response")</technical_language>

Target:
public void create(final Scenario scenario) { try { verifyPreCondition(scenario); resetMail(); RpslObject objectForScenario = objectForScenario(scenario); logEvent("Creating", objectForScenario); WhoisResources whoisResources = RestTest.target(context.getRestPort(), "whois/test/mntner?password=123") .request() .post(Entity.entity(context.getWhoisObjectMapper().mapRpslObjects(FormattedClientAttributeMapper.class, objectForScenario), MediaType.APPLICATION_XML), WhoisResources.class); logEvent("Created", whoisResources); verifyPostCondition(scenario, Scenario.Result.SUCCESS, whoisResources); verifyNotificationEmail(scenario); } catch (ClientErrorException exc) { logEvent("Create", exc.getResponse().readEntity(WhoisResources.class)); verifyPostCondition(scenario, Scenario.Result.FAILURE); verifyNotificationEmail(scenario); } }
Source:
<code>public void testStartpointTimestampVisitorShouldUpdateTheFetchOffsetInConsumer() { final Long testTimeStamp = 10L; final KafkaConsumer consumer = Mockito.mock(KafkaConsumer.class); final KafkaConsumerProxy kafkaConsumerProxy = Mockito.mock(KafkaConsumerProxy.class); KafkaSystemConsumer kafkaSystemConsumer = new KafkaSystemConsumer(consumer, TEST_SYSTEM, new MapConfig(), TEST_CLIENT_ID, kafkaConsumerProxy, Mockito.mock(KafkaSystemConsumerMetrics.class), new TestClock(), REGISTRATION_HANDLER); KafkaStartpointRegistrationHandler kafkaStartpointRegistrationHandler = kafkaSystemConsumer.new KafkaStartpointRegistrationHandler(); final StartpointTimestamp startpointTimestamp = new StartpointTimestamp(testTimeStamp); final Map<TopicPartition, OffsetAndTimestamp> offsetForTimesResult = ImmutableMap.of( TEST_TOPIC_PARTITION, new OffsetAndTimestamp(Long.valueOf(TEST_OFFSET), testTimeStamp)); Mockito.when(consumer.offsetsForTimes(Mockito.anyMap())).thenReturn(offsetForTimesResult); Mockito.doNothing().when(consumer).seek(TEST_TOPIC_PARTITION, Long.valueOf(TEST_OFFSET)); kafkaStartpointRegistrationHandler.visit(TEST_SYSTEM_STREAM_PARTITION, startpointTimestamp); Mockito.verify(consumer).seek(TEST_TOPIC_PARTITION, Long.valueOf(TEST_OFFSET)); Mockito.verify(consumer).offsetsForTimes(Mockito.anyMap()); <START> Mockito.verify(kafkaConsumerProxy).addTopicPartition(Mockito.any(SystemStreamPartition.class), Mockito.anyLong()); <END> }</code><technical_language>"any"</technical_language>

Target:
public void testStartpointTimestampVisitorShouldUpdateTheFetchOffsetInConsumer() { final Long testTimeStamp = 10L; final KafkaConsumer consumer = Mockito.mock(KafkaConsumer.class); final KafkaConsumerProxy kafkaConsumerProxy = Mockito.mock(KafkaConsumerProxy.class); final KafkaStartpointRegistrationHandler kafkaStartpointRegistrationHandler = new KafkaStartpointRegistrationHandler(consumer, kafkaConsumerProxy); final StartpointTimestamp startpointTimestamp = new StartpointTimestamp(testTimeStamp); final Map<TopicPartition, OffsetAndTimestamp> offsetForTimesResult = ImmutableMap.of( TEST_TOPIC_PARTITION, new OffsetAndTimestamp(Long.valueOf(TEST_OFFSET), testTimeStamp)); Mockito.when(consumer.offsetsForTimes(ImmutableMap.of(TEST_TOPIC_PARTITION, testTimeStamp))).thenReturn(offsetForTimesResult); Mockito.doNothing().when(consumer).seek(TEST_TOPIC_PARTITION, Long.valueOf(TEST_OFFSET)); Mockito.when(consumer.position(TEST_TOPIC_PARTITION)).thenReturn(Long.valueOf(TEST_OFFSET)); kafkaStartpointRegistrationHandler.visit(TEST_SYSTEM_STREAM_PARTITION, startpointTimestamp); Mockito.verify(consumer).seek(TEST_TOPIC_PARTITION, Long.valueOf(TEST_OFFSET)); Mockito.verify(consumer).offsetsForTimes(ImmutableMap.of(TEST_TOPIC_PARTITION, testTimeStamp)); Mockito.verify(kafkaConsumerProxy).addTopicPartition(TEST_SYSTEM_STREAM_PARTITION, Long.valueOf(TEST_OFFSET)); }
Source:
<code>public void testAfterSessionExpiration() throws Exception { TestingServer oldServer = server; Semaphore counter = new Semaphore(0); final CuratorFramework client = newClient(counter); try { client.start(); final CountDownLatch connectedLatch = new CountDownLatch(1); final CountDownLatch lostLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.CONNECTED ) { connectedLatch.countDown(); } if ( newState == ConnectionState.LOST ) { lostLatch.countDown(); } if ( newState == ConnectionState.RECONNECTED ) { reconnectedLatch.countDown(); } } }; <START> client.getConnectionStateListenable().addListener(listener); <END> Assert.assertTrue(timing.awaitLatch(connectedLatch)); server.stop(); Assert.assertTrue(timing.awaitLatch(lostLatch)); counter.drainPermits(); for ( int i = 0; i < 5; ++i ) { Assert.assertTrue(timing.acquireSemaphore(counter), "Failed when i is: " + i); } server = new TestingServer(); Assert.assertTrue(timing.awaitLatch(reconnectedLatch)); } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(oldServer); } }</code><technical_language>Is a potential race condition here? connected event listener is added client is started prior listener added</technical_language>

Target:
public void testAfterSessionExpiration() throws Exception { TestingServer oldServer = server; Semaphore counter = new Semaphore(0); final CuratorFramework client = newClient(counter); try { final CountDownLatch connectedLatch = new CountDownLatch(1); final CountDownLatch lostLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ( newState == ConnectionState.CONNECTED ) { connectedLatch.countDown(); } if ( newState == ConnectionState.LOST ) { lostLatch.countDown(); } if ( newState == ConnectionState.RECONNECTED ) { reconnectedLatch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); client.start(); Assert.assertTrue(timing.awaitLatch(connectedLatch)); server.stop(); Assert.assertTrue(timing.awaitLatch(lostLatch)); counter.drainPermits(); for ( int i = 0; i < 5; ++i ) { Assert.assertTrue(timing.acquireSemaphore(counter), "Failed when i is: " + i); } server = new TestingServer(); Assert.assertTrue(timing.awaitLatch(reconnectedLatch)); } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(oldServer); } }
Source:
<code>public QProfileComparisonResult compare(DbSession dbSession, QualityProfileDto left, QualityProfileDto right) { <START> QProfileComparisonResult result = new QProfileComparisonResult(); <END> result.left = left; result.right = right; Map<RuleKey, ActiveRuleDto> leftActiveRulesByRuleKey = loadActiveRules(dbSession, left); Map<RuleKey, ActiveRuleDto> rightActiveRulesByRuleKey = loadActiveRules(dbSession, right); Set<RuleKey> allRules = Sets.newHashSet(); allRules.addAll(leftActiveRulesByRuleKey.keySet()); allRules.addAll(rightActiveRulesByRuleKey.keySet()); for (RuleKey ruleKey : allRules) { if (!leftActiveRulesByRuleKey.containsKey(ruleKey)) { result.inRight.put(ruleKey, rightActiveRulesByRuleKey.get(ruleKey)); } else if (!rightActiveRulesByRuleKey.containsKey(ruleKey)) { result.inLeft.put(ruleKey, leftActiveRulesByRuleKey.get(ruleKey)); } else { compareActivationParams(dbSession, leftActiveRulesByRuleKey.get(ruleKey), rightActiveRulesByRuleKey.get(ruleKey), result); } } return result; }</code><technical_language>legacy code, I know, sense left right properties final (ie. mutable)</technical_language>

Target:
public QProfileComparisonResult compare(DbSession dbSession, QualityProfileDto left, QualityProfileDto right) { Map<RuleKey, ActiveRuleDto> leftActiveRulesByRuleKey = loadActiveRules(dbSession, left); Map<RuleKey, ActiveRuleDto> rightActiveRulesByRuleKey = loadActiveRules(dbSession, right); Set<RuleKey> allRules = Sets.newHashSet(); allRules.addAll(leftActiveRulesByRuleKey.keySet()); allRules.addAll(rightActiveRulesByRuleKey.keySet()); QProfileComparisonResult result = new QProfileComparisonResult(left, right); for (RuleKey ruleKey : allRules) { if (!leftActiveRulesByRuleKey.containsKey(ruleKey)) { result.inRight.put(ruleKey, rightActiveRulesByRuleKey.get(ruleKey)); } else if (!rightActiveRulesByRuleKey.containsKey(ruleKey)) { result.inLeft.put(ruleKey, leftActiveRulesByRuleKey.get(ruleKey)); } else { compareActivationParams(dbSession, leftActiveRulesByRuleKey.get(ruleKey), rightActiveRulesByRuleKey.get(ruleKey), result); } } return result; }
Source:
<code>public String toString() { StringBuilder buf = new StringBuilder(); if (approximate && distinct) { buf.append("APPROX_COUNT_DISTINCT"); <START> } else { <END> buf.append(aggFunction.toString()); } buf.append("("); if (distinct && !approximate) { buf.append((argList.size() == 0) ? "DISTINCT" : "DISTINCT "); } int i = -1; for (Integer arg : argList) { if (++i > 0) { buf.append(", "); } buf.append("$"); buf.append(arg); } buf.append(")"); if (!collation.equals(RelCollations.EMPTY)) { buf.append(" WITHIN GROUP ("); buf.append(collation); buf.append(")"); } if (hasFilter()) { buf.append(" FILTER $"); buf.append(filterArg); } return buf.toString(); }</code><technical_language>Agreed Julian, modify agg call name is a unique identifier of function, add some distinct flag Aggregate digest instead: java public RelWriter explainTerms(RelWriter pw) { // skip "groups" element if is a singleton of "group". super.explainTerms(pw) .item("group", groupSet) .itemIf("groups", groupSets, getGroupType() != Group.SIMPLE) .itemIf("aggs", aggCalls, pw.nest()); if (!pw.nest()) { for (Ord<AggregateCall> ord : Ord.zip(aggCalls)) { pw.item(Util.first(ord.e.name, "agg#" + ord.i), ord.e); } } return pw; }</technical_language>

Target:
public String toString() { StringBuilder buf = new StringBuilder(aggFunction.toString()); buf.append("("); if (approximate) { buf.append("APPROXIMATE "); } if (distinct) { buf.append((argList.size() == 0) ? "DISTINCT" : "DISTINCT "); } int i = -1; for (Integer arg : argList) { if (++i > 0) { buf.append(", "); } buf.append("$"); buf.append(arg); } buf.append(")"); if (!collation.equals(RelCollations.EMPTY)) { buf.append(" WITHIN GROUP ("); buf.append(collation); buf.append(")"); } if (hasFilter()) { buf.append(" FILTER $"); buf.append(filterArg); } return buf.toString(); }