auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Throwable createException() { Iterator<?> realSequenceIterator = TestSequence.getRealSequence().iterator(); Iterator<?> expectedSequenceIterator = getExpectedSequence().iterator(); int i = 0; while (realSequenceIterator.hasNext() && expectedSequenceIterator.hasNext()){ Object real = realSequenceIterator.next(); Object expected = expectedSequenceIterator.next(); System.out.println(real.toString() + " vs. " + expected.toString()); if (!real.equals(expected)){ return new AssertionFailedError("Expected and real sequence differ at index " + i + ". Expected: " + expected + ", real: " + real); } i++; } if (realSequenceIterator.hasNext()){ return new AssertionFailedError("Real sequence contains more items than the expected one"); } else { return new AssertionFailedError("Expected sequence contains more items than the real one"); } }

Target:
private Throwable createException() { Iterator<?> realSequenceIterator = TestSequence.getRealSequence().iterator(); Iterator<?> expectedSequenceIterator = getExpectedSequence().iterator(); int i = 0; while (realSequenceIterator.hasNext() && expectedSequenceIterator.hasNext()){ Object real = realSequenceIterator.next(); Object expected = expectedSequenceIterator.next(); if (!real.equals(expected)){ return new AssertionFailedError("Expected and real sequence differ at index " + i + ". Expected: " + expected + ", real: " + real); } i++; } if (realSequenceIterator.hasNext()){ return new AssertionFailedError("Real sequence contains more items than the expected one"); } else { return new AssertionFailedError("Expected sequence contains more items than the real one"); } }
Source:
public void handleStepDown( long term, String dbName ) { boolean wasLeaderForTerm = Objects.equals( myself, leaderInfo.memberId() ) && term == leaderInfo.term(); if ( wasLeaderForTerm ) { log.info( String.format( "Step down event detected. This topology member, with MemberId %s, was leader in term %s, now moving " + "to follower.", myself, leaderInfo.term() ) ); HazelcastClusterTopology.casLeaders( hazelcastInstance, leaderInfo.stepDown(), dbName, log); } }

Target:
public void handleStepDown( long term, String dbName ) { boolean wasLeaderForTerm = Objects.equals( myself, leaderInfo.memberId() ) && term == leaderInfo.term(); if ( wasLeaderForTerm ) { log.info( "Step down event detected. This topology member, with MemberId %s, was leader in term %s, now moving " + "to follower.", myself, leaderInfo.term() ); HazelcastClusterTopology.casLeaders( hazelcastInstance, leaderInfo.stepDown(), dbName ); } }
Source:
public void onOpen() { super.onOpen(); filterSettingsManager.defaultActiveFilterInit(filterSettings -> addActiveFilters(filterSettings), filterSettings -> { setFilterSettings(filterSettings, table -> { setupActiveSearchFilters(); addDataDisplay(table); }); }); }

Target:
public void onOpen() { super.onOpen(); if (existActiveSearchFilters()) { clearAllActiveFiltersEvent.fire(new ClearAllActiveFiltersEvent()); setFilterSettings(filterSettingsManager.createDefaultFilterSettingsPrototype(), table -> { setupActiveSearchFilters(); addDataDisplay(table); }); } else { filterSettingsManager.defaultActiveFilterInit(filterSettings -> addActiveFilters(filterSettings)); } }
Source:
public boolean isArchived() { return getLifecycleFlags().getArchived(); }

Target:
public final boolean isArchived() { return getLifecycleFlags().getArchived(); }
Source:
private void setToCButtonFadedIn(boolean shouldFadeIn) { if (!ApiUtil.hasHoneyComb()) { return; } if (shouldFadeIn && !isToCButtonFadedIn) { Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in_toc); tocButton.startAnimation(anim); isToCButtonFadedIn = true; } else if (!shouldFadeIn && isToCButtonFadedIn) { Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_out_toc); tocButton.startAnimation(anim); isToCButtonFadedIn = false; } }

Target:
private void setToCButtonFadedIn(boolean shouldFadeIn) { if (!ApiUtil.hasHoneyComb() || shouldFadeIn == isToCButtonFadedIn) { return; } if (shouldFadeIn) { Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in_toc); tocButton.startAnimation(anim); isToCButtonFadedIn = true; } else { Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_out_toc); tocButton.startAnimation(anim); isToCButtonFadedIn = false; } }
Source:
public void seekToUs(long positionUs) { lastSeekPositionUs = positionUs; boolean seekInsideBuffer = !isPendingReset() && sampleQueue.skipToKeyframeBefore(positionUs, isWithinLastChunk(positionUs)); if (seekInsideBuffer) { while (mediaChunks.size() > 1 && mediaChunks.get(1).getFirstSampleIndex() <= sampleQueue.getReadIndex()) { mediaChunks.removeFirst(); } } else { pendingResetPositionUs = positionUs; loadingFinished = false; mediaChunks.clear(); if (loader.isLoading()) { loader.cancelLoading(); } else { sampleQueue.reset(true); } } }

Target:
public void seekToUs(long positionUs) { lastSeekPositionUs = positionUs; boolean seekInsideBuffer = !isPendingReset() && sampleQueue.skipToKeyframeBefore(positionUs, (positionUs < getNextLoadPositionUs())); if (seekInsideBuffer) { while (mediaChunks.size() > 1 && mediaChunks.get(1).getFirstSampleIndex() <= sampleQueue.getReadIndex()) { mediaChunks.removeFirst(); } } else { pendingResetPositionUs = positionUs; loadingFinished = false; mediaChunks.clear(); if (loader.isLoading()) { loader.cancelLoading(); } else { sampleQueue.reset(true); } } }
Source:
public void sweep(Collection<WriteInfo> unfilteredWrites, Sweeper sweeper) { Collection<WriteInfo> writes = filter.filter(unfilteredWrites); Map<TableReference, Map<Cell, TimestampRangeDelete>> maxTimestampByCell = writesPerTable(writes, sweeper); for (Map.Entry<TableReference, Map<Cell, TimestampRangeDelete>> entry : maxTimestampByCell.entrySet()) { try { Iterables.partition(entry.getValue().keySet(), SweepQueueUtils.BATCH_SIZE_KVS) .forEach(cells -> { Map<Cell, TimestampRangeDelete> maxTimestampByCellPartition = cells.stream() .collect(Collectors.toMap(Function.identity(), entry.getValue()::get)); follower.run(entry.getKey(), maxTimestampByCellPartition.keySet()); if (sweeper.shouldAddSentinels()) { kvs.addGarbageCollectionSentinelValues(entry.getKey(), maxTimestampByCellPartition.keySet()); kvs.deleteAllTimestamps(entry.getKey(), maxTimestampByCellPartition); } else { kvs.deleteAllTimestamps(entry.getKey(), maxTimestampByCellPartition); } }); } catch (Exception e) { if (tableWasDropped(entry.getKey())) { log.info("The table has been deleted.", LoggingArgs.tableRef(entry.getKey()), e); } else { throw e; } } } }

Target:
public void sweep(Collection<WriteInfo> unfilteredWrites, Sweeper sweeper) { Collection<WriteInfo> writes = filter.filter(unfilteredWrites); Map<TableReference, Map<Cell, TimestampRangeDelete>> maxTimestampByCell = writesPerTable(writes, sweeper); for (Map.Entry<TableReference, Map<Cell, TimestampRangeDelete>> entry : maxTimestampByCell.entrySet()) { try { Iterables.partition(entry.getValue().keySet(), SweepQueueUtils.BATCH_SIZE_KVS) .forEach(cells -> { Map<Cell, TimestampRangeDelete> maxTimestampByCellPartition = cells.stream() .collect(Collectors.toMap(Function.identity(), entry.getValue()::get)); follower.run(entry.getKey(), maxTimestampByCellPartition.keySet()); if (sweeper.shouldAddSentinels()) { kvs.addGarbageCollectionSentinelValues(entry.getKey(), maxTimestampByCellPartition.keySet()); } kvs.deleteAllTimestamps(entry.getKey(), maxTimestampByCellPartition); }); } catch (Exception e) { if (tableWasDropped(entry.getKey())) { log.info("The table has been deleted.", LoggingArgs.tableRef(entry.getKey()), e); } else { throw e; } } } }
Source:
public void testInstantiation() { NuxeoMetricSet metrics = new NuxeoMetricSet(); assertEquals(null, metrics.getPrefixName()); assertNotNull(metrics.getMetrics()); assertTrue(metrics.getMetrics().isEmpty()); }

Target:
public void testInstantiation() { NuxeoMetricSet metrics = new NuxeoMetricSet(); assertNull(metrics.getPrefixName()); assertNotNull(metrics.getMetrics()); assertTrue(metrics.getMetrics().isEmpty()); }
Source:
public String translate(final StringAgg stringAgg) { inject(stringAgg.column); if (stringAgg.isDistinct()) { 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() ); } }

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:
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(); 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 == 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); } } } }

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:
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; }

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:
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(null); getModel().getMigrationMode().setIsChangable(false); getModel().getMigrationMode().setChangeProhibitionReason(constants.vmUsesScsiReservation()); } }

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:
protected boolean canEdit(ClusterNetworkModel clusterNetworkModel) { return clusterNetworkModel.isAttached() && !clusterNetworkModel.isExternal()&& !(multiCluster && clusterNetworkModel.getOriginalNetworkCluster().isManagement()); }

Target:
protected boolean canEdit(ClusterNetworkModel clusterNetworkModel) { return clusterNetworkModel.isAttached() && !clusterNetworkModel.isExternal() && !(multiCluster && isManagementOriginally(clusterNetworkModel)); }
Source:
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) { future.get(); } } } } catch (final AvroRemoteException | InterruptedException | ExecutionException e) { e.printStackTrace(); } }

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:
public Object invokeService(ServiceTunnelRequest request) { if (IFuture.CURRENT.get().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(); }

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:
public void testBuild() throws Exception { initTestData(WORKSPACE); executeBndCmd("clean"); executeBndCmd("compile"); executeBndCmd("build"); capturedStdIO.getSystemErrContent() .contains( EMPTY_JAR_MSG); expectFileStatus(FileStatus.CREATED, "p/generated/p.jar"); expectFileStatus(FileStatus.CREATED, "p2/generated/p2.jar"); expectFileStatus(FileStatus.CREATED, "p3/generated/p3.jar"); }

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:
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(); LOG.info("coros {}", corsor); LOG.info("query {}", query); LOG.info("courseId {}", courseId); users.update(corsor, query); }

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:
public String explain(String impliedTableName) { switch(getExpressionType()) { case OPERATOR_IS_NULL: return "(" + m_left.explain(impliedTableName) + " IS NULL)"; 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) + ")"; } }

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:
public static List<EObject> getNonUnionSupersetReferences(EReference reference) { return Lists.newArrayList(Iterables.filter(getSupersetReferences(reference), 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()); } }); } })); }

Target:
public static List<EObject> getNonUnionSupersetReferences(EReference reference) { return Lists.newArrayList(Iterables.filter(getSupersetReferences(reference), new KeepOnlyNonUnionEReferences())); }
Source:
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()) .equals(user.getRoleName()), "User role assert"); 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"); }

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:
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() .sorted(Comparator.comparingInt(RatingStat::getRating).reversed()) .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)); }

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:
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); } } if (!VmHandler.isGraphicsAndDisplaySupported(getParameters().getVmStaticData().getOsId(), getEntityGraphicsTypes(getVmTemplateId()), getParameters().getVm().getDefaultDisplayType(), getReturnValue().getCanDoActionMessages(), getVdsGroup().getcompatibility_version())) { return false; } return retValue; }

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:
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; 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); }

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:
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("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; }

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:
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); out.limit(out.position()); return result; }

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:
private int removePossessives(char[] s, int len) { if (len > 5) { if (StemmerUtil.endsWith(s, len, "ov")) return len - 2; if (StemmerUtil.endsWith(s, len, "in")) return palatalize(s, len - 1); } return len; }

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:
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); } if (entries[0] != Double.toString(DEFAULT_ENTRY)) { updateStatus(CHECK_NAME, SystemStatus.FAIL, new Exception("LOADED ARRAY NOT EQUAL TO SAVED ARRAY")); } }

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:
protected boolean isHotPlugSupported() { if (FeatureSupported.hotPlug(getVds().getVdsGroupCompatibilityVersion())) { return true; } return failCanDoAction(VdcBllMessages.HOT_PLUG_IS_NOT_SUPPORTED); }

Target:
protected boolean isHotPlugSupported() { if (FeatureSupported.hotPlug(getVm().getVdsGroupCompatibilityVersion())) { return true; } return failCanDoAction(VdcBllMessages.HOT_PLUG_IS_NOT_SUPPORTED); }
Source:
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); forceBlockingFlush(LEGACY_PEERS); 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); }

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:
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( defaultEngine).setHoldingData(conflictsDetectorData); interactiveUis.put(EMFComparePreferences.CONFLICTS_DETECTOR, uiBuilder.build()); }

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:
private void shuffleDataset() { Random random = new Random(); int iterator, shufflePosition; Object temp; for(iterator = dataset.length - 1; iterator > 0; iterator--) { shufflePosition = random.nextInt(iterator); temp = dataset[iterator]; dataset[iterator] = dataset[shufflePosition]; dataset[shufflePosition] = temp; } }

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:
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 = SpringContext.getBean(PersonService.class) .getPersonByPrincipalName(rassAwardPiCoPi.getProjectDirectorPrincipalName()).getPrincipalId(); projectDirector.setPrincipalId(principalId); projectDirector.setProposalPrimaryProjectDirectorIndicator(rassAwardPiCoPi.getPrimary()); projectDirectors.add(projectDirector); } } return projectDirectors; }

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:
public JUnitRule silent() { return new JUnitRule(logger, true); }

Target:
public MockitoRule silent() { return new JUnitRule(logger, Strictness.LENIENT); }
Source:
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) { LogMessages.LOGGER.debugf(Messages.MESSAGES.jsonBDeserializationError(e.toString())); throw new ProcessingException(Messages.MESSAGES.jsonBDeserializationError("")); } }

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:
public void onPlaceBlock(ActivateEvent event, EntityRef item) { if (!event.getTarget().exists()) { event.consume(); return; } BlockItemComponent blockItem = item.getComponent(BlockItemComponent.class); BlockFamily blockFamily = blockItem.blockFamily; Side surfaceSide = Side.inDirection(event.getHitNormal()); BlockComponent blockComponent = event.getTarget().getComponent(BlockComponent.class); if (blockComponent == null) { event.consume(); return; } Vector3i targetBlock = new Vector3i(blockComponent.position); Vector3i placementPos = new Vector3i(targetBlock); placementPos.add(surfaceSide.getVector3i()); Vector3f targetPosition = event.getTargetLocation(); Vector2f relativePlacementPosition; if (targetPosition != null) { relativePlacementPosition = getSideHitPosition(event.getHitPosition(), targetPosition); } else { relativePlacementPosition = new Vector2f(); } Block block = blockFamily.getBlockForPlacement(new BlockPlacementData( JomlUtil.from(placementPos), surfaceSide, JomlUtil.from(event.getDirection()), relativePlacementPosition )); if (canPlaceBlock(block, targetBlock, placementPos)) { if (networkSystem.getMode().isAuthority()) { PlaceBlocks placeBlocks = new PlaceBlocks(placementPos, block, event.getInstigator()); worldProvider.getWorldEntity().send(placeBlocks); if (!placeBlocks.isConsumed()) { item.send(new OnBlockItemPlaced(placementPos, blockEntityRegistry.getBlockEntityAt(placementPos), event.getInstigator())); } else { event.consume(); } } recordBlockPlaced(event, blockFamily); event.getInstigator().send(new PlaySoundEvent(Assets.getSound("engine:PlaceBlock").get(), 0.5f)); } else { event.consume(); } }

Target:
public void onPlaceBlock(ActivateEvent event, EntityRef item) { if (!event.getTarget().exists()) { event.consume(); return; } BlockItemComponent blockItem = item.getComponent(BlockItemComponent.class); BlockFamily blockFamily = blockItem.blockFamily; Side surfaceSide = Side.inDirection(event.getHitNormal()); BlockComponent blockComponent = event.getTarget().getComponent(BlockComponent.class); if (blockComponent == null) { event.consume(); return; } Vector3i targetBlock = new Vector3i(blockComponent.position); Vector3i placementPos = new Vector3i(targetBlock); placementPos.add(surfaceSide.getVector3i()); Vector2f relativeAttachmentPosition = getRelativeAttachmentPosition(event); Block block = blockFamily.getBlockForPlacement(new BlockPlacementData( JomlUtil.from(placementPos), surfaceSide, JomlUtil.from(event.getDirection()), relativeAttachmentPosition )); if (canPlaceBlock(block, targetBlock, placementPos)) { if (networkSystem.getMode().isAuthority()) { PlaceBlocks placeBlocks = new PlaceBlocks(placementPos, block, event.getInstigator()); worldProvider.getWorldEntity().send(placeBlocks); if (!placeBlocks.isConsumed()) { item.send(new OnBlockItemPlaced(placementPos, blockEntityRegistry.getBlockEntityAt(placementPos), event.getInstigator())); } else { event.consume(); } } recordBlockPlaced(event, blockFamily); event.getInstigator().send(new PlaySoundEvent(Assets.getSound("engine:PlaceBlock").get(), 0.5f)); } else { event.consume(); } }