auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean isInSelection(Event event) { if (selection.x == selection.y) return false; int offset = getOffsetAtPoint(event.x, event.y, null, true); if (selection.x <= offset && offset < selection.y) return true; START else return false; END } we can just use 'return false' instead of 'else return false'

Target:
private boolean isInSelection(Event event) { if (selection.x == selection.y) return false; int offset = getOffsetAtPoint(event.x, event.y, null, true); if (selection.x <= offset && offset < selection.y) return true; return false; }
Source:
START public void setUp() throws Exception { cuMarshalService = new CUMarshalServiceImpl(); xmlFile = new File(EXAMPLE_FILE_NAME); } END Is the throws Exception needed here?

Target:
public void setUp() { cuMarshalService = new CUMarshalServiceImpl(); xmlFile = new File(EXAMPLE_FILE_NAME); }
Source:
public void actionPerformed(ActionEvent e) { if(e.getSource() == okButton){ //controller should be passed to this class only if there is need to modification content of Keystore. START System.out.println(certControll); END if (certControll != null) { certControll.setAddToKeystore(true); } this.dispose(); }else if(e.getSource() == cancelButton){ if (certControll != null) { certControll.setAddToKeystore(false); } this.dispose(); } } System.out? Booh!

Target:
public void actionPerformed(ActionEvent e) { if(e.getSource() == okButton){ //controller should be passed to this class only if there is need to modification content of Keystore. if (certControll != null) { certControll.setAddToKeystore(true); } this.dispose(); }else if(e.getSource() == cancelButton){ if (certControll != null) { certControll.setAddToKeystore(false); } this.dispose(); } }
Source:
public FilteredSourceFiles( List<Path> rawSrcFiles, BuildTarget buildTarget, GoToolchain goToolchain, GoPlatform platform, List<FileType> fileTypes) { this.rawSrcFiles = rawSrcFiles; this.extraSrcFiles = new ArrayList<>(); START initFilterSteps(buildTarget, goToolchain, platform, fileTypes); END } instead of initializing `filterSteps` in `initFilterSteps` could you do the following? ``` filterSteps = createFilterSteps(buildTarget, goToolchain, platform, fileTypes); ```

Target:
public FilteredSourceFiles( List<Path> rawSrcFiles, BuildTarget buildTarget, GoToolchain goToolchain, GoPlatform platform, List<FileType> fileTypes) { this(rawSrcFiles, ImmutableList.of(), buildTarget, goToolchain, platform, fileTypes); }
Source:
START public static char complementBase(char base, boolean RNA) { END if (base == 'A' && RNA) return 'U'; if (base == 'A') return 'T'; if (base == 'T' && !RNA) return 'A'; if (base == 'U' && RNA) return 'A'; if (base == 'C') return 'G'; if (base == 'G') return 'C'; return ' '; } Isn't this already present elsewhere in biojava?

Target:
protected static char complementBase(char base, boolean RNA) { if (base == 'A' && RNA) return 'U'; if (base == 'A') return 'T'; if (base == 'T' && !RNA) return 'A'; if (base == 'U' && RNA) return 'A'; if (base == 'C') return 'G'; if (base == 'G') return 'C'; return ' '; }
Source:
public TCCLObjectInputStream(InputStream in) throws IOException { super(in); START this.classLoader = Thread.currentThread().getContextClassLoader(); END } Replace with `this(in, null)`

Target:
public TCCLObjectInputStream(InputStream in) throws IOException { this(in, null); }
Source:
private void run() { try { boolean valid = connectionSanityCheck.isValid(); if (!valid) { onInvalidConnection.run(); } } catch (Exception e) { START logger.warn("Impossible to correctly monitor the Axon Server connection state."); END } } Add the cause to the log.

Target:
private void run() { try { boolean valid = connectionSanityCheck.isValid(); if (!valid) { onInvalidConnection.run(); } } catch (Exception e) { logger.warn("Impossible to correctly monitor the Axon Server connection state.", e); } }
Source:
protected String getStateParameter(final WebContext context) { START final String stateParameter; END final String stateData = getState(); if (CommonHelper.isNotBlank(stateData)) { stateParameter = stateData; } else { stateParameter = CommonHelper.randomString(10); } return stateParameter; } Why did you remove the `stateData`?

Target:
protected String getStateParameter(final WebContext context) { final String stateParameter; if (CommonHelper.isNotBlank(stateData)) { stateParameter = stateData; } else { stateParameter = CommonHelper.randomString(10); } return stateParameter; }
Source:
public DSpaceCommandLineParameter(String parameter) { START this(StringUtils.substringBefore(parameter, " "), StringUtils.substringAfter(parameter, " ")); END } This logic seems potentially fragile. What if someone accidentally types in *two spaces*, e.g. `-c[space][space]test`. Also, have you investigated whether there is a way to potentially use the tools/API in Apache Commons CLI to do this parameter parsing for us (instead of doing string parsing)? If we could just use that CLI API directly, it'd be better than rewriting it ourselves.

Target:
protected DSpaceCommandLineParameter(String parameter) { this(StringUtils.substringBefore(parameter, " "), StringUtils.substringAfter(parameter, " ")); }
Source:
protected Transferable createTransferable(JComponent c) { indices = list.getSelectedIndices(); START if (list.isSelectionEmpty()) return null; END return new ActionTransferable((ArrayList<Action>) list.getSelectedValuesList()); } Does this have to be after the above line? Seems like it may as well be right before. Or you could just check that the returned list is empty. Or you can do both.

Target:
protected Transferable createTransferable(JComponent c) { if (list.isSelectionEmpty()) return null; indices = list.getSelectedIndices(); return new ActionTransferable((ArrayList<Action>) list.getSelectedValuesList()); }
Source:
public List<NimbusInfo> getAllNimbuses() { List<NimbusInfo> nimbusInfos = new ArrayList<>(); try { Collection<Participant> participants = leaderLatch.get().getParticipants(); for (Participant participant : participants) { nimbusInfos.add(Zookeeper.toNimbusInfo(participant)); } } catch (Exception e) { LOG.warn("failed to get nimbuses", e); START } END return nimbusInfos; } Again don't eat the exception throw it, and wrap it if you cannot update the interface.

Target:
public List<NimbusInfo> getAllNimbuses() throws Exception { List<NimbusInfo> nimbusInfos = new ArrayList<>(); Collection<Participant> participants = leaderLatch.get().getParticipants(); for (Participant participant : participants) { nimbusInfos.add(Zookeeper.toNimbusInfo(participant)); } return nimbusInfos; }
Source:
START protected void doBegin() throws TransactionException { END if (txManager == null) { throw new IllegalStateException(CoreMessages .objectNotRegistered("javax.transaction.TransactionManager", "Transaction Manager").getMessage()); } try { txManager.setTransactionTimeout(getTimeoutInSeconds()); txManager.begin(); synchronized (this) { transaction = txManager.getTransaction(); } } catch (Exception e) { throw new TransactionException(cannotStartTransaction("XA"), e); } } deprecate this

Target:
protected void doBegin() throws TransactionException { if (txManager == null) { throw new IllegalStateException(objectNotRegistered("javax.transaction.TransactionManager", "Transaction Manager") .getMessage()); } try { txManager.setTransactionTimeout(getTimeoutInSeconds()); txManager.begin(); synchronized (this) { transaction = txManager.getTransaction(); } } catch (Exception e) { throw new TransactionException(cannotStartTransaction("XA"), e); } }
Source:
public int hashCode() { int hash = 7; hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0); START return hash; END } Why not use `org.modeshape.common.util.HashCode.compute(...)` instead of this? Or better yet, why not just return `name.hashCode()`? (When can `name` be null?)

Target:
public int hashCode() { return name.hashCode(); }
Source:
public void postProcessRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; frontendMetrics.securityServicePostProcessRequestRate.mark(); long startTimeMs = System.currentTimeMillis(); if (!isOpen) { exception = new RestServiceException("SecurityService is closed", RestServiceErrorCode.ServiceUnavailable); } else if (restRequest == null || callback == null) { throw new IllegalArgumentException("RestRequest or Callback is null"); } START callback.onCompletion(null, exception); END frontendMetrics.securityServicePostProcessRequestTimeInMs.update(System.currentTimeMillis() - startTimeMs); } this should be before the callback I think

Target:
public void postProcessRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; frontendMetrics.securityServicePostProcessRequestRate.mark(); long startTimeMs = System.currentTimeMillis(); if (!isOpen) { exception = new RestServiceException("SecurityService is closed", RestServiceErrorCode.ServiceUnavailable); } else if (restRequest == null || callback == null) { throw new IllegalArgumentException("RestRequest or Callback is null"); } frontendMetrics.securityServicePostProcessRequestTimeInMs.update(System.currentTimeMillis() - startTimeMs); callback.onCompletion(null, exception); }
Source:
START private IMethod[] END toArray(List<IMethod> methods) { return methods.toArray(new IMethod[methods.size()]); } static

Target:
private static IMethod[] toArray(List<IMethod> methods) { return methods.toArray(new IMethod[methods.size()]); }
Source:
public UserProfileParameters() { START profile.setId(Guid.newGuid()); END } update wouldn't work if the id is always a new id setting a new id is the job of add command

Target:
public UserProfileParameters() { }
Source:
public void onActivityPaused(Activity activity) { if (null != mCurInAppNotification) { START mCurInAppNotification.dismiss(); END } } It is safe to call dismiss multiple times, in the source for dismiss(), there's a nice global if check along the lines of (mView != null && isVisible()) or something.

Target:
public void onActivityPaused(Activity activity)
Source:
START public void createReplyReplyDone() { END createButton(buttonparent, buttonReply_ID, buttonReply_caption, true); createButton(buttonparent, buttonReplyDone_ID, buttonReplyDone_caption, true); buttonBar.pack(); } Done

Target:
private void createReplyReplyDone() { createButton(buttonparent, buttonReply_ID, buttonReply_caption, true); createButton(buttonparent, buttonReplyDone_ID, buttonReplyDone_caption, true); buttonBar.pack(); }
Source:
public void noMoreBubble() { config.setProperty(PARTITION_OPERATION_THREAD_COUNT.getName(), "1"); initExecutor(); final DummyPartitionTaskFactory taskFactory = new DummyPartitionTaskFactory(); taskFactory.delayMs = 1000; executor.executeOnPartitions(taskFactory, newPartitions()); final DummyOperation op = new DummyOperation(); executor.execute(op); assertTrueEventually(new AssertTask() { @Override public void run() { assertTrue(op.completed); } START }, SECONDS.toMillis(5)); END } `SECONDS.toMillis(5)` -> `5`. Timeout parameter of `assertTrueEventually(..)` is in seconds, not milliseconds.

Target:
public void noMoreBubble() { config.setProperty(PARTITION_OPERATION_THREAD_COUNT.getName(), "1"); initExecutor(); final DummyPartitionTaskFactory taskFactory = new DummyPartitionTaskFactory(); taskFactory.delayMs = 1000; executor.executeOnPartitions(taskFactory, newPartitions()); final DummyOperation op = new DummyOperation(); executor.execute(op); assertTrueEventually(new AssertTask() { @Override public void run() { assertTrue(op.completed); } }, 5); }
Source:
public void equal_shouldReturnTrueIfObjectReferenceAreTheSame() { CohortMembership cohortMembership = new CohortMembership(12); START boolean result = cohortMembership.equals(cohortMembership); END assertTrue(result); } I guess we could just assert without the temporary variable.

Target:
public void equal_shouldReturnTrueIfObjectReferenceAreTheSame() { CohortMembership cohortMembership = new CohortMembership(12); assertTrue(cohortMembership.equals(cohortMembership)); }
Source:
START public DynamicState withPendingLocalization(Future<Void> pendingDownload) { END return new DynamicState(this.state, this.newAssignment, this.container, this.currentAssignment, this.pendingLocalization, this.startTime, pendingDownload, this.profileActions, this.pendingStopProfileActions); } nit, could return: withPendingLocalization(this.pendingLocalization, pendingDownload);

Target:
public DynamicState withPendingLocalization(Future<Void> pendingDownload) { return withPendingLocalization(this.pendingLocalization, pendingDownload); }
Source:
public boolean verifyUser(String username, String password, ESClientVersionInfo clientVersionInfo) { try { final Optional<ESAuthenticationInformation> information = doVerifyUser(username, password, clientVersionInfo); if (!information.isPresent()) { /* to many bad attempts, otherwise we get an exception */ ModelUtil.logWarning( MessageFormat.format(Messages.LoginService_VerifyUserTooManyFailedRequests, username, delay)); } return START information.isPresent(); END } catch (final AccessControlException ex) { /* regular bad attempt */ return false; } } We could also return true here, which seems to be more obvious to me

Target:
public boolean verifyUser(String username, String password, ESClientVersionInfo clientVersionInfo) { try { final Optional<ESAuthenticationInformation> information = doVerifyUser(username, password, clientVersionInfo); if (!information.isPresent()) { /* too many bad attempts, otherwise we get an exception */ ModelUtil.logWarning( MessageFormat.format(Messages.LoginService_VerifyUserTooManyFailedRequests, username, delay)); } return true; } catch (final AccessControlException ex) { /* regular bad attempt */ return false; } }
Source:
public void test() throws Exception { ExternalBuildReport report = new ExternalBuildReport("http://some.url.com"); assertEquals("View External Report", report.getDisplayName()); assertEquals("graph.gif", report.getIconFileName()); START assertEquals("graph.gif", report.getIconFileName()); END assertEquals("http://some.url.com", report.getUrlName()); assertEquals(null, report.getTarget()); } duplicate assert

Target:
public void test() throws Exception { ExternalBuildReport report = new ExternalBuildReport("http://some.url.com"); assertEquals("View External Report", report.getDisplayName()); assertEquals("graph.gif", report.getIconFileName()); assertEquals("http://some.url.com", report.getUrlName()); assertEquals(null, report.getTarget()); }
Source:
public void publishEvent(Object event) { START publishEvent(new PayloadApplicationEvent<Object>(null, event)); END } The null `source` looks odd.

Target:
public void publishEvent(Object event) { publishEvent(new PayloadApplicationEvent<>(this, event)); }
Source:
public boolean isList() { START if (isProperty) END return prop.isList(); else return false; } Personally for all these simple things, I would simple it down to a ternary operation for code simplicity. Always keep in mind code size.

Target:
public boolean isList() { return isProperty && prop.isList(); }
Source:
private GlusterGeoRepSession getGeoRepSession() { if (getParameters().getGeoRepSessionId() != null) { return geoRepDao.getById(getParameters().getGeoRepSessionId()); } START return null; END } I don't think we need this check nor this method. simply call geoRepDao.getById(getParameters().getGeoRepSessionId()) when needed, if getParameters().getGeoRepSessionId() we will simply won't get any result

Target:
private GlusterGeoRepSession getGeoRepSession() { return geoRepDao.getById(getParameters().getGeoRepSessionId()); }
Source:
protected Statement createFailOnTimeoutStatement( START Statement statement, Description description) throws Exception { END return FailOnTimeout.builder() .withTimeout(timeout, timeUnit) .withLookingForStuckThread(lookForStuckThread) .withDescription(description) .build(statement); } Unfortunately this method is protected. Changing the signature may break someone. @junit-team/junit-committers how should we handle this? We could not add the new feature without breaking the extension point. I'm in favour of modifying the methods signature and making it private. Users should create a new rule instead of extending Timeout. They could use the builder for creating the statement.

Target:
private Statement createFailOnTimeoutStatement( Statement statement, Description description) throws Exception { return FailOnTimeout.builder() .withDescription(description) .build(createFailOnTimeoutStatement(statement)); }
Source:
@Override public Iterator<? extends TripPatternInfo<TripSchedule>> patternIterator( IntIterator stops ) { Set<TripPatternInfo<TripSchedule>> activeTripPatternsForGivenStops = new HashSet<>(); int stopIndex = stops.next(); while (stopIndex > 0) { activeTripPatternsForGivenStops.addAll(activeTripPatternsPerStop.get(stopIndex)); stopIndex = stops.next(); } START return activeTripPatternsForGivenStops.iterator(); END } The loop fails if `stops` contains _the first_ stop (`0`). The method should be: ``` Set<TripPatternInfo<TripSchedule>> activeTripPatternsForGivenStops = new HashSet<>(); while (stops.hasNext()) { activeTripPatternsForGivenStops.addAll(activeTripPatternsPerStop.get(stops.next())); } return activeTripPatternsForGivenStops.iterator(); ```

Target:
@Override public Iterator<? extends TripPatternInfo<TripSchedule>> patternIterator( IntIterator stops ) { Set<TripPatternInfo<TripSchedule>> activeTripPatternsForGivenStops = new HashSet<>(); while (stops.hasNext()) { activeTripPatternsForGivenStops.addAll(activeTripPatternsPerStop.get(stops.next())); } return activeTripPatternsForGivenStops.iterator(); }
Source:
public ContextHolder(T context, Class<T> type, Set<Annotation> qualifiers) { this.context = context; this.type = type; START this.qualifiers = asSet(DefaultLiteral.INSTANCE, AnyLiteral.INSTANCE); END this.qualifiers.addAll(qualifiers); } This is likely unnecessary. The set of qualifiers is expected to contain all elements. See also `org.jboss.weld.bootstrap.WeldStartup.createContexts(ServiceRegistry)` and other places where this constructor is used.

Target:
public ContextHolder(T context, Class<T> type, Set<Annotation> qualifiers) { this.context = context; this.type = type; this.qualifiers = qualifiers; }
Source:
public void setUp() { START jenkins.CLI.get().setEnabled(true); END Set<String> agentProtocols = new HashSet<>(j.jenkins.getAgentProtocols()); agentProtocols.add(ExtensionList.lookupSingleton(CliProtocol2.class).getName()); j.jenkins.setAgentProtocols(agentProtocols); } Unnecessary; it is still enabled by default in core, disabled in wizard.

Target:
public void setUp() { Set<String> agentProtocols = new HashSet<>(j.jenkins.getAgentProtocols()); agentProtocols.add(ExtensionList.lookupSingleton(CliProtocol2.class).getName()); j.jenkins.setAgentProtocols(agentProtocols); }
Source:
public FieldWrapper(HighlightExecutionContext executionContext, HighlighterContext context, BasicQueryWeigher weigher) { this.executionContext = executionContext; this.context = context; this.weigher = weigher; this.positionGap = START 1; END } There is a lack of symmetry here. `positionGap` should be initialized in both ctors.

Target:
public FieldWrapper(HighlightExecutionContext executionContext, HighlighterContext context, BasicQueryWeigher weigher) { this.executionContext = executionContext; this.context = context; this.weigher = weigher; }
Source:
public StripeFooter(List<Stream> streams, List<ColumnEncoding> columnEncodings, List<Slice> stripeEncryptionGroups) { this.streams = ImmutableList.copyOf(requireNonNull(streams, "streams is null")); this.columnEncodings = ImmutableList.copyOf(requireNonNull(columnEncodings, "columnEncodings is null")); START this.stripeEncryptionGroups = requireNonNull(stripeEncryptionGroups, "stripeEncryptionGroups is null"); END } `ImmutableList.copyOf`

Target:
public StripeFooter(List<Stream> streams, List<ColumnEncoding> columnEncodings, List<Slice> stripeEncryptionGroups) { this.streams = ImmutableList.copyOf(requireNonNull(streams, "streams is null")); this.columnEncodings = ImmutableList.copyOf(requireNonNull(columnEncodings, "columnEncodings is null")); this.stripeEncryptionGroups = ImmutableList.copyOf(requireNonNull(stripeEncryptionGroups, "stripeEncryptionGroups is null")); }
Source:
public Double getValue() { //do not miss the last tuple try { START estimator.accumulate(cx); END } catch (ExecException ex) { throw new RuntimeException("Error while accumulating sample frequency: " + ex); } return estimator.getEntropy(); } i'm not sure how getValue() is supposed to be called, but I would make it work correctly even if it is called twice. that is, set cx back to zero after you accumulate.

Target:
public Double getValue() { //do not miss the last tuple try { this.estimator.accumulate(this.cx); } catch (ExecException ex) { throw new RuntimeException("Error while accumulating sample frequency: " + ex); } return this.estimator.getEntropy(); }
Source:
private boolean usesCatalogsAsSchemas(DatabaseMetaData metaData) { boolean result = true; ResultSet rs = null; try { rs = metaData.getSchemas(); while (rs.next() && result) { result = false; } } catch (SQLException e) { throw JdbcUtils.wrapException(e, "retrieve schema and catalog metadata", JdbcActionType.METADATA); } finally { FileHelper.safeClose(rs); START close(null); END } return result; } Hmm I think we should remove this line. Seems like it's not needed since `close(null)` will just do nothing. Maybe it's a left-over line from some previous version of the file where the result set got closed properly or something :-)

Target:
private boolean usesCatalogsAsSchemas(DatabaseMetaData metaData) { boolean result = true; ResultSet rs = null; try { rs = metaData.getSchemas(); while (rs.next() && result) { result = false; } } catch (SQLException e) { throw JdbcUtils.wrapException(e, "retrieve schema and catalog metadata", JdbcActionType.METADATA); } finally { FileHelper.safeClose(rs); } return result; }
Source:
public void processCacheEntryDestroyed(CacheEntryRemovedEvent event) { if (!event.isPre()) { emitSessionDestroyedEvent((String) event.getKey()); } START } END those `if (!event.isPre())` can be avoided by adding `@Listener(observation = Observation.POST)` at class level

Target:
public void processCacheEntryDestroyed(CacheEntryRemovedEvent event) { emitSessionDestroyedEvent((String) event.getKey()); }
Source:
public void invalidate(@Nullable String path) { if (path == null) { START return; END } invalidate(Uri.parse(path)); } Flip the `if` and move the invalidate call up inside

Target:
public void invalidate(@Nullable String path) { if (path != null) { invalidate(Uri.parse(path)); } }
Source:
public MerlinBuilder withRxCallbacks() { rxCallbacksManager = new RxCallbacksManager(); if (connectableRegisterer == null && disconnectableRegisterer == null) { return this.withConnectableCallbacks().withDisconnectableCallbacks(); } else if (connectableRegisterer == null) { return this.withConnectableCallbacks(); } else if (disconnectableRegisterer == null) { return this.withDisconnectableCallbacks(); } START return this; END } could this block be simplified? ``` java public MerlinBuilder withRxCallbacks() { rxCallbacksManager = new RxCallbacksManager(); if (connectableRegisterer == null) { withConnectableCallbacks(); } if (disconnectableRegisterer == null) { withDisconnectableCallbacks(); } return this; } ```

Target:
public MerlinBuilder withRxCallbacks() { rxCallbacksManager = new RxCallbacksManager(); if (connectableRegisterer == null) { withConnectableCallbacks(); } if (disconnectableRegisterer == null) { withDisconnectableCallbacks(); } return this; }
Source:
public static String localizeProvider(String name) { if (name==null) { Assert.isTrue(false); return null; START } END switch (name) { case DIRECT_PROVIDER: return Messages.ProxySelector_0; case ECLIPSE_PROVIDER: return Messages.ProxySelector_1; case NATIVE_PROVIDER: return Messages.ProxySelector_2; default: break; } Assert.isTrue(false); return null; } I don't like this code duplication. How about if (name != null) { switch (name) { ... } } Assert.isTrue(false); return null;

Target:
public static String localizeProvider(String name) { if (name != null) { switch (name) { case DIRECT_PROVIDER: return Messages.ProxySelector_0; case ECLIPSE_PROVIDER: return Messages.ProxySelector_1; case NATIVE_PROVIDER: return Messages.ProxySelector_2; default: break; } } Assert.isTrue(false); return null; }
Source:
START public String removeSuffix(String loaderFileName, char suffixTerm) { END return loaderFileName.substring(0, loaderFileName.lastIndexOf(suffixTerm)); } Does this need to be public?

Target:
private String removeSuffix(String loaderFileName, char suffixTerm) { return loaderFileName.substring(0, loaderFileName.lastIndexOf(suffixTerm)); }
Source:
private BootstrapConfigurationImpl() { this.defaultProviderClassName = null; this.constraintValidatorFactoryClassName = null; this.messageInterpolatorClassName = null; this.traversableResolverClassName = null; this.parameterNameProviderClassName = null; this.clockProviderClassName = null; START this.valueExtractorClassNames = new HashSet<>( 0 ); END this.validatedExecutableTypes = DEFAULT_VALIDATED_EXECUTABLE_TYPES; this.isExecutableValidationEnabled = true; this.constraintMappingResourcePaths = newHashSet(); this.properties = newHashMap(); } Very minor but maybe let's make it consistent and initialize the set and map below in the same way? I had to check if there was a specific reason to initialize it this way compared to the others.

Target:
private BootstrapConfigurationImpl() { this.defaultProviderClassName = null; this.constraintValidatorFactoryClassName = null; this.messageInterpolatorClassName = null; this.traversableResolverClassName = null; this.parameterNameProviderClassName = null; this.clockProviderClassName = null; this.valueExtractorClassNames = new HashSet<>(); this.validatedExecutableTypes = DEFAULT_VALIDATED_EXECUTABLE_TYPES; this.isExecutableValidationEnabled = true; this.constraintMappingResourcePaths = new HashSet<>(); this.properties = new HashMap<>(); }
Source:
public static FileUtils.FileCopyResult copyToFileAndClose(InputStream is, File file) throws IOException { file.getParentFile().mkdirs(); try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { ByteStreams.copy(is, os); } finally { CloseQuietly.close(is); } START return FileUtils.FileCopyResult.buildResult(file.toPath()); END } I am concerned about the addition of buildResult here, since this will cause every single copy to read the data twice for the copy and for the checksum, instead of once as before, which could be expensive when dealing with large files and cause performance regressions.

Target:
public static long copyToFileAndClose(InputStream is, File file) throws IOException { file.getParentFile().mkdirs(); try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { return ByteStreams.copy(is, os); } finally { CloseQuietly.close(is); } }
Source:
START @Override public synchronized boolean cancel( final boolean mayInterruptIfRunning ) { END return canceled.compareAndSet( false, true ); } If you are using an AtomicBoolean (and dont do anything else), you no longer need the synchronized keyword here.

Target:
@Override public boolean cancel( final boolean mayInterruptIfRunning ) { return canceled.compareAndSet( false, true ); }
Source:
protected AbstractToolbarItem<S> getItem(final ToolbarCommand<?> command) { return items .entrySet() .stream() .filter(e -> e.getKey().equals(command)) .findFirst() .orElse(null) START .getValue(); END } hey @manstis , quick looking at this seems that a potential NPE can be produced here? I mean for `orElse(null).getValue()`?

Target:
protected AbstractToolbarItem<S> getItem(final ToolbarCommand<?> command) { return items .entrySet() .stream() .filter(e -> e.getKey().equals(command)) .findFirst() .map(Map.Entry::getValue) .orElse(null); }
Source:
public CellIdentityCdma() { START super(CellIdentityCdma.class.getSimpleName(), TYPE_CDMA, END null, null); mNetworkId = Integer.MAX_VALUE; mSystemId = Integer.MAX_VALUE; mBasestationId = Integer.MAX_VALUE; mLongitude = Integer.MAX_VALUE; mLatitude = Integer.MAX_VALUE; mAlphaLong = null; mAlphaShort = null; } TAG

Target:
public CellIdentityCdma() { super(TAG, TYPE_CDMA, null, null); mNetworkId = Integer.MAX_VALUE; mSystemId = Integer.MAX_VALUE; mBasestationId = Integer.MAX_VALUE; mLongitude = Integer.MAX_VALUE; mLatitude = Integer.MAX_VALUE; mAlphaLong = null; mAlphaShort = null; }
Source:
private void header(@NonNull final BecauseYouReadCard card) { CardLargeHeaderView header = new CardLargeHeaderView(getContext()) .setTitle(card.title()) .setSubtitle(card.subtitle()) START .setPageTitle(card.pageTitle().getDisplayText()) END .setImage(card.image()); header(header); } Would encapsulating the underlying implementation of BecauseYouReadCard be better or do we need the PageTitle elsewhere? I'm thinking of my recent PageTitle.getText() bug where I meant to call getDisplayText(). At least the bug could only live in one place. If we expose a large object like PageTitle, we have lots of flexibility to do things beyond what a Card is really meant for. There's some notes on some of the tradeoffs here: https://en.wikipedia.org/wiki/Law_of_Demeter.

Target:
private void header(@NonNull final BecauseYouReadCard card) { CardLargeHeaderView header = new CardLargeHeaderView(getContext()) .setTitle(card.title()) .setSubtitle(card.subtitle()) .setPageTitle(card.pageTitle()) .setImage(card.image()); header(header); }
Source:
private int getCheckTimeoutInSeconds(ConfigurationGenerator cg) { int checkTimeout = DEFAULT_CHECK_TIMEOUT_IN_SECONDS; try { START checkTimeout = Integer.parseInt(cg.getUserConfig().getProperty(PARAM_MONGODB_CHECK_TIMEOUT, DEFAULT_CHECK_TIMEOUT_IN_SECONDS.toString())); END } catch (NumberFormatException e) { log.warn(String.format("Invalid format for %s parameter, using default value instead", PARAM_MONGODB_CHECK_TIMEOUT), e); } return checkTimeout; } `DEFAULT_CHECK_TIMEOUT_IN_SECONDS.toString()` -> `String.valueOf(DEFAULT_CHECK_TIMEOUT_IN_SECONDS)` now that it's an `int`

Target:
private int getCheckTimeoutInSeconds(ConfigurationGenerator cg) { int checkTimeout = DEFAULT_CHECK_TIMEOUT_IN_SECONDS; try { checkTimeout = Integer.parseInt(cg.getUserConfig().getProperty(PARAM_MONGODB_CHECK_TIMEOUT, String.valueOf(DEFAULT_CHECK_TIMEOUT_IN_SECONDS))); } catch (NumberFormatException e) { log.warn(String.format("Invalid format for %s parameter, using default value instead", PARAM_MONGODB_CHECK_TIMEOUT), e); } return checkTimeout; }
Source:
private void closeConnection(String deviceId) { DeviceConfig device = deviceConfigCache.get(deviceId); if (device == null) { START logger.error("Could not find device '{}'", deviceId); END return; } EpsonProjectorDevice remoteController = device.getConnection(); if (remoteController != null) { try { logger.debug("Closing connection to device '{}' ", deviceId); remoteController.disconnect(); } catch (EpsonProjectorException e) { logger.debug("Error occurred when closing connection to device '{}'", deviceId); } } } This should be a WARN instead of an ERROR.

Target:
private void closeConnection(String deviceId) { DeviceConfig device = deviceConfigCache.get(deviceId); if (device == null) { logger.warn("Could not find device '{}'", deviceId); return; } EpsonProjectorDevice remoteController = device.getConnection(); if (remoteController != null) { try { logger.debug("Closing connection to device '{}' ", deviceId); remoteController.disconnect(); } catch (EpsonProjectorException e) { logger.debug("Error occurred when closing connection to device '{}'", deviceId); } } }
Source:
public void testSimpleAnnotation() { assertGeneratedMatches( START Lists.newArrayList("import javax.annotation.Nullable;"), END Lists.newArrayList("@Nullable"), Lists.newArrayList("@javax.annotation.Nullable")); } I'd prefer ImmutableList.of throughout.

Target:
public void testSimpleAnnotation() { assertGeneratedMatches( ImmutableList.of("import javax.annotation.Nullable;"), ImmutableList.of("@Nullable"), ImmutableList.of("@javax.annotation.Nullable")); }
Source:
public void testUnionPointWithEmptyLineString() { START assertUnion("POINT (1 2)", "LINESTRING EMPTY", "GEOMETRYCOLLECTION (POINT (1 2))"); END } I'd expect the union of `POINT (1, 2)` and `LINESTRING EMPTY` to be `POINT (1, 2)`, but this test asserts the result to be `GEOMETRYCOLLECTION (POINT (1 2))`.

Target:
public void testUnionPointWithEmptyLineString() { assertUnion("POINT (1 2)", "LINESTRING EMPTY", "POINT (1 2)"); }
Source:
START public Layers(EntityLivingBase entity, RenderLivingBase<T> entityRenderer, LayerRenderer<T> layerRenderer, double x, double y, double z) END { super(entity, entityRenderer, x, y, z); this.layerRenderer = layerRenderer; } protected?

Target:
protected Layers(EntityLivingBase entity, RenderLivingBase<T> entityRenderer, LayerRenderer<T> layerRenderer, double x, double y, double z) { super(entity, entityRenderer, x, y, z); this.layerRenderer = layerRenderer; }
Source:
public void deleteOldDeployments(final IServer server) throws CoreException { File deploymentsRootFolder = getDeploymentsRootFolder(); Arrays.stream(server.getModules()) START .forEach(module -> deleteOldDeployment(module, deploymentsRootFolder)); END } Seems the output name cache should be reset here, not below.

Target:
public void deleteOldDeployments(final IServer server) throws CoreException { File deploymentsRootFolder = getDeploymentsRootFolder(); Arrays.stream(server.getModules()) .forEach(module -> deleteOldDeployment(module, deploymentsRootFolder, server)); }
Source:
public CronTab(String format, int line, Hash hash) throws ANTLRException { START set(format, line, hash); END } I would recommend to use <code>this()</code> in this constructor

Target:
public CronTab(String format, int line, Hash hash) throws ANTLRException { this(format, line, hash, null); }
Source:
public boolean isKeyFrame(byte[] buff, int off, int len) { START if (buff == null || len < 1 || buff.length < len) END { return false; } int nalType = buff[off] & kTypeMask; // Single NAL Unit Packet if (nalType == kFuA) { // Fragmented NAL units (FU-A). if (parseFuaNaluForKeyFrame(buff, off, len)) { return true; } } else { if (parseSingleNaluForKeyFrame(buff, off, len)) { return true; } } return false; } @mdaneshi, do you think it would make sense to have something like this in every static methods that you wrote? ``` if (buf == null || Math.min(buf.length, len) < off + 1 /* required array length for this method to work correctly */) { return false; } ``` I know this is not a common practice currently in libjitsi and we sometimes are a little sloppy when we access arrays, but I believe we should change this and write more defensive code whenever possible.

Target:
public static boolean isKeyFrame(byte[] buff, int off, int len) { if (buff == null || buff.length < off + Math.max(len, 1)) { return false; } int nalType = buff[off] & kTypeMask; // Single NAL Unit Packet if (nalType == kFuA) { // Fragmented NAL units (FU-A). if (parseFuaNaluForKeyFrame(buff, off, len)) { return true; } } else { if (parseSingleNaluForKeyFrame(buff, off, len)) { return true; } } return false; }
Source:
START public ResponseEntity<?> delete(@RequestBody List<Long> printerIds) throws IOException { END for (long id : printerIds) { Printer printer = printerService.get(id); if (printer != null) { printerService.remove(printer); } } return new ResponseEntity<>(HttpStatus.OK); } `@ResponseStatus(HttpStatus.NO_RESPONSE)` Then you can change return type to void and remove the return statement

Target:
public void delete(@RequestBody List<Long> printerIds) throws IOException { for (long id : printerIds) { Printer printer = printerService.get(id); if (printer != null) { printerService.remove(printer); } } }
Source:
public DiskWriteModel getDisk(int deviceId) { return fDisks.computeIfAbsent(deviceId, k -> new START DiskWriteModel(deviceId, checkNotNull(getStateSystemBuilder()))); END } Use k, like you did in the other files

Target:
public DiskWriteModel getDisk(int deviceId) { return fDisks.computeIfAbsent(deviceId, k -> new DiskWriteModel(k, checkNotNull(getStateSystemBuilder()))); }
Source:
public void testIsConditionValidWhenHeaderIsValid() throws Exception { final ConditionCol52 conditionCol1 = fakeConditionCol52("header1"); final ConditionCol52 conditionCol2 = fakeConditionCol52("header2"); final Validator validator = new Validator(fakeCompositeColumn(conditionCol1, conditionCol2)); START assertFalse(validator.isConditionValid(conditionCol2)); END } In the context of GUVNOR-2821 I would expect `assertTrue` here, can you please update the `fakeConditionCol52` method to achieve this? Let me know if you don't see my point.

Target:
public void testIsConditionValidWhenHeaderIsValid() throws Exception { final ConditionCol52 conditionCol1 = fakeConditionCol52("header1"); final ConditionCol52 conditionCol2 = fakeConditionCol52("header2"); final Validator validator = new Validator(fakeCompositeColumn(conditionCol1, conditionCol2)); assertTrue(validator.isConditionValid(conditionCol2)); }
Source:
public StatsManagerMetrics(MetricRegistry registry) { START this.registry = registry; END statsPublishFailureCount = registry.counter(MetricRegistry.name(StatsManager.class, "StatsPublishFailureCount")); totalFetchAndAggregateTime = registry.histogram(MetricRegistry.name(StatsManager.class, "TotalFetchAndAggregateTime")); fetchAndAggregateTimePerStore = registry.histogram(MetricRegistry.name(StatsManager.class, "FetchAndAggregateTimePerStore")); } does this need to be a class member?

Target:
public StatsManagerMetrics(MetricRegistry registry) { statsPublishFailureCount = registry.counter(MetricRegistry.name(StatsManager.class, "StatsPublishFailureCount")); totalFetchAndAggregateTime = registry.histogram(MetricRegistry.name(StatsManager.class, "TotalFetchAndAggregateTime")); fetchAndAggregateTimePerStore = registry.histogram(MetricRegistry.name(StatsManager.class, "FetchAndAggregateTimePerStore")); }
Source:
BlobStatus(List<String> replicaList) { if (replicaList != null && replicaList.size() > 0) { unavailable.addAll(replicaList); } START } END minor: the `replicaList.size() > 0` check isn't really needed

Target:
BlobStatus(List<String> replicaList) { if (replicaList != null) { unavailable.addAll(replicaList); } }
Source:
START protected MemcachedClientCallback createMemcachedClientCallback() { END return new MemcachedClientCallback() { @Override public byte[] get(final String key) throws IOException { return _memcached.get(_memcachedNodesManager.getStorageKeyFormat().format( key )); } }; } MemcachedClientCallback should be renamed to StorageClientCallback

Target:
protected MemcachedClientCallback createMemcachedClientCallback() { return new MemcachedClientCallback() { @Override public byte[] get(final String key) { return _memcached.get(_memcachedNodesManager.getStorageKeyFormat().format( key )); } }; }
Source:
public void clientId() throws IOException { START Stripe.clientId = "ca_test"; END chargeBody = resource("charge.json"); } Your tests don't rely on `Stripe.clientId` at all, so you should remove this line, rename the method, and get rid of `tearDownMockAndClientId()` entirely.

Target:
public void clientId() throws IOException { chargeBody = resource("charge.json"); }
Source:
private XADataSource createXaDataSourceInstance(String className) { try { Class<?> dataSourceClass = ClassUtils.forName(className, this.getClass().getClassLoader()); Object instance = BeanUtils.instantiate(dataSourceClass); Assert.isInstanceOf(XADataSource.class, instance); return (XADataSource) instance; } catch (Exception ex) { throw new IllegalStateException( START "Unable to create XADataSource instance from '" + className + "'"); END } } Maybe it would be good to include the causing exception so user knows why it couldn't be created.

Target:
private XADataSource createXaDataSourceInstance(String className) { try { Class<?> dataSourceClass = ClassUtils.forName(className, this.getClass().getClassLoader()); Object instance = BeanUtils.instantiate(dataSourceClass); Assert.isInstanceOf(XADataSource.class, instance); return (XADataSource) instance; } catch (Exception ex) { throw new IllegalStateException( "Unable to create XADataSource instance from '" + className + "'", ex); } }
Source:
protected Optional<ExampleProjectError> getError(Path projectPath) { POM pom = this.getPom(pomService, projectPath); START if (pom.getModules().isEmpty() || pom.getModules() == null) { END return Optional.empty(); } else { return Optional.of(new ExampleProjectError(CheckModulesValidator.class.getCanonicalName(), "")); } } You need to swap the order of nullcheck / isEmpty, otherwise it will lead to NPE (if getModules returns null, not sure that's possible) and this validator will fail.

Target:
protected Optional<ExampleProjectError> getError(Path projectPath) { POM pom = this.getPom(pomService, projectPath); if (pom.getModules() == null || pom.getModules().isEmpty()) { return Optional.empty(); } else { return Optional.of(new ExampleProjectError(CheckModulesValidator.class.getCanonicalName(), "")); } }
Source:
public boolean isOpen() { START return mBaseTransport.isOpen() && mTransport != null && mTransport.isOpen(); END } When is `mTransport == null`? Isn't it always set to something in `open()`? Also, why do you need to check `mBaseTransport`?

Target:
public boolean isOpen() { return mTransport != null && mTransport.isOpen(); }
Source:
public static void restoreSystemProperties() { System.clearProperty("org.uberfire.nio.git.daemon.enabled"); START System.clearProperty("org.uberfire.nio.git.ssh.enabled"); END System.clearProperty("org.uberfire.sys.repo.monitor.disabled"); } why enabled? why restore those?

Target:
public static void restoreSystemProperties() { System.clearProperty("org.uberfire.sys.repo.monitor.disabled"); System.clearProperty("org.uberfire.nio.git.daemon.enabled"); System.clearProperty("org.uberfire.nio.git.ssh.enabled"); System.clearProperty("org.uberfire.sys.repo.monitor.disabled"); }
Source:
protected void patch(Context context, HttpServletRequest request, String apiCategory, String model, UUID id, Patch patch) throws AuthorizeException, SQLException { final Group group = dsoService.find(context, id); if (group != null && isPatchUnprocessable(context, group)) { START throw new UnprocessableEntityException("This group cannot be patched."); END } patchDSpaceObject(apiCategory, model, id, patch); } I'd rather see more specific error messages here, as there's a few different scenarios here we should be aware of: * A permanent group's name can *never* be patched. But, its description can be updated. * Same with a Community/Collection group's name (not editable) & description (editable), unless it's detached. In which case it can be patched. So, at a minimum, it seems like we need different errors & checks here. Permanent groups can *never* have name updates, but can have description updates. Community/Collection groups can be updated if the Community/Collection is deleted, but are otherwise considered "permanent".

Target:
protected void patch(Context context, HttpServletRequest request, String apiCategory, String model, UUID id, Patch patch) throws AuthorizeException, SQLException { patchDSpaceObject(apiCategory, model, id, patch); }
Source:
protected String computeMetricName(Message<?> message) { START String counterName = nameExpression.getValue(evaluationContext, message, CharSequence.class).toString(); END return counterName; } no need to assign to counterName just to return on next line. However, we probably should add a null check for the evaluationContext.

Target:
protected String computeMetricName(Message<?> message) { return nameExpression.getValue(evaluationContext, message, CharSequence.class).toString(); }
Source:
public boolean supportsBitmapIndex(final BitmapIndexSelector selector) { // We can operate on bitmap indexes if this is a constant expression, or if it reads one column that has // an index and does not have multiple values. The lack of multiple values is important because expression // filters treat multi-value arrays as nulls, which doesn't permit index based filtering. START return requiredBindings.isEmpty() END || (requiredBindings.size() == 1 && selector.getBitmapIndex(Iterables.getOnlyElement(requiredBindings)) != null && !selector.hasMultipleValues(Iterables.getOnlyElement(requiredBindings))); } Could you break this statement into multiple for readability?

Target:
public boolean supportsBitmapIndex(final BitmapIndexSelector selector) { if (requiredBindings.isEmpty()) { // Constant expression. return true; } else if (requiredBindings.size() == 1) { // Single-column expression. We can use bitmap indexes if this column has an index and does not have // multiple values. The lack of multiple values is important because expression filters treat multi-value // arrays as nulls, which doesn't permit index based filtering. final String column = Iterables.getOnlyElement(requiredBindings); return selector.getBitmapIndex(column) != null && !selector.hasMultipleValues(column); } else { // Multi-column expression. return false; } }
Source:
START public END void setM(Market currentMarket) { this.currentMarket = currentMarket; } this method should be changed to private

Target:
private void setM(Market currentMarket) { this.currentMarket = currentMarket; }
Source:
private long countMapWithAtleastOneQueryCache(Node node) { return maps.stream().filter(distributedObject -> { MapConfig config = node.getConfig().getMapConfig(distributedObject.getName()); if (config != null) { START return config.getQueryCacheConfigs().size() >= 1; END } return false; }).count(); } Please write it as `!config.getQueryCacheConfigs().isEmpty()` instead of checking the size.

Target:
private long countMapWithAtleastOneQueryCache(Node node) { return maps.stream().filter(distributedObject -> { MapConfig config = node.getConfig().getMapConfig(distributedObject.getName()); if (config != null) { return !config.getQueryCacheConfigs().isEmpty(); } return false; }).count(); }
Source:
public void addModifiedColumns( GlobalConfiguration globalCfg, Value value, Element parent, PropertyAuditingData propertyAuditingData) { String columnName = propertyAuditingData.getModifiedFlagName(); if ( propertyAuditingData.isModifiedFlagNameExplicitlySpecified() ) { columnName = propertyAuditingData.getExplicitModifiedFlagName(); START } END MetadataTools.addModifiedFlagProperty( parent, propertyAuditingData.getName(), globalCfg.getModifiedFlagSuffix(), columnName ); } probably it is better to change it to ``` String columnName; if ( propertyAuditingData.isModifiedFlagNameExplicitlySpecified() ) { columnName = propertyAuditingData.getExplicitModifiedFlagName(); } else { columnName = propertyAuditingData.getModifiedFlagName(); } ```

Target:
public void addModifiedColumns( GlobalConfiguration globalCfg, Value value, Element parent, PropertyAuditingData propertyAuditingData) { final String columnName; if ( propertyAuditingData.isModifiedFlagNameExplicitlySpecified() ) { columnName = propertyAuditingData.getExplicitModifiedFlagName(); } else { columnName = propertyAuditingData.getModifiedFlagName(); } MetadataTools.addModifiedFlagProperty( parent, propertyAuditingData.getName(), globalCfg.getModifiedFlagSuffix(), columnName ); }
Source:
private boolean isFailedEqualityComparison(Throwable exception) { if (!(exception instanceof ConditionNotSatisfiedError)) return false; START final ConditionNotSatisfiedError conditionNotSatisfiedError = (ConditionNotSatisfiedError) exception; END Condition condition = conditionNotSatisfiedError.getCondition(); ExpressionInfo expr = condition.getExpression(); return expr != null && expr.isEqualityComparison() && // it is equality conditionNotSatisfiedError.getCause() == null; // and it is not failed because of exception } Why is this final and condition not? Same issue on line 130. Since final is normally not used for local variables in spock, I'd remove it.

Target:
private boolean isFailedEqualityComparison(Throwable exception) { if (!(exception instanceof ConditionNotSatisfiedError)) return false; ConditionNotSatisfiedError conditionNotSatisfiedError = (ConditionNotSatisfiedError) exception; Condition condition = conditionNotSatisfiedError.getCondition(); ExpressionInfo expr = condition.getExpression(); return expr != null && expr.isEqualityComparison() && // it is equality conditionNotSatisfiedError.getCause() == null; // and it is not failed because of exception }