auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static byte[] fileToBytes(File path) throws IOException { byte[] bytes = null; try { bytes = Files.readAllBytes(path.toPath()); } catch (IOException ioe) { throw new IOException("File " + path.getAbsolutePath() + " is empty"); } return bytes; }

Target:
This error message is no longer accurate. You don't have catch it here, just let it throw.
Source:
public void offerSp(InitiateResponseMessage msg, boolean isLeader, long handle) { // System.out.println(String.format("Leader %s, truncation handle %d, replica truncation handle %d", // Boolean.toString(isLeader), handle, m_lastSpTruncationHandle)); long truncationHandle = m_lastSpTruncationHandle; if (isLeader) { truncationHandle = handle; } if (msg.getSpHandle() >= truncationHandle || truncationHandle == Long.MIN_VALUE) { m_mailbox.send(msg.getInitiatorHSId(), msg); } else { m_shortCircuitReadSp.add(new Item(msg)); } releaseShortCircuitRead(truncationHandle, IS_SP); }

Target:
No need to check for `truncationHandle == Long.MIN_VALUE`.
Source:
private void stagePathConfiguration(Configuration config) { File depFH = new VoltFile(config.m_voltdbRoot, VoltDB.INITIALIZED_PATHS); try (PrintWriter pw = new PrintWriter(new FileWriter(depFH), true)) { m_pathList.store(pw, "DO NOT MODIFY THIS FILE"); pw.flush(); pw.close(); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to stage configuration path destination", false, e); } }

Target:
flush and close are done automagically when you get out from the try with resource block
Source:
private void loadPathConfiguration(Configuration config) { File depFH = new VoltFile(config.m_voltdbRoot, VoltDB.INITIALIZED_PATHS); try (FileInputStream is = new FileInputStream(depFH)) { consoleLog.info("Loading Path configuration from " + depFH.getAbsolutePath()); m_pathList.load(is); is.close(); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to read configuration path destination", false, e); } }

Target:
flush and close are done automagically when you get out from the try with resource block
Source:
public static ImmutableSortedSet<String> hosts(int...ports) { if (ports.length == 0) { return ImmutableSortedSet.of( HostAndPort.fromParts("", DEFAULT_INTERNAL_PORT).toString()); } ImmutableSortedSet.Builder<String> sbld = ImmutableSortedSet.naturalOrder(); for (int p: ports) { sbld.add(HostAndPort.fromParts("", p).toString()); } return sbld.build(); }

Target:
What's this used for without passing any IP/hostname?
Source:
public static boolean isInitialAckDRId(long drId) { if (drId == -1) return true; int clusterId = getClusterIdFromDRId(drId); if (clusterId >= 0 && clusterId < MAX_CLUSTER_ID) { return !((drId >>> 63) == 1L) && (getSequenceNumberFromDRId(drId) == MAX_SEQUENCE_NUMBER); } return false; }

Target:
The second condition should be clusterId <= MAX_CLUSTER_ID
Source:
public static boolean isEmptyDRId (long drId) { return ((drId >>> 63) == 1L) && !(drId == -1); }

Target:
Maybe you can use !=, which is simpler
Source:
private void checkProcStatistics(Client client) throws NoConnectionsException, IOException, ProcCallException { VoltTable vt; vt = client.callProcedure("@Statistics", "PROCEDUREPROFILE", 1).getResults()[0]; System.out.println(vt.toString()); }

Target:
This function just seems to be cluttering the test output. Is it really serving a purpose? Can it be modifed to do an actual validation rather than just dump output for a visual inspection that, practically speaking, will never happen. In general, I LIKE keeping around PROVEN USEFUL visual diagnostic code so it can be quickly enabled when something goes wrong, BUT I like it DISABLED when all is running as expected for a less verbose successful run and the clearer identification of actual problem diagnostics.
Source:
public void shutdown() throws InterruptedException { for (VoltNetwork vn : m_networks) { vn.shutdown(); } // end "Reverse DNS lookups" thread before shutdown ReverseDNSCache.m_es.shutdown(); }

Target:
catch any exceptions on vn.shutdown() to ensure ReverseDNSCache.m_es.shutdown() is invoked.
Source:
static private void addTableToProject(VoltProjectBuilder project, int tableId, boolean partitioned) { try { project.addLiteralSchema(String.format(tableDDL, tableId)); project.addStmtProcedure("Insert" + tableId, "INSERT INTO T" + tableId + " VALUES (?)"); if (partitioned) { project.addLiteralSchema(String.format(partitionDDL, tableId)); } } catch (IOException e) { assertFalse(true); } }

Target:
You will automatically get a CRUD proc called T1.Insert, etc when you create the table, so I think these procedures are unnecessary.
Source:
public boolean allInnerJoins() { return m_joinType == JoinType.INNER && (m_leftNode == null ? true : m_leftNode.allInnerJoins()) && (m_rightNode == null ? true : m_rightNode.allInnerJoins()); }

Target:
`X ? true : Y` simplifies to `X || Y`.
Source:
public static byte[] compressJSONString(String data) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length()); GZIPOutputStream gzip = new GZIPOutputStream(bos); gzip.write(data.getBytes(StandardCharsets.UTF_8)); gzip.close(); byte[] compressed = bos.toByteArray(); bos.close(); return compressed; }

Target:
``` java public static byte[] compressJSONString(String data) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length()); try (GZIPOutputStream gzip = new GZIPOutputStream(bos)) { gzip.write(data.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw e; } return bos.toByteArray(); } ```
Source:
public void addImport(boolean enabled, String importType, String importFormat, String importBundle, Properties config) { addImport(enabled, importType, importFormat, importBundle, config, null); }

Target:
why not send empty Properties so you dont have to deal with null.
Source:
void expandConditions() { expandConditions(whereExpressions, false); for (HsqlArrayList whereExpression : whereExpressions) { if (whereExpression.size() > whereExpressionElementsUpperBound) { // If the query's where clause is composed of 240+ predicate expressions, when parsing these // expressions, due to mutual recursion, thread stack can grow to it's maximum capacity, // resulting in stack overflow error. The optimal solution to avoid this is to convert the // mutual recursion into tail-recursion or iterative approach. Though the change needed // are at multiple places like generating unique id for the expression during construction // of volt XML elements and converting the expression tree for the plan to json-string. // So at present guard against query whose where clause has more than 232 predicates. String msg = "Limit of predicate expressions in \"where\" clause exceeded the maximum limit of " + whereExpressionElementsUpperBound + " predicates, predicates detected: " + whereExpression.size() + ". Reduce the number of predicates in the \"where\" clause to " + whereExpressionElementsUpperBound; throw new HsqlException(msg, "", ErrorCode.X_47002); } } expandConditions(joinExpressions, false); }

Target:
I think a generic check would be best if at all possible. There are lots of places where expressions can appear, and it would be easy to miss some. You could add a new field to Expression that is the number of levels in the tree, that is computed whenever a building an expression. Any time an expression is constructed, the new number of levels is the max(number_of_levels_in_nth_child_tree) + 1. Not sure if this is feasible.
Source:
private ExpressionLike(ExpressionLike other) { super(OpTypes.LIKE); this.nodes = other.nodes; this.likeObject = other.likeObject; this.noOptimisation = true; }

Target:
Why set this to true here, instead of copying the value from other?
Source:
public void shutdown(ShutdownInput shutDownInput) { if (shutDownInput.getShutdownReason().equals(ShutdownReason.TERMINATE)) { //The shard may be split or merged. checkpoint one last time commitCheckPoint(shutDownInput.getCheckpointer()); } }

Target:
``` java if (ShutdownReason.TERMINATE.equals(shutDownInput.getShutdownReason()) { ```
Source:
public void activate() { m_isActive = true; setupExecutor(); }

Target:
Shouldnt this be on executor lock?
Source:
public HTTPClientInterface() { final ClientResponseImpl r = new ClientResponseImpl(ClientResponse.CONNECTION_TIMEOUT, new VoltTable[0], "Request Timeout"); m_timeoutResponse = r.toJSONString(); m_closeAllExecutor = CoreUtils.getSingleThreadExecutor("HttpClientInterface-closeAll"); // STEBUG remove m_servicePrincipal = getAuthSystem().getServicePrincipal(); m_spnegoEnabled = m_servicePrincipal != null && !m_servicePrincipal.isEmpty(); }

Target:
Do u mean to leave STEBUG?
Source:
VoltFormatter (String name, Properties prop) { if (!("csv".equalsIgnoreCase(name) || "tsv".equalsIgnoreCase(name))) { throw new RuntimeException("Invalid format " + name + ", choices are either \"csv\" or \"tsv\"."); } m_parser = new CSVParser("csv".equalsIgnoreCase(name) ? ',' : '\t'); }

Target:
please use IllegalArgumentException
Source:
public void reset() { drId = Long.MIN_VALUE; spUniqueId = Long.MIN_VALUE; mpUniqueId = Long.MIN_VALUE; }

Target:
As a matter of default, it's a little odd that these are using `Long.MIN_VALUE` while the rest of DR uses 0, a.k.a. `InvocationBuffer.UNSET_UNIQUE_ID`
Source:
private void verifyPerspectiveIsLoaded(String perspectiveID, By elementInPerspective) { try { Waits.elementPresent(elementInPerspective, 10); } catch (WebDriverException ex) { Assertions.fail("The perspective with ID " + perspectiveID + " could not be loaded."); } }

Target:
I forgot we should add `ex` as the second parameter of `Assertions.fail` not to loose the failure stacktrace. Please add it.
Source:
public void goOnline() { ReadOnlyStoreStatusValidation validation = validateReadOnlyStoreStatusBeforeGoingOnline(); if (validation.readyToGoOnline) { createOnlineServices(); startOnlineServices(); getMetadataStore().setOfflineState(false); } if (validation.e != null) { throw new VoldemortException("Problem while going online!", validation.e); } }

Target:
In the existing code, this was the first statement. Any reason, why you are changing the order ? If not, I would like to keep the getMetadataStore().setOfflineState(false) to be the first statement.
Source:
public synchronized void recordWarningCode(int code) { Integer Icode = code; if(!warningCodes.containsKey(Icode)) { int[] val = new int[1]; val[0] = 0; warningCodes.put(Icode, val); } warningCodes.get(Icode)[0]++; }

Target:
Nipick: can we follow Java conventions of beginning variable names with a lower case? We also don't typically prefix variables with type information, though I guess that's not a big deal if you want to leave it as is.
Source:
public void testVersionedDelete() { System.out.println("*********** testing versioned delete ***********"); ByteArray key = new ByteArray("keyOne".getBytes()); List<Versioned<byte[]>> conflictingVersions = generatePutWithConflictionVersions(key); if(conflictingVersions.size() == 0) { Assert.fail("Could not generate conflicting versions "); } testDelete(key, conflictingVersions.get(0).getVersion()); }

Target:
get rid of these s.o.plns and replace with logger?
Source:
public VoldemortService getService(ServiceType type) { for(VoldemortService service: services) if(service.getType().equals(type)) return service; throw new IllegalStateException(type.getDisplayName() + " has not been initialized."); }

Target:
Please add { } even if its a single line statement.
Source:
public static String writeSingleClientConfigAvro(Properties props) { // FIXME: This sucks. We shouldn't be manually manipulating json... String avroConfig = new String(); Boolean firstProp = true; for(String key: props.stringPropertyNames()) { if(firstProp) { firstProp = false; } else { avroConfig = avroConfig + ",\n"; } avroConfig = avroConfig + "\t\t\"" + key + "\": \"" + props.getProperty(key) + "\""; } if(avroConfig.isEmpty()) { return "{}"; } else { return "{\n" + avroConfig + "\n\t}"; } }

Target:
Any specific reason for not using just the String literal here. As in just using String avroConfig; instead of creating String object.
Source:
private DbSpace getBdbStats() { return new DbSpace(environment, sorted); }

Target:
Is nt sorted always false here? can you remove the variable?
Source:
public <T> Mono<CosmosItemResponse<T>> upsertItem(T item, PartitionKey partitionKey, CosmosItemRequestOptions options) { final CosmosItemRequestOptions requestOptions = options == null ? new CosmosItemRequestOptions() : options; ModelBridgeInternal.setPartitionKey(options, partitionKey); return withContext(context -> upsertItemInternal(item, requestOptions, context)); }

Target:
This is a bug, we need to pass `requestOptions` instead of `options` Since you are OOF, I will fix it in your branch and push it.
Source:
private void releaseAfterCancel(HttpMethod method) { if (mayHaveBody(method) && this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.CANCELLED)) { if (logger.isDebugEnabled()) { logger.debug("Releasing body, not yet subscribed"); } this.bodyIntern() .doOnNext(byteBuf -> {}) .subscribe(byteBuf -> {}, ex -> {}); } }

Target:
Do we need mayHaveBody check , what happen if we clear on all cancel irrespective of body, we can avoid extra check ?
Source:
public BenchmarkRequestSubscriber(Meter successMeter, Meter failureMeter, Semaphore concurrencyControlSemaphore, AtomicLong count) { this.successMeter = successMeter; this.failureMeter = failureMeter; this.concurrencyControlSemaphore = concurrencyControlSemaphore; this.count = count; logger = LoggerFactory.getLogger(this.getClass()); }

Target:
this class is getting instantiated in a for loop in your benchmark, meaning the logger initialization will be called per for loop iteration. logger should be static to avoid initialization cost per loop iteration.
Source:
public void testDelete() { Mono<LongIdDomainPartition> saveMono = this.repository.save(DOMAIN_1); StepVerifier.create(saveMono).thenConsumeWhile(domain -> true).expectComplete().verify(); Mono<Void> deleteMono = this.repository.delete(DOMAIN_1); StepVerifier.create(deleteMono).verifyComplete(); Mono<Long> countMono = repository.count(); StepVerifier.create(countMono).expectNext(1L).verifyComplete(); }

Target:
`expectNext = DOMAIN_1`
Source:
public static Object getStringIDValue(Object idValue) { Assert.notNull(idValue, "id should not be null"); if (idValue instanceof String) { Assert.hasText(idValue.toString(), "id should not be empty or only whitespaces."); return idValue; } else if (idValue instanceof Integer) { return Integer.toString((Integer) idValue); } else if (idValue instanceof Long) { return Long.toString((Long) idValue); } else { throw new IllegalQueryException("Type of id field must be String or Integer or Long"); } }

Target:
This should return <String> type, why is it returning Object ?
Source:
public AnalyzeTextOptions setTokenFilters(TokenFilterName... tokenFilters) { this.tokenFilters = Arrays.asList(tokenFilters); return this; }

Target:
The options are input only
Source:
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties, CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } Database wrappedDatabase = new Database(); wrappedDatabase.setId(databaseProperties.getId()); final CosmosDatabaseRequestOptions requestOptions = options; return withContext(context -> createDatabaseInternal(wrappedDatabase, requestOptions, context)); }

Target:
From a code style perspective, it would be better to do lines 255-257 and 260 on a single line: `final CosmosDatabaseRequestOptions requestOptions = options == null ? new CosmosDatabaseRequestOptions() : options;`
Source:
CosmosPagedFlux<CosmosDatabaseProperties> readAllDatabases(CosmosQueryRequestOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { String spanName = "readAllDatabases"; pagedFluxOptions.setTracerInformation(this.tracerProvider, spanName, this.serviceEndpoint, null); setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readDatabases(options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosDatabasePropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); }

Target:
Could you save a variable declaration and set by just directly passing the string into the method call?
Source:
private RecognizeOptions getRecognizeOptionsProperties(RecognizeOptions userProvidedOptions) { if (userProvidedOptions != null) { return new RecognizeOptions() .setPollInterval(userProvidedOptions.getPollInterval()) .setFormContentType(userProvidedOptions.getFormContentType()) .setIncludeTextContent(userProvidedOptions.isIncludeTextContent()); } else { return new RecognizeOptions(); } }

Target:
why do we make a copy of the user-provided options here?
Source:
void setup() { MockitoAnnotations.initMocks(this); when(asyncClient.getEntityPath()).thenReturn(ENTITY_PATH); when(asyncClient.getFullyQualifiedNamespace()).thenReturn(NAMESPACE); when(asyncClient.getReceiverOptions()).thenReturn(new ReceiverOptions(ReceiveMode.PEEK_LOCK, 1, maxAutoLockRenewalDuration)); when(messageLockToken).thenReturn(LOCK_TOKEN); client = new ServiceBusReceiverClient(asyncClient, OPERATION_TIMEOUT); }

Target:
You don't need to mock this anymore you can set the string and return it.
Source:
public int compareTo(UInt128 other) { if (this.equals(other)) { return 0; } if ((this.high < this.high) || ((this.high == other.high) && (this.low < other.low))) { return -1; } return 1; }

Target:
I think this is a typo -> `this.high < this.high` -> should be -> `this.high < other.high` ??
Source:
public TablesSharedKeyCredential(String accountName, String accountKey) { Objects.requireNonNull(accountName, "'accountName' cannot be null."); Objects.requireNonNull(accountKey, "'accountKey' cannot be null."); this.accountName = accountName; this.accountKey = accountKey; }

Target:
This can be simplified to. Same with the line below. ```java this.accountName = Objects.requireNonNull(accountName, "'accountName' cannot be null."); ```
Source:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { String authorizationValue = this.credential.generateAuthorizationHeader(context.getHttpRequest().getUrl(), context.getHttpRequest().getHeaders().toMap()); context.getHttpRequest().setHeader("Authorization", authorizationValue); return next.process(); }

Target:
Remove `this.`
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)) .expectError(com.azure.data.tables.implementation.models.TableServiceErrorException.class) .verify(); }

Target:
If you import this, it won't need to be fully qualified.
Source:
public BoundingBox(final List<Point> points) { if (points == null) { this.points = null; } else { this.points = Collections.unmodifiableList(new ArrayList<>(points)); } }

Target:
Don't need to create a new ArrayList here.
Source:
public CustomFormSubmodel(final Float accuracy, final Map<String, CustomFormModelField> fields, final String formType) { this.accuracy = accuracy; this.fields = fields == null ? null : Collections.unmodifiableMap(new HashMap<>(fields)); this.formType = formType; }

Target:
```suggestion this.fields = fields == null ? null : Collections.unmodifiableMap(fields); ```
Source:
public List<TokenCredential> getCredentials() { return tokenCredentials; }

Target:
This should return an unmodifiable list. Create the unmodifiable list in the ctor itself.
Source:
public Response<AppendBlobItem> createWithResponse(AppendBlobCreateOptions options, Duration timeout, Context context) { return StorageImplUtils.blockWithOptionalTimeout(appendBlobAsyncClient. createWithResponse(options, context), options == null ? null : timeout); }

Target:
This should just be timeout
Source:
private Mono<AmqpSendLink> getSendLink() { return connectionProcessor .flatMap(connection -> { String linkName = entityName; 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())); }

Target:
This link name doesn't have to be declared. You only use the corresponding value within the if statement for each of them.
Source:
public float getX() { return this.xCoordinate; }

Target:
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.
Source:
public void createTable() { TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder() .connectionString("connectionString") .buildAsyncClient(); tableServiceAsyncClient.createTable("OfficeSupplies").subscribe( Void -> {}, error -> logger.error("There was an error creating the table. Error: " + error), () -> logger.info("Table creation successful.")); }

Target:
System.err.println` over ClientLogger
Source:
public void queryTable() { TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder() .connectionString("connectionString") .buildAsyncClient(); QueryOptions queryOptions = new QueryOptions(); 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); }); }

Target:
Highlight usage of the fluent model. var queryOptions = new QueryOptions().setFilter("TableName eq OfficeSupplies");
Source:
public boolean isWriting() { return writing == true || (!reading && isSimpleTargetType()); }

Target:
Can simplify to... `return writing || (!reading && isSimpleTargetType());`
Source:
public CassandraTemplate(Session session, CassandraConverter converter) { setSession(session); setConverter(converter == null ? getDefaultCassandraConverter() : converter); }

Target:
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());`
Source:
public static Book random() { return new Book("title" + uuid(), "isbn" + uuid()); }

Target:
I included your fix in our test code cleanup, see #51.
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 ) ); }

Target:
I don't see why the `newMonitor` methods need to be synchronised.
Source:
public void execute( Runnable runnable ) { if ( latch.compareAndSet( false, true ) ) { jobScheduler.schedule( group, () -> { runnable.run(); latch.set( false ); } ); } }

Target:
The latch should probably be set in a finally
Source:
public Stream<BuiltInProcedures.SchemaIndexInfo> createIndex( String indexSpecification, String providerName ) throws ProcedureException { String statusMessage = "index created"; return createIndex( indexSpecification, providerName, statusMessage, ( schemaWrite, descriptor, provider ) -> schemaWrite.indexCreate( descriptor, Optional.of( provider ), Optional.empty() ) ); }

Target:
Inline this
Source:
private int getOrCreateLabelId( String labelName ) throws ProcedureException { try { return ktx.tokenWrite().labelGetOrCreateForName( labelName ); } catch ( TooManyLabelsException | IllegalTokenNameException e ) { throw new ProcedureException( e.status(), e, "" ); } }

Target:
Please replace empty string with a proper error message
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 ) { throw new ProcedureException( e.status(), e, "" ); } } return propertyKeyIds; }

Target:
Please replace empty string with a proper error message
Source:
boolean timeToResize() { return numberOfEntries == resizeLimit; }

Target:
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.
Source:
IndexDescriptor( IndexDescriptor indexDescriptor ) { schema = indexDescriptor.schema; type = indexDescriptor.type; userSuppliedName = indexDescriptor.userSuppliedName; providerDescriptor = indexDescriptor.providerDescriptor; }

Target:
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.
Source:
public static void main( String[] args ) throws InterruptedException, IOException { FileSystemAbstraction fs = new DefaultFileSystemAbstraction(); File indexFile = new File( "index" ); Runtime.getRuntime().addShutdownHook( new Thread( () -> fs.deleteFile( indexFile ) ) ); new GBPTreePlayground( fs, indexFile ).run(); }

Target:
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?
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 e.addSuppressed( closeException ); } } } ); indexesToDropAfterCompletedRecovery.clear(); }

Target:
If we are swallowing exception here we don't need to `addSuppressed`.
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 && (predicate.valueGroup() == ValueGroup.NUMBER || predicate.valueGroup() == ValueGroup.GEOMETRY); }

Target:
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.
Source:
void shouldFailWithNonExistentProviderName( IndexCreator creator ) throws KernelException { // given SchemaWrite schemaWrite = schemaWriteInNewTransaction(); // when try { schemaWrite.indexCreate( forLabel( 0, 0 ), "something-completely-different" ); fail( "Should have failed" ); } catch ( IllegalArgumentException e ) { // then good } }

Target:
I think you meant to use the `creator` here?
Source:
public void handleStepDown( long term, String dbName ) { boolean wasLeaderForTerm = Objects.equals( myself, leaderInfo.memberId() ) && term == leaderInfo.term(); if ( wasLeaderForTerm ) { log.info( String.format( "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, log); } }

Target:
Don't need `String.format`
Source:
public void tearDown() throws Throwable { server.stop(); server.shutdown(); }

Target:
Check so that server != null when tearing down.
Source:
public void setUp() throws Throwable { server = createServer(); server.init(); assertFalse( canConnect( server.address(), clientGroup ) ); }

Target:
`canConnect( server.address(), clientGroup )` can be extracted to a no-params method
Source:
private void notifyLeaderChanges( Outcome outcome ) { LeaderInfo leaderInfo = new LeaderInfo( outcome.getLeader(), outcome.getTerm() ); boolean isStepDown = outcome.isSteppingDown(); if ( isStepDown ) { leaderInfo.stepDown(); } for ( LeaderListener listener : leaderListeners ) { if ( isStepDown ) { listener.onLeaderStepDown( leaderInfo ); } listener.onLeaderSwitch( leaderInfo ); } }

Target:
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.
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 { throw new UnsupportedTemporalUnitException( "Should only attach offsets to local times, not zone ids." ); } } }

Target:
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.
Source:
public static TimeValue parse( CharSequence text, Supplier<ZoneId> defaultZone, CSVHeaderInformation fieldsFromHeader ) { if ( fieldsFromHeader != null ) { if ( !(fieldsFromHeader instanceof TimeCSVHeaderInformation) ) { throw new TemporalParseException( "Wrong header information type: " + fieldsFromHeader ); } // Override defaultZone defaultZone = ((TimeCSVHeaderInformation) fieldsFromHeader).zoneSupplier( defaultZone ); } return parse( TimeValue.class, PATTERN, TimeValue::parse, text, defaultZone ); }

Target:
Same concern as above.
Source:
ZoneId getZoneId() { throw new UnsupportedTemporalUnitException( "Cannot get the timezone of: %s" + this ); }

Target:
Don't you need a `String.format` with the `%s` ?
Source:
private String obsfucateIfSecret( Map.Entry<String,String> param ) { return secrets.contains( param.getKey() ) ? Secret.OBSFUCATED : param.getValue(); }

Target:
There is a `log` inside `updateDynamicSetting` that also should be obfuscated.
Source:
public Register.DoubleLongRegister indexSample( IndexReference index, Register.DoubleLongRegister target ) throws IndexNotFoundKernelException { ktx.assertOpen(); ktx.assertOpen(); return storeReadLayer.indexUpdatesAndSize( SchemaDescriptorFactory.forLabel( index.label(), index.properties() ), target ); }

Target:
It's definitely open now!
Source:
private boolean areSameZone( ZoneId thisZone, ZoneId thatZone ) { boolean thisIsOffset = thisZone instanceof ZoneOffset; boolean thatIsOffset = thatZone instanceof ZoneOffset; if ( thisIsOffset && thatIsOffset ) { return thisZone.equals( thatZone ); } else if ( !thisIsOffset && !thatIsOffset ) { return TimeZones.map( thisZone.getId() ) == TimeZones.map( thatZone.getId() ); } return false; }

Target:
`thisIsOffset` and `thatIsOffset` are already evaluated in `unsafeCompareTo`. Send them in as two boolean parameters to this function instead of evaluating them agan
Source:
private Profile[] findExistingProfiles( List<PagedFile> pagedFiles ) { return pagedFiles.stream() .map( pf -> pf.file().getParentFile() ) .distinct() .flatMap( dir -> Profile.findProfilesInDirectory( fs, dir ) ) .sorted() .toArray( Profile[]::new ); }

Target:
This adds nothing.
Source:
public int nodeDetachDelete( final long nodeId ) throws KernelException { final MutableInt count = new MutableInt(); TwoPhaseNodeForRelationshipLocking locking = new TwoPhaseNodeForRelationshipLocking( relId -> { ktx.assertOpen(); relationshipDelete( relId ); count.increment(); } ); locking.lockAllNodesAndConsumeRelationships( nodeId, ktx ); ktx.assertOpen(); nodeDelete( nodeId ); return count.intValue(); }

Target:
If we are to keep the previous semantic, we should only increment `count` if `relationshipDelete` returns true.
Source:
public synchronized void init0() throws Throwable { localDatabase.init(); }

Target:
you no longer need those methods to be synch right?
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() ) { dispose( channel ); channel = null; } if ( channels.isEmpty() ) { idleChannels.remove( catchUpAddress ); } } return channel; }

Target:
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
Source:
private static PointValue randomPoint( int index, int dimension ) { CoordinateReferenceSystem crs = index % 2 == 0 ? dimension == 2 ? WGS84 : WGS84_3D : dimension == 2 ? Cartesian : Cartesian_3D; return unsafePointValue( crs, random().doubles( dimension, Double.MIN_VALUE, Double.MAX_VALUE ).toArray() ); }

Target:
For increased readability I would prefer the outer `if` to **not** be written with `x ? y : z` notation
Source:
public static PointValue parse( CharSequence text, AnyValue[] fieldsFromHeader ) { 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 ); }

Target:
How about renaming `fieldsFromHeader` to something like `defaultFields` to make it user agnostic?
Source:
public boolean acceptsValue( Value value ) { if ( value == null ) { return false; } if ( value instanceof PointValue ) { PointValue point = (PointValue) value; if ( point.getCRS() == crs ) { return point.withinRange( from, fromInclusive, to, toInclusive ); } } return false; }

Target:
`==` assuming too much? Better with `.equals`?
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 Result result = db().execute( "CYPHER 3.3 MATCH (b) WITH b LIMIT 1 CREATE UNIQUE (b)-[:REL]->()" ); }

Target:
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
Source:
void flipAfterPopulation() { for ( IndexPopulation population : populations ) { try { Thread.sleep( 1000 ); population.flip(); populations.remove( population ); } catch ( Throwable t ) { fail( population, t ); } } }

Target:
yes right, we already too fast lets give a cpu some time to sleep :)
Source:
public static PointValue fromMap( MapValue map ) { AnyValue[] fields = new Value[PointValueField.__MAX_VALUE__.ordinal()]; 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 ); }

Target:
It feels like you could as well use `PointValueField.values().length` and get rid of this `__MAX_VALUE__` altogether.
Source:
public static int countOutgoing( NodeCursor nodeCursor, RelationshipGroupCursor group, int type ) { nodeCursor.relationships( group ); int count = 0; while ( group.next() ) { if ( group.type() == type ) { count += group.outgoingCount() + group.loopCount(); } } return count; }

Target:
We will only encounter the type in one group, so we can return once we found it. Same thing below.
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 ) ) { builder.add( String.format( "%s_%d", wrapper.name(), i ), handler ); } return builder; }

Target:
i always equals 0?
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; return (T) array[cursor]; } }; }

Target:
I don't see how this is an improvement.
Source:
public List<ModifierProtocol> modifierProtocols() { return Collections.unmodifiableList( modifierProtocols ); }

Target:
You could make it unmodifiable already in the constructor.
Source:
public void readKey( PageCursor cursor, RawBytes into, int keySize ) { int offsetBeforeRead = cursor.getOffset(); try { into.bytes = new byte[keySize]; cursor.getBytes( into.bytes ); } catch ( BufferUnderflowException e ) { throw Exceptions.withMessage( e, e.getMessage() + " keySize:" + keySize + " offset: " + offsetBeforeRead + " page size:" + cursor.getCurrentPageSize() ); } }

Target:
Oh, I don't think this debug-catch should be here, should it?
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; if ( pool != null ) { pool.accept( this ); } } }

Target:
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).
Source:
private static TemporalType find( int temporalType ) { if ( temporalType < TYPES.length ) { return TYPES[temporalType]; } else { // Kernel code requires no exceptions in deeper PropertyChain processing of corrupt/invalid data return TEMPORAL_INVALID; } }

Target:
`&& temporalType >= 0` ?
Source:
public final boolean eq( Object other ) { if ( other == null ) { return false; } if ( other instanceof SequenceValue ) { return this.equals( (SequenceValue) other ); } return other instanceof Value && equals( (Value) other ); }

Target:
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.
Source:
public void shutdown() throws IOException { if ( index != null ) { index.close(); } }

Target:
Maybe take the opportunity to set `index = null` here?
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 ) ) { if ( propertyIsAllowed( propertyKeyId ) ) { return dataRead().nodeGetProperty( statement, node.get(), propertyKeyId ); } else { return Values.NO_VALUE; } } }

Target:
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.
Source:
public void run() { List<Throwable> errors = new LinkedList<>(); 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; } }

Target:
please just use arraylist
Source:
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 ); } }

Target:
This was mistakenly moved
Source:
public void setup() { try { folder.create(); 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" ); }

Target:
Can't we just rely on `@Rule`
Source:
public void releaseCursor( Cursor cursor ) { if ( cursorsInUse > 0 ) { if ( TRACK_CURSORS ) { cursorsOpenCloseCalls.remove( cursor ); } cursorsInUse--; } }

Target:
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.
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(); this.single = true; }

Target:
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.
Source:
int length() { return (int) Math.pow( 2, dimension ); }

Target:
Should be final.
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 ) { cursor.setCursorException( "Tried to read key on offset " + keyOffset + ". Page size is " + pageSize ); } // Set cursor to actual offset cursor.setOffset( keyOffset ); }

Target:
PageCursor checks bounds, later propagated in `checkAndClearBoundsFlag()` doesn't it? Do we need to do this specifically here anyway?
Source:
public synchronized void close() { isOpen = false; }

Target:
I don't see any other method that this synchronisation would avoid overlapping with.
Source:
public void setUp() throws Exception { 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(); }

Target:
Checkstyle; missing space at the end there.
Source:
private int readInt( long pageId, int pageOffset ) throws IOException { // Cross-page read? int bytesInCurentPage = pageSize - pageOffset; 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; }

Target:
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.
Source:
public IndexReader newReader() { Map<CoordinateReferenceSystem,IndexReader> indexReaders = new HashMap<>(); for ( Map.Entry<CoordinateReferenceSystem,SpatialKnownIndex> index : indexMap.entrySet() ) { try { indexReaders.put( index.getKey(), index.getValue().getOnlineAccessor(descriptor, samplingConfig).newReader() ); } catch ( IOException e ) { e.printStackTrace(); } } return new SpatialFusionIndexReader( indexReaders, descriptor ); }

Target:
What are the plans for this fellow?
Source:
public void shouldNotGenerateUpdateForMultipleExistingPropertiesAndLabels() { // When NodeUpdates updates = NodeUpdates.forNode( nodeId, labels ) .existing( propertyKeyId1, Values.of( "Neo" ) ) .existing( propertyKeyId2, Values.of( 100L ) ) .existing( propertyKeyId3, Values.of( Values.pointValue( CoordinateReferenceSystem.WGS84, 12.3, 45.6 ) ) ) .build(); // Then assertThat( updates.forIndexKeys( indexes, assertNoLoading() ), emptyIterable() ); }

Target:
Don't need the extra `Values.of` wrap.
Source:
public void close() throws Exception { writer.close(); super.close(); }

Target:
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?
Source:
public boolean labels( String[] labels ) { checkClear(); for ( String label : labels ) { this.labels.add( label ); } return delegate.labels( labels ); }

Target:
`Collections.addAll`
Source:
public boolean append( RecordCursor<RECORD> cursor, RECORD[] array, long id, int index ) { RECORD record = array[index]; if ( !cursor.next( id, record, RecordLoad.CHECK ) || (filter != null && !filter.test( record )) ) { return false; } return true; }

Target:
This can be simplified to return an expression. And the null-check could be avoided by initialising the `filter` field to `Predicates.alwaysTrue` if no filter is otherwise given in the constructor.
Source:
private void recalculatePercent() { int percent = (int) (totalRead * 100 / size); if ( percent > lastReportedPercent ) { lastReportedPercent = percent; listener.onProgress( percent ); } }

Target:
i would add additional check to make sure we will never make it to more then 100 :)
Source:
public void addToArchive( Path archiveDestination, DiagnosticsReporterProgressCallback monitor ) throws IOException { long size = fs.getFileSize( source ); InputStream in = fs.openAsInputStream( source ); // Track progress of the file reading, source might be a very large file ProgressAwareInputStream inStream = new ProgressAwareInputStream( in, size, monitor::percentChanged ); Files.copy( inStream, archiveDestination ); }

Target:
this stream needs to be closed
Source:
public synchronized void stop() throws Throwable { stopped = true; if ( currentJob != null ) { currentJob.stop(); } if ( jobHandle != null ) { jobHandle.cancel( false ); try { jobHandle.waitTermination(); } catch ( CancellationException ignored ) { } } }

Target:
The scheduler is designed to only run one task at the time so this should have no effect. Since it is either currently running or completed.
Source:
protected void sharedOptimisticLock( ResourceType resource, long resourceId ) { ktx.locks().optimistic().acquireShared( ktx.lockTracer(), resource, resourceId ); }

Target:
Can be package private
Source:
void scan( Read read ) { if ( getId() != NO_ID ) { reset(); } if ( pageCursor == null ) { pageCursor = read.nodePage( 0 ); } this.next = 0; this.highMark = read.nodeHighMark(); this.read = read; if ( labelCursor != null ) { labelCursor = read.labelCursor(); } }

Target:
I might be missing something here but shouldn't it be `labelCursor == null`
Source:
public void stop() throws Throwable { if (currentJob != null) { currentJob.stop(); } }

Target:
synchronize this also