auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testCloseAdminClientInCallback() throws InterruptedException { <START> AdminClientUnitTestEnv env = mockClientEnv(); <END> final ListTopicsResult result = env.adminClient().listTopics(new ListTopicsOptions().timeoutMs(1000)); final KafkaFuture<Map<String, TopicListing>> kafkaFuture = result.namesToListings(); final Semaphore callbackCalled = new Semaphore(0); kafkaFuture.whenComplete((stringTopicListingMap, throwable) -> { env.close(); callbackCalled.release(); }); callbackCalled.acquire(); }</code><technical_language>change this MockTime instead</technical_language>

Target:
public void testCloseAdminClientInCallback() throws InterruptedException { MockTime time = new MockTime(); AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(time, mockCluster(3, 0)); final ListTopicsResult result = env.adminClient().listTopics(new ListTopicsOptions().timeoutMs(1000)); final KafkaFuture<Collection<TopicListing>> kafkaFuture = result.listings(); final Semaphore callbackCalled = new Semaphore(0); kafkaFuture.whenComplete((topicListings, throwable) -> { env.close(); callbackCalled.release(); }); time.sleep(2000); callbackCalled.acquire(); }
Source:
<code><START> public String toString() { <END> StringBuffer annotation = new StringBuffer(512); annotation.append("Gene Name: ") .append(geneName).append(System.lineSeparator()) .append("Gene Position: ").append(getGenomePosition()) .append(System.lineSeparator()).append("Mutation Type: ") .append(typeOfMutation).append(System.lineSeparator()) .append("Change: ").append(change) .append(System.lineSeparator()).append("Filter: ") .append(filter).append(System.lineSeparator()) .append("Drug Resistance: ").append(drugResistance); return annotation.toString(); }</code><technical_language>I this rewritten more cleanly [String formatter](<LINK_0></technical_language>

Target:
public String toString() { Formatter formatter = new Formatter(); formatter .format("Gene Name: %1$s%nGene Position: %2$s%nMutation Type: %3$s%nChange: %4$s%nFilter: %5$s%nDrug Resistance: %6$s", geneName, getGenomePosition(), typeOfMutation, change, filter, drugResistance); String annotation = formatter.toString(); formatter.close(); return annotation; }
Source:
<code>public void testFoo() throws Exception { Handle h = db.openHandle(); try { h.insert("WOOF", 7, "Tom"); <START> fail("Should throw a statement exception because of a bad SQL"); <END> } catch (StatementException e) { assertThat(e.getStatementContext().getRawSql()).isEqualTo("WOOF"); } }</code><technical_language>Nice catch</technical_language>

Target:
public void testFoo() throws Exception { assertThatExceptionOfType(StatementException.class) .isThrownBy(()-> db.openHandle().insert("WOOF", 7, "Tom")) .satisfies(e -> assertThat(e.getStatementContext().getRawSql()).isEqualTo("WOOF")); }
Source:
<code>public static final VelocityModeHandler modeHandler(final PageMode mode, final HttpServletRequest request, final HttpServletResponse response, final String uri, final Host host) { final long langId = WebAPILocator.getLanguageWebAPI().getLanguage(request).getId(); try { final Identifier id = APILocator.getIdentifierAPI().find(host, uri); final IHTMLPage htmlPage = APILocator.getHTMLPageAssetAPI().findByIdLanguageFallback(id, langId, mode.showLive, APILocator.systemUser(), mode.respectAnonPerms); return pageModeVelocityMap.get(mode).apply(request, response, htmlPage, host); } catch (DotDataException | DotSecurityException e) { <START> throw new DotRuntimeException(e); <END> } }</code><technical_language>is worth add a Log.debug here? warning</technical_language>

Target:
public static final VelocityModeHandler modeHandler(final PageMode mode, final HttpServletRequest request, final HttpServletResponse response, final String uri, final Host host) { final IHTMLPage htmlPage= getHtmlPageFromURI(mode, request, uri, host); return pageModeVelocityMap.get(mode).apply(request, response, htmlPage, host); }
Source:
<code>private boolean hasElseOrElsif(AstNode ifNode){ <START> return ifNode.hasDirectChildren(PuppetGrammar.ELSEIF_STMT) || ifNode.hasDirectChildren(PuppetGrammar.ELSE_STMT); <END> }</code><technical_language>Shorter way: return ifNode.hasDirectChildren(PuppetGrammar.ELSEIF_STMT, PuppetGrammar.ELSE_STMT);</technical_language>

Target:
private boolean hasElseOrElsif(AstNode ifNode){ return ifNode.hasDirectChildren(PuppetGrammar.ELSIF_STMT, PuppetGrammar.ELSE_STMT); }
Source:
<code>int complete(Xid xid, boolean commit) { try { if (trace) { <START> log.tracef("%s transaction xid=%s, remote-cache=%s", commit ? "Committing" : "Rolling-Back", xid, <END> cacheName); } CompleteTransactionOperation operation = operationsFactory.newCompleteTransactionOperation(xid, commit); return operation.execute().get(); } catch (Exception e) { log.debug("Exception while commit/rollback.", e); return XAException.XA_HEURRB; } }</code><technical_language>Off-topic, prefer "Complete(true|false) transaction..."</technical_language>

Target:
int complete(Xid xid, boolean commit) { try { if (trace) { log.tracef("Complete (%s) transaction xid=%s, cache-name=%s", commit, xid, cacheName); } CompleteTransactionOperation operation = operationsFactory.newCompleteTransactionOperation(xid, commit); return operation.execute().get(); } catch (Exception e) { log.debug("Exception while commit/rollback.", e); return XAException.XA_HEURRB; } }
Source:
<code>private void onLoadMessageFromDatabaseFinished() { if (callback == null) { throw new IllegalStateException("unexpected call when callback is already detached"); } callback.onMessageDataLoadFinished(localMessage); <START> boolean messageIsIncomplete = <END> !localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL); if (messageIsIncomplete) { startDownloadingMessageBody(false); return; } if (account.isOpenPgpProviderConfigured()) { startOrResumeCryptoOperation(); return; } startOrResumeDecodeMessage(); }</code><technical_language>Tiny detail: messageIncomplete a getter isMessageIncomplete()</technical_language>

Target:
private void onLoadMessageFromDatabaseFinished() { if (callback == null) { throw new IllegalStateException("unexpected call when callback is already detached"); } callback.onMessageDataLoadFinished(localMessage); boolean messageIncomplete = !localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL); if (messageIncomplete) { startDownloadingMessageBody(false); return; } if (account.isOpenPgpProviderConfigured()) { startOrResumeCryptoOperation(); return; } startOrResumeDecodeMessage(); }
Source:
<code>private Session loadSessionIfNotExpired(Session session, File file, MicroServiceContext microServiceContext) { if (System.currentTimeMillis() - session.getLastAccessedTime() >= (long) session.getMaxInactiveInterval() * 60L * 1000L && !file.delete()) { log.warn("Couldn't delete expired session file " + file.getAbsolutePath()); <START> return null; <END> } else { session.setManager(this); session.setMicroServiceContext(microServiceContext); return microServiceContext.putSession(session.getId(), session); } }</code><technical_language>optional</technical_language>

Target:
private Optional<Session> loadSessionIfNotExpired(Session session, File file, MicroServiceContext microServiceContext) { if (System.currentTimeMillis() - session.getLastAccessedTime() >= (long) session.getMaxInactiveInterval() * 60L * 1000L && !file.delete()) { log.warn("Couldn't delete expired session file " + file.getAbsolutePath()); return Optional.empty(); } else { session.setManager(this); microServiceContext.putSession(session.getId(), session); return Optional.of(session); } }
Source:
<code>public List<Long> getSizeOfTasksWithProcessingStatusForNotTemplateProcessesForProjectIdOrderByOrdering( Integer processingStatus, Integer projectId) { <START> return getCount("SELECT COUNT(t.id) FROM Task AS t INNER JOIN t.process AS p INNER JOIN p.project AS pr " <END> + "WITH pr.id = " + projectId + " WHERE t.processingStatus = " + processingStatus + " GROUP BY t.title ORDER BY t.ordering"); }</code><technical_language>change query parameters other places</technical_language>

Target:
public List<Long> getSizeOfTasksWithProcessingStatusForNotTemplateProcessesForProjectIdOrderByOrdering( Integer processingStatus, Integer projectId) { Map<String, Object> parameters = new HashMap<>(); parameters.put("projectId", projectId); parameters.put("processingStatus", processingStatus); return getCount("SELECT COUNT(t.id) FROM Task AS t INNER JOIN t.process AS p INNER JOIN p.project AS pr " + "WITH pr.id = :projectId WHERE t.processingStatus = :processingStatus " + "GROUP BY t.title ORDER BY t.ordering", parameters); }
Source:
<code><START> protected void validateSchedulingRequirements( <END> final Collection<ExecutionVertexSchedulingRequirements> schedulingRequirements) { schedulingRequirements.stream() .map(ExecutionVertexSchedulingRequirements::getExecutionVertexId) .forEach(id -> checkState( !pendingSlotAssignments.containsKey(id), "BUG: vertex %s tries to allocate a slot when its previous slot request is still pending", id)); }</code><technical_language>suggestion void validateSchedulingRequirements( nit: sure, need protected for methods in AbstractExecutionSlotAllocator if is package</technical_language>

Target:
void validateSchedulingRequirements(final Collection<ExecutionVertexSchedulingRequirements> schedulingRequirements) { schedulingRequirements.stream() .map(ExecutionVertexSchedulingRequirements::getExecutionVertexId) .forEach(id -> checkState( !pendingSlotAssignments.containsKey(id), "BUG: vertex %s tries to allocate a slot when its previous slot request is still pending", id)); }
Source:
<code>public AbstractListDataView<T> addItemsAfter(Collection<T> items, T after) { if (items == null || items.isEmpty()) { return this; } final ListDataProvider<T> dataProvider = getDataProvider(); final Collection<T> backendItems = dataProvider.getItems(); final int afterItemIndex = getItemIndex(after); if (afterItemIndex == -1) { throw new IllegalArgumentException( "Item to insert after is not available in the data"); } if (backendItems instanceof List) { final List<T> itemList = (List<T>) backendItems; <START> final List<T> itemsToAdd = items.stream() <END> .filter(item -> !contains(item, dataProvider)) .collect(Collectors.toList()); itemList.addAll(afterItemIndex + 1, itemsToAdd); dataProvider.refreshAll(); return this; } throw new IllegalArgumentException( String.format(COLLECTION_TYPE_ERROR_MESSAGE_PATTERN, backendItems.getClass().getSimpleName())); }</code><technical_language>collection added existing items "moved" new positions</technical_language>

Target:
public AbstractListDataView<T> addItemsAfter(Collection<T> items, T after) { addItemCollectionOnTarget(items, after, "Item to insert after is not available in the data", (index, containsTarget) -> containsTarget ? index : index + 1); return this; }
Source:
<code>private Product applyProvidedProductChanges(Product entity, ProductInfo update, Owner owner) { if (update.getProvidedProducts() != null && !update.getProvidedProducts().isEmpty()) { Set<Product> product = new HashSet<>(); for (ProductInfo pInfo : update.getProvidedProducts()) { if (pInfo != null && pInfo.getId() != null) { <START> Product newProd = this.ownerProductCurator.getProductById(owner, <END> pInfo.getId()); if (newProd != null) { product.add(newProd); } } } entity.setProvidedProducts(product); } return entity; }</code><technical_language>This block shown in another PR, is a sign dependent work, is strive avoid in cases. Additionally, database operations slow, lookups avoided in loops if possible. Change this a bulk lookup</technical_language>

Target:
private Product applyProvidedProductChanges(Product entity, ProductInfo update, Owner owner) { if (update.getProvidedProducts() != null) { if (update.getProvidedProducts().isEmpty()) { entity.getProvidedProducts().clear(); } else { entity.getProvidedProducts().clear(); for (ProductInfo providedProductDTO : update.getProvidedProducts()) { if (providedProductDTO != null && providedProductDTO.getId() != null) { Product newProd = this.ownerProductCurator.getProductById(owner, providedProductDTO.getId()); if (newProd != null) { entity.addProvidedProduct(newProd); } } } } } return entity; }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { final GitFlowRepository gfRepo = GitFlowHandlerUtil.getRepository(event); try { FeatureFinishOperation operation = new FeatureFinishOperation(gfRepo); String featureBranch = gfRepo.getRepository().getBranch(); String develop = gfRepo.getConfig().getDevelop(); JobUtil.scheduleUserWorkspaceJob(operation, UIText.FeatureFinishHandler_finishingFeature, JobFamilies.GITFLOW_FAMILY); IJobManager jobMan = Job.getJobManager(); jobMan.join(JobFamilies.GITFLOW_FAMILY, null); MergeResult mergeResult = operation.getMergeResult(); MergeStatus mergeStatus = mergeResult.getMergeStatus(); if (MergeStatus.CONFLICTING.equals(mergeStatus)) { MultiStatus conflictInfo = createMergeConflictInfo(develop, featureBranch); <START> MultiStatus warning = createMergeConflictWarning(mergeResult); <END> conflictInfo.addAll(warning); ErrorDialog.openError(null, UIText.FeatureFinishHandler_Conflicts, null, warning); } } catch (WrongGitFlowStateException | CoreException | IOException | OperationCanceledException | InterruptedException e) { return error(e.getMessage(), e); } return null; }</code><technical_language>createMergeConflictInfo() shows warning, adding warning implementation detail of createMergeConflictInfor() mergeResult needs passed a parameter</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { final GitFlowRepository gfRepo = GitFlowHandlerUtil.getRepository(event); try { FeatureFinishOperation operation = new FeatureFinishOperation(gfRepo); String featureBranch = gfRepo.getRepository().getBranch(); String develop = gfRepo.getConfig().getDevelop(); JobUtil.scheduleUserWorkspaceJob(operation, UIText.FeatureFinishHandler_finishingFeature, JobFamilies.GITFLOW_FAMILY); IJobManager jobMan = Job.getJobManager(); jobMan.join(JobFamilies.GITFLOW_FAMILY, null); MergeResult mergeResult = operation.getMergeResult(); MergeStatus mergeStatus = mergeResult.getMergeStatus(); if (MergeStatus.CONFLICTING.equals(mergeStatus)) { MultiStatus status = createMergeConflictInfo(develop, featureBranch, mergeResult); ErrorDialog.openError(null, UIText.FeatureFinishHandler_Conflicts, null, status); } } catch (WrongGitFlowStateException | CoreException | IOException | OperationCanceledException | InterruptedException e) { return error(e.getMessage(), e); } return null; }
Source:
<code>protected void configure() { final CommandName gerrit = Commands.named("gerrit"); command(gerrit, "approve").to(ReviewCommand.class); command(gerrit, "create-account").to(CreateAccountCommand.class); command(gerrit, "create-group").to(CreateGroupCommand.class); command(gerrit, "create-project").to(CreateProject.class); command(gerrit, "gsql").to(AdminQueryShell.class); command(gerrit, "set-reviewers").to(SetReviewersCommand.class); command(gerrit, "receive-pack").to(Receive.class); command(gerrit, "replicate").to(Replicate.class); command(gerrit, "set-project-parent").to(AdminSetParent.class); command(gerrit, "review").to(ReviewCommand.class); <START> command(gerrit, "archive-project").to(ArchiveProject.class); <END> }</code><technical_language>ArchiveProject class is contained in this change. forget add it</technical_language>

Target:
protected void configure() { final CommandName gerrit = Commands.named("gerrit"); command(gerrit, "approve").to(ReviewCommand.class); command(gerrit, "create-account").to(CreateAccountCommand.class); command(gerrit, "create-group").to(CreateGroupCommand.class); command(gerrit, "rename-group").to(RenameGroupCommand.class); command(gerrit, "create-project").to(CreateProjectCommand.class); command(gerrit, "gsql").to(AdminQueryShell.class); command(gerrit, "set-reviewers").to(SetReviewersCommand.class); command(gerrit, "receive-pack").to(Receive.class); command(gerrit, "replicate").to(Replicate.class); command(gerrit, "set-project-parent").to(AdminSetParent.class); command(gerrit, "review").to(ReviewCommand.class); command(gerrit, "archive-project").to(ArchiveProject.class); }
Source:
<code>private static String readMapping() { JSONParser parser = new JSONParser(); JSONObject jsonObject = new JSONObject(); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); <START> InputStream inputStream = classloader.getResourceAsStream("mapping.json"); <END> try { String mapping = IOUtils.toString(inputStream, "UTF-8"); Object object = parser.parse(mapping); jsonObject = (JSONObject) object; } catch (IOException | ParseException e ) { logger.error(e); } return jsonObject.toJSONString(); }</code><technical_language>Opening a stream closing - this avoided replaced try-with-resources statements</technical_language>

Target:
private static String readMapping() { JSONParser parser = new JSONParser(); JSONObject jsonObject = new JSONObject(); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); try (InputStream inputStream = classloader.getResourceAsStream("mapping.json")) { String mapping = IOUtils.toString(inputStream, "UTF-8"); Object object = parser.parse(mapping); jsonObject = (JSONObject) object; } catch (IOException | ParseException e ) { logger.error(e); } return jsonObject.toJSONString(); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof ByteKeyMap)) return false; final ByteKeyMap<?> other = (ByteKeyMap<?>) obj; if (other.size() != size()) return false; final ByteIterator i = keySet().iterator(); while (i.hasNext()) { byte key = i.next(); V value = get(key); if (value == null) { if (!(other.get(key) == null && other.containsKey(key))) return false; } else { <START> if (value.equals(other.get(key))) { <END> return false; } } } return true; }</code><technical_language>Missing ! operator</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof ByteKeyMap)) return false; final ByteKeyMap<?> other = (ByteKeyMap<?>) obj; if (other.size() != size()) return false; final ByteIterator i = keySet().iterator(); while (i.hasNext()) { byte key = i.next(); V value = get(key); if (value == null) { if (!(other.get(key) == null && other.containsKey(key))) return false; } else { if (!value.equals(other.get(key))) { return false; } } } return true; }
Source:
<code>private synchronized SecretKey getKey(final String keyVersion) throws GeneralSecurityException, IOException { if (VERSION_USER_DEFINED.equals(keyVersion)) { return getSecretKey(AuthenticationSettings.INSTANCE.getSecretKeyData()); } if (VERSION_ANDROID_KEY_STORE.equals(keyVersion)) { <START> if (Build.VERSION.SDK_INT >= 18) { <END> final File keyFile = new File(mContext.getDir(mContext.getPackageName(), Context.MODE_PRIVATE), ADALKS); mKeyPair = readKeyPair(); mSecretKeyFromAndroidKeyStore = getUnwrappedSecretKey(keyFile); return mSecretKeyFromAndroidKeyStore; } } throw new IllegalArgumentException("keyVersion = " + keyVersion); }</code><technical_language>Flip this check throw</technical_language>

Target:
private synchronized SecretKey getKey(final String keyVersion) throws GeneralSecurityException, IOException { switch (keyVersion) { case VERSION_USER_DEFINED : return getSecretKey(AuthenticationSettings.INSTANCE.getSecretKeyData()); case VERSION_ANDROID_KEY_STORE : mKeyPair = readKeyPair(); mSecretKeyFromAndroidKeyStore = getUnwrappedSecretKey(); return mSecretKeyFromAndroidKeyStore; default : throw new IOException("Unknown keyVersion."); } }
Source:
<code>public TrackedVisitor2User getOrCreate(Long memberId) { if (memberId == null) { <START> return create(); <END> } return trackedVisitor2UserDao.getByMemberId(memberId) .orElseGet(() -> { TrackedVisitor2User newInstance = new TrackedVisitor2User(); newInstance.setUserId(memberId); newInstance.setUuid_(generateUniqueUUID()); return trackedVisitor2UserDao.create(newInstance); }); }</code><technical_language>This sense me. passing a memberId == null result in a new TrackedVisitor2User created</technical_language>

Target:
public TrackedVisitor2User getOrCreate(Long memberId) { if (memberId == null) { return createUnknownVisitor(); } return trackedVisitor2UserDao.getByMemberId(memberId).orElse(create(memberId)); }
Source:
<code>public void shouldCaptureAPaymentSuccessfully() { when(response.getStatus()).thenReturn(HttpStatus.SC_OK); when(response.readEntity(String.class)).thenReturn(successCaptureResponse()); Either<GatewayError, GatewayClient.Response> response = right(new TestResponse(this.response)); when(client.postRequestFor(isNull(), any(GatewayAccountEntity.class), any(GatewayOrder.class))).thenReturn(response); Either<GatewayError, SmartpayCaptureResponse> unmarshalledResponse = right(new SmartpayCaptureResponse()); when(client.unmarshallResponse(any(TestResponse.class), any(Class.class))).thenReturn(unmarshalledResponse); ChargeEntity chargeEntity = aValidChargeEntity() .withGatewayAccountEntity(aServiceAccount()) .build(); CaptureGatewayRequest request = CaptureGatewayRequest.valueOf(chargeEntity); CaptureResponse gatewayResponse = smartpayCaptureHandler.capture(request); <START> assertTrue(gatewayResponse.isSuccessful()); <END> }</code><technical_language>Assert some extra things</technical_language>

Target:
public void shouldCaptureAPaymentSuccessfully() { when(response.getStatus()).thenReturn(HttpStatus.SC_OK); when(response.readEntity(String.class)).thenReturn(successCaptureResponse()); Either<GatewayError, GatewayClient.Response> response = right(new TestResponse(this.response)); when(client.postRequestFor(isNull(), any(GatewayAccountEntity.class), any(GatewayOrder.class))).thenReturn(response); Either<GatewayError, SmartpayCaptureResponse> unmarshalledResponse = right(new SmartpayCaptureResponse()); when(client.unmarshallResponse(any(TestResponse.class), any(Class.class))).thenReturn(unmarshalledResponse); ChargeEntity chargeEntity = aValidChargeEntity() .withGatewayAccountEntity(aServiceAccount()) .build(); CaptureGatewayRequest request = CaptureGatewayRequest.valueOf(chargeEntity); CaptureResponse gatewayResponse = smartpayCaptureHandler.capture(request); assertTrue(gatewayResponse.isSuccessful()); assertThat(gatewayResponse.state(), is(CaptureResponse.ChargeState.PENDING)); }
Source:
<code>public SqlStatements() { attributes = new ConcurrentHashMap<>(); templateEngine = new DefinedAttributeTemplateEngine(); sqlParser = new ColonPrefixSqlParser(); sqlLogger = SqlLogger.NOP_SQL_LOGGER; queryTimeout = null; <START> customizers = new ArrayList<>(); <END> }</code><technical_language>this a threadsafe list</technical_language>

Target:
public SqlStatements() { attributes = new ConcurrentHashMap<>(); templateEngine = new DefinedAttributeTemplateEngine(); sqlParser = new ColonPrefixSqlParser(); sqlLogger = SqlLogger.NOP_SQL_LOGGER; queryTimeout = null; }
Source:
<code>protected void handleSwingDropTargetChanged(TreePath path, Transferable swingTransferable) { if (getUpdateSwingFromScoutLock().isAcquired()) { return; } if (swingTransferable != null) { <START> if (getScoutObject() != null) { <END> final ITreeNode scoutNode = treePathToScoutNode(path); Runnable t = new Runnable() { @Override public void run() { getScoutObject().getUIFacade().fireNodeDropTargetChangedFromUI(scoutNode); } }; getSwingEnvironment().invokeScoutLater(t, 0); } } }</code><technical_language>if (swingTransferable != null && getScoutObject() != null) {...}</technical_language>

Target:
protected void handleSwingDropTargetChanged(TreePath path, Transferable swingTransferable) { if (getUpdateSwingFromScoutLock().isAcquired()) { return; } if (swingTransferable != null && getScoutObject() != null) { final ITreeNode scoutNode = treePathToScoutNode(path); Runnable t = new Runnable() { @Override public void run() { getScoutObject().getUIFacade().fireNodeDropTargetChangedFromUI(scoutNode); } }; getSwingEnvironment().invokeScoutLater(t, 0); } }
Source:
<code>protected void executeQueryCommand() { <START> getQueryReturnValue().setReturnValue(DbFacade.getInstance().getVmTemplateDao().getCount()); <END> }</code><technical_language>please separate a method, getVmTemplateDao() getDbFacade()</technical_language>

Target:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(getVmTemplateDao().getCount()); }
Source:
<code>private CompletableFuture<Void> rollbackLocks(CommitData cd) throws Exception { CommitStep firstStep = new RollbackOtherLocks(); firstStep.andThen(new RollbackPrimaryLock()); return firstStep.compose(cd) <START> .thenAccept(v -> cd.commitObserver.commitFailed(cd.getShortCollisionMessage())); <END> }</code><technical_language>v is used/needed, thenRun .thenRun(() -> cd</technical_language>

Target:
private CompletableFuture<Void> rollbackLocks(CommitData cd) { CommitStep firstStep = new RollbackOtherLocks(); firstStep.andThen(new RollbackPrimaryLock()); return firstStep.compose(cd) .thenRun(() -> cd.commitObserver.commitFailed(cd.getShortCollisionMessage())); }
Source:
<code><START> public static AbstractStreamingAnalyticsConnection createStreamingAnalyticsConnection( <END> String vcap, String serviceName) throws IOException { return createStreamingAnalyticsConnection(vcap, serviceName, false); }</code><technical_language>methods public if this is internal interface</technical_language>

Target:
static AbstractStreamingAnalyticsConnection createStreamingAnalyticsConnection( String vcap, String serviceName) throws IOException { return createStreamingAnalyticsConnection(vcap, serviceName, false); }
Source:
<code>public void testFactoryPositionalParameters() { final List<String> names = new ArrayList<>(); names.add("?"); names.add("?"); names.add("?"); final String sql = "insert into test (a, b, c) values (?, ?, ?)"; final ParsedParameters parameters = ParsedParameters.of(true, names); final ParsedSql parsedSql = ParsedSql.of(sql, parameters); assertThat(parsedSql).isNotNull(); assertThat(parsedSql.getSql()).isEqualTo(sql); assertThat(parsedSql.getParameters().isPositional()).isTrue(); <START> assertThat(parsedSql.getParameters().getParameterNames()).containsExactly("?", "?", "?"); <END> }</code><technical_language>containsOnly("?")</technical_language>

Target:
public void testFactoryPositionalParameters() { final String sql = "insert into test (a, b, c) values (?, ?, ?)"; final ParsedParameters parameters = ParsedParameters.positional(3); final ParsedSql parsedSql = ParsedSql.of(sql, parameters); assertThat(parsedSql).isNotNull(); assertThat(parsedSql.getSql()).isEqualTo(sql); assertThat(parsedSql.getParameters().isPositional()).isTrue(); assertThat(parsedSql.getParameters().getParameterNames()).containsOnly("?"); }
Source:
<code>public void fill(ToolBar parent, int toolbarItemIndex) { fResourceClassCombo = new Combo(parent, SWT.NONE); fResourceClassCombo.setEnabled(enabled); int width = populateCombo(); fResourceClassCombo.addSelectionListener(new SelectionListener() { @SuppressWarnings({ "null"}) @Override public void widgetSelected(SelectionEvent e) { String description = fResourceClassCombo.getText(); String id = null; for (int i = 0; i < resourceClasses.length; ++i) if (resourceClasses[i].getHumanDescription().equals(description)) { id = resourceClasses[i].getId(); break; } <START> if (!id.equals(fResourceClassId)) <END> { fResourceClassId = id; getDialogSettings().put("resourceClass", id); if (fListener != null && !blockListener) fListener.resourceClassChanged(fResourceClassId); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); toolItem = new ToolItem(parent, SWT.SEPARATOR); toolItem.setControl(fResourceClassCombo); toolItem.setWidth(width); }</code><technical_language>FindBugs complains this, I suggest following: assert id != null; if (id != null && !id.equals(fResourceClassId))</technical_language>

Target:
public void fill(ToolBar parent, int toolbarItemIndex) { fResourceClassCombo = new Combo(parent, SWT.NONE); fResourceClassCombo.setEnabled(enabled); int width = populateCombo(); fResourceClassCombo.addSelectionListener(new SelectionListener() { @SuppressWarnings({ "null"}) @Override public void widgetSelected(SelectionEvent e) { String description = fResourceClassCombo.getText(); String id = null; for (int i = 0; i < resourceClasses.length; ++i) if (resourceClasses[i].getHumanDescription().equals(description)) { id = resourceClasses[i].getId(); break; } assert id != null; if (id != null && !id.equals(fResourceClassId)) { fResourceClassId = id; getDialogSettings().put("resourceClass", id); if (fListener != null && !blockListener) fListener.resourceClassChanged(fResourceClassId); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); toolItem = new ToolItem(parent, SWT.SEPARATOR); toolItem.setControl(fResourceClassCombo); toolItem.setWidth(width); }
Source:
<code>public void onGrantLeadership() { synchronized (lock) { if (running) { issuedLeaderSessionID = UUID.randomUUID(); clearConfirmedLeaderInformation(); if (LOG.isDebugEnabled()) { LOG.debug( "Grant leadership to contender with session ID {}.", leaderContender.getDescription(), issuedLeaderSessionID); } <START> leaderContender.grantLeadership(issuedLeaderSessionID); <END> } else { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring the grant leadership notification since the has " + "already been closed.", leaderElectionDriver); } } } }</code><technical_language>I call leaderContender lock. This lead deadlocks</technical_language>

Target:
public void onGrantLeadership() { synchronized (lock) { if (running) { issuedLeaderSessionID = UUID.randomUUID(); clearConfirmedLeaderInformation(); if (LOG.isDebugEnabled()) { LOG.debug( "Grant leadership to contender with session ID {}.", leaderContender.getDescription(), issuedLeaderSessionID); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring the grant leadership notification since the has " + "already been closed.", leaderElectionDriver); } return; } } leaderContender.grantLeadership(issuedLeaderSessionID); }
Source:
<code>protected void groupMembershipFromFile(String username) throws LoginException { try (FileInputStream stream = new FileInputStream(groupFile)) { <START> BufferedReader reader = new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8)); <END> String line = null; while ((line = reader.readLine()) != null) { String[] u2g = line.split(":"); if (u2g[0].trim().equals(username)) { subject.getPrincipals().add(new GroupNamePrincipal(u2g[1])); logger.debug("adding group principal '" + u2g[1] + "' for user '" + username + "'"); } } } catch (FileNotFoundException e) { throw new LoginException(e.toString()); } catch (IOException e) { throw new LoginException(e.toString()); } }</code><technical_language>exists a ProActive property could, perhaps, reused: PAProperties#getFileEncoding. However, a quick look, I setting file encoding is required. define encoding JVM startup UTF-8, default encoding is UTF-8. Then, if charset is set creating InputStreamReader, default encoding is used</technical_language>

Target:
protected void groupMembershipFromFile(String username) throws LoginException { try (FileInputStream stream = new FileInputStream(groupFile)) { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line = null; while ((line = reader.readLine()) != null) { String[] u2g = line.split(":"); if (u2g[0].trim().equals(username)) { subject.getPrincipals().add(new GroupNamePrincipal(u2g[1])); logger.debug("adding group principal '" + u2g[1] + "' for user '" + username + "'"); } } } catch (FileNotFoundException e) { throw new LoginException(e.toString()); } catch (IOException e) { throw new LoginException(e.toString()); } }
Source:
<code>public BoundedIterable<Long> newAllEntriesReader() { ArrayList<BoundedIterable<Long>> allEntriesReader = new ArrayList<>(); for ( SpatialKnownIndex index : indexMap.values() ) { try { allEntriesReader.add( index.getOnlineAccessor( descriptor, samplingConfig ).newAllEntriesReader() ); } catch ( IOException e ) { e.printStackTrace(); } } return new BoundedIterable<Long>() { @Override public long maxCount() { return allEntriesReader.stream().map( BoundedIterable::maxCount ).reduce( 0L, ( acc, e ) -> { if ( acc == UNKNOWN_MAX_COUNT || e == UNKNOWN_MAX_COUNT ) { return UNKNOWN_MAX_COUNT; } return acc + e; } ); } @Override <START> public void close() throws Exception <END> { forAll( entries -> ((BoundedIterable) entries).close(), allEntriesReader.toArray() ); } @Override public Iterator<Long> iterator() { return new CombiningIterable( allEntriesReader ).iterator(); } }; }</code><technical_language>Unchecked assignment</technical_language>

Target:
public BoundedIterable<Long> newAllEntriesReader() { ArrayList<BoundedIterable<Long>> allEntriesReader = new ArrayList<>(); for ( SpatialKnownIndex index : indexMap.values() ) { allEntriesReader.add( index.newAllEntriesReader() ); } return new BoundedIterable<Long>() { @Override public long maxCount() { return allEntriesReader.stream().map( BoundedIterable::maxCount ).reduce( 0L, ( acc, e ) -> { if ( acc == UNKNOWN_MAX_COUNT || e == UNKNOWN_MAX_COUNT ) { return UNKNOWN_MAX_COUNT; } return acc + e; } ); } @Override public void close() { forAll( entries -> ((BoundedIterable) entries).close(), allEntriesReader.toArray() ); } @Override public Iterator<Long> iterator() { return new CombiningIterable( allEntriesReader ).iterator(); } }; }
Source:
<code>protected void compute() { final List<ParallelParse> walks = new ArrayList<>(); try { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (!SourceRoot.isSensibleDirectoryToEnter(dir)) { return SKIP_SUBTREE; } <START> if (Files.isSameFile(dir, ParallelParse.this.path)) { <END> ParallelParse w = new ParallelParse(dir, callback); w.fork(); walks.add(w); return SKIP_SUBTREE; } else { return CONTINUE; } } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { return callback.process(file, attrs); } }); } catch (IOException e) { Log.error(e); } for (ParallelParse w : walks) { w.join(); } }</code><technical_language>This is malfunctioning. I why, easy fix is revert, issue SourceRoot</technical_language>

Target:
protected void compute() { final List<ParallelParse> walks = new ArrayList<>(); try { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (!SourceRoot.isSensibleDirectoryToEnter(dir)) { return SKIP_SUBTREE; } if (!Files.isSameFile(dir, ParallelParse.this.path)) { ParallelParse w = new ParallelParse(dir, callback); w.fork(); walks.add(w); return SKIP_SUBTREE; } else { return CONTINUE; } } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { return callback.process(file, attrs); } }); } catch (IOException e) { Log.error(e); } for (ParallelParse w : walks) { w.join(); } }
Source:
<code>public StreamsResultSet readCurrent() { Queue<StreamsDatum> batch = Queues.newConcurrentLinkedQueue(); <START> while(!this.dataQueue.isEmpty()) { <END> ComponentUtils.offerUntilSuccess(ComponentUtils.pollWhileNotEmpty(this.dataQueue), batch); } this.isCompleted.set(batch.size() == 0 && this.dataQueue.isEmpty() && this.dataCollector.isCompleted()); return new StreamsResultSet(batch); }</code><technical_language>data queue continue added to, readCurrent enter a case method return data stops inserted queue. I add a max batch size ensure method returns. Also, want thread calling readCurrent a time</technical_language>

Target:
public StreamsResultSet readCurrent() { Queue<StreamsDatum> batch = Queues.newConcurrentLinkedQueue(); int count = 0; while(!this.dataQueue.isEmpty() && count < MAX_BATCH_SIZE) { ComponentUtils.offerUntilSuccess(ComponentUtils.pollWhileNotEmpty(this.dataQueue), batch); ++count; } this.isCompleted.set(batch.size() == 0 && this.dataQueue.isEmpty() && this.dataCollector.isCompleted()); return new StreamsResultSet(batch); }
Source:
<code>public void buildShellScriptAfterRestart() throws Exception { Assume.assumeNotNull( System.getProperty("port"), "This test requires a fixed port to be available."); <START> final AtomicReference<String> projectName = new AtomicReference<>(); <END> story.addStep( new Statement() { @Override public void evaluate() throws Throwable { Node node = TestUtils.createSwarmClient( story.j, processDestroyer, tmpDir.allocate(), "-deleteExistingClients"); WorkflowJob project = story.j.createProject(WorkflowJob.class); projectName.set(project.getName()); project.setConcurrentBuild(false); project.setDefinition(new CpsFlowDefinition(getFlow(node, 1), true)); WorkflowRun build = project.scheduleBuild2(0).waitForStart(); SemaphoreStep.waitForStart("wait-0/1", build); } }); story.addStep( new Statement() { @Override public void evaluate() throws Throwable { SemaphoreStep.success("wait-0/1", null); WorkflowJob project = story.j.jenkins.getItemByFullName( projectName.get(), WorkflowJob.class); assertNotNull(project); WorkflowRun build = Iterables.getOnlyElement(project.getBuilds()); story.j.waitForCompletion(build); story.j.assertLogContains("ON_SWARM_CLIENT=true", build); story.j.assertBuildStatusSuccess(build); tearDown(); } }); }</code><technical_language>Unnecessary; pass a name argument createProject</technical_language>

Target:
public void buildShellScriptAfterRestart() throws Exception { Assume.assumeNotNull( System.getProperty("port"), "This test requires a fixed port to be available."); story.then( s -> { Node node = TestUtils.createSwarmClient( story.j, processDestroyer, temporaryFolder, "-deleteExistingClients"); WorkflowJob project = story.j.createProject(WorkflowJob.class, "test"); project.setConcurrentBuild(false); project.setDefinition(new CpsFlowDefinition(getFlow(node, 1), true)); WorkflowRun build = project.scheduleBuild2(0).waitForStart(); SemaphoreStep.waitForStart("wait-0/1", build); }); story.then( s -> { SemaphoreStep.success("wait-0/1", null); WorkflowJob project = story.j.jenkins.getItemByFullName("test", WorkflowJob.class); assertNotNull(project); WorkflowRun build = project.getBuildByNumber(1); story.j.assertBuildStatusSuccess(story.j.waitForCompletion(build)); story.j.assertLogContains("ON_SWARM_CLIENT=true", build); tearDown(); }); }
Source:
<code>private UserSyncState calculateUserSyncState(String accountId, String envCrnString, UserSyncStatus userSyncStatus) { Operation lastSync = userSyncStatus.getLastStartedFullSync(); UserSyncState state = UserSyncState.STALE; switch (lastSync.getStatus()) { case RUNNING: state = UserSyncState.SYNCING; break; case COMPLETED: <START> if (lastSync.getSuccessList().stream() .anyMatch(details -> envCrnString.equals(details.getEnvironment()))) { <END> UmsEventGenerationIds currentEventGenerationIds = umsEventGenerationIdsProvider.getEventGenerationIds(accountId, MDCUtils.getRequestId()); if (eventGenerationIdsChecker.isInSync(userSyncStatus, currentEventGenerationIds)) { state = UserSyncState.IN_SYNC; } } break; case REQUESTED: case REJECTED: LOGGER.error("UserSyncStatus.lastStartedFullSync '{}' in unexpected state for environment '{}'", lastSync, lastSync.getStatus(), envCrnString); throw new IllegalStateException( String.format("Last sync operation [%s] for environment '%s' is in unexpected state %s", lastSync.getOperationId(), envCrnString, lastSync.getStatus())); case TIMEDOUT: LOGGER.warn("UserSyncStatus.lastStartedFullSync '{}' is timed out for environment '{}'", lastSync.getOperationId(), envCrnString); break; case FAILED: default: break; } return state; }</code><technical_language>move this a method/variable</technical_language>

Target:
private UserSyncState calculateUserSyncState(String accountId, String envCrnString, UserSyncStatus userSyncStatus) { Operation lastSync = userSyncStatus.getLastStartedFullSync(); UserSyncState state; switch (lastSync.getStatus()) { case RUNNING: state = UserSyncState.SYNC_IN_PROGRESS; break; case COMPLETED: state = calculateStateForCompletedOperation(accountId, envCrnString, userSyncStatus); break; case REQUESTED: case REJECTED: throw createExceptionForUnexpectedOperationStatus(envCrnString, userSyncStatus); case TIMEDOUT: LOGGER.warn("UserSyncStatus.lastStartedFullSync '{}' is timed out for environment '{}'", lastSync.getOperationId(), envCrnString); state = UserSyncState.STALE; break; case FAILED: default: state = UserSyncState.STALE; break; } return state; }
Source:
<code>private void resetView() { fStopThread = true; final Display display = Display.getDefault(); if (display == null || display.isDisposed()) { return; } display.asyncExec(new Runnable() { @Override public void run() { if (display.isDisposed()) { return; } Map<TmfPcapProtocol, Table> tableMap = fTableMap; if (tableMap == null) { return; } for (Entry<TmfPcapProtocol, Table> protocol : <START> tableMap.entrySet()) <END> { if (!protocol.getValue().isDisposed()) { protocol.getValue().removeAll(); } } } }); }</code><technical_language>tableMap.values()</technical_language>

Target:
private void resetView() { fStopThread = true; final Display display = Display.getDefault(); if (display == null || display.isDisposed()) { return; } display.asyncExec(new Runnable() { @Override public void run() { if (display.isDisposed()) { return; } Map<TmfPcapProtocol, Table> tableMap = fTableMap; if (tableMap == null) { return; } for (Table table : tableMap.values()) { if (!table.isDisposed()) { table.removeAll(); } } } }); }
Source:
<code>private boolean isInRebasingState(Repository repo) { if (repo == null) return false; RepositoryState state = repo.getRepositoryState(); <START> return RebaseActionHandler.isRebasing(state); <END> }</code><technical_language>want isRebasing() a method in RepositoryState</technical_language>

Target:
private boolean isInRebasingState(Repository repo) { if (repo == null) return false; RepositoryState state = repo.getRepositoryState(); return state.isRebasing(); }
Source:
<code>private boolean isNonEmpty(@Nullable ICaptureSupplier supplier) { <START> if (supplier != null && !supplier.isEmpty()) { <END> return true; } return false; }</code><technical_language>return supplier != null && !supplier.isEmpty()</technical_language>

Target:
private boolean isNonEmpty(@Nullable ICaptureSupplier supplier) { return supplier != null && !supplier.isEmpty(); }
Source:
<code><START> @Nullable public LatLng parseLatLng(String value) { <END> if (value == null) { return null; } String[] components = value.split(","); if (components.length != 2) { return null; } try { return new LatLng(Double.valueOf(components[0]), Double.valueOf(components[1])); } catch (NumberFormatException e) { return null; } }</code><technical_language>static</technical_language>

Target:
@Nullable public static LatLng parseLatLng(String value) { if (value == null) { return null; } String[] components = value.split(","); if (components.length != 2) { return null; } try { return new LatLng(Double.valueOf(components[0]), Double.valueOf(components[1])); } catch (NumberFormatException e) { return null; } }
Source:
<code>static JavaFile createJavaFile(RuntimePermissionsAnnotatedElement element) { List<ExecutableElement> permissionsMethods = element.getAllNeedsPermissionsMethods(); TypeSpec clazz = TypeSpec.classBuilder(element.getDispatcherClassName()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addFields(createFields(permissionsMethods)) .addMethod(createConstructor()) .addMethods(createNeedsPermissionMethods(element)) .addMethods(createNeedsPermissionsMethods(element)) <START> .addMethod(createOnRequestPermissionsResult(element.getClassName(), permissionsMethods, element)) <END> .build(); String packageName = element.getPackageName(); return JavaFile.builder(packageName, clazz).build(); }</code><technical_language>Please reduce arguments 'element'. valued of element</technical_language>

Target:
static JavaFile createJavaFile(RuntimePermissionsAnnotatedElement element) { List<ExecutableElement> permissionsMethods = element.getAllNeedsPermissionsMethods(); TypeSpec clazz = TypeSpec.classBuilder(element.getDispatcherClassName()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addFields(createFields(permissionsMethods)) .addMethod(createConstructor()) .addMethods(createNeedsPermissionMethods(element)) .addMethods(createNeedsPermissionsMethods(element)) .addMethod(createOnRequestPermissionsResult(element)) .build(); String packageName = element.getPackageName(); return JavaFile.builder(packageName, clazz).build(); }
Source:
<code><START> public VPNConfigParser(Json json) { <END> super(json, TypeLiteral.get(VPNConfig.class)); }</code><technical_language>Remove publicmodifier if this parser class remains</technical_language>

Target:
VPNConfigParser(Json json) { super(json, TypeLiteral.get(VPNConfig.class)); }
Source:
<code>public List<RpslObject> getByKeys(final ObjectType type, final Collection<CIString> searchKeys) { final List<RpslObject> result = new ArrayList<>(searchKeys.size()); for (final CIString searchKey : searchKeys) { try { result.add(getByKey(type, searchKey)); } catch (EmptyResultDataAccessException ignored) { <START> LOGGER.debug("EmptyResultDataAccessException in class ", ignored.getMessage(), ignored.getClass().getName()); <END> } } return result; }</code><technical_language>This is expected exception, if is matching row in database, ignore instead</technical_language>

Target:
public List<RpslObject> getByKeys(final ObjectType type, final Collection<CIString> searchKeys) { final List<RpslObject> result = new ArrayList<>(searchKeys.size()); for (final CIString searchKey : searchKeys) { try { result.add(getByKey(type, searchKey)); } catch (EmptyResultDataAccessException ignored) { } } return result; }
Source:
<code>public void testWithSet() { final AlarmNotification alarmNotification = new AlarmNotification(AlarmType.CLOCK_INVALID, true); final Set<AlarmNotification> alarmNotificationSet = new TreeSet<AlarmNotification>(); alarmNotificationSet.add(alarmNotification); final AlarmNotifications alarmNotifications = new AlarmNotifications(alarmNotificationSet); final AlarmNotificationsDto alarmNotificationsDto = this.configurationMapper.map(alarmNotifications, AlarmNotificationsDto.class); <START> assertNotNull(alarmNotifications); <END> assertNotNull(alarmNotificationsDto); assertNotNull(alarmNotificationSet); assertNotNull(alarmNotificationsDto.getAlarmNotifications()); assertEquals(alarmNotificationSet.size(), alarmNotificationsDto.getAlarmNotifications().size()); assertFalse(alarmNotificationSet.isEmpty()); assertFalse(alarmNotificationsDto.getAlarmNotifications().isEmpty()); assertEquals(alarmNotificationSet.isEmpty(), alarmNotificationsDto.getAlarmNotifications().isEmpty()); final AlarmNotificationDto alarmNotificationDto = new AlarmNotificationDto(AlarmTypeDto.CLOCK_INVALID, true); assertTrue(alarmNotificationsDto.getAlarmNotifications().contains(alarmNotificationDto)); }</code><technical_language>delete this line</technical_language>

Target:
public void testWithSet() { final AlarmNotification alarmNotification = new AlarmNotification(AlarmType.CLOCK_INVALID, true); final Set<AlarmNotification> alarmNotificationSet = new TreeSet<AlarmNotification>(); alarmNotificationSet.add(alarmNotification); final AlarmNotifications alarmNotifications = new AlarmNotifications(alarmNotificationSet); final AlarmNotificationsDto alarmNotificationsDto = this.configurationMapper.map(alarmNotifications, AlarmNotificationsDto.class); assertNotNull(alarmNotificationsDto); assertNotNull(alarmNotificationsDto.getAlarmNotificationsSet()); assertEquals(alarmNotificationSet.size(), alarmNotificationsDto.getAlarmNotificationsSet().size()); assertFalse(alarmNotificationsDto.getAlarmNotificationsSet().isEmpty()); final AlarmNotificationDto alarmNotificationDto = new AlarmNotificationDto(AlarmTypeDto.CLOCK_INVALID, true); assertTrue(alarmNotificationsDto.getAlarmNotificationsSet().contains(alarmNotificationDto)); }