auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START boolean hasInflightBatches(TopicPartition topicPartition) { END return topicPartitionBookkeeper.contains(topicPartition) && !topicPartitionBookkeeper.getPartition(topicPartition).inflightBatchesBySequence.isEmpty(); } Does this method need to be synchronized?

Target:
synchronized boolean hasInflightBatches(TopicPartition topicPartition) { return topicPartitionBookkeeper.contains(topicPartition) && !topicPartitionBookkeeper.getPartition(topicPartition).inflightBatchesBySequence.isEmpty(); }
Source:
protected void executeQueryCommand() { List<GlusterServerService> serviceList = null; if(getParameters().getServiceType() == null) { serviceList = getGlusterServerServiceDao().getByClusterId(getParameters().getId()); } else { serviceList = getGlusterServerServiceDao().getByClusterIdAndServiceType(getParameters().getId(), getParameters().getServiceType()); } START if(serviceList != null && serviceList.size() > 0) { END getQueryReturnValue().setReturnValue(serviceList); } } Question (matter of choise) - don't you prefer to set it anyway? if serverList is null or empty, setReurnValue will contain a null or empty list -what's the problem with that?

Target:
protected void executeQueryCommand() { List<GlusterServerService> serviceList = null; if(getParameters().getServiceType() == null) { serviceList = getGlusterServerServiceDao().getByClusterId(getParameters().getId()); } else { serviceList = getGlusterServerServiceDao().getByClusterIdAndServiceType(getParameters().getId(), getParameters().getServiceType()); } getQueryReturnValue().setReturnValue(serviceList); }
Source:
START ViewerSorter createSorterInstance() throws CoreException { END Object contributed = element.createExecutableExtension(ATT_CLASS); if (contributed instanceof ViewerSorter) { return (ViewerSorter) contributed; } if (contributed instanceof ViewerComparator) { return new WrappedViewerComparator((ViewerComparator) contributed); } throw new ClassCastException("Class contributed by " + element.getNamespaceIdentifier() + //$NON-NLS-1$ " to " + INavigatorContentExtPtConstants.TAG_NAVIGATOR_CONTENT + //$NON-NLS-1$ "/" + INavigatorContentExtPtConstants.TAG_COMMON_SORTER //$NON-NLS-1$ + " is not an instance of " + ViewerComparator.class.getName() + ": " + contributed.getClass().getName() //$NON-NLS-1$ //$NON-NLS-2$ ); } Why package-visible?

Target:
private ViewerSorter createSorterInstance() throws CoreException { Object contributed = element.createExecutableExtension(ATT_CLASS); if (contributed instanceof ViewerSorter) { return (ViewerSorter) contributed; } if (contributed instanceof ViewerComparator) { return new WrappedViewerComparator((ViewerComparator) contributed); } throw new ClassCastException("Class contributed by " + element.getNamespaceIdentifier() + //$NON-NLS-1$ " to " + INavigatorContentExtPtConstants.TAG_NAVIGATOR_CONTENT + //$NON-NLS-1$ "/" + INavigatorContentExtPtConstants.TAG_COMMON_SORTER //$NON-NLS-1$ + " is not an instance of " + ViewerComparator.class.getName() + ": " + contributed.getClass().getName() //$NON-NLS-1$ //$NON-NLS-2$ ); }
Source:
public <X> X unwrap(Long value, Class<X> type, WrapperOptions options) { START log.debug( " unwrap !" ); END byte[] bytes = ByteBuffer.allocate( Long.SIZE ).putLong( value ).array(); return (X) new BsonBinary( bytes ); } This debug message is not very useful

Target:
public <X> X unwrap(Long value, Class<X> type, WrapperOptions options) { byte[] bytes = ByteBuffer.allocate( Long.SIZE ).putLong( value ).array(); return (X) new BsonBinary( bytes ); }
Source:
START public final <R> R as(@NonNull CompletableConverter<? extends R> converter) { END try { return ObjectHelper.requireNonNull(converter, "converter is null").apply(this); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); throw ExceptionHelper.wrapOrThrow(ex); } } Please add `@Experimental` and `@since 2.1.7 - experimental` to all of them.

Target:
public final <R> R as(@NonNull CompletableConverter<? extends R> converter) { return ObjectHelper.requireNonNull(converter, "converter is null").apply(this); }
Source:
public Object instantiateItem(ViewGroup collection, int position) { START int resId = PAGE_READING_LISTS; END switch (position) { case PAGE_READING_LISTS: resId = R.id.list_of_lists_page; break; case PAGE_LIST_DETAIL: resId = R.id.list_detail_page; break; default: } return getView().findViewById(resId); } Is this a find/replace artifact? Semantically it should probably still be explicitly set to 0. (I imagine you've only initialized it to please the IDE/checkstyle).

Target:
public Object instantiateItem(ViewGroup collection, int position) { int resId; switch (position) { case PAGE_LIST_DETAIL: resId = R.id.list_detail_page; break; case PAGE_READING_LISTS: default: resId = R.id.list_of_lists_page; break; } return getView().findViewById(resId); }
Source:
public void initialize(URI uri, Configuration configuration) throws IOException { START this.dataTier.initialize(uri, configuration); END } remove `this.`

Target:
public void initialize(URI uri, Configuration configuration) throws IOException { dataTier.initialize(uri, configuration); }
Source:
public static void main(String[] args) { START int status = getConf(args); END System.exit(status); } `System.exit(getConf(args));`

Target:
public static void main(String[] args) { System.exit(getConf(args)); }
Source:
public void processBean(CRResolvableBean bean, IndexWriter writer) throws CRException { START System.out.println(writer.numDocs()); END } done

Target:
public void processBean(CRResolvableBean bean, IndexWriter writer) throws CRException { }
Source:
public List<@NonNull ITimeGraphEntry> getChildren() { START return Collections.<@NonNull ITimeGraphEntry>emptyList(); END } This is changing behaviour. I'd do that separately.

Target:
public List<@NonNull ITimeGraphEntry> getChildren() { return null; }
Source:
public void addNewMailNotification(Account account, LocalMessage message, int previousUnreadMessageCount) { boolean hasHighPriority = false; START for (String iter : message.getHeader("X-Priority")) { END if (iter.contains(context.getString(R.string.x_priority))) hasHighPriority = true; } newMailNotifications.addNewMailNotification(account, message, previousUnreadMessageCount, hasHighPriority); } this logic should be part of `Message`. it's also unnecessary to check all headers, just the first one should suffice.

Target:
public void addNewMailNotification(Account account, LocalMessage message, int previousUnreadMessageCount) { newMailNotifications.addNewMailNotification(account, message, previousUnreadMessageCount); }
Source:
public void loadTrace(ITmfTrace trace) { super.loadTrace(trace); updateContent(); START clearContent(); END } I'm not sure if this change is intentional, but it shouldn't make a difference with TmfCommonXLineChartViewer because of its use of asyncExec(). However since updateContent() is abstract here, it would seem that clearContent() should be called first.

Target:
public void loadTrace(ITmfTrace trace) { super.loadTrace(trace); clearContent(); updateContent(); }
Source:
START public static void killAllSpawnedHadoopJobs(String logFilePath, Logger log) { END Set<String> allSpawnedJobs = findApplicationIdFromLog(logFilePath, log); log.info("applicationIds to kill: " + allSpawnedJobs); for (String appId : allSpawnedJobs) { try { killJobOnCluster(appId, log); } catch (Throwable t) { log.warn("something happened while trying to kill this job: " + appId, t); } } } Seems like it is useful for this method to return a list of Hadoop jobs that were killed by this method and caller can print them out.

Target:
public static Set<String> killAllSpawnedHadoopJobs(String logFilePath, Logger log) { Set<String> allSpawnedJobs = findApplicationIdFromLog(logFilePath, log); log.info("applicationIds to kill: " + allSpawnedJobs); for (String appId : allSpawnedJobs) { try { killJobOnCluster(appId, log); } catch (Throwable t) { log.warn("something happened while trying to kill this job: " + appId, t); } } return allSpawnedJobs; }
Source:
public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } START if (!(this.getClass().equals(o.getClass()))) { END return false; } SitePropertySource that = (SitePropertySource) o; return Objects.equal(mFilename, that.mFilename); } is this because of the inheritance?

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || this.getClass() != o.getClass()) { return false; } SitePropertySource that = (SitePropertySource) o; return Objects.equal(mFilename, that.mFilename); }
Source:
public void testFetchSkipsBlackedOutNodes() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); START client.updateMetadata(initialUpdateResponseWithLeaderEpoch); END Node node = initialUpdateResponse.brokers().iterator().next(); client.blackout(node, 500); assertEquals(0, fetcher.sendFetches()); time.sleep(500); assertEquals(1, fetcher.sendFetches()); } Do we need to change some of these other tests? We're still using `initialUpdateResponse` above in `assignFromUser` and below.

Target:
public void testFetchSkipsBlackedOutNodes() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); Node node = initialUpdateResponse.brokers().iterator().next(); client.blackout(node, 500); assertEquals(0, fetcher.sendFetches()); time.sleep(500); assertEquals(1, fetcher.sendFetches()); }
Source:
public DefaultByteBufHolder(ByteBuf data) { ObjectUtil.checkNotNull(data, "data"); START this.data = data; END } nit: you can merge both lines above as `checkNotNull` will return the given argument

Target:
public DefaultByteBufHolder(ByteBuf data) { this.data = ObjectUtil.checkNotNull(data, "data"); }
Source:
public synchronized void removeConnection(Socket conn) { try { START connections.remove(conn); END conn.close(); } catch (IOException ioe) { tsLogger.i18NLogger.warn_could_not_close_transaction_listener_connection(conn, ioe); } finally { notifyAll(); } } I think it would be clearer if the connections.remove was outside of this block as I don't think it will be throwing IOException, unless you think the notifyAll always done even with a problem on the linkedlist.remove() but if that is the case perhaps the conn.close() should be in it's own try block?

Target:
public synchronized void removeConnection(Socket conn) { connections.remove(conn); try { conn.close(); } catch (IOException ioe) { tsLogger.i18NLogger.warn_could_not_close_transaction_listener_connection(conn, ioe); } finally { notifyAll(); } }
Source:
public List<CourseGroup> getLecturing() { START String userId = proxy.getCurrentUser().getDisplayName(); END List <CourseGroupDAO> groupDaos = dao.findLecturingCourseGroups(userId); List<CourseGroup> groups = new ArrayList<CourseGroup>(groupDaos.size()); for(CourseGroupDAO groupDao : groupDaos) { groups.add(new CourseGroupImpl(groupDao, this)); } return groups; } You're getting the display name and using it todo a search my userId. Either there is a bug in the UserProxy or this code is wrong.

Target:
public List<CourseGroup> getLecturing() { String userId = proxy.getCurrentUser().getId(); List <CourseGroupDAO> groupDaos = dao.findLecturingCourseGroups(userId); List<CourseGroup> groups = new ArrayList<CourseGroup>(groupDaos.size()); for(CourseGroupDAO groupDao : groupDaos) { groups.add(new CourseGroupImpl(groupDao, this)); } return groups; }
Source:
protected SLDGenerator(Item item, Item selectedItem, Integer ribbon, SLDConfig config) { this.item = item; this.ribbon = ribbon; if (config instanceof ShorelineConfig) { ShorelineConfig slc = (ShorelineConfig)config; START slc.finalize(item, selectedItem); END this.config = slc; } else { this.config = config; } } Seems at this point you could just pass in the selectedItem instead of both.

Target:
protected SLDGenerator(Item item, Item selectedItem, Integer ribbon, SLDConfig config) { this.item = item; this.ribbon = ribbon; if (config instanceof ShorelineConfig) { ShorelineConfig slc = (ShorelineConfig)config; slc.finalize(selectedItem); this.config = slc; } else { this.config = config; } }
Source:
public static void copy(File source, File dest) throws IOException { START try (InputStream in = new FileInputStream(source)) { END try (OutputStream out = new BufferedOutputStream(new FileOutputStream(dest))) { transferData(in, out); } } } consider replacing 96-97 with just one try block (see line 455)

Target:
public static void copy(File source, File dest) throws IOException { try (InputStream in = new FileInputStream(source); OutputStream out = new BufferedOutputStream(new FileOutputStream(dest))) { transferData(in, out); } }
Source:
public XWikiAttachment setAttachment(XWikiAttachment attachment) { attachment.setDoc(this); XWikiAttachmentList list = this.attachmentList; START XWikiAttachment currentAttachment = list.getByFilename(attachment.getFilename()); END list.set(attachment); return currentAttachment; } set() already take care of this so you could simply return the result of set().

Target:
public XWikiAttachment setAttachment(XWikiAttachment attachment) { return this.attachmentList.set(attachment); }
Source:
public PropertyValue(MAPIProperty property, long flags, byte[] data) { START this.property = property; END this.flags = flags; this.data = data; this.actualType = property.usualType; } could you call this(property, flags, data, null) ?

Target:
public PropertyValue(MAPIProperty property, long flags, byte[] data) { this(property, flags, data, property.usualType); }
Source:
START public boolean charTyped(char p_charTyped_1_, int p_charTyped_2_) { END if (super.charTyped(p_charTyped_1_, p_charTyped_2_) || !canEdit) { return true; } else if (SharedConstants.isAllowedCharacter(p_charTyped_1_)) { this.insertTextIntoPage(Character.toString(p_charTyped_1_)); return true; } else { return false; } } Again, parameter names

Target:
public boolean charTyped(char p_charTyped_1_, int p_charTyped_2_) { if (super.charTyped(p_charTyped_1_, p_charTyped_2_) || !canEdit) return true; else if (SharedConstants.isAllowedCharacter(p_charTyped_1_)) { this.insertTextIntoPage(Character.toString(p_charTyped_1_)); return true; } else return false; }
Source:
Map<String, String> getAPITypeParameters() throws BonitaHomeNotSetException, ServerAPIException { Map<String, String> parameters; try { parameters = APITypeManager.getAPITypeParameters(); } catch (IOException e) { throw new ServerAPIException(e); } START return parameters; END } Could be great to return an empty map instead of null

Target:
protected Map<String, String> getAPITypeParameters() throws BonitaHomeNotSetException, ServerAPIException { try { return APITypeManager.getAPITypeParameters(); } catch (IOException e) { throw new ServerAPIException(e); } }
Source:
public static Driver createDriver(DriverContext driverContext, List<Operator> operators) { START Driver driver = new Driver(requireNonNull(driverContext, "driverContext is null"), requireNonNull(operators, "operators is null")); END driver.initialize(); return driver; } Move the `requireNonNull` checks to a separate line. Calling them inline looks messy.

Target:
public static Driver createDriver(DriverContext driverContext, List<Operator> operators) { requireNonNull(driverContext, "driverContext is null"); requireNonNull(operators, "operators is null"); Driver driver = new Driver(driverContext, operators); driver.initialize(); return driver; }
Source:
public static AbstractTaskContextStore loadTaskContextStore() { ExtensionPointReader<AbstractTaskContextStore> reader = new ExtensionPointReader<AbstractTaskContextStore>( ITasksCoreConstants.ID_PLUGIN, "contextStore", "contextStore", AbstractTaskContextStore.class); //$NON-NLS-1$ //$NON-NLS-2$ IStatus status = reader.read(); if (!status.isOK()) { START StatusHandler.log(status); END } AbstractTaskContextStore contextStore = reader.getItem(); if (contextStore != null) { return contextStore; } return new DefaultTaskContextStore(); } This already happens inorg.eclipse.mylyn.commons.core.ExtensionPointReader.handleResult(IStatus)

Target:
public static AbstractTaskContextStore loadTaskContextStore() { ExtensionPointReader<AbstractTaskContextStore> reader = new ExtensionPointReader<AbstractTaskContextStore>( ITasksCoreConstants.ID_PLUGIN, "contextStore", "contextStore", AbstractTaskContextStore.class); //$NON-NLS-1$ //$NON-NLS-2$ reader.read(); AbstractTaskContextStore contextStore = reader.getItem(); if (contextStore != null) { return contextStore; } return new DefaultTaskContextStore(); }
Source:
public void sendMessage(String message) { START buffer.append(message + "\n"); END } That's not how you use a StringBuffer though. `buffer.append(message).append("\n");` PS: Wrong ping.

Target:
public void sendMessage(String message) { buffer.append(message).append("\n"); }
Source:
private void updateStatusOfPushMessageInformation(final PushMessageInformation pushMessageInformation, final String variantID, final int receivers, final Boolean deliveryStatus, final String reason) { final VariantMetricInformation variantMetricInformation = new VariantMetricInformation(); variantMetricInformation.setPushMessageInformation(pushMessageInformation); variantMetricInformation.setVariantID(variantID); variantMetricInformation.setReceivers(receivers); variantMetricInformation.setDeliveryStatus(deliveryStatus); variantMetricInformation.setReason(reason); START pushMessageInformation.getVariantInformations().add(variantMetricInformation); END dispatchVariantMetricEvent.fire(variantMetricInformation); } This is a reason why I got 2 receivers.. The variant information is added to PushMessageInformation in the `MetricCollector#updateExistingMetric`: https://github.com/matzew/aerogear-unifiedpush-server/blob/AGPUSH-1374/push/sender/src/main/java/org/jboss/aerogear/unifiedpush/message/MetricsCollector.java#L66 Since it is already added in the `NotificationDispatcher`, it re-adds "existing" variant metric. By removing this line it starts to work correctly

Target:
private void updateStatusOfPushMessageInformation(final PushMessageInformation pushMessageInformation, final String variantID, final int receivers, final Boolean deliveryStatus, final String reason) { final VariantMetricInformation variantMetricInformation = new VariantMetricInformation(); variantMetricInformation.setPushMessageInformation(pushMessageInformation); variantMetricInformation.setVariantID(variantID); variantMetricInformation.setReceivers(receivers); variantMetricInformation.setDeliveryStatus(deliveryStatus); variantMetricInformation.setReason(reason); dispatchVariantMetricEvent.fire(variantMetricInformation); }
Source:
START public void createActions() { END setGoalOrderAction = new SetGoalOrderAction((GoalArtifact) editor.getAwa(), this); RemovedFromGoalHandler handler = new RemovedFromGoalHandler() { @Override public void removedFromGoal(Collection<? extends Artifact> removed) { worldComposite.removeItems(removed); worldComposite.getXViewer().remove(removed); worldComposite.getXViewer().refresh(goalArtifact); } }; removeFromGoalAction = new RemoveFromGoalAction((GoalArtifact) editor.getAwa(), this, handler); } private

Target:
private void createActions() { setGoalOrderAction = new SetGoalOrderAction((GoalArtifact) editor.getAwa(), this); RemovedFromGoalHandler handler = new RemovedFromGoalHandler() { @Override public void removedFromGoal(Collection<? extends Artifact> removed) { worldComposite.removeItems(removed); worldComposite.getXViewer().remove(removed); worldComposite.getXViewer().refresh(goalArtifact); } }; removeFromGoalAction = new RemoveFromGoalAction((GoalArtifact) editor.getAwa(), this, handler); }
Source:
@After public void tearDown() throws Exception { if (socksProxy != null) { socksProxy.shutdown(); } if (cache != null) { cache.delete(); } client.connectionPool().evictAll(); START if (client.connectionPool().connectionCount() > 0) { END // Minimise test flakiness due to possible race conditions with connections closing. // Some number of tests will report here, but not fail due to this delay. System.out.println("Delaying to avoid flakes"); Thread.sleep(500L); System.out.println("After delay: " + client.connectionPool().connectionCount()); } } Move this to `OkHttpClientTestRule.ensureAllConnectionsReleased()`

Target:
@After public void tearDown() throws Exception { if (socksProxy != null) { socksProxy.shutdown(); } if (cache != null) { cache.delete(); } }
Source:
public void addQueueNames(String... queueNames) { try { addQueues(Arrays.stream(queueNames)); } catch (AmqpIOException e) { START throw new AmqpIOException("Failed to add " + queueNames, e.getCause()); END } super.addQueueNames(queueNames); } Or `Arrays.toString`

Target:
public void addQueueNames(String... queueNames) { try { addQueues(Arrays.stream(queueNames)); } catch (AmqpIOException e) { throw new AmqpIOException("Failed to add " + Arrays.asList(queueNames), e.getCause()); } super.addQueueNames(queueNames); }
Source:
protected void buildScript(int age) { // hard-coded list of card types to load when continuing the feed if (age == 0) { init(); } addPendingClient(new BecauseYouReadClient()); addPendingClient(new ContinueReadingClient()); addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new IntegerListClient()); addPendingClient(new MostReadClient()); START addPendingClient(new RandomClient(new RandomCard(getContext(), getSite()))); END } This kind of breaks the really clean streak of "new Client()" calls with no arguments. Could we make it adhere to this pattern?

Target:
protected void buildScript(int age) { // hard-coded list of card types to load when continuing the feed if (age == 0) { init(); } addPendingClient(new BecauseYouReadClient()); addPendingClient(new ContinueReadingClient()); addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new IntegerListClient()); addPendingClient(new MostReadClient()); addPendingClient(new RandomClient()); }
Source:
private UpdateAccountResponse updateAccount(URL updateAccountUrl, String requestBody) throws Exception { RealmLog.debug("Network request (updateAccount): " + updateAccountUrl); Request request = newAuthRequest(updateAccountUrl) .post(RequestBody.create(JSON, requestBody)) .build(); START RealmLog.error(updateAccountUrl.toString()); END RealmLog.error(requestBody); Call call = client.newCall(request); Response response = call.execute(); return UpdateAccountResponse.from(response); } debugging logging? if not the level should be `log` not `error`

Target:
private UpdateAccountResponse updateAccount(URL updateAccountUrl, String requestBody) throws Exception { RealmLog.debug("Network request (updateAccount): " + updateAccountUrl); Request request = newAuthRequest(updateAccountUrl) .post(RequestBody.create(JSON, requestBody)) .build(); Call call = client.newCall(request); Response response = call.execute(); return UpdateAccountResponse.from(response); }
Source:
START public ListObjectStream(List<T> items) { END this.items = items; this.i = 0; } does not need to be public in non-public class

Target:
ListObjectStream(List<T> items) { this.items = items; this.i = 0; }
Source:
START private void closeGroups(hdf5.Group[] groupArray) { END for (int i = 0; i < groupArray.length; i++) { groupArray[i].deallocate(); } } Haha, fair enough.

Target:
private void closeGroups(hdf5.Group[] groupArray) { for (int i = groupArray.length - 1; i >= 0; i--) { groupArray[i].deallocate(); } }
Source:
public void writeTo(ObjectOutput output) throws IOException { output.writeObject(ackTarget); if (ackTarget != null) { output.writeLong(id); } output.writeInt(topologyId); START if (keys != null) { END MarshallUtil.marshallCollection(keys, output); } else { assert segments != null; MarshallUtil.marshallIntCollection(segments, output); } } `marshallCollection` handles `null`

Target:
public void writeTo(ObjectOutput output) throws IOException { output.writeObject(ackTarget); if (ackTarget != null) { output.writeLong(id); } output.writeInt(topologyId); MarshallUtil.marshallCollection(keys, output); }
Source:
public static ModelPlotConfig createRandomized() { START return new ModelPlotConfig(randomBoolean(), randomAlphaOfLengthBetween(1, 30), randomBoolean()); END } Would be good to have a `null` case here for `annotationsEnabled`

Target:
public static ModelPlotConfig createRandomized() { return new ModelPlotConfig(randomBoolean(), randomAlphaOfLengthBetween(1, 30), randomBoolean() ? randomBoolean() : null); }
Source:
START boolean deregisterHardDeleteMetric(String storeId) { END String prefix = storeId + SEPERATOR; return registry.remove(MetricRegistry.name(PersistentIndex.class, prefix + "CurrentHardDeleteProgress")) && registry .remove(MetricRegistry.name(Log.class, prefix + "PercentageHardDeleteCompleted")) && registry.remove( MetricRegistry.name(PersistentIndex.class, prefix + "HardDeleteThreadRunning")) && registry.remove( MetricRegistry.name(PersistentIndex.class, prefix + "HardDeleteCaughtUp")); } this function can be `private`

Target:
private boolean deregisterHardDeleteMetric(String storeId) { String prefix = storeId + SEPERATOR; return registry.remove(MetricRegistry.name(PersistentIndex.class, prefix + "CurrentHardDeleteProgress")) && registry .remove(MetricRegistry.name(Log.class, prefix + "PercentageHardDeleteCompleted")) && registry.remove( MetricRegistry.name(PersistentIndex.class, prefix + "HardDeleteThreadRunning")) && registry.remove( MetricRegistry.name(PersistentIndex.class, prefix + "HardDeleteCaughtUp")); }
Source:
public void dispose() { START this.runInControlledConcurrency(() -> { END log.info("IrsProxyData::disposing"); resetIrs(); getSchedulUtil().deleteJob(storagePoolRefreshJobId); getSchedulUtil().deleteJob(domainRecoverOnHostJobId); _disposed = true; }); } no need for 'this'

Target:
public void dispose() { runInControlledConcurrency(() -> { log.info("IrsProxyData::disposing"); resetIrs(); getSchedulUtil().deleteJob(storagePoolRefreshJobId); getSchedulUtil().deleteJob(domainRecoverOnHostJobId); _disposed = true; }); }
Source:
public boolean isEnabled() { START return selectionMapsToSingleRepository(); END } This is also a regression, it no longer works for multiple repositories. Note that there is extra code below which handles multiple repositories.

Target:
public boolean isEnabled() { return true; }
Source:
private void eventuallyAssertEvictions(float expectedValue) { eventuallyAssertAttributeValue("Evictions", expectedValue); START assert expectedValue == advanced.getStats().getEvictions(); END } When updating code can you replace plain asserts with those from the testing framework ?

Target:
private void eventuallyAssertEvictions(float expectedValue) { eventuallyAssertAttributeValue("Evictions", expectedValue); assertEquals(expectedValue, (float) advanced.getStats().getEvictions()); }
Source:
public static boolean isNumber(Class<?> clazz) { if ( clazz == null ) { return false; } else if ( clazz.isPrimitive() ) { return NUMBER_TYPES.contains( clazz ); } else { START return Number.class.isAssignableFrom( clazz ); END } } These seem to be covered by `NUMBER_TYPES` already?

Target:
public static boolean isNumber(Class<?> clazz) { if ( clazz == null ) { return false; } else { return NUMBER_TYPES.contains( clazz ); } }
Source:
public List<Connection> getTransitivelyConnectedElements(EObject element, EObject traceModel, int maximumDepth) { START ArrayList<Object> accumulator = new ArrayList<>(); END return getTransitivelyConnectedElements(element, traceModel, accumulator, DEFAULT_INITIAL_TRANSITIVITY_DEPTH, maximumDepth); } Should be of type List<Object>.

Target:
public List<Connection> getTransitivelyConnectedElements(EObject element, EObject traceModel, int maximumDepth) { List<Object> accumulator = new ArrayList<>(); return getTransitivelyConnectedElements(element, traceModel, accumulator, DEFAULT_INITIAL_TRANSITIVITY_DEPTH, maximumDepth); }
Source:
public final CompletableFuture<Void> enterSynchronizationAsync(CompletableFuture<Void> releaseFuture) { START while (true) { END CompletableFuture<Void> currentFuture = synchronization.get(); if (synchronization.compareAndSet(currentFuture, releaseFuture)) return currentFuture; } } a `do-while` will avoid checking 2 conditions (the while true and the CAS)

Target:
public final CompletableFuture<Void> enterSynchronizationAsync(CompletableFuture<Void> releaseFuture) { CompletableFuture<Void> currentFuture; do { currentFuture = synchronization.get(); } while (!synchronization.compareAndSet(currentFuture, releaseFuture)); return currentFuture; }
Source:
public ReferenceCounter referenceCounter() { START return new ReferenceCounter() { @Override public boolean increment() { return ReferenceCountingSegment.this.increment(); } @Override public Closeable decrementOnceCloseable() { return ReferenceCountingSegment.this.decrementOnceCloseable(); } @Override public void decrement() { ReferenceCountingSegment.this.decrement(); } }; END } Make `ReferenceCountingSegment` implement `ReferenceCounter`. Then this function can just be `return this;` Which also means less inner classes and less lines of code to read in a delta 🙃

Target:
public ReferenceCounter referenceCounter() { return this; }
Source:
public void connectionDown() { START for (Object listenerObject : coordinateListenerList.toArray()) { END CoordinateListener coordinateListener = (CoordinateListener) listenerObject; coordinateListener.onCoordinateEvent( CoordinateListener.Event.NO_CONNECTION_TO_STORAGE, "down"); } isSynchronizedWithZooKeeper.set(false); } toArray copies the elements of the list into an array I think. Might depend on the implementation, but there are better ways to loop this. It also seems to lose type information.

Target:
public void connectionDown() { for (CoordinateListener coordinateListener : coordinateListenerList) { coordinateListener.onCoordinateEvent( CoordinateListener.Event.NO_CONNECTION_TO_STORAGE, "down"); } isSynchronizedWithZooKeeper.set(false); }
Source:
public void addLocation(long blockId, BlockLocation location) { START mBlockLocations.computeIfAbsent(blockId, x -> new HashMap<>()); END mBlockLocations.get(blockId).put(location.getWorkerId(), location); } What is the initial size of this `HashMap`?

Target:
public void addLocation(long blockId, BlockLocation location) { mBlockLocations.computeIfAbsent(blockId, x -> new HashMap<>(4)); mBlockLocations.get(blockId).put(location.getWorkerId(), location); }
Source:
public String getName() { return getHeader(Constants.BUNDLE_NAME) != null START ? bundle.getHeaders().get(Constants.BUNDLE_NAME) END : getSymbolicName(); } You can re-use your `getHeader(...)` method - which I very much like - here?

Target:
public String getName() { return getHeader(Constants.BUNDLE_NAME) != null ? getHeader(Constants.BUNDLE_NAME) : getSymbolicName(); }
Source:
public MojoParameterMetadataProvider(MavenProject project, Plugin plugin) { this.project = project; this.plugin = plugin; maven = (MavenImpl) MavenPlugin.getMaven(); START parameters = new HashMap<String, List<MojoParameter>>(); END } please use diamond operator, i.e. "<>", instead of type parameters. reduces clutter and makes code easier to maintain.

Target:
public MojoParameterMetadataProvider(MavenProject project, Plugin plugin) { this.project = project; this.plugin = plugin; maven = (MavenImpl) MavenPlugin.getMaven(); parameters = new HashMap<>(); }
Source:
protected void onPostExecute(OEmbed embed) { if (embed != null) { // TODO: decide if this is ok. Most likely because the setStep // function isnt intensive if(!isCancelled()) { mMainWebView.loadUrl(mStep.getEmded().getOembed().getURL()); START mMainWebView.setTag(mStep.getEmded().getOembed().getURL()); END } } } Let's make this DRY. ``` String url = mStep.getEmded().getOembed().getURL(); mMainWebView.loadUrl(url); mMainWebView.setTag(url); ```

Target:
protected void onPostExecute(OEmbed embed) { if (embed != null) { // TODO: decide if this is ok. Most likely because the setStep // function isnt intensive if(!isCancelled()) { String url = mStep.getEmded().getOembed().getURL(); mMainWebView.loadUrl(url); mMainWebView.setTag(url); } } }
Source:
public int read(int offset, int[] positions, int positionCount) { outputPositions = initializeOutputPositions(outputPositions, positions, positionCount); START outputPositionCount = positionCount; END return outputPositionCount; } outputPositionCount variable is not used; remove it `return positionCount;`

Target:
public int read(int offset, int[] positions, int positionCount) { outputPositions = initializeOutputPositions(outputPositions, positions, positionCount); return positionCount; }
Source:
START public void start(BootstrapContext ctx) END throws ResourceAdapterInternalException { if (engine == null) { engine = new ModeShapeEngine(); engine.start(); } } This method should probably be `synchronized`.

Target:
public synchronized void start(BootstrapContext ctx) throws ResourceAdapterInternalException { if (engine == null) { engine = new ModeShapeEngine(); engine.start(); } }
Source:
public String getValue() { START return name().toLowerCase(); END } wouldn't it be preferred to store the value of each type in lower case instead of creating it each time this method invoked ?

Target:
public String getValue() { return value; }
Source:
START public boolean start() END { if (!started.get()) { LOGGER.info("started polling lookup [%s]", id); started.set(pollingLookup.isOpen()); } return started.get(); } should be made such that start and stop cannot be called at the same time

Target:
public boolean start() { synchronized (started) { if (!started.get()) { LOGGER.info("started polling lookup [%s]", id); started.set(pollingLookup.isOpen()); } return started.get(); } }
Source:
public void tearDown(final ManagementClient managementClient, final String containerId) { // TODO: add {"allow-resource-service-restart" => true} to ejbRemoteAddress write-attribute operation once WFLY-8793 / JBEAP-10955 is fixed // and remove this reload try { ServerReload.reloadIfRequired(managementClient.getControllerClient()); } catch (Exception e) { throw new RuntimeException(e); } // TODO: remove this reload once WFLY-8821 / JBEAP-11074 is fixed try { START ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); END } catch (Exception e) { throw new RuntimeException(e); } applyRemoveAllowReload(managementClient.getControllerClient(), domainAddress, false); applyRemoveAllowReload(managementClient.getControllerClient(), realmAddress, false); } This should be probably moved after following applyRemoveAllowReload.

Target:
public void tearDown(final ManagementClient managementClient, final String containerId) { applyRemoveAllowReload(managementClient.getControllerClient(), domainAddress, false); applyRemoveAllowReload(managementClient.getControllerClient(), realmAddress, false); }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result START + ((section == null) ? 0 : section.hashCode()); END result = prime * result + ((subsection == null) ? 0 : subsection.hashCode()); return result; } I think its OK to assume section != null here.

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + section.hashCode(); result = prime * result + ((subsection == null) ? 0 : subsection.hashCode()); return result; }
Source:
private START List<ProjectInfo> list(final END ListRequest request) throws RestApiException { ListProjects lp = listProvider.get(); lp.setShowDescription(request.getDescription()); lp.setLimit(request.getLimit()); lp.setStart(request.getStart()); lp.setMatchPrefix(request.getPrefix()); Map<String, ProjectInfo> result = lp.apply(); return ImmutableList.copyOf(result.values()); } I think List is fine.

Target:
private List<ProjectInfo> list(final ListRequest request) throws RestApiException { ListProjects lp = listProvider.get(); lp.setShowDescription(request.getDescription()); lp.setLimit(request.getLimit()); lp.setStart(request.getStart()); lp.setMatchPrefix(request.getPrefix()); return ImmutableList.copyOf(lp.apply().values()); }
Source:
public void testGetItemId() { START Long expected = CoreArtifactTokens.OseeTypesFolder.getId(); END Long actual = item.getItemId().getId(); assertEquals(expected, actual); } replace with this 1 line: assertEquals(oreArtifactTokens.OseeTypesFolder, item.getItemId());

Target:
public void testGetItemId() { assertEquals(CoreArtifactTokens.OseeTypesFolder, item.getItemId()); }
Source:
public void onDestroyView() { super.onDestroyView(); START ((PageActivity)getActivity()).getDrawerToggle().setDrawerIndicatorEnabled(true); END app.getBus().unregister(this); } I would put this in on Pause

Target:
public void onDestroyView() { super.onDestroyView(); app.getBus().unregister(this); }
Source:
START public GroupScan clone(List<SchemaPath> columns) { END logger.debug("HttpGroupScan clone {}", columns); HttpGroupScan newScan = new HttpGroupScan(this); newScan.columns = columns; return newScan; } Better to have a constuctor that takes a `HttpGroupScan` and the list of columns. That way, the `columns` member can be `final` and the class can be immutable.

Target:
public GroupScan clone(List<SchemaPath> columns) { return new HttpGroupScan(this, columns); }
Source:
private void executeUpdate(String sql) { try { Statement statement = this.connection.createStatement(); statement.executeUpdate(sql); START statement.close(); END } catch (Exception e) { throw new RuntimeException(e); } } `finally` here?

Target:
private void executeUpdate(String sql) { try (Statement statement = this.connection.createStatement()) { statement.executeUpdate(sql); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
private void buildDependenciesMap(@NotNull Module module, @NotNull Collection<VirtualFile> erlangModules, @NotNull List<String> globalParseTransforms) { for (VirtualFile erlangModule : erlangModules) { Set<String> dependencies = ContainerUtil.newHashSet(); ErlangFile erlangFile = getErlangFile(erlangModule); addDeclaredDependencies(module, erlangFile, dependencies); START dependencies.addAll(resolvePathsFromNames(globalParseTransforms, module)); END myPathsToDependenciesMap.put(erlangModule.getPath(), ContainerUtil.newArrayList(dependencies)); } } There is no need to resolve these paths on every iteration - you only need it resolved once. Moreover, you can resolve it once one level above, passing resolved parse transforms to this method.

Target:
private void buildDependenciesMap(@NotNull Module module, @NotNull Collection<VirtualFile> erlangModules, @NotNull List<String> globalParseTransforms) { for (VirtualFile erlangModule : erlangModules) { Set<String> dependencies = ContainerUtil.newHashSet(); ErlangFile erlangFile = getErlangFile(erlangModule); addDeclaredDependencies(module, erlangFile, dependencies); dependencies.addAll(globalParseTransforms); myPathsToDependenciesMap.put(erlangModule.getPath(), ContainerUtil.newArrayList(dependencies)); } }
Source:
public void createFeaturesTest() throws IOException { String[] tokens = new String[] {"he", "went", "with", "you"}; START AdaptiveFeatureGenerator generator = new BrownBigramFeatureGenerator(brownCluster); END List<String> features = new ArrayList<>(); generator.createFeatures(features, tokens, 3, null); Assert.assertEquals(2, features.size()); Assert.assertTrue(features.contains("pbrowncluster,browncluster=0101,0010")); Assert.assertTrue(features.contains("pbrowncluster,browncluster=01010,00101")); } This line can be moved up to the @Before method too.

Target:
public void createFeaturesTest() throws IOException { String[] tokens = new String[] {"he", "went", "with", "you"}; List<String> features = new ArrayList<>(); generator.createFeatures(features, tokens, 3, null); Assert.assertEquals(2, features.size()); Assert.assertTrue(features.contains("pbrowncluster,browncluster=0101,0010")); Assert.assertTrue(features.contains("pbrowncluster,browncluster=01010,00101")); }
Source:
public void getRelatedNoResult() throws Exception { PushOneCommit push = pushFactory.create(db, admin.getIdent()); PatchSet.Id ps = push.to(git, "refs/for/master").getPatchSetId(); List<ChangeAndCommit> related = getRelated(ps); START assertThat(related.size()).isEqualTo(0); END } assertThat(related).isEmpty();

Target:
public void getRelatedNoResult() throws Exception { PushOneCommit push = pushFactory.create(db, admin.getIdent()); PatchSet.Id ps = push.to(git, "refs/for/master").getPatchSetId(); List<ChangeAndCommit> related = getRelated(ps); assertThat(related).isEmpty(); }
Source:
protected void destroyVm() { boolean vmMigrating = getVm().getStatus() == VMStatus.MigratingFrom && getVm().getMigratingToVds() != null; setActionReturnValue(vmMigrating ? destroyMigratingVm() : destroyNonMigratingVm()); START managedBlockStorageCommandUtil.disconnectManagedBlockStorageDisks(getVm(), vmHandler, getVdsId()); END } This should be moved to: ProcessDownVmCommand

Target:
protected void destroyVm() { boolean vmMigrating = getVm().getStatus() == VMStatus.MigratingFrom && getVm().getMigratingToVds() != null; setActionReturnValue(vmMigrating ? destroyMigratingVm() : destroyNonMigratingVm()); }
Source:
START public void testParseDateFailed() { END try { CommonUtils.parseFromUtcTime("this is obviously not a date"); fail("Parsing date should never be successfull here"); } catch (ParseException e) { } } You may be able to simplify this test case through JUnit4 annotations, with the `@Expected`

Target:
public void testParseDateFailed() throws ParseException { CommonUtils.parseFromUtcTime("this is obviously not a date"); }
Source:
public static String toString(int oid) { try { Field[] fields = Oid.class.getFields(); START for (int i = 0; i < fields.length; i++) { END Field field = fields[i]; if (field.getInt(null) == oid) { return field.getName(); } } } catch (IllegalAccessException e) { // never happens } return "<unknown:" + oid + ">"; } @vlsi performance issues with using foreach ??

Target:
public static String toString(int oid) { try { Field[] fields = Oid.class.getFields(); for (Field field : fields) { if (field.getInt(null) == oid) { return field.getName(); } } } catch (IllegalAccessException e) { // never happens } return "<unknown:" + oid + ">"; }
Source:
public List<Patient> getDuplicatePatientsByAttributes(List<String> attributes) throws APIException { START if (attributes == null || !attributes.isEmpty()) { END throw new APIException("Patient.no.attribute", (Object[]) null); } return dao.getDuplicatePatientsByAttributes(attributes); } Are you sure you did the above line correctly? :)

Target:
public List<Patient> getDuplicatePatientsByAttributes(List<String> attributes) throws APIException { if (attributes == null || attributes.isEmpty()) { throw new APIException("Patient.no.attribute", (Object[]) null); } return dao.getDuplicatePatientsByAttributes(attributes); }
Source:
START private int countOccurrencesInTopology(final String topologyString, END final String searchPattern) { final Matcher matcher = Pattern.compile(searchPattern).matcher(topologyString); final List<String> repartitionTopicsFound = new ArrayList<>(); while (matcher.find()) { repartitionTopicsFound.add(matcher.group()); } return repartitionTopicsFound.size(); } likewise, this one can be static

Target:
private static int countOccurrencesInTopology(final String topologyString, final String searchPattern) { final Matcher matcher = Pattern.compile(searchPattern).matcher(topologyString); final List<String> repartitionTopicsFound = new ArrayList<>(); while (matcher.find()) { repartitionTopicsFound.add(matcher.group()); } return repartitionTopicsFound.size(); }
Source:
public void testPasswordResetWithNoExistingUser_shouldThrow() { String username= "anyUser"; //mocks when(userRepository.findUser(anyString())).thenReturn(null); //Test passwordResetService.resetUserPassword(username); Assert.assertNotNull(userRepository.findUser(username)); START verify(userRepository).findUser(username); END verify(passwordResetService).resetUserPassword(username); } @tumijacob I don't think that these verifies are ever called since the method call above should throw.

Target:
public void testPasswordResetWithNoExistingUser_shouldThrow() { String username = "anyUser"; // mocks when(userRepository.findUser(anyString())).thenReturn(null); // Test passwordResetService.resetUserPassword(username); }
Source:
public void run() { log.info(Thread.currentThread().getName() + " is starting DFS"); try { frontier.searchForScenarios(queue, flag); } catch (IOException e) { START e.printStackTrace(); END } log.info(Thread.currentThread().getName() + " is done with DFS"); } Don't use printStackTrace() and instead write to the logger using log.error("<Appropriate message>",e);

Target:
public void run() { log.info(Thread.currentThread().getName() + " is starting DFS"); try { frontier.searchForScenarios(queue, flag); } catch (IOException e) { log.error("", e); } log.info(Thread.currentThread().getName() + " is done with DFS"); }
Source:
public BusinessServiceGraph getGraph() { m_rwLock.readLock().lock(); try { START return m_g; END } finally { m_rwLock.readLock().unlock(); } } Can we return a copy of the graph instead of a reference? There's also no point in using a read lock when returning the reference. I'm mostly worried that callers may alter the graph in some way.

Target:
public BusinessServiceGraph getGraph() { return m_g; }
Source:
public static Iterable<Object[]> constructorFeeder() { return ImmutableList.of( START new Object[]{LockGranularity.TIME_CHUNK, false}, new Object[]{LockGranularity.TIME_CHUNK, true}, new Object[]{LockGranularity.SEGMENT, false}, new Object[]{LockGranularity.SEGMENT, true} END ); } This is a relatively slow test (~15 seconds per parameterized run), so all the permutations may be overkill. Perhaps remove (SEGMENT, false), which will still give coverage of both lock granularities and both with/without the input format API.

Target:
public static Iterable<Object[]> constructorFeeder() { return ImmutableList.of( new Object[]{LockGranularity.TIME_CHUNK, false}, new Object[]{LockGranularity.TIME_CHUNK, true}, new Object[]{LockGranularity.SEGMENT, true} ); }
Source:
START public static ByteBuffer handleBufferUnderflow(final SSLEngine engine, ByteBuffer buffer) { END if (buffer.position() < buffer.limit()) { return buffer; } ByteBuffer replaceBuffer = enlargeBuffer(buffer, engine.getSession().getPacketBufferSize()); buffer.flip(); replaceBuffer.put(buffer); return replaceBuffer; } Add `Preconditions.checkArgument` checks to verify that the passed `engine` and `buffer` are not `null`.

Target:
public static ByteBuffer handleBufferUnderflow(final SSLEngine engine, ByteBuffer buffer) { if (engine == null || buffer == null) { return buffer; } if (buffer.position() < buffer.limit()) { return buffer; } ByteBuffer replaceBuffer = enlargeBuffer(buffer, engine.getSession().getPacketBufferSize()); buffer.flip(); replaceBuffer.put(buffer); return replaceBuffer; }
Source:
public void givenIdenticalSimpleObjects_whenCompared_thenEqual() { JsonParser parser = new JsonParser(); String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27 }}"; String string2 = "{\"customer\": {\"id\": \"44521\", \"fullName\": \"Emily Jenkins\",\"age\": 27}}"; Assert.assertTrue(parser.parse(string1) .isJsonObject()); START Assert.assertEquals(parser.parse(string1), parser.parse(string2)); END } Let's static import the assertions inside `org.junit.Assert` so we don't need to prefix them with `Assert.`

Target:
public void givenIdenticalSimpleObjects_whenCompared_thenEqual() { JsonParser parser = new JsonParser(); String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27 }}"; String string2 = "{\"customer\": {\"id\": \"44521\", \"fullName\": \"Emily Jenkins\",\"age\": 27}}"; assertTrue(parser.parse(string1) .isJsonObject()); assertEquals(parser.parse(string1), parser.parse(string2)); }
Source:
public TitleMatchingContainerScorer(double exactTitleMatchScore) { START this.scorer = new ContentTitleScorer<>( END NAME, Functions.<String>identity(), Score.valueOf(exactTitleMatchScore), Score.ONE ); } ```suggestion this(Score.valueOf(exactTitleMatchScore), Score.ONE); ```

Target:
public TitleMatchingContainerScorer(double exactTitleMatchScore) { this(Score.valueOf(exactTitleMatchScore), Score.ONE); }