auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { START String authorizationValue = this.credential.generateAuthorizationHeader(context.getHttpRequest().getUrl(), END context.getHttpRequest().getHeaders().toMap()); context.getHttpRequest().setHeader("Authorization", authorizationValue); return next.process(); } Remove `this.`

Target:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { String authorizationValue = credential.generateAuthorizationHeader(context.getHttpRequest().getUrl(), context.getHttpRequest().getHeaders().toMap()); context.getHttpRequest().setHeader("Authorization", authorizationValue); return next.process(); }
Source:
void createTableDuplicateName() { // Arrange String tableName = testResourceNamer.randomName("test", 20); TableProperties tableProperties = new TableProperties().setTableName(tableName); createTable(tableName); String requestId = testResourceNamer.randomUuid(); // Act & Assert StepVerifier.create(azureTable.getTables().createWithResponseAsync(tableProperties, requestId, ResponseFormat.RETURN_CONTENT, null, Context.NONE)) START .expectError(com.azure.data.tables.implementation.models.TableServiceErrorException.class) END .verify(); } If you import this, it won't need to be fully qualified.

Target:
void createTableDuplicateName() { // Arrange String tableName = testResourceNamer.randomName("test", 20); TableProperties tableProperties = new TableProperties().setTableName(tableName); createTable(tableName); String requestId = testResourceNamer.randomUuid(); // Act & Assert StepVerifier.create(azureTable.getTables().createWithResponseAsync(tableProperties, requestId, ResponseFormat.RETURN_CONTENT, null, Context.NONE)) .expectError(TableServiceErrorException.class) .verify(); }
Source:
public BoundingBox(final List<Point> points) { if (points == null) { this.points = null; } else { START this.points = Collections.unmodifiableList(new ArrayList<>(points)); END } } Don't need to create a new ArrayList here.

Target:
public BoundingBox(final List<Point> points) { if (points == null) { this.points = null; } else { this.points = Collections.unmodifiableList(points); } }
Source:
public CustomFormSubmodel(final Float accuracy, final Map<String, CustomFormModelField> fields, final String formType) { this.accuracy = accuracy; START this.fields = fields == null ? null : Collections.unmodifiableMap(new HashMap<>(fields)); END this.formType = formType; } ```suggestion this.fields = fields == null ? null : Collections.unmodifiableMap(fields); ```

Target:
public CustomFormSubmodel(final Float accuracy, final Map<String, CustomFormModelField> fields, final String formType) { this.accuracy = accuracy; this.fields = fields == null ? null : Collections.unmodifiableMap(fields); this.formType = formType; }
Source:
public List<TokenCredential> getCredentials() { START return tokenCredentials; END } This should return an unmodifiable list. Create the unmodifiable list in the ctor itself.

Target:
public List<TokenCredential> getCredentials() { return super.getCredentials(); }
Source:
public Response<AppendBlobItem> createWithResponse(AppendBlobCreateOptions options, Duration timeout, Context context) { return StorageImplUtils.blockWithOptionalTimeout(appendBlobAsyncClient. START createWithResponse(options, context), options == null ? null : timeout); END } This should just be timeout

Target:
public Response<AppendBlobItem> createWithResponse(AppendBlobCreateOptions options, Duration timeout, Context context) { return StorageImplUtils.blockWithOptionalTimeout(appendBlobAsyncClient. createWithResponse(options, context), timeout); }
Source:
private Mono<AmqpSendLink> getSendLink() { return connectionProcessor .flatMap(connection -> { START String linkName = entityName; END if (!CoreUtils.isNullOrEmpty(viaEntityName)) { linkName = "VIA-".concat(viaEntityName); return connection.createSendLink(linkName, viaEntityName, retryOptions, entityName); } else { return connection.createSendLink(linkName, entityName, retryOptions, null); } }) .doOnNext(next -> linkName.compareAndSet(null, next.getLinkName())); } This link name doesn't have to be declared. You only use the corresponding value within the if statement for each of them.

Target:
private Mono<AmqpSendLink> getSendLink() { return connectionProcessor .flatMap(connection -> { if (!CoreUtils.isNullOrEmpty(viaEntityName)) { return connection.createSendLink("VIA-".concat(viaEntityName), viaEntityName, retryOptions, entityName); } else { return connection.createSendLink(entityName, entityName, retryOptions, null); } }) .doOnNext(next -> linkName.compareAndSet(null, next.getLinkName())); }
Source:
START public float getX() { END return this.xCoordinate; } Wonder if we should use `float` or `double` for these properties. I'd lean towards double as this is meant to be a generic class and double can store float but not vice-versa.

Target:
public double getX() { return this.xCoordinate; }
Source:
public void createTable() { TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder() .connectionString("connectionString") .buildAsyncClient(); tableServiceAsyncClient.createTable("OfficeSupplies").subscribe( Void -> {}, START error -> logger.error("There was an error creating the table. Error: " + error), END () -> logger.info("Table creation successful.")); } System.err.println` over ClientLogger

Target:
public void createTable() { TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder() .connectionString("connectionString") .buildAsyncClient(); tableServiceAsyncClient.createTable("OfficeSupplies").subscribe( Void -> { }, error -> System.err.println("There was an error creating the table. Error: " + error), () -> System.out.println("Table creation successful.")); }
Source:
public void queryTable() { TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder() .connectionString("connectionString") .buildAsyncClient(); START QueryOptions queryOptions = new QueryOptions(); END queryOptions.setFilter("TableName eq OfficeSupplies"); tableServiceAsyncClient.queryTables(queryOptions).subscribe(azureTable -> { logger.info(azureTable.getName()); }, error -> { logger.error("There was an error querying the service. Error: " + error); }); } Highlight usage of the fluent model. var queryOptions = new QueryOptions().setFilter("TableName eq OfficeSupplies");

Target:
public void queryTable() { TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder() .connectionString("connectionString") .buildAsyncClient(); QueryOptions queryOptions = new QueryOptions().setFilter("TableName eq OfficeSupplies"); tableServiceAsyncClient.queryTables(queryOptions).subscribe(azureTable -> { System.out.println(azureTable.getName()); }, error -> { System.err.println("There was an error querying the service. Error: " + error); }); }
Source:
public boolean isWriting() { START return writing == true || (!reading && isSimpleTargetType()); END } Can simplify to... `return writing || (!reading && isSimpleTargetType());`

Target:
public boolean isWriting() { return writing || (!reading && isSimpleTargetType()); }
Source:
public CassandraTemplate(Session session, CassandraConverter converter) { setSession(session); START setConverter(converter == null ? getDefaultCassandraConverter() : converter); END } Not a big deal, but I generally always take a positive perspective first (i.e. innocent until proven guilty ;-), such as... `setConverter(converter != null ? converter : getDefaultCassandraConverter());`

Target:
public CassandraTemplate(Session session, CassandraConverter converter) { setSession(session); setConverter(converter != null ? converter : getDefaultCassandraConverter()); }
Source:
public static Book random() { START return new Book("title" + uuid(), "isbn" + uuid()); END } I included your fix in our test code cleanup, see #51.

Target:
public static Book random() { return new Book(uuid(), uuid()); }
Source:
public synchronized <T> T newMonitor( Class<T> monitorClass, String... tags ) { requireInterface( monitorClass ); ClassLoader classLoader = monitorClass.getClassLoader(); MonitorInvocationHandler monitorInvocationHandler = new MonitorInvocationHandler( tags ); return monitorClass.cast( Proxy.newProxyInstance( classLoader, new Class<?>[]{monitorClass}, monitorInvocationHandler ) ); START } END I don't see why the `newMonitor` methods need to be synchronised.

Target:
public <T> T newMonitor( Class<T> monitorClass, String... tags ) { requireInterface( monitorClass ); ClassLoader classLoader = monitorClass.getClassLoader(); MonitorInvocationHandler monitorInvocationHandler = new MonitorInvocationHandler( tags ); return monitorClass.cast( Proxy.newProxyInstance( classLoader, new Class<?>[]{monitorClass}, monitorInvocationHandler ) ); }
Source:
public void execute( Runnable runnable ) { if ( latch.compareAndSet( false, true ) ) { jobScheduler.schedule( group, () -> { START runnable.run(); END latch.set( false ); } ); } } The latch should probably be set in a finally

Target:
public void execute( Runnable runnable ) { if ( latch.compareAndSet( false, true ) ) { jobScheduler.schedule( group, () -> { try { runnable.run(); } finally { latch.set( false ); } } ); } }
Source:
public Stream<BuiltInProcedures.SchemaIndexInfo> createIndex( String indexSpecification, String providerName ) throws ProcedureException { START String statusMessage = "index created"; END return createIndex( indexSpecification, providerName, statusMessage, ( schemaWrite, descriptor, provider ) -> schemaWrite.indexCreate( descriptor, Optional.of( provider ), Optional.empty() ) ); } Inline this

Target:
public Stream<BuiltInProcedures.SchemaIndexInfo> createIndex( String indexSpecification, String providerName ) throws ProcedureException { return createIndex( indexSpecification, providerName, "index created", ( schemaWrite, descriptor, provider ) -> schemaWrite.indexCreate( descriptor, Optional.of( provider ), Optional.empty() ) ); }
Source:
private int getOrCreateLabelId( String labelName ) throws ProcedureException { try { return ktx.tokenWrite().labelGetOrCreateForName( labelName ); } catch ( TooManyLabelsException | IllegalTokenNameException e ) { START throw new ProcedureException( e.status(), e, "" ); END } } Please replace empty string with a proper error message

Target:
private int getOrCreateLabelId( String labelName ) throws ProcedureException { try { return ktx.tokenWrite().labelGetOrCreateForName( labelName ); } catch ( TooManyLabelsException | IllegalTokenNameException e ) { throw new ProcedureException( e.status(), e, e.getMessage() ); } }
Source:
private int[] getOrCreatePropertyIds( String[] propertyKeyNames ) throws ProcedureException { int[] propertyKeyIds = new int[propertyKeyNames.length]; for ( int i = 0; i < propertyKeyIds.length; i++ ) { try { propertyKeyIds[i] = ktx.tokenWrite().propertyKeyGetOrCreateForName( propertyKeyNames[i] ); } catch ( IllegalTokenNameException e ) { START throw new ProcedureException( e.status(), e, "" ); END } } return propertyKeyIds; } Please replace empty string with a proper error message

Target:
private int[] getOrCreatePropertyIds( String[] propertyKeyNames ) throws ProcedureException { int[] propertyKeyIds = new int[propertyKeyNames.length]; for ( int i = 0; i < propertyKeyIds.length; i++ ) { try { propertyKeyIds[i] = ktx.tokenWrite().propertyKeyGetOrCreateForName( propertyKeyNames[i] ); } catch ( IllegalTokenNameException e ) { throw new ProcedureException( e.status(), e, e.getMessage() ); } } return propertyKeyIds; }
Source:
boolean timeToResize() { START return numberOfEntries == resizeLimit; END } I have some spider-sense that tingles here. If a user of this table claims twice without checking timeToResize, it will never resize. Putting in a `>=` or some assert might provide better safety for future devs.

Target:
boolean timeToResize() { return numberOfEntries >= resizeLimit; }
Source:
IndexDescriptor( IndexDescriptor indexDescriptor ) { schema = indexDescriptor.schema; type = indexDescriptor.type; START userSuppliedName = indexDescriptor.userSuppliedName; END providerDescriptor = indexDescriptor.providerDescriptor; } This constructor should delegate to other constructor. It's a bit weird that the enums are in between the two constructors. I would prefer if they could live at the bottom of this class.

Target:
IndexDescriptor( IndexDescriptor indexDescriptor ) { this( indexDescriptor.schema, indexDescriptor.type, indexDescriptor.userSuppliedName, indexDescriptor.providerDescriptor ); }
Source:
public static void main( String[] args ) throws InterruptedException, IOException { FileSystemAbstraction fs = new DefaultFileSystemAbstraction(); START File indexFile = new File( "index" ); END Runtime.getRuntime().addShutdownHook( new Thread( () -> fs.deleteFile( indexFile ) ) ); new GBPTreePlayground( fs, indexFile ).run(); } I would like it if it would first look at `args` to see if its length > 0 and if so grab the first arg as the file (could be absolute). It was the first thing I ran into when trying this out. It could also perhaps print which file (absolute path) it's working on when starting up. And should it really delete the file in the end, always? What if want to try out what happens between restarts, with generations and all that?

Target:
public static void main( String[] args ) throws InterruptedException, IOException { File indexFile; if ( args.length > 0 ) { indexFile = new File( args[0] ); } else { indexFile = new File( "index" ); } FileSystemAbstraction fs = new DefaultFileSystemAbstraction(); new GBPTreePlayground( fs, indexFile ).run(); }
Source:
private void performRecoveredIndexDropActions() { indexesToDropAfterCompletedRecovery.values().forEach( index -> { try { index.drop(); } catch ( Exception e ) { // This is OK to get during recovery because the underlying index can be in any unknown state // while we're recovering. Let's just move on to closing it instead. try { index.close(); } catch ( IOException closeException ) { // This is OK for the same reason as above START e.addSuppressed( closeException ); END } } } ); indexesToDropAfterCompletedRecovery.clear(); } If we are swallowing exception here we don't need to `addSuppressed`.

Target:
private void performRecoveredIndexDropActions() { indexesToDropAfterCompletedRecovery.values().forEach( index -> { try { index.drop(); } catch ( Exception e ) { // This is OK to get during recovery because the underlying index can be in any unknown state // while we're recovering. Let's just move on to closing it instead. try { index.close(); } catch ( IOException closeException ) { // This is OK for the same reason as above } } } ); indexesToDropAfterCompletedRecovery.clear(); }
Source:
private static boolean isNumericOrGeometricPredicate( IndexQuery predicate ) { if ( predicate.type() == IndexQuery.IndexQueryType.exact ) { IndexQuery.ExactPredicate exactPredicate = (IndexQuery.ExactPredicate) predicate; return isNumberGeometryOrArray(exactPredicate.value()); } else return predicate.type() == IndexQuery.IndexQueryType.range && START (predicate.valueGroup() == ValueGroup.NUMBER || predicate.valueGroup() == ValueGroup.GEOMETRY); END } I think this is harder to read, because we previously searched for specific types and otherwise fell through to return `false` by default. Now, the fall through is folded into a more complicated expression.

Target:
private static boolean isNumericOrGeometricPredicate( IndexQuery predicate ) { if ( predicate.type() == IndexQuery.IndexQueryType.exact ) { IndexQuery.ExactPredicate exactPredicate = (IndexQuery.ExactPredicate) predicate; if ( isNumberGeometryOrArray( exactPredicate.value() ) ) { return true; } } else if ( predicate.type() == IndexQuery.IndexQueryType.range && ( predicate.valueGroup() == ValueGroup.NUMBER || predicate.valueGroup() == ValueGroup.GEOMETRY ) ) { return true; } return false; }
Source:
void shouldFailWithNonExistentProviderName( IndexCreator creator ) throws KernelException { // given SchemaWrite schemaWrite = schemaWriteInNewTransaction(); // when try { START schemaWrite.indexCreate( forLabel( 0, 0 ), "something-completely-different" ); END fail( "Should have failed" ); } catch ( IllegalArgumentException e ) { // then good } } I think you meant to use the `creator` here?

Target:
void shouldFailWithNonExistentProviderName( IndexCreator creator ) throws KernelException { // given SchemaWrite schemaWrite = schemaWriteInNewTransaction(); // when try { creator.create( schemaWrite, forLabel( 0, 0 ), "something-completely-different" ); fail( "Should have failed" ); } catch ( IllegalArgumentException e ) { // then good } }
Source:
public void handleStepDown( long term, String dbName ) { boolean wasLeaderForTerm = Objects.equals( myself, leaderInfo.memberId() ) && term == leaderInfo.term(); if ( wasLeaderForTerm ) { START log.info( String.format( "Step down event detected. This topology member, with MemberId %s, was leader in term %s, now moving " + END "to follower.", myself, leaderInfo.term() ) ); HazelcastClusterTopology.casLeaders( hazelcastInstance, leaderInfo.stepDown(), dbName, log); } } Don't need `String.format`

Target:
public void handleStepDown( long term, String dbName ) { boolean wasLeaderForTerm = Objects.equals( myself, leaderInfo.memberId() ) && term == leaderInfo.term(); if ( wasLeaderForTerm ) { log.info( "Step down event detected. This topology member, with MemberId %s, was leader in term %s, now moving " + "to follower.", myself, leaderInfo.term() ); HazelcastClusterTopology.casLeaders( hazelcastInstance, leaderInfo.stepDown(), dbName ); } }
Source:
public void tearDown() throws Throwable { START server.stop(); END server.shutdown(); } Check so that server != null when tearing down.

Target:
public void tearDown() throws Throwable { if ( server != null ) { server.stop(); server.shutdown(); } if ( channel != null ) { channel.close(); } }
Source:
public void setUp() throws Throwable { server = createServer(); server.init(); START assertFalse( canConnect( server.address(), clientGroup ) ); END } `canConnect( server.address(), clientGroup )` can be extracted to a no-params method

Target:
public void setUp() throws Throwable { server = createServer(); server.init(); assertFalse( canConnect() ); }
Source:
private void notifyLeaderChanges( Outcome outcome ) { LeaderInfo leaderInfo = new LeaderInfo( outcome.getLeader(), outcome.getTerm() ); boolean isStepDown = outcome.isSteppingDown(); if ( isStepDown ) { leaderInfo.stepDown(); } START END for ( LeaderListener listener : leaderListeners ) { if ( isStepDown ) { listener.onLeaderStepDown( leaderInfo ); } listener.onLeaderSwitch( leaderInfo ); } } I'm wondering if it would be better to have a default final method on LeadershipListener called something sensible like `foo` that checks isStepDown, if true calls onLeaderStepDown and then calls onLeaderSwitch.

Target:
private void notifyLeaderChanges( Outcome outcome ) { LeaderInfo leaderInfo = new LeaderInfo( outcome.getLeader(), outcome.getTerm(), outcome.isSteppingDown() ); for ( LeaderListener listener : leaderListeners ) { if ( outcome.isSteppingDown() ) { listener.onLeaderStepDown( leaderInfo ); } listener.onLeaderSwitch( leaderInfo ); } }
Source:
private TemporalValue attachTimeZone( TemporalValue temporal, ZoneId zoneIdToAttach ) { if ( temporal.isSupported( ChronoField.MONTH_OF_YEAR ) ) { // turn local date time into date time return datetime( ZonedDateTime.of( temporal.getDatePart(), temporal.getLocalTimePart(), zoneIdToAttach ) ); } else { // turn local time into time if ( zoneIdToAttach instanceof ZoneOffset ) { return time( OffsetTime.of( temporal.getLocalTimePart(), (ZoneOffset) zoneIdToAttach ) ); } else { START throw new UnsupportedTemporalUnitException( "Should only attach offsets to local times, not zone ids." ); END } } } Since we had an `IllegalStateException` before, is this code path a case we ever expect to happen? If not, an `IllegalStateException` is the right choice, since it signals that _we_ did wrong, not the user of the product.

Target:
private TemporalValue attachTimeZone( TemporalValue temporal, ZoneId zoneIdToAttach ) { if ( temporal.isSupported( ChronoField.MONTH_OF_YEAR ) ) { // turn local date time into date time return datetime( ZonedDateTime.of( temporal.getDatePart(), temporal.getLocalTimePart(), zoneIdToAttach ) ); } else { // turn local time into time if ( zoneIdToAttach instanceof ZoneOffset ) { return time( OffsetTime.of( temporal.getLocalTimePart(), (ZoneOffset) zoneIdToAttach ) ); } else { throw new IllegalStateException( "Should only attach offsets to local times, not zone ids." ); } } }
Source:
public static TimeValue parse( CharSequence text, Supplier<ZoneId> defaultZone, CSVHeaderInformation fieldsFromHeader ) { if ( fieldsFromHeader != null ) { if ( !(fieldsFromHeader instanceof TimeCSVHeaderInformation) ) { START throw new TemporalParseException( "Wrong header information type: " + fieldsFromHeader ); END } // Override defaultZone defaultZone = ((TimeCSVHeaderInformation) fieldsFromHeader).zoneSupplier( defaultZone ); } return parse( TimeValue.class, PATTERN, TimeValue::parse, text, defaultZone ); } Same concern as above.

Target:
public static TimeValue parse( CharSequence text, Supplier<ZoneId> defaultZone, CSVHeaderInformation fieldsFromHeader ) { if ( fieldsFromHeader != null ) { if ( !(fieldsFromHeader instanceof TimeCSVHeaderInformation) ) { throw new IllegalStateException( "Wrong header information type: " + fieldsFromHeader ); } // Override defaultZone defaultZone = ((TimeCSVHeaderInformation) fieldsFromHeader).zoneSupplier( defaultZone ); } return parse( TimeValue.class, PATTERN, TimeValue::parse, text, defaultZone ); }
Source:
ZoneId getZoneId() { START throw new UnsupportedTemporalUnitException( "Cannot get the timezone of: %s" + this ); END } Don't you need a `String.format` with the `%s` ?

Target:
ZoneId getZoneId() { throw new UnsupportedTemporalUnitException( String.format( "Cannot get the timezone of: %s", this ) ); }
Source:
START private String obsfucateIfSecret( Map.Entry<String,String> param ) END { return secrets.contains( param.getKey() ) ? Secret.OBSFUCATED : param.getValue(); } There is a `log` inside `updateDynamicSetting` that also should be obfuscated.

Target:
private String obsfucateIfSecret( Map.Entry<String,String> param ) { return obsfucateIfSecret( param.getKey(), param.getValue() ); }
Source:
public Register.DoubleLongRegister indexSample( IndexReference index, Register.DoubleLongRegister target ) throws IndexNotFoundKernelException { ktx.assertOpen(); START ktx.assertOpen(); END return storeReadLayer.indexUpdatesAndSize( SchemaDescriptorFactory.forLabel( index.label(), index.properties() ), target ); } It's definitely open now!

Target:
public Register.DoubleLongRegister indexSample( IndexReference index, Register.DoubleLongRegister target ) throws IndexNotFoundKernelException { ktx.assertOpen(); return storeReadLayer.indexSample( SchemaDescriptorFactory.forLabel( index.label(), index.properties() ), target ); }
Source:
private boolean areSameZone( ZoneId thisZone, ZoneId thatZone ) { boolean thisIsOffset = thisZone instanceof ZoneOffset; START boolean thatIsOffset = thatZone instanceof ZoneOffset; END if ( thisIsOffset && thatIsOffset ) { return thisZone.equals( thatZone ); } else if ( !thisIsOffset && !thatIsOffset ) { return TimeZones.map( thisZone.getId() ) == TimeZones.map( thatZone.getId() ); } return false; } `thisIsOffset` and `thatIsOffset` are already evaluated in `unsafeCompareTo`. Send them in as two boolean parameters to this function instead of evaluating them agan

Target:
private boolean areSameZone( ZoneId thisZone, ZoneId thatZone ) { boolean thisIsOffset = thisZone instanceof ZoneOffset; boolean thatIsOffset = thatZone instanceof ZoneOffset; return areSameZone( thisZone, thatZone, thisIsOffset, thatIsOffset ); }
Source:
private Profile[] findExistingProfiles( List<PagedFile> pagedFiles ) { return pagedFiles.stream() .map( pf -> pf.file().getParentFile() ) .distinct() .flatMap( dir -> Profile.findProfilesInDirectory( fs, dir ) ) START .sorted() END .toArray( Profile[]::new ); } This adds nothing.

Target:
private Profile[] findExistingProfiles( List<PagedFile> pagedFiles ) { return pagedFiles.stream() .map( pf -> pf.file().getParentFile() ) .distinct() .flatMap( dir -> Profile.findProfilesInDirectory( fs, dir ) ) .toArray( Profile[]::new ); }
Source:
public int nodeDetachDelete( final long nodeId ) throws KernelException { final MutableInt count = new MutableInt(); TwoPhaseNodeForRelationshipLocking locking = new TwoPhaseNodeForRelationshipLocking( relId -> { ktx.assertOpen(); relationshipDelete( relId ); START count.increment(); END } ); locking.lockAllNodesAndConsumeRelationships( nodeId, ktx ); ktx.assertOpen(); nodeDelete( nodeId ); return count.intValue(); } If we are to keep the previous semantic, we should only increment `count` if `relationshipDelete` returns true.

Target:
public int nodeDetachDelete( final long nodeId ) throws KernelException { final MutableInt count = new MutableInt(); TwoPhaseNodeForRelationshipLocking locking = new TwoPhaseNodeForRelationshipLocking( relId -> { ktx.assertOpen(); if ( relationshipDelete( relId ) ) { count.increment(); } } ); locking.lockAllNodesAndConsumeRelationships( nodeId, ktx ); ktx.assertOpen(); nodeDelete( nodeId ); return count.intValue(); }
Source:
START public synchronized void init0() throws Throwable END { localDatabase.init(); } you no longer need those methods to be synch right?

Target:
public void init0() throws Throwable { localDatabase.init(); }
Source:
private synchronized CHANNEL getIdleChannel( AdvertisedSocketAddress catchUpAddress ) { CHANNEL channel = null; LinkedList<CHANNEL> channels = idleChannels.get( catchUpAddress ); if ( channels != null ) { channel = channels.poll(); if ( channel != null && !channel.isActive() ) { START dispose( channel ); END channel = null; } if ( channels.isEmpty() ) { idleChannels.remove( catchUpAddress ); } } return channel; } What would you think about a while-loop here, when the channel !isActive()? e.g. so that we exhaust all suitable idle channels before we return null and cause the creation of a new one

Target:
private synchronized CHANNEL getIdleChannel( AdvertisedSocketAddress catchUpAddress ) { CHANNEL channel = null; LinkedList<CHANNEL> channels = idleChannels.get( catchUpAddress ); if ( channels != null ) { while ( (channel = channels.poll()) != null ) { if ( channel.isActive() ) { break; } } if ( channels.isEmpty() ) { idleChannels.remove( catchUpAddress ); } } return channel; }
Source:
private static PointValue randomPoint( int index, int dimension ) { CoordinateReferenceSystem crs = START index % 2 == 0 ? END dimension == 2 ? WGS84 : WGS84_3D : dimension == 2 ? Cartesian : Cartesian_3D; return unsafePointValue( crs, random().doubles( dimension, Double.MIN_VALUE, Double.MAX_VALUE ).toArray() ); } For increased readability I would prefer the outer `if` to **not** be written with `x ? y : z` notation

Target:
private static PointValue randomPoint( int index, int dimension ) { CoordinateReferenceSystem crs; if ( index % 2 == 0 ) { crs = dimension == 2 ? WGS84 : WGS84_3D; } else { crs = dimension == 2 ? Cartesian : Cartesian_3D; } return unsafePointValue( crs, random().doubles( dimension, Double.MIN_VALUE, Double.MAX_VALUE ).toArray() ); }
Source:
START public static PointValue parse( CharSequence text, AnyValue[] fieldsFromHeader ) END { AnyValue[] fieldsFromData = parseIntoArray( text ); if ( fieldsFromHeader != null ) { //It is given that fieldsFromData.length == fieldsFromHeader.length because parseIntoArray produces fixed length arrays // Merge InputFields: Data fields override header fields for ( int i = 0; i < fieldsFromData.length; i++ ) { if ( fieldsFromData[i] == null ) { fieldsFromData[i] = fieldsFromHeader[i]; } } } return fromInputFields( fieldsFromData ); } How about renaming `fieldsFromHeader` to something like `defaultFields` to make it user agnostic?

Target:
public static PointValue parse( CharSequence text, AnyValue[] fieldsFromHeader ) { AnyValue[] fieldsFromData = parseIntoArray( text ); if ( fieldsFromHeader != null ) { // If fieldsFromHeader comes from parseIntoArray it is given that fieldsFromData.length == fieldsFromHeader.length // because parseIntoArray produces fixed length arrays assert fieldsFromData.length == fieldsFromHeader.length; // Merge InputFields: Data fields override header fields for ( int i = 0; i < fieldsFromData.length; i++ ) { if ( fieldsFromData[i] == null ) { fieldsFromData[i] = fieldsFromHeader[i]; } } } return fromInputFields( fieldsFromData ); }
Source:
public boolean acceptsValue( Value value ) { if ( value == null ) { return false; } if ( value instanceof PointValue ) { PointValue point = (PointValue) value; START if ( point.getCRS() == crs ) END { return point.withinRange( from, fromInclusive, to, toInclusive ); } } return false; } `==` assuming too much? Better with `.equals`?

Target:
public boolean acceptsValue( Value value ) { if ( value == null ) { return false; } if ( value instanceof PointValue ) { PointValue point = (PointValue) value; if ( point.getCRS().equals( crs ) ) { return point.withinRange( from, fromInclusive, to, toInclusive ); } } return false; }
Source:
public void shouldGetErrorWhenUsingCreateUniqueWhenCypherVersionIs3_3() { // expect exception thrown.expect( QueryExecutionException.class ); thrown.expectMessage( "CREATE UNIQUE is no longer supported. You can achieve the same result using MERGE"); // when START Result result = db().execute( "CYPHER 3.3 MATCH (b) WITH b LIMIT 1 CREATE UNIQUE (b)-[:REL]->()" ); END } You are not using `result` anymore so you can call `db().execute( "CYPHER 3.3 MATCH (b) WITH b LIMIT 1 CREATE UNIQUE (b)-[:REL]->()" );` without storing the result in a variable

Target:
public void shouldGetErrorWhenUsingCreateUniqueWhenCypherVersionIs3_3() { // expect exception thrown.expect( QueryExecutionException.class ); thrown.expectMessage( "CREATE UNIQUE is no longer supported. You can achieve the same result using MERGE"); // when db().execute( "CYPHER 3.3 MATCH (b) WITH b LIMIT 1 CREATE UNIQUE (b)-[:REL]->()" ); }
Source:
void flipAfterPopulation() { for ( IndexPopulation population : populations ) { try { START Thread.sleep( 1000 ); END population.flip(); populations.remove( population ); } catch ( Throwable t ) { fail( population, t ); } } } yes right, we already too fast lets give a cpu some time to sleep :)

Target:
void flipAfterPopulation() { for ( IndexPopulation population : populations ) { try { population.flip(); } catch ( Throwable t ) { fail( population, t ); } } }
Source:
public static PointValue fromMap( MapValue map ) { START AnyValue[] fields = new Value[PointValueField.__MAX_VALUE__.ordinal()]; END for ( PointValueField f : PointValueField.values() ) { if ( f != PointValueField.__MAX_VALUE__ ) { AnyValue fieldValue = map.get( f.name().toLowerCase() ); fields[f.ordinal()] = fieldValue != Values.NO_VALUE ? fieldValue : null; } } return fromInputFields( fields ); } It feels like you could as well use `PointValueField.values().length` and get rid of this `__MAX_VALUE__` altogether.

Target:
public static PointValue fromMap( MapValue map ) { AnyValue[] fields = new Value[PointValueField.values().length]; for ( PointValueField f : PointValueField.values() ) { AnyValue fieldValue = map.get( f.name().toLowerCase() ); fields[f.ordinal()] = fieldValue != Values.NO_VALUE ? fieldValue : null; } return fromInputFields( fields ); }
Source:
public static int countOutgoing( NodeCursor nodeCursor, RelationshipGroupCursor group, int type ) { nodeCursor.relationships( group ); int count = 0; while ( group.next() ) { if ( group.type() == type ) { START count += group.outgoingCount() + group.loopCount(); END } } return count; } We will only encounter the type in one group, so we can return once we found it. Same thing below.

Target:
public static int countOutgoing( NodeCursor nodeCursor, RelationshipGroupCursor group, int type ) { nodeCursor.relationships( group ); while ( group.next() ) { if ( group.type() == type ) { return group.outgoingCount() + group.loopCount(); } } return 0; }
Source:
public NettyPipelineBuilder create( Channel channel, Log log ) throws Exception { ChannelPipeline pipeline = channel.pipeline(); NettyPipelineBuilder builder = NettyPipelineBuilder.with( pipeline, log ); int i = 0; for ( ChannelHandler handler : wrapper.handlersFor( channel ) ) { START builder.add( String.format( "%s_%d", wrapper.name(), i ), handler ); END } return builder; } i always equals 0?

Target:
public NettyPipelineBuilder create( Channel channel, Log log ) throws Exception { ChannelPipeline pipeline = channel.pipeline(); NettyPipelineBuilder builder = NettyPipelineBuilder.with( pipeline, log ); int i = 0; for ( ChannelHandler handler : wrapper.handlersFor( channel ) ) { builder.add( String.format( "%s_%d", wrapper.name(), i ), handler ); i++; } return builder; }
Source:
public Iterator<T> iterator() { if ( count == -1 ) { // This should never happen in generated code but is here to simplify debugging if used incorrectly throw new IllegalStateException( "sort() needs to be called before requesting an iterator" ); } return new Iterator<T>() { private int cursor = count; @Override public boolean hasNext() { return cursor > 0; } @Override @SuppressWarnings( "unchecked" ) public T next() { if ( !hasNext() ) { throw new NoSuchElementException(); } --cursor; START return (T) array[cursor]; END } }; } I don't see how this is an improvement.

Target:
public Iterator<T> iterator() { if ( count == -1 ) { // This should never happen in generated code but is here to simplify debugging if used incorrectly throw new IllegalStateException( "sort() needs to be called before requesting an iterator" ); } return new Iterator<T>() { private int cursor = count; @Override public boolean hasNext() { return cursor > 0; } @Override @SuppressWarnings( "unchecked" ) public T next() { if ( !hasNext() ) { throw new NoSuchElementException(); } int offset = --cursor; return (T) array[offset]; } }; }
Source:
public List<ModifierProtocol> modifierProtocols() { START return Collections.unmodifiableList( modifierProtocols ); END } You could make it unmodifiable already in the constructor.

Target:
public List<ModifierProtocol> modifierProtocols() { return modifierProtocols; }
Source:
public void readKey( PageCursor cursor, RawBytes into, int keySize ) { int offsetBeforeRead = cursor.getOffset(); try { into.bytes = new byte[keySize]; cursor.getBytes( into.bytes ); } START catch ( BufferUnderflowException e ) END { throw Exceptions.withMessage( e, e.getMessage() + " keySize:" + keySize + " offset: " + offsetBeforeRead + " page size:" + cursor.getCurrentPageSize() ); } } Oh, I don't think this debug-catch should be here, should it?

Target:
public void readKey( PageCursor cursor, RawBytes into, int keySize ) { into.bytes = new byte[keySize]; cursor.getBytes( into.bytes ); }
Source:
public void close() { read = null; hasChanges = HasChanges.MAYBE; addedNodes = emptySet(); reset(); if ( labelCursor != null ) { labelCursor.close(); labelCursor = null; } if ( pageCursor != null ) { pageCursor.close(); pageCursor = null; START if ( pool != null ) END { pool.accept( this ); } } } Why are we doing this null check? Are we expecting this pool to be null in some real scenarios? If this check is here to allow tests to pass in null then I think that they should pass in a no-op consumer instead so that we can get rid of this condition. (many similar places below too).

Target:
public void close() { read = null; hasChanges = HasChanges.MAYBE; addedNodes = emptySet(); reset(); if ( labelCursor != null ) { labelCursor.close(); labelCursor = null; } if ( pageCursor != null ) { pageCursor.close(); pageCursor = null; pool.accept( this ); } }
Source:
private static TemporalType find( int temporalType ) { START if ( temporalType < TYPES.length ) END { return TYPES[temporalType]; } else { // Kernel code requires no exceptions in deeper PropertyChain processing of corrupt/invalid data return TEMPORAL_INVALID; } } `&& temporalType >= 0` ?

Target:
private static TemporalType find( int temporalType ) { if ( temporalType < TYPES.length && temporalType >= 0 ) { return TYPES[temporalType]; } else { // Kernel code requires no exceptions in deeper PropertyChain processing of corrupt/invalid data return TEMPORAL_INVALID; } }
Source:
public final boolean eq( Object other ) { if ( other == null ) { return false; } if ( other instanceof SequenceValue ) { return this.equals( (SequenceValue) other ); } START return other instanceof Value && equals( (Value) other ); END } Can an `ArrayValue` ever equal something which is not another array and thus an instance of `SequenceValue`? I would assume that this row always returns false.

Target:
public final boolean eq( Object other ) { if ( other == null ) { return false; } return other instanceof SequenceValue && this.equals( (SequenceValue) other ); }
Source:
public void shutdown() throws IOException { if ( index != null ) { START index.close(); END } } Maybe take the opportunity to set `index = null` here?

Target:
public void shutdown() throws IOException { if ( index != null ) { index.close(); index = null; } }
Source:
public Value nodeGetProperty( long nodeId, int propertyKeyId ) throws EntityNotFoundException { statement.assertOpen(); if ( propertyKeyId == StatementConstants.NO_SUCH_PROPERTY_KEY ) { return Values.NO_VALUE; } try ( Cursor<NodeItem> node = dataRead().nodeCursorById( statement, nodeId ) ) { START if ( propertyIsAllowed( propertyKeyId ) ) END { return dataRead().nodeGetProperty( statement, node.get(), propertyKeyId ); } else { return Values.NO_VALUE; } } } This check could be made before getting the node cursor. No need to spend any more time in `OperationsFacade` though... it's gone before 3.4 comes out.

Target:
public Value nodeGetProperty( long nodeId, int propertyKeyId ) throws EntityNotFoundException { statement.assertOpen(); if ( propertyKeyId == StatementConstants.NO_SUCH_PROPERTY_KEY ) { return Values.NO_VALUE; } try ( Cursor<NodeItem> node = dataRead().nodeCursorById( statement, nodeId ) ) { return dataRead().nodeGetProperty( statement, node.get(), propertyKeyId ); } }
Source:
public void run() { START List<Throwable> errors = new LinkedList<>(); END for ( Runnable o : operations ) { try { o.run(); } catch ( RuntimeException e ) { errors.add( e ); } } if ( !errors.isEmpty() ) { RuntimeException exception = new RuntimeException(); errors.forEach( exception::addSuppressed ); throw exception; } } please just use arraylist

Target:
public void run() { List<Throwable> errors = new ArrayList<>(); for ( Runnable o : operations ) { try { o.run(); } catch ( RuntimeException e ) { errors.add( e ); } } if ( !errors.isEmpty() ) { RuntimeException exception = new RuntimeException(); errors.forEach( exception::addSuppressed ); throw exception; } }
Source:
public void assertContinue() throws StoreCopyFailedException { long currentTime = clock.millis(); if ( timeHasExpired( previousCheck, currentTime ) ) { tries++; } START previousCheck = currentTime; END if ( tries >= maxRetries ) { throw new StoreCopyFailedException( "Maximum allowed retries exceeded: " + maxRetries ); } } This was mistakenly moved

Target:
public void assertContinue() throws StoreCopyFailedException { long currentTime = clock.millis(); if ( timeHasExpired( previousCheck, currentTime ) ) { tries++; previousCheck = currentTime; } if ( tries >= maxRetries ) { throw new StoreCopyFailedException( "Maximum allowed retries exceeded: " + maxRetries ); } }
Source:
public void setup() { try { START folder.create(); END readTestSupport.setup( folder.getRoot(), a -> { } ); } catch ( IOException e ) { fail(); } kernel = readTestSupport.kernelToTest(); session = kernel.beginSession( SecurityContext.AUTH_DISABLED ); System.setProperty( "org.neo4j.kernel.impl.newapi.Read.trackCursors", "true" ); } Can't we just rely on `@Rule`

Target:
public void setup() { readTestSupport.setup( folder.getRoot(), a -> { } ); kernel = readTestSupport.kernelToTest(); session = kernel.beginSession( SecurityContext.AUTH_DISABLED ); }
Source:
public void releaseCursor( Cursor cursor ) { if ( cursorsInUse > 0 ) { if ( TRACK_CURSORS ) { cursorsOpenCloseCalls.remove( cursor ); } START cursorsInUse--; END } } Looks like setting `RECORD_CURSOR_TRACES` to `false` will increase the overhead of recording cursor traces, since the traces are captured regardless, and then stored in a cache shared among all threads, and the cache has to evict on all but the first put.

Target:
public void releaseCursor( Cursor cursor ) { //System.out.println("REL "+ cursor + "@" + System.identityHashCode( cursor )); cursorsOpenCloseCalls.remove( cursor ); // TODO: Test this }
Source:
void single( long reference, Read read ) { if ( getId() != NO_ID ) { reset(); } if ( pageCursor == null ) { pageCursor = read.nodePage( reference ); } this.next = reference; //This marks the cursor as a "single cursor" this.highMark = NO_ID; this.read = read; this.hasChanges = HasChanges.MAYBE; this.addedNodes = emptySet(); START this.single = true; END } I think you can use `this.highMark == NO_ID` to check for `single` without introducing a new field. There is already a method `isSingle` method you can use instead.

Target:
void single( long reference, Read read ) { if ( getId() != NO_ID ) { reset(); } if ( pageCursor == null ) { pageCursor = read.nodePage( reference ); } this.next = reference; //This marks the cursor as a "single cursor" this.highMark = NO_ID; this.read = read; this.hasChanges = HasChanges.MAYBE; this.addedNodes = emptySet(); }
Source:
START int length() END { return (int) Math.pow( 2, dimension ); } Should be final.

Target:
final int length() { return (int) Math.pow( 2, dimension ); }
Source:
private void placeCursorAtActualKey( PageCursor cursor, int pos, Type type ) { // Set cursor to correct place in offset array int keyPosOffset = keyPosOffset( pos, type ); cursor.setOffset( keyPosOffset ); // Read actual offset to key int keyOffset = readKeyOffset( cursor ); // Verify offset is reasonable if ( keyOffset > pageSize ) { START cursor.setCursorException( "Tried to read key on offset " + keyOffset + ". Page size is " + pageSize ); END } // Set cursor to actual offset cursor.setOffset( keyOffset ); } PageCursor checks bounds, later propagated in `checkAndClearBoundsFlag()` doesn't it? Do we need to do this specifically here anyway?

Target:
private void placeCursorAtActualKey( PageCursor cursor, int pos, Type type ) { // Set cursor to correct place in offset array int keyPosOffset = keyPosOffset( pos, type ); cursor.setOffset( keyPosOffset ); // Read actual offset to key int keyOffset = readKeyOffset( cursor ); // Verify offset is reasonable if ( keyOffset > pageSize || keyOffset < 0 ) { cursor.setCursorException( "Tried to read key on offset " + keyOffset + ". Page size is " + pageSize ); } // Set cursor to actual offset cursor.setOffset( keyOffset ); }
Source:
START public synchronized void close() END { isOpen = false; } I don't see any other method that this synchronisation would avoid overlapping with.

Target:
public void close() { isOpen = false; }
Source:
public void setUp() throws Exception { File folder = testDir.directory( "folder" ); indexStorage = new PartitionedIndexStorage( directoryFactory, fileSystemRule.get(), folder, false ); START index = LuceneSchemaIndexBuilder.create( descriptor, Config.defaults(), directoryFactory) END .withIndexStorage( indexStorage ) .build(); schemaDescriptor = descriptor.schema(); } Checkstyle; missing space at the end there.

Target:
public void setUp() { File folder = testDir.directory( "folder" ); indexStorage = new PartitionedIndexStorage( directoryFactory, fileSystemRule.get(), folder, false ); index = LuceneSchemaIndexBuilder.create( descriptor, Config.defaults(), directoryFactory ) .withIndexStorage( indexStorage ) .build(); schemaDescriptor = descriptor.schema(); }
Source:
private int readInt( long pageId, int pageOffset ) throws IOException { // Cross-page read? START int bytesInCurentPage = pageSize - pageOffset; END if ( bytesInCurentPage < 4 ) { return readPageCrossingInt( pageId, pageOffset, bytesInCurentPage ); } // Regular read moveCursorTo( pageId, pageOffset ); int val; do { val = cursor.getInt( pageOffset ); } while ( cursor.shouldRetry() ); if ( cursor.checkAndClearBoundsFlag() ) { throw newEOFException( "Cursor bounds check failed" ); } return val; } This method seems to be pretty hot. I wonder if you could optimistically combine `pageId`, `pageOffset` and `moveCursorTo` into a single method call, and then go straight to the int-read loop. And then rely on `checkAndClearBoundsFlag` to indicate if you should throw away that result and try a cross-page instead instead, which in turn would figure out if we're actually really EOF or not.

Target:
private int readInt( long pageId, int pageOffset ) throws IOException { // 1. Optimistic fast path, relies on bounds check at checkAndClearBoundsFlag moveCursorTo( pageId, pageOffset ); int val; do { // This may totally fail, since we may be reading an int that's split // across multiple pages - meaning this call is reading more bytes than // what fits in current page. If that happens, checkAndClearBoundsFlag // saves us, and we fall back to the slow path readPageCrossingInt val = cursor.getInt( pageOffset ); } while ( cursor.shouldRetry() ); // Our savior! if ( !cursor.checkAndClearBoundsFlag() ) { // Fast path worked return val; } // 2. Slow path return readPageCrossingInt( pageId, pageOffset ); }
Source:
public IndexReader newReader() { Map<CoordinateReferenceSystem,IndexReader> indexReaders = new HashMap<>(); for ( Map.Entry<CoordinateReferenceSystem,SpatialKnownIndex> index : indexMap.entrySet() ) { try { START indexReaders.put( index.getKey(), index.getValue().getOnlineAccessor(descriptor, samplingConfig).newReader() ); END } catch ( IOException e ) { e.printStackTrace(); } } return new SpatialFusionIndexReader( indexReaders, descriptor ); } What are the plans for this fellow?

Target:
public IndexReader newReader() { Map<CoordinateReferenceSystem,IndexReader> indexReaders = new HashMap<>(); for ( Map.Entry<CoordinateReferenceSystem,SpatialKnownIndex> index : indexMap.entrySet() ) { // TODO should this be populated here, or delegate to SpatialFusionIndexReader? indexReaders.put( index.getKey(), index.getValue().newReader( samplingConfig, descriptor ) ); } return new SpatialFusionIndexReader( indexReaders, descriptor ); }
Source:
public void shouldNotGenerateUpdateForMultipleExistingPropertiesAndLabels() { // When NodeUpdates updates = NodeUpdates.forNode( nodeId, labels ) .existing( propertyKeyId1, Values.of( "Neo" ) ) .existing( propertyKeyId2, Values.of( 100L ) ) START .existing( propertyKeyId3, Values.of( Values.pointValue( CoordinateReferenceSystem.WGS84, 12.3, 45.6 ) ) ) END .build(); // Then assertThat( updates.forIndexKeys( indexes, assertNoLoading() ), emptyIterable() ); } Don't need the extra `Values.of` wrap.

Target:
public void shouldNotGenerateUpdateForMultipleExistingPropertiesAndLabels() { // When NodeUpdates updates = NodeUpdates.forNode( nodeId, labels ) .existing( propertyKeyId1, Values.of( "Neo" ) ) .existing( propertyKeyId2, Values.of( 100L ) ) .existing( propertyKeyId3, Values.pointValue( CoordinateReferenceSystem.WGS84, 12.3, 45.6 ) ) .build(); // Then assertThat( updates.forIndexKeys( indexes, assertNoLoading() ), emptyIterable() ); }
Source:
public void close() throws Exception { writer.close(); START super.close(); END } The `super.close()` method will close the executor, after which the task queues will be empty and all workers will have terminated. If we close the `writer` before we close the executor, we can risk racing with on-going work, can we not?

Target:
public void close() throws Exception { super.close(); writer.close(); }
Source:
public boolean labels( String[] labels ) { checkClear(); START for ( String label : labels ) END { this.labels.add( label ); } return delegate.labels( labels ); } `Collections.addAll`

Target:
public boolean labels( String[] labels ) { checkClear(); Collections.addAll( this.labels, labels ); return delegate.labels( labels ); }