focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final FileEntity entity = new FilesApi(new BrickApiClient(session))
.download(StringUtils.removeStart(file.getAbsolute(), String.v... | @Test
public void testReadRange() throws Exception {
final Path room = new BrickDirectoryFeature(session).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus());
final Path test = new Path(room, new Alphan... |
public static boolean testURLPassesExclude(String url, String exclude) {
// If the url doesn't decode to UTF-8 then return false, it could be trying to get around our rules with nonstandard encoding
// If the exclude rule includes a "?" character, the url must exactly match the exclude rule.
// ... | @Test
public void wildcardInExcludeBlockedWhenWildcardsNotAllowed() throws Exception {
AuthCheckFilter.ALLOW_WILDCARDS_IN_EXCLUDES.setValue(false);
assertFalse(AuthCheckFilter.testURLPassesExclude("setup/setup-new.jsp","setup/setup-*"));
} |
public static KTableHolder<GenericKey> build(
final KGroupedTableHolder groupedTable,
final TableAggregate aggregate,
final RuntimeBuildContext buildContext,
final MaterializedFactory materializedFactory) {
return build(
groupedTable,
aggregate,
buildContext,
... | @Test
public void shouldBuildMaterializedWithCorrectNameForAggregate() {
// When:
aggregate.build(planBuilder, planInfo);
// Then:
verify(materializedFactory).create(any(), any(), eq("agg-regate-Materialize"));
} |
@Udf(description = "Returns the hyperbolic sine of an INT value")
public Double sinh(
@UdfParameter(
value = "value",
description = "The value in radians to get the hyperbolic sine of."
) final Integer value
) {
return sinh(value == null ? null : value.dou... | @Test
public void shouldHandleLessThanNegative2Pi() {
assertThat(udf.sinh(-9.1), closeTo(-4477.64629590835, 0.000000000000001));
assertThat(udf.sinh(-6.3), closeTo(-272.28503691057597, 0.000000000000001));
assertThat(udf.sinh(-7), closeTo(-548.3161232732465, 0.000000000000001));
assertThat(udf.sinh(-7... |
public static String getSuffixName(String dirPath, String filePath) {
if (!FeConstants.runningUnitTest) {
Preconditions.checkArgument(filePath.startsWith(dirPath),
"dirPath " + dirPath + " should be prefix of filePath " + filePath);
}
//we had checked the startsW... | @Test
public void testGetSuffixName() {
Assert.assertEquals("file", getSuffixName("/path/", "/path/file"));
Assert.assertEquals("file", getSuffixName("/path", "/path/file"));
Assert.assertEquals("file", getSuffixName("/dt=(a)/", "/dt=(a)/file"));
} |
public static <T> Response call(RestUtils.RestCallable<T> callable,
AlluxioConfiguration alluxioConf, @Nullable Map<String, Object> headers) {
try {
// TODO(cc): reconsider how to enable authentication
if (SecurityUtils.isSecurityEnabled(alluxioConf)
&& AuthenticatedClientUser.get(alluxi... | @Test
public void voidOkResponse() {
Response response = RestUtils.call(new RestUtils.RestCallable<Void>() {
@Override
public Void call() throws Exception {
return null;
}
}, Configuration.global());
Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
... |
@VisibleForTesting
void addQueues(String args, SchedConfUpdateInfo updateInfo) {
if (args == null) {
return;
}
ArrayList<QueueConfigInfo> queueConfigInfos = new ArrayList<>();
for (String arg : args.split(";")) {
queueConfigInfos.add(getQueueConfigInfo(arg));
}
updateInfo.setAddQue... | @Test(timeout = 10000)
public void testAddQueuesWithCommaInValue() {
SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo();
cli.addQueues("root.a:a1=a1Val1\\,a1Val2 a1Val3,a2=a2Val1\\,a2Val2",
schedUpdateInfo);
List<QueueConfigInfo> addQueueInfo = schedUpdateInfo.getAddQueueInfo();
M... |
public Map<String, Properties> getNameServerConfig(final List<String> nameServers, long timeoutMillis)
throws InterruptedException,
RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException,
MQClientException, UnsupportedEncodingException {
List<String> invokeNameS... | @Test
public void assertGetNameServerConfig() throws RemotingException, InterruptedException, UnsupportedEncodingException, MQClientException {
mockInvokeSync();
setResponseBody("{\"key\":\"value\"}");
Map<String, Properties> actual = mqClientAPI.getNameServerConfig(Collections.singletonList... |
@Deprecated
@RequestMapping("/meta")
public List<ServiceDTO> getMetaService() {
return Collections.emptyList();
} | @Test
public void testGetMetaService() {
assertTrue(serviceController.getMetaService().isEmpty());
} |
public Heap<T> insert(T item) {
data.add(item);
bubbleUp();
return this;
} | @Test
public void insert() {
Heap<Integer> h = new Heap<>(data, MIN);
assertEquals("incorrect size", 10, h.size());
h.insert(3);
assertEquals("incorrect size", 11, h.size());
} |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testFetchOffsetOutOfRange() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 0);
assertEquals(1, sendFetches());
client.prepareResponse(fullFetchResponse(tidp0, records, Errors.OFFSET_OUT_OF_RANGE, 100L, 0));
consumerClient.... |
@Override
public boolean tryFence(HAServiceTarget target, String argsStr)
throws BadFencingConfigurationException {
Args args = new Args(argsStr);
InetSocketAddress serviceAddr = target.getAddress();
String host = serviceAddr.getHostName();
Session session;
try {
session = create... | @Test(timeout=20000)
public void testConnectTimeout() throws BadFencingConfigurationException {
Configuration conf = new Configuration();
conf.setInt(SshFenceByTcpPort.CONF_CONNECT_TIMEOUT_KEY, 3000);
SshFenceByTcpPort fence = new SshFenceByTcpPort();
fence.setConf(conf);
assertFalse(fence.tryFenc... |
@VisibleForTesting
static Path resolveEntropy(Path path, EntropyInjectingFileSystem efs, boolean injectEntropy)
throws IOException {
final String entropyInjectionKey = efs.getEntropyInjectionKey();
if (entropyInjectionKey == null) {
return path;
} else {
... | @Test
void testPathOnlyMatching() throws Exception {
EntropyInjectingFileSystem efs = new TestEntropyInjectingFs("_entropy_key_", "xyzz");
Path path = new Path("/path/_entropy_key_/file");
assertThat(EntropyInjector.resolveEntropy(path, efs, true))
.isEqualTo(new Path("/path... |
@Override
public Object handle(String targetService, List<Object> invokers, Object invocation, Map<String, String> queryMap,
String serviceInterface) {
if (!shouldHandle(invokers)) {
return invokers;
}
List<Object> result = getTargetInvokersByRules(invokers, targetSe... | @Test
public void testGetTargetInvokerByConsumerTagRules() {
// initialize the routing rule
RuleInitializationUtils.initConsumerTagRules();
List<Object> invokers = new ArrayList<>();
Map<String, String> parameters1 = new HashMap<>();
parameters1.put(RouterConstant.PARAMETERS_... |
@Override
public void remove(NamedNode master) {
connection.sync(RedisCommands.SENTINEL_REMOVE, master.getName());
} | @Test
public void testRemove() {
Collection<RedisServer> masters = connection.masters();
connection.remove(masters.iterator().next());
} |
@VisibleForTesting
public WeightedPolicyInfo getWeightedPolicyInfo() {
return weightedPolicyInfo;
} | @Test
public void testPolicyInfoSetCorrectly() throws Exception {
serializeAndDeserializePolicyManager(wfp, expectedPolicyManager,
expectedAMRMProxyPolicy, expectedRouterPolicy);
// check the policyInfo propagates through ser/der correctly
Assert.assertEquals(
((PriorityBroadcastPolicyMan... |
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) {
return validate(klass, options, false);
} | @Test
public void testSuperInterfaceRequiredOptionsAlsoRequiredInSubInterface() {
SubOptions subOpts = PipelineOptionsFactory.as(SubOptions.class);
subOpts.setFoo("Bar");
subOpts.setRunner(CrashingRunner.class);
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMes... |
@Override
protected int rsv(WebSocketFrame msg) {
return msg.rsv() | WebSocketExtension.RSV1;
} | @Test
public void testAlreadyCompressedFrame() {
EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerFrameDeflateEncoder(9, 15, false));
// initialize
byte[] payload = new byte[300];
random.nextBytes(payload);
BinaryWebSocketFrame frame = new BinaryWebSocketFrame(tr... |
public void createReport() throws Exception {
// Create a new report
//
report = new MasterReport();
// Define where which transformation and step to read from, explain it to the reporting engine
//
KettleFileTableModel transMetaTableModel = new KettleFileTableModel( parentObject, filenames );
... | @Test
public void createReport() throws Exception {
LoggingObjectInterface log = mock( LoggingObjectInterface.class );
AutoDocOptionsInterface options = mock( AutoDocOptionsInterface.class );
when( options.isIncludingImage() ).thenReturn( Boolean.TRUE );
KettleReportBuilder builder = new KettleRepor... |
public Map<Integer, Long> queryCorrectionOffset(final String addr, final String topic, final String group,
Set<String> filterGroup,
long timeoutMillis) throws MQClientException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException,
InterruptedException {
Query... | @Test
public void assertQueryCorrectionOffset() throws RemotingException, InterruptedException, MQClientException {
mockInvokeSync();
QueryCorrectionOffsetBody responseBody = new QueryCorrectionOffsetBody();
responseBody.getCorrectionOffsets().put(1, 1L);
setResponseBody(responseBody... |
public static String format(double amount, boolean isUseTraditional) {
return format(amount, isUseTraditional, false);
} | @Test
public void formatThousandLongTest() {
String f = NumberChineseFormatter.format(0, false);
assertEquals("零", f);
f = NumberChineseFormatter.format(1, false);
assertEquals("一", f);
f = NumberChineseFormatter.format(10, false);
assertEquals("一十", f);
f = NumberChineseFormatter.format(12, false);
as... |
public static boolean createFile(final Path filePath) {
try {
final Path parent = filePath.getParent();
if (parent == null) {
return false;
}
if (Files.notExists(parent)) {
Files.createDirectories(parent);
}
... | @Test
void testCreateFileSubDir() {
Path subDirHistoryFile = Paths.get(realFolder.toFile().getPath(), "subdir", "history.file");
CliUtils.createFile(subDirHistoryFile);
assertThat(Files.exists(subDirHistoryFile)).isTrue();
} |
@Override
public void updateInstanceStatus(String status) {
client.updateInstanceStatus(status);
} | @Test
public void updateInstanceStatus() {
nacosRegister.updateInstanceStatus(status);
Mockito.verify(client, Mockito.times(1)).updateInstanceStatus(status);
} |
public static boolean isEmpty(String s) {
return s == null || s.isEmpty();
} | @SuppressWarnings("ConstantConditions")
@Test
public void testEmptyString() {
assertTrue(isEmpty(null));
assertTrue(isEmpty(""));
assertFalse(isEmpty("hello world"));
} |
public static Date jsToDate( Object value, String classType ) throws KettleValueException {
double dbl;
if ( !classType.equalsIgnoreCase( JS_UNDEFINED ) ) {
if ( classType.equalsIgnoreCase( "org.mozilla.javascript.NativeDate" ) ) {
dbl = Context.toNumber( value );
} else if ( classType.equal... | @Test
public void jsToDate_Undefined() throws Exception {
assertNull( JavaScriptUtils.jsToDate( null, UNDEFINED ) );
} |
public static String pickBestEncoding(String acceptHeader, Set<String> customMimeTypesSupported)
{
return pickBestEncoding(acceptHeader, null, customMimeTypesSupported);
} | @Test(dataProvider = "invalidHeaders")
public void testPickBestEncodingWithInvalidHeaders(String header)
{
try
{
RestUtils.pickBestEncoding(header, Collections.emptySet());
Assert.fail();
}
catch (RestLiServiceException e)
{
Assert.assertEquals(e.getStatus(), HttpStatus.S_400_B... |
public static FromEndOfWindow pastEndOfWindow() {
return new FromEndOfWindow();
} | @Test
public void testFromEndOfWindowToString() {
Trigger trigger = AfterWatermark.pastEndOfWindow();
assertEquals("AfterWatermark.pastEndOfWindow()", trigger.toString());
} |
public String getStageName() {
if(isBuilding()) {
try {
return buildLocator.split("/")[2];
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
}
return null;
} | @Test
public void shouldReturnTheStageName() {
AgentBuildingInfo agentBuildingInfo = new AgentBuildingInfo("buildInfo", "foo/1/bar");
assertThat(agentBuildingInfo.getStageName(), is("bar"));
} |
@Override
public void debug(String msg) {
logger.debug(msg);
} | @Test
void testMarkerDebugWithException() {
Exception exception = new Exception();
jobRunrDashboardLogger.debug(marker, "Debug", exception);
verify(slfLogger).debug(marker, "Debug", exception);
} |
public <T extends AwsSyncClientBuilder> void applyHttpClientConfigurations(T builder) {
if (Strings.isNullOrEmpty(httpClientType)) {
httpClientType = CLIENT_TYPE_DEFAULT;
}
switch (httpClientType) {
case CLIENT_TYPE_URLCONNECTION:
UrlConnectionHttpClientConfigurations urlConnectionHttpC... | @Test
public void testInvalidHttpClientType() {
Map<String, String> properties = Maps.newHashMap();
properties.put(HttpClientProperties.CLIENT_TYPE, "test");
HttpClientProperties httpProperties = new HttpClientProperties(properties);
S3ClientBuilder s3ClientBuilder = S3Client.builder();
assertTha... |
@Nullable
public static ZNRecord fetchTaskMetadata(HelixPropertyStore<ZNRecord> propertyStore, String taskType,
String tableNameWithType) {
String newPath = ZKMetadataProvider.constructPropertyStorePathForMinionTaskMetadata(tableNameWithType, taskType);
if (propertyStore.exists(newPath, AccessOption.PER... | @Test
public void testFetchTaskMetadata() {
// no metadata path exists
HelixPropertyStore<ZNRecord> propertyStore = new FakePropertyStore();
assertNull(MinionTaskMetadataUtils.fetchTaskMetadata(propertyStore, TASK_TYPE, TABLE_NAME_WITH_TYPE));
// only the old metadata path exists
propertyStore = ... |
public static void initRequestFromEntity(HttpRequestBase requestBase, Map<String, String> body, String charset)
throws Exception {
if (body == null || body.isEmpty()) {
return;
}
List<NameValuePair> params = new ArrayList<>(body.size());
for (Map.Entry<String, Str... | @Test
void testInitRequestFromEntity3() throws Exception {
BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity("");
HttpUtils.initRequestFromEntity(httpRequest, Collections.emptyMap(), "UTF-8");
// nothing change
assertEquals(new Base... |
@Override
public boolean isIn(String ipAddress) {
//is cache expired
//Uses Double Checked Locking using volatile
if (cacheExpiryTimeStamp >= 0 && cacheExpiryTimeStamp < System.currentTimeMillis()) {
synchronized(this) {
//check if cache expired again
if (cacheExpiryTimeStamp < Syste... | @Test
public void testRemovalWithSleepForCacheTimeout() throws IOException, InterruptedException {
String[] ips = {"10.119.103.112", "10.221.102.0/23",
"10.222.0.0/16", "10.113.221.221", "10.113.221.222"};
TestFileBasedIPList.createFileWithEntries ("ips.txt", ips);
CacheableIPList cipl = new Ca... |
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) {
return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context);
} | @Test
public void testShowCreateExternalCatalogNotExists() {
new MockUp<CatalogMgr>() {
@Mock
public Catalog getCatalogByName(String name) {
return null;
}
};
ShowCreateExternalCatalogStmt stmt = new ShowCreateExternalCatalogStmt("catalog_... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
for(Path f : files.keySet()) {
try {
new FilesApi(new BrickApiClient(session)).deleteFilesPath(
StringUtils... | @Test
public void testDeleteWithLock() throws Exception {
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final Local local = new Local(System.getProperty("java.io.tmpdir"), test.getName());
... |
public CompletableFuture<Map<TopicIdPartition, PartitionData>> fetchMessages(
String groupId,
String memberId,
FetchParams fetchParams,
Map<TopicIdPartition, Integer> partitionMaxBytes
) {
log.trace("Fetch request for topicIdPartitions: {} with groupId: {} fetch params: {}",
... | @Test
public void testReplicaManagerFetchShouldProceed() {
String groupId = "grp";
Uuid memberId = Uuid.randomUuid();
FetchParams fetchParams = new FetchParams(ApiKeys.SHARE_FETCH.latestVersion(), FetchRequest.ORDINARY_CONSUMER_ID, -1, 0,
1, 1024 * 1024, FetchIsolation.HIGH_WATER... |
@Override
public synchronized ConsumerStats getStats() {
if (stats == null) {
return null;
}
stats.reset();
consumers.forEach((partition, consumer) -> stats.updateCumulativeStats(partition, consumer.getStats()));
return stats;
} | @Test
public void testGetStats() throws Exception {
String topicName = "test-stats";
ClientConfigurationData conf = new ClientConfigurationData();
// ip and port is arbitrary since test will attempt to make a connection
// and the connection is not needed for making the test to pass.... |
private void setOptions( JMSProducer producer ) {
String optionValue = meta.getDisableMessageId();
getLogChannel().logDebug( "Disable Message ID is set to " + optionValue );
if ( !StringUtil.isEmpty( optionValue ) ) {
producer.setDisableMessageID( BooleanUtils.toBoolean( optionValue ) );
}
op... | @Test
public void testSetOptions() throws KettleException {
step.init( meta, data );
//Defaults
step.processRow( meta, data );
assertEquals( false, step.producer.getDisableMessageID() );
assertEquals( false, step.producer.getDisableMessageTimestamp() );
assertEquals( 2, step.producer.getDeli... |
@Subscribe
public void publishClusterEvent(Object event) {
if (event instanceof DeadEvent) {
LOG.debug("Skipping DeadEvent on cluster event bus");
return;
}
final String className = AutoValueUtils.getCanonicalName(event.getClass());
final ClusterEvent cluster... | @Test
public void publishClusterEventSkipsDeadEvent() throws Exception {
@SuppressWarnings("deprecation")
DBCollection collection = mongoConnection.getDatabase().getCollection(ClusterEventPeriodical.COLLECTION_NAME);
DeadEvent event = new DeadEvent(clusterEventBus, new SimpleEvent("test"));
... |
public static List<String> notEmptyElements(List<String> list, String name) {
notNull(list, name);
for (int i = 0; i < list.size(); i++) {
notEmpty(list.get(i), MessageFormat.format("list [{0}] element [{1}]", name, i));
}
return list;
} | @Test(expected = IllegalArgumentException.class)
public void notEmptyElementsNullList() {
Check.notEmptyElements(null, "name");
} |
@Override
public String render(String text) {
if (StringUtils.isBlank(text)) {
return "";
}
if (regex.isEmpty() || link.isEmpty()) {
Comment comment = new Comment();
comment.escapeAndAdd(text);
return comment.render();
}
try {
... | @Test
public void shouldRenderStringWithRegexThatHasSubSelect() throws Exception {
String link = "http://mingle05/projects/cce/cards/${ID}";
String regex = "evo-(\\d+)";
trackingTool = new DefaultCommentRenderer(link, regex);
String result = trackingTool.render("evo-111: checkin mes... |
public static String removeLeadingAndEndingQuotes(final String s) {
if (ObjectHelper.isEmpty(s)) {
return s;
}
String copy = s.trim();
if (copy.length() < 2) {
return s;
}
if (copy.startsWith("'") && copy.endsWith("'")) {
return copy.s... | @Test
public void testRemoveLeadingAndEndingQuotesWithSpaces() {
assertNull(StringHelper.removeLeadingAndEndingQuotes(null));
assertEquals(" ", StringHelper.removeLeadingAndEndingQuotes(" "));
assertEquals("Hello World", StringHelper.removeLeadingAndEndingQuotes("Hello World"));
asse... |
public static boolean isWebService(Optional<String> serviceName) {
return serviceName.isPresent()
&& IS_PLAIN_HTTP_BY_KNOWN_WEB_SERVICE_NAME.containsKey(
Ascii.toLowerCase(serviceName.get()));
} | @Test
public void isWebService_whenHttpsService_returnsTrue() {
assertThat(
NetworkServiceUtils.isWebService(
NetworkService.newBuilder().setServiceName("https").build()))
.isTrue();
} |
@Override
public Optional<ErrorResponse> filter(DiscFilterRequest request) {
try {
Optional<ResourceNameAndAction> resourceMapping =
requestResourceMapper.getResourceNameAndAction(request);
log.log(Level.FINE, () -> String.format("Resource mapping for '%s': %s", r... | @Test
void returns_unauthorized_for_request_with_disabled_credential_type() {
AthenzAuthorizationFilter filter =
createFilter(new AllowingZpe(), List.of(EnabledCredentials.ROLE_CERTIFICATE, EnabledCredentials.ACCESS_TOKEN));
MockResponseHandler responseHandler = new MockResponseHand... |
@Override
public Meter submit(MeterRequest request) {
checkNotNull(request, "request cannot be null.");
MeterCellId cellId;
if (request.index().isPresent()) {
checkArgument(userDefinedIndex, "Index cannot be provided when userDefinedIndex mode is disabled");
// User p... | @Test(expected = IllegalArgumentException.class)
public void testWrongAdd() {
initMeterStore();
manager.submit(userDefinedRequest.add());
} |
@Override
public void reset() {
resetCount++;
super.reset();
initEvaluatorMap();
initCollisionMaps();
root.recursiveReset();
resetTurboFilterList();
cancelScheduledTasks();
fireOnReset();
resetListenersExceptResetResistant();
resetStatu... | @SuppressWarnings("unchecked")
@Test
public void collisionMapsPostReset() {
lc.reset();
Map<String, String> fileCollisions = (Map<String, String>) lc.getObject(FA_FILENAME_COLLISION_MAP);
assertNotNull(fileCollisions);
assertTrue(fileCollisions.isEmpty());
Map<String, F... |
public static GoPluginBundleDescriptor parseXML(InputStream pluginXml,
BundleOrPluginFileDetails bundleOrPluginJarFile) throws IOException, JAXBException, XMLStreamException, SAXException {
return parseXML(pluginXml, bundleOrPluginJarFile.file().getAbsolutePat... | @Test
void shouldNotAllowPluginWithEmptyListOfExtensionsInABundle() throws Exception {
try (InputStream pluginXml = getClass().getClassLoader().getResourceAsStream("defaultFiles/gocd-bundle-with-no-extension-classes.xml")) {
final JAXBException e = assertThrows(JAXBException.class, () ->
... |
@Override
public ListenableFuture<HttpResponse> sendAsync(HttpRequest httpRequest) {
return sendAsync(httpRequest, null);
} | @Test
public void sendAsync_whenPostRequestWithEmptyHeaders_returnsExpectedHttpResponse()
throws IOException, ExecutionException, InterruptedException {
String responseBody = "{ \"test\": \"json\" }";
mockWebServer.enqueue(
new MockResponse()
.setResponseCode(HttpStatus.OK.code())
... |
public static SinkConfig validateUpdate(SinkConfig existingConfig, SinkConfig newConfig) {
SinkConfig mergedConfig = clone(existingConfig);
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
}
if (!existingC... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Tenants differ")
public void testMergeDifferentTenant() {
SinkConfig sinkConfig = createSinkConfig();
SinkConfig newSinkConfig = createUpdatedSinkConfig("tenant", "Different");
SinkConfigUtils.valid... |
@Override
public Hotspots.HotspotPullQueryTimestamp generateTimestampMessage(long timestamp) {
Hotspots.HotspotPullQueryTimestamp.Builder responseBuilder = Hotspots.HotspotPullQueryTimestamp.newBuilder();
responseBuilder.setQueryTimestamp(timestamp);
return responseBuilder.build();
} | @Test
public void generateTimestampMessage_shouldMapTimestamp() {
long timestamp = System.currentTimeMillis();
HotspotPullQueryTimestamp result = underTest.generateTimestampMessage(timestamp);
assertThat(result.getQueryTimestamp()).isEqualTo(timestamp);
} |
@Override
public Properties info(RedisClusterNode node) {
Map<String, String> info = execute(node, RedisCommands.INFO_ALL);
Properties result = new Properties();
for (Entry<String, String> entry : info.entrySet()) {
result.setProperty(entry.getKey(), entry.getValue());
}
... | @Test
public void testInfo() {
RedisClusterNode master = getFirstMaster();
Properties info = connection.info(master);
assertThat(info.size()).isGreaterThan(10);
} |
@Override
public V get(K key) {
return cache.get(key);
} | @Test
public void testGet() {
cache.put(42, "foobar");
String result = adapter.get(42);
assertEquals("foobar", result);
} |
public static void executeWithRetries(
final Function function,
final RetryBehaviour retryBehaviour
) throws Exception {
executeWithRetries(() -> {
function.call();
return null;
}, retryBehaviour);
} | @Test
public void shouldNotRetryOnCustomRetryableDenied() throws Exception {
// Given:
final AtomicBoolean firstCall = new AtomicBoolean(true);
final Callable<Object> throwsException = () -> {
if (firstCall.get()) {
firstCall.set(false);
// this is a retryable exception usually
... |
public void appBecomeActive() {
synchronized (mTrackTimer) {
try {
for (Map.Entry<String, EventTimer> entry : mTrackTimer.entrySet()) {
if (entry != null) {
EventTimer eventTimer = entry.getValue();
if (eventTimer !=... | @Test
public void appBecomeActive() {
mInstance.addEventTimer("EventTimer", new EventTimer(TimeUnit.SECONDS, 10000L));
mInstance.appBecomeActive();
Assert.assertEquals(100, mInstance.getEventTimer("EventTimer").getStartTime());
} |
public void shortenIdsIfAvailable(java.util.@Nullable List<CounterUpdate> counters) {
if (counters == null) {
return;
}
for (CounterUpdate update : counters) {
cache.shortenIdsIfAvailable(update);
}
} | @Test
public void testNullUpdates() {
CounterShortIdCache shortIdCache = new CounterShortIdCache();
shortIdCache.shortenIdsIfAvailable(null);
} |
@Override
public boolean add(FilteredBlock block) throws VerificationException, PrunedException {
boolean success = super.add(block);
if (success) {
trackFilteredTransactions(block.getTransactionCount());
}
return success;
} | @Test
public void coinbaseTransactionAvailability() throws Exception {
Context.propagate(new Context(100, Coin.ZERO, false, true));
// Check that a coinbase transaction is only available to spend after NetworkParameters.getSpendableCoinbaseDepth() blocks.
// Create a second wallet to receiv... |
public Set<Cookie> decode(String header) {
Set<Cookie> cookies = new TreeSet<Cookie>();
decode(cookies, header);
return cookies;
} | @Test
public void testDecodingSingleCookie() {
String cookieString = "myCookie=myValue";
Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString);
assertEquals(1, cookies.size());
Cookie cookie = cookies.iterator().next();
assertNotNull(cookie);
assertEqu... |
@Override
public MaterialPollResult responseMessageForLatestRevision(String responseBody) {
Map responseBodyMap = getResponseMap(responseBody);
return new MaterialPollResult(toMaterialDataMap(responseBodyMap), toSCMRevision(responseBodyMap));
} | @Test
public void shouldBuildSCMRevisionFromLatestRevisionResponse() throws Exception {
String revisionJSON = "{\"revision\":\"r1\",\"timestamp\":\"2011-07-14T19:43:37.100Z\",\"user\":\"some-user\",\"revisionComment\":\"comment\",\"data\":{\"dataKeyTwo\":\"data-value-two\",\"dataKeyOne\":\"data-value-one\"}... |
public static List<File> loopFiles(String path, FileFilter fileFilter) {
return loopFiles(file(path), fileFilter);
} | @Test
@Disabled
public void loopFilesTest2() {
FileUtil.loopFiles("").forEach(Console::log);
} |
private Main() {
// Utility Class.
} | @Test
public void runsRepeatedDatasetAgainstRelease() throws Exception {
final File pwd = temp.newFolder();
Main.main(
String.format("--%s=5.5.0", UserInput.DISTRIBUTION_VERSION_PARAM),
String.format("--workdir=%s", pwd.getAbsolutePath()),
String.format("--%s=%d",... |
public static UriTemplate create(String template, Charset charset) {
return new UriTemplate(template, true, charset);
} | @Test
void literalTemplate() {
String template = "https://www.example.com/do/stuff";
UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8);
String expandedTemplate = uriTemplate.expand(Collections.emptyMap());
assertThat(expandedTemplate).isEqualToIgnoringCase(template);
assertThat(UR... |
@Override
public CompletableFuture<Void> localCleanupAsync(JobID jobId, Executor unusedExecutor) {
if (isRegistered(jobId)) {
return unregister(jobId).closeAsync();
}
return FutureUtils.completedVoidFuture();
} | @Test
void testLocalCleanupAsyncOnUnknownJobId() {
assertThat(testInstance.localCleanupAsync(new JobID(), Executors.directExecutor()))
.isCompleted();
} |
@Override
public boolean remove(Object o) {
return map.remove(o) != null;
} | @Test
public void testRemove() {
ExtendedSet<TestValue> set = new ExtendedSet<>(Maps.newConcurrentMap());
TestValue val = new TestValue("foo", 1);
assertTrue(set.add(val));
TestValue nextval = new TestValue("goo", 2);
assertTrue(set.add(nextval));
assertTrue(set.remov... |
public <T> Map<String, Object> properties(Class<T> base, Class<? extends T> cls) {
return this.generate(cls, base);
} | @SuppressWarnings("unchecked")
@Test
void testEnum() {
Map<String, Object> generate = jsonSchemaGenerator.properties(Task.class, TaskWithEnum.class);
assertThat(generate, is(not(nullValue())));
assertThat(((Map<String, Map<String, Object>>) generate.get("properties")).size(), is(4));
... |
public static SerializableFunction<Row, Mutation> beamRowToMutationFn(
Mutation.Op operation, String table) {
return (row -> {
switch (operation) {
case INSERT:
return MutationUtils.createMutationFromBeamRows(Mutation.newInsertBuilder(table), row);
case DELETE:
return... | @Test
public void testCreateReplaceMutationFromRow() {
Mutation expectedMutation = createMutation(Mutation.Op.REPLACE);
Mutation mutation = beamRowToMutationFn(Mutation.Op.REPLACE, TABLE).apply(WRITE_ROW);
assertEquals(expectedMutation, mutation);
} |
@Override
public <T> void write(T payload) {
if (payload == null) {
LOG.debug("Payload was null. Skipping.");
return;
}
String canonicalClassName = AutoValueUtils.getCanonicalName(payload.getClass());
write(canonicalClassName, payload);
} | @Test
public void writePostsClusterConfigChangedEvent() throws Exception {
CustomConfig customConfig = new CustomConfig();
customConfig.text = "TEST";
final ClusterConfigChangedEventHandler eventHandler = new ClusterConfigChangedEventHandler();
clusterEventBus.registerClusterEventSu... |
@Override
public void writeInt(final int v) throws IOException {
ensureAvailable(INT_SIZE_IN_BYTES);
MEM.putInt(buffer, ARRAY_BYTE_BASE_OFFSET + pos, v);
pos += INT_SIZE_IN_BYTES;
} | @Test
public void testWriteIntForPositionV() throws Exception {
int expected = 100;
out.writeInt(1, expected);
int actual = Bits.readInt(out.buffer, 1, ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN);
assertEquals(expected, actual);
} |
public float getBulletPosition() {
return bullet.getPosition();
} | @Test
void testGetBulletPosition() {
assertEquals(controller.bullet.getPosition(), controller.getBulletPosition(), 0);
} |
public static String encodeMap(Map<String, String> map) {
if (map == null) {
return null;
}
if (map.isEmpty()) {
return StringUtils.EMPTY;
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : map.entrySet()) {
... | @Test
public void encodeMap() {
Map<String, String> map = null;
Assertions.assertNull(CollectionUtils.encodeMap(map));
map = new LinkedHashMap<>();
Assertions.assertEquals("", CollectionUtils.encodeMap(map));
map.put("x", "1");
Assertions.assertEquals("x=1", Collecti... |
public int getPrefixMatchLength(ElementPath p) {
if (p == null) {
return 0;
}
int lSize = this.partList.size();
int rSize = p.partList.size();
// no match possible for empty sets
if ((lSize == 0) || (rSize == 0)) {
return 0;
}
int minLen = (lSize <= rSize) ? lSize : rSize;... | @Test
public void testPrefixMatch() {
{
ElementPath p = new ElementPath("/a/b");
ElementSelector ruleElementSelector = new ElementSelector("/x/*");
assertEquals(0, ruleElementSelector.getPrefixMatchLength(p));
}
{
ElementPath p = new ElementPath("/a");
ElementSelector ruleEl... |
static void checkFormat(final String originalFilename) {
final List<String> fileNameSplit = Splitter.on(".").splitToList(originalFilename);
if (fileNameSplit.size() <= 1) {
throw new BadRequestException("The file format is invalid.");
}
for (String s : fileNameSplit) {
if (StringUtils.isEmp... | @Test
public void checkFormat() {
ConfigFileUtils.checkFormat("1234+default+app.properties");
ConfigFileUtils.checkFormat("1234+default+app.yml");
ConfigFileUtils.checkFormat("1234+default+app.json");
} |
protected boolean isConnectPoint(String field, FieldPresence presence) {
return isConnectPoint(object, field, presence);
} | @Test
public void isConnectPoint() {
assertTrue("is not proper connectPoint", cfg.isConnectPoint(CONNECT_POINT, MANDATORY));
assertTrue("is not proper connectPoint", cfg.isConnectPoint(CONNECT_POINT, OPTIONAL));
assertTrue("is not proper connectPoint", cfg.isConnectPoint("none", OPTIONAL));
... |
public double sphericalDistance(LatLong other) {
return LatLongUtils.sphericalDistance(this, other);
} | @Test
public void sphericalDistance_nearOfSriLankaToIslaGenovesa_returnHalfOfEarthEquatorCircumference() {
// These coordinates are 1/4 Earth circumference from zero on the equator
LatLong nearSriLanka = new LatLong(0d, 90d);
// These coordinates are 1/4 Earth circumference from zero on the ... |
@VisibleForTesting
Object[] callHttpService( RowMetaInterface rowMeta, Object[] rowData ) throws KettleException {
HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder();
if ( data.realConnectionTimeout > -1 ) {
clientBuilder.setConnectionTimeout( data... | @Test
public void callHttpServiceWithoutEncoding() throws Exception {
try ( MockedStatic<HttpClientManager> httpClientManagerMockedStatic = mockStatic( HttpClientManager.class ) ) {
httpClientManagerMockedStatic.when( HttpClientManager::getInstance ).thenReturn( manager );
doReturn( null ).when( meta ... |
ClassicGroup getOrMaybeCreateClassicGroup(
String groupId,
boolean createIfNotExists
) throws GroupIdNotFoundException {
Group group = groups.get(groupId);
if (group == null && !createIfNotExists) {
throw new GroupIdNotFoundException(String.format("Classic group %s not f... | @Test
public void testSyncGroupFollowerAfterLeader() throws Exception {
// To get a group of two members:
// 1. join and sync with a single member (because we can't immediately join with two members)
// 2. join and sync with the first member and a new member
GroupMetadataManagerTestC... |
public void parseStepParameter(
Map<String, Map<String, Object>> allStepOutputData,
Map<String, Parameter> workflowParams,
Map<String, Parameter> stepParams,
Parameter param,
String stepId) {
parseStepParameter(
allStepOutputData, workflowParams, stepParams, param, stepId, new ... | @Test
public void testParseStepParameterWithInvalidReference() {
AssertHelper.assertThrows(
"cannot find a step id or signal instance",
MaestroInvalidExpressionException.class,
"Expression evaluation throws an exception",
() ->
paramEvaluator.parseStepParameter(
... |
int getMaxLevel(int maxLevel) {
return (maxLevel <= 0 || maxLevel > this.maxLevelAllowed) ? this.maxLevelAllowed : maxLevel;
} | @Test
public void givenMaxLevelZeroOrNegative_whenGetMaxLevel_thenReturnDefaultMaxLevel() {
assertThat(repo.getMaxLevel(0), equalTo(repo.getMaxLevelAllowed()));
assertThat(repo.getMaxLevel(-1), equalTo(repo.getMaxLevelAllowed()));
assertThat(repo.getMaxLevel(-2), equalTo(repo.getMaxLevelAllo... |
public static Optional<Path> getQualifiedRemoteProvidedUsrLib(
org.apache.flink.configuration.Configuration configuration,
YarnConfiguration yarnConfiguration)
throws IOException, IllegalArgumentException {
String usrlib = configuration.get(YarnConfigOptions.PROVIDED_USRLIB_D... | @Test
void testInvalidRemoteUsrLib(@TempDir Path tempDir) throws IOException {
final String sharedLibPath = "hdfs:///flink/badlib";
final org.apache.hadoop.conf.Configuration hdConf =
new org.apache.hadoop.conf.Configuration();
hdConf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR,... |
int run() {
final Map<String, String> configProps = options.getConfigFile()
.map(Ksql::loadProperties)
.orElseGet(Collections::emptyMap);
final Map<String, String> sessionVariables = options.getVariables();
try (KsqlRestClient restClient = buildClient(configProps)) {
try (Cli cli = c... | @Test
public void shouldRunNonInteractiveCommandWhenExecuteOptionIsUsed() {
// Given:
when(options.getExecute()).thenReturn(Optional.of("this is a command"));
// When:
ksql.run();
// Then:
verify(cli).runCommand("this is a command");
} |
public ConsumerGroup consumerGroup(
String groupId,
long committedOffset
) throws GroupIdNotFoundException {
Group group = group(groupId, committedOffset);
if (group.type() == CONSUMER) {
return (ConsumerGroup) group;
} else {
// We don't support upgr... | @Test
public void testJoiningConsumerGroupReplacingExistingStaticMember() throws Exception {
String groupId = "group-id";
Uuid fooTopicId = Uuid.randomUuid();
String fooTopicName = "foo";
String memberId = Uuid.randomUuid().toString();
String instanceId = "instance-id";
... |
public void sendReportMail(Collector collector, boolean collectorServer,
List<JavaInformations> javaInformationsList, Period period) throws Exception { // NOPMD
final File tmpFile = new File(Parameters.TEMPORARY_DIRECTORY,
PdfReport.getFileName(collector.getApplication()));
try {
try (OutputStream output ... | @Test
public void testSendReportMail() throws Exception {
final Counter counter = new Counter("http", null);
final Collector collector = new Collector("test", Collections.singletonList(counter));
final List<JavaInformations> javaInformationslist = Collections
.singletonList(new JavaInformations(null, true));... |
public static DBSCAN<double[]> fit(double[][] data, int minPts, double radius) {
return fit(data, new KDTree<>(data, data), minPts, radius);
} | @Test
public void testGaussianMixture() throws Exception {
System.out.println("Gaussian Mixture");
double[][] x = GaussianMixture.x;
int[] y = GaussianMixture.y;
DBSCAN<double[]> model = DBSCAN.fit(x,200, 0.8);
System.out.println(model);
double r = RandInde... |
public byte[] toByteArray() {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
write(stream);
} catch (IOException e) {
// Should not happen as ByteArrayOutputStream does not throw IOException on write
throw new RuntimeException(e);
}
... | @Test
public void testToByteArray_OP_PUSHDATA2() {
// OP_PUSHDATA2
byte[] bytes = new byte[0x0102];
RANDOM.nextBytes(bytes);
byte[] expected = ByteUtils.concat(new byte[] { OP_PUSHDATA2, 0x02, 0x01 }, bytes);
byte[] actual = new ScriptChunk(OP_PUSHDATA2, bytes).toByteArray();... |
public static <T> void padRight(Collection<T> list, int minLen, T padObj) {
Objects.requireNonNull(list);
for (int i = list.size(); i < minLen; i++) {
list.add(padObj);
}
} | @Test
public void testPadRight() {
final List<String> srcList = CollUtil.newArrayList("a");
final List<String> answerList = CollUtil.newArrayList("a", "b", "b", "b", "b");
CollUtil.padRight(srcList, 5, "b");
assertEquals(srcList, answerList);
} |
@InvokeOnHeader(Web3jConstants.ETH_BLOCK_NUMBER)
void ethBlockNumber(Message message) throws IOException {
Request<?, EthBlockNumber> request = web3j.ethBlockNumber();
setRequestId(message, request);
EthBlockNumber response = request.send();
boolean hasError = checkForError(message, ... | @Test
public void ethBlockNumberTest() throws Exception {
EthBlockNumber response = Mockito.mock(EthBlockNumber.class);
Mockito.when(mockWeb3j.ethBlockNumber()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getBlockNumber()).thenReturn(... |
@Nonnull
@Override
public Future<?> submit(@Nonnull Runnable runnable) {
submitted.mark();
try {
return delegate.submit(new InstrumentedRunnable(runnable));
} catch (RejectedExecutionException e) {
rejected.mark();
throw e;
}
} | @Test
public void reportsTasksInformation() throws Exception {
this.executor = Executors.newCachedThreadPool();
final InstrumentedExecutorService instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "xs");
final Meter submitted = registry.meter("xs.submitted");
... |
static void unregisterCommand(PrintStream stream, Admin adminClient, int id) throws Exception {
try {
adminClient.unregisterBroker(id).all().get();
stream.println("Broker " + id + " is no longer registered.");
} catch (ExecutionException ee) {
Throwable cause = ee.get... | @Test
public void testUnregisterBroker() throws Exception {
Admin adminClient = new MockAdminClient.Builder().numBrokers(3).
usingRaftController(true).
build();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ClusterTool.unregisterCommand(new Print... |
protected DataTranslator()
{
} | @Test
public void testDataTranslator() throws IOException
{
boolean debug = false;
String[][][] inputs =
{
// {
// {
// 1 string holding the Pegasus schema in JSON.
// The string may be marked with ##T_START and ##T_END markers. The markers are used for typeref testi... |
public CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> commitOffset(
RequestContext context,
OffsetCommitRequestData request
) throws ApiException {
Group group = validateOffsetCommit(context, request);
// In the old consumer group protocol, the offset commits maintai... | @Test
public void testGenericGroupOffsetCommitWithFencedInstanceId() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build();
// Create an empty group.
ClassicGroup group = context.groupMetadataManager.getOrMaybeCreateClassicGroup(
"fo... |
public void wakeup() {
// wakeup should be safe without holding the client lock since it simply delegates to
// Selector's wakeup, which is thread-safe
log.debug("Received user wakeup");
this.wakeup.set(true);
this.client.wakeup();
} | @Test
public void wakeup() {
RequestFuture<ClientResponse> future = consumerClient.send(node, heartbeat());
consumerClient.wakeup();
assertThrows(WakeupException.class, () -> consumerClient.poll(time.timer(0)));
client.respond(heartbeatResponse(Errors.NONE));
consumerClient.... |
List<DataflowPackage> stageClasspathElements(
Collection<StagedFile> classpathElements, String stagingPath, CreateOptions createOptions) {
return stageClasspathElements(classpathElements, stagingPath, DEFAULT_SLEEPER, createOptions);
} | @Test
public void testPackageUploadWithDirectorySucceeds() throws Exception {
Pipe pipe = Pipe.open();
File tmpDirectory = tmpFolder.newFolder("folder");
tmpFolder.newFolder("folder", "empty_directory");
tmpFolder.newFolder("folder", "directory");
makeFileWithContents("folder/file.txt", "This is a... |
public TableView addRow(final Object... row) {
if (row.length > sizeOfColumnsInRow) {
throw new IllegalArgumentException(String.format("Expecting the size of row to be %d but was %s", sizeOfColumnsInRow, row.length));
}
String[] columns = Arrays.stream(row).map(Object::toString).map(... | @Test
void testUnexpectedColumns() {
TableView tableView = new TableView("header 1", "header 2", "header 3", "header 4");
Assertions.assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> tableView.addRow("column 1", "column 2", "column 3", "column 4", "column 5"... |
ConsumerRecord<Object, Object> deserialize(final ProcessorContext<?, ?> processorContext,
final ConsumerRecord<byte[], byte[]> rawRecord) {
try {
return new ConsumerRecord<>(
rawRecord.topic(),
rawRecord.partition(),
... | @Test
public void shouldFailWhenDeserializationFailsAndExceptionHandlerReturnsNull() {
try (final Metrics metrics = new Metrics()) {
final RecordDeserializer recordDeserializer = new RecordDeserializer(
new TheSourceNode(
sourceNodeName,
... |
public boolean init(String uri, final SnapshotThrottle snapshotThrottle, final SnapshotCopierOptions opts) {
this.rpcService = opts.getRaftClientService();
this.timerManager = opts.getTimerManager();
this.raftOptions = opts.getRaftOptions();
this.snapshotThrottle = snapshotThrottle;
... | @Test
public void testInitFail() {
Mockito.when(rpcService.connect(new Endpoint("localhost", 8081))).thenReturn(false);
assertFalse(copier.init("remote://localhost:8081/999", null, new SnapshotCopierOptions(GROUP_ID, rpcService,
timerManager, new RaftOptions(), new NodeOptions())));
... |
public ObjectArray() {
this(0);
} | @Test
public void testObjectArray() {
ObjectArray array = new ObjectArray(10);
for (int i = 0; i < 10; i++) {
array.add("abc");
}
assertEquals(array.objects, IntStream.range(0, 10).mapToObj(i -> "abc").toArray());
Object[] elementData = array.objects;
array.add(1);
assertNotSame(elem... |
public static <T extends PipelineOptions> T as(Class<T> klass) {
return new Builder().as(klass);
} | @Test
public void testMultipleGettersWithInconsistentJsonIgnore() {
// Initial construction is valid.
MultiGetters options = PipelineOptionsFactory.as(MultiGetters.class);
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Property getters are inconsistently ma... |
public void patchBoardById(
final Long boardId,
final Long memberId,
final BoardUpdateRequest request
) {
Board board = findBoardWithImages(boardId);
board.validateWriter(memberId);
BoardUpdateResult result = board.update(request.title(), request.content()... | @Test
void 게시글을_수정한다() {
// given
Board savedBoard = boardRepository.save(게시글_생성_사진없음());
Long boardId = savedBoard.getId();
Long memberId = savedBoard.getWriterId();
MockMultipartFile file = new MockMultipartFile("name", "origin.jpg", "image", "content".getBytes());
... |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String colType = null;
String colName... | @Test
public void testAggregateMultiStatsWhenUnmergeableBitVectors() throws MetaException {
List<String> partitions = Arrays.asList("part1", "part2", "part3");
ColumnStatisticsData data1 = new ColStatsBuilder<>(String.class).numNulls(1).numDVs(3).avgColLen(20.0 / 3).maxColLen(13)
.fmSketch(S_1, S_2, ... |
public Transaction createSend(Address address, Coin value)
throws InsufficientMoneyException, CompletionException {
return createSend(address, value, false);
} | @Test
public void balances() throws Exception {
Coin nanos = COIN;
Transaction tx1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, nanos);
assertEquals(nanos, tx1.getValueSentToMe(wallet));
assertTrue(tx1.getWalletOutputs(wallet).size() >= 1);
// Send 0.10 to ... |
public static TDigest merge(double compression, Iterable<TDigest> subData) {
Preconditions.checkArgument(subData.iterator().hasNext(), "Can't merge 0 digests");
List<TDigest> elements = Lists.newArrayList(subData);
int n = Math.max(1, elements.size() / 4);
TDigest r = new TDigest(compres... | @Test
public void testMerge() {
Random gen = RandomUtils.getRandom();
for (int parts : new int[]{2, 5, 10, 20, 50, 100}) {
List<Double> data = Lists.newArrayList();
TDigest dist = new TDigest(100, gen);
dist.recordAllData();
List<TDigest> many = Lis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.