auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START private void addFreemarkerVariables(Map<String, Object> freemarkerVariables) END { } Overriding is quiet hard now that the method is private ;-)

Target:
protected void addFreemarkerVariables(Map<String, Object> freemarkerVariables) { }
Source:
private boolean isAttributeAvailable(String attributeName, Iterable<String> attributeNames) { START if (attributeName == null || Iterables.contains(attributeNames, attributeName)) END { return true; } return false; } Can be simplified to ```java return attributeName == null || Iterables.contains(attributeNames, attributeName); ```

Target:
private boolean isAttributeAvailable(String attributeName, Iterable<String> attributeNames) { return (attributeName == null || Iterables.contains(attributeNames, attributeName)); }
Source:
public AmazonBucketIngester(ImportServiceFactory importServiceFactory, FileRepositoryCollectionFactory fileRepositoryCollectionFactory, FileMetaFactory fileMetaFactory, FileStore fileStore, AmazonBucketClient amazonBucketClient) { this.importServiceFactory = requireNonNull(importServiceFactory); this.fileRepositoryCollectionFactory = requireNonNull(fileRepositoryCollectionFactory); this.fileMetaFactory = requireNonNull(fileMetaFactory); START this.fileStore = fileStore; END this.amazonBucketClient = amazonBucketClient; } requireNonNull?

Target:
public AmazonBucketIngester(ImportServiceFactory importServiceFactory, FileRepositoryCollectionFactory fileRepositoryCollectionFactory, FileMetaFactory fileMetaFactory, FileStore fileStore, AmazonBucketClient amazonBucketClient) { this.importServiceFactory = requireNonNull(importServiceFactory); this.fileRepositoryCollectionFactory = requireNonNull(fileRepositoryCollectionFactory); this.fileMetaFactory = requireNonNull(fileMetaFactory); this.fileStore = requireNonNull(fileStore); this.amazonBucketClient = requireNonNull(amazonBucketClient); }
Source:
START public void setDefaultValues() END { super.setDefaultValues(); setType(SORTA_MATCH_JOB_TYPE); } Can we get rid of setDefaultValues? Or move setType to factory class.

Target:
private void setDefaultValues() { setType(SORTA_MATCH_JOB_TYPE); }
Source:
public double getValueByName(String row, String column) { if (!inited) init(); Integer rowIndex = rowMap.get(row); Integer columnIndex = columnMap.get(column); if (rowIndex == null) throw new MolgenisDataException("Unknown row name [" + row + "]"); START if (rowIndex == null) throw new MolgenisDataException("Unknown column name [" + column + "]"); END return getValueByIndex(rowIndex, columnIndex); } Shouldnt this be columnIndex == null?

Target:
public double getValueByName(String row, String column) { if (!inited) init(); Integer rowIndex = rowMap.get(row); Integer columnIndex = columnMap.get(column); if (rowIndex == null) throw new MolgenisDataException("Unknown row name [" + row + "]"); if (columnIndex == null) throw new MolgenisDataException("Unknown column name [" + column + "]"); return getValueByIndex(rowIndex, columnIndex); }
Source:
private DoubleMatrix getMatrixByEntityTypeId(String entityId) { START DoubleMatrix matrix = null; END Entity entity = dataService.findOneById(MatrixMetadata.PACKAGE + "_" + MatrixMetadata.SIMPLE_NAME, entityId); if (entity != null) { return getMatrix(entityId, entity); } else { throw new MolgenisDataException("Unknown Matrix Metadata EntityID [" + entityId + "]"); } } Variable is never used

Target:
private DoubleMatrix getMatrixByEntityTypeId(String entityId) { Entity entity = dataService.findOneById(MatrixMetadata.PACKAGE + "_" + MatrixMetadata.SIMPLE_NAME, entityId); if (entity != null) { return getMatrix(entity); } else { throw new MolgenisDataException("Unknown Matrix Metadata EntityID [" + entityId + "]"); } }
Source:
public StandardBuilder ignoreFailure() { START ignoreFailure = true; END return this; } or just call `ignoreFailure(true)` for consistency?

Target:
public StandardBuilder ignoreFailure() { return ignoreFailure(true); }
Source:
public void notifyVideoEnd() // Must match Javascript interface method of VideoEnabledWebChromeClient { START Log.d("___", "GOT IT"); END // This code is not executed in the UI thread, so we must force that to happen new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (videoEnabledWebChromeClient != null) { videoEnabledWebChromeClient.onHideCustomView(); } } }); } Debug logging accidentally left in?

Target:
public void notifyVideoEnd() // Must match Javascript interface method of VideoEnabledWebChromeClient { // This code is not executed in the UI thread, so we must force that to happen new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (videoEnabledWebChromeClient != null) { videoEnabledWebChromeClient.onHideCustomView(); } } }); }
Source:
public MavenExecutionRequest setPom( File pom ) { this.pom = pom; START if ( this.pom != null && this.pom.getParentFile() != null ) END { this.setBaseDirectory( this.pom.getParentFile() ); } return this; } IIRC this will go wrong. There are a couple of plugins that want to rewrite the pom (maven-shade-plugin, flatten-maven-plugin). This pom will be in the target directory, so it can be cleaned up. However, the basedir should stay the same.

Target:
public MavenExecutionRequest setPom( File pom ) { this.pom = pom; return this; }
Source:
private void visit( Properties properties ) { if ( properties != null ) { for ( Map.Entry<Object, Object> entry : properties.entrySet() ) { Object v = entry.getValue(); if ( v instanceof String ) { String value = (String) v; String inter = interpolate( value ); START if ( value != inter && Objects.nonNull( inter ) ) END { entry.setValue( inter ); } } } } } `nonNull` is used in Lambda with Method Reference and not like this. That's the reason why `Objects.nonNull` was introduced in Java 1.8. Simple is better. Therefore `!= null`.

Target:
private void visit( Properties properties ) { if ( properties != null ) { for ( Map.Entry<Object, Object> entry : properties.entrySet() ) { Object v = entry.getValue(); if ( v instanceof String ) { String value = (String) v; String inter = interpolate( value ); if ( value != inter && inter != null ) { entry.setValue( inter ); } } } } }
Source:
protected ArtifactRepository getLocalRepository() throws Exception { ArtifactRepositoryLayout repoLayout = lookup( ArtifactRepositoryLayout.class, "legacy" ); START ArtifactRepository r = repositorySystem.createArtifactRepository( "local", "file://" + getLocalRepositoryPath().getAbsolutePath(), repoLayout, null, null ); END return r; } This is wrong. You cannot construct a URI like that. Please do: `toPath().toUri().toASCIIString()`.

Target:
protected ArtifactRepository getLocalRepository() throws Exception { ArtifactRepositoryLayout repoLayout = lookup( ArtifactRepositoryLayout.class ); ArtifactRepository r = repositorySystem.createArtifactRepository( "local", "file://" + getLocalRepositoryPath().getAbsolutePath(), repoLayout, null, null ); return r; }
Source:
public boolean equals( Object obj ) { if ( this == obj ) { return true; } START if ( ( obj == null ) || !( obj instanceof FileModelSource ) ) END { return false; } FileModelSource other = ( FileModelSource ) obj; return getFile().equals( other.getFile() ); } Compare with null not necessary since `null instanceof FileModelSource` is `false`

Target:
public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( !( obj instanceof FileModelSource ) ) { return false; } FileModelSource other = ( FileModelSource ) obj; return getFile().equals( other.getFile() ); }
Source:
public MetadataResolutionResult addError( Exception e ) { if ( exceptions == null ) { exceptions = initList( exceptions ); } exceptions.add( e ); START return this; END } Please remove that whitespace

Target:
public MetadataResolutionResult addError( Exception e ) { exceptions = initList( exceptions ); exceptions.add( e ); return this; }
Source:
START void setOnTop() { END System.out.println("set on top!!"); setAlwaysOnTop(false); repaint(); setAlwaysOnTop(true); repaint(); } Why is this necessay? it is called every 20ms! Why is it not sufficient to set it on top once?

Target:
void setOnTop() { setAlwaysOnTop(false); repaint(); setAlwaysOnTop(true); repaint(); }
Source:
public void storeData(String data, String filepath) throws AREAsapiException { START this.storeData(data, filepath, RES_TYPE.DATA, Charsets.UTF_8); END } so only the UTF-8 version will be supported? what about the version with the given charset name?

Target:
public void storeData(String data, String filepath) throws AREAsapiException { this.storeData(data, filepath, RES_TYPE.DATA); }
Source:
private String parseCodeName() { if (this.major == 10) { START MACOS_VERSIONS_PROPERTIES = "macos.versions.properties"; END Properties verProps = FileUtil.readPropertiesFromFilename(MACOS_VERSIONS_PROPERTIES); String version_number = this.major + "." + this.minor; String version_name = verProps.getProperty(version_number); return version_name; } LOG.warn("Unable to parse version {}.{} to a codename.", this.major, this.minor); return ""; } Sorry I wasn't more clear here. Need to keep the `oshi` to prevent conflicting with any other possible properties files on the class path. But define the string `final` up above instead of changing it here.

Target:
private String parseCodeName() { if (this.major == 10) { Properties verProps = FileUtil.readPropertiesFromFilename(MACOS_VERSIONS_PROPERTIES); return verProps.getProperty(this.major + "." + this.minor); } LOG.warn("Unable to parse version {}.{} to a codename.", this.major, this.minor); return ""; }
Source:
private void finishAllThreads(Collection<Future<Void>> results) throws Throwable { for (final Future<Void> result : results) { try { result.get(); START } catch (final ExecutionException e) { END throw e.getCause(); } } } Now that this is not a part of the original method anymore, it makes even more sense to not unwrap the original exception in order to not lose the whole trace leading not only to the executor thread but also to this `finishAllThreads` method. I think my original attempt to make the stack trace shorter has the potential of reducing clarity rather than improving it (in other words, I did a stupid thing originally).

Target:
private static void finishAllThreads(Collection<Future<Void>> results) throws InterruptedException, ExecutionException { for (final Future<Void> result : results) { result.get(); } }
Source:
START public static Double get(String key, double def) { END String value = configuration.getProperty(key); return value == null ? def : ParseUtil.parseDoubleOrDefault(value, def); } Why are we returning the boxed Double?

Target:
public static double get(String key, double def) { String value = configuration.getProperty(key); return value == null ? def : ParseUtil.parseDoubleOrDefault(value, def); }
Source:
START static String findOuiByMacAddressIfPossible(String mac) { END return vmMacAddressOUI.entrySet().stream() .filter(entry -> mac.startsWith(entry.getKey())) .map(Map.Entry::getValue) .collect(Collectors.joining()); } Can you make this public or private?

Target:
public static String findOuiByMacAddressIfPossible(String mac) { return vmMacAddressOUI.entrySet().stream() .filter(entry -> mac.startsWith(entry.getKey())) .map(Map.Entry::getValue) .collect(Collectors.joining()); }
Source:
public HWDiskStore() { name = ""; model = ""; serial = ""; START size = 0L; END reads = 0L; readBytes = 0L; writes = 0L; writeBytes = 0L; currentQueueLength = 0L; transferTime = 0L; partitions = new HWPartition[0]; timeStamp = 0L; } this is probably unnecessary as it's the default initialization.

Target:
public HWDiskStore() { }
Source:
private Boolean listElementStarts(List<String> aList, String charSeq) { for (String match : aList) { START if (match.startsWith(match)){ END return Boolean.TRUE; } } return Boolean.FALSE; } Is this line (`match.startsWith(match)`) correct? You aren't ever checking `charSeq`.

Target:
private Boolean listElementStarts(List<String> aList, String charSeq) { for (String match : aList) { if (match.startsWith(charSeq)){ return Boolean.TRUE; } } return Boolean.FALSE; }
Source:
private List<CustomAction> customActions() { List<CustomAction> actions = new LinkedList<>(); CustomAction pos = new CustomAction("org.finra.datagenerator", "transform", Transform.class); actions.add(pos); pos = new CustomAction("org.finra.datagenerator", "positive", Assign.class); actions.add(pos); return actions; START } END Why do we have to touch the positive engine?

Target:
private List<CustomAction> customActions() { List<CustomAction> actions = new LinkedList<>(); CustomAction pos = new CustomAction("org.finra.datagenerator", "transform", Transform.class); actions.add(pos); return actions; }
Source:
protected InputStream doGetInputStream() throws Exception { if (this.stat == null) { throw new FileSystemException("vfs.provider/read-not-file.error", getName()); } START final byte[] data = (this.stat.getDataLength() == 0) ? new byte[0] END : framework.getData().forPath(this.path); return new ByteArrayInputStream(data); } Extra ()'s are superfluous.

Target:
protected InputStream doGetInputStream() throws Exception { if (this.stat == null) { throw new FileSystemException("vfs.provider/read-not-file.error", getName()); } final byte[] data = this.stat.getDataLength() == 0 ? new byte[0] : framework.getData().forPath(this.path); return new ByteArrayInputStream(data); }
Source:
START private static File getCanonicalFile(final File file) { END try { return file.getCanonicalFile(); } catch (final IOException e) { return file.getAbsoluteFile(); } } There is no need to hide methods in tests, it just makes reusing code more difficult when using discovery features in IDEs like CTRL-space for method names.

Target:
public static File getCanonicalFile(final File file) { try { return file.getCanonicalFile(); } catch (final IOException e) { return file.getAbsoluteFile(); } }
Source:
public List<Integer> getTransferAbortedOkStatusCodes(final FileSystemOptions opts) { // See VFS-674, its accompanying PR and https://github.com/apache/commons-vfs/pull/51 as to why 426 and 550 are here @SuppressWarnings("unchecked") List<Integer> statusCodes = (List<Integer>) getParam(opts, TRANSFER_ABORTED_OK_STATUS_CODES); START return statusCodes != null ? statusCodes : Arrays.asList(FTPReply.TRANSFER_ABORTED, FTPReply.FILE_UNAVAILABLE); END } @boris-petrov, One more detail. I would also create a protected method called ```getDefault...``` that returns the ```Arrays.asList(FTPReply.TRANSFER_ABORTED, FTPReply.FILE_UNAVAILABLE)``` to make it clear what the defaults are with the possibility of easy override though subclassing. Gary

Target:
public List<Integer> getTransferAbortedOkStatusCodes(final FileSystemOptions opts) { return (List<Integer>) getParam(opts, TRANSFER_ABORTED_OK_STATUS_CODES); }
Source:
public int compareTo(InformationLoss<?> other) { START if (!other.getClass().equals(this.getClass())) { END throw new IllegalArgumentException("Incompatible class (" + other.getClass().getSimpleName() + ")"); } BigFraction otherValue = ((ILScore)other).getValue(); return value.compareTo(otherValue) * -1; } Is this really needed? Maybe this should be removed for efficiency reasons (but I don't know how often this method is actually used...)

Target:
public int compareTo(InformationLoss<?> other) { BigFraction otherValue = ((ILScore)other).getValue(); return value.compareTo(otherValue) * -1; }
Source:
protected ILScore convert(InformationLoss<?> other) { if (other == null) return null; START if (!other.getClass().equals(this.getClass())) { END throw new IllegalArgumentException("Incompatible class (" + other.getClass().getSimpleName() + ")"); } else { return (ILScore)other; } } Is this really needed? Maybe this should be removed for efficiency reasons (but I don't know how often this method is actually used...)

Target:
protected ILScore convert(InformationLoss<?> other) { if (other == null) return null; return (ILScore)other; }
Source:
public ElementData render() { ElementData result = new ElementData("Differential privacy"); result.addProperty("Epsilon", epsilon); result.addProperty("Delta", delta); START result.addProperty("Uniqueness threshold (k)", getK()); END result.addProperty("Sampling probability (beta)", getBeta()); return result; } Catch exception

Target:
public ElementData render() { ElementData result = new ElementData("Differential privacy"); result.addProperty("Epsilon", epsilon); result.addProperty("Delta", delta); try { result.addProperty("Uniqueness threshold (k)", getK()); result.addProperty("Sampling probability (beta)", getBeta()); } catch (Exception e) { // No harm is done if these properties can not be set } return result; }
Source:
public DataDependentEDDifferentialPrivacy(double epsilonAnon, double epsilonSearch, double delta, int steps) { START super(delta); END this.epsilonAnon = epsilonAnon; this.epsilonSearch = epsilonSearch; this.beta = calculateBeta(epsilonAnon); this.k = calculateK(getDelta(), epsilonAnon, this.beta); this.steps = steps; } this(epsilonAnon, epsilonSearch, delta, steps, false); ???

Target:
public DataDependentEDDifferentialPrivacy(double epsilonAnon, double epsilonSearch, double delta, int steps) { this(epsilonAnon, epsilonSearch, delta, steps, false); }
Source:
public Image getImage(AttributeType type) { if (type == AttributeType.IDENTIFYING_ATTRIBUTE) { return getManagedImage("bullet_red.png"); } START if (type == AttributeType.INSENSITIVE_ATTRIBUTE) { return getManagedImage("bullet_green.png"); } END if (type == AttributeType.SENSITIVE_ATTRIBUTE) { return getManagedImage("bullet_purple.png"); } if (type == AttributeType.QUASI_IDENTIFYING_ATTRIBUTE) { return getManagedImage("bullet_yellow.png"); } throw new IllegalArgumentException("Unknown attribute type '" + type +"'"); } Please use a switch statement here

Target:
public Image getImage(AttributeType type) { if (type == AttributeType.IDENTIFYING_ATTRIBUTE) { return getManagedImage("bullet_red.png"); } else if (type == AttributeType.INSENSITIVE_ATTRIBUTE) { return getManagedImage("bullet_green.png"); } else if (type == AttributeType.SENSITIVE_ATTRIBUTE) { return getManagedImage("bullet_purple.png"); } else if (type == AttributeType.QUASI_IDENTIFYING_ATTRIBUTE) { return getManagedImage("bullet_yellow.png"); } else { throw new IllegalArgumentException("Unknown attribute type '" + type + "'"); } }
Source:
public int hashCode() { START return Objects.hashCode( referenceExpression ); END } Revert this. `referenceExpression` is non-null AFAICS

Target:
public int hashCode() { return referenceExpression.hashCode(); }
Source:
public MappingModelExpressable getExpressionType() { SqlSelection first = selectClause.getSqlSelections().get(0); START return ( (SqlSelectionImpl) first ).getWrappedSqlExpression().getExpressionType(); END } Probably the second makes more sense

Target:
public MappingModelExpressable getExpressionType() { SqlSelection first = selectClause.getSqlSelections().get(0); return first.getExpressionType(); }
Source:
private static void assertRootCause(Exception exception, Class<?> type, String message) { Throwable root = exception; while ( root.getCause() != null ) { root = root.getCause(); } assertTyping( type, root ); START assertEquals( root.getMessage(), message ); END } should we swap method parametrr orders above?

Target:
private static void assertRootCause(Exception exception, Class<?> type, String message) { Throwable root = exception; while ( root.getCause() != null ) { root = root.getCause(); } assertTyping( type, root ); assertEquals( message, root.getMessage() ); }
Source:
public static <T> T coalesce(T... values) { if ( values == null ) { return null; } for ( T value : values ) { if ( value != null ) { if ( String.class.isInstance( value ) ) { START if ( StringHelper.isNotEmpty( (String) value ) ) { END return value; } } else { return value; } } } return null; } Minor nitpicking, as I've recently being removing the use of "unnecessary helpers": when you know already that "value" is not null, there is no reason to use the `StringHelper`. Just go with `((String) value).isEmpty()` ?

Target:
public static <T> T coalesce(T... values) { if ( values == null ) { return null; } for ( T value : values ) { if ( value != null ) { if ( String.class.isInstance( value ) ) { if ( !( (String) value ).isEmpty() ) { return value; } } else { return value; } } } return null; }
Source:
private String[] getSubclassNameClosureBySubclassTable(int subclassTableNumber) { final int index = subclassTableNumber - getTableSpan(); if ( index >= subclassNamesBySubclassTable.length ) { throw new IllegalArgumentException( "Given subclass table number is outside expected range [" + subclassNamesBySubclassTable.length START + "] as defined by subclassTableNameClosure/subclassClosure" END ); } return subclassNamesBySubclassTable[index]; } The upper limit should be corrected in the error message to be ```subclassNamesBySubclassTable - 1```.

Target:
private String[] getSubclassNameClosureBySubclassTable(int subclassTableNumber) { final int index = subclassTableNumber - getTableSpan(); if ( index >= subclassNamesBySubclassTable.length ) { throw new IllegalArgumentException( "Given subclass table number is outside expected range [" + (subclassNamesBySubclassTable.length -1) + "] as defined by subclassTableNameClosure/subclassClosure" ); } return subclassNamesBySubclassTable[index]; }
Source:
protected String[] getPropertyAliases(Loadable persister, int j) { String[] propertyColumnNames = persister.getPropertyColumnNames(j); START if (propertyColumnNames!=null && propertyColumnNames.length==1 && propertyColumnNames[0]==null) { END return new String[]{ persister.getPropertyNames()[j] }; } return propertyColumnNames; } It would be great to use space chars consistently with existing coding format as ` if ( propertyColumnNames != null && propertyColumnNames.length == 1 && propertyColumnNames[0] == null ) `

Target:
protected String[] getPropertyAliases(Loadable persister, int j) { String[] propertyColumnNames = persister.getPropertyColumnNames(j); if ( Arrays.equals( propertyColumnNames, new String[] { null } ) ) { return new String[]{ persister.getPropertyNames()[j] }; } return propertyColumnNames; }
Source:
public ParametersBuilder addPersistedWithoutHibernate(int yearWhenPersistedWithoutHibernate, int monthWhenPersistedWithoutHibernate, int dayWhenPersistedWithoutHibernate, int hour, int minute, int second, int nanosecond, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { START nanosecond = 0; END } return add( defaultTimeZone, hour, minute, second, nanosecond, yearWhenPersistedWithoutHibernate, monthWhenPersistedWithoutHibernate, dayWhenPersistedWithoutHibernate ); } Should ```if``` condition be: ```if ( !isNanosecondPrecisionSupported() )``` ?

Target:
public ParametersBuilder addPersistedWithoutHibernate(int yearWhenPersistedWithoutHibernate, int monthWhenPersistedWithoutHibernate, int dayWhenPersistedWithoutHibernate, int hour, int minute, int second, int nanosecond, ZoneId defaultTimeZone) { if ( !isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, hour, minute, second, nanosecond, yearWhenPersistedWithoutHibernate, monthWhenPersistedWithoutHibernate, dayWhenPersistedWithoutHibernate ); }
Source:
public ParametersBuilder add(int year, int month, int day, int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { START nanosecond = 0; END } return add( defaultTimeZone, year, month, day, hour, minute, second, nanosecond, offset ); } Should ```if``` condition be: ```if ( !isNanosecondPrecisionSupported() )``` ?

Target:
public ParametersBuilder add(int year, int month, int day, int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( !isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, year, month, day, hour, minute, second, nanosecond, offset ); }
Source:
public ParametersBuilder addPersistedWithoutHibernate(int yearWhenPersistedWithoutHibernate, int monthWhenPersistedWithoutHibernate, int dayWhenPersistedWithoutHibernate, int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { START nanosecond = 0; END } return add( defaultTimeZone, hour, minute, second, nanosecond, offset, yearWhenPersistedWithoutHibernate, monthWhenPersistedWithoutHibernate, dayWhenPersistedWithoutHibernate ); } Should ```if``` condition be: ```if ( !isNanosecondPrecisionSupported() )``` ?

Target:
public ParametersBuilder addPersistedWithoutHibernate(int yearWhenPersistedWithoutHibernate, int monthWhenPersistedWithoutHibernate, int dayWhenPersistedWithoutHibernate, int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( !isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, hour, minute, second, nanosecond, offset, yearWhenPersistedWithoutHibernate, monthWhenPersistedWithoutHibernate, dayWhenPersistedWithoutHibernate ); }
Source:
public ParametersBuilder add(int year, int month, int day, int hour, int minute, int second, int nanosecond, String zone, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { START nanosecond = 0; END } return add( defaultTimeZone, year, month, day, hour, minute, second, nanosecond, zone ); } Should ```if``` condition be: ```if ( !isNanosecondPrecisionSupported() )``` ?

Target:
public ParametersBuilder add(int year, int month, int day, int hour, int minute, int second, int nanosecond, String zone, ZoneId defaultTimeZone) { if ( !isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, year, month, day, hour, minute, second, nanosecond, zone ); }
Source:
void compiled(long microseconds) { START log.tracef( "QueryStatistics - query compiled : %s", query ); END planCacheMissCount.increment(); planCompilationTotalMicroseconds.addAndGet( microseconds ); } We are in the process of removing the other logger calls so let's not add more.

Target:
void compiled(long microseconds) { planCacheMissCount.increment(); planCompilationTotalMicroseconds.addAndGet( microseconds ); }
Source:
void incrementPlanCacheHitCount() { START log.tracef( "QueryStatistics - plan cache hit : %s", query ); END planCacheHitCount.increment(); } We are in the process of removing the other logger calls so let's not add more.

Target:
void incrementPlanCacheHitCount() { planCacheHitCount.increment(); }
Source:
public void setUp() throws Exception { doInHibernate( this::sessionFactory, s -> { Post post = new Post(); post.setDetails(new PostDetails()); post.getDetails().setCreatedBy("ME"); post.getDetails().setCreatedOn(new Date()); post.setTitle("title"); s.persist(post); s.flush(); START s.clear(); END } ); } I don't think you need to flush() and clear(). Considering this init is specific to the test method, I would have moved it to the test method and would remove this setUp() altogether.

Target:
public void setUp() throws Exception { doInHibernate( this::sessionFactory, s -> { Post post = new Post(); post.setDetails( new PostDetails() ); post.getDetails().setCreatedBy( "ME" ); post.getDetails().setCreatedOn( new Date() ); post.setTitle( "title" ); s.persist( post ); } ); }
Source:
START public String getTableName() { END Queryable queryable = getQueryable(); return ( queryable != null ) ? queryable.getTableName() : "{none}"; } I don't think this is needed?

Target:
private String getTableName() { Queryable queryable = getQueryable(); return ( queryable != null ) ? queryable.getTableName() : "{none}"; }
Source:
public final Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner, Map copyCache) { if ( original == null && target == null ) { return null; } if ( original == LazyPropertyInitializer.UNFETCHED_PROPERTY ) { return target; } if ( target == LazyPropertyInitializer.UNFETCHED_PROPERTY ) { return getReplacement( (T) original, null, session ); START } END return getReplacement( (T) original, (T) target, session ); } You might want to have a look at the other `replace()` method below, which also calls `getReplacement`, but without executing this code. Probably a bug? It might be a dumb suggestion, but couldn't we just move all this code to the caller(s) of `replace()`? Then any type would benefit from this code, not just types extending `AbstractStandardBasicType`. From what I can see it's rather simple, and it would remove the need for type implementations to refer to `LazyPropertyInitializer`, which is an SPI type...

Target:
public final Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner, Map copyCache) { if ( original == null && target == null ) { return null; } return getReplacement( (T) original, (T) target, session ); }
Source:
public void release(Statement statement) { log.tracev( "Releasing statement [{0}]", statement ); START final Set<ResultSet> resultSets = xref.get( statement ); END if ( resultSets != null ) { closeAll( resultSets ); xref.remove( statement ); } else if ( log.isDebugEnabled() ) { // Keep this at DEBUG level, rather than warn. Numerous connection pool implementations can return a // proxy/wrapper around the JDBC Statement, causing excessive logging here. See HHH-8210. log.unregisteredStatement(); } close( statement ); if ( lastQuery == statement ) { lastQuery = null; } } Why not just `final Set<ResultSet> resultSets = xref.remove( statement );` here, and no `remove()` call below? Then you would only need to access the map once. That might change the behavior slightly if `closeAll` throws an exception or somehow uses xref, though. Maybe it's not such a good idea.

Target:
public void release(Statement statement) { log.tracev( "Releasing statement [{0}]", statement ); // Keep this at DEBUG level, rather than warn. Numerous connection pool implementations can return a // proxy/wrapper around the JDBC Statement, causing excessive logging here. See HHH-8210. if ( log.isDebugEnabled() && !xref.containsKey( statement ) ) { log.unregisteredStatement(); } else { final Set<ResultSet> resultSets = xref.get( statement ); if ( resultSets != null ) { closeAll( resultSets ); } xref.remove( statement ); } close( statement ); if ( lastQuery == statement ) { lastQuery = null; } }
Source:
protected void createLoaders() { final Map loaders = getLoaders(); loaders.put( LockMode.NONE, createEntityLoader( LockMode.NONE ) ); START END noneLockLoader = createEntityLoader( LockMode.NONE ); readLockLoader = createEntityLoader( LockMode.READ ); // The loaders for the other lock modes are loaded lazily. loaders.put( "merge", new CascadeEntityLoader( this, CascadingActions.MERGE, getFactory() ) ); loaders.put( "refresh", new CascadeEntityLoader( this, CascadingActions.REFRESH, getFactory() ) ); } This is the second instance of an entity loader for LockMode.NONE. Please move this line and maybe the next line before the line 4118 and reuse the instance.

Target:
protected void createLoaders() { // We load the entity loaders for the most common lock modes. noneLockLoader = createEntityLoader( LockMode.NONE ); readLockLoader = createEntityLoader( LockMode.READ ); final Map loaders = getLoaders(); // The loaders for the other lock modes are lazily loaded and will later be stored in this map. loaders.put( "merge", new CascadeEntityLoader( this, CascadingActions.MERGE, getFactory() ) ); loaders.put( "refresh", new CascadeEntityLoader( this, CascadingActions.REFRESH, getFactory() ) ); }
Source:
private UniqueEntityLoader getLoaderByLockMode(LockMode lockMode) { START if ( LockMode.NONE.equals( lockMode ) ) { END return noneLockLoader; } else if ( LockMode.READ.equals( lockMode ) ) { return readLockLoader; } return loaders.computeIfAbsent( lockMode, this::createLazyLoadedEntityLoader ); } It is common practice in Hibernate to use '==' to compare enum values for equality. You shall follow this practice here too.

Target:
private UniqueEntityLoader getLoaderByLockMode(LockMode lockMode) { if ( LockMode.NONE == lockMode ) { return noneLockLoader; } else if ( LockMode.READ == lockMode ) { return readLockLoader; } return loaders.computeIfAbsent( lockMode, this::createLazyLoadedEntityLoader ); }
Source:
public static String toArrayTypeString(ArrayType type, Context context) { TypeMirror componentMirror = type.getComponentType(); if ( !componentMirror.getAnnotationMirrors().isEmpty() ) { TypeMirror component = type.getComponentType().accept( new SimpleTypeVisitor6<TypeMirror, Void>() { @Override protected TypeMirror defaultAction(TypeMirror e, Void aVoid) { return e; } }, null ); return extractClosestRealTypeAsString( component, context ) + "[]"; } START return toTypeString( type ); END } So in this case, you're not returning an array type?

Target:
public static String toArrayTypeString(ArrayType type, Context context) { // When an ArrayType is annotated with an annotation which uses TYPE_USE targets, // we cannot simply take the TypeMirror returned by #getComponentType because it // itself is an AnnotatedType. // // The simplest approach here to get the TypeMirror for both ArrayType use cases // is to use the visitor to retrieve the underlying TypeMirror. TypeMirror component = type.getComponentType().accept( new SimpleTypeVisitor6<TypeMirror, Void>() { @Override protected TypeMirror defaultAction(TypeMirror e, Void aVoid) { return e; } }, null ); return extractClosestRealTypeAsString( component, context ) + "[]"; }
Source:
public void begin() { if ( !session.isOpen() ) { throw new IllegalStateException( "Cannot begin Transaction on closed Session/EntityManager" ); } if ( transactionDriverControl == null ) { transactionDriverControl = transactionCoordinator.getTransactionDriverControl(); } // per-JPA if ( isActive() ) { throw new IllegalStateException( "Transaction already active" ); } START if ( LOG.isDebugEnabled() ) { END LOG.debug( "begin" ); } this.transactionDriverControl.begin(); } Why are we changing these? Generally this is done to avoid expensive resolution of the message to log. Here, that is not the case. In fact, doesn't this perform worse? IIUC this simply forces 2 "is debug enabled" checks

Target:
public void begin() { if ( !session.isOpen() ) { throw new IllegalStateException( "Cannot begin Transaction on closed Session/EntityManager" ); } if ( transactionDriverControl == null ) { transactionDriverControl = transactionCoordinator.getTransactionDriverControl(); } // per-JPA if ( isActive() ) { throw new IllegalStateException( "Transaction already active" ); } LOG.debug( "begin" ); this.transactionDriverControl.begin(); }
Source:
START public String getMessage() { END return message; } Can you make all of the accessors `final`?

Target:
public final String getMessage() { return message; }
Source:
START public final String getUsername() { END return username; } Oops, I meant only the accessors in the abstract chat message class to indicate that they should not be overridden. Could you undo all of these except for the ones in the abstract class?

Target:
public String getUsername() { return username; }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RequestParam that = (RequestParam) o; return name.equals(that.name); START } END this may be confusing to people. why are params with the same name considered "equal"? what about the value? if some part of the code wants to treat these Params as "equal" as long as they have equal names, it is better to keep this comparison logic close to that area, maybe with a local Comparator class or something, but not inside the data object itself. this would allow reusability for this class in the future.

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RequestParam that = (RequestParam) o; return name.equals(that.name) && value.equals(that.value); }
Source:
public boolean hasSomeResults() { START return !results.isEmpty(); END } I assume the list is never null. right?

Target:
public boolean hasSomeResults() { return results != null && !results.isEmpty(); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CustomFieldDefinition that = (CustomFieldDefinition) o; START if (id != that.id) { END return false; } return true; } This is an identity comparison. Equal (in sense of .equals()) Integers may be different according to == (and !=). Please, use .equals and provide proper null-handling code.

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomFieldDefinition that = (CustomFieldDefinition) o; if (id != null ? !id.equals(that.id) : that.id != null) return false; return true; }
Source:
public CustomField getCustomFieldById(int customFieldId) { START if(customFields == null) return null; END for (CustomField customField : customFields) { if (customFieldId == customField.getId()) { return customField; } } return null; } no need in null check here, although it's a matter of personal preference

Target:
public CustomField getCustomFieldById(int customFieldId) { for (CustomField customField : customFields) { if (customFieldId == customField.getId()) { return customField; } } return null; }
Source:
public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length > 1) { START User target = getPlayer(server, args, 0, true); END sender.sendMessage("§7SocialSpy " + (target.toggleSocialSpy() ? _("enabled") : _("disabled"))); } else { throw new NotEnoughArgumentsException(); } } This is wrong.

Target:
public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length > 1) { User target = getPlayer(server, args, 0, true, false); sender.sendMessage("§7SocialSpy " + (target.toggleSocialSpy() ? _("enabled") : _("disabled"))); } else { throw new NotEnoughArgumentsException(); } }
Source:
private static int calculateBinaryShiftCost(State state) { START if (state.binaryShiftByteCount > 62) { END return 21; // B/S with extended length } else if (state.binaryShiftByteCount > 31) { return 20; // two B/S } else if (state.binaryShiftByteCount > 0) { return 10; // one B/S } else { return 0; } } Nit: use 2-space indent here. Also I think you can dispense with the "else" statements and just write: ``` if (...) { return ...; } if (...) { return ...; } ```

Target:
private static int calculateBinaryShiftCost(State state) { if (state.binaryShiftByteCount > 62) { return 21; // B/S with extended length } if (state.binaryShiftByteCount > 31) { return 20; // two B/S } if (state.binaryShiftByteCount > 0) { return 10; // one B/S } return 0; }
Source:
START public void testEncodeIllegalCharacters() throws WriterException { END int illegalArgument = 0; try { BitMatrix result = new EAN8Writer().encode("96385abc", BarcodeFormat.EAN_8, 0, 0); } catch (IllegalArgumentException e) { illegalArgument = 1; } assertEquals(illegalArgument, 1); } You should be able to write `@Test(expected = WriterException.class)` and then the body of the test is just the line that causes the exception.

Target:
public void testEncodeIllegalCharacters() throws WriterException { new EAN8Writer().encode("96385abc", BarcodeFormat.EAN_8, 0, 0); }
Source:
protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) { int numAdded = 9; for (int bit : pattern) { START target[pos++] = bit == 0 ? false : true; END } return numAdded; } just `= bit != 0`?

Target:
protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) { for (int bit : pattern) { target[pos++] = bit != 0; } return 9; }
Source:
private static int computeChecksumIndex(String contents, int maxWeight) { int weight = 1; int total = 0; for (int i = contents.length()-1; i >= 0; i--) { int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); total += indexInString * weight; if (++weight > maxWeight) { weight = 1; } } START int checksum = total % 47; END return checksum; } Last trivial thing, just return this value directly.

Target:
private static int computeChecksumIndex(String contents, int maxWeight) { int weight = 1; int total = 0; for (int i = contents.length() - 1; i >= 0; i--) { int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); total += indexInString * weight; if (++weight > maxWeight) { weight = 1; } } return total % 47; }
Source:
protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) { START int numAdded = 9; END for (int bit : pattern) { target[pos++] = bit != 0; } return numAdded; } This value isn't changed; is it always 9? return 9 directly then.

Target:
protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) { for (int bit : pattern) { target[pos++] = bit != 0; } return 9; }
Source:
public void unset(int x, int y) { int offset = y * rowSize + (x / 32); START int intMask = (1 << (x & 0x1f)); END if ((bits[offset] & intMask) > 0) { bits[offset] ^= intMask; } } I think this method can work just like `set()`. You complement the `intMask` with `~` and then `&=` it.

Target:
public void unset(int x, int y) { int offset = y * rowSize + (x / 32); bits[offset] &= ~(1 << (x & 0x1f)); }
Source:
protected void setLoadedHostsEntries(Collection<HostEntryPair> keys) { START keysSupplier = () -> keys; END } Update of keysSupplier field is not mutually exclusive...

Target:
protected void setLoadedHostsEntries(Collection<HostEntryPair> keys) { keysSupplier.set(() -> keys); }
Source:
START public AbstractSecurityKeySignature(String keyType) { END this.keyType = keyType; } Please make this `protected`

Target:
protected AbstractSecurityKeySignature(String keyType) { this.keyType = keyType; }
Source:
default T verify(Duration timeout) throws IOException { START return verify(timeout.toMillis()); END } In other locations the code interprets `null` as *forever* - let's maintain this convention (or fix the other code - `ClientChannel#waitFor`) ```java default T verify(Duration timeout) throws IOException { return (duration == null) ? verify() : verify(timeout.toMillis()); } ```

Target:
default T verify(Duration timeout) throws IOException { return timeout != null ? verify(timeout.toMillis()) : verify(); }
Source:
default boolean await(Duration timeout) throws IOException { START return await(timeout.toMillis()); END } In other locations the code interprets `null` as *forever* - let's maintain this convention (or fix the other code - `ClientChannel#waitFor`)

Target:
default boolean await(Duration timeout) throws IOException { return timeout != null ? await(timeout.toMillis()) : await(); }
Source:
START private void signalRemoving(Path p, SftpEventListener listener, ServerSession session, END boolean isDirectory) throws IOException { if (isDirectory) { listener.removingDirectory(session, p); } else { listener.removingFile(session, p); } } protected please - we always try to allow users to override any behavior they like

Target:
protected void signalRemoving( Path p, SftpEventListener listener, ServerSession session, boolean isDirectory) throws IOException { if (isDirectory) { listener.removingDirectory(session, p); } else { listener.removingFile(session, p); } }
Source:
START private void signalRemoved(Path p, SftpEventListener listener, ServerSession session, END boolean isDirectory, Exception e) throws IOException { if (isDirectory) { listener.removedDirectory(session, p, e); } else { listener.removedFile(session, p, e); } } protected please - we always try to allow users to override any behavior they like

Target:
protected void signalRemoved( Path p, SftpEventListener listener, ServerSession session, boolean isDirectory, Exception e) throws IOException { if (isDirectory) { listener.removedDirectory(session, p, e); } else { listener.removedFile(session, p, e); } }
Source:
private synchronized void asyncAuth(int cmd, Buffer buffer, boolean authed) { START try { END if (authed) { handleAuthenticationSuccess(cmd, buffer); } else { handleAuthenticationFailure(cmd, buffer); } } catch (Exception e) { log.warn("Error performing async authentication: {}", e.getMessage(), e); } } Let's make it _protected_ to allow users to override if they want

Target:
protected synchronized void asyncAuth(int cmd, Buffer buffer, boolean authed) { try { if (authed) { handleAuthenticationSuccess(cmd, buffer); } else { handleAuthenticationFailure(cmd, buffer); } } catch (Exception e) { log.warn("Error performing async authentication: {}", e.getMessage(), e); } }
Source:
public static String getFileOwner(Path path, LinkOption... options) throws IOException { String owner = null; try { UserPrincipal principal = Files.getOwner(path, options); if (principal != null) { owner = principal.getName(); } } catch (UnsupportedOperationException e) { // ignore } return owner; START } END Simpler code: ``` java try { UserPrincipal principal = Files.getOwner(path, options} return (principal != null) ? principal.getName() : null; } catch (UnsupportedOperationException e) { return null; // ignore } ```

Target:
public static String getFileOwner(Path path, LinkOption... options) throws IOException { try { UserPrincipal principal = Files.getOwner(path, options); return (principal == null) ? null : principal.getName(); } catch (UnsupportedOperationException e) { return null; } }
Source:
public Histogram getTemperatures() { Metadata metadata = new Metadata("temperatures", MetricType.HISTOGRAM, "degrees F"); metadata.setDescription("A histogram of recent New York temperatures."); START final int[] RECENT_NEW_YORK_TEMPS = { 46, 45, 50, 46, 45, 27, 30, 48, 55, 54, 45, 41, 45, 43, 46 }; END histogram = registry.histogram(metadata); for(int temp : RECENT_NEW_YORK_TEMPS) { histogram.update(temp); } return histogram; } RECENT_NEW_YORK_TEMPS seems to be a convention of a constant variable. I suggest you move it out of the method and add private along with static to match the java convention.

Target:
public Histogram getTemperatures() { Metadata metadata = new Metadata("temperatures", MetricType.HISTOGRAM, "degrees F"); metadata.setDescription("A histogram of recent New York temperatures."); histogram = registry.histogram(metadata); for(int temp : RECENT_NEW_YORK_TEMPS) { histogram.update(temp); } return histogram; }
Source:
public JsonWebToken currentPrincipal() { Objects.requireNonNull(httpServletRequest, "HTTP Servlet Request is required to produce a JSonWebToken principal."); // not very beatiful, but avoids having the MPJWTFilter setting the request or the principal in a thread local // CDI integration already has one - dunno which approach is the best for now final Object tokenAttribute = httpServletRequest.getAttribute(JsonWebToken.class.getName()); START if (tokenAttribute != null && Function.class.isInstance(tokenAttribute)) { END return (JsonWebToken) Function.class.cast(tokenAttribute).apply(httpServletRequest); } return null; } not null check not needed before class.isInstance() call. Method returns false when passing a null argument

Target:
public JsonWebToken currentPrincipal() { Objects.requireNonNull(httpServletRequest, "HTTP Servlet Request is required to produce a JSonWebToken principal."); // not very beautiful, but avoids having the MPJWTFilter setting the request or the principal in a thread local // CDI integration already has one - dunno which approach is the best for now final Object tokenAttribute = httpServletRequest.getAttribute(JsonWebToken.class.getName()); if (Function.class.isInstance(tokenAttribute)) { return (JsonWebToken) Function.class.cast(tokenAttribute).apply(httpServletRequest); } return null; }
Source:
START final public boolean equals(Object obj) { END if (obj == this) { return true; } else if (obj instanceof ModuleAdapter<?>) { ModuleAdapter<?> that = (ModuleAdapter<?>) obj; return this.moduleClass.equals(that.moduleClass); } else { return false; } } JLS order is `public final boolean` and for consistency with other methods

Target:
public final boolean equals(Object obj) { if (obj == this) { return true; } else if (obj instanceof ModuleAdapter<?>) { ModuleAdapter<?> that = (ModuleAdapter<?>) obj; return this.moduleClass.equals(that.moduleClass); } else { return false; } }