language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/cache/interceptor/CacheResolver.java
{ "start": 959, "end": 1322 }
interface ____ { /** * Return the cache(s) to use for the specified invocation. * @param context the context of the particular invocation * @return the cache(s) to use (never {@code null}) * @throws IllegalStateException if cache resolution failed */ Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> context); }
CacheResolver
java
apache__camel
components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/vm/DisruptorVmInOutChainedTimeoutTest.java
{ "start": 1331, "end": 2942 }
class ____ extends AbstractVmTestSupport { @Test void testDisruptorVmInOutChainedTimeout() { StopWatch watch = new StopWatch(); try { template2.requestBody("disruptor-vm:a?timeout=1000", "Hello World"); fail("Should have thrown an exception"); } catch (CamelExecutionException e) { // the chained vm caused the timeout ExchangeTimedOutException cause = assertIsInstanceOf(ExchangeTimedOutException.class, e.getCause()); assertEquals(200, cause.getTimeout()); } long delta = watch.taken(); assertTrue(delta < 1100, "Should be faster than 1 sec, was: " + delta); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("disruptor-vm:b") .to("mock:b") .delay(500) .transform().constant("Bye World"); } }; } @Override protected RouteBuilder createRouteBuilderForSecondContext() { return new RouteBuilder() { @Override public void configure() { errorHandler(noErrorHandler()); from("disruptor-vm:a") .to("mock:a") // this timeout will trigger an exception to occur .to("disruptor-vm:b?timeout=200") .to("mock:a2"); } }; } }
DisruptorVmInOutChainedTimeoutTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/NonUniqueResultException.java
{ "start": 602, "end": 1147 }
class ____ extends HibernateException { private final int resultCount; /** * Constructs a {@code NonUniqueResultException}. * * @param resultCount The number of actual results. */ public NonUniqueResultException(int resultCount) { super( "Query did not return a unique result: " + resultCount + " results were returned" ); this.resultCount = resultCount; } /** * Get the number of actual results. * @return number of actual results */ public int getResultCount() { return this.resultCount; } }
NonUniqueResultException
java
elastic__elasticsearch
x-pack/plugin/profiling/src/main/java/org/elasticsearch/xpack/profiling/persistence/Migration.java
{ "start": 4670, "end": 5487 }
class ____ implements Migration { private final int targetVersion; private final Map<String, ?> body; public PutMappingMigration(int targetVersion, Map<String, ?> body) { this.targetVersion = targetVersion; this.body = body; } @Override public int getTargetIndexTemplateVersion() { return targetVersion; } public void apply(String index, Consumer<PutMappingRequest> mappingConsumer, Consumer<UpdateSettingsRequest> settingsConsumer) { mappingConsumer.accept(new PutMappingRequest(index).source(body)); } @Override public String toString() { return String.format(Locale.ROOT, "put mapping to target version [%d]", targetVersion); } }
PutMappingMigration
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/web/server/TestingServerHttpSecurity.java
{ "start": 838, "end": 1088 }
class ____ extends ServerHttpSecurity { public TestingServerHttpSecurity applicationContext(ApplicationContext applicationContext) throws BeansException { super.setApplicationContext(applicationContext); return this; } }
TestingServerHttpSecurity
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/mapping/UnidirectionalOneToManyOrderColumnTest.java
{ "start": 7566, "end": 7791 }
class ____ { @Id @GeneratedValue long id; String childId; public ChildData() { } public ChildData(String id) { childId = id; } @Override public String toString() { return childId; } } }
ChildData
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/slot/FileSlotAllocationSnapshotPersistenceServiceTest.java
{ "start": 1702, "end": 6377 }
class ____ { @TempDir private File tempDirectory; @Test void loadNoSlotAllocationSnapshotsIfDirectoryIsEmpty() throws IOException { assumeTrue(FileUtils.isEmptyDirectory(tempDirectory)); final FileSlotAllocationSnapshotPersistenceService persistenceService = new FileSlotAllocationSnapshotPersistenceService(tempDirectory); assertThat(persistenceService.loadAllocationSnapshots()).isEmpty(); } @Test void loadPersistedSlotAllocationSnapshots() throws IOException { final FileSlotAllocationSnapshotPersistenceService persistenceService = new FileSlotAllocationSnapshotPersistenceService(tempDirectory); final Collection<SlotAllocationSnapshot> slotAllocationSnapshots = createRandomSlotAllocationSnapshots(3); for (SlotAllocationSnapshot slotAllocationSnapshot : slotAllocationSnapshots) { persistenceService.persistAllocationSnapshot(slotAllocationSnapshot); } final Collection<SlotAllocationSnapshot> loadedSlotAllocationSnapshots = persistenceService.loadAllocationSnapshots(); assertThat(loadedSlotAllocationSnapshots) .containsAll(slotAllocationSnapshots) .usingRecursiveComparison(); } @Test void newInstanceLoadsPersistedSlotAllocationSnapshots() throws IOException { final FileSlotAllocationSnapshotPersistenceService persistenceService = new FileSlotAllocationSnapshotPersistenceService(tempDirectory); final Collection<SlotAllocationSnapshot> slotAllocationSnapshots = createRandomSlotAllocationSnapshots(3); for (SlotAllocationSnapshot slotAllocationSnapshot : slotAllocationSnapshots) { persistenceService.persistAllocationSnapshot(slotAllocationSnapshot); } final FileSlotAllocationSnapshotPersistenceService newPersistenceService = new FileSlotAllocationSnapshotPersistenceService(tempDirectory); final Collection<SlotAllocationSnapshot> loadedSlotAllocationSnapshots = newPersistenceService.loadAllocationSnapshots(); assertThat(loadedSlotAllocationSnapshots) .containsAll(slotAllocationSnapshots) .usingRecursiveComparison(); } @Test void deletePersistedSlotAllocationSnapshot() throws IOException { final FileSlotAllocationSnapshotPersistenceService persistenceService = new FileSlotAllocationSnapshotPersistenceService(tempDirectory); final SlotAllocationSnapshot singleSlotAllocationSnapshot = createSingleSlotAllocationSnapshot(); persistenceService.persistAllocationSnapshot(singleSlotAllocationSnapshot); persistenceService.deleteAllocationSnapshot(singleSlotAllocationSnapshot.getSlotIndex()); assertThat(persistenceService.loadAllocationSnapshots()).isEmpty(); } @Test void deleteCorruptedSlotAllocationSnapshots() throws IOException { final FileSlotAllocationSnapshotPersistenceService persistenceService = new FileSlotAllocationSnapshotPersistenceService(tempDirectory); final SlotAllocationSnapshot singleSlotAllocationSnapshot = createSingleSlotAllocationSnapshot(); persistenceService.persistAllocationSnapshot(singleSlotAllocationSnapshot); final File[] files = tempDirectory.listFiles(); assertThat(files).hasSize(1); final File file = files[0]; // corrupt the file FileUtils.writeByteArrayToFile(file, new byte[] {1, 2, 3, 4}); assertThat(persistenceService.loadAllocationSnapshots()).isEmpty(); assertThat(tempDirectory).isEmptyDirectory(); } @Nonnull private Collection<SlotAllocationSnapshot> createRandomSlotAllocationSnapshots(int number) { final Collection<SlotAllocationSnapshot> result = new ArrayList<>(); final ResourceID resourceId = ResourceID.generate(); for (int slotIndex = 0; slotIndex < number; slotIndex++) { result.add( new SlotAllocationSnapshot( new SlotID(resourceId, slotIndex), new JobID(), "foobar", new AllocationID(), ResourceProfile.UNKNOWN)); } return result; } private SlotAllocationSnapshot createSingleSlotAllocationSnapshot() { return Iterables.getOnlyElement(createRandomSlotAllocationSnapshots(1)); } }
FileSlotAllocationSnapshotPersistenceServiceTest
java
alibaba__nacos
core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/AbstractProtocolNegotiatorBuilderSingleton.java
{ "start": 1306, "end": 3724 }
class ____ implements ProtocolNegotiatorBuilder { /** * Map to store ProtocolNegotiatorBuilders based on their types. */ protected static final Map<String, ProtocolNegotiatorBuilder> BUILDER_MAP = new ConcurrentHashMap<>(); static { try { for (ProtocolNegotiatorBuilder each : NacosServiceLoader.load(ProtocolNegotiatorBuilder.class)) { BUILDER_MAP.put(each.type(), each); Loggers.REMOTE.info("Load ProtocolNegotiatorBuilder {} for type {}", each.getClass().getCanonicalName(), each.type()); } } catch (Exception e) { Loggers.REMOTE.warn("Load ProtocolNegotiatorBuilder failed.", e); } } /** * The property key to retrieve the actual type of ProtocolNegotiatorBuilder. */ protected final String typePropertyKey; /** * The actual type of ProtocolNegotiatorBuilder, retrieved from system properties. */ protected String actualType; /** * Constructs an instance of AbstractProtocolNegotiatorBuilderSingleton with the specified type property key. * * @param typePropertyKey the property key to retrieve the actual type */ public AbstractProtocolNegotiatorBuilderSingleton(String typePropertyKey) { this.typePropertyKey = typePropertyKey; this.actualType = EnvUtil.getProperty(typePropertyKey, defaultBuilderPair().getFirst()); } /** * Builds a ProtocolNegotiator instance based on the actual type. * * @return a ProtocolNegotiator instance */ @Override public NacosGrpcProtocolNegotiator build() { ProtocolNegotiatorBuilder actualBuilder = BUILDER_MAP.get(actualType); if (null == actualBuilder) { Loggers.REMOTE.warn("Not found ProtocolNegotiatorBuilder for type {}, will use default type {}", actualType, defaultBuilderPair().getFirst()); return defaultBuilderPair().getSecond().build(); } return actualBuilder.build(); } /** * Declare default ProtocolNegotiatorBuilders in case loading from SPI fails. * * @return a Pair of String and ProtocolNegotiatorBuilder representing the default builder */ protected abstract Pair<String, ProtocolNegotiatorBuilder> defaultBuilderPair(); }
AbstractProtocolNegotiatorBuilderSingleton
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/common/DefaultConversionContext.java
{ "start": 438, "end": 2740 }
class ____ implements ConversionContext { private final FormattingMessager messager; private final Type sourceType; private final Type targetType; private final FormattingParameters formattingParameters; private final String dateFormat; private final String numberFormat; private final String locale; private final TypeFactory typeFactory; public DefaultConversionContext(TypeFactory typeFactory, FormattingMessager messager, Type sourceType, Type targetType, FormattingParameters formattingParameters) { this.typeFactory = typeFactory; this.messager = messager; this.sourceType = sourceType; this.targetType = targetType; this.formattingParameters = formattingParameters; this.dateFormat = this.formattingParameters.getDate(); this.numberFormat = this.formattingParameters.getNumber(); this.locale = this.formattingParameters.getLocale(); validateDateFormat(); } /** * Validate the dateFormat if it is not null */ private void validateDateFormat() { if ( !Strings.isEmpty( dateFormat ) ) { DateFormatValidator dateFormatValidator = DateFormatValidatorFactory.forTypes( sourceType, targetType ); DateFormatValidationResult validationResult = dateFormatValidator.validate( dateFormat ); if ( !validationResult.isValid() ) { validationResult.printErrorMessage( messager, formattingParameters.getElement(), formattingParameters.getMirror(), formattingParameters.getDateAnnotationValue() ); } } } @Override public Type getTargetType() { return targetType; } @Override public String getNumberFormat() { return numberFormat; } @Override public String getLocale() { return locale != null ? locale.toString() : null; } @Override public String getDateFormat() { return dateFormat; } @Override public TypeFactory getTypeFactory() { return typeFactory; } protected FormattingMessager getMessager() { return messager; } }
DefaultConversionContext
java
quarkusio__quarkus
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/typesafe/fragment/MissingCheckedTemplateFragmentTest.java
{ "start": 572, "end": 1662 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot(root -> root .addClasses(Templates.class, Item.class) .addAsResource(new StringAsset("{#each items}{it.name}{/each}"), "templates/MissingCheckedTemplateFragmentTest/items.html")) .assertException(t -> { Throwable e = t; TemplateException te = null; while (e != null) { if (e instanceof TemplateException) { te = (TemplateException) e; break; } e = e.getCause(); } assertNotNull(te); assertEquals("Fragment [item] not defined in template MissingCheckedTemplateFragmentTest/items.html", te.getMessage()); });; @Test public void test() { fail(); } @CheckedTemplate public static
MissingCheckedTemplateFragmentTest
java
google__gson
gson/src/main/java/com/google/gson/package-info.java
{ "start": 728, "end": 1092 }
class ____ use is {@link com.google.gson.Gson} which can be constructed with {@code * new Gson()} (using default settings) or by using {@link com.google.gson.GsonBuilder} (to * configure various options such as using versioning and so on). * * @author Inderjeet Singh, Joel Leitch */ @com.google.errorprone.annotations.CheckReturnValue package com.google.gson;
to
java
apache__camel
core/camel-core-xml/src/test/java/org/apache/camel/core/xml/AbstractCamelContextFactoryBeanTest.java
{ "start": 2240, "end": 9374 }
class ____ { // any properties (abstract methods in AbstractCamelContextFactoryBean that // return String and receive no arguments) that do not support property // placeholders final Set<String> propertiesThatAreNotPlaceholdered = Collections.singleton("{{getErrorHandlerRef}}"); final TypeConverter typeConverter = new DefaultTypeConverter( new DefaultPackageScanClassResolver(), new Injector() { @Override public <T> T newInstance(Class<T> type) { return newInstance(type, false); } @Override public <T> T newInstance(Class<T> type, String factoryMethod) { return null; } @Override public <T> T newInstance(Class<T> type, Class<?> factoryClass, String factoryMethod) { return null; } @Override public <T> T newInstance(Class<T> type, boolean postProcessBean) { return ObjectHelper.newInstance(type); } @Override public boolean supportsAutoWiring() { return false; } }, false, false); // properties that should return value that can be converted to boolean final Set<String> valuesThatReturnBoolean = new HashSet<>( asList("{{getStreamCache}}", "{{getDebug}}", "{{getTrace}}", "{{getBacklogTrace}}", "{{getMessageHistory}}", "{{getLogMask}}", "{{getLogExhaustedMessageBody}}", "{{getCaseInsensitiveHeaders}}", "{{getAutoStartup}}", "{{getDumpRoutes}}", "{{getUseMDCLogging}}", "{{getUseDataType}}", "{{getUseBreadcrumb}}", "{{getBeanPostProcessorEnabled}}", "{{getAllowUseOriginalMessage}}", "{{getLoadTypeConverters}}", "{{getTypeConverterStatisticsEnabled}}", "{{getInflightRepositoryBrowseEnabled}}")); // properties that should return value that can be converted to long final Set<String> valuesThatReturnLong = new HashSet<>(List.of("{{getDelayer}}")); public AbstractCamelContextFactoryBeanTest() { ((Service) typeConverter).start(); } @Test public void shouldSupportPropertyPlaceholdersOnAllProperties() throws Exception { final DefaultCamelContext context = mock(DefaultCamelContext.class); final ExtendedCamelContext extendedCamelContext = mock(ExtendedCamelContext.class); when(context.getCamelContextExtension()).thenReturn(extendedCamelContext); // program the property resolution in context mock when(context.resolvePropertyPlaceholders(anyString())).thenAnswer(invocation -> { final String placeholder = invocation.getArgument(0); // we receive the argument and check if the method should return a // value that can be converted to boolean if (valuesThatReturnBoolean.contains(placeholder) || placeholder.endsWith("Enabled}}")) { return "true"; } // or long if (valuesThatReturnLong.contains(placeholder)) { return "1"; } // else is just plain string return "string"; }); when(context.getTypeConverter()).thenReturn(typeConverter); when(context.getRuntimeEndpointRegistry()).thenReturn(mock(RuntimeEndpointRegistry.class)); when(context.getManagementNameStrategy()).thenReturn(mock(ManagementNameStrategy.class)); when(context.getExecutorServiceManager()).thenReturn(mock(ExecutorServiceManager.class)); when(context.getInflightRepository()).thenReturn(mock(InflightRepository.class)); when(context.getCamelContextExtension().getContextPlugin(CamelBeanPostProcessor.class)) .thenReturn(mock(CamelBeanPostProcessor.class)); @SuppressWarnings("unchecked") final AbstractCamelContextFactoryBean<ModelCamelContext> factory = mock(AbstractCamelContextFactoryBean.class); when(factory.getContext()).thenReturn(context); doCallRealMethod().when(factory).initCamelContext(context); final Set<String> expectedPropertiesToBeResolved = propertiesToBeResolved(factory); // method under test factory.initCamelContext(context); // we want to capture the arguments initCamelContext tried to resolve // and check if it tried to resolve all placeholders we expected final ArgumentCaptor<String> capturedPlaceholders = ArgumentCaptor.forClass(String.class); verify(context, atLeastOnce()).resolvePropertyPlaceholders(capturedPlaceholders.capture()); // removes any properties that are not using property placeholders expectedPropertiesToBeResolved.removeAll(propertiesThatAreNotPlaceholdered); assertThat(capturedPlaceholders.getAllValues()) .as("The expectation is that all abstract getter methods that return Strings should support property " + "placeholders, and that for those will delegate to CamelContext::resolvePropertyPlaceholders, " + "we captured all placeholders that tried to resolve and found differences") .containsAll(expectedPropertiesToBeResolved); } Set<String> propertiesToBeResolved(final AbstractCamelContextFactoryBean<ModelCamelContext> factory) { final Set<String> expectedPropertiesToBeResolved = new HashSet<>(); // looks at all abstract methods in AbstractCamelContextFactoryBean that // do have no declared parameters and programs the mock to return // "{{methodName}}" on calling that method, this happens when // AbstractCamelContextFactoryBean::initContext invokes the programmed // mock, so the returned collection will be empty until initContext // invokes the mocked method stream(AbstractCamelContextFactoryBean.class.getDeclaredMethods()) .filter(m -> Modifier.isAbstract(m.getModifiers()) && m.getParameterCount() == 0).forEach(m -> { try { when(m.invoke(factory)).thenAnswer(invocation -> { final Method method = invocation.getMethod(); final String name = method.getName(); if (String.class.equals(method.getReturnType())) { final String placeholder = "{{" + name + "}}"; expectedPropertiesToBeResolved.add(placeholder); return placeholder; } return null; }); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ignored) { // ignored } }); return expectedPropertiesToBeResolved; } }
AbstractCamelContextFactoryBeanTest
java
apache__camel
components/camel-netty/src/test/java/org/apache/camel/component/netty/BaseNettyTest.java
{ "start": 1440, "end": 3728 }
class ____ extends CamelTestSupport { private static final Logger LOG = LoggerFactory.getLogger(BaseNettyTest.class); @RegisterExtension protected AvailablePortFinder.Port port = AvailablePortFinder.find(); @BeforeAll public static void startLeakDetection() { System.setProperty("io.netty.leakDetection.maxRecords", "100"); System.setProperty("io.netty.leakDetection.acquireAndReleaseOnly", "true"); System.setProperty("io.netty.leakDetection.targetRecords", "100"); LogCaptureAppender.reset(); } @AfterAll public static void verifyNoLeaks() { // Force GC to bring up leaks System.gc(); // Kick leak detection logging ByteBufAllocator.DEFAULT.buffer(1).release(); Collection<LogEvent> events = LogCaptureAppender.getEvents(ResourceLeakDetector.class); if (!events.isEmpty()) { String message = "Leaks detected while running tests: " + events; // Just write the message into log to help debug for (LogEvent event : events) { LOG.info(event.getMessage().toString()); } throw new AssertionError(message); } } @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); context.getPropertiesComponent().setLocation("ref:prop"); return context; } @BindToRegistry("prop") public Properties loadProperties() { Properties prop = new Properties(); prop.setProperty("port", Integer.toString(getPort())); return prop; } protected int getPort() { return port.getPort(); } protected String byteArrayToHex(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02x", b & 0xff)); } return sb.toString(); } protected byte[] fromHexString(String hexstr) { byte data[] = new byte[hexstr.length() / 2]; int i = 0; for (int n = hexstr.length(); i < n; i += 2) { data[i / 2] = (Integer.decode("0x" + hexstr.charAt(i) + hexstr.charAt(i + 1))).byteValue(); } return data; } }
BaseNettyTest
java
apache__dubbo
dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java
{ "start": 1254, "end": 1900 }
class ____ extends AbstractMetadataReportFactory { private ZookeeperClientManager zookeeperClientManager; public ZookeeperMetadataReportFactory(ApplicationModel applicationModel) { this.zookeeperClientManager = ZookeeperClientManager.getInstance(applicationModel); } @DisableInject public void setZookeeperTransporter(ZookeeperClientManager zookeeperClientManager) { this.zookeeperClientManager = zookeeperClientManager; } @Override public MetadataReport createMetadataReport(URL url) { return new ZookeeperMetadataReport(url, zookeeperClientManager); } }
ZookeeperMetadataReportFactory
java
apache__camel
components/camel-microprofile/camel-microprofile-health/src/main/java/org/apache/camel/microprofile/health/CamelMicroProfileHealthHelper.java
{ "start": 1107, "end": 1155 }
class ____ MicroProfile health checks. */ final
for
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingNonUpdateableTest.java
{ "start": 1445, "end": 1612 }
class ____ { @Id @GeneratedValue( strategy = GenerationType.AUTO ) long id; @Version long version; @Column( updatable = false ) String special; } }
Thing
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/type/BaseTypeHandler.java
{ "start": 1027, "end": 1346 }
class ____ call the {@link ResultSet#wasNull()} and {@link CallableStatement#wasNull()} * method for handling the SQL {@code NULL} value. In other words, {@code null} value handling should be performed on * subclass. * * @author Clinton Begin * @author Simone Tripodi * @author Kzuki Shimizu */ public abstract
never
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/TopLongFloatAggregator.java
{ "start": 3147, "end": 4384 }
class ____ implements GroupingAggregatorState { private final LongFloatBucketedSort sort; private GroupingState(BigArrays bigArrays, int limit, boolean ascending) { this.sort = new LongFloatBucketedSort(bigArrays, ascending ? SortOrder.ASC : SortOrder.DESC, limit); } public void add(int groupId, long value, float outputValue) { sort.collect(value, outputValue, groupId); } @Override public void toIntermediate(Block[] blocks, int offset, IntVector selected, DriverContext driverContext) { sort.toBlocks(driverContext.blockFactory(), blocks, offset, selected); } Block toBlock(BlockFactory blockFactory, IntVector selected) { Block[] blocks = new Block[2]; sort.toBlocks(blockFactory, blocks, 0, selected); Releasables.close(blocks[0]); return blocks[1]; } @Override public void enableGroupIdTracking(SeenGroupIds seen) { // we figure out seen values from nulls on the values block } @Override public void close() { Releasables.closeExpectNoException(sort); } } public static
GroupingState
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/introspect/POJOPropertyBuilder.java
{ "start": 54084, "end": 58182 }
class ____<T> { public final T value; public final Linked<T> next; public final PropertyName name; public final boolean isNameExplicit; public final boolean isVisible; public final boolean isMarkedIgnored; public Linked(T v, Linked<T> n, PropertyName name, boolean explName, boolean visible, boolean ignored) { value = v; next = n; // ensure that we'll never have missing names this.name = (name == null || name.isEmpty()) ? null : name; if (explName) { if (this.name == null) { // sanity check to catch internal problems throw new IllegalArgumentException("Cannot pass true for 'explName' if name is null/empty"); } // 03-Apr-2014, tatu: But how about name-space only override? // Probably should not be explicit? Or, need to merge somehow? if (!name.hasSimpleName()) { explName = false; } } isNameExplicit = explName; isVisible = visible; isMarkedIgnored = ignored; } public Linked<T> withoutNext() { if (next == null) { return this; } return new Linked<T>(value, null, name, isNameExplicit, isVisible, isMarkedIgnored); } public Linked<T> withValue(T newValue) { if (newValue == value) { return this; } return new Linked<T>(newValue, next, name, isNameExplicit, isVisible, isMarkedIgnored); } public Linked<T> withNext(Linked<T> newNext) { if (newNext == next) { return this; } return new Linked<T>(value, newNext, name, isNameExplicit, isVisible, isMarkedIgnored); } public Linked<T> withoutIgnored() { if (isMarkedIgnored) { return (next == null) ? null : next.withoutIgnored(); } if (next != null) { Linked<T> newNext = next.withoutIgnored(); if (newNext != next) { return withNext(newNext); } } return this; } public Linked<T> withoutNonVisible() { Linked<T> newNext = (next == null) ? null : next.withoutNonVisible(); return isVisible ? withNext(newNext) : newNext; } /** * Method called to append given node(s) at the end of this * node chain. */ protected Linked<T> append(Linked<T> appendable) { if (next == null) { return withNext(appendable); } return withNext(next.append(appendable)); } public Linked<T> trimByVisibility() { if (next == null) { return this; } Linked<T> newNext = next.trimByVisibility(); if (name != null) { // this already has highest; how about next one? if (newNext.name == null) { // next one not, drop it return withNext(null); } // both have it, keep return withNext(newNext); } if (newNext.name != null) { // next one has higher, return it... return newNext; } // neither has explicit name; how about visibility? if (isVisible == newNext.isVisible) { // same; keep both in current order return withNext(newNext); } return isVisible ? withNext(null) : newNext; } @Override public String toString() { String msg = String.format("%s[visible=%b,ignore=%b,explicitName=%b]", value.toString(), isVisible, isMarkedIgnored, isNameExplicit); if (next != null) { msg = msg + ", "+next.toString(); } return msg; } } }
Linked
java
apache__camel
components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/OffsetCacheTest.java
{ "start": 1612, "end": 5718 }
class ____ { private final OffsetCache offsetCache = new OffsetCache(); @Order(1) @Test @DisplayName("Tests whether the cache can record offset a single offset") void updateOffsetsSinglePartition() { final TopicPartition topic1 = new TopicPartition("topic1", 1); assertDoesNotThrow(() -> offsetCache.recordOffset(topic1, 1)); assertDoesNotThrow(() -> offsetCache.recordOffset(topic1, 2)); assertDoesNotThrow(() -> offsetCache.recordOffset(topic1, 2), "The cache should not throw exceptions for duplicate records"); } @Order(2) @Test @DisplayName("Tests whether the cache can retrieve offset information") void getOffset() { final TopicPartition topic1 = new TopicPartition("topic1", 1); assertTrue(offsetCache.contains(topic1)); assertEquals(2, offsetCache.getOffset(topic1)); assertEquals(1, offsetCache.cacheSize()); } @Order(3) @Test @DisplayName("Tests whether the cache records and updates multiple offsets to be committed") void updateOffsetsMultiplePartitionsSameTopic() { final TopicPartition topic11 = new TopicPartition("topic1", 1); final TopicPartition topic12 = new TopicPartition("topic1", 2); final TopicPartition topic13 = new TopicPartition("topic1", 3); assertDoesNotThrow(() -> offsetCache.recordOffset(topic11, 1)); assertDoesNotThrow(() -> offsetCache.recordOffset(topic11, 2)); assertDoesNotThrow(() -> offsetCache.recordOffset(topic11, 2), "The cache should not throw exceptions for duplicate records"); assertDoesNotThrow(() -> offsetCache.recordOffset(topic12, 1)); assertDoesNotThrow(() -> offsetCache.recordOffset(topic12, 2)); assertDoesNotThrow(() -> offsetCache.recordOffset(topic12, 2), "The cache should not throw exceptions for duplicate records"); assertDoesNotThrow(() -> offsetCache.recordOffset(topic13, 3)); assertDoesNotThrow(() -> offsetCache.recordOffset(topic13, 4)); assertDoesNotThrow(() -> offsetCache.recordOffset(topic13, 5), "The cache should not throw exceptions for duplicate records"); assertTrue(offsetCache.contains(topic11), "The cache should contain an entry for the topic1 on partition 1"); assertTrue(offsetCache.contains(topic12), "The cache should contain an entry for the topic1 on partition 2"); assertTrue(offsetCache.contains(topic13), "The cache should contain an entry for the topic1 on partition 3"); assertEquals(2, offsetCache.getOffset(topic11)); assertEquals(2, offsetCache.getOffset(topic12)); assertEquals(5, offsetCache.getOffset(topic13)); assertEquals(3, offsetCache.cacheSize()); } @Order(4) @Test @DisplayName("Tests whether the cache removes committed offsets") void removeCommittedEntries() { final TopicPartition topic11 = new TopicPartition("topic1", 1); final TopicPartition topic12 = new TopicPartition("topic1", 2); final TopicPartition topic13 = new TopicPartition("topic1", 3); final Map<TopicPartition, OffsetAndMetadata> offsets = Collections.singletonMap(topic12, new OffsetAndMetadata(3)); offsetCache.removeCommittedEntries(offsets, null); assertEquals(2, offsetCache.getOffset(topic11)); assertNull(offsetCache.getOffset(topic12)); assertEquals(5, offsetCache.getOffset(topic13)); assertEquals(2, offsetCache.cacheSize()); } @Order(5) @Test @DisplayName("Tests whether the cache retains offsets if the consumer fails to commit") void removeRetainCommittedEntries() { final TopicPartition topic13 = new TopicPartition("topic1", 3); final Map<TopicPartition, OffsetAndMetadata> offsets = Collections.singletonMap(topic13, new OffsetAndMetadata(3)); assertDoesNotThrow(() -> offsetCache.removeCommittedEntries(offsets, new Exception("Fake exception"))); assertEquals(2, offsetCache.cacheSize()); } }
OffsetCacheTest
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/util/ParallelSorter.java
{ "start": 6401, "end": 6475 }
interface ____ { int compare(int i, int j); } static
Comparer
java
apache__hadoop
hadoop-tools/hadoop-archives/src/main/java/org/apache/hadoop/tools/HadoopArchives.java
{ "start": 14724, "end": 14829 }
class ____ keeps * track of status of a path * and there children if path is a dir */ static
that
java
apache__camel
dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/CodeRestGenerator.java
{ "start": 2220, "end": 2509 }
class ____ implements Iterable<String> { public OpenApiVersionCompletionCandidates() { } @Override public Iterator<String> iterator() { return List.of("3.0", "3.1").iterator(); } } public static
OpenApiVersionCompletionCandidates
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/commit/ITestAbfsManifestStoreOperations.java
{ "start": 2321, "end": 3816 }
class ____ extends AbstractManifestCommitterTest { private static final Logger LOG = LoggerFactory.getLogger(ITestAbfsManifestStoreOperations.class); private final ABFSContractTestBinding binding; public ITestAbfsManifestStoreOperations() throws Exception { binding = new ABFSContractTestBinding(); } @BeforeEach @Override public void setup() throws Exception { binding.setup(); super.setup(); // skip tests on non-HNS stores assumeThat(getFileSystem().hasPathCapability(getContract().getTestPath(), ETAGS_PRESERVED_IN_RENAME)).as("Resilient rename not available") .isTrue(); } @Override protected Configuration createConfiguration() { return enableManifestCommitter(prepareTestConfiguration(binding)); } @Override protected AbstractFSContract createContract(final Configuration conf) { return new AbfsFileSystemContract(conf, binding.isSecureMode()); } /** * basic consistency across operations, as well as being non-empty. */ @Test public void testEtagConsistencyAcrossListAndHead() throws Throwable { describe("Etag values must be non-empty and consistent across LIST and HEAD Calls."); final Path path = methodPath(); final FileSystem fs = getFileSystem(); ContractTestUtils.touch(fs, path); final ManifestStoreOperations operations = createManifestStoreOperations(); Assertions.assertThat(operations) .describedAs("Store operations
ITestAbfsManifestStoreOperations
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestStateAlignmentContextWithHA.java
{ "start": 2444, "end": 3106 }
class ____ { public static final Logger LOG = LoggerFactory.getLogger(TestStateAlignmentContextWithHA.class.getName()); private static final int NUMDATANODES = 1; private static final int NUMCLIENTS = 10; private static final int NUMFILES = 120; private static final Configuration CONF = new HdfsConfiguration(); private static final List<ClientGSIContext> AC_LIST = new ArrayList<>(); private static MiniQJMHACluster qjmhaCluster; private static MiniDFSCluster cluster; private static List<Worker> clients; private DistributedFileSystem dfs; private int active = 0; private int standby = 1; static
TestStateAlignmentContextWithHA
java
dropwizard__dropwizard
dropwizard-jersey/src/main/java/io/dropwizard/jersey/validation/FuzzyEnumParamConverter.java
{ "start": 710, "end": 1003 }
enum ____ used as resource parameters that provide better error handling. If an * invalid value is provided for the parameter a {@code 400 Bad Request} is returned and the error message will * include the parameter name and a list of valid values.</p> * * @since 2.0 */ @Provider public
types
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/TableEnvironment.java
{ "start": 31740, "end": 32844 }
class ____ of UDF to be registered. * @param resourceUris The list of udf resource uris in local or remote. */ void createTemporarySystemFunction( String name, String className, List<ResourceUri> resourceUris); /** * Creates a temporary system function using a {@link FunctionDescriptor} to describe the * function. * * <p>Temporary functions can shadow permanent ones. If a permanent function under a given name * exists, it will be inaccessible in the current session. To make the permanent function * available again one can drop the corresponding temporary system function. * * @param name The name under which the function will be registered globally. * @param functionDescriptor The descriptor of the function to create. */ void createTemporarySystemFunction(String name, FunctionDescriptor functionDescriptor); /** * Drops a catalog function registered in the given path. * * @param path The path under which the function has been registered. See also the {@link * TableEnvironment}
name
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/HamletSpec.java
{ "start": 3128, "end": 3751 }
enum ____ { /** * */ alternate, /** * */ stylesheet, /** * */ start, /** * */ next, /** * */ prev, /** * */ contents, /** * */ index, /** * */ glossary, /** * */ copyright, /** * */ chapter, /** * */ section, /** * */ subsection, /** * */ appendix, /** * */ help, /** * */ bookmark }; /** Values for form methods (case-insensitive) */ public
LinkType
java
quarkusio__quarkus
independent-projects/qute/core/src/main/java/io/quarkus/qute/TemplateEnum.java
{ "start": 720, "end": 931 }
enum ____ declares the {@link TemplateData} annotation or is specified by any {@link TemplateData#target()} then the * {@link TemplateEnum} annotation is ignored. * <p> * {@link TemplateEnum} declared on non-
also
java
elastic__elasticsearch
test/framework/src/test/java/org/elasticsearch/test/test/LoggingListenerTests.java
{ "start": 15847, "end": 16003 }
class ____ an invalid {@link TestIssueLogging} annotation. */ @TestIssueLogging(value = "abc", issueUrl = "https://example.com") public static
with
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FsMergingCheckpointStorageAccess.java
{ "start": 1527, "end": 5015 }
class ____ extends FsCheckpointStorageAccess implements Closeable { /** FileMergingSnapshotManager manages files and meta information for checkpoints. */ private final FileMergingSnapshotManager fileMergingSnapshotManager; /** The identity of subtask. */ private final FileMergingSnapshotManager.SubtaskKey subtaskKey; public FsMergingCheckpointStorageAccess( Path checkpointBaseDirectory, @Nullable Path defaultSavepointDirectory, JobID jobId, int fileSizeThreshold, int writeBufferSize, FileMergingSnapshotManager fileMergingSnapshotManager, Environment environment) throws IOException { super( // Multiple subtask/threads would share one output stream, // SafetyNetWrapperFileSystem cannot be used to prevent different threads from // interfering with each other when exiting. FileSystem.getUnguardedFileSystem(checkpointBaseDirectory.toUri()), checkpointBaseDirectory, defaultSavepointDirectory, false, jobId, fileSizeThreshold, writeBufferSize); this.fileMergingSnapshotManager = fileMergingSnapshotManager; this.subtaskKey = SubtaskKey.of(environment); } @Override public void initializeBaseLocationsForCheckpoint() throws IOException { super.initializeBaseLocationsForCheckpoint(); fileMergingSnapshotManager.initFileSystem( fileSystem, checkpointsDirectory, sharedStateDirectory, taskOwnedStateDirectory, writeBufferSize); fileMergingSnapshotManager.registerSubtaskForSharedStates(subtaskKey); } @Override public CheckpointStreamFactory resolveCheckpointStorageLocation( long checkpointId, CheckpointStorageLocationReference reference) throws IOException { if (reference.isDefaultReference()) { // default reference, construct the default location for that particular checkpoint final Path checkpointDir = createCheckpointDirectory(checkpointsDirectory, checkpointId); return new FsMergingCheckpointStorageLocation( subtaskKey, fileSystem, checkpointDir, sharedStateDirectory, taskOwnedStateDirectory, reference, fileSizeThreshold, writeBufferSize, fileMergingSnapshotManager, checkpointId); } else { // location encoded in the reference final Path path = decodePathFromReference(reference); return new FsMergingCheckpointStorageLocation( subtaskKey, path.getFileSystem(), path, path, path, reference, fileSizeThreshold, writeBufferSize, fileMergingSnapshotManager, checkpointId); } } /** This will be registered to resource closer of {@code StreamTask}. */ @Override public void close() { fileMergingSnapshotManager.unregisterSubtask(subtaskKey); } }
FsMergingCheckpointStorageAccess
java
spring-projects__spring-boot
module/spring-boot-health/src/test/java/org/springframework/boot/health/autoconfigure/contributor/CompositeReactiveHealthContributorConfigurationTests.java
{ "start": 1317, "end": 1937 }
class ____ extends AbstractCompositeHealthContributorConfigurationTests<ReactiveHealthContributor, TestReactiveHealthIndicator> { @Override protected AbstractCompositeHealthContributorConfiguration<ReactiveHealthContributor, TestReactiveHealthIndicator, TestBean> newComposite() { return new TestCompositeReactiveHealthContributorConfiguration(); } @Override protected Stream<String> allNamesFromComposite(ReactiveHealthContributor composite) { return ((ReactiveHealthContributors) composite).stream().map(ReactiveHealthContributors.Entry::name); } static
CompositeReactiveHealthContributorConfigurationTests
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/math/ExpUnsignedLongEvaluator.java
{ "start": 3982, "end": 4572 }
class ____ implements EvalOperator.ExpressionEvaluator.Factory { private final Source source; private final EvalOperator.ExpressionEvaluator.Factory val; public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory val) { this.source = source; this.val = val; } @Override public ExpUnsignedLongEvaluator get(DriverContext context) { return new ExpUnsignedLongEvaluator(source, val.get(context), context); } @Override public String toString() { return "ExpUnsignedLongEvaluator[" + "val=" + val + "]"; } } }
Factory
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/body/ResetOffsetBodyForC.java
{ "start": 1014, "end": 1326 }
class ____ extends RemotingSerializable { private List<MessageQueueForC> offsetTable; public List<MessageQueueForC> getOffsetTable() { return offsetTable; } public void setOffsetTable(List<MessageQueueForC> offsetTable) { this.offsetTable = offsetTable; } }
ResetOffsetBodyForC
java
alibaba__nacos
naming/src/main/java/com/alibaba/nacos/naming/controllers/ClusterController.java
{ "start": 2223, "end": 4139 }
class ____ { private final ClusterOperatorV2Impl clusterOperatorV2; public ClusterController(ClusterOperatorV2Impl clusterOperatorV2) { this.clusterOperatorV2 = clusterOperatorV2; } /** * Update cluster. * * @param request http request * @return 'ok' if success * @throws Exception if failed */ @PutMapping @Secured(action = ActionTypes.WRITE) @Compatibility(apiType = ApiType.CONSOLE_API, alternatives = "PUT ${contextPath:nacos}/v3/console/ns/service/cluster") public String update(HttpServletRequest request) throws Exception { final String namespaceId = WebUtils .optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID); final String clusterName = WebUtils.required(request, CommonParams.CLUSTER_NAME); final String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME); ClusterMetadata clusterMetadata = new ClusterMetadata(); clusterMetadata.setHealthyCheckPort(NumberUtils.toInt(WebUtils.required(request, "checkPort"))); clusterMetadata.setUseInstancePortForCheck( ConvertUtils.toBoolean(WebUtils.required(request, "useInstancePort4Check"))); AbstractHealthChecker healthChecker = HealthCheckerFactory .deserialize(WebUtils.required(request, "healthChecker")); clusterMetadata.setHealthChecker(healthChecker); clusterMetadata.setHealthyCheckType(healthChecker.getType()); clusterMetadata.setExtendData( UtilsAndCommons.parseMetadata(WebUtils.optional(request, "metadata", StringUtils.EMPTY))); judgeClusterOperator().updateClusterMetadata(namespaceId, serviceName, clusterName, clusterMetadata); return "ok"; } private ClusterOperator judgeClusterOperator() { return clusterOperatorV2; } }
ClusterController
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/PgEventEndpointBuilderFactory.java
{ "start": 1603, "end": 2797 }
interface ____ extends EndpointConsumerBuilder { default AdvancedPgEventEndpointConsumerBuilder advanced() { return (AdvancedPgEventEndpointConsumerBuilder) this; } /** * Password for login. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param pass the value to set * @return the dsl builder */ default PgEventEndpointConsumerBuilder pass(String pass) { doSetProperty("pass", pass); return this; } /** * Username for login. * * The option is a: <code>java.lang.String</code> type. * * Default: postgres * Group: security * * @param user the value to set * @return the dsl builder */ default PgEventEndpointConsumerBuilder user(String user) { doSetProperty("user", user); return this; } } /** * Advanced builder for endpoint consumers for the PostgresSQL Event component. */ public
PgEventEndpointConsumerBuilder
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/binding/SubcomponentDeclaration.java
{ "start": 2241, "end": 3629 }
class ____ { private final KeyFactory keyFactory; private final DaggerSuperficialValidation superficialValidation; @Inject Factory(KeyFactory keyFactory, DaggerSuperficialValidation superficialValidation) { this.keyFactory = keyFactory; this.superficialValidation = superficialValidation; } ImmutableSet<SubcomponentDeclaration> forModule(XTypeElement module) { ModuleAnnotation moduleAnnotation = ModuleAnnotation.moduleAnnotation(module, superficialValidation).get(); XElement subcomponentAttribute = moduleAnnotation.annotation().getType().getTypeElement().getDeclaredMethods().stream() .filter(method -> getSimpleName(method).contentEquals("subcomponents")) .collect(toOptional()) .get(); ImmutableSet.Builder<SubcomponentDeclaration> declarations = ImmutableSet.builder(); for (XTypeElement subcomponent : moduleAnnotation.subcomponents()) { declarations.add( new AutoValue_SubcomponentDeclaration( Optional.of(subcomponentAttribute), Optional.of(module), keyFactory.forSubcomponentCreator( getSubcomponentCreator(subcomponent).get().getType()), subcomponent, moduleAnnotation)); } return declarations.build(); } } }
Factory
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cascade/circle/Transport.java
{ "start": 149, "end": 2274 }
class ____ { // @Id // @SequenceGenerator(name="TRANSPORT_SEQ", sequenceName="TRANSPORT_SEQ", initialValue=1, allocationSize=1) // @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="TRANSPORT_SEQ") private Long transportID; private long version; private String name; /** node value object at which the order is picked up */ // @ManyToOne(optional=false, cascade={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, fetch=FetchType.EAGER) // @JoinColumn(name="PICKUPNODEID", /*nullable=false,*/insertable=true, updatable=true) private Node pickupNode = null; /** node value object at which the order is delivered */ // @ManyToOne(optional=false, cascade={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, fetch=FetchType.EAGER) // @JoinColumn(name="DELIVERYNODEID", /*nullable=false,*/ insertable=true, updatable=true) private Node deliveryNode = null; private Vehicle vehicle; // @Transient private String transientField = "transport original value"; public Node getDeliveryNode() { return deliveryNode; } public void setDeliveryNode(Node deliveryNode) { this.deliveryNode = deliveryNode; } public Node getPickupNode() { return pickupNode; } protected void setTransportID(Long transportID) { this.transportID = transportID; } public void setPickupNode(Node pickupNode) { this.pickupNode = pickupNode; } public Vehicle getVehicle() { return vehicle; } public void setVehicle(Vehicle vehicle) { this.vehicle = vehicle; } public Long getTransportID() { return transportID; } public long getVersion() { return version; } protected void setVersion(long version) { this.version = version; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(name + " id: " + transportID + "\n"); return buffer.toString(); } public String getTransientField() { return transientField; } public void setTransientField(String transientField) { this.transientField = transientField; } }
Transport
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/event/command/CommandBaseEvent.java
{ "start": 218, "end": 1104 }
class ____ { private final RedisCommand<Object, Object, Object> command; private final Map<String, Object> context; protected CommandBaseEvent(RedisCommand<Object, Object, Object> command, Map<String, Object> context) { this.command = command; this.context = context; } /** * @return the actual command. */ public RedisCommand<Object, Object, Object> getCommand() { return command; } /** * @return shared context. */ public Map<String, Object> getContext() { return context; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); sb.append(" [command=").append(command); sb.append(", context=").append(context); sb.append(']'); return sb.toString(); } }
CommandBaseEvent
java
google__guava
android/guava/src/com/google/common/collect/LinkedListMultimap.java
{ "start": 4865, "end": 5393 }
class ____<K extends @Nullable Object, V extends @Nullable Object> extends SimpleEntry<K, V> { @Nullable Node<K, V> next; // the next node (with any key) @Weak @Nullable Node<K, V> previous; // the previous node (with any key) @Nullable Node<K, V> nextSibling; // the next node with the same key @Weak @Nullable Node<K, V> previousSibling; // the previous node with the same key Node(@ParametricNullness K key, @ParametricNullness V value) { super(key, value); } } private static final
Node
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/lazyload/AtomikosJtaLazyLoadingTest.java
{ "start": 1895, "end": 3189 }
class ____ { private static final int CHILDREN_SIZE = 3; private Long parentID; private Long lastChildID; @BeforeEach public void prepareTest(SessionFactoryScope scope) throws Exception { scope.inTransaction( session -> { Parent p = new Parent(); for ( int i = 0; i < CHILDREN_SIZE; i++ ) { final Child child = new Child(p); session.persist( child ); lastChildID = child.getId(); } session.persist( p ); parentID = p.getId(); } ); } @Test @JiraKey(value = "HHH-7971") public void testLazyCollectionLoadingAfterEndTransaction(SessionFactoryScope scope) { Parent loadedParent = scope.fromTransaction( session -> session.getReference( Parent.class, parentID ) ); assertFalse( Hibernate.isInitialized( loadedParent.getChildren() ) ); int i = 0; for ( Child child : loadedParent.getChildren() ) { i++; assertNotNull( child ); } assertEquals( CHILDREN_SIZE, i ); Child loadedChild = scope.fromTransaction( session -> session.getReference( Child.class, lastChildID ) ); Parent p = loadedChild.getParent(); int j = 0; for ( Child child : p.getChildren() ) { j++; assertNotNull( child ); } assertEquals( CHILDREN_SIZE, j ); } @Entity(name = "Parent") public static
AtomikosJtaLazyLoadingTest
java
apache__camel
components/camel-jaxb/src/test/java/org/apache/camel/example/DataFormatTest.java
{ "start": 1289, "end": 3482 }
class ____ extends CamelTestSupport { private MockEndpoint resultEndpoint; @Override public void doPostSetup() throws Exception { resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class); } @Test public void testMarshalThenUnmarshalBean() throws Exception { PurchaseOrder bean = new PurchaseOrder(); bean.setName("Beer"); bean.setAmount(23); bean.setPrice(2.5); resultEndpoint.expectedBodiesReceived(bean); template.sendBody("direct:start", bean); resultEndpoint.assertIsSatisfied(); } @Test public void testMarshalPrettyPrint() throws Exception { PersonType person = new PersonType(); person.setFirstName("Willem"); person.setLastName("Jiang"); resultEndpoint.expectedMessageCount(1); template.sendBody("direct:prettyPrint", person); resultEndpoint.assertIsSatisfied(); Exchange exchange = resultEndpoint.getExchanges().get(0); String result = exchange.getIn().getBody(String.class); assertNotNull("The result should not be null", result); int indexPerson = result.indexOf("<Person>"); int indexFirstName = result.indexOf("<firstName>"); assertTrue(indexPerson > 0, "we should find the <Person>"); assertTrue(indexFirstName > 0, "we should find the <firstName>"); assertTrue(indexFirstName - indexPerson > 8, "There should some sapce between <Person> and <firstName>"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { JaxbDataFormat example = new JaxbDataFormat("org.apache.camel.example"); JaxbDataFormat person = new JaxbDataFormat("org.apache.camel.foo.bar"); person.setPrettyPrint(true); from("direct:start").marshal(example).to("direct:marshalled"); from("direct:marshalled").unmarshal().jaxb("org.apache.camel.example").to("mock:result"); from("direct:prettyPrint").marshal(person).to("mock:result"); } }; } }
DataFormatTest
java
google__truth
extensions/liteproto/src/test/java/com/google/common/truth/extensions/proto/LiteProtoSubjectTest.java
{ "start": 2454, "end": 11870 }
class ____ { abstract Builder setNonEmptyMessage(MessageLite messageLite); abstract Builder setEquivalentNonEmptyMessage(MessageLite messageLite); abstract Builder setNonEmptyMessageOfOtherValue(MessageLite messageLite); abstract Builder setNonEmptyMessageOfOtherType(MessageLite messageLite); abstract Builder setDefaultInstance(MessageLite messageLite); abstract Builder setDefaultInstanceOfOtherType(MessageLite messageLite); abstract Builder setMessageWithoutRequiredFields(MessageLite messageLite); abstract Config build(); } } @Parameters(name = "{0}") public static Collection<Object[]> data() { // Missing a required_int field. TestMessageLite2WithRequiredFields withoutRequiredFields = TestMessageLite2WithRequiredFields.newBuilder().setOptionalString("foo").buildPartial(); Config proto2Config = Config.newBuilder() .setNonEmptyMessage(TestMessageLite2.newBuilder().setOptionalInt(3).build()) .setEquivalentNonEmptyMessage(TestMessageLite2.newBuilder().setOptionalInt(3).build()) .setNonEmptyMessageOfOtherValue( TestMessageLite2.newBuilder() .setOptionalInt(3) .setSubMessage( TestMessageLite2.SubMessage.newBuilder().setOptionalString("foo")) .build()) .setNonEmptyMessageOfOtherType( OtherTestMessageLite2.newBuilder().setOptionalInt(3).build()) .setDefaultInstance(TestMessageLite2.newBuilder().buildPartial()) .setDefaultInstanceOfOtherType(OtherTestMessageLite2.newBuilder().buildPartial()) .setMessageWithoutRequiredFields(withoutRequiredFields) .build(); Config proto3Config = Config.newBuilder() .setNonEmptyMessage(TestMessageLite3.newBuilder().setOptionalInt(3).build()) .setEquivalentNonEmptyMessage(TestMessageLite3.newBuilder().setOptionalInt(3).build()) .setNonEmptyMessageOfOtherValue( TestMessageLite3.newBuilder() .setOptionalInt(3) .setSubMessage( TestMessageLite3.SubMessage.newBuilder().setOptionalString("foo")) .build()) .setNonEmptyMessageOfOtherType( OtherTestMessageLite3.newBuilder().setOptionalInt(3).build()) .setDefaultInstance(TestMessageLite3.newBuilder().buildPartial()) .setDefaultInstanceOfOtherType(OtherTestMessageLite3.newBuilder().buildPartial()) .build(); return ImmutableList.of( new Object[] {"Proto 2", proto2Config}, new Object[] {"Proto 3", proto3Config}); } @Rule public final Expect expect = Expect.create(); private final Config config; public LiteProtoSubjectTest(@SuppressWarnings("unused") String name, Config config) { this.config = config; } private LiteProtoSubject expectThat(@Nullable MessageLite m) { return expect.about(LiteProtoTruth.liteProtos()).that(m); } private Subject expectThat(@Nullable Object o) { return expect.that(o); } @Test public void subjectMethods() { expectThat(config.nonEmptyMessage()).isSameInstanceAs(config.nonEmptyMessage()); expectThat(config.nonEmptyMessage().toBuilder()).isNotSameInstanceAs(config.nonEmptyMessage()); expectThat(config.nonEmptyMessage()).isInstanceOf(MessageLite.class); expectThat(config.nonEmptyMessage().toBuilder()).isInstanceOf(MessageLite.Builder.class); expectThat(config.nonEmptyMessage()).isNotInstanceOf(MessageLite.Builder.class); expectThat(config.nonEmptyMessage().toBuilder()).isNotInstanceOf(MessageLite.class); expectThat(config.nonEmptyMessage()).isIn(Arrays.asList(config.nonEmptyMessage())); expectThat(config.nonEmptyMessage()) .isNotIn(Arrays.asList(config.nonEmptyMessageOfOtherValue())); expectThat(config.nonEmptyMessage()) .isAnyOf(config.nonEmptyMessage(), config.nonEmptyMessageOfOtherValue()); expectThat(config.nonEmptyMessage()) .isNoneOf(config.nonEmptyMessageOfOtherValue(), config.nonEmptyMessageOfOtherType()); } @Test public void isEqualTo_success() { expectThat(null).isEqualTo(null); expectThat(null).isNull(); expectThat(config.nonEmptyMessage()).isEqualTo(config.nonEmptyMessage()); expectThat(config.nonEmptyMessage()).isEqualTo(config.equivalentNonEmptyMessage()); expectThat(config.nonEmptyMessage()).isNotEqualTo(config.nonEmptyMessage().toBuilder()); assertThat(config.defaultInstance()).isNotEqualTo(config.defaultInstanceOfOtherType()); assertThat(config.nonEmptyMessage()).isNotEqualTo(config.nonEmptyMessageOfOtherType()); assertThat(config.nonEmptyMessage()).isNotEqualTo(config.nonEmptyMessageOfOtherValue()); } @Test public void isEqualTo_failure() { AssertionError e = expectFailure( whenTesting -> whenTesting .that(config.nonEmptyMessage()) .isEqualTo(config.nonEmptyMessageOfOtherValue())); expectRegex(e, ".*expected:.*\"foo\".*"); expectNoRegex(e, ".*but was:.*\"foo\".*"); e = expectFailure( whenTesting -> whenTesting .that(config.nonEmptyMessage()) .isEqualTo(config.nonEmptyMessageOfOtherType())); assertThat(e) .factKeys() .containsExactly("expected", "an instance of", "but was", "an instance of") .inOrder(); e = expectFailure( whenTesting -> whenTesting .that(config.nonEmptyMessage()) .isNotEqualTo(config.equivalentNonEmptyMessage())); expectRegex( e, String.format( "Not true that protos are different\\.\\s*Both are \\(%s\\) <.*optional_int: 3.*>\\.", Pattern.quote(config.nonEmptyMessage().getClass().getName()))); } @Test public void hasAllRequiredFields_success() { expectThat(config.nonEmptyMessage()).hasAllRequiredFields(); } @Test public void hasAllRequiredFields_failures() { if (!config.messageWithoutRequiredFields().isPresent()) { return; } AssertionError e = expectFailure( whenTesting -> whenTesting .that(config.messageWithoutRequiredFields().get()) .hasAllRequiredFields()); expectRegex( e, "expected to have all required fields set\\s*but was: .*\\(Lite runtime could not" + " determine which fields were missing.\\)"); } @Test public void defaultInstance_success() { expectThat(config.defaultInstance()).isEqualToDefaultInstance(); expectThat(config.defaultInstanceOfOtherType()).isEqualToDefaultInstance(); expectThat(config.nonEmptyMessage().getDefaultInstanceForType()).isEqualToDefaultInstance(); expectThat(null).isNotEqualToDefaultInstance(); expectThat(config.nonEmptyMessage()).isNotEqualToDefaultInstance(); } @Test public void defaultInstance_failure() { AssertionError e = expectFailure( whenTesting -> whenTesting.that(config.nonEmptyMessage()).isEqualToDefaultInstance()); expectRegex( e, "Not true that <.*optional_int:\\s*3.*> is a default proto instance\\.\\s*" + "It has set values\\."); e = expectFailure( whenTesting -> whenTesting.that(config.defaultInstance()).isNotEqualToDefaultInstance()); expectRegex( e, String.format( "Not true that \\(%s\\) <.*\\[empty proto\\].*> is not a default " + "proto instance\\.\\s*It has no set values\\.", Pattern.quote(config.defaultInstance().getClass().getName()))); } @Test public void serializedSize_success() { int size = config.nonEmptyMessage().getSerializedSize(); expectThat(config.nonEmptyMessage()).serializedSize().isEqualTo(size); expectThat(config.defaultInstance()).serializedSize().isEqualTo(0); } @Test public void serializedSize_failure() { int size = config.nonEmptyMessage().getSerializedSize(); AssertionError e = expectFailure( whenTesting -> whenTesting.that(config.nonEmptyMessage()).serializedSize().isGreaterThan(size)); assertThat(e).factValue("value of").isEqualTo("liteProto.getSerializedSize()"); assertThat(e).factValue("liteProto was").containsMatch("optional_int:\\s*3"); e = expectFailure( whenTesting -> whenTesting.that(config.defaultInstance()).serializedSize().isGreaterThan(0)); assertThat(e).factValue("value of").isEqualTo("liteProto.getSerializedSize()"); assertThat(e).factValue("liteProto was").contains("[empty proto]"); } private void expectRegex(AssertionError e, String regex) { expect.that(e).hasMessageThat().matches(Pattern.compile(regex, Pattern.DOTALL)); } private void expectNoRegex(AssertionError e, String regex) { expect.that(e).hasMessageThat().doesNotMatch(Pattern.compile(regex, Pattern.DOTALL)); } private static AssertionError expectFailure( SimpleSubjectBuilderCallback<LiteProtoSubject, MessageLite> assertionCallback) { return expectFailureAbout(liteProtos(), assertionCallback); } }
Builder
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/AutoValueConstructorOrderChecker.java
{ "start": 1402, "end": 1816 }
class ____. These names * are only included if you compile with debugging symbols (-g) or with -parameters. You also need * to tell the compiler to read these names from the classfiles and so must compile your project * with -parameters too. * * @author andrewrice@google.com (Andrew Rice) */ @BugPattern(summary = "Arguments to AutoValue constructor are in the wrong order", severity = ERROR) public final
files
java
micronaut-projects__micronaut-core
management/src/main/java/io/micronaut/management/endpoint/annotation/Write.java
{ "start": 1285, "end": 1886 }
interface ____ { /** * @return Description of the operation */ String description() default ""; /** * @return The produced MediaType values. Defaults to application/json */ @AliasFor(annotationName = "io.micronaut.http.annotation.Produces", member = "value") String[] produces() default {"application/json"}; /** * @return The consumed MediaType for request bodies Defaults to application/json */ @AliasFor(annotationName = "io.micronaut.http.annotation.Consumes", member = "value") String[] consumes() default {"application/json"}; }
Write
java
bumptech__glide
library/src/main/java/com/bumptech/glide/load/engine/bitmap_recycle/BitmapPoolAdapter.java
{ "start": 395, "end": 1099 }
class ____ implements BitmapPool { @Override public long getMaxSize() { return 0; } @Override public void setSizeMultiplier(float sizeMultiplier) { // Do nothing. } @Override public void put(Bitmap bitmap) { bitmap.recycle(); } @NonNull @Override public Bitmap get(int width, int height, Bitmap.Config config) { return Bitmap.createBitmap(width, height, config); } @NonNull @Override public Bitmap getDirty(int width, int height, Bitmap.Config config) { return get(width, height, config); } @Override public void clearMemory() { // Do nothing. } @Override public void trimMemory(int level) { // Do nothing. } }
BitmapPoolAdapter
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/CollectionLoggingTest.java
{ "start": 1601, "end": 3253 }
class ____ { private final ListAppender app; public CollectionLoggingTest(@Named("List") final ListAppender app) { this.app = app.clear(); } @Test @ResourceLock(value = Resources.SYSTEM_PROPERTIES, mode = ResourceAccessMode.READ) void testSystemProperties(final LoggerContext context) { final Logger logger = context.getLogger(CollectionLoggingTest.class.getName()); logger.error(System.getProperties()); // logger.error(new MapMessage(System.getProperties())); // TODO: some assertions } @Test @ResourceLock(value = Resources.SYSTEM_PROPERTIES, mode = ResourceAccessMode.READ) void testSimpleMap(final LoggerContext context) { final Logger logger = context.getLogger(CollectionLoggingTest.class.getName()); logger.error(System.getProperties()); final Map<String, String> map = new HashMap<>(); map.put("MyKey1", "MyValue1"); map.put("MyKey2", "MyValue2"); logger.error(new StringMapMessage(map)); logger.error(map); // TODO: some assertions } @Test void testNetworkInterfaces(final LoggerContext context) throws SocketException { final Logger logger = context.getLogger(CollectionLoggingTest.class.getName()); logger.error(NetworkInterface.getNetworkInterfaces()); // TODO: some assertions } @Test void testAvailableCharsets(final LoggerContext context) { final Logger logger = context.getLogger(CollectionLoggingTest.class.getName()); logger.error(Charset.availableCharsets()); // TODO: some assertions } }
CollectionLoggingTest
java
quarkusio__quarkus
extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/config/DialectVersions.java
{ "start": 601, "end": 1910 }
class ____ { // The following constants must be at least equal to the default dialect version in Hibernate ORM // These constants must be removed as soon as Hibernate ORM's minimum requirements become // greater than or equal to these versions. public static final String MARIADB = "10.6"; public static final String MSSQL = "13"; // 2016 // This must be aligned on the H2 version in the Quarkus BOM // This must never be removed public static final String H2 = "2.4.240"; private Defaults() { } } public static String toString(DatabaseVersion version) { StringBuilder stringBuilder = new StringBuilder(); if (version.getMajor() != DatabaseVersion.NO_VERSION) { stringBuilder.append(version.getMajor()); if (version.getMinor() != DatabaseVersion.NO_VERSION) { stringBuilder.append("."); stringBuilder.append(version.getMinor()); if (version.getMicro() != DatabaseVersion.NO_VERSION) { stringBuilder.append("."); stringBuilder.append(version.getMicro()); } } } return stringBuilder.toString(); } private DialectVersions() { } }
Defaults
java
quarkusio__quarkus
independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/MultiByteHttpData.java
{ "start": 2221, "end": 12257 }
class ____ extends AbstractHttpData implements FileUpload { private static final Logger log = Logger.getLogger(MultiByteHttpData.class); public static final int DEFAULT_BUFFER_SIZE = 16384; private static final int BUFFER_SIZE; private Subscription subscription; private String filename; private String contentType; private String contentTransferEncoding; // TODO: replace with a simple array based? // TODO: we do `discardReadBytes` on it which is not optimal - copies array every time private final ByteBuf buffer = VertxByteBufAllocator.DEFAULT.heapBuffer(BUFFER_SIZE, BUFFER_SIZE); private final Context context; private volatile boolean done = false; private boolean paused = false; private int awaitedBytes; static { BUFFER_SIZE = Integer .parseInt(System.getProperty("quarkus.rest.client.multipart-buffer-size", String.valueOf(DEFAULT_BUFFER_SIZE))); if (BUFFER_SIZE < DEFAULT_BUFFER_SIZE) { throw new IllegalStateException( "quarkus.rest.client.multipart-buffer-size cannot be lower than " + DEFAULT_BUFFER_SIZE); } } /** * * @param name name of the parameter * @param filename file name * @param contentType content type * @param contentTransferEncoding "binary" for sending binary files * @param charset the charset * @param content the Multi to send * @param errorHandler error handler invoked when the Multi emits an exception * @param context Vertx context on which the data is sent * @param resumption the action to execute when the requested amount of bytes is ready, or the Multi is completed */ public MultiByteHttpData(String name, String filename, String contentType, String contentTransferEncoding, Charset charset, Multi<Byte> content, Consumer<Throwable> errorHandler, Context context, Runnable resumption) { super(name, charset, 0); this.context = context; setFilename(filename); setContentType(contentType); setContentTransferEncoding(contentTransferEncoding); var contextualExecutor = new ExecutorWithContext(context); content.emitOn(contextualExecutor).runSubscriptionOn(contextualExecutor).subscribe().with( subscription -> { MultiByteHttpData.this.subscription = subscription; subscription.request(BUFFER_SIZE); }, b -> { buffer.writeByte(b); if (paused && (done || buffer.readableBytes() >= awaitedBytes)) { paused = false; awaitedBytes = 0; resumption.run(); } }, th -> { log.error("Multi<Byte> used to send a multipart message failed", th); done = true; errorHandler.accept(th); }, () -> { done = true; if (paused) { paused = false; resumption.run(); } }); } void suspend(int awaitedBytes) { this.awaitedBytes = awaitedBytes; this.paused = true; } @Override public void setContent(ByteBuf buffer) throws IOException { throw new IllegalStateException("setting content of MultiByteHttpData is not supported"); } @Override public void addContent(ByteBuf buffer, boolean last) throws IOException { throw new IllegalStateException("adding content to MultiByteHttpData is not supported"); } @Override public void setContent(File file) throws IOException { throw new IllegalStateException("setting content of MultiByteHttpData is not supported"); } @Override public void setContent(InputStream inputStream) throws IOException { throw new IllegalStateException("setting content of MultiByteHttpData is not supported"); } @Override public void delete() { // do nothing } @Override public byte[] get() throws IOException { throw new IllegalStateException("getting all the contents of a MultiByteHttpData is not supported"); } @Override public ByteBuf getByteBuf() { throw new IllegalStateException("getting all the contents of a MultiByteHttpData is not supported"); } /** * check if it is possible to read the next chunk of data of a given size * * @param chunkSize amount of bytes * @return true if the requested amount of bytes is ready to be read or the Multi is completed, i.e. there will be * no more bytes to read */ public boolean isReady(int chunkSize) { return done || buffer.readableBytes() >= chunkSize; } /** * {@inheritDoc} * <br/> * NOTE: should only be invoked when {@link #isReady(int)} returns true * * @param toRead amount of bytes to read * @return ByteBuf with the requested bytes */ @Override public ByteBuf getChunk(int toRead) { if (Vertx.currentContext() != context) { throw new IllegalStateException("MultiByteHttpData invoked on an invalid context : " + Vertx.currentContext() + ", thread: " + Thread.currentThread()); } if (buffer.readableBytes() == 0 && done) { return Unpooled.EMPTY_BUFFER; } ByteBuf result = VertxByteBufAllocator.DEFAULT.heapBuffer(toRead, toRead); // finish if the whole buffer is filled // or we hit the end, `done` && buffer.readableBytes == 0 while (toRead > 0 && !(buffer.readableBytes() == 0 && done)) { int readBytes = Math.min(buffer.readableBytes(), toRead); result.writeBytes(buffer.readBytes(readBytes)); buffer.discardReadBytes(); subscription.request(readBytes); toRead -= readBytes; } return result; } @Override public String getString() { throw new IllegalStateException("Reading MultiByteHttpData as String is not supported"); } @Override public String getString(Charset encoding) { throw new IllegalStateException("Reading MultiByteHttpData as String is not supported"); } @Override public boolean renameTo(File dest) { throw new IllegalStateException("Renaming destination file for MultiByteHttpData is not supported"); } @Override public boolean isInMemory() { return true; } @Override public File getFile() { return null; } @Override public FileUpload copy() { throw new IllegalStateException("Copying MultiByteHttpData is not supported"); } @Override public FileUpload duplicate() { throw new IllegalStateException("Duplicating MultiByteHttpData is not supported"); } @Override public FileUpload retainedDuplicate() { throw new IllegalStateException("Duplicating MultiByteHttpData is not supported"); } @Override public FileUpload replace(ByteBuf content) { throw new IllegalStateException("Replacing MultiByteHttpData is not supported"); } @Override public FileUpload retain(int increment) { super.retain(increment); return this; } @Override public FileUpload retain() { super.retain(); return this; } @Override public FileUpload touch() { touch(null); return this; } @Override public FileUpload touch(Object hint) { buffer.touch(hint); return this; } @Override public int hashCode() { return System.identityHashCode(this); } @Override public boolean equals(Object o) { return System.identityHashCode(this) == System.identityHashCode(o); } @Override public int compareTo(InterfaceHttpData o) { if (!(o instanceof MultiByteHttpData)) { throw new ClassCastException("Cannot compare " + getHttpDataType() + " with " + o.getHttpDataType()); } return compareTo((MultiByteHttpData) o); } public int compareTo(MultiByteHttpData o) { return Integer.compare(System.identityHashCode(this), System.identityHashCode(o)); } @Override public HttpDataType getHttpDataType() { return HttpDataType.FileUpload; } @Override public String getFilename() { return filename; } @Override public void setFilename(String filename) { this.filename = ObjectUtil.checkNotNull(filename, "filename"); } @Override public void setContentType(String contentType) { this.contentType = ObjectUtil.checkNotNull(contentType, "contentType"); } @Override public String getContentType() { return contentType; } @Override public String getContentTransferEncoding() { return contentTransferEncoding; } @Override public void setContentTransferEncoding(String contentTransferEncoding) { this.contentTransferEncoding = contentTransferEncoding; } @Override public long length() { return buffer.readableBytes() + super.length(); } @Override public String toString() { return HttpHeaderNames.CONTENT_DISPOSITION + ": " + HttpHeaderValues.FORM_DATA + "; " + HttpHeaderValues.NAME + "=\"" + getName() + "\"; " + HttpHeaderValues.FILENAME + "=\"" + filename + "\"\r\n" + HttpHeaderNames.CONTENT_TYPE + ": " + contentType + (getCharset() != null ? "; " + HttpHeaderValues.CHARSET + '=' + getCharset().name() + "\r\n" : "\r\n") + HttpHeaderNames.CONTENT_LENGTH + ": " + length() + "\r\n" + "Completed: " + isCompleted(); } static
MultiByteHttpData
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/lucene/LuceneTopNSourceOperatorTests.java
{ "start": 2445, "end": 9294 }
class ____ extends SourceOperatorTestCase { private static final MappedFieldType S_FIELD = new NumberFieldMapper.NumberFieldType("s", NumberFieldMapper.NumberType.LONG); private Directory directory = newDirectory(); private IndexReader reader; @After public void closeIndex() throws IOException { IOUtils.close(reader, directory); } @Override protected LuceneTopNSourceOperator.Factory simple(SimpleOptions options) { return simple(DataPartitioning.SHARD, 10_000, 100); } private LuceneTopNSourceOperator.Factory simple(DataPartitioning dataPartitioning, int size, int limit) { int commitEvery = Math.max(1, size / 10); try ( RandomIndexWriter writer = new RandomIndexWriter( random(), directory, newIndexWriterConfig().setMergePolicy(NoMergePolicy.INSTANCE) ) ) { for (int d = 0; d < size; d++) { List<IndexableField> doc = new ArrayList<>(); doc.add(new SortedNumericDocValuesField("s", d)); writer.addDocument(doc); if (d % commitEvery == 0) { writer.commit(); } } reader = writer.getReader(); } catch (IOException e) { throw new RuntimeException(e); } ShardContext ctx = new LuceneSourceOperatorTests.MockShardContext(reader, 0) { @Override public Optional<SortAndFormats> buildSort(List<SortBuilder<?>> sorts) { SortField field = new SortedNumericSortField("s", SortField.Type.LONG, false, SortedNumericSelector.Type.MIN); return Optional.of(new SortAndFormats(new Sort(field), new DocValueFormat[] { null })); } }; Function<ShardContext, List<LuceneSliceQueue.QueryAndTags>> queryFunction = c -> List.of( new LuceneSliceQueue.QueryAndTags(new MatchAllDocsQuery(), List.of()) ); int taskConcurrency = 0; int maxPageSize = between(10, Math.max(10, size)); List<SortBuilder<?>> sorts = List.of(new FieldSortBuilder("s")); long estimatedPerRowSortSize = 16; return new LuceneTopNSourceOperator.Factory( new IndexedByShardIdFromSingleton<>(ctx), queryFunction, dataPartitioning, taskConcurrency, maxPageSize, limit, sorts, estimatedPerRowSortSize, scoring ); } @Override protected Matcher<String> expectedToStringOfSimple() { return matchesRegex( "LuceneTopNSourceOperator\\[shards = \\[test], maxPageSize = \\d+, limit = 100, needsScore = " + scoring + ", sorts = \\[\\{.+}]]" ); } @Override protected Matcher<String> expectedDescriptionOfSimple() { return matchesRegex( "LuceneTopNSourceOperator" + "\\[dataPartitioning = (DOC|SHARD|SEGMENT), maxPageSize = \\d+, limit = 100, needsScore = " + scoring + ", sorts = \\[\\{.+}]]" ); } // TODO tests for the other data partitioning configurations public void testShardDataPartitioning() { testShardDataPartitioning(driverContext()); } public void testShardDataPartitioningWithCranky() { try { testShardDataPartitioning(crankyDriverContext()); logger.info("cranky didn't break"); } catch (CircuitBreakingException e) { logger.info("broken", e); assertThat(e.getMessage(), equalTo(CrankyCircuitBreakerService.ERROR_MESSAGE)); } } void testShardDataPartitioning(DriverContext context) { int size = between(1_000, 20_000); int limit = between(10, size); testSimple(context, size, limit); } public void testWithCranky() { try { int size = between(1_000, 20_000); int limit = between(10, size); testSimple(crankyDriverContext(), size, limit); logger.info("cranky didn't break"); } catch (CircuitBreakingException e) { logger.info("broken", e); assertThat(e.getMessage(), equalTo(CrankyCircuitBreakerService.ERROR_MESSAGE)); } } public void testEmpty() { testEmpty(driverContext()); } public void testEmptyWithCranky() { try { testEmpty(crankyDriverContext()); logger.info("cranky didn't break"); } catch (CircuitBreakingException e) { logger.info("broken", e); assertThat(e.getMessage(), equalTo(CrankyCircuitBreakerService.ERROR_MESSAGE)); } } void testEmpty(DriverContext context) { testSimple(context, 0, between(10, 10_000)); } protected void testSimple(DriverContext ctx, int size, int limit) { LuceneTopNSourceOperator.Factory factory = simple(DataPartitioning.SHARD, size, limit); Operator.OperatorFactory readS = ValuesSourceReaderOperatorTests.factory(reader, S_FIELD, ElementType.LONG); List<Page> results = new ArrayList<>(); OperatorTestCase.runDriver( TestDriverFactory.create(ctx, factory.get(ctx), List.of(readS.get(ctx)), new TestResultPageSinkOperator(results::add)) ); OperatorTestCase.assertDriverContext(ctx); long expectedS = 0; for (Page page : results) { if (limit - expectedS < factory.maxPageSize()) { assertThat(page.getPositionCount(), equalTo((int) (limit - expectedS))); } else { assertThat(page.getPositionCount(), equalTo(factory.maxPageSize())); } LongBlock sBlock = page.getBlock(initialBlockIndex(page)); for (int p = 0; p < page.getPositionCount(); p++) { assertThat(sBlock.getLong(sBlock.getFirstValueIndex(p)), equalTo(expectedS++)); } } assertAllRefCountedSameInstance(results); int pages = (int) Math.ceil((float) Math.min(size, limit) / factory.maxPageSize()); assertThat(results, hasSize(pages)); } // Scores are not interesting to this test, but enabled conditionally and effectively ignored just for coverage. private final boolean scoring = randomBoolean(); // Returns the initial block index, ignoring the score block if scoring is enabled private int initialBlockIndex(Page page) { assert page.getBlock(0) instanceof DocBlock : "expected doc block at index 0"; if (scoring) { assert page.getBlock(1) instanceof DoubleBlock : "expected double block at index 1"; return 2; } else { return 1; } } }
LuceneTopNSourceOperatorTests
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/it/file/CustomFileResolverFactory.java
{ "start": 576, "end": 752 }
class ____ implements FileResolverFactory { @Override public FileResolver resolver(VertxOptions options) { return new CustomFileResolver(); } }
CustomFileResolverFactory
java
quarkusio__quarkus
extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/reactive/ReactiveMongoDatabase.java
{ "start": 18671, "end": 20160 }
class ____ decode each document into * @param <T> the target document type of the iterable * @param options the stream options * @return the stream of change events. */ <T> Multi<ChangeStreamDocument<T>> watch(ClientSession clientSession, List<? extends Bson> pipeline, Class<T> clazz, ChangeStreamOptions options); /** * Runs an aggregation framework pipeline on the database for pipeline stages * that do not require an underlying collection, such as {@code $currentOp} and {@code $listLocalSessions}. * * @param pipeline the aggregation pipeline * @return a stream of the result of the aggregation operation */ Multi<Document> aggregate(List<? extends Bson> pipeline); /** * Runs an aggregation framework pipeline on the database for pipeline stages * that do not require an underlying collection, such as {@code $currentOp} and {@code $listLocalSessions}. * * @param pipeline the aggregation pipeline * @param options the stream options * @return a stream of the result of the aggregation operation */ Multi<Document> aggregate(List<? extends Bson> pipeline, AggregateOptions options); /** * Runs an aggregation framework pipeline on the database for pipeline stages * that do not require an underlying collection, such as {@code $currentOp} and {@code $listLocalSessions}. * * @param pipeline the aggregation pipeline * @param clazz the
to
java
spring-projects__spring-framework
spring-web/src/testFixtures/java/org/springframework/web/testfixture/method/MvcAnnotationPredicates.java
{ "start": 6612, "end": 7152 }
class ____ implements Predicate<Method> { private String name; public ModelAttributeMethodPredicate name(String name) { this.name = name; return this; } public ModelAttributeMethodPredicate noName() { this.name = ""; return this; } @Override public boolean test(Method method) { ModelAttribute annot = AnnotatedElementUtils.findMergedAnnotation(method, ModelAttribute.class); return annot != null && (this.name == null || annot.name().equals(this.name)); } } public static
ModelAttributeMethodPredicate
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/context/visitor/ContextConfigurerVisitor.java
{ "start": 1293, "end": 2205 }
class ____ implements TypeElementVisitor<ContextConfigurer, Object> { private static final Set<String> SUPPORTED_SERVICE_TYPES = Collections.singleton( ApplicationContextConfigurer.class.getName() ); @Override public @NonNull VisitorKind getVisitorKind() { return VisitorKind.ISOLATING; } @Override public String getElementType() { return ContextConfigurer.class.getName(); } @Override public void visitClass(ClassElement element, VisitorContext context) { assertNoConstructorForContextAnnotation(element); element.getInterfaces() .stream() .map(Element::getName) .filter(SUPPORTED_SERVICE_TYPES::contains) .forEach(serviceType -> context.visitServiceDescriptor(serviceType, element.getName(), element)); } /** * Checks that a
ContextConfigurerVisitor
java
apache__spark
core/src/main/java/org/apache/spark/shuffle/sort/ShuffleInMemorySorter.java
{ "start": 5488, "end": 6913 }
class ____ { private final LongArray pointerArray; private final int limit; final PackedRecordPointer packedRecordPointer = new PackedRecordPointer(); private int position = 0; ShuffleSorterIterator(int numRecords, LongArray pointerArray, int startingPosition) { this.limit = numRecords + startingPosition; this.pointerArray = pointerArray; this.position = startingPosition; } public boolean hasNext() { return position < limit; } public void loadNext() { packedRecordPointer.set(pointerArray.get(position)); position++; } } /** * Return an iterator over record pointers in sorted order. */ public ShuffleSorterIterator getSortedIterator() { int offset = 0; if (useRadixSort) { offset = RadixSort.sort( array, pos, PackedRecordPointer.PARTITION_ID_START_BYTE_INDEX, PackedRecordPointer.PARTITION_ID_END_BYTE_INDEX, false, false); } else { MemoryBlock unused = new MemoryBlock( array.getBaseObject(), array.getBaseOffset() + pos * 8L, (array.size() - pos) * 8L); LongArray buffer = new LongArray(unused); Sorter<PackedRecordPointer, LongArray> sorter = new Sorter<>(new ShuffleSortDataFormat(buffer)); sorter.sort(array, 0, pos, SORT_COMPARATOR); } return new ShuffleSorterIterator(pos, array, offset); } }
ShuffleSorterIterator
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/foreach/MyBeanParameterProvider.java
{ "start": 813, "end": 1124 }
class ____ { final Provider<MyConfiguration> configuration; MyBeanParameterProvider(@Parameter Provider<MyConfiguration> configuration) { this.configuration = configuration; } public MyConfiguration getConfiguration() { return configuration.get(); } }
MyBeanParameterProvider
java
micronaut-projects__micronaut-core
http-client-jdk/src/main/java/io/micronaut/http/client/jdk/HttpResponseAdapter.java
{ "start": 1696, "end": 5539 }
class ____<O> extends BaseHttpResponseAdapter<byte[], O> { private static final Logger LOG = LoggerFactory.getLogger(HttpResponseAdapter.class); @NonNull private final Argument<O> bodyType; private final MediaTypeCodecRegistry mediaTypeCodecRegistry; private final MessageBodyHandlerRegistry messageBodyHandlerRegistry; public HttpResponseAdapter(java.net.http.HttpResponse<byte[]> httpResponse, @Nullable Argument<O> bodyType, ConversionService conversionService, MediaTypeCodecRegistry mediaTypeCodecRegistry, MessageBodyHandlerRegistry messageBodyHandlerRegistry) { super(httpResponse, conversionService); this.bodyType = bodyType; this.mediaTypeCodecRegistry = mediaTypeCodecRegistry; this.messageBodyHandlerRegistry = messageBodyHandlerRegistry; } @Override public Optional<O> getBody() { return getBody(bodyType); } @Override public <T> Optional<T> getBody(Argument<T> type) { final boolean isOptional = type.getType() == Optional.class; final Argument<Object> theArgument = (Argument<Object>) (isOptional ? type.getFirstTypeVariable().orElse(type) : type); Optional<?> optional = convertBytes(getContentType().orElse(null), httpResponse.body(), theArgument); if (isOptional) { // If the requested type is an Optional, then we need to wrap the result again return Optional.of((T) optional); } return (Optional<T>) optional; } private <T> Optional<T> convertBytes(@Nullable MediaType contentType, byte[] bytes, Argument<T> type) { if (bytes.length == 0) { return Optional.empty(); } if (type.getType().equals(byte[].class)) { return Optional.of((T) bytes); } if (contentType != null) { if (CharSequence.class.isAssignableFrom(type.getType())) { Charset charset = contentType.getCharset().orElse(StandardCharsets.UTF_8); return Optional.of((T) new String(bytes, charset)); } } if (mediaTypeCodecRegistry != null) { Optional<MediaTypeCodec> foundCodec = mediaTypeCodecRegistry.findCodec(contentType); if (foundCodec.isPresent()) { try { return foundCodec.map(codec -> codec.decode(type, bytes)); } catch (CodecException e) { logCodecError(contentType, type, e); } } } if (messageBodyHandlerRegistry != null) { MessageBodyReader<T> reader = messageBodyHandlerRegistry.findReader(type, contentType).orElse(null); if (reader != null) { try { T value = reader.read( type, contentType, getHeaders(), ByteArrayBufferFactory.INSTANCE.wrap(bytes) ); return Optional.of(value); } catch (CodecException e) { logCodecError(contentType, type, e); } } } // last chance, try type conversion return conversionService.convert(bytes, ConversionContext.of(type)); } private <T> void logCodecError(MediaType contentType, Argument<T> type, CodecException e) { if (LOG.isDebugEnabled()) { var message = e.getMessage(); LOG.debug("Error decoding body for type [{}] from '{}'. Attempting fallback.", type, contentType); LOG.debug("CodecException Message was: {}", message == null ? "null" : message.replace("\n", "")); } } }
HttpResponseAdapter
java
apache__camel
components/camel-bindy/src/main/java/org/apache/camel/dataformat/bindy/format/factories/FormatFactoryInterface.java
{ "start": 1011, "end": 1847 }
interface ____ { /** * Returns the list of supported classes. When the list doesn't contain elements the factory is supposed to support * all kinds of classes. The factory must decide on other criteria whether it can build a {@link Format}. * * @return the list of supported classes */ Collection<Class<?>> supportedClasses(); /** * Can it build a {@link Format}. Answers the question about whether it can build a {@link Format}. * * @param formattingOptions * @return can build */ boolean canBuild(FormattingOptions formattingOptions); /** * Builds the {@link Format}. * * @param formattingOptions * @return the format */ Format<?> build(FormattingOptions formattingOptions); }
FormatFactoryInterface
java
bumptech__glide
annotation/compiler/test/src/test/java/com/bumptech/glide/annotation/compiler/InvalidGlideTypeExtensionTest.java
{ "start": 14521, "end": 15691 }
class ____ {", " private Extension() {}", " @NonNull", " @GlideType(Number.class)", " public static RequestBuilder<Number> asNumber(", " RequestBuilder<Number> builder, Object arg1) {", " return builder;", " }", "}")); } }); } @Test public void compilation_withAnnotatedStaticMethod_returningBuilder_nonBuilderParam_fails() { try { javac() .withProcessors(new GlideAnnotationProcessor()) .compile( emptyAppModule(), JavaFileObjects.forSourceLines( "IncorrectParameterExtension", "package com.bumptech.glide.test;", "import androidx.annotation.NonNull;", "import com.bumptech.glide.RequestBuilder;", "import com.bumptech.glide.annotation.GlideExtension;", "import com.bumptech.glide.annotation.GlideType;", "@GlideExtension", "public
Extension
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/CoreSubscriber.java
{ "start": 1282, "end": 2147 }
interface ____<T> extends Subscriber<T> { /** * Request a {@link Context} from dependent components which can include downstream * operators during subscribing or a terminal {@link org.reactivestreams.Subscriber}. * * @return a resolved context or {@link Context#empty()} */ default Context currentContext(){ return Context.empty(); } /** * Implementors should initialize any state used by {@link #onNext(Object)} before * calling {@link Subscription#request(long)}. Should further {@code onNext} related * state modification occur, thread-safety will be required. * <p> * Note that an invalid request {@code <= 0} will not produce an onError and * will simply be ignored or reported through a debug-enabled * {@link reactor.util.Logger}. * * {@inheritDoc} */ @Override void onSubscribe(Subscription s); }
CoreSubscriber
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/expressions/parser/ast/operator/unary/EmptyOperator.java
{ "start": 1549, "end": 4513 }
class ____ extends UnaryOperator { private static final String IS_EMPTY = "isEmpty"; public EmptyOperator(ExpressionNode operand) { super(operand); } @Override protected ExpressionDef generateExpression(ExpressionCompilationContext ctx) { ClassElement type = operand.resolveClassElement(ctx); ExpressionDef opExp = operand.compile(ctx); if (type.isAssignable(CharSequence.class)) { return ClassTypeDef.of(StringUtils.class) .invokeStatic( ReflectionUtils.getRequiredMethod( StringUtils.class, IS_EMPTY, CharSequence.class ), opExp ); } else if (type.isAssignable(Collection.class)) { return ClassTypeDef.of(CollectionUtils.class) .invokeStatic( ReflectionUtils.getRequiredMethod( CollectionUtils.class, IS_EMPTY, Collection.class ), opExp ); } else if (type.isAssignable(Map.class)) { return ClassTypeDef.of(CollectionUtils.class) .invokeStatic( ReflectionUtils.getRequiredMethod( CollectionUtils.class, IS_EMPTY, Map.class ), opExp ); } else if (type.isAssignable(Optional.class)) { return opExp.invoke( ReflectionUtils.getRequiredMethod( Optional.class, IS_EMPTY ) ); } else if (type.isArray() && !type.isPrimitive()) { return ClassTypeDef.of(ArrayUtils.class) .invokeStatic( ReflectionUtils.getRequiredMethod( ArrayUtils.class, IS_EMPTY, Object[].class ), opExp ); } else if (type.isPrimitive()) { // primitives are never empty return ExpressionDef.falseValue(); } else { return ClassTypeDef.of(Objects.class) .invokeStatic( ReflectionUtils.getRequiredMethod( Objects.class, "isNull", Object.class ), opExp ); } } @Override public TypeDef doResolveType(@NonNull ExpressionVisitorContext ctx) { return TypeDef.Primitive.BOOLEAN; } @Override protected ClassElement doResolveClassElement(ExpressionVisitorContext ctx) { return PrimitiveElement.BOOLEAN; } }
EmptyOperator
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/TableConfigOptions.java
{ "start": 1686, "end": 15545 }
class ____ { private TableConfigOptions() {} @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<String> TABLE_CATALOG_NAME = key("table.builtin-catalog-name") .stringType() .defaultValue("default_catalog") .withDescription( "The name of the initial catalog to be created when " + "instantiating a TableEnvironment."); @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<String> TABLE_DATABASE_NAME = key("table.builtin-database-name") .stringType() .defaultValue("default_database") .withDescription( "The name of the default database in the initial catalog to be created " + "when instantiating TableEnvironment."); @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<List<String>> TABLE_CATALOG_MODIFICATION_LISTENERS = key("table.catalog-modification.listeners") .stringType() .asList() .noDefaultValue() .withDescription( "A (semicolon-separated) list of factories that creates listener for catalog " + "modification which will be notified in catalog manager after it " + "performs database and table ddl operations successfully."); @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<Boolean> TABLE_DML_SYNC = key("table.dml-sync") .booleanType() .defaultValue(false) .withDescription( "Specifies if the DML job (i.e. the insert operation) is executed asynchronously or synchronously. " + "By default, the execution is async, so you can submit multiple DML jobs at the same time. " + "If set this option to true, the insert operation will wait for the job to finish."); @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<Boolean> TABLE_DYNAMIC_TABLE_OPTIONS_ENABLED = key("table.dynamic-table-options.enabled") .booleanType() .defaultValue(true) .withDescription( "Enable or disable the OPTIONS hint used to specify table options " + "dynamically, if disabled, an exception would be thrown " + "if any OPTIONS hint is specified"); @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<String> TABLE_SQL_DIALECT = key("table.sql-dialect") .stringType() .defaultValue(SqlDialect.DEFAULT.name().toLowerCase()) .withDescription( "The SQL dialect defines how to parse a SQL query. " + "A different SQL dialect may support different SQL grammar. " + "Currently supported dialects are: default and hive"); @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<String> LOCAL_TIME_ZONE = key("table.local-time-zone") .stringType() // special value to decide whether to use ZoneId.systemDefault() in // TableConfig.getLocalTimeZone() .defaultValue("default") .withDescription( "The local time zone defines current session time zone id. It is used when converting to/from " + "<code>TIMESTAMP WITH LOCAL TIME ZONE</code>. Internally, timestamps with local time zone are always represented in the UTC time zone. " + "However, when converting to data types that don't include a time zone (e.g. TIMESTAMP, TIME, or simply STRING), " + "the session time zone is used during conversion. The input of option is either a full name " + "such as \"America/Los_Angeles\", or a custom timezone id such as \"GMT-08:00\"."); @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<Integer> DISPLAY_MAX_COLUMN_WIDTH = key("table.display.max-column-width") .intType() .defaultValue(30) .withDescription( "When printing the query results to the client console, this parameter determines the number of characters shown on screen before truncating. " + "This only applies to columns with variable-length types (e.g. CHAR, VARCHAR, STRING) in the streaming mode. " + "Fixed-length types are printed in the batch mode using a deterministic column width."); @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) @Documentation.OverrideDefault("System.getProperty(\"java.io.tmpdir\")") public static final ConfigOption<String> RESOURCES_DOWNLOAD_DIR = key("table.resources.download-dir") .stringType() .defaultValue(System.getProperty("java.io.tmpdir")) .withDescription( "Local directory that is used by planner for storing downloaded resources."); @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<Boolean> TABLE_RTAS_CTAS_ATOMICITY_ENABLED = key("table.rtas-ctas.atomicity-enabled") .booleanType() .defaultValue(false) .withDescription( "Specifies if the CREATE TABLE/REPLACE TABLE/CREATE OR REPLACE AS SELECT statement is executed atomically. By default, the statement is non-atomic. " + "The target table is created/replaced on the client side, and it will not be rolled back even though the job fails or is canceled. " + "If set this option to true and the underlying DynamicTableSink implements the SupportsStaging interface, " + "the statement is expected to be executed atomically, the behavior of which depends on the actual DynamicTableSink."); @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<List<ColumnExpansionStrategy>> TABLE_COLUMN_EXPANSION_STRATEGY = key("table.column-expansion-strategy") .enumType(ColumnExpansionStrategy.class) .asList() .defaultValues() .withDescription( "Configures the default expansion behavior of 'SELECT *'. " + "By default, all top-level columns of the table's " + "schema are selected and nested fields are retained."); @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<Boolean> LEGACY_NESTED_ROW_NULLABILITY = key("table.legacy-nested-row-nullability") .booleanType() .defaultValue(false) .withDescription( "Before Flink 2.2, row types defined in SQL " + "e.g. `SELECT CAST(f AS ROW<i NOT NULL>)` did ignore the `NOT NULL` constraint. " + "This was more aligned with the SQL standard but caused many type inconsistencies " + "and cryptic error message when working on nested data. " + "For example, it prevented using rows in computed columns or join keys. " + "The new behavior takes the nullability into consideration."); // ------------------------------------------------------------------------------------------ // Options for plan handling // ------------------------------------------------------------------------------------------ @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<CatalogPlanCompilation> PLAN_COMPILE_CATALOG_OBJECTS = key("table.plan.compile.catalog-objects") .enumType(CatalogPlanCompilation.class) .defaultValue(CatalogPlanCompilation.ALL) .withDescription( Description.builder() .text( "Strategy how to persist catalog objects such as tables, " + "functions, or data types into a plan during compilation.") .linebreak() .linebreak() .text( "It influences the need for catalog metadata to be present " + "during a restore operation and affects the plan size.") .linebreak() .linebreak() .text( "This configuration option does not affect anonymous/inline " + "or temporary objects. Anonymous/inline objects will " + "be persisted entirely (including schema and options) " + "if possible or fail the compilation otherwise. " + "Temporary objects will be persisted only by their " + "identifier and the object needs to be present in " + "the session context during a restore.") .build()); @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<CatalogPlanRestore> PLAN_RESTORE_CATALOG_OBJECTS = key("table.plan.restore.catalog-objects") .enumType(CatalogPlanRestore.class) .defaultValue(CatalogPlanRestore.ALL) .withDescription( "Strategy how to restore catalog objects such as tables, functions, or data " + "types using a given plan and performing catalog lookups if " + "necessary. It influences the need for catalog metadata to be" + "present and enables partial enrichment of plan information."); @Documentation.TableOption(execMode = Documentation.ExecMode.STREAMING) public static final ConfigOption<Boolean> PLAN_FORCE_RECOMPILE = key("table.plan.force-recompile") .booleanType() .defaultValue(false) .withDescription( "When false COMPILE PLAN statement will fail if the output plan file is already existing, " + "unless the clause IF NOT EXISTS is used. " + "When true COMPILE PLAN will overwrite the existing output plan file. " + "We strongly suggest to enable this flag only for debugging purpose."); // ------------------------------------------------------------------------------------------ // Options for code generation // ------------------------------------------------------------------------------------------ @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING) public static final ConfigOption<Integer> MAX_LENGTH_GENERATED_CODE = key("table.generated-code.max-length") .intType() .defaultValue(4000) .withDescription( "Specifies a threshold where generated code will be split into sub-function calls. " + "Java has a maximum method length of 64 KB. This setting allows for finer granularity if necessary. " + "Default value is 4000 instead of 64KB as by default JIT refuses to work on methods with more than 8K byte code."); @Documentation.ExcludeFromDocumentation( "This option is rarely used. The default value is good enough for almost all cases.") public static final ConfigOption<Integer> MAX_MEMBERS_GENERATED_CODE = key("table.generated-code.max-members") .intType() .defaultValue(10000) .withDescription( "Specifies a threshold where
TableConfigOptions
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java
{ "start": 622, "end": 5555 }
class ____ { @Rule public MockitoRule r = MockitoJUnit.rule(); @Mock private UnmockableHashCodeAndEquals mock1; @Test public void can_add_mock_that_have_failing_hashCode_method() throws Exception { new HashCodeAndEqualsSafeSet().add(mock1); } @Test public void mock_with_failing_hashCode_method_can_be_added() throws Exception { new HashCodeAndEqualsSafeSet().add(mock1); } @Test public void mock_with_failing_equals_method_can_be_used() throws Exception { HashCodeAndEqualsSafeSet mocks = new HashCodeAndEqualsSafeSet(); mocks.add(mock1); assertThat(mocks.contains(mock1)).isTrue(); UnmockableHashCodeAndEquals mock2 = mock(UnmockableHashCodeAndEquals.class); assertThat(mocks.contains(mock2)).isFalse(); } @Test public void can_remove() throws Exception { HashCodeAndEqualsSafeSet mocks = new HashCodeAndEqualsSafeSet(); UnmockableHashCodeAndEquals mock = mock1; mocks.add(mock); mocks.remove(mock); assertThat(mocks.isEmpty()).isTrue(); } @Test public void can_add_a_collection() throws Exception { HashCodeAndEqualsSafeSet mocks = HashCodeAndEqualsSafeSet.of(mock1, mock(Observer.class)); HashCodeAndEqualsSafeSet workingSet = new HashCodeAndEqualsSafeSet(); workingSet.addAll(mocks); assertThat(workingSet.containsAll(mocks)).isTrue(); } @Test public void can_retain_a_collection() throws Exception { HashCodeAndEqualsSafeSet mocks = HashCodeAndEqualsSafeSet.of(mock1, mock(Observer.class)); HashCodeAndEqualsSafeSet workingSet = new HashCodeAndEqualsSafeSet(); workingSet.addAll(mocks); workingSet.add(mock(List.class)); assertThat(workingSet.retainAll(mocks)).isTrue(); assertThat(workingSet.containsAll(mocks)).isTrue(); } @Test public void can_remove_a_collection() throws Exception { HashCodeAndEqualsSafeSet mocks = HashCodeAndEqualsSafeSet.of(mock1, mock(Observer.class)); HashCodeAndEqualsSafeSet workingSet = new HashCodeAndEqualsSafeSet(); workingSet.addAll(mocks); workingSet.add(mock(List.class)); assertThat(workingSet.removeAll(mocks)).isTrue(); assertThat(workingSet.containsAll(mocks)).isFalse(); } @Test public void can_iterate() throws Exception { HashCodeAndEqualsSafeSet mocks = HashCodeAndEqualsSafeSet.of(mock1, mock(Observer.class)); LinkedList<Object> accumulator = new LinkedList<Object>(); for (Object mock : mocks) { accumulator.add(mock); } assertThat(accumulator).isNotEmpty(); } @Test public void toArray_just_work() throws Exception { HashCodeAndEqualsSafeSet mocks = HashCodeAndEqualsSafeSet.of(mock1); assertThat(mocks.toArray()[0]).isSameAs(mock1); assertThat(mocks.toArray(new UnmockableHashCodeAndEquals[0])[0]).isSameAs(mock1); } @Test public void cloneIsNotSupported() { assertThatThrownBy( () -> { HashCodeAndEqualsSafeSet.of().clone(); }) .isInstanceOf(CloneNotSupportedException.class); } @Test public void isEmptyAfterClear() { HashCodeAndEqualsSafeSet set = HashCodeAndEqualsSafeSet.of(mock1); set.clear(); assertThat(set).isEmpty(); } @Test @SuppressWarnings("SelfAssertion") // https://github.com/google/error-prone/issues/5131 public void isEqualToItself() { HashCodeAndEqualsSafeSet set = HashCodeAndEqualsSafeSet.of(mock1); assertThat(set).isEqualTo(set); } @Test public void isNotEqualToAnOtherTypeOfSetWithSameContent() { HashCodeAndEqualsSafeSet set = HashCodeAndEqualsSafeSet.of(); assertThat(set).isNotEqualTo(new HashSet<Object>()); } @Test public void isNotEqualWhenContentIsDifferent() { HashCodeAndEqualsSafeSet set = HashCodeAndEqualsSafeSet.of(mock1); assertThat(set).isNotEqualTo(HashCodeAndEqualsSafeSet.of()); } @Test public void hashCodeIsEqualIfContentIsEqual() { HashCodeAndEqualsSafeSet set = HashCodeAndEqualsSafeSet.of(mock1); assertThat(set.hashCode()).isEqualTo(HashCodeAndEqualsSafeSet.of(mock1).hashCode()); } @Test public void toStringIsNotNullOrEmpty() throws Exception { HashCodeAndEqualsSafeSet set = HashCodeAndEqualsSafeSet.of(mock1); assertThat(set.toString()).isNotEmpty(); } @Test public void removeByIterator() throws Exception { HashCodeAndEqualsSafeSet set = HashCodeAndEqualsSafeSet.of(mock1); Iterator<Object> iterator = set.iterator(); iterator.next(); iterator.remove(); assertThat(set).isEmpty(); } private static
HashCodeAndEqualsSafeSetTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/converter/ConvertedConfigValidator.java
{ "start": 1744, "end": 3323 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(ConvertedConfigValidator.class); public void validateConvertedConfig(String outputDir) throws Exception { QueueMetrics.clearQueueMetrics(); Path configPath = new Path(outputDir, "capacity-scheduler.xml"); CapacitySchedulerConfiguration csConfig = new CapacitySchedulerConfiguration( new Configuration(false), false); csConfig.addResource(configPath); Path convertedSiteConfigPath = new Path(outputDir, "yarn-site.xml"); Configuration siteConf = new YarnConfiguration( new Configuration(false)); siteConf.addResource(convertedSiteConfigPath); RMContextImpl rmContext = new RMContextImpl(); siteConf.set(YarnConfiguration.FS_BASED_RM_CONF_STORE, outputDir); ConfigurationProvider provider = new FileSystemBasedConfigurationProvider(); provider.init(siteConf); rmContext.setConfigurationProvider(provider); RMNodeLabelsManager mgr = new RMNodeLabelsManager(); mgr.init(siteConf); rmContext.setNodeLabelManager(mgr); try (CapacityScheduler cs = new CapacityScheduler()) { cs.setConf(siteConf); cs.setRMContext(rmContext); cs.serviceInit(csConfig); cs.serviceStart(); LOG.info("Capacity scheduler was successfully started"); cs.serviceStop(); } catch (Exception e) { LOG.error("Could not start Capacity Scheduler", e); throw new VerificationException( "Verification of converted configuration failed", e); } } }
ConvertedConfigValidator
java
alibaba__fastjson
src/test/java/com/alibaba/json/test/entity/pagemodel/ComponentInstance.java
{ "start": 224, "end": 550 }
class ____ { protected Long sid; protected String cid; public Long getSid() { return sid; } public void setSid(Long sid) { this.sid = sid; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } }
ComponentInstance
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/TAEWallTest.java
{ "start": 831, "end": 1198 }
class ____ extends TestCase { public void test_true() throws Exception { assertTrue(WallUtils.isValidateMySql(// "select * from t where 1=1 AND status = 1")); } public void test_false() throws Exception { assertFalse(WallUtils.isValidateMySql(// "select * from t where status = 1 OR 1=1")); } }
TAEWallTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Issue944.java
{ "start": 243, "end": 536 }
class ____ extends TestCase { public void test_for_issue() throws Exception { Model model = new Model(); model.id = 1001; String text = JSON.toJSONString(model, SerializerFeature.SkipTransientField); assertEquals("{}", text); } public static
Issue944
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/inheritance/classrolesallowed/ClassRolesAllowedBaseResourceWithoutPathImplInterface_SecurityOnInterface.java
{ "start": 167, "end": 325 }
class ____ implements ClassRolesAllowedInterfaceWithPath_SecurityOnInterface { }
ClassRolesAllowedBaseResourceWithoutPathImplInterface_SecurityOnInterface
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerRequiredModifiers.java
{ "start": 15465, "end": 17991 }
class ____ hold the logger, and make the logger a private member of that class. */ fix.delete(member); return defineNestedClassWithLogger(topLevelClassInFile, state, fix); } } fix.addImport(GOOGLE_LOGGER); if (targetClassSym.isInterface()) { // Interfaces should get a nested class, not a normal field. return defineNestedClassWithLogger(topLevelClassInFile, state, fix); } String name = REASONABLE_LOGGER_NAMES.stream() .filter( candidate -> Iterables.isEmpty( targetClassSym.members().getSymbolsByName(state.getName(candidate)))) .findFirst() .orElseThrow(IllegalStateException::new); String newMember = String.format( "private static final FluentLogger %s =" + " FluentLogger.forEnclosingClass();", name); fix.merge( SuggestedFixes.addMembers(topLevelClassInFile, state, AdditionPosition.FIRST, newMember)); return new LocalLogger(LocalLogger.Provenance.DEFINED_BY_FIX, Optional.empty(), name); } private static LocalLogger defineNestedClassWithLogger( ClassTree topLevelClassInFile, VisitorState state, SuggestedFix.Builder fix) { fix.merge(SuggestedFixes.addMembers(topLevelClassInFile, state, NESTED_LOGGER_DEFINITION)); return new LocalLogger( LocalLogger.Provenance.DEFINED_BY_FIX, Optional.empty(), String.format("%s.%s", NESTED_LOGGER_CLASSNAME, NESTED_LOGGER_FIELDNAME)); } private static ClassTree outermostClassTree(TreePath path) { ClassTree result = null; while (path != null) { Tree leaf = path.getLeaf(); if (leaf instanceof ClassTree classTree) { result = classTree; } path = path.getParentPath(); } Verify.verifyNotNull(result, "No enclosing class"); return result; } private static boolean canHaveStaticFields(ClassSymbol enclosingClassSym) { return enclosingClassSym.getNestingKind() == NestingKind.TOP_LEVEL || enclosingClassSym.getNestingKind() == NestingKind.MEMBER && ((enclosingClassSym.flags() & Flags.STATIC) != 0); } @Override public Description matchIdentifier(IdentifierTree tree, VisitorState state) { return rehomeLogger(tree, state); } @Override public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) { return rehomeLogger(tree, state); } /** * If the expression refers to a FluentLogger owned by a
to
java
google__guice
tools/OsgiWrapper.java
{ "start": 481, "end": 3981 }
class ____ implements Callable<Integer> { private static final String REMOVEHEADERS = Arrays.stream( new String[] { "Embed-Dependency", "Embed-Transitive", "Built-By", "Tool", "Created-By", "Build-Jdk", "Originally-Created-By", "Archiver-Version", "Include-Resource", "Private-Package", "Ignore-Package", "Bnd-LastModified" }) .collect(Collectors.joining(",")); private static final String DESCRIPTION = "Guice is a lightweight dependency injection framework for Java 11 and above"; private static final String COPYRIGHT = "Copyright (C) 2022 Google Inc."; private static final String DOC_URL = "https://github.com/google/guice"; @Option( names = {"--input_jar"}, description = "The jar file to wrap with OSGi metadata") private File inputJar; @Option( names = {"--output_jar"}, description = "Output path to the wrapped jar") private File outputJar; @Option( names = {"--classpath"}, description = "The classpath that contains dependencies of the input jar, separated with :") private String classpath; @Option( names = {"--bundle_name"}, description = "The name of the bundle") private String bundleName; @Option( names = {"--import_package"}, description = "The imported packages from this bundle") private String importPackage; @Option( names = {"--fragment"}, description = "Whether this bundle is a fragment") private boolean fragment; @Option( names = {"--export_package"}, description = "The exported packages from this bundle") private String exportPackage; @Option( names = {"--symbolic_name"}, description = "The symbolic name of the bundle") private String symbolicName; @Option( names = {"--bundle_version"}, description = "The version of the bundle") private String bundleVersion; @Override public Integer call() throws Exception { Analyzer analyzer = new Analyzer(); Jar bin = new Jar(inputJar); analyzer.setJar(bin); analyzer.setProperty(Analyzer.BUNDLE_NAME, bundleName); analyzer.setProperty(Analyzer.BUNDLE_SYMBOLICNAME, symbolicName); analyzer.setProperty(Analyzer.BUNDLE_VERSION, bundleVersion); analyzer.setProperty(Analyzer.IMPORT_PACKAGE, importPackage); analyzer.setProperty(Analyzer.EXPORT_PACKAGE, exportPackage); if (fragment) { analyzer.setProperty(Analyzer.FRAGMENT_HOST, "com.google.inject"); } analyzer.setProperty(Analyzer.NOUSES, "true"); analyzer.setProperty(Analyzer.BUNDLE_DESCRIPTION, DESCRIPTION); analyzer.setProperty(Analyzer.BUNDLE_COPYRIGHT, COPYRIGHT); analyzer.setProperty(Analyzer.BUNDLE_DOCURL, DOC_URL); analyzer.setProperty(Analyzer.REMOVEHEADERS, REMOVEHEADERS); for (String dep : Arrays.asList(classpath.split(":"))) { analyzer.addClasspath(new File(dep)); } analyzer.analyze(); Manifest manifest = analyzer.calcManifest(); if (analyzer.isOk()) { analyzer.getJar().setManifest(manifest); if (analyzer.save(outputJar, true)) { return 0; } } return 1; } public static void main(String[] args) { int exitCode = new CommandLine(new OsgiWrapper()).execute(args); System.exit(exitCode); } }
OsgiWrapper
java
quarkusio__quarkus
extensions/spring-di/deployment/src/test/java/io/quarkus/spring/di/deployment/SpringDIProcessorTest.java
{ "start": 11426, "end": 11491 }
class ____ { } @ConflictService public
ConflictNamedBean
java
apache__camel
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindySimpleCsvBooleanUnmarshallTest.java
{ "start": 4082, "end": 4765 }
class ____ extends RouteBuilder { BindyCsvDataFormat camelDataFormat = new BindyCsvDataFormat( org.apache.camel.dataformat.bindy.model.simple.bool.BooleanExample.class); @Override public void configure() { // from("file://src/test/data?move=./target/done").unmarshal(camelDataFormat).to("mock:result"); // default should errors go to mock:error errorHandler(deadLetterChannel(URI_MOCK_ERROR).redeliveryDelay(0)); onException(Exception.class).maximumRedeliveries(0).handled(true); from(URI_DIRECT_START).unmarshal(camelDataFormat).to(URI_MOCK_RESULT); } } }
ContextConfig
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/activities/ActivitiesLogger.java
{ "start": 11600, "end": 12660 }
class ____ { /* * Record activities of a queue */ public static void recordQueueActivity(ActivitiesManager activitiesManager, SchedulerNode node, String parentQueueName, String queueName, ActivityState state, String diagnostic) { recordQueueActivity(activitiesManager, node, parentQueueName, queueName, state, () -> diagnostic); } public static void recordQueueActivity(ActivitiesManager activitiesManager, SchedulerNode node, String parentQueueName, String queueName, ActivityState state, Supplier<String> diagnosticSupplier) { if (activitiesManager == null) { return; } NodeId nodeId = getRecordingNodeId(activitiesManager, node); if (activitiesManager.shouldRecordThisNode(nodeId)) { recordActivity(activitiesManager, nodeId, parentQueueName, queueName, null, state, diagnosticSupplier.get(), ActivityLevel.QUEUE); } } } /** * Methods for recording overall activities from one node update */ public static
QUEUE
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/generation/multipart/FormDataOutputMapperGenerator.java
{ "start": 1448, "end": 2110 }
class ____ { private static final Logger LOGGER = Logger.getLogger(FormDataOutputMapperGenerator.class); private static final String TRANSFORM_METHOD_NAME = "mapFrom"; private static final String ADD_FORM_DATA_METHOD_NAME = "addFormData"; private FormDataOutputMapperGenerator() { } /** * Returns true whether the returning type uses either {@link org.jboss.resteasy.reactive.RestForm} * or {@link org.jboss.resteasy.reactive.server.core.multipart.FormData} annotations. */ public static boolean isReturnTypeCompatible(ClassInfo returnTypeClassInfo, IndexView index) { // go up the
FormDataOutputMapperGenerator
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/testers/SetCreationTester.java
{ "start": 1897, "end": 3622 }
class ____<E> extends AbstractSetTester<E> { @CollectionFeature.Require(value = ALLOWS_NULL_VALUES, absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nullDuplicatesNotRejected() { E[] array = createArrayWithNullElement(); array[0] = null; collection = getSubjectGenerator().create(array); List<E> expectedWithDuplicateRemoved = asList(array).subList(1, getNumElements()); expectContents(expectedWithDuplicateRemoved); } @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() { E[] array = createSamplesArray(); array[1] = e0(); collection = getSubjectGenerator().create(array); List<E> expectedWithDuplicateRemoved = asList(array).subList(1, getNumElements()); expectContents(expectedWithDuplicateRemoved); } @CollectionFeature.Require({ALLOWS_NULL_VALUES, REJECTS_DUPLICATES_AT_CREATION}) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nullDuplicatesRejected() { E[] array = createArrayWithNullElement(); array[0] = null; assertThrows( IllegalArgumentException.class, () -> collection = getSubjectGenerator().create(array)); } @CollectionFeature.Require(REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nonNullDuplicatesRejected() { E[] array = createSamplesArray(); array[1] = e0(); assertThrows( IllegalArgumentException.class, () -> collection = getSubjectGenerator().create(array)); } }
SetCreationTester
java
quarkusio__quarkus
extensions/security/test-utils/src/main/java/io/quarkus/security/test/utils/AuthData.java
{ "start": 225, "end": 1666 }
class ____ { public final Set<String> roles; public final boolean anonymous; public final String name; public final Set<Permission> permissions; public final boolean applyAugmentors; public AuthData(Set<String> roles, boolean anonymous, String name) { this.roles = roles; this.anonymous = anonymous; this.name = name; this.permissions = null; this.applyAugmentors = false; } public AuthData(Set<String> roles, boolean anonymous, String name, Set<Permission> permissions) { this.roles = roles; this.anonymous = anonymous; this.name = name; this.permissions = permissions; this.applyAugmentors = false; } public AuthData(Set<String> roles, boolean anonymous, String name, Set<Permission> permissions, boolean applyAugmentors) { this.roles = roles; this.anonymous = anonymous; this.name = name; this.permissions = permissions; this.applyAugmentors = applyAugmentors; } public AuthData(AuthData authData, boolean applyAugmentors) { this(authData.roles, authData.anonymous, authData.name, authData.permissions, applyAugmentors); } public AuthData(AuthData authData, boolean applyAugmentors, Permission... permissions) { this(authData.roles, authData.anonymous, authData.name, new HashSet<>(Arrays.asList(permissions)), applyAugmentors); } }
AuthData
java
elastic__elasticsearch
x-pack/plugin/sql/sql-proto/src/main/java/org/elasticsearch/xpack/sql/proto/content/AbstractObjectParser.java
{ "start": 1827, "end": 1888 }
class ____ the same name in ES XContent. */ public abstract
with
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/TextExpansionConfigTests.java
{ "start": 580, "end": 2505 }
class ____ extends InferenceConfigItemTestCase<TextExpansionConfig> { public static TextExpansionConfig createRandom() { // create a tokenization config with a no span setting. var tokenization = new BertTokenization( randomBoolean() ? null : randomBoolean(), randomBoolean() ? null : randomBoolean(), randomBoolean() ? null : randomIntBetween(1, 1024), randomBoolean() ? null : randomFrom(Tokenization.Truncate.FIRST), null ); return new TextExpansionConfig( randomBoolean() ? null : VocabularyConfigTests.createRandom(), randomBoolean() ? null : tokenization, randomBoolean() ? null : randomAlphaOfLength(5) ); } public static TextExpansionConfig mutateForVersion(TextExpansionConfig instance, TransportVersion version) { return new TextExpansionConfig( instance.getVocabularyConfig(), InferenceConfigTestScaffolding.mutateTokenizationForVersion(instance.getTokenization(), version), instance.getResultsField() ); } @Override protected Writeable.Reader<TextExpansionConfig> instanceReader() { return TextExpansionConfig::new; } @Override protected TextExpansionConfig createTestInstance() { return createRandom(); } @Override protected TextExpansionConfig mutateInstance(TextExpansionConfig instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected TextExpansionConfig doParseInstance(XContentParser parser) throws IOException { return TextExpansionConfig.fromXContentLenient(parser); } @Override protected TextExpansionConfig mutateInstanceForVersion(TextExpansionConfig instance, TransportVersion version) { return instance; } }
TextExpansionConfigTests
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/typeinfo/Types.java
{ "start": 11447, "end": 12358 }
class ____ extends Tuple2<Integer, String> { * * public int getId() { return f0; } * * public String getName() { return f1; } * } * } * * Types.TUPLE(MyTuple.class) * </pre> * * @param tupleSubclass A subclass of {@link org.apache.flink.api.java.tuple.Tuple0} till {@link * org.apache.flink.api.java.tuple.Tuple25} that defines all field types and does not add * any additional fields */ public static <T extends Tuple> TypeInformation<T> TUPLE(Class<T> tupleSubclass) { final TypeInformation<T> ti = TypeExtractor.createTypeInfo(tupleSubclass); if (ti instanceof TupleTypeInfo) { return ti; } throw new InvalidTypesException("Tuple type expected but was: " + ti); } /** * Returns type information for a POJO (Plain Old Java Object). * * <p>A POJO
MyTuple
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/AutoValueBoxedValuesTest.java
{ "start": 24276, "end": 25813 }
class ____ { abstract int foo(); abstract Long bar(); static Test createTrivial(int foo, Long bar) { return new AutoValue_Test(foo, bar); } static String notFactoryMethod(int foo, Long bar) { return String.format("foo: %d, bar: %d", foo, bar); } static Test createWrongOrder(Long bar, int foo) { return new AutoValue_Test(foo, bar); } static Test createLessArguments(int foo) { return new AutoValue_Test(foo, 0L); } static Test createMoreArguments(int foo, Long bar, Long baz) { return new AutoValue_Test(foo, bar + baz); } static Test createWithValidation(int foo, Long bar) { if (bar == null) { throw new AssertionError(); } return new AutoValue_Test(foo, bar); } static Test createModifyArgs(int foo, Long bar) { return new AutoValue_Test(foo + 1, bar); } static Test createModifyArgsIfNull(int foo, Long bar) { return new AutoValue_Test(foo, bar == null ? 0L : bar); } } """) .addOutputLines( "out/Test.java", """ package test; import com.google.auto.value.AutoValue; @AutoValue abstract
Test
java
spring-projects__spring-boot
module/spring-boot-security/src/test/java/org/springframework/boot/security/autoconfigure/ReactiveUserDetailsServiceAutoConfigurationTests.java
{ "start": 9417, "end": 9717 }
class ____ { @Bean ReactiveAuthenticationManagerResolver<?> reactiveAuthenticationManagerResolver() { return mock(ReactiveAuthenticationManagerResolver.class); } } @Configuration(proxyBeanMethods = false) @Import(TestSecurityConfiguration.class) static
AuthenticationManagerResolverConfig
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/SelfAlwaysReturnsThisTest.java
{ "start": 1636, "end": 2036 }
class ____ { public Builder self() { return (Builder) this; } } """) .expectUnchanged() .doTest(); } @Test public void selfReturnsThis_withParenthesizedCast() { helper .addInputLines( "Builder.java", """ package com.google.frobber; public final
Builder
java
netty__netty
codec-classes-quic/src/main/java/io/netty/handler/codec/quic/QuicheQuicSslEngineMap.java
{ "start": 816, "end": 1234 }
class ____ { private final ConcurrentMap<Long, QuicheQuicSslEngine> engines = new ConcurrentHashMap<>(); @Nullable QuicheQuicSslEngine get(long ssl) { return engines.get(ssl); } @Nullable QuicheQuicSslEngine remove(long ssl) { return engines.remove(ssl); } void put(long ssl, QuicheQuicSslEngine engine) { engines.put(ssl, engine); } }
QuicheQuicSslEngineMap
java
grpc__grpc-java
core/src/testFixtures/java/io/grpc/internal/WritableBufferTestBase.java
{ "start": 835, "end": 932 }
class ____ tests of {@link WritableBuffer} subclasses. */ @RunWith(JUnit4.class) public abstract
for
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/util/SampleQuantiles.java
{ "start": 1906, "end": 8259 }
class ____ implements QuantileEstimator { /** * Total number of items in stream */ private long count = 0; /** * Current list of sampled items, maintained in sorted order with error bounds */ private LinkedList<SampleItem> samples; /** * Buffers incoming items to be inserted in batch. Items are inserted into * the buffer linearly. When the buffer fills, it is flushed into the samples * array in its entirety. */ private long[] buffer = new long[500]; private int bufferCount = 0; /** * Array of Quantiles that we care about, along with desired error. */ private final Quantile quantiles[]; public SampleQuantiles(Quantile[] quantiles) { this.quantiles = quantiles; this.samples = new LinkedList<SampleItem>(); } /** * Specifies the allowable error for this rank, depending on which quantiles * are being targeted. * * This is the f(r_i, n) function from the CKMS paper. It's basically how wide * the range of this rank can be. * * @param rank * the index in the list of samples */ private double allowableError(int rank) { int size = samples.size(); double minError = size + 1; for (Quantile q : quantiles) { double error; if (rank <= q.quantile * size) { error = (2.0 * q.error * (size - rank)) / (1.0 - q.quantile); } else { error = (2.0 * q.error * rank) / q.quantile; } if (error < minError) { minError = error; } } return minError; } /** * Add a new value from the stream. * * @param v v. */ synchronized public void insert(long v) { buffer[bufferCount] = v; bufferCount++; count++; if (bufferCount == buffer.length) { insertBatch(); compress(); } } /** * Merges items from buffer into the samples array in one pass. * This is more efficient than doing an insert on every item. */ private void insertBatch() { if (bufferCount == 0) { return; } Arrays.sort(buffer, 0, bufferCount); // Base case: no samples int start = 0; if (samples.size() == 0) { SampleItem newItem = new SampleItem(buffer[0], 1, 0); samples.add(newItem); start++; } ListIterator<SampleItem> it = samples.listIterator(); SampleItem item = it.next(); for (int i = start; i < bufferCount; i++) { long v = buffer[i]; while (it.nextIndex() < samples.size() && item.value < v) { item = it.next(); } // If we found that bigger item, back up so we insert ourselves before it if (item.value > v) { it.previous(); } // We use different indexes for the edge comparisons, because of the above // if statement that adjusts the iterator int delta; if (it.previousIndex() == 0 || it.nextIndex() == samples.size()) { delta = 0; } else { delta = ((int) Math.floor(allowableError(it.nextIndex()))) - 1; } SampleItem newItem = new SampleItem(v, 1, delta); it.add(newItem); item = newItem; } bufferCount = 0; } /** * Try to remove extraneous items from the set of sampled items. This checks * if an item is unnecessary based on the desired error bounds, and merges it * with the adjacent item if it is. */ private void compress() { if (samples.size() < 2) { return; } ListIterator<SampleItem> it = samples.listIterator(); SampleItem prev = null; SampleItem next = it.next(); while (it.hasNext()) { prev = next; next = it.next(); if (prev.g + next.g + next.delta <= allowableError(it.previousIndex())) { next.g += prev.g; // Remove prev. it.remove() kills the last thing returned. it.previous(); it.previous(); it.remove(); // it.next() is now equal to next, skip it back forward again it.next(); } } } /** * Get the estimated value at the specified quantile. * * @param quantile Queried quantile, e.g. 0.50 or 0.99. * @return Estimated value at that quantile. */ private long query(double quantile) { Preconditions.checkState(!samples.isEmpty(), "no data in estimator"); int rankMin = 0; int desired = (int) (quantile * count); ListIterator<SampleItem> it = samples.listIterator(); SampleItem prev = null; SampleItem cur = it.next(); for (int i = 1; i < samples.size(); i++) { prev = cur; cur = it.next(); rankMin += prev.g; if (rankMin + cur.g + cur.delta > desired + (allowableError(i) / 2)) { return prev.value; } } // edge case of wanting max value return samples.get(samples.size() - 1).value; } /** * Get a snapshot of the current values of all the tracked quantiles. * * @return snapshot of the tracked quantiles. If no items are added * to the estimator, returns null. */ synchronized public Map<Quantile, Long> snapshot() { // flush the buffer first for best results insertBatch(); if (samples.isEmpty()) { return null; } Map<Quantile, Long> values = new TreeMap<Quantile, Long>(); for (int i = 0; i < quantiles.length; i++) { values.put(quantiles[i], query(quantiles[i].quantile)); } return values; } /** * Returns the number of items that the estimator has processed * * @return count total number of items processed */ synchronized public long getCount() { return count; } /** * Returns the number of samples kept by the estimator * * @return count current number of samples */ @VisibleForTesting synchronized public int getSampleCount() { return samples.size(); } /** * Resets the estimator, clearing out all previously inserted items */ synchronized public void clear() { count = 0; bufferCount = 0; samples.clear(); } @Override synchronized public String toString() { Map<Quantile, Long> data = snapshot(); if (data == null) { return "[no samples]"; } else { return Joiner.on("\n").withKeyValueSeparator(": ").join(data); } } /** * Describes a measured value passed to the estimator, tracking additional * metadata required by the CKMS algorithm. */ private static
SampleQuantiles
java
spring-projects__spring-boot
module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java
{ "start": 3384, "end": 4089 }
class ____ { public final Environment environment; Config(Environment environment) { this.environment = environment; } @Bean ClassPathFileSystemWatcher watcher(ClassPathRestartStrategy restartStrategy) { FileSystemWatcher watcher = new FileSystemWatcher(false, Duration.ofMillis(100), Duration.ofMillis(10)); URL[] urls = this.environment.getProperty("urls", URL[].class); assertThat(urls).isNotNull(); return new ClassPathFileSystemWatcher(new MockFileSystemWatcherFactory(watcher), restartStrategy, urls); } @Bean ClassPathRestartStrategy restartStrategy() { return (file) -> false; } @Bean Listener listener() { return new Listener(); } } static
Config
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/commons/util/CollectionUtilsTests.java
{ "start": 2088, "end": 2893 }
class ____ { @SuppressWarnings("DataFlowIssue") @Test void nullCollection() { assertPreconditionViolationNotNullFor("collection", () -> CollectionUtils.getOnlyElement(null)); } @Test void emptyCollection() { assertPreconditionViolationFor(() -> CollectionUtils.getOnlyElement(Set.of()))// .withMessage("collection must contain exactly one element: []"); } @Test void singleElementCollection() { var expected = new Object(); var actual = CollectionUtils.getOnlyElement(Set.of(expected)); assertSame(expected, actual); } @Test void multiElementCollection() { assertPreconditionViolationFor(() -> CollectionUtils.getOnlyElement(List.of("foo", "bar")))// .withMessage("collection must contain exactly one element: [foo, bar]"); } } @Nested
OnlyElement
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RVectorSetReactive.java
{ "start": 1065, "end": 4734 }
interface ____ extends RExpirableReactive { /** * Adds an element * * @param args add arguments * @return <code>true</code> if element was added and <code>false</code> if updated */ Mono<Boolean> add(VectorAddArgs args); /** * Returns the number of elements * * @return number of elements */ Mono<Integer> size(); /** * Returns the number of dimensions of vectors * * @return dimensions count */ Mono<Integer> dimensions(); /** * Retrieves approximate vector associated with a given element name * * @param name element name * @return list of vector coordinates */ Mono<List<Double>> getVector(String name); /** * Retrieves raw internal representation of * the approximate vector associated with a given element name * * @param name element name * @return list of raw vector values */ Mono<List<Object>> getRawVector(String name); /** * Retrieves attributes associated with a given element name * * @param name element name * @param clazz type for deserialization * @return attributes */ <T> Mono<T> getAttributes(String name, Class<T> clazz); /** * Returns metadata for this vector set * * @return vector set information */ Mono<VectorInfo> getInfo(); /** * Retrieves the neighbors of a specified element by name * * @param element element name * @return list of neighbor element names */ Mono<List<String>> getNeighbors(String element); /** * Retrieves the neighbors with scores of a specified element by name * * @param element element name * @return list of neighbor elements with scores */ Mono<List<ScoredEntry<String>>> getNeighborEntries(String element); /** * Returns a random element name * * @return random element name */ Mono<String> random(); /** * Returns random element names * * @param count number of elements to return * @return list of random element names */ Mono<List<String>> random(int count); /** * Removes an element by name * * @param element element name to remove * @return <code>true</code> if element was removed, <code>false</code> otherwise */ Mono<Boolean> remove(String element); /** * Sets attributes for an element by name * * @param element element name * @param attributes attributes * @param jsonCodec json codec for attributes serialization * @return <code>true</code> if attributes were set, <code>false</code> otherwise */ Mono<Boolean> setAttributes(String element, Object attributes, JsonCodec jsonCodec); /** * Retrieves element names similar to a specified vector or element * * @param args vector similarity arguments * @return list of similar element names */ Mono<List<String>> getSimilar(VectorSimilarArgs args); /** * Retrieves element names with scores similar to a given vector or element * * @param args similarity arguments * @return list of similar element names with scores */ Mono<List<ScoredEntry<String>>> getSimilarEntries(VectorSimilarArgs args); /** * Retrieves element names with scores and attributes similar to a given vector or element * * @param args similarity arguments * @return list of similar element names with scores and attributes */ Mono<List<ScoreAttributesEntry<String>>> getSimilarEntriesWithAttributes(VectorSimilarArgs args); }
RVectorSetReactive
java
apache__camel
components/camel-bean-validator/src/test/java/org/apache/camel/component/bean/validator/BeanValidatorConfigurationTest.java
{ "start": 4292, "end": 4631 }
class ____ implements ConstraintValidatorFactory { @Override public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) { return null; } @Override public void releaseInstance(ConstraintValidator<?, ?> arg0) { // noop } } }
MyConstraintValidatorFactory
java
google__truth
core/src/test/java/com/google/common/truth/IterableSubjectTest.java
{ "start": 54511, "end": 54620 }
class ____ { private final int x; private Foo(int x) { this.x = x; } } private static
Foo
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/internal/AbstractInvocationHandler.java
{ "start": 2220, "end": 2428 }
class ____ the method through. * * @param args an array of objects containing the values of the arguments passed in the method invocation on the proxy * instance, or {@code null} if
inherits
java
quarkusio__quarkus
integration-tests/mongodb-panache/src/main/java/io/quarkus/it/mongodb/panache/bugs/AbstractRepository.java
{ "start": 115, "end": 196 }
class ____<T> implements PanacheMongoRepositoryBase<T, String> { }
AbstractRepository
java
elastic__elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/slack/message/Field.java
{ "start": 1885, "end": 6786 }
class ____ implements ToXContentObject { final TextTemplate title; final TextTemplate value; final Boolean isShort; Template(TextTemplate title, TextTemplate value, Boolean isShort) { this.title = title; this.value = value; this.isShort = isShort; } public Field render( TextTemplateEngine engine, Map<String, Object> model, SlackMessageDefaults.AttachmentDefaults.FieldDefaults defaults ) { String title = this.title != null ? engine.render(this.title, model) : defaults.title; String value = this.value != null ? engine.render(this.value, model) : defaults.value; Boolean isShort = this.isShort != null ? this.isShort : defaults.isShort; return new Field(title, value, isShort); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Template template = (Template) o; if (isShort != template.isShort) return false; if (title.equals(template.title) == false) return false; return value.equals(template.value); } @Override public int hashCode() { int result = title.hashCode(); result = 31 * result + value.hashCode(); result = 31 * result + (isShort ? 1 : 0); return result; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.startObject() .field(XField.TITLE.getPreferredName(), title) .field(XField.VALUE.getPreferredName(), value) .field(XField.SHORT.getPreferredName(), isShort) .endObject(); } public static Template parse(XContentParser parser) throws IOException { TextTemplate title = null; TextTemplate value = null; boolean isShort = false; XContentParser.Token token = null; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (XField.TITLE.match(currentFieldName, parser.getDeprecationHandler())) { try { title = TextTemplate.parse(parser); } catch (ElasticsearchParseException pe) { throw new ElasticsearchParseException( "could not parse message attachment field. failed to parse [{}] field", pe, XField.TITLE ); } } else if (XField.VALUE.match(currentFieldName, parser.getDeprecationHandler())) { try { value = TextTemplate.parse(parser); } catch (ElasticsearchParseException pe) { throw new ElasticsearchParseException( "could not parse message attachment field. failed to parse [{}] field", pe, XField.VALUE ); } } else if (XField.SHORT.match(currentFieldName, parser.getDeprecationHandler())) { if (token == XContentParser.Token.VALUE_BOOLEAN) { isShort = parser.booleanValue(); } else { throw new ElasticsearchParseException( "could not parse message attachment field. expected a boolean value for " + "[{}] field, but found [{}]", XField.SHORT, token ); } } else { throw new ElasticsearchParseException( "could not parse message attachment field. unexpected field [{}]", currentFieldName ); } } if (title == null) { throw new ElasticsearchParseException( "could not parse message attachment field. missing required [{}] field", XField.TITLE ); } if (value == null) { throw new ElasticsearchParseException( "could not parse message attachment field. missing required [{}] field", XField.VALUE ); } return new Template(title, value, isShort); } }
Template
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice/src/test/java/org/apache/hadoop/yarn/server/timelineservice/collector/TestPerNodeAggTimelineCollectorMetrics.java
{ "start": 1272, "end": 2004 }
class ____ { private PerNodeAggTimelineCollectorMetrics metrics; @Test void testTimelineCollectorMetrics() { assertNotNull(metrics); assertEquals(10, metrics.getPutEntitiesSuccessLatency().getInterval()); assertEquals(10, metrics.getPutEntitiesFailureLatency().getInterval()); assertEquals(10, metrics.getAsyncPutEntitiesSuccessLatency().getInterval()); assertEquals(10, metrics.getAsyncPutEntitiesFailureLatency().getInterval()); } @BeforeEach public void setup() { metrics = PerNodeAggTimelineCollectorMetrics.getInstance(); } @AfterEach public void tearDown() { PerNodeAggTimelineCollectorMetrics.destroy(); } }
TestPerNodeAggTimelineCollectorMetrics
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/jackson/RememberMeAuthenticationTokenMixin.java
{ "start": 1671, "end": 2283 }
class ____ { /** * Constructor used by Jackson to create * {@link org.springframework.security.authentication.RememberMeAuthenticationToken} * object. * @param keyHash hashCode of above given key. * @param principal the principal (typically a <code>UserDetails</code>) * @param authorities the authorities granted to the principal */ @JsonCreator RememberMeAuthenticationTokenMixin(@JsonProperty("keyHash") Integer keyHash, @JsonProperty("principal") Object principal, @JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities) { } }
RememberMeAuthenticationTokenMixin
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/builditem/ConsoleCommandBuildItem.java
{ "start": 495, "end": 1364 }
class ____ extends MultiBuildItem { final CommandContainer consoleCommand; public ConsoleCommandBuildItem(CommandContainer consoleCommand) { this.consoleCommand = consoleCommand; } public ConsoleCommandBuildItem(ProcessedCommand consoleCommand) { this.consoleCommand = new AeshCommandContainer( CommandLineParserBuilder.builder() .processedCommand(consoleCommand) .create()); } public ConsoleCommandBuildItem(Command<?> consoleCommand) { try { this.consoleCommand = new AeshCommandContainerBuilder().create(consoleCommand); } catch (CommandLineParserException e) { throw new RuntimeException(e); } } public CommandContainer getConsoleCommand() { return consoleCommand; } }
ConsoleCommandBuildItem
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/net/impl/MappingLookup.java
{ "start": 213, "end": 610 }
class ____<A extends Address, B> { private static final List INITIAL = Collections.singletonList(new Object()); final A address; final EndpointBuilder<B, SocketAddress> builder; List<SocketAddress> endpoints; B list; MappingLookup(A name, EndpointBuilder<B, SocketAddress> builder) { this.endpoints = INITIAL; this.address = name; this.builder = builder; } }
MappingLookup
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/error/ShouldHaveSuperclass.java
{ "start": 764, "end": 842 }
class ____ a given superclass failed. * * @author Stefano Cordio */ public
has
java
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/support/ModifierSupport.java
{ "start": 5699, "end": 6240 }
class ____ {@code static} * @see java.lang.reflect.Modifier#isStatic(int) */ public static boolean isStatic(Class<?> clazz) { return ReflectionUtils.isStatic(clazz); } /** * Determine if the supplied member is {@code static}. * * @param member the member to check; never {@code null} * @return {@code true} if the member is {@code static} * @see java.lang.reflect.Modifier#isStatic(int) */ public static boolean isStatic(Member member) { return ReflectionUtils.isStatic(member); } /** * Determine if the supplied
is
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/json/DB2JsonObjectFunction.java
{ "start": 373, "end": 780 }
class ____ extends JsonObjectFunction { public DB2JsonObjectFunction(TypeConfiguration typeConfiguration) { super( typeConfiguration, false ); } @Override protected void renderValue(SqlAppender sqlAppender, SqlAstNode value, SqlAstTranslator<?> walker) { value.accept( walker ); if ( ExpressionTypeHelper.isJson( value ) ) { sqlAppender.appendSql( " format json" ); } } }
DB2JsonObjectFunction