auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public LgoProductCurrency( @JsonProperty("id") String id, @JsonProperty("increment") BigDecimal increment, @JsonProperty("limits") LgoLimit limits) { this.id = id; START this.increment = increment != null ? increment.stripTrailingZeros() : null; END this.limits = limits; } DTOs should represent what came from the exchange, this is premature adaptation and should not be here

Target:
public LgoProductCurrency( @JsonProperty("id") String id, @JsonProperty("increment") BigDecimal increment, @JsonProperty("limits") LgoLimit limits) { this.id = id; this.increment = increment; this.limits = limits; }
Source:
private Menu createSortMenu() { Menu submenu = new Menu(shell, SWT.DROP_DOWN); MenuItem subitem; for(int i = 0; i < columnNames.length; i++) { subitem = new MenuItem (submenu, SWT.NONE); subitem.setText(columnNames [i]); final int column = i; subitem.addSelectionListener(widgetSelectedAdapter( e -> { START sort(column); END })); } return submenu; } Put in one line

Target:
private Menu createSortMenu() { Menu submenu = new Menu(shell, SWT.DROP_DOWN); MenuItem subitem; for(int i = 0; i < columnNames.length; i++) { subitem = new MenuItem (submenu, SWT.NONE); subitem.setText(columnNames [i]); final int column = i; subitem.addSelectionListener(widgetSelectedAdapter( e -> sort(column))); } return submenu; }
Source:
public static Properties loadPropertyFile(Resource f) throws IOException { InputStream in = f.in(); try { return loadUniversal(in); } finally { START in.close(); END } } Could be a try-with-resources.

Target:
public static Properties loadPropertyFile(Resource f) throws IOException { try (InputStream in = f.in()) { return loadUniversal(in); } }
Source:
START public static ETwitterCardType getTwitterCardType(@Nullable String identifier) { END return ID_MAP.get(identifier).get(); } keep Optional return parameter in all enums

Target:
public static Optional<ETwitterCardType> getTwitterCardType(@Nullable String identifier) { return ID_MAP.get(identifier); }
Source:
public byte[] get(NamedKey key) { byte[] res = level1.get(key); if (res == null) { START res = level2.get(key); END } if (res == null) { missCount.incrementAndGet(); } else { put(key, res); hitCount.incrementAndGet(); } return res; } wondering if we should also warm up level1 cache when there is a miss in l1 cache and hit in l2 cache ?

Target:
public byte[] get(NamedKey key) { byte[] res = level1.get(key); if (res == null) { res = level2.get(key); if(res != null) { level1.put(key, res); hitCount.incrementAndGet(); return res; } missCount.incrementAndGet(); } if (res != null) { hitCount.incrementAndGet(); } return res; }
Source:
START public Statistic END createHugePagesFree(HugePage page) { return setDatum( create("hugepages." + page.getSizeKB() + ".free", "Amount of free huge pages of the given size", GAUGE, NONE, INTEGER), page.getAmount()); } private?

Target:
private Statistic createHugePagesFree(HugePage page) { return setDatum( create("hugepages." + page.getSizeKB() + ".free", "Amount of free huge pages of the given size", GAUGE, NONE, INTEGER), page.getAmount()); }
Source:
private void encodeComponent(CharSequence s) { START if (CharsetUtil.UTF_8.equals(charset)) { END encodeUtf8Component(s); } else { encodeNonUtf8Component(s); } } imho we can do the equals check once in the constructor, store the result in an field and so reduce the overhead even more..

Target:
private void encodeComponent(CharSequence s) { if (charset == null) { encodeUtf8Component(s); } else { encodeNonUtf8Component(s); } }
Source:
public MatchingApplicabilityTagsRule(IAtsClient atsClient) { this.atsClient = atsClient; featureDefinitionData = null; START validFeatureValues = null; END } not necessary since JVM initializes all object fields to null

Target:
public MatchingApplicabilityTagsRule(IAtsClient atsClient) { this.atsClient = atsClient; }
Source:
public void test() { START connect(); END Assert.assertEquals(jq("$innerLabel").text(), "someValue"); } ``` Assert.assertTrue(jq("$innerLabel").exists()); Assert.assertEquals(jq("$innerLabel").text(), "someValue"); ```

Target:
public void test() { connect(); Assert.assertTrue(jq("$innerLabel").exists()); Assert.assertEquals(jq("$innerLabel").text(), "someValue"); }
Source:
public void addResolverListener(String expression, ResolverListener listener) throws CloudnameException { START DynamicExpression dynamicExpression = END new DynamicExpression(expression, listener, this, zkGetter); synchronized (dynamicAddressMonitor) { DynamicExpression previousExpression = dynamicAddressesByListener.put( listener, dynamicExpression); if (previousExpression != null) { throw new IllegalArgumentException("It is not legal to register a listener twice."); } } dynamicExpression.start(); } final

Target:
public void addResolverListener(String expression, ResolverListener listener) throws CloudnameException { final DynamicExpression dynamicExpression = new DynamicExpression(expression, listener, this, zkGetter); synchronized (dynamicAddressMonitor) { DynamicExpression previousExpression = dynamicAddressesByListener.put( listener, dynamicExpression); if (previousExpression != null) { throw new IllegalArgumentException("It is not legal to register a listener twice."); } } dynamicExpression.start(); }
Source:
public void clearCache() throws SQLException { START ((Session)this.getDBConnection().getSession()).clear(); END } I think we should extend the DBConnection interface to have a clearCache() & have the hibernate implementation call this clear. Having it in here ties the context object to close to the hibernate implementation (which I want to avoid if we ever want to drop hibernate).

Target:
public void clearCache() throws SQLException { this.getDBConnection().clearCache(); }
Source:
private Optional<LocalMemoryContext> getSystemMemoryContext() { try { return Optional.of(systemMemoryContextSupplier.get()); } START catch (Exception ignored) { END // This is possible with races, e.g., a task is created and then immediately aborted, // so that the task context hasn't been created yet (as a result there's no memory context available). } return Optional.empty(); } `RuntimeException`?

Target:
private Optional<LocalMemoryContext> getSystemMemoryContext() { try { return Optional.of(systemMemoryContextSupplier.get()); } catch (RuntimeException ignored) { // This is possible with races, e.g., a task is created and then immediately aborted, // so that the task context hasn't been created yet (as a result there's no memory context available). } return Optional.empty(); }
Source:
private boolean isFilterExpressionValid(InetAddress inetAddress, String filterExpression) { // Consider profiles without filter expression or an empty one as matching. if (Strings.isNullOrEmpty(filterExpression)) { return true; } else { try { return filterDao.isValid(inetAddress.getHostAddress(), filterExpression); } catch (FilterParseException e) { START LOG.warn("Filter expression '{}' is invalid. ", e); END } } return false; } Missing filter expression?

Target:
private boolean isFilterExpressionValid(InetAddress inetAddress, String filterExpression) { // Consider profiles without filter expression or an empty one as matching. if (Strings.isNullOrEmpty(filterExpression)) { return true; } else { try { return filterDao.isValid(inetAddress.getHostAddress(), filterExpression); } catch (FilterParseException e) { LOG.warn("Filter expression '{}' is invalid. ", filterExpression, e); } } return false; }
Source:
public void replaceNodeShouldRemoveOldNode() throws Exception { Node oldNode = r.createSlave("foo", "", null); Node newNode = r.createSlave("foo-new", "", null); r.jenkins.addNode(oldNode); r.jenkins.getNodesObject().replaceNode(oldNode, newNode); r.jenkins.getNodesObject().load(); START assertNull(r.jenkins.getNode(oldNode.getNodeName())); END } ```suggestion assertNull(r.jenkins.getNode("foo")); ``` since it is not otherwise obvious that the node’s name did not change somewhere in here.

Target:
public void replaceNodeShouldRemoveOldNode() throws Exception { Node oldNode = r.createSlave("foo", "", null); Node newNode = r.createSlave("foo-new", "", null); r.jenkins.addNode(oldNode); r.jenkins.getNodesObject().replaceNode(oldNode, newNode); r.jenkins.getNodesObject().load(); assertNull(r.jenkins.getNode("foo")); }
Source:
protected void rename() { if ( isDirty() ) { view.showYesNoCancelPopup( CommonConstants.INSTANCE.Information(), Constants.INSTANCE.modelEditor_confirm_save_before_rename(), new Command() { @Override public void execute() { rename( true ); } }, new Command() { @Override public void execute() { rename( false ); } }, START new Command() { END @Override public void execute() { //do nothing. } } ); } else { //just rename. rename( false ); } } Don't have it as a parameter then! I guess it was just easier to copy and paste the code used before, but now delegate to the View interface.

Target:
protected void rename() { if ( isDirty() ) { view.showYesNoCancelPopup( CommonConstants.INSTANCE.Information(), Constants.INSTANCE.modelEditor_confirm_save_before_rename(), new Command() { @Override public void execute() { rename( true ); } }, new Command() { @Override public void execute() { rename( false ); } } ); } else { //just rename. rename( false ); } }
Source:
public void removeThreadFilters(IExecutionDMContext[] threads) throws CoreException { START synchronized (fFilteredThreadsByTarget) { END if (threads != null && threads.length > 0) { IContainerDMContext target = DMContexts.getAncestorOfType(threads[0], IContainerDMContext.class); Set<IExecutionDMContext> set = fFilteredThreadsByTarget.get(target); if (set != null) { set.removeAll(Arrays.asList(threads)); if (set.isEmpty()) { fFilteredThreadsByTarget.remove(target); } } } } } I'm not clear on why this one is needed.

Target:
public void removeThreadFilters( IExecutionDMContext[] threads ) throws CoreException { if ( threads != null && threads.length > 0 ) { IContainerDMContext target = DMContexts.getAncestorOfType(threads[0], IContainerDMContext.class); Set<IExecutionDMContext> set = fFilteredThreadsByTarget.get( target ); if ( set != null ) { set.removeAll( Arrays.asList( threads ) ); if ( set.isEmpty() ) { fFilteredThreadsByTarget.remove( target ); } } } }
Source:
public Collection<IAtsTeamWorkflow> getSiblingTeamWorkflows(IAtsTeamWorkflow teamWf) { List<IAtsTeamWorkflow> teams = new LinkedList<IAtsTeamWorkflow>(); START teamWf.getStoreObject(); END Object action = getAction(teamWf); for (Object teamArt : atsServices.getRelationResolver().getRelated(action, AtsRelationTypes.ActionToWorkflow_WorkFlow)) { if (!teamArt.equals(teamWf)) { teams.add(atsServices.getWorkItemFactory().getTeamWf(teamArt)); } } return teams; } Doesn't look like the above store object is being used. Suggest removing it.

Target:
public Collection<IAtsTeamWorkflow> getSiblingTeamWorkflows(IAtsTeamWorkflow teamWf) { List<IAtsTeamWorkflow> teams = new LinkedList<IAtsTeamWorkflow>(); Object action = getAction(teamWf); for (Object teamArt : atsServices.getRelationResolver().getRelated(action, AtsRelationTypes.ActionToWorkflow_WorkFlow)) { if (!teamArt.equals(teamWf)) { teams.add(atsServices.getWorkItemFactory().getTeamWf(teamArt)); } } return teams; }
Source:
START public ResultIterator iterator(String query, int fetchSize, int readTimeoutOverride) throws DatabaseEngineException { END try { getConnection(); Statement stmt = createSelectStatement(readTimeoutOverride); stmt.setFetchSize(fetchSize); logger.trace(query); return createResultIterator(stmt, query); } catch (final DatabaseEngineTimeoutException e) { throw e; } catch (final Exception e) { throw new DatabaseEngineException("Error querying", e); } } The first `iterator` method in AbstractDatabaseEngine had this signature: ``` public synchronized ResultIterator iterator(String query) ``` Then people added more iterator methods, some of them `synchronized`, some of them not. I think all methods that use the connection should be `synchronized`; this means this one would need to be `synchronized`, but all other `iterator` methods call this one and don't need to be.

Target:
public synchronized ResultIterator iterator(String query, int fetchSize, int readTimeoutOverride) throws DatabaseEngineException { try { getConnection(); Statement stmt = createSelectStatement(readTimeoutOverride); stmt.setFetchSize(fetchSize); logger.trace(query); return createResultIterator(stmt, query); } catch (final DatabaseEngineTimeoutException e) { throw e; } catch (final Exception e) { throw new DatabaseEngineException("Error querying", e); } }
Source:
public void initializeServers(NotificationSystem notificationSystem) { List<MockDataNodeId> dataNodes = clusterMap.getDataNodes(); for (int i = 0; i < dataNodes.size(); i++) { if (sslEnabledDataCenterList != null) { dataNodes.get(i).setSslEnabledDataCenters(sslEnabledDataCenterList); } START initializeServer(dataNodes.get(i), sslProps, enableHardDeletes, prefetchDataNodeIndex == i ? true : false, END notificationSystem, time); } } suggest changing `prefetchDataNodeIndex == i ? true : false` to `prefetchDataNodeIndex == i`.

Target:
public void initializeServers(NotificationSystem notificationSystem) { List<MockDataNodeId> dataNodes = clusterMap.getDataNodes(); for (int i = 0; i < dataNodes.size(); i++) { if (sslEnabledDataCenterList != null) { dataNodes.get(i).setSslEnabledDataCenters(sslEnabledDataCenterList); } initializeServer(dataNodes.get(i), sslProps, enableHardDeletes, prefetchDataNodeIndex == i, notificationSystem, time); } }
Source:
public Payload(final Object data, final Visibility visibility, final String visibilityId) { if(null == data){ START this.type = Object.class.getName(); END }else{ this.type = data.getClass().getName(); } this.data = data; this.visibility = visibility; this.visibilityId = visibilityId; } why object class?, maybe set type to null could be a better idea

Target:
public Payload(final Object data, final Visibility visibility, final String visibilityId) { this.type = data.getClass().getName(); this.data = data; this.visibility = visibility; this.visibilityId = visibilityId; }
Source:
public CloseableIterator<CacheEntry<K, V>> iterator() { return new CloseableIteratorMapper<>(new RemovableCloseableIterator<>(Closeables.iterator(stream()), cache, START e -> e.getKey()), e -> new EntryWrapper<>(cache, e)); END } nitpick: `e -> e.getKey()` could be replaced by `CacheEntry::getKey`. the same for the change below. ps. not sure which one is more efficient.

Target:
public CloseableIterator<CacheEntry<K, V>> iterator() { return new CloseableIteratorMapper<>(new RemovableCloseableIterator<>(Closeables.iterator(stream()), cache, CacheEntry::getKey), e -> new EntryWrapper<>(cache, e)); }
Source:
public void disableAutoLimit() { START autoLimitRowCount = null; END } ```suggestion autoLimitRowCount = 0; ```

Target:
public void disableAutoLimit() { autoLimitRowCount = 0; }
Source:
public void testScriptCallFromJavascript() throws Exception { START cacheManager.getCache().remove("a"); END assertNull(cacheManager.getCache().get("a")); String result = (String) scriptingManager.runScript("testInnerScriptCall.js", new TaskContext().cache(cacheManager.getCache("test_cache")).addParameter("a", "ahoj")).get(); assertEquals("script1:additionFromJavascript", result); assertEquals("ahoj", cacheManager.getCache().get("a")); } Do we need those 2 lines here?

Target:
public void testScriptCallFromJavascript() throws Exception { String result = (String) scriptingManager.runScript("testInnerScriptCall.js", new TaskContext().cache(cacheManager.getCache("test_cache")).addParameter("a", "ahoj")).get(); assertEquals("script1:additionFromJavascript", result); assertEquals("ahoj", cacheManager.getCache().get("a")); }
Source:
public RestartVdsReturnValue getReturnValue() { START return (RestartVdsReturnValue)(super.getReturnValue()); END } Please remove unnecessary brackets: return (RestartVdsReturnValue) super.getReturnValue();

Target:
public RestartVdsReturnValue getReturnValue() { return (RestartVdsReturnValue) super.getReturnValue(); }
Source:
public void closeThisNode(long endtime) { super.closeThisNode(endtime); START fListeners.stream().forEach(l -> l.nodeClosed(this, endtime)); END } idem

Target:
public void closeThisNode(long endtime) { super.closeThisNode(endtime); fListeners.forEach(l -> l.nodeClosed(this, endtime)); }
Source:
public Set<Integer> getSegments() { synchronized (segments) { Set<Integer> segmentsCopy = new HashSet<Integer>(segments); START segmentsCopy.addAll(segments); END return segmentsCopy; } } why the `addAll()`?

Target:
public Set<Integer> getSegments() { synchronized (segments) { return new HashSet<Integer>(segments); } }
Source:
public void dispose() { //Remove all message from the queue START this.h.removeCallbacksAndMessages(null); END this.parent.dispose(); this.h = null; this.owner = null; this.parent = null; } > Use this.h.removeCallbacksAndMessages(null) instead. Done in Patch set 2

Target:
public void dispose() { }
Source:
private boolean isHost(final Permissionable permissionable) { return permissionable instanceof Host || START (permissionable instanceof Contentlet && Host.class.getSimpleName().equals(((Contentlet) permissionable).getContentType().name())) || END (null != permissionable && permissionable instanceof PermissionableProxy && Host.class.getName().equals(PermissionableProxy.class.cast(permissionable).getType())); } I think we should use the `contentlet.isHost()` method here rather than recreating it

Target:
private boolean isHost(final Permissionable permissionable) { return permissionable instanceof Host || (permissionable instanceof Contentlet && ((Contentlet) permissionable).isHost()) || (null != permissionable && permissionable instanceof PermissionableProxy && Host.class.getName().equals(PermissionableProxy.class.cast(permissionable).getType())); }
Source:
public boolean isMine() { IRepository repos = getReview() != null ? getReview().getRepository() : null; return getAuthor() != null && repos != null START && (repos.getAccount() == getAuthor() || (repos.getAccount() != null && (repos.getAccount().getEmail().equals(getAuthor().getEmail())))); END } Don't need parens around repos.getAccount().getEmail().equals(getAuthor().getEmail())

Target:
public boolean isMine() { IRepository repos = getReview() != null ? getReview().getRepository() : null; return getAuthor() != null && repos != null && (repos.getAccount() == getAuthor() || (repos.getAccount() != null && repos.getAccount().getEmail().equals(getAuthor().getEmail()))); }
Source:
private void runSe(String filename) { JavaScriptVisitorContext context; START try { END context = createContext(new TestInputFile("src/test/resources/se/", filename)); verifier.scanExpectedIssues(context); SeChecksDispatcher seChecksDispatcher = new SeChecksDispatcher(ImmutableList.of((SeCheck) verifier)); seChecksDispatcher.scanTree(context); } catch (IOException e) { Throwables.propagate(e); } } @janos-ss I would rather catch the `IOException` inside `createContext `.

Target:
private void runSe(String filename) { JavaScriptVisitorContext context = createContext(new TestInputFile("src/test/resources/se/", filename)); verifier.scanExpectedIssues(context); SeChecksDispatcher seChecksDispatcher = new SeChecksDispatcher(ImmutableList.of((SeCheck) verifier)); seChecksDispatcher.scanTree(context); }
Source:
public void testReturnKey() throws Exception { long[] ids = b.insertNames("a", "b", "c", "d", "e"); START assertThat(ids).containsExactly(new long[] { 1, 2, 3, 4, 5 }); END } Meh: This is a vararg method. I think you can just say `.containsExactly(1, 2, 3, 4, 5)`

Target:
public void testReturnKey() throws Exception { long[] ids = b.insertNames("a", "b", "c", "d", "e"); assertThat(ids).containsExactly(1, 2, 3, 4, 5); }
Source:
public void testIndexSeekAndScan() throws Exception { updateAndCommit( asList( IndexEntryUpdate.add( 1L, index, "a" ), IndexEntryUpdate.add( 2L, index, "a" ), IndexEntryUpdate.add( 3L, index, "b" ) ) ); assertThat( query( exact( 1, "a" ) ), equalTo( asList( 1L, 2L ) ) ); START assertThat( query( IndexQuery.exists( 1 ) ), equalTo( asList( 1L, 2L, 3L ) ) ); END } exists is statically imported.

Target:
public void testIndexSeekAndScan() throws Exception { updateAndCommit( asList( IndexEntryUpdate.add( 1L, index, "a" ), IndexEntryUpdate.add( 2L, index, "a" ), IndexEntryUpdate.add( 3L, index, "b" ) ) ); assertThat( query( exact( 1, "a" ) ), equalTo( asList( 1L, 2L ) ) ); assertThat( query( exists( 1 ) ), equalTo( asList( 1L, 2L, 3L ) ) ); }
Source:
Response forget(URI lraId, URI parentId) { START return invokeParticipantMethod(forgetMethod, lraId, parentId, FORGET); END } Shouldn't you be clearing out the entry in participantStatusMap. Similarly whenever compensate or complete callbacks finish successfully.

Target:
synchronized Response forget(URI lraId, URI parentId) { return invokeParticipantMethod(forgetMethod, lraId, parentId, FORGET); }
Source:
START private void resetAuthorities(String username) { END UserDetails userDetails = userDetailsService.loadUserByUsername(username); Collection<? extends GrantedAuthority> updatedAuthorities = userDetails.getAuthorities(); Object principal = toPrincipal(username); principalSecurityContextRegistry .getSecurityContexts(principal) .forEach(securityContext -> resetAuthorities(securityContext, updatedAuthorities)); } I think that this may overlap with concurrent updates to the authorities by other threads

Target:
private synchronized void resetAuthorities(String username) { UserDetails userDetails = userDetailsService.loadUserByUsername(username); Collection<? extends GrantedAuthority> updatedAuthorities = userDetails.getAuthorities(); Object principal = toPrincipal(username); principalSecurityContextRegistry .getSecurityContexts(principal) .forEach(securityContext -> resetAuthorities(securityContext, updatedAuthorities)); }
Source:
private void internalEndWithFailure() { log.error("Ending command '{}' with failure.", getClass().getName()); endWithFailure(); rollbackQuota(); START if (getCommandCompensationPhase() == CommandCompensationPhase.END_COMMAND) { END compensate(); } } similar approach should be taken here, but the condition is simpler: try { endWithFailure(); } finally { if (getCommandCompensationPhase() == CommandCompensationPhase.END_COMMAND) { compensate(); } }

Target:
private void internalEndWithFailure() { log.error("Ending command '{}' with failure.", getClass().getName()); try { endWithFailure(); } finally { if (getCommandCompensationPhase() == CommandCompensationPhase.END_COMMAND) { compensate(); } } rollbackQuota(); }
Source:
public void testCountWithInternalStore() { final StreamsBuilder builder = new StreamsBuilder(); final String input = "count-test-input"; START final MockProcessorSupplier<String, Object> supplier = new MockProcessorSupplier<>(); END builder .table(input, consumed) .groupBy(MockMapper.selectValueKeyValueMapper(), stringSerialized) .count() .toStream() .process(supplier); testCountHelper(builder, input, supplier); } Why we cannot continue to reuse a single `MockProcessorSupplier`?

Target:
public void testCountWithInternalStore() { final StreamsBuilder builder = new StreamsBuilder(); final String input = "count-test-input"; builder .table(input, consumed) .groupBy(MockMapper.selectValueKeyValueMapper(), stringSerialized) .count() .toStream() .process(supplier); testCountHelper(builder, input, supplier); }
Source:
private static URL mapToURL(String path) { try { return new URL(path); } catch (MalformedURLException e) { try { return new File(path).toURI().toURL(); } catch (MalformedURLException e1) { START throw new IllegalStateException(e1); END } } } new IllegalArgumentException is more appropriate

Target:
private static URL mapToURL(String path) { try { return new URL(path); } catch (MalformedURLException e) { try { return new File(path).toURI().toURL(); } catch (MalformedURLException e1) { throw new IllegalArgumentException(e1); } } }
Source:
protected void addSearchFilter(final ActiveFilterItem filter, final ColumnFilter columnFilter) { START ((CoreFunctionFilter)columnFilter).setLabelValue(filter.getLabelValue()); END basicFilterAddEvent.fire(new BasicFilterAddEvent(getDataSetId(), filter, columnFilter)); } unchecked cast, in class below there's a checked cast. Isn't it necessary here too?

Target:
protected void addSearchFilter(final ActiveFilterItem filter, final ColumnFilter columnFilter) { if (columnFilter instanceof CoreFunctionFilter) { ((CoreFunctionFilter) columnFilter).setLabelValue(filter.getLabelValue()); } basicFilterAddEvent.fire(new BasicFilterAddEvent(getDataSetId(), filter, columnFilter)); }
Source:
START void addAdditionalDependencies(Set<String> back) throws Exception { END if (additionalDependencies != null) { for (Dependency dependency : additionalDependencies) { addToClasspath(factory.createDependencyArtifact(dependency), back, false); } } } protected

Target:
protected void addAdditionalDependencies(Set<String> back) throws Exception { if (additionalDependencies != null) { for (Dependency dependency : additionalDependencies) { addToClasspath(factory.createDependencyArtifact(dependency), back, false); } } }
Source:
private void runEventLoopUntilEmpty() { Display display = Display.getCurrent(); while (display.readAndDispatch()) { } START display.sleep(); END return; } Possible deadlock: remove this call to sleep(). It's possible that no events will ever arrive.

Target:
private void runEventLoopUntilEmpty() { Display display = Display.getCurrent(); while (display.readAndDispatch()) { } return; }
Source:
private Map<String, List<Entry<T>>> copy(final Map<String, List<Entry<T>>> original) { final Map<String, List<Entry<T>>> copy = new HashMap<>(); original.forEach((key, value) -> copy.put(key, new CopyOnWriteArrayList<>(value))); START return copy; END } OK, thanks for the size improvement. As for the synchronized issue, let's open a jira then and do nothing for now.

Target:
private Map<String, List<Entry<T>>> copy(final Map<String, List<Entry<T>>> original) { final Map<String, List<Entry<T>>> copy = new HashMap<>(original.size()); original.forEach((key, value) -> copy.put(key, new CopyOnWriteArrayList<>(value))); return copy; }
Source:
@Override public void track(TrackPayload track) { super.track(track); START Double value = track.properties().getDouble("value", Double.MIN_VALUE); END if (value.equals(Double.MIN_VALUE)) { Apptimize.track(track.event()); } else { Apptimize.track(track.event(), value); } } You can leave it as `double` to avoid auto boxing.

Target:
@Override public void track(TrackPayload track) { super.track(track); double value = track.properties().getDouble("value", Double.MIN_VALUE); if (value == Double.MIN_VALUE) { Apptimize.track(track.event()); } else { Apptimize.track(track.event(), value); } }
Source:
START public ContentTypeManager() { END super(null, InstanceScope.INSTANCE); } Can the constructor be private?

Target:
private ContentTypeManager() { super(null, InstanceScope.INSTANCE); }
Source:
public void testStartAndCompleteTaskUseOfAsyncResponseHandler() { START ResponseCallback callback = new BlockingResponseCallback(null); END testStartAndCompleteTask(new AsyncResponseHandler(callback)); } You may also check responses from callback.

Target:
public void testStartAndCompleteTaskUseOfAsyncResponseHandler() throws Exception { ResponseCallback callback = new BlockingResponseCallback(null); testStartAndCompleteTask(new AsyncResponseHandler(callback)); }
Source:
Delete(String keyspace, String table, List<Selector> columns) { super(keyspace); this.table = table; this.columns = columns; this.where = new Where(this); this.usings = new Options(this); this.conditions = new Conditions(this); // This is for JAVA-1089, if the query deletes an element in a list, the statement should be non-idempotent. for (Selector sel : columns) { if (sel instanceof CollectionElementSelector) { START if (((CollectionElementSelector) sel).key instanceof Integer) { END setNonIdempotentOps(); } } } } I believe this is wrong: it would also return true for maps with integer keys. We will need to create separate subclasses or find another way to distinguish list element deletions from other cases.

Target:
Delete(String keyspace, String table, List<Selector> columns) { this(keyspace, table, null, null, columns); }
Source:
File remove(long sizeInBytes) { File reserveFile = null; Queue<File> reserveFilesForSize = internalMap.get(sizeInBytes); START if (reserveFilesForSize != null) { END if (reserveFilesForSize.size() != 0) { reserveFile = reserveFilesForSize.remove(); } } return reserveFile; } minor: can put both conditions together with a "&&"?

Target:
File remove(long sizeInBytes) { File reserveFile = null; Queue<File> reserveFilesForSize = internalMap.get(sizeInBytes); if (reserveFilesForSize != null && reserveFilesForSize.size() != 0) { reserveFile = reserveFilesForSize.remove(); } return reserveFile; }
Source:
public PersistenceConfiguration create() { START List<StoreConfiguration> stores = new LinkedList<StoreConfiguration>(); END for (StoreConfigurationBuilder<?, ?> loader : this.stores) stores.add(loader.create()); return new PersistenceConfiguration(passivation, stores); } This was like this before, but shouldn't we make this List<StoreConfiguration> stores = new ArrayList<StoreConfiguration>(stores.size()); instead. LinkedList should only really be used when removing or adding not from the tail.

Target:
public PersistenceConfiguration create() { List<StoreConfiguration> stores = new ArrayList<StoreConfiguration>(this.stores.size()); for (StoreConfigurationBuilder<?, ?> loader : this.stores) stores.add(loader.create()); return new PersistenceConfiguration(passivation, stores); }
Source:
START private void setAmbryHeadersForPut(JSONObject headers, String ttlInSecs, String serviceId, Container container, END String contentType, String ownerId) throws JSONException { setAmbryHeadersForPut(headers, ttlInSecs, serviceId, container, contentType, ownerId, true, true); } `container` is not specified in @param.

Target:
private void setAmbryHeadersForPut(JSONObject headers, String ttlInSecs, String serviceId, Container container, String contentType, String ownerId) throws JSONException { setAmbryHeadersForPut(headers, ttlInSecs, serviceId, container, contentType, ownerId, true); }
Source:
public void validateArguments(List<Expr> args) { START if (!(args.size() > 0)) { END throw new IAE("Function[%s] needs at least 1 argument", name()); } } Could simplify to: ```java if (args.isEmpty()) { ```

Target:
public void validateArguments(List<Expr> args) { if (args.isEmpty()) { throw new IAE("Function[%s] needs at least 1 argument", name()); } }
Source:
public boolean setValue(T newValue) { if (!validator.validate(newValue)) return false; PropertyChangeEvent event = new PropertyChangeEvent(this, id.toString(), this.value, newValue); START this.value = newValue; END dispatchChangedEvent(event); return true; } I'd remove the empty lines before and after this one.

Target:
public boolean setValue(T newValue) { if (!validate(newValue)) { return false; } PropertyChangeEvent event = new PropertyChangeEvent(this, id.toString(), this.value, newValue); this.value = newValue; dispatchChangedEvent(event); return true; }
Source:
public void testNestedInvalidateAndApplyCompletes() throws Exception { final AtomicBoolean hasRun = new AtomicBoolean(); START final SideEffect innerSideEffect = SideEffect.createPaused(() -> { END }).resume(); SideEffect.createPaused(() -> { // Make sure that there are no infinite loops. assertFalse(hasRun.get()); hasRun.set(true); innerSideEffect.markDirty(); innerSideEffect.runIfDirty(); }).resume(); runAsync(); assertTrue(hasRun.get()); } Here is the same issue like in line 208 (resume being void)

Target:
public void testNestedInvalidateAndApplyCompletes() throws Exception { AtomicBoolean hasRun = new AtomicBoolean(); SideEffect innerSideEffect = SideEffect.createPaused(() -> { }); innerSideEffect.resume(); SideEffect.createPaused(() -> { // Make sure that there are no infinite loops. assertFalse(hasRun.get()); hasRun.set(true); innerSideEffect.markDirty(); innerSideEffect.runIfDirty(); }).resume(); runAsync(); assertTrue(hasRun.get()); }
Source:
SubscribedRepository(String name) { this.name = name; START subscribeSpecs = new HashMap<String, SubscribeSpec>(); END } Use a concurrentHasMap, then you can remove the synchronized on the public methods.

Target:
private SubscribedRepository(String name) { this.name = name; subscribeSpecs = new HashSet<SubscribeSpec>(); }
Source:
public void testFixedMeanFixedVariance() { Double[] params = new Double[2]; params[0] = MEAN; START params[1] = VARIANCE; END UnivarGaussian gaussian = new UnivarGaussian(); gaussian.setParams(params); testGaussian(gaussian); } Simpler: `Double[] params = { MEAN, VARIANCE }`

Target:
public void testFixedMeanFixedVariance() { Double[] params = { MEAN, VARIANCE }; UnivarGaussian gaussian = new UnivarGaussian(); gaussian.setParams(params); testGaussian(gaussian); }
Source:
START public void saveSessionBackupFromResult( final BackupResult backupResult ) throws IOException { END final byte[] data = backupResult.getData(); if ( data != null ) { final String key = _sessionIdFormat.createBackupKey( _session.getId() ); _memcached.set( key, toMemcachedExpiration(_session.getMemcachedExpirationTimeToSet()), data ); } else { _log.warn( "No data set for backupResultStatus " + backupResult.getStatus() + " for sessionId " + _session.getIdInternal() + ", skipping backup" + " of non-sticky session in secondary memcached." ); } } I can't see it here, but probably it's now blocking while it shouldn't (at least not always).

Target:
public void saveSessionBackupFromResult( final BackupResult backupResult ) { final byte[] data = backupResult.getData(); if ( data != null ) { final String key = _sessionIdFormat.createBackupKey( _session.getId() ); _memcached.set( key, toMemcachedExpiration(_session.getMemcachedExpirationTimeToSet()), data ); } else { _log.warn( "No data set for backupResultStatus " + backupResult.getStatus() + " for sessionId " + _session.getIdInternal() + ", skipping backup" + " of non-sticky session in secondary memcached." ); } }
Source:
public void teardown() throws Exception { if (lifeCycleManager != null) { START lifeCycleManager.stop(); END } } Something per-method needs to assign null to lifeCycleManager.

Target:
public void teardown() throws Exception { if (lifeCycleManager != null) { lifeCycleManager.stop(); lifeCycleManager = null; } }
Source:
protected void queueRequest(final ITmfDataRequest request) { START if (fExecutor == null || fExecutor.isShutdown()) { END request.cancel(); return; } TmfEventThread thread = new TmfEventThread(this, request); if (TmfCoreTracer.isRequestTraced()) { TmfCoreTracer.traceRequest(request, "QUEUED"); //$NON-NLS-1$ } fExecutor.execute(thread); } Could be replaced with executorIsShutdown?

Target:
protected void queueRequest(final ITmfDataRequest request) { if (fExecutor.isShutdown()) { request.cancel(); return; } TmfEventThread thread = new TmfEventThread(this, request); if (TmfCoreTracer.isRequestTraced()) { TmfCoreTracer.traceRequest(request, "QUEUED"); //$NON-NLS-1$ } fExecutor.execute(thread); }
Source:
public boolean isDuplicate(@NonNull AvoidRoadInfo item) { for (AvoidRoadInfo existingItem : existingItems) { START if (item.latitude == existingItem.latitude END && item.longitude == existingItem.longitude && item.name.equals(existingItem.name)) { return true; } } return false; } Implement equals in AvoidRoadInfo

Target:
public boolean isDuplicate(@NonNull AvoidRoadInfo item) { return existingItems.contains(item); }
Source:
public void onCompleted() { START long r = get(); END if (r != Long.MIN_VALUE) { actual.onCompleted(); } } nit: inline

Target:
public void onCompleted() { if (get() != Long.MIN_VALUE) { actual.onCompleted(); } }
Source:
public Extensions() { START factories = new CopyOnWriteArrayList<>(); END } Again, now this initializer will have to be repeated in any additional constructors added.

Target:
public Extensions()
Source:
public void export_credentials_provider_extension_credentials() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); ConfigurationAsCode.get().export(out); START System.out.println(out.toString()); END assertThat(out.toString(), containsString("username: \"user1\"")); assertThat(out.toString(), containsString("id: \"sudo_password\"")); } this still needed?

Target:
public void export_credentials_provider_extension_credentials() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); ConfigurationAsCode.get().export(out); assertThat(out.toString(), containsString("username: \"user1\"")); assertThat(out.toString(), containsString("id: \"sudo_password\"")); }
Source:
private Predicate<String> createPredicate() { START if(includeLists != null) { END return e -> includeLists.contains(e); } else if (excludeLists != null) { return e -> !excludeLists.contains(e); } else { return e -> true; } } Missing a blank after "if" If `propertyToList` returns empty list, check `if (!includeLists.isEmpty())`

Target:
private Predicate<String> createPredicate() { if (includeLists.isPresent()) { return e -> includeLists.get().contains(e); } else if (excludeLists.isPresent()) { return e -> !excludeLists.get().contains(e); } else { return e -> true; } }
Source:
public void testEmailWith64CharacterLocalPartIsValid() { // Local part should allow up to 64 octets: https://tools.ietf.org/html/rfc5321#section-4.5.3.1.1 START for (int num = 1; num < 64; num++) { END isValidEmail( stringOfLength( num ) + "@foo.com" ); } } You're missing 64 here. `<=` would be better.

Target:
public void testEmailWith64CharacterLocalPartIsValid() { // Local part should allow up to 64 octets: https://tools.ietf.org/html/rfc5321#section-4.5.3.1.1 for (int num = 1; num <= 64; num++) { isValidEmail( stringOfLength( num ) + "@foo.com" ); } }
Source:
public void save(AuditLog event) { START Map<String, Object> returnVal = null; END if (event.isExternal()) { returnVal = getCallsHandler().executeModification("InsertExternalAuditLog", getExternalEventSqlMapper(event)); } else { returnVal = getCallsHandler().executeModification("InsertAuditLog", getSqlMapper(event)); } event.setAuditLogId((Integer) returnVal.get("audit_log_id")); } No need to set null here ...

Target:
public void save(AuditLog event) { if (event.isExternal()) { getCallsHandler().executeModification("InsertExternalAuditLog", getExternalEventSqlMapper(event)); } else { getCallsHandler().executeModification("InsertAuditLog", getSqlMapper(event)); } }
Source:
public void testCrossSourceMultiFragmentJoin() throws Exception { try { client.alterSession(ExecConstants.SLICE_TARGET, 1); START client.queryBuilder() END .sql("select x.person_id, y.salary from h2.drill_h2_test.person x " + "join %s y on x.person_id = y.person_id ", TABLE_NAME) .run(); } finally { client.resetSession(ExecConstants.SLICE_TARGET); } } Not critical but there is `queryBuilder()` method that implicitly performs `client.queryBuilder()`, also there is `run` method for those queries that does not need to return any result (check `ClusterTest` class).

Target:
public void testCrossSourceMultiFragmentJoin() throws Exception { try { client.alterSession(ExecConstants.SLICE_TARGET, 1); run("select x.person_id, y.salary from h2.drill_h2_test.person x " + "join %s y on x.person_id = y.person_id ", TABLE_NAME); } finally { client.resetSession(ExecConstants.SLICE_TARGET); } }
Source:
private static void setDropdown(Combo comboBox, INamedElement el, List<String> names) { comboBox.removeAll(); START for (String name : names) { comboBox.add(name); } END // pre-selects the elements that are now in the action: comboBox.select((null == el) ? names.size() - 1 : comboBox.indexOf(el.getName())); } names.forEach( name -> comboBox.add(name)); would be more concise

Target:
private static void setDropdown(Combo comboBox, INamedElement el, List<String> names) { comboBox.removeAll(); names.forEach(comboBox::add); // pre-selects the elements that are now in the action: comboBox.select((null == el) ? names.size() - 1 : comboBox.indexOf(el.getName())); }
Source:
boolean isHandleWritable() { START return !getLedgerMetadata().isClosed(); END } I am not sure that it is 'closed' for a non recovery reader. Maybe I need a coffee :)

Target:
protected boolean isHandleWritable() { return !getLedgerMetadata().isClosed(); }
Source:
public SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX() START END Don't leave this empty - better to add the call to _super()_ - even though it is implicit, as this enables placing a debug breakpoint in the constructor.

Target:
public SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX() { super(); }
Source:
public double approximate(int currentNode) { Dijkstra dijkstra = new Dijkstra(graph, weighting, traversalMode); Path path = reverse ? dijkstra.calcPath(to, currentNode) : dijkstra.calcPath(currentNode, to); START if (path.isFound()) return path.getWeight(); else return Double.POSITIVE_INFINITY; END } really only btw :) .... wouldn't `return path.isFound() ? path.getWeight() : Double.POSITIVE_INFINITY;` be slightly better as you used the ternary op in the line above?

Target:
public double approximate(int currentNode) { Dijkstra dijkstra = new Dijkstra(graph, weighting, traversalMode); Path path = reverse ? dijkstra.calcPath(to, currentNode) : dijkstra.calcPath(currentNode, to); return path.isFound() ? path.getWeight() : Double.POSITIVE_INFINITY; }
Source:
public boolean isValidAuthorizations(String user, List<ByteBuffer> auths) throws AccumuloSecurityException { START if (auths.size() == 0) { END // avoid deserializing auths from ZK cache return true; } Authorizations userauths = getCachedUserAuthorizations(user); for (ByteBuffer auth : auths) { if (!userauths.contains(ByteBufferUtil.toBytes(auth))) { return false; } } return true; } You should call `.isEmpty()`

Target:
public boolean isValidAuthorizations(String user, List<ByteBuffer> auths) throws AccumuloSecurityException { if (auths.isEmpty()) { // avoid deserializing auths from ZK cache return true; } Authorizations userauths = getCachedUserAuthorizations(user); for (ByteBuffer auth : auths) { if (!userauths.contains(ByteBufferUtil.toBytes(auth))) { return false; } } return true; }
Source:
public synchronized long getTimestamp(final int offset) { HistogramScaledData scaledData = fScaledData; if (scaledData != null) { return START fScaledData.fFirstBucketTime END + Math.round(scaledData.fBucketDuration * offset); } return 0; } scaledData, thread safety and all

Target:
public synchronized long getTimestamp(final int offset) { HistogramScaledData scaledData = fScaledData; if (scaledData != null) { return scaledData.fFirstBucketTime + Math.round(scaledData.fBucketDuration * offset); } return 0; }
Source:
private String serializeToXmlString(EntityDescriptor entityDescriptor) { try { START Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(entityDescriptor); END if (marshaller == null) { throw new Saml2Exception("Unable to resolve Marshaller"); } Element element = marshaller.marshall(entityDescriptor); return SerializeSupport.prettyPrintXML(element); } catch (Exception e) { throw new Saml2Exception(e); } } I think lines 71-74 don't need to be inside the try block. It would be nice to take them out in order to keep the try block as small as possible.

Target:
private String serializeToXmlString(EntityDescriptor entityDescriptor) { Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(entityDescriptor); if (marshaller == null) { throw new Saml2Exception("Unable to resolve Marshaller"); } Element element; try { element = marshaller.marshall(entityDescriptor); } catch (Exception e) { throw new Saml2Exception(e); } return SerializeSupport.prettyPrintXML(element); }
Source:
public boolean isInIdClass() { START return isInIdClass != null ? isInIdClass : ( parent != null && parent.isInIdClass() ); END } just my personal opinion but not sure this helps code readability

Target:
public boolean isInIdClass() { if ( isInIdClass != null ) { return isInIdClass; } if ( parent != null ) { return parent.isInIdClass(); } return false; }
Source:
public FakeHttpServletRequest( Map<String, String> parameterMap, Cookie[] cookies, String workspace) { this.parameterMap = parameterMap; this.cookies = cookies; this.workspace = workspace; // grab the original request from Spring to forward security related attributes // such as requests host, ports and headers this.original = Optional.ofNullable( (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) START .map(atts -> atts.getRequest()); END } Not sure if you notice, a method reference can be used here: ``` this.original = Optional.ofNullable( (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .map(ServletRequestAttributes::getRequest); ```

Target:
public FakeHttpServletRequest( Map<String, String> parameterMap, Cookie[] cookies, String workspace) { this.parameterMap = parameterMap; this.cookies = cookies; this.workspace = workspace; // grab the original request from Spring to forward security related attributes // such as requests host, ports and headers this.original = Optional.ofNullable( (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .map(ServletRequestAttributes::getRequest); }
Source:
AbstractBuilder(int initialCapacity) { START this.list = new ArrayList<T>(initialCapacity); END } minor: no need to add explicit type argument here

Target:
AbstractBuilder(int initialCapacity) { this.list = new ArrayList<>(initialCapacity); }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (Guid.isNullOrEmpty(getParameters().getHookId())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_ID_IS_REQUIRED); return false; } if (getGlusterHook() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_DOES_NOT_EXIST); return false; START } END if (getMissingServerHooks().isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_NO_CONFLICT_SERVERS); return false; } return true; } The above two checks can be moved to a common parent class, as the same is repeated in GlusterHookStatusChangeCommand as well.

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getMissingServerHooks().isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_NO_CONFLICT_SERVERS); return false; } return true; }
Source:
private void displayDetails(String period, String unit, String dataType) throws Exception { START System.out.println("***********************************************"); END System.out.println("executing for:"); System.out.println(unit + "(" + period + ")"); System.out.println("dataType=" + dataType); System.out.println("***********************************************"); } Can we use logger ?

Target:
private void displayDetails(String period, String unit, String dataType) throws Exception { logger.info("***********************************************"); logger.info("executing for:"); logger.info(unit + "(" + period + ")"); logger.info("dataType=" + dataType); logger.info("***********************************************"); }
Source:
static Module module() { return new CacheModule() { @Override protected void configure() { final String cacheName = CACHE_NAME; final TypeLiteral<Cache<ActiveSession.Key, ActiveSession>> type = new TypeLiteral<Cache<ActiveSession.Key, ActiveSession>>() {}; core(type, cacheName) // .memoryLimit(1024) // reasonable default for many sites START .maxAge(12, HOURS) // expire sessions if they are inactive END .evictionPolicy(EvictionPolicy.LRU) // keep most recently used ; bind(WebSession.class).in(RequestScoped.class); } }; } This doesn't exactly work anymore. We need to implement the same behavior in the database code.

Target:
static Module module() { return new CacheModule() { @Override protected void configure() { final TypeLiteral<Cache<ActiveSession.Key, ActiveSession>> type = new TypeLiteral<Cache<ActiveSession.Key, ActiveSession>>() {}; core(type, CACHE_NAME) // .memoryLimit(1024) // reasonable default for many sites .maxAge(12, HOURS) // expire sessions if they are inactive .evictionPolicy(EvictionPolicy.LRU) // keep most recently used ; bind(WebSession.class).in(RequestScoped.class); } }; }