auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void waitUntilAllBlocked() { try { _blockersDoneLatch.await(); } START catch (Exception ex) { END } } missing exception. either log, rethrow runtime or rename exception ignored. Expand Exception

Target:
public void waitUntilAllBlocked() throws InterruptedException { _blockersDoneLatch.await(); }
Source:
private static boolean hasMatrixParam(List<PathSegment> pathSegments, String param) { if (pathSegments != null) for (PathSegment segement : pathSegments) { MultivaluedMap<String, String> matrixParams = segement.getMatrixParameters(); if (matrixParams != null && !matrixParams.isEmpty()) for (String key : matrixParams.keySet()) { if (key.equals(param)) return true; START } END } return false; } Why not if (matrixParams.containsKey(param) { ... } ?

Target:
private static boolean hasMatrixParam(List<PathSegment> pathSegments, String param) { if (pathSegments != null) for (PathSegment segement : pathSegments) { MultivaluedMap<String, String> matrixParams = segement.getMatrixParameters(); if (matrixParams != null && !matrixParams.isEmpty() && matrixParams.containsKey(param)) return true; } return false; }
Source:
public void setAttached(boolean attached) { START attached = attached; END } this is self assignment - please modify to: this.attached = attached

Target:
public void setAttached(boolean attached) { this.attached = attached; }
Source:
public void visited(RevObject o) { START lowestDepthVisited.put(o, Long.valueOf(walk.getTreeDepth())); END } Stupid question: why long/Long? walk.getTreeDepth() returns int, so why not use Integer (also in the Map, and intValue() above)?

Target:
public void visited(RevObject o) { lowestDepthVisited.put(o, Integer.valueOf(walk.getTreeDepth())); }
Source:
private List<Object[]> convertIntegerToLong(List<Object[]> list, int index) { for (Object[] item : list) { START item[index] = new Long((long) item[index]); END } return list; } Is this superfluous casting?

Target:
private List<Object[]> convertIntegerToLong(List<Object[]> list, int index) { for (Object[] item : list) { item[index] = (long) item[index]; } return list; }
Source:
private void flushAll() throws AuthException { for (DynamicMap.Entry<Cache<?, ?>> e : cacheMap) { CacheResource cacheResource = new CacheResource(e.getPluginName(), e.getExportName(), e.getProvider()); if (FlushCache.WEB_SESSIONS.equals(cacheResource.getName())) { continue; } flushCache.get().apply(cacheResource, START new FlushCache.Input()); END } } No new for constant object in loop. Either pass null, or construct the instance outside of the looop.

Target:
private void flushAll() throws AuthException { for (DynamicMap.Entry<Cache<?, ?>> e : cacheMap) { CacheResource cacheResource = new CacheResource(e.getPluginName(), e.getExportName(), e.getProvider()); if (FlushCache.WEB_SESSIONS.equals(cacheResource.getName())) { continue; } flushCache.apply(cacheResource, null); } }
Source:
START public static Map<String, IAnalysisModule> getAnalysisModules() { END if (fAnalysisModules.isEmpty()) { TmfAnalysisType analysis = TmfAnalysisType.getInstance(); List<IAnalysisModule> modules = analysis.getAnalysisModules(); for (IAnalysisModule module : modules) { fAnalysisModules.add(module); } } return getExecutableModules(); } I'm not sure I like the fact we're creating 2-3 Lists and Maps everytime the "get" is called. Wouldn't there be a way to keep the fAnalsysiModules map always up-to-date as analyzes register, so that the get can simply return the map directly (wrapped into a Collections.unmodifiableMap of course) ?

Target:
public static Map<String, IAnalysisModule> getAnalysisModules() { synchronized (fAnalysisModules) { if (fAnalysisModules.isEmpty()) { TmfAnalysisType analysis = TmfAnalysisType.getInstance(); List<IAnalysisModule> modules = analysis.getAnalysisModules(); for (IAnalysisModule module : modules) { fAnalysisModules.add(module); } } } return getExecutableModules(); }
Source:
void validateValueParameter(String name, Object value) { Class<? extends IValueValidator> validators[] = wrappedParameter.validateValueWith(); START if (validators != null && validators.length>0) { END for(final Class<? extends IValueValidator> validator: validators) { validateValueParameter(validator, name, value); } } } Spaces.

Target:
void validateValueParameter(String name, Object value) { final Class<? extends IValueValidator> validators[] = wrappedParameter.validateValueWith(); if (validators != null && validators.length > 0) { for(final Class<? extends IValueValidator> validator: validators) { validateValueParameter(validator, name, value); } } }
Source:
START public <C> Stream<Match> match(Object object, Captures captures, C context) END { if (previous.isPresent()) { return previous.get().match(object, captures, context) .flatMap(match -> accept(object, match.captures(), context)); } else { return accept(object, captures, context); } } final?

Target:
public final <C> Stream<Match> match(Object object, Captures captures, C context) { if (previous.isPresent()) { return previous.get().match(object, captures, context) .flatMap(match -> accept(object, match.captures(), context)); } else { return accept(object, captures, context); } }
Source:
public ArticlePageObject savePage() { waitForElementInViewPort(editSummary); waitForElementInViewPort(reviewChangesButton); waitForElementVisibleByElement(savePanel); publishButton.click(); START PageObjectLogging.log("savePage", "The 2nd Publish Button is clicked", true); END return new ArticlePageObject(driver); } Global listener catch each click. You don't need to log it.

Target:
public ArticlePageObject savePage() { waitForElementInViewPort(editSummary); waitForElementInViewPort(reviewChangesButton); waitForElementVisibleByElement(savePanel); publishButton.click(); return new ArticlePageObject(driver); }
Source:
public void executeCommand(CommandSender sender, List<String> arguments) { // Get the list of banned players Set<OfflinePlayer> bannedPlayers = bukkitService.getBannedPlayers(); Set<String> namedBanned = new HashSet<>(bannedPlayers.size()); for (OfflinePlayer offlinePlayer : bannedPlayers) { namedBanned.add(offlinePlayer.getName()); } START purgeService.purgePlayers(sender, namedBanned, bannedPlayers.toArray(new OfflinePlayer[0])); END } Please revert. I know it's an IntelliJ warning but why should we tell Java to create an array generically by reflection when we literally know the size beforehand?

Target:
public void executeCommand(CommandSender sender, List<String> arguments) { // Get the list of banned players Set<OfflinePlayer> bannedPlayers = bukkitService.getBannedPlayers(); Set<String> namedBanned = new HashSet<>(bannedPlayers.size()); for (OfflinePlayer offlinePlayer : bannedPlayers) { namedBanned.add(offlinePlayer.getName()); } purgeService.purgePlayers(sender, namedBanned, bannedPlayers.toArray(new OfflinePlayer[bannedPlayers.size()])); }
Source:
START public static Keyspace getKeyspace() { END return keyspace; } Why do we need to make this public? It should be package scoped, protected would work as well. All Astyanax classes in com.rackspace.blueflood.io.astyanax.\* should be able to call this method without it being public.

Target:
protected static Keyspace getKeyspace() { return keyspace; }
Source:
void setNewElementYPosition(final Element elementReference, final Element newElement) { START int referencePosition = getDndListComponent().getPositionY(elementReference); END getDndListComponent().setPositionY(newElement, referencePosition); } just for consistency, can we use `final int`?

Target:
void setNewElementYPosition(final Element elementReference, final Element newElement) { final int referencePosition = getDndListComponent().getPositionY(elementReference); getDndListComponent().setPositionY(newElement, referencePosition); }
Source:
public void layoutTopRight(CTabFolder ctf) { Composite trComp = getTRComposite(ctf); if (trComp.getChildren().length > 0) { trComp.setVisible(true); ctf.setTopRight(trComp, SWT.RIGHT | SWT.WRAP); } else { ctf.setTopRight(null); trComp.setVisible(false); } trComp.pack(); START ctf.layout(true, true); END } I'm not sure if we should fix it in this way. Removing the CTabFolder.layout invocation is a part of the optimization process that is needed to fix the issue exposed by the "JRockit Mission Control " application. It blocks the similar applications to be migrated to the E4 (poor GUI rendering performance) Daniel

Target:
public void layoutTopRight(CTabFolder ctf) { Composite trComp = getTRComposite(ctf); if (trComp.getChildren().length > 0) { trComp.setVisible(true); ctf.setTopRight(trComp, SWT.RIGHT | SWT.WRAP); } else { ctf.setTopRight(null); trComp.setVisible(false); } trComp.pack(); trComp.layout(true, true); }
Source:
ByteBuf buffer() throws IOException { if (buf == null) { buf = Netty4Utils.toByteBuf(context.get()); context = null; START } END return buf; } Can we `assert context == null` here?

Target:
ByteBuf buffer() throws IOException { if (buf == null) { buf = Netty4Utils.toByteBuf(context.get()); context = null; } assert context == null; return buf; }
Source:
public String getName() { String name = super.getName(); START if (name == null || name.isEmpty()) { END return ""; } else { return name; } } Now we have `isEmpty` method for Strings in Utils. Is it good idea to use it here as well? https://github.com/kiegroup/kie-wb-common/blob/master/kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-api/kie-wb-common-stunner-core-api/src/main/java/org/kie/workbench/common/stunner/core/util/StringUtils.java

Target:
public String getName() { String name = super.getName(); if (StringUtils.isEmpty(name)) { return ""; } else { return name; } }
Source:
private void verifyInvalidValueSize(IndexValue value, String logSegmentName) { try { int capacity = TestUtils.RANDOM.nextInt(value.getBytes().capacity()); ByteBuffer invalidValue = ByteBuffer.allocate(capacity); invalidValue.put(value.getBytes().array(), 0, capacity); START new IndexValue(logSegmentName, invalidValue, version); END fail( "Contruction of IndexValue expected to fail with invalid byte buffer capacity of " + invalidValue.capacity()); } catch (IllegalArgumentException e) { } } minor: put _only_ the statement you expect to fail in `try`.

Target:
private void verifyInvalidValueSize(IndexValue value, String logSegmentName) { int capacity = TestUtils.RANDOM.nextInt(value.getBytes().capacity()); ByteBuffer invalidValue = ByteBuffer.allocate(capacity); invalidValue.put(value.getBytes().array(), 0, capacity); try { new IndexValue(logSegmentName, invalidValue, version); fail( "Contruction of IndexValue expected to fail with invalid byte buffer capacity of " + invalidValue.capacity()); } catch (IllegalArgumentException e) { } }
Source:
void dispose() { if (semanticResourcesUpdater != null) { semanticResourcesUpdater.dispose(); semanticResourcesUpdater = null; START } END } session could be set to null on dispose().

Target:
void dispose() { session = null; if (semanticResourcesUpdater != null) { semanticResourcesUpdater.dispose(); semanticResourcesUpdater = null; } }
Source:
public void deleteByContentType(final ContentTypeIf type) throws DotDataException{ START final DotConnect dc = new DotConnect(); END dc.setSQL(sql.DELETE_RELATIONSHIP_BY_PARENT_OR_CHILD_INODE); dc.addParam(type.id()); dc.addParam(type.id()); dc.loadResults(); } you can do this things in one line such as ``` new DotConnect().setSQL(sql.DELETE_RELATIONSHIP_BY_PARENT_OR_CHILD_INODE).addParam(type.id()).addParam(type.id()).loadResults(); ```

Target:
public void deleteByContentType(final ContentTypeIf type) throws DotDataException{ new DotConnect() .setSQL(sql.DELETE_RELATIONSHIP_BY_PARENT_OR_CHILD_INODE) .addParam(type.id()) .addParam(type.id()) .loadResults(); }
Source:
public int getUniqueNotificationId() { if (uniqueNotificationIdCounter == null) { uniqueNotificationIdCounter = new AtomicInteger(0); START } END return uniqueNotificationIdCounter.incrementAndGet(); } Is the if block still needed?

Target:
public int getUniqueNotificationId() { return uniqueNotificationIdCounter.incrementAndGet(); }
Source:
public void run() { // Loops till QueueProcessorThread is shutdown while (!shutdown) { synchronized (this) { try { // start processing queue if active, other wait for sometime if (isActive) { processQueuedFlows(activeExecutorRefreshWindowInMilisec, activeExecutorRefreshWindowInFlows); } wait(QUEUE_PROCESSOR_WAIT_IN_MS); } catch (Exception e) { START logger.info( END "QueueProcessorThread Interrupted. Probably to shut down.", e); } } } } How come not logger.error()?

Target:
public void run() { // Loops till QueueProcessorThread is shutdown while (!shutdown) { synchronized (this) { try { // start processing queue if active, other wait for sometime if (isActive) { processQueuedFlows(activeExecutorRefreshWindowInMilisec, activeExecutorRefreshWindowInFlows); } wait(QUEUE_PROCESSOR_WAIT_IN_MS); } catch (Exception e) { logger.error( "QueueProcessorThread Interrupted. Probably to shut down.", e); } } } }
Source:
public HllSketchMergeBufferAggregator( final ColumnValueSelector<HllSketch> selector, final int lgK, final TgtHllType tgtHllType, final int size ) { this.selector = selector; this.lgK = lgK; this.tgtHllType = tgtHllType; this.size = size; this.emptyUnion = new byte[size]; //noinspection ResultOfObjectAllocationIgnored (Union writes to "emptySketch" as a side effect of construction) START new Union(lgK, WritableMemory.wrap(emptyUnion, ByteOrder.LITTLE_ENDIAN)); END } No need to force byte order when wrapping byte[]

Target:
public HllSketchMergeBufferAggregator( final ColumnValueSelector<HllSketch> selector, final int lgK, final TgtHllType tgtHllType, final int size ) { this.selector = selector; this.lgK = lgK; this.tgtHllType = tgtHllType; this.size = size; this.emptyUnion = new byte[size]; //noinspection ResultOfObjectAllocationIgnored (Union writes to "emptyUnion" as a side effect of construction) new Union(lgK, WritableMemory.wrap(emptyUnion)); }
Source:
public void checkIPAdress() { Set<ConstraintViolation<IPAdress>> validate = validator.validate(new IPAdress(address)); START assertEquals(validate.isEmpty(), expectedResult); END } The expected value should be 1st, it affects error messages by junit

Target:
public void checkIPAdress() { Set<ConstraintViolation<IPAdress>> validate = validator.validate(new IPAdress(address)); assertEquals(expectedResult, validate.isEmpty()); }
Source:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { try { // Ignore first call, which comes from onCreate() if (currentFormat != null) calc(); } catch (GeopointException e) { START context.showToast(e.getMessage()); END spinner.setSelection(currentFormat.ordinal()); return; } currentFormat = coordInputFormatEnum.fromInt(pos); settings.setCoordInputFormat(currentFormat); updateGUI(); } No good idea. ;)

Target:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // Ignore first call, which comes from onCreate() if (currentFormat != null && !calc()) { // An error occurred, reset spinner to current format spinner.setSelection(currentFormat.ordinal()); return; } currentFormat = coordInputFormatEnum.fromInt(pos); settings.setCoordInputFormat(currentFormat); updateGUI(); }
Source:
public boolean visitTableWithType(String schemaName, String tableName, TableType type) { Preconditions .checkNotNull(type, "Error. Type information for table %s.%s provided is null.", schemaName, tableName); records.add(new Records.Table(IS_CATALOG_NAME, schemaName, tableName, type.toString())); START return false; END } why return `false`?

Target:
private void visitTableWithType(String schemaName, String tableName, TableType type) { Preconditions .checkNotNull(type, "Error. Type information for table %s.%s provided is null.", schemaName, tableName); records.add(new Records.Table(IS_CATALOG_NAME, schemaName, tableName, type.toString())); return; }
Source:
public boolean add(XWikiAttachment attachment) { START return set(attachment) != null; END } Comparing with null is not enough. You might replace an existing attachment with a different instance in which case you should return true. In short if the return is different from the input then something changed.

Target:
public boolean add(XWikiAttachment attachment) { XWikiAttachment set = set(attachment); return set != attachment; }
Source:
public String toString() { START return Objects.toStringHelper(this).add("liveWorkerNum", mLiveWorkerNum) END .add("lostWorkerNum", mLostWorkerNum).add("capacityBytes", mCapacityBytes) .add("usedBytes", mUsedBytes).add("freeBytes", mFreeBytes) .add("capacityBytesOnTiers", mCapacityBytesOnTiers) .add("usedBytesOnTiers", mUsedBytesOnTiers).toString(); } ditto: sort by name please

Target:
public String toString() { return Objects.toStringHelper(this).add("capacityBytes", mCapacityBytes) .add("capacityBytesOnTiers", mCapacityBytesOnTiers) .add("freeBytes", mFreeBytes) .add("liveWorkerNum", mLiveWorkerNum) .add("lostWorkerNum", mLostWorkerNum) .add("usedBytes", mUsedBytes) .add("usedBytesOnTiers", mUsedBytesOnTiers).toString(); }
Source:
public static final void assertJenkinsNotInQuietMode(final JenkinsRule j) { await().pollInterval(250, TimeUnit.MILLISECONDS) .atMost(10, TimeUnit.SECONDS) START .until(() -> !j.jenkins.get().getQueue().isBlockedByShutdown(task)); END } ```suggestion .until(() -> !j.jenkins.getQueue().isBlockedByShutdown(task)); ```

Target:
public static final void assertJenkinsNotInQuietMode(final JenkinsRule j) { await().pollInterval(250, TimeUnit.MILLISECONDS) .atMost(10, TimeUnit.SECONDS) .until(() -> !j.jenkins.getQueue().isBlockedByShutdown(task)); }
Source:
private TreeLayer START getTreeLayer() END { NatTable natTable = (NatTable) getTableManager().getAdapter(NatTable.class); ILayer layer = natTable.getLayer(); if (layer instanceof PapyrusGridLayer) { PapyrusGridLayer gridLayer = (PapyrusGridLayer) layer; ILayer rowLayer = gridLayer.getRowHeaderLayer(); if (rowLayer instanceof RowHeaderHierarchicalLayerStack) { return ((RowHeaderHierarchicalLayerStack) rowLayer).getTreeLayer(); } } throw new UnknownError("TreeLayer has not been found"); //$NON-NLS-1$ } The method signature doesn't specify the Exception which could be thrown.

Target:
private TreeLayer getTreeLayer() throws Exception { NatTable natTable = (NatTable) getTableManager().getAdapter(NatTable.class); ILayer layer = natTable.getLayer(); if (layer instanceof PapyrusGridLayer) { PapyrusGridLayer gridLayer = (PapyrusGridLayer) layer; ILayer rowLayer = gridLayer.getRowHeaderLayer(); if (rowLayer instanceof RowHeaderHierarchicalLayerStack) { return ((RowHeaderHierarchicalLayerStack) rowLayer).getTreeLayer(); } } throw new UnknownError("TreeLayer has not been found"); //$NON-NLS-1$ }
Source:
public boolean equals(@Nullable Object obj) { START if (!(obj instanceof DataDrivenValueSelf)) { END return false; } return true; } return directly

Target:
public boolean equals(@Nullable Object obj) { if (!(obj instanceof DataDrivenValueSelf)) { return false; } return super.equals(obj); }
Source:
public void differentUrlForPostsAndVideo() { START SearchInput searchInput = new SearchInput().searchInputValue(); END SearchInput searchInputSubmit = new SearchInput().searchInputSubmit(); String URL = driver.getCurrentUrl(); Assert.assertEquals(URL, "http://qa.fandom.wikia.com/?s=TEST"); SearchInput postsResult = new SearchInput().searchResultsPosts(); String postUrl = driver.getCurrentUrl(); SearchInput videosResult = new SearchInput().searchResultsVideos(); String videoUrl = driver.getCurrentUrl(); Assert.assertNotEquals(postUrl, videoUrl); } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Remove this unused "searchInput" local variable. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://sonar-s1/coding_rules#rule_key=squid%3AS1481)

Target:
public void differentUrlForPostsAndVideo() { SearchInput searchInput = new SearchInput().searchInputValue(); SearchInput searchInputSubmit = new SearchInput().searchInputSubmit(); SearchInput postsResult = new SearchInput().searchResultsPosts(); String postUrl = driver.getCurrentUrl(); SearchInput videosResult = new SearchInput().searchResultsVideos(); String videoUrl = driver.getCurrentUrl(); Assert.assertNotEquals(postUrl, videoUrl); }
Source:
START String convert(Blob blob) { END if (blob.getLength() == 0L) { return ""; } try (InputStream stream = blob.getStream()) { Xml2TextHandler xml2text = new Xml2TextHandler(); return xml2text.parse(stream); } catch (IOException | SAXException | ParserConfigurationException e) { throw new ConversionException("Error during XML2Text conversion", e); } } I would deprecate it and add a new one.

Target:
protected String convert(Blob blob) { if (blob.getLength() == 0L) { return ""; } try (InputStream stream = blob.getStream()) { Xml2TextHandler xml2text = new Xml2TextHandler(); return xml2text.parse(stream); } catch (IOException | SAXException | ParserConfigurationException e) { throw new ConversionException("Error during XML2Text conversion", blob, e); } }
Source:
START public static void validateHeaderConfigAction(String action) { END if (!HEADER_ACTIONS.stream().anyMatch(action::equalsIgnoreCase)) { throw new ConfigException(String.format("Invalid header config action: '%s'. " + "Expected one of %s", action, HEADER_ACTIONS)); } } This should be package-level protected: ```suggestion // Visible for testing static void validateHeaderConfigAction(String action) { ```

Target:
static void validateHeaderConfigAction(String action) { if (!HEADER_ACTIONS.stream().anyMatch(action::equalsIgnoreCase)) { throw new ConfigException(String.format("Invalid header config action: '%s'. " + "Expected one of %s", action, HEADER_ACTIONS)); } }
Source:
private String getVariableLabel(VariableMetadata variableMetadata) { if (variableMetadata.getName().startsWith(CASE_VARIABLE_PREFIX)) { return translationService.getValue(CASE_VARIABLE_LABEL_PREFIX) + " " + START variableMetadata.getName().substring(CASE_VARIABLE_PREFIX.length(), variableMetadata.getName().length()); END } else { return variableMetadata.getName(); } } `variableMetadata.getName().length()` invocation is redundant.

Target:
private String getVariableLabel(VariableMetadata variableMetadata) { if (variableMetadata.getName().startsWith(CASE_VARIABLE_PREFIX)) { return translationService.getValue(CASE_VARIABLE_LABEL_PREFIX) + " " + variableMetadata.getName().substring(CASE_VARIABLE_PREFIX.length()); } else { return variableMetadata.getName(); } }
Source:
private Long findFreeId(){ START while(personRepository.findOne(lastId) != null){ // New person END lastId++; } return lastId; } [existsById(long id)](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html#existsById-ID-) 💯

Target:
private Long findFreeId(){ while(personRepository.exists(lastId)){ // New person lastId++; } return lastId; }
Source:
public void cameraDeviceCallsAreForwardedToCallback() throws InterruptedException { START Assume.assumeTrue(mCameraId != null); END mUseCase.addStateChangeListener( mCameraRepository.getCamera( getCameraIdForLensFacingUnchecked(mConfig.getLensFacing()))); mUseCase.doNotifyActive(); mCameraRepository.onGroupActive(mUseCaseGroup); // Wait for the CameraDevice.onOpened callback. mUseCase.mDeviceStateCallback.waitForOnOpened(1); mCameraRepository.onGroupInactive(mUseCaseGroup); // Wait for the CameraDevice.onClosed callback. mUseCase.mDeviceStateCallback.waitForOnClosed(1); } Move to setUp(). You can make mCameraId a local variable again.

Target:
public void cameraDeviceCallsAreForwardedToCallback() throws InterruptedException { mUseCase.addStateChangeListener( mCameraRepository.getCamera( getCameraIdForLensFacingUnchecked(mConfig.getLensFacing()))); mUseCase.doNotifyActive(); mCameraRepository.onGroupActive(mUseCaseGroup); // Wait for the CameraDevice.onOpened callback. mUseCase.mDeviceStateCallback.waitForOnOpened(1); mCameraRepository.onGroupInactive(mUseCaseGroup); // Wait for the CameraDevice.onClosed callback. mUseCase.mDeviceStateCallback.waitForOnClosed(1); }
Source:
public String getDescription() { START return getStatuteType().getName().getContent(I18N.getLocale()) END + (studentStatute instanceof SeniorStatute ? (" (" + ((SeniorStatute) studentStatute).getRegistration().getDegree().getPresentationName() + ") ") : ""); } Beware that invoking [`getContent(I18N.getLocale())`](https://github.com/FenixEdu/fenixedu-commons/blob/v1.1.0/src/main/java/org/fenixedu/commons/i18n/LocalizedString.java#L461-L475) is different than just invoking [`getContent()`](https://github.com/FenixEdu/fenixedu-commons/blob/v1.1.0/src/main/java/org/fenixedu/commons/i18n/LocalizedString.java#L480-L496).

Target:
public String getDescription() { return getStatuteType().getName().getContent() + (studentStatute instanceof SeniorStatute ? (" (" + ((SeniorStatute) studentStatute).getRegistration().getDegree().getPresentationName() + ") ") : ""); }
Source:
START public boolean teleportToSpawn() { END Location target = server.getWorlds().get(0).getSpawnLocation(); EntityPortalEvent event = EventFactory.callEvent(new EntityPortalEvent(this, location.clone(), target, null)); if (event.isCancelled()) { return false; } target = event.getTo(); teleport(target); return true; } Do this and the other method need to be public? Would `protected` suffice?

Target:
protected boolean teleportToSpawn() { Location target = server.getWorlds().get(0).getSpawnLocation(); EntityPortalEvent event = EventFactory.callEvent(new EntityPortalEvent(this, location.clone(), target, null)); if (event.isCancelled()) { return false; } target = event.getTo(); teleport(target); return true; }
Source:
public String[] getGroupFilters() { START String[] result = null; END IAnnotation before = m_annotationFinder.findAnnotation(getConstructorOrMethod(), IBeforeMethod.class); if (before != null) { result = ((ConfigurationAnnotation) before).getGroupFilters(); } return result; } Can we please have this variable initialized to an empty array so that we can avoid a null check to be done ?

Target:
public String[] getGroupFilters() { IBeforeMethod before = m_annotationFinder.findAnnotation(getConstructorOrMethod(), IBeforeMethod.class); if (before == null) { return new String[0]; } return before.getGroupFilters(); }
Source:
START protected PageCacheNumberArray( PagedFile pagedFile, int entrySize, long length, END long defaultValue, long base ) throws IOException { this.pagedFile = pagedFile; this.entrySize = entrySize; this.entriesPerPage = pagedFile.pageSize() / entrySize; this.length = length; this.defaultValue = defaultValue; this.base = base; try ( PageCursor cursorToSetLength = pagedFile.io( 0, PF_SHARED_WRITE_LOCK ) ) { setLength( cursorToSetLength, length ); } if ( defaultValue != 0 ) { setDefaultValue( defaultValue ); } } some of the protected items here can be package private

Target:
PageCacheNumberArray( PagedFile pagedFile, int entrySize, long length, long defaultValue, long base ) throws IOException { this.pagedFile = pagedFile; this.entrySize = entrySize; this.entriesPerPage = pagedFile.pageSize() / entrySize; this.length = length; this.defaultValue = defaultValue; this.base = base; try ( PageCursor cursorToSetLength = pagedFile.io( 0, PF_SHARED_WRITE_LOCK ) ) { setLength( cursorToSetLength, length ); } if ( defaultValue != 0 ) { setDefaultValue( defaultValue ); } }
Source:
public InterpretedPageProjectionOutput(DriverYieldSignal yieldSignal, Page page, SelectedPositions selectedPositions) { this.yieldSignal = requireNonNull(yieldSignal, "yieldSignal is null"); this.blocks = requireNonNull(page, "page is null").getBlocks(); this.selectedPositions = requireNonNull(selectedPositions, "selectedPositions is null"); this.nextIndexOrPosition = selectedPositions.getOffset(); if (selectedPositions.isList()) { this.positions = selectedPositions.getPositions(); } else { this.positions = null; START } END } Don't precompute `selectedPositions.getPositions`. It is unnecessary. And it makes the code harder to follow.

Target:
public InterpretedPageProjectionOutput(DriverYieldSignal yieldSignal, Page page, SelectedPositions selectedPositions) { this.yieldSignal = requireNonNull(yieldSignal, "yieldSignal is null"); this.blocks = requireNonNull(page, "page is null").getBlocks(); this.selectedPositions = requireNonNull(selectedPositions, "selectedPositions is null"); this.nextIndexOrPosition = selectedPositions.getOffset(); }
Source:
public String getDicomViewerUrl(Study study) { if (study == null) throw new IllegalArgumentException("study cannot be null"); else if (study.getStudyInstanceUid() == null) throw new IllegalArgumentException("studyInstanceUid cannot be null"); START return study.isCompleted() ? this.radiologyProperties.getDicomViewerUrl() + "studyUID=" END + study.getStudyInstanceUid() : null; } this ternary will not behave as stated in the 1. should annotation

Target:
public String getDicomViewerUrl(Study study) { if (study == null) throw new IllegalArgumentException("study cannot be null"); else if (study.getStudyInstanceUid() == null) throw new IllegalArgumentException("studyInstanceUid cannot be null"); return radiologyProperties.getDicomViewerUrl() + "studyUID=" + study.getStudyInstanceUid(); }
Source:
private Declaration getDeclarationCorrespondingToXpath( Pattern pattern, boolean isXPath, Constraint constraint ) { START Declaration declFromXpath = null; END if (!isXPath && pattern.hasXPath()) { Declaration xPathDecl = pattern.getXPathDeclaration(); if (xPathDecl != null) { for ( Declaration decl : constraint.getRequiredDeclarations() ) { if (xPathDecl.equals( decl )) { declFromXpath = decl; break; } } } } return declFromXpath; } ..and change as well the variable name `declFromXpath` to `declCorrXpath` also here.

Target:
private Declaration getDeclarationCorrespondingToXpath( Pattern pattern, boolean isXPath, Constraint constraint ) { if (!isXPath && pattern.hasXPath()) { Declaration xPathDecl = pattern.getXPathDeclaration(); if (xPathDecl != null) { for ( Declaration decl : constraint.getRequiredDeclarations() ) { if (xPathDecl.equals( decl )) { return decl; } } } } return null; }
Source:
public void setQueryTimeout( int seconds ) throws AlreadyClosedSqlException, START InvalidParameterSqlException, END SQLException { throwIfClosed(); super.setQueryTimeout(seconds); } the parent setQueryTimeout will throw a SQLException if the parameter is invalid, so this method now no longer throws an InvalidParameterSqlException

Target:
public void setQueryTimeout( int seconds ) throws AlreadyClosedSqlException, SQLException { throwIfClosed(); super.setQueryTimeout(seconds); }
Source:
private List<Disk> manualAggregateSnapshots() { List<Disk> START Param = END new ArrayList<>(); DiskImage diskWithSnaps = diskWithSnapshots; diskWithSnaps.getSnapshots().addAll(snapshotsList); Param.add(diskWithSnapshots); Param.add(diskWithoutSnapshots); Param.add(ovfImage); Param.add(cinderDisk); return Param; } Please use Java conventions - param

Target:
private List<DiskImage> manualAggregateSnapshots() { DiskImage diskWithSnaps = diskWithSnapshots; diskWithSnaps.getSnapshots().addAll(snapshotsList); return Arrays.asList(diskWithSnapshots, diskWithoutSnapshots, ovfImage, cinderDisk); }
Source:
public IndexingConfigurationBuilder autoConfig(boolean autoConfig) { START enable(); END attributes.attribute(AUTO_CONFIG).set(autoConfig); return this; } Enabling indexing even if autoConfig == false? Maybe this auto-enabling should happen only if autoConfig==true?

Target:
public IndexingConfigurationBuilder autoConfig(boolean autoConfig) { if (autoConfig) enable(); attributes.attribute(AUTO_CONFIG).set(autoConfig); return this; }
Source:
private boolean shouldBeDirectlyAttached(String vfName, Guid vmId) { return START CollectionUtils .isNotEmpty(vmDeviceDao.getVmDeviceByVmIdTypeAndDevice(vmId, END VmDeviceGeneralType.HOSTDEV, vfName)); } dao will return either an empty list or populated one, but never null.

Target:
private boolean shouldBeDirectlyAttached(String vfName, Guid vmId) { return !vmDeviceDao.getVmDeviceByVmIdTypeAndDevice(vmId, VmDeviceGeneralType.HOSTDEV, vfName).isEmpty(); }
Source:
START private void safeCloseStream(Closeable stream) { END if (stream != null) { try { stream.close(); } catch (IOException e) { // swallow error in this case Logger.e(TAG, "Failed to close the stream: ", "", ADALError.IO_EXCEPTION, e); } } } static

Target:
private static void safeCloseStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { // swallow error in this case Logger.e(TAG, "Failed to close the stream: ", "", ADALError.IO_EXCEPTION, e); } } }
Source:
public static String zkSecuritySysConfigString() { String loginConfig = System.getProperty(JAVA_LOGIN_CONFIG_PARAM); String clientEnabled = System.getProperty(ZK_SASL_CLIENT); START String contextName = System.getProperty(ZK_LOGIN_CONTEXT_NAME_KEY); END return "[" + JAVA_LOGIN_CONFIG_PARAM + "=" + loginConfig + ", " + ZK_SASL_CLIENT + "=" + (clientEnabled == null ? "default:" + DEFAULT_ZK_SASL_CLIENT : clientEnabled) + ", " + ZK_LOGIN_CONTEXT_NAME_KEY + "=" + (contextName == null ? "default:" + DEFAULT_ZK_LOGIN_CONTEXT_NAME : contextName) + "]"; } How about the following to simplify the string construction below: ```java String clientEnabled = System.getProperty(ZK_SASL_CLIENT, "default:" + DEFAULT_ZK_SASL_CLIENT); String contextName = System.getProperty(ZK_LOGIN_CONTEXT_NAME_KEY, "default:" + DEFAULT_ZK_LOGIN_CONTEXT_NAME); ```

Target:
public static String zkSecuritySysConfigString() { String loginConfig = System.getProperty(JAVA_LOGIN_CONFIG_PARAM); String clientEnabled = System.getProperty(ZK_SASL_CLIENT, "default:" + DEFAULT_ZK_SASL_CLIENT); String contextName = System.getProperty(ZK_LOGIN_CONTEXT_NAME_KEY, "default:" + DEFAULT_ZK_LOGIN_CONTEXT_NAME); return "[" + JAVA_LOGIN_CONFIG_PARAM + "=" + loginConfig + ", " + ZK_SASL_CLIENT + "=" + clientEnabled + ", " + ZK_LOGIN_CONTEXT_NAME_KEY + "=" + contextName + "]"; }
Source:
START public void updateNode(final @Nonnull Node node) throws IOException { END if (node == nodes.get(node.getNodeName())) { Queue.withLock(new Runnable() { @Override public void run() { jenkins.trimLabels(); } }); persistNode(node); } } I would recommend returning a boolean, `true` for a successful update and `false` for the "no-op" case

Target:
public boolean updateNode(final @Nonnull Node node) throws IOException { if (node == nodes.get(node.getNodeName())) { Queue.withLock(new Runnable() { @Override public void run() { jenkins.trimLabels(); } }); persistNode(node); return true; } return false; }
Source:
public void onSaveInstanceState(Bundle outState) { START if (backStack != null) { END // update the topmost entry in the backstack updateCurrentBackStackItem(); outState.putParcelableArrayList("backStack", backStack); } } The rest of this class expects backStack to be nonnull. I recommend we initialize backStack to an empty mutable list and specify @NonNull in the setter.

Target:
public void onSaveInstanceState(Bundle outState) { // update the topmost entry in the back stack updateCurrentBackStackItem(); outState.putParcelableArrayList("backStack", backStack); }
Source:
public Trader(String name, double cashInHand) { START super(); END this.name = name; this.cashInHand = cashInHand; this.position = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); } Is this necessary?

Target:
public Trader(String name, double cashInHand) { //super(); this.name = name; this.cashInHand = cashInHand; this.position = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); }
Source:
START private Iterable<ITask> getTasksAssosciatedWithReviewTask(ITask reviewTask) { END String lookupUrl = reviewTask.getUrl(); // TODO: Fetch from mapping with the lookupUrl String taskUrl = "http://someurl"; AbstractRepositoryConnector repository = TasksUiPlugin.getRepositoryManager() .getConnectorForRepositoryTaskUrl(taskUrl); String taskId = repository.getTaskIdFromTaskUrl(taskUrl); String repositoryUrl = repository.getRepositoryUrlFromTaskUrl(taskUrl); ITask assosciatedTask = taskList.getTask(repositoryUrl, taskId); if (assosciatedTask == null) { return Collections.emptyList(); } return ImmutableSet.of(assosciatedTask); } There can only be one associated task.

Target:
private ITask getTasksAssosciatedWithReviewTask(ITask reviewTask) { String lookupUrl = reviewTask.getUrl(); // TODO: Fetch from mapping with the lookupUrl String taskUrl = "http://someurl"; AbstractRepositoryConnector repository = TasksUiPlugin.getRepositoryManager() .getConnectorForRepositoryTaskUrl(taskUrl); String taskId = repository.getTaskIdFromTaskUrl(taskUrl); String repositoryUrl = repository.getRepositoryUrlFromTaskUrl(taskUrl); ITask assosciatedTask = taskList.getTask(repositoryUrl, taskId); return assosciatedTask; }
Source:
START protected void toLegacyText(StringBuilder builder) END { builder.append(this.value); } Override

Target:
protected void toLegacyText(StringBuilder builder) { builder.append( this.value ); super.toLegacyText( builder ); }
Source:
START public static boolean isRoute(URL url) { END return ROUTE_PROTOCOL.equals(url.getProtocol()) || ROUTERS_CATEGORY.equals(url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY)); } `public static boolean isRoute(final URL url)`

Target:
public static boolean isRoute(URL url) { return ROUTE_PROTOCOL.equals(url.getProtocol()) || ROUTERS_CATEGORY.equals(url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY)); }
Source:
void thread2() { int[] vs1; synchronized (lock) { vs1 = values; state = 1; } int s; do { synchronized (lock) { s = state; } } while (s != 2); // Busy loop. int[] vs2; START synchronized (lock) { END vs2 = values; } int v1 = vs1[0]; int v2 = vs2[0]; System.out.println("b17689750TestMonitor failed: " + v1 + ", " + v2); } I would delete this synchronized block. Values cannot be modified while we're reading it since we already saw state as 2. It's also OK to move the prior accesses to values to before the synchronized blocks they are currently in, but it may be a better test without doing that.

Target:
void thread2() { int[] vs1; synchronized (lock) { vs1 = values; state = 1; } int s; do { synchronized (lock) { s = state; } } while (s != 2); // Busy loop. int[] vs2 = values; int v1 = vs1[0]; int v2 = vs2[0]; System.out.println("b17689750TestMonitor failed: " + v1 + ", " + v2); }
Source:
public void testWriteAndReadObject() throws Exception { START InternalSerializationService serializationService = new DefaultSerializationServiceBuilder().build(); END String expected = "test input"; String actual = (String) writeAndReadObject(serializationService, expected); assertNotNull(actual); assertEquals(expected, actual); } Isn't it easier to have the serializationService as a field on this test? Are there any serializationServices created with different settings? Having it as field instead of local variable, will simplify the test methods.

Target:
public void testWriteAndReadObject() throws Exception { String expected = "test input"; String actual = (String) writeAndReadObject(expected); assertNotNull(actual); assertEquals(expected, actual); }
Source:
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final ArArchiveEntry other = (ArArchiveEntry) obj; if (name == null) { return other.name == null; START } else return name.equals(other.name); END } please add braces for the else block.

Target:
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final ArArchiveEntry other = (ArArchiveEntry) obj; if (name == null) { return other.name == null; } else { return name.equals(other.name); } }
Source:
public ByteBufferReadableStreamChannel(List<ByteBuffer> bufferList) { if (bufferList == null || bufferList.isEmpty()) { throw new IllegalArgumentException("Input List of ByteBuffer cannot be null/empty for ByteBufferReadableStreamChannel"); } START buffers = new ArrayList<>(bufferList); END size = computeSize(bufferList); } why do you need to wrap it in a new `ArrayList`? Seems wasteful.

Target:
public ByteBufferReadableStreamChannel(List<ByteBuffer> bufferList) { if (bufferList == null || bufferList.isEmpty()) { throw new IllegalArgumentException( "Input List of ByteBuffer cannot be null/empty for ByteBufferReadableStreamChannel"); } buffers = bufferList; size = computeSize(bufferList); }
Source:
boolean areRequiredNetworksAvailable(final List<VmNetworkInterface> vmNetworkInterfaces, final List<VdsNetworkInterface> allInterfacesForVds) { for (final VmNetworkInterface vmIf : vmNetworkInterfaces) { boolean found = false; for (final VdsNetworkInterface vdsIf : allInterfacesForVds) { if (StringUtils.equals(vmIf.getNetworkName(), vdsIf.getNetworkName())) { found = true; break; } } if (!found) { START log.debug("VDS is not ok for running the VM as network is missing"); END return false; } } return true; } I don't know if it's necessary to log this message for each host, since for other unmet conditions we don't log anything. If it looks necessary to you then at least VDS ID would be helpful to know (assuming VM ID is already printed elsewehere).

Target:
boolean areRequiredNetworksAvailable(final List<VmNetworkInterface> vmNetworkInterfaces, final List<VdsNetworkInterface> allInterfacesForVds) { for (final VmNetworkInterface vmIf : vmNetworkInterfaces) { boolean found = false; for (final VdsNetworkInterface vdsIf : allInterfacesForVds) { if (StringUtils.equals(vmIf.getNetworkName(), vdsIf.getNetworkName())) { found = true; break; } } if (!found) { return false; } } return true; }
Source:
public void testStash() { try { // 1) call stash create command git.stashCreate().call(); readFile("Stash Created", git.getRepository().getWorkTree() + "/File1.txt"); // 2) call stash list git.stashList().call(); // 3) apply stash git.stashApply().call(); // 4) verify stash applied by outputting file readFile("Stash Created", git.getRepository().getWorkTree() + "/File1.txt"); START } catch (Exception e) { END e.printStackTrace(); } } Never catch exceptions in test code unless you actually want to do something use. Just declare that this method throws Exception

Target:
public void testStash() throws Exception { // 1) call stash create command git.stashCreate().call(); readFile("Stash Created", git.getRepository().getWorkTree() + "/File1.txt"); // 2) call stash list git.stashList().call(); // 3) apply stash git.stashApply().call(); // 4) verify stash applied by outputting file readFile("Stash Created", git.getRepository().getWorkTree() + "/File1.txt"); }
Source:
public List<WorkerInfo> getWorkerInfoList() throws UnavailableException { if (mSafeModeManager.isInSafeMode()) { throw new UnavailableException(ExceptionMessage.MASTER_IN_SAFEMODE.getMessage()); } try { return mWorkerInfoCache.get(WORKER_INFO_CACHE_KEY); } catch (ExecutionException e) { START throw new UnavailableException("Unable to get worker info list from cache"); END } } Can we include the information from `e` in this exception message?

Target:
public List<WorkerInfo> getWorkerInfoList() throws UnavailableException { if (mSafeModeManager.isInSafeMode()) { throw new UnavailableException(ExceptionMessage.MASTER_IN_SAFEMODE.getMessage()); } try { return mWorkerInfoCache.get(WORKER_INFO_CACHE_KEY); } catch (ExecutionException e) { throw new UnavailableException("Unable to get worker info list from cache", e); } }
Source:
public static void tearDownTestCase() throws Exception { if(dataSource != null) { Connection con = dataSource.getConnection(); if(con != null) { // rollback any changes done to DB during the test case execution START con.rollback(); END } } } Rollback should be done after each test case (i.e., with an @After notation, not an @AfterClass notataion), and I think we should preserve the current behavior od tearDownTestCase(). I suggest creating a new tearDown() method for performing the rollback.

Target:
public static void tearDownTestCase() throws Exception { }
Source:
public void checkSelectFilter(final String label, final String value) { selectInputs.computeIfPresent(label, (key, values) -> { values.forEach(i -> { START if ((i.getValue().equals(value) || i.getValue() == value) && i.getChecked() == false) { END i.setChecked(true); } }); return values; }); } Why do we have equality check here? it should have been done by the equals.

Target:
public void checkSelectFilter(final String label, final String value) { selectInputs.computeIfPresent(label, (key, values) -> { values.forEach(i -> { if (i.getValue().equals(value) && i.getChecked() == false) { i.setChecked(true); } }); return values; }); }
Source:
public ColdMergeVDSCommandParameters(Guid storageJobId, SubchainInfo subchainInfo) { START super(); END this.storageJobId = storageJobId; this.subchainInfo = subchainInfo; } needed?

Target:
public ColdMergeVDSCommandParameters(Guid storageJobId, SubchainInfo subchainInfo) { this.storageJobId = storageJobId; this.subchainInfo = subchainInfo; }
Source:
private void putResize (K key, V value) { K[] keyTable = this.keyTable; V[] valueTable = this.valueTable; for (int i = place(key); ; i = (i + 1) & mask) { // space is available so we insert and break (resize is later) if (keyTable[i] == null) { keyTable[i] = key; valueTable[i] = value; break; } } START if (++size >= threshold) { END resize(keyTable.length << 1); } } I think we don't need to check this, as we know that the resize will not result in the threshold being exceeded.

Target:
private void putResize (K key, V value) { K[] keyTable = this.keyTable; V[] valueTable = this.valueTable; for (int i = place(key); ; i = (i + 1) & mask) { // space is available so we insert and break if (keyTable[i] == null) { keyTable[i] = key; valueTable[i] = value; break; } } ++size; }
Source:
protected void onLoad() { enableForm(false); super.onLoad(); Util.PROJECT_SVC.projectDetail(projectName, new GerritCallback<ProjectDetail>() { public void onSuccess(final ProjectDetail result) { enableForm(true); display(result); START addPanel.setVisible(result.canModifyData); END delRight.setVisible(result.canModifyData); } }); } This isn't canModifyData. I think you've overloaded the variable for too many meanings. What we need is: * canModifyDescription * canModifyMergeType * canModifyAgreements * canModifyAccess The first 3 are true only if projectControl.isOwner() is true. The last one is true if projectControl.isOwnerAnyRef() is true, and is what you want to be using here for addPanel.

Target:
protected void onLoad() { enableForm(false); super.onLoad(); Util.PROJECT_SVC.projectDetail(projectName, new GerritCallback<ProjectDetail>() { public void onSuccess(final ProjectDetail result) { enableForm(true); display(result); } }); }
Source:
public static EncodeFormat checkedValueOf(String name) { try { START return Enum.valueOf(EncodeFormat.class, name); END } catch (Exception ex) { VoltDB.crashLocalVoltDB("Illegal encoding format " + name, true, ex); } return null; } Why not use `EncodeFormat.valueOf`

Target:
public static EncodeFormat checkedValueOf(String name) { try { return valueOf(EncodeFormat.class, name); } catch (Exception ex) { VoltDB.crashLocalVoltDB("Illegal encoding format " + name, true, ex); } return null; }
Source:
public Set<K> keySet(Predicate predicate) { checkNotNull(predicate, "Predicate cannot be null!"); Set<K> resultingSet = new HashSet<K>(); Set<QueryableEntry> query = indexes.query(predicate); if (query != null) { for (QueryableEntry entry : query) { START K key = (K) serializationService.toObject(entry.getKeyData()); END resultingSet.add(key); } } else { doFullKeyScan(predicate, resultingSet); } return resultingSet; } Minor: there is a shortcut `toObject()` method for doing the deserialization in this class and in `DefaultQueryCache`. Maybe that should be used to be consistent at all places.

Target:
public Set<K> keySet(Predicate predicate) { checkNotNull(predicate, "Predicate cannot be null!"); Set<K> resultingSet = new HashSet<K>(); Set<QueryableEntry> query = indexes.query(predicate); if (query != null) { for (QueryableEntry entry : query) { K key = toObject(entry.getKeyData()); resultingSet.add(key); } } else { doFullKeyScan(predicate, resultingSet); } return resultingSet; }