auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static ZonedDateTime parse(String dateString) { int n = 0; for (DateTimeFormatter df : DATE_TIME_FORMATTERS) { try { return toZonedDateTime(df.parse(dateString)); } catch (DateTimeParseException dte) { // we ignore wrong formats START n++; END continue; } } if (IS_NUMERIC_P.matcher(dateString) .matches()) { long ldate = Long.parseLong(dateString); return Instant.ofEpochMilli(ldate) .atZone(UTC_ZONE_ID); } return null; } What does the `n` variable do here?

Target:
public static ZonedDateTime parse(String dateString) { for (DateTimeFormatter df : DATE_TIME_FORMATTERS) { try { return toZonedDateTime(df.parse(dateString)); } catch (DateTimeParseException dte) { // we ignore wrong formats continue; } } if (IS_NUMERIC_P.matcher(dateString) .matches()) { long ldate = Long.parseLong(dateString); return Instant.ofEpochMilli(ldate) .atZone(UTC_ZONE_ID); } return null; }
Source:
public Optional<RGBValues> getFillColor() { RGBValues rgbValues = null; if (style instanceof NodeStyle) { rgbValues = new NodeStyleQuery((NodeStyle) style).getBackgroundColor().get(); } else if (style instanceof FlatContainerStyle) { rgbValues = ((FlatContainerStyle) style).getBackgroundColor(); } else if (style instanceof ShapeContainerStyle) { rgbValues = START ((FlatContainerStyle) style).getBackgroundColor(); END } return Optional.ofNullable(rgbValues); } Copy/Paste error: should be ShapeContainerStyle. This causes errors in tests: java.lang.ClassCastException: org.eclipse.sirius.diagram.business.internal.metamodel.spec.ShapeContainerStyleSpec cannot be cast to org.eclipse.sirius.diagram.FlatContainerStyle at org.eclipse.sirius.diagram.ui.business.internal.query.ColorStyleQuery.getFillColor(ColorStyleQuery.java:105)

Target:
public Optional<RGBValues> getFillColor() { RGBValues rgbValues = null; if (style instanceof NodeStyle) { rgbValues = new NodeStyleQuery((NodeStyle) style).getBackgroundColor().get(); } else if (style instanceof FlatContainerStyle) { rgbValues = ((FlatContainerStyle) style).getBackgroundColor(); } else if (style instanceof ShapeContainerStyle) { rgbValues = ((ShapeContainerStyle) style).getBackgroundColor(); } return Optional.ofNullable(rgbValues); }
Source:
public void indexMembers() throws InterruptedException { MassIndexer mi = Search.getFullTextEntityManager(em).createIndexer(Member.class); mi.startAndWait(); START Search.getFullTextEntityManager(em).flushToIndexes(); END } There is no need to flush here

Target:
public void indexMembers() throws InterruptedException { MassIndexer mi = Search.getFullTextEntityManager(em).createIndexer(Member.class); mi.startAndWait(); }
Source:
public void testGetPublicKeyPairNullInput1() { try{ KeyGenUtils.getPublicKeyPair(null, truePublicKeys[0]); } catch (UnsupportedTypeException e) { START fail("UnsupportedTypeException thrown"); END } } Is it possible to declare the function with `throws UnsupportedTypeException` instead of the try-catch? (Other functions do similarly.) Will JUnit still fail reasonably if it does throw?

Target:
public void testGetPublicKeyPairNullInput1() { KeyGenUtils.getPublicKeyPair(null, truePublicKeys[0]); }
Source:
private boolean containsNullOrEmpty(List<String> values) { //return values != null && ( values.contains(null) || values.contains("") ); if(values == null) return true ; START if(values.isEmpty()) return true ; END for(String str : values) { if(StringUtils.isBlank(str)) return true ; } return false; } Another minor note, any reason not to merge this into a single check? `if(values == null || values.isEmpty()) return true ;`

Target:
private boolean containsNullOrEmpty(List<String> values) { if(values == null || values.isEmpty()) return true ; for(String str : values) { if(StringUtils.isBlank(str)) return true ; } return false; }
Source:
START public static <T> Flowable<T> fromOptional(@NonNull Optional<T> optional) { END ObjectHelper.requireNonNull(optional, "optional is null"); return optional.map(Flowable::just).orElseGet(Flowable::empty); } +NonNull for return type

Target:
public static <T> Flowable<@NonNull T> fromOptional(@NonNull Optional<T> optional) { ObjectHelper.requireNonNull(optional, "optional is null"); return optional.map(Flowable::just).orElseGet(Flowable::empty); }
Source:
private static Map<AbstractProject,DependencyChange> getDependencyChanges(Run<?,?> run) { START AbstractBuild<?,?> build = null; END if(run instanceof AbstractBuild) return ((AbstractBuild) run).getDependencyChanges((AbstractBuild)run); //jenkins workflow plugin etc. else return Maps.newHashMap(); } Unused

Target:
private static Map<AbstractProject,DependencyChange> getDependencyChanges(Run<?,?> run) { if(run instanceof AbstractBuild) return ((AbstractBuild) run).getDependencyChanges((AbstractBuild)run); //jenkins workflow plugin etc. else return Maps.newHashMap(); }
Source:
public void onRemoved(Iterable<CacheEntryEvent<? extends K, ? extends V>> events) throws CacheEntryListenerException { START for (Object event1 : events) { END CacheEntryEvent event = (CacheEntryEvent) event1; Assert.assertEquals(EventType.REMOVED, event.getEventType()); this.removed.incrementAndGet(); event.getKey(); if (event.isOldValueAvailable()) { event.getOldValue(); } } } Same regarding cast

Target:
public void onRemoved(Iterable<CacheEntryEvent<? extends K, ? extends V>> events) throws CacheEntryListenerException { for (CacheEntryEvent<? extends K, ? extends V> event : events) { Assert.assertEquals(EventType.REMOVED, event.getEventType()); this.removed.incrementAndGet(); if (event.isOldValueAvailable()) { event.getOldValue(); } } }
Source:
Attribute(String name, ModelType type, CapabilityReferenceRecorder reference) { START this.definition = new SimpleAttributeDefinitionBuilder(name, type, true) END .setCapabilityReference(reference) .setFlags(Flag.RESTART_RESOURCE_SERVICES) .build(); } But the attribute actually is required. So we'd be reporting incorrect metadata to work around a test fixture problem?

Target:
Attribute(String name, ModelType type, CapabilityReferenceRecorder reference) { this.definition = new SimpleAttributeDefinitionBuilder(name, type) .setCapabilityReference(reference) .setFlags(Flag.RESTART_RESOURCE_SERVICES) .build(); }
Source:
Page<Book> getDefaultPageable(Pageable pageable) { if (pageable != null) { START return new PageImpl<>(Collections.singletonList(new Book()), pageable, 1); END } return new PageImpl<>(Collections.emptyList(), pageable, 0); } I think we have to (should) stay with Java 6 syntax here.

Target:
Page<Book> getDefaultPageable(Pageable pageable) { if (pageable != null) { return new PageImpl<Book>(Collections.singletonList(new Book()), pageable, 1); } return new PageImpl<Book>(Collections.emptyList(), pageable, 0); }
Source:
public String getEmbedMapID(){ String mapID = mapFrame.getAttribute("data-mapid"); START return mapID; END } combine the two lines and return the String

Target:
public String getEmbedMapID() { return mapFrame.getAttribute("data-mapid"); }
Source:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_FACILITY_ATTR_DEF); attr.setFriendlyName("accountExpirationTime"); START attr.setDisplayName("Accoun expiration."); END attr.setType(Integer.class.getName()); attr.setDescription("Account expiration."); return attr; } "Account" instead of "Accoun"

Target:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_FACILITY_ATTR_DEF); attr.setFriendlyName("accountExpirationTime"); attr.setDisplayName("Account expiration."); attr.setType(Integer.class.getName()); attr.setDescription("Account expiration."); return attr; }
Source:
private Disk clone(Disk parent) { Disk disk = new Disk(); disk.setId(parent.getId()); START disk.setVm(new VM()); END if (parent.isSetVm()) { disk.getVm().setId(parent.getVm().getId()); } return disk; } disk.setVm(new VM()); should be inside of this /if/

Target:
private Disk clone(Disk parent) { Disk disk = new Disk(); disk.setId(parent.getId()); if (parent.isSetVm()) { disk.setVm(new VM()); disk.getVm().setId(parent.getVm().getId()); } return disk; }
Source:
public boolean shouldRun() { final boolean shouldRun = START pendingPartitions.size() END > 0; return shouldRun; } not synchronized

Target:
public boolean shouldRun() { synchronized (pendingPartitions) { final boolean shouldRun = pendingPartitions.size() > 0; return shouldRun; } }
Source:
public static String join(String[] array) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String s : array) { if (first) { first = false; } else { sb.append('.'); } sb.append(s); } START return sb.toString(); END } What is the reason for the longer version? EDIT: ok, did no see it was from hibernate. You could use `String.join` from Java 8 though.

Target:
public static String join(String[] array) { return join(Arrays.asList(array)); }
Source:
START public synchronized void lock() { END hasBeenInitialized = true; internalMap = ImmutableMap.copyOf(internalMap); } I imagine the ```synchronized``` keyword is going to move up to init and then this will become private. Is there any situation where we want this to be locked externally?

Target:
private void lock() { hasBeenInitialized = true; internalMap = ImmutableMap.copyOf(internalMap); }
Source:
private String findHostId(String hostName) throws DotDataException { String hostId = null; DotConnect dc = new DotConnect(); dc.setSQL(SELECT_HOSTID_BY_NAME_QUERY); dc.addParam(hostName); List<Map<String,String>> result = dc.loadResults(); if(!result.isEmpty()){ START hostId = result.get(0).get("identifier").toString(); END } return hostId; } ![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') "get" returns a string, there's no need to call "toString()". [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS1858)

Target:
private String findHostId(String hostName) throws DotDataException { String hostId = null; DotConnect dc = new DotConnect(); dc.setSQL(SELECT_HOSTID_BY_NAME_QUERY); dc.addParam(hostName); List<Map<String, String>> result = dc.loadResults(); if (!result.isEmpty()) { hostId = result.get(0).get("identifier"); } return hostId; }
Source:
START public void notifyCameraDeviceClose() { END synchronized (mExecutingCaptureConfigCallbacks) { for (CaptureConfigCaptureCallback callback : mExecutingCaptureConfigCallbacks) { callback.onRequestCancelled(); } mExecutingCaptureConfigCallbacks.clear(); } notifySurfaceDetached(); } Should this just call the StateCallback.onClosed() method? And should the onClosed() method aslo have the request canceling?

Target:
public void notifyCameraDeviceClose() { notifySurfaceDetached(); }
Source:
public boolean commit() { if (os != null) { unlock(); throw new IllegalStateException(MessageFormat.format(JGitText.get().lockOnNotClosed, ref)); } saveStatInformation(); try { FileUtils.rename(lck, ref, StandardCopyOption.ATOMIC_MOVE); haveLck = false; START token.close(); END return true; } catch (IOException e) { unlock(); return false; } } shouldn't we set token to null now? If a token is succesfully closed and the link has been deleted we shouldn't keep references to it.

Target:
public boolean commit() { if (os != null) { unlock(); throw new IllegalStateException(MessageFormat.format(JGitText.get().lockOnNotClosed, ref)); } saveStatInformation(); try { FileUtils.rename(lck, ref, StandardCopyOption.ATOMIC_MOVE); haveLck = false; token.close(); token = null; return true; } catch (IOException e) { unlock(); return false; } }
Source:
public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription delegatingResourceDescription = new DelegatingResourceDescription(); delegatingResourceDescription.addProperty("fulfillerStatus"); delegatingResourceDescription.addProperty("fulfillerComment"); START delegatingResourceDescription.addProperty("uuid"); END delegatingResourceDescription.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); delegatingResourceDescription.addSelfLink(); return delegatingResourceDescription; } You don't need these properties because they actually don't exist nor apply

Target:
public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription delegatingResourceDescription = new DelegatingResourceDescription(); delegatingResourceDescription.addProperty("fulfillerStatus"); delegatingResourceDescription.addProperty("fulfillerComment"); return delegatingResourceDescription; }
Source:
public gov.hhs.fha.nhinc.common.connectionmanagerinfo.UDDIUpdateManagerForceRefreshResponseType forceRefreshFileFromUDDIServer( START gov.hhs.fha.nhinc.common.connectionmanagerinfo.UDDIUpdateManagerForceRefreshRequestType uddiUpdateManagerForceRefreshRequest) { END LOG.info("forceRefreshFileFromUDDIServer"); UDDIUpdateManagerHelper helper = new UDDIUpdateManagerHelper(); return helper.forceRefreshFileFromUDDIServer(uddiUpdateManagerForceRefreshRequest); } I don't think we ever use this method again

Target:
public gov.hhs.fha.nhinc.common.connectionmanagerinfo.UDDIUpdateManagerForceRefreshResponseType forceRefreshFileFromUDDIServer( gov.hhs.fha.nhinc.common.connectionmanagerinfo.UDDIUpdateManagerForceRefreshRequestType uddiUpdateManagerForceRefreshRequest) { LOG.trace("forceRefreshFileFromUDDIServer"); UDDIUpdateManagerHelper helper = new UDDIUpdateManagerHelper(); return helper.forceRefreshFileFromUDDIServer(uddiUpdateManagerForceRefreshRequest); }
Source:
START void remove(Closeable hook) { END if (closeHooks != null) { closeHooks.remove(hook); } } synchronization issue here.

Target:
synchronized void remove(Closeable hook) { if (closeHooks != null) { closeHooks.remove(hook); } }
Source:
private boolean isInTimeRange(ITmfTimestamp traceStartTime, ITmfTimestamp traceEndTime) { START if END (traceStartTime.compareTo(fEndTimeRange) <= 0 && traceEndTime.compareTo(fStartTimeRange) >= 0) { return true; } return false; } return the condition 's value directly?

Target:
private boolean isInTimeRange(ITmfTimestamp traceStartTime, ITmfTimestamp traceEndTime) { return traceStartTime.compareTo(fEndTimeRange) <= 0 && traceEndTime.compareTo(fStartTimeRange) >= 0; }
Source:
public void testMakingAttachment() { START testMakingAttachmentFile("attachment.txt","normal text file") END } missing semicolon;

Target:
public void testMakingAttachment() { testMakingAttachmentFile("attachment.txt","normal text file"); }
Source:
@Test public void givesAllArgsAChanceToShrink() { assertThat(testResult(GivesAllArgsAChanceToShrink.class), failureCountIs(2)); START assertThat(Others.shrinkAttempts, greaterThan(0)); END } shrinkAttempts should be greaterThan(1) (equal to 2), or did I misunderstand that?

Target:
@Test public void givesAllArgsAChanceToShrink() { assertThat(testResult(GivesAllArgsAChanceToShrink.class), failureCountIs(2)); assertThat(Others.shrinkAttempts, greaterThan(1)); }
Source:
private void waitForStatus(final long jobId, final Status status) throws InterruptedException, TimeoutException { CommonUtils.waitFor("Waiting for job status", () -> { try { return mJobMaster.getStatus(jobId).getStatus() == status; } catch (Exception e) { Throwables.propagate(e); } return null; START }, WaitForOptions.defaults().setInterval(10).setTimeoutMs(10 * Constants.SECOND_MS)); END } why is this needed?

Target:
private void waitForStatus(final long jobId, final Status status) throws InterruptedException, TimeoutException { CommonUtils.waitFor("Waiting for job status", () -> { try { return mJobMaster.getStatus(jobId).getStatus() == status; } catch (Exception e) { Throwables.propagate(e); } return null; }, WaitForOptions.defaults().setTimeoutMs(10 * Constants.SECOND_MS)); }
Source:
public Predicate<ChangeData> message(String text) { START return new MessagePredicate(args.dbProvider, args.repoManager, args.index, text); END } Since the message operator is now only supported if the secondary index is enabled, we should check for this before creating the predicate (the same way as it is done for the file operator): if (args.index == ChangeIndex.DISABLED) { throw error("secondary index must be enabled for message:" + text); }

Target:
public Predicate<ChangeData> message(String text) { return new MessagePredicate(args.dbProvider, args.index, text); }
Source:
public START boolean setBranchSameAsAccess(boolean END branchSameAsAccess) { return this.branchSameAsAccess = branchSameAsAccess; } Other setters in this class are void.

Target:
public void setBranchSameAsAccess(boolean branchSameAsAccess) { this.branchSameAsAccess = branchSameAsAccess; }
Source:
public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay readerWay, EncodingManager.Access access, long relationFlags) { if (readerWay.hasTag("toll", "yes")) tollEnc.setEnum(false, edgeFlags, Toll.ALL); if (readerWay.hasTag("toll:hgv", "yes")) START tollEnc.setEnum(false, edgeFlags, Toll.HGV); END return edgeFlags; } For an edge with: ``` toll=yes toll:hgv=yes ``` This would result in `Toll.HGV` and not `Toll.ALL`

Target:
public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay readerWay, EncodingManager.Access access, long relationFlags) { if (readerWay.hasTag("toll", "yes")) tollEnc.setEnum(false, edgeFlags, Toll.ALL); else if (readerWay.hasTag("toll:hgv", "yes")) tollEnc.setEnum(false, edgeFlags, Toll.HGV); return edgeFlags; }
Source:
START @Override public boolean isPlayer() END { return false; } Fix your formatter settings please or disable it :wink:

Target:
public boolean isPlayer() { return false; }
Source:
byte[] byteArrayFromInt(int val) { byte[] b = new byte[4]; b[3] = (byte) (val); b[2] = (byte) (val >>> 8); b[1] = (byte) (val >>> 16); b[0] = (byte) (val >>> 24); START return b; END } It doesn't really matter, but could be: ```java return new byte[] { (byte) (val >>> 24), (byte) (val >>> 16), (byte) (val >>> 8), (byte) val }; ```

Target:
byte[] byteArrayFromInt(int val) { return new byte[] { (byte) (val >>> 24), (byte) (val >>> 16), (byte) (val >>> 8), (byte) (val) }; }
Source:
START protected int END getFontStyle(String fontStyleExpression, EAttribute eAttribute, FontData defaultFontData, StyledText text) { int fontStyle = defaultFontData.getStyle(); if (fontStyleExpression != null && !fontStyleExpression.isEmpty()) { Eval eval = new Eval(interpreter, variableManager); String fontStyleValue = eval.get(eAttribute, fontStyleExpression, String.class); fontStyle = getFontStyle(fontStyleValue, fontStyle, text); } return fontStyle; } not useful, you are not using this method outside of the AbstractEEFLifecycleManager

Target:
private int getFontStyle(String fontStyleExpression, EAttribute eAttribute, FontData defaultFontData, StyledText text) { int fontStyle = defaultFontData.getStyle(); if (fontStyleExpression != null && !fontStyleExpression.isEmpty()) { Eval eval = new Eval(interpreter, variableManager); String fontStyleValue = eval.get(eAttribute, fontStyleExpression, String.class); fontStyle = getFontStyle(fontStyleValue, fontStyle, text); } return fontStyle; }
Source:
private static HandlerDecorator buildDecorator(Class<? extends HandlerDecorator> decoratorClass) { HandlerDecorator decorator; try { START decorator = decoratorClass.getConstructor().newInstance(); END } catch (ReflectiveOperationException e) { throw new IllegalStateException("Decorator class " + decoratorClass + "cannot be instantiated", e); } return decorator; } We could the variable declaration and just use `return decoratorClass.getConstructor().newInstance();`

Target:
private static HandlerDecorator buildDecorator(Class<? extends HandlerDecorator> decoratorClass) { try { return decoratorClass.getConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new IllegalStateException("Decorator class " + decoratorClass + "cannot be instantiated", e); } }
Source:
START private XML(String identifier) { END this.identifier = identifier; } Modifier 'private' is redundant for Enum constructor - needs to be removed.

Target:
XML(String identifier) { this.identifier = identifier; }
Source:
public CompareToBuilder append(final boolean lhs, final boolean rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs) { START comparison = +1; END } else { comparison = -1; } return this; } Why do we need `+` here?

Target:
public CompareToBuilder append(final boolean lhs, final boolean rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs) { comparison = 1; } else { comparison = -1; } return this; }
Source:
START private JavaSymbolicObject expandMacro(JavaSymbolicObject node) { END JavaSymbolicObject expandedNode = (JavaSymbolicObject) node.accept(this); while (!node.equals(expandedNode)) { node = expandedNode; expandedNode = (JavaSymbolicObject) node.accept(this); } return node; } pretty sure this was right before... This looks like it might have an impact on performance. Why was this change made?

Target:
private JavaSymbolicObject expandMacro(JavaSymbolicObject node) { JavaSymbolicObject expandedNode = (JavaSymbolicObject) node.accept(this); // while some macro rule has applied, making the term references different while (node != expandedNode) { node = expandedNode; expandedNode = (JavaSymbolicObject) node.accept(this); } return node; }
Source:
public ExtendedSymbolKindType(int _v) { try { START SymbolKind s = SymbolKind.forValue(_v); END value = _v; isProtocolSymbol = true; } catch (IllegalArgumentException e) { try { CquerySymbolKind c = CquerySymbolKind.forValue(_v); value = _v; isProtocolSymbol = false; } catch (IllegalArgumentException y) { throw new IllegalArgumentException("Illegal value for SymbolKind"); } } } The variable 's' is not used. If you're doing this for the bounds check, you can just do 'SymbolKind.forValue(_v)' and discard the return value. (Does your IDE show a warning for the unused variable? If not, you may want to turn that on. In general, please try to avoid introducing new warnings if they can be avoided. (Sometimes, it cannot be avoided; for example, Server2ClientProtocolExtension derives from LanguageClientImpl which is technically not public API, and the API tooling gives me a warning about that, but there's nothing we can do about it except suppress it.))

Target:
public ExtendedSymbolKindType(int _v) { try { SymbolKind.forValue(_v); value = _v; isProtocolSymbol = true; } catch (IllegalArgumentException e) { try { CquerySymbolKind.forValue(_v); value = _v; isProtocolSymbol = false; } catch (IllegalArgumentException y) { throw new IllegalArgumentException("Illegal value for SymbolKind"); //$NON-NLS-1$ } } }
Source:
private boolean applyTypedFilter(Instance instance) { // Loop through all the type filters for (String type : this.typeFilters.keySet()) { if (checkType(instance.getDefinition(), type)) { // instance equals type name for (Filter innerFilter : this.typeFilters.get(type)) { if (innerFilter.match(instance)) return true; } // So, instance matches type and but does not match filter return false; } } // it reaches here that means Instance does not match any type of // type filters. Method should return true. START return true; END } But returning true here will result in the OR to yield always true, meaning that when an instance's type does not match the type of a type filter it will always be included, no matter what the result of the unconditional filters would be.

Target:
private boolean applyTypedFilter(Instance instance) { // Loop through all the type filters for (String type : this.typeFilters.keySet()) { if (checkType(instance.getDefinition(), type)) { // instance equals type name for (Filter innerFilter : this.typeFilters.get(type)) { if (innerFilter.match(instance)) return true; } // So, instance matches type and but does not match filter return false; } } // it reaches here that means Instance does not match any type of // type filters. Method should return false for lazy evaluation. return false; }
Source:
START public void synchronized setServiceContext(ServiceContext ctx) { END setContext(ctx); } synchronized should be before void. Seems you didn't run `mvn clean package` after making this change else the compiler would have caught it. See travis error here https://travis-ci.org/openmrs/openmrs-core/builds/320193916#L2148

Target:
public synchronized void setServiceContext(ServiceContext ctx) { setContext(ctx); }
Source:
public void testNoAvailabilitiesSetsActivelyPublishedToFalse() throws IOException { LoveFilmDataRow row = rowFromFile("battle-royale-no-availability.csv"); Optional<Content> extracted = extractor.extract(row); START assertTrue(extracted.isPresent()); END Content content = extracted.get(); Film film = (Film) content; assertFalse(film.isActivelyPublished()); } Not strictly necessary, since the .get() will throw if there's no extracted content.

Target:
public void testNoAvailabilitiesSetsActivelyPublishedToFalse() throws IOException { LoveFilmDataRow row = rowFromFile("battle-royale-no-availability.csv"); Optional<Content> extracted = extractor.extract(row); Content content = extracted.get(); Film film = (Film) content; assertFalse(film.isActivelyPublished()); }
Source:
public ClusterFeatures list() { ClusterFeatures features = new ClusterFeatures(); Set<AdditionalFeature> addlFeatures = BackendClusterFeatureHelper.getClusterFeatures(this, version); addlFeatures.forEach(clusterFeature -> { org.ovirt.engine.api.model.ClusterFeature feature = START addLinks(ClusterFeaturesMapper.map(clusterFeature, END null)); features.getClusterFeatures().add(feature); }); return features; } You can use just "map" here, it is defined in the base class.

Target:
public ClusterFeatures list() { ClusterFeatures features = new ClusterFeatures(); Set<AdditionalFeature> addlFeatures = BackendClusterFeatureHelper.getClusterFeatures(this, version); addlFeatures.forEach(clusterFeature -> { org.ovirt.engine.api.model.ClusterFeature feature = addLinks(map(clusterFeature, null)); features.getClusterFeatures().add(feature); }); return features; }
Source:
public QueryInfo updateQueryInfo(Optional<StageInfo> stageInfo) { QueryInfo queryInfo = getQueryInfo(stageInfo); if (queryInfo.isFinalQueryInfo()) { START session.getSessionLogger().log(() -> "Marking query finally done"); END queryInfo.setSessionLogEntries(session.getSessionLogger().getEntries()); finalQueryInfo.compareAndSet(Optional.empty(), Optional.of(queryInfo)); } return queryInfo; } nit: remove

Target:
public QueryInfo updateQueryInfo(Optional<StageInfo> stageInfo) { QueryInfo queryInfo = getQueryInfo(stageInfo); if (queryInfo.isFinalQueryInfo()) { queryInfo.setSessionLogEntries(session.getSessionLogger().getEntries()); finalQueryInfo.compareAndSet(Optional.empty(), Optional.of(queryInfo)); } return queryInfo; }
Source:
public Object execute(ExecutionEvent event) { InputDialog dialog = new InputDialog(Display.getCurrent() .getActiveShell(), Messages.PerfSaveSession_title, Messages.PerfSaveSession_msg, "", new IInputValidator() { //$NON-NLS-1$ @Override public String isValid(String newText) { START if ("".equals(newText)) { //$NON-NLS-1$ END return Messages.PerfSaveSession_invalid_filename_msg; } return null; } }); if (dialog.open() == Window.OK) { saveData(dialog.getValue()); } return null; } You would better use newText.isEmpty() here.

Target:
public Object execute(ExecutionEvent event) { InputDialog dialog = new InputDialog(Display.getCurrent() .getActiveShell(), Messages.PerfSaveSession_title, Messages.PerfSaveSession_msg, "", new IInputValidator() { //$NON-NLS-1$ @Override public String isValid(String newText) { if (newText.isEmpty()) { return Messages.PerfSaveSession_invalid_filename_msg; } return null; } }); if (dialog.open() == Window.OK) { saveData(dialog.getValue()); } return null; }
Source:
public void unsubscribeOthers(AmbSubscriber<T> notThis) { for (AmbSubscriber<T> other : ambSubscribers) { if (other != notThis) { other.unsubscribe(); } START ambSubscribers.clear(); END } } `ambSubscribers.clear();` should be out of the loop.

Target:
public void unsubscribeOthers(AmbSubscriber<T> notThis) { for (AmbSubscriber<T> other : ambSubscribers) { if (other != notThis) { other.unsubscribe(); } } ambSubscribers.clear(); }
Source:
protected IPageStore newPersistentStore() { StoreSettings storeSettings = application.getStoreSettings(); Bytes maxSizePerSession = storeSettings.getMaxSizePerSession(); File fileStoreFolder = storeSettings.getFileStoreFolder(); START if (storeSettings.isEncrypted()) { END return new SerializingPageStore(new CryptingPageStore(new DiskPageStore(application.getName(), fileStoreFolder, maxSizePerSession)), getSerializer()); } else { return new DiskPageStore(application.getName(), fileStoreFolder, maxSizePerSession, getSerializer()); } } Maybe it would be nice to not make the chain configurable by a field in general but to have something more spring like. (Like in case of spring Filters) They implemented it with a List in which you can add filter at various places and they delegate to each other. You can add new filters in between like filters.add(0,new MyFilter(...)); WDYT?

Target:
protected IPageStore newPersistentStore() { StoreSettings storeSettings = application.getStoreSettings(); Bytes maxSizePerSession = storeSettings.getMaxSizePerSession(); File fileStoreFolder = storeSettings.getFileStoreFolder(); return new DiskPageStore(application.getName(), fileStoreFolder, maxSizePerSession); }
Source:
public void onInfoWindowClick(Marker marker) { // Stop any callbacks to refresh the vehicle marker popup balloons mCustomInfoWindowAdapter.cancelUpdates(); // Show trip details screen for the vehicle associated with this marker ObaTripStatus status = mMarkerData.getStatusFromMarker(marker); START String focusedStopId = mController.getFocusedStopId(); END if (mController != null && mController.getFocusedStopId != null) { TripDetailsActivity.start(mActivity, status.getActiveTripId(), focusedStopId); } else { TripDetailsActivity.start(mActivity, status.getActiveTripId()); } } @azizmb9494 It looks like the Amazon implementation is slightly different here than the Google implementation. Sometimes this can happen if the Gradle copy script doesn't execute properly when you're building the Google variant. Could you try re-building this project again using any of the Google build variants (oba, agencyx, agencyy) to re-generate the Amazon code, and then push that new version here?

Target:
public void onInfoWindowClick(Marker marker) { // Stop any callbacks to refresh the vehicle marker popup balloons mCustomInfoWindowAdapter.cancelUpdates(); // Show trip details screen for the vehicle associated with this marker ObaTripStatus status = mMarkerData.getStatusFromMarker(marker); if (mController != null && mController.getFocusedStopId() != null) { TripDetailsActivity.start(mActivity, status.getActiveTripId(), mController.getFocusedStopId()); } else { TripDetailsActivity.start(mActivity, status.getActiveTripId()); } }
Source:
public ElevationModule(ElevationGridCoverageFactory factory) { START gridCoverageFactory = factory; END cachedElevationsFile = null; readCachedElevations = false; writeCachedElevations = false; elevationUnitMultiplier = 1; } Use `this(factory, null, false, false, 1)`. Then if someone add/remove a new parameter to the "main" constructor he/she needs to make a decision what to do with this one.

Target:
public ElevationModule(ElevationGridCoverageFactory factory) { this( factory, null, false, false, 1, true, false ); }
Source:
public int maxDepth( Envelope referenceEnvelope, Envelope range, int nbrDim, int maxLevel ) { double searchRatio = range.getArea() / referenceEnvelope.getArea(); START final int i = (int) (Math.log( searchRatio ) / Math.log( Math.pow( 2, nbrDim ) )) + extraLevels; END return i; } I'm not sure, but do we need to use the natural logarithmic here or are you just after logarithmic behaviour in general? In the latter case, it would be more efficient to use `log2`, I suppose. Then you could write this as `(int) (Math.log2(searchRatio) / nbrDim) + extraLevels`

Target:
public int maxDepth( Envelope referenceEnvelope, Envelope range, int nbrDim, int maxLevel ) { double searchRatio = range.getArea() / referenceEnvelope.getArea(); return (int) (Math.log( searchRatio ) / Math.log( Math.pow( 2, nbrDim ) )) + extraLevels; }
Source:
public StatementsMatcher(List<Statement> statements) { START Collections.copy(statements, unmatched); END } Its the _Matcher_ that gets reused multiple times - the list probably doesn't.

Target:
public StatementsMatcher(List<Statement> statements) { unmatched = new ArrayList<>(); // Make a local copy of statements, because it's probably mutable // and we don't want to change it upon a later removeAll call. Collections.copy(statements, unmatched); }
Source:
public void addNewAuthorization() { START if (groups.get(0).getRule() != null) { END groups.add(0, new AuthorizationGroupBean()); } } What if groups is empty at this point ?

Target:
public void addNewAuthorization() { if ((!groups.isEmpty() && groups.get(0).getRule() != null) || groups.isEmpty()) { groups.add(0, new AuthorizationGroupBean()); } }
Source:
public static boolean allUnique(List<String> argListNames) { START return argListNames.stream().allMatch(new HashSet<>()::add); END } `new HashSet<>(list).size() == list.size();`

Target:
public static boolean allUnique(List<String> argListNames) { return argListNames.size() == new HashSet<>(argListNames).size(); }
Source:
private void fixSize() { perspSwitcherToolbar.pack(); perspSwitcherToolbar.getParent().pack(); START perspSwitcherToolbar.getShell().requestLayout(); END } Shouldn't requestLayout be called on the perspSwitcherToolbar Control directly, instead of the Shell?

Target:
private void fixSize() { perspSwitcherToolbar.pack(); perspSwitcherToolbar.getParent().pack(); perspSwitcherToolbar.requestLayout(); }
Source:
protected final List<?> createValues() { START if (withNulls == Nulls.ALL) { END return NULL_VALUES; } if (withNulls == Nulls.PARTIAL) { return IntStream.range(0, ROWS).mapToObj(i -> i % 2 == 0 ? createValue() : null).collect(toList()); } return IntStream.range(0, ROWS).mapToObj(i -> createValue()).collect(toList()); } nit: switch statement would be more natural here ``` switch (withNulls) { case ALL: return NULL_VALUES; case PARTIAL: return IntStream.range(0, ROWS).mapToObj(i -> i % 2 == 0 ? createValue() : null).collect(toList()); default: return IntStream.range(0, ROWS).mapToObj(i -> createValue()).collect(toList()); } ```

Target:
protected final List<?> createValues() { switch (withNulls) { case ALL: return NULL_VALUES; case PARTIAL: return IntStream.range(0, ROWS).mapToObj(i -> i % 2 == 0 ? createValue() : null).collect(toList()); default: return IntStream.range(0, ROWS).mapToObj(i -> createValue()).collect(toList()); } }
Source:
protected void setComparator(Comparator comparator) { this.comparator = comparator; Iterable items = getItems(); if (items == null) { return; } Iterable identicalItems = (comparator == null) ? new ArrayList() : new TreeSet(comparator); for (Object item : items) { START setItems(identicalItems); END } } did you mean- for (Object item : items) { identicalItems.add(item); } setItems(identicalItems); - Cause now the loop is redundant and you reset the old items when you set the comparator.

Target:
protected void setComparator(Comparator comparator) { if (comparator == this.comparator) { return; } this.comparator = comparator; Iterable items = getItems(); if (items == null) { return; } Collection identicalItems = (comparator == null) ? new ArrayList() : new TreeSet(comparator); for (Object item : items) { identicalItems.add(item); } setItems(identicalItems); }
Source:
public void notifySurfaceDetached() { // Release active image reader in detached listener super.notifySurfaceDetached(); // Release inactive image readers START if (mImageReaderToReleaseList.size() > 0) { END for (ImageReaderProxy imageReader : mImageReaderToReleaseList) { Surface surface = imageReader.getSurface(); if (surface != null) { surface.release(); } imageReader.close(); } mImageReaderToReleaseList.clear(); } } Use isEmpty() or alternatively, don't have to check size, the for loop will not run if it is empty.

Target:
public void notifySurfaceDetached() { // Release active image reader in detached listener super.notifySurfaceDetached(); // Release inactive image readers if (!mImageReaderToReleaseList.isEmpty()) { for (ImageReaderProxy imageReader : mImageReaderToReleaseList) { // There will be the stric mode erro under API Level 23. Add surface // release to dereference. Surface surface = imageReader.getSurface(); if (surface != null) { surface.release(); } imageReader.close(); } mImageReaderToReleaseList.clear(); } }
Source:
private T findUniqueResult() { START if (collection.size() == 1) { END return collection.iterator().next(); } return uniqueResult; } Ternary if?

Target:
private T findUniqueResult() { return collection.size() == 1 ? collection.iterator().next() : null; }
Source:
public MetadataMap getMetadata() { if (metadata == null) { START metadata = new MetadataMap(); END } return metadata; } If you are going to do this do you need to @sychronize? If not indicate it is not threadsafe...

Target:
public synchronized MetadataMap getMetadata() { if (metadata == null) { metadata = new MetadataMap(); } return metadata; }
Source:
public void updateMemoryUsage(long deltaUserMemoryInBytes, long deltaTotalMemoryInBytes) { START long currentUserMemoryValue = currentUserMemory.addAndGet(deltaUserMemoryInBytes); END long currentTotalMemoryValue = currentTotalMemory.addAndGet(deltaTotalMemoryInBytes); peakUserMemory.updateAndGet(currentPeakValue -> Math.max(currentUserMemoryValue, currentPeakValue)); peakTotalMemory.updateAndGet(currentPeakValue -> Math.max(currentTotalMemoryValue, currentPeakValue)); } `currentXXMemoryValue` is a weird name; maybe we can just inline these two variables. Or use `currentUserMemory.get()` below.

Target:
public void updateMemoryUsage(long deltaUserMemoryInBytes, long deltaTotalMemoryInBytes) { currentUserMemory.addAndGet(deltaUserMemoryInBytes); currentTotalMemory.addAndGet(deltaTotalMemoryInBytes); peakUserMemory.updateAndGet(currentPeakValue -> Math.max(currentUserMemory.get(), currentPeakValue)); peakTotalMemory.updateAndGet(currentPeakValue -> Math.max(currentTotalMemory.get(), currentPeakValue)); }
Source:
public final Date getExtendedExpiresOn() { START return this.mExtendedExpiresOn; END } > this [](start = 15, length = 4) no this. please

Target:
public final Date getExtendedExpiresOn() { return mExtendedExpiresOn; }
Source:
public FileInfo(FileSystem srcFs, Path sourcePath, String subDir) { this.srcFs = srcFs; this.sourcePath = sourcePath; START this.cmPath = null; END this.checkSum = null; this.useSourcePath = true; this.subDir = subDir; } this constructor can directly call the below one

Target:
public FileInfo(FileSystem srcFs, Path sourcePath, String subDir) { this(srcFs, sourcePath, null, null, true, subDir); }
Source:
public boolean isAuthorized() { if (session.isVoAdmin(voId)) { return true; } else { START return group != null && session.isGroupAdmin(groupId); END } } Hi, since existing object ids start with 1 and you define voId/groupId=0 by default, then you can safely use something like: `session.isVoAdmin(voId) || session.isGroupAdmin(groupId)` in the first IF.

Target:
public boolean isAuthorized() { return (session.isVoAdmin(voId) || session.isGroupAdmin(groupId)); }
Source:
public String propertyForUserName(Criteria criteria, boolean creator) { criteria.createAlias("creator", "creator"); START criteria.createAlias("lastModifier", "lastModifier"); END return creator ? "creator.loginName" : "lastModifier.loginName"; } `"creator"` and `"lastModifier"` should be added to `STANDARD_ALIASES` instead of creating the aliases here

Target:
public String propertyForUserName(Criteria criteria, boolean creator) { return creator ? "creator.loginName" : "lastModifier.loginName"; }
Source:
public List<RadiologyReport> getRadiologyReportsByRadiologyOrderAndRadiologyReportStatus(RadiologyOrder radiologyOrder, RadiologyReportStatus radiologyReportStatus) { START List<RadiologyReport> result = sessionFactory.getCurrentSession() END .createCriteria(RadiologyReport.class) .add(Restrictions.eq("radiologyOrder", radiologyOrder)) .add(Restrictions.eq("reportStatus", radiologyReportStatus)) .list(); return result == null ? new ArrayList<RadiologyReport>() : result; } use final

Target:
public List<RadiologyReport> getRadiologyReportsByRadiologyOrderAndRadiologyReportStatus(RadiologyOrder radiologyOrder, RadiologyReportStatus radiologyReportStatus) { final List<RadiologyReport> result = sessionFactory.getCurrentSession() .createCriteria(RadiologyReport.class) .add(Restrictions.eq("radiologyOrder", radiologyOrder)) .add(Restrictions.eq("reportStatus", radiologyReportStatus)) .list(); return result == null ? new ArrayList<RadiologyReport>() : result; }
Source:
public static Boolean notExists( EvaluationContext ctx, List tests, Object target) { for (Object test : tests) { Boolean r = applyUnaryTest(ctx, test, target); START if (r != null && r) return false; END } return true; } just double checking that this is really the intent? change looks odd..

Target:
public static Boolean notExists( EvaluationContext ctx, List tests, Object target) { for (Object test : tests) { Boolean r = applyUnaryTest(ctx, test, target); if (r == null || r) return false; } return true; }
Source:
public Optional<U> generate(final WebContext context, final U profile) { init(); final U linkedProfile = profileService.findByLinkedId(profile.getId()); if (linkedProfile != null) { return Optional.of(linkedProfile); } else { if (failIfLinkedUserNotFound) { throw new TechnicalException("No linked account found for: " + profile); } else { // fallback to the original account START return Optional.ofNullable(profile); END } } } the ofNullable makes no sense because you called profile.getId() on it at the beginning of the method: if it was null we wouldn't have arrived here in the code. The profile parameter is meant to be non-null.

Target:
public U generate(final WebContext context, final U profile) { init(); final U linkedProfile = profileService.findByLinkedId(profile.getId()); if (linkedProfile != null) { return linkedProfile; } else { if (failIfLinkedUserNotFound) { throw new TechnicalException("No linked account found for: " + profile); } else { // fallback to the original account return profile; } } }
Source:
public String toString() { START return "SslSession(alpn=" + (alpn == null ? "null" : alpn) + END ", npn=" + (npn == null ? "null" : npn) + ", version=" + (version == null ? "null" : version) + ", cipher=" + (cipher == null ? "null" : cipher) + ", establishedTime=" + Long.toString(establishedTime) + ", peerCert=" + (peerCert == null ? "null" : peerCert.toString()) + ")"; } There is no need to do check for null, right? I mean you could just write something like return "SslSession(alpn=" + alpn +...

Target:
public String toString() { return "SslSession(alpn=" + alpn + ", npn=" + npn + ", version=" + version + ", cipher=" + cipher + ", establishedTime=" + Long.toString(establishedTime) + ", peerCert=" + peerCert + ")"; }
Source:
/* package */void openFirstTimeWindow() { final boolean showProgress = PrefUtil.getAPIPreferenceStore().getBoolean( IWorkbenchPreferenceConstants.SHOW_PROGRESS_ON_STARTUP); if (!showProgress) { doOpenFirstTimeWindow(); } else { // We don't know how many plug-ins will be loaded, // assume we are loading a tenth of the installed plug-ins. // (The Eclipse SDK loads 7 of 86 plug-ins at startup as of // 2005-5-20) START final int expectedProgressCount = Math.max(1, WorkbenchPlugin.getDefault().getBundleCount()); END runStartupWithProgress(expectedProgressCount, () -> doOpenFirstTimeWindow()); } } I would move this down to 2508 where it's used.

Target:
/* package */void openFirstTimeWindow() { final boolean showProgress = PrefUtil.getAPIPreferenceStore().getBoolean( IWorkbenchPreferenceConstants.SHOW_PROGRESS_ON_STARTUP); if (!showProgress) { doOpenFirstTimeWindow(); } else { // We don't know how many plug-ins will be loaded, // assume we are loading a tenth of the installed plug-ins. // (The Eclipse SDK loads 7 of 86 plug-ins at startup as of // 2005-5-20) runStartupWithProgress(() -> doOpenFirstTimeWindow()); } }
Source:
START public String getY() { END return y; } change to package-private access

Target:
String getY() { return y; }
Source:
public void run() { Object selection = getStructuredSelection().getFirstElement(); if (selection instanceof IBuild) { IBuild build = (IBuild) selection; if (editor != null) { abortBuild(build, editor); } else { START abortBuild(build); END } } else if (selection instanceof IBuildPlan) { IBuildPlan buildPlan = (IBuildPlan) selection; abortBuild(buildPlan.getLastBuild()); } } this just calls abortBuild with a null editor, so why not just delete the if and call abortBuild(build,editor)

Target:
public void run() { Object selection = getStructuredSelection().getFirstElement(); if (selection instanceof IBuild) { IBuild build = (IBuild) selection; abortBuild(build); } else if (selection instanceof IBuildPlan) { IBuildPlan buildPlan = (IBuildPlan) selection; abortBuild(buildPlan.getLastBuild()); } }
Source:
private boolean hasNotAllowedTwoEmptyLinesBefore(DetailAST token) { boolean result = false; if (!allowMultipleEmptyLines) { START result = hasEmptyLineBefore(token) && isPrePreviousLineEmpty(token); END } return result; } Why was this changed? The logic looks the same.

Target:
private boolean hasNotAllowedTwoEmptyLinesBefore(DetailAST token) { return !allowMultipleEmptyLines && hasEmptyLineBefore(token) && isPrePreviousLineEmpty(token); }
Source:
public boolean matches(String type, URI uri, String realm) { //Realm is not used as for now START boolean match = true; END match &= AuthScheme.NEGOTIATE.toString().equalsIgnoreCase(type); match &= getServiceUri().getScheme().equalsIgnoreCase(uri.getScheme()); match &= getServiceUri().getHost().equalsIgnoreCase(uri.getHost()); return match; } Rewrite this as a single boolean expression: ``` java return AuthScheme.NEGOTIATE... && getServiceUri().getScheme()..... && .... ```

Target:
public boolean matches(String type, URI uri, String realm) { // The class matches all requests for Negotiate scheme.Realm is not used as for now return NEGOTIATE.equalsIgnoreCase(type); }
Source:
public static boolean isStringAssignable(TypeKind kind, boolean isPrimitive, String in) { NumberFormatValidator validator = VALIDATORS.get( kind ); START return validator != null ? validator.validate( isPrimitive, in ) : false; END } How about `validator != null && validator.validate( isPrimitive, in )`

Target:
public static boolean isStringAssignable(TypeKind kind, boolean isPrimitive, String in) { NumberFormatValidator validator = VALIDATORS.get( kind ); return validator != null && validator.validate( isPrimitive, in ); }
Source:
private LockManager() { START locks = new Hashtable<URI, LockProvider>(); END } No point in Hashtable if you are protecting the map yourself anyway by your own synchronized methods.

Target:
private LockManager() { locks = new HashMap<URI, LockProvider>(); }
Source:
public final Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable { if (!passivation) { //if we don't have passivation then it is a simple remove from DataContainer. The CDL already locks the key in //commit entries (EntryWrappingInterceptor) return invokeNextInterceptor(ctx, command); } final Object key = command.getKey(); try { START cdl.lock(key, true); END return invokeNextInterceptor(ctx, command); } finally { cdl.unlock(key); } } Do we want this to throw a TimeoutException? My thinking is if you couldn't acquire the lock we just return without running next interceptor and make it a noop like method defines.

Target:
public final Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable { if (!passivation) { //if we don't have passivation then it is a simple remove from DataContainer. The CDL already locks the key in //commit entries (EntryWrappingInterceptor) return invokeNextInterceptor(ctx, command); } final Object key = command.getKey(); if (!cdl.lock(key, true)) { return null; //no-op } try { return invokeNextInterceptor(ctx, command); } finally { cdl.unlock(key); } }