auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String translate(final StringAgg stringAgg) { inject(stringAgg.column); <START> if (stringAgg.isDistinct()) { <END> return String.format( "LISTAGG(DISTINCT CAST (%s AS TEXT), CAST ('%c' AS TEXT))", stringAgg.getColumn().translate(), stringAgg.getDelimiter() ); } else { return String.format( "LISTAGG(CAST (%s AS TEXT), CAST ('%c' AS TEXT))", stringAgg.getColumn().translate(), stringAgg.getDelimiter() ); } }</code><technical_language>I suggest if adding a new variable String.format return "" "DISTINCT "</technical_language>

Target:
public String translate(final StringAgg stringAgg) { if (stringAgg.isDistinct()) { throw new OperationNotSupportedRuntimeException("LISTAGG does not support distinct in this DB2 version. " + "If you really need it, " + "you may do it using regex or a subquery."); } inject(stringAgg.column); String column = stringAgg.getColumn().translate(); return String.format( "LISTAGG(%s, '%c') WITHIN GROUP(ORDER BY %s)", column, stringAgg.getDelimiter(), column ); }
Source:
<code>public static void showWhile(Display display, Runnable runnable) { if (runnable == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (display == null) { display = Display.getCurrent(); if (display == null) { runnable.run(); return; } } Integer busyId = Integer.valueOf(nextBusyId); nextBusyId++; Cursor cursor = display.getSystemCursor(SWT.CURSOR_WAIT); Shell[] shells = display.getShells(); <START> for (int i = 0; i < shells.length; i++) { <END> Shell shell = shells[i]; if (shell.isDisposed()) { continue; } Integer id = (Integer)shell.getData(BUSYID_NAME); if (id == null) { shell.setCursor(cursor); shell.setData(BUSYID_NAME, busyId); } } try { runnable.run(); } finally { shells = display.getShells(); for (int i = 0; i < shells.length; i++) { Shell shell = shells[i]; if (shell.isDisposed()) { continue; } Integer id = (Integer)shell.getData(BUSYID_NAME); if (id == busyId) { shell.setCursor(null); shell.setData(BUSYID_NAME, null); } } } }</code><technical_language>foreach here? code a bit more readable</technical_language>

Target:
public static void showWhile(Display display, Runnable runnable) { if (runnable == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (display == null) { display = Display.getCurrent(); if (display == null) { runnable.run(); return; } } Integer busyId = Integer.valueOf(nextBusyId); nextBusyId++; Cursor cursor = display.getSystemCursor(SWT.CURSOR_WAIT); for (Shell shell: display.getShells()) { if (shell.isDisposed()) { continue; } Integer id = (Integer)shell.getData(BUSYID_NAME); if (id == null) { shell.setCursor(cursor); shell.setData(BUSYID_NAME, busyId); } } try { runnable.run(); } finally { for (Shell shell: display.getShells()) { if (shell.isDisposed()) { continue; } Integer id = (Integer)shell.getData(BUSYID_NAME); if (id == busyId) { shell.setCursor(null); shell.setData(BUSYID_NAME, null); } } } }
Source:
<code>public boolean isAdvancedConfigurationSupported(Jid jid) throws InterruptedException, XMPPException, SmackException { DiscoverItems discoverItems = adHocCommandManager.discoverCommands(jid); for (DiscoverItems.Item item : discoverItems.getItems()) { <START> if (item.getNode().equals(ADVANCED_CONFIG_NAMESPACE)) return true; <END> } return false; }</code><technical_language>Nit: Please enclosing brackets return true;</technical_language>

Target:
public boolean isAdvancedConfigurationSupported(Jid jid) throws InterruptedException, XMPPException, SmackException { DiscoverItems discoverItems = adHocCommandManager.discoverCommands(jid); for (DiscoverItems.Item item : discoverItems.getItems()) { if (item.getNode().equals(ADVANCED_CONFIG_NAMESPACE)) { return true; } } return false; }
Source:
<code><START> protected void updateMigrationModeAvailabilityBasedOnScsiReservation() { <END> boolean isUsingScsiReservation = false; for (Disk disk : getVm().getDiskMap().values()) { if (disk instanceof LunDisk) { if (((LunDisk)disk).isUsingScsiReservation()) { isUsingScsiReservation = true; break; } } } if (isUsingScsiReservation) { getModel().getMigrationMode().setSelectedItem(null); getModel().getMigrationMode().setIsChangable(false); getModel().getMigrationMode().setChangeProhibitionReason(constants.vmUsesScsiReservation()); } }</code><technical_language>formatter</technical_language>

Target:
protected void updateMigrationModeAvailabilityBasedOnScsiReservation() { boolean isUsingScsiReservation = false; for (Disk disk : getVm().getDiskMap().values()) { if (disk instanceof LunDisk) { if (((LunDisk)disk).isUsingScsiReservation()) { isUsingScsiReservation = true; break; } } } if (isUsingScsiReservation) { getModel().getMigrationMode().setSelectedItem(MigrationSupport.PINNED_TO_HOST); getModel().getMigrationMode().setIsChangable(false); getModel().getMigrationMode().setChangeProhibitionReason(constants.vmUsesScsiReservation()); } }
Source:
<code>protected boolean canEdit(ClusterNetworkModel clusterNetworkModel) { <START> return clusterNetworkModel.isAttached() && !clusterNetworkModel.isExternal()&& <END> !(multiCluster && clusterNetworkModel.getOriginalNetworkCluster().isManagement()); }</code><technical_language>Formatting</technical_language>

Target:
protected boolean canEdit(ClusterNetworkModel clusterNetworkModel) { return clusterNetworkModel.isAttached() && !clusterNetworkModel.isExternal() && !(multiCluster && isManagementOriginally(clusterNetworkModel)); }
Source:
<code>public void run() { try { while (true) { final RecoveryInfo recoveryInfo = proxyToMaster.pullRecoveringGroups(taskHostname); LOG.log(Level.INFO, "Recovering groups: {0}", recoveryInfo.getRecoveryGroupList().toString()); if (recoveryInfo.getRecoveryGroupList().isEmpty()) { isRecoveryRunning.set(false); break; } else { final List<Future> futureList = new ArrayList<>(); for (final String recoveryGroup : recoveryInfo.getRecoveryGroupList()) { futureList.add(executorService.submit(new RecoveryRunner(recoveryGroup, checkpointManager))); } for (final Future future : futureList) { <START> future.get(); <END> } } } } catch (final AvroRemoteException | InterruptedException | ExecutionException e) { e.printStackTrace(); } }</code><technical_language>do wait</technical_language>

Target:
public void run() { try { while (true) { final RecoveryInfo recoveryInfo = proxyToMaster.pullRecoveringGroups(taskHostname); LOG.log(Level.INFO, "Recovering groups: {0}", recoveryInfo.getRecoveryGroupList().toString()); if (recoveryInfo.getRecoveryGroupList().isEmpty()) { isRecoveryRunning.set(false); break; } else { final List<Future> futureList = new ArrayList<>(); for (final String recoveryGroup : recoveryInfo.getRecoveryGroupList()) { futureList.add(executorService.submit(new SingleGroupRecoveryRunner(recoveryGroup, checkpointManager))); } for (final Future future : futureList) { future.get(); } } } } catch (final AvroRemoteException | InterruptedException | ExecutionException e) { e.printStackTrace(); } }
Source:
<code>public Object invokeService(ServiceTunnelRequest request) { <START> if (IFuture.CURRENT.get().isCancelled()) { <END> throw new CancellationException("Future is already cancelled"); } long t0 = System.nanoTime(); beforeTunnel(request); ServiceTunnelResponse response = tunnel(request); afterTunnel(t0, response); Throwable t = response.getException(); if (t != null) { RuntimeException serviceException = interceptException(t); if (serviceException instanceof PlatformException) { ((PlatformException) serviceException) .withContextInfo("remote-service.name", request.getServiceInterfaceClassName()) .withContextInfo("remote-service.operation", request.getOperation()); } StackTraceElement[] trace1 = serviceException.getStackTrace(); StackTraceElement[] trace2 = new Exception().getStackTrace(); StackTraceElement[] both = new StackTraceElement[trace1.length + trace2.length]; System.arraycopy(trace1, 0, both, 0, trace1.length); System.arraycopy(trace2, 0, both, trace1.length, trace2.length); serviceException.setStackTrace(both); throw serviceException; } BEANS.get(ServiceUtility.class).updateHolderArguments(request.getArgs(), response.getOutVars(), false); return response.getData(); }</code><technical_language>null check added here: IFuture future = IFuture.CURRENT.get(); if (future != null && future.isCancelled()) { ..</technical_language>

Target:
public Object invokeService(ServiceTunnelRequest request) { final IFuture<?> future = IFuture.CURRENT.get(); if (future != null && future.isCancelled()) { throw new CancellationException("Future is already cancelled"); } long t0 = System.nanoTime(); beforeTunnel(request); ServiceTunnelResponse response = tunnel(request); afterTunnel(t0, response); Throwable t = response.getException(); if (t != null) { RuntimeException serviceException = interceptException(t); if (serviceException instanceof PlatformException) { ((PlatformException) serviceException) .withContextInfo("remote-service.name", request.getServiceInterfaceClassName()) .withContextInfo("remote-service.operation", request.getOperation()); } StackTraceElement[] trace1 = serviceException.getStackTrace(); StackTraceElement[] trace2 = new Exception().getStackTrace(); StackTraceElement[] both = new StackTraceElement[trace1.length + trace2.length]; System.arraycopy(trace1, 0, both, 0, trace1.length); System.arraycopy(trace2, 0, both, trace1.length, trace2.length); serviceException.setStackTrace(both); throw serviceException; } BEANS.get(ServiceUtility.class).updateHolderArguments(request.getArgs(), response.getOutVars(), false); return response.getData(); }
Source:
<code>public void testBuild() throws Exception { initTestData(WORKSPACE); executeBndCmd("clean"); executeBndCmd("compile"); executeBndCmd("build"); capturedStdIO.getSystemErrContent() .contains( <START> EMPTY_JAR_MSG); <END> expectFileStatus(FileStatus.CREATED, "p/generated/p.jar"); expectFileStatus(FileStatus.CREATED, "p2/generated/p2.jar"); expectFileStatus(FileStatus.CREATED, "p3/generated/p3.jar"); }</code><technical_language>in general do assertTrue(processor.check("The JAR is empty:")); strings in parameters filtered errors warnings. If remains a string is false is returned</technical_language>

Target:
public void testBuild() throws Exception { initTestData(WORKSPACE); executeBndCmd("clean"); executeBndCmd("compile"); executeBndCmd("build"); expectNoError(false, EMPTY_JAR_MSG, WARNINGS_FRAME); expectFileStatus(FileStatus.CREATED, "p/generated/p.jar"); expectFileStatus(FileStatus.CREATED, "p2/generated/p2.jar"); expectFileStatus(FileStatus.CREATED, "p3/generated/p3.jar"); }
Source:
<code>static void addCourseToUser(final DB database, final String userId, final String courseId) { LOG.info("The users Id {}", userId); final DBCollection users = database.getCollection(USER_COLLECTION); final BasicDBObject query = new BasicDBObject("$addToSet", new BasicDBObject(COURSE_LIST, courseId)); final DBRef myDbRef = new DBRef(database, USER_COLLECTION, userId); final DBObject corsor = myDbRef.fetch(); <START> LOG.info("coros {}", corsor); <END> LOG.info("query {}", query); LOG.info("courseId {}", courseId); users.update(corsor, query); }</code><technical_language>do need log cursor anymore</technical_language>

Target:
static void addCourseToUser(final DB database, final String userId, final String courseId) { LOG.debug("The users Id {}", userId); final DBCollection users = database.getCollection(USER_COLLECTION); final BasicDBObject query = new BasicDBObject("$addToSet", new BasicDBObject(COURSE_LIST, courseId)); final DBRef myDbRef = new DBRef(database, USER_COLLECTION, userId); final DBObject corsor = myDbRef.fetch(); LOG.info("query {}", query); LOG.info("courseId {}", courseId); users.update(corsor, query); }
Source:
<code>public String explain(String impliedTableName) { switch(getExpressionType()) { case OPERATOR_IS_NULL: <START> return "(" + m_left.explain(impliedTableName) + " IS NULL)"; <END> case OPERATOR_NOT: return "(NOT " + m_left.explain(impliedTableName) + ")"; case OPERATOR_CAST: return "(CAST (" + m_left.explain(impliedTableName) + " AS " + m_valueType.toSQLString() + "))"; case OPERATOR_EXISTS: return "(EXISTS " + m_left.explain(impliedTableName) + ")"; case OPERATOR_CASE_WHEN: return "(CASE WHEN " + m_left.explain(impliedTableName) + " THEN " + m_right.m_left.explain(impliedTableName) + " ELSE " + m_right.m_right.explain(impliedTableName) + " END)"; case OPERATOR_UNARY_MINUS: return "-" + m_left.explain(impliedTableName); default: return "(" + m_left.explain(impliedTableName) + " " + getExpressionType().symbol() + " " + m_right.explain(impliedTableName) + ")"; } }</code><technical_language>a StringBuilder construct result string pass m_left.explain() instead of constructing concatenating multiple strings</technical_language>

Target:
public String explain(String impliedTableName) { final String explainLeftTableName = m_left.explain(impliedTableName); switch(getExpressionType()) { case OPERATOR_IS_NULL: return String.format("(%s IS NULL)", explainLeftTableName); case OPERATOR_NOT: return String.format("(NOT %s)", explainLeftTableName); case OPERATOR_CAST: return String.format("(CAST (%s AS %s))", explainLeftTableName, m_valueType.toSQLString()); case OPERATOR_EXISTS: return String.format("(EXISTS %s)", explainLeftTableName); case OPERATOR_CASE_WHEN: return String.format("(CASE WHEN %s THEN %s ELSE %s END)", explainLeftTableName, m_right.m_left.explain(impliedTableName), m_right.m_right.explain(impliedTableName)); case OPERATOR_UNARY_MINUS: return String.format("-%s", explainLeftTableName); default: return String.format("(%s %s %s)", explainLeftTableName, getExpressionType().symbol(), m_right.explain(impliedTableName)); } }
Source:
<code>public static List<EObject> getNonUnionSupersetReferences(EReference reference) { <START> return Lists.newArrayList(Iterables.filter(getSupersetReferences(reference), <END> new Predicate<EObject>() { public boolean apply(EObject input) { return input instanceof EReference && !Iterables.any(((EReference)input).getEAnnotations(), new Predicate<EAnnotation>() { public boolean apply(EAnnotation annotation) { return annotation.getSource().equals( UMLUtilForCompare.getAnnotationUnionID()); } }); } })); }</code><technical_language>more readable (maybe creating private static class for predicates)</technical_language>

Target:
public static List<EObject> getNonUnionSupersetReferences(EReference reference) { return Lists.newArrayList(Iterables.filter(getSupersetReferences(reference), new KeepOnlyNonUnionEReferences())); }
Source:
<code>public void administratorTabsTest(User user) { homePage = new HomePage(driver); userInfoPage = homePage.logIn(user.getLogin(), user.getPassword()); loggingAssert.assertTrue(userInfoPage.getElementText(UserInfoPageLocators.USER_ROLE_LABEL.getBy()) <START> .equals(user.getRoleName()), "User role assert"); <END> loggingAssert.assertTrue(userInfoPage.isElementDisplayed(CommonLocators.USER_INFO_TAB.getBy()), "User Info tab display assert"); loggingAssert.assertTrue(userInfoPage.isElementDisplayed(CommonLocators.ADMINISTRATION_TAB.getBy()), "Administration tab display assert"); loggingAssert.assertTrue(userInfoPage.getElementText(CommonLocators.ACTIVE_TAB.getBy()) .equals(userInfoPage.getElementText(CommonLocators.USER_INFO_TAB.getBy())), "Default tab assert"); administrationPage = userInfoPage.clickAdministrationTab(); loggingAssert.assertTrue(administrationPage.getElementText(CommonLocators.ACTIVE_TAB.getBy()) .equals(administrationPage.getElementText(CommonLocators.ADMINISTRATION_TAB.getBy())), "Switch to Administration tab assert"); loggingAssert.assertTrue(administrationPage.isElementDisplayed(AdministrationPageLocators.CREATE_NEW_USER_LINK.getBy()), "Create new user link display assert"); userInfoPage = administrationPage.clickUserInfoTab(); loggingAssert.assertTrue(userInfoPage.getElementText(CommonLocators.ACTIVE_TAB.getBy()) .equals(userInfoPage.getElementText(CommonLocators.USER_INFO_TAB.getBy())), "Switch to User Info tab assert"); }</code><technical_language>Assert message useless, redo</technical_language>

Target:
public void administratorTabsTest(User user) { homePage = new HomePage(driver); userInfoPage = homePage.logIn(user.getLogin(), user.getPassword()); loggingAssert.assertTrue(userInfoPage.getElementText(UserInfoPageLocators.USER_ROLE_LABEL) .equals(user.getRoleName()), "User roles match"); loggingAssert.assertTrue(userInfoPage.isElementDisplayed(CommonLocators.USER_INFO_TAB), "User Info tab displayed"); loggingAssert.assertTrue(userInfoPage.isElementDisplayed(CommonLocators.ADMINISTRATION_TAB), "Administration tab displayed"); loggingAssert.assertTrue(userInfoPage.getElementText(CommonLocators.ACTIVE_TAB) .equals(userInfoPage.getElementText(CommonLocators.USER_INFO_TAB)), "User info tab is the default tab"); administrationPage = userInfoPage.clickAdministrationTab(); loggingAssert.assertTrue(administrationPage.getElementText(CommonLocators.ACTIVE_TAB) .equals(administrationPage.getElementText(CommonLocators.ADMINISTRATION_TAB)), "Switched to Administration tab"); loggingAssert.assertTrue(administrationPage.isElementDisplayed(AdministrationPageLocators.CREATE_NEW_USER_LINK), "Create new user link displayed"); userInfoPage = administrationPage.clickUserInfoTab(); loggingAssert.assertTrue(userInfoPage.getElementText(CommonLocators.ACTIVE_TAB) .equals(userInfoPage.getElementText(CommonLocators.USER_INFO_TAB)), "Switched to User Info tab"); }
Source:
<code>private void plotRatingDistributions(List<RatingStat> ratingStats, Player player) { XYChart.Series<String, Integer> series = new XYChart.Series<>(); series.setName(i18n.get("ranked1v1.players", LeaderboardService.MINIMUM_GAMES_PLAYED_TO_BE_SHOWN )); series.getData().addAll(ratingStats.stream() <START> .sorted(Comparator.comparingInt(RatingStat::getRating).reversed()) <END> .map(item -> { int rating = item.getRating(); XYChart.Data<String, Integer> data = new XYChart.Data<>(i18n.number(rating), item.getCount()); int currentPlayerRating = RatingUtil.getLeaderboardRating(player); if (rating == (currentPlayerRating / 100) * 100) { data.nodeProperty().addListener((observable, oldValue, newValue) -> newValue.pseudoClassStateChanged(NOTIFICATION_HIGHLIGHTED_PSEUDO_CLASS, true)); } return data; }) .collect(Collectors.toList())); Platform.runLater(() -> ratingDistributionChart.getData().setAll(series)); }</code><technical_language>reversed() numbers left high numbers right</technical_language>

Target:
private void plotRatingDistributions(List<RatingStat> ratingStats, Player player) { XYChart.Series<String, Integer> series = new XYChart.Series<>(); series.setName(i18n.get("ranked1v1.players", LeaderboardService.MINIMUM_GAMES_PLAYED_TO_BE_SHOWN)); int currentPlayerRating = RatingUtil.roundRatingToNextLowest100(RatingUtil.getLeaderboardRating(player)); series.getData().addAll(ratingStats.stream() .sorted(Comparator.comparingInt(RatingStat::getRating)) .map(item -> { int rating = item.getRating(); XYChart.Data<String, Integer> data = new XYChart.Data<>(i18n.number(rating), item.getCountWithEnoughGamesPlayed()); if (rating == currentPlayerRating) { data.nodeProperty().addListener((observable, oldValue, newValue) -> { newValue.pseudoClassStateChanged(NOTIFICATION_HIGHLIGHTED_PSEUDO_CLASS, true); addNodeOnTopOfBar(data, youLabel); }); } return data; }) .collect(Collectors.toList())); Platform.runLater(() -> ratingDistributionChart.getData().setAll(series)); }
Source:
<code>protected boolean canDoAction() { boolean retValue = super.canDoAction(); if (retValue) { for (DiskImage dit : getVmTemplate().getDiskTemplateMap().values()) { retValue = ImagesHandler.checkImageConfiguration(destStorages.get(diskInfoDestinationMap.get(dit.getId()).getStorageIds().get(0)) .getStorageStaticData(), diskInfoDestinationMap.get(dit.getId()), getReturnValue().getCanDoActionMessages()); if (!retValue) { break; } } if (getParameters().getVm().isUseLatestVersion()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CANNOT_USE_LATEST_WITH_CLONE); } } <START> if (!VmHandler.isGraphicsAndDisplaySupported(getParameters().getVmStaticData().getOsId(), <END> getEntityGraphicsTypes(getVmTemplateId()), getParameters().getVm().getDefaultDisplayType(), getReturnValue().getCanDoActionMessages(), getVdsGroup().getcompatibility_version())) { return false; } return retValue; }</code><technical_language>in addVmCommand? this command is responsible for cloning</technical_language>

Target:
protected boolean canDoAction() { boolean retValue = super.canDoAction(); if (retValue) { for (DiskImage dit : getVmTemplate().getDiskTemplateMap().values()) { retValue = ImagesHandler.checkImageConfiguration(destStorages.get(diskInfoDestinationMap.get(dit.getId()).getStorageIds().get(0)) .getStorageStaticData(), diskInfoDestinationMap.get(dit.getId()), getReturnValue().getCanDoActionMessages()); if (!retValue) { break; } } if (getParameters().getVm().isUseLatestVersion()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CANNOT_USE_LATEST_WITH_CLONE); } } return retValue; }
Source:
<code>public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mRvAllergens = (RecyclerView) view.findViewById(R.id.allergens_recycle); mEmptyMessageView = (LinearLayout) view.findViewById(R.id.emptyAllergensView); productRepository = ProductRepository.getInstance(); mDataObserver = new DataObserver(); productRepository.getAllergensByEnabledAndLanguageCode(true, Locale.getDefault().getLanguage()) <START> .subscribeOn(Schedulers.io()) <END> .observeOn(AndroidSchedulers.mainThread()) .subscribe(allergens -> { mAllergensEnabled = allergens; mAdapter = new AllergensAdapter(productRepository, mAllergensEnabled, getActivity()); mRvAllergens.setAdapter(mAdapter); mRvAllergens.setLayoutManager(new LinearLayoutManager(view.getContext())); mRvAllergens.setHasFixedSize(true); mAdapter.registerAdapterDataObserver(mDataObserver); mDataObserver.onChanged(); }, Throwable::printStackTrace); productRepository.getAllergensByLanguageCode(Locale.getDefault().getLanguage()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(allergens -> { mAllergensFromDao = allergens; }, Throwable::printStackTrace); mView = view; mRvAllergens = mView.findViewById(R.id.allergens_recycle); mAdapter = new AllergensAdapter(productRepository, mAllergensEnabled, getActivity()); mRvAllergens.setAdapter(mAdapter); mRvAllergens.setLayoutManager(new LinearLayoutManager(mView.getContext())); mRvAllergens.setHasFixedSize(true); }</code><technical_language>mRvAllergens mAdapater initialized for some reason. clean code here</technical_language>

Target:
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mRvAllergens = (RecyclerView) view.findViewById(R.id.allergens_recycle); mEmptyMessageView = (LinearLayout) view.findViewById(R.id.emptyAllergensView); productRepository = ProductRepository.getInstance(); mDataObserver = new DataObserver(); productRepository.getAllergensByEnabledAndLanguageCode(true, Locale.getDefault().getLanguage()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(allergens -> { mAllergensEnabled = allergens; mAdapter = new AllergensAdapter(productRepository, mAllergensEnabled, getActivity()); mRvAllergens.setAdapter(mAdapter); mRvAllergens.setLayoutManager(new LinearLayoutManager(view.getContext())); mRvAllergens.setHasFixedSize(true); mAdapter.registerAdapterDataObserver(mDataObserver); mDataObserver.onChanged(); }, Throwable::printStackTrace); productRepository.getAllergensByLanguageCode(Locale.getDefault().getLanguage()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(allergens -> { mAllergensFromDao = allergens; }, Throwable::printStackTrace); mView = view; mSettings = getActivity().getSharedPreferences("prefs", 0); }
Source:
<code>protected TableViewer createTable(Composite tableContainer) { Table table = new Table(tableContainer, SWT.BORDER | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL); table.setLinesVisible(true); table.setHeaderVisible(true); this.viewer = new TableViewerBuilder(table, tableContainer).contentProvider(new ArrayContentProvider()) .<Label>column(new DelegatingStyledCellLabelProvider(new LabelTextProvider() { @Override public String getValue(Label label) { return label.getName(); } <START> })).name("Key").align(SWT.LEFT).weight(2).minWidth(100).buildColumn() <END> .<Label>column(new DelegatingStyledCellLabelProvider(new LabelTextProvider() { @Override public String getValue(Label label) { return label.getValue(); } })).name("Value").align(SWT.LEFT).weight(2).minWidth(100).buildColumn().buildViewer(); viewer.addDoubleClickListener( e -> editLabel((Label) ((IStructuredSelection) e.getSelection()).getFirstElement())); viewer.setComparator(new ViewerComparator() { @Override public int compare(Viewer viewer, Object e1, Object e2) { Label first = (Label) e1; Label other = (Label) e2; return first.getName().compareTo(other.getName()); } }); return viewer; }</code><technical_language>LABEL_KEY constant here, added</technical_language>

Target:
protected TableViewer createTable(Composite tableContainer) { Table table = new Table(tableContainer, SWT.BORDER | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL); table.setLinesVisible(true); table.setHeaderVisible(true); this.viewer = new TableViewerBuilder(table, tableContainer).contentProvider(new ArrayContentProvider()) .<Label>column(new DelegatingStyledCellLabelProvider(new LabelTextProvider() { @Override public String getValue(Label label) { return label.getName(); } })).name(LABEL_KEY).align(SWT.LEFT).weight(2).minWidth(100).buildColumn() .<Label>column(new DelegatingStyledCellLabelProvider(new LabelTextProvider() { @Override public String getValue(Label label) { return label.getValue(); } })).name("Value").align(SWT.LEFT).weight(2).minWidth(100).buildColumn().buildViewer(); viewer.addDoubleClickListener( e -> editLabel((Label) ((IStructuredSelection) e.getSelection()).getFirstElement())); viewer.setComparator(new ViewerComparator() { @Override public int compare(Viewer viewer, Object e1, Object e2) { Label first = (Label) e1; Label other = (Label) e2; return first.getName().compareTo(other.getName()); } }); return viewer; }
Source:
<code>public static IconvResult decode(long pointer, ByteBuffer in, CharBuffer out) { boolean isInDirect = in.isDirect(); boolean isOutDirect = out.isDirect(); ByteBuffer bufferInData = copyByteBufferData(in); CharBuffer bufferOutData = copyCharBufferData(out); int res = -1; IconvResult result = new IconvResult(); if (isInDirect && isOutDirect) { res = decodeNativeBuffer(pointer, in, out, result, in.position(), in.limit(), out.position(), out.limit()); } else if (!isInDirect && !isOutDirect) { res = decodeNativeArray(pointer, bufferInData.array(), bufferOutData.array(), result, in.position(), in.limit(), out.position(), out.limit()); } else if(isInDirect && !isOutDirect) { res = decodeHybridBufferArray(pointer, in, bufferOutData.array(), result, in.position(), in.limit(), out.position(), out.limit()); } else { res = decodeHybridArrayBuffer(pointer, bufferInData.array(), out, result, in.position(), in.limit(), out.position(), out.limit()); } ConversionResult conversionState = ConversionResult.getResult(res); result.setResultCode(conversionState); in.position(in.position() + result.getBytesReadFromSource()); out.position(out.position() + result.getBytesWrittenToDestination() / 2); <START> out.limit(out.position()); <END> return result; }</code><technical_language>touch limit</technical_language>

Target:
public static IconvResult decode(long pointer, ByteBuffer in, CharBuffer out) { boolean isInDirect = in.isDirect(); boolean isOutDirect = out.isDirect(); ByteBuffer bufferInData = copyByteBufferData(in); CharBuffer bufferOutData = copyCharBufferData(out); int res = -1; IconvResult result = new IconvResult(); if (isInDirect && isOutDirect) { res = decodeNativeBuffer(pointer, in, out, result, in.position(), in.limit(), out.position(), out.limit()); } else if (!isInDirect && !isOutDirect) { res = decodeNativeArray(pointer, bufferInData.array(), bufferOutData.array(), result, bufferInData.position(), bufferInData.limit(), bufferOutData.position(), bufferOutData.limit()); } else if(isInDirect && !isOutDirect) { res = decodeHybridBufferArray(pointer, in, bufferOutData.array(), result, in.position(), in.limit(), bufferOutData.position(), bufferOutData.limit()); } else { res = decodeHybridArrayBuffer(pointer, bufferInData.array(), out, result, bufferInData.position(), bufferInData.limit(), out.position(), out.limit()); } ConversionResult conversionState = ConversionResult.getResult(res); result.setResultCode(conversionState); in.position(in.position() + result.getBytesReadFromSource()); if (out != bufferOutData) { bufferOutData.limit(result.getBytesWrittenToDestination()/2); out.put(bufferOutData); } else { out.position(out.position() + result.getBytesWrittenToDestination() / 2); } return result; }
Source:
<code>private int removePossessives(char[] s, int len) { if (len > 5) { <START> if (StemmerUtil.endsWith(s, len, "ov")) <END> return len - 2; if (StemmerUtil.endsWith(s, len, "in")) return palatalize(s, len - 1); } return len; }</code><technical_language>nitpick: curly</technical_language>

Target:
private int removePossessives(char[] s, int len) { if (len > 5) { if (endsWith(s, len, "ov")) { return len - 2; } if (endsWith(s, len, "in")) { return palatalize(s, len - 1); } } return len; }
Source:
<code>public void initialize() { inst = NetworkTableInstance.getDefault(); table = inst.getTable("table"); entry = table.getEntry("entry"); entry.setDefaultDouble(DEFAULT_ENTRY); try { table.saveEntries(SAVE_FILE); entries = table.loadEntries(SAVE_FILE); } catch (PersistentException e) { updateStatus(CHECK_NAME, SystemStatus.FAIL, e); } <START> if (entries[0] != Double.toString(DEFAULT_ENTRY)) { END> updateStatus(CHECK_NAME, SystemStatus.FAIL, new Exception("LOADED ARRAY NOT EQUAL TO SAVED ARRAY")); } }</code><technical_language>done this</technical_language>

Target:
public void initialize() { inst = NetworkTableInstance.getDefault(); table = inst.getTable("table"); entry = table.getEntry("entry"); entry.setDefaultDouble(DEFAULT_ENTRY); try { table.saveEntries(SAVE_FILE); entries = table.loadEntries(SAVE_FILE); } catch (PersistentException e) { updateStatusFail(CHECK_NAME, e); } if (entries[0] != Double.toString(DEFAULT_ENTRY)) { updateStatusFail(CHECK_NAME, new Exception("LOADED ARRAY NOT EQUAL TO SAVED ARRAY")); } }
Source:
<code>protected boolean isHotPlugSupported() { <START> if (FeatureSupported.hotPlug(getVds().getVdsGroupCompatibilityVersion())) { <END> return true; } return failCanDoAction(VdcBllMessages.HOT_PLUG_IS_NOT_SUPPORTED); }</code><technical_language>check is needed anymore osrepository reflects support architecture version</technical_language>

Target:
protected boolean isHotPlugSupported() { if (FeatureSupported.hotPlug(getVm().getVdsGroupCompatibilityVersion())) { return true; } return failCanDoAction(VdcBllMessages.HOT_PLUG_IS_NOT_SUPPORTED); }
Source:
<code>public static synchronized void updatePreferredIP(InetAddressAndPort ep, InetAddressAndPort preferred_ip) { if (getPreferredIP(ep) == preferred_ip) return; String req = "INSERT INTO system.%s (peer, preferred_ip) VALUES (?, ?)"; executeInternal(String.format(req, LEGACY_PEERS), ep.address, preferred_ip.address); <START> forceBlockingFlush(LEGACY_PEERS); <END> req = "INSERT INTO system.%s (peer, peer_port, preferred_ip, preferred_port) VALUES (?, ?, ?, ?)"; executeInternal(String.format(req, PEERS_V2), ep.address, ep.port, preferred_ip.address, preferred_ip.port); forceBlockingFlush(PEERS_V2); }</code><technical_language>Well... do this in a lot of places. Some called indirectly. I add a bit of complexity solve a problem have. is this issue this patch increases number of places do this is out of scope? implemented, number of places I applying this due indirection disappointing</technical_language>

Target:
public static synchronized void updatePreferredIP(InetAddressAndPort ep, InetAddressAndPort preferred_ip) { if (getPreferredIP(ep) == preferred_ip) return; String req = "INSERT INTO system.%s (peer, preferred_ip) VALUES (?, ?)"; executeInternal(String.format(req, LEGACY_PEERS), ep.address, preferred_ip.address); req = "INSERT INTO system.%s (peer, peer_port, preferred_ip, preferred_port) VALUES (?, ?, ?, ?)"; executeInternal(String.format(req, PEERS_V2), ep.address, ep.port, preferred_ip.address, preferred_ip.port); forceBlockingFlush(LEGACY_PEERS, PEERS_V2); }
Source:
<code>private void createConflictDetectorTab(TabFolder tabFolder) { IItemRegistry<IConflictDetector> conflictDetectorDescriptorRegistry = EMFCompareRCPPlugin .getDefault().getConflictDetectorDescriptorRegistry(); Composite tabComposite = createTabSkeleton(tabFolder, EMFCompareRCPUIMessages .getString("EnginesPreferencePage.CONFLICT_DETECTOR_TAB_LABEL"), EMFCompareRCPUIMessages.getString("EnginesPreferencePage.CONFLICT_DETECTOR_INTRO_TEXT")); IItemDescriptor<IConflictDetector> defaultEngine = ItemUtil.getDefaultItemDescriptor( conflictDetectorDescriptorRegistry, EMFComparePreferences.CONFLICTS_DETECTOR, EMFCompareRCPPlugin.getDefault().getEMFComparePreferences()); InteractiveUIBuilder<IConflictDetector> uiBuilder = new InteractiveUIBuilder<IConflictDetector>( tabComposite, conflictDetectorDescriptorRegistry); uiBuilder.setSimple(true).setDefaultCheck(Collections.singleton(defaultEngine)).setDefaultSelection( <START> defaultEngine).setHoldingData(conflictsDetectorData); <END> interactiveUis.put(EMFComparePreferences.CONFLICTS_DETECTOR, uiBuilder.build()); }</code><technical_language>This next chunks of changed code exact lines... a single difference preference key. this extracted a createEngineUIBuilder(IItemRegistry<T> registry, String enginePreferenceKey, Preferences preferences)</technical_language>

Target:
private void createConflictDetectorTab(TabFolder tabFolder) { IItemRegistry<IConflictDetector> conflictDetectorDescriptorRegistry = EMFCompareRCPPlugin .getDefault().getConflictDetectorDescriptorRegistry(); Composite tabComposite = createTabSkeleton(tabFolder, EMFCompareRCPUIMessages .getString("EnginesPreferencePage.CONFLICT_DETECTOR_TAB_LABEL"), EMFCompareRCPUIMessages.getString("EnginesPreferencePage.CONFLICT_DETECTOR_INTRO_TEXT")); InteractiveUIContent interactiveContent = createEngineUIBuilder(conflictDetectorDescriptorRegistry, EMFComparePreferences.CONFLICTS_DETECTOR, EMFCompareRCPPlugin.getDefault() .getEMFComparePreferences(), tabComposite, conflictsDetectorData); interactiveUis.put(EMFComparePreferences.CONFLICTS_DETECTOR, interactiveContent); }
Source:
<code>private void shuffleDataset() { Random random = new Random(); int iterator, shufflePosition; <START> Object temp; <END> for(iterator = dataset.length - 1; iterator > 0; iterator--) { shufflePosition = random.nextInt(iterator); temp = dataset[iterator]; dataset[iterator] = dataset[shufflePosition]; dataset[shufflePosition] = temp; } }</code><technical_language>This declared scope, for loop</technical_language>

Target:
private void shuffleDataset() { Random random = new Random(); for(int shufflePosition = 0, iterator = dataset.length - 1; iterator > 0; iterator--) { shufflePosition = random.nextInt(iterator); Object temp = dataset[iterator]; dataset[iterator] = dataset[shufflePosition]; dataset[shufflePosition] = temp; } }
Source:
<code>public Object convert(Object rassInput) { List<RassXMLAwardPiCoPiEntry> rassAwardPiCoPiEntries = (List<RassXMLAwardPiCoPiEntry>) rassInput; List<ProposalProjectDirector> projectDirectors = new ArrayList<>(); if (rassAwardPiCoPiEntries != null && rassAwardPiCoPiEntries.size() > 0) { for (RassXMLAwardPiCoPiEntry rassAwardPiCoPi : rassAwardPiCoPiEntries) { ProposalProjectDirector projectDirector = new ProposalProjectDirector(); <START> String principalId = SpringContext.getBean(PersonService.class) <END> .getPersonByPrincipalName(rassAwardPiCoPi.getProjectDirectorPrincipalName()).getPrincipalId(); projectDirector.setPrincipalId(principalId); projectDirector.setProposalPrimaryProjectDirectorIndicator(rassAwardPiCoPi.getPrimary()); projectDirectors.add(projectDirector); } } return projectDirectors; }</code><technical_language>this springcontext call moved a service getter class, easily mocked if/when need write unit tests for this</technical_language>

Target:
public Object convert(Object rassInput) { List<RassXMLAwardPiCoPiEntry> rassAwardPiCoPiEntries = (List<RassXMLAwardPiCoPiEntry>) rassInput; List<ProposalProjectDirector> projectDirectors = new ArrayList<>(); if (rassAwardPiCoPiEntries != null && rassAwardPiCoPiEntries.size() > 0) { for (RassXMLAwardPiCoPiEntry rassAwardPiCoPi : rassAwardPiCoPiEntries) { ProposalProjectDirector projectDirector = new ProposalProjectDirector(); String principalId = getPersonService() .getPersonByPrincipalName(rassAwardPiCoPi.getProjectDirectorPrincipalName()).getPrincipalId(); projectDirector.setPrincipalId(principalId); projectDirector.setProposalPrimaryProjectDirectorIndicator(rassAwardPiCoPi.getPrimary()); projectDirectors.add(projectDirector); } } return projectDirectors; }
Source:
<code>public JUnitRule silent() { <START> return new JUnitRule(logger, true); <END> }</code><technical_language>constructor strictness arg</technical_language>

Target:
public MockitoRule silent() { return new JUnitRule(logger, Strictness.LENIENT); }
Source:
<code>public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws java.io.IOException, javax.ws.rs.WebApplicationException { Jsonb jsonb = getJsonb(type); try { return jsonb.fromJson(entityStream, genericType); } catch (Throwable e) { <START> LogMessages.LOGGER.debugf(Messages.MESSAGES.jsonBDeserializationError(e.toString())); <END> throw new ProcessingException(Messages.MESSAGES.jsonBDeserializationError("")); } }</code><technical_language>@rsearls like: if (LogMessages.LOGGER.isDebugEnabled()) { LogMessages.LOGGER.debugf(Messages.MESSAGES.jsonBDeserializationError(e.toString())); } avoid generating stacktrace string needed</technical_language>

Target:
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws java.io.IOException, javax.ws.rs.WebApplicationException { Jsonb jsonb = getJsonb(type); try { return jsonb.fromJson(entityStream, genericType); } catch (Throwable e) { if (LogMessages.LOGGER.isDebugEnabled()) { LogMessages.LOGGER.debugf(Messages.MESSAGES.jsonBDeserializationError(e.toString())); } throw new ProcessingException(Messages.MESSAGES.jsonBDeserializationError("")); } }
Source:
<code>private DataSerializable readInternal(ObjectDataInput in, Class aClass) throws IOException { setInputVersion(in, version); DataSerializable ds = null; if (null != aClass) { try { <START> try { <END> ds = (DataSerializable) aClass.newInstance(); } catch (InstantiationException e) { throw clarifyInstantiationException(aClass, e); } } catch (Exception e) { throw new HazelcastSerializationException("Requested class " + aClass + " could not be instantiated.", e); } } final byte header = in.readByte(); int id = 0; int factoryId = 0; String className = null; try { if (isFlagSet(header, IDS_FLAG)) { factoryId = in.readInt(); final DataSerializableFactory dsf = factories.get(factoryId); if (dsf == null) { throw new HazelcastSerializationException("No DataSerializerFactory registered for namespace: " + factoryId); } id = in.readInt(); if (null == aClass) { ds = dsf.create(id); if (ds == null) { throw new HazelcastSerializationException(dsf + " is not be able to create an instance for ID: " + id + " on factory ID: " + factoryId); } } } else { className = in.readUTF(); if (null == aClass) { try { ds = ClassLoaderUtil.newInstance(in.getClassLoader(), className); } catch (NoSuchMethodException e) { throw clarifyNoSuchMethodException(in.getClassLoader(), className, e); } } } if (isFlagSet(header, EE_FLAG)) { in.readByte(); in.readByte(); } ds.readData(in); return ds; } catch (Exception e) { throw rethrowReadException(id, factoryId, className, e); } }</code><technical_language>crazy catching exception, mutating recatching it. code more complex due nesting. I move catching main catchblock of method deal there</technical_language>

Target:
private DataSerializable readInternal(ObjectDataInput in, Class aClass) throws IOException { setInputVersion(in, version); DataSerializable ds = null; if (null != aClass) { try { ds = (DataSerializable) aClass.newInstance(); } catch (Exception e) { e = tryClarifyInstantiationException(aClass, e); throw new HazelcastSerializationException("Requested class " + aClass + " could not be instantiated.", e); } } final byte header = in.readByte(); int id = 0; int factoryId = 0; String className = null; try { if (isFlagSet(header, IDS_FLAG)) { factoryId = in.readInt(); final DataSerializableFactory dsf = factories.get(factoryId); if (dsf == null) { throw new HazelcastSerializationException("No DataSerializerFactory registered for namespace: " + factoryId); } id = in.readInt(); if (null == aClass) { ds = dsf.create(id); if (ds == null) { throw new HazelcastSerializationException(dsf + " is not be able to create an instance for ID: " + id + " on factory ID: " + factoryId); } } } else { className = in.readUTF(); if (null == aClass) { ds = ClassLoaderUtil.newInstance(in.getClassLoader(), className); } } if (isFlagSet(header, EE_FLAG)) { in.readByte(); in.readByte(); } ds.readData(in); return ds; } catch (Exception e) { e = tryClarifyNoSuchMethodException(in.getClassLoader(), className, e); throw rethrowReadException(id, factoryId, className, e); } }
Source:
<code>private static <T> Object toObject( T value, Function<T,Object>... converters) { return Stream.of( converters) .map( converter -> converter.apply( value)) <START> .filter( object -> object != null) <END> .findFirst() .orElse( null); }</code><technical_language>written as: .filter(Objects::nonNull). is better, FYI</technical_language>

Target:
private static <T> Object toObject( T value, Function<T,Object>... converters) { return Stream.of( converters) .map( converter -> converter.apply( value)) .filter( Objects::nonNull) .findFirst() .orElse( null); }
Source:
<code>public static void getLoad(DSFSessionState sessionState, final IDMContext context, final DSFDebugModelListener listener, <START> final Object arg, <END> final RequestMonitor rm) { IGDBHardwareAndOS2 hwService = sessionState.getService(IGDBHardwareAndOS2.class); if (hwService == null) { return; } hwService.getLoadInfo(context, new ImmediateDataRequestMonitor<ILoadInfo>(rm) { @Override protected void handleSuccess() { ILoadInfo loadInfo = getData(); listener.getLoadDone(context, loadInfo, arg); rm.done(); } } ); }</code><technical_language>RM listener strange</technical_language>

Target:
public static void getLoad(DSFSessionState sessionState, final IDMContext context, final DSFDebugModelListener listener, final Object arg, final RequestMonitor rm) { IGDBHardwareAndOS2 hwService = sessionState.getService(IGDBHardwareAndOS2.class); if (hwService == null) { listener.getLoadDone(context, null, arg); rm.done(); return; } hwService.getLoadInfo(context, new ImmediateDataRequestMonitor<ILoadInfo>(rm) { @Override protected void handleCompleted() { listener.getLoadDone(context, getData(), arg); rm.done(); } } ); }
Source:
<code>void unlockSubtree(final String path, final long ignoreStoInodeId) throws IOException { <START> boolean failed = true; <END> try{ unlockSubtreeInternal(path, ignoreStoInodeId); }catch(Exception e ){ setAsyncLockRemoval(path); throw e; } }</code><technical_language>This boolean used</technical_language>

Target:
void unlockSubtree(final String path, final long ignoreStoInodeId) throws IOException { try{ unlockSubtreeInternal(path, ignoreStoInodeId); }catch(Exception e ){ setAsyncLockRemoval(path); throw e; } }
Source:
<code>public void wrapVoidNoReindex (final VoidDelegate delegate) { final ThreadContext threadContext = <START> UtilMethods.get(INSTANCE.getContext(), ()->new ThreadContext()); <END> boolean reindex = threadContext.isReindex(); try { threadContext.setReindex(false); this.setContext(threadContext); delegate.execute(); } catch(Exception e) { throw new DotRuntimeException(e); } finally { threadContext.setReindex(reindex); } }</code><technical_language>create a method called getOrCreateContext()</technical_language>

Target:
public static void wrapVoidNoReindex (final VoidDelegate delegate) { final ThreadContext threadContext = getOrCreateContext(); final boolean reindex = threadContext.isReindex(); try { threadContext.setReindex(false); delegate.execute(); } catch(Throwable e) { throw new DotRuntimeException(e); } finally { threadContext.setReindex(reindex); } }
Source:
<code>public List<String> getNames() { <START> return List.of(SUBMERGE_SUBS_VS_AIR_ONLY); <END> }</code><technical_language>If return 0 1 element, Optional<String> a return API? In case confusion more element clear zero one</technical_language>

Target:
public List<String> getNames() { return valid() ? List.of(SUBMERGE_SUBS_VS_AIR_ONLY) : List.of(); }
Source:
<code>public Map<String, LocalFileIngestPlugin<?>> getDefaultLocalIngestPlugins() { final Map<String, LocalFileIngestPlugin<?>> retVal = new HashMap<>(getPluginProviderRegistry().size()); for (final Entry<String, IngestFormatPluginProviderSpi<?, ?>> e : getPluginProviderRegistry().entrySet()) { retVal.put( e.getKey(), e.getValue().createLocalFileIngestPlugin(e.getValue().createOptionsInstances())); } return retVal; <START> } <END></code><technical_language>This a bit cleaner Java8 streams: return getPluginProviderRegistry().entrySet().stream().collect( Collectors.toMap( Entry::getKey, e -> e.getValue().createLocalFileIngestPlugin(e.getValue().createOptionsInstances())));</technical_language>

Target:
public Map<String, LocalFileIngestPlugin<?>> getDefaultLocalIngestPlugins() { return getPluginProviderRegistry().entrySet().stream().collect( Collectors.toMap( Entry::getKey, e -> e.getValue().createLocalFileIngestPlugin(e.getValue().createOptionsInstances()))); }
Source:
<code>Optional<MemorySegment> getUnconsumedSegment() throws IOException { final int position = lengthBuffer.position(); if (position > 0) { MemorySegment segment = MemorySegmentFactory.allocateUnpooledSegment(position); lengthBuffer.position(0); segment.put(0, lengthBuffer, position); return Optional.of(segment); } if (recordLength > THRESHOLD_FOR_SPILLING) { throw new UnsupportedOperationException("Unaligned checkpoint currently do not support spilled " + "records."); } else if (recordLength != -1) { int leftOverSize = leftOverData != null ? leftOverLimit - leftOverStart : 0; <START> int unconsumedSize = Integer.BYTES + accumulatedRecordBytes + leftOverSize; <END> DataOutputSerializer serializer = new DataOutputSerializer(unconsumedSize); serializer.writeInt(recordLength); serializer.write(buffer, 0, accumulatedRecordBytes); if (leftOverSize > 0) { serializer.write(leftOverData, leftOverStart, leftOverSize); } MemorySegment segment = MemorySegmentFactory.allocateUnpooledSegment(unconsumedSize); segment.put(0, serializer.getSharedBuffer(), 0, segment.size()); return Optional.of(segment); } return Optional.empty(); }</code><technical_language>Thanks for finding this bug! I root state inconsistency {leftOverLimit, leftOverStart} leftOverData. #clear() reset leftOverData null, reset derived {leftOverLimit, leftOverStart} leftOverData. check condition leftOverData here. Another option is reset {leftOverLimit, leftOverStart} #clear() consistency</technical_language>

Target:
Optional<MemorySegment> getUnconsumedSegment() throws IOException { final int position = lengthBuffer.position(); if (position > 0) { MemorySegment segment = MemorySegmentFactory.allocateUnpooledSegment(position); lengthBuffer.position(0); segment.put(0, lengthBuffer, position); return Optional.of(segment); } if (recordLength > THRESHOLD_FOR_SPILLING) { throw new UnsupportedOperationException("Unaligned checkpoint currently do not support spilled " + "records."); } else if (recordLength != -1) { int leftOverSize = leftOverLimit - leftOverStart; int unconsumedSize = Integer.BYTES + accumulatedRecordBytes + leftOverSize; DataOutputSerializer serializer = new DataOutputSerializer(unconsumedSize); serializer.writeInt(recordLength); serializer.write(buffer, 0, accumulatedRecordBytes); if (leftOverData != null) { serializer.write(leftOverData, leftOverStart, leftOverSize); } MemorySegment segment = MemorySegmentFactory.allocateUnpooledSegment(unconsumedSize); segment.put(0, serializer.getSharedBuffer(), 0, segment.size()); return Optional.of(segment); } return Optional.empty(); }