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 |
|---|---|---|---|---|---|
I am not sure I get how we obtain this executor but can we be sure that it never rejects (`RejectedExecutionException`) the task? Or are we just accepting that intentionally and propagate it? | public CompletionStage<Void> invoke(ScheduledExecution execution) throws Exception {
long delay = ThreadLocalRandom.current().nextLong(maxDelay);
DelayedExecution delayedExecution = new DelayedExecution(execution, delay);
try {
event.fire(delayedExecution);
event.fireAsync(delayedExecution);
} catch (Exception e) {
LOG... | executor.schedule(new Runnable() { | public CompletionStage<Void> invoke(ScheduledExecution execution) throws Exception {
long delay = ThreadLocalRandom.current().nextLong(maxDelay);
DelayedExecution delayedExecution = new DelayedExecution(execution, delay);
try {
event.fire(delayedExecution);
event.fireAsync(delayedExecution);
} catch (Exception e) {
LOG... | class DelayedExecutionInvoker extends DelegateInvoker {
private static final Logger LOG = Logger.getLogger(DelayedExecutionInvoker.class);
private final long maxDelay;
private final ScheduledExecutorService executor;
private final Event<DelayedExecution> event;
public DelayedExecutionInvoker(ScheduledInvoker delegate, ... | class DelayedExecutionInvoker extends DelegateInvoker {
private static final Logger LOG = Logger.getLogger(DelayedExecutionInvoker.class);
private final long maxDelay;
private final ScheduledExecutorService executor;
private final Event<DelayedExecution> event;
public DelayedExecutionInvoker(ScheduledInvoker delegate, ... |
This is done to prevent an if condition inside for loop. Since we know if rest bp exists, it will be at the last, we should get the advantage of that without checking the if for each loop. | private BLangMatchPattern transformMatchPattern(Node matchPattern) {
Location matchPatternPos = matchPattern.location();
SyntaxKind kind = matchPattern.kind();
if (kind == SyntaxKind.SIMPLE_NAME_REFERENCE &&
((SimpleNameReferenceNode) matchPattern).name().isMissing()) {
dlog.error(matchPatternPos, DiagnosticErrorCode.M... | } | private BLangMatchPattern transformMatchPattern(Node matchPattern) {
Location matchPatternPos = matchPattern.location();
SyntaxKind kind = matchPattern.kind();
if (kind == SyntaxKind.SIMPLE_NAME_REFERENCE &&
((SimpleNameReferenceNode) matchPattern).name().isMissing()) {
dlog.error(matchPatternPos, DiagnosticErrorCode.M... | class definition
*/
@Override
public BLangNode transform(ObjectConstructorExpressionNode objectConstructorExpressionNode) {
Location pos = getPositionWithoutMetadata(objectConstructorExpressionNode);
BLangClassDefinition anonClass = transformObjectCtorExpressionBody(objectConstructorExpressionNode.members());
anonClass... | class definition
*/
@Override
public BLangNode transform(ObjectConstructorExpressionNode objectConstructorExpressionNode) {
Location pos = getPositionWithoutMetadata(objectConstructorExpressionNode);
BLangClassDefinition anonClass = transformObjectCtorExpressionBody(objectConstructorExpressionNode.members());
anonClass... |
I mean the `KeyGenerator` instance, but if it's done once, then that's okay | public static SecretKey generateSecretKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);
return keyGenerator.generateKey();
} | keyGenerator.init(256); | public static SecretKey generateSecretKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);
return keyGenerator.generateKey();
} | class OidcCommonUtils {
public static final Duration CONNECTION_BACKOFF_DURATION = Duration.ofSeconds(2);
static final byte AMP = '&';
static final byte EQ = '=';
static final String HTTP_SCHEME = "http";
private static final Logger LOG = Logger.getLogger(OidcCommonUtils.class);
private OidcCommonUtils() {
}
public sta... | class OidcCommonUtils {
public static final Duration CONNECTION_BACKOFF_DURATION = Duration.ofSeconds(2);
static final byte AMP = '&';
static final byte EQ = '=';
static final String HTTP_SCHEME = "http";
private static final Logger LOG = Logger.getLogger(OidcCommonUtils.class);
private OidcCommonUtils() {
}
public sta... |
Is it intended that we neglect the non-record type member types in the union types? If so shall we clearly mention that in the documentations? | public static String getModifiedSignature(DocumentServiceContext context, String signature) {
Matcher matcher = TYPE_NAME_DECOMPOSE_PATTERN.matcher(signature);
while (matcher.find()) {
String orgName = matcher.group(1);
String moduleName = matcher.group(2);
String matchedString = matcher.group();
String modulePrefix = ... | } | public static String getModifiedSignature(DocumentServiceContext context, String signature) {
Matcher matcher = TYPE_NAME_DECOMPOSE_PATTERN.matcher(signature);
while (matcher.find()) {
String orgName = matcher.group(1);
String moduleName = matcher.group(2);
String matchedString = matcher.group();
String modulePrefix = ... | class CommonUtil {
public static final String MD_LINE_SEPARATOR = " " + System.lineSeparator();
public static final String LINE_SEPARATOR = System.lineSeparator();
public static final String FILE_SEPARATOR = File.separator;
public static final Pattern MD_NEW_LINE_PATTERN = Pattern.compile("\\s\\s\\r\\n?|\\s\\s\\n|\\r\... | class CommonUtil {
public static final String MD_LINE_SEPARATOR = " " + System.lineSeparator();
public static final String LINE_SEPARATOR = System.lineSeparator();
public static final String FILE_SEPARATOR = File.separator;
public static final Pattern MD_NEW_LINE_PATTERN = Pattern.compile("\\s\\s\\r\\n?|\\s\\s\\n|\\r\... |
Thanks, please consider also moving the DEV mode test as then you can remove the hibernate dependency @gsmet | public AgroalDataSource doCreateDataSource(String dataSourceName) {
if (!dataSourceSupport.entries.containsKey(dataSourceName)) {
throw new IllegalArgumentException("No datasource named '" + dataSourceName + "' exists");
}
DataSourceJdbcBuildTimeConfig dataSourceJdbcBuildTimeConfig = getDataSourceJdbcBuildTimeConfig(da... | if (dataSourceJdbcRuntimeConfig.telemetry.orElse(dataSourceJdbcBuildTimeConfig.telemetry) | public AgroalDataSource doCreateDataSource(String dataSourceName) {
if (!dataSourceSupport.entries.containsKey(dataSourceName)) {
throw new IllegalArgumentException("No datasource named '" + dataSourceName + "' exists");
}
DataSourceJdbcBuildTimeConfig dataSourceJdbcBuildTimeConfig = getDataSourceJdbcBuildTimeConfig(da... | class DataSources {
private static final Logger log = Logger.getLogger(DataSources.class.getName());
public static final String TRACING_DRIVER_CLASSNAME = "io.opentracing.contrib.jdbc.TracingDriver";
private static final String JDBC_URL_PREFIX = "jdbc:";
private static final String JDBC_TRACING_URL_PREFIX = "jdbc:traci... | class DataSources {
private static final Logger log = Logger.getLogger(DataSources.class.getName());
public static final String TRACING_DRIVER_CLASSNAME = "io.opentracing.contrib.jdbc.TracingDriver";
private static final String JDBC_URL_PREFIX = "jdbc:";
private static final String JDBC_TRACING_URL_PREFIX = "jdbc:traci... |
@yvgopal Do you have any idea? | public void setDefaultMessageTimeToLive(Duration defaultMessageTimeToLive) {
if (defaultMessageTimeToLive != null
&& (defaultMessageTimeToLive.compareTo(ManagementClientConstants.MIN_ALLOWED_TTL) < 0
|| defaultMessageTimeToLive.compareTo(ManagementClientConstants.MAX_ALLOWED_TTL) > 0)) {
throw new IllegalArgumentExcept... | if (this.defaultMessageTimeToLive != null | public void setDefaultMessageTimeToLive(Duration defaultMessageTimeToLive) {
if (defaultMessageTimeToLive == null
|| (defaultMessageTimeToLive.compareTo(ManagementClientConstants.MIN_ALLOWED_TTL) < 0
|| defaultMessageTimeToLive.compareTo(ManagementClientConstants.MAX_ALLOWED_TTL) > 0)) {
throw new IllegalArgumentExcept... | class QueueDescription {
Duration duplicationDetectionHistoryTimeWindow = ManagementClientConstants.DEFAULT_HISTORY_DEDUP_WINDOW;
String path;
Duration lockDuration = ManagementClientConstants.DEFAULT_LOCK_DURATION;
Duration defaultMessageTimeToLive = ManagementClientConstants.MAX_DURATION;
Duration autoDeleteOnIdle = ... | class QueueDescription {
Duration duplicationDetectionHistoryTimeWindow = ManagementClientConstants.DEFAULT_HISTORY_DEDUP_WINDOW;
String path;
Duration lockDuration = ManagementClientConstants.DEFAULT_LOCK_DURATION;
Duration defaultMessageTimeToLive = ManagementClientConstants.MAX_DURATION;
Duration autoDeleteOnIdle = ... |
Created issue to track this. : https://github.com/ballerina-platform/ballerina-lang/issues/18342 | private void checkForExportableType(BTypeSymbol symbol, DiagnosticPos pos) {
if (symbol == null || symbol.type == null || Symbols.isFlagOn(symbol.flags, Flags.TYPE_PARAM)) {
return;
}
switch (symbol.type.tag) {
case TypeTags.ARRAY:
checkForExportableType(((BArrayType) symbol.type).eType.tsymbol, pos);
return;
case Type... | private void checkForExportableType(BTypeSymbol symbol, DiagnosticPos pos) {
if (symbol == null || symbol.type == null || Symbols.isFlagOn(symbol.flags, Flags.TYPE_PARAM)) {
return;
}
switch (symbol.type.tag) {
case TypeTags.ARRAY:
checkForExportableType(((BArrayType) symbol.type).eType.tsymbol, pos);
return;
case Type... | 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... | |
(although it's not like the test was actually verifying this before...) | public void testPutSuspendedJobOnClusterShutdown() throws Exception {
final Duration timeout = Duration.ofSeconds(5);
try (final MiniCluster miniCluster =
new PersistingMiniCluster(new MiniClusterConfiguration.Builder().build())) {
miniCluster.start();
final JobGraph jobGraph = JobGraphTestUtils.singleNoOpJobGraph();
f... | return miniCluster.getJobStatus(jobId).get() == JobStatus.FINISHED; | public void testPutSuspendedJobOnClusterShutdown() throws Exception {
try (final MiniCluster miniCluster =
new PersistingMiniCluster(new MiniClusterConfiguration.Builder().build())) {
miniCluster.start();
final JobVertex vertex = new JobVertex("blockingVertex");
vertex.setInvokableClass(SignallingBlockingNoOpInvokable.... | class FileExecutionGraphInfoStoreTest extends TestLogger {
private static final List<JobStatus> GLOBALLY_TERMINAL_JOB_STATUS =
Arrays.stream(JobStatus.values())
.filter(JobStatus::isGloballyTerminalState)
.collect(Collectors.toList());
@ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder();
/*... | class FileExecutionGraphInfoStoreTest extends TestLogger {
private static final List<JobStatus> GLOBALLY_TERMINAL_JOB_STATUS =
Arrays.stream(JobStatus.values())
.filter(JobStatus::isGloballyTerminalState)
.collect(Collectors.toList());
@ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder();
/*... |
nit: possibly just make this the same exception as above? (New types are going to be added without this list being updated, this different wording could lead to user confusion.) | void validateJavaUdfZetaSqlType(Type type) {
switch (type.getKind()) {
case TYPE_INT64:
case TYPE_DOUBLE:
case TYPE_BOOL:
case TYPE_STRING:
case TYPE_BYTES:
break;
case TYPE_NUMERIC:
case TYPE_DATE:
case TYPE_TIME:
case TYPE_DATETIME:
case TYPE_TIMESTAMP:
case TYPE_ARRAY:
case TYPE_STRUCT:
throw new UnsupportedOperatio... | throw new UnsupportedOperationException("Unknown ZetaSQL type: " + type.getKind().name()); | void validateJavaUdfZetaSqlType(Type type) {
switch (type.getKind()) {
case TYPE_INT64:
case TYPE_DOUBLE:
case TYPE_BOOL:
case TYPE_STRING:
case TYPE_BYTES:
break;
case TYPE_NUMERIC:
case TYPE_DATE:
case TYPE_TIME:
case TYPE_DATETIME:
case TYPE_TIMESTAMP:
case TYPE_ARRAY:
case TYPE_STRUCT:
default:
throw new Unsupporte... | class BeamZetaSqlCatalog {
public static final String PRE_DEFINED_WINDOW_FUNCTIONS = "pre_defined_window_functions";
public static final String USER_DEFINED_SQL_FUNCTIONS = "user_defined_functions";
public static final String USER_DEFINED_JAVA_SCALAR_FUNCTIONS =
"user_defined_java_scalar_functions";
/**
* Same as {@lin... | class BeamZetaSqlCatalog {
public static final String PRE_DEFINED_WINDOW_FUNCTIONS = "pre_defined_window_functions";
public static final String USER_DEFINED_SQL_FUNCTIONS = "user_defined_functions";
public static final String USER_DEFINED_JAVA_SCALAR_FUNCTIONS =
"user_defined_java_scalar_functions";
/**
* Same as {@lin... |
Consider matching every value as switch expression on enum is exhaustive, i.e. not matching a value is a compile error if there isn't a `default` clause. | private static Object decodePayload(Inspector entry) {
return switch (entry.type()) {
case STRING -> entry.asString();
case LONG -> entry.asLong();
case BOOL -> entry.asBool();
case DOUBLE -> entry.asDouble();
case DATA -> entry.asData();
default -> null;
};
} | default -> null; | private static Object decodePayload(Inspector entry) {
return switch (entry.type()) {
case STRING -> entry.asString();
case LONG -> entry.asLong();
case BOOL -> entry.asBool();
case DOUBLE -> entry.asDouble();
case DATA -> entry.asData();
default -> null;
};
} | class SlimeTraceDeserializer {
private final Inspector entry;
public SlimeTraceDeserializer(Inspector inspector) {
this.entry = inspector;
}
public TraceNode deserialize() {
return deserialize(entry);
}
private static TraceNode deserialize(Inspector entry) {
Object payload = decodePayload(entry.field(SlimeTraceSerializ... | class SlimeTraceDeserializer {
private final Inspector entry;
public SlimeTraceDeserializer(Inspector inspector) {
this.entry = inspector;
}
public TraceNode deserialize() {
return deserialize(entry);
}
private static TraceNode deserialize(Inspector entry) {
Object payload = decodePayload(entry.field(SlimeTraceSerializ... |
should we have a more specific error message? something like `function invocations are not allowed in lhs...` | public void testCompoundAssignmentNegative() {
CompileResult compileResult = BCompileUtil.compile(
"test-src/statements/compoundassignment/compound_assignment_negative.bal");
int i = 0;
Assert.assertEquals(compileResult.getErrorCount(), 22);
BAssertUtil.validateError(compileResult, i++, "operator '+' not defined for 'a... | BAssertUtil.validateError(compileResult, i, "invalid assignment in variable 'foo(bar)'", 156, 5); | public void testCompoundAssignmentNegative() {
CompileResult compileResult = BCompileUtil.compile(
"test-src/statements/compoundassignment/compound_assignment_negative.bal");
int i = 0;
Assert.assertEquals(compileResult.getErrorCount(), 22);
BAssertUtil.validateError(compileResult, i++, "operator '+' not defined for 'a... | class CompoundAssignmentTest {
private CompileResult result;
@BeforeClass
public void setup() {
result = BCompileUtil.compile("test-src/statements/compoundassignment/compound_assignment.bal");
}
@Test(description = "Test compound assignment with addition.")
public void testCompoundAssignmentAddition() {
BValue[] return... | class CompoundAssignmentTest {
private CompileResult result;
@BeforeClass
public void setup() {
result = BCompileUtil.compile("test-src/statements/compoundassignment/compound_assignment.bal");
}
@Test(description = "Test compound assignment with addition.")
public void testCompoundAssignmentAddition() {
BValue[] return... |
Fixed. ApplicationDispatcherBootstrap now returns "unknown" JobResult in case job result can no longer be retrieved after fail-over. | public void testDuplicateJobSubmissionWithTerminatedJobId() throws Throwable {
final JobID testJobID = new JobID(0, 2);
final Configuration configurationUnderTest = getConfiguration();
configurationUnderTest.set(
PipelineOptionsInternal.PIPELINE_FIXED_JOB_ID, testJobID.toHexString());
configurationUnderTest.set(
HighAv... | CompletableFuture.completedFuture( | public void testDuplicateJobSubmissionWithTerminatedJobId() throws Throwable {
final JobID testJobID = new JobID(0, 2);
final Configuration configurationUnderTest = getConfiguration();
configurationUnderTest.set(
PipelineOptionsInternal.PIPELINE_FIXED_JOB_ID, testJobID.toHexString());
configurationUnderTest.set(
HighAv... | class ApplicationDispatcherBootstrapTest extends TestLogger {
private static final String MULTI_EXECUTE_JOB_CLASS_NAME =
"org.apache.flink.client.testjar.MultiExecuteJob";
private static final int TIMEOUT_SECONDS = 10;
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
final ScheduledExecuto... | class ApplicationDispatcherBootstrapTest extends TestLogger {
private static final String MULTI_EXECUTE_JOB_CLASS_NAME =
"org.apache.flink.client.testjar.MultiExecuteJob";
private static final int TIMEOUT_SECONDS = 10;
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
final ScheduledExecuto... |
@g2vinay: Let's try reusing the `randomByteBufferFlux`. | public Mono<Void> runAsync() {
return dataLakeFileAsyncClient.append(createRandomByteBufferFlux(options.getSize()), 0, options.getSize());
} | return dataLakeFileAsyncClient.append(createRandomByteBufferFlux(options.getSize()), 0, options.getSize()); | public Mono<Void> runAsync() {
return dataLakeFileAsyncClient.append(byteBufferFlux, 0, options.getSize());
} | class AppendFileDatalakeTest extends DirectoryTest<PerfStressOptions> {
private static final String FILE_NAME = "perfstress-file-" + UUID.randomUUID().toString();
protected final DataLakeFileClient dataLakeFileClient;
protected final DataLakeFileAsyncClient dataLakeFileAsyncClient;
public AppendFileDatalakeTest(PerfStr... | class AppendFileDatalakeTest extends DirectoryTest<PerfStressOptions> {
private static final String FILE_NAME = "perfstress-file-" + UUID.randomUUID().toString();
protected final DataLakeFileClient dataLakeFileClient;
protected final DataLakeFileAsyncClient dataLakeFileAsyncClient;
protected final RepeatingInputStream ... |
value and type. I will change it. | private void checkUniqueness(BLangConstant constant) {
if (constant.symbol.kind == SymbolKind.CONSTANT) {
String nameString = constant.name.value;
BLangConstantValue value = constant.symbol.value;
String valueNType;
if (value == null) {
valueNType = String.valueOf(value);
} else {
valueNType = String.valueOf(value) + v... | String valueNType; | private void checkUniqueness(BLangConstant constant) {
if (constant.symbol.kind == SymbolKind.CONSTANT) {
String nameString = constant.name.value;
BLangConstantValue value = constant.symbol.value;
if (constantMap.containsKey(nameString)) {
BLangConstantValue lastValue = constantMap.get(nameString);
if (!value.equals(la... | class ConstantValueResolver extends BLangNodeVisitor {
private static final CompilerContext.Key<ConstantValueResolver> CONSTANT_VALUE_RESOLVER_KEY =
new CompilerContext.Key<>();
private BConstantSymbol currentConstSymbol;
private BLangConstantValue result;
private BLangDiagnosticLog dlog;
private Location currentPos;
p... | class ConstantValueResolver extends BLangNodeVisitor {
private static final CompilerContext.Key<ConstantValueResolver> CONSTANT_VALUE_RESOLVER_KEY =
new CompilerContext.Key<>();
private BConstantSymbol currentConstSymbol;
private BLangConstantValue result;
private BLangDiagnosticLog dlog;
private Location currentPos;
p... |
Could we risk upgrading the package left out? | public void testInstall() {
TaskContext taskContext = mock(TaskContext.class);
TestCommandSupplier commandSupplier = new TestCommandSupplier(taskContext);
commandSupplier.expectCommand("yum list installed package-1", 0, "");
commandSupplier.expectCommand("yum list installed package-2", 1, "");
commandSupplier.expectCom... | "yum install --assumeyes --enablerepo=repo-name package-1 package-2", | public void testInstall() {
TaskContext taskContext = mock(TaskContext.class);
TestCommandSupplier commandSupplier = new TestCommandSupplier(taskContext);
commandSupplier.expectCommand("yum list installed package-1", 0, "");
commandSupplier.expectCommand("yum list installed package-2", 1, "");
commandSupplier.expectCom... | class YumTest {
@Test
public void testAlreadyInstalled() {
TaskContext taskContext = mock(TaskContext.class);
TestCommandSupplier commandSupplier = new TestCommandSupplier(taskContext);
commandSupplier.expectCommand("yum list installed package-1", 0, "");
commandSupplier.expectCommand("yum list installed package-2", 0,... | class YumTest {
@Test
public void testAlreadyInstalled() {
TaskContext taskContext = mock(TaskContext.class);
TestCommandSupplier commandSupplier = new TestCommandSupplier(taskContext);
commandSupplier.expectCommand("yum list installed package-1", 0, "");
commandSupplier.expectCommand("yum list installed package-2", 0,... |
Maybe it would be a good idea to log on `info` if we fall back to another key if `fallbackKey.isDeprecated == false`. That way, the user knows from which option it has read the value. | public boolean contains(ConfigOption<?> configOption) {
synchronized (this.confData){
if (this.confData.containsKey(configOption.key())) {
return true;
}
else if (configOption.hasFallbackKeys()) {
for (FallbackKey fallbackKey : configOption.fallbackKeys()) {
if (this.confData.containsKey(fallbackKey.getKey())) {
if (fa... | if (fallbackKey.isDeprecated()) { | public boolean contains(ConfigOption<?> configOption) {
synchronized (this.confData){
if (this.confData.containsKey(configOption.key())) {
return true;
}
else if (configOption.hasFallbackKeys()) {
for (FallbackKey fallbackKey : configOption.fallbackKeys()) {
if (this.confData.containsKey(fallbackKey.getKey())) {
loggin... | class loader on the caller.
*
* @param key The key of the pair to be added
* @param klazz The value of the pair to be added
* @see
*/
public void setClass(String key, Class<?> klazz) {
setValueInternal(key, klazz.getName());
} | class loader on the caller.
*
* @param key The key of the pair to be added
* @param klazz The value of the pair to be added
* @see
*/
public void setClass(String key, Class<?> klazz) {
setValueInternal(key, klazz.getName());
} |
If the project went through the `package` phase then it will be the JAR. | public void execute() throws MojoExecutionException {
if (project.getPackaging().equals("pom")) {
getLog().info("Type of the artifact is POM, skipping build goal");
return;
}
if (skip) {
getLog().info("Skipping Quarkus build");
return;
}
boolean clear = false;
try {
final Properties projectProperties = project.getPrope... | File projectFile = projectArtifact.getFile(); | public void execute() throws MojoExecutionException {
if (project.getPackaging().equals("pom")) {
getLog().info("Type of the artifact is POM, skipping build goal");
return;
}
if (skip) {
getLog().info("Skipping Quarkus build");
return;
}
boolean clear = false;
try {
final Properties projectProperties = project.getPrope... | class BuildMojo extends AbstractMojo {
protected static final String QUARKUS_PACKAGE_UBER_JAR = "quarkus.package.uber-jar";
/**
* The entry point to Aether, i.e. the component doing all the work.
*
* @component
*/
@Component
private RepositorySystem repoSystem;
@Component
private MavenProjectHelper projectHelper;
/**
*... | class BuildMojo extends AbstractMojo {
protected static final String QUARKUS_PACKAGE_UBER_JAR = "quarkus.package.uber-jar";
/**
* The entry point to Aether, i.e. the component doing all the work.
*
* @component
*/
@Component
private RepositorySystem repoSystem;
@Component
private MavenProjectHelper projectHelper;
/**
*... |
means aggregation functions only use one column | public boolean check(OptExpression input, OptimizerContext context) {
LogicalAggregationOperator aggregate = (LogicalAggregationOperator) input.getOp();
LogicalRepeatOperator repeatOperator = (LogicalRepeatOperator) input.inputAt(0).getOp();
if (aggregate.getType() != AggType.GLOBAL || repeatOperator.getRepeatColumnRef... | return false; | public boolean check(OptExpression input, OptimizerContext context) {
LogicalAggregationOperator aggregate = (LogicalAggregationOperator) input.getOp();
LogicalRepeatOperator repeatOperator = (LogicalRepeatOperator) input.inputAt(0).getOp();
if (aggregate.getType() != AggType.GLOBAL || repeatOperator.getRepeatColumnRef... | class PushDownAggregateGroupingSetsRule extends TransformationRule {
private static final List<String> SUPPORT_AGGREGATE_FUNCTIONS = Lists.newArrayList(FunctionSet.MAX,
FunctionSet.MIN, FunctionSet.SUM);
public PushDownAggregateGroupingSetsRule() {
super(RuleType.TF_PUSHDOWN_AGG_GROUPING_SET,
Pattern.create(OperatorTyp... | class PushDownAggregateGroupingSetsRule extends TransformationRule {
private static final List<String> SUPPORT_AGGREGATE_FUNCTIONS = Lists.newArrayList(FunctionSet.MAX,
FunctionSet.MIN, FunctionSet.SUM);
public PushDownAggregateGroupingSetsRule() {
super(RuleType.TF_PUSHDOWN_AGG_GROUPING_SET,
Pattern.create(OperatorTyp... |
Because in this commit there is no `createAndSetUpSlotPool(Clock clock)` method in `SlotPoolImpl` related test cases. In future commits, I replace all the `createAndSetUpSlotPool` with `SlotPoolBuilder`. | public void testDiscardIdleSlotIfReleasingFailed() throws Exception {
final ManualClock clock = new ManualClock();
try (TestingSlotPoolImpl slotPool = createSlotPoolImpl(clock)) {
setupSlotPool(slotPool, resourceManagerGateway, mainThreadExecutor);
final AllocationID expiredAllocationId = new AllocationID();
final Slot... | setupSlotPool(slotPool, resourceManagerGateway, mainThreadExecutor); | public void testDiscardIdleSlotIfReleasingFailed() throws Exception {
final ManualClock clock = new ManualClock();
try (TestingSlotPoolImpl slotPool = createAndSetUpSlotPool(resourceManagerGateway, clock, TIMEOUT)) {
final AllocationID expiredAllocationId = new AllocationID();
final SlotOffer slotToExpire = new SlotOff... | class SlotPoolImplTest extends TestLogger {
private final Time timeout = Time.seconds(10L);
private JobID jobId;
private TaskManagerLocation taskManagerLocation;
private SimpleAckingTaskManagerGateway taskManagerGateway;
private TestingResourceManagerGateway resourceManagerGateway;
private ComponentMainThreadExecutor m... | class SlotPoolImplTest extends TestLogger {
private static final Time TIMEOUT = SlotPoolUtils.TIMEOUT;
private TaskManagerLocation taskManagerLocation;
private SimpleAckingTaskManagerGateway taskManagerGateway;
private TestingResourceManagerGateway resourceManagerGateway;
private static final ComponentMainThreadExecuto... |
Ok, It's about ones' design thinking, you can keep your style. | public static List<SqlNode> convertOrderByItems(final Collection<OrderByItemSegment> orderByItems) {
List<SqlNode> sqlNodes = Lists.newArrayList();
for (OrderByItemSegment orderByItemSegment : orderByItems) {
Optional<SqlNode> optional = Optional.empty();
if (orderByItemSegment instanceof ColumnOrderByItemSegment) {
op... | List<SqlNode> sqlNodes = Lists.newArrayList(); | public static List<SqlNode> convertOrderByItems(final Collection<OrderByItemSegment> orderByItems) {
List<SqlNode> sqlNodes = Lists.newArrayList();
for (OrderByItemSegment orderByItemSegment : orderByItems) {
Optional<SqlNode> optional = Optional.empty();
if (orderByItemSegment instanceof ColumnOrderByItemSegment) {
op... | class SqlNodeConverterUtil {
/**
* Convert order by items.
* @param orderByItems order by item list.
* @return a collection of order by item <code>SqlNode</code>
*/
} | class SqlNodeConverterUtil {
/**
* Convert order by items.
* @param orderByItems order by item list.
* @return a collection of order by item <code>SqlNode</code>
*/
} |
Nope. The mailbox executes the writer. | public void write(IN element, Context context) throws IOException, InterruptedException {
sinkContextAdapter.updateTimestamp(context);
RawMessage<byte[]> message = serializationSchema.serialize(element, sinkContextAdapter);
List<String> availableTopics = metadataListener.availableTopics();
String topic = topicRouter.ro... | } | public void write(IN element, Context context) throws IOException, InterruptedException {
PulsarMessage<?> message = serializationSchema.serialize(element, sinkContext);
String key = message.getKey();
List<String> availableTopics = metadataListener.availableTopics();
String topic = topicRouter.route(element, key, avail... | class PulsarWriter<IN> implements SinkWriter<IN, PulsarCommittable, Void> {
private static final Logger LOG = LoggerFactory.getLogger(PulsarWriter.class);
private final SinkConfiguration sinkConfiguration;
private final DeliveryGuarantee deliveryGuarantee;
private final PulsarSerializationSchema<IN> serializationSchema... | class PulsarWriter<IN> implements PrecommittingSinkWriter<IN, PulsarCommittable> {
private static final Logger LOG = LoggerFactory.getLogger(PulsarWriter.class);
private final SinkConfiguration sinkConfiguration;
private final PulsarSerializationSchema<IN> serializationSchema;
private final TopicMetadataListener metada... |
non synchronized access to `childTokenSourceList` may cause concurrency access failure. | public void cancel() {
if (this.cancellationRequested.compareAndSet(false, true)) {
for (LinkedCancellationTokenSource childTokenSource : this.childTokenSourceList) {
childTokenSource.close();
}
childTokenSourceList.clear();
}
} | childTokenSourceList.clear(); | public void cancel() {
synchronized (this) {
if (this.cancellationRequested.compareAndSet(false, true)) {
for (LinkedCancellationTokenSource childTokenSource : this.childTokenSourceList) {
childTokenSource.close();
}
childTokenSourceList.clear();
}
}
} | class LinkedCancellationToken {
private final List<LinkedCancellationTokenSource> childTokenSourceList;
private final LinkedCancellationTokenSource tokenSource;
private final AtomicBoolean cancellationRequested;
public LinkedCancellationToken(LinkedCancellationTokenSource tokenSource) {
this.childTokenSourceList = new ... | class LinkedCancellationToken {
private final List<LinkedCancellationTokenSource> childTokenSourceList;
private final LinkedCancellationTokenSource tokenSource;
private final AtomicBoolean cancellationRequested;
public LinkedCancellationToken(LinkedCancellationTokenSource tokenSource) {
this.childTokenSourceList = new ... |
Can't we just use something like `container.beanManager().getEvent().select(new TypeLiteral<AtomicReference<String>>(){}).fire(msg);` instead? | public void testObserverNotification() {
ArcContainer container = Arc.container();
ReferenceWrapper msg = new ReferenceWrapper();
RequestFoo.DESTROYED.set(false);
container.beanManager().getEvent().select(ReferenceWrapper.class).fire(msg);
String fooId1 = msg.getReference().get();
assertNotNull(fooId1);
assertTrue(Requ... | container.beanManager().getEvent().select(ReferenceWrapper.class).fire(msg); | public void testObserverNotification() {
ArcContainer container = Arc.container();
AtomicReference<String> msg = new AtomicReference<>();
RequestFoo.DESTROYED.set(false);
container.beanManager().getEvent().select(new TypeLiteral<AtomicReference<String>>() {
}).fire(msg);
String fooId1 = msg.get();
assertNotNull(fooId1)... | class RequestInObserverNotificationTest {
@RegisterExtension
public ArcTestContainer container = new ArcTestContainer(RequestFoo.class, MyObserver.class);
@Test
@Singleton
static class MyObserver {
@SuppressWarnings({ "rawtypes", "unchecked" })
void observeString(@Observes ReferenceWrapper value, RequestFoo foo) {
valu... | class RequestInObserverNotificationTest {
@RegisterExtension
public ArcTestContainer container = new ArcTestContainer(RequestFoo.class, MyObserver.class);
@Test
@Singleton
static class MyObserver {
@SuppressWarnings({ "rawtypes", "unchecked" })
void observeString(@Observes AtomicReference value, RequestFoo foo) {
value... |
How i atomicity ensured here? WOuldn't you need to hold at least a read lock to read this.lastDatabaseAccount and locationCache atomically? | private List<String> getEffectivePreferredRegions() {
if (this.connectionPolicy.getPreferredRegions() != null && !this.connectionPolicy.getPreferredRegions().isEmpty()) {
return this.connectionPolicy.getPreferredRegions();
}
if (this.latestDatabaseAccount == null) {
return Collections.emptyList();
}
return this.locatio... | private List<String> getEffectivePreferredRegions() {
if (this.connectionPolicy.getPreferredRegions() != null && !this.connectionPolicy.getPreferredRegions().isEmpty()) {
return this.connectionPolicy.getPreferredRegions();
}
this.databaseAccountReadLock.lock();
try {
if (this.latestDatabaseAccount == null) {
return Col... | class GlobalEndpointManager implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(GlobalEndpointManager.class);
private static final CosmosDaemonThreadFactory theadFactory = new CosmosDaemonThreadFactory("cosmos-global-endpoint-mgr");
private final int backgroundRefreshLocationTimeInte... | class GlobalEndpointManager implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(GlobalEndpointManager.class);
private static final CosmosDaemonThreadFactory theadFactory = new CosmosDaemonThreadFactory("cosmos-global-endpoint-mgr");
private final int backgroundRefreshLocationTimeInte... | |
We can do a direct assignment here | public void windowCleanupScheduled() throws Exception {
final String stateId = "my-state-id";
PCollection<KV<String, Integer>> input =
pipeline
.apply(Create.of(KV.of("hello", 1), KV.of("hello", 2)))
.apply(Window.into(FixedWindows.of(Duration.millis(10))));
TupleTag<Integer> mainOutput = new TupleTag<>();
final ParDoM... | @StateId(stateId) | public void windowCleanupScheduled() throws Exception {
final String stateId = "my-state-id";
PCollection<KV<String, Integer>> input =
pipeline
.apply(Create.of(KV.of("hello", 1), KV.of("hello", 2)))
.apply(Window.into(FixedWindows.of(Duration.millis(10))));
TupleTag<Integer> mainOutput = new TupleTag<>();
final ParDoM... | class StatefulParDoEvaluatorFactoryTest implements Serializable {
@Mock private transient EvaluationContext mockEvaluationContext;
@Mock private transient DirectExecutionContext mockExecutionContext;
@Mock private transient DirectExecutionContext.DirectStepContext mockStepContext;
@Mock private transient ReadyCheckingS... | class StatefulParDoEvaluatorFactoryTest implements Serializable {
@Mock private transient EvaluationContext mockEvaluationContext;
@Mock private transient DirectExecutionContext mockExecutionContext;
@Mock private transient DirectExecutionContext.DirectStepContext mockStepContext;
@Mock private transient ReadyCheckingS... |
We'd better to wrap the requiredParams and SQL template string by a individual class rather than hard code it in every single method. | public static String buildStatsMinValueSql(Map<String, String> params) throws InvalidFormatException {
Set<String> requiredParams = Sets.newHashSet("table", "column");
if (checkParams(requiredParams, params)) {
return processTemplate(MIN_VALUE_SQL, params);
} else {
throw new InvalidFormatException("Wrong parameter for... | Set<String> requiredParams = Sets.newHashSet("table", "column"); | public static String buildStatsMinValueSql(Map<String, String> params) throws InvalidFormatException {
Set<String> requiredParams = getTemplateParams(MIN_VALUE_SQL);
if (checkParams(requiredParams, params)) {
return processTemplate(MIN_VALUE_SQL, params);
} else {
throw new InvalidFormatException("Wrong parameter forma... | class InternalSqlTemplate {
/** -------------------------- for statistics begin -------------------------- */
public static final String MIN_VALUE_SQL = "SELECT MIN(${column}) AS min_value FROM ${table};";
public static final String PARTITION_MIN_VALUE_SQL = "SELECT MIN(${column}) AS min_value"
+ " FROM ${table} PARTIT... | class InternalSqlTemplate {
/** -------------------------- for statistics begin -------------------------- */
public static final String MIN_VALUE_SQL = "SELECT MIN(${column}) AS min_value FROM ${table};";
public static final String PARTITION_MIN_VALUE_SQL = "SELECT MIN(${column}) AS min_value"
+ " FROM ${table} PARTIT... |
Consider moving the comment (or comma) here and above to make the inline comment point at the right parameter | protected void setUp(boolean dontInitializeNode2) throws Exception {
Distribution distribution = new Distribution(Distribution.getSimpleGroupConfig(2, 10));
jsonWriter.setDefaultPathPrefix("/cluster/v2");
{
Set<ConfiguredNode> nodes = FleetControllerTest.toNodes(0, 1, 2, 3);
ContentCluster cluster = new ContentCluster(... | "music", nodes, distribution, 4 /* minStorageNodesUp*/, 0.0, /* minRatioOfStorageNodesUp */true); | protected void setUp(boolean dontInitializeNode2) throws Exception {
Distribution distribution = new Distribution(Distribution.getSimpleGroupConfig(2, 10));
jsonWriter.setDefaultPathPrefix("/cluster/v2");
{
Set<ConfiguredNode> nodes = FleetControllerTest.toNodes(0, 1, 2, 3);
ContentCluster cluster = new ContentCluster(... | class StateRequest implements UnitStateRequest {
private String[] path;
private int recursive;
StateRequest(String req, int recursive) {
path = req.isEmpty() ? new String[0] : req.split("/");
this.recursive = recursive;
}
@Override
public int getRecursiveLevels() { return recursive;
}
@Override
public String[] getUnitP... | class StateRequest implements UnitStateRequest {
private String[] path;
private int recursive;
StateRequest(String req, int recursive) {
path = req.isEmpty() ? new String[0] : req.split("/");
this.recursive = recursive;
}
@Override
public int getRecursiveLevels() { return recursive;
}
@Override
public String[] getUnitP... |
You are right, currently HBase connector only support atomic types as columns (HBase qualifier). | private HBaseTableSchema validateTableSchema(TableSchema schema) {
HBaseTableSchema hbaseSchema = new HBaseTableSchema();
String[] fieldNames = schema.getFieldNames();
TypeInformation[] fieldTypes = schema.getFieldTypes();
for (int i = 0; i < fieldNames.length; i++) {
String name = fieldNames[i];
TypeInformation<?> typ... | clazz = Timestamp.class; | private HBaseTableSchema validateTableSchema(TableSchema schema) {
HBaseTableSchema hbaseSchema = new HBaseTableSchema();
String[] fieldNames = schema.getFieldNames();
TypeInformation[] fieldTypes = schema.getFieldTypes();
for (int i = 0; i < fieldNames.length; i++) {
String name = fieldNames[i];
TypeInformation<?> typ... | class HBaseTableFactory implements StreamTableSourceFactory<Row>, StreamTableSinkFactory<Tuple2<Boolean, Row>> {
@Override
public StreamTableSource<Row> createStreamTableSource(Map<String, String> properties) {
final DescriptorProperties descriptorProperties = getValidatedProperties(properties);
Configuration hbaseClie... | class HBaseTableFactory implements StreamTableSourceFactory<Row>, StreamTableSinkFactory<Tuple2<Boolean, Row>> {
@Override
public StreamTableSource<Row> createStreamTableSource(Map<String, String> properties) {
final DescriptorProperties descriptorProperties = getValidatedProperties(properties);
Configuration hbaseClie... |
Sorry, I missed this on the first pass. We want `RuntimeException` to be passed through without modification if possible. I believe this will work: ``` if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw new RuntimeException(e); ``` | private void outputRow(TimestampedFuture c, OutputReceiver<Row> r) throws InterruptedException {
final Value v;
try {
v = c.future().get();
} catch (ExecutionException e) {
throw new RuntimeException(checkArgumentNotNull(e.getCause()));
}
if (!v.isNull()) {
Row row = ZetaSqlBeamTranslationUtils.toBeamRow(v, outputSchem... | throw new RuntimeException(checkArgumentNotNull(e.getCause())); | private void outputRow(TimestampedFuture c, OutputReceiver<Row> r) throws InterruptedException {
final Value v;
try {
v = c.future().get();
} catch (ExecutionException e) {
throw extractException(e);
}
if (!v.isNull()) {
Row row = ZetaSqlBeamTranslationUtils.toBeamRow(v, outputSchema, verifyRowValues);
r.outputWithTime... | class OutputReceiverForFinishBundle implements OutputReceiver<Row> {
private final FinishBundleContext c;
private final BoundedWindow w;
private OutputReceiverForFinishBundle(FinishBundleContext c, BoundedWindow w) {
this.c = c;
this.w = w;
}
@Override
public void output(Row output) {
throw new RuntimeException("Unsupp... | class OutputReceiverForFinishBundle implements OutputReceiver<Row> {
private final FinishBundleContext c;
private final BoundedWindow w;
private OutputReceiverForFinishBundle(FinishBundleContext c, BoundedWindow w) {
this.c = c;
this.w = w;
}
@Override
public void output(Row output) {
throw new RuntimeException("Unsupp... |
Can you extract these if condition to new private method? | private SqlNode convertSQLStatement(final ExplainStatement deleteStatement) {
return deleteStatement.getStatement().map(each -> {
if (each instanceof SelectStatement) {
return new SelectStatementConverter().convert((SelectStatement) each);
} else if (each instanceof DeleteStatement) {
return new DeleteStatementConverte... | if (each instanceof SelectStatement) { | private SqlNode convertSQLStatement(final ExplainStatement deleteStatement) {
return deleteStatement.getStatement().map(this::convertSqlNode).orElseThrow(IllegalStateException::new);
} | class ExplainStatementConverter implements SQLStatementConverter<ExplainStatement, SqlNode> {
@Override
public SqlNode convert(final ExplainStatement deleteStatement) {
return new SqlExplain(SqlParserPos.ZERO, convertSQLStatement(deleteStatement), SqlExplainLevel.ALL_ATTRIBUTES.symbol(SqlParserPos.ZERO),
SqlExplain.Dep... | class ExplainStatementConverter implements SQLStatementConverter<ExplainStatement, SqlNode> {
@Override
public SqlNode convert(final ExplainStatement deleteStatement) {
return new SqlExplain(SqlParserPos.ZERO, convertSQLStatement(deleteStatement), SqlExplainLevel.ALL_ATTRIBUTES.symbol(SqlParserPos.ZERO),
SqlExplain.Dep... |
EXECUTE COMMAND need return binary row format | private void initQueryOptions(ConnectContext context) {
this.queryOptions = context.getSessionVariable().toThrift();
this.queryOptions.setEnablePipelineEngine(SessionVariable.enablePipelineEngine());
this.queryOptions.setBeExecVersion(Config.be_exec_version);
this.queryOptions.setQueryTimeout(context.getExecTimeout());... | this.queryOptions.setMysqlRowBinaryFormat( | private void initQueryOptions(ConnectContext context) {
this.queryOptions = context.getSessionVariable().toThrift();
this.queryOptions.setEnablePipelineEngine(SessionVariable.enablePipelineEngine());
this.queryOptions.setBeExecVersion(Config.be_exec_version);
this.queryOptions.setQueryTimeout(context.getExecTimeout());... | class Coordinator implements CoordInterface {
private static final Logger LOG = LogManager.getLogger(Coordinator.class);
private static final String localIP = FrontendOptions.getLocalHostAddress();
private static final Random instanceRandom = new Random();
Status queryStatus = new Status();
Map<TNetworkAddress, Long> a... | class Coordinator implements CoordInterface {
private static final Logger LOG = LogManager.getLogger(Coordinator.class);
private static final String localIP = FrontendOptions.getLocalHostAddress();
private static final Random instanceRandom = new Random();
Status queryStatus = new Status();
Map<TNetworkAddress, Long> a... |
```suggestion assertThatFuture(allocatedFuture).eventuallySucceeds(); ``` The test is succeeding even with the production code change not being applied. We're getting into the right code path for this test, but we're not asserting the returned future correctly as far as I can see. (hint: You have to statically... | void testAllocationUpdatesIgnoredIfSlotRemoved() throws Exception {
final FineGrainedTaskManagerTracker taskManagerTracker =
new FineGrainedTaskManagerTracker();
final CompletableFuture<
Tuple6<
SlotID,
JobID,
AllocationID,
ResourceProfile,
String,
ResourceManagerId>>
requestFuture = new CompletableFuture<>();
final Co... | assertThat(allocatedFuture).isNotCompletedExceptionally(); | void testAllocationUpdatesIgnoredIfSlotRemoved() throws Exception {
testSlotAllocation(
(slotStatusSyncer, taskManagerTracker, instanceID, allocationId) -> {
taskManagerTracker.removeTaskManager(instanceID);
assertThat(taskManagerTracker.getAllocatedOrPendingSlot(allocationId))
.isEmpty();
});
} | class DefaultSlotStatusSyncerTest {
private static final Time TASK_MANAGER_REQUEST_TIMEOUT = Time.seconds(10);
private static final TaskExecutorConnection TASK_EXECUTOR_CONNECTION =
new TaskExecutorConnection(
ResourceID.generate(),
new TestingTaskExecutorGatewayBuilder().createTestingTaskExecutorGateway());
@RegisterE... | class DefaultSlotStatusSyncerTest {
private static final Time TASK_MANAGER_REQUEST_TIMEOUT = Time.seconds(10);
private static final TaskExecutorConnection TASK_EXECUTOR_CONNECTION =
new TaskExecutorConnection(
ResourceID.generate(),
new TestingTaskExecutorGatewayBuilder().createTestingTaskExecutorGateway());
@RegisterE... |
Here a trailing WS is not required AFAIU. | public ImportDeclarationNode transform(ImportDeclarationNode importDeclarationNode) {
Token importKeyword = formatToken(importDeclarationNode.importKeyword(), 0, 0);
if (importDeclarationNode.orgName().isPresent()) {
ImportOrgNameNode orgName = formatNode(importDeclarationNode.orgName().get(), 0, 0);
importDeclarationN... | ImportPrefixNode prefix = formatNode(importDeclarationNode.prefix().get(), 0, 0); | public ImportDeclarationNode transform(ImportDeclarationNode importDeclarationNode) {
Token importKeyword = formatToken(importDeclarationNode.importKeyword(), 1, 0);
boolean hasOrgName = importDeclarationNode.orgName().isPresent();
boolean hasVersion = importDeclarationNode.version().isPresent();
boolean hasPrefix = im... | class NewFormattingTreeModifier extends FormattingTreeModifier {
/**
* Number of of whitespace characters to be used as the indentation for the current line.
*/
private int indentation = 0;
/**
* Number of leading newlines to be added to the currently processing node.
*/
private int leadingNL = 0;
/**
* Number of trail... | class NewFormattingTreeModifier extends FormattingTreeModifier {
/**
* Number of of whitespace characters to be used as the indentation for the current line.
*/
private int indentation = 0;
/**
* Number of leading newlines to be added to the currently processing node.
*/
private int leadingNL = 0;
/**
* Number of trail... |
If we can return `false` from the calling methods (ie `hasQualifiedIdentifier` and `hasBacktickExpr`) whenever `peek(lookahead.offset).kind == SyntaxKind.BACKTIC_CONTENT` then we can simplify this by removing the `Lookahead` class | private boolean isValidBacktickContentSequence(ReferenceGenre refGenre) {
boolean hasMatch;
Lookahead lookahead = new Lookahead();
switch (refGenre) {
case SPECIAL_KEY:
hasMatch = hasQualifiedIdentifier(lookahead);
break;
case FUNCTION_KEY:
hasMatch = hasBacktickExpr(lookahead, true);
break;
case NO_KEY:
hasMatch = has... | return hasMatch && peek(lookahead.offset).kind == SyntaxKind.BACKTICK_TOKEN; | private boolean isValidBacktickContentSequence(ReferenceGenre refGenre) {
boolean hasMatch;
Lookahead lookahead = new Lookahead();
switch (refGenre) {
case SPECIAL_KEY:
hasMatch = hasQualifiedIdentifier(lookahead);
break;
case FUNCTION_KEY:
hasMatch = hasBacktickExpr(lookahead, true);
break;
case NO_KEY:
hasMatch = has... | class Lookahead {
private int offset = 1;
} | class Lookahead {
private int offset = 1;
} |
Please use each to replace tableHintLimitedContext. | public ASTNode visitWithTableHint(final WithTableHintContext ctx) {
WithTableHintSegment withTableHintSegment = new WithTableHintSegment(ctx.start.getStartIndex(), ctx.stop.getStopIndex());
if (null != ctx.tableHintLimited()) {
Collection<TableHintLimitedSegment> tableHintLimitedSegments = new LinkedList<>();
for (Tabl... | for (TableHintLimitedContext tableHintLimitedContext : ctx.tableHintLimited()) { | public ASTNode visitWithTableHint(final WithTableHintContext ctx) {
WithTableHintSegment result = new WithTableHintSegment(ctx.start.getStartIndex(), ctx.stop.getStopIndex());
if (null != ctx.tableHintLimited()) {
Collection<TableHintLimitedSegment> tableHintLimitedSegments = new LinkedList<>();
for (TableHintLimitedCo... | class SQLServerStatementVisitor extends SQLServerStatementBaseVisitor<ASTNode> {
private final Collection<ParameterMarkerSegment> parameterMarkerSegments = new LinkedList<>();
@Override
public final ASTNode visitParameterMarker(final ParameterMarkerContext ctx) {
return new ParameterMarkerValue(parameterMarkerSegments.... | class SQLServerStatementVisitor extends SQLServerStatementBaseVisitor<ASTNode> {
private final Collection<ParameterMarkerSegment> parameterMarkerSegments = new LinkedList<>();
@Override
public final ASTNode visitParameterMarker(final ParameterMarkerContext ctx) {
return new ParameterMarkerValue(parameterMarkerSegments.... |
The keySet method of org.springframework.messaging.MessageHeaders returns an unmodified Set. I have updated the copyHeaders as a map and use the putAll API. | protected void setCustomHeaders(MessageHeaders headers, ServiceBusMessage message) {
Set<String> copyHeaders = new HashSet<String>();
headers.forEach((key, value) -> {
copyHeaders.add(key);
});
getStringHeader(headers, copyHeaders, MessageHeaders.ID).ifPresent(message::setMessageId);
getStringHeader(headers, copyHeader... | }); | protected void setCustomHeaders(MessageHeaders headers, ServiceBusMessage message) {
Map<String, Object> copySpringMessageHeaders = new HashMap<String, Object>();
copySpringMessageHeaders.putAll(headers);
getAndRemove(copySpringMessageHeaders, MessageHeaders.ID, UUID.class)
.ifPresent(val -> message.setMessageId(val.to... | class ServiceBusMessageConverter
extends AbstractAzureMessageConverter<ServiceBusReceivedMessage, ServiceBusMessage> {
private final ObjectMapper objectMapper;
public ServiceBusMessageConverter() {
objectMapper = OBJECT_MAPPER;
}
public ServiceBusMessageConverter(ObjectMapper objectMapper) {
this.objectMapper = objectM... | class ServiceBusMessageConverter
extends AbstractAzureMessageConverter<ServiceBusReceivedMessage, ServiceBusMessage> {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceBusMessageConverter.class);
private final ObjectMapper objectMapper;
public ServiceBusMessageConverter() {
objectMapper = OBJECT_MAPP... |
```suggestion Objects.equals(checkPointType, that.checkpointType) && ``` | public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CheckpointStatistics that = (CheckpointStatistics) o;
return id == that.id &&
savepoint == that.savepoint &&
triggerTimestamp == that.triggerTimestamp &&
latestAckTimestamp == that.latestAckT... | Objects.equals(checkPointType, that.checkPointType) && | public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CheckpointStatistics that = (CheckpointStatistics) o;
return id == that.id &&
savepoint == that.savepoint &&
triggerTimestamp == that.triggerTimestamp &&
latestAckTimestamp == that.latestAckT... | class CheckpointStatistics implements ResponseBody {
public static final String FIELD_NAME_ID = "id";
public static final String FIELD_NAME_STATUS = "status";
public static final String FIELD_NAME_IS_SAVEPOINT = "is_savepoint";
public static final String FIELD_NAME_TRIGGER_TIMESTAMP = "trigger_timestamp";
public static... | class CheckpointStatistics implements ResponseBody {
public static final String FIELD_NAME_ID = "id";
public static final String FIELD_NAME_STATUS = "status";
public static final String FIELD_NAME_IS_SAVEPOINT = "is_savepoint";
public static final String FIELD_NAME_TRIGGER_TIMESTAMP = "trigger_timestamp";
public static... |
hi, silver These two cases are meant to explain the critical scenario | public void dateFormat() {
Locale.setDefault(Locale.ENGLISH);
ConstantOperator testDate = ConstantOperator.createDatetime(LocalDateTime.of(2001, 1, 9, 13, 4, 5));
assertEquals("1",
ScalarOperatorFunctions.dateFormat(testDate, ConstantOperator.createVarchar("%c")).getVarchar());
assertEquals("09",
ScalarOperatorFunction... | ConstantOperator.createVarchar("%v")).getVarchar()); | public void dateFormat() {
Locale.setDefault(Locale.ENGLISH);
ConstantOperator testDate = ConstantOperator.createDatetime(LocalDateTime.of(2001, 1, 9, 13, 4, 5));
assertEquals("1",
ScalarOperatorFunctions.dateFormat(testDate, ConstantOperator.createVarchar("%c")).getVarchar());
assertEquals("09",
ScalarOperatorFunction... | class ScalarOperatorFunctionsTest {
private static ConstantOperator O_DT_20101102_183010;
private static ConstantOperator O_DT_20101202_023010;
private static ConstantOperator O_DT_20150323_092355;
private static ConstantOperator O_TI_10;
private static ConstantOperator O_SI_10;
private static ConstantOperator O_INT_10... | class ScalarOperatorFunctionsTest {
private static ConstantOperator O_DT_20101102_183010;
private static ConstantOperator O_DT_20101202_023010;
private static ConstantOperator O_DT_20150323_092355;
private static ConstantOperator O_TI_10;
private static ConstantOperator O_SI_10;
private static ConstantOperator O_INT_10... |
This should be in an `else` block of `if (errorAfter` above. See the .NET version: https://github.com/Azure/azure-sdk-for-net/blob/main/common/Perf/Azure.Sample.Perf/Event/MockEventProcessor.cs#L131 | private void process(int partition) {
MockEventContext mockEventContext = mockEventContexts[partition];
if (maxEventsPerSecond > 0) {
while (process) {
long elapsedTime = (System.nanoTime() - startTime);
if (errorAfter != null && !errorRaised
&& (errorAfter.compareTo(Duration.ofNanos(elapsedTime)) < 0)) {
errorLock.loc... | processEvent.accept(mockEventContext); | private void process(int partition) {
MockEventContext mockEventContext = mockEventContexts[partition];
if (maxEventsPerSecond > 0) {
while (process) {
long elapsedTime = (System.nanoTime() - startTime);
if (errorAfter != null && !errorRaised
&& (errorAfter.compareTo(Duration.ofNanos(elapsedTime)) < 0)) {
errorLock.loc... | class MockEventProcessor {
private final Consumer<MockErrorContext> processError;
private final Consumer<MockEventContext> processEvent;
private boolean process;
private final double maxEventsPerSecondPerPartition;
private final int maxEventsPerSecond;
private final int partitions;
private final Duration errorAfter;
pr... | class MockEventProcessor {
private final Consumer<MockErrorContext> processError;
private final Consumer<MockEventContext> processEvent;
private volatile boolean process;
private final double maxEventsPerSecondPerPartition;
private final int maxEventsPerSecond;
private final int partitions;
private final Duration error... |
nit: "a bit" is a little confusing since it's just waiting ditto below | public void testScheduledBudgetRefresh() throws InterruptedException {
CountDownLatch redistributeBudgetLatch = new CountDownLatch(1);
Runnable redistributeBudget = redistributeBudgetLatch::countDown;
GetWorkBudgetRefresher budgetRefresher = createBudgetRefresher(redistributeBudget);
budgetRefresher.start();
redistribu... | public void testScheduledBudgetRefresh() throws InterruptedException {
CountDownLatch redistributeBudgetLatch = new CountDownLatch(1);
Runnable redistributeBudget = redistributeBudgetLatch::countDown;
GetWorkBudgetRefresher budgetRefresher = createBudgetRefresher(redistributeBudget);
budgetRefresher.start();
redistribu... | class GetWorkBudgetRefresherTest {
private static final int WAIT_BUFFER = 10;
@Rule public transient Timeout globalTimeout = Timeout.seconds(600);
private GetWorkBudgetRefresher createBudgetRefresher(Runnable redistributeBudget) {
return createBudgetRefresher(false, redistributeBudget);
}
private GetWorkBudgetRefresher... | class GetWorkBudgetRefresherTest {
private static final int WAIT_BUFFER = 10;
@Rule public transient Timeout globalTimeout = Timeout.seconds(600);
private GetWorkBudgetRefresher createBudgetRefresher(Runnable redistributeBudget) {
return createBudgetRefresher(false, redistributeBudget);
}
private GetWorkBudgetRefresher... | |
Shall we also recheck formatting for all the code introduced? | public void visit(BLangFunction funcNode) {
SymbolEnv fucEnv = SymbolEnv.createFunctionEnv(funcNode, funcNode.symbol.scope, env);
if (!funcNode.interfaceFunction) {
addReturnIfNotPresent(funcNode);
}
funcNode.originalFuncSymbol = funcNode.symbol;
funcNode.symbol = ASTBuilderUtil.duplicateInvokableSymbol(funcNode.symbol... | rewriteExpr(compoundAssignment.modifiedExpr)); | public void visit(BLangFunction funcNode) {
SymbolEnv fucEnv = SymbolEnv.createFunctionEnv(funcNode, funcNode.symbol.scope, env);
if (!funcNode.interfaceFunction) {
addReturnIfNotPresent(funcNode);
}
funcNode.originalFuncSymbol = funcNode.symbol;
funcNode.symbol = ASTBuilderUtil.duplicateInvokableSymbol(funcNode.symbol... | class Desugar extends BLangNodeVisitor {
private static final CompilerContext.Key<Desugar> DESUGAR_KEY =
new CompilerContext.Key<>();
private static final String QUERY_TABLE_WITH_JOIN_CLAUSE = "queryTableWithJoinClause";
private static final String QUERY_TABLE_WITHOUT_JOIN_CLAUSE = "queryTableWithoutJoinClause";
privat... | class Desugar extends BLangNodeVisitor {
private static final CompilerContext.Key<Desugar> DESUGAR_KEY =
new CompilerContext.Key<>();
private static final String QUERY_TABLE_WITH_JOIN_CLAUSE = "queryTableWithJoinClause";
private static final String QUERY_TABLE_WITHOUT_JOIN_CLAUSE = "queryTableWithoutJoinClause";
privat... |
My bad. It is a kind of unnecessary condition. Will remove. Thanks. | private void updateSymbolType(BLangConstant constant) {
if (constant.symbol.kind == SymbolKind.CONSTANT && constant.symbol.type.getKind() != TypeKind.FINITE &&
constant.symbol.value != null) {
BFiniteType finiteType = checkType(constant, constant.symbol.value.value, constant.symbol.type,
constant.symbol.pos);
if (finit... | if (constant.symbol.kind == SymbolKind.CONSTANT && constant.symbol.type.getKind() != TypeKind.FINITE && | private void updateSymbolType(BLangConstant constant) {
BConstantSymbol symbol = constant.symbol;
if (symbol.type.getKind() != TypeKind.FINITE && symbol.value != null) {
BType singletonType = checkType(constant.expr, constant, symbol.value.value, symbol.type, symbol.pos);
if (singletonType != null) {
symbol.type = sing... | class ConstantValueResolver extends BLangNodeVisitor {
private static final CompilerContext.Key<ConstantValueResolver> CONSTANT_VALUE_RESOLVER_KEY =
new CompilerContext.Key<>();
private BConstantSymbol currentConstSymbol;
private BLangConstantValue result;
private BLangDiagnosticLog dlog;
private Location currentPos;
p... | class ConstantValueResolver extends BLangNodeVisitor {
private static final CompilerContext.Key<ConstantValueResolver> CONSTANT_VALUE_RESOLVER_KEY =
new CompilerContext.Key<>();
private BConstantSymbol currentConstSymbol;
private BLangConstantValue result;
private BLangDiagnosticLog dlog;
private Location currentPos;
p... |
These shouldn't be equal in any case, though ;) | public void createFromActiveSession() {
PrepareResult result = deployApp(testApp);
long sessionId = applicationRepository.createSessionFromExisting(applicationId(),
new SilentDeployLogger(),
false,
timeoutBudget);
long originalSessionId = result.sessionId();
ApplicationMetaData originalApplicationMetaData = getApplicat... | assertNotEquals(applicationMetaData.getGeneration(), originalApplicationMetaData.getApplicationName()); | public void createFromActiveSession() {
PrepareResult result = deployApp(testApp);
long sessionId = applicationRepository.createSessionFromExisting(applicationId(),
new SilentDeployLogger(),
false,
timeoutBudget);
long originalSessionId = result.sessionId();
ApplicationMetaData originalApplicationMetaData = getApplicat... | class ApplicationRepositoryTest {
private final static File testApp = new File("src/test/apps/app");
private final static File testAppJdiscOnly = new File("src/test/apps/app-jdisc-only");
private final static File testAppJdiscOnlyRestart = new File("src/test/apps/app-jdisc-only-restart");
private final static File test... | class ApplicationRepositoryTest {
private final static File testApp = new File("src/test/apps/app");
private final static File testAppJdiscOnly = new File("src/test/apps/app-jdisc-only");
private final static File testAppJdiscOnlyRestart = new File("src/test/apps/app-jdisc-only-restart");
private final static File test... |
this method is no longer used | void testExceptionHistoryWithTaskFailure() throws Exception {
final Exception expectedException = new Exception("Expected Local Exception");
BiConsumer<AdaptiveScheduler, List<ExecutionAttemptID>> testLogic =
(scheduler, attemptIds) -> {
final ExecutionAttemptID attemptId = attemptIds.get(1);
scheduler.updateTaskExecut... | }; | void testExceptionHistoryWithTaskFailure() throws Exception {
final Exception expectedException = new Exception("Expected Local Exception");
BiConsumer<AdaptiveScheduler, List<ExecutionAttemptID>> testLogic =
(scheduler, attemptIds) -> {
final ExecutionAttemptID attemptId = attemptIds.get(1);
scheduler.updateTaskExecut... | class AdaptiveSchedulerTest {
private static final Duration DEFAULT_TIMEOUT = Duration.ofHours(1);
private static final int PARALLELISM = 4;
private static final JobVertex JOB_VERTEX = createNoOpVertex("v1", PARALLELISM);
private static final Logger LOG = LoggerFactory.getLogger(AdaptiveSchedulerTest.class);
@RegisterE... | class AdaptiveSchedulerTest {
private static final Duration DEFAULT_TIMEOUT = Duration.ofHours(1);
private static final int PARALLELISM = 4;
private static final JobVertex JOB_VERTEX = createNoOpVertex("v1", PARALLELISM);
private static final Logger LOG = LoggerFactory.getLogger(AdaptiveSchedulerTest.class);
@RegisterE... |
Lets handle float and decimal diffrently and other types use same isEqual which will minimise code duplication. | public static boolean isReferenceEqual(Object lhsValue, Object rhsValue) {
if (lhsValue == rhsValue) {
return true;
}
if (lhsValue == null || rhsValue == null) {
return false;
}
Type lhsType = getType(lhsValue);
Type rhsType = getType(rhsValue);
switch(lhsType.getTag()) {
case TypeTags.INT_TAG:
if (rhsType.getTag() != ... | if (rhsType.getTag() != TypeTags.BYTE_TAG || rhsType.getTag() != TypeTags.INT_TAG) { | public static boolean isReferenceEqual(Object lhsValue, Object rhsValue) {
if (lhsValue == rhsValue) {
return true;
}
if (lhsValue == null || rhsValue == null) {
return false;
}
Type lhsType = getType(lhsValue);
Type rhsType = getType(rhsValue);
switch (lhsType.getTag()) {
case TypeTags.FLOAT_TAG:
if (rhsType.getTag() ... | class TypeChecker {
public static Object checkCast(Object sourceVal, Type targetType) {
if (checkIsType(sourceVal, targetType)) {
return sourceVal;
}
Type sourceType = getType(sourceVal);
if (sourceType.getTag() <= TypeTags.BOOLEAN_TAG && targetType.getTag() <= TypeTags.BOOLEAN_TAG) {
return TypeConverter.castValues(ta... | class TypeChecker {
public static Object checkCast(Object sourceVal, Type targetType) {
if (checkIsType(sourceVal, targetType)) {
return sourceVal;
}
Type sourceType = getType(sourceVal);
if (sourceType.getTag() <= TypeTags.BOOLEAN_TAG && targetType.getTag() <= TypeTags.BOOLEAN_TAG) {
return TypeConverter.castValues(ta... |
Because we can definitively say that a if-else statement causes a function to return only when there are return statements inside all if, if else and else blocks. If at least one such block does not contain the return statement, the whole if-else statement is marked as a statement which will not cause a function to ret... | public void visit(IfElseStmt ifElseStmt) {
boolean stmtReturns = true;
Expression expr = ifElseStmt.getCondition();
visitSingleValueExpr(expr);
if (expr.getType() != BTypes.typeBoolean) {
BLangExceptionHelper
.throwSemanticError(ifElseStmt, SemanticErrors.INCOMPATIBLE_TYPES_BOOLEAN_EXPECTED, expr.getType());
}
Statemen... | stmtReturns = false; | public void visit(IfElseStmt ifElseStmt) {
boolean stmtReturns = true;
Expression expr = ifElseStmt.getCondition();
visitSingleValueExpr(expr);
if (expr.getType() != BTypes.typeBoolean) {
BLangExceptionHelper
.throwSemanticError(ifElseStmt, SemanticErrors.INCOMPATIBLE_TYPES_BOOLEAN_EXPECTED, expr.getType());
}
Statemen... | class SemanticAnalyzer implements NodeVisitor {
private int stackFrameOffset = -1;
private int staticMemAddrOffset = -1;
private int connectorMemAddrOffset = -1;
private int structMemAddrOffset = -1;
private int workerMemAddrOffset = -1;
private String currentPkg;
private TypeLattice packageTypeLattice;
private Callabl... | class SemanticAnalyzer implements NodeVisitor {
private int stackFrameOffset = -1;
private int staticMemAddrOffset = -1;
private int connectorMemAddrOffset = -1;
private int structMemAddrOffset = -1;
private int workerMemAddrOffset = -1;
private String currentPkg;
private TypeLattice packageTypeLattice;
private Callabl... |
Periodic tasks are added to the Task framework later. | public List<Task> showTask() {
List<Task> taskList = Lists.newArrayList();
taskList.addAll(manualTaskMap.values());
return taskList;
} | taskList.addAll(manualTaskMap.values()); | public List<Task> showTask() {
List<Task> taskList = Lists.newArrayList();
taskList.addAll(manualTaskMap.values());
return taskList;
} | class TaskManager {
private static final Logger LOG = LogManager.getLogger(TaskManager.class);
public static final long TASK_EXISTS = -1L;
public static final long DUPLICATE_CREATE_TASK = -2L;
public static final long TASK_CREATE_TIMEOUT = -3L;
private final Map<Long, Task> manualTaskMap;
private final Map<String, Task... | class TaskManager {
private static final Logger LOG = LogManager.getLogger(TaskManager.class);
public static final long TASK_EXISTS = -1L;
public static final long DUPLICATE_CREATE_TASK = -2L;
public static final long GET_TASK_LOCK_FAILED = -3L;
private final Map<Long, Task> manualTaskMap;
private final Map<String, Tas... |
Removes the use of a Supplier function to store the TableSchema and simply uses a class property to hold the TableSchema. | public T read(T reuse, Decoder in) throws IOException {
GenericRecord record = (GenericRecord) this.reader.read(reuse, in);
return parseFn.apply(new SchemaAndRecord(record, this.tableSchema));
} | return parseFn.apply(new SchemaAndRecord(record, this.tableSchema)); | public T read(T reuse, Decoder in) throws IOException {
GenericRecord record = (GenericRecord) this.reader.read(reuse, in);
return parseFn.apply(new SchemaAndRecord(record, this.tableSchema));
} | class GenericDatumTransformer<T> implements DatumReader<T> {
private final SerializableFunction<SchemaAndRecord, T> parseFn;
private final TableSchema tableSchema;
private GenericDatumReader<T> reader;
private org.apache.avro.Schema writerSchema;
public GenericDatumTransformer(
SerializableFunction<SchemaAndRecord, T> ... | class GenericDatumTransformer<T> implements DatumReader<T> {
private final SerializableFunction<SchemaAndRecord, T> parseFn;
private final TableSchema tableSchema;
private GenericDatumReader<T> reader;
private org.apache.avro.Schema writerSchema;
public GenericDatumTransformer(
SerializableFunction<SchemaAndRecord, T> ... |
~~That said, we could make it configurable...~~ Actually, it would make more sense to allow the test to modify the `SmallRyeConfigBuilder`. This would be a more advanced feature compared to the `QuarkusComponentTest#configConverters()`. And it could be only used from the `QuarkusComponentTestExtensionBuilder`. | private void startContainer(ExtensionContext context, Lifecycle testInstanceLifecycle) throws Exception {
if (testInstanceLifecycle.equals(context.getTestInstanceLifecycle().orElse(Lifecycle.PER_METHOD))) {
Arc.initialize();
QuarkusComponentTestConfiguration configuration = context.getRoot().getStore(NAMESPACE)
.get(KE... | .addDefaultInterceptors() | private void startContainer(ExtensionContext context, Lifecycle testInstanceLifecycle) throws Exception {
if (testInstanceLifecycle.equals(context.getTestInstanceLifecycle().orElse(Lifecycle.PER_METHOD))) {
Arc.initialize();
QuarkusComponentTestConfiguration configuration = store(context).get(KEY_TEST_CLASS_CONFIG,
Qua... | class QuarkusComponentTestExtension
implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback, TestInstancePostProcessor,
ParameterResolver {
public static QuarkusComponentTestExtensionBuilder builder() {
return new QuarkusComponentTestExtensionBuilder();
}
private static final Logger LOG = ... | class QuarkusComponentTestExtension
implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback, TestInstancePostProcessor,
ParameterResolver {
public static QuarkusComponentTestExtensionBuilder builder() {
return new QuarkusComponentTestExtensionBuilder();
}
private static final Logger LOG = ... |
Thanks for pointing this out, after rethinking the semantics of `read()`, I think changing the [NoFetchingInput#readBytes()](https://github.com/apache/flink/blob/9d2ae5572897f3e2d9089414261a250cfc2a2ab8/flink-core/src/main/java/org/apache/flink/api/java/typeutils/runtime/NoFetchingInput.java#L115-L140) is a better way ... | public int read(byte[] b, int off, int len) throws IOException {
final int bytesLeft = data.length - index;
if (bytesLeft > 0) {
final int bytesToCopy = Math.min(len, bytesLeft);
System.arraycopy(data, index, b, off, bytesToCopy);
index += bytesToCopy;
return bytesToCopy;
} else {
return len == 0 ? 0 : -1;
}
} | return len == 0 ? 0 : -1; | public int read(byte[] b, int off, int len) throws IOException {
final int bytesLeft = data.length - index;
if (bytesLeft > 0) {
final int bytesToCopy = Math.min(len, bytesLeft);
System.arraycopy(data, index, b, off, bytesToCopy);
index += bytesToCopy;
return bytesToCopy;
} else {
return len == 0 ? 0 : -1;
}
} | class ByteStateHandleInputStream extends FSDataInputStream {
private final byte[] data;
private int index;
public ByteStateHandleInputStream(byte[] data) {
this.data = data;
}
@Override
public void seek(long desired) throws IOException {
if (desired >= 0 && desired <= data.length) {
index = (int) desired;
} else {
thro... | class ByteStateHandleInputStream extends FSDataInputStream {
private final byte[] data;
private int index;
public ByteStateHandleInputStream(byte[] data) {
this.data = data;
}
@Override
public void seek(long desired) throws IOException {
if (desired >= 0 && desired <= data.length) {
index = (int) desired;
} else {
thro... |
These changes are not covered. Consider adding a test in `PrintConnectorITCase` so that the result shows this `printIdentifier`. | public SinkRuntimeProvider getSinkRuntimeProvider(DynamicTableSink.Context context) {
DataStructureConverter converter = context.createDataStructureConverter(type);
staticPartitions.forEach(
(key, value) -> {
printIdentifier = null != printIdentifier ? printIdentifier + ":" : "";
printIdentifier += key + "=" + value;
}... | }); | public SinkRuntimeProvider getSinkRuntimeProvider(DynamicTableSink.Context context) {
DataStructureConverter converter = context.createDataStructureConverter(type);
staticPartitions.forEach(
(key, value) -> {
printIdentifier = null != printIdentifier ? printIdentifier + ":" : "";
printIdentifier += key + "=" + value;
}... | class PrintSink implements DynamicTableSink, SupportsPartitioning {
private final DataType type;
private String printIdentifier;
private final boolean stdErr;
private final @Nullable Integer parallelism;
private final List<String> partitionKeys;
private Map<String, String> staticPartitions = new LinkedHashMap<>();
priv... | class PrintSink implements DynamicTableSink, SupportsPartitioning {
private final DataType type;
private String printIdentifier;
private final boolean stdErr;
private final @Nullable Integer parallelism;
private final List<String> partitionKeys;
private Map<String, String> staticPartitions = new LinkedHashMap<>();
priv... |
Can we consider adding integration test to cover this line? Or we can add a test in the `remote.management` module. | public Object getDetail(String detailKey) {
return details.getOrDefault(detailKey, null);
} | return details.getOrDefault(detailKey, null); | public Object getDetail(String detailKey) {
return details.getOrDefault(detailKey, null);
} | class ArtifactImpl extends Artifact {
private final Map<String, Object> details;
public ArtifactImpl(String name, ArtifactType type) {
super(name, type);
this.details = new HashMap<>();
}
private void addDetail(String detailsKey, Object value) {
this.details.put(detailsKey, value);
}
@Override
} | class ArtifactImpl extends Artifact {
private final Map<String, Object> details;
public ArtifactImpl(String name, ArtifactType type) {
super(name, type);
this.details = new HashMap<>();
}
private void addDetail(String detailsKey, Object value) {
this.details.put(detailsKey, value);
}
@Override
@Override
public Map<Stri... |
@mosche, what about switching from `AtomicInteger` to `Integer` as @adude3141 suggested ? Indeed, this counter is always accessed in a synchronised block, there is no need to add extract sync mechanism. And by the way it will also allow to remove the `SuppressWarning` | private void setupSharedProducer() {
synchronized (producerRefCount) {
if (producer == null) {
producer =
spec.getAWSClientsProvider().createKinesisProducer(spec.producerConfiguration());
producerRefCount.set(0);
}
}
producerRefCount.incrementAndGet();
} | } | private void setupSharedProducer() {
synchronized (KinesisWriterFn.class) {
if (producer == null) {
producer =
spec.getAWSClientsProvider()
.createKinesisProducer(spec.createProducerConfiguration());
producerRefCount = 0;
}
producerRefCount++;
}
} | class KinesisWriterFn extends DoFn<byte[], Void> {
private static final int MAX_NUM_FAILURES = 10;
/** Usage count of static, shared Kinesis producer. */
private static final AtomicInteger producerRefCount = new AtomicInteger();
/** Static, shared Kinesis producer. */
private static IKinesisProducer producer;
private f... | class KinesisWriterFn extends DoFn<byte[], Void> {
private static final int MAX_NUM_FAILURES = 10;
/** Usage count of static, shared Kinesis producer. */
private static int producerRefCount = 0;
/** Static, shared Kinesis producer. */
private static IKinesisProducer producer;
private final KinesisIO.Write spec;
private... |
This code appears to be substituting calls to `getQualifiedUser()` with calls to `getUser()`. The review of such a change depends upon the exact implementation of these two methods, which is not included in the snippet provided. Broadly, this might imply a significant shift from using "qualified" (potentially containin... | private boolean hasUserNameNoLock(String userName) {
for (UserIdentity userIdentity : userToAuthenticationInfo.keySet()) {
if (userIdentity.getUser().equals(userName)) {
return true;
}
}
return false;
} | } | private boolean hasUserNameNoLock(String userName) {
for (UserIdentity userIdentity : userToAuthenticationInfo.keySet()) {
if (userIdentity.getUser().equals(userName)) {
return true;
}
}
return false;
} | class UserAuthInfoTreeMap extends TreeMap<UserIdentity, UserAuthenticationInfo> {
public UserAuthInfoTreeMap() {
super((o1, o2) -> {
int compareHostScore = scoreUserIdentityHost(o1).compareTo(scoreUserIdentityHost(o2));
if (compareHostScore != 0) {
return compareHostScore;
}
int compareByHost = o1.getHost().compareTo(o... | class UserAuthInfoTreeMap extends TreeMap<UserIdentity, UserAuthenticationInfo> {
public UserAuthInfoTreeMap() {
super((o1, o2) -> {
int compareHostScore = scoreUserIdentityHost(o1).compareTo(scoreUserIdentityHost(o2));
if (compareHostScore != 0) {
return compareHostScore;
}
int compareByHost = o1.getHost().compareTo(o... |
also worth adding the low bound comparison , like` duration.getSeconds > timeout based on the httpTimeoutPolicy`. By just comparing the high bound, it will not catch the issue | private void validateDataPlaneRetryPolicyResponseTimeouts(CosmosDiagnostics cosmosDiagnostics) {
List<ClientSideRequestStatistics.GatewayStatistics> gatewayStatisticsList = diagnosticsAccessor.getClientSideRequestStatistics(cosmosDiagnostics)
.stream()
.map(ClientSideRequestStatistics::getGatewayStatisticsList)
.flatMa... | assertThat(durationInMillis.getSeconds()).isLessThanOrEqualTo(62); | private void validateDataPlaneRetryPolicyResponseTimeouts(CosmosDiagnostics cosmosDiagnostics) {
List<ClientSideRequestStatistics.GatewayStatistics> gatewayStatisticsList = diagnosticsAccessor.getClientSideRequestStatistics(cosmosDiagnostics)
.stream()
.map(ClientSideRequestStatistics::getGatewayStatisticsList)
.flatMa... | class WebExceptionRetryPolicyE2ETests extends TestSuiteBase {
private final static
ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagnosticsAccessor =
ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor();
private CosmosAsyncClient cosmosAsyncClient;
private ... | class WebExceptionRetryPolicyE2ETests extends TestSuiteBase {
private final static Logger logger = LoggerFactory.getLogger(WebExceptionRetryPolicyE2ETests.class);
private final static
ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagnosticsAccessor =
ImplementationBridgeHelpers.CosmosDi... |
Couldn't you inject the Agroal datasource directly? I see Flyway has a method for this: https://github.com/flyway/flyway/blob/master/flyway-core/src/main/java/org/flywaydb/core/api/configuration/FluentConfiguration.java#L735 . | public Flyway produceFlyway() {
FluentConfiguration configure = Flyway.configure();
String url = agroalRuntimeConfig.defaultDataSource.url
.orElseThrow(() -> new IllegalStateException(
"No default datasource configured. Please specify the quarkus.datasource.* properties"));
String username = agroalRuntimeConfig.default... | flywayRuntimeConfig.repeatableSqlMigrationPrefix.ifPresent(configure::repeatableSqlMigrationPrefix); | public Flyway produceFlyway() {
FluentConfiguration configure = Flyway.configure();
configure.dataSource(dataSource);
flywayRuntimeConfig.connectRetries.ifPresent(configure::connectRetries);
List<String> notEmptySchemas = filterBlanks(flywayRuntimeConfig.schemas);
if (!notEmptySchemas.isEmpty()) {
configure.schemas(not... | class FlywayProducer {
private AgroalRuntimeConfig agroalRuntimeConfig;
private FlywayRuntimeConfig flywayRuntimeConfig;
private FlywayBuildConfig flywayBuildConfig;
@Produces
@Dependent
public void setAgroalRuntimeConfig(AgroalRuntimeConfig agroalRuntimeConfig) {
this.agroalRuntimeConfig = agroalRuntimeConfig;
}
publi... | class FlywayProducer {
@Inject
AgroalDataSource dataSource;
private FlywayRuntimeConfig flywayRuntimeConfig;
private FlywayBuildConfig flywayBuildConfig;
@Produces
@Dependent
private List<String> filterBlanks(List<String> values) {
return values.stream().filter(it -> it != null && !"".equals(it))
.collect(Collectors.to... |
configRegistry will never be null, right? | public Tracer getTracer(String tracerName, String serviceName) {
if (Objects.isNull(configRegistry)) {
throw new IllegalStateException("Tracer not initialized with configurations");
}
return new Configuration(
serviceName,
new Configuration.SamplerConfiguration(samplerType, samplerParam),
new Configuration.ReporterConf... | if (Objects.isNull(configRegistry)) { | public Tracer getTracer(String tracerName, String serviceName) {
if (Objects.isNull(configRegistry)) {
throw new IllegalStateException("Tracer not initialized with configurations");
}
return new Configuration(
serviceName,
new Configuration.SamplerConfiguration(samplerType, samplerParam),
new Configuration.ReporterConf... | class OpenTracingExtension implements OpenTracer {
private ConfigRegistry configRegistry;
private String hostname;
private int port;
private String samplerType;
private Number samplerParam;
private int reporterFlushInterval;
private int reporterBufferSize;
private static final PrintStream console = System.out;
private ... | class OpenTracingExtension implements OpenTracer {
private ConfigRegistry configRegistry;
private String hostname;
private int port;
private String samplerType;
private Number samplerParam;
private int reporterFlushInterval;
private int reporterBufferSize;
private static final PrintStream console = System.out;
private ... |
Is this format consistent for all cases? | static String cleanupObjectTypeName(String callName, BType objectType) {
if (!objectType.tsymbol.name.value.isEmpty() && callName.startsWith(objectType.tsymbol.name.value)) {
callName = callName.replace(objectType.tsymbol.name.value + ".", "").trim();
}
if (callName.startsWith("(") && callName.contains(").")) {
callNam... | static String cleanupObjectTypeName(String callName, BType objectType) {
if (!objectType.tsymbol.name.value.isEmpty() && callName.startsWith(objectType.tsymbol.name.value)) {
callName = callName.replace(objectType.tsymbol.name.value + ".", "").trim();
}
if (callName.startsWith("(") && callName.contains(").")) {
callNam... | class JvmCodeGenUtil {
public static final Unifier UNIFIER = new Unifier();
private static final Pattern JVM_RESERVED_CHAR_SET = Pattern.compile("[\\.:/<>]");
public static final String SCOPE_PREFIX = "_SCOPE_";
public static final NameHashComparator NAME_HASH_COMPARATOR = new NameHashComparator();
static void visitInv... | class JvmCodeGenUtil {
public static final Unifier UNIFIER = new Unifier();
private static final Pattern JVM_RESERVED_CHAR_SET = Pattern.compile("[\\.:/<>]");
public static final String SCOPE_PREFIX = "_SCOPE_";
public static final NameHashComparator NAME_HASH_COMPARATOR = new NameHashComparator();
static void visitInv... | |
what is it for ? | public void replace(Map<Slot, Slot> replaceMap) {
slots = slots.stream()
.map(s -> replaceMap.getOrDefault(s, s))
.collect(Collectors.toSet());
slotSets = slotSets.stream()
.map(set -> set.stream().map(s -> replaceMap.getOrDefault(s, s))
.collect(ImmutableSet.toImmutableSet()))
.collect(Collectors.toSet());
} | .map(set -> set.stream().map(s -> replaceMap.getOrDefault(s, s)) | public void replace(Map<Slot, Slot> replaceMap) {
uniformSet.replace(replaceMap);
uniqueSet.replace(replaceMap);
} | class Builder {
private final NestedSet uniqueSet;
private final NestedSet uniformSet;
public Builder() {
uniqueSet = new NestedSet();
uniformSet = new NestedSet();
}
public Builder(FunctionalDependencies other) {
this.uniformSet = new NestedSet(other.uniformSet);
this.uniqueSet = new NestedSet(other.uniqueSet);
}
publ... | class Builder {
private final NestedSet uniqueSet;
private final NestedSet uniformSet;
public Builder() {
uniqueSet = new NestedSet();
uniformSet = new NestedSet();
}
public Builder(FunctionalDependencies other) {
this.uniformSet = new NestedSet(other.uniformSet);
this.uniqueSet = new NestedSet(other.uniqueSet);
}
publ... |
``` List<Library> deps = platform.libraries.stream().filter(library -> library.getModules() == null || Arrays.asList(library.getModules()).contains(moduleName)).toList(); ``` | public String getTargetPlatform(String moduleName) {
if (isTemplateModule(moduleName)) {
return ProgramFileConstants.ANY_PLATFORM;
}
if (null != platform.libraries) {
if (null == platform.target) {
throw new BLangCompilerException("Platform target is not specified in the Ballerina.toml");
}
if (!(Arrays.stream(ProgramF... | ).collect(Collectors.toList()); | public String getTargetPlatform(String moduleName) {
if (isTemplateModule(moduleName)) {
return ProgramFileConstants.ANY_PLATFORM;
}
if (null != platform.libraries) {
if (null == platform.target) {
throw new BLangCompilerException("Platform target is not specified in the Ballerina.toml");
}
if (!(Arrays.stream(ProgramF... | class Manifest {
private Project project = new Project();
private Map<String, Object> dependencies = new LinkedHashMap<>();
public Platform platform = new Platform();
private BuildOptions buildOptions;
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
pu... | class Manifest {
private Project project = new Project();
private Map<String, Object> dependencies = new LinkedHashMap<>();
public Platform platform = new Platform();
private BuildOptions buildOptions;
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
pu... |
@cescoffier maybe we could merge and adjust later if needed? I'm a bit worried that we could have annoying conflicts, considering it touches a lot of places. | public void testHealth() {
try {
RestAssured.defaultParser = Parser.JSON;
RestAssured.when().get("/health").then()
.body("outcome", is("UP"),
"checks.state", contains("UP"),
"checks.name", contains("basic"));
} finally {
RestAssured.reset();
}
} | RestAssured.defaultParser = Parser.JSON; | public void testHealth() {
try {
RestAssured.defaultParser = Parser.JSON;
RestAssured.when().get("/health").then()
.body("outcome", is("UP"),
"checks.state", contains("UP"),
"checks.name", contains("basic"));
} finally {
RestAssured.reset();
}
} | class HealthUnitTest {
@Deployment
public static JavaArchive deploy() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(BasicHealthCheck.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Test
} | class HealthUnitTest {
@Deployment
public static JavaArchive deploy() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(BasicHealthCheck.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Test
} |
Does this need to include the try count as that is inferred by attempting more than the maximum limit | private boolean isValidRedirectCount(int tryCount) {
if (tryCount >= getMaxAttempts()) {
LOGGER.atError()
.addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount)
.addKeyValue("maxAttempts", getMaxAttempts())
.log("Redirect attempts have been exhausted.");
return false;
}
return true;
} | .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) | private boolean isValidRedirectCount(int tryCount) {
if (tryCount >= getMaxAttempts()) {
LOGGER.atError()
.addKeyValue("maxAttempts", getMaxAttempts())
.log("Redirect attempts have been exhausted.");
return false;
}
return true;
} | class DefaultRedirectStrategy implements RedirectStrategy {
private static final ClientLogger LOGGER = new ClientLogger(DefaultRedirectStrategy.class);
private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3;
private static final String DEFAULT_REDIRECT_LOCATION_HEADER_NAME = "Location";
private static final int PER... | class DefaultRedirectStrategy implements RedirectStrategy {
private static final ClientLogger LOGGER = new ClientLogger(DefaultRedirectStrategy.class);
private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3;
private static final String DEFAULT_REDIRECT_LOCATION_HEADER_NAME = "Location";
private static final int PER... |
I think we need to call `setProperties` in `gsonPostProcess` as well to make sure all properties are set after metadata replay. | private void setProperties(Map<String, String> properties) {
try {
nodes = properties.get(PROP_HOSTS).trim().split(",");
if (properties.containsKey(PROP_SSL)) {
enableSsl = EsUtil.getBoolean(properties, PROP_SSL);
}
if (StringUtils.isNotBlank(properties.get(PROP_USERNAME))) {
username = properties.get(PROP_USERNAME).tr... | try { | private void setProperties(Map<String, String> properties) {
try {
nodes = properties.get(PROP_HOSTS).trim().split(",");
if (properties.containsKey(PROP_SSL)) {
enableSsl = EsUtil.getBoolean(properties, PROP_SSL);
}
if (StringUtils.isNotBlank(properties.get(PROP_USERNAME))) {
username = properties.get(PROP_USERNAME).tr... | class EsExternalCatalog extends ExternalCatalog {
private static final Logger LOG = LogManager.getLogger(EsExternalCatalog.class);
public static final String DEFAULT_DB = "default_db";
public static final String PROP_HOSTS = "elasticsearch.hosts";
public static final String PROP_SSL = "elasticsearch.ssl";
public static... | class EsExternalCatalog extends ExternalCatalog {
private static final Logger LOG = LogManager.getLogger(EsExternalCatalog.class);
public static final String DEFAULT_DB = "default_db";
public static final String PROP_HOSTS = "elasticsearch.hosts";
public static final String PROP_SSL = "elasticsearch.ssl";
public static... |
In this case, we would like a matching extension (if found) to be added as a `forcedDependency`. For example in any quarkus project the following should always work: ```sh mvn quarkus:deploy -Dquarkus.deploy.target=knative mvn quarkus:deploy -Dquarkus.deploy.target=openshift ``` Besides the hard coding approach which... | protected void doExecute() throws MojoExecutionException {
try (CuratedApplication curatedApplication = bootstrapApplication()) {
AtomicReference<List<String>> tooMany = new AtomicReference<>();
AugmentAction action = curatedApplication.createAugmentor();
action.performCustomBuild(DeployCommandDeclarationHandler.class.... | getLog().error( | protected void doExecute() throws MojoExecutionException {
try (CuratedApplication curatedApplication = bootstrapApplication()) {
AtomicReference<List<String>> tooMany = new AtomicReference<>();
AugmentAction action = curatedApplication.createAugmentor();
action.performCustomBuild(DeployCommandDeclarationHandler.class.... | class DeployMojo extends AbstractDeploymentMojo {
@Override
protected boolean beforeExecute() throws MojoExecutionException {
return super.beforeExecute();
}
@Override
} | class DeployMojo extends AbstractDeploymentMojo {
@Override
protected boolean beforeExecute() throws MojoExecutionException {
return super.beforeExecute();
}
@Override
} |
i'll have a look at what the flink runner does as well. | public void translate(GroupByKey<K, V> transform, Context cxt) {
WindowingStrategy<?, ?> windowing = cxt.getInput().getWindowingStrategy();
TimestampCombiner tsCombiner = windowing.getTimestampCombiner();
Dataset<WindowedValue<KV<K, V>>> input = cxt.getDataset(cxt.getInput());
KvCoder<K, V> inputCoder = (KvCoder<K, V>)... | public void translate(GroupByKey<K, V> transform, Context cxt) {
WindowingStrategy<?, ?> windowing = cxt.getInput().getWindowingStrategy();
TimestampCombiner tsCombiner = windowing.getTimestampCombiner();
Dataset<WindowedValue<KV<K, V>>> input = cxt.getDataset(cxt.getInput());
KvCoder<K, V> inputCoder = (KvCoder<K, V>)... | class GroupByKeyTranslatorBatch<K, V>
extends GroupingTranslator<K, V, Iterable<V>, GroupByKey<K, V>> {
/** Literal of binary encoded Pane info. */
private static final Expression PANE_NO_FIRING = lit(toByteArray(NO_FIRING, PaneInfoCoder.of()));
/** Defaults for value in single global window. */
private static final Li... | class GroupByKeyTranslatorBatch<K, V>
extends TransformTranslator<
PCollection<KV<K, V>>, PCollection<KV<K, Iterable<V>>>, GroupByKey<K, V>> {
/** Literal of binary encoded Pane info. */
private static final Expression PANE_NO_FIRING = lit(toByteArray(NO_FIRING, PaneInfoCoder.of()));
/** Defaults for value in single gl... | |
I think mapping ctor expression is more suitable as we don't know the error type completely yet | public void visit(BLangErrorConstructorExpr errorConstructorExpr) {
BLangUserDefinedType userProvidedTypeRef = errorConstructorExpr.errorTypeRef;
if (userProvidedTypeRef != null) {
symResolver.resolveTypeNode(userProvidedTypeRef, env, DiagnosticErrorCode.UNDEFINED_ERROR_TYPE_DESCRIPTOR);
}
validateErrorConstructorPosit... | dlog.error(errorConstructorExpr.pos, DiagnosticErrorCode.INCOMPATIBLE_TYPES, symTable.errorType, expType); | public void visit(BLangErrorConstructorExpr errorConstructorExpr) {
BLangUserDefinedType userProvidedTypeRef = errorConstructorExpr.errorTypeRef;
if (userProvidedTypeRef != null) {
symResolver.resolveTypeNode(userProvidedTypeRef, env, DiagnosticErrorCode.UNDEFINED_ERROR_TYPE_DESCRIPTOR);
}
validateErrorConstructorPosit... | class TypeChecker extends BLangNodeVisitor {
private static final CompilerContext.Key<TypeChecker> TYPE_CHECKER_KEY = new CompilerContext.Key<>();
private static Set<String> listLengthModifierFunctions = new HashSet<>();
private static Map<String, HashSet<String>> modifierFunctions = new HashMap<>();
private static fin... | class TypeChecker extends BLangNodeVisitor {
private static final CompilerContext.Key<TypeChecker> TYPE_CHECKER_KEY = new CompilerContext.Key<>();
private static Set<String> listLengthModifierFunctions = new HashSet<>();
private static Map<String, HashSet<String>> modifierFunctions = new HashMap<>();
private static fin... |
https://stackoverflow.com/questions/35792590/how-to-check-number-of-digits-from-bigdecimal There is a trick to this as well.. ```Java xInBigDecimal = xInBigDecimal.stripTrailingZeros(); int y = xInBigDecimal.precision() - xInBigDecimal.scale() if (y > digitsTmp) { return 0; } ``` | public static double round(double x, long fractionDigits) {
if (isSpecialValue(x)) {
return x;
}
if (fractionDigits == 0) {
return Math.rint(x);
}
if (fractionDigits > Integer.MAX_VALUE) {
return x;
}
if (fractionDigits < Integer.MIN_VALUE) {
return 0;
}
int fractionDigitsAsInt = (int) fractionDigits;
BigDecimal xInBig... | while (digitsTmp++ < 0) { | public static double round(double x, long fractionDigits) {
if (Double.isInfinite(x) || Double.isNaN(x) || x == 0.0d) {
return x;
}
if (fractionDigits == 0) {
return Math.rint(x);
}
if (fractionDigits > Integer.MAX_VALUE) {
return x;
}
if (fractionDigits < Integer.MIN_VALUE) {
return 0;
}
int fractionDigitsAsInt = (int... | class Round {
private static boolean isSpecialValue(double x) {
return Double.isInfinite(x) || Double.isNaN(x) || x == 0.0d;
}
} | class Round {
} |
We should move the cases into the `types`. In line 225, we will create test cases with or without nullbility. | private static List<LogicalType> generateTestData() {
List<LogicalType> types =
Arrays.asList(
new BooleanType(),
new TinyIntType(),
new SmallIntType(),
new IntType(),
new BigIntType(),
new FloatType(),
new DoubleType(),
new DateType(),
CharType.ofEmptyLiteral(),
new CharType(),
new CharType(5),
VarCharType.ofEmptyLite... | testTypes.add(new YearMonthIntervalType(YearMonthIntervalType.YearMonthResolution.MONTH)); | private static List<LogicalType> generateTestData() {
List<LogicalType> types =
Arrays.asList(
new BooleanType(),
new TinyIntType(),
new SmallIntType(),
new IntType(),
new BigIntType(),
new FloatType(),
new DoubleType(),
new DateType(),
CharType.ofEmptyLiteral(),
new CharType(),
new CharType(5),
VarCharType.ofEmptyLite... | class LogicalTypeJsonSerDeTest {
private final ObjectMapper mapper = buildObjectMapper();
@ParameterizedTest
@MethodSource("generateTestData")
void testLogicalTypeJsonSerDe(LogicalType logicalType) throws IOException {
String json = mapper.writeValueAsString(logicalType);
LogicalType actualType = mapper.readValue(json,... | class LogicalTypeJsonSerDeTest {
private final ObjectMapper mapper = buildObjectMapper();
@ParameterizedTest
@MethodSource("generateTestData")
void testLogicalTypeJsonSerDe(LogicalType logicalType) throws IOException {
String json = mapper.writeValueAsString(logicalType);
LogicalType actualType = mapper.readValue(json,... |
```suggestion throw new RpcLoaderException( ``` | public RpcSystem loadRpcSystem(Configuration config) {
try {
LOG.debug(
"Using Fallback AkkaRpcSystemLoader; this loader will invoke maven to retrieve the dependencies of flink-rpc-akka.");
final ClassLoader flinkClassLoader = RpcSystem.class.getClassLoader();
final Path akkaRpcModuleDirectory =
findAkkaRpcModuleDirect... | throw new RuntimeException( | public RpcSystem loadRpcSystem(Configuration config) {
try {
LOG.debug(
"Using Fallback AkkaRpcSystemLoader; this loader will invoke maven to retrieve the dependencies of flink-rpc-akka.");
final ClassLoader flinkClassLoader = RpcSystem.class.getClassLoader();
final Path akkaRpcModuleDirectory =
findAkkaRpcModuleDirect... | class FallbackAkkaRpcSystemLoader implements RpcSystemLoader {
private static final Logger LOG = LoggerFactory.getLogger(FallbackAkkaRpcSystemLoader.class);
private static final String MODULE_FLINK_RPC = "flink-rpc";
private static final String MODULE_FLINK_RPC_AKKA = "flink-rpc-akka";
@Override
private static Path get... | class FallbackAkkaRpcSystemLoader implements RpcSystemLoader {
private static final Logger LOG = LoggerFactory.getLogger(FallbackAkkaRpcSystemLoader.class);
private static final String MODULE_FLINK_RPC = "flink-rpc";
private static final String MODULE_FLINK_RPC_AKKA = "flink-rpc-akka";
@Override
private static Path get... |
Is this possible? Don't above checks preclude this condition? | 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... |
should include WindowExpression inner trival-agg | public Rule build() {
return logicalAggregate().whenNot(LogicalAggregate::isNormalized).then(aggregate -> {
Set<Expression> groupingByExprs =
ImmutableSet.copyOf(aggregate.getGroupByExpressions());
List<NamedExpression> aggregateOutput = aggregate.getOutputExpressions();
List<AggregateFunction> aggFuncs = Lists.newArra... | public Rule build() {
return logicalAggregate().whenNot(LogicalAggregate::isNormalized).then(aggregate -> {
Set<Expression> groupingByExprs =
ImmutableSet.copyOf(aggregate.getGroupByExpressions());
List<NamedExpression> aggregateOutput = aggregate.getOutputExpressions();
List<AggregateFunction> aggFuncs = Lists.newArra... | class NormalizeAggregate extends OneRewriteRuleFactory implements NormalizeToSlot {
@Override
private List<NamedExpression> normalizeOutput(List<NamedExpression> aggregateOutput,
NormalizeToSlotContext groupByToSlotContext, NormalizeToSlotContext normalizedAggFuncsToSlotContext) {
List<NamedExpression> upperProjects = ... | class NormalizeAggregate extends OneRewriteRuleFactory implements NormalizeToSlot {
@Override
private List<NamedExpression> normalizeOutput(List<NamedExpression> aggregateOutput,
NormalizeToSlotContext groupByToSlotContext, NormalizeToSlotContext normalizedAggFuncsToSlotContext) {
List<NamedExpression> upperProjects = ... | |
Same as above. Async client should be built with autocomplete enabled for the processor. We may have to find a different way to disable it on the `receive()` method on the sync client. | public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout());
} | return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout()); | public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout());
} | class ServiceBusSessionReceiverClientBuilder {
private boolean enableAutoComplete = true;
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK;
private String sessionId;
private String subscrip... | class ServiceBusSessionReceiverClientBuilder {
private boolean enableAutoComplete = true;
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK;
private String sessionId;
private String subscrip... |
**1. For a partitioned table:** `create table testsparkstats (id int, name string) partitioned by(dt string) tored as orc;` **2. insert two partition dt=2024 and dt=2025** `insert into testsparkstats values(1243,'ttetw','2024'),(8945,'erw','2024'),(456,'df','2025'),(568,'tom','2025');` **3. analyze column statistic... | public HivePartitionStats getTableStatistics(String dbName, String tblName) {
org.apache.hadoop.hive.metastore.api.Table table = client.getTable(dbName, tblName);
HiveCommonStats commonStats = toHiveCommonStats(table.getParameters());
long totalRowNums = commonStats.getRowNums();
if (totalRowNums == -1) {
return HivePa... | if (statisticsObjs.isEmpty()) { | public HivePartitionStats getTableStatistics(String dbName, String tblName) {
org.apache.hadoop.hive.metastore.api.Table table = client.getTable(dbName, tblName);
HiveCommonStats commonStats = toHiveCommonStats(table.getParameters());
long totalRowNums = commonStats.getRowNums();
if (totalRowNums == -1) {
return HivePa... | class HiveMetastore implements IHiveMetastore {
private static final Logger LOG = LogManager.getLogger(CachingHiveMetastore.class);
private final HiveMetaClient client;
private final String catalogName;
private final MetastoreType metastoreType;
public HiveMetastore(HiveMetaClient client, String catalogName, MetastoreT... | class HiveMetastore implements IHiveMetastore {
private static final Logger LOG = LogManager.getLogger(CachingHiveMetastore.class);
private final HiveMetaClient client;
private final String catalogName;
private final MetastoreType metastoreType;
public HiveMetastore(HiveMetaClient client, String catalogName, MetastoreT... |
Shall we change this to report a diagnostic? | public void init(CompilerPluginContext pluginContext) {
pluginContext.addCodeAnalyzer(new CodeAnalyzer() {
@Override
public void init(CodeAnalysisContext codeAnalysisContext) {
System.out.println("Hello from the analyzer");
}
});
pluginContext.addCodeGenerator(new CodeGenerator() {
@Override
public void init(CodeGenera... | System.out.println("Hello from the generator"); | public void init(CompilerPluginContext pluginContext) {
pluginContext.addCodeAnalyzer(new CodeAnalyzer() {
@Override
public void init(CodeAnalysisContext codeAnalysisContext) {
appendToOutputFile(CodeType.ANALYZER);
}
});
pluginContext.addCodeGenerator(new CodeGenerator() {
@Override
public void init(CodeGeneratorConte... | class CombinedCompilerPlugin extends CompilerPlugin {
@Override
} | class CombinedCompilerPlugin extends CompilerPlugin {
String lockFilePath = "./src/test/resources/compiler_plugin_tests/" +
"package_comp_plugin_with_analyzer_generator_modifier/target/combined_plugin_output.lock";
@Override
private void appendToOutputFile(CodeType codeType) {
String filePath = "./src/test/resources/co... |
Can we wrap using ZstdOutputStream instead of first encoding the entire value to bytes? Ditto for decoding. | public void encode(T value, OutputStream os) throws IOException {
ZstdCompressCtx ctx = new ZstdCompressCtx();
try {
ctx.setLevel(level);
ctx.setMagicless(true);
ctx.setDictID(false);
ctx.loadDict(dict);
byte[] encoded = CoderUtils.encodeToByteArray(innerCoder, value);
ctx.setPledgedSrcSize(encoded.length);
byte[] comp... | byte[] encoded = CoderUtils.encodeToByteArray(innerCoder, value); | public void encode(T value, OutputStream os) throws IOException {
ZstdCompressCtx ctx = new ZstdCompressCtx();
try {
ctx.setLevel(level);
ctx.setMagicless(true);
ctx.setDictID(false);
ctx.loadDict(dict);
byte[] encoded = CoderUtils.encodeToByteArray(innerCoder, value);
byte[] compressed = ctx.compress(encoded);
ByteArr... | class ZstdCoder<T> extends StructuredCoder<T> {
private final Coder<T> innerCoder;
private final @Nullable byte[] dict;
private final int level;
/** Wraps the given coder into a {@link ZstdCoder}. */
public static <T> ZstdCoder<T> of(Coder<T> innerCoder, byte[] dict, int level) {
return new ZstdCoder<>(innerCoder, dict... | class ZstdCoder<T> extends Coder<T> {
private final Coder<T> innerCoder;
private final @Nullable byte[] dict;
private final int level;
/** Wraps the given coder into a {@link ZstdCoder}. */
public static <T> ZstdCoder<T> of(Coder<T> innerCoder, byte[] dict, int level) {
return new ZstdCoder<>(innerCoder, dict, level);
... |
The WARNING log may misunderstand the user. I think the behavior is normal when some tables are dropped before publishing. | public void updateReplicaVersions(List<TTabletVersionPair> tabletVersions) {
if (span != null) {
span.addEvent("update_replica_version_start");
span.setAttribute("num_replicas", tabletVersions.size());
}
TabletInvertedIndex tablets = GlobalStateMgr.getCurrentInvertedIndex();
List<Long> tabletIds = tabletVersions.stream... | if (!droppedTablets.isEmpty()) { | public void updateReplicaVersions(List<TTabletVersionPair> tabletVersions) {
if (span != null) {
span.addEvent("update_replica_version_start");
span.setAttribute("num_replicas", tabletVersions.size());
}
TabletInvertedIndex tablets = GlobalStateMgr.getCurrentInvertedIndex();
List<Long> tabletIds = tabletVersions.stream... | class PublishVersionTask extends AgentTask {
private static final Logger LOG = LogManager.getLogger(PublishVersionTask.class);
private long transactionId;
private List<TPartitionVersionInfo> partitionVersionInfos;
private List<Long> errorTablets;
private Set<Long> errorReplicas;
private long commitTimestamp;
private Tr... | class PublishVersionTask extends AgentTask {
private static final Logger LOG = LogManager.getLogger(PublishVersionTask.class);
private long transactionId;
private List<TPartitionVersionInfo> partitionVersionInfos;
private List<Long> errorTablets;
private Set<Long> errorReplicas;
private long commitTimestamp;
private Tr... |
Yes you are correct, will update. | private void checkFixedLength(long length) {
if (arrayType != null && arrayType.getTag() == TypeTags.TUPLE_TAG) {
BTupleType tupleType = (BTupleType) this.arrayType;
if (tupleType.getRestType() == null
|| (tupleType.getRestType() != null && tupleType.getTupleTypes().size() > length)) {
throw BLangExceptionHelper.getRun... | if (tupleType.getRestType() == null | private void checkFixedLength(long length) {
if (arrayType == null) {
return;
}
if (arrayType.getTag() == TypeTags.TUPLE_TAG) {
BTupleType tupleType = (BTupleType) this.arrayType;
if (tupleType.getRestType() == null) {
throw BLangExceptionHelper.getRuntimeException(BallerinaErrorReasons.INHERENT_TYPE_VIOLATION_ERROR,
R... | class ArrayValue implements RefValue, CollectionValue {
static final int SYSTEM_ARRAY_MAX = Integer.MAX_VALUE - 8;
protected BType arrayType;
private volatile Status freezeStatus = new Status(State.UNFROZEN);
/**
* The maximum size of arrays to allocate.
* <p>
* This is same as Java
*/
protected int maxArraySize = SYST... | class ArrayValue implements RefValue, CollectionValue {
static final int SYSTEM_ARRAY_MAX = Integer.MAX_VALUE - 8;
protected BType arrayType;
private volatile Status freezeStatus = new Status(State.UNFROZEN);
/**
* The maximum size of arrays to allocate.
* <p>
* This is same as Java
*/
protected int maxArraySize = SYST... |
If this throws InterruptedException then locked will be true but the lock will not have been acquired, and the finally block will attempt to unlock a lock it does not hold. | private Object writeLock(Lock lock, InvocationContext ctx) throws Exception {
boolean locked = true;
long time = lock.time();
try {
if (time > 0) {
locked = readWriteLock.writeLock().tryLock(time, lock.unit());
if (!locked) {
throw new LockException("Write lock not acquired in " + lock.unit().toMillis(time) + " ms");
}... | locked = readWriteLock.writeLock().tryLock(time, lock.unit()); | private Object writeLock(Lock lock, InvocationContext ctx) throws Exception {
boolean locked = false;
long time = lock.time();
try {
if (time > 0) {
locked = readWriteLock.writeLock().tryLock(time, lock.unit());
if (!locked) {
throw new LockException("Write lock not acquired in " + lock.unit().toMillis(time) + " ms");
... | class LockInterceptor {
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
@AroundInvoke
Object lock(InvocationContext ctx) throws Exception {
Lock lock = getLock(ctx);
switch (lock.value()) {
case WRITE:
return writeLock(lock, ctx);
case READ:
return readLock(lock, ctx);
case NONE:
return ctx.pr... | class LockInterceptor {
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
@AroundInvoke
Object lock(InvocationContext ctx) throws Exception {
Lock lock = getLock(ctx);
switch (lock.value()) {
case WRITE:
return writeLock(lock, ctx);
case READ:
return readLock(lock, ctx);
case NONE:
return ctx.pr... |
Just a formatting thing: I think it would be more readable to have both lambda statements on new lines. | 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... |
for checkstyle: `preTransactionType != null` => `null != preTransactionType` | public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
ShardingTransactionType shardingTransactionType = getAnnotation(methodInvocation);
Objects.requireNonNull(shardingTransactionType, "could not found sharding transaction type annotation");
TransactionType preTransactionType = TransactionTyp... | if (preTransactionType != null) { | public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
ShardingTransactionType shardingTransactionType = getAnnotation(methodInvocation);
Objects.requireNonNull(shardingTransactionType, "could not found sharding transaction type annotation");
TransactionType preTransactionType = TransactionTyp... | class ShardingTransactionTypeInterceptor implements MethodInterceptor {
@Override
private ShardingTransactionType getAnnotation(final MethodInvocation invocation) {
Objects.requireNonNull(invocation.getThis());
Class<?> targetClass = AopUtils.getTargetClass(invocation.getThis());
ShardingTransactionType result = getMet... | class ShardingTransactionTypeInterceptor implements MethodInterceptor {
@Override
private ShardingTransactionType getAnnotation(final MethodInvocation invocation) {
Objects.requireNonNull(invocation.getThis());
Class<?> targetClass = AopUtils.getTargetClass(invocation.getThis());
ShardingTransactionType result = getMet... |
I think you could just use phase instead of getPhase() here | public void onNext(T value) {
synchronized (lock) {
if (++numMessages >= maxMessagesBeforeCheck) {
numMessages = 0;
int waitTime = 1;
int totalTimeWaited = 0;
int phase = phaser.getPhase();
int initialPhase = phase;
while (!outboundObserver.isReady()) {
try {
phase = phaser.awaitAdvanceInterruptibly(phase, waitTime, Ti... | if (initialPhase == phaser.getPhase()) { | public void onNext(T value) {
synchronized (lock) {
if (++numMessages >= maxMessagesBeforeCheck) {
numMessages = 0;
int waitTime = 1;
int totalTimeWaited = 0;
int phase = phaser.getPhase();
int initialPhase = phase;
while (!outboundObserver.isReady()) {
try {
phase = phaser.awaitAdvanceInterruptibly(phase, waitTime, Ti... | class DirectStreamObserver<T> implements StreamObserver<T> {
private static final Logger LOG = LoggerFactory.getLogger(DirectStreamObserver.class);
private static final int DEFAULT_MAX_MESSAGES_BEFORE_CHECK = 100;
private final Phaser phaser;
private final CallStreamObserver<T> outboundObserver;
/**
* Controls the numb... | class DirectStreamObserver<T> implements StreamObserver<T> {
private static final Logger LOG = LoggerFactory.getLogger(DirectStreamObserver.class);
private static final int DEFAULT_MAX_MESSAGES_BEFORE_CHECK = 100;
private final Phaser phaser;
private final CallStreamObserver<T> outboundObserver;
/**
* Controls the numb... |
ops! yes ;) I've used [guava](https://guava.dev/releases/19.0/api/docs/com/google/common/io/Closer.html) nomenclature | public void close() throws RocksDBException {
try {
if (batch.count() != 0) {
flush();
}
} finally {
IOUtils.closeQuietly(batch);
if (ownsWriteOptions) {
IOUtils.closeQuietly(options);
}
}
} | } | public void close() throws RocksDBException {
try {
if (batch.count() != 0) {
flush();
}
} finally {
IOUtils.closeAllQuietly(toClose);
}
} | class RocksDBWriteBatchWrapper implements AutoCloseable {
private static final int MIN_CAPACITY = 100;
private static final int MAX_CAPACITY = 1000;
private static final int PER_RECORD_BYTES = 100;
private static final long DEFAULT_BATCH_SIZE = 0;
private final RocksDB db;
private final WriteBatch batch;
private final ... | class RocksDBWriteBatchWrapper implements AutoCloseable {
private static final int MIN_CAPACITY = 100;
private static final int MAX_CAPACITY = 1000;
private static final int PER_RECORD_BYTES = 100;
private static final long DEFAULT_BATCH_SIZE = 0;
private final RocksDB db;
private final WriteBatch batch;
private final ... |
We should also check for `isNullLiteral`? | private void setArguments(CallContext callContext) {
DataType[] inputTypes = callContext.getArgumentDataTypes().toArray(new DataType[0]);
Object[] constantArgs = new Object[inputTypes.length];
for (int i = 0; i < constantArgs.length; i++) {
if (callContext.isArgumentLiteral(i)) {
constantArgs[i] = callContext.getArgume... | if (callContext.isArgumentLiteral(i)) { | private void setArguments(CallContext callContext) {
DataType[] inputTypes = callContext.getArgumentDataTypes().toArray(new DataType[0]);
Object[] constantArgs = new Object[inputTypes.length];
for (int i = 0; i < constantArgs.length; i++) {
if (callContext.isArgumentLiteral(i)) {
constantArgs[i] = callContext.getArgume... | class HiveScalarFunction<UDFType> extends ScalarFunction {
protected final HiveFunctionWrapper<UDFType> hiveFunctionWrapper;
protected Object[] constantArguments;
protected DataType[] argTypes;
protected transient UDFType function;
protected transient ObjectInspector returnInspector;
private transient boolean isArgsSin... | class HiveScalarFunction<UDFType> extends ScalarFunction {
protected final HiveFunctionWrapper<UDFType> hiveFunctionWrapper;
protected Object[] constantArguments;
protected DataType[] argTypes;
protected transient UDFType function;
protected transient ObjectInspector returnInspector;
private transient boolean isArgsSin... |
Let's stay with the option 2 (as you have currently implemented) | public BufferAndBacklog getNextBuffer() throws IOException {
if (isReleased) {
return null;
}
Buffer current = dataReader.nextBuffer();
if (current == null) {
return null;
}
updateStatistics(current);
Buffer.DataType nextDataType = Buffer.DataType.NONE;
if (numDataBuffers > 0) {
nextDataType = Buffer.DataType.DATA_BUFF... | } | public BufferAndBacklog getNextBuffer() throws IOException {
if (isReleased) {
return null;
}
Buffer current = dataReader.nextBuffer();
if (current == null) {
return null;
}
updateStatistics(current);
Buffer.DataType nextDataType = Buffer.DataType.NONE;
if (numDataBuffers > 0) {
nextDataType = Buffer.DataType.DATA_BUFF... | class BoundedBlockingSubpartitionDirectTransferReader implements ResultSubpartitionView {
/** The result subpartition that we read. */
private final BoundedBlockingSubpartition parent;
/** The reader/decoder to the file region with the data we currently read from. */
private final BoundedData.Reader dataReader;
/** The... | class BoundedBlockingSubpartitionDirectTransferReader implements ResultSubpartitionView {
/** The result subpartition that we read. */
private final BoundedBlockingSubpartition parent;
/** The reader/decoder to the file region with the data we currently read from. */
private final BoundedData.Reader dataReader;
/** The... |
same as above (if I understand your suggestion correctly) | private static String getTargetOrNullOldSemconv(Attributes attributes, int defaultPort) {
String peerService = attributes.get(SemanticAttributes.PEER_SERVICE);
if (peerService != null) {
return peerService;
}
String host = attributes.get(SemanticAttributes.NET_PEER_NAME);
if (host != null) {
Long port = attributes.get(... | Long port = attributes.get(SemanticAttributes.NET_SOCK_PEER_PORT); | private static String getTargetOrNullOldSemconv(Attributes attributes, int defaultPort) {
String peerService = attributes.get(SemanticAttributes.PEER_SERVICE);
if (peerService != null) {
return peerService;
}
String host = attributes.get(SemanticAttributes.NET_PEER_NAME);
if (host != null) {
Long port = attributes.get(... | class SpanDataMapper {
public static final String MS_PROCESSED_BY_METRIC_EXTRACTORS = "_MS.ProcessedByMetricExtractors";
private static final Set<String> SQL_DB_SYSTEMS =
new HashSet<>(
asList(
SemanticAttributes.DbSystemValues.DB2,
SemanticAttributes.DbSystemValues.DERBY,
SemanticAttributes.DbSystemValues.MARIADB,
Sem... | class SpanDataMapper {
public static final String MS_PROCESSED_BY_METRIC_EXTRACTORS = "_MS.ProcessedByMetricExtractors";
private static final Set<String> SQL_DB_SYSTEMS =
new HashSet<>(
asList(
SemanticAttributes.DbSystemValues.DB2,
SemanticAttributes.DbSystemValues.DERBY,
SemanticAttributes.DbSystemValues.MARIADB,
Sem... |
Instead of the `StatelessIdentityDoFn` we could use `MapElements.into(...).via(e -> KV.of("", e.getValue())`, which would enforce shuffle semantically. That might improve readability a bit. | private JobGraph getStatefulParDoAfterCombineChainingJobGraph(boolean stablePartitioning) {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
final FlinkStreamingPipelineTranslator translator =
new FlinkStreamingPipelineTranslator(env, PipelineOptionsFactory.create());
final P... | aggregate = aggregate.apply(ParDo.of(new StatelessIdentityDoFn<>())); | private JobGraph getStatefulParDoAfterCombineChainingJobGraph(boolean stablePartitioning) {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
final FlinkStreamingPipelineTranslator translator =
new FlinkStreamingPipelineTranslator(env, PipelineOptionsFactory.create());
final P... | class FlinkStreamingPipelineTranslatorTest {
@Test
public void testAutoBalanceShardKeyResolvesMaxParallelism() {
int parallelism = 3;
assertThat(
new FlinkAutoBalancedShardKeyShardingFunction<>(parallelism, -1, StringUtf8Coder.of())
.getMaxParallelism(),
equalTo(KeyGroupRangeAssignment.computeDefaultMaxParallelism(para... | class FlinkStreamingPipelineTranslatorTest {
@Test
public void testAutoBalanceShardKeyResolvesMaxParallelism() {
int parallelism = 3;
assertThat(
new FlinkAutoBalancedShardKeyShardingFunction<>(parallelism, -1, StringUtf8Coder.of())
.getMaxParallelism(),
equalTo(KeyGroupRangeAssignment.computeDefaultMaxParallelism(para... |
This won't be the correct error when the constructed record is also open, right? E.g., the example you raised ```ballerina type Student record {| string name; int age; int...; |}; type Employee record { string name; int age; }; public function main() { Employee emp = {name: "A", age: 1}; ... | private BType checkMappingField(RecordLiteralNode.RecordField field, BType mappingType, AnalyzerData data) {
BType fieldType = symTable.semanticError;
boolean keyValueField = field.isKeyValueField();
boolean spreadOpField = field.getKind() == NodeKind.RECORD_LITERAL_SPREAD_OP;
boolean readOnlyConstructorField = false;
... | errored = true; | private BType checkMappingField(RecordLiteralNode.RecordField field, BType mappingType, AnalyzerData data) {
BType fieldType = symTable.semanticError;
boolean keyValueField = field.isKeyValueField();
boolean spreadOpField = field.getKind() == NodeKind.RECORD_LITERAL_SPREAD_OP;
boolean readOnlyConstructorField = false;
... | class InferredTupleDetails {
List<BType> fixedMemberTypes = new ArrayList<>();
List<BType> restMemberTypes = new ArrayList<>();
} | class InferredTupleDetails {
List<BType> fixedMemberTypes = new ArrayList<>();
List<BType> restMemberTypes = new ArrayList<>();
} |
I think this is in-correct. Don't we want to use `getIdleTcpConnectionTimeout` ? | public Builder(ConnectionPolicy connectionPolicy) {
this.bufferPageSize = DEFAULT_OPTIONS.bufferPageSize;
this.connectionAcquisitionTimeout = DEFAULT_OPTIONS.connectionAcquisitionTimeout;
this.connectTimeout = connectionPolicy.getConnectTimeout();
this.idleChannelTimeout = connectionPolicy.getIdleConnectionTimeout();
t... | this.idleChannelTimeout = connectionPolicy.getIdleConnectionTimeout(); | public Builder(ConnectionPolicy connectionPolicy) {
this.bufferPageSize = DEFAULT_OPTIONS.bufferPageSize;
this.connectionAcquisitionTimeout = DEFAULT_OPTIONS.connectionAcquisitionTimeout;
this.connectTimeout = connectionPolicy.getConnectTimeout();
this.idleChannelTimeout = connectionPolicy.getIdleTcpConnectionTimeout()... | class Builder {
private static final String DEFAULT_OPTIONS_PROPERTY_NAME = "azure.cosmos.directTcp.defaultOptions";
private static final Options DEFAULT_OPTIONS;
static {
Options options = null;
try {
final String string = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME);
if (string != null) {
try {
options = RntbdOb... | class Builder {
private static final String DEFAULT_OPTIONS_PROPERTY_NAME = "azure.cosmos.directTcp.defaultOptions";
private static final Options DEFAULT_OPTIONS;
static {
Options options = null;
try {
final String string = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME);
if (string != null) {
try {
options = RntbdOb... |
Nevermind, I see it just continued the trend from before. | public static void main(Function<String, String> environmentVarGetter) throws Exception {
JvmInitializers.runOnStartup();
System.out.format("SDK Fn Harness started%n");
System.out.format("Harness ID %s%n", environmentVarGetter.apply(HARNESS_ID));
System.out.format(
"Logging location %s%n", environmentVarGetter.apply(LO... | System.out.format("Pipeline options %s%n", pipelineOptionsJson); | public static void main(Function<String, String> environmentVarGetter) throws Exception {
JvmInitializers.runOnStartup();
System.out.format("SDK Fn Harness started%n");
System.out.format("Harness ID %s%n", environmentVarGetter.apply(HARNESS_ID));
System.out.format(
"Logging location %s%n", environmentVarGetter.apply(LO... | class FnHarness {
private static final String HARNESS_ID = "HARNESS_ID";
private static final String CONTROL_API_SERVICE_DESCRIPTOR = "CONTROL_API_SERVICE_DESCRIPTOR";
private static final String LOGGING_API_SERVICE_DESCRIPTOR = "LOGGING_API_SERVICE_DESCRIPTOR";
private static final String STATUS_API_SERVICE_DESCRIPTOR... | class FnHarness {
private static final String HARNESS_ID = "HARNESS_ID";
private static final String CONTROL_API_SERVICE_DESCRIPTOR = "CONTROL_API_SERVICE_DESCRIPTOR";
private static final String LOGGING_API_SERVICE_DESCRIPTOR = "LOGGING_API_SERVICE_DESCRIPTOR";
private static final String STATUS_API_SERVICE_DESCRIPTOR... |
The only qualm I have with verifying the version is that it creates a dependency on a cluster being available. I had hoped to keep the ability (depending on explicitly setting `withBackendVersion`) for `DocToBulk` to be fully free from IO/dependency on an available cluster. I could do the checking in `ElasticsearchIO.... | public boolean start() throws IOException {
restClient = source.spec.getConnectionConfiguration().createClient();
String query = source.spec.getQuery() != null ? source.spec.getQuery().get() : null;
if (query == null) {
query = "{\"query\": { \"match_all\": {} }}";
}
if ((source.backendVersion >= 5) && source.numSlices... | } | public boolean start() throws IOException {
restClient = source.spec.getConnectionConfiguration().createClient();
String query = source.spec.getQuery() != null ? source.spec.getQuery().get() : null;
if (query == null) {
query = "{\"query\": { \"match_all\": {} }}";
}
if ((source.backendVersion >= 5) && source.numSlices... | class BoundedElasticsearchReader extends BoundedSource.BoundedReader<String> {
private final BoundedElasticsearchSource source;
private RestClient restClient;
private String current;
private String scrollId;
private ListIterator<String> batchIterator;
private BoundedElasticsearchReader(BoundedElasticsearchSource source... | class BoundedElasticsearchReader extends BoundedSource.BoundedReader<String> {
private final BoundedElasticsearchSource source;
private RestClient restClient;
private String current;
private String scrollId;
private ListIterator<String> batchIterator;
private BoundedElasticsearchReader(BoundedElasticsearchSource source... |
Both JDK client and Netty client have to do the same logic for converting response byte array to string. It would be better to put this in Core utils somewhere to reduce duplication and if there are any fixes or updates to this logic, we don't need to update in two places. | public Mono<String> getBodyAsString() {
return getBodyAsByteArray().map(bytes -> {
if (bytes.length >= 3 && bytes[0] == (byte) 239 && bytes[1] == (byte) 187 && bytes[2] == (byte) 191) {
return new String(bytes, 3, bytes.length - 3, StandardCharsets.UTF_8);
} else if (bytes.length >= 2 && bytes[0] == (byte) 254 && bytes... | return getBodyAsByteArray().map(bytes -> { | public Mono<String> getBodyAsString() {
return getBodyAsByteArray().map(bytes ->
CoreUtils.bomAwareToString(bytes, reactorNettyResponse.responseHeaders().get("Content-Type")));
} | class ReactorNettyHttpResponse extends HttpResponse {
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
private final boolean disableBufferCopy;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection,
HttpRequest httpRequ... | class ReactorNettyHttpResponse extends HttpResponse {
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
private final boolean disableBufferCopy;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection,
HttpRequest httpRequ... |
Yes, sorry (I changed it but then accidentially rolled back together with type changes for other comment). | public void testMetadataOperationLogged() throws IOException {
TestingStateChangelogWriter writer = new TestingStateChangelogWriter();
InternalKeyContextImpl<String> keyContext =
new InternalKeyContextImpl<>(KeyGroupRange.of(1, 1000), 1000);
StateChangeLogger<String, Namespace> logger = getLogger(writer, keyContext);
L... | Tuple2.of(-1 /* see AbstractStateChangeLogger | public void testMetadataOperationLogged() throws IOException {
TestingStateChangelogWriter writer = new TestingStateChangelogWriter();
InternalKeyContextImpl<String> keyContext =
new InternalKeyContextImpl<>(KeyGroupRange.of(1, 1000), 1000);
StateChangeLogger<String, Namespace> logger = getLogger(writer, keyContext);
L... | class StateChangeLoggerTestBase<Namespace> {
/** A basic test for appending the metadata on first state access. */
@Test
protected abstract StateChangeLogger<String, Namespace> getLogger(
TestingStateChangelogWriter writer, InternalKeyContextImpl<String> keyContext);
protected Optional<Tuple2<Integer, StateChangeOperat... | class StateChangeLoggerTestBase<Namespace> {
/** A basic test for appending the metadata on first state access. */
@Test
protected abstract StateChangeLogger<String, Namespace> getLogger(
TestingStateChangelogWriter writer, InternalKeyContextImpl<String> keyContext);
protected Optional<Tuple2<Integer, StateChangeOperat... |
:( Waiting for a brain reboot | protected double maintain() {
Exception lastException = null;
int attempts = 0;
int failures = 0;
var metrics = collectClusterMetrics();
for (var application : applications.asList()) {
for (var instance : application.instances().values()) {
for (var deployment : instance.productionDeployments().values()) {
if (shutting... | log.log(Level.FINE, "Could not update traffic share on all applications", lastException); | protected double maintain() {
Exception lastException = null;
int attempts = 0;
int failures = 0;
var metrics = collectClusterMetrics();
for (var application : applications.asList()) {
for (var instance : application.instances().values()) {
for (var deployment : instance.productionDeployments().values()) {
if (shutting... | class BcpGroupUpdater extends ControllerMaintainer {
private final ApplicationController applications;
private final NodeRepository nodeRepository;
public BcpGroupUpdater(Controller controller, Duration duration, Double successFactorBaseline) {
super(controller, duration, successFactorBaseline);
this.applications = con... | class BcpGroupUpdater extends ControllerMaintainer {
private final ApplicationController applications;
private final NodeRepository nodeRepository;
private final Double successFactorBaseline;
public BcpGroupUpdater(Controller controller, Duration duration, Double successFactorBaseline) {
super(controller, duration, suc... |
By just looking at the code, I would say `newProducedType` should be initialized with only physical columns. Not sure what the tests say to this. But `toSourceRowDataType` includes also computed column which makes no sense for the DynamicTableSource as the source doesn't know this concept. After the spec is applied in ... | private DynamicTableSource getTableSource(FlinkContext context, FlinkTypeFactory typeFactory) {
if (tableSource == null) {
DynamicTableSourceFactory factory =
context.getModuleManager()
.getFactory(Module::getTableSourceFactory)
.orElse(null);
if (factory == null) {
Catalog catalog =
context.getCatalogManager()
.getCat... | .getLogicalType(); | private DynamicTableSource getTableSource(FlinkContext context, FlinkTypeFactory typeFactory) {
if (tableSource == null) {
DynamicTableSourceFactory factory =
context.getModuleManager()
.getFactory(Module::getTableSourceFactory)
.orElse(null);
if (factory == null) {
Catalog catalog =
context.getCatalogManager()
.getCat... | class DynamicTableSourceSpec extends DynamicTableSpecBase {
public static final String FIELD_NAME_CATALOG_TABLE = "table";
public static final String FIELD_NAME_SOURCE_ABILITIES = "abilities";
private final ContextResolvedTable contextResolvedTable;
private final @Nullable List<SourceAbilitySpec> sourceAbilities;
priva... | class DynamicTableSourceSpec extends DynamicTableSpecBase {
public static final String FIELD_NAME_CATALOG_TABLE = "table";
public static final String FIELD_NAME_SOURCE_ABILITIES = "abilities";
private final ContextResolvedTable contextResolvedTable;
private final @Nullable List<SourceAbilitySpec> sourceAbilities;
priva... |
@mssfang please revert the changes where you got rid of the static import such as here. Once you've done that, please let me know what CheckStyle tests fail and we can work to modify that. | public void onDelivery(Event event) {
Delivery delivery = event.getDelivery();
while (delivery != null) {
Sender sender = (Sender) delivery.getLink();
if (TRACE_LOGGER.isTraceEnabled()) {
TRACE_LOGGER.trace(
"onDelivery linkName[" + sender.getName()
+ "], unsettled[" + sender.getUnsettled() + "], credit[" + sender.getR... | + "], delivery.isBuffered[" + delivery.isBuffered() + "], delivery.id[" + new String(delivery.getTag(), StandardCharsets.UTF_8) + "]"); | public void onDelivery(Event event) {
Delivery delivery = event.getDelivery();
while (delivery != null) {
Sender sender = (Sender) delivery.getLink();
if (TRACE_LOGGER.isTraceEnabled()) {
TRACE_LOGGER.trace(
"onDelivery linkName[" + sender.getName()
+ "], unsettled[" + sender.getUnsettled() + "], credit[" + sender.getR... | class SendLinkHandler extends BaseLinkHandler {
private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(SendLinkHandler.class);
private final AmqpSender msgSender;
private final Object firstFlow;
private boolean isFirstFlow;
public SendLinkHandler(final AmqpSender sender) {
super(sender);
this.msgSender = se... | class SendLinkHandler extends BaseLinkHandler {
private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(SendLinkHandler.class);
private final AmqpSender msgSender;
private final Object firstFlow;
private boolean isFirstFlow;
public SendLinkHandler(final AmqpSender sender) {
super(sender);
this.msgSender = se... |
@radcortez could you have a look at this? I wonder if it's not a side effect of one of your patches and might be undesired? | public OidcClient apply(String tokenRequestUri, Throwable t) {
if (t != null) {
throw toOidcClientException(authServerUri.toString(), t);
}
if (tokenRequestUri == null) {
throw new ConfigurationException(
"OpenId Connect Provider token endpoint URL is not configured and can not be discovered");
}
MultiMap tokenGrantPar... | if (oidcConfig.getGrantOptions() != null) { | public OidcClient apply(String tokenRequestUri, Throwable t) {
if (t != null) {
throw toOidcClientException(authServerUri.toString(), t);
}
if (tokenRequestUri == null) {
throw new ConfigurationException(
"OpenId Connect Provider token endpoint URL is not configured and can not be discovered");
}
MultiMap tokenGrantPar... | class OidcClientRecorder {
private static final Logger LOG = Logger.getLogger(OidcClientRecorder.class);
private static final String DEFAULT_OIDC_CLIENT_ID = "Default";
private static final Duration CONNECTION_BACKOFF_DURATION = Duration.ofSeconds(2);
public OidcClients setup(OidcClientsConfig oidcClientsConfig, TlsCon... | class OidcClientRecorder {
private static final Logger LOG = Logger.getLogger(OidcClientRecorder.class);
private static final String DEFAULT_OIDC_CLIENT_ID = "Default";
private static final Duration CONNECTION_BACKOFF_DURATION = Duration.ofSeconds(2);
public OidcClients setup(OidcClientsConfig oidcClientsConfig, TlsCon... |
reach ```suggestion for (ZoneId zone : controller.zoneRegistry().zones().reachable().ids()) { ``` | private static Slime toSlime(Controller controller) {
try {
Slime slime = new Slime();
Cursor root = slime.setObject();
Cursor zonesArray = root.setArray("zones");
for (ZoneId zone : controller.zoneRegistry().zones().all().ids()) {
NodeRepoStats stats = controller.serviceRegistry().configServer().nodeRepository().getSt... | for (ZoneId zone : controller.zoneRegistry().zones().all().ids()) { | private static Slime toSlime(Controller controller) {
Slime slime = new Slime();
Cursor root = slime.setObject();
Cursor zonesArray = root.setArray("zones");
for (ZoneId zone : controller.zoneRegistry().zones().reachable().ids()) {
NodeRepoStats stats = controller.serviceRegistry().configServer().nodeRepository().getSt... | class StatsResponse extends SlimeJsonResponse {
public StatsResponse(Controller controller) {
super(toSlime(controller));
}
private static void toSlime(ApplicationStats stats, Cursor applicationObject) {
applicationObject.setString("id", stats.id().toFullString());
toSlime(stats.load(), applicationObject.setObject("loa... | class StatsResponse extends SlimeJsonResponse {
public StatsResponse(Controller controller) {
super(toSlime(controller));
}
private static void toSlime(ApplicationStats stats, Cursor applicationObject) {
applicationObject.setString("id", stats.id().toFullString());
toSlime(stats.load(), applicationObject.setObject("loa... |
It is likely that`value++` is time-consuming if there is a vast range. Here are some of my ideas. For instance,the shardings are as follows, 1,2 | 3,4,5 | 6,7,8,9 | 10,11 So the `range.partition.split.value` is `2,5,9,11` Imaging the query condition is `2 =< x <= 9`, then we just need to calcute 2==2 and 9<11, therefor... | public Collection<String> doSharding(final Collection<String> availableTargetNames, final RangeShardingValue<Long> shardingValue) {
Preconditions.checkNotNull(properties.get(RANGE_PARTITION_SPLIT_VALUE), "Range sharding algorithm range partition split value cannot be null.");
Map<Integer, Range<Long>> partitionRangeMap... | for (long value = shardingValue.getValueRange().lowerEndpoint(); value <= shardingValue.getValueRange().upperEndpoint(); value++) { | public Collection<String> doSharding(final Collection<String> availableTargetNames, final RangeShardingValue<Long> shardingValue) {
Preconditions.checkNotNull(properties.get(RANGE_PARTITION_SPLIT_VALUE), "Range sharding algorithm range partition split value cannot be null.");
Map<Integer, Range<Long>> partitionRangeMap... | class RangeShardingAlgorithm implements StandardShardingAlgorithm<Long> {
private static final String RANGE_PARTITION_SPLIT_VALUE = "range.partition.split.value";
private Properties properties = new Properties();
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValu... | class RangeShardingAlgorithm implements StandardShardingAlgorithm<Long> {
private static final String RANGE_PARTITION_SPLIT_VALUE = "range.partition.split.value";
@Getter
@Setter
private Properties properties = new Properties();
@Override
public String doSharding(final Collection<String> availableTargetNames, final Pre... |
Hmm... good point. So far I could not figure out a solution. However I am wondering how important it is we cover all different configurations. In the end we are pretty much testing that java serialization works well here. Is that crucial that we test all possible values? | public void testSavepoint() throws Exception {
final Random rnd = new Random();
final byte[] locationBytes = new byte[rnd.nextInt(41) + 1];
rnd.nextBytes(locationBytes);
final SnapshotType[] snapshotTypes = {
CHECKPOINT,
FULL_CHECKPOINT,
SavepointType.savepoint(SavepointFormatType.CANONICAL),
SavepointType.suspend(Save... | }; | public void testSavepoint() throws Exception {
final Random rnd = new Random();
final byte[] locationBytes = new byte[rnd.nextInt(41) + 1];
rnd.nextBytes(locationBytes);
final SnapshotType[] snapshotTypes = {
CHECKPOINT,
FULL_CHECKPOINT,
SavepointType.savepoint(SavepointFormatType.CANONICAL),
SavepointType.suspend(Save... | class CheckpointOptionsTest {
@Test
public void testDefaultCheckpoint() throws Exception {
final CheckpointOptions options = CheckpointOptions.forCheckpointWithDefaultLocation();
assertEquals(CheckpointType.CHECKPOINT, options.getCheckpointType());
assertTrue(options.getTargetLocation().isDefaultReference());
final Che... | class CheckpointOptionsTest {
@Test
public void testDefaultCheckpoint() throws Exception {
final CheckpointOptions options = CheckpointOptions.forCheckpointWithDefaultLocation();
assertEquals(CheckpointType.CHECKPOINT, options.getCheckpointType());
assertTrue(options.getTargetLocation().isDefaultReference());
final Che... |
Notable change since the last round of reviews: The documentation for `Source`'s `getCurrent`, `getCurrentRecordId` and `getCurrentTimestamp` include the following: > * @throws NoSuchElementException if the reader is at the beginning of the input and {@link > * #start} or {@link #advance} wasn't called, o... | public boolean advance() throws IOException {
try {
Channel channel = connectionHandler.getChannel();
GetResponse delivery = channel.basicGet(queueName, false);
if (delivery == null) {
current = null;
currentRecordId = null;
currentTimestamp = null;
checkpointMark.advanceWatermark(Instant.now());
return false;
}
if (so... | current = null; | public boolean advance() throws IOException {
try {
Channel channel = connectionHandler.getChannel();
GetResponse delivery = channel.basicGet(queueName, false);
if (delivery == null) {
current = null;
currentRecordId = null;
currentTimestamp = null;
checkpointMark.advanceWatermark(Instant.now());
return false;
}
if (so... | class UnboundedRabbitMqReader
extends UnboundedSource.UnboundedReader<RabbitMqMessage> {
private final RabbitMQSource source;
private RabbitMqMessage current;
private byte[] currentRecordId;
private ConnectionHandler connectionHandler;
private String queueName;
private Instant currentTimestamp;
private final RabbitMQCh... | class UnboundedRabbitMqReader
extends UnboundedSource.UnboundedReader<RabbitMqMessage> {
private final RabbitMQSource source;
private RabbitMqMessage current;
private byte[] currentRecordId;
private ConnectionHandler connectionHandler;
private String queueName;
private Instant currentTimestamp;
private final RabbitMQCh... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.