auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void writeConfigToFile( Config config, File file ) { try { Writer fileWriter = new BufferedWriter( new FileWriter( file ) ); for ( Map.Entry<String,String> entry : config.getRaw().entrySet() ) { fileWriter.write( String.format( "%s=%s\n", entry.getKey(), entry.getValue() ) ); } fileWriter.close(); } catch ( IOException e ) { e.printStackTrace(); } }

Target:
Does not look like a good handling of exception? should we be able to continue if this fails?
Source:
private String argAdditionalConf( File backupTarget ) { if ( additionalConfig == null ) { return ""; } File configFile = neo4jHomeFromTarget( backupTarget ).resolve( "../additional_neo4j.conf" ).toFile(); writeConfigToFile( additionalConfig, configFile ); return String.format( "--additional-config=%s", configFile ); }

Target:
what is additional_neo4j.conf and why do we need it? how its correlate with other tools behavior?
Source:
public String getHARole() { if (true) return roles.keySet().toString(); // TODO delete this if ( roles.containsKey( HighAvailabilityModeSwitcher.MASTER ) ) { return HighAvailabilityModeSwitcher.MASTER; } if ( roles.containsKey( HighAvailabilityModeSwitcher.SLAVE ) ) { return HighAvailabilityModeSwitcher.SLAVE; } return HighAvailabilityModeSwitcher.UNKNOWN; }

Target:
I think you should address this TODO.
Source:
public void shutdown() { try ( ErrorHandler errorHandler = new ErrorHandler( "Error when trying to shutdown cluster" ) ) { shutdownCoreMembers( errorHandler ); shutdownReadReplicas( errorHandler ); } }

Target:
You switched the order of cores and read replicas here.
Source:
public org.neo4j.internal.kernel.api.Session beginSession( SecurityContext securityContext ) { return new KernelSession( engine, kernel, securityContext ); }

Target:
Java supports covariant return types, so you can make this method return `KernelSession` without breaking the type safety of the interface. Would be easier on the eye.
Source:
public MapValue properties() { MapValue m = properties; if ( m == null ) { synchronized ( propLock ) { m = properties; if ( m == null ) { m = properties = ValueUtils.asMapValue( node.getAllProperties() ); } } } return m; }

Target:
I remember us talking about decoupling synchronization on this class, but when I tried to completely remove synchronization it still didn't solve the regression according to the benchmarks I ran, way back i september or something. Back then I probably messed something up, but I would love to see some benchmark result to confirm this fix!
Source:
public static InFlightCache create( Config config, Monitors monitors ) { Type type = config.get( CausalClusteringSettings.in_flight_cache_type ); switch ( type ) { case NONE: return new VoidInFlightCache(); case CONSECUTIVE: return new ConsecutiveInFlightCache( config.get( in_flight_cache_max_entries ), config.get( in_flight_cache_max_bytes ), monitors.newMonitor( InFlightCacheMonitor.class ), false ); case UNBOUNDED: return new UnboundedInFlightCache(); default: throw new IllegalArgumentException( "Unrecognized type" ); } }

Target:
This logic could be included in the enum as an overridden method
Source:
public boolean equals( Value value ) { if ( value instanceof org.neo4j.values.storable.UTF8StringValue ) { return Arrays.equals( bytes, ((org.neo4j.values.storable.UTF8StringValue) value).bytes ); } else { return super.equals( value ); } }

Target:
It seems strange that we would need a fully qualified name here.
Source:
static GeometryHeader fromArrayHeaderBytes( byte[] header ) { int geometryType = Byte.toUnsignedInt( header[1] ); int dimension = Byte.toUnsignedInt( header[2] ); int crsTableId = Byte.toUnsignedInt( header[3] ); int crsCode = Byte.toUnsignedInt( header[5] ) + (Byte.toUnsignedInt( header[4] ) << 8); return new GeometryHeader( geometryType, dimension, crsTableId, crsCode ); }

Target:
can we please update line to "(Byte.toUnsignedInt( header[4] ) << 8) + Byte.toUnsignedInt( header[5] ) "
Source:
public static CoordinateReferenceSystem get( String href ) { if ( CoordinateReferenceSystem.WGS84.href.equals( href ) ) { return CoordinateReferenceSystem.WGS84; } else if ( CoordinateReferenceSystem.Cartesian.href.equals( href ) ) { return CoordinateReferenceSystem.Cartesian; } else { throw new UnsupportedOperationException( "Unknown CRS: " + href ); } }

Target:
would say that its more illegal argument
Source:
public synchronized Group get( String name ) { boolean global = name == null; if ( globalMode != null && global != globalMode.booleanValue() ) { throw mixingOfGroupModesException(); } if ( name == null ) { return Group.GLOBAL; } Group group = byName.get( name ); if ( group == null ) { throw new HeaderException( "Group '" + name + "' not found. Available groups are: " + groupNames() ); } return group; }

Target:
`.booleanValue()` is not needed
Source:
public void shouldFailOnMixedGroupModeInGetOrCreate() throws Exception { // given Groups groups = new Groups(); groups.getOrCreate( null ); try { // when groups.getOrCreate( "Something" ); fail( "Should fail" ); } catch ( IllegalStateException e ) { // then OK } }

Target:
Would prefer to have expected exceptions in the added tests since nothing is invoked after the throw.
Source:
private void lockAllNodes( KernelStatement state, long[] nodeIds ) { for ( long nodeId : nodeIds ) { state.locks().optimistic().acquireExclusive( state.lockTracer(), ResourceTypes.NODE, nodeId ); } }

Target:
You could use one call since the id argument is a vararg
Source:
public void shouldCheckpointEvenIfNoChanges() throws Exception { // GIVEN CheckpointCounter checkpointCounter = new CheckpointCounter(); // WHEN try ( GBPTree<MutableLong,MutableLong> index = index().with( checkpointCounter ).build() ) { checkpointCounter.reset(); for ( int i = 0; i < 2; i++ ) { } index.checkpoint( unlimited() ); // THEN assertEquals( 1, checkpointCounter.count() ); } }

Target:
Empty loop
Source:
static final File baseSchemaIndexFolder( File databaseStoreDir ) { return path( databaseStoreDir, "schema", "index" ); }

Target:
Does not need to be final.
Source:
public RenewableBatchIdSequence( IdSequence source, int batchSize, LongConsumer excessIdConsumer ) { this.source = source; this.batchSize = batchSize; this.excessIdConsumer = excessIdConsumer; }

Target:
constructor can be package private
Source:
public void release( T obj ) { // Return it locally if possible LocalSlot<T> localSlot = puddle.get(); if ( localSlot.release( obj ) ) { // It was released back into the slot } else { // Fall back to the delegate pool pool.release( obj ); } }

Target:
``` if ( !localSlot.release( obj ) ) { // Fall back to the delegate pool pool.release( obj ); } ```
Source:
public RecoveryApplier getRecoveryApplier( TransactionApplicationMode mode ) throws Exception { transactionsToApply = new TransactionQueue( 100, ( first, last ) -> storageEngine.apply( first, mode ) ); return new RecoveryVisitor( transactionsToApply ); }

Target:
we don't need `transactionsToApply` as field anymore
Source:
public GivenTransactionCursor( CommittedTransactionRepresentation... transactions ) { this.transactions = transactions; }

Target:
can be `private`
Source:
public TestGraphDatabaseFacadeFactory( TestGraphDatabaseFactoryState state, boolean impermanent ) { this( state, impermanent, DatabaseInfo.COMMUNITY, CommunityEditionModule::new ); }

Target:
`protected` is enough
Source:
public UpdateCapturingIndexProvider( SchemaIndexProvider actual, Map<Long,Collection<IndexEntryUpdate>> initialUpdates ) { super( actual.getProviderDescriptor(), actual.priority() ); this.actual = actual; this.initialUpdates = initialUpdates; }

Target:
A copy constructor in `SchemaIndexProvider` might be more appropriate than having a public getter method
Source:
public Statement apply( Statement base, Description description ) { Repeat repeat = description.getAnnotation( Repeat.class ); if ( repeat != null || defaultTimes > 1 ) { return new RepeatStatement( max( repeat != null ? repeat.times() : 1, defaultTimes ), base, description ); } return base; }

Target:
I would expect that the annotation would overrule the default, even if it is smaller.
Source:
public Stream<BooleanResult> nodeManualIndexExists( @Name( "indexName" ) String legacyIndexName ) { BooleanResult result = new BooleanResult( graphDatabaseAPI.index().existsForNodes( legacyIndexName ) ); ArrayList<BooleanResult> arrayResult = new ArrayList<>(); arrayResult.add( result ); return arrayResult.stream(); }

Target:
Better use `Stream#of()` everywhere to convert single element to stream.
Source:
public Stream<BooleanResult> nodeManualIndexAdd( @Name( "indexName" ) String legacyIndexName, @Name( "node" ) Node node, @Name( "key" ) String key, @Name( "value" ) Object value ) { graphDatabaseAPI.index().forNodes( legacyIndexName ).add( node, key, value ); List<BooleanResult> results = new ArrayList<>( 1 ); results.add( new BooleanResult( true ) ); return results.stream(); }

Target:
Stream.of
Source:
private PrimitiveLongIterator partitionedOperation( Function<ReadOnlyFulltext,PrimitiveLongIterator> readerFunction ) { return PrimitiveLongCollections.concat( indexReaders.parallelStream().map( readerFunction::apply ).collect( Collectors.toList() ) ); }

Target:
you can use readerFunction directly here, without apply
Source:
public void dispatch( DummyRequest dummyRequest, long commandIndex, Consumer<Result> callback ) { if ( benchmarkMachine != null ) { benchmarkMachine.applyCommand( dummyRequest, commandIndex, callback ); } }

Target:
If `benchmarkMachine` may be null, then perhaps it should be an `Optional<BenchmarkMachine>`
Source:
public void shouldRunRecurringJob() throws Throwable { // Given long period = 100; int count = 5; life.start(); // When scheduler.scheduleRecurring( indexPopulation, countInvocationsJob, period, MILLISECONDS ); awaitFirstInvocation(); // Alright it's running now. Let's await all the invocations to take place awaitInvocationCount( count ); scheduler.shutdown(); // Then assert that the recurring job was stopped (when the scheduler was shut down) int actualInvocations = invocations.get(); sleep( period * 2 ); assertThat( invocations.get(), equalTo( actualInvocations ) ); }

Target:
Can remove this call because of `awaitInvocationCount( count )` below.
Source:
public void failIfUnknownSetting() throws Exception { expect.expect( new NestedThrowableMatcher( IllegalArgumentException.class ) ); expect.expectMessage( "Unknown setting: unknown.setting.indeed" ); db.execute( "CALL dbms.setConfigValue('unknown.setting.indeed', 'foo')" ); fail( "Should throw IllegalArgumentException" ); }

Target:
you do not need those fail in the end of the test since `ExpectedException` will throw an exception if expected error was not thrown and will fail the test (same for other tests)
Source:
private void flushAll() { populations.forEach( population -> flush( population, population.takeCurrentBatch() ) ); }

Target:
there is no need to pass second param here since population is already passed as first one
Source:
public static <T> long count( Iterable<T> iterable, Predicate<T> filter ) { try ( ResourceIterator<T> iterator = Iterators.asResourceIterator( iterable.iterator() ) ) { return Iterators.count( iterator, filter ); } }

Target:
Instead of wrapping in a resource iterator, which is potentially one unnecessary object instantiation, couldn't we just do the usual check of `Resource` in `finally`?
Source:
ResultRowImpl( ) { this( new HashMap<>() ); }

Target:
Formatting?
Source:
public static PathValue path( NodeValue[] nodes, EdgeValue[] edges ) { assert nodes != null; assert edges != null; if ( nodes.length + edges.length % 2 == 0 ) { throw new IllegalArgumentException( "Tried to construct a path that is not built like a path: even number of elements" ); } return new PathValue( nodes, edges ); }

Target:
you want `if ( ( nodes.length + edges.length ) % 2 == 0 )` or maybe `nodes.length != edges.length + 1`?
Source:
public LongArray newLongArray( long length, long defaultValue, long base ) { // Here we want to have the property of a dynamic array which makes some parts of the array // live on heap, some off. At the same time we want a fixed size array. Therefore first create // the array as a dynamic array and make it grow to the requested length. LongArray array = newDynamicLongArray( fractionOf( length ), defaultValue ); array.at( length - 1 ); return array; }

Target:
rely on side effects of magic `at`?
Source:
public PageCacheByteArray( PagedFile pagedFile, long length, byte[] defaultValue, long base ) throws IOException { // '0' default value means we skip filling it out in super super( pagedFile, defaultValue.length, length, 0, base ); this.defaultValue = defaultValue; setDefaultValue( -1 ); }

Target:
and why not to pass -1 directly here as a default value?
Source:
public PageCachedNumberArrayFactory( PageCache pageCache, File storeDir ) { this.pageCache = pageCache; this.storeDir = storeDir; }

Target:
this can be package private
Source:
public PageCacheLongArray( PagedFile pagedFile, long length, long defaultValue, long base ) throws IOException { super( pagedFile, Long.BYTES, length, defaultValue, base ); }

Target:
package private constructor here as well
Source:
protected int offset( long index ) { return toIntExact( rebase( index ) % entriesPerPage ) * entrySize; }

Target:
whole expression should be wrapped into `toIntExact` not only `rebase( index ) % entriesPerPage`
Source:
public static Fixture prepareDirectoryAndPageCache( Class<?> testClass ) throws IOException { DefaultFileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction(); TestDirectory testDirectory = TestDirectory.testDirectory( testClass, fileSystem ); File dir = testDirectory.prepareDirectoryForTest( "test" ); fileSystem.mkdirs( dir ); PageCache pageCache = StandalonePageCacheFactory.createPageCache( fileSystem ); return new Fixture( pageCache, fileSystem, dir ); }

Target:
you don't need to do it, testDirectory does that for you already
Source:
public void moveMigratedFiles( File migrationDir, File storeDir, String versionToUpgradeFrom, String versionToMigrateTo ) throws IOException { if ( deleteObsoleteIndexes ) { deleteIndexes( schemaIndexDirectory ); } deleteIndexes( LuceneLabelScanDirectory.getLuceneStoreDirectory( storeDir ) ); }

Target:
This will gonna delete old label scan store if that was used which is a nice thing. In the same time, we will not gonna create the new index as part of migration for those guys and people will be forced to wait during the startup, while they expecting everything is ready to fly. I know that proposed behaviour differs from how it was before at the same time that is something we had complaints in the recent past and as well it sounds like a correct thing to do. WDYT?
Source:
public final boolean equals( Object other ) { if ( other == null ) { return false; } // suppose that we will only ever call equals with Objects of AnyValue but just in case try { if ( ((AnyValue) other).isSequenceValue() && this.isSequenceValue() ) { return ((SequenceValue) this).equals( (SequenceValue) other ); } return other instanceof VirtualValue && equals( (VirtualValue) other ); } catch ( ClassCastException e ) { return false; } }

Target:
doing ``` try { (AnyValue) other) } catch ( ClassCastException e ) { return false } ``` is much more slower and not that easy to read compared to using instanceOf operator, so would suggest here to use instanceOf AnyValue instead. This also applies to ArrayValue `equals`
Source:
private File findFile( String targetFile, File directory ) { File foundFile = null; boolean didFindFile = false; for ( File file : directory.listFiles() ) { if ( file.getName().equals( targetFile ) ) { foundFile = file; didFindFile = true; break; } } if ( !didFindFile ) { fail( "Could not find file " + targetFile ); } return foundFile; }

Target:
maybe something like this instead? ``` File file = new File( directory, targetFile ); if (!file.exists()) { fail( "Could not find file " + targetFile ); } return file; ```
Source:
public void reset() { initCalled = rebuildingCalled = rebuiltCalled = noIndexCalled = corruptedIndex = false; }

Target:
please use separate lines
Source:
public boolean equals( VirtualValue other ) { if ( other == null || !(other instanceof PathValue) ) { return false; } PathValue that = (PathValue) other; return size() == that.size() && Arrays.equals( nodes, that.nodes ) && Arrays.equals( edges, that.edges ); }

Target:
same here, redundant?
Source:
public NodeCountsProcessor( NodeStore nodeStore, NodeLabelsCache cache, int highLabelId, CountsAccessor.Updater counts, MigrationProgressMonitor.Section progressMonitor ) { this.nodeStore = nodeStore; this.cache = cache; this.anyLabel = highLabelId; this.counts = counts; // Instantiate with high id + 1 since we need that extra slot for the ANY count this.labelCounts = new long[highLabelId + 1]; this.progressMonitor = progressMonitor; }

Target:
This one can be package-private and the other constructor is not used by anyone and can be removed.
Source:
public void releaseShared( ResourceType resourceType, long... resourceIds ) { stateHolder.incrementActiveClients( this ); try { PrimitiveLongObjectMap<LockResource> localLocks = localShared( resourceType ); for ( long resourceId : resourceIds ) { LockResource resource = localLocks.get( resourceId ); if ( resource.releaseReference() != 0 ) { return; } localLocks.remove( resourceId ); manager.releaseReadLock( new LockResource( resourceType, resourceId ), lockTransaction ); } } finally { stateHolder.decrementActiveClients(); } }

Target:
Do we not want to try releasing any remaining resources after the first failure? I don't know, maybe this will terminate the transaction and release everything anyway, just noting this observation.
Source:
public void accept( PageCursor cursor ) { byte[] bytesToWrite = failureBytes; cursor.putByte( NativeSchemaNumberIndexPopulator.BYTE_FAILED ); int availableSpace = cursor.getCurrentPageSize() - cursor.getOffset(); if ( bytesToWrite.length + HEADER_LENGTH_FIELD_LENGTH > availableSpace ) { bytesToWrite = Arrays.copyOf( bytesToWrite, availableSpace - 2 ); } cursor.putShort( (short) bytesToWrite.length ); cursor.putBytes( bytesToWrite ); }

Target:
you can't just fix all magic 2 :)
Source:
public void freeId( long id ) { if ( freeIdCondition.getAsBoolean() ) { idContainer.freeId( id ); } }

Target:
Do we have a feel for the probability of ending up here, and the condition is false?
Source:
public void freeId( long id ) { idContainer.freeId( id ); }

Target:
`IdGeneratorImpl` protects its `IdContainer` by making its methods `synchronized`. This class does not do that, so does this not expose the `IdContainer` to concurrency that it is not prepared to handle?
Source:
public boolean equals( Object other ) { return false; }

Target:
replace with `return this == other;`
Source:
public boolean equals( Value other ) { return false; }

Target:
replace with `return this == other;`
Source:
public static Lifecycle multiple( Lifecycle... lifecycles ) { return new CombinedLifecycle( Arrays.asList( lifecycles ) ); }

Target:
We can reuse `multiple( Iterable lifecycles )` here.
Source:
public WrappingFileHandle( File file, File baseDirectory, FileSystemAbstraction fs ) { this.file = file; this.baseDirectory = baseDirectory; this.fs = fs; }

Target:
Checkstyle says this `public` modifier is redundant.
Source:
protected void process( Void batch, BatchSender sender ) throws Throwable { System.out.println( Thread.currentThread().getName() + " process" ); latch.await(); }

Target:
Oops.
Source:
private static Long parseMaxMemory( String maxMemoryString ) { if ( maxMemoryString != null ) { if ( maxMemoryString.endsWith( "%" ) ) { int percent = Integer.parseInt( maxMemoryString.substring( 0, maxMemoryString.length() - 1 ) ); return calculateMaxMemoryFromPercent( percent ); } return Settings.parseLongWithUnit( maxMemoryString ); } return null; }

Target:
we at least need to trim user provided string before trying to figure out what is inside of it
Source:
public static long calculateMaxMemoryFromPercent( int percent ) { if ( percent < 1 ) { throw new IllegalArgumentException( "Expected percentage to be > 0, was " + percent ); } if ( percent > 100 ) { throw new IllegalArgumentException( "Expected percentage to be < 100, was " + percent ); } long freePhysicalMemory = OsBeanUtil.getFreePhysicalMemory(); if ( freePhysicalMemory == OsBeanUtil.VALUE_UNAVAILABLE ) { throw new UnsupportedOperationException( "Unable to detect amount of free memory, so max memory has to be explicitly set" ); } double factor = percent / 100D; return round( (freePhysicalMemory - Runtime.getRuntime().maxMemory()) * factor ); }

Target:
there is no need to declare it `public`
Source:
public static boolean tryWriteLock( long address ) { long s, n; for (; ; ) { s = getState( address ); boolean unwritablyLocked = (s & EXL_MASK) != 0; boolean writeCountOverflow = (s & CNT_MASK) == CNT_MASK; // bitwise-OR to reduce branching and allow more ILP if ( unwritablyLocked | writeCountOverflow ) { return failWriteLock( s, writeCountOverflow ); } n = s + CNT_UNIT | MOD_MASK; if ( compareAndSetState( address, s, n ) ) { UnsafeUtil.storeFence(); return true; } } }

Target:
Just because the code resembles C doesn't mean that you have to adopt horrendous naming standards ;)
Source:
public void init() throws IOException { monitor.init(); boolean storeExists = hasStore(); boolean isDirty; try { needsRebuild = !storeExists; if ( !storeExists ) { monitor.noIndex(); } isDirty = instantiateTree(); } catch ( MetadataMismatchException e ) { // GBPTree is corrupt. Try to rebuild. isDirty = true; } if ( isDirty ) { monitor.notValidIndex(); dropStrict(); instantiateTree(); } if ( isDirty || !storeExists ) { needsRebuild = true; } }

Target:
The `|| !storeExists` part is covered by the `needsRebuild = !storeExists;` further up, is it not?
Source:
public void close() throws IOException { writerCheckpointMutex.lock(); try { if ( closed ) { return; } closed = true; // Force close on writer to not risk deadlock on pagedFile.close() writer.close(); pagedFile.close(); } finally { writerCheckpointMutex.unlock(); } }

Target:
isn't that unexpected thing to have a flag that say that index is closed to be raised before it's actually is?
Source:
public IndexMap( Map<Long, IndexProxy> indexesById ) { this( indexesById, indexesByDescriptor( indexesById ), indexIdsByDescriptor( indexesById ) ); }

Target:
this could fit on a single line...
Source:
public static <E extends Exception> void assertException( ThrowingAction<E> f, Class typeOfException ) throws Exception { try { f.apply(); fail( "Expected exception of type " + typeOfException + ", but no exception was thrown" ); } catch ( Exception e ) { if ( !typeOfException.isInstance( e ) ) { fail( "Got unexpected exception " + e.getClass() + "\nExpected: " + typeOfException ); } } }

Target:
isn't it copy paste mostly of another assertException method? why not reused that?
Source:
protected ConstraintDescriptor readNonStandardConstraint( ConstraintRule rule, String errorMessage ) { if ( !rule.getConstraintDescriptor().type().enforcesPropertyExistence() ) { throw new IllegalStateException( "Unsupported constraint type: " + rule ); } return rule.getConstraintDescriptor(); }

Target:
Do we really need to check anything here? Surely the enterprise edition supports all constraints?
Source:
private int[] propertyKeyIds() { return populations.keySet().stream().flatMapToInt( this::propertyKeyIds ).distinct().toArray(); }

Target:
This method is actually pretty inefficient, it is only ever used together with `labelIds()`, it would be better to just have a single for-loop build both arrays at once, the streams just add overhead.
Source:
public static boolean nodeHasSchemaProperties( PrimitiveIntObjectMap<PropertyBlock> nodePropertyMap, int[] indexPropertyIds ) { for ( int indexPropertyId : indexPropertyIds ) { if ( !nodePropertyMap.containsKey( indexPropertyId ) ) { return false; } } return true; }

Target:
this method can be private now right?
Source:
private NewIndexDescriptor getIndex( int labelId, int propertyKeyId, IndexSpecifier index ) throws ProcedureException { try { final int labelId1 = labelId; final int[] propertyKeyIds = new int[]{propertyKeyId}; return operations.indexGetForLabelAndPropertyKey( SchemaDescriptorFactory.forLabel( labelId1, propertyKeyIds ) ); } catch ( SchemaRuleNotFoundException e ) { throw new ProcedureException( Status.Schema.IndexNotFound, e, "No index on %s", index ); } }

Target:
`getPropertyIds()` as above
Source:
public static String[] getPropertyKeys( ReadOperations readOperations, LabelSchemaDescriptor descriptor ) throws PropertyKeyIdNotFoundKernelException { int[] propertyKeyIds = false ? descriptor.getPropertyIds() : new int[]{descriptor.getPropertyId()}; String[] propertyKeys = new String[propertyKeyIds.length]; for ( int i = 0; i < propertyKeyIds.length; i++ ) { propertyKeys[i] = readOperations.propertyKeyGetName( propertyKeyIds[i] ); } return propertyKeys; }

Target:
Whaat?
Source:
public static String[] getPropertyKeys( TokenNameLookup tokenNameLookup, LabelSchemaDescriptor descriptor ) { int[] propertyKeyIds = false ? descriptor.getPropertyIds() : new int[]{descriptor.getPropertyId()}; String[] propertyKeys = new String[propertyKeyIds.length]; for ( int i = 0; i < propertyKeyIds.length; i++ ) { propertyKeys[i] = tokenNameLookup.propertyKeyGetName( propertyKeyIds[i] ); } return propertyKeys; }

Target:
Whaat 2
Source:
private NewIndexDescriptor findAnyIndexByLabelAndProperty( ReadOperations readOps, int propertyId, int labelId ) { try { final int labelId1 = labelId; final int[] propertyKeyIds = new int[]{propertyId}; NewIndexDescriptor descriptor = readOps.indexGetForLabelAndPropertyKey( SchemaDescriptorFactory.forLabel( labelId1, propertyKeyIds ) ); if ( readOps.indexGetState( descriptor ) == InternalIndexState.ONLINE ) { // Ha! We found an index - let's use it to find matching nodes return descriptor; } } catch ( SchemaRuleNotFoundException | IndexNotFoundKernelException e ) { // If we don't find a matching index rule, we'll scan all nodes and filter manually (below) } return null; }

Target:
`getPropertyIds`
Source:
public void createLabelAndProperty() throws Exception { TokenWriteOperations tokenWrites = tokenWriteOperationsInNewTransaction(); labelId = tokenWrites.labelGetOrCreateForName( LABEL ); propertyKeyId = tokenWrites.propertyKeyGetOrCreateForName( PROPERTY_KEY ); final int labelId1 = labelId; final int[] propertyKeyIds = new int[]{propertyKeyId}; descriptor = SchemaDescriptorFactory.forLabel( labelId1, propertyKeyIds ); commit(); }

Target:
Another one
Source:
public PopulationProgress indexGetPopulationProgress( LabelSchemaDescriptor descriptor ) throws IndexNotFoundKernelException { return indexService.getIndexProxy( NewIndexDescriptorFactory.forSchema( descriptor ) ).getIndexPopulationProgress(); }

Target:
This is only called for general indexes, because unique index population is synchronous?
Source:
private boolean isIgnoringSomething() { return ignoreBadRelationships | ignoreDuplicateNodes | ignoreExtraColumns; }

Target:
Is there a reason why you want to do bitwise OR here instead of `||` Did you want to explicitly avoid short-circuiting?
Source:
public void exceptionWhenStartingNewTransactionOnShutdownInstance() throws Throwable { KernelTransactions kernelTransactions = newKernelTransactions(); SecurityContext securityContext = mock( SecurityContext.class ); availabilityGuard.shutdown(); t2.execute( (OtherThreadExecutor.WorkerCommand<Void,Void>) state -> { stopKernelTransactions( kernelTransactions ); return null; } ); expectedException.expect( DatabaseShutdownException.class ); kernelTransactions.newInstance( KernelTransaction.Type.explicit, securityContext, 0L ); }

Target:
Won't this exception now be racing with the worker thread started above, now that you removed the `get` on the future?
Source:
public String evidenceMessage( TokenNameLookup tokenNameLookup, LabelSchemaDescriptor schema ) { assert schema.getPropertyIds().length == propertyValues.values().length; String labelName = tokenNameLookup.labelGetName( schema.getLabelId() ); if ( addedNodeId == NO_SUCH_NODE ) { return format( "Node(%d) already exists with label `%s` and %s", existingNodeId, labelName, propertyString( tokenNameLookup, schema.getPropertyIds() ) ); } else { return format( "Both Node(%d) and Node(%d) have the label `%s` and %s", existingNodeId, addedNodeId, labelName, propertyString( tokenNameLookup, schema.getPropertyIds() ) ); } }

Target:
since we already have a specific value object for property values i think it's super strange that we fall back to backing array to get that would propose to have propertyValues.size() method instead
Source:
public Object getSinglePropertyValue() { assert propertyValues.values().length == 1; return propertyValues.values()[0]; }

Target:
also here why not provide method to get single method in helper class
Source:
private void setValues( Object... values ) { removeAllValueFields(); for ( int i = 0; i < values.length; i++ ) { ValueEncoding encoding = ValueEncoding.forValue( values[i] ); Field reusableField = getFieldWithValue( i, "composite", encoding, values[i] ); document.add( reusableField ); } }

Target:
Keeping existing indexes working? 👍
Source:
private void setValues( Object... values ) { if( values.length == 1 ) { setValue( values[0] ); return; } removeAllValueFields(); for ( int i = 0; i < values.length; i++ ) { ValueEncoding encoding = ValueEncoding.forValue( values[i] ); Field reusableField = getFieldWithValue( i, "composite", encoding, values[i] ); document.add( reusableField ); } }

Target:
Aha, _this_ is how single-property indexes retain their format. Very good.
Source:
private void insert( Collection<PropertyValue> data ) throws IOException { PropertyValue[] dataArray = data.toArray( new PropertyValue[data.size()] ); for ( int i = 0; i < dataArray.length; i++ ) { Document doc = LuceneDocumentStructure.documentRepresentingProperties( (long) i, dataArray[i].value ); index.getIndexWriter().addDocument( doc ); } index.maybeRefreshBlocking(); }

Target:
Why this cast to `long`? It should automatically coerce. Similarly in `SimpleUniquenessVerifierTest`. Not a big issue, though.
Source:
private Object[] arraysOfDepth( int n ) { return n == 0 ? new Object[]{"hej"} : arraysOfDepth( n-1 ); }

Target:
This doesn't wrap or nest any arrays. It just returns the array at the recursion base case.
Source:
public KeyValueFileReader(final File keyValueFile) { try { this.reader = new BufferedReader(new FileReader(keyValueFile)); this.fileName = keyValueFile.getName(); } catch (FileNotFoundException ex) { throw new OsmosisRuntimeException("Unable to read from key.value file " + fileName + ".", ex); } }

Target:
The conversion to OsmosisRuntimeExceptions should happen in the task itself, not in the helper class (as someone might use that helper class in an unrelated context).
Source:
private File getLogsRoot() { final String overriddenLogsRoot = System.getProperty("hudson.triggers.SafeTimerTask.logsTargetDir"); if (overriddenLogsRoot == null) { return new File(Jenkins.get().getRootDir(), "logs"); } else { return new File(overriddenLogsRoot); } }

Target:
Maybe the common stuff could be moved into a utility class or something that avoids repeated code.
Source:
public DirectoryComponent(String includes, String excludes, boolean defaultExcludes, int maxDepth) { setExcludes(excludes); setIncludes(includes); setDefaultExcludes(defaultExcludes); setMaxDepth(maxDepth); }

Target:
No super?
Source:
private static Set<String> getAllAsciiCharacters() { final int SPACE = ' '; //20 final int TILDE = '~'; //126 Set<String> singleChars = new HashSet<>(TILDE - SPACE + 1); for (int i = SPACE; i <= TILDE; i++) { singleChars.add(Character.toString((char) i)); } return singleChars; }

Target:
```suggestion for (char i = SPACE; i <= TILDE; i++) { ``` Can you do that? Can remove need for casting below, and can make SPACE and TILDE chars.
Source:
public abstract void writeTo(OutputStream os, ContentFilter filter) throws IOException; @Override public boolean shouldBeFiltered() { return false; }

Target:
Could this be declared final?
Source:
public void addContents(@NonNull Container container) { Jenkins j = Jenkins.getActiveInstance(); addUnixContents(container, j); for (Node node : j.getNodes()) { addUnixContents(container, node); } }

Target:
:NIT: should be part of a different PR (I assume it's safe to use and should just get rid of the helper version and just use the one in the `Jenkins` class.
Source:
public static String isRetrospectiveVisit(Visit visit) { String retrospective = "false"; for (Encounter e : visit.getEncounters()) { if (e.getEncounterType().getUuid().equals(MetadataConstants.HIV_RETROSPECTIVE_ENCOUNTER_TYPE_UUID)) { retrospective = "true"; break; } } return retrospective; }

Target:
This should be a boolean... no reason to use Strings
Source:
public FileSystemWatcher createFileSystemWatcher(String name, OptionMap options) { boolean useWatchService = options.get(Options.USE_WATCH_SERVICE, true); boolean daemonThread = options.get(Options.THREAD_DAEMON, true); if(useWatchService) { try { return new WatchServiceFileSystemWatcher(name, daemonThread); } catch (LinkageError e) { //ignore } } int pollInterval = options.get(Options.WATCHER_POLL_INTERVAL, 5000); return new PollingFileSystemWatcher(name, pollInterval, daemonThread); }

Target:
here you'd delegate up to super.createFileSystemWatcher()
Source:
private static String urlEncode(String s) { try { return URLEncoder.encode(s, Charsets.UTF_8.name()) .replace("+", "%20").replace("*", "%2A").replace("%7E", "~"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // should not happen } }

Target:
How about we switch this to `.replace("+", "%20")` as it appears the only problematic character is the space.
Source:
public Subscriptions getSubscriptions(final SubscriptionState state, final QueryParams params) { if (state != null) params.put("state", state.getType()); return doGET(Subscriptions.SUBSCRIPTIONS_RESOURCE, Subscriptions.class, params); }

Target:
Nit: explicit braces.
Source:
public int hashCode() { return Objects.hash( account, plan, uuid, unitAmountInCents, currency, quantity, activatedAt, canceledAt, expiresAt, currentPeriodStartedAt, currentPeriodEndsAt, trialStartedAt, trialEndsAt, addOns, pendingSubscription, startsAt, collectionMethod, netTerms, poNumber ); }

Target:
Odd that state was left out? We should re-introduce it.
Source:
protected void refreshInputKinds() { List<String> basePath = new ArrayList<String>(); Set<InputKind> kinds = assembleInputKindSet(basePath); this.inputKinds.clear(); this.inputKinds.addAll(kinds); }

Target:
Could this be private?
Source:
public InputKind(String relpath, Class inputClass) { this( relpath, inputClass, relpath.contains("data/inputs") ? relpath.substring(relpath.indexOf("data/inputs") + 12) : relpath ); }

Target:
Nit: Unnecessary extra level of indentation.
Source:
public InputKind(String relpath, Class inputClass, String kind) { this.relpath = relpath; this.inputClass = inputClass; this.kind = kind; knownKinds.put(kind, this); }

Target:
Definitely SDK-internal. Package access please.
Source:
public InputKind(String relpath, Class inputClass) { this( relpath, inputClass, Util.substringAfter(relpath, "data/inputs/", relpath) ); }

Target:
Probably want this to be package access as well. Every other entity constructor is.
Source:
public String getBucketRebuildMemoryHint() throws OperationNotSupportedException { if (this.service.versionCompare("5.0") < 0) { // We're on 4.x, which doesn't support this. throw new OperationNotSupportedException("bucketRebuildMemoryHint unavailable before Splunk 5.0"); } else { return getString("bucketRebuildMemoryHint"); } }

Target:
When migrating to use UnsupportedOperationException, please remove the throws clauses on the method declarations. UOE is a runtime exception so the clauses are not necessary.
Source:
private String getStoriesId() { Stories stories = getAnnotation(Stories.class); if(stories == null || stories.id().isEmpty()) { return null; } else { return stories.id(); } }

Target:
Mmm.. I guess you need 3 checks then: `if(stories == null || stories.id() == null || stories.id().isEmpty())`
Source:
public String getIgnoredMessage(Description description) { Ignore ignore = description.getAnnotation(Ignore.class); return ignore == null ? "Test ignored (without reason)!" : ignore.value(); }

Target:
think you should add it as method somewhere
Source:
private void logError(LifecycleListener listener, Exception e) { logger.error("Error for listener " + listener, e); }

Target:
maybe get class of listener?
Source:
private static void copy(JarFile jar, JarEntry from, File to) throws IOException { InputStream is = jar.getInputStream(from); FileOutputStream os = new FileOutputStream(to); IOUtils.copy(is, os); os.close(); is.close(); }

Target:
may be try-with-resources?
Source:
private static void copy(JarFile jar, JarEntry from, File to) throws IOException { InputStream is = null; FileOutputStream os = null; try { is = jar.getInputStream(from); os = new FileOutputStream(to); IOUtils.copy(is, os); } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } }

Target:
if jar not null, all be ok. Read the link ive wrote
Source:
public static String getMessageMask(String message) { return message.replaceAll("\\s\\d+\\s", " {number} ").replaceAll("\\s+", " "); }

Target:
а что потом происходит с `{number}`?
Source:
public void register() { if (!registered.get() && registered.compareAndSet(false, true)) { DubboShutdownHook dubboShutdownHook = getDubboShutdownHook(); Runtime.getRuntime().addShutdownHook(dubboShutdownHook); dispatch(new DubboShutdownHookRegisteredEvent(dubboShutdownHook)); ShutdownHookCallbacks.INSTANCE.addCallback(() -> { // backward compatibility: make sure shutdown logic takes effect when DubboBootstrap is not used. AbstractRegistryFactory.destroyAll(); this.destroyProtocols(); }); } }

Target:
If `DubboBootstrap` is enabled, will it also register the `DubboShutdownHook` and repeatedly call these destroy operations?
Source:
private void log(String accessLog, AccessLogData accessLogData) { Set<AccessLogData> logSet = LOG_ENTRIES.computeIfAbsent(accessLog, k -> new ConcurrentHashSet<>()); if (logSet.size() >= LOG_MAX_BUFFER) { logSet.add(accessLogData); } else { logger.warn("AccessLog buffer is full. Do a force writing to file to clear buffer."); //just write current logSet to file. writeLogSetToFile(accessLog, logSet); //after force writing, add accessLogData to current logSet logSet.add(accessLogData); } }

Target:
Shouldn't this comparator be "<", which means we can only add new item to logSet when it's size does not exceed `LOG_MAX_BUFFER `?
Source:
public static boolean isValidGenericValue(String generic) { return isGeneric(generic) || Boolean.FALSE.toString().equals(generic); }

Target:
Boolean.FALSE.toString() need to ignore upcase?
Source:
protected void updatePortIfAbsent(Integer value) { if (value != null && port == null) { this.port = value; } }

Target:
change to `if (value != null && value > 0 && port == null) {`
Source:
private void putPropertyIfAbsent(URL url, Properties properties, String propertyName) { String propertyValue = url.getParameter(propertyName); if (propertyValue != null && propertyValue.length() != 0) { properties.setProperty(propertyName, propertyValue); } }

Target:
perhaps you need to `trim` first ?
Source:
private NacosConfigListener createTargetListener(String key, String group) { String normalizedKey = normalizedKey(key); NacosConfigListener configListener = new NacosConfigListener(); configListener.fillContext(normalizedKey, group); return configListener; }

Target:
duplicate call of `normalizedKey(key)`, the caller of createTargetListener() has already called the same method, so the key passed in is a normalized one.
Source:
public void run(Timeout timeout) { DefaultFuture future = DefaultFuture.getFuture(requestID); if (future.isDone()) { return; } // create exception response. Response timeoutResponse = new Response(future.getId()); // set timeout status. timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT); timeoutResponse.setErrorMessage(future.getTimeoutMessage(true)); // handle response. DefaultFuture.received(future.getChannel(), timeoutResponse, true); }

Target:
Seems like we should judge null for future since the normal response will have called `DefaultFuture.remove`.
Source:
public boolean accept(Type type, Class<?> clazz) { if (clazz == null) { return false; } if (GeneratedMessageV3.class.isAssignableFrom(clazz)) { return true; } return false; }

Target:
pls. simplify it to 'return GeneratedMessageV3.class.isAssignableFrom(clazz);'
Source:
public void innerReceive(String dataId, String group, String configInfo) { String oldValue = cacheData.get(dataId); ConfigChangeEvent event = new ConfigChangeEvent(dataId, configInfo, getChangeType(configInfo, oldValue)); cacheData.put(dataId, configInfo); listeners.forEach(listener -> listener.process(event)); }

Target:
if `configInfo` is null, which means a config has been deleted. This line will throw NPE: ```java java.lang.NullPointerException at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011) at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006) at org.apache.dubbo.configcenter.support.nacos.NacosDynamicConfiguration$NacosConfigListener.innerReceive(NacosDynamicConfiguration.java:229) at com.alibaba.nacos.api.config.listener.AbstractSharedListener.receiveConfigInfo(AbstractSharedListener.java:37) at com.alibaba.nacos.client.config.impl.CacheData$1.run(CacheData.java:188) at com.alibaba.nacos.client.config.impl.CacheData.safeNotifyListener(CacheData.java:209) at com.alibaba.nacos.client.config.impl.CacheData.checkListenerMd5(CacheData.java:160) at com.alibaba.nacos.client.config.impl.ClientWorker$LongPollingRunnable.run(ClientWorker.java:505) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834) ``` In order to avoid that, it is necessary to remove the dataID from cacheDate.
Source:
public void setProtocol(String protocol) { this.protocols = new ArrayList<>(Arrays.asList(new ProtocolConfig[]{new ProtocolConfig(protocol)})); }

Target:
This can be simplified as `new ArrayList<>(Arrays.asList(new ProtocolConfig(protocol)))`
Source:
public boolean isAllowable() { long now = System.currentTimeMillis(); if (now > lastResetTime + interval) { token = buildLongAdder(rate); lastResetTime = now; } boolean flag = false; while (token.sum() > 0 && !flag) { token.decrement(); flag = true; } return flag; }

Target:
`token.sum()` can be replaced with `getToken()`
Source:
public static String getSimpleClassName(String qualifiedName) { int i = qualifiedName.lastIndexOf('.'); return i < 0 ? qualifiedName : qualifiedName.substring(i + 1); }

Target:
Better to check and have check for non empty or null string `org.apache.dubbo.common.utils.Assert.notEmptyString(qualifiedName, "Name can't be null or blank");`
Source:
public static int getHeartbeat(URL url) { String dubbo = url.getParameter(Constants.DUBBO_VERSION_KEY); return url.getParameter(Constants.HEARTBEAT_KEY, dubbo != null && dubbo.startsWith("1.0.") ? Constants.DEFAULT_HEARTBEAT : 0); }

Target:
Since `2.0.x` has been widely adopted, keep the `1.0.x` compatible code may be unnecessary and remove it may make code cleaner. What do you think?
Source:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { if (evt instanceof IdleStateEvent) { logger.info("IdleStateEvent triggered, close channel " + channel); channel.close(); } super.userEventTriggered(ctx, evt); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } }

Target:
Seems like we should keep the logic same with NettyClientHandler. We can call `NettyChannel.getOrAddChannel` after `if (evt instanceof IdleStateEvent)`
Source:
public void doDestroy() { if (!destroyed.compareAndSet(false, true)) { return; } // unregister the shutdownHook unregister(); // destroy all the registries AbstractRegistryFactory.destroyAll(); // destroy all the protocols destroyProtocols(); }

Target:
don't call `unregister` here. When shutdown hook runs, it will lead to IllegalStateException if we try to remove the hook. ```java static synchronized void add(Thread hook) { if(hooks == null) throw new IllegalStateException("Shutdown in progress"); if (hook.isAlive()) throw new IllegalArgumentException("Hook already running"); if (hooks.containsKey(hook)) throw new IllegalArgumentException("Hook previously registered"); hooks.put(hook, hook); } ```
Source:
private void processWithAccessKeyLogger(Set<AccessLogData> logSet, File file) throws IOException { FileWriter writer = new FileWriter(file, true); try { for (Iterator<AccessLogData> iterator = logSet.iterator(); iterator.hasNext(); iterator.remove()) { writer.write(iterator.next().getLogMessage()); writer.write("\r\n"); } writer.flush(); } finally { writer.close(); } }

Target:
need formation here.
Source:
private static void append(StringBuilder builder, String value) { if (StringUtils.hasText(value)) { builder.append(value).append(SEPARATOR); } }

Target:
why not use builder.append(SEPARATOR).append(value) . In this way , there is no need to remove last ":" in build method.
Source:
public String doGetContent(String path) { try { byte[] dataBytes = client.getData().forPath(path); if (dataBytes == null || dataBytes.length == 0) { return null; } return new String(dataBytes, charset); } catch (NodeExistsException e) { } catch (NoNodeException e) { } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } return null; }

Target:
can be rewritten as `return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, charset);`
Source:
public String doGetContent(String path) { try { byte[] dataBytes = client.getData().forPath(path); return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, charset); } catch (NodeExistsException e) { } catch (NoNodeException e) { } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } return null; }

Target:
pls. add `// ignore`
Source:
private boolean hasProviderProtocol() { return getProvider() != null && getProvider().getProtocols() != null && getProvider().getProtocols().isEmpty(); }

Target:
should be `!getProvider().getProtocols().isEmpty()`
Source:
static boolean isValidAddress(InetAddress address) { if (address == null || address.isLoopbackAddress()) { return false; } String name = address.getHostAddress(); return (name != null && !Constants.ANYHOST_VALUE.equals(name) && !Constants.LOCALHOST_VALUE.equals(name) && IP_PATTERN.matcher(name).matches()); }

Target:
@CrazyHZM I think once the **name** is not null the rest of two evaulation ``` !Constants.ANYHOST_VALUE.equals(name) && !Constants.LOCALHOST_VALUE.equals(name) ``` most likely be evaluates to **true** for non localhost so the chances of this whole condition to become true depends on **IP_PATTERN.matcher(name).matches()**. So from better understanding and performance point of view I think it would be better if we change it to ``` (name != null && IP_PATTERN.matcher(name).matches() && !Constants.ANYHOST_VALUE.equals(name) && !Constants.LOCALHOST_VALUE.equals(name)); ``` What do yu say?
Source:
default Object getProperty(String key, Object defaultValue) { Object value = getInternalProperty(key); if (value == null) { value = defaultValue; } return value; }

Target:
can be simplified with `return value!=null? value : defaultValue?`
Source:
public static boolean isProvider(URL url) { return PROVIDERS_CATEGORY.equals(url.getParameter(Constants.CATEGORY_KEY, PROVIDERS_CATEGORY)) && !OVERRIDE_PROTOCOL.equals(url.getProtocol()) && !ROUTE_PROTOCOL.equals(url.getProtocol()); }

Target:
may be we can apply the same approach here.
Source:
public Semaphore getActivesSemaphore(int maxThreadNum) { if(maxThreadNum <= 0) { return null; } if (activesLimit == null || activesPermits != maxThreadNum) { synchronized (this) { if (activesLimit == null || activesPermits != maxThreadNum) { activesLimit = new Semaphore(maxThreadNum); activesPermits = maxThreadNum; } } } return activesLimit; }

Target:
format your code, pls.
Source:
public void setLevel(Level level) { }

Target:
`SetLevel` method isn't implemented,