auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<String> getMoreStable(String branch) { int i = order.indexOf(fullName(branch)); if (0 <= i) { START return order.subList(i + 1, order.size()); END } else { return Collections.emptyList(); } } This subList should not be mutable to the caller.

Target:
public List<String> getMoreStable(String branch) { int i = order.indexOf(fullName(branch)); if (0 <= i) { return order.subList(i + 1, order.size()); } else { return ImmutableList.of(); } }
Source:
public void notifyListeners(int eventType, Event event) { if START (this.dropdownTableViewer != END null && !this.dropdownTable.isDisposed()) this.dropdownTable.notifyListeners(eventType, event); } why a check for the viewer here? shouldn't this be the dropdownTable? Now that we keep the table.

Target:
public void notifyListeners(int eventType, Event event) { if (this.dropdownTable != null && !this.dropdownTable.isDisposed()) this.dropdownTable.notifyListeners(eventType, event); }
Source:
public static void setup() throws Exception { START assumeTrue("Skipping tests since Hive supports only JDK 8.", HiveTestUtilities.supportedJavaVersion()); END startMiniDfsCluster(TestSqlStdBasedAuthorization.class.getSimpleName()); prepHiveConfAndData(); setSqlStdBasedAuthorizationInHiveConf(); startHiveMetaStore(); startDrillCluster(true); addHiveStoragePlugin(getHivePluginConfig()); addMiniDfsBasedStorage(new HashMap<>()); generateTestData(); } Can't we move check to `BaseTestHiveImpersonation` and extend from some common Hive test class?

Target:
public static void setup() throws Exception { startMiniDfsCluster(TestSqlStdBasedAuthorization.class.getSimpleName()); prepHiveConfAndData(); setSqlStdBasedAuthorizationInHiveConf(); startHiveMetaStore(); startDrillCluster(true); addHiveStoragePlugin(getHivePluginConfig()); addMiniDfsBasedStorage(new HashMap<>()); generateTestData(); }
Source:
public OrderType retireOrderType(OrderType orderType, String reason) { orderType.setRetired(true); START orderType.setRetireReason(reason); END return dao.saveOrderType(orderType); } these fields are already set by AOP in RetireSaveHandler and this needs to delegate to saveOrderType instead of calling the DAO just in case there is extra logic in the save method we don't want to by pass

Target:
public OrderType retireOrderType(OrderType orderType, String reason) { orderType.setRetired(true); orderType.setRetireReason(reason); return saveOrderType(orderType); }
Source:
private void updateFiltersCheckState() { Object[] children = filterContentProvider .getElements(getContentService()); ICommonFilterDescriptor filterDescriptor; INavigatorFilterService filterService = getContentService() .getFilterService(); for (Object START element : END children) { filterDescriptor = (ICommonFilterDescriptor) element; if(filterService.isActive(filterDescriptor.getId())) { getTableViewer().setChecked(element, true); getCheckedItems().add(element); } else { getTableViewer().setChecked(element, false); } } } rename 'child'?

Target:
private void updateFiltersCheckState() { ICommonFilterDescriptor filterDescriptor; INavigatorFilterService filterService = getContentService() .getFilterService(); for (Object child : filterContentProvider.getElements(getContentService())) { filterDescriptor = (ICommonFilterDescriptor) child; if(filterService.isActive(filterDescriptor.getId())) { getTableViewer().setChecked(child, true); getCheckedItems().add(child); } else { getTableViewer().setChecked(child, false); } } }
Source:
public FeatureTypeStyle transform(MBStyle styleContext, Double minScaleDenominator, Double maxScaleDenominator) { // Would prefer to accept zoom levels here (less concepts in our API) // If we accept zoom levels we may be able to reduce, and return a list of FeatureTypeStyles // (with the understanding that the list may be empty if the MBLayer does not contribute any content // at a specific zoom level range) START FeatureTypeStyle style = transform(styleContext); END for (Rule rule : style.rules()) { if (minScaleDenominator != null) { rule.setMinScaleDenominator(minScaleDenominator); } if (maxScaleDenominator != null) { rule.setMaxScaleDenominator(maxScaleDenominator); } } return style; } This may return null if layer visibility = false

Target:
public FeatureTypeStyle transform(MBStyle styleContext, Double minScaleDenominator, Double maxScaleDenominator) { // Would prefer to accept zoom levels here (less concepts in our API) // If we accept zoom levels we may be able to reduce, and return a list of FeatureTypeStyles // (with the understanding that the list may be empty if the MBLayer does not contribute any content // at a specific zoom level range) FeatureTypeStyle style = transform(styleContext); if (style == null) { return null; } for (Rule rule : style.rules()) { if (minScaleDenominator != null) { rule.setMinScaleDenominator(minScaleDenominator); } if (maxScaleDenominator != null) { rule.setMaxScaleDenominator(maxScaleDenominator); } } return style; }
Source:
public Optional<RevCommit> areAllReachable(Collection<RevCommit> targets, Collection<RevCommit> starters) throws MissingObjectException, IncorrectObjectTypeException, IOException { walk.reset(); START walk.setRetainBody(false); END if (topoSort) { walk.sort(RevSort.TOPO); } for (RevCommit target: targets) { walk.markStart(target); } for (RevCommit starter : starters) { walk.markUninteresting(starter); } return Optional.ofNullable(walk.next()); } The reason why ReachabilityChecker supports reusing an existing RevWalk (instead of maintaining our own), presumably, is so that we can save on object parsing. So I think it's less flexible if we set this here - the caller should be setting it if they know that they want it.

Target:
public Optional<RevCommit> areAllReachable(Collection<RevCommit> targets, Collection<RevCommit> starters) throws MissingObjectException, IncorrectObjectTypeException, IOException { walk.reset(); if (topoSort) { walk.sort(RevSort.TOPO); } for (RevCommit target: targets) { walk.markStart(target); } for (RevCommit starter : starters) { walk.markUninteresting(starter); } return Optional.ofNullable(walk.next()); }
Source:
START public Optional<SessionStore<J2EContext>> buildFromTrackableSession(final J2EContext context, final Object trackableSession) { END return trackableSession == null ? Optional.empty() : Optional.of(new J2EProvidedSessionStore((HttpSession) trackableSession)); } shouldn't trackableSession be an Optional? Either they are both or none are for me… actually, I don't think we really need to introduce Optional here, it is the caller that should be careful of not calling this with a null value!

Target:
public Optional<SessionStore<J2EContext>> buildFromTrackableSession(final J2EContext context, final Object trackableSession) { return trackableSession != null ? Optional.of(new J2EProvidedSessionStore((HttpSession) trackableSession)) : Optional.empty(); }
Source:
public Response awaitResponse() throws Exception { START return Objects.requireNonNull(remoteFuture).get(); END } I don't see any advantage of using `requireNonNull()`

Target:
public Response awaitResponse() throws Exception { return remoteFuture.get(); }
Source:
static boolean isDefaultArgumentsConstructor(final MethodNode methodNode) { START if (!methodNode.name.equals("<init>")) { END return false; } final Type[] argumentTypes = Type.getMethodType(methodNode.desc) .getArgumentTypes(); if (argumentTypes.length < 2) { return false; } return "kotlin.jvm.internal.DefaultConstructorMarker" .equals(argumentTypes[argumentTypes.length - 1].getClassName()); } "<init>".equals() is null safe and consistent to the last check in this method.

Target:
static boolean isDefaultArgumentsConstructor(final MethodNode methodNode) { if (!"<init>".equals(methodNode.name)) { return false; } final Type[] argumentTypes = Type.getMethodType(methodNode.desc) .getArgumentTypes(); if (argumentTypes.length < 2) { return false; } return "kotlin.jvm.internal.DefaultConstructorMarker" .equals(argumentTypes[argumentTypes.length - 1].getClassName()); }
Source:
public void increment(long amount) { long now = clock.now() / 1000L; START if (now != currentSecond.get()) { END currentCount.set(0); } long count = currentCount.addAndGet(amount); updatePeak(count); } Where is currentSecond being updated?

Target:
public void increment(long amount) { long now = clock.now() / 1000L; if (now != currentSecond.get()) { currentCount.set(0); currentSecond.set(now); } long count = currentCount.addAndGet(amount); updatePeak(count); }
Source:
public static void assertValidSubmodulePath(String path) throws SubmoduleValidationException { if (path.startsWith("-")) { //$NON-NLS-1$ throw new SubmoduleValidationException( MessageFormat.format( JGitText.get().submodulePathInvalid, path), START ObjectChecker.ErrorType.GITMODULES_PATH); END } } Ack

Target:
public static void assertValidSubmodulePath(String path) throws SubmoduleValidationException { if (path.startsWith("-")) { //$NON-NLS-1$ throw new SubmoduleValidationException( MessageFormat.format( JGitText.get().submodulePathInvalid, path), GITMODULES_PATH); } }
Source:
public String getMessage() { START String ret = super.getMessage(); END if (pql.isPresent()) { ret += " with pql \"" + pql.get() + "\""; } return ret; } `ret` -> `message`

Target:
public String getMessage() { String message = super.getMessage(); if (pql.isPresent()) { message += " with pql \"" + pql.get() + "\""; } return message; }
Source:
protected AbstractGraphDecorator(Graph g) { if (g == null) { START throw new NullPointerException("g may not be null."); END } this.inner = g; } Minor suggestion to change this exception to: ``` throw new IllegalArgumentException("g may not be null."); ```

Target:
protected AbstractGraphDecorator(Graph g) { if (g == null) { throw new IllegalArgumentException("g may not be null."); } this.inner = g; }
Source:
public boolean isDTS() { START return getCodecA() != null && (getCodecA().startsWith("dts") || "dca".equals(getCodecA()) || "dca (dts)".equals(getCodecA())); END } `return getCodecA() != null && ("dts".contains(getCodecA()) || "dca".contains(getCodecA()));`

Target:
public boolean isDTS() { return getCodecA() != null && (getCodecA().contains("dts") || getCodecA().contains("dca")); }
Source:
START public CacheCollection<V> values(EnumSet<Flag> explicitFlags, ClassLoader explicitClassLoader) { END return new ValueCacheCollection<>(this, cacheEntrySet(explicitFlags, explicitClassLoader)); } This one shouldn't be public.

Target:
CacheCollection<V> values(EnumSet<Flag> explicitFlags, ClassLoader explicitClassLoader) { return new ValueCacheCollection<>(this, cacheEntrySet(explicitFlags, explicitClassLoader)); }
Source:
public synchronized void setBrightnessInUserInterfaceDimensionUnit(float percent) { if (percent < 0f) { percent = 0f; } else if (percent > 200f) { percent = 200f; } brightness = percent / 100f; START changeShader = true; END refreshTextures(); } Please, change as discussed.

Target:
public synchronized void setBrightnessInUserInterfaceDimensionUnit(float percent) { if (percent < 0f) { percent = 0f; } else if (percent > 200f) { percent = 200f; } brightness = percent / 100f; refreshTextures(true); }
Source:
START public Handles setForceEndTransactions(boolean forceEndTransactions) { END this.forceEndTransactions = forceEndTransactions; return this; } This is a backwards incompatible change and cannot be merged.

Target:
public void setForceEndTransactions(boolean forceEndTransactions) { this.forceEndTransactions = forceEndTransactions; }
Source:
protected Cause createUpstreamCause(Run<?, ?> build) { if(Jenkins.getInstance().getPlugin("promoted-builds") != null) { // Test only when promoted-builds is installed. if(build instanceof Promotion) { Promotion promotion = (Promotion)build; // This cannot be done for PromotionCause#PromotionCause is in a package scope. // return new PromotionCause(build, promotion.getTarget()); return new UpstreamCause((Run<?,?>)promotion.getTarget()); } } START return new UpstreamCause((Run) build); END } You should remove obsolete class casts

Target:
protected Cause createUpstreamCause(Run<?, ?> build) { if(Jenkins.getInstance().getPlugin("promoted-builds") != null) { // Test only when promoted-builds is installed. if(build instanceof Promotion) { Promotion promotion = (Promotion)build; // This cannot be done for PromotionCause#PromotionCause is in a package scope. // return new PromotionCause(build, promotion.getTarget()); return new UpstreamCause((Run<?,?>)promotion.getTarget()); } } return new UpstreamCause(build); }
Source:
public static <Arg1, Arg2 extends Arg1> boolean nullSafeEquals(Arg1 d1, Arg2 d2) { if (d1 == null) { return d2 == null; } else if (d2 == null) { return false; } START return (d1 instanceof Timestamp || d2 instanceof Timestamp) ? compare((Date) d1, (Date) d2) == 0 : d1.equals(d2); END } Wouldn't it actually be better to check if instance of Date and then delegate to compare(Date, Date)?

Target:
public static <Arg1, Arg2 extends Arg1> boolean nullSafeEquals(Arg1 d1, Arg2 d2) { if (d1 == null) { return d2 == null; } else if (d2 == null) { return false; } return (d1 instanceof Date && d2 instanceof Date) ? compare((Date) d1, (Date) d2) == 0 : d1.equals(d2); }
Source:
public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final HeapObject other = (HeapObject) obj; if ( node == null ) { return other.node == null; } START else return node.equals(other.node); END } You don't need the `else` clause because the `if` clause does a `return`.

Target:
public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final HeapObject other = (HeapObject) obj; if ( node == null ) { return other.node == null; } return node.equals(other.node); }
Source:
public void testSignalIntermediateThrow() throws Exception { KieBase kbase = createKnowledgeBase("BPMN2-IntermediateThrowEventSignal.bpmn2"); ksession = createKnowledgeSession(kbase); Map<String, Object> params = new HashMap<String, Object>(); params.put("x", "MyValue"); ProcessInstance processInstance = ksession.startProcess( "SignalIntermediateEvent", params); START Assertions.assertThat(processInstance.getState()).isEqualTo(ProcessInstance.STATE_COMPLETED); END } I think in this class it is possible.

Target:
public void testSignalIntermediateThrow() throws Exception { KieBase kbase = createKnowledgeBase("BPMN2-IntermediateThrowEventSignal.bpmn2"); ksession = createKnowledgeSession(kbase); Map<String, Object> params = new HashMap<String, Object>(); params.put("x", "MyValue"); ProcessInstance processInstance = ksession.startProcess( "SignalIntermediateEvent", params); assertThat(processInstance.getState()).isEqualTo(ProcessInstance.STATE_COMPLETED); }
Source:
public KHyperLogLog(int maxSize, int hllBuckets, Long2ObjectSortedMap<HyperLogLog> minhash) { this.maxSize = maxSize; this.hllBuckets = hllBuckets; this.minhash = requireNonNull(minhash, "minhash is null"); hllsTotalEstimatedInMemorySize = 0; hllsTotalEstimatedSerializedSize = 0; START for (HyperLogLog hll : minhash.values()) { END increaseTotalHllSize(hll); } } nit: how about `minhash.values().stream().forEach(this:: increaseTotalHllSize)`?

Target:
public KHyperLogLog(int maxSize, int hllBuckets, Long2ObjectSortedMap<HyperLogLog> minhash) { this.maxSize = maxSize; this.hllBuckets = hllBuckets; this.minhash = requireNonNull(minhash, "minhash is null"); minhash.values().forEach(this::increaseTotalHllSize); }
Source:
public ChangeControl controlFor(Change change, CurrentUser user) throws NoSuchChangeException { START final Project.NameKey projectKey = projectCache.get(change.getProject()).getProject().getNameKey(); END try { return projectControl.controlFor(projectKey, user).controlFor(change); } catch (NoSuchProjectException e) { throw new NoSuchChangeException(change.getId(), e); } } This is dumb. Add a Project.Id form to ProjectControl.GenericFactory and ProjectControl.Factory. That way we only have to perform 1 cache lookup, not 2.

Target:
public ChangeControl controlFor(Change change, CurrentUser user) throws NoSuchChangeException { try { return projectControl.controlFor(change.getProject(), user).controlFor(change); } catch (NoSuchProjectException e) { throw new NoSuchChangeException(change.getId(), e); } }
Source:
public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (ShareFragmentListener) activity; } catch (ClassCastException e) { START throw new ClassCastException(activity.toString() END + " must implement OnShareFragmentInteractionListener"); } } Should throw ```IllegalStateException``` , or similar.

Target:
public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (ShareFragmentListener) activity; } catch (IllegalStateException e) { throw new IllegalStateException(activity.toString() + " must implement OnShareFragmentInteractionListener"); } }
Source:
START public void afterTaskInputVariableChangedEvent(TaskEvent event, Map<String, Object> variables) { END if (variables == null || variables.isEmpty()) { return; } Task task = event.getTask(); List<TaskVariableImpl> taskVariables = indexVariables(task, variables, VariableType.INPUT); AuditTaskImpl auditTaskImpl = createAuditTask(task, event.getEventDate()); sendMessage(new AuditTaskData(auditTaskImpl, null, taskVariables, null), 2); } I wonder why we don't emit an event in this case. Another thing is that I think in this case (using JMS) we will update autitTaskImpl in the database, but we currently don't update it in case we use normal JPA LifeCycleListener for tasks. Isn't this a little bit inconsistent? https://github.com/kiegroup/jbpm/blob/25fabbca948df52f69475ca54a8cf85fe09e4074/jbpm-human-task/jbpm-human-task-audit/src/main/java/org/jbpm/services/task/audit/JPATaskLifeCycleEventListener.java#L743-L753 Here we just index and persist variables.

Target:
public void afterTaskInputVariableChangedEvent(TaskEvent event, Map<String, Object> variables) { if (variables == null || variables.isEmpty()) { return; } Task task = event.getTask(); List<TaskVariableImpl> taskVariables = indexVariables(task, variables, VariableType.INPUT); sendMessage(new AuditTaskData(null, null, taskVariables, null), 2); }
Source:
public RubyGemParser(IFile file) throws IOException, CoreException { mSetupDefinitions = new HashMap<String, ArrayList<Object>>(); mSetupDependencies = new HashMap<String, ArrayList<Object>>(); START if (file.getContents().available() <= 0) END return; this.file = file; gemVariable = ""; parse(); } Remember to put around if/else/while/for etc.

Target:
public RubyGemParser(IFile file) throws IOException, CoreException { mSetupDefinitions = new HashMap<String, ArrayList<String>>(); mSetupDependencies = new HashMap<String, ArrayList<String>>(); if (file.getContents().available() <= 0) { return; } this.file = file; gemVariable = ""; parse(); }
Source:
public boolean canHandle(Message<?> message) { START return super.canHandle(message) && deadlineNameMatch((DeadlineMessage) message); END } I would turn this `&&` around. A simple deadlineName check is a lot cheaper than the full parameter assignment verification.

Target:
public boolean canHandle(Message<?> message) { return message instanceof DeadlineMessage && deadlineNameMatch((DeadlineMessage) message) && super.canHandle(message); }
Source:
private void checkImportedSymbol(Symbol symbol) { for (IdentifierTree usageIdentifier : symbol.usages()) { Tree parent = usageIdentifier.parent(); START if (parent.is(Kind.MEMBER_SELECT) && ((MemberSelectExpressionTree) parent).expression().is(Kind.MEMBER_SELECT)) { END reportIssue(parent, String.format(MESSAGE, symbol.name())); hasIssue.add(parent); } } } This approach won't work if all the classes of a project are in a single root package: ``` package org; import org.B; class A { org.B b; // should be noncompliant } ``` ``` package org; class B { ... } ``` You probably should rather rely on the type of the symbol associated to the identifier of the parent member select, if the parent is a member select. ``` if (parent.is(Kind.MEMBER_SELECT)) { ExpressionTree expression = ((MemberSelectExpressionTree) parent).expression(); if (expression.is(Kind.MEMBER_SELECT) && !((MemberSelectExpressionTree) expression).identifier().symbol().isTypeSymbol()) { return; } reportIssue(parent, String.format(MESSAGE, symbol.name())); hasIssue.add(parent); } ```

Target:
private void checkImportedSymbol(Symbol symbol) { for (IdentifierTree usageIdentifier : symbol.usages()) { Tree parent = usageIdentifier.parent(); if (parent.is(Kind.MEMBER_SELECT) && ((MemberSelectExpressionTree) parent).expression().is(Kind.MEMBER_SELECT)) { reportIssue(parent, String.format(MESSAGE, symbol.name())); } } }
Source:
public void jmsPort_shouldBeExportedWithCorrectId() throws Exception { START if (!featuresService.isInstalled(featuresService.getFeature("openengsb-ports-ws"))) { END featuresService.installFeature("openengsb-ports-jms"); } OutgoingPort serviceWithId = OpenEngSBCoreServices.getServiceUtilsService().getServiceWithId(OutgoingPort.class, "jms-json", 60000); assertNotNull(serviceWithId); } maybe, if @ Before doesn't work, create a method setUp for this? since the same code lines are in the beginning of each test of this class

Target:
public void jmsPort_shouldBeExportedWithCorrectId() throws Exception { OutgoingPort serviceWithId = OpenEngSBCoreServices.getServiceUtilsService().getServiceWithId(OutgoingPort.class, "jms-json", 60000); assertNotNull(serviceWithId); }
Source:
private EventHandler createContextEventHandler() { if (contextEventHandler == null) { contextEventHandler = START new EventHandler() { END @Override public void handleEvent(Event event) { handleContextSet(event); } }; } return contextEventHandler; } we have lambdas for this now.

Target:
private EventHandler createContextEventHandler() { if (contextEventHandler == null) { contextEventHandler = event -> handleContextSet(event); } return contextEventHandler; }
Source:
public AnnotationValueReader(@Nonnull DexBuffer dex, @Nonnull ByteInput in) { START super(dex, in); this.dex = dex; END } Make the "super" dex field protected and remove this one? Or a protected getDexBuffer() method?

Target:
public AnnotationValueReader(@Nonnull DexBuffer dex, @Nonnull ByteInput in) { super(dex, in); }
Source:
protected Blob convertBlobToMimeType(Blob blob, String destinationMimeType) { BlobHolder bh = new SimpleBlobHolder(blob); START bh = convertToMimeType(destinationMimeType, bh, new HashMap<String, Serializable>()); END if (bh == null) { return null; } Blob result = bh.getBlob(); return result; } You can pass `null` instead of `new HashMap<String, Serializable>()`.

Target:
protected Blob convertBlobToMimeType(Blob blob, String destinationMimeType) { BlobHolder bh = new SimpleBlobHolder(blob); bh = convertToMimeType(destinationMimeType, bh, null); return bh == null ? null : bh.getBlob(); }
Source:
private Set<SupportedAdditionalClusterFeature> getAdditionalClusterFeaturesAdded() { // Lets not modify the existing collection. Hence creating a new hashset. Set<SupportedAdditionalClusterFeature> featuresSupported = START new HashSet<SupportedAdditionalClusterFeature>(getVdsGroup().getAddtionalFeaturesSupported()); END featuresSupported.removeAll(clusterFeatureDao.getSupportedFeaturesByClusterId(getVdsGroup().getId())); return featuresSupported; } i don't think redeclaring the type on the right side is needed.

Target:
private Set<SupportedAdditionalClusterFeature> getAdditionalClusterFeaturesAdded() { // Lets not modify the existing collection. Hence creating a new hashset. Set<SupportedAdditionalClusterFeature> featuresSupported = new HashSet<>(getVdsGroup().getAddtionalFeaturesSupported()); featuresSupported.removeAll(clusterFeatureDao.getSupportedFeaturesByClusterId(getVdsGroup().getId())); return featuresSupported; }
Source:
static void runScript(String filename, Connection cx) throws SQLException { try { SqlUtil.runScript(new GeoPackage().getClass().getResourceAsStream(filename), cx); } catch (IOException e) { START END } } Eeek, eatin away exceptions?

Target:
static void runScript(String filename, Connection cx) throws SQLException { try { SqlUtil.runScript(new GeoPackage().getClass().getResourceAsStream(filename), cx); } catch (IOException e) { throw new SQLException(e); } }
Source:
public void recycleAttributes(long ts) { START fPoolAttributes.entrySet().stream().forEach(e END -> { NonNullUtils.checkNotNull(e.getKey()).recycle(e.getValue(), ts); }); } why stream? entrySet is iterable.

Target:
public void recycleAttributes(long ts) { fPoolAttributes.entrySet().forEach(e -> { NonNullUtils.checkNotNull(e.getKey()).recycle(e.getValue(), ts); }); }
Source:
public boolean hasNext() { // If we do not have the next element pipelined, go ahead and fetch it. START if (next == null) { END // If the iterator is valid, this means that the next entry exists. checkInvariants(); if (iterator.isValid()) { // Go ahead and cache that entry. next = new AbstractMap.SimpleEntry( serializer.deserialize(Unpooled.wrappedBuffer(iterator.key()), corfuRuntime), serializer.deserialize(Unpooled.wrappedBuffer(iterator.value()), corfuRuntime)); // Advance the underlying iterator. iterator.next(); } else { // If there is no more elements to consume, we should release the resources. iterator.close(); } } return next != null; } please invert `if` condition

Target:
public boolean hasNext() { // If we have the next element pipelined, go ahead and return true. if (next != null) { return true; } // If the iterator is valid, this means that the next entry exists. checkInvariants(); if (iterator.isValid()) { // Go ahead and cache that entry. next = new AbstractMap.SimpleEntry( serializer.deserialize(Unpooled.wrappedBuffer(iterator.key()), corfuRuntime), serializer.deserialize(Unpooled.wrappedBuffer(iterator.value()), corfuRuntime)); // Advance the underlying iterator. iterator.next(); } else { // If there is no more elements to consume, we should release the resources. iterator.close(); } return next != null; }
Source:
public int run() throws IOException { int b; if (in != null) { START while ((b = in.read()) != -1) out.write(b); END in.close(); } out.close(); return -1; } Missing braces

Target:
public int run() throws IOException { int b; if (in != null) { while ((b = in.read()) != -1) { out.write(b); } in.close(); } out.close(); return -1; }
Source:
public List<Cohort> getCohortsContainingPatientId(Integer patientId) throws DAOException { return (List<Cohort>) sessionFactory.getCurrentSession().createCriteria(Cohort.class) START .add(Restrictions.eq("voided", false)) END .createAlias("members", "m") .createAlias("m.patientId", "p") .add(Restrictions.eq("p.patientId", patientId)) .list(); } Do you have a voided field in this cohort_member table? In theory members don't get removed from the set. You might need to update Cohort.removeMember() to set stop date instead of removing. Which means that getCohortsContainingPatientId() should return cohorts that contain the patient as of the current date i.e members that have no stop date or those where the startDate is before current date and end date is after current date

Target:
public List<Cohort> getCohortsContainingPatientId(Integer patientId) throws DAOException { return getCohortsContainingPatientId(patientId, false); }
Source:
protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { try { if (dataSink != null) { tupleWriter.open(dataSink.getOutputStream()); } START tupleWriter.writeColumnHeaders(getChild().getSchema().getColumnNames()); END } catch (IOException e) { throw new DbException(e); } } How can this succeed if `tupleWriter.open()` isn't called (when `dataSink` is `null`)?

Target:
protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { try { tupleWriter.open(dataSink.getOutputStream()); tupleWriter.writeColumnHeaders(getChild().getSchema().getColumnNames()); } catch (IOException e) { throw new DbException(e); } }
Source:
public long getSizeInBytes() { long sizeInBytes = 0; START int partitionCount = partitionFunction.getPartitionCount(); END for (int i = 0; i < partitionCount; i++) { sizeInBytes += partitionData[i].getSizeInBytes(); } return sizeInBytes; } use partitionData.length for consistency with getRetainedSizeInBytes ``` public long getSizeInBytes() { long sizeInBytes = 0; for (int i = 0; i < partitionData.length; i++) { sizeInBytes += partitionData[i].getSizeInBytes(); } return sizeInBytes; } ```

Target:
public long getSizeInBytes() { long sizeInBytes = 0; for (int i = 0; i < partitionData.length; i++) { sizeInBytes += partitionData[i].getSizeInBytes(); } return sizeInBytes; }
Source:
public FixedRealVarImpl(String name, double value, Model model) { START super(name, model); this.lb = value; this.ub = value; END } Replace by `this(name, value, value, model);`

Target:
public FixedRealVarImpl(String name, double value, Model model) { this(name, value, value, model); }
Source:
public void isGreaterThan() { assertTrue(V3_0.isGreaterThan(of(2, 0))); assertFalse(V3_0.isGreaterThan(of(3, 0))); assertFalse(V3_0.isGreaterThan(of(4, 0))); assertTrue(V3_0.isGreaterThan(NEGATIVE_VERSION_1)); START assertTrue(NEGATIVE_VERSION_1.isGreaterThan(NEGATIVE_VERSION_2)); END } I'd expect this to be the other way around, when version is a WAN version. I'm thinking about subclassing `Version`. That way we can create `ClusterVersion` and `WanVersion` that can - compare/sort the versions properly, - validate that once we set a cluster version, it can't be replaced by a WAN version (checking the sign bit) and vice-versa. WDYT?

Target:
public void isGreaterThan() throws Exception { assertTrue(V3_0.isGreaterThan(of(2, 0))); assertFalse(V3_0.isGreaterThan(of(3, 0))); assertFalse(V3_0.isGreaterThan(of(4, 0))); }
Source:
private String extractDefinitionLine(String typeDeclaration) { String typeLine = ""; String[] lines = typeDeclaration.split("\n"); for (String line : lines) { typeLine = typeLine + "\n" + line; if (line.contains("{")) { break; } } return typeLine; START } END I think that it is ok, although I am not sure how I feel about including the "\n".

Target:
private String extractDefinitionLine(String typeDeclaration) { String typeLine = ""; String[] lines = typeDeclaration.split("\n"); for (String line : lines) { typeLine = line; if (line.contains("{")) { break; } } return typeLine; }
Source:
public ItemAshenMask(ArmorMaterial material, int renderIndex, EntityEquipmentSlot slot, AshenMasks maskType) { super(material, renderIndex, slot); setHasSubtypes(true); START this.maxStackSize = 64; END this.maskType = maskType; ItemRegistry.maskMap.put(maskType, this); } stackable armo(u)r?

Target:
public ItemAshenMask(ArmorMaterial material, int renderIndex, EntityEquipmentSlot slot, AshenMasks maskType) { super(material, renderIndex, slot); this.maskType = maskType; ItemRegistry.maskMap.put(maskType, this); }
Source:
private void onSuccess() { START if (errorCount.getAndSet(0) >= config.storeIOErrorCountToTriggerShutdown) { END logger.info("Resetting the error count of BlobStore because restart or one operation succeeded", storeId); } } I don't understand the `if` here. If the errorCount() was higher or equal to `config.storeIOErrorCountToTriggerShutdown`, won't the store be shutting/shut down?

Target:
private void onSuccess() { errorCount.getAndSet(0); }
Source:
private ApplicationReportModel createAppDependencyGraphReport(GraphContext context) { START ApplicationReportService applicationReportService = new ApplicationReportService(context); END ApplicationReportModel report = applicationReportService.create(); report.setReportPriority(104); report.setReportIconClass("glyphicon glyphicon-tree-deciduous"); report.setTemplatePath(TEMPLATE); report.setTemplateType(TemplateType.FREEMARKER); report.setDisplayInApplicationReportIndex(Boolean.TRUE); report.setDescription(REPORT_DESCRIPTION); return report; } Perhaps the '104' could be a constant?

Target:
private ApplicationReportModel createAppDependencyGraphReport(GraphContext context) { ApplicationReportService applicationReportService = new ApplicationReportService(context); ApplicationReportModel report = applicationReportService.create(); report.setReportPriority(104); report.setReportIconClass("glyphicon glyphicon-tree-deciduous"); report.setTemplatePath(TEMPLATE); report.setTemplateType(TemplateType.FREEMARKER); report.setDisplayInApplicationReportIndex(Boolean.TRUE); return report; }
Source:
private void startClient() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, UnknownHostException { if (client == null) { LOG.info("Connecting to the ElasticSearch cluster: " + configuration.getClusterName()); if (configuration.getHostAddressesList() != null && !configuration.getHostAddressesList().isEmpty()) { client = createClient(); } else { START LOG.info("Incorrect ip address and port parameters settings for ElasticSearch cluster"); END } } } Should this not be WARN or some exception thrown? Instead of logging that the ip is incorrect. And maybe this validation should be done in the doStart method so its validated earlier

Target:
private void startClient() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, UnknownHostException { if (client == null) { LOG.info("Connecting to the ElasticSearch cluster: " + configuration.getClusterName()); if (configuration.getHostAddressesList() != null && !configuration.getHostAddressesList().isEmpty()) { client = createClient(); } else { LOG.warn("Incorrect ip address and port parameters settings for ElasticSearch cluster"); } } }
Source:
protected String getRemoveQosMessage(int size) { START return ConstantsManager.getInstance().getMessages().removeStorageQoSMessage(); END } shouldn't the message get the 'size'?

Target:
protected String getRemoveQosMessage(int size) { return ConstantsManager.getInstance().getMessages().removeStorageQoSMessage(size); }
Source:
public static Map<Guid, List<DiskImage>> getImagesLeaf(List<DiskImage> images) { Map<Guid, List<DiskImage>> retVal = new HashMap<>(); START images.stream().forEach(image END -> MultiValueMapUtils.addToMap(image.getId(), image, retVal)); retVal.values().forEach(ImagesHandler::sortImageList); return retVal; } Just use images.forEach

Target:
public static Map<Guid, List<DiskImage>> getImagesLeaf(List<DiskImage> images) { Map<Guid, List<DiskImage>> retVal = new HashMap<>(); images.forEach(image -> MultiValueMapUtils.addToMap(image.getId(), image, retVal)); retVal.values().forEach(ImagesHandler::sortImageList); return retVal; }
Source:
protected boolean moveToState(STATE to) { if (state.get() == to) { START return false; END } return moveToState(state.get(), to); } What is the contract for the return of this method? If we are already at the state that we are trying to move to, it could be said that the moveToState is successful (i.e. true).

Target:
protected void moveToState(STATE to) { if (state.get() != to) { moveToState(state.get(), to); } }
Source:
public void writeTo(Resource file) throws JDOMException, IOException { OutputStream out = path.out(); try { IOUtils.write(body, out); } finally { out.close(); START } END } @NielsCharlier try-with-resources?

Target:
public void writeTo(Resource file) throws JDOMException, IOException { try (OutputStream out = path.out()) { IOUtils.write(body, out); } }
Source:
START public ApplicationFetchException(String apiKey, ErrorCode errorCode) { END super(); this.apiKey = apiKey; this.errorCode = errorCode; } The class is abstract. Constructor should be `protected`

Target:
protected ApplicationFetchException(String apiKey, ErrorCode errorCode) { super(); this.apiKey = apiKey; this.errorCode = errorCode; }
Source:
private void addResource(final BackendResource resource) { resource.setMessageBundle(messageBundle); resource.setBackend(backend); resource.setSessionHelper(sessionHelper); if (resource instanceof AbstractBackendResource) { ((AbstractBackendResource) resource).setMappingLocator(mappingLocator); } else if (resource instanceof CapabilitiesResource) { ((BackendCapabilitiesResource) resource).setMappingLocator(mappingLocator); } START resource.setValidatorLocator(validatorLocator); END singletons.add(resource); } using this approach only root collections will have validatorLocator, all sub-collections/resources will get NPE, when you'll try to use it, you need to inject it in runtime to every resource.

Target:
private void addResource(final BackendResource resource) { resource.setMessageBundle(messageBundle); resource.setBackend(backend); resource.setSessionHelper(sessionHelper); if (resource instanceof AbstractBackendResource) { ((AbstractBackendResource) resource).setMappingLocator(mappingLocator); } else if (resource instanceof CapabilitiesResource) { ((BackendCapabilitiesResource) resource).setMappingLocator(mappingLocator); } singletons.add(resource); }
Source:
public boolean isEmpty() { START synchronized (listeners) END { return listeners.size() == 0; } } listeners is atomic

Target:
public boolean isEmpty() { return listeners.isEmpty(); }
Source:
void setEnd(int end) { this.end = end; START if (this.end > this.maxSeen) END { this.maxSeen = this.end; } } Here we need to take sequence number wrap around into account. Alternatively, what we could do is unconditionally set the `maxSeen`, and prevent the `maxSeen` from being set if the `end` has been set. However, I don't like adding this kind of logic in the setters. Maybe it'd be better to have a getMaxOrEnd() method.

Target:
void setEnd(int end) { this.end = end; }
Source:
public void dispose() { //Remove all messages from the queue START this.mHandler.removeCallbacksAndMessages(null); END this.mHandler = null; this.mPhone = null; } > Use this.mHandler.removeCallbacksAndMessages(null) instead. Done in Patch set 2

Target:
public void dispose() { }
Source:
public boolean indexShareable() { TypedProperties properties = properties(); boolean hasRamDirectoryProvider = false; boolean hasOtherDirectoryProvider = false; for (Object objKey : properties.keySet()) { String key = (String) objKey; if (key.endsWith(DIRECTORY_PROVIDER_KEY)) { if (properties.get(key).equals(RAM_DIRECTORY_PROVIDER)) { hasRamDirectoryProvider = true; } else { START hasOtherDirectoryProvider = true; END } } } boolean ramOnly = hasRamDirectoryProvider && !hasOtherDirectoryProvider; return !ramOnly; } a couple of questions: - can't you return true here? - is it possible to configure multiple directory providers?

Target:
public boolean indexShareable() { TypedProperties properties = properties(); boolean hasRamDirectoryProvider = false; for (Object objKey : properties.keySet()) { String key = (String) objKey; if (key.endsWith(DIRECTORY_PROVIDER_KEY)) { if (properties.get(key).equals(RAM_DIRECTORY_PROVIDER)) { hasRamDirectoryProvider = true; } else { return true; } } } return !hasRamDirectoryProvider; }
Source:
public boolean delete( final ConcreteResource resource, final EventMetadata eventMetadata ) throws TransferException { final Transfer item = getCacheReference( resource ); if ( !resource.allowsDeletion() ) { throw new TransferException( "Deletion not allowed for: {}", resource ); START } END return doDelete( item, eventMetadata ); } move this to the first line of this method for optimization.

Target:
public boolean delete( final ConcreteResource resource, final EventMetadata eventMetadata ) throws TransferException { if ( !resource.allowsDeletion() ) { throw new TransferException( "Deletion not allowed for: {}", resource ); } final Transfer item = getCacheReference( resource ); return doDelete( item, eventMetadata ); }
Source:
public String getActualCpuTopology() { START if (actualCpuTopology < 0) { END return ConstantsManager.getInstance().getConstants().notAvailableLabel(); } else { return String.valueOf(actualCpuTopology); } } when will it be < 0? isnt it better to use Integer that can be null? (like other fields in vm dynamic)

Target:
public String getActualCpuTopology() { if (actualCpuTopology > 0) { return String.valueOf(actualCpuTopology); } else { return ConstantsManager.getInstance().getConstants().notAvailableLabel(); } }
Source:
public void onPageScrolled(int i, float v, int i2) { if (pager.getCurrentItem() != 0) { speakerbox.stop(); } if (pager.getCurrentItem() == pagerPositionWhenPaused) { resume.setVisibility(View.GONE); START getView().findViewById(R.id.routes).setBackgroundColor(act.getBaseContext() END .getResources().getColor(R.color.transparent_white)); } } Oh I see now it does get slightly darker when you manually page. It was so subtle I didn't see it at first.

Target:
public void onPageScrolled(int i, float v, int i2) { if (pager.getCurrentItem() != 0) { speakerbox.stop(); } if (pager.getCurrentItem() == pagerPositionWhenPaused) { resume.setVisibility(View.GONE); } }
Source:
public void benchWavTrack() throws Exception { WavTrack wavTrack = new WavTrack(url); boolean isEOMReached = false; while (!isEOMReached) { Frame process = wavTrack.process(0); isEOMReached = process.isEOM(); } START wavTrack.close(); END } If an exception can be thrown, then wrap wavTrack.close() in a try-finally block, to guarantee resources are properly closed.

Target:
public void benchWavTrack() throws Exception { try { wavTrack = new WavTrack(url); boolean isEOMReached = false; while (!isEOMReached) { Frame process = wavTrack.process(0); isEOMReached = process.isEOM(); } }finally { wavTrack.close(); } }
Source:
private static void setupLogger(Map<String, Object> args) throws IOException{ String logfile = (String)args.get("log-file"); Logger logger = Logger.getLogger(""); logger.setLevel((Level)args.get("log-level")); logger.addHandler(new ConsoleHandler()); if(logfile != null) { FileHandler fh = new FileHandler(logfile); fh.setFormatter(new SimpleFormatter()); logger.addHandler(fh); START } END } aren't these already set by logging.properties?

Target:
private void setupLogger(Map<String, Object> args) throws IOException{ Logger logger = Logger.getLogger(""); logger.setLevel((Level)args.get("log-level")); String logfile = (String)args.get("log-file"); if(logfile != null) { FileHandler fh = new FileHandler(logfile); fh.setFormatter(new SimpleFormatter()); logger.addHandler(fh); } }
Source:
public XWikiAttachment set(XWikiAttachment attachment) { XWikiAttachment put = map.put(attachment.getFilename(), attachment); START if (put == null || !put.equals(attachment)) { END added(attachment); updatedMap(); } return put; } I would use == instead of equals. XWikiAttachment don't implement equals and even if they were is might be super slow (they would have to compare sometime big files contents). Then no need for `put == null` anymore since the input cannot be null.

Target:
public XWikiAttachment set(XWikiAttachment attachment) { XWikiAttachment put = map.put(attachment.getFilename(), attachment); if (put != attachment) { added(attachment); updatedMap(); } return put; }
Source:
START public boolean equals(Object obj) { END if (obj instanceof MethodKey) { MethodKey toCompare = (MethodKey) obj; return toCompare.name.equals(name) && toCompare.parameterTypes.equals(parameterTypes); } return false; } final, here and elsewhere

Target:
public final boolean equals(Object obj) { if (obj instanceof MethodKey) { MethodKey toCompare = (MethodKey) obj; return toCompare.name.equals(name) && toCompare.parameterTypes.equals(parameterTypes); } return false; }
Source:
MongoDBTracing(Builder builder) { tracing = builder.tracing; maxAbbreviatedCommandLength = builder.maxAbbreviatedCommandLength; START commandsWithCollectionName = Collections.unmodifiableSet(builder.commandsWithCollectionName); END } Copy into a new set too, the user will still be able to modify the set through the builder.

Target:
MongoDBTracing(Builder builder) { tracing = builder.tracing; }
Source:
public void disconnect() { START Object lock = partitions != null ? partitions : new Object(); END synchronized (lock) { document = null; partitions = null; try { inputStream.close(); } catch (IOException e) { } } } this makes no sense. synchronizing on a new object is meaningless. I do not know why partitions must be null, if we want synchronize on this object, we should make it final and never null, instead simply clear() them on dispose

Target:
public void disconnect() { Object lock = partitions != null ? partitions : new Object(); synchronized (lock) { document = null; partitions.clear(); try { inputStream.close(); } catch (IOException e) { } } }
Source:
private void printInfo(String sizeMessage, String inAlluxioMessage, String inMemMessage, String path) { START System.out.println(inMemMessage.equals("") END ? String.format(SHORT_INFO_FORMAT, sizeMessage, inAlluxioMessage, path) : String.format(LONG_INFO_FORMAT, sizeMessage, inAlluxioMessage, inMemMessage, path)); } can use `inMemMessage.isEmpty()`

Target:
private void printInfo(String sizeMessage, String inAlluxioMessage, String inMemMessage, String path) { System.out.println(inMemMessage.isEmpty() ? String.format(SHORT_INFO_FORMAT, sizeMessage, inAlluxioMessage, path) : String.format(LONG_INFO_FORMAT, sizeMessage, inAlluxioMessage, inMemMessage, path)); }
Source:
public void tearDown() { // Destroy JMX beans created during testing. START MetricsService metricsService = new MetricsService(nodeEngineMock, () -> metricsRegistry); END metricsService.init(nodeEngineMock, new Properties()); metricsService.shutdown(true); JmxLeakHelper.checkJmxBeans(); // Stop executor service. if (executionService != null) { executionService.shutdown(); } } I think alternatively we can move out the construction of the service from the test cases into a factory method that sets a shutdown function object field that we can call in the tearDown. This may prevent some other unwanted potential side-effects. With this approach we construct two services, but shutdown only one. For example, the service submits a scheduled task. I think it is fine for now, but it would be safer with the function proposed.

Target:
public void tearDown() { // Destroy JMX beans created during testing. if (metricsService != null) { metricsService.shutdown(true); metricsService = null; } JmxLeakHelper.checkJmxBeans(); // Stop executor service. if (executionService != null) { executionService.shutdown(); } }
Source:
public AdsBaseObject verifyAdImage(String slotName, String src, String imageUrl) { WebElement element = getWebElement(slotName); START boolean isMobile = src.toUpperCase().equals("MOBILE"); END Assertion.assertTrue(new AdsComparison().compareImageWithScreenshot(imageUrl, element, driver, isMobile)); PageObjectLogging.log("verifyAdImage", "Ad looks good", true, driver); return this; } swap the left and right for the equals to avoid NullPointerException also, use equalsIgnoreCase instead ``` "MOBILE".equalsIgnoreCase(src); ```

Target:
public AdsBaseObject verifyAdImage(String slotName, String src, String imageUrl) { WebElement element = getWebElement(slotName); boolean isMobile = "MOBILE".equalsIgnoreCase(src); Assertion.assertTrue(new AdsComparison().compareImageWithScreenshot(imageUrl, element, driver, isMobile)); PageObjectLogging.log("verifyAdImage", "Ad looks good", true, driver); return this; }
Source:
START public Set<String> getUnmatchedLabels() { END return Collections.unmodifiableSet(unmatchedLabels); } Missing synchronization?

Target:
public synchronized Set<String> getUnmatchedLabels() { return Collections.unmodifiableSet(unmatchedLabels); }
Source:
public void scanForRepoChanges() throws IOException { refs.refresh(); START getAllRefs(); // This will look for changes to refs END if (!isBare()) getIndex(); // This will detect changes in the index } This shouldn't be necessary anymore. RefDirectory.refresh() should trigger an event listener if one or more refs was detected to be modified, which means we can drop the getAllRefs() call here.

Target:
public void scanForRepoChanges() throws IOException { getAllRefs(); // This will look for changes to refs if (!isBare()) getIndex(); // This will detect changes in the index }
Source:
public List<Server> getReachableServers() { START return getServerList(true); END } In the LB impls (both this and the Base version), if we are deprecating getServerList(boolean), it would be preferable to move the code logic into getReachableServer() and getAllServers(), and defer getServerList(boolean) to call either getReachableServers or getAllServers based on the boolean.

Target:
public List<Server> getReachableServers() { return null; }