auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static Set<String> getRootQualifiers(ResourceTypes resourceTypes) { return resourceTypes.getRoots().stream() .map(ResourceType::getQualifier) START .filter(q -> !DEPRECATED_QUALIFIERS.contains(q)) END .collect(Collectors.toCollection(TreeSet::new)); } I think LIBRARY are no more used

Target:
private static Set<String> getRootQualifiers(ResourceTypes resourceTypes) { return resourceTypes.getRoots().stream() .map(ResourceType::getQualifier) .collect(Collectors.toCollection(TreeSet::new)); }
Source:
public RuntimeFilterManager(QueryWorkUnit workUnit, DrillbitContext drillbitContext) { this.rootWrapper = workUnit.getRootWrapper(); this.drillbitContext = drillbitContext; START lineSeparator = java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("line.separator")); END } Consider using `System.lineSeparator()` instead.

Target:
public RuntimeFilterManager(QueryWorkUnit workUnit, DrillbitContext drillbitContext) { this.rootWrapper = workUnit.getRootWrapper(); this.drillbitContext = drillbitContext; }
Source:
private void activateMarkers() { if (!fGerritClient.getRepository().getServerInfo().isAnonymous()) { String value = NLS.bind(Messages.ChangeDetailEditor_EGerriTipValue, START fChangeInfo.getUserSelectedRevision().get_number()); END UIUtils.showDialogTip(MARKERS_KEY, headerSection.getShell(), Messages.EGerriTip, value); } } ChangeDetailEditor_EGerriTipValue has no more arguments, should we just use it directly , no need to set the arguments ?

Target:
private void activateMarkers() { if (!fGerritClient.getRepository().getServerInfo().isAnonymous()) { UIUtils.showDialogTip(MARKERS_KEY, headerSection.getShell(), Messages.EGerriTip, Messages.ChangeDetailEditor_EGerriTipValue); } }
Source:
public void testCreate() throws StripeException { Map<String, Object> params = new HashMap<String, Object>(); params.put("currency", "usd"); final Order order = Order.create(params); assertNotNull(order); verifyRequest( APIResource.RequestMethod.POST, START "/v1/orders", END params ); } should be called `resource`

Target:
public void testCreate() throws StripeException { final Map<String, Object> params = new HashMap<String, Object>(); params.put("currency", "usd"); final Order order = Order.create(params); assertNotNull(order); verifyRequest( APIResource.RequestMethod.POST, "/v1/orders", params ); }
Source:
private FirewallRule findById(List<FirewallRule> collection, String id) { FirewallRule result = null; for (FirewallRule rule : collection) { if (rule.id().equals(id)) { START result = rule; END } } return result; } Just `return rule`.

Target:
private FirewallRule findById(List<FirewallRule> collection, String id) { for (FirewallRule rule : collection) { if (rule.id().equals(id)) { return rule; } } return null; }
Source:
public void addDownload(String download){ START if(!downloads.contains(download)) { END downloads.add(download); } } Should probably use a Set<String> instead of a List<String> so that the intention of the code is clear by first glance.

Target:
public void addDownload(String download) { downloads.add(download); }
Source:
public void copyDetailsFromOtherCuObjectCodeActivationGlobal(CuObjectCodeActivationGlobal oldGlobal) { for (CuObjectCodeGlobalDetail oldDetail : oldGlobal.getObjectCodeGlobalDetails()) { CuObjectCodeGlobalDetail newDetail = (CuObjectCodeGlobalDetail) ObjectUtils.deepCopy(oldDetail); newDetail.setObjectId(null); newDetail.setDocumentNumber(getDocumentNumber()); START newDetail.setVersionNumber(new Long(0)); END getObjectCodeGlobalDetails().add(newDetail); } } Should this be 1 or null instead of 0?

Target:
public void copyDetailsFromOtherCuObjectCodeActivationGlobal(CuObjectCodeActivationGlobal oldGlobal) { for (CuObjectCodeGlobalDetail oldDetail : oldGlobal.getObjectCodeGlobalDetails()) { CuObjectCodeGlobalDetail newDetail = (CuObjectCodeGlobalDetail) ObjectUtils.deepCopy(oldDetail); newDetail.setObjectId(null); newDetail.setDocumentNumber(getDocumentNumber()); newDetail.setVersionNumber(new Long(1)); getObjectCodeGlobalDetails().add(newDetail); } }
Source:
private void loadVncData(HasConsoleModel model, KeyMaker keyMaker) { if (!(model.getDefaultConsoleModel() instanceof VncConsoleModel)) { return; } model.setSelectedProtocol(ConsoleProtocol.VNC); asVncConsoleModel(model).setVncImplementation(VncConsoleModel.ClientConsoleMode START .valueOf(clientStorage.getLocalItem(keyMaker.make(VNC_CLIENT_MODE)))); END } You can not be sure that the value is present in the local storage (see the storeVncData). Please wrap the ...valueOf(...) by try-catch

Target:
private void loadVncData(HasConsoleModel model, KeyMaker keyMaker) { if (!(model.getDefaultConsoleModel() instanceof VncConsoleModel)) { return; } model.setSelectedProtocol(ConsoleProtocol.VNC); try { asVncConsoleModel(model).setVncImplementation(VncConsoleModel.ClientConsoleMode .valueOf(clientStorage.getLocalItem(keyMaker.make(VNC_CLIENT_MODE)))); } catch (Exception e) { } }
Source:
private RuleApplication applyRule() { SymbolAllocator symbolAllocator = new SymbolAllocator(symbols); Memo memo = new Memo(idAllocator, plan); Lookup lookup = Lookup.from(memo::resolve); Optional<PlanNode> result = inTransaction(session -> rule.apply(memo.getNode(memo.getRootGroup()), lookup, idAllocator, symbolAllocator, session)); START return new RuleApplication( END memo, lookup, symbolAllocator.getTypes(), result); } These arguments can all go on the same line

Target:
private RuleApplication applyRule() { SymbolAllocator symbolAllocator = new SymbolAllocator(symbols); Memo memo = new Memo(idAllocator, plan); Lookup lookup = Lookup.from(memo::resolve); Optional<PlanNode> result = inTransaction(session -> rule.apply(memo.getNode(memo.getRootGroup()), lookup, idAllocator, symbolAllocator, session)); return new RuleApplication(lookup, symbolAllocator.getTypes(), result); }
Source:
public void testPushDownArray() throws Exception { testParquetFilterPushDown("t.`user`.hobby_ids[0] = 1", 3, 2); testParquetFilterPushDown("t.`user`.hobby_ids[0] = 100", 0, 1); START testParquetFilterPushDown("t.`user`.hobby_ids[0] <> 1", 8, 7); END testParquetFilterPushDown("t.`user`.hobby_ids[2] > 20", 5, 4); testParquetFilterPushDown("t.`user`.hobby_ids[0] between 10 and 20", 5, 5); testParquetFilterPushDown("t.`user`.hobby_ids[4] = 15", 1, 3); testParquetFilterPushDown("t.`user`.hobby_ids[2] is not null", 11, 6); testParquetFilterPushDown("t.`user`.hobby_ids[3] is null", 11, 7); } Why the expected output was changed?

Target:
public void testPushDownArray() throws Exception { testParquetFilterPushDown("t.`user`.hobby_ids[0] = 1", 3, 2); testParquetFilterPushDown("t.`user`.hobby_ids[0] = 100", 0, 1); testParquetFilterPushDown("t.`user`.hobby_ids[0] <> 1", 8, 6); testParquetFilterPushDown("t.`user`.hobby_ids[2] > 20", 5, 3); testParquetFilterPushDown("t.`user`.hobby_ids[0] between 10 and 20", 5, 4); testParquetFilterPushDown("t.`user`.hobby_ids[4] = 15", 1, 3); testParquetFilterPushDown("t.`user`.hobby_ids[2] is not null", 11, 6); testParquetFilterPushDown("t.`user`.hobby_ids[3] is null", 11, 7); }
Source:
default Direction getBubbleElevatorDirection() { Block block = this.getBlockState().getBlock(); if (block == Blocks.BUBBLE_COLUMN) { START return this.getBlockState().get(BubbleColumnBlock.DRAG) ? Direction.DOWN : Direction.UP; END } else { return block.getBubbleElevatorDirection(this.getBlockState()); } } This logic should be in the default implementation.

Target:
default Direction getBubbleElevatorDirection() { return this.getBlockState().getBlock().getBubbleElevatorDirection(this.getBlockState()); }
Source:
public void testSystemPropertiesOverrideConfigurationValues() { final String keyName = CoreConfig.MAX_CASSANDRA_CONNECTIONS.toString(); Configuration config = Configuration.getInstance(); try { Assert.assertEquals("75", config.getStringProperty(CoreConfig.MAX_CASSANDRA_CONNECTIONS)); System.setProperty(keyName, "something else"); Assert.assertEquals("something else", config.getStringProperty(CoreConfig.MAX_CASSANDRA_CONNECTIONS)); } finally { System.clearProperty(keyName); START Configuration.clearProperty(keyName); END } } Why access this method staticly?

Target:
public void testSystemPropertiesOverrideConfigurationValues() { final String keyName = CoreConfig.MAX_CASSANDRA_CONNECTIONS.toString(); Configuration config = Configuration.getInstance(); try { Assert.assertEquals("75", config.getStringProperty(CoreConfig.MAX_CASSANDRA_CONNECTIONS)); System.setProperty(keyName, "something else"); Assert.assertEquals("something else", config.getStringProperty(CoreConfig.MAX_CASSANDRA_CONNECTIONS)); } finally { System.clearProperty(keyName); config.clearProperty(keyName); } }
Source:
public void onSubscribe(Subscription inner) { START SubscriptionHelper.setOnce(this, inner); END o.onSubscribe(this); inner.request(Long.MAX_VALUE); } You can set it on a plain field, no need for atomics: ``` java this.inner = inner; o.onSubscribe(this); inner.request(Long.MAX_VALUE); ```

Target:
public void onSubscribe(Subscription inner) { this.inner = inner; o.onSubscribe(this); inner.request(Long.MAX_VALUE); }
Source:
public WebElement forElementPresent(By by) { changeImplicitWait(250, TimeUnit.MILLISECONDS); try { return wait.until(ExpectedConditions.presenceOfElementLocated(by)); } catch(TimeoutException e) { PageObjectLogging.log( ELEMENT_PRESENT_MESSAGE, String.format(ELEMENT_PRESENT_ERROR_FORMAT, by.toString()), START true END ); throw e; } finally { restoreDeaultImplicitWait(); } } `true` -> `false` ?

Target:
public WebElement forElementPresent(By by) { changeImplicitWait(250, TimeUnit.MILLISECONDS); try { return wait.until(ExpectedConditions.presenceOfElementLocated(by)); } catch(TimeoutException e) { PageObjectLogging.log( ELEMENT_PRESENT_MESSAGE, String.format(ELEMENT_PRESENT_ERROR_FORMAT, by.toString()), false ); throw e; } finally { restoreDeaultImplicitWait(); } }
Source:
public boolean accept(Issue issue) { START if (issueShouldNotBeReported(issue, excludedLinesByRule())) { END return false; } return true; } could be simplified.

Target:
public boolean accept(Issue issue) { return !issueShouldNotBeReported(issue, excludedLinesByRule()); }
Source:
START public HashMap<String, END ArrayList<Order>> getBuyOrders() { return buyOrders; } this method should be changed to private

Target:
private HashMap<String, ArrayList<Order>> getBuyOrders() { return buyOrders; }
Source:
START public static END Color getSystemForegroundColor(Display display) { ColorRegistry colorRegistry = JFaceResources.getColorRegistry(); Color foreground = colorRegistry.get(JFacePreferences.INFORMATION_FOREGROUND_COLOR); if (foreground == null) { return JFaceColors.getInformationViewerForegroundColor(display); } return foreground; } There's no need to make these public, even if the package is internal.

Target:
private static Color getSystemForegroundColor(Display display) { ColorRegistry colorRegistry = JFaceResources.getColorRegistry(); Color foreground = colorRegistry.get(JFacePreferences.INFORMATION_FOREGROUND_COLOR); if (foreground == null) { return JFaceColors.getInformationViewerForegroundColor(display); } return foreground; }
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } SwitchStatementTree switchStatementTree = (SwitchStatementTree) tree; START Optional<CaseLabelTree> defaultLabel = getDefaultLabel(switchStatementTree); END if (!defaultLabel.isPresent()) { if (!isSwitchOnEnum(switchStatementTree)) { reportIssue(switchStatementTree.switchKeyword(), "Add a default case to this switch."); } else if (missingCasesOfEnum(switchStatementTree)) { reportIssue(switchStatementTree.switchKeyword(), "Complete cases by adding the missing enum constants or add a default case to this switch."); } } } You should go one step more in simplifying the rule: Change this method to return a boolean: `hasNoDefault(switchStatementTree)` ``` return allLabels(switchStatementTree).noneMatch(SwitchLastCaseIsDefaultCheck::isDefault); ```

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } SwitchStatementTree switchStatementTree = (SwitchStatementTree) tree; if (getDefaultLabel(switchStatementTree)) { if (!isSwitchOnEnum(switchStatementTree)) { reportIssue(switchStatementTree.switchKeyword(), "Add a default case to this switch."); } else if (missingCasesOfEnum(switchStatementTree)) { reportIssue(switchStatementTree.switchKeyword(), "Complete cases by adding the missing enum constants or add a default case to this switch."); } } }
Source:
START public String getAttribute() { END if (fAttribute.equals(NOT_SET)) { setAttribute(); } return fAttribute; } This method should be synchronized, otherwise, chances are eventually there might be a race condition for setting fAttribute.

Target:
public synchronized String getAttribute() { if (fAttribute.equals(NOT_SET)) { setAttribute(); } return fAttribute; }
Source:
public DotRunnableThread(final List<DotRunnable> allListeners) { this.listeners = getListeners(allListeners); this.flushers = getFlushers(allListeners); START this.networkCacheFlushThread.start(); END } ![BLOCKER](https://sonarsource.github.io/sonar-github/severity-blocker.png 'Severity: BLOCKER') Move this "start" call to another method. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS2693)

Target:
public DotRunnableThread(final List<DotRunnable> allListeners) { this.listeners = getListeners(allListeners); this.flushers = getFlushers(allListeners); }
Source:
private void createIndex() { lastFoundElementPosition = 0; filteredPlan.clear(); for (PlanElement element : plan.getList()) { START if (!element.isComment()) { END filteredPlan.add(element); } } } style nit: no braces around single line blocks

Target:
private void createIndex() { lastFoundElementPosition = 0; filteredPlan.clear(); for (PlanElement element : plan.getList()) { if (!element.isComment()) filteredPlan.add(element); } }
Source:
public Collection<Map.Entry<K, V>> scanAndFilterByEntry( Predicate<? super Map.Entry<K, V>> entryPredicate) { START return mainMap.entryStream().parallel() END .filter(entryPredicate) .collect(Collectors.toCollection(ArrayList::new)); } is there a difference between parallelStream() and entryStream().parallel() ?

Target:
public Collection<Map.Entry<K, V>> scanAndFilterByEntry( Predicate<? super Map.Entry<K, V>> entryPredicate) { return mainMap.entryStream() .filter(entryPredicate) .collect(Collectors.toCollection(ArrayList::new)); }
Source:
START protected boolean isValidChar(final char c) { END return isValidChar(regExp, c); } can be `private`? or at least package protected access?

Target:
private boolean isValidChar(final char c) { return isValidChar(regExp, c); }
Source:
public boolean verifyEventIdentifier(AbstractPlaceEvent event) { boolean equals = Objects.equals(getEditorIdentifier(), event.getPlace().getIdentifier()); boolean equals1 = Objects.equals(editorPlaceRequest, event.getPlace()); return (equals && START equals1); END } Toni, could we please choose better variable names here? `equals` and `equals1` do not say much for newcomer to the codebase. Or we could avoid storing partial results by: ```java if(!Objects.equals(editorPlaceRequest, event.getPlace())) { return false; } if (!Objects.equals(getEditorIdentifier(), event.getPlace().getIdentifier())) { return false; } return true; ``` Please let me know what do you think.

Target:
public boolean verifyEventIdentifier(AbstractPlaceEvent event) { return (Objects.equals(getEditorIdentifier(), event.getPlace().getIdentifier()) && Objects.equals(editorPlaceRequest, event.getPlace())); }
Source:
public void star() throws IOException { this.entry.uri() START .path(RtGist.PATH_ELEMENT_STAR).back().method("PUT") END .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_NO_CONTENT); } It's an obvious code duplication. We can save this new request with a modified URI into `this.request`, and use it in all methods. This is how it works in other classes, take a look

Target:
public void star() throws IOException { this.request.method("PUT") .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_NO_CONTENT); }
Source:
public IssueOutputView(Issue issue) { START this(issue, null, null); END } What is the need to make `issueArticles` nullable? It would be easier to understand this view class if we required it. If that's totally impractical, we should consider having a separate view class to capture the difference.

Target:
public IssueOutputView(Issue issue) { this(issue, null); }
Source:
START public ProcessEngineConfiguration setDefaultNumberOfRetries(int defaultNumberOfRetries) { END this.defaultNumberOfRetries = defaultNumberOfRetries; return this; } not 100% sure, but this breaks binary compatibility, right?

Target:
public void setDefaultNumberOfRetries(int defaultNumberOfRetries) { this.defaultNumberOfRetries = defaultNumberOfRetries; }
Source:
START public void testSequenceFlowSupplier() throws Exception { END final CaseManagementSetChildNodeGraphCommand command = new CaseManagementSetChildNodeGraphCommand(parent, candidate, index, originalParent, originalIndex); final Supplier<ViewConnector<SequenceFlow>> supplier = command.sequenceFlowSupplier(); final ViewConnector<SequenceFlow> viewConnector = supplier.get(); assertNotNull(viewConnector); assertNotNull(viewConnector.getSourceConnection()); assertNotNull(viewConnector.getTargetConnection()); assertNotNull(viewConnector.getBounds()); assertNotNull(viewConnector.getDefinition()); } The Exception is never thrown.

Target:
public void testSequenceFlowSupplier() { final CaseManagementSetChildNodeGraphCommand command = new CaseManagementSetChildNodeGraphCommand(parent, candidate, index, originalParent, originalIndex); final Supplier<ViewConnector<SequenceFlow>> supplier = command.sequenceFlowSupplier(); final ViewConnector<SequenceFlow> viewConnector = supplier.get(); assertNotNull(viewConnector); assertNotNull(viewConnector.getSourceConnection()); assertNotNull(viewConnector.getTargetConnection()); assertNotNull(viewConnector.getBounds()); assertNotNull(viewConnector.getDefinition()); }
Source:
public long getSessionSeqId() { if (sessionSeqId == null) { START sessionSeqId = -1L; END String sessionId = getContext().getEngineContext().getSessionId(); // The session may not exists for quartz jobs if (getSessionDataContainer().isSessionExists(sessionId)) { sessionSeqId = getSessionDataContainer().getEngineSessionSeqId(sessionId); } } return sessionSeqId; } instead of an early assignment which might be overridden in line 2355, it can be set as the 'else' part of the if statement below (line 2356).

Target:
public long getSessionSeqId() { if (sessionSeqId == null) { String sessionId = getContext().getEngineContext().getSessionId(); // The session may not exists for quartz jobs sessionSeqId = getSessionDataContainer().isSessionExists(sessionId) ? getSessionDataContainer().getEngineSessionSeqId(sessionId) : -1L; } return sessionSeqId; }
Source:
private boolean isTxnRelatedEvent(final NotificationEvent event) { return ((event.getEventType().equals(MessageFactory.OPEN_TXN_EVENT)) || (event.getEventType().equals(MessageFactory.COMMIT_TXN_EVENT)) || (event.getEventType().equals(MessageFactory.ABORT_TXN_EVENT)) || START (event.getEventType().equals(MessageFactory.ALLOC_WRITE_ID_EVENT)) END ); } Allocate write ID is a DB/table related event and should be ignored if not lookup on this DB/table.

Target:
private boolean isTxnRelatedEvent(final NotificationEvent event) { return ((event.getEventType().equals(MessageFactory.OPEN_TXN_EVENT)) || (event.getEventType().equals(MessageFactory.COMMIT_TXN_EVENT)) || (event.getEventType().equals(MessageFactory.ABORT_TXN_EVENT))); }
Source:
public static void setBackground(boolean async) { background = async; START } END Can't we have this static flag on FS instead? Then we wouldn't need to make FileStoreAttributeCache public.

Target:
private static void setBackground(boolean async) { background.set(async); }
Source:
public V put(@NonNull K key, @NonNull V value) { map.put(key, new Entry<>(key, value, ++time)); START if (map.size() >= maximumSize) { END purge(); } return value; } For a small maximuSize, like 1, it may be more reasonable to check for: map.size() > maximumSize

Target:
public V put(@NonNull K key, @NonNull V value) { map.put(key, new Entry<>(key, value, ++time)); if (map.size() > maximumSize) { purge(); } return value; }
Source:
private static void setIfNotNullOrEmpty( MongoProperties.Builder builder, MongoProp prop, String value ) { if ( value != null && value.trim().length() > 0 ) { boolean isPassword = MongoProp.PASSWORD.equals( prop ); START boolean isEncrypted = value.startsWith( Encr.PASSWORD_ENCRYPTED_PREFIX ); END if ( isPassword && isEncrypted ) { value = Encr.decryptPasswordOptionallyEncrypted( value ); } builder.set( prop, value ); } } Shouldn't do this line - it's handled by the ...Optionally... bit in the Encr class. https://github.com/pentaho/pentaho-kettle/blob/master/core/src/org/pentaho/di/core/encryption/KettleTwoWayPasswordEncoder.java#L86-L91

Target:
private static void setIfNotNullOrEmpty( MongoProperties.Builder builder, MongoProp prop, String value ) { if ( value != null && value.trim().length() > 0 ) { boolean isPassword = MongoProp.PASSWORD.equals( prop ); if ( isPassword ) { value = Encr.decryptPasswordOptionallyEncrypted( value ); } builder.set( prop, value ); } }
Source:
public Mutation toMutation(K key) { START V valueFromStorage = (V) valueDataConversion.fromStorage(value); END return new Mutations.ReadWriteWithValue<>(valueFromStorage, f); } One use/test case is, a non-serializable pojo (user type) that is encoded as a UTF-8 byte[ ] with some string representation of it.

Target:
public Mutation toMutation(K key) { return new Mutations.ReadWriteWithValue<>(value, f); }
Source:
START public Entry(Map.Entry<String,String> e) { END this(e.getKey(), e.getValue()); } IMHO it does not need to be public

Target:
private Entry(Map.Entry<String,String> e) { this(e.getKey(), e.getValue()); }
Source:
private String parsePath() throws URISyntaxException { String[] parts = uri.split("\\?")[0].split(":", 2); START if (parts.length < 2 || parts[1].length() < 1) throw new URISyntaxException(uri, "invalid path"); END else return parts[1]; } parts[1].isEmpty

Target:
private String parsePath() throws URISyntaxException { String[] parts = uri.split("\\?")[0].split(":", 2); if (parts.length < 2 || parts[1].isEmpty()) throw new URISyntaxException(uri, "invalid path"); else return parts[1]; }
Source:
public void setItems(Collection value) { genVersionToBaseTemplate(value); START final List<VmTemplate> sortedValues = sortTemplates(value); END super.setItems(sortedValues); } this will affect the sorting also on the webadmin - but on webadmin we support sortable columns. Please move this logic to UserPortalTemplateListModel.

Target:
public void setItems(Collection value) { genVersionToBaseTemplate(value); super.setItems(value); }
Source:
public void edit(VolumeBrickModel object) { START table.setRowData(new ArrayList<ListModel>()); END table.edit(object.getBricks()); Driver.driver.edit(object); } why you need this line? table.setRowData(new ArrayList<ListModel>());

Target:
public void edit(VolumeBrickModel object) { table.edit(object.getBricks()); Driver.driver.edit(object); }
Source:
public List<QuickFilter> getQuickFilters() { START return this.quickFilters; END } `return quickFilters`

Target:
public List<QuickFilter> getQuickFilters() { return quickFilters; }
Source:
public void testBounds() { int low = fCondition.min(); START assertEquals(LOW, low); END int high = fCondition.max(); assertEquals(HIGH, high); } why not directly assertEquals(LOW, fCondition.min()); ?

Target:
public void testBounds() { assertEquals(LOW, (int) fCondition.min()); assertEquals(HIGH, (int) fCondition.max()); }
Source:
public String weather() { START String result = this.restTemplate.getForObject("http://" + WEATHER_SERVICE + "/weather", String.class); END return "Weather Service Response: " + result; } `this` is redundant here.

Target:
public String weather() { String result = restTemplate.getForObject("http://" + WEATHER_SERVICE + "/weather", String.class); return "Weather Service Response: " + result; }
Source:
public boolean isExtensionEnabled() { if (enablement != null) { try { START return enablement.getExpression().evaluate(new EvaluationContext(null, new Object())) END .equals(EvaluationResult.TRUE); } catch (CoreException e) { // TODO: handle exception } } return true; } Let's move this into an EnablementTester.evaluate(...) method.

Target:
public boolean isExtensionEnabled() { return enablement != null ? enablement.evaluate() : true; }
Source:
public ProviderNotificationManager createProviderNotificationManager(final DiagramEventBroker diagramEventBroker, final EObject view, final NotificationListener notificationListener) { START if (manager != null) { END return manager; } manager = new ProviderNotificationManager(diagramEventBroker, view, notificationListener) { @Override protected void registerListeners() { // TODO install listener on allocation(Abstraction) of the model. } }; return manager; } 'null' must be first operande

Target:
public ProviderNotificationManager createProviderNotificationManager(final DiagramEventBroker diagramEventBroker, final EObject view, final NotificationListener notificationListener) { if (null != manager) { return manager; } manager = new ProviderNotificationManager(diagramEventBroker, view, notificationListener) { @Override protected void registerListeners() { // TODO install listener on allocation(Abstraction) of the model. } }; return manager; }
Source:
START public void startSyncFolderOperation(OCFile folder) { END long currentSyncTime = System.currentTimeMillis(); mSyncInProgress = true; // perform folder synchronization RemoteOperation synchFolderOp = new RefreshFolderOperation( folder, currentSyncTime, false, false, false, getStorageManager(), getAccount(), getApplicationContext() ); synchFolderOp.execute(getAccount(), this, null, null); } This method can be`private`.

Target:
private void startSyncFolderOperation(OCFile folder) { long currentSyncTime = System.currentTimeMillis(); mSyncInProgress = true; // perform folder synchronization RemoteOperation synchFolderOp = new RefreshFolderOperation( folder, currentSyncTime, false, false, false, getStorageManager(), getAccount(), getApplicationContext() ); synchFolderOp.execute(getAccount(), this, null, null); }
Source:
START public static ProtobufMetadataManagerImpl getProtobufMetadataManager(EmbeddedCacheManager cacheManager) { END if (cacheManager == null) { throw new IllegalArgumentException("cacheManager cannot be null"); } ProtobufMetadataManagerImpl metadataManager = (ProtobufMetadataManagerImpl) cacheManager.getGlobalComponentRegistry().getComponent(ProtobufMetadataManager.class); if (metadataManager == null) { throw new IllegalStateException("ProtobufMetadataManager not initialised yet!"); } return metadataManager; } This can be private again.

Target:
private static ProtobufMetadataManagerImpl getProtobufMetadataManager(EmbeddedCacheManager cacheManager) { if (cacheManager == null) { throw new IllegalArgumentException("cacheManager cannot be null"); } ProtobufMetadataManagerImpl metadataManager = (ProtobufMetadataManagerImpl) cacheManager.getGlobalComponentRegistry().getComponent(ProtobufMetadataManager.class); if (metadataManager == null) { throw new IllegalStateException("ProtobufMetadataManager not initialised yet!"); } return metadataManager; }
Source:
public void onSessionKeyUpdate(SessionKey sessionKey) { START log.info("Session key updated"); END synchronized (DistributedHerder.this) { DistributedHerder.this.sessionKey = sessionKey.key(); if (isLeader() && keyRotationIntervalMs > 0) { DistributedHerder.this.keyExpiration = sessionKey.creationTimestamp() + keyRotationIntervalMs; } } } Should this log message be before or after we actually do update the session key?

Target:
public void onSessionKeyUpdate(SessionKey sessionKey) { log.info("Session key updated"); synchronized (DistributedHerder.this) { DistributedHerder.this.sessionKey = sessionKey.key(); // Track the expiration of the key if and only if this worker is the leader // Followers will receive rotated keys from the follower and won't be responsible for // tracking expiration and distributing new keys themselves if (isLeader() && keyRotationIntervalMs > 0) { DistributedHerder.this.keyExpiration = sessionKey.creationTimestamp() + keyRotationIntervalMs; } } }
Source:
public String getAuthorizationUrl(OAuthConfig config) { START System.out.print("Authorisation URL: "); END // User must provide these 5 elements to the service builder String url = String.format(AUTHORIZE_URL, OAuthEncoder.encode(config.getApiKey()), OAuthEncoder.encode(config.getCallback()), OAuthEncoder.encode(config.getScope()), OAuthEncoder.encode(config.getState())); return url; } forgotten line of code?

Target:
public String getAuthorizationUrl(OAuthConfig config) { // User must provide these 4 elements to the service builder String url = String.format(AUTHORIZE_URL, OAuthEncoder.encode(config.getApiKey()), OAuthEncoder.encode(config.getCallback()), OAuthEncoder.encode(config.getScope()), OAuthEncoder.encode(config.getState())); return url; }
Source:
public Object getParameter(String name) { START final HostThread currentHostThread = fCurrentHostThread; END if (currentHostThread == null) { return null; } if (name.equals(CriticalPathModule.PARAM_WORKER)) { /* Try to find the worker for the critical path */ IAnalysisModule mod = getModule(); if ((mod != null) && (mod instanceof CriticalPathModule)) { LttngWorker worker = new LttngWorker(currentHostThread, "", 0); //$NON-NLS-1$ return worker; } return currentHostThread; } return null; } This code here should be inside the if, because we don't need to do anything if the parameter request is not PARAM_WORKER

Target:
public Object getParameter(String name) { if (name.equals(CriticalPathModule.PARAM_WORKER)) { final HostThread currentHostThread = fCurrentHostThread; if (currentHostThread == null) { return null; } /* Try to find the worker for the critical path */ IAnalysisModule mod = getModule(); if ((mod != null) && (mod instanceof CriticalPathModule)) { LttngWorker worker = new LttngWorker(currentHostThread, "", 0); //$NON-NLS-1$ return worker; } return currentHostThread; } return null; }
Source:
public static ExceptionThrowingSubTest expectThrowable(Runnable runnable) { START return expectException( runnable.toString(), runnable ); END } Maybe `expectThrowable` for consistency?

Target:
public static ExceptionThrowingSubTest expectThrowable(Runnable runnable) { return expectThrowable( runnable.toString(), runnable ); }
Source:
protected CONNECTCXFClient(ServicePortDescriptor<T> portDescriptor, String url, AssertionType assertion, ServicePortBuilder<T> portBuilder) { serviceEndpoint = super.configureBasePort(portBuilder.createPort(), url, assertion != null ? assertion.getTransactionTimeout() : null); START configCNCheck(); END } remove this

Target:
protected CONNECTCXFClient(ServicePortDescriptor<T> portDescriptor, String url, AssertionType assertion, ServicePortBuilder<T> portBuilder) { serviceEndpoint = super.configureBasePort(portBuilder.createPort(), url, assertion != null ? assertion.getTransactionTimeout() : null); }
Source:
public <V> Setting<V> get(SimpleUri id, Class<V> valueType) { Setting setting = settings.get(id); Class settingValueClass = setting.getValueClass(); if (!settingValueClass.equals(valueType)) { throw new ClassCastException( "Expected a Setting of type " + valueType.getName() + ", found a Setting of type " + settingValueClass.getName() START ); END } return (Setting<V>) setting; } Can we add the name of the setting in there somewhere as well?

Target:
public <V> Setting<V> get(SimpleUri id, Class<V> valueType) { Setting setting = settings.get(id); if (setting == null) { return null; } Class settingValueClass = setting.getValueClass(); if (!settingValueClass.equals(valueType)) { throw new ClassCastException( "Expected a Setting of type " + valueType.getName() + ", found a Setting of type " + settingValueClass.getName() ); } return (Setting<V>) setting; }
Source:
public String getCustomField(String fieldName) { START if(customFields == null) return null; END for (CustomField f : customFields) { if (f.getName().equals(fieldName)) { return f.getValue(); } } return null; } it's better to init customFields with an empty collection to avoid "==null"

Target:
public String getCustomField(String fieldName) { for (CustomField f : customFields) { if (f.getName().equals(fieldName)) { return f.getValue(); } } return null; }
Source:
private CommandCall duplicateCommandForDifferentElement(CommandCall commandCall, Element element) { String expression = commandCall.getExpression(); START if (expression.equals("")) { END expression = element.getText(); } return new CommandCall(null, commandCall.getCommand(), element, expression, commandCall.getResource()); } Any way we can clean this up? It seems to only be needed for example commands, but hard to check what the command is here since it's wrapped in decorators.

Target:
private CommandCall duplicateCommandForDifferentElement(CommandCall commandCall, Element element) { return new CommandCall( null, commandCall.getCommand(), element, commandCall.getExpression(), commandCall.getResource()); }
Source:
public M fromBytes(byte[] messageBuffer) { if (deserializer == null) deserializer = new ThriftBinaryDeserializer(); try { M message = typeRef.safeNewInstance(); deserializer.deserialize(message, messageBuffer); return message; } catch (TException e) { logWarning("failed to deserialize", e); return null; START } catch (Throwable e) { END // Arbitrary bytes can cause a runtime exception in Thrift logWarning("failed to deserialize", e); return null; } } TException is throwable, too, and treated the same -- combine the catch clauses?

Target:
public M fromBytes(byte[] messageBuffer) { if (deserializer == null) deserializer = new ThriftBinaryDeserializer(); try { M message = typeRef.safeNewInstance(); deserializer.deserialize(message, messageBuffer); return message; } catch (Throwable e) { // normally a TException. but some corrupt records can cause // other runtime exceptions (e.g. IndexOutOfBoundsException). logWarning("failed to deserialize", e); return null; } }
Source:
public void showPage(Control page) { if (page.isDisposed() || page.getParent() != this) { return; } currentPage = page; // show new page page.setVisible(true); layout(true); // hide old (and all others) *after* new page has been made visible in // order to avoid flashing Control[] children = getChildren(); for (Control element : children) { START Control child = element; END if (child != page && !child.isDisposed()) { child.setVisible(false); } } } remove

Target:
public void showPage(Control page) { if (page.isDisposed() || page.getParent() != this) { return; } currentPage = page; // show new page page.setVisible(true); layout(true); // hide old (and all others) *after* new page has been made visible in // order to avoid flashing for (Control child : getChildren()) { if (child != page && !child.isDisposed()) { child.setVisible(false); } } }
Source:
public void info(String message, Object... objects) { START LOG.warn(message, objects); END } info vs warn

Target:
public void info(String message, Object... objects) { LOG.info(message, objects); }
Source:
public String getLinkAt(int offset) { // Check if there is a link at the offset for (int i = 0; i < linkRanges.size(); i++) { if (linkRanges.get(i).isOffsetInRange(offset)) { return hrefs.get(i); } } START return null; END } Let's avoid `null` and rework to empty string

Target:
public Optional<String> getLinkAt(int offset) { // Check if there is a link at the offset for (int i = 0; i < linkRanges.size(); i++) { if (linkRanges.get(i).contains(offset)) { return Optional.of(hrefs.get(i)); } } return Optional.empty(); }
Source:
public String toString() { readLock.lock(); try { START return "FileListCacheValue{fileNames=" + getFileNames() + "}"; END } finally { readLock.unlock(); } } This change I requested was supposed to remove the need for a read lock

Target:
public String toString() { return "FileListCacheValue{fileNames=" + getFileNames() + "}"; }
Source:
protected Control createControl(Composite parent) { // Configure table CTConfiguration config = new CTConfiguration(parent, CTConfiguration.STYLE_GRID); config.setHorizontalAlignment(SWT.CENTER); config.setCellSelectionEnabled(false); config.setColumnSelectionEnabled(false); config.setRowSelectionEnabled(false); config.setColumnHeaderLayout(CTConfiguration.COLUMN_HEADER_LAYOUT_FILL_EQUAL); config.setRowHeaderLayout(CTConfiguration.ROW_HEADER_LAYOUT_DEFAULT); START this.table = new ComponentTable(parent, SWT.FULL_SELECTION, config); END return this.table.getControl(); } Please not here. This is not a standard SWT table.

Target:
protected Control createControl(Composite parent) { // Configure table CTConfiguration config = new CTConfiguration(parent, CTConfiguration.STYLE_GRID); config.setHorizontalAlignment(SWT.CENTER); config.setCellSelectionEnabled(false); config.setColumnSelectionEnabled(false); config.setRowSelectionEnabled(false); config.setColumnHeaderLayout(CTConfiguration.COLUMN_HEADER_LAYOUT_FILL_EQUAL); config.setRowHeaderLayout(CTConfiguration.ROW_HEADER_LAYOUT_DEFAULT); this.table = new ComponentTable(parent, SWT.NONE, config); return this.table.getControl(); }
Source:
public boolean isEnabled() { return START getActiveTextEditor() != null; END } return 'true'

Target:
public boolean isEnabled() { return true; }
Source:
void verifyMetadata(MessageMetadata metadata) throws Exception { if (metadata.getMessageMetadataType() != MessageType.LOG_ENTRY_MESSAGE || metadata.getSnapshotTimestamp() != srcGlobalSnapshot) { log.error("Wrong message metadata {}, expecting type snapshot {}", metadata, MessageType.LOG_ENTRY_MESSAGE, srcGlobalSnapshot); START throw new Exception("wrong type of message"); END } } maybe you need a specific Exception Type

Target:
void verifyMetadata(MessageMetadata metadata) throws Exception { if (metadata.getMessageMetadataType() != MessageType.LOG_ENTRY_MESSAGE) { log.error("Wrong message metadata {}, expecting type snapshot {}", metadata, MessageType.LOG_ENTRY_MESSAGE, srcGlobalSnapshot); throw new Exception("wrong type of message"); } }
Source:
public void setVmBackup(VmBackup value) { START vmBackup = value; END } This is a bug, the setter does nothing, use 'this'

Target:
public void setVmBackup(VmBackup value) { this.vmBackup = value; }
Source:
public void setPrice1(int price3) { if (price3 < 0 || price3 > 10000) { START throw new IllegalArgumentException("Invalid price: " + price3); // Compliant END } if (true) { assert price3 > 1000; // Noncompliant } } what is this part for? you are not checking throw statements.

Target:
public void setPrice1(int price3) { if (true) { assert price3 > 1000; // Noncompliant } }
Source:
public String evaluate(TransactionContext txnCtx, Input<Object>[] args) { assert args.length == 2 : "repeat takes exactly two arguments"; var text = (String) args[0].value(); if (text == null) { return null; } START var repetitions = (int) args[1].value(); END if (repetitions <= 0) { return ""; } else { return text.repeat(repetitions); } } This will fail on `null`

Target:
public String evaluate(TransactionContext txnCtx, Input<Object>[] args) { assert args.length == 2 : "repeat takes exactly two arguments"; var text = (String) args[0].value(); var repetitions = (Integer) args[1].value(); if (text == null || repetitions == null) { return null; } if (repetitions <= 0) { return ""; } else { return text.repeat(repetitions); } }
Source:
START public void setActionBarNotificationBarColor(MaterialColor color) { END getSupportActionBar().setBackgroundDrawable(new ColorDrawable(color.toActionBarColor(this))); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(color.toStatusBarColor(this)); } } why is this public?

Target:
private void setActionBarNotificationBarColor(MaterialColor color) { getSupportActionBar().setBackgroundDrawable(new ColorDrawable(color.toActionBarColor(this))); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(color.toStatusBarColor(this)); } }
Source:
public static ProjectBuildType getProjectType(IProject project) { // ------------ AUTOTOOLS // Autotools has an 'Autotools' nature by which we can identify it. START if (isAutoTools(project)) END return ProjectBuildType.AUTO_TOOLS; IConfiguration defaultConfiguration = helper_getActiveConfiguration(project); IBuilder builder = defaultConfiguration.getBuilder(); Boolean projIsManaged = builder.isManagedBuildOn(); if (projIsManaged) return ProjectBuildType.MANAGED_MAKEFILE; else return ProjectBuildType.OTHER; //E.g a manual makefile. } Please use for every if/else/for/etc. block.

Target:
public static ProjectBuildType getProjectType(IProject project) { // ---------- AUTOTOOLS // Autotools has an 'Autotools' nature by which we can identify it. if (isAutoTools(project)) { return ProjectBuildType.AUTO_TOOLS; } IConfiguration defaultConfiguration = helper_getActiveConfiguration(project); IBuilder builder = defaultConfiguration.getBuilder(); Boolean projIsManaged = builder.isManagedBuildOn(); // ---------- MANAGED PROJECT if (projIsManaged) { return ProjectBuildType.MANAGED_MAKEFILE; } else { return ProjectBuildType.OTHER; //E.g a manual makefile. } }
Source:
protected long download(T object, File outFile) throws IOException { try { openObjectFunction.open(object, outFile); } START catch (IOException e) { END throw new RuntimeException(e); } return outFile.length(); } This isn't necessary.

Target:
protected long download(T object, File outFile) throws IOException { openObjectFunction.open(object, outFile); return outFile.length(); }
Source:
private Collection<VCastResult> getResultFiles(VCastDataStore dataStore) { Collection<VCastResult> results = null; try { results = dataStore.getAllResults(); } catch (OseeCoreException ex) { START throw new OseeCoreException(ex, "SQL error while reading results"); END } return results; } what's the point of catching and then throwing the same exception type?

Target:
private Collection<VCastResult> getResultFiles(VCastDataStore dataStore) { Collection<VCastResult> results = null; results = dataStore.getAllResults(); return results; }
Source:
public PinotQueryGeneratorContext visitFilter(FilterNode node, PinotQueryGeneratorContext context) START { END context = node.getSource().accept(this, context); requireNonNull(context, "context is null"); LinkedHashMap<VariableReferenceExpression, Selection> selections = context.getSelections(); String filter = node.getPredicate().accept(pinotFilterExpressionConverter, (var) -> selections.get(var)).getDefinition(); return context.withFilter(filter).withOutputColumns(node.getOutputVariables()); } public

Target:
public PinotQueryGeneratorContext visitFilter(FilterNode node, PinotQueryGeneratorContext context) { context = node.getSource().accept(this, context); requireNonNull(context, "context is null"); LinkedHashMap<VariableReferenceExpression, Selection> selections = context.getSelections(); String filter = node.getPredicate().accept(pinotFilterExpressionConverter, selections::get).getDefinition(); return context.withFilter(filter).withOutputColumns(node.getOutputVariables()); }
Source:
START private Space(String enumeratedValue) { END this.enumeratedValue = enumeratedValue; } JavaDoc and method signature did not match. Please update the JavaDoc!

Target:
Space(String enumeratedValue) { this.enumeratedValue = enumeratedValue; }
Source:
public Guid getStorageDomainIdForPoolByType(Guid pool, StorageDomainType type) { Guid returnValue = Guid.Empty; List<storage_domains> domains = getAllForStoragePool(pool); for (storage_domains domain : domains) { START if (domain.getstorage_domain_type() == StorageDomainType.Master) { END returnValue = domain.getId(); break; } } return returnValue; } still requires fix: domain.getstorage_domain_type() == type

Target:
public Guid getStorageDomainIdForPoolByType(Guid pool, StorageDomainType type) { Guid returnValue = Guid.Empty; List<storage_domains> domains = getAllForStoragePool(pool); for (storage_domains domain : domains) { if (domain.getstorage_domain_type() == type) { returnValue = domain.getId(); break; } } return returnValue; }
Source:
public void lock(T id) throws InterruptedException { START threadsLocked.inc(); END idsLocked.update(1); lockInternal(id); threadsLocked.dec(); } For this it's better to do: ``` threadsLocked.inc(); try { // other stuff } finally { threadsLocked.dec(); } ``` This way if an exception is thrown we still decrement the threadsLocked counter.

Target:
public void lock(T id) throws InterruptedException { threadsLocked.inc(); try { idsLocked.update(1); lockInternal(id); } finally { threadsLocked.dec(); } }
Source:
public RunLengthEncodedBlock(Block value, int positionCount) { requireNonNull(value, "value is null"); if (value.getPositionCount() != 1) { throw new IllegalArgumentException(format("Expected value to contain a single position but has %s positions", value.getPositionCount())); } // value can not be a RunLengthEncodedBlock because this could cause stack overflow in some of the methods if (value instanceof RunLengthEncodedBlock) { throw new IllegalArgumentException(format("Value can not be an instance of a %s", getClass().getName())); } if (positionCount < 0) { throw new IllegalArgumentException("positionCount is negative"); } START this.value = value END this.positionCount = positionCount; } looks like syntax typo (`Add position checks in RunLenghtEncodedBlock` commit)

Target:
public RunLengthEncodedBlock(Block value, int positionCount) { requireNonNull(value, "value is null"); if (value.getPositionCount() != 1) { throw new IllegalArgumentException(format("Expected value to contain a single position but has %s positions", value.getPositionCount())); } if (value instanceof RunLengthEncodedBlock) { this.value = ((RunLengthEncodedBlock) value).getValue(); } else { this.value = value; } if (positionCount < 0) { throw new IllegalArgumentException("positionCount is negative"); } this.positionCount = positionCount; }
Source:
public Message.Request request() { START Message.Request request = callback.request(); END if (retryConsistencyLevel != null && retryConsistencyLevel != request.consistency()) return request.copy(retryConsistencyLevel); else return request; } Is the idea to always copy because the request could be used again in a Retry (independent of a speculative execution being executed?)

Target:
public Message.Request request() { if (retryConsistencyLevel != null && retryConsistencyLevel != request.consistency()) return request.copy(retryConsistencyLevel); else return request; }
Source:
public void init(FilterConfig filterConfig) throws ServletException { START dirAllowed = Context.getConfig().getBoolean("media.dirAllowed"); END } I would prefer to use full words. For example `directoryAllow`.

Target:
public void init(FilterConfig filterConfig) throws ServletException { }
Source:
public ExtentBufferedCompositePattern(Extent extent, Pattern... patterns) { super(extent); START checkArgument(patterns.length == 0, "patterns cannot be empty"); END this.patterns = patterns; } This is backwards, you want the expected condition to be here.

Target:
public ExtentBufferedCompositePattern(Extent extent, Pattern... patterns) { super(extent); checkArgument(patterns.length != 0, "patterns cannot be empty"); this.patterns = patterns; }
Source:
public boolean isValid(Object[] value, ConstraintValidatorContext context) { if ( value.length != 3 ) { START throw new IllegalStateException( "Unexpected method signature" ); END } // one or both limits are unbounded => always consistent if ( value[1] == null || value[2] == null ) { return true; } return ( (Date) value[1] ).before( (Date) value[2] ); } It's tangential, but `IllegalArgumentException` seems more reasonable.

Target:
public boolean isValid(Object[] value, ConstraintValidatorContext context) { if ( value.length != 3 ) { throw new IllegalArgumentException( "Unexpected method signature" ); } // one or both limits are unbounded => always consistent if ( value[1] == null || value[2] == null ) { return true; } return ( (Date) value[1] ).before( (Date) value[2] ); }