comment stringlengths 16 8.84k | method_body stringlengths 37 239k | target_code stringlengths 0 242 | method_body_after stringlengths 29 239k | context_before stringlengths 14 424k | context_after stringlengths 14 284k |
|---|---|---|---|---|---|
@malinthar let's push this as a separate PR. | private List<PackageInfo> getPackagesFromRepository(PackageRepository repository, List<String> skipList) {
Map<String, List<String>> packageMap = repository.getPackages();
List<PackageInfo> packages = new ArrayList<>();
packageMap.forEach((key, value) -> {
if (key.equals(Names.BALLERINA_INTERNAL_ORG.getValue())) {
retu... | clientLogger.logTrace("Failed to resolve package " | private List<PackageInfo> getPackagesFromRepository(PackageRepository repository, List<String> skipList) {
Map<String, List<String>> packageMap = repository.getPackages();
List<PackageInfo> packages = new ArrayList<>();
packageMap.forEach((key, value) -> {
if (key.equals(Names.BALLERINA_INTERNAL_ORG.getValue())) {
retu... | class LSPackageLoader {
public static final LanguageServerContext.Key<LSPackageLoader> LS_PACKAGE_LOADER_KEY =
new LanguageServerContext.Key<>();
private final List<PackageInfo> distRepoPackages;
private List<PackageInfo> remoteRepoPackages;
private List<PackageInfo> localRepoPackages;
private final LSClientLogger clie... | class LSPackageLoader {
public static final LanguageServerContext.Key<LSPackageLoader> LS_PACKAGE_LOADER_KEY =
new LanguageServerContext.Key<>();
private final List<PackageInfo> distRepoPackages;
private List<PackageInfo> remoteRepoPackages;
private List<PackageInfo> localRepoPackages;
private final LSClientLogger clie... |
I think we should stop discussing this here; this is relevant for the entirety of the documentation, and we could get much more experienced people involved if we target that instead. | private static Set<String> findEnabledReportersInConfiguration(Configuration configuration, String includedReportersString) {
Set<String> includedReporters = reporterListPattern.splitAsStream(includedReportersString)
.filter(r -> !r.isEmpty())
.collect(Collectors.toSet());
Set<String> namedOrderedReporters = new TreeSe... | LOG.info("Excluding reporter {}, not configured in reporter list ({}).", reporterName, includedReportersString); | private static Set<String> findEnabledReportersInConfiguration(Configuration configuration, String includedReportersString) {
Set<String> includedReporters = reporterListPattern.splitAsStream(includedReportersString)
.filter(r -> !r.isEmpty())
.collect(Collectors.toSet());
Set<String> namedOrderedReporters = new TreeSe... | class ReporterSetup {
private static final Logger LOG = LoggerFactory.getLogger(ReporterSetup.class);
private static final Pattern reporterListPattern = Pattern.compile("\\s*,\\s*");
private static final Pattern reporterClassPattern = Pattern.compile(
Pattern.quote(ConfigConstants.METRICS_REPORTER_PREFIX) +
"([\\S&&[^.... | class ReporterSetup {
private static final Logger LOG = LoggerFactory.getLogger(ReporterSetup.class);
private static final Pattern reporterListPattern = Pattern.compile("\\s*,\\s*");
private static final Pattern reporterClassPattern = Pattern.compile(
Pattern.quote(ConfigConstants.METRICS_REPORTER_PREFIX) +
"([\\S&&[^.... |
The output seems to be wrong. For the combination where Dependencies.toml exists and --sticky flag is given, we don't update automatically. Instead, we give a hint asking the user to set sticky to false. | public void testBuildProjectPrecompiledWithOlderDistWithStickyFlag() throws IOException {
Path projectPath = testResources.resolve("dep-dist-version-projects").resolve("preCompiledPackage");
replaceDependenciesTomlContent(projectPath, "**INSERT_DISTRIBUTION_VERSION_HERE**", "2201.5.0");
System.setProperty("user.dir", p... | .replaceAll("INSERT_OLD_DIST_VERSION_HERE", getOldVersionForOldDistWarning("2201.5.0"))); | public void testBuildProjectPrecompiledWithOlderDistWithStickyFlag() throws IOException {
Path projectPath = testResources.resolve("dep-dist-version-projects").resolve("preCompiledPackage");
replaceDependenciesTomlContent(projectPath, "**INSERT_DISTRIBUTION_VERSION_HERE**", "2201.5.0");
System.setProperty("user.dir", p... | class file
*/
@Test(description = "Build a ballerina project with conflicted jars")
public void testBuildBalProjectWithJarConflicts() throws IOException {
Path projectPath = this.testResources.resolve("projectWithConflictedJars");
System.setProperty("user.dir", projectPath.toString());
BuildCommand buildCommand = new B... | class file
*/
@Test(description = "Build a ballerina project with conflicted jars")
public void testBuildBalProjectWithJarConflicts() throws IOException {
Path projectPath = this.testResources.resolve("projectWithConflictedJars");
System.setProperty("user.dir", projectPath.toString());
BuildCommand buildCommand = new B... |
Immutable expression should not has mutable field. if we need some mutable state, we should depend the expression type to compute state, and change it when replace children e.g. UnboundExression.isAnalyzed() = false. other expression.isAnalyzed() = Suppliers.memoized(() -> children().allMatch(Expression::isAnalyzed)). | public List<Rule> buildRules() {
return ImmutableList.of(
RuleType.ANALYZE_PROJECT_SUBQUERY.build(
logicalProject().thenApply(ctx -> {
LogicalProject<GroupPlan> project = ctx.root;
List<SubqueryExpr> subqueryExprs = new ArrayList<>();
project.getProjects()
.forEach(expr -> subqueryExprs.addAll(extractSubquery(expr)));
... | RuleType.ANALYZE_SORT_SUBQUERY.build( | public List<Rule> buildRules() {
return ImmutableList.of(
RuleType.ANALYZE_FILTER_SUBQUERY.build(
logicalFilter().thenApply(ctx -> {
LogicalFilter filter = ctx.root;
List<SubqueryExpr> subqueryExprs = filter.getPredicates()
.collect(SubqueryExpr.class::isInstance);
if (subqueryExprs.isEmpty()) {
return filter;
}
return... | class AnalyzeSubquery implements AnalysisRuleFactory {
@Override
private List<SubqueryExpr> extractSubquery(Expression expression) {
if (expression instanceof SubqueryExpr) {
return ImmutableList.of((SubqueryExpr) expression);
}
Builder<SubqueryExpr> builder = ImmutableList.<SubqueryExpr>builder();
getAllSubquery(expre... | class AnalyzeSubquery implements AnalysisRuleFactory {
@Override
private LogicalPlan analyzedSubquery(List<SubqueryExpr> subqueryExprs,
LogicalPlan childPlan, CascadesContext ctx) {
LogicalPlan tmpPlan = childPlan;
for (SubqueryExpr subqueryExpr : subqueryExprs) {
if (!ctx.subqueryIsAnalyzed(subqueryExpr)) {
tmpPlan = ... |
We should generally avoid the use of [magic number ](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad) and replace it with what it stands for. | public static String parseOperationId(String operationLocation) {
if (!CoreUtils.isNullOrEmpty(operationLocation)) {
int lastIndex = operationLocation.lastIndexOf('/');
if (lastIndex != -1) {
return operationLocation.substring(lastIndex + 1, lastIndex + 37);
}
}
throw LOGGER.logExceptionAsError(
new RuntimeException("F... | return operationLocation.substring(lastIndex + 1, lastIndex + 37); | public static String parseOperationId(String operationLocation) {
if (!CoreUtils.isNullOrEmpty(operationLocation)) {
final int indexBeforeOperationId = operationLocation.lastIndexOf('/');
if (indexBeforeOperationId != -1) {
return operationLocation.substring(indexBeforeOperationId + 1,
indexBeforeOperationId + OPERATIO... | class Utility {
public static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(30);
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
private static final int NEUTRAL_SCORE_ZERO = 0;
private static final String DOCUMENT_SENTENCES_ASSESSMENTS_REG_EXP =
"
private static final Pattern PA... | class Utility {
public static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(30);
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
private static final int NEUTRAL_SCORE_ZERO = 0;
private static final int OPERATION_ID_LENGTH = 37;
private static final String DOCUMENT_SENTENCES_ASSE... |
If the cluster is using FQDN, but the host specified in the external OLAP table is IP, this check will not work. But I think it's OK to keep this simple logic, because creating OLAP External table mapping to self is a rare case, and using FQDN but specified IP is rare too. | public boolean checkFeExistByRPCPort(String host, int rpcPort) {
try {
tryLock(true);
return frontends
.values()
.stream()
.anyMatch(fe -> fe.getHost().equals(host) && fe.getRpcPort() == rpcPort);
} finally {
unlock();
}
} | .anyMatch(fe -> fe.getHost().equals(host) && fe.getRpcPort() == rpcPort); | public boolean checkFeExistByRPCPort(String host, int rpcPort) {
try {
tryLock(true);
return frontends
.values()
.stream()
.anyMatch(fe -> fe.getHost().equals(host) && fe.getRpcPort() == rpcPort);
} finally {
unlock();
}
} | class NodeMgr {
private static final Logger LOG = LogManager.getLogger(NodeMgr.class);
private static final int HTTP_TIMEOUT_SECOND = 5;
/**
* LeaderInfo
*/
@SerializedName(value = "r")
private int leaderRpcPort;
@SerializedName(value = "h")
private int leaderHttpPort;
@SerializedName(value = "ip")
private String leade... | class NodeMgr {
private static final Logger LOG = LogManager.getLogger(NodeMgr.class);
private static final int HTTP_TIMEOUT_SECOND = 5;
/**
* LeaderInfo
*/
@SerializedName(value = "r")
private int leaderRpcPort;
@SerializedName(value = "h")
private int leaderHttpPort;
@SerializedName(value = "ip")
private String leade... |
There are more than one `JandexUtil` used inside the enhancer ? Stange ... | private String recursivelyFindEntityTypeFromClass(DotName clazz, DotName repositoryDotName) {
if (clazz.equals(OBJECT_DOT_NAME)) {
return null;
}
List<org.jboss.jandex.Type> typeParameters = io.quarkus.deployment.util.JandexUtil
.resolveTypeParameters(clazz, repositoryDotName, indexView);
if (typeParameters.isEmpty())
... | List<org.jboss.jandex.Type> typeParameters = io.quarkus.deployment.util.JandexUtil | private String recursivelyFindEntityTypeFromClass(DotName clazz, DotName repositoryDotName) {
if (clazz.equals(OBJECT_DOT_NAME)) {
return null;
}
List<org.jboss.jandex.Type> typeParameters = io.quarkus.deployment.util.JandexUtil
.resolveTypeParameters(clazz, repositoryDotName, indexView);
if (typeParameters.isEmpty())
... | class PanacheRepositoryClassVisitor extends ClassVisitor {
protected Type entityType;
protected String entitySignature;
protected String entityBinaryType;
protected String daoBinaryName;
protected ClassInfo panacheRepositoryBaseClassInfo;
protected IndexView indexView;
public PanacheRepositoryClassVisitor(String classN... | class PanacheRepositoryClassVisitor extends ClassVisitor {
protected Type entityType;
protected String entitySignature;
protected String entityBinaryType;
protected String daoBinaryName;
protected ClassInfo panacheRepositoryBaseClassInfo;
protected IndexView indexView;
public PanacheRepositoryClassVisitor(String classN... |
Variable name of `describeStatement` should be `result`. | public ASTNode visitDesc(final DescContext ctx) {
TableSegment tablename = (TableSegment) visit(ctx.tableName());
DescribeStatement describeStatement = new DescribeStatement();
describeStatement.setTableName(tablename);
return describeStatement;
} | DescribeStatement describeStatement = new DescribeStatement(); | public ASTNode visitDesc(final DescContext ctx) {
TableSegment table = (TableSegment) visit(ctx.tableName());
DescribeStatement result = new DescribeStatement();
result.setTable(table);
return result;
} | class MySQLVisitor extends MySQLStatementBaseVisitor<ASTNode> implements SQLVisitor {
private int currentParameterIndex;
@Override
public ASTNode visitUse(final UseContext ctx) {
LiteralValue schema = (LiteralValue) visit(ctx.schemaName());
UseStatement useStatement = new UseStatement();
useStatement.setSchema(schema.g... | class MySQLVisitor extends MySQLStatementBaseVisitor<ASTNode> implements SQLVisitor {
private int currentParameterIndex;
@Override
public ASTNode visitUse(final UseContext ctx) {
LiteralValue schema = (LiteralValue) visit(ctx.schemaName());
UseStatement result = new UseStatement();
result.setSchema(schema.getLiteral())... |
maybe a enum is better than a boolean | public SortItems genSortItems(SortItemContext ctx) {
boolean orderDirection = true;
if (ctx.DESC() != null) {
orderDirection = false;
} else {
orderDirection = true;
}
Expression expression = typedVisit(ctx.expression());
NamedExpression namedExpression;
if (expression instanceof NamedExpression) {
namedExpression = (... | orderDirection = false; | public SortItems genSortItems(SortItemContext ctx) {
OrderDirection orderDirection;
if (ctx.DESC() != null) {
orderDirection = OrderDirection.DESC;
} else {
orderDirection = OrderDirection.ASC;
}
Expression expression = typedVisit(ctx.expression());
return new SortItems(expression, orderDirection);
} | class LogicalPlanBuilder extends DorisParserBaseVisitor<Object> {
/**
* Create a logical plan using a where clause.
*/
private final BiFunction<WhereClauseContext, LogicalPlan, LogicalPlan> withWhereClause =
(WhereClauseContext ctx, LogicalPlan plan)
-> new LogicalUnaryPlan(new LogicalFilter(expression((ctx.booleanExpr... | class LogicalPlanBuilder extends DorisParserBaseVisitor<Object> {
/**
* Create a logical plan using a where clause.
*/
private final BiFunction<WhereClauseContext, LogicalPlan, LogicalPlan> withWhereClause =
(WhereClauseContext ctx, LogicalPlan plan)
-> new LogicalUnaryPlan(new LogicalFilter(expression((ctx.booleanExpr... |
If the thread is still alive, do we also need to `Thread.currentThread().interrupt()`? | public void close() throws IOException {
wasClosed = true;
while (thread.isAlive()) {
thread.interrupt();
try {
thread.join();
} catch (InterruptedException e) {
if (!thread.isAlive()) {
Thread.currentThread().interrupt();
}
LOG.debug("interrupted while waiting for the writer thread to die", e);
}
}
if (thrown != null)... | thread.interrupt(); | public void close() throws IOException {
wasClosed = true;
while (thread.isAlive()) {
thread.interrupt();
try {
thread.join();
} catch (InterruptedException e) {
if (!thread.isAlive()) {
Thread.currentThread().interrupt();
}
LOG.debug("interrupted while waiting for the writer thread to die", e);
}
}
if (thrown != null)... | class ChannelStateWriteRequestExecutorImpl implements ChannelStateWriteRequestExecutor {
private static final Logger LOG = LoggerFactory.getLogger(ChannelStateWriteRequestExecutorImpl.class);
private static final int DEFAULT_HANDOVER_CAPACITY = 10_000;
private final ChannelStateWriteRequestDispatcher dispatcher;
privat... | class ChannelStateWriteRequestExecutorImpl implements ChannelStateWriteRequestExecutor {
private static final Logger LOG = LoggerFactory.getLogger(ChannelStateWriteRequestExecutorImpl.class);
private static final int DEFAULT_HANDOVER_CAPACITY = 10_000;
private final ChannelStateWriteRequestDispatcher dispatcher;
privat... |
not necessary to log warning, I will add it to query trace log. | private void prepareRelatedMVs(Set<Table> queryTables, Set<MaterializedView> relatedMvs, boolean isSyncMV) {
String queryExcludingMVNames = connectContext.getSessionVariable().getQueryExcludingMVNames();
String queryIncludingMVNames = connectContext.getSessionVariable().getQueryIncludingMVNames();
if (!Strings.isNullOr... | private void prepareRelatedMVs(Set<Table> queryTables, Set<MaterializedView> relatedMvs, boolean isSyncMV) {
String queryExcludingMVNames = connectContext.getSessionVariable().getQueryExcludingMVNames();
String queryIncludingMVNames = connectContext.getSessionVariable().getQueryIncludingMVNames();
if (!Strings.isNullOr... | class MvRewritePreprocessor {
private static final Logger LOG = LogManager.getLogger(MvRewritePreprocessor.class);
private final ConnectContext connectContext;
private final ColumnRefFactory queryColumnRefFactory;
private final OptimizerContext context;
private final OptExpression logicOperatorTree;
public MvRewritePre... | class MvRewritePreprocessor {
private static final Logger LOG = LogManager.getLogger(MvRewritePreprocessor.class);
private final ConnectContext connectContext;
private final ColumnRefFactory queryColumnRefFactory;
private final OptimizerContext context;
private final OptExpression logicOperatorTree;
public MvRewritePre... | |
convert TIME, FIXED,BINARY to VARBINARY? | public static Type fromIcebergType(org.apache.iceberg.types.Type icebergType) {
if (icebergType == null) {
return Type.NULL;
}
PrimitiveType primitiveType;
switch (icebergType.typeId()) {
case BOOLEAN:
primitiveType = PrimitiveType.BOOLEAN;
break;
case INTEGER:
primitiveType = PrimitiveType.INT;
break;
case LONG:
primi... | case FIXED: | public static Type fromIcebergType(org.apache.iceberg.types.Type icebergType) {
if (icebergType == null) {
return Type.NULL;
}
PrimitiveType primitiveType;
switch (icebergType.typeId()) {
case BOOLEAN:
primitiveType = PrimitiveType.BOOLEAN;
break;
case INTEGER:
primitiveType = PrimitiveType.INT;
break;
case LONG:
primi... | class ColumnTypeConverter {
public static final String DECIMAL_PATTERN = "^decimal\\((\\d+), *(\\d+)\\)";
public static final String COMPLEX_PATTERN = "([0-9a-z<>(),:_ ]+)";
public static final String ARRAY_PATTERN = "^array<" + COMPLEX_PATTERN + ">";
public static final String MAP_PATTERN = "^map<" + COMPLEX_PATTERN +... | class ColumnTypeConverter {
public static final String DECIMAL_PATTERN = "^decimal\\((\\d+), *(\\d+)\\)";
public static final String COMPLEX_PATTERN = "([0-9a-z<>(),:_ ]+)";
public static final String ARRAY_PATTERN = "^array<" + COMPLEX_PATTERN + ">";
public static final String MAP_PATTERN = "^map<" + COMPLEX_PATTERN +... |
Can we move this line into the open method? | public void emitResults() throws IOException {
byte[] udfResult;
while ((udfResult = userDefinedFunctionResultQueue.poll()) != null) {
bais.setBuffer(udfResult, 0, udfResult.length);
reader.loadNextBatch();
VectorSchemaRoot root = reader.getVectorSchemaRoot();
if (arrowReader == null) {
arrowReader = ArrowUtils.createB... | arrowReader = ArrowUtils.createBaseRowArrowReader(root); | public void emitResults() throws IOException {
byte[] udfResult;
while ((udfResult = userDefinedFunctionResultQueue.poll()) != null) {
bais.setBuffer(udfResult, 0, udfResult.length);
reader.loadNextBatch();
VectorSchemaRoot root = reader.getVectorSchemaRoot();
if (arrowReader == null) {
arrowReader = ArrowUtils.createB... | class BaseRowArrowPythonScalarFunctionOperator extends AbstractBaseRowPythonScalarFunctionOperator {
private static final long serialVersionUID = 1L;
/**
* Allocator which is used for byte buffer allocation.
*/
private transient BufferAllocator allocator;
/**
* Reader which is responsible for deserialize the Arrow form... | class BaseRowArrowPythonScalarFunctionOperator extends AbstractBaseRowPythonScalarFunctionOperator {
private static final long serialVersionUID = 1L;
/**
* Allocator which is used for byte buffer allocation.
*/
private transient BufferAllocator allocator;
/**
* Reader which is responsible for deserialize the Arrow form... |
I did another deep search - I found one case in SQL's codegen which I fixed, but can't find anything else. | private static List<TableFieldSchema> toTableFieldSchema(Schema schema) {
List<TableFieldSchema> fields = new ArrayList<>(schema.getFieldCount());
for (Field schemaField : schema.getFields()) {
FieldType type = schemaField.getType();
TableFieldSchema field = new TableFieldSchema().setName(schemaField.getName());
if (sc... | if (type.getTypeName().isCollectionType()) { | private static List<TableFieldSchema> toTableFieldSchema(Schema schema) {
List<TableFieldSchema> fields = new ArrayList<>(schema.getFieldCount());
for (Field schemaField : schema.getFields()) {
FieldType type = schemaField.getType();
TableFieldSchema field = new TableFieldSchema().setName(schemaField.getName());
if (sc... | class Builder {
public abstract Builder setTruncateTimestamps(TruncateTimestamps truncateTimestamps);
public abstract ConversionOptions build();
} | class Builder {
public abstract Builder setTruncateTimestamps(TruncateTimestamps truncateTimestamps);
public abstract ConversionOptions build();
} |
Timestamp is the sort key here. As our OrderedListState interface is based on TimestampedValue<T>, the sort key is actually an Instant, but I agree that I should be consistent here by using "sort key". The reason why I put the value encoded bytes before the sort key encoded bytes is that the same order is used in the ... | public CompletableFuture<StateResponse> handle(StateRequest.Builder requestBuilder) {
assertEquals("", requestBuilder.getId());
requestBuilder.setId(generateId());
StateRequest request = requestBuilder.build();
StateKey key = request.getStateKey();
StateResponse.Builder response;
assertNotEquals(RequestCase.REQUEST_NOT... | public CompletableFuture<StateResponse> handle(StateRequest.Builder requestBuilder) {
assertEquals("", requestBuilder.getId());
requestBuilder.setId(generateId());
StateRequest request = requestBuilder.build();
StateKey key = request.getStateKey();
StateResponse.Builder response;
assertNotEquals(RequestCase.REQUEST_NOT... | class FakeBeamFnStateClient implements BeamFnStateClient {
private static final int DEFAULT_CHUNK_SIZE = 6;
private final Map<StateKey, List<ByteString>> data;
private int currentId;
private final Map<StateKey, NavigableSet<Long>> orderedListKeys;
public <V> FakeBeamFnStateClient(Coder<V> valueCoder, Map<StateKey, List... | class FakeBeamFnStateClient implements BeamFnStateClient {
private static final int DEFAULT_CHUNK_SIZE = 6;
private final Map<StateKey, List<ByteString>> data;
private int currentId;
private final Map<StateKey, NavigableSet<Long>> orderedListSortKeysFromStateKey;
public <V> FakeBeamFnStateClient(Coder<V> valueCoder, Ma... | |
Hi @totalo This change causes build failed on JDK11 and JDK17. Is there any problem before? ``` [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project shardingsphere-infra-common: Compilation failure [ERROR] /Users/wuweijie/IdeaProjects/shardingsphere/s... | public YamlSchema swapToYamlConfiguration(final ShardingSphereSchema schema) {
Map<String, YamlTableMetaData> tables = schema.getAllTableNames().stream()
.collect(Collectors.<String, String, YamlTableMetaData, Map>toMap(each -> each, each -> swapYamlTable(schema.get(each)), (oldValue, currentValue) -> oldValue, LinkedH... | .collect(Collectors.<String, String, YamlTableMetaData, Map>toMap(each -> each, each -> swapYamlTable(schema.get(each)), (oldValue, currentValue) -> oldValue, LinkedHashMap::new)); | public YamlSchema swapToYamlConfiguration(final ShardingSphereSchema schema) {
Map<String, YamlTableMetaData> tables = schema.getAllTableNames().stream()
.collect(Collectors.<String, String, YamlTableMetaData, Map>toMap(each -> each, each -> swapYamlTable(schema.get(each)), (oldValue, currentValue) -> oldValue, LinkedH... | class SchemaYamlSwapper implements YamlConfigurationSwapper<YamlSchema, ShardingSphereSchema> {
@Override
@Override
public ShardingSphereSchema swapToObject(final YamlSchema yamlConfig) {
return Optional.ofNullable(yamlConfig).map(this::swapSchema).orElseGet(ShardingSphereSchema::new);
}
private ShardingSphereSchema sw... | class SchemaYamlSwapper implements YamlConfigurationSwapper<YamlSchema, ShardingSphereSchema> {
@Override
@Override
public ShardingSphereSchema swapToObject(final YamlSchema yamlConfig) {
return Optional.ofNullable(yamlConfig).map(this::swapSchema).orElseGet(ShardingSphereSchema::new);
}
private ShardingSphereSchema sw... |
consider putting `UnregisteredMetricGroups.createUnregisteredJobManagerJobMetricGroup()` into some static variable and using that. | void testRegisterConsumedPartitionGroupToEdgeManager() throws Exception {
JobVertex v1 = new JobVertex("source");
JobVertex v2 = new JobVertex("sink");
v1.setParallelism(2);
v2.setParallelism(2);
v2.connectNewDataSetAsInput(
v1, DistributionPattern.ALL_TO_ALL, ResultPartitionType.BLOCKING);
List<JobVertex> ordered = ne... | ordered, UnregisteredMetricGroups.createUnregisteredJobManagerJobMetricGroup()); | void testRegisterConsumedPartitionGroupToEdgeManager() throws Exception {
JobVertex v1 = new JobVertex("source");
JobVertex v2 = new JobVertex("sink");
v1.setParallelism(2);
v2.setParallelism(2);
v2.connectNewDataSetAsInput(
v1, DistributionPattern.ALL_TO_ALL, ResultPartitionType.BLOCKING);
List<JobVertex> ordered = ne... | class DefaultExecutionGraphConstructionTest {
@RegisterExtension
static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_RESOURCE =
TestingUtils.defaultExecutorExtension();
private ExecutionGraph createDefaultExecutionGraph(List<JobVertex> vertices) throws Exception {
return TestingDefaultExecutionGraphBu... | class DefaultExecutionGraphConstructionTest {
@RegisterExtension
static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_RESOURCE =
TestingUtils.defaultExecutorExtension();
private static final JobManagerJobMetricGroup JOB_MANAGER_JOB_METRIC_GROUP =
UnregisteredMetricGroups.createUnregisteredJobManagerJob... |
Are these two lines necessary? Because we haven't even call the `write` method, why do we care about them? | void testClose() {
int numSubpartitions = 10;
TestingTierProducerAgent tierProducerAgent = new TestingTierProducerAgent();
tierProducerAgent.setTryStartNewSegmentReturnValueSupplier(() -> true);
tierProducerAgent.setTryWriteReturnValueSupplier(() -> new Boolean[] {false, true});
assertThat(tierProducerAgent.isClosed())... | tierProducerAgent.setTryWriteReturnValueSupplier(() -> new Boolean[] {false, true}); | void testClose() {
int numSubpartitions = 10;
AtomicBoolean isClosed = new AtomicBoolean(false);
TestingTierProducerAgent tierProducerAgent =
new TestingTierProducerAgent.Builder()
.setCloseRunnable(() -> isClosed.set(true))
.build();
TieredStorageProducerClient tieredStorageProducerClient =
createTieredStorageProducer... | class TieredStorageProducerClientTest {
private static final int NUM_TOTAL_BUFFERS = 1000;
private static final int NETWORK_BUFFER_SIZE = 1024;
@Parameter public boolean isBroadcast;
private NetworkBufferPool globalPool;
@Parameters(name = "isBroadcast={0}")
public static Collection<Boolean> parameters() {
return Array... | class TieredStorageProducerClientTest {
private static final int NUM_TOTAL_BUFFERS = 1000;
private static final int NETWORK_BUFFER_SIZE = 1024;
@Parameter public boolean isBroadcast;
private NetworkBufferPool globalPool;
@Parameters(name = "isBroadcast={0}")
public static Collection<Boolean> parameters() {
return Array... |
`ArrayList<JarFile>` should be declared as `Collection<JarFile>` | public void assertInitPluginLifecycleService() {
Map<String, PluginConfiguration> pluginConfigs = new HashMap<>();
ArrayList<JarFile> pluginJars = new ArrayList<>();
PluginLifecycleServiceManager.init(pluginConfigs, pluginJars, new MultipleParentClassLoader(new ArrayList<>()),
true);
} | ArrayList<JarFile> pluginJars = new ArrayList<>(); | public void assertInitPluginLifecycleService() {
Map<String, PluginConfiguration> pluginConfigs = new HashMap<>();
Collection<JarFile> pluginJars = new LinkedList<>();
PluginLifecycleServiceManager.init(pluginConfigs, pluginJars, new MultipleParentClassLoader(new LinkedList<>()),
true);
} | class PluginLifecycleServiceManagerTest {
@Test
@Test
public void assertInitPluginLifecycleServiceWithMap() {
Map<String, PluginConfiguration> stringPluginConfigurationMap = new HashMap<>();
stringPluginConfigurationMap.put("Key", new PluginConfiguration("localhost", 8080, "random", new Properties()));
ArrayList<JarFil... | class PluginLifecycleServiceManagerTest {
@Test
@Test
public void assertInitPluginLifecycleServiceWithMap() {
Map<String, PluginConfiguration> stringPluginConfigurationMap = new HashMap<>();
stringPluginConfigurationMap.put("Key", new PluginConfiguration("localhost", 8080, "random", new Properties()));
Collection<JarFi... |
Move the `() ->` down to the next line too, so it is `() -> listKeysFirstPage(),` | public PagedFlux<KeyBase> listKeys() {
return new PagedFlux<>(() -> listKeysFirstPage(),
continuationToken -> listKeysNextPage(continuationToken));
} | continuationToken -> listKeysNextPage(continuationToken)); | public PagedFlux<KeyBase> listKeys() {
return new PagedFlux<>(() ->
listKeysFirstPage(),
continuationToken -> listKeysNextPage(continuationToken));
} | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String endpoint;
private final Ke... | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String endpoint;
private final Ke... |
I am planning to do another round of cleanup to make things a bit more consistent , I will address this later during the code cleanup ;) | public void publishTelemetryLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient client = getAsyncClient(httpClient, serviceVersion);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
S... | createModelsAndTwins(client, wifiModelId, roomWithWifiModelId, roomWithWifiTwinId); | public void publishTelemetryLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient client = getAsyncClient(httpClient, serviceVersion);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
S... | class PublishTelemetryAsyncTests extends PublishTelemetryTestBase {
private final ClientLogger logger = new ClientLogger(PublishTelemetryAsyncTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
private void createModelsAndTwins(DigitalTwin... | class PublishTelemetryAsyncTests extends PublishTelemetryTestBase {
private final ClientLogger logger = new ClientLogger(PublishTelemetryAsyncTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
private void createModelsAndTwins(DigitalTwin... |
Is this `if` check a relevant change to this bug fix? If not, could you please extract it to a separate hotfix commit in this PR to avoid confusions? | public void recycle(MemorySegment segment) {
Buffer releasedFloatingBuffer = null;
synchronized (bufferQueue) {
try {
if (inputChannel.isReleased()) {
globalPool.recycleMemorySegments(Collections.singletonList(segment));
} else {
releasedFloatingBuffer =
bufferQueue.addExclusiveBuffer(
new NetworkBuffer(segment, this),... | } | public void recycle(MemorySegment segment) {
@Nullable Buffer releasedFloatingBuffer = null;
synchronized (bufferQueue) {
try {
if (inputChannel.isReleased()) {
globalPool.recycleMemorySegments(Collections.singletonList(segment));
return;
} else {
releasedFloatingBuffer =
bufferQueue.addExclusiveBuffer(
new NetworkBuff... | class BufferManager implements BufferListener, BufferRecycler {
/** The available buffer queue wraps both exclusive and requested floating buffers. */
private final AvailableBufferQueue bufferQueue = new AvailableBufferQueue();
/** The buffer provider for requesting exclusive buffers. */
private final MemorySegmentProv... | class BufferManager implements BufferListener, BufferRecycler {
/** The available buffer queue wraps both exclusive and requested floating buffers. */
private final AvailableBufferQueue bufferQueue = new AvailableBufferQueue();
/** The buffer provider for requesting exclusive buffers. */
private final MemorySegmentProv... |
This should be performed after closing the output stream | private static void runCompressionGzip(File oldFile) {
File gzippedFile = new File(oldFile.getPath() + ".gz");
try (GZIPOutputStream compressor = new GZIPOutputStream(new FileOutputStream(gzippedFile), 0x100000);
FileInputStream inputStream = new FileInputStream(oldFile)) {
byte[] buffer = new byte[0x400000];
long tota... | nativeIO.dropFileFromCache(gzippedFile); | private static void runCompressionGzip(File oldFile) {
File gzippedFile = new File(oldFile.getPath() + ".gz");
NativeIO nativeIO = new NativeIO();
try (GZIPOutputStream compressor = new GZIPOutputStream(new FileOutputStream(gzippedFile), 0x100000);
FileInputStream inputStream = new FileInputStream(oldFile)) {
byte[] bu... | class LogThread<LOGTYPE> extends Thread {
long lastFlush = 0;
private FileOutputStream currentOutputStream = null;
private long nextRotationTime = 0;
private final String filePattern;
private String fileName;
private long lastDropPosition = 0;
private final LogWriter<LOGTYPE> logWriter;
private final ArrayBlockingQueue... | class LogThread<LOGTYPE> extends Thread {
private final Pollable<LOGTYPE> operationProvider;
long lastFlush = 0;
private FileOutputStream currentOutputStream = null;
private long nextRotationTime = 0;
private final String filePattern;
private volatile String fileName;
private long lastDropPosition = 0;
private final Lo... |
Yeah, didn't want to add extra dependency :) but yes, I agree. We could use that. | private String getVersionFromPomFile() {
String fileName = "pom.xml";
String versionStartTag = "<version>";
String versionEndTag = "</version>";
File file = new File(fileName);
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while((line = bufferedReader.readLine()) != null) ... | try { | private String getVersionFromPomFile() {
String fileName = "pom.xml";
String versionStartTag = "<version>";
String versionEndTag = "</version>";
File file = new File(fileName);
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while((line = bufferedReader.readLine()) != null) ... | class AzureCosmosPropertiesTest {
@Test(groups = "unit")
public void verifyAzureCosmosProperties() {
Map<String, String> properties =
CoreUtils.getProperties(HttpConstants.Versions.AZURE_COSMOS_PROPERTIES_FILE_NAME);
assertThat(properties).isNotNull();
assertThat(properties).isNotEmpty();
assertThat(properties.get("ver... | class AzureCosmosPropertiesTest {
@Test(groups = "unit")
public void verifyAzureCosmosProperties() {
Map<String, String> properties =
CoreUtils.getProperties(HttpConstants.Versions.AZURE_COSMOS_PROPERTIES_FILE_NAME);
assertThat(properties).isNotNull();
assertThat(properties).isNotEmpty();
assertThat(properties.get("ver... |
Are you afraid that the `System.getProperty("user.home")` is cached at build time? | public String getObjectStoreDir() {
return System.getProperty("user.home") + File.separator + "ObjectStore";
} | return System.getProperty("user.home") + File.separator + "ObjectStore"; | public String getObjectStoreDir() {
return System.getProperty("user.home") + File.separator + "ObjectStore";
} | class ObjectStoreEnvironmentBeanSubstitution {
/**
* @return fixed ObjectStore path resolved during runtime
*/
@Substitute
} | class ObjectStoreEnvironmentBeanSubstitution {
/**
* @return fixed ObjectStore path resolved during runtime
*/
@Substitute
} |
@IrushiL, Thank you for pointing out the issue here. Fixed the logical error. | public XMLNamespaceDeclarationNode transform(XMLNamespaceDeclarationNode xMLNamespaceDeclarationNode) {
Token xmlnsKeyword = getToken(xMLNamespaceDeclarationNode.xmlnsKeyword());
ExpressionNode namespaceuri = this.modifyNode(xMLNamespaceDeclarationNode.namespaceuri());
Token asKeyword = getToken(xMLNamespaceDeclaration... | if (asKeyword != null || namespacePrefix != null) { | public XMLNamespaceDeclarationNode transform(XMLNamespaceDeclarationNode xMLNamespaceDeclarationNode) {
Token xmlnsKeyword = getToken(xMLNamespaceDeclarationNode.xmlnsKeyword());
ExpressionNode namespaceuri = this.modifyNode(xMLNamespaceDeclarationNode.namespaceuri());
Token asKeyword = getToken(xMLNamespaceDeclaration... | class FormattingTreeModifier extends TreeModifier {
private FormattingOptions formattingOptions;
private LineRange lineRange;
@Override
public ImportDeclarationNode transform(ImportDeclarationNode importDeclarationNode) {
if (!isInLineRange(importDeclarationNode)) {
return importDeclarationNode;
}
Token importKeyword =... | class FormattingTreeModifier extends TreeModifier {
private FormattingOptions formattingOptions;
private LineRange lineRange;
@Override
public ImportDeclarationNode transform(ImportDeclarationNode importDeclarationNode) {
if (!isInLineRange(importDeclarationNode)) {
return importDeclarationNode;
}
Token importKeyword =... |
Good catch. I wasn't previously thinking about state restoring. I think type serializer does need to be checkpointed and restored (code [link](https://github.com/apache/flink/blob/master/flink-runtime/src/main/java/org/apache/flink/runtime/state/StateSerializerProvider.java#L99)) I'm less sure about how type info ser... | private void writeObject(ObjectOutputStream oos) throws IOException {
byte[] schemaStrInBytes = schema.toString(false).getBytes(StandardCharsets.UTF_8);
oos.writeInt(schemaStrInBytes.length);
oos.write(schemaStrInBytes);
} | byte[] schemaStrInBytes = schema.toString(false).getBytes(StandardCharsets.UTF_8); | private void writeObject(ObjectOutputStream oos) throws IOException {
byte[] schemaStrInBytes = schema.toString(false).getBytes(StandardCharsets.UTF_8);
oos.writeInt(schemaStrInBytes.length);
oos.write(schemaStrInBytes);
} | class GenericRecordAvroTypeInfo extends TypeInformation<GenericRecord> {
private static final long serialVersionUID = 4141977586453820650L;
private transient Schema schema;
public GenericRecordAvroTypeInfo(Schema schema) {
this.schema = checkNotNull(schema);
}
@Override
public boolean isBasicType() {
return false;
}
@O... | class GenericRecordAvroTypeInfo extends TypeInformation<GenericRecord> {
private static final long serialVersionUID = 4141977586453820650L;
private transient Schema schema;
public GenericRecordAvroTypeInfo(Schema schema) {
this.schema = checkNotNull(schema);
}
@Override
public boolean isBasicType() {
return false;
}
@O... |
Can cpuPeriod() and cpuQuota() be updated to return long? | private CreateContainerCmd createCreateContainerCmd() {
List<Bind> volumeBinds = volumeBindSpecs.stream().map(Bind::parse).collect(Collectors.toList());
final HostConfig hostConfig = new HostConfig()
.withSecurityOpts(new ArrayList<>(securityOpts))
.withBinds(volumeBinds)
.withUlimits(ulimits)
.withCapAdd(addCapabiliti... | .withCpuPeriod(cr.cpuQuota() > 0 ? (long) cr.cpuPeriod() : null) | private CreateContainerCmd createCreateContainerCmd() {
List<Bind> volumeBinds = volumeBindSpecs.stream().map(Bind::parse).collect(Collectors.toList());
final HostConfig hostConfig = new HostConfig()
.withSecurityOpts(new ArrayList<>(securityOpts))
.withBinds(volumeBinds)
.withUlimits(ulimits)
.withCapAdd(addCapabiliti... | class CreateContainerCommandImpl implements Docker.CreateContainerCommand {
private final DockerClient docker;
private final DockerImage dockerImage;
private final ContainerName containerName;
private final Map<String, String> labels = new HashMap<>();
private final List<String> environmentAssignments = new ArrayList<>... | class CreateContainerCommandImpl implements Docker.CreateContainerCommand {
private final DockerClient docker;
private final DockerImage dockerImage;
private final ContainerName containerName;
private final Map<String, String> labels = new HashMap<>();
private final List<String> environmentAssignments = new ArrayList<>... |
@Sanne the kube use case is only valid for demos IMO, and even then providing a cache cr is a more production real use case than creating it from the properties, but for simplicity is clearly something easy to be done. I will remove the file and let URI and pasted configuration as it is | private ConfigurationBuilder builderFromProperties(Properties properties) {
ConfigurationBuilder builder = new ConfigurationBuilder();
Object marshallerInstance = properties.remove(ConfigurationProperties.MARSHALLER);
if (marshallerInstance != null) {
if (marshallerInstance instanceof ProtoStreamMarshaller) {
handlePro... | InfinispanClientRuntimeConfig.RemoteCacheConfig remoteCacheConfig = cache.getValue(); | private ConfigurationBuilder builderFromProperties(Properties properties) {
ConfigurationBuilder builder = new ConfigurationBuilder();
Object marshallerInstance = properties.remove(ConfigurationProperties.MARSHALLER);
if (marshallerInstance != null) {
if (marshallerInstance instanceof ProtoStreamMarshaller) {
handlePro... | class path to read contents of
* @return string containing the contents of the file
*/
private static String getContents(String fileName) {
InputStream stream = InfinispanClientProducer.class.getResourceAsStream(fileName);
return getContents(stream);
} | class path to read contents of
* @return string containing the contents of the file
*/
private static String getContents(String fileName) {
InputStream stream = InfinispanClientProducer.class.getResourceAsStream(fileName);
return getContents(stream);
} |
I created a JIRA for this: https://issues.apache.org/jira/browse/BEAM-10611 Please add a TODO here such that we can make improvement on this in the future. | private static Value beamLogicalObjectToZetaSqlValue(Object object, String identifier) {
if (SqlTypes.DATE.getIdentifier().equals(identifier)) {
if (object instanceof Long) {
return Value.createDateValue(((Long) object).intValue());
} else {
return Value.createDateValue((int) ((LocalDate) object).toEpochDay());
}
} els... | return Value.createDatetimeValue( | private static Value beamLogicalObjectToZetaSqlValue(Object object, String identifier) {
if (SqlTypes.DATE.getIdentifier().equals(identifier)) {
if (object instanceof Long) {
return Value.createDateValue(((Long) object).intValue());
} else {
return Value.createDateValue((int) ((LocalDate) object).toEpochDay());
}
} els... | class ZetaSqlBeamTranslationUtils {
private static final long MICROS_PER_MILLI = 1000L;
private ZetaSqlBeamTranslationUtils() {}
public static Type beamFieldTypeToZetaSqlType(FieldType fieldType) {
switch (fieldType.getTypeName()) {
case INT64:
return TypeFactory.createSimpleType(TypeKind.TYPE_INT64);
case DOUBLE:
retu... | class ZetaSqlBeamTranslationUtils {
private static final long MICROS_PER_MILLI = 1000L;
private ZetaSqlBeamTranslationUtils() {}
public static Type beamFieldTypeToZetaSqlType(FieldType fieldType) {
switch (fieldType.getTypeName()) {
case INT64:
return TypeFactory.createSimpleType(TypeKind.TYPE_INT64);
case DOUBLE:
retu... |
@glefloch can you think of a trick to make `quarkusGenerateCodeDev` run only when the intention is to launch the dev mode? Perhaps, the task can be disabled by default and enabled by the `quarkusDev` somehow? | private void registerTasks(Project project, QuarkusPluginExtension quarkusExt) {
TaskContainer tasks = project.getTasks();
tasks.create(LIST_EXTENSIONS_TASK_NAME, QuarkusListExtensions.class);
tasks.create(LIST_CATEGORIES_TASK_NAME, QuarkusListCategories.class);
tasks.create(LIST_PLATFORMS_TASK_NAME, QuarkusListPlatfor... | compileJavaTask.mustRunAfter(quarkusGenerateCode); | private void registerTasks(Project project, QuarkusPluginExtension quarkusExt) {
TaskContainer tasks = project.getTasks();
tasks.create(LIST_EXTENSIONS_TASK_NAME, QuarkusListExtensions.class);
tasks.create(LIST_CATEGORIES_TASK_NAME, QuarkusListCategories.class);
tasks.create(LIST_PLATFORMS_TASK_NAME, QuarkusListPlatfor... | class QuarkusPlugin implements Plugin<Project> {
public static final String ID = "io.quarkus";
public static final String QUARKUS_PACKAGE_TYPE = "quarkus.package.type";
public static final String EXTENSION_NAME = "quarkus";
public static final String LIST_EXTENSIONS_TASK_NAME = "listExtensions";
public static final Str... | class QuarkusPlugin implements Plugin<Project> {
public static final String ID = "io.quarkus";
public static final String QUARKUS_PACKAGE_TYPE = "quarkus.package.type";
public static final String EXTENSION_NAME = "quarkus";
public static final String LIST_EXTENSIONS_TASK_NAME = "listExtensions";
public static final Str... |
As of now, no. We may eventually need to support both import and provided but currently we have no use case for them. | static List<BomDependency> parsePomFileContent(Reader responseStream) {
List<BomDependency> bomDependencies = new ArrayList<>();
ObjectMapper mapper = new XmlMapper();
try {
HashMap<String, Object> value = mapper.readValue(responseStream, HashMap.class);
Object packagingProp = value.getOrDefault("packaging", null);
if(... | default: scopeType = ScopeType.COMPILE; | static List<BomDependency> parsePomFileContent(Reader responseStream) {
List<BomDependency> bomDependencies = new ArrayList<>();
ObjectMapper mapper = new XmlMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
try {
Model value = mapper.readValue(responseStream, Model.class);
List<Dependency> d... | class Utils {
public static final String COMMANDLINE_INPUTDIRECTORY = "inputdir";
public static final String COMMANDLINE_OUTPUTDIRECTORY = "outputdir";
public static final String EMPTY_STRING = "";
public static final String COMMANDLINE_INPUTFILE = "inputfile";
public static final String COMMANDLINE_OUTPUTFILE = "outpu... | class Utils {
public static final String COMMANDLINE_INPUTDIRECTORY = "inputdir";
public static final String COMMANDLINE_OUTPUTDIRECTORY = "outputdir";
public static final String COMMANDLINE_MODE = "mode";
public static final String ANALYZE_MODE = "analyze";
public static final String GENERATE_MODE = "generate";
public... |
With 864788ea19e77a6292976f2b999a8c933034371d we simply rewrite the build file | public void save() {
Path buildFilePath = this.sourceRoot.resolve(TARGET_DIR_NAME).resolve(BUILD_FILE);
boolean shouldUpdate = this.currentPackage().getResolution().autoUpdate();
if (!buildFilePath.toFile().exists()) {
createBuildFile(buildFilePath);
writeBuildFile(buildFilePath);
writeDependencies();
} else {
try {
Bu... | writeDependencies(); | public void save() {
Path buildFilePath = this.sourceRoot.resolve(TARGET_DIR_NAME).resolve(BUILD_FILE);
boolean shouldUpdate = this.currentPackage().getResolution().autoUpdate();
if (!buildFilePath.toFile().exists()) {
createBuildFile(buildFilePath);
writeBuildFile(buildFilePath);
writeDependencies();
} else {
BuildJso... | class BuildProject extends Project {
/**
* Loads a BuildProject from the provided path.
*
* @param projectPath Ballerina project path
* @return build project
*/
public static BuildProject load(ProjectEnvironmentBuilder environmentBuilder, Path projectPath) {
return load(environmentBuilder, projectPath, new BuildOptions... | class BuildProject extends Project {
/**
* Loads a BuildProject from the provided path.
*
* @param projectPath Ballerina project path
* @return build project
*/
public static BuildProject load(ProjectEnvironmentBuilder environmentBuilder, Path projectPath) {
return load(environmentBuilder, projectPath, new BuildOptions... |
Can you modify the kernel logic instead of sql parse logic? | private BinaryOperationExpression createPatternMatchingOperationSegment(final AExprContext ctx) {
String operator = getOriginalText(ctx.patternMatchingOperator()).toUpperCase();
ExpressionSegment left = (ExpressionSegment) visit(ctx.aExpr(0));
ListExpression right = new ListExpression(ctx.aExpr(1).start.getStartIndex()... | String operator = getOriginalText(ctx.patternMatchingOperator()).toUpperCase(); | private BinaryOperationExpression createPatternMatchingOperationSegment(final AExprContext ctx) {
String operator = getOriginalText(ctx.patternMatchingOperator()).toUpperCase();
ExpressionSegment left = (ExpressionSegment) visit(ctx.aExpr(0));
ListExpression right = new ListExpression(ctx.aExpr(1).start.getStartIndex()... | class PostgreSQLStatementSQLVisitor extends PostgreSQLStatementParserBaseVisitor<ASTNode> {
private final Collection<ParameterMarkerSegment> parameterMarkerSegments = new LinkedList<>();
public PostgreSQLStatementSQLVisitor(final Properties props) {
}
@Override
public final ASTNode visitParameterMarker(final ParameterM... | class PostgreSQLStatementSQLVisitor extends PostgreSQLStatementParserBaseVisitor<ASTNode> {
private final Collection<ParameterMarkerSegment> parameterMarkerSegments = new LinkedList<>();
public PostgreSQLStatementSQLVisitor(final Properties props) {
}
@Override
public final ASTNode visitParameterMarker(final ParameterM... |
do we need to validate whether exception is CosmosException? | public Mono<ShouldRetryResult> shouldRetry(Exception e) {
if (this.request == null) {
logger.error("onBeforeSendRequest has not been invoked with the MetadataRequestRetryPolicy...");
return Mono.just(ShouldRetryResult.error(e));
}
CosmosException cosmosException = Utils.as(e, CosmosException.class);
if (shouldMarkRegio... | CosmosException cosmosException = Utils.as(e, CosmosException.class); | public Mono<ShouldRetryResult> shouldRetry(Exception e) {
return webExceptionRetryPolicy.shouldRetry(e).flatMap(shouldRetryResult -> {
if (!shouldRetryResult.shouldRetry) {
if (this.request == null || this.webExceptionRetryPolicy == null) {
logger.error("onBeforeSendRequest has not been invoked with the MetadataRequest... | class MetadataRequestRetryPolicy implements IRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(MetadataRequestRetryPolicy.class);
private final GlobalEndpointManager globalEndpointManager;
private RxDocumentServiceRequest request;
public MetadataRequestRetryPolicy(GlobalEndpointManager globalEn... | class MetadataRequestRetryPolicy implements IRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(MetadataRequestRetryPolicy.class);
private final GlobalEndpointManager globalEndpointManager;
private RxDocumentServiceRequest request;
private WebExceptionRetryPolicy webExceptionRetryPolicy;
public ... |
thats what that method returns | private ParserRuleContext getNextRuleForVarName() {
ParserRuleContext parentCtx = getParentContext();
if (parentCtx == ParserRuleContext.REQUIRED_PARAM || parentCtx == ParserRuleContext.PARAM_LIST) {
return ParserRuleContext.REQUIRED_PARAM_NAME_RHS;
} else if (parentCtx == ParserRuleContext.DEFAULTABLE_PARAM) {
return ... | return getNextRuleForTypedBindingPattern(); | private ParserRuleContext getNextRuleForVarName() {
ParserRuleContext parentCtx = getParentContext();
if (parentCtx == ParserRuleContext.REQUIRED_PARAM || parentCtx == ParserRuleContext.PARAM_LIST) {
return ParserRuleContext.REQUIRED_PARAM_NAME_RHS;
} else if (parentCtx == ParserRuleContext.DEFAULTABLE_PARAM) {
return ... | class BallerinaParserErrorHandler extends AbstractParserErrorHandler {
/**
* FUNC_DEF_OR_FUNC_TYPE --> When a func-def and func-type-desc are possible.
* e.g: start of a module level construct that starts with 'function' keyword.
*/
private static final ParserRuleContext[] FUNC_TYPE_OR_DEF_OPTIONAL_RETURNS =
{ ParserRu... | class BallerinaParserErrorHandler extends AbstractParserErrorHandler {
/**
* FUNC_DEF_OR_FUNC_TYPE --> When a func-def and func-type-desc are possible.
* e.g: start of a module level construct that starts with 'function' keyword.
*/
private static final ParserRuleContext[] FUNC_TYPE_OR_DEF_OPTIONAL_RETURNS =
{ ParserRu... |
Add a rule to check whether this jar exists | public static URLClassLoader getClassLoader(String jarPath, ClassLoader parent) throws MalformedURLException {
URL url = new URL(jarPath);
return URLClassLoader.newInstance(new URL[] {url}, parent);
} | URL url = new URL(jarPath); | public static URLClassLoader getClassLoader(String jarPath, ClassLoader parent)
throws MalformedURLException, FileNotFoundException {
File file = new File(jarPath);
if (!file.exists()) {
throw new FileNotFoundException("Can not find local file: " + jarPath);
}
URL url = file.toURI().toURL();
return URLClassLoader.newIn... | class || c == Character.class) {
return Sets.newHashSet(JavaUdfDataType.CHAR);
} | class || c == Character.class) {
return Sets.newHashSet(JavaUdfDataType.CHAR);
} |
nit: shorter branch first is slightly easier to read | private Schema payloadSchema() {
if (useFlatSchema()) {
Schema.Builder builder = Schema.builder();
for (Schema.Field field : messageSchema().getFields()) {
if (field.getName().equals(TIMESTAMP_FIELD)) {
continue;
}
builder.addField(field);
}
return builder.build();
} else {
return messageSchema().getField(PAYLOAD_FIELD... | continue; | private Schema payloadSchema() {
if (!useFlatSchema()) {
return messageSchema().getField(PAYLOAD_FIELD).getType().getRowSchema();
} else {
return new Schema(
messageSchema().getFields().stream()
.filter(f -> !f.getName().equals(TIMESTAMP_FIELD))
.collect(Collectors.toList()));
}
} | class PubsubMessageToRow extends DoFn<PubsubMessage, Row> {
static final String TIMESTAMP_FIELD = "event_timestamp";
static final String ATTRIBUTES_FIELD = "attributes";
static final String PAYLOAD_FIELD = "payload";
static final TupleTag<PubsubMessage> DLQ_TAG = new TupleTag<PubsubMessage>() {};
static final TupleTag<... | class PubsubMessageToRow extends DoFn<PubsubMessage, Row> {
static final String TIMESTAMP_FIELD = "event_timestamp";
static final String ATTRIBUTES_FIELD = "attributes";
static final String PAYLOAD_FIELD = "payload";
static final TupleTag<PubsubMessage> DLQ_TAG = new TupleTag<PubsubMessage>() {};
static final TupleTag<... |
Is it valid when no Condition, or no Action? If it is valid, should we let user create without calling them? Would avoid user write `define...().withMatchConditions().withActions().attach()` | public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) {
List<DeliveryRuleAction> actionList = new ArrayList<>();
if (actions != null) {
actionList.addAll(Arrays.asList(actions));
}
innerModel().withActions(actionList);
return this;
} | } | public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) {
List<DeliveryRuleAction> actionList = new ArrayList<>();
if (actions != null) {
actionList.addAll(Arrays.asList(actions));
}
innerModel().withActions(actionList);
return this;
} | class CdnStandardRulesEngineRuleImpl
extends ChildResourceImpl<DeliveryRule, CdnEndpointImpl, CdnEndpoint>
implements CdnStandardRulesEngineRule,
CdnStandardRulesEngineRule.Definition<CdnEndpointImpl>,
CdnStandardRulesEngineRule.Update<CdnEndpointImpl> {
CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, String nam... | class CdnStandardRulesEngineRuleImpl
extends ChildResourceImpl<DeliveryRule, CdnEndpointImpl, CdnEndpoint>
implements CdnStandardRulesEngineRule,
CdnStandardRulesEngineRule.Definition<CdnEndpointImpl>,
CdnStandardRulesEngineRule.Update<CdnEndpointImpl> {
CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, String nam... |
Shouldn't we reset the original TCCL after the command is run? | public void run(Runnable command) {
Thread.currentThread().setContextClassLoader(classLoader);
command.run();
} | command.run(); | public void run(Runnable command) {
ClassLoader originalTccl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try {
command.run();
} finally {
Thread.currentThread().setContextClassLoader(originalTccl);
}
} | class DevModeWrapper {
private final ClassLoader classLoader;
public DevModeWrapper(ClassLoader contextClassLoader) {
classLoader = contextClassLoader;
}
} | class DevModeWrapper {
private final ClassLoader classLoader;
public DevModeWrapper(ClassLoader contextClassLoader) {
classLoader = contextClassLoader;
}
} |
According with documentation, I could do just this. Tell me what do you think. ``` Path artifact = target.getOutputDirectory().resolve(name); File file = new File(artifact.toString()); file.setExecutable(true, true); ``` | public static void writeExecutableFile(OutputTargetBuildItem target, String name, String output) throws IOException {
writeFile(target, name, output);
Path artifact = target.getOutputDirectory().resolve(name);
Set<PosixFilePermission> permissions = new HashSet<>();
permissions.add(PosixFilePermission.OWNER_READ);
permi... | Files.setPosixFilePermissions(artifact, permissions); | public static void writeExecutableFile(OutputTargetBuildItem target, String name, String output) throws IOException {
writeFile(target, name, output);
Path artifact = target.getOutputDirectory().resolve(name);
artifact.toFile().setExecutable(true, true);
} | class LambdaUtil {
/**
* Strips period, dash, and numbers. Turns characters after to uppercase. i.e.
* Also strips "-SNAPSHOT" from end of name.
*
* "foo.bar-1.0-SNAPSHOT" to "FooBar"
*
* @param basename
* @return
*/
public static String artifactToLambda(String basename) {
if (basename.endsWith("-SNAPSHOT"))
basename =... | class LambdaUtil {
/**
* Strips period, dash, and numbers. Turns characters after to uppercase. i.e.
* Also strips "-SNAPSHOT" from end of name.
*
* "foo.bar-1.0-SNAPSHOT" to "FooBar"
*
* @param basename
* @return
*/
public static String artifactToLambda(String basename) {
if (basename.endsWith("-SNAPSHOT"))
basename =... |
This comment seems out of place, no? | public Enumeration<URL> getResources(String nm) throws IOException {
ClassLoaderState state = getState();
String name = sanitizeName(nm);
boolean banned = state.bannedResources.contains(name);
Set<URL> resources = new LinkedHashSet<>();
if (name.startsWith(META_INF_SERVICES)) {
try {
Class<?> c = loadClass(name.substri... | public Enumeration<URL> getResources(String nm) throws IOException {
ClassLoaderState state = getState();
String name = sanitizeName(nm);
boolean banned = state.bannedResources.contains(name);
Set<URL> resources = new LinkedHashSet<>();
if (name.startsWith(META_INF_SERVICES)) {
try {
Class<?> c = loadClass(name.substri... | class loading where it attempts to resolve stuff from the parent
super(PLATFORM_CLASS_LOADER);
this.name = builder.name;
this.elements = builder.elements;
this.bytecodeTransformers = builder.bytecodeTransformers;
this.bannedElements = builder.bannedElements;
this.parentFirstElements = builder.parentFirstElements;
this.... | class loading where it attempts to resolve stuff from the parent
super(PLATFORM_CLASS_LOADER);
this.name = builder.name;
this.elements = builder.elements;
this.bytecodeTransformers = builder.bytecodeTransformers;
this.bannedElements = builder.bannedElements;
this.parentFirstElements = builder.parentFirstElements;
this.... | |
Why do we need this exactly? | public Receive createReceive() {
return ReceiveBuilder.create()
.match(
RemoteHandshakeMessage.class,
withCleanContextClassLoader(this::handleHandshakeMessage))
.match(
ControlMessages.class,
withCleanContextClassLoader(this::handleControlMessage))
.matchAny(withCleanContextClassLoader(this::handleMessage))
.build();
} | .matchAny(withCleanContextClassLoader(this::handleMessage)) | public Receive createReceive() {
return ReceiveBuilder.create()
.match(RemoteHandshakeMessage.class, this::handleHandshakeMessage)
.match(ControlMessages.class, this::handleControlMessage)
.matchAny(this::handleMessage)
.build();
} | class AkkaRpcActor<T extends RpcEndpoint & RpcGateway> extends AbstractActor {
protected final Logger log = LoggerFactory.getLogger(getClass());
/** the endpoint to invoke the methods on. */
protected final T rpcEndpoint;
/** the helper that tracks whether calls come from the main thread. */
private final MainThreadVal... | class AkkaRpcActor<T extends RpcEndpoint & RpcGateway> extends AbstractActor {
protected final Logger log = LoggerFactory.getLogger(getClass());
/** the endpoint to invoke the methods on. */
protected final T rpcEndpoint;
private final ClassLoader flinkClassLoader;
/** the helper that tracks whether calls come from the... |
I see 2 paths above for assigning to `from`: ``` String from = String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName()); if (!Strings.isNullOrEmpty(options.getPrismLocation())) { checkArgument( !options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX), ... | String resolve() throws IOException {
String from =
String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName());
if (!Strings.isNullOrEmpty(options.getPrismLocation())) {
checkArgument(
!options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX),
"Provided --prismLocation URL is not an Apache... | if (from.startsWith("http")) { | String resolve() throws IOException {
String from =
String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName());
if (!Strings.isNullOrEmpty(options.getPrismLocation())) {
checkArgument(
!options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX),
"Provided --prismLocation URL is not an Apache... | class PrismLocator {
static final String OS_NAME_PROPERTY = "os.name";
static final String ARCH_PROPERTY = "os.arch";
static final String USER_HOME_PROPERTY = "user.home";
private static final String ZIP_EXT = "zip";
private static final String SHA512_EXT = "sha512";
private static final ReleaseInfo RELEASE_INFO = Rele... | class PrismLocator {
static final String OS_NAME_PROPERTY = "os.name";
static final String ARCH_PROPERTY = "os.arch";
static final String USER_HOME_PROPERTY = "user.home";
private static final String ZIP_EXT = "zip";
private static final ReleaseInfo RELEASE_INFO = ReleaseInfo.getReleaseInfo();
private static final Stri... |
I don't think the comment `// this is not used any more in the new scheduler` is needed. It would not be consistent to comment here because there is another invocation of this constructor where we do not comment. I would remove the parameters `slotProvider` and `slotRequestTimeout` from the `DefaultScheduler`, and if p... | public DefaultScheduler build() throws Exception {
return new DefaultScheduler(
log,
jobGraph,
backPressureStatsTracker,
ioExecutor,
jobMasterConfiguration,
new SimpleSlotProvider(jobGraph.getJobID(), 0),
futureExecutor,
delayExecutor,
userCodeLoader,
checkpointRecoveryFactory,
rpcTimeout,
blobWriter,
jobManagerJobMetr... | new SimpleSlotProvider(jobGraph.getJobID(), 0), | public DefaultScheduler build() throws Exception {
return new DefaultScheduler(
log,
jobGraph,
backPressureStatsTracker,
ioExecutor,
jobMasterConfiguration,
futureExecutor,
delayExecutor,
userCodeLoader,
checkpointRecoveryFactory,
rpcTimeout,
blobWriter,
jobManagerJobMetricGroup,
shuffleMaster,
partitionTracker,
schedu... | class DefaultSchedulerBuilder {
private final JobGraph jobGraph;
private SchedulingStrategyFactory schedulingStrategyFactory;
private Logger log = LOG;
private BackPressureStatsTracker backPressureStatsTracker = VoidBackPressureStatsTracker.INSTANCE;
private Executor ioExecutor = java.util.concurrent.Executors.newSingl... | class DefaultSchedulerBuilder {
private final JobGraph jobGraph;
private SchedulingStrategyFactory schedulingStrategyFactory;
private Logger log = LOG;
private BackPressureStatsTracker backPressureStatsTracker = VoidBackPressureStatsTracker.INSTANCE;
private Executor ioExecutor = TestingUtils.defaultExecutor();
private... |
Shall we move this to a constant? | public static Object removeIfHasKey(Strand strand, MapValue<?, ?> m, String k) {
String op = "removeIfHasKey()";
checkIsMapOnlyOperation(m.getType(), op);
checkValidFieldForRecord(m, k, op);
try {
return m.remove(k);
} catch (org.ballerinalang.jvm.util.exceptions.BLangFreezeException e) {
throw BallerinaErrors.createEr... | String op = "removeIfHasKey()"; | public static Object removeIfHasKey(Strand strand, MapValue<?, ?> m, String k) {
String op = Constants.REMOVE_IF_HAS_KEY;
checkIsMapOnlyOperation(m.getType(), op);
checkValidFieldForRecord(m, k, op);
try {
return m.remove(k);
} catch (org.ballerinalang.jvm.util.exceptions.BLangFreezeException e) {
throw BallerinaErrors... | class RemoveIfHasKey {
} | class RemoveIfHasKey {
} |
Hmm I wonder how are we going to handle parallel artifact upload streams in the future. Fine to leave as a TODO for now, I suspect it'd require some small API changes. | public void onNext(PutArtifactRequest putArtifactRequest) {
if (metadata == null) {
metadata = putArtifactRequest.getMetadata();
try {
ResourceId artifactsDirId = getArtifactDirResourceId(
putArtifactRequest.getMetadata().getStagingSessionToken());
LOG.info("Going to stage artifact {} in {}.", metadata.getMetadata().ge... | public void onNext(PutArtifactRequest putArtifactRequest) {
if (metadata == null) {
checkNotNull(putArtifactRequest);
checkNotNull(putArtifactRequest.getMetadata());
metadata = putArtifactRequest.getMetadata();
try {
ResourceId artifactsDirId = getArtifactDirResourceId(
putArtifactRequest.getMetadata().getStagingSessio... | class PutArtifactStreamObserver implements StreamObserver<PutArtifactRequest> {
private final StreamObserver<PutArtifactResponse> outboundObserver;
private PutArtifactMetadata metadata;
private ResourceId artifactId;
private WritableByteChannel artifactWritableByteChannel;
PutArtifactStreamObserver(StreamObserver<PutAr... | class PutArtifactStreamObserver implements StreamObserver<PutArtifactRequest> {
private final StreamObserver<PutArtifactResponse> outboundObserver;
private PutArtifactMetadata metadata;
private ResourceId artifactId;
private WritableByteChannel artifactWritableByteChannel;
PutArtifactStreamObserver(StreamObserver<PutAr... | |
If we're using this private method in `restRead` too, it should go below it to be more readable. Could you move this? | private void testWrite() {
Pipeline pipeline = Pipeline.create(options);
BigQueryIO.Write.Method method = BigQueryIO.Write.Method.valueOf(writeMethod);
pipeline
.apply("Read from source", Read.from(new SyntheticBoundedSource(sourceOptions)))
.apply("Gather time", ParDo.of(new TimeMonitor<>(NAMESPACE, WRITE_TIME_METRIC_... | .apply("Read from source", Read.from(new SyntheticBoundedSource(sourceOptions))) | private void testWrite() {
Pipeline pipeline = Pipeline.create(options);
BigQueryIO.Write.Method method = BigQueryIO.Write.Method.valueOf(options.getWriteMethod());
pipeline
.apply("Read from source", Read.from(new SyntheticBoundedSource(sourceOptions)))
.apply("Gather time", ParDo.of(new TimeMonitor<>(NAMESPACE, WRITE... | class BigQueryIOIT {
private static final String NAMESPACE = BigQueryIOIT.class.getName();
private static String metricsBigQueryTable;
private static String metricsBigQueryDataset;
private static String testBigQueryDataset;
private static String testBigQueryTable;
private static SyntheticSourceOptions sourceOptions;
pr... | class BigQueryIOIT {
private static final String NAMESPACE = BigQueryIOIT.class.getName();
private static final String TEST_ID = UUID.randomUUID().toString();
private static final String TEST_TIMESTAMP = Timestamp.now().toString();
private static final String READ_TIME_METRIC_NAME = "read_time";
private static final St... |
This logic won't be required anymore. | private void setCurrentReader(int index) {
Preconditions.checkArgument(index != currentSourceIndex);
if (currentReader != null) {
try {
currentReader.close();
} catch (Exception e) {
throw new RuntimeException("Failed to close current reader", e);
}
LOG.debug(
"Reader closed: subtask={} sourceIndex={} currentReader={}"... | completeAndResetAvailabilityHelper(); | private void setCurrentReader(int index) {
Preconditions.checkArgument(index != currentSourceIndex);
if (currentReader != null) {
try {
currentReader.close();
} catch (Exception e) {
throw new RuntimeException("Failed to close current reader", e);
}
LOG.debug(
"Reader closed: subtask={} sourceIndex={} currentReader={}"... | class HybridSourceReader<T> implements SourceReader<T, HybridSourceSplit> {
private static final Logger LOG = LoggerFactory.getLogger(HybridSourceReader.class);
private final SourceReaderContext readerContext;
private final SwitchedSources switchedSources = new SwitchedSources();
private int currentSourceIndex = -1;
pr... | class HybridSourceReader<T> implements SourceReader<T, HybridSourceSplit> {
private static final Logger LOG = LoggerFactory.getLogger(HybridSourceReader.class);
private final SourceReaderContext readerContext;
private final SwitchedSources switchedSources = new SwitchedSources();
private int currentSourceIndex = -1;
pr... |
Shall we call `analyzeNode` instead? ```suggestion conversionExpr.annAttachments.forEach(annotationAttachment -> analyzeNode(annotationAttachment, env)); ``` | public void visit(BLangTypeConversionExpr conversionExpr) {
analyzeExpr(conversionExpr.expr);
conversionExpr.annAttachments.forEach(annotationAttachment -> annotationAttachment.accept(this));
} | conversionExpr.annAttachments.forEach(annotationAttachment -> annotationAttachment.accept(this)); | public void visit(BLangTypeConversionExpr conversionExpr) {
analyzeExpr(conversionExpr.expr);
conversionExpr.annAttachments.forEach(annotationAttachment -> analyzeNode(annotationAttachment, env));
} | class CodeAnalyzer extends BLangNodeVisitor {
private static final CompilerContext.Key<CodeAnalyzer> CODE_ANALYZER_KEY =
new CompilerContext.Key<>();
private static final String NULL_LITERAL = "null";
private final SymbolResolver symResolver;
private int loopCount;
private int transactionCount;
private boolean statemen... | class CodeAnalyzer extends BLangNodeVisitor {
private static final CompilerContext.Key<CodeAnalyzer> CODE_ANALYZER_KEY =
new CompilerContext.Key<>();
private static final String NULL_LITERAL = "null";
private final SymbolResolver symResolver;
private int loopCount;
private int transactionCount;
private boolean statemen... |
Yes, that's a good addition. | private static void testSourceDoesNotShutdown(boolean shouldHaveReaders) throws Exception {
final int parallelism = 2;
FlinkPipelineOptions options = PipelineOptionsFactory.as(FlinkPipelineOptions.class);
TestCountingSource source = new TestCountingSource(20).withoutSplitting();
UnboundedSourceWrapper<KV<Integer, Integ... | thread.interrupt(); | private static void testSourceDoesNotShutdown(boolean shouldHaveReaders) throws Exception {
final int parallelism = 2;
FlinkPipelineOptions options = PipelineOptionsFactory.as(FlinkPipelineOptions.class);
TestCountingSource source = new TestCountingSource(20).withoutSplitting();
UnboundedSourceWrapper<KV<Integer, Integ... | class BasicTest {
/** Check serialization a {@link UnboundedSourceWrapper}. */
@Test
public void testSerialization() throws Exception {
final int parallelism = 1;
final int numElements = 20;
PipelineOptions options = PipelineOptionsFactory.create();
TestCountingSource source = new TestCountingSource(numElements);
Unbou... | class BasicTest {
/** Check serialization a {@link UnboundedSourceWrapper}. */
@Test
public void testSerialization() throws Exception {
final int parallelism = 1;
final int numElements = 20;
PipelineOptions options = PipelineOptionsFactory.create();
TestCountingSource source = new TestCountingSource(numElements);
Unbou... |
if we are matching specific scenarios (eg. a native function) in these if conditions; shall we move those into private methods for the readability. For example; then we may write `if (isNativeFunction(...)) {` | public String getSourceForFunction(JsonObject node, boolean pretty, boolean replaceLambda, SourceGenParams sourceGenParams) {
if (node.get("defaultConstructor") != null
&& node.get("defaultConstructor") .getAsBoolean()) {
return "";
} else if (node.get("isConstructor") != null
&& node.get("isConstructor") .getAsBoolean... | && node.get("returnTypeNode") != null) { | public String getSourceForFunction(JsonObject node, boolean pretty, boolean replaceLambda, SourceGenParams sourceGenParams) {
if (node.get("defaultConstructor") != null
&& node.get("defaultConstructor") .getAsBoolean()) {
return "";
} else if (node.get("isConstructor") != null
&& node.get("isConstructor") .getAsBoolean... | class SourceGen {
private static final String TAB = " ";
private int l = 0;
private Map<String, JsonObject> anonTypes = new HashMap<>();
public SourceGen(int l) {
this.l = l;
}
public String getSourceForImport(JsonObject node, boolean pretty, boolean replaceLambda, SourceGenParams sourceGenParams) {
if (node.get("is... | class SourceGen {
private static final String TAB = " ";
private int l = 0;
private Map<String, JsonObject> anonTypes = new HashMap<>();
public SourceGen(int l) {
this.l = l;
}
public String getSourceForImport(JsonObject node, boolean pretty, boolean replaceLambda, SourceGenParams sourceGenParams) {
if (node.get("is... |
the purpose of `getCreateDocumentRequest` is just to create the request. retry-policy interaction should happen outside. why are we moving this? | private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PUT);
if(request.requestContext != null && documentClientRetryPolicy.getRetryCount() > 0) {
documentClientRetryPolicy.updateEndTime();
request.req... | return getStoreProxy(request).processMessage(request); | private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PUT);
if(request.requestContext != null && documentClientRetryPolicy.getRetryCount() > 0) {
documentClientRetryPolicy.updateEndTime();
request.req... | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider {
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEn... | class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider {
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper();
private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class);
private final String masterKeyOrResourceToken;
private final URI serviceEn... |
For now, this is ok I guess. But this should be set to the position covering the finite type elements. i.e., starting pos should be the first element's starting pos and the ending pos should be the last element's ending pos. | public BLangNode transform(UnionTypeDescriptorNode unionTypeDescriptorNode) {
List<TypeDescriptorNode> nodes = flattenUnionType(unionTypeDescriptorNode);
List<TypeDescriptorNode> finiteTypeElements = new ArrayList<>();
List<List<TypeDescriptorNode>> unionTypeElementsCollection = new ArrayList<>();
for (TypeDescriptorNo... | bLangFiniteTypeNode.setPosition(unionTypeNode.pos); | public BLangNode transform(UnionTypeDescriptorNode unionTypeDescriptorNode) {
List<TypeDescriptorNode> nodes = flattenUnionType(unionTypeDescriptorNode);
List<TypeDescriptorNode> finiteTypeElements = new ArrayList<>();
List<List<TypeDescriptorNode>> unionTypeElementsCollection = new ArrayList<>();
for (TypeDescriptorNo... | class BLangNodeTransformer extends NodeTransformer<BLangNode> {
private static final String IDENTIFIER_LITERAL_PREFIX = "'";
private BLangDiagnosticLog dlog;
private SymbolTable symTable;
private PackageCache packageCache;
private PackageID packageID;
private String currentCompUnitName;
private BLangCompilationUnit cur... | class BLangNodeTransformer extends NodeTransformer<BLangNode> {
private static final String IDENTIFIER_LITERAL_PREFIX = "'";
private BLangDiagnosticLog dlog;
private SymbolTable symTable;
private PackageCache packageCache;
private PackageID packageID;
private String currentCompUnitName;
private BLangCompilationUnit cur... |
Yes it does. If we see flakiness later we can add some idle time. | public void validQuerySucceeds(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
... | StepVerifier.create(asyncClient.query(queryString, BasicDigitalTwin.class)) | public void validQuerySucceeds(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
... | class QueryAsyncTests extends QueryTestBase{
private final ClientLogger logger = new ClientLogger(ComponentsTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | class QueryAsyncTests extends QueryTestBase{
private final ClientLogger logger = new ClientLogger(ComponentsTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} |
These are [already cleared](https://github.com/ballerina-platform/ballerina-lang/blob/274e1dca660da80cc2854bbba37cec60a9b51acb/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsolationAnalyzer.java#L3527) at the end of this method though, via [`inferIsolation`](https://github.co... | public BLangPackage analyze(BLangPackage pkgNode) {
this.arrowFunctionTempSymbolMap.clear();
this.isolationInferenceInfoMap.clear();
this.dlog.setCurrentPackageId(pkgNode.packageID);
SymbolEnv pkgEnv = this.symTable.pkgEnvMap.get(pkgNode.symbol);
Set<BSymbol> moduleLevelVarSymbols = getModuleLevelVarSymbols(pkgNode.glo... | this.isolationInferenceInfoMap.clear(); | public BLangPackage analyze(BLangPackage pkgNode) {
this.arrowFunctionTempSymbolMap.clear();
this.isolationInferenceInfoMap.clear();
this.dlog.setCurrentPackageId(pkgNode.packageID);
SymbolEnv pkgEnv = this.symTable.pkgEnvMap.get(pkgNode.symbol);
Set<BSymbol> moduleLevelVarSymbols = getModuleLevelVarSymbols(pkgNode.glo... | class IsolationAnalyzer extends BLangNodeVisitor {
private static final CompilerContext.Key<IsolationAnalyzer> ISOLATION_ANALYZER_KEY = new CompilerContext.Key<>();
private static final String VALUE_LANG_LIB = "lang.value";
private static final String CLONE_LANG_LIB_METHOD = "clone";
private static final String CLONE_R... | class IsolationAnalyzer extends BLangNodeVisitor {
private static final CompilerContext.Key<IsolationAnalyzer> ISOLATION_ANALYZER_KEY = new CompilerContext.Key<>();
private static final String VALUE_LANG_LIB = "lang.value";
private static final String CLONE_LANG_LIB_METHOD = "clone";
private static final String CLONE_R... |
Hi, there is problem in here. When we are loading image, we shouldn't write the editLog, or else some error will report (Because bdbje is open only after the image has been loaded). | public static DeleteHandler read(DataInput in) throws IOException {
String json = Text.readString(in);
DeleteHandler deleteHandler = GsonUtils.GSON.fromJson(json, DeleteHandler.class);
deleteHandler.removeOldDeleteInfos();
return deleteHandler;
} | return deleteHandler; | public static DeleteHandler read(DataInput in) throws IOException {
String json = Text.readString(in);
DeleteHandler deleteHandler = GsonUtils.GSON.fromJson(json, DeleteHandler.class);
deleteHandler.removeOldDeleteInfos(new Timestamp());
return deleteHandler;
} | class DeleteHandler extends MasterDaemon implements Writable {
private static final Logger LOG = LogManager.getLogger(DeleteHandler.class);
private Map<Long, DeleteJob> idToDeleteJob;
@SerializedName(value = "dbToDeleteInfos")
private Map<Long, List<DeleteInfo>> dbToDeleteInfos;
private ReentrantReadWriteLock lock;
pub... | class DeleteHandler implements Writable {
private static final Logger LOG = LogManager.getLogger(DeleteHandler.class);
private Map<Long, DeleteJob> idToDeleteJob;
@SerializedName(value = "dbToDeleteInfos")
private Map<Long, List<DeleteInfo>> dbToDeleteInfos;
private ReentrantReadWriteLock lock;
public DeleteHandler() {... |
Hm this is concerning - if we start with 0 shards, the queue is forever doomed to be of size 1 which is probably quite bad for performance. | void start() throws TransientKinesisException {
ImmutableMap.Builder<String, ShardRecordsIterator> shardsMap = ImmutableMap.builder();
for (ShardCheckpoint checkpoint : initialCheckpoint) {
shardsMap.put(checkpoint.getShardId(), createShardIterator(kinesis, checkpoint));
}
shardIteratorsMap.set(shardsMap.build());
if (... | } | void start() throws TransientKinesisException {
ImmutableMap.Builder<String, ShardRecordsIterator> shardsMap = ImmutableMap.builder();
for (ShardCheckpoint checkpoint : initialCheckpoint) {
shardsMap.put(checkpoint.getShardId(), createShardIterator(kinesis, checkpoint));
}
shardIteratorsMap.set(shardsMap.build());
if (... | class ShardReadersPool {
private static final Logger LOG = LoggerFactory.getLogger(ShardReadersPool.class);
private static final int DEFAULT_CAPACITY_PER_SHARD = 10_000;
/**
* Executor service for running the threads that read records from shards handled by this pool.
* Each thread runs the {@link ShardReadersPool
* ha... | class ShardReadersPool {
private static final Logger LOG = LoggerFactory.getLogger(ShardReadersPool.class);
private static final int DEFAULT_CAPACITY_PER_SHARD = 10_000;
/**
* Executor service for running the threads that read records from shards handled by this pool.
* Each thread runs the {@link ShardReadersPool
* ha... |
Ok, I changed a total time of retrying to 1 minute. I believe it should be quite enough for most of the cases as a default value. | private void flush(int numMax) throws InterruptedException, IOException {
int retries = spec.getRetries();
int numOutstandingRecords = producer.getOutstandingRecordsCount();
while (numOutstandingRecords > numMax && retries-- > 0) {
producer.flush();
Thread.sleep(1000);
numOutstandingRecords = producer.getOutstandingRec... | } | private void flush(int numMax) throws InterruptedException, IOException {
int retries = spec.getRetries();
int numOutstandingRecords = producer.getOutstandingRecordsCount();
int retryTimeout = 1000;
while (numOutstandingRecords > numMax && retries-- > 0) {
producer.flush();
Thread.sleep(retryTimeout);
numOutstandingRec... | class KinesisWriterFn extends DoFn<byte[], Void> {
private static final int MAX_NUM_RECORDS = 100 * 1000;
private static final int MAX_NUM_FAILURES = 10;
private final KinesisIO.Write spec;
private transient IKinesisProducer producer;
private transient KinesisPartitioner partitioner;
private transient LinkedBlockingDeq... | class KinesisWriterFn extends DoFn<byte[], Void> {
private static final int MAX_NUM_RECORDS = 100 * 1000;
private static final int MAX_NUM_FAILURES = 10;
private final KinesisIO.Write spec;
private transient IKinesisProducer producer;
private transient KinesisPartitioner partitioner;
private transient LinkedBlockingDeq... |
you are right, i will fix it. | private boolean executeStatement(String statement, ExecutionMode executionMode) {
try {
final Optional<Operation> operation = parseCommand(statement);
operation.ifPresent(op -> callOperation(op, executionMode));
} catch (SqlExecutionException e) {
Throwable t = ExceptionUtils.getRootCause(e);
if (t instanceof Interrupt... | } | private boolean executeStatement(String statement, ExecutionMode executionMode) {
try {
final Optional<Operation> operation = parseCommand(statement);
operation.ifPresent(
op -> {
final Thread thread = Thread.currentThread();
final Terminal.SignalHandler previousHandler =
terminal.handle(
Terminal.Signal.INT, (signal) ... | class CliClient implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(CliClient.class);
public static final Supplier<Terminal> DEFAULT_TERMINAL_FACTORY =
TerminalUtils::createDefaultTerminal;
private final Executor executor;
private final String sessionId;
private final Path historyFilePa... | class CliClient implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(CliClient.class);
public static final Supplier<Terminal> DEFAULT_TERMINAL_FACTORY =
TerminalUtils::createDefaultTerminal;
private final Executor executor;
private final String sessionId;
private final Path historyFilePa... |
I think this should be testing the json content rather than an exact JSON string. For some examples see: https://github.com/rest-assured/rest-assured/wiki/usage . I think it should be more like: .body("errorMessage", is("Resource Not Found")) .body("existingResourcesDetails.basePath",is("/")) etc | public void testJsonResourceNotFound() {
RestAssured.given().accept(ContentType.JSON)
.when().get("/not_found")
.then()
.statusCode(404)
.body(Matchers.is("{\"errorMessage\":\"Resource Not Found\",\"existingResourcesDetails\":" +
"[{\"basePath\":\"/\",\"calls\":[{\"fullPath\":\"/\",\"method\":\"GET\"}]}]}"));
} | .body(Matchers.is("{\"errorMessage\":\"Resource Not Found\",\"existingResourcesDetails\":" + | public void testJsonResourceNotFound() {
RestAssured.given().accept(ContentType.JSON)
.when().get("/not_found")
.then()
.statusCode(404)
.body("errorMessage", is("Resource Not Found"))
.body("existingResourcesDetails[0].basePath", is("/"));
} | class NotFoundExceptionMapperTestCase {
@RegisterExtension
static QuarkusDevModeTest test = new QuarkusDevModeTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClasses(RootResource.class));
@Test
public void testHtmlResourceNotFound() {
RestAssured.when().get("/not_found")
.then()
.statusCode(40... | class NotFoundExceptionMapperTestCase {
@RegisterExtension
static QuarkusDevModeTest test = new QuarkusDevModeTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClasses(RootResource.class));
@Test
public void testHtmlResourceNotFound() {
RestAssured.when().get("/not_found")
.then()
.statusCode(40... |
There is also a case to be made for using `getEnvVarOrProperty` here, but let's be cautious and only broaden the scope a little instead of all the way | public Result get() {
StartupLogCompressor compressor = new StartupLogCompressor("Checking Docker Environment", Optional.empty(), null,
(s) -> s.getName().startsWith("ducttape"));
try {
Class<?> dockerClientFactoryClass = Thread.currentThread().getContextClassLoader()
.loadClass("org.testcontainers.DockerClientFactory"... | .getMethod("getEnvVarOrUserProperty", String.class, String.class) | public Result get() {
StartupLogCompressor compressor = new StartupLogCompressor("Checking Docker Environment", Optional.empty(), null,
(s) -> s.getName().startsWith("ducttape"));
try {
Class<?> dockerClientFactoryClass = Thread.currentThread().getContextClassLoader()
.loadClass("org.testcontainers.DockerClientFactory"... | class TestContainersStrategy implements Strategy {
private final boolean silent;
private TestContainersStrategy(boolean silent) {
this.silent = silent;
}
@Override
} | class TestContainersStrategy implements Strategy {
private final boolean silent;
private TestContainersStrategy(boolean silent) {
this.silent = silent;
}
@Override
} |
Hm based on that I think what you had before (hard-code "0.11.3") would be preferable.That way the test is deterministic. Let's break it out into a constant `LOCALSTACK_VERSION` or something though. Sorry for the churn :grimacing: | private static void setupLocalstack() throws Exception {
System.setProperty(SDKGlobalConfiguration.DISABLE_CERT_CHECKING_SYSTEM_PROPERTY, "true");
System.setProperty(SDKGlobalConfiguration.AWS_CBOR_DISABLE_SYSTEM_PROPERTY, "true");
now = Instant.ofEpochMilli(Long.divideUnsigned(Instant.now().getMillis(), 1000));
locals... | new LocalStackContainer("0.11.3") | private static void setupLocalstack() {
now = Instant.ofEpochMilli(Long.divideUnsigned(now.getMillis(), 1000L));
System.setProperty(SDKGlobalConfiguration.DISABLE_CERT_CHECKING_SYSTEM_PROPERTY, "true");
System.setProperty(SDKGlobalConfiguration.AWS_CBOR_DISABLE_SYSTEM_PROPERTY, "true");
localstackContainer =
new LocalS... | class KinesisIOIT implements Serializable {
@Rule public TestPipeline pipelineWrite = TestPipeline.create();
@Rule public TestPipeline pipelineRead = TestPipeline.create();
private static LocalStackContainer localstackContainer;
private static KinesisTestOptions options;
private static Instant now = Instant.now();
@Bef... | class KinesisIOIT implements Serializable {
private static final String LOCALSTACK_VERSION = "0.11.3";
@Rule public TestPipeline pipelineWrite = TestPipeline.create();
@Rule public TestPipeline pipelineRead = TestPipeline.create();
private static KinesisTestOptions options;
private static AmazonKinesis kinesisClient;
p... |
I don't think we want this, doesn't this essentially remove batching? | public void processElement(ProcessContext c, BoundedWindow window) throws Exception {
for (Future<?> f = outstandingWrites.peek();
f != null && f.isDone();
f = outstandingWrites.peek()) {
outstandingWrites.remove().get();
}
checkForFailures();
KV<ByteString, Iterable<Mutation>> record = c.element();
Instant writeStart ... | for (Future<?> f = outstandingWrites.peek(); | public void processElement(ProcessContext c, BoundedWindow window) throws Exception {
drainCompletedElementFutures();
checkForFailures();
KV<ByteString, Iterable<Mutation>> record = c.element();
Instant writeStart = Instant.now();
pendingThrottlingMsecs = 0;
CompletableFuture<Void> f =
bigtableWriter
.writeRecord(recor... | class BigtableWriterFn
extends DoFn<KV<ByteString, Iterable<Mutation>>, BigtableWriteResult> {
private final BigtableServiceFactory factory;
private final BigtableServiceFactory.ConfigId id;
private final Coder<KV<ByteString, Iterable<Mutation>>> inputCoder;
private final BadRecordRouter badRecordRouter;
private final ... | class BigtableWriterFn
extends DoFn<KV<ByteString, Iterable<Mutation>>, BigtableWriteResult> {
private final BigtableServiceFactory factory;
private final BigtableServiceFactory.ConfigId id;
private final Coder<KV<ByteString, Iterable<Mutation>>> inputCoder;
private final BadRecordRouter badRecordRouter;
private final ... |
Shouldn't we have separate checks for these? In case decode started, and never finished. It may provide insights on gaps in the SDK or decode process or any internal errors. Like we have for other events. where we see null end time. | private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdReq... | if (response.getDecodeEndTime() != null && response.getDecodeStartTime() != null) { | private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdReq... | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelEx... | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelEx... |
this function is just called by line 80, is this a function for debugging? | private static String addLineNumber(String code) {
String[] lines = code.split("\n");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < lines.length; i++) {
builder.append(i + 1).append(" ").append(lines[i]).append("\n");
}
return builder.toString();
} | builder.append(i + 1).append(" ").append(lines[i]).append("\n"); | private static String addLineNumber(String code) {
String[] lines = code.split("\n");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < lines.length; i++) {
builder.append(i + 1).append(" ").append(lines[i]).append("\n");
}
return builder.toString();
} | class " + name, e);
}
} | class " + name, e);
}
}
/**
* To output more information when an error occurs.
* Generally, when cook fails, it shows which line is wrong. This line number starts at 1.
*/ |
Shall we convert the static collections to instance collections? | private void loadServices() {
if (!CodeActionProvidersHolder.nodeBasedProviders.isEmpty()) {
return;
}
ServiceLoader<LSCodeActionProvider> serviceLoader = ServiceLoader.load(LSCodeActionProvider.class);
for (CodeActionNodeType nodeType : CodeActionNodeType.values()) {
CodeActionProvidersHolder.nodeBasedProviders.put(no... | CodeActionProvidersHolder.nodeBasedProviders.put(nodeType, new ArrayList<>()); | private void loadServices() {
if (!CodeActionProvidersHolder.nodeBasedProviders.isEmpty()) {
return;
}
ServiceLoader<LSCodeActionProvider> serviceLoader = ServiceLoader.load(LSCodeActionProvider.class);
for (CodeActionNodeType nodeType : CodeActionNodeType.values()) {
CodeActionProvidersHolder.nodeBasedProviders.put(no... | class CodeActionProvidersHolder {
private static final Map<CodeActionNodeType, List<LSCodeActionProvider>> nodeBasedProviders = new HashMap<>();
private static final List<LSCodeActionProvider> diagnosticsBasedProviders = new ArrayList<>();
private static final LanguageServerContext.Key<CodeActionProvidersHolder> CODE_A... | class CodeActionProvidersHolder {
private static final Map<CodeActionNodeType, List<LSCodeActionProvider>> nodeBasedProviders = new HashMap<>();
private static final List<LSCodeActionProvider> diagnosticsBasedProviders = new ArrayList<>();
private static final LanguageServerContext.Key<CodeActionProvidersHolder> CODE_A... |
Currently what happens is the following: If the user doesn't specify anything, the default is used. If the user does specify something that is not resolvable from the classpath root, we print a warning message. If it is resolvable, we show it and also show the "Powered by..." text | private String readBannerFile(BannerConfig config) {
URL resource = Thread.currentThread().getContextClassLoader().getResource(config.path);
if (resource != null) {
try (InputStream is = resource.openStream()) {
byte[] content = FileUtil.readFileContents(is);
StringBuilder bannerTitle = new StringBuilder(new String(con... | if (!config.isDefaultPath()) { | private String readBannerFile(BannerConfig config) {
try {
Map.Entry<URL, Boolean> entry = getBanner(config);
URL bannerResourceURL = entry.getKey();
if (bannerResourceURL == null) {
logger.warn("Could not locate banner file");
return "";
}
try (InputStream is = bannerResourceURL.openStream()) {
byte[] content = FileUt... | class })
@Record(ExecutionTime.RUNTIME_INIT)
public ConsoleFormatterBannerBuildItem recordBanner(BannerRecorder recorder, BannerConfig config,
BannerRuntimeConfig bannerRuntimeConfig) {
String bannerText = readBannerFile(config);
return new ConsoleFormatterBannerBuildItem(recorder.provideBannerSupplier(bannerText, bann... | class })
@Record(ExecutionTime.RUNTIME_INIT)
public ConsoleFormatterBannerBuildItem recordBanner(BannerRecorder recorder, BannerConfig config,
BannerRuntimeConfig bannerRuntimeConfig) {
String bannerText = readBannerFile(config);
return new ConsoleFormatterBannerBuildItem(recorder.provideBannerSupplier(bannerText, bann... |
nit, also remove the `public` in function `testJoinWithFilter()` below. BTW, maybe we need to consider how to make the weak constraint about removing `public` in test functions more conspicuous. | void testLeftOuterJoinWithLiteralTrue() {
String sinkTableDdl =
"CREATE TABLE MySink (\n"
+ " a varchar,\n"
+ " b varchar\n"
+ ") with (\n"
+ " 'connector' = 'values',\n"
+ " 'table-sink-class' = 'DEFAULT')";
tEnv.executeSql(sinkTableDdl);
util.addTemporarySystemFunction("func1", TableFunc1.class);
String sqlQuery ... | + " a varchar,\n" | void testLeftOuterJoinWithLiteralTrue() {
String sinkTableDdl =
"CREATE TABLE MySink (\n"
+ " a varchar,\n"
+ " b varchar\n"
+ ") with (\n"
+ " 'connector' = 'values',\n"
+ " 'table-sink-class' = 'DEFAULT')";
tEnv.executeSql(sinkTableDdl);
util.addTemporarySystemFunction("func1", TableFunc1.class);
String sqlQuery ... | class CorrelateJsonPlanTest extends TableTestBase {
private StreamTableTestUtil util;
private TableEnvironment tEnv;
@BeforeEach
void setup() {
util = streamTestUtil(TableConfig.getDefault());
tEnv = util.getTableEnv();
String srcTableDdl =
"CREATE TABLE MyTable (\n"
+ " a bigint,\n"
+ " b int not null,\n"
+ " c var... | class CorrelateJsonPlanTest extends TableTestBase {
private StreamTableTestUtil util;
private TableEnvironment tEnv;
@BeforeEach
void setup() {
util = streamTestUtil(TableConfig.getDefault());
tEnv = util.getTableEnv();
String srcTableDdl =
"CREATE TABLE MyTable (\n"
+ " a bigint,\n"
+ " b int not null,\n"
+ " c var... |
Also, just checked the sample_invoice.jpg currently is returning just these fields ```java "Amount" "Description" "Quantity" "UnitPrice" ``` | public static void main(final String[] args) throws IOException {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
String invoiceUrl =
"https:
+ "azure-ai-formrecognizer/samples/sample_forms/forms/sample_invoice.jpg";
SyncPoll... | Float unit = formField.getValue().asFloat(); | public static void main(final String[] args) throws IOException {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
String invoiceUrl =
"https:
+ "azure-ai-formrecognizer/samples/sample_forms/forms/sample_invoice.jpg";
SyncPoll... | class RecognizeInvoicesFromUrl {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} | class RecognizeInvoicesFromUrl {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} |
shouldn't we change the order here as discussed offline? ``` .doOnError(throwable -> { this.refreshInProgress.set(null); logger.warn("Background refresh task failed", throwable); ``` | private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) {
return this.value
.get()
.flatMap(cachedValue -> createRefreshFunction.apply(cachedValue))
.flatMap(response -> {
this.refreshInProgress.set(null);
return this.value.updateAndGet(existingValue -> Mono.just(response)... | this.refreshInProgress.set(null); | private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) {
return this.value
.get()
.flatMap(createRefreshFunction)
.flatMap(response -> {
this.refreshInProgress.set(null);
return this.value.updateAndGet(existingValue -> Mono.just(response));
})
.doOnError(throwable -> {
th... | class AsyncLazyWithRefresh<TValue> {
private final AtomicBoolean removeFromCache = new AtomicBoolean(false);
private final AtomicReference<Mono<TValue>> value;
private final AtomicReference<Mono<TValue>> refreshInProgress;
public AsyncLazyWithRefresh(TValue value) {
this.value = new AtomicReference<>();
this.value.set(... | class AsyncLazyWithRefresh<TValue> {
private final AtomicBoolean removeFromCache = new AtomicBoolean(false);
private final AtomicReference<Mono<TValue>> value;
private final AtomicReference<Mono<TValue>> refreshInProgress;
public AsyncLazyWithRefresh(TValue value) {
this.value = new AtomicReference<>();
this.value.set(... |
Unable to obtain catalog name | public void analyze(Analyzer analyzer) throws AnalysisException, UserException {
super.analyze(analyzer);
if (Strings.isNullOrEmpty(db)) {
ErrorReport.reportAnalysisException(ErrorCode.ERR_WRONG_DB_NAME, db);
}
if (!Env.getCurrentEnv().getAccessManager()
.checkDbPriv(ConnectContext.get(), InternalCatalog.INTERNAL_CATAL... | .checkDbPriv(ConnectContext.get(), InternalCatalog.INTERNAL_CATALOG_NAME, db, | public void analyze(Analyzer analyzer) throws AnalysisException, UserException {
super.analyze(analyzer);
if (Strings.isNullOrEmpty(db)) {
ErrorReport.reportAnalysisException(ErrorCode.ERR_WRONG_DB_NAME, db);
}
if (!Env.getCurrentEnv().getAccessManager()
.checkDbPriv(ConnectContext.get(), InternalCatalog.INTERNAL_CATAL... | class ShowCreateDbStmt extends ShowStmt {
private static final ShowResultSetMetaData META_DATA =
ShowResultSetMetaData.builder()
.addColumn(new Column("Database", ScalarType.createVarchar(20)))
.addColumn(new Column("Create Database", ScalarType.createVarchar(30)))
.build();
private String db;
public ShowCreateDbStmt(S... | class ShowCreateDbStmt extends ShowStmt {
private static final ShowResultSetMetaData META_DATA =
ShowResultSetMetaData.builder()
.addColumn(new Column("Database", ScalarType.createVarchar(20)))
.addColumn(new Column("Create Database", ScalarType.createVarchar(30)))
.build();
private String db;
public ShowCreateDbStmt(S... |
also plz add test case for this grant | public void saveV2(DataOutputStream dos) throws IOException {
try {
final int cnt = 1 + 1 + userToPrivilegeCollection.size() * 2
+ 1 + roleIdToPrivilegeCollection.size() * 2;
SRMetaBlockWriter writer = new SRMetaBlockWriter(dos, SRMetaBlockID.AUTHORIZATION_MGR, cnt);
writer.writeJson(this);
writer.writeJson(userToPrivi... | writer.writeJson(this); | public void saveV2(DataOutputStream dos) throws IOException {
try {
final int cnt = 1 + 1 + userToPrivilegeCollection.size() * 2
+ 1 + roleIdToPrivilegeCollection.size() * 2;
SRMetaBlockWriter writer = new SRMetaBlockWriter(dos, SRMetaBlockID.AUTHORIZATION_MGR, cnt);
writer.writeJson(this);
writer.writeJson(userToPrivi... | class AuthorizationMgr {
private static final Logger LOG = LogManager.getLogger(AuthorizationMgr.class);
@SerializedName(value = "r")
private final Map<String, Long> roleNameToId;
@SerializedName(value = "i")
private short pluginId;
@SerializedName(value = "v")
private short pluginVersion;
protected AuthorizationProvid... | class AuthorizationMgr {
private static final Logger LOG = LogManager.getLogger(AuthorizationMgr.class);
@SerializedName(value = "r")
private final Map<String, Long> roleNameToId;
@SerializedName(value = "i")
private short pluginId;
@SerializedName(value = "v")
private short pluginVersion;
protected AuthorizationProvid... |
> List<ScalarOperator> partitions = new ArrayList<>(); for (Expr partitionExpression : windowOperator.getPartitionExprs()) { ScalarOperator operator = SqlToScalarOperatorTranslator .translate(partitionExpression, subOpt.getExpressionMapping(), columnRefFactor... | private OptExprBuilder window(OptExprBuilder subOpt, List<AnalyticExpr> window) {
if (window.isEmpty()) {
return subOpt;
}
/*
* Build ProjectOperator of partition expression and order by expression in window function.
*/
List<Expr> projectExpressions = new ArrayList<>();
for (AnalyticExpr analyticExpr : window) {
proje... | } | private OptExprBuilder window(OptExprBuilder subOpt, List<AnalyticExpr> window) {
if (window.isEmpty()) {
return subOpt;
}
/*
* Build ProjectOperator of partition expression and order by expression in window function.
*/
List<Expr> projectExpressions = new ArrayList<>();
for (AnalyticExpr analyticExpr : window) {
proje... | class QueryTransformer {
private final ColumnRefFactory columnRefFactory;
private final ConnectContext session;
private final List<ColumnRefOperator> correlation = new ArrayList<>();
private final CTETransformerContext cteContext;
private final boolean inlineView;
private final Map<Operator, ParseNode> optToAstMap;
pub... | class QueryTransformer {
private final ColumnRefFactory columnRefFactory;
private final ConnectContext session;
private final List<ColumnRefOperator> correlation = new ArrayList<>();
private final CTETransformerContext cteContext;
private final boolean inlineView;
private final Map<Operator, ParseNode> optToAstMap;
pub... |
I specifically did not want to use it, in case there is an exception (or restart of host-admin) after createTempFile and before the move: It would leave stray files in the directory. | private void writeBytes(byte[] content, boolean atomic) {
if (atomic) {
String tmpPath = path.toPath().toString() + ".FileSyncTmp";
new UnixPath(path.toPath().getFileSystem().getPath(tmpPath))
.writeBytes(content)
.atomicMove(path.toPath());
} else {
path.writeBytes(content);
}
} | String tmpPath = path.toPath().toString() + ".FileSyncTmp"; | private void writeBytes(byte[] content, boolean atomic) {
if (atomic) {
String tmpPath = path.toPath().toString() + ".FileSyncTmp";
new UnixPath(path.toPath().getFileSystem().getPath(tmpPath))
.writeBytes(content)
.atomicMove(path.toPath());
} else {
path.writeBytes(content);
}
} | class FileSync {
private static final Logger logger = Logger.getLogger(FileSync.class.getName());
private final UnixPath path;
private final FileContentCache contentCache;
public FileSync(Path path) {
this.path = new UnixPath(path);
this.contentCache = new FileContentCache(this.path);
}
public boolean convergeTo(TaskCo... | class FileSync {
private static final Logger logger = Logger.getLogger(FileSync.class.getName());
private final UnixPath path;
private final FileContentCache contentCache;
public FileSync(Path path) {
this.path = new UnixPath(path);
this.contentCache = new FileContentCache(this.path);
}
public boolean convergeTo(TaskCo... |
I changed it to check the result of the operation into the assert | private void testCopy(S3Options options) throws IOException {
S3FileSystem s3FileSystem = buildMockedS3FileSystem(s3Options());
S3ResourceId sourcePath = S3ResourceId.fromUri("s3:
S3ResourceId destinationPath = S3ResourceId.fromUri("s3:
HeadObjectResponse.Builder builder = HeadObjectResponse.builder().contentLength(0L)... | headObjectResponse.toBuilder().contentLength(5_368_709_120L).build(); | private void testCopy(S3Options options) throws IOException {
S3FileSystem s3FileSystem = buildMockedS3FileSystem(s3Options());
S3ResourceId sourcePath = S3ResourceId.fromUri("s3:
S3ResourceId destinationPath = S3ResourceId.fromUri("s3:
HeadObjectResponse.Builder builder = HeadObjectResponse.builder().contentLength(0L)... | class S3FileSystemTest {
private static S3Mock api;
private static S3Client client;
@BeforeClass
public static void beforeClass() {
api = new S3Mock.Builder().withInMemoryBackend().withPort(8002).build();
Http.ServerBinding binding = api.start();
URI endpoint = URI.create("http:
S3Configuration s3Configuration =
S3Conf... | class S3FileSystemTest {
private static S3Mock api;
private static S3Client client;
@BeforeClass
public static void beforeClass() {
api = new S3Mock.Builder().withInMemoryBackend().withPort(8002).build();
Http.ServerBinding binding = api.start();
URI endpoint = URI.create("http:
S3Configuration s3Configuration =
S3Conf... |
This TODO can be solved now | protected Mono<NetworkInterfaceInner> getInnerAsync() {
return this
.manager()
.inner()
.networkInterfaces()
.getByResourceGroupAsync(this.resourceGroupName(), this.name(), null);
} | protected Mono<NetworkInterfaceInner> getInnerAsync() {
return this
.manager()
.inner()
.networkInterfaces()
.getByResourceGroupAsync(this.resourceGroupName(), this.name());
} | class NetworkInterfaceImpl
extends GroupableParentResourceWithTagsImpl<
NetworkInterface, NetworkInterfaceInner, NetworkInterfaceImpl, NetworkManager>
implements NetworkInterface, NetworkInterface.Definition, NetworkInterface.Update {
/** the name of the network interface. */
private final String nicName;
/** used to g... | class NetworkInterfaceImpl
extends GroupableParentResourceWithTagsImpl<
NetworkInterface, NetworkInterfaceInner, NetworkInterfaceImpl, NetworkManager>
implements NetworkInterface, NetworkInterface.Definition, NetworkInterface.Update {
/** the name of the network interface. */
private final String nicName;
/** used to g... | |
To make sure the mv's plan is selected forcefully, skip to check upper cost for the group expression which contains mv rewrite plan. | public void execute() {
if (groupExpression.isUnused()) {
return;
}
if (!checkCTEPropertyValid(groupExpression, context.getRequiredProperty())) {
return;
}
initRequiredProperties();
SessionVariable sessionVariable = context.getOptimizerContext().getSessionVariable();
boolean isMVPlanForceRewrite = sessionVariable.isEna... | if (isMVPlanForceRewrite) { | public void execute() {
if (groupExpression.isUnused()) {
return;
}
if (!checkCTEPropertyValid(groupExpression, context.getRequiredProperty())) {
return;
}
if (context.getOptimizerContext().getSessionVariable().isEnableMaterializedViewForceRewrite() &&
groupExpression.getGroup().hasMVGroupExpression()) {
if (!groupExpr... | class EnforceAndCostTask extends OptimizerTask implements Cloneable {
private final GroupExpression groupExpression;
private List<List<PhysicalPropertySet>> childrenRequiredPropertiesList;
private double curTotalCost;
private double localCost;
private int curChildIndex = -1;
private int prevChildIndex = -1;
private int... | class EnforceAndCostTask extends OptimizerTask implements Cloneable {
private final GroupExpression groupExpression;
private List<List<PhysicalPropertySet>> childrenRequiredPropertiesList;
private double curTotalCost;
private double localCost;
private int curChildIndex = -1;
private int prevChildIndex = -1;
private int... |
imo, using a constant fro `$0092` will improve the readability of the code. It is not mandatory because it is using only in here. | public Value getChildByName(String name) throws DebugVariableException {
if (namedChildVariables == null) {
namedChildVariables = computeChildVariables();
}
if (!namedChildVariables.containsKey(name)) {
for (Map.Entry<String, Value> childVariable : namedChildVariables.entrySet()) {
String escaped = childVariable.getKey... | String escaped = childVariable.getKey().replaceAll("\\$0092(\\$0092)?", "$1"); | public Value getChildByName(String name) throws DebugVariableException {
if (namedChildVariables == null) {
namedChildVariables = computeChildVariables();
}
if (!namedChildVariables.containsKey(name)) {
for (Map.Entry<String, Value> childVariable : namedChildVariables.entrySet()) {
String unicodeOfSlash = "&0092";
Stri... | class NamedCompoundVariable extends BCompoundVariable {
private Map<String, Value> namedChildVariables;
public NamedCompoundVariable(SuspendedContext context, String varName, BVariableType bVarType, Value jvmValue) {
super(context, varName, bVarType, jvmValue);
}
/**
* Retrieves JDI value representations of all the chi... | class NamedCompoundVariable extends BCompoundVariable {
private Map<String, Value> namedChildVariables;
public NamedCompoundVariable(SuspendedContext context, String varName, BVariableType bVarType, Value jvmValue) {
super(context, varName, bVarType, jvmValue);
}
/**
* Retrieves JDI value representations of all the chi... |
should be `replayDropNode`? this will be only focus on warehouse restore its internal state, not triggering starmgr to drop the node again because starmgr itself have edit log and can replay to its final state. | public void replayDropBackend(Backend backend) {
LOG.debug("replayDropBackend: {}", backend);
Map<Long, Backend> copiedBackends = Maps.newHashMap(idToBackendRef);
copiedBackends.remove(backend.getId());
idToBackendRef = ImmutableMap.copyOf(copiedBackends);
Map<Long, AtomicLong> copiedReportVerions = Maps.newHashMap(idT... | warehouse.getAnyAvailableCluster().dropNode(backend.getId()); | public void replayDropBackend(Backend backend) {
LOG.debug("replayDropBackend: {}", backend);
Map<Long, Backend> copiedBackends = Maps.newHashMap(idToBackendRef);
copiedBackends.remove(backend.getId());
idToBackendRef = ImmutableMap.copyOf(copiedBackends);
Map<Long, AtomicLong> copiedReportVerions = Maps.newHashMap(idT... | class SerializeData {
@SerializedName("computeNodes")
public List<ComputeNode> computeNodes;
} | class SerializeData {
@SerializedName("computeNodes")
public List<ComputeNode> computeNodes;
} |
You are right, It's my mistake. I see this checkpointCoordinator isn't used, so removed it. For the convenience of review, friendly reminder: - It's recovered in the first commit, and I removed the `CheckpointCoordinator checkpointCoordinator =` due to it's not necessary. - I did some extra work in this PR during f... | private CheckpointCoordinator getCheckpointCoordinator(ExecutionGraph graph) throws Exception {
return new CheckpointCoordinatorBuilder()
.setCheckpointCoordinatorConfiguration(
CheckpointCoordinatorConfiguration.builder()
.setAlignedCheckpointTimeout(Long.MAX_VALUE)
.setMaxConcurrentCheckpoints(Integer.MAX_VALUE)
.bui... | .setTimer(manuallyTriggeredScheduledExecutor) | private CheckpointCoordinator getCheckpointCoordinator(ExecutionGraph graph) throws Exception {
return new CheckpointCoordinatorBuilder()
.setCheckpointCoordinatorConfiguration(
CheckpointCoordinatorConfiguration.builder()
.setAlignedCheckpointTimeout(Long.MAX_VALUE)
.setMaxConcurrentCheckpoints(Integer.MAX_VALUE)
.bui... | class CheckpointCoordinatorTest extends TestLogger {
@ClassRule
public static final TestExecutorResource<ScheduledExecutorService> EXECUTOR_RESOURCE =
TestingUtils.defaultExecutorResource();
@Test
public void testSharedStateNotDiscaredOnAbort() throws Exception {
JobVertexID v1 = new JobVertexID(), v2 = new JobVertexID... | class CheckpointCoordinatorTest extends TestLogger {
@RegisterExtension
static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_RESOURCE =
TestingUtils.defaultExecutorExtension();
@Test
void testSharedStateNotDiscaredOnAbort() throws Exception {
JobVertexID v1 = new JobVertexID(), v2 = new JobVertexID();
... |
Also, this error will be given to the beginning of the function. Check and see if you can give the error to the correct position of the relevant field in the annotation. | public void process(FunctionNode functionNode, List<AnnotationAttachmentNode> annotations) {
if (!enabled) {
return;
}
BLangPackage parent = (BLangPackage) ((BLangFunction) functionNode).parent;
String packageName = getPackageName(parent);
TestSuite suite = registry.getTestSuites().get(packageName);
if (suite == null) ... | "Module name cannot be empty"); | public void process(FunctionNode functionNode, List<AnnotationAttachmentNode> annotations) {
if (!enabled) {
return;
}
parent = (BLangPackage) ((BLangFunction) functionNode).parent;
String packageName = getPackageName(parent);
TestSuite suite = registry.getTestSuites().get(packageName);
if (suite == null) {
suite = reg... | class TestAnnotationProcessor extends AbstractCompilerPlugin {
private static final String TEST_ANNOTATION_NAME = "Config";
private static final String BEFORE_SUITE_ANNOTATION_NAME = "BeforeSuite";
private static final String AFTER_SUITE_ANNOTATION_NAME = "AfterSuite";
private static final String BEFORE_EACH_ANNOTATION... | class TestAnnotationProcessor extends AbstractCompilerPlugin {
private static final String TEST_ANNOTATION_NAME = "Config";
private static final String BEFORE_SUITE_ANNOTATION_NAME = "BeforeSuite";
private static final String AFTER_SUITE_ANNOTATION_NAME = "AfterSuite";
private static final String BEFORE_EACH_ANNOTATION... |
Since this will be called more than once (in a general scenario when compiling a Ballerina program), I think it is better to compile this Regex once (declare as a top level variable) to reduce the overhead. WDYT? | public void exitSimpleLiteral(BallerinaParser.SimpleLiteralContext ctx) {
if (isInErrorState) {
return;
}
TerminalNode node;
DiagnosticPos pos = getCurrentPos(ctx);
Set<Whitespace> ws = getWS(ctx);
Object value;
BallerinaParser.IntegerLiteralContext integerLiteralContext = ctx.integerLiteral();
if (integerLiteralContex... | Pattern pattern = Pattern.compile(Constants.UNICODE_REGEX); | public void exitSimpleLiteral(BallerinaParser.SimpleLiteralContext ctx) {
if (isInErrorState) {
return;
}
TerminalNode node;
DiagnosticPos pos = getCurrentPos(ctx);
Set<Whitespace> ws = getWS(ctx);
Object value;
BallerinaParser.IntegerLiteralContext integerLiteralContext = ctx.integerLiteral();
if (integerLiteralContex... | class BLangParserListener extends BallerinaParserBaseListener {
private static final String KEYWORD_PUBLIC = "public";
private static final String KEYWORD_KEY = "key";
private BLangPackageBuilder pkgBuilder;
private BDiagnosticSource diagnosticSrc;
private BLangDiagnosticLog dlog;
private List<String> pkgNameComps;
pri... | class BLangParserListener extends BallerinaParserBaseListener {
private static final String KEYWORD_PUBLIC = "public";
private static final String KEYWORD_KEY = "key";
private BLangPackageBuilder pkgBuilder;
private BDiagnosticSource diagnosticSrc;
private BLangDiagnosticLog dlog;
private List<String> pkgNameComps;
pri... |
Yes, if 'use v2 rollup' is true, only base index will be selected | public BestIndexInfo selectBestMV(ScanNode scanNode) throws UserException {
long start = System.currentTimeMillis();
Preconditions.checkState(scanNode instanceof OlapScanNode);
OlapScanNode olapScanNode = (OlapScanNode) scanNode;
ConnectContext connectContext = ConnectContext.get();
if (connectContext != null && connec... | if (connectContext != null && connectContext.getSessionVariable().isUseV2Rollup()) { | public BestIndexInfo selectBestMV(ScanNode scanNode) throws UserException {
long start = System.currentTimeMillis();
Preconditions.checkState(scanNode instanceof OlapScanNode);
OlapScanNode olapScanNode = (OlapScanNode) scanNode;
Map<Long, List<Column>> candidateIndexIdToSchema = predicates(olapScanNode);
long bestInde... | class MaterializedViewSelector {
private static final Logger LOG = LogManager.getLogger(MaterializedViewSelector.class);
private final SelectStmt selectStmt;
private final Analyzer analyzer;
/**
* The key of following maps is table name.
* The value of following maps is column names.
* `columnNamesInPredicates` means t... | class MaterializedViewSelector {
private static final Logger LOG = LogManager.getLogger(MaterializedViewSelector.class);
private final SelectStmt selectStmt;
private final Analyzer analyzer;
/**
* The key of following maps is table name.
* The value of following maps is column names.
* `columnNamesInPredicates` means t... |
Need to update the doc comment with the new grammar. Applicable for all places. | private STNode parseWhileStatement() {
startContext(ParserRuleContext.WHILE_BLOCK);
STNode whileKeyword = parseWhileKeyword();
STNode condition = parseExpression();
STNode whileBody = parseBlockNode();
endContext();
STNode onFailClause;
if (peek().kind == SyntaxKind.ON_KEYWORD) {
onFailClause = parseOnFailClause();
} e... | if (peek().kind == SyntaxKind.ON_KEYWORD) { | private STNode parseWhileStatement() {
startContext(ParserRuleContext.WHILE_BLOCK);
STNode whileKeyword = parseWhileKeyword();
STNode condition = parseExpression();
STNode whileBody = parseBlockNode();
endContext();
STNode onFailClause = parseOptionalOnFailClause();
return STNodeFactory.createWhileStatementNode(whileKe... | class BallerinaParser extends AbstractParser {
private static final OperatorPrecedence DEFAULT_OP_PRECEDENCE = OperatorPrecedence.DEFAULT;
protected BallerinaParser(AbstractTokenReader tokenReader) {
super(tokenReader, new BallerinaParserErrorHandler(tokenReader));
}
/**
* Start parsing the given input.
*
* @return Par... | class member, object member or object member descriptor.
* </p>
* <code>
* class-member := object-field | method-defn | object-type-inclusion
* <br/>
* object-member := object-field | method-defn
* <br/>
* object-member-descriptor := object-field-descriptor | method-decl | object-type-inclusion
* </code>
*
* @param con... |
Because `or expansion` could generate new CTE, it may break the assumption that the CTE anchor always is at the top of the plan in the rewritten CTE children | private static List<RewriteJob> getWholeTreeRewriteJobs(List<RewriteJob> jobs) {
return jobs(
topic("cte inline and pull up all cte anchor",
custom(RuleType.PULL_UP_CTE_ANCHOR, PullUpCteAnchor::new),
custom(RuleType.CTE_INLINE, CTEInline::new)
),
topic("process limit session variables",
custom(RuleType.ADD_DEFAULT_LIMI... | topic("or expansion", | private static List<RewriteJob> getWholeTreeRewriteJobs(List<RewriteJob> jobs) {
return jobs(
topic("cte inline and pull up all cte anchor",
custom(RuleType.PULL_UP_CTE_ANCHOR, PullUpCteAnchor::new),
custom(RuleType.CTE_INLINE, CTEInline::new)
),
topic("process limit session variables",
custom(RuleType.ADD_DEFAULT_LIMI... | class Rewriter extends AbstractBatchJobExecutor {
private static final List<RewriteJob> CTE_CHILDREN_REWRITE_JOBS = jobs(
topic("Plan Normalization",
topDown(
new EliminateOrderByConstant(),
new EliminateSortUnderSubquery(),
new EliminateGroupByConstant(),
new LogicalSubQueryAliasToLogicalProject(),
new ExpressionNorma... | class Rewriter extends AbstractBatchJobExecutor {
private static final List<RewriteJob> CTE_CHILDREN_REWRITE_JOBS = jobs(
topic("Plan Normalization",
topDown(
new EliminateOrderByConstant(),
new EliminateSortUnderSubquery(),
new EliminateGroupByConstant(),
new LogicalSubQueryAliasToLogicalProject(),
new ExpressionNorma... |
```suggestion LocalVariableProxyImpl selfVariable = stackFrame.visibleVariableByName(SELF_VAR_NAME); ``` | private static String getFilteredStackFrame(StackFrameProxyImpl stackFrame) throws JdiProxyException {
String stackFrameName = stackFrame.location().method().name();
LocalVariableProxyImpl selfVisibleVariable = stackFrame.visibleVariableByName(SELF_VAR_NAME);
if (selfVisibleVariable == null) {
return stackFrameName;
}
... | LocalVariableProxyImpl selfVisibleVariable = stackFrame.visibleVariableByName(SELF_VAR_NAME); | private static String getFilteredStackFrame(StackFrameProxyImpl stackFrame) throws JdiProxyException {
String stackFrameName = stackFrame.location().method().name();
LocalVariableProxyImpl selfVariable = stackFrame.visibleVariableByName(SELF_VAR_NAME);
if (selfVariable == null) {
return stackFrameName;
}
Value selfValu... | class BallerinaStackFrame {
private final ExecutionContext context;
private final Integer frameId;
private final StackFrameProxyImpl jStackFrame;
private StackFrame dapStackFrame;
private static final String STRAND_FIELD_NAME = "name";
private static final String FRAME_TYPE_START = "start";
private static final String ... | class BallerinaStackFrame {
private final ExecutionContext context;
private final Integer frameId;
private final StackFrameProxyImpl jStackFrame;
private StackFrame dapStackFrame;
private static final String STRAND_FIELD_NAME = "name";
private static final String FRAME_TYPE_START = "start";
private static final String ... |
Why are removing the hyphen? Same for L3599. | public void visit(BLangOnFailClause onFailClause, AnalyzerData data) {
SymbolEnv onFailEnv = SymbolEnv.createBlockEnv(onFailClause.body, data.env);
if (onFailClause.variableDefinitionNode != null) {
handleForeachDefinitionVariables(onFailClause.variableDefinitionNode, symTable.errorType,
onFailClause.isDeclaredWithVar,... | public void visit(BLangOnFailClause onFailClause, AnalyzerData data) {
SymbolEnv onFailEnv = SymbolEnv.createBlockEnv(onFailClause.body, data.env);
VariableDefinitionNode onFailVarDefNode = onFailClause.variableDefinitionNode;
if (onFailVarDefNode != null) {
handleForeachDefinitionVariables(onFailVarDefNode, symTable.e... | class representing a service-decl or object-ctor with service prefix
AttachPoint.Point attachedPoint;
Set<Flag> flagSet = classDefinition.flagSet;
if (flagSet.contains(Flag.OBJECT_CTOR) && flagSet.contains(Flag.SERVICE)) {
attachedPoint = AttachPoint.Point.SERVICE;
} | class representing a service-decl or object-ctor with service prefix
AttachPoint.Point attachedPoint;
Set<Flag> flagSet = classDefinition.flagSet;
if (flagSet.contains(Flag.OBJECT_CTOR) && flagSet.contains(Flag.SERVICE)) {
attachedPoint = AttachPoint.Point.SERVICE;
} | |
Should use uppercase, I will modify it. | public void getTablePrivStatus(List<TPrivilegeStatus> tblPrivResult, UserIdentity currentUser) {
readLock();
try {
for (PrivEntry entry : tablePrivTable.getEntries()) {
TablePrivEntry tblPrivEntry = (TablePrivEntry) entry;
String dbName = ClusterNamespace.getNameFromFullName(tblPrivEntry.getOrigDb());
String tblName = ... | String isGrantable = tblPrivEntry.getPrivSet().get(2) ? "yes" : "no"; | public void getTablePrivStatus(List<TPrivilegeStatus> tblPrivResult, UserIdentity currentUser) {
readLock();
try {
for (PrivEntry entry : tablePrivTable.getEntries()) {
TablePrivEntry tblPrivEntry = (TablePrivEntry) entry;
String dbName = ClusterNamespace.getNameFromFullName(tblPrivEntry.getOrigDb());
String tblName = ... | class PaloAuth implements Writable {
private static final Logger LOG = LogManager.getLogger(PaloAuth.class);
public static final String ROOT_USER = "root";
public static final String ADMIN_USER = "admin";
private UserPrivTable userPrivTable = new UserPrivTable();
private DbPrivTable dbPrivTable = new DbPrivTable();
pri... | class PaloAuth implements Writable {
private static final Logger LOG = LogManager.getLogger(PaloAuth.class);
public static final String ROOT_USER = "root";
public static final String ADMIN_USER = "admin";
private UserPrivTable userPrivTable = new UserPrivTable();
private DbPrivTable dbPrivTable = new DbPrivTable();
pri... |
should not add check here, the fourth child should be string type or varchar type, but maybe not string literal. signature already check the type, so remove this check please. | public AesDecryptV2 withChildren(List<Expression> children) {
Preconditions.checkArgument(children.size() >= 2 && children.size() <= 4);
if (children.size() == 2) {
return new AesDecryptV2(children.get(0), children.get(1));
} else if (children().size() == 3) {
return new AesDecryptV2(children.get(0), children.get(1), c... | } | public AesDecryptV2 withChildren(List<Expression> children) {
Preconditions.checkArgument(children.size() >= 2 && children.size() <= 4);
if (children.size() == 2) {
return new AesDecryptV2(children.get(0), children.get(1));
} else if (children().size() == 3) {
return new AesDecryptV2(children.get(0), children.get(1), c... | class AesDecryptV2 extends AesDecrypt {
/**
* AesDecryptV2
*/
public AesDecryptV2(Expression arg0, Expression arg1) {
super(arg0, arg1, getDefaultBlockEncryptionMode());
String blockEncryptionMode = String.valueOf(getDefaultBlockEncryptionMode());
if (!blockEncryptionMode.toUpperCase().equals("'AES_128_ECB'")
&& !block... | class AesDecryptV2 extends AesDecrypt {
/**
* AesDecryptV2
*/
public AesDecryptV2(Expression arg0, Expression arg1) {
super(arg0, arg1, getDefaultBlockEncryptionMode());
String blockEncryptionMode = String.valueOf(getDefaultBlockEncryptionMode());
if (!blockEncryptionMode.toUpperCase().equals("'AES_128_ECB'")
&& !block... |
Will fix the same with "Adding documentation for the whole document" | private static String getDocumentationAttachment(List<String> attributes, int offset) {
String offsetStr = String.join("", Collections.nCopies(offset, " "));
if (attributes == null || attributes.isEmpty()) {
return String.format("%n%sdocumentation {%n%s\t%n%s}", offsetStr, offsetStr, offsetStr);
} else {
String joinedL... | } else { | private static String getDocumentationAttachment(List<String> attributes, int offset) {
String offsetStr = String.join("", Collections.nCopies(offset, " "));
if (attributes == null || attributes.isEmpty()) {
return String.format("%n%sdocumentation {%n%s\t%n%s}", offsetStr, offsetStr, offsetStr);
} else {
String joinedL... | class CommandArgument {
private String argumentK;
private String argumentV;
CommandArgument(String argumentK, String argumentV) {
this.argumentK = argumentK;
this.argumentV = argumentV;
}
public String getArgumentK() {
return argumentK;
}
public String getArgumentV() {
return argumentV;
}
} | class CommandArgument {
private String argumentK;
private String argumentV;
CommandArgument(String argumentK, String argumentV) {
this.argumentK = argumentK;
this.argumentV = argumentV;
}
public String getArgumentK() {
return argumentK;
}
public String getArgumentV() {
return argumentV;
}
} |
Unrelated to this PR - I'm wondering if at some point we shouldn't use something like https://github.com/zalando/problem. | private void htmlResponse(RoutingContext event, String details, Throwable exception) {
event.response().headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8");
final TemplateHtmlBuilder htmlBuilder = new TemplateHtmlBuilder("Internal Server Error", details, details);
if (showStack && exception != null)... | event.response().headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8"); | private void htmlResponse(RoutingContext event, String details, Throwable exception) {
event.response().headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8");
final TemplateHtmlBuilder htmlBuilder = new TemplateHtmlBuilder("Internal Server Error", details, details);
if (showStack && exception != null)... | class QuarkusErrorHandler implements Handler<RoutingContext> {
private static final Logger log = getLogger(QuarkusErrorHandler.class);
private static final Pattern ACCEPT_HEADER_SEPARATOR_PATTERN = Pattern.compile("\\s*,\\s*");
/**
* we don't want to generate a new UUID each time as it is slowish. Instead we just gener... | class QuarkusErrorHandler implements Handler<RoutingContext> {
private static final Logger log = getLogger(QuarkusErrorHandler.class);
/**
* we don't want to generate a new UUID each time as it is slowish. Instead we just generate one based one
* and then use a counter.
*/
private static final String BASE_ID = UUID.ran... |
Why do we need Stack for this? Would a simple String variable work? It make sense for classes with inner classes to be able to pop() and come back to parent class... But, can we find a new Method_DEF inside a Method_def? | public void leaveToken(DetailAST token) {
switch (token.getType()) {
case TokenTypes.CLASS_DEF:
if (!classNameStack.isEmpty()) {
classNameStack.pop();
}
break;
case TokenTypes.METHOD_DEF:
if (!methodDefStack.isEmpty()) {
methodDefStack.pop();
}
break;
default:
break;
}
} | methodDefStack.pop(); | public void leaveToken(DetailAST token) {
if (token.getType() == TokenTypes.CLASS_DEF && !classNameStack.isEmpty()) {
classNameStack.pop();
}
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private Deque<DetailAST> methodDefStack = new ArrayDeque<>();
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private DetailAST methodDefToken = null;
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} |
should this be using the CoreUtils method added above? | private HttpPipeline createPipeline() {
if (pipeline != null) {
return pipeline;
}
final Configuration buildConfiguration = configuration == null
? Configuration.getGlobalConfiguration().clone()
: configuration;
final List<HttpPipelinePolicy> httpPolicies = new ArrayList<>();
final String applicationId = CoreUtils.getA... | } | private HttpPipeline createPipeline() {
if (pipeline != null) {
return pipeline;
}
final Configuration buildConfiguration = configuration == null
? Configuration.getGlobalConfiguration().clone()
: configuration;
final List<HttpPipelinePolicy> httpPolicies = new ArrayList<>();
final String applicationId = CoreUtils.getA... | class ServiceBusAdministrationClientBuilder {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-messaging-servicebus.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = pr... | class ServiceBusAdministrationClientBuilder {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-messaging-servicebus.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = pr... |
More fuel for the "node states should be immutable" fire... 🔥 | NodeState getNodeState(int index) {
NodeState ns = nodeStates.get(index);
if (ns != null) return ns;
return (index >= getMaxIndex() || ! upNodes.get(index))
? new NodeState(type, State.DOWN)
: new NodeState(type, State.UP);
} | : new NodeState(type, State.UP); | NodeState getNodeState(int index) {
NodeState ns = nodeStates.get(index);
if (ns != null) return ns;
return (index >= getLogicalNodeCount() || ! upNodes.get(index))
? new NodeState(type, State.DOWN)
: new NodeState(type, State.UP);
} | class Nodes {
private int maxIndex;
private final NodeType type;
private final BitSet upNodes;
private final Map<Integer, NodeState> nodeStates = new HashMap<>();
Nodes(NodeType type) {
this.type = type;
upNodes = new BitSet();
}
Nodes(Nodes b) {
maxIndex = b.maxIndex;
type = b.type;
upNodes = (BitSet) b.upNodes.clone(... | class Nodes {
private int logicalNodeCount;
private final NodeType type;
private final BitSet upNodes;
private final Map<Integer, NodeState> nodeStates = new HashMap<>();
Nodes(NodeType type) {
this.type = type;
upNodes = new BitSet();
}
Nodes(Nodes b) {
logicalNodeCount = b.logicalNodeCount;
type = b.type;
upNodes = (... |
I'm not sure why this change can fix database lost, could you please add some comment to explain it? | public long loadCluster(DataInputStream dis, long checksum) throws IOException, DdlException {
if (Catalog.getCurrentCatalogJournalVersion() >= FeMetaVersion.VERSION_30) {
int clusterCount = dis.readInt();
checksum ^= clusterCount;
for (long i = 0; i < clusterCount; ++i) {
final Cluster cluster = Cluster.read(dis);
che... | cluster.addDb(dbName, fullNameToDb.get(dbName).getId()); | public long loadCluster(DataInputStream dis, long checksum) throws IOException, DdlException {
if (Catalog.getCurrentCatalogJournalVersion() >= FeMetaVersion.VERSION_30) {
int clusterCount = dis.readInt();
checksum ^= clusterCount;
for (long i = 0; i < clusterCount; ++i) {
final Cluster cluster = Cluster.read(dis);
che... | class SingletonHolder {
private static final Catalog INSTANCE = new Catalog();
} | class SingletonHolder {
private static final Catalog INSTANCE = new Catalog();
} |
I strongly dislike this test. (sorry!) What is the actual _behavior_ that should change based on the mock. I really don't think a mock is necessary or a good idea here. | public void testLaunchFnHarnessAndTeardownCleanly() throws Exception {
Function<String, String> environmentVariableMock = mock(Function.class);
PipelineOptions options = PipelineOptionsFactory.create();
when(environmentVariableMock.apply("HARNESS_ID")).thenReturn("id");
when(environmentVariableMock.apply("PIPELINE_OPTI... | inOrder.verify(instructionResponses).add(INSTRUCTION_RESPONSE); | public void testLaunchFnHarnessAndTeardownCleanly() throws Exception {
Function<String, String> environmentVariableMock = mock(Function.class);
PipelineOptions options = PipelineOptionsFactory.create();
when(environmentVariableMock.apply("HARNESS_ID")).thenReturn("id");
when(environmentVariableMock.apply("PIPELINE_OPTI... | class FnHarnessTestInitializer extends BeamWorkerInitializer {
@Override
public void onStartup() {
onStartupMock.run();
}
@Override
public void beforeProcessing(PipelineOptions options) {
beforeProcessingMock.accept(options);
}
} | class FnHarnessTestInitializer implements JvmInitializer {
@Override
public void onStartup() {
onStartupMock.run();
}
@Override
public void beforeProcessing(PipelineOptions options) {
beforeProcessingMock.accept(options);
}
} |
Do we add a UT to cover the branch of `!containsInTableContainedRule(tableName, materials)` ? | private void refresh(final CreateTableStatement createTableStatement) throws SQLException {
createTableStatement.setTable(new SimpleTableSegment(new TableNameSegment(1, 3, new IdentifierValue("t_order_0"))));
Map<String, DataSource> dataSourceMap = mock(HashMap.class);
when(materials.getDataSourceMap()).thenReturn(data... | schemaRefresher.refresh(schema, Collections.singleton("ds"), createTableStatement, materials); | private void refresh(final CreateTableStatement createTableStatement) throws SQLException {
createTableStatement.setTable(new SimpleTableSegment(new TableNameSegment(1, 3, new IdentifierValue("t_order_0"))));
Map<String, DataSource> dataSourceMap = mock(HashMap.class);
when(materials.getDataSourceMap()).thenReturn(data... | class CreateTableStatementSchemaRefresherTest {
private SchemaBuilderMaterials materials = mock(SchemaBuilderMaterials.class);
@Test
public void refreshForMySQL() throws SQLException {
MySQLCreateTableStatement createTableStatement = new MySQLCreateTableStatement();
createTableStatement.setNotExisted(false);
when(mater... | class CreateTableStatementSchemaRefresherTest {
private SchemaBuilderMaterials materials = mock(SchemaBuilderMaterials.class);
@Test
public void refreshForMySQL() throws SQLException {
MySQLCreateTableStatement createTableStatement = new MySQLCreateTableStatement();
createTableStatement.setNotExisted(false);
when(mater... |
jfyi we could also do: ``` headerMapper = simpleMapper .copy() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); ``` https://static.javadoc.io/com.fasterxml.jackson.core/jackson-databind/2.9.8/com/fasterxml/jackson/databind/ObjectMapper.html#copy-- | public JacksonAdapter() {
simpleMapper = initializeObjectMapper(new ObjectMapper());
xmlMapper = initializeObjectMapper(new XmlMapper());
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
xmlMapper.setDefaultUseWrapper(false);
ObjectMapper flatteningMapper = initializeObjectMapper(new ObjectMappe... | headerMapper = initializeHeaderMapper(new ObjectMapper()); | public JacksonAdapter() {
simpleMapper = initializeObjectMapper(new ObjectMapper());
xmlMapper = initializeObjectMapper(new XmlMapper());
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
xmlMapper.setDefaultUseWrapper(false);
ObjectMapper flatteningMapper = initializeObjectMapper(new ObjectMappe... | class JacksonAdapter implements SerializerAdapter {
private final ClientLogger logger = new ClientLogger(JacksonAdapter.class);
/**
* An instance of {@link ObjectMapper} to serialize/deserialize objects.
*/
private final ObjectMapper mapper;
/**
* An instance of {@link ObjectMapper} that does not do flattening.
*/
priv... | class JacksonAdapter implements SerializerAdapter {
private final ClientLogger logger = new ClientLogger(JacksonAdapter.class);
/**
* An instance of {@link ObjectMapper} to serialize/deserialize objects.
*/
private final ObjectMapper mapper;
/**
* An instance of {@link ObjectMapper} that does not do flattening.
*/
priv... |
it is better to return 0 directly. Objects.hash() will return 0. | public int hashCode() {
return Objects.hash();
} | return Objects.hash(); | public int hashCode() {
return 0;
} | class DataType {
/**
* Convert data type in Doris catalog to data type in Nereids.
* TODO: throw exception when cannot convert catalog type to Nereids type
*
* @param catalogType data type in Doris catalog
* @return data type in Nereids
*/
public static DataType convertFromCatalogDataType(Type catalogType) {
if (catalo... | class DataType {
/**
* Convert data type in Doris catalog to data type in Nereids.
* TODO: throw exception when cannot convert catalog type to Nereids type
*
* @param catalogType data type in Doris catalog
* @return data type in Nereids
*/
public static DataType convertFromCatalogDataType(Type catalogType) {
if (catalo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.