auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Response getChargesJson(@PathParam(ACCOUNT_ID) Long accountId, @QueryParam(EMAIL_KEY) String email, @QueryParam(REFERENCE_KEY) String reference, @QueryParam(STATE_KEY) String state, @QueryParam(CARD_BRAND_KEY) String cardBrand, @QueryParam(FROM_DATE_KEY) String fromDate, @QueryParam(TO_DATE_KEY) String toDate, @QueryParam(PAGE) Long pageNumber, @QueryParam(DISPLAY_SIZE) Long displaySize, @Context UriInfo uriInfo, @HeaderParam(FEATURES_HEADER) String features) { List<Pair<String, String>> inputDatePairMap = ImmutableList.of(Pair.of(FROM_DATE_KEY, fromDate), Pair.of(TO_DATE_KEY, toDate)); List<Pair<String, Long>> nonNegativePairMap = ImmutableList.of(Pair.of(PAGE, pageNumber), Pair.of(DISPLAY_SIZE, displaySize)); return ApiValidators .validateQueryParams(inputDatePairMap, nonNegativePairMap) .map(ResponseUtil::badRequestResponse) .orElseGet(() -> reduce(validateGatewayAccountReference(gatewayAccountDao, accountId) .bimap(handleError, listCharges(new ChargeSearchParams() .withGatewayAccountId(accountId) .withEmailLike(email) .withReferenceLike(reference) .withExternalChargeState(state) .withCardBrand(cardBrand) .withFromDate(parseDate(fromDate)) .withToDate(parseDate(toDate)) .withDisplaySize(displaySize != null ? displaySize : configuration.getTransactionsPaginationConfig().getDisplayPageSize()) <START> .withPage(pageNumber != null ? pageNumber : 1), uriInfo, Optional.ofNullable(features))))); END> }</code><technical_language>features string is a comma-separated list, right? passing down, I desirable tokenise a (possibly empty) list of strings pass down</technical_language>

Target:
public Response getChargesJson(@PathParam(ACCOUNT_ID) Long accountId, @QueryParam(EMAIL_KEY) String email, @QueryParam(REFERENCE_KEY) String reference, @QueryParam(STATE_KEY) String state, @QueryParam(CARD_BRAND_KEY) String cardBrand, @QueryParam(FROM_DATE_KEY) String fromDate, @QueryParam(TO_DATE_KEY) String toDate, @QueryParam(PAGE) Long pageNumber, @QueryParam(DISPLAY_SIZE) Long displaySize, @Context UriInfo uriInfo, @HeaderParam(FEATURES_HEADER) String features) { List<Pair<String, String>> inputDatePairMap = ImmutableList.of(Pair.of(FROM_DATE_KEY, fromDate), Pair.of(TO_DATE_KEY, toDate)); List<Pair<String, Long>> nonNegativePairMap = ImmutableList.of(Pair.of(PAGE, pageNumber), Pair.of(DISPLAY_SIZE, displaySize)); List<String> userFeatures = Optional.ofNullable(features).map(FEATURES_STRING_SPLITTER::splitToList).orElseGet(Collections::emptyList); return ApiValidators .validateQueryParams(inputDatePairMap, nonNegativePairMap) .map(ResponseUtil::badRequestResponse) .orElseGet(() -> reduce(validateGatewayAccountReference(gatewayAccountDao, accountId) .bimap(handleError, listTransactions(new ChargeSearchParams() .withGatewayAccountId(accountId) .withEmailLike(email) .withReferenceLike(reference) .withExternalChargeState(state) .withCardBrand(cardBrand) .withFromDate(parseDate(fromDate)) .withToDate(parseDate(toDate)) .withDisplaySize(displaySize != null ? displaySize : configuration.getTransactionsPaginationConfig().getDisplayPageSize()) .withPage(pageNumber != null ? pageNumber : 1), uriInfo, userFeatures)))); }
Source:
<code>public JClogin() { <START> logger.trace("JClogin(constructor) called."); <END> logger.trace("JClogin(this={}) called.",this); }</code><technical_language>of trace lines removed</technical_language>

Target:
public JClogin() { logger.trace("JClogin(constructor) called."); }
Source:
<code>public void testRemoveVolume() throws Exception { requireDockerApiVersionAtLeast("1.21", "volumes"); final Volume volume1 = sut.createVolume(); sut.removeVolume(volume1); try { sut.removeVolume(volume1); fail("Should not be able to remove a non-existent volume."); } catch (VolumeNotFoundException e) { assertEquals(volume1.name(), e.getVolumeName()); } final Volume volume2 = sut.createVolume(); final HostConfig hostConfig = HostConfig.builder() .binds(Bind.from(volume2).to("/tmp").build()) .build(); final ContainerConfig config = ContainerConfig.builder() .image(BUSYBOX) .hostConfig(hostConfig) .build(); final ContainerCreation container = sut.createContainer(config); try { sut.removeVolume(volume2); <START> fail("Should not be able to remove a volume in use by a container."); <END> } catch (ConflictException ignored) { } sut.removeContainer(container.id()); sut.removeVolume(volume2); }</code><technical_language>ExpectedException too</technical_language>

Target:
public void testRemoveVolume() throws Exception { requireDockerApiVersionAtLeast("1.21", "volumes"); final Volume volume1 = sut.createVolume(); sut.removeVolume(volume1); exception.expect(VolumeNotFoundException.class); exception.expect(volumeNotFoundExceptionWithName(volume1.name())); sut.removeVolume(volume1); final Volume volume2 = sut.createVolume(); final HostConfig hostConfig = HostConfig.builder() .binds(Bind.from(volume2).to("/tmp").build()) .build(); final ContainerConfig config = ContainerConfig.builder() .image(BUSYBOX) .hostConfig(hostConfig) .build(); final ContainerCreation container = sut.createContainer(config); exception.expect(ConflictException.class); sut.removeVolume(volume2); sut.removeContainer(container.id()); sut.removeVolume(volume2); }
Source:
<code>public static PublicKey decodeKeyString(final String key) throws IOException, GeneralSecurityException { String[] words = key.split("\\s+", 3); <START> if (!words[0].equals(SSH_RSA)) { <END> throw new GeneralSecurityException("Unsupported SSH public key"); } try ( ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.decodeBase64(words[1])); DataInputStream dataInputStream = new DataInputStream(inputStream) ) { if (!Arrays.equals(getByteArrayOfData(dataInputStream), SSH_RSA.getBytes(StandardCharsets.UTF_8))) { throw new GeneralSecurityException("Unsupported SSH public key"); } byte[] exponentBytes = getByteArrayOfData(dataInputStream); byte[] modulusBytes = getByteArrayOfData(dataInputStream); return KeyFactory.getInstance("RSA").generatePublic( new RSAPublicKeySpec( new BigInteger(modulusBytes), new BigInteger(exponentBytes) ) ); } }</code><technical_language>if word[0] null, is null-safer compare constant first, SSH_RSA.equals(word[0])</technical_language>

Target:
public static PublicKey decodeKeyString(final String key) throws IOException, GeneralSecurityException { String[] words = key.split("\\s+", 3); if (words.length < 2 || !SSH_RSA.equals(words[0])) { throw new GeneralSecurityException("Unsupported SSH public key"); } try ( ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.decodeBase64(words[1])); DataInputStream dataInputStream = new DataInputStream(inputStream) ) { if (!Arrays.equals(getByteArrayOfData(dataInputStream), SSH_RSA.getBytes(StandardCharsets.UTF_8))) { throw new GeneralSecurityException("Unsupported SSH public key"); } byte[] exponentBytes = getByteArrayOfData(dataInputStream); byte[] modulusBytes = getByteArrayOfData(dataInputStream); return KeyFactory.getInstance("RSA").generatePublic( new RSAPublicKeySpec( new BigInteger(modulusBytes), new BigInteger(exponentBytes) ) ); } }
Source:
<code>public Map<String, String> configure(@NotNull Module ijModule) { JavaModuleClasspath moduleClasspath = new JavaModuleClasspath(); moduleClasspath.dependentModules().add(ijModule); <START> collectModuleClasspath(moduleClasspath, ijModule, true, false); <END> Map<String, String> properties = new HashMap<>(); if (!moduleClasspath.libraries().isEmpty()) { String joinedLibs = StringUtils.join(moduleClasspath.libraries(), SEPARATOR); properties.put(JAVA_LIBRARIES_PROPERTY, joinedLibs); } if (!moduleClasspath.testLibraries().isEmpty()) { String joinedLibs = StringUtils.join(moduleClasspath.testLibraries(), SEPARATOR); properties.put(JAVA_TEST_LIBRARIES_PROPERTY, joinedLibs); } if (!moduleClasspath.binaries().isEmpty()) { String joinedPaths = StringUtils.join(moduleClasspath.binaries(), SEPARATOR); properties.put(JAVA_BINARIES_PROPERTY, joinedPaths); } if (!moduleClasspath.testBinaries().isEmpty()) { String joinedPaths = StringUtils.join(moduleClasspath.testBinaries(), SEPARATOR); properties.put(JAVA_TEST_BINARIES_PROPERTY, joinedPaths); } configureJavaSourceTarget(ijModule, properties); return properties; }</code><technical_language>I simplify boolean flags. In collectModuleClasspath if topLevel==false do loop, in this case do in method is call processCompilerOutput. instead of calling collectModuleClasspath topLevel=false, call processCompilerOutput (probably a null check moved). get rid of topLevel is true. flag simplified in collectModuleClasspath is false. In end this simplify collectModuleClasspath</technical_language>

Target:
public Map<String, String> configure(@NotNull Module ijModule) { JavaModuleClasspath moduleClasspath = new JavaModuleClasspath(); moduleClasspath.dependentModules().add(ijModule); collectModuleClasspath(moduleClasspath, ijModule, true, false); Map<String, String> properties = new HashMap<>(); setMultiValuePropertyIfNonEmpty(properties, JAVA_LIBRARIES_PROPERTY, moduleClasspath.libraries()); setMultiValuePropertyIfNonEmpty(properties, JAVA_TEST_LIBRARIES_PROPERTY, moduleClasspath.testLibraries()); setMultiValuePropertyIfNonEmpty(properties, JAVA_BINARIES_PROPERTY, moduleClasspath.binaries()); setMultiValuePropertyIfNonEmpty(properties, JAVA_TEST_BINARIES_PROPERTY, moduleClasspath.testBinaries()); configureJavaSourceTarget(ijModule, properties); return properties; }
Source:
<code>public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { if(ignoreHiddenFiles && Files.isHidden(dir)){ logger.debug("Skipping cause ignore hidden files/directories", dir); return FileVisitResult.SKIP_SUBTREE; } <START> if(ignoreHiddenFiles && System.getProperty("os.name").contains("Windows") && <END> Files.readAttributes(dir, DosFileAttributes.class).isHidden()){ logger.debug("Skipping since we are ignoring hidden files", dir); return FileVisitResult.SKIP_SUBTREE; } return FileVisitResult.CONTINUE; }</code><technical_language>feels this logic refactored a utility function multiple copies of it. I generally prefer wrap compound clauses in parentheses clarify & components paired: java if(ignoreHiddenFiles && (System.getProperty("os.name").contains("Windows") && Files.readAttributes(dir, DosFileAttributes.class).isHidden())){</technical_language>

Target:
public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { if(ignoreHiddenFiles && Files.isHidden(dir)){ logger.debug("Skipping cause ignore hidden files/directories", dir); return FileVisitResult.SKIP_SUBTREE; } if(ignoreHiddenFiles && PathUtils.isHiddenWindowsFile(dir)){ logger.debug("Skipping since we are ignoring hidden files", dir); return FileVisitResult.SKIP_SUBTREE; } return FileVisitResult.CONTINUE; }
Source:
<code>private String getSignatureAlgorithmURI(X509Certificate certificate) { String sigAlgoUri = RFC5698_DSSC_OID_TO_URI_MAP.get(certificate.getSigAlgOID()); if (sigAlgoUri == null) { sigAlgoUri = ("DSA".equalsIgnoreCase(certificate.getPublicKey().getAlgorithm())) <START> ? WSS4JConstants.SHA384 <END> : WSS4JConstants.RSA; } LOGGER.debug("Using Signature algorithm {}", sigAlgoUri); return sigAlgoUri; }</code><technical_language>SHA384 from</technical_language>

Target:
private String getSignatureAlgorithmURI(X509Certificate certificate) { String sigAlgoUri = ("DSA".equalsIgnoreCase(certificate.getPublicKey().getAlgorithm())) ? DSA_ALGO_URI : RSA_ALGO_URI; LOGGER.debug("Using Signature algorithm {}", sigAlgoUri); return sigAlgoUri; }
Source:
<code>public void tick() { long timeStart = System.currentTimeMillis(); <START> long timeStop = timeStart + CubicChunks.Config.getMaxTimeSpentGeneratingCubesPerTick(); <END> this.skylightCubeDiffuseProcessor.processQueueUntil(timeStop); }</code><technical_language>LightingManager generate cubes. This separate option</technical_language>

Target:
public void tick() { long timeStart = System.currentTimeMillis(); long timeStop = timeStart + CubicChunks.Config.getLightingTickBudget(); this.skylightCubeDiffuseProcessor.processQueueUntil(timeStop); }
Source:
<code>public void onAcceptButtonClicked() { updateFinalEdits(); WorkspaceEdit edit = new WorkspaceEdit(); edit.setChanges(workspaceEdit.getChanges()); <START> edit.setResourceChanges(new LinkedList<>()); <END> for (ResourceChange resourceChange : workspaceEdit.getResourceChanges()) { edit.getResourceChanges().add(Either.forLeft(resourceChange)); } applyWorkspaceEditAction.applyWorkspaceEdit(edit); view.close(); refactoringActionDelegate.closeWizard(); }</code><technical_language>invokes onCancelButtonClicked(); I view.close() is enough</technical_language>

Target:
public void onAcceptButtonClicked() { updateFinalEdits(); applyWorkspaceEditAction.applyWorkspaceEdit(workspaceEdit); view.close(); refactoringActionDelegate.closeWizard(); }
Source:
<code>protected void onBind() { super.onBind(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { List<ActionButtonDefinition<?>> pluginActionButtonList = actionButtonPluginHandler.getButtons(getProxy().getTargetHistoryToken()); <START> if (getTable() != null && pluginActionButtonList != null) { <END> for(ActionButtonDefinition<?> buttonDef: pluginActionButtonList) { getTable().addActionButton((ActionButtonDefinition) buttonDef); } } } }); registerHandler(getEventBus().addHandler(AddTabActionButtonEvent.getType(), new AddTabActionButtonEvent.AddTabActionButtonHandler() { @Override public void onAddTabActionButton(AddTabActionButtonEvent event) { if (getProxy().getTargetHistoryToken().equals(event.getHistoryToken())) { if (getTable() != null) { getTable().addActionButton((ActionButtonDefinition) event.getButtonDefinition()); } } } })); }</code><technical_language>ensure actionButtonPluginHandler.getButtons() returns some (even empty) list null</technical_language>

Target:
protected void onBind() { super.onBind(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { addPluginActionButtons(actionButtonPluginHandler.getButtons(getProxy().getTargetHistoryToken())); } }); registerHandler(getEventBus().addHandler(AddTabActionButtonEvent.getType(), new AddTabActionButtonEvent.AddTabActionButtonHandler() { @Override public void onAddTabActionButton(AddTabActionButtonEvent event) { if (getProxy().getTargetHistoryToken().equals(event.getHistoryToken())) { List<ActionButtonDefinition<?>> pluginActionButtonList = new ArrayList<ActionButtonDefinition<?>>(); pluginActionButtonList.add(event.getButtonDefinition()); addPluginActionButtons(pluginActionButtonList); } } })); }
Source:
<code>protected List<String> getExecutorCommand(String containerId) { final Map<ExecutorPort, String> ports = KubernetesConstants.EXECUTOR_PORTS.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toString())); final Config configuration = getConfiguration(); final Config runtimeConfiguration = getRuntimeConfiguration(); final String[] executorCommand = SchedulerUtils.getExecutorCommand(configuration, runtimeConfiguration, <START> Integer.valueOf(containerId), ports); <END> return Arrays.asList( "sh", "-c", KubernetesUtils.getFetchCommand(configuration, runtimeConfiguration) + " && " + setShardIdEnvironmentVariableCommand() + " && " + String.join(" ", executorCommand) ); }</code><technical_language>This needs a string environment variable for shard id for statefuel sets</technical_language>

Target:
protected List<String> getExecutorCommand(String containerId) { final Map<ExecutorPort, String> ports = KubernetesConstants.EXECUTOR_PORTS.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toString())); final Config configuration = getConfiguration(); final Config runtimeConfiguration = getRuntimeConfiguration(); final String[] executorCommand = SchedulerUtils.getExecutorCommand(configuration, runtimeConfiguration, containerId, ports); return Arrays.asList( "sh", "-c", KubernetesUtils.getFetchCommand(configuration, runtimeConfiguration) + " && " + setShardIdEnvironmentVariableCommand() + " && " + String.join(" ", executorCommand) ); }
Source:
<code>private void updateCodePanel() { String input = info_.getSnippet(); <START> String pattern = "\\$\\{([0-9]+):([^:=}]+)(=([^:}]+))?(:([^}]+))?\\}"; <END> RegExp regExp = RegExp.compile(pattern, "g"); StringBuilder builder = new StringBuilder(); int inputIndex = 0; for (MatchResult matcher = regExp.exec(input); matcher != null; matcher = regExp.exec(input)) { if (matcher.getGroupCount() >= 2) { String key = matcher.getGroup(2); String value = matcher.getGroupCount() >= 4 ? matcher.getGroup(4) : null; String connStringField = matcher.getGroupCount() >= 6 ? matcher.getGroup(6) : null; if (value != null) { value = value.replaceAll("\\$colon\\$", ":"); value = value.replaceAll("\\$equal\\$", "="); } builder.append(input.substring(inputIndex, matcher.getIndex())); if (partsKeyValues_.containsKey(key)) { value = partsKeyValues_.get(key); } if (value != null) { if (connStringField != null) { builder.append(connStringField); builder.append("="); } builder.append(value); if (connStringField != null) { builder.append(";"); } } inputIndex = matcher.getIndex() + matcher.getGroup(0).length(); } } builder.append(input.substring(inputIndex, input.length())); codePanel_.setCode(builder.toString(), ""); }</code><technical_language>Nit: If this needs stay in sync w/ copy of regex, a constant</technical_language>

Target:
private void updateCodePanel() { String input = info_.getSnippet(); RegExp regExp = RegExp.compile(pattern_, "g"); StringBuilder builder = new StringBuilder(); int inputIndex = 0; for (MatchResult matcher = regExp.exec(input); matcher != null; matcher = regExp.exec(input)) { if (matcher.getGroupCount() >= 2) { String key = matcher.getGroup(2); String value = matcher.getGroupCount() >= 4 ? matcher.getGroup(4) : null; String connStringField = matcher.getGroupCount() >= 6 ? matcher.getGroup(6) : null; if (value != null) { value = value.replaceAll("\\$colon\\$", ":"); value = value.replaceAll("\\$equal\\$", "="); } builder.append(input.substring(inputIndex, matcher.getIndex())); if (partsKeyValues_.containsKey(key)) { value = partsKeyValues_.get(key); } if (value != null) { if (connStringField != null) { builder.append(connStringField); builder.append("="); } builder.append(value); if (connStringField != null) { builder.append(";"); } } inputIndex = matcher.getIndex() + matcher.getGroup(0).length(); } } builder.append(input.substring(inputIndex, input.length())); codePanel_.setCode(builder.toString(), ""); }
Source:
<code>private void fillContactDataFromQuery(String query, List<Recipient> recipients, Map<String, Recipient> recipientMap) { ContentResolver contentResolver = getContext().getContentResolver(); query = "%" + query + "%"; final String[] PROJECTION_NICKNAME = new String[]{ContactsContract.Data.CONTACT_ID, ContactsContract.CommonDataKinds.Nickname.NAME}; final int INDEX_CONTACT_ID = 0; final int INDEX_NICKNAME = 1; Uri queryUri = ContactsContract.CommonDataKinds.Email.CONTENT_URI; Uri queryUriForNickname = ContactsContract.Data.CONTENT_URI; Cursor cursorForNickname = contentResolver.query(queryUriForNickname, PROJECTION_NICKNAME, ContactsContract.CommonDataKinds.Nickname.NAME + " LIKE ? AND " + Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE + "'", new String[] { query }, null); <START> if (cursorForNickname != null && cursorForNickname.moveToFirst()) { <END> while (!cursorForNickname.isAfterLast()) { String id = cursorForNickname.getString(INDEX_CONTACT_ID); String selection = ContactsContract.Data.CONTACT_ID + " = ?"; Cursor cursor = contentResolver.query(queryUri, PROJECTION, selection, new String[]{id}, SORT_ORDER); fillContactDataFromCursor(cursor, recipients, recipientMap, cursorForNickname.getString(INDEX_NICKNAME)); cursorForNickname.moveToNext(); } cursorForNickname.close(); } String selection = Contacts.DISPLAY_NAME_PRIMARY + " LIKE ? " + " OR (" + Email.ADDRESS + " LIKE ? AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "')"; String[] selectionArgs = { query, query }; Cursor cursor = contentResolver.query(queryUri, PROJECTION, selection, selectionArgs, SORT_ORDER); if (cursor == null) { return; } fillContactDataFromCursor(cursor, recipients, recipientMap); if (observerContact != null) { observerContact = new ForceLoadContentObserver(); contentResolver.registerContentObserver(queryUri, false, observerContact); } }</code><technical_language>do create a method for this logic too. Smaller methods easier read, logic is more obvious prone error</technical_language>

Target:
private void fillContactDataFromQuery(String query, List<Recipient> recipients, Map<String, Recipient> recipientMap) { boolean foundValidCursor = false; foundValidCursor |= fillContactDataFromNickname(query, recipients, recipientMap); foundValidCursor |= fillContactDataFromNameAndEmail(query, recipients, recipientMap); if (foundValidCursor) { registerContentObserver(); } }
Source:
<code>protected String tryResourceLookup(Resource resource) { try { Method lookup = Resource.class.getDeclaredMethod("lookup"); return (String) lookup.invoke(resource); <START> } catch (NoSuchMethodException e) { return ""; } catch (IllegalAccessException e) { return ""; } catch (InvocationTargetException e) { return ""; } <END> }</code><technical_language>suggestion } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { return ""; }</technical_language>

Target:
protected String tryResourceLookup(Resource resource) { try { Method lookup = Resource.class.getDeclaredMethod("lookup"); return (String) lookup.invoke(resource); } catch (Exception e) { return ""; } }
Source:
<code>private LegacyLabelType(String name, List<LabelValue> values) { super(name, values); <START> checkArgument(id.length() <= 4, "Invalid legacy label ID: \"%s\"", id); <END> }</code><technical_language>This is NPE. do check setId() supplied id != null</technical_language>

Target:
private LegacyLabelType(String name, List<LabelValue> values) { super(name, values); }
Source:
<code>private ExpressionNode nestedBlock(final MethodBuilder builder) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); expect(NewBlock, DelimiterOpeningTag.class); builder.addArgument("$blockSelf", getEmptySource()); if (sym == Colon) { blockPattern(builder); } if (builder.getFirstOuterMethod() == null) { <START> throw new java.lang.NullPointerException("The outer context of a block should never be null"); <END> } String outerMethodName = stripColons(builder.getFirstOuterMethod(). getSignature().getString()); String blockSig = "λ" + outerMethodName + "@" + lexer.getCurrentLineNumber() + "@" + lexer.getCurrentColumn(); int argSize = builder.getNumberOfArguments(); for (int i = 1; i < argSize; i++) { blockSig += ":"; } builder.setSignature(symbolFor(blockSig)); ExpressionNode expressions = blockContents(builder); expect(EndBlock, DelimiterClosingTag.class); lastMethodsSourceSection = getSource(coord); return expressions; }</code><technical_language>this turned assertion? Java assert builder.getFirstOuterMethod() == null: "The outer context of a block null";</technical_language>

Target:
private ExpressionNode nestedBlock(final MethodBuilder builder) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); expect(NewBlock, DelimiterOpeningTag.class); builder.addArgument("$blockSelf", getEmptySource()); if (sym == Colon) { blockPattern(builder); } String outerMethodName = stripColons(builder.getOuterBuilder(). getSignature().getString()); String blockSig = "λ" + outerMethodName + "@" + coord.startLine + "@" + coord.startColumn; int argSize = builder.getNumberOfArguments(); for (int i = 1; i < argSize; i++) { blockSig += ":"; } builder.setSignature(symbolFor(blockSig)); ExpressionNode expressions = blockContents(builder); expect(EndBlock, DelimiterClosingTag.class); lastMethodsSourceSection = getSource(coord); return expressions; }
Source:
<code>public int visit(IASTExpression expression) { if (!ctorDtorStack.empty()) { if (expression instanceof IASTFunctionCallExpression) { IASTFunctionCallExpression fCall = (IASTFunctionCallExpression) expression; IASTExpression fNameExp = fCall.getFunctionNameExpression(); IBinding fBinding = null; if (fNameExp instanceof IASTIdExpression) { IASTIdExpression fName = (IASTIdExpression) fNameExp; fBinding = fName.getName().resolveBinding(); } else if (fNameExp instanceof IASTFieldReference) { IASTFieldReference fName = (IASTFieldReference) fNameExp; if (referencesThis(fName.getFieldOwner())) fBinding = fName.getFieldName().resolveBinding(); } if <START> (fBinding != null && <END> fBinding instanceof ICPPMethod) { ICPPMethod method = (ICPPMethod) fBinding; if (method.isPureVirtual() || ClassTypeHelper.isVirtual(method)) { reportProblem(VIRTUAL_CALL_ID, expression); } } } } return PROCESS_CONTINUE; }</code><technical_language>redundant null check</technical_language>

Target:
public int visit(IASTExpression expression) { if (!ctorDtorStack.empty() && ctorDtorStack.peek()) { if (expression instanceof IASTFunctionCallExpression) { IASTFunctionCallExpression fCall = (IASTFunctionCallExpression) expression; IASTExpression fNameExp = fCall.getFunctionNameExpression(); IBinding fBinding = null; IASTNode problemNode = expression; if (fNameExp instanceof IASTIdExpression) { IASTIdExpression fName = (IASTIdExpression) fNameExp; fBinding = fName.getName().resolveBinding(); } else if (fNameExp instanceof IASTFieldReference) { IASTFieldReference fName = (IASTFieldReference) fNameExp; problemNode = fName.getFieldName(); if (referencesThis(fName.getFieldOwner())) fBinding = fName.getFieldName().resolveBinding(); } if (fBinding instanceof ICPPMethod) { ICPPMethod method = (ICPPMethod) fBinding; if (method.isPureVirtual() || ClassTypeHelper.isVirtual(method)) { reportProblem(VIRTUAL_CALL_ID, problemNode); } } } } return PROCESS_CONTINUE; }
Source:
<code>public PhoenixTTLRegionScanner(RegionCoprocessorEnvironment env, Scan scan, RegionScanner scanner) throws IOException { this.scan = scan; this.scanner = scanner; byte[] requestIdBytes = scan.getAttribute(MASK_PHOENIX_TTL_EXPIRED_REQUEST_ID_ATTR); this.requestId = Bytes.toLong(requestIdBytes); deleteIfExpired = ScanUtil.isDeleteTTLExpiredRows(scan); <START> maskIfExpired = !deleteIfExpired && ScanUtil.isMaskTTLExpiredRows(scan); <END> region = env.getRegion(); emptyCF = scan.getAttribute(EMPTY_COLUMN_FAMILY_NAME); emptyCQ = scan.getAttribute(EMPTY_COLUMN_QUALIFIER_NAME); byte[] txnScn = scan.getAttribute(BaseScannerRegionObserver.TX_SCN); if (txnScn != null) { TimeRange timeRange = scan.getTimeRange(); scan.setTimeRange(timeRange.getMin(), Bytes.toLong(txnScn)); } minTimestamp = scan.getTimeRange().getMin(); maxTimestamp = scan.getTimeRange().getMax(); now = maxTimestamp != HConstants.LATEST_TIMESTAMP ? maxTimestamp : EnvironmentEdgeManager.currentTimeMillis(); }</code><technical_language>checks avoid a case of attributes set? screw if happen</technical_language>

Target:
public PhoenixTTLRegionScanner(RegionCoprocessorEnvironment env, Scan scan, RegionScanner scanner) throws IOException { this.scan = scan; this.scanner = scanner; byte[] requestIdBytes = scan.getAttribute(MASK_PHOENIX_TTL_EXPIRED_REQUEST_ID_ATTR); this.requestId = Bytes.toString(requestIdBytes); deleteIfExpired = ScanUtil.isDeleteTTLExpiredRows(scan); maskIfExpired = !deleteIfExpired && ScanUtil.isMaskTTLExpiredRows(scan); region = env.getRegion(); emptyCF = scan.getAttribute(EMPTY_COLUMN_FAMILY_NAME); emptyCQ = scan.getAttribute(EMPTY_COLUMN_QUALIFIER_NAME); scanTableName = scan.getAttribute(BaseScannerRegionObserver.PHOENIX_TTL_SCAN_TABLE_NAME); byte[] txnScn = scan.getAttribute(BaseScannerRegionObserver.TX_SCN); if (txnScn != null) { TimeRange timeRange = scan.getTimeRange(); scan.setTimeRange(timeRange.getMin(), Bytes.toLong(txnScn)); } minTimestamp = scan.getTimeRange().getMin(); maxTimestamp = scan.getTimeRange().getMax(); now = maxTimestamp != HConstants.LATEST_TIMESTAMP ? maxTimestamp : EnvironmentEdgeManager.currentTimeMillis(); }
Source:
<code>public void initialize() { windowSize = this.windowSizeOption.getValue(); alphaDrift = this.alphaDriftOption.getValue(); alphaWarning = this.alphaWarningOption.getValue(); storedPredictions = new byte[windowSize]; resetLearning(); <START> System.out.println("STEPD - Parameters: Window Size = " + windowSize + ", Alpha Drift = " + alphaDrift + ", Alpha Warning = " + alphaWarning); <END> }</code><technical_language>preferable system.out.println if possible</technical_language>

Target:
public void initialize() { windowSize = this.windowSizeOption.getValue(); alphaDrift = this.alphaDriftOption.getValue(); alphaWarning = this.alphaWarningOption.getValue(); storedPredictions = new byte[windowSize]; resetLearning(); }
Source:
<code>public void testSeekControlsPostAdBreak() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(2); eventEmitter.on(OnceUxEventType.END_AD_BREAK, new EventListener() { @Override public void processEvent(Event event) { Log.v(TAG, "END_AD_BREAK Emitted. Seeking from: " + progress); seekTo(40000); latch.countDown(); } }); eventEmitter.on(EventType.PROGRESS, new EventListener() { @Override public void processEvent(Event event) { if (progress > 39500) { <START> if (progress < 41500) { <END> Log.v(TAG, "Successful seek at: " + progress); latch.countDown(); } else { Log.v(TAG, "Too far."); } } else { Log.v(TAG, "Not far enough. "); } } }); mainActivity.getOnceUxPlugin().processVideo(adUrl, contentUrl); eventEmitter.emit(EventType.PLAY); assertTrue("Timeout occurred.", latch.await(2, TimeUnit.MINUTES)); brightcoveVideoView.stopPlayback(); }</code><technical_language>progress positions significant? defined a constant</technical_language>

Target:
public void testSeekControlsPostAdBreak() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(2); eventEmitter.on(OnceUxEventType.END_AD_BREAK, new EventListener() { @Override public void processEvent(Event event) { Log.v(TAG, "END_AD_BREAK Emitted. Seeking from: " + progress); seekTo(40000); latch.countDown(); } }); eventEmitter.on(EventType.PROGRESS, new EventListener() { @Override public void processEvent(Event event) { int playheadPositionBefore = 39500; int playheadPositionAfter = 41500; if (progress > playheadPositionBefore) { if (progress < playheadPositionAfter) { Log.v(TAG, "Successful seek at: " + progress); latch.countDown(); } else { Log.v(TAG, "Position has extended past the defined seek location."); } } else { Log.v(TAG, "Position has not yet reached the defined seek location."); } } }); mainActivity.getOnceUxPlugin().processVideo(adUrl, contentUrl); eventEmitter.emit(EventType.PLAY); assertTrue("Timeout occurred.", latch.await(2, TimeUnit.MINUTES)); brightcoveVideoView.stopPlayback(); }
Source:
<code>public Object getResult() { <START> if(resultField == null) { <END> return ""; } try { return resultField.get(this); } catch (IllegalArgumentException e) { log.error("Cannot access result field"); } catch (IllegalAccessException e) { log.error("No permissions to access result field"); } return null; }</code><technical_language>nit: missing space if</technical_language>

Target:
public Object getResult() { if (resultField == null) { return null; } try { return resultField.get(this); } catch (IllegalArgumentException e) { log.error("Cannot access result field"); } catch (IllegalAccessException e) { log.error("No permissions to access result field"); } return null; }
Source:
<code>private boolean isCanadaFipsCountryCode (String countryCode) { return (StringUtils.isNotBlank(countryCode) && <START> StringUtils.equalsIgnoreCase(countryCode, PaymentWorksConstants.COUNTRY_CODE_CANADA)); <END> }</code><technical_language>StringUtils.equalsIgnoreCase() null-safe, need a non-blank check here</technical_language>

Target:
private boolean isCanadaFipsCountryCode (String countryCode) { return (StringUtils.equalsIgnoreCase(countryCode, PaymentWorksConstants.FIPS_COUNTRY_CODE_CANADA)); }
Source:
<code>public WithBuilder<Q> withRecursive(final EntityPath<?> alias, Path<?>... columns) { final Expression<Object> columnsCombined = ExpressionUtils.list(Object.class, columns); final Expression<?> aliasCombined = Expressions.operation(alias.getType(), JPQLNextOps.WITH_RECURSIVE_COLUMNS, alias, columnsCombined); <START> return new WithBuilder<Q>() { <END> @Override public Q as(Expression expr) { Expression<?> flag = ExpressionUtils.operation(alias.getType(), JPQLNextOps.WITH_RECURSIVE_ALIAS, aliasCombined, expr); return queryMixin.addFlag(new QueryFlag(QueryFlag.Position.WITH, flag)); } }; }</code><technical_language>create a private static class for this instead a field for JPQLNextOps pass JPQLNextOps.WITH_RECURSIVE_COLUMNS here. In method class pass JPQLNextOps.WITH_ALIAS</technical_language>

Target:
public WithBuilder<Q> withRecursive(final EntityPath<?> alias, Path<?>... columns) { final Expression<Object> columnsCombined = ExpressionUtils.list(Object.class, columns); final Expression<?> aliasCombined = Expressions.operation(alias.getType(), JPQLNextOps.WITH_RECURSIVE_COLUMNS, alias, columnsCombined); return new WithBuilderImpl(JPQLNextOps.WITH_RECURSIVE_ALIAS, alias, aliasCombined); }
Source:
<code>public static LocalDateTime combineDateTimeNew(String inputDate, String inputTimeHours) { if (inputDate == null || inputTimeHours == null) { return null; } DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy H.mm"); String dateTimeString; if ("24".equals(inputTimeHours)) { dateTimeString = inputDate + " 23.59"; } else { dateTimeString = inputDate + " " + inputTimeHours + ".00"; } try { return LocalDateTime.parse(dateTimeString, formatter); <START> } catch (Exception e) { <END> return null; } }</code><technical_language>this intentional</technical_language>

Target:
public static LocalDateTime combineDateTimeNew(String inputDate, String inputTimeHours) { if (inputDate == null || inputTimeHours == null) { return null; } DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy H.mm"); String dateTimeString; if ("24".equals(inputTimeHours)) { dateTimeString = inputDate + " 23.59"; } else { dateTimeString = inputDate + " " + inputTimeHours + ".00"; } try { return LocalDateTime.parse(dateTimeString, formatter); } catch (DateTimeParseException e) { return null; } }
Source:
<code>protected Command getShowHideCompartmentCommand(ShowHideCompartmentRequest request) { if (getHost() instanceof TopGraphicEditPart) { List<?> views = getAllNotationViews((TopGraphicEditPart) getHost()); for (Iterator<?> iter = views.iterator(); iter.hasNext();) { View childView = (View) iter.next(); if (ViewUtil.isPropertySupported(childView, request.getPropertyID())) { if (childView.equals(request.getCompartment())) { if (request.getValue() instanceof Boolean && ((Boolean) request.getValue())) { <START> getDiagramEventBroker().addNotificationListener(childView, <END> listener); childlistened.add(childView); } else { getDiagramEventBroker().removeNotificationListener(childView, listener); childlistened.remove(childView); } return new ICommandProxy(new SetPropertyCommand(getEditingDomain(), new EObjectAdapter(childView), request.getPropertyID(), request.getPropertyName(), request.getValue())); } } } } return null; }</code><technical_language>This method return a null implies a NPE</technical_language>

Target:
protected Command getShowHideCompartmentCommand(ShowHideCompartmentRequest request) { if (getHost() instanceof TopGraphicEditPart) { List<?> views = getAllNotationViews((TopGraphicEditPart) getHost()); for (Iterator<?> iter = views.iterator(); iter.hasNext();) { View childView = (View) iter.next(); if (ViewUtil.isPropertySupported(childView, request.getPropertyID())) { if (childView.equals(request.getCompartment())) { DiagramEventBroker diagramEventBroker = getDiagramEventBroker(); if (request.getValue() instanceof Boolean && null != diagramEventBroker) { if ((Boolean) request.getValue()) { diagramEventBroker.addNotificationListener(childView, listener); childlistened.add(childView); } else { diagramEventBroker.removeNotificationListener(childView, listener); childlistened.remove(childView); } } return new ICommandProxy(new SetPropertyCommand(getEditingDomain(), new EObjectAdapter(childView), request.getPropertyID(), request.getPropertyName(), request.getValue())); } } } } return null; }
Source:
<code>private Configuration getConfiguration(SessionParams params) { Configuration config = new Configuration(); HardwareConfig hardwareConfig = params.getHardwareConfig(); ScreenSize screenSize = hardwareConfig.getScreenSize(); if (screenSize != null) { switch (screenSize) { case SMALL: config.screenLayout |= 0x1; break; case NORMAL: config.screenLayout |= 0x2; break; case LARGE: config.screenLayout |= 0x3; break; case XLARGE: config.screenLayout |= 0x4; } <START> <END> } Density density = hardwareConfig.getDensity(); if (density == null) { density = Density.MEDIUM; } config.screenWidthDp = (hardwareConfig.getScreenWidth() / density.getDpiValue()); config.screenHeightDp = (hardwareConfig.getScreenHeight() / density.getDpiValue()); if (config.screenHeightDp < config.screenWidthDp) { config.smallestScreenWidthDp = config.screenHeightDp; } else { config.smallestScreenWidthDp = config.screenWidthDp; } config.densityDpi = density.getDpiValue(); config.compatScreenWidthDp = config.screenWidthDp; config.compatScreenHeightDp = config.screenHeightDp; ScreenOrientation orientation = hardwareConfig.getOrientation(); if (orientation != null) { switch (orientation) { case PORTRAIT: config.orientation = 1; break; case LANDSCAPE: config.orientation = 2; break; case SQUARE: config.orientation = 3; } } else { config.orientation = 0; } return config; }</code><technical_language>remove blank line</technical_language>

Target:
private static Configuration getConfiguration(SessionParams params) { Configuration config = new Configuration(); HardwareConfig hardwareConfig = params.getHardwareConfig(); ScreenSize screenSize = hardwareConfig.getScreenSize(); if (screenSize != null) { switch (screenSize) { case SMALL: config.screenLayout |= 0x1; break; case NORMAL: config.screenLayout |= 0x2; break; case LARGE: config.screenLayout |= 0x3; break; case XLARGE: config.screenLayout |= 0x4; } } Density density = hardwareConfig.getDensity(); if (density == null) { density = Density.MEDIUM; } config.screenWidthDp = (hardwareConfig.getScreenWidth() / density.getDpiValue()); config.screenHeightDp = (hardwareConfig.getScreenHeight() / density.getDpiValue()); if (config.screenHeightDp < config.screenWidthDp) { config.smallestScreenWidthDp = config.screenHeightDp; } else { config.smallestScreenWidthDp = config.screenWidthDp; } config.densityDpi = density.getDpiValue(); config.compatScreenWidthDp = config.screenWidthDp; config.compatScreenHeightDp = config.screenHeightDp; ScreenOrientation orientation = hardwareConfig.getOrientation(); if (orientation != null) { switch (orientation) { case PORTRAIT: config.orientation = 1; break; case LANDSCAPE: config.orientation = 2; break; case SQUARE: config.orientation = 3; } } else { config.orientation = 0; } return config; }
Source:
<code>private static void sendOneZipEntry(ZipOutputStream zos, VirtualFile vf, String relativePath) throws IOException { ZipEntry e = new ZipEntry(relativePath.replace('\\', '/')); e.setTime(vf.lastModified()); zos.putNextEntry(e); try (InputStream in = vf.open()) { IOUtils.copy(in, zos); } <START> zos.closeEntry(); <END> }</code><technical_language>add finally? ZIP stream corrupted if cf.open() copy fail</technical_language>

Target:
private static void sendOneZipEntry(ZipOutputStream zos, VirtualFile vf, String relativePath) throws IOException { ZipEntry e = new ZipEntry(relativePath.replace('\\', '/')); e.setTime(vf.lastModified()); zos.putNextEntry(e); try (InputStream in = vf.open()) { IOUtils.copy(in, zos); } finally { zos.closeEntry(); } }
Source:
<code>public static void setVmHook(VMHook vmHook) { <START> logger.warn("This deprecated method doesn't set VM hook. Define your hook component as a Spring bean."); <END> }</code><technical_language>preserve setVmHook logic compatible</technical_language>

Target:
public static void setVmHook(VMHook vmHook) { logger.warn("VM.setVmHook(VMHook vmHook) is deprecated method. Define your hook component as a Spring bean."); BackwardCompatibilityVmHook.setDeprecatedHook(vmHook); }
Source:
<code>public void call(final Subscriber<? super Cursor> subscriber) { final ContentResolver contentResolver = context.getContentResolver(); final DefaultContentObserver observer = new DefaultContentObserver(new Handler(Looper.getMainLooper())) { @Override public void onChange(boolean selfChange) { worker.schedule(new Action0() { @Override public void call() { subscriber.onNext(getCursor()); } }); } }; <START> final Subscription subscription = AndroidSubscriptions.unsubscribeInUiThread(new Action0() { <END> @Override public void call() { contentResolver.unregisterContentObserver(observer); } }); worker.schedule(new Action0() { @Override public void call() { subscriber.onNext(getCursor()); } }); contentResolver.registerContentObserver(uri, true, observer); subscriber.add(subscription); }</code><technical_language>this happen main UI thread? Subscriptions thread safe I practice unsubscribe soon instead of delaying waiting for main looper process</technical_language>

Target:
public void call(final Subscriber<? super Cursor> subscriber) { final DefaultContentObserver observer = new DefaultContentObserver(new Handler(Looper.getMainLooper())) { @Override public void onChange(boolean selfChange) { worker.schedule(new Action0() { @Override public void call() { subscriber.onNext(executeQuery()); } }); } }; final Subscription subscription = Subscriptions.create(new Action0() { @Override public void call() { resolver.unregisterContentObserver(observer); } }); worker.schedule(new Action0() { @Override public void call() { subscriber.onNext(executeQuery()); } }); resolver.registerContentObserver(uri, true, observer); subscriber.add(subscription); }
Source:
<code>public void getSlotsEligibleReturnsSlotsThatWereNotRolled() { slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L); List<Integer> slots = slotStateManager.getSlotsEligibleForRollup(2346L, 0, 1); assertNotNull(slots); assertEquals(1, slots.size()); <START> assertEquals(0, slots.get(0).intValue()); <END> }</code><technical_language>add message assert easy assert failed? assertEquals("Slot size", 1, slots.size());</technical_language>

Target:
public void getSlotsEligibleReturnsSlotsThatWereNotRolled() { slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L); List<Integer> slots = slotStateManager.getSlotsEligibleForRollup(2346L, 0, 1); assertNotNull(slots); assertEquals("Only one slot should be returned", 1, slots.size()); assertEquals("Slot zero should be included", 0, slots.get(0).intValue()); }
Source:
<code>public static PythonDependencyInfo create(PythonConfig pythonConfig, DistributedCache distributedCache) { Map<String, String> pythonFiles = new HashMap<>(); Map<String, String> filesIdToFilesName = pythonConfig.getPythonFilesInfo(); for (Map.Entry<String, String> entry: filesIdToFilesName.entrySet()) { File pythonFile = distributedCache.getFile(entry.getKey()); String filePath = pythonFile.getAbsolutePath(); pythonFiles.put(filePath, entry.getValue()); } String requirementsFilePath = null; String requirementsCacheDir = null; if (pythonConfig.getPythonRequirementsFileInfo().isPresent()) { requirementsFilePath = distributedCache.getFile( pythonConfig.getPythonRequirementsFileInfo().get()).getAbsolutePath(); if (pythonConfig.getPythonRequirementsCacheDirInfo().isPresent()) { requirementsCacheDir = distributedCache.getFile( pythonConfig.getPythonRequirementsCacheDirInfo().get()).getAbsolutePath(); } } Map<String, String> archives = new HashMap<>(); <START> Map<String, String> archivesMap = pythonConfig.getPythonArchivesInfo(); <END> for (Map.Entry<String, String> entry: archivesMap.entrySet()) { String archiveFilePath = distributedCache.getFile(entry.getKey()).getAbsolutePath(); String targetPath = entry.getValue(); archives.put(archiveFilePath, targetPath); } String pythonExec = pythonConfig.getPythonExec(); return new PythonDependencyInfo( pythonFiles, requirementsFilePath, requirementsCacheDir, archives, pythonExec); }</code><technical_language>Remove this local variable is difficult differentiate local variable archives</technical_language>

Target:
public static PythonDependencyInfo create(PythonConfig pythonConfig, DistributedCache distributedCache) { Map<String, String> pythonFiles = new HashMap<>(); for (Map.Entry<String, String> entry: pythonConfig.getPythonFilesInfo().entrySet()) { File pythonFile = distributedCache.getFile(entry.getKey()); String filePath = pythonFile.getAbsolutePath(); pythonFiles.put(filePath, entry.getValue()); } String requirementsFilePath = null; String requirementsCacheDir = null; if (pythonConfig.getPythonRequirementsFileInfo().isPresent()) { requirementsFilePath = distributedCache.getFile( pythonConfig.getPythonRequirementsFileInfo().get()).getAbsolutePath(); if (pythonConfig.getPythonRequirementsCacheDirInfo().isPresent()) { requirementsCacheDir = distributedCache.getFile( pythonConfig.getPythonRequirementsCacheDirInfo().get()).getAbsolutePath(); } } Map<String, String> archives = new HashMap<>(); for (Map.Entry<String, String> entry: pythonConfig.getPythonArchivesInfo().entrySet()) { String archiveFilePath = distributedCache.getFile(entry.getKey()).getAbsolutePath(); String targetPath = entry.getValue(); archives.put(archiveFilePath, targetPath); } String pythonExec = pythonConfig.getPythonExec(); return new PythonDependencyInfo( pythonFiles, requirementsFilePath, requirementsCacheDir, archives, pythonExec); }
Source:
<code>private void setDiskImageActiveBySnapshotType(Map<Guid, List<DiskImage>> diskImageMap, Snapshot snapshot) { List<DiskImage> diskImages = diskImageMap.get(snapshot.getId()); if (diskImages == null) { return; } <START> diskImages.forEach(diskImage -> diskImage.setActive(snapshot.getType() == SnapshotType.ACTIVE || snapshot.getType() == SnapshotType.PREVIEW)); <END> diskImageMap.remove(snapshot.getId()); }</code><technical_language>suggesting break this line for readability: bool active = snapshot.getType() == SnapshotType.ACTIVE || snapshot.getType() == SnapshotType.PREVIEW; diskImages.forEach(diskImage -> diskImage.setActive(active));</technical_language>

Target:
private void setDiskImageActiveBySnapshotType(Map<Guid, List<DiskImage>> diskImageMap, Snapshot snapshot) { List<DiskImage> diskImages = diskImageMap.get(snapshot.getId()); if (diskImages == null) { return; } boolean isActiveSnapshotType = snapshot.getType() == SnapshotType.ACTIVE || snapshot.getType() == SnapshotType.PREVIEW; diskImages.forEach(diskImage -> diskImage.setActive(isActiveSnapshotType)); diskImageMap.remove(snapshot.getId()); }
Source:
<code>public Iterator<String> getKeys(final String prefix) { return new Iterator<String>() { Iterator<String> iter = getKeys(); String next; <START> String prev; <END> { while (iter.hasNext()) { next = iter.next(); if (next.startsWith(prefix)) { break; } else { next = null; } } } @Override public boolean hasNext() { return next != null; } @Override public String next() { if (next == null) { throw new IllegalStateException(); } prev = next; while (iter.hasNext()) { next = iter.next(); if (next.startsWith(prefix)) { break; } else { next = null; } } if (next != null && next.equals(prev)) { next = null; } return prev; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }</code><technical_language>need for 'prev' a field</technical_language>

Target:
public Iterator<String> getKeys(final String prefix) { return new Iterator<String>() { Iterator<String> iter = getKeys(); String next; { while (iter.hasNext()) { next = iter.next(); if (next.startsWith(prefix)) { break; } else { next = null; } } } @Override public boolean hasNext() { return next != null; } @Override public String next() { if (next == null) { throw new IllegalStateException(); } String current = next; next = null; while (iter.hasNext()) { next = iter.next(); if (next.startsWith(prefix)) { break; } else { next = null; } } return current; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }