auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Payment getPaymentByExternalKey(final String paymentExternalKey, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext) throws PaymentApiException { final Payment payment = paymentProcessor.getPaymentByExternalKey(paymentExternalKey, withPluginInfo, properties, tenantContext, internalCallContextFactory.createInternalTenantContext(tenantContext)); if (payment == null) { throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT, paymentExternalKey); } return payment; }

Target:
Same here: The new flag `withAttempts` is not passed (used) the `paymentProcessor#getAccountPayments`
Source:
public Pagination<Payment> searchPayments(final String searchKey, final Long offset, final Long limit, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext context) { return paymentProcessor.searchPayments(searchKey, offset, limit, withPluginInfo, properties, context, internalCallContextFactory.createInternalTenantContext(context)); }

Target:
Same here: The new flag `withAttempts` is not passed (used) the `paymentProcessor#getAccountPayments`
Source:
public Pagination<Payment> searchPayments(final String searchKey, final Long offset, final Long limit, final String pluginName, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext context) throws PaymentApiException { return paymentProcessor.searchPayments(searchKey, offset, limit, pluginName, withPluginInfo, properties, context, internalCallContextFactory.createInternalTenantContext(context)); }

Target:
Same here: The new flag `withAttempts` is not passed (used) the `paymentProcessor#getAccountPayments`
Source:
public Page getNextPage() { PrestoSparkSerializedPage prestoSparkSerializedPage = null; synchronized (this) { while (prestoSparkSerializedPage == null) { if (currentIteratorIndex >= serializedPageIterators.size()) { return null; } Iterator<PrestoSparkSerializedPage> currentIterator = serializedPageIterators.get(currentIteratorIndex); if (!currentIterator.hasNext()) { currentIteratorIndex++; continue; } prestoSparkSerializedPage = currentIterator.next(); } } return pagesSerde.deserialize(toSerializedPage(prestoSparkSerializedPage)); }

Target:
I would prefer this way ``` if (currentIterator.hasNext()) { prestoSparkSerializedPage = currentIterator.next(); } else { currentIteratorIndex++; } ```
Source:
public static void combine(@AggregationState NullableDoubleState state, @AggregationState NullableDoubleState otherState) { if (state.isNull()) { state.setNull(false); state.setDouble(otherState.getDouble()); } else { state.setDouble(state.getDouble() + otherState.getDouble()); } }

Target:
Is there a performance difference between this and original code?
Source:
private static Response responseWithHeaders(ResponseBuilder builder, ProxyResponse response) { response.getHeaders().asMap().forEach((headerName, values) -> { String name = headerName.toString(); if (isPrestoHeader(name) || name.equalsIgnoreCase(SET_COOKIE)) { values.forEach(value -> builder.header(name, value)); } }); return builder.build(); }

Target:
Would `response.getHeaders().forEach((headerName, value)` work? Just remove `asMap()`.
Source:
private boolean isDateTimeConstantType(Type type) { return type == DateType.DATE || type == TimestampType.TIMESTAMP || type == TimestampWithTimeZoneType.TIMESTAMP_WITH_TIME_ZONE; }

Target:
Can be private static
Source:
public FSDataInputStream openFile(Path path, HiveFileContext hiveFileContext) throws Exception { // URIStatus is the mechanism to pass the hiveFileContext to the source filesystem URIStatus uriStatus = mFileSystem.getStatus(getAlluxioPath(path)); AlluxioURIStatus alluxioURIStatus = new AlluxioURIStatus(uriStatus.getFileInfo(), hiveFileContext); FileInStream fileInStream = mFileSystem.openFile(alluxioURIStatus, OpenFilePOptions.getDefaultInstance()); return new FSDataInputStream(new AlluxioCachingHdfsFileInputStream(fileInStream, fileSystem.openFile(path, hiveFileContext), cacheValidationEnabled)); }

Target:
We should avoid fileSystem.openFile in case validation is disabled.
Source:
public static HivePartitioningHandle createHiveCompatiblePartitioningHandle( int bucketCount, List<HiveType> hiveTypes, OptionalInt maxCompatibleBucketCount) { return new HivePartitioningHandle( bucketCount, maxCompatibleBucketCount, BucketFunctionType.HIVE_COMPATIBLE, Optional.of(hiveTypes), Optional.empty()); }

Target:
nit: static import
Source:
public static HivePartitioningHandle createPrestoNativePartitioningHandle( int bucketCount, List<Type> types, OptionalInt maxCompatibleBucketCount) { return new HivePartitioningHandle( bucketCount, maxCompatibleBucketCount, BucketFunctionType.PRESTO_NATIVE, Optional.empty(), Optional.of(types)); }

Target:
nit: static import
Source:
public boolean tryReserveMemory(String allocationTag, long delta, boolean enforceBroadcastMemoryLimit) { if (enforceBroadcastMemoryLimit && !tryUpdateBroadcastMemoryFunction.test(delta)) { return false; } return tryReserveMemoryFunction.test(allocationTag, delta); }

Target:
put this after tryReserveMemoryFunctinon.test()... so that local memory limit errors will be thrown first
Source:
public Builder addSetupQueryId(String queryId) { checkState(!this.queryId.isPresent(), "queryId is already set"); this.setupQueryIds.add(queryId); return this; }

Target:
is this the right check?
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if ((obj == null) || (getClass() != obj.getClass())) { return false; } ErrorMatcher o = (ErrorMatcher) obj; return Objects.equals(errorCode, o.errorCode) && Objects.equals(queryStage, o.queryStage) && Objects.equals(errorMessagePattern, o.errorMessagePattern); }

Target:
nit: The parentheses in `(obj == null) ` and `(getClass() != obj.getClass())` are not needed
Source:
public RunningSplitInfo(long startTime, String threadId, Thread thread, PrioritizedSplitRunner split) { this.startTime = startTime; this.threadId = threadId; this.thread = thread; this.printed = false; this.split = split; }

Target:
move this above `this.printed = false;` to align with stack order
Source:
protected void setup(Binder binder) { bindAuthenticationModule( config -> config.getDruidAuthenticationType() == DruidConfig.DruidAuthenticationType.NONE, noneAuthenticationModule()); bindAuthenticationModule( config -> config.getDruidAuthenticationType() == DruidConfig.DruidAuthenticationType.BASIC, basicAuthenticationModule()); bindAuthenticationModule( config -> config.getDruidAuthenticationType() == DruidConfig.DruidAuthenticationType.KERBEROS, kerberosbAuthenticationModule()); }

Target:
static import DruidConfig.DruidAuthenticationType.KERBEROS
Source:
public void testDefaults() { assertRecordedDefaults(recordDefaults(DruidConfig.class) .setDruidBrokerUrl(null) .setDruidCoordinatorUrl(null) .setDruidSchema("druid") .setComputePushdownEnabled(false) .setHadoopConfiguration("") .setDruidAuthenticationType(DruidConfig.DruidAuthenticationType.NONE) .setBasicAuthenticationUsername(null) .setBasicAuthenticationPassword(null)); }

Target:
static import DruidConfig.DruidAuthenticationType.NONE?
Source:
public ConnectorPartitioningHandle getPartitioningHandleForExchange(ConnectorSession session, int partitionCount, List<Type> partitionTypes) { return new HivePartitioningHandle( partitionCount, partitionTypes.stream() .map(type -> toHiveType( typeTranslator, translateHiveUnsupportedTypeForTemporaryTable(type, typeManager), getDefaultHiveTypeForTemporaryTable(getTemporaryTableStorageFormat(session)))) .collect(toImmutableList()), OptionalInt.empty()); }

Target:
Let this thing fail for now. Ideally the `HivePartitioningHandle ` shouldn't contain the hive types if the partition handle is for materialized exchange.
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CacheQuotaRequirement that = (CacheQuotaRequirement) o; return cacheQuotaScope == that.cacheQuotaScope && Objects.equals(quota, that.quota); }

Target:
Use `Objects.equals` for `cacheQuotaScope`
Source:
public void start() { if (started.compareAndSet(false, true)) { refreshExecutor.scheduleWithFixedDelay(() -> { try { refreshAndStartQueries(); } catch (Throwable t) { log.error(t, "Error while executing refreshAndStartQueries"); throw t; } lastSchedulingCycleRunTimeMs.getAndSet(System.currentTimeMillis()); }, 1, 1, TimeUnit.MILLISECONDS); } }

Target:
Let's suppress this Exception per the docs: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleWithFixedDelay-java.lang.Runnable-long-long-java.util.concurrent.TimeUnit- Logging should be sufficient.
Source:
public void testDefaults() { assertRecordedDefaults(recordDefaults(DruidConfig.class) .setDruidBrokerUrl(null) .setDruidCoordinatorUrl(null) .setDruidSchema("druid") .setComputePushdownEnabled(false) .setHadoopConfiguration((String) null)); }

Target:
get it. could the following work? `setHadoopConfiguration("") `
Source:
private OrcCorruptionException propagate(Throwable throwable, String message) { propagateIfPossible(throwable, InvalidFunctionArgumentException.class); propagateIfPossible(throwable, NotSupportedException.class); propagateIfPossible(throwable, GenericInternalException.class); return new OrcCorruptionException(throwable, orcDataSourceId, message); }

Target:
But checking the callsites, I think we need to catch NotSupportedException for getNextPage method in both OrcBatchPageSource and OrcSelectivePageSource. We also need to catch InvalidFunctionArgumentException for OrcBatchPageSource.getNextPage
Source:
private KeyProvider toKeyProvider(DwrfProto.Encryption.KeyProvider keyProvider) { switch (keyProvider) { case CRYPTO_SERVICE: return KeyProvider.CRYPTO_SERVICE; default: // TODO: should we throw an exception instead? return KeyProvider.UNKNOWN; } }

Target:
UNKNOWN is basically a stub for anything. For example, during test, we write a file using some fake key provider, and set it to unknown. As long as the reader uses the same key provider, it is able to read the file without making the fake provider an actual provider in the proto
Source:
private List<EncryptionGroup> toEncryptionGroups(List<DwrfProto.EncryptionGroup> encryptionGroups) { ImmutableList.Builder<EncryptionGroup> encryptionGroupBuilder = ImmutableList.builder(); for (DwrfProto.EncryptionGroup dwrfEncryptionGroup : encryptionGroups) { encryptionGroupBuilder.add(new EncryptionGroup( dwrfEncryptionGroup.getNodesList(), dwrfEncryptionGroup.hasKeyMetadata() ? Optional.of(byteStringToSlice(dwrfEncryptionGroup.getKeyMetadata())) : Optional.empty(), byteStringToSlice(dwrfEncryptionGroup.getStatistics()))); } return encryptionGroupBuilder.build(); }

Target:
this method can be static
Source:
public static <T> Class<? extends T> defineClass(ClassDefinition classDefinition, Class<T> superType, Map<Long, MethodHandle> callSiteBindings, ClassLoader parentClassLoader) { try { return defineClass(classDefinition, superType, new DynamicClassLoader(parentClassLoader, callSiteBindings)); } catch (ByteCodeTooLargeException byteCodeTooLargeException) { throw new PrestoException(GENERATED_BYTECODE_TOO_LARGE, ERROR_LARGE_BYTECODE); } }

Target:
This is not needed if you already handles the exception in the other method?
Source:
private void testWithAllStorageFormats(BiConsumer<Session, HiveStorageFormat> test) { for (HiveStorageFormat storageFormat : HiveStorageFormat.values()) { Session session = getSession(); if (storageFormat == PAGEFILE) { session = Session.builder(getSession()) .setCatalogSessionProperty(catalog, "compression_codec", "SNAPPY") .build(); } test.accept(session, storageFormat); } }

Target:
Why do we have to reset it here? Is it because the standard, GZIP compression is not supported? How hard is it to simply support it?
Source:
private Request prepareMetadataQuery(String query) { HttpUriBuilder uriBuilder = uriBuilderFrom(druidBroker).replacePath(SQL_ENDPOINT); return setContentTypeHeaders(preparePost()) .setUri(uriBuilder.build()) .setBodyGenerator(createStaticBodyGenerator(createRequestBody(query, DruidResultFormat.OBJECT, false))) .build(); }

Target:
static import OBJECT, ARRAY_LINES ... ?
Source:
public List<URIStatus> listStatus(AlluxioURI path, ListStatusPOptions options) throws IOException { List<URIStatus> statuses = Arrays.stream(fileSystem.listStatus(toPath(path))).map(this::toUriStatus).collect(Collectors.toList()); return statuses; }

Target:
directly return
Source:
public List<BlockLocationInfo> getBlockLocations(AlluxioURI alluxioURI) throws IOException { Path path = toPath(alluxioURI); BlockLocation[] fileBlockLocations = fileSystem.getFileBlockLocations(path, 0, path.toString().length()); Arrays.stream(fileBlockLocations).map(this::toBlockLocationInfo).collect(Collectors.toList()); throw new UnsupportedOperationException("GetBlockLocations is not supported."); }

Target:
why throw after some operations?
Source:
public FileInStream openFile(AlluxioURI alluxioURI, OpenFilePOptions options) throws IOException { FSDataInputStream inputStream = fileSystem.open(toPath(alluxioURI)); return new AlluxioCachingInputStream(inputStream); }

Target:
Will this be a problem given we always force to use `FSDataInputStream openFile(Path path, HiveFileContext hiveFileContext)` to open files?
Source:
public FileStatus getFileStatus(Path path) throws IOException { if (files.containsKey(path)) { return generateURIStatus(path, files.get(path).length); } else { throw new FileNotFoundException(path.toString()); } }

Target:
remove `else`
Source:
private static byte[] createRequestBody(String query, String resultFormat, boolean queryHeader) { if (!queryHeader) { return format("{\"query\":\"%s\",\"resultFormat" + "\":\"%s\",\"header\": false }\n", query, resultFormat).getBytes(); } else { return format("{\"query\":\"%s\"}\n", query).getBytes(); } }

Target:
change the order: if (queryHeader) { return ... } return ...
Source:
private HiveCompressionCodec getHiveCompressionCodec(ConnectorSession session, boolean isTemporaryTable, HiveStorageFormat storageFormat) { if (isTemporaryTable) { return getTemporaryTableCompressionCodec(session); } if (storageFormat.equals(ORC) || storageFormat.equals(DWRF)) { return getOrcCompressionCodec(session); } return getCompressionCodec(session); }

Target:
- For the purpose of checking compatibility between `StorageFormat` and `HiveCompressionCodec`, you can use `HiveCompressionCodec::isSupportedStorageFormat` - For the purpose of getting ORC specific compression method, you can use `HiveCompressionCodec::orcCompressionKind` - I didn't quite understand why existing `hive.compression-codec` is not good enough.
Source:
public PageFileFooterOutput(List<Long> stripeOffsets) { this.stripeOffsets = ImmutableList.copyOf(requireNonNull(stripeOffsets, "stripeOffsets is null")); checkArgument(!stripeOffsets.isEmpty(), "stripeOffsets should at least contain offset 0"); }

Target:
nit: lets move it before the assignment
Source:
public PageWriter(DataSink dataSink, DataSize pageFileStripeMaxSize) { this.dataSink = requireNonNull(dataSink, "pageDataSink is null"); this.maxBufferedBytes = requireNonNull(pageFileStripeMaxSize, "pageFileStripeMaxSize is null").toBytes(); bufferedPages = new ArrayList<>(); stripeOffsets = new ArrayList<>(ImmutableList.of(0L)); }

Target:
What if there's no stripes? It feels like this should be initialized as empty.
Source:
public boolean hasNext() { return readBytes < readLength && input.isReadable(); }

Target:
Instead of keeping track of `readBytes` you can use `ByteStreams#limit`
Source:
PageFilePageReader( long readStart, long readLength, FSDataInputStream inputStream, PagesSerde pagesSerde) throws IOException { this.pagesSerde = requireNonNull(pagesSerde, "pagesSerde is null"); this.readLength = readLength; requireNonNull(inputStream, "inputStream is null"); inputStream.seek(readStart); this.input = new InputStreamSliceInput(inputStream); }

Target:
How about passing an already positioned and limited input stream? (doing `inputStream.seek(readStart);` and `ByteStreams#limit` outside)? If you do that then most likely you won't even need this class.
Source:
public void close() { if (closed) { return; } closed = true; block = null; Throwable innerException = null; for (Closer closer : closers) { try { closer.close(); } catch (Throwable t) { if (innerException == null) { innerException = t; } else if (innerException != t) { // Self-suppression not permitted innerException.addSuppressed(t); } } } if (innerException != null) { // Convert to unchecked exception throw new RuntimeException(innerException); } }

Target:
This change is problematic. The lease doesn't own the block and the same block can be used to create multiple leases.
Source:
public HiveOrcAggregatedMemoryContext() { this.delegate = newSimpleAggregatedMemoryContext(); }

Target:
`this(this.delegate = newSimpleAggregatedMemoryContext());`
Source:
public void write(SerializedPage page) throws IOException { retainedBytes += page.getRetainedSizeInBytes(); PageDataOutput pageDataOutput = new PageDataOutput(page); long writtenSize = pageDataOutput.size(); if (maxBufferedBytes - bufferedBytes < writtenSize) { dataSink.write(bufferedPages); bufferedPages.clear(); bufferedBytes = 0; retainedBytes = 0; } else { bufferedPages.add(new PageDataOutput(page)); bufferedBytes += writtenSize; } }

Target:
Given that this bug wasn't caught by test I would suggest improving the test (or adding a unit test) to cover this case.
Source:
public CachedTableChecker(List<String> cachedTables) { this.cacheAllTables = cachedTables.contains("*"); if (cacheAllTables) { checkArgument(cachedTables.size() == 1, "Only '*' is expected when caching all tables"); this.cachedTableNames = ImmutableSet.of(); } else { this.cachedTableNames = cachedTables.stream() .map(CachingDirectoryLister::parseTableName) .collect(toImmutableSet()); } }

Target:
s/this.cacheAllTables/cacheAllTables/g I think we prefer not to use this to reference variables
Source:
public static Slice stSphericalAsText(@SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice input) { if (input == null) { return utf8Slice("POINT EMPTY"); } return utf8Slice(wktFromJtsGeometry(deserialize(input))); }

Target:
If the input is null, the output should be null. ScalarFunctions do this automatically, unless you use the `@SqlNullable` annotation.
Source:
public Object getObjectValue(ConnectorSession session, Block block, int position) { if (block.isNull(position)) { return null; } Slice slice = block.getSlice(position, 0, block.getSliceLength(position)); if (slice == Slices.EMPTY_SLICE) { return null; } return deserialize(slice).asText(); }

Target:
Remove this by returning null above.
Source:
public void serializeTo(SliceOutput output) { writeLengthPrefixedString(output, NAME); output.writeInt(bufferedPositionCount); serializeNullsTo(output); if (valuesBufferIndex > 0) { try { output.appendBytes(valuesBuffer, 0, valuesBufferIndex); } catch (Exception e) { e.printStackTrace(); } } }

Target:
@yingsu00 debugging leftovers?
Source:
public String getClientInfo() { return clientInfo.orElse(null); }

Target:
just return `Optional<String>` that way the implementation can decide what to do if the value is not present.
Source:
public void addInput(Page page) { requireNonNull(page, "page is null"); if (page.getPositionCount() == 0) { return; } page = pagePreprocessor.apply(page); pagePartitioner.partitionPage(page); System.out.println(pagePartitioner.getRetainedSizeInBytes()); // TODO: PartitionedOutputOperator reports incorrect output data size #11770 operatorContext.recordOutput(page.getSizeInBytes(), page.getPositionCount()); systemMemoryContext.setBytes(pagePartitioner.getRetainedSizeInBytes()); }

Target:
Debugging? Remove.
Source:
public FunctionImplementationType getFunctionImplementationType() { switch (routineCharacteristics.getLanguage()) { case SQL: return FunctionImplementationType.SQL; case JAVA: return FunctionImplementationType.THRIFT; default: throw new UnsupportedOperationException(format("Unsupported language %s", routineCharacteristics.getLanguage())); } }

Target:
Using a static map would be easier?
Source:
public void setTaskLimitExceeded(boolean exceeded) { this.taskLimitExceeded.set(exceeded); }

Target:
nit: drop "this."
Source:
public Optional<HostAddress> getAddress() { return address; }

Target:
remove
Source:
public DruidQueryGeneratorContext withOutputColumns(List<VariableReferenceExpression> outputColumns) { LinkedHashMap<VariableReferenceExpression, Selection> newSelections = new LinkedHashMap<>(); outputColumns.forEach(o -> newSelections.put(o, requireNonNull(selections.get(o), "Cannot find the selection " + o + " in the original context " + this))); return new DruidQueryGeneratorContext(newSelections, from, filter); }

Target:
Can we replace all these to map?
Source:
public TestTpchTaskUpdateSizeLimitIntegrationTest() { this(() -> createQueryRunner(ImmutableMap.of("experimental.internal-communication.max-task-update-size", "100B"))); }

Target:
`super(() -> createQueryRunner(ImmutableMap.of("experimental.internal-communication.max-task-update-size", "100B")));`
Source:
MissingFieldStreamReader(Type type) { requireNonNull(type, "type is required"); this.outputType = type; }

Target:
combine with assignment `this.outputType = requireNonNull(type, "type is required");`
Source:
public Optional<List<InternalNode>> getBucketToNode() { if (bucketToNodeInfo.size() == 0) { return Optional.empty(); } return Optional.of(bucketToNodeInfo.values().stream().map(InternalNodeInfo::getInternalNode).collect(Collectors.toList())); }

Target:
`bucketToNodeInfo.isEmpty()`
Source:
public static Block ipSubnetRange(@SqlType(StandardTypes.IPPREFIX) Slice value) { validateIpPrefixAndGetBytes(value); BlockBuilder blockBuilder = IPADDRESS.createBlockBuilder(null, 2); IPADDRESS.writeSlice(blockBuilder, ipSubnetMin(value)); IPADDRESS.writeSlice(blockBuilder, ipSubnetMax(value)); return blockBuilder.build(); }

Target:
The `value` is validated 3 times in this function.
Source:
public static Slice ipSubnetMin(@SqlType(StandardTypes.IPPREFIX) Slice value) { validateIpPrefixAndGetBytes(value); return castFromIpPrefixToIpAddress(value); }

Target:
The input has to be a valid ipprefix so you don't need to validate it.
Source:
public void testIpSubnetMin() { assertFunction("IP_SUBNET_MIN(IPPREFIX '1.2.3.4/24')", IPADDRESS, "1.2.3.0"); assertFunction("IP_SUBNET_MIN(IPPREFIX '1.2.3.4/32')", IPADDRESS, "1.2.3.4"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/64')", IPADDRESS, "64:ff9b::"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/127')", IPADDRESS, "64:ff9b::16"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/128')", IPADDRESS, "64:ff9b::17"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/0')", IPADDRESS, "::"); assertInvalidCast("IP_SUBNET_MIN(IPPREFIX '64::ff9b::10/48')", "Cannot cast value to IPPREFIX: 64::ff9b::10/48"); assertInvalidCast("IP_SUBNET_MIN(IPPREFIX '123.456.789.012/24')", "Cannot cast value to IPPREFIX: 123.456.789.012/24"); }

Target:
Those 2 test cases do not belong to this test method. Unlike the `IP_PREFIX`, which can take `VARCHAR` as the input, those 2 test cases are not testing the behavior of `IP_SUBNET_MIN`, but the behavior of casting `VARCHAR` to `IPPREFIX`.
Source:
public void testIpSubnetMax() { assertFunction("IP_SUBNET_MAX(IPPREFIX '1.2.3.128/26')", IPADDRESS, "1.2.3.191"); assertFunction("IP_SUBNET_MAX(IPPREFIX '192.168.128.4/32')", IPADDRESS, "192.168.128.4"); assertFunction("IP_SUBNET_MAX(IPPREFIX '10.1.16.3/9')", IPADDRESS, "10.127.255.255"); assertFunction("IP_SUBNET_MAX(IPPREFIX '2001:db8::16/127')", IPADDRESS, "2001:db8::17"); assertFunction("IP_SUBNET_MAX(IPPREFIX '2001:db8::16/128')", IPADDRESS, "2001:db8::16"); assertFunction("IP_SUBNET_MAX(IPPREFIX '64:ff9b::17/64')", IPADDRESS, "64:ff9b::ffff:ffff:ffff:ffff"); assertFunction("IP_SUBNET_MAX(IPPREFIX '64:ff9b::17/72')", IPADDRESS, "64:ff9b::ff:ffff:ffff:ffff"); assertFunction("IP_SUBNET_MAX(IPPREFIX '64:ff9b::17/0')", IPADDRESS, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); assertInvalidCast("IP_SUBNET_MAX(IPPREFIX '64::ff9b::10/24')", "Cannot cast value to IPPREFIX: 64::ff9b::10/24"); assertInvalidCast("IP_SUBNET_MAX(IPPREFIX '123.456.789.012/-1')", "Cannot cast value to IPPREFIX: 123.456.789.012/-1"); }

Target:
Same here, remove.
Source:
public Block readBlock(Type type, int batchSize) throws IOException { checkArgument(type == DOUBLE); BlockBuilder builder = type.createBlockBuilder(null, batchSize); for (int i = 0; i < batchSize; ++i) { type.writeDouble(builder, valueSelector.getDouble()); } return builder.build(); }

Target:
not needed; same for other readers
Source:
public int getOffset() { int offset = row; ++row; return offset; }

Target:
it's weird to increment `row` inside `getOffset`. How about having this class inheriting `Offset` rather than `ReadableOffset`?
Source:
private static int chunkedRead(InflaterInputStream inflaterInputStream, byte[] buffer, int offset, int length) throws IOException { int position = offset; int bytesRead = 0; while (((position - offset) < length) && bytesRead != -1) { bytesRead = inflaterInputStream.read(buffer, position, offset + length - position); if (bytesRead > 0) { position += bytesRead; } } return position - offset; }

Target:
nit: ``` while (position - offset < length && bytesRead != -1) { ```
Source:
public ZipIndexFileSource(DataInputSource dataInputSource) { this.dataInputSource = requireNonNull(dataInputSource, "dataInputSource is null"); this.zipData = readCentralDirectory(); }

Target:
put this on stack
Source:
private boolean isEntireColumn(Subfield subfield) { return subfield.getPath().isEmpty(); }

Target:
static, same for other helpers
Source:
public Optional<ReadMapping> toPrestoType(ConnectorSession session, JdbcTypeHandle typeHandle) { if (typeHandle.getJdbcType() == microsoft.sql.Types.DATETIMEOFFSET) { return Optional.of(dateTimeOffsetReadMapping()); } return super.toPrestoType(session, typeHandle); }

Target:
Static import `DATETIMEOFFSET`
Source:
public FunctionImplementationType getFunctionImplementationType() { return SQL; }

Target:
This should be a function derived from `RoutineCharacteristics.language`. Actually is it better to expose language rather than implementation type?
Source:
private List<InternalNode> convertToInternalNode(NodeMap nodeMap, List<HostAddress> preferredNodes) { List<InternalNode> internalNodes = new ArrayList<>(); preferredNodes.stream().forEach(node -> internalNodes.addAll(nodeMap.getNodesByHostAndPort().get(node))); return ImmutableList.copyOf(internalNodes); }

Target:
static
Source:
public void testEmptyNodeSelectionStrategyConfig() { ConnectorSession connectorSession = new TestingConnectorSession( new HiveSessionProperties( new HiveClientConfig(), new OrcFileWriterConfig(), new ParquetFileWriterConfig()).getSessionProperties()); assertEquals(getNodeSelectionStrategy(connectorSession), NodeSelectionStrategy.NO_PREFERENCE); }

Target:
static import?
Source:
public NodeSelectionStrategy getNodeSelectionStrategy() { return NodeSelectionStrategy.HARD_AFFINITY; }

Target:
static import
Source:
public void testDefaults() { assertRecordedDefaults(ConfigAssertions.recordDefaults(DbResourceGroupConfig.class) .setConfigDbUrl(null) .setMaxRefreshInterval(new Duration(1, HOURS)) .setReloadRefreshInterval(new Duration(1, SECONDS)) .setExactMatchSelectorEnabled(false)); }

Target:
Would this compile?
Source:
protected BytesRange(byte[] lower, boolean lowerExclusive, byte[] upper, boolean upperExclusive, boolean nullAllowed) { super(true, nullAllowed); this.lower = lower; this.upper = upper; this.lowerExclusive = lowerExclusive; this.upperExclusive = upperExclusive; this.singleValue = !lowerExclusive && !upperExclusive && Arrays.equals(upper, lower); }

Target:
keep this private
Source:
public RaptorCachingHdfsConfiguration( @ForCachingFileSystem RaptorHdfsConfiguration hiveHdfsConfiguration, CacheConfig cacheConfig, CacheManager cacheManager) { this.hiveHdfsConfiguration = requireNonNull(hiveHdfsConfiguration, "hiveHdfsConfiguration is null"); this.cacheManager = requireNonNull(cacheManager, "CacheManager is null"); cacheConfig = requireNonNull(cacheConfig, "cacheConfig is null"); this.cacheValidationEnabled = cacheConfig.isValidationEnabled(); }

Target:
nit: `this.cacheValidationEnabled = requireNonNull(cacheConfig, "cacheConfig is null").isValidationEnabled();`
Source:
private PlanBuilder planBuilderFor(PlanBuilder builder, Scope scope, Iterable<? extends Expression> expressionsToRemap) { PlanBuilder newBuilder = planBuilderFor(builder, scope); for (Expression expression : expressionsToRemap) { // We can't deduplicate expressions here because even if two expressions are equal, // the TranslationMap maps sql names to symbols, and any lambda expressions will be // resolved differently since the lambdaDeclarationToVariableMap is identity based. newBuilder.getTranslations().put(expression, builder.translate(expression)); } return newBuilder; }

Target:
Maybe just do ``` stream(expressionsToRemap) .forEach(expression -> newBuilder.getTranslations().put(expression, builder.translate(expression))); ``` I don't have strong opinions. Just that overall the codebase seems to prefer stream API when logic is simple.
Source:
public TestHiveDistributedQueries() { super(() -> createQueryRunner( getTables(), ImmutableMap.of("internal-communication.task-communication-protocol", "THRIFT"), ImmutableMap.of(), Optional.empty())); }

Target:
I think the convention these days is to "fork" `TestHiveDistributedQueries`, such as `TestHiveDistributedQueriesWithOptimizedRepartitioning`, `TestHivePushdownDistributedQueries`, `TestHiveDistributedQueriesWithExchangeMaterialization`. I do agree in this case it doesn't seem that necessary (since HTTP has been covered by other tests)... but following the convention doesn't seem to hurt :)
Source:
public void acknowledgeResultsAsync(long nextToken) { executor.execute(() -> { try { thriftClient.acknowledgeResults(taskId, outputBufferId, nextToken); } catch (Exception exception) { log.debug(exception, "Acknowledge request failed: %s/%s/%s", taskId, outputBufferId, nextToken); } }); }

Target:
Instead of popping this into an executor, can we instead just make the Thrift interface async? We don't need to handle the future if we don't care about the result.
Source:
private PageSinkCommitStrategy getPageSinkCommitStrategy() { if (pageSinkCommitRequired) { return TASK_COMMIT; } if (stageExecutionDescriptor.isRecoverableGroupedExecution()) { return LIFESPAN_COMMIT; } return NO_COMMIT; }

Target:
Should we first check whether `isRecoverableGroupedExecution` is `true` and return `LIFESPAN_COMMIT` first? I feel like `isRecoverableGroupedExecution` is a stronger predicate than `pageSinkCommitRequired`. What do you think?
Source:
public void start() { if (!enabled || started.getAndSet(true)) { log.info("ShardOrganizationManager return"); return; } startDiscovery(); }

Target:
Do we really need this?
Source:
public static Block stPoints(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { Geometry geometry = deserialize(input); validateType("ST_Points", geometry, VALID_TYPES_FOR_ST_POINTS); if (geometry.isEmpty()) { return null; } int pointCount = geometry.getNumPoints(); BlockBuilder blockBuilder = GEOMETRY.createBlockBuilder(null, pointCount); buildPointsBlock(geometry, blockBuilder); return blockBuilder.build(); }

Target:
Since this is all current geometries, and the method would work for any additional geometry that JTS supports, we can remove this (and the associated bit in lines 150-152.
Source:
private boolean evaluateDeterministicFilterFunctionsWithConstantInputs(List<FilterFunction> filterFunctions) { for (FilterFunction function : filterFunctions) { if (function.isDeterministic() && hasInputs(function) && allConstantInputs(function)) { if (!evaluateDeterministicFilterFunctionWithConstantInputs(function)) { return false; } } } return true; }

Target:
```java if (function.isDeterministic() && hasInputs(function) && allConstantInputs(function) && !evaluateDeterministicFilterFunctionWithConstantInputs(function)) { return false; }
Source:
private static boolean isSTDistance(RowExpression expression, FunctionManager functionManager) { if (expression instanceof CallExpression) { return functionManager.getFunctionMetadata(((CallExpression) expression).getFunctionHandle()).getName().equals(ST_DISTANCE); } return false; }

Target:
return (expression instanceof CallExpression) && functionManager.getFunctionMetadata(...
Source:
private Map<String, Type> buildBigIntTypeProviderMap(String... variables) { ImmutableMap.Builder<String, Type> builder = ImmutableMap.builder(); Arrays.stream(variables).forEach(variable -> builder.put(variable, BIGINT)); return builder.build(); }

Target:
static
Source:
public boolean testDouble(double value) { if (Double.isNaN(value)) { return nanAllowed; } for (TupleDomainFilter filter : filters) { if ((nanAllowed && Double.isNaN(value)) || filter.testDouble(value)) { return true; } } return false; }

Target:
@bhhari - `nanAllowed && Double.isNaN(value)` filter is redundant; NaN has been checked already - ditto testFloat
Source:
private static boolean findColumnName(String tableName, String columnName, Connection connection) throws SQLException { Statement statement = connection.createStatement(); ResultSet results = statement.executeQuery("SELECT * FROM " + tableName + " LIMIT 0"); ResultSetMetaData metadata = results.getMetaData(); int columnCount = metadata.getColumnCount(); for (int i = 1; i <= columnCount; i++) { if (columnName.equalsIgnoreCase(metadata.getColumnName(i))) { return true; } } return false; }

Target:
i = 0; i < columnCount
Source:
public void testBackoffTimeCapped() { VerificationContext verificationContext = new VerificationContext(); RetryDriver retryDriver = new RetryDriver<>( new RetryConfig() .setMaxAttempts(5) .setMinBackoffDelay(new Duration(10, MILLISECONDS)) .setMaxBackoffDelay(new Duration(100, MILLISECONDS)) .setScaleFactor(1000), QueryException::isRetryable, QueryException.class, verificationContext::addException); retryDriver.run("test", new MockOperation(5, RETRYABLE_EXCEPTION)); }

Target:
@caithagoras I understand `@Test(singleThreaded = true)` change, but why is this change?
Source:
private static void alterTable(Runnable alterTableFunction) { try { alterTableFunction.run(); } catch (Exception e) { log.info("Alter table failed: %s", e); } }

Target:
`log.warn(e, "Alter table failed");`
Source:
public void testTableTablesWithoutUpgrading() { // without perform upgrading operation would cause metadata incorrect long tableId = dao.insertTable("schema1", "table1", true, false, null, 0, false); assertNotNull(tableId); }

Target:
No need to create `tableId` and assign/assert on it. The code will never reach this point.
Source:
public Optional<BitSet> getRowsDeleted() { // Just load once if (!loaded && tableSupportsDeltaDelete && deltaShardUuid.isPresent()) { rowsDeleted = orcStorageManager.getRowsFromUuid(fileSystem, deltaShardUuid); loaded = true; } return rowsDeleted; }

Target:
private
Source:
private <T> void assertBlockPositions(Block block, Supplier<BlockBuilder> newBlockBuilder, T[] expectedValues) { try { assertEquals(block.getPositionCount(), expectedValues.length); } catch (Exception e) { e.printStackTrace(); } for (int position = 0; position < block.getPositionCount(); position++) { assertBlockPosition(block, newBlockBuilder, position, expectedValues[position], expectedValues.getClass().getComponentType()); } }

Target:
I don't understand this change. Would you explain?
Source:
public synchronized boolean isFinished() { StageExecutionState rootStageState = rootStage.getStageExecution().getState(); return rootStageState.isDone() && !rootStageState.isFailure(); }

Target:
Defensive synchronized methods everywhere? 😄
Source:
public KafkaProducer<Long, Object> createProducer() { Properties properties = new Properties(); properties.setProperty(BOOTSTRAP_SERVERS_CONFIG, getConnectString()); properties.setProperty(VALUE_SERIALIZER_CLASS_CONFIG, JsonEncoder.class.getName()); properties.setProperty(KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); properties.setProperty(PARTITIONER_CLASS_CONFIG, DefaultPartitioner.class.getName()); properties.setProperty(ACKS_CONFIG, "1"); return new KafkaProducer<>(properties); }

Target:
Default partitioner is default. Need to specify?
Source:
public Object readBlocksWithoutJni(BenchmarkData data) throws Throwable { OrcBatchRecordReader recordReader = data.createRecordReader(false); List<Block> blocks = new ArrayList<>(); while (recordReader.nextBatch() > 0) { Block block = recordReader.readBlock(data.type, 0); blocks.add(block); } return blocks; }

Target:
Use ImmutableList.builder
Source:
protected final List<?> createValues() { switch (withNulls) { case ALL: return NULL_VALUES; case PARTIAL: return IntStream.range(0, ROWS).mapToObj(i -> i % 2 == 0 ? createValue() : null).collect(toList()); default: return IntStream.range(0, ROWS).mapToObj(i -> createValue()).collect(toList()); } }

Target:
nit: we don't usually use `final` on method. (Also, as a side note: we don't use `final` for tmp variables)
Source:
static String getAlphaNumericString(int length) { String alphaNumericString = "USINDIA"; StringBuilder stringBuilder = new StringBuilder(length); for (int index = 0; index < length; index++) { int arrayIndex = (int) (alphaNumericString.length() * Math.random()); stringBuilder.append(alphaNumericString.charAt(arrayIndex)); } return stringBuilder.toString(); }

Target:
private
Source:
public void testIsDistinctFrom() { long[] arr1 = {112L, 0L}; // DECIMAL '1.12' long[] arr2 = {185L, 0L}; // DECIMAL '1.85' Block left = new Int128ArrayBlock(1, Optional.empty(), arr1); Block right = new Int128ArrayBlock(1, Optional.empty(), arr2); assertFalse(DecimalInequalityOperators.distinctBlockPositionLongLong(left, 0, left, 0)); assertTrue(DecimalInequalityOperators.distinctBlockPositionLongLong(left, 0, right, 0)); }

Target:
- don't use a1, a2, etc. variables names; here, I'd just inline arr1 and arr2 - static import distinctBlockPositionLongLong ``` @Test public void testIsDistinctFrom() { Block left = new Int128ArrayBlock(1, Optional.empty(), new long[] {112L, 0L}); Block right = new Int128ArrayBlock(1, Optional.empty(), new long[] {185L, 0L}); assertFalse(distinctBlockPositionLongLong(left, 0, left, 0)); assertTrue(distinctBlockPositionLongLong(left, 0, right, 0)); } ```
Source:
public BenchmarkSuite get() { BenchmarkSuite benchmarkSuite; ImmutableList.Builder<BenchmarkQuery> benchmarkQueries = ImmutableList.builder(); try (Handle handle = jdbi.open()) { BenchmarkSuiteDao benchmarkDao = handle.attach(BenchmarkSuiteDao.class); BenchmarkSuiteInfo benchmarkSuiteInfo = benchmarkDao.getBenchmarkSuiteInfo(suitesTableName, suite); benchmarkQueries.addAll(benchmarkDao.getBenchmarkQueries(queriesTableName, benchmarkSuiteInfo.getQuerySet())); benchmarkSuite = new BenchmarkSuite(benchmarkSuiteInfo, benchmarkQueries.build()); } return benchmarkSuite; }

Target:
`benchmarkDao.getBenchmarkQueries` returns a list. Why do you need to create an empty list and then the elements?
Source:
public void testDefault() { assertRecordedDefaults(recordDefaults(BenchmarkSuiteConfig.class) .setDatabase(null) .setSuitesTableName("benchmark_suites") .setQueriesTableName("benchmark_queries") .setSuite(null)); }

Target:
Keep them in the order of the definition in `BenchmarkSuiteConfig `
Source:
public void setup() throws Exception { mySqlServer = setupMySql(); jdbi = getJdbi(mySqlServer); handle = jdbi.open(); config = new BenchmarkSuiteConfig() .setSuitesTableName(BENCHMARK_SUITES_TABLE) .setQueriesTableName(BENCHMARK_QUERIES_TABLE); }

Target:
You can just use the default config.
Source:
private void transitionToFinished() { cleanupQueryQuietly(); queryStateTimer.endQuery(); session.getSessionLogger().log(() -> "Query state machine finished"); queryState.setIf(FINISHED, currentState -> !currentState.isDone()); }

Target:
nit: remove
Source:
private synchronized void startSplit(PrioritizedSplitRunner split) { allSplits.add(split); split.getTaskHandle().getSessionLogger().log(() -> "offering split " + split); waitingSplits.offer(split); }

Target:
nit: remove
Source:
public void start() { try (SetThreadName ignored = new SetThreadName("HttpRemoteTask-%s", taskId)) { // to start we just need to trigger an update scheduleUpdate(); taskStatusFetcher.start(); taskInfoFetcher.start(); session.getSessionLogger().log(() -> String.format("started task %s", taskId)); } }

Target:
nit: remove
Source:
public ColumnChunk readNext() { ColumnChunk columnChunk = null; try { seek(); if (field.isRequired()) { columnChunk = readWithoutNull(); } else { columnChunk = readWithNull(); } } catch (IOException ex) { throw new PrestoException(PARQUET_IO_READ_ERROR, "Error reading Parquet column " + columnDescriptor, ex); } readOffset = 0; nextBatchSize = 0; return columnChunk; }

Target:
s/ex/exception/g
Source:
private void assertQuery(String query, byte[] checksum) { byte[] expected = (byte[]) computeActual(query).getOnlyValue(); for (int i = 0; i < expected.length; i++) { System.err.print(expected[i] + ", "); } assertEquals(computeActual(query).getOnlyValue(), checksum); }

Target:
Remove before merging
Source:
public LongInputStreamV1(OrcInputStream input, boolean signed) { this.input = input; this.signed = signed; lastReadInputCheckpoint = input.getCheckpoint(); }

Target:
`lastReadInputCheckpoint` is never used anymore. Could you remove?
Source:
public InternalResourceGroup getRoot() { synchronized (root) { return root; } }

Target:
`root` would not change and I can't think why its access needs to be serialized with other methods so why does this need to be synchronized?
Source:
private List<QueryStateInfo> getAllAggregatedRunningQueriesInfo() { synchronized (root) { InternalResourceGroup resourceGroup = this; List<QueryStateInfo> result = new ArrayList<>(resourceGroup.getAggregatedRunningQueriesInfo()); while (resourceGroup.getPrev().isPresent()) { resourceGroup = resourceGroup.getPrev().get(); result.addAll(resourceGroup.getAggregatedRunningQueriesInfo()); } return ImmutableList.copyOf(result); } }

Target:
```suggestion ImmutableList.Builder<QueryStateInfo> result = ImmutableList.builder().addAll(resourceGroup.getAggregatedRunningQueriesInfo()); ```
Source:
public TestFixedHistogramJacknifeAggregation() { super(DifferentialEntropyStateStrategy.FIXED_HISTOGRAM_JACKNIFE_METHOD_NAME); }

Target:
nit: static import
Source:
public Double getExpectedValue(int start, int length) { assertTrue(length < MAX_SAMPLES); double[] samples = new double[2 * length]; for (int i = 0; i < length; i++) { samples[i] = (double) (start + i); samples[i + length] = (double) (start + i); } return calculateFromSamplesUsingVasicek(samples); }

Target:
move this change to the previous commit
Source:
public Set<Class<?>> getFunctionTranslators() { return ImmutableSet.of(OperatorTranslators.class); }

Target:
private
Source:
private static <T extends PlanNode> Optional<T> findSinglePlanNode(StreamingSubPlan plan, Class<T> clazz) { List<PlanNode> allMatches = findPlanNodes(plan, clazz); switch (allMatches.size()) { case 0: return Optional.empty(); case 1: return Optional.of((T) getOnlyElement(allMatches)); default: throw new IllegalStateException(format("Multiple matches found for class %s", clazz)); } }

Target:
You can avoid the unchecked cast: * `List<PlanNode> allMatches` -> `List<T> allMatches` * In `findPlanNodes`: `<T extends PlanNode> List<PlanNode>` -> `<T extends PlanNode> List<T>`, `.findAll())` -> `.<T>findAll())`
Source:
public WriterTarget getTarget() { return target; }

Target:
Add `@JsonIgnore`
Source:
private int getValidPercentile(String fraction) { try { double p = Double.parseDouble(fraction); if (p < 0 || p > 1) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Percentile must be between 0 and 1"); } double percent = p * 100.0; if (percent == Math.floor(percent)) { return (int) percent; } } catch (NumberFormatException ne) { // Skip } return -1; }

Target:
just call this `percent`
Source:
public PinotQueryGeneratorContext visitTopN(TopNNode node, PinotQueryGeneratorContext context) { context = node.getSource().accept(this, context); requireNonNull(context, "context is null"); checkSupported(preferBrokerQueries, "Cannot push topn in segment mode"); checkSupported(node.getStep().equals(TopNNode.Step.SINGLE), "Can only push single logical topn in"); return context.withTopN(PushdownUtils.getOrderingScheme(node), node.getCount()).withOutputColumns(node.getOutputVariables()); }

Target:
Map<...>
Source:
public String sendHttpGetToController(String path) { return doHttpActionWithHeaders( Request.builder().prepareGet().setUri(URI.create(String.format("http://%s/%s", getControllerUrl(), path))), Optional.empty(), Optional.ofNullable(pinotConfig.getControllerRestService())); }

Target:
private
Source:
public IdentityHashMap<TableScanNode, Void> visitTableScan(TableScanNode node, Void context) { IdentityHashMap<TableScanNode, Void> ret = new IdentityHashMap<>(); ret.put(node, null); return ret; }

Target:
`Map<TableScanNode, Void> result = new IdentityHashMap<>();`
Source:
public TranslatedExpression<T> translate(FunctionMetadata functionMetadata, RowExpression original) { return translate(functionMetadata, original, emptyList()); }

Target:
ImmutableList.of()
Source:
public TestRowExpressionTranslator() { this.functionManager = METADATA.getFunctionManager(); this.functionResolution = new FunctionResolution(functionManager); this.determinismEvaluator = new RowExpressionDeterminismEvaluator(functionManager); this.sqlToRowExpressionTranslator = new TestingRowExpressionTranslator(METADATA); }

Target:
Can you also cover: 1) Function that does not have a rule, so we cannot translate? 2) Function has same name but different signature (for example input types are different)? 3) Function that is hidden, probably `not`. 4) Simple operators such as: +, -, > .
Source:
public static TypeSignature removeTypeParameters(TypeSignature typeSignature) { return new TypeSignature(typeSignature.getBase()); }

Target:
private
Source:
public static <T> TranslatedExpression<T> untranslated(RowExpression originalExpression) { return new TranslatedExpression<>(Optional.empty(), originalExpression, emptyList()); }

Target:
ImmutableList.of()
Source:
public void checkCanSetCatalogSessionProperty(ConnectorTransactionHandle transaction, ConnectorIdentity identity, String propertyName) { if (false && !isAdmin(transaction, identity)) { denySetCatalogSessionProperty(connectorId, propertyName); } }

Target:
Is this change intentional? As this means the method is not doing anything no matter what the input is.
Source:
Type getTypeForBlock(PinotColumnHandle pinotColumnHandle) { if (pinotColumnHandle.getColumnType().equals(INTEGER)) { return BIGINT; } else { return pinotColumnHandle.getColumnType(); } }

Target:
private static
Source:
private int getEstimatedColumnSizeInBytes(DataSchema.ColumnDataType dataType) { if (dataType.isNumber()) { switch (dataType) { case LONG: return Long.BYTES; case FLOAT: return Float.BYTES; case DOUBLE: return Double.BYTES; case INT: default: return Integer.BYTES; } } else { return pinotConfig.getEstimatedSizeInBytesForNonNumericColumn(); } }

Target:
`else` is redundant
Source:
static int getHashTableSize(int positionCount){ return HashCommon.arraySize(positionCount, 0.75f); }

Target:
nit: private?
Source:
static long getEstimatedAdditionalSize(int positionCount){ int hashSize = getHashTableSize(positionCount); long predictedKeySize = sizeOfIntArray(hashSize); long predictedPositionToHashesSize = sizeOfByteArray(positionCount); long predictedPositionLinksSize = sizeOfIntArray(positionCount); return predictedKeySize + predictedPositionToHashesSize + predictedPositionLinksSize; }

Target:
nit: public
Source:
private void skip(int items) throws IOException { if (presentStream != null) { int dataToSkip = presentStream.countBitsSet(items); if (inDictionaryStream != null) { inDictionaryStream.skip(dataToSkip); } if (dataStream != null) { dataStream.skip(dataToSkip); } } else { if (inDictionaryStream != null) { inDictionaryStream.skip(items); } dataStream.skip(items); } }

Target:
dataStream here can't be null, can it?
Source:
protected BlockLease newLease(Block block) { valuesInUse = true; return ClosingBlockLease.newLease(block, () -> valuesInUse = false); }

Target:
make it private