auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void announceTask(Worker theWorker, RemoteTaskRunnerWorkItem taskRunnerWorkItem) throws Exception { final Task task = taskRunnerWorkItem.getTask(); log.info("Coordinator asking Worker[%s] to add task[%s]", theWorker.getHost(), task.getId()); byte[] rawBytes = jsonMapper.writeValueAsBytes(task); if (rawBytes.length > config.getMaxNumBytes()) { throw new ISE("Length of raw bytes for task too large[%,d > %,d]", rawBytes.length, config.getMaxNumBytes()); } String taskPath = JOINER.join(config.getIndexerTaskPath(), theWorker.getHost(), task.getId()); if (cf.checkExists().forPath(taskPath) == null) { cf.create() .withMode(CreateMode.EPHEMERAL) .forPath( taskPath, rawBytes ); } <START> runningTasks.put(task.getId(), pendingTasks.remove(task.getId()).withWorker(theWorker)); <END> log.info("Task %s switched from pending to running", task.getId()); Stopwatch timeoutStopwatch = new Stopwatch(); timeoutStopwatch.start(); synchronized (statusLock) { while (!isWorkerRunningTask(theWorker, task)) { statusLock.wait(config.getTaskAssignmentTimeoutDuration().getMillis()); if (timeoutStopwatch.elapsed(TimeUnit.MILLISECONDS) >= config.getTaskAssignmentTimeoutDuration().getMillis()) { log.error( "Something went wrong! %s never ran task %s after %s!", theWorker.getHost(), task.getId(), config.getTaskAssignmentTimeoutDuration() ); taskRunnerWorkItem.setResult(TaskStatus.failure(taskRunnerWorkItem.getTask().getId())); break; } } } }</code><technical_language>pendingTasks.remove() null</technical_language>

Target:
private void announceTask(Worker theWorker, RemoteTaskRunnerWorkItem taskRunnerWorkItem) throws Exception { final Task task = taskRunnerWorkItem.getTask(); log.info("Coordinator asking Worker[%s] to add task[%s]", theWorker.getHost(), task.getId()); byte[] rawBytes = jsonMapper.writeValueAsBytes(task); if (rawBytes.length > config.getMaxNumBytes()) { throw new ISE("Length of raw bytes for task too large[%,d > %,d]", rawBytes.length, config.getMaxNumBytes()); } String taskPath = JOINER.join(config.getIndexerTaskPath(), theWorker.getHost(), task.getId()); if (cf.checkExists().forPath(taskPath) == null) { cf.create() .withMode(CreateMode.EPHEMERAL) .forPath( taskPath, rawBytes ); } RemoteTaskRunnerWorkItem workItem = pendingTasks.remove(task.getId()); if (workItem == null) { log.makeAlert("WTF?! Got a null work item from pending tasks?! How can this be?!") .addData("taskId", task.getId()) .emit(); return; } runningTasks.put(task.getId(), workItem.withWorker(theWorker)); log.info("Task %s switched from pending to running", task.getId()); Stopwatch timeoutStopwatch = new Stopwatch(); timeoutStopwatch.start(); synchronized (statusLock) { while (!isWorkerRunningTask(theWorker, task)) { statusLock.wait(config.getTaskAssignmentTimeoutDuration().getMillis()); if (timeoutStopwatch.elapsed(TimeUnit.MILLISECONDS) >= config.getTaskAssignmentTimeoutDuration().getMillis()) { log.error( "Something went wrong! %s never ran task %s after %s!", theWorker.getHost(), task.getId(), config.getTaskAssignmentTimeoutDuration() ); taskRunnerWorkItem.setResult(TaskStatus.failure(taskRunnerWorkItem.getTask().getId())); break; } } } }
Source:
<code>public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { Attributes resAtts = atts; <START> if ((TOPIC_XREF.matches(atts) || TOPIC_LINK.matches(atts) || TOPIC_IMAGE.matches(atts) || SVG_D_SVGREF.matches(atts)) <END> && !Objects.equals(ATTR_SCOPE_VALUE_EXTERNAL, atts.getValue(ATTRIBUTE_NAME_SCOPE)) && atts.getValue(ATTRIBUTE_NAME_HREF) != null) { resAtts = new XMLUtils.AttributesBuilder(atts) .add(ATTRIBUTE_NAME_HREF, updateHref(atts.getValue(ATTRIBUTE_NAME_HREF))) .build(); } getContentHandler().startElement(uri, localName, qName, resAtts); }</code><technical_language>I addition anything, <svgref> is specialized xref match condition</technical_language>

Target:
public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { Attributes resAtts = atts; if ((TOPIC_XREF.matches(atts) || TOPIC_LINK.matches(atts) || TOPIC_IMAGE.matches(atts)) && !Objects.equals(ATTR_SCOPE_VALUE_EXTERNAL, atts.getValue(ATTRIBUTE_NAME_SCOPE)) && atts.getValue(ATTRIBUTE_NAME_HREF) != null) { resAtts = new XMLUtils.AttributesBuilder(atts) .add(ATTRIBUTE_NAME_HREF, updateHref(atts.getValue(ATTRIBUTE_NAME_HREF))) .build(); } getContentHandler().startElement(uri, localName, qName, resAtts); }
Source:
<code><START> public QueryTraversal(GraphQLSchema schema, <END> Document document, String operation, Map<String, Object> variables) { NodeUtil.GetOperationResult getOperationResult = NodeUtil.getOperation(document, operation); this.schema = schema; this.variables = variables; this.fragmentsByName = getOperationResult.fragmentsByName; this.roots = getOperationResult.operationDefinition.getSelectionSet().getChildren(); this.rootParentType = getRootTypeFromOperation(getOperationResult.operationDefinition); this.childrenOfSelectionProvider = new ChildrenOfSelectionProvider(fragmentsByName); }</code><technical_language>Put a Builder this constructor private. This allows for API evolution time</technical_language>

Target:
private QueryTraversal(GraphQLSchema schema, Document document, String operation, Map<String, Object> variables) { assertNotNull(document, "document can't be null"); NodeUtil.GetOperationResult getOperationResult = NodeUtil.getOperation(document, operation); this.schema = assertNotNull(schema, "schema can't be null"); this.variables = assertNotNull(variables, "variables can't be null"); this.fragmentsByName = getOperationResult.fragmentsByName; this.roots = getOperationResult.operationDefinition.getSelectionSet().getChildren(); this.rootParentType = getRootTypeFromOperation(getOperationResult.operationDefinition); this.childrenOfSelectionProvider = new ChildrenOfSelectionProvider(fragmentsByName); }
Source:
<code>private void invalidate() { List<String> expiredList = new ArrayList<>(); try { expiredList = activityDao.findExpired(System.currentTimeMillis()); } catch (ServerException e) { <START> LOG.error(e.getLocalizedMessage(), e); <END> } for (String workspaceId : expiredList) { try { Workspace workspace = workspaceManager.getWorkspace(workspaceId); workspace.getAttributes().put(WORKSPACE_STOPPED_BY, ACTIVITY_CHECKER); workspaceManager.updateWorkspace(workspaceId, workspace); workspaceManager.stopWorkspace(workspaceId, emptyMap()); } catch (NotFoundException ignored) { } catch (ConflictException e) { LOG.warn(e.getLocalizedMessage()); } catch (Exception ex) { LOG.error(ex.getLocalizedMessage()); LOG.debug(ex.getLocalizedMessage(), ex); } finally { try { activityDao.removeExpiration(workspaceId); } catch (ServerException e) { LOG.error(e.getLocalizedMessage(), e); } } } }</code><technical_language>In this case, flow is kinda interrupted expiredList empty. sense put return explicitly show this</technical_language>

Target:
private void invalidate() { try { activityDao.findExpired(System.currentTimeMillis()).forEach(this::stopExpired); } catch (ServerException e) { LOG.error(e.getLocalizedMessage(), e); } }
Source:
<code>public void testStrictVerificationFailure() { PrintableResult result = testResult(HasTempFolderWithAssuredDeletion.class); assertThat(result, failureCountIs(1)); <START> assertThat(result.toString(), CoreMatchers.containsString("Unable to clean up temporary folder")); <END> }</code><technical_language>Please add a static import for containsString</technical_language>

Target:
public void testStrictVerificationFailure() { PrintableResult result = testResult(HasTempFolderWithAssuredDeletion.class); assertThat(result, failureCountIs(1)); assertThat(result.toString(), containsString("Unable to clean up temporary folder")); }
Source:
<code>public void testDefault() throws Exception { final String msg = getCheckMessage(InvalidJavadocPositionCheck.class, "invalid.position"); final String[] expected = { "1:9: " + msg, <START> "3:1: " + msg, <END> "6:1: " + msg, "9:5: " + msg, "13:5: " + msg, "23:9: " + msg, "24:17: " + msg, "25:17: " + msg, "35:10: " + msg, "36:19: " + msg, "37:19: " + msg, "38:21: " + msg, "39:23: " + msg, "43:1: " + msg, "45:7: " + msg, "46:36: " + msg, "47:1: " + msg, }; final Configuration checkConfig = getModuleConfig("InvalidJavadocPosition"); final String filePath = getPath("InputInvalidJavadocPosition.java"); final Integer[] warnList = getLinesWithWarn(filePath); verify(checkConfig, filePath, expected, warnList); }</code><technical_language>please name variable message , better</technical_language>

Target:
public void testDefault() throws Exception { final String message = getCheckMessage(InvalidJavadocPositionCheck.class, "invalid.position"); final String[] expected = { "1:9: " + message, "3:1: " + message, "6:1: " + message, "9:5: " + message, "14:5: " + message, "17:5: " + message, "27:9: " + message, "28:17: " + message, "29:17: " + message, "39:10: " + message, "40:19: " + message, "41:19: " + message, "42:21: " + message, "43:23: " + message, "47:1: " + message, "52:7: " + message, "53:36: " + message, "54:1: " + message, }; final Configuration checkConfig = getModuleConfig("InvalidJavadocPosition"); final String filePath = getPath("InputInvalidJavadocPosition.java"); final Integer[] warnList = getLinesWithWarn(filePath); verify(checkConfig, filePath, expected, warnList); }
Source:
<code>public UndefinedExpressionColumn(final HeaderMetaData headerMetaData, final UndefinedExpressionGrid gridWidget, final CellEditorControls cellEditorControls, final Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier) { this(new ArrayList<HeaderMetaData>() {{ add(headerMetaData); <START> }}, <END> gridWidget, cellEditorControls, expressionEditorDefinitionsSupplier); }</code><technical_language>shortened as: Collections.singletonList(headerMetadata)</technical_language>

Target:
public UndefinedExpressionColumn(final HeaderMetaData headerMetaData, final UndefinedExpressionGrid gridWidget, final CellEditorControls cellEditorControls, final Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier) { this(Collections.singletonList(headerMetaData), gridWidget, cellEditorControls, expressionEditorDefinitionsSupplier); }
Source:
<code>ContiguousOffsetCalculator(int numBlocks) { if (numBlocks <= 0 && (numBlocks & (numBlocks - 1)) == 0) { throw new IllegalArgumentException("maxOffset " + numBlocks + " must be greater than 0 and a power of 2"); <START> } <END> offsetBitPosition = 31 - Integer.numberOfTrailingZeros(numBlocks); }</code><technical_language>MAXIMUM_CAPACITY is longer</technical_language>

Target:
ContiguousOffsetCalculator(int numBlocks) { if (numBlocks <= 0 || (numBlocks & (numBlocks - 1)) != 0) { throw new IllegalArgumentException("numBlocks " + numBlocks + " must be greater than 0 and a power of 2"); } offsetShift = 31 - Integer.numberOfTrailingZeros(numBlocks); }
Source:
<code>default PlanNode resolve(PlanNode node) { <START> if (node instanceof GroupReference) { <END> return getOnlyElement(resolveGroup(node)); } return node; }</code><technical_language>rationale for semantics for resolve resolveGroup? arguments in commit message apply for Lookup::resolve (while depricated is valid method of interface). previous semantics of methods is a bit more natural: * resolveGroup: resolve a group (whatever means) * resolve: resolveGroup, assume group is singleton (valid for iterative) In fact, current semantics of resolve is convenience strict semantics. Do want get rid of this convenience eventually? E.g: test algorithms raw trees group references</technical_language>

Target:
default PlanNode resolve(PlanNode node) { if (node instanceof GroupReference) { return resolveGroup(node).collect(toOptional()).get(); } return node; }
Source:
<code>private List<Long> getCommittedTimestampsDescendingAndCleanupAborted( ShardAndStrategy shardStrategy, Multimap<Long, WriteInfo> startTsWrites) { Map<Long, Long> startToCommitTs = commitTsLoader.loadBatch(startTsWrites.keySet()); Map<TableReference, Multimap<Cell, Long>> cellsToDelete = new HashMap<>(); List<Long> committedTimestamps = new ArrayList<>(); for (Map.Entry<Long, Long> entry : startToCommitTs.entrySet()) { if (entry.getValue() == TransactionConstants.FAILED_COMMIT_TS) { startTsWrites.get(entry.getKey()) .forEach(write -> cellsToDelete .computeIfAbsent(write.tableRef(), ignore -> HashMultimap.create()) .put(write.cell(), write.timestamp())); } else { committedTimestamps.add(entry.getKey()); } } cellsToDelete.forEach((tableRef, multimap) -> { kvs.delete(tableRef, multimap); maybeMetrics.ifPresent(metrics -> metrics.updateAbortedWritesDeleted(shardStrategy, multimap.size())); <START> log.info("Deleted aborted writes from the KVS.", multimap.size()); <END> }); committedTimestamps.sort(Comparator.reverseOrder()); return committedTimestamps; }</code><technical_language>nit: SafeArg</technical_language>

Target:
private List<Long> getCommittedTimestampsDescendingAndCleanupAborted( ShardAndStrategy shardStrategy, Multimap<Long, WriteInfo> startTsWrites) { Map<Long, Long> startToCommitTs = commitTsLoader.loadBatch(startTsWrites.keySet()); Map<TableReference, Multimap<Cell, Long>> cellsToDelete = new HashMap<>(); List<Long> committedTimestamps = new ArrayList<>(); for (Map.Entry<Long, Long> entry : startToCommitTs.entrySet()) { if (entry.getValue() == TransactionConstants.FAILED_COMMIT_TS) { startTsWrites.get(entry.getKey()) .forEach(write -> cellsToDelete .computeIfAbsent(write.tableRef(), ignore -> HashMultimap.create()) .put(write.cell(), write.timestamp())); } else { committedTimestamps.add(entry.getKey()); } } cellsToDelete.forEach((tableRef, multimap) -> { kvs.delete(tableRef, multimap); maybeMetrics.ifPresent(metrics -> metrics.updateAbortedWritesDeleted(shardStrategy, multimap.size())); log.info("Deleted aborted writes from the KVS.", SafeArg.of("number", multimap.size())); }); committedTimestamps.sort(Comparator.reverseOrder()); return committedTimestamps; }
Source:
<code>public JobManagerRunnerImpl( final JobGraph jobGraph, final JobMasterServiceFactory jobMasterFactory, final HighAvailabilityServices haServices, final LibraryCacheManager.ClassLoaderLease classLoaderLease, final Executor executor, final FatalErrorHandler fatalErrorHandler) throws Exception { this.resultFuture = new CompletableFuture<>(); this.terminationFuture = new CompletableFuture<>(); this.leadershipOperation = CompletableFuture.completedFuture(null); this.jobGraph = checkNotNull(jobGraph); this.classLoaderLease = checkNotNull(classLoaderLease); this.executor = checkNotNull(executor); this.fatalErrorHandler = checkNotNull(fatalErrorHandler); checkArgument(jobGraph.getNumberOfVertices() > 0, "The given job is empty"); final ClassLoader userCodeLoader; try { userCodeLoader = classLoaderLease.getOrResolveClassLoader( jobGraph.getUserJarBlobKeys(), jobGraph.getClasspaths()); } catch (IOException e) { throw new Exception("Cannot set up the user code libraries: " + e.getMessage(), e); } this.runningJobsRegistry = haServices.getRunningJobsRegistry(); this.leaderElectionService = haServices.getJobManagerLeaderElectionService(jobGraph.getJobID()); this.leaderGatewayFuture = new CompletableFuture<>(); <START> try { this.jobMasterService = jobMasterFactory.createJobMasterService(jobGraph, this, userCodeLoader); } catch (Throwable t) { ClusterEntryPointExceptionUtils.tryEnrichClusterEntryPointError(t); throw t; } <END> }</code><technical_language>I move this specific exception handling out enrich OOMs occur here. if OOM in a line (e.g. classLoaderLease.getOrResolveClassLoader(...))? I put Dispatcher.internalSubmitJob</technical_language>

Target:
public JobManagerRunnerImpl( final JobGraph jobGraph, final JobMasterServiceFactory jobMasterFactory, final HighAvailabilityServices haServices, final LibraryCacheManager.ClassLoaderLease classLoaderLease, final Executor executor, final FatalErrorHandler fatalErrorHandler) throws Exception { this.resultFuture = new CompletableFuture<>(); this.terminationFuture = new CompletableFuture<>(); this.leadershipOperation = CompletableFuture.completedFuture(null); this.jobGraph = checkNotNull(jobGraph); this.classLoaderLease = checkNotNull(classLoaderLease); this.executor = checkNotNull(executor); this.fatalErrorHandler = checkNotNull(fatalErrorHandler); checkArgument(jobGraph.getNumberOfVertices() > 0, "The given job is empty"); final ClassLoader userCodeLoader; try { userCodeLoader = classLoaderLease.getOrResolveClassLoader( jobGraph.getUserJarBlobKeys(), jobGraph.getClasspaths()); } catch (IOException e) { throw new Exception("Cannot set up the user code libraries: " + e.getMessage(), e); } this.runningJobsRegistry = haServices.getRunningJobsRegistry(); this.leaderElectionService = haServices.getJobManagerLeaderElectionService(jobGraph.getJobID()); this.leaderGatewayFuture = new CompletableFuture<>(); this.jobMasterService = jobMasterFactory.createJobMasterService(jobGraph, this, userCodeLoader); }
Source:
<code>@Override public void onTxEnd(GridCacheSharedContext cctx, IgniteInternalTx tx, boolean commit) { for (int i = 0; i < activeCacheIds.size(); i++) { int cacheId = activeCacheIds.get(i); GridCacheContext cacheCtx = cctx.cacheContext(cacheId); <START> assert cacheCtx != null : "cacheCtx == null"; <END> onTxEnd(cacheCtx, tx, commit); } }</code><technical_language>Maybe, need add some information? CacheId, for example</technical_language>

Target:
@Override public void onTxEnd(GridCacheSharedContext cctx, IgniteInternalTx tx, boolean commit) { for (int i = 0; i < activeCacheIds.size(); i++) { int cacheId = activeCacheIds.get(i); GridCacheContext cacheCtx = cctx.cacheContext(cacheId); assert cacheCtx != null : "cacheCtx == null, cacheId=" + cacheId; onTxEnd(cacheCtx, tx, commit); } }
Source:
<code>public void verifyIvParameterSpecIdentity() throws Exception { boolean done = false; int iterations = 0; final int maxIterations = 10000; while (!done && iterations++ < maxIterations) { SupportedCipherDetails cipherDetails = AesCtrCipherDetails.INSTANCE_256_BIT; final byte[] iv = cipherDetails.generateIv(); AlgorithmParameterSpec spec = cipherDetails.getEncryptionParameterSpec(iv, 0L); Cipher cipher = cipherDetails.getCipher(); SecretKey secretKey = SecretKeyUtils.generate(cipherDetails); cipher.init(Cipher.DECRYPT_MODE, secretKey, spec); Assert.assertEquals(iv, cipher.getIV(), "Calculated initialization " + "vector does not match expected value [expected=" + Arrays.toString(iv) + " actual=" + Arrays.toString(cipher.getIV()) + "]"); final BigInteger ivBigInt = new BigInteger(iv); <START> if (ivBigInt.compareTo(BigInteger.ZERO) == -1) { <END> done = true; } } }</code><technical_language>potentially replace: if (ivBigInt.compareTo(BigInteger.ZERO) == -1) -> if (ivBigInt.compareTo(BigInteger.ZERO) < 0)</technical_language>

Target:
public void verifyIvParameterSpecIdentity() throws Exception { boolean done = false; int iterations = 0; final int maxIterations = 10000; while (!done && iterations++ < maxIterations) { SupportedCipherDetails cipherDetails = AesCtrCipherDetails.INSTANCE_256_BIT; final byte[] iv = cipherDetails.generateIv(); AlgorithmParameterSpec spec = cipherDetails.getEncryptionParameterSpec(iv, 0L); Cipher cipher = cipherDetails.getCipher(); SecretKey secretKey = SecretKeyUtils.generate(cipherDetails); cipher.init(Cipher.DECRYPT_MODE, secretKey, spec); Assert.assertEquals(iv, cipher.getIV(), "Calculated initialization " + "vector does not match expected value [expected=" + Arrays.toString(iv) + " actual=" + Arrays.toString(cipher.getIV()) + "]"); final BigInteger ivBigInt = new BigInteger(iv); if (ivBigInt.compareTo(BigInteger.ZERO) < 0) { done = true; } } }
Source:
<code>void migratePerJobCredentials() { if (credentials == null && !mayHaveLegacyPerJobCredentials ) { return; } boolean allOk = true; Jenkins instance = Jenkins.getInstance(); <START> if (instance != null) { <END> for (AbstractProject<?, ?> job : instance.getAllItems(AbstractProject.class)) { File jobCredentials = new File(job.getRootDir(), "subversion.credentials"); if (jobCredentials.isFile()) { try { new PerJobCredentialStore(job).migrateCredentials(this); job.save(); if (!jobCredentials.delete()) { LOGGER.log(Level.WARNING, "Could not remove legacy per-job credentials store file: {0}", jobCredentials); allOk = false; } } catch (IOException e) { LOGGER.log(Level.WARNING, "Could not migrate per-job credentials for " + job.getFullName(), e); allOk = false; } } } } mayHaveLegacyPerJobCredentials = !allOk; save(); }</code><technical_language>This approach a huge diff. I check Jenkins instance pass empty array cycle if is null</technical_language>

Target:
void migratePerJobCredentials() { if (credentials == null && !mayHaveLegacyPerJobCredentials ) { return; } boolean allOk = true; Jenkins instance = Jenkins.getInstance(); List<AbstractProject> allItems; if (instance == null) { allItems = Collections.emptyList(); } else { allItems = instance.getAllItems(AbstractProject.class); } for (AbstractProject<?, ?> job : allItems) { File jobCredentials = new File(job.getRootDir(), "subversion.credentials"); if (jobCredentials.isFile()) { try { new PerJobCredentialStore(job).migrateCredentials(this); job.save(); if (!jobCredentials.delete()) { LOGGER.log(Level.WARNING, "Could not remove legacy per-job credentials store file: {0}", jobCredentials); allOk = false; } } catch (IOException e) { LOGGER.log(Level.WARNING, "Could not migrate per-job credentials for " + job.getFullName(), e); allOk = false; } } } mayHaveLegacyPerJobCredentials = !allOk; save(); }
Source:
<code>public void invokeCallbackMethods() { initCommandExecutor(); Iterator<Entry<Guid, CommandContainer>> iterator = cmdCallbackMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<Guid, CommandContainer> entry = iterator.next(); <START> if (--entry.getValue().executionCountdown > 0) { <END> continue; } Guid cmdId = entry.getKey(); CommandCallback callback = entry.getValue().callback; CommandStatus status = coco.getCommandStatus(cmdId); boolean errorInCallback = false; try { switch (status) { case FAILED: callback.onFailed(cmdId, coco.getChildCommandIds(cmdId)); break; case SUCCEEDED: callback.onSucceeded(cmdId, coco.getChildCommandIds(cmdId)); break; case ACTIVE: if (coco.getCommandEntity(cmdId).isExecuted()) { callback.doPolling(cmdId, coco.getChildCommandIds(cmdId)); } break; default: break; } } catch (Exception ex) { errorInCallback = true; handleError(ex, status, cmdId); } finally { if (CommandStatus.FAILED.equals(status) || (CommandStatus.SUCCEEDED.equals(status) && !errorInCallback)) { coco.updateCallbackNotified(cmdId); iterator.remove(); } else { int maxDelay = Config.<Integer>getValue(ConfigValues.AsyncCommandPollingRateInSeconds); entry.getValue().executionDelay = Math.min(maxDelay, entry.getValue().executionDelay * 2); entry.getValue().executionCountdown = entry.getValue().executionDelay; } } } }</code><technical_language>this entry.getValue().executionDelay = entry.getValue().executionDelay - POLLING_RATE</technical_language>

Target:
public void invokeCallbackMethods() { initCommandExecutor(); Iterator<Entry<Guid, CommandContainer>> iterator = cmdCallbackMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<Guid, CommandContainer> entry = iterator.next(); if ((entry.getValue().remainingDelay -= POLLING_RATE) > 0) { continue; } Guid cmdId = entry.getKey(); CommandCallback callback = entry.getValue().callback; CommandStatus status = coco.getCommandStatus(cmdId); boolean errorInCallback = false; try { switch (status) { case FAILED: callback.onFailed(cmdId, coco.getChildCommandIds(cmdId)); break; case SUCCEEDED: callback.onSucceeded(cmdId, coco.getChildCommandIds(cmdId)); break; case ACTIVE: if (coco.getCommandEntity(cmdId).isExecuted()) { callback.doPolling(cmdId, coco.getChildCommandIds(cmdId)); } break; default: break; } } catch (Exception ex) { errorInCallback = true; handleError(ex, status, cmdId); } finally { if (CommandStatus.FAILED.equals(status) || (CommandStatus.SUCCEEDED.equals(status) && !errorInCallback)) { coco.updateCallbackNotified(cmdId); iterator.remove(); } else { int maxDelay = Config.<Integer>getValue(ConfigValues.AsyncCommandPollingRateInSeconds); entry.getValue().initialDelay = Math.min(maxDelay, entry.getValue().initialDelay * 2); entry.getValue().remainingDelay = entry.getValue().initialDelay; } } } }
Source:
<code><START> public Boolean getUseForBackup() { <END> return useForBackup; }</code><technical_language>isUsedForBackup? returning Boolean object attribute is defined primitive boolean type</technical_language>

Target:
public boolean getUseForBackup() { return useForBackup; }
Source:
<code>private void createDefaultFileStats(Object[] fileNames) { for (int i = 0; i < fileNames.length; i++) { <START> fileStats.put((String) fileNames[i], null); <END> } }</code><technical_language>This is correct, discuss f2f</technical_language>

Target:
private void createDefaultFileStats(Object[] fileNames) { for (int i = 0; i < fileNames.length; i++) { fileStats.put((String) fileNames[i], Collections.<String, Object>emptyMap()); } }
Source:
<code>public void batchReadComplex() throws Exception { String[] bins = new String[] {binName}; List<BatchRead> records = new ArrayList<BatchRead>(); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 1), bins)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 2), true)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 3), true)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 4), false)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 5), true)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 6), true)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 7), bins)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 8), new String[] {"binnotfound"})); records.add(new BatchRead(new Key(args.namespace, args.set, "keynotfound"), bins)); Mono<List<BatchRead>> mono = reactorClient.get(records); StepVerifier.create(mono) .expectNextMatches(batchReads -> { int found = 0; int count = 0; for (BatchRead record : batchReads) { Record rec = record.record; count++; if (rec != null) { found++; Object value = rec.getValue(binName); <START> if (count != 4 && count <= 7) { <END> assertEquals(valuePrefix + count, value); } else { assertNull(value); } } } assertEquals(8, found); return true; }) .verifyComplete(); }</code><technical_language>asserts complicated. match separate assert index checking</technical_language>

Target:
public void batchReadComplex() { String[] bins = new String[] {binName}; List<BatchRead> records = new ArrayList<BatchRead>(); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 1), bins)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 2), true)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 3), true)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 4), false)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 5), true)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 6), true)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 7), bins)); records.add(new BatchRead(new Key(args.namespace, args.set, keyPrefix + 8), new String[] {"binnotfound"})); records.add(new BatchRead(new Key(args.namespace, args.set, "keynotfound"), bins)); Mono<List<BatchRead>> mono = reactorClient.get(records); StepVerifier.create(mono) .expectNextMatches(batchReads -> { List<BatchRead> recordsFound = batchReads.stream() .filter(record -> record.record != null) .collect(Collectors.toList()); assertThat(recordsFound).hasSize(8); assertThat(recordsFound).extracting(record -> record.record.getValue(binName)) .containsExactly( "batchvalue1", "batchvalue2", "batchvalue3", null, "batchvalue5", "batchvalue6", "batchvalue7", null); return true; }) .verifyComplete(); }
Source:
<code><START> public static void registerFormat(String name, Format<?> fmt) { <END> if (fmt == null) throw new NullPointerException(); FormatEntry old, entry; do { old = formats.get(name); if (old == null) { entry = new FormatEntry(fmt, 1); continue; } if (!old.format.equals(fmt)) throw new JGitInternalException(MessageFormat.format( JGitText.get().archiveFormatAlreadyRegistered, name)); entry = new FormatEntry(old.format, old.refcnt + 1); } while (!replace(formats, name, old, entry)); }</code><technical_language>Do this needs return actual Format in case fmt? If I hold fmt I passed in, of classes written, behave identically, I ok. a reference class, in case matters</technical_language>

Target:
public static Format<?> registerFormat(String name, Format<?> fmt) { if (fmt == null) throw new NullPointerException(); FormatEntry old, entry; do { old = formats.get(name); if (old == null) { entry = new FormatEntry(fmt, 1); continue; } if (!old.format.equals(fmt)) throw new JGitInternalException(MessageFormat.format( JGitText.get().archiveFormatAlreadyRegistered, name)); entry = new FormatEntry(old.format, old.refcnt + 1); } while (!replace(formats, name, old, entry)); return entry.format; }
Source:
<code><START> public List<AuthScope> matchingScopes(@NonNull Set<String> scopeStrings) { val result = scopeStrings.stream().map(s -> AuthScope.from(s)) .filter(p -> matches(p)) .collect(Collectors.toList()); return result; } <END></code><technical_language>replace this java return scopeStrings.stream() .map(AuthScope::from) .filter(this::matches) .collect(toUnmodifiableList();</technical_language>

Target:
public List<AuthScope> matchingScopes(@NonNull Set<String> scopeStrings) { return scopeStrings.stream() .map(AuthScope::from) .filter(this::matches) .collect(toUnmodifiableList()); }
Source:
<code>public ListenableFuture<TaskStatus> run(final Task task) { final int taskId = Integer.parseInt(task.getId()); ListenableFuture<TaskStatus> future = MoreExecutors.listeningDecorator( Execs.singleThreaded( "noop_test_task_exec_%s" ) ).submit( new Callable<TaskStatus>() { @Override public TaskStatus call() throws Exception { try { <START> taskLatches[taskId].await(2, TimeUnit.SECONDS); <END> } catch (InterruptedException e) { throw new RuntimeException("Thread was interrupted!"); } runningTaskRunnerWorkItems.remove(taskId); return TaskStatus.success(task.getId()); } } ); TaskRunnerWorkItem taskRunnerWorkItem = new TaskRunnerWorkItem(task.getId(), future); runningTaskRunnerWorkItems.put(taskId, taskRunnerWorkItem); taskRunnerWorkItems.put(taskId, taskRunnerWorkItem); return future; }</code><technical_language>other places await() needs a timeout here? seems, test fail if timeout is reached, is anything</technical_language>

Target:
public ListenableFuture<TaskStatus> run(final Task task) { final int taskId = Integer.parseInt(task.getId()); ListenableFuture<TaskStatus> future = MoreExecutors.listeningDecorator( Execs.singleThreaded( "noop_test_task_exec_%s" ) ).submit( new Callable<TaskStatus>() { @Override public TaskStatus call() throws Exception { try { taskLatches[taskId].await(); } catch (InterruptedException e) { throw new RuntimeException("Thread was interrupted!"); } runningTaskRunnerWorkItems.remove(taskId); return TaskStatus.success(task.getId()); } } ); TaskRunnerWorkItem taskRunnerWorkItem = new TaskRunnerWorkItem(task.getId(), future); runningTaskRunnerWorkItems.put(taskId, taskRunnerWorkItem); taskRunnerWorkItems.put(taskId, taskRunnerWorkItem); return future; }
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_collaborations, container, false); mCollaboratorsListView = (ListView) view.findViewById(R.id.collaboratorsList); mCollaboratorsListView.setDivider(null); mCollaboratorsAdapter = new CollaboratorsAdapter(getActivity(), getItem(), mController); mCollaboratorsListView.setAdapter(mCollaboratorsAdapter); mCollaboratorsListView.setOnItemClickListener(this); mNoCollaboratorsText = (TextView) view.findViewById(R.id.no_collaborators_text); if (savedInstanceState == null) { fetchCollaborations(); <START> }else if (savedInstanceState != null) { <END> mCollaborations = (BoxIteratorCollaborations)savedInstanceState.getSerializable(CollaborationUtils.EXTRA_COLLABORATIONS); updateUi(); } else if (getArguments() != null){ Bundle args = getArguments(); mCollaborations = (BoxIteratorCollaborations)args.getSerializable(CollaborationUtils.EXTRA_COLLABORATIONS); updateUi(); } if (getItem().getAllowedInviteeRoles() == null) { fetchRoles(); } return view; }</code><technical_language>Insert space }</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_collaborations, container, false); mCollaboratorsListView = (ListView) view.findViewById(R.id.collaboratorsList); mCollaboratorsListView.setDivider(null); mCollaboratorsAdapter = new CollaboratorsAdapter(getActivity(), getItem(), mController); mCollaboratorsListView.setAdapter(mCollaboratorsAdapter); mCollaboratorsListView.setOnItemClickListener(this); mNoCollaboratorsText = (TextView) view.findViewById(R.id.no_collaborators_text); if (savedInstanceState == null) { if (getArguments() != null){ Bundle args = getArguments(); mCollaborations = (BoxIteratorCollaborations)args.getSerializable(CollaborationUtils.EXTRA_COLLABORATIONS); } if (mCollaborations != null){ updateUi(); } fetchCollaborations(); } else { mCollaborations = (BoxIteratorCollaborations)savedInstanceState.getSerializable(CollaborationUtils.EXTRA_COLLABORATIONS); updateUi(); if (mCollaborations == null) { fetchCollaborations(); } } if (getItem().getAllowedInviteeRoles() == null) { fetchRoles(); } return view; }
Source:
<code>public final T create(final CreationalContext<T> cc) { Context initialContext = null; CreationException e = null; try { initialContext = this.getNewInitialContext(); return this.type.cast(initialContext.lookup(this.name)); } catch (final NamingException namingException) { e = new CreationException(namingException.getMessage(), namingException); throw e; } finally { try { <START> initialContext.close(); <END> } catch (final NamingException namingException) { if (e != null) { e.addSuppressed(namingException); } else { e = new CreationException(namingException.getMessage(), namingException); } throw e; } } }</code><technical_language>I worried initialContext null in some inauspicious cases, be</technical_language>

Target:
public final T create(final CreationalContext<T> cc) { Context initialContext = null; CreationException e = null; try { initialContext = this.getNewInitialContext(); return this.type.cast(initialContext.lookup(this.name)); } catch (final NamingException namingException) { e = new CreationException(namingException.getMessage(), namingException); throw e; } finally { if (initialContext != null) { try { initialContext.close(); } catch (final NamingException namingException) { if (e != null) { e.addSuppressed(namingException); } else { e = new CreationException(namingException.getMessage(), namingException); } throw e; } } } }
Source:
<code>private static String key(Tree tree) { if (tree.is(Kind.NUMERIC_LITERAL)) { return ((NumericLiteral) tree).valueAsString(); } else if (tree.is(Kind.STRING_LITERAL)) { return ((StringLiteral) tree).trimmedQuotesValue(); } else if (tree.is(Kind.NAME)) { return ((Name) tree).name(); } else if (tree.is(Kind.SLICE_ITEM)) { SliceItem sliceItem = (SliceItem) tree; List<String> keyParts = Stream.of(sliceItem.lowerBound(), sliceItem.upperBound(), sliceItem.stride()) .map(e -> e == null ? "" : key(e)) .collect(Collectors.toList()); <START> return keyParts.contains(null) ? null : String.join(":", keyParts); <END> } return null; }</code><technical_language>keyParts null here? code test case fulfilling this condition</technical_language>

Target:
private static String key(Tree tree) { if (tree.is(Kind.NUMERIC_LITERAL)) { return ((NumericLiteral) tree).valueAsString(); } else if (tree.is(Kind.STRING_LITERAL)) { return ((StringLiteral) tree).trimmedQuotesValue(); } else if (tree.is(Kind.NAME)) { return ((Name) tree).name(); } else if (tree.is(Kind.SLICE_ITEM)) { SliceItem sliceItem = (SliceItem) tree; return Stream.of(sliceItem.lowerBound(), sliceItem.upperBound(), sliceItem.stride()) .map(e -> e == null ? "" : key(e)) .collect(Collectors.joining(":")); } return null; }
Source:
<code>public Optional<Block> compute() { int length = selectedPositions.getOffset() + selectedPositions.size(); if (selectedPositions.isList()) { for (int index = nextIndexOrPosition; index < length; index++) { <START> writeNativeValue(evaluator.getType(), blockBuilder, evaluator.evaluate(selectedPositions.getPositions()[index], blocks)); <END> if (yieldSignal.isSet()) { nextIndexOrPosition = index + 1; return Optional.empty(); } } } else { for (int position = nextIndexOrPosition; position < length; position++) { writeNativeValue(evaluator.getType(), blockBuilder, evaluator.evaluate(position, blocks)); if (yieldSignal.isSet()) { nextIndexOrPosition = position + 1; return Optional.empty(); } } } Block block = blockBuilder.build(); blockBuilder = blockBuilder.newBlockBuilderLike(new BlockBuilderStatus()); return Optional.of(block); }</code><technical_language>Put selectedPositions.getPositions() in a variable</technical_language>

Target:
public Optional<Block> compute() { int length = selectedPositions.getOffset() + selectedPositions.size(); if (selectedPositions.isList()) { int[] positions = selectedPositions.getPositions(); while (nextIndexOrPosition < length) { writeNativeValue(evaluator.getType(), blockBuilder, evaluator.evaluate(positions[nextIndexOrPosition], blocks)); nextIndexOrPosition++; if (yieldSignal.isSet()) { return Optional.empty(); } } } else { while (nextIndexOrPosition < length) { writeNativeValue(evaluator.getType(), blockBuilder, evaluator.evaluate(nextIndexOrPosition, blocks)); nextIndexOrPosition++; if (yieldSignal.isSet()) { return Optional.empty(); } } } Block block = blockBuilder.build(); blockBuilder = blockBuilder.newBlockBuilderLike(new BlockBuilderStatus()); return Optional.of(block); }
Source:
<code>MandateConnectorResponse createMandate(Account account, MandateConnectorRequest mandateConnectorRequest) { String requestJson; try { requestJson = objectMapper.writeValueAsString(mandateConnectorRequest); } catch (JsonProcessingException e) { throw new RuntimeException(e); } Response response = client.target(getDDConnectorUrl(format("/v1/api/accounts/%s/mandates", account.getName()))) .request() .accept(MediaType.APPLICATION_JSON) <START> .post(json(requestJson)); <END> if (response.getStatus() == HttpStatus.SC_CREATED) return response.readEntity(MandateConnectorResponse.class); throw new CreateAgreementException(response); }</code><technical_language>do this a lot cleaner .post(Entity.entity(mandateConnectorRequest, MediaType.APPLICATION_JSONTYPE);</technical_language>

Target:
MandateConnectorResponse createMandate(Account account, MandateConnectorRequest mandateConnectorRequest) { Response response = client.target(getDDConnectorUrl(format("/v1/api/accounts/%s/mandates", account.getName()))) .request() .accept(MediaType.APPLICATION_JSON) .post(Entity.entity(mandateConnectorRequest, MediaType.APPLICATION_JSON)); if (response.getStatus() == HttpStatus.SC_CREATED) return response.readEntity(MandateConnectorResponse.class); throw new CreateAgreementException(response); }
Source:
<code>protected Builder() { id("dimensiondata-cloudcontrol").name("DimensionData CloudControl API").identityName("user name") .credentialName("user password") .documentation(URI.create("<LINK_1>")) .defaultEndpoint("<LINK_0>").version("2.4") .defaultProperties(DimensionDataCloudControlApiMetadata.defaultProperties()) .view(typeToken(ComputeServiceContext.class)).defaultModules( ImmutableSet.<Class<? extends Module>>builder().add(DimensionDataCloudControlHttpApiModule.class) .add(DimensionDataCloudControlParserModule.class) <START> .add(DimensionDataComputeServiceContextModule.class).build()); <END> }</code><technical_language>For remove ComputeServiceAdapter module, implementation other transformation functions. implemented return null placeholders, provide add complexity code PR. remove stuff start a clean API set a good foundation for provider. allow PRs easier faster</technical_language>

Target:
protected Builder() { id("dimensiondata-cloudcontrol").name("DimensionData CloudControl API").identityName("user name") .credentialName("user password") .documentation(URI.create("<LINK_1>")) .defaultEndpoint("<LINK_0>").version("2.4") .defaultProperties(DimensionDataCloudControlApiMetadata.defaultProperties()) .view(typeToken(ComputeServiceContext.class)).defaultModules( ImmutableSet.<Class<? extends Module>>builder().add(DimensionDataCloudControlHttpApiModule.class) .add(DimensionDataCloudControlParserModule.class).build()); }
Source:
<code>public static RegisteredTypeConstraint alreadyVisited(Set<String> encounteredTypeSymbolicNames, String anotherEncounteredType) { BasicRegisteredTypeConstraint result = new BasicRegisteredTypeConstraint(); <START> result.encounteredTypes = MutableSet.copyOf(encounteredTypeSymbolicNames); <END> if (anotherEncounteredType!=null) result.encounteredTypes.add(anotherEncounteredType); return result; }</code><technical_language>ImmutableSet avoid accidental changes. for method well, a NOP in general case passing immutable already</technical_language>

Target:
public static RegisteredTypeConstraint alreadyVisited(Set<String> encounteredTypeSymbolicNames, String anotherEncounteredType) { BasicRegisteredTypeConstraint result = new BasicRegisteredTypeConstraint(); MutableSet<String> encounteredTypes = MutableSet.copyOf(encounteredTypeSymbolicNames); encounteredTypes.addIfNotNull(anotherEncounteredType); result.encounteredTypes = encounteredTypes.asUnmodifiable(); return result; }
Source:
<code>public void execute() throws ExecutionException, InterruptedException { final String password = "password"; final DefaultResetPasswordFormData resetPasswordFormData = new DefaultResetPasswordFormData(); resetPasswordFormData.setConfirmPassword(password); resetPasswordFormData.setNewPassword(password); final String resetTokenValue = "reset-token-value"; when: { when(hookRunner.runUnaryOperatorHook(eq(CustomerPasswordResetCommandHook.class), any(), customerPasswordResetCommandCaptor.capture())) .thenAnswer(invocation -> invocation.getArgument(2)); when(sphereClient.execute(any())) .thenReturn(CompletableFuture.completedFuture(customer)); } final CompletableFuture<Customer> customerCompletableFuture = (CompletableFuture<Customer>) defaultResetPasswordControllerAction.apply(resetTokenValue, resetPasswordFormData); <START> final Customer customer = customerCompletableFuture.get(); <END> then: { assertThat(customer).isNotNull(); final CustomerPasswordResetCommand customerPasswordResetCommand = customerPasswordResetCommandCaptor.getValue(); assertThat(customerPasswordResetCommand.getTokenValue()).isEqualTo(resetTokenValue); assertThat(customerPasswordResetCommand.getNewPassword()).isEqualTo(password); } }</code><technical_language>I consider making a one-liner: java final Customer customer = defaultResetPasswordControllerAction.apply(resetTokenValue, resetPasswordFormData).toCompletableFuture().get(); I find natural conversion completable future more readable casting, (didn't check) shows a warning in IDE too</technical_language>

Target:
public void execute() throws ExecutionException, InterruptedException { final String password = "password"; final DefaultResetPasswordFormData resetPasswordFormData = new DefaultResetPasswordFormData(); resetPasswordFormData.setConfirmPassword(password); resetPasswordFormData.setNewPassword(password); final String resetTokenValue = "reset-token-value"; when: { when(hookRunner.runUnaryOperatorHook(eq(CustomerPasswordResetCommandHook.class), any(), customerPasswordResetCommandCaptor.capture())) .thenAnswer(invocation -> invocation.getArgument(2)); when(sphereClient.execute(any())) .thenReturn(CompletableFuture.completedFuture(customer)); } final Customer updatedCustomer = defaultResetPasswordControllerAction.apply(resetTokenValue, resetPasswordFormData) .toCompletableFuture().get(); then: { assertThat(updatedCustomer).isNotNull(); final CustomerPasswordResetCommand customerPasswordResetCommand = customerPasswordResetCommandCaptor.getValue(); assertThat(customerPasswordResetCommand.getTokenValue()).isEqualTo(resetTokenValue); assertThat(customerPasswordResetCommand.getNewPassword()).isEqualTo(password); } }
Source:
<code>private static void populateAnalysisModules() { IPath pathToFiles = XmlUtils.getXmlFilesPath(); File fFolder = pathToFiles.toFile(); if (!(fFolder.isDirectory() && fFolder.exists())) { return; } File fOldFolder = XML_DIRECTORY_LEGACY.toFile(); if ((fOldFolder.isDirectory() && fOldFolder.exists())) { for (File fromFile : fOldFolder.listFiles()) { File toFile = <START> pathToFiles.addTrailingSeparator().append(fromFile.getName()).toFile(); <END> if (!toFile.exists()) { try (FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); FileChannel source = fis.getChannel(); FileChannel destination = fos.getChannel();) { destination.transferFrom(source, 0, source.size()); } catch (IOException e) { String error = Messages.XmlUtils_ErrorCopyingFile; Activator.logError(error, e); } } } } for (File xmlFile : fFolder.listFiles()) { processFile(xmlFile); } }</code><technical_language>append() adds a segment, adding trailing separator is unnecessary</technical_language>

Target:
private static void populateAnalysisModules() { IPath pathToFiles = XmlUtils.getXmlFilesPath(); File fFolder = pathToFiles.toFile(); if (!(fFolder.isDirectory() && fFolder.exists())) { return; } File fOldFolder = XML_DIRECTORY_LEGACY.toFile(); if ((fOldFolder.isDirectory() && fOldFolder.exists())) { for (File fromFile : fOldFolder.listFiles()) { File toFile = pathToFiles.append(fromFile.getName()).toFile(); if (!toFile.exists() && !fromFile.isDirectory()) { try (FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); FileChannel source = fis.getChannel(); FileChannel destination = fos.getChannel();) { destination.transferFrom(source, 0, source.size()); } catch (IOException e) { String error = Messages.XmlUtils_ErrorCopyingFile; Activator.logError(error, e); } } } } for (File xmlFile : fFolder.listFiles()) { processFile(xmlFile); } }
Source:
<code>public void pageFilterIsAppliedToReadRowsRequest() throws IOException { final String TABLE_ID = "tableId"; final RequestContext requestContext = RequestContext.create( InstanceName.of("ProjectId", "InstanceId"), "AppProfile"); ReadHooks hooks = new DefaultReadHooks(); FilterAdapterContext context = new FilterAdapterContext(new Scan(), hooks); PageFilter pageFilter = new PageFilter(20); Filters.Filter adaptedFilter = pageFilterAdapter.adapt(context, pageFilter); Assert.assertNull("PageFilterAdapter should not return a Filters.Filter.", adaptedFilter); Query query = Query.create(TABLE_ID).limit(100); Query postHookRequest = hooks.applyPreSendHook(query); <START> Assert.assertEquals(20, postHookRequest.toProto(requestContext).getRowsLimit()); <END> }</code><technical_language>get rows limit Query</technical_language>

Target:
public void pageFilterIsAppliedToReadRowsRequest() throws IOException { final String TABLE_ID = "tableId"; final RequestContext requestContext = RequestContext.create("ProjectId", "InstanceId", "AppProfile"); ReadHooks hooks = new DefaultReadHooks(); FilterAdapterContext context = new FilterAdapterContext(new Scan(), hooks); PageFilter pageFilter = new PageFilter(20); Filters.Filter adaptedFilter = pageFilterAdapter.adapt(context, pageFilter); Assert.assertNull("PageFilterAdapter should not return a Filters.Filter.", adaptedFilter); Query query = Query.create(TABLE_ID).limit(100); hooks.applyPreSendHook(query); Assert.assertEquals(20, query.toProto(requestContext).getRowsLimit()); }
Source:
<code>public boolean isExistsQuery() { <START> return getName().toLowerCase().startsWith("exists"); <END> }</code><technical_language>Locale.ROOT in toLowerCase</technical_language>

Target:
public boolean isExistsQuery() { return getName().toLowerCase(Locale.ROOT).startsWith("exists"); }