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
elastic__elasticsearch
modules/transport-netty4/src/test/java/org/elasticsearch/transport/netty4/NettyTransportMultiPortTests.java
{ "start": 1370, "end": 5098 }
class ____ extends ESTestCase { private String host; @Before public void setup() { if (NetworkUtils.SUPPORTS_V6 && randomBoolean()) { host = "::1"; } else { host = "127.0.0.1"; } } public void testThatNettyCanBindToMultiplePorts() throws Exception { Settings settings = Settings.builder() .put("network.host", host) .put(TransportSettings.PORT.getKey(), 22) // will not actually bind to this .put("transport.profiles.default.port", 0) .put("transport.profiles.client1.port", 0) .build(); ThreadPool threadPool = new TestThreadPool("tst"); try (TcpTransport transport = startTransport(settings, threadPool)) { assertEquals(1, transport.profileBoundAddresses().size()); assertEquals(1, transport.boundAddress().boundAddresses().length); } finally { terminate(threadPool); } } public void testThatDefaultProfileInheritsFromStandardSettings() throws Exception { Settings settings = Settings.builder() .put("network.host", host) .put(TransportSettings.PORT.getKey(), 0) .put("transport.profiles.client1.port", 0) .build(); ThreadPool threadPool = new TestThreadPool("tst"); try (TcpTransport transport = startTransport(settings, threadPool)) { assertEquals(1, transport.profileBoundAddresses().size()); assertEquals(1, transport.boundAddress().boundAddresses().length); } finally { terminate(threadPool); } } public void testThatProfileWithoutPortSettingsFails() throws Exception { Settings settings = Settings.builder() .put("network.host", host) .put(TransportSettings.PORT.getKey(), 0) .put("transport.profiles.client1.whatever", "foo") .build(); ThreadPool threadPool = new TestThreadPool("tst"); try { IllegalStateException ex = expectThrows(IllegalStateException.class, () -> startTransport(settings, threadPool)); assertEquals("profile [client1] has no port configured", ex.getMessage()); } finally { terminate(threadPool); } } public void testThatDefaultProfilePortOverridesGeneralConfiguration() throws Exception { Settings settings = Settings.builder() .put("network.host", host) .put(TransportSettings.PORT.getKey(), 22) // will not actually bind to this .put("transport.profiles.default.port", 0) .build(); ThreadPool threadPool = new TestThreadPool("tst"); try (TcpTransport transport = startTransport(settings, threadPool)) { assertEquals(0, transport.profileBoundAddresses().size()); assertEquals(1, transport.boundAddress().boundAddresses().length); } finally { terminate(threadPool); } } private TcpTransport startTransport(Settings settings, ThreadPool threadPool) { PageCacheRecycler recycler = new MockPageCacheRecycler(Settings.EMPTY); TcpTransport transport = new Netty4Transport( settings, TransportVersion.current(), threadPool, new NetworkService(Collections.emptyList()), recycler, new NamedWriteableRegistry(Collections.emptyList()), new NoneCircuitBreakerService(), new SharedGroupFactory(settings) ); transport.start(); assertThat(transport.lifecycleState(), is(Lifecycle.State.STARTED)); return transport; } }
NettyTransportMultiPortTests
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointStatsCountsTest.java
{ "start": 992, "end": 7132 }
class ____ { /** Tests that counts are reported correctly. */ @Test void testCounts() { CheckpointStatsCounts counts = new CheckpointStatsCounts(); assertThat(counts.getNumberOfRestoredCheckpoints()).isZero(); assertThat(counts.getTotalNumberOfCheckpoints()).isZero(); assertThat(counts.getNumberOfInProgressCheckpoints()).isZero(); assertThat(counts.getNumberOfCompletedCheckpoints()).isZero(); assertThat(counts.getNumberOfFailedCheckpoints()).isZero(); counts.incrementRestoredCheckpoints(); assertThat(counts.getNumberOfRestoredCheckpoints()).isOne(); assertThat(counts.getTotalNumberOfCheckpoints()).isZero(); assertThat(counts.getNumberOfInProgressCheckpoints()).isZero(); assertThat(counts.getNumberOfCompletedCheckpoints()).isZero(); assertThat(counts.getNumberOfFailedCheckpoints()).isZero(); // 1st checkpoint counts.incrementInProgressCheckpoints(); assertThat(counts.getNumberOfRestoredCheckpoints()).isOne(); assertThat(counts.getTotalNumberOfCheckpoints()).isOne(); assertThat(counts.getNumberOfInProgressCheckpoints()).isOne(); assertThat(counts.getNumberOfCompletedCheckpoints()).isZero(); assertThat(counts.getNumberOfFailedCheckpoints()).isZero(); counts.incrementCompletedCheckpoints(); assertThat(counts.getNumberOfRestoredCheckpoints()).isOne(); assertThat(counts.getTotalNumberOfCheckpoints()).isOne(); assertThat(counts.getNumberOfInProgressCheckpoints()).isZero(); assertThat(counts.getNumberOfCompletedCheckpoints()).isOne(); assertThat(counts.getNumberOfFailedCheckpoints()).isZero(); // 2nd checkpoint counts.incrementInProgressCheckpoints(); assertThat(counts.getNumberOfRestoredCheckpoints()).isOne(); assertThat(counts.getTotalNumberOfCheckpoints()).isEqualTo(2); assertThat(counts.getNumberOfInProgressCheckpoints()).isOne(); assertThat(counts.getNumberOfCompletedCheckpoints()).isOne(); assertThat(counts.getNumberOfFailedCheckpoints()).isZero(); counts.incrementFailedCheckpoints(); assertThat(counts.getNumberOfRestoredCheckpoints()).isOne(); assertThat(counts.getTotalNumberOfCheckpoints()).isEqualTo(2); assertThat(counts.getNumberOfInProgressCheckpoints()).isZero(); assertThat(counts.getNumberOfCompletedCheckpoints()).isOne(); assertThat(counts.getNumberOfFailedCheckpoints()).isOne(); counts.incrementFailedCheckpointsWithoutInProgress(); assertThat(counts.getNumberOfRestoredCheckpoints()).isOne(); assertThat(counts.getTotalNumberOfCheckpoints()).isEqualTo(3); assertThat(counts.getNumberOfInProgressCheckpoints()).isZero(); assertThat(counts.getNumberOfCompletedCheckpoints()).isOne(); assertThat(counts.getNumberOfFailedCheckpoints()).isEqualTo(2); } /** * Tests that increment the completed or failed number of checkpoints without incrementing the * in progress checkpoints before throws an Exception. */ @Test void testCompleteOrFailWithoutInProgressCheckpoint() { CheckpointStatsCounts counts = new CheckpointStatsCounts(); counts.incrementCompletedCheckpoints(); assertThat(counts.getNumberOfInProgressCheckpoints()) .as("Number of checkpoints in progress should never be negative") .isGreaterThanOrEqualTo(0); counts.incrementFailedCheckpoints(); assertThat(counts.getNumberOfInProgressCheckpoints()) .as("Number of checkpoints in progress should never be negative") .isGreaterThanOrEqualTo(0); } /** Tests that taking snapshots of the state are independent of the parent. */ @Test void testCreateSnapshot() { CheckpointStatsCounts counts = new CheckpointStatsCounts(); counts.incrementRestoredCheckpoints(); counts.incrementRestoredCheckpoints(); counts.incrementRestoredCheckpoints(); counts.incrementInProgressCheckpoints(); counts.incrementCompletedCheckpoints(); counts.incrementInProgressCheckpoints(); counts.incrementCompletedCheckpoints(); counts.incrementInProgressCheckpoints(); counts.incrementCompletedCheckpoints(); counts.incrementInProgressCheckpoints(); counts.incrementCompletedCheckpoints(); counts.incrementInProgressCheckpoints(); counts.incrementFailedCheckpoints(); long restored = counts.getNumberOfRestoredCheckpoints(); long total = counts.getTotalNumberOfCheckpoints(); long inProgress = counts.getNumberOfInProgressCheckpoints(); long completed = counts.getNumberOfCompletedCheckpoints(); long failed = counts.getNumberOfFailedCheckpoints(); CheckpointStatsCounts snapshot = counts.createSnapshot(); assertThat(snapshot.getNumberOfRestoredCheckpoints()).isEqualTo(restored); assertThat(snapshot.getTotalNumberOfCheckpoints()).isEqualTo(total); assertThat(snapshot.getNumberOfInProgressCheckpoints()).isEqualTo(inProgress); assertThat(snapshot.getNumberOfCompletedCheckpoints()).isEqualTo(completed); assertThat(snapshot.getNumberOfFailedCheckpoints()).isEqualTo(failed); // Update the original counts.incrementRestoredCheckpoints(); counts.incrementRestoredCheckpoints(); counts.incrementInProgressCheckpoints(); counts.incrementCompletedCheckpoints(); counts.incrementInProgressCheckpoints(); counts.incrementFailedCheckpoints(); assertThat(snapshot.getNumberOfRestoredCheckpoints()).isEqualTo(restored); assertThat(snapshot.getTotalNumberOfCheckpoints()).isEqualTo(total); assertThat(snapshot.getNumberOfInProgressCheckpoints()).isEqualTo(inProgress); assertThat(snapshot.getNumberOfCompletedCheckpoints()).isEqualTo(completed); assertThat(snapshot.getNumberOfFailedCheckpoints()).isEqualTo(failed); } }
CheckpointStatsCountsTest
java
elastic__elasticsearch
x-pack/plugin/old-lucene-versions/src/main/java/org/elasticsearch/xpack/lucene/bwc/codecs/lucene60/MetadataOnlyBKDReader.java
{ "start": 1343, "end": 5544 }
class ____ extends PointValues { public static final int VERSION_START = 0; public static final int VERSION_SELECTIVE_INDEXING = 6; public static final int VERSION_META_FILE = 9; public static final int VERSION_CURRENT = VERSION_META_FILE; final BKDConfig config; final int numLeaves; final byte[] minPackedValue; final byte[] maxPackedValue; final long pointCount; final int docCount; final int version; public MetadataOnlyBKDReader(IndexInput metaIn, boolean isVersionPost86) throws IOException { version = CodecUtil.checkHeader(metaIn, "BKD", VERSION_START, VERSION_CURRENT); final int numDims = metaIn.readVInt(); final int numIndexDims; if (version >= VERSION_SELECTIVE_INDEXING) { numIndexDims = metaIn.readVInt(); } else { numIndexDims = numDims; } final int maxPointsInLeafNode = metaIn.readVInt(); final int bytesPerDim = metaIn.readVInt(); config = new BKDConfig(numDims, numIndexDims, bytesPerDim, maxPointsInLeafNode); numLeaves = metaIn.readVInt(); assert numLeaves > 0; minPackedValue = new byte[config.packedIndexBytesLength()]; maxPackedValue = new byte[config.packedIndexBytesLength()]; metaIn.readBytes(minPackedValue, 0, config.packedIndexBytesLength()); metaIn.readBytes(maxPackedValue, 0, config.packedIndexBytesLength()); final ArrayUtil.ByteArrayComparator comparator = ArrayUtil.getUnsignedComparator(config.bytesPerDim()); for (int dim = 0; dim < config.numIndexDims(); dim++) { if (comparator.compare(minPackedValue, dim * config.bytesPerDim(), maxPackedValue, dim * config.bytesPerDim()) > 0) { throw new CorruptIndexException( "minPackedValue " + new BytesRef(minPackedValue) + " is > maxPackedValue " + new BytesRef(maxPackedValue) + " for dim=" + dim, metaIn ); } } pointCount = metaIn.readVLong(); docCount = metaIn.readVInt(); // The pre-8.6 code does not read the following fields that its standard Lucene counterpart does. After experimenting with the // code, we got to the conclusion that these are the last fields being read, which are not needed in the metadata-only reader, and // we can safely ignore them when loading the file. Although by coincidence, nothing breaks if we read a couple of VLongs, as long // as some bytes are available to read. // // The extra reads have been introduced to process IndexInput created with Lucene86Codec+, where a new BKD format has been // introduced. We have stricter checks around the header and footer starting from the 86 formats hence we do need to // consume all the data input there but not in previous formats. // // For correctness, we added version checking here. If and only if, the version is 8.6 or higher, we read the additional fields. if (isVersionPost86) { metaIn.readVInt(); metaIn.readLong(); // The following fields are not used in this class, but we need to read them to advance the pointer metaIn.readLong(); } } @Override public PointTree getPointTree() { throw new UnsupportedOperationException("only metadata operations allowed"); } @Override public byte[] getMinPackedValue() { return minPackedValue; } @Override public byte[] getMaxPackedValue() { return maxPackedValue; } @Override public int getNumDimensions() { return config.numDims(); } @Override public int getNumIndexDimensions() { return config.numIndexDims(); } @Override public int getBytesPerDimension() { return config.bytesPerDim(); } @Override public long size() { return pointCount; } @Override public int getDocCount() { return docCount; } }
MetadataOnlyBKDReader
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/server/reactive/ServletServerHttpRequest.java
{ "start": 11913, "end": 12344 }
class ____ implements ReadListener { @Override public void onDataAvailable() throws IOException { RequestBodyPublisher.this.onDataAvailable(); } @Override public void onAllDataRead() throws IOException { RequestBodyPublisher.this.onAllDataRead(); } @Override public void onError(Throwable throwable) { RequestBodyPublisher.this.onError(throwable); } } } }
RequestBodyPublisherReadListener
java
spring-projects__spring-boot
module/spring-boot-jetty/src/test/java/org/springframework/boot/jetty/autoconfigure/servlet/JettyServletWebServerAutoConfigurationTests.java
{ "start": 4842, "end": 5288 }
class ____ { private final JettyServerCustomizer customizer = mock(JettyServerCustomizer.class); @Bean JettyServerCustomizer serverCustomizer() { return this.customizer; } @Bean WebServerFactoryCustomizer<JettyServletWebServerFactory> jettyCustomizer() { return (jetty) -> jetty.addServerCustomizers(this.customizer); } } @Configuration(proxyBeanMethods = false) static
DoubleRegistrationJettyServerCustomizerConfiguration
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/resume/Resumable.java
{ "start": 1227, "end": 1650 }
interface ____ { /** * Gets the offset key (i.e.: the addressable part of the resumable object) * * @return An OffsetKey instance with the addressable part of the object. May return null or an EmptyOffset * depending on the type of the resumable */ OffsetKey<?> getOffsetKey(); /** * Gets the last offset * * @return the last offset value according to the
Resumable
java
micronaut-projects__micronaut-core
aop/src/main/java/io/micronaut/aop/Around.java
{ "start": 5110, "end": 5764 }
enum ____ { /** * Do not allow types with constructor arguments to be proxied. This is the default behaviour and compilation will fail. */ ERROR, /** * Allow types to be proxied but print a warning when this feature is used. * * <p>In this case if a constructor parameter cannot be injected Micronaut will inject <code>null</code> for objects or <code>false</code> for boolean or <code>0</code> for any other primitive.</p> */ WARN, /** * Allow types to be proxied and don't print any warnings. */ ALLOW } }
ProxyTargetConstructorMode
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/FactoryBean.java
{ "start": 3236, "end": 6787 }
interface ____<T> { /** * The name of an attribute that can be * {@link org.springframework.core.AttributeAccessor#setAttribute set} on a * {@link org.springframework.beans.factory.config.BeanDefinition} so that * factory beans can signal their object type when it cannot be deduced from * the factory bean class. * @since 5.2 */ String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType"; /** * Return an instance (possibly shared or independent) of the object * managed by this factory. * <p>As with a {@link BeanFactory}, this allows support for both the * Singleton and Prototype design patterns. * <p>If this FactoryBean is not fully initialized yet at the time of * the call (for example because it is involved in a circular reference), * throw a corresponding {@link FactoryBeanNotInitializedException}. * <p>FactoryBeans are allowed to return {@code null} objects. The bean * factory will consider this as a normal value to be used and will not throw * a {@code FactoryBeanNotInitializedException} in this case. However, * FactoryBean implementations are encouraged to throw * {@code FactoryBeanNotInitializedException} themselves, as appropriate. * @return an instance of the bean (can be {@code null}) * @throws Exception in case of creation errors * @see FactoryBeanNotInitializedException */ @Nullable T getObject() throws Exception; /** * Return the type of object that this FactoryBean creates, * or {@code null} if not known in advance. * <p>This allows one to check for specific types of beans without * instantiating objects, for example on autowiring. * <p>In the case of implementations that create a singleton object, * this method should try to avoid singleton creation as far as possible; * it should rather estimate the type in advance. * For prototypes, returning a meaningful type here is advisable too. * <p>This method can be called <i>before</i> this FactoryBean has * been fully initialized. It must not rely on state created during * initialization; of course, it can still use such state if available. * <p><b>NOTE:</b> Autowiring will simply ignore FactoryBeans that return * {@code null} here. Therefore, it is highly recommended to implement * this method properly, using the current state of the FactoryBean. * @return the type of object that this FactoryBean creates, * or {@code null} if not known at the time of the call * @see ListableBeanFactory#getBeansOfType */ @Nullable Class<?> getObjectType(); /** * Is the object managed by this factory a singleton? That is, * will {@link #getObject()} always return the same object * (a reference that can be cached)? * <p><b>NOTE:</b> If a FactoryBean indicates that it holds a singleton * object, the object returned from {@code getObject()} might get cached * by the owning BeanFactory. Hence, do not return {@code true} * unless the FactoryBean always exposes the same reference. * <p>The singleton status of the FactoryBean itself will generally * be provided by the owning BeanFactory; usually, it has to be * defined as singleton there. * <p><b>NOTE:</b> This method returning {@code false} does not * necessarily indicate that returned objects are independent instances. * An implementation of the extended {@link SmartFactoryBean} interface * may explicitly indicate independent instances through its * {@link SmartFactoryBean#isPrototype()} method. Plain {@link FactoryBean} * implementations which do not implement this extended
FactoryBean
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/catalog/TableDistribution.java
{ "start": 1550, "end": 5237 }
enum ____ { UNKNOWN, HASH, RANGE } private final Kind kind; private final @Nullable Integer bucketCount; private final List<String> bucketKeys; private TableDistribution(Kind kind, @Nullable Integer bucketCount, List<String> bucketKeys) { this.kind = Preconditions.checkNotNull(kind, "Distribution kind must not be null."); this.bucketCount = bucketCount; this.bucketKeys = Preconditions.checkNotNull(bucketKeys, "Bucket keys must not be null."); } /** Distribution of the given kind over the given keys with a declared number of buckets. */ public static TableDistribution of( Kind kind, @Nullable Integer bucketCount, List<String> bucketKeys) { return new TableDistribution(kind, bucketCount, bucketKeys); } /** Connector-dependent distribution with a declared number of buckets. */ public static TableDistribution ofUnknown(int bucketCount) { return new TableDistribution(Kind.UNKNOWN, bucketCount, Collections.emptyList()); } /** Connector-dependent distribution with a declared number of buckets. */ public static TableDistribution ofUnknown( List<String> bucketKeys, @Nullable Integer bucketCount) { return new TableDistribution(Kind.UNKNOWN, bucketCount, bucketKeys); } /** Hash distribution over the given keys among the declared number of buckets. */ public static TableDistribution ofHash(List<String> bucketKeys, @Nullable Integer bucketCount) { return new TableDistribution(Kind.HASH, bucketCount, bucketKeys); } /** Range distribution over the given keys among the declared number of buckets. */ public static TableDistribution ofRange( List<String> bucketKeys, @Nullable Integer bucketCount) { return new TableDistribution(Kind.RANGE, bucketCount, bucketKeys); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TableDistribution that = (TableDistribution) o; return kind == that.kind && Objects.equals(bucketCount, that.bucketCount) && Objects.equals(bucketKeys, that.bucketKeys); } @Override public int hashCode() { return Objects.hash(kind, bucketCount, bucketKeys); } public Kind getKind() { return kind; } public List<String> getBucketKeys() { return bucketKeys; } public Optional<Integer> getBucketCount() { return Optional.ofNullable(bucketCount); } private String asSerializableString() { if (getBucketKeys().isEmpty() && getBucketCount().isPresent() && getBucketCount().get() != 0) { return "DISTRIBUTED INTO " + getBucketCount().get() + " BUCKETS"; } StringBuilder sb = new StringBuilder(); sb.append("DISTRIBUTED BY "); if (getKind() != null && getKind() != Kind.UNKNOWN) { sb.append(getKind()); } sb.append("("); sb.append( getBucketKeys().stream() .map(EncodingUtils::escapeIdentifier) .collect(Collectors.joining(", "))); sb.append(")"); if (getBucketCount().isPresent() && getBucketCount().get() != 0) { sb.append(" INTO "); sb.append(getBucketCount().get()); sb.append(" BUCKETS"); } return sb.toString(); } @Override public String toString() { return asSerializableString(); } }
Kind
java
google__guava
guava-tests/test/com/google/common/base/ToStringHelperTest.java
{ "start": 5791, "end": 22225 }
class ____ various fields @GwtIncompatible // Class names are obfuscated in GWT public void testToString_oneField() { String toTest = MoreObjects.toStringHelper(new TestClass()).add("field1", "Hello").toString(); assertEquals("TestClass{field1=Hello}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToString_oneIntegerField() { String toTest = MoreObjects.toStringHelper(new TestClass()).add("field1", Integer.valueOf(42)).toString(); assertEquals("TestClass{field1=42}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToString_nullInteger() { String toTest = MoreObjects.toStringHelper(new TestClass()).add("field1", (Integer) null).toString(); assertEquals("TestClass{field1=null}", toTest); } public void testToStringLenient_oneField() { String toTest = MoreObjects.toStringHelper(new TestClass()).add("field1", "Hello").toString(); assertTrue(toTest, toTest.matches(".*\\{field1\\=Hello\\}")); } public void testToStringLenient_oneIntegerField() { String toTest = MoreObjects.toStringHelper(new TestClass()).add("field1", Integer.valueOf(42)).toString(); assertTrue(toTest, toTest.matches(".*\\{field1\\=42\\}")); } public void testToStringLenient_nullInteger() { String toTest = MoreObjects.toStringHelper(new TestClass()).add("field1", (Integer) null).toString(); assertTrue(toTest, toTest.matches(".*\\{field1\\=null\\}")); } @GwtIncompatible // Class names are obfuscated in GWT public void testToString_complexFields() { Map<String, Integer> map = ImmutableMap.<String, Integer>builder().put("abc", 1).put("def", 2).put("ghi", 3).build(); String toTest = MoreObjects.toStringHelper(new TestClass()) .add("field1", "This is string.") .add("field2", Arrays.asList("abc", "def", "ghi")) .add("field3", map) .toString(); String expected = "TestClass{" + "field1=This is string., field2=[abc, def, ghi], field3={abc=1, def=2, ghi=3}}"; assertEquals(expected, toTest); } public void testToStringLenient_complexFields() { Map<String, Integer> map = ImmutableMap.<String, Integer>builder().put("abc", 1).put("def", 2).put("ghi", 3).build(); String toTest = MoreObjects.toStringHelper(new TestClass()) .add("field1", "This is string.") .add("field2", Arrays.asList("abc", "def", "ghi")) .add("field3", map) .toString(); String expectedRegex = ".*\\{" + "field1\\=This is string\\., " + "field2\\=\\[abc, def, ghi\\], " + "field3=\\{abc\\=1, def\\=2, ghi\\=3\\}\\}"; assertTrue(toTest, toTest.matches(expectedRegex)); } public void testToString_addWithNullName() { MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(new TestClass()); assertThrows(NullPointerException.class, () -> helper.add(null, "Hello")); } @GwtIncompatible // Class names are obfuscated in GWT public void testToString_addWithNullValue() { String result = MoreObjects.toStringHelper(new TestClass()).add("Hello", null).toString(); assertEquals("TestClass{Hello=null}", result); } public void testToStringLenient_addWithNullValue() { String result = MoreObjects.toStringHelper(new TestClass()).add("Hello", null).toString(); assertTrue(result, result.matches(".*\\{Hello\\=null\\}")); } @GwtIncompatible // Class names are obfuscated in GWT public void testToString_toStringTwice() { MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(new TestClass()) .add("field1", 1) .addValue("value1") .add("field2", "value2"); String expected = "TestClass{field1=1, value1, field2=value2}"; assertEquals(expected, helper.toString()); // Call toString again assertEquals(expected, helper.toString()); // Make sure the cached value is reset when we modify the helper at all String expected2 = "TestClass{field1=1, value1, field2=value2, 2}"; helper.addValue(2); assertEquals(expected2, helper.toString()); } @GwtIncompatible // Class names are obfuscated in GWT public void testToString_addValue() { String toTest = MoreObjects.toStringHelper(new TestClass()) .add("field1", 1) .addValue("value1") .add("field2", "value2") .addValue(2) .toString(); String expected = "TestClass{field1=1, value1, field2=value2, 2}"; assertEquals(expected, toTest); } public void testToStringLenient_addValue() { String toTest = MoreObjects.toStringHelper(new TestClass()) .add("field1", 1) .addValue("value1") .add("field2", "value2") .addValue(2) .toString(); String expected = ".*\\{field1\\=1, value1, field2\\=value2, 2\\}"; assertTrue(toTest, toTest.matches(expected)); } @GwtIncompatible // Class names are obfuscated in GWT public void testToString_addValueWithNullValue() { String result = MoreObjects.toStringHelper(new TestClass()) .addValue(null) .addValue("Hello") .addValue(null) .toString(); String expected = "TestClass{null, Hello, null}"; assertEquals(expected, result); } public void testToStringLenient_addValueWithNullValue() { String result = MoreObjects.toStringHelper(new TestClass()) .addValue(null) .addValue("Hello") .addValue(null) .toString(); String expected = ".*\\{null, Hello, null\\}"; assertTrue(result, result.matches(expected)); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitNullValues_oneField() { String toTest = MoreObjects.toStringHelper(new TestClass()).omitNullValues().add("field1", null).toString(); assertEquals("TestClass{}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitEmptyValues_oneField() { String toTest = MoreObjects.toStringHelper(new TestClass()).omitEmptyValues().add("field1", "").toString(); assertEquals("TestClass{}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitNullValues_manyFieldsFirstNull() { String toTest = MoreObjects.toStringHelper(new TestClass()) .omitNullValues() .add("field1", null) .add("field2", "Googley") .add("field3", "World") .toString(); assertEquals("TestClass{field2=Googley, field3=World}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitEmptyValues_manyFieldsFirstEmpty() { String toTest = MoreObjects.toStringHelper(new TestClass()) .omitEmptyValues() .add("field1", "") .add("field2", "Googley") .add("field3", "World") .toString(); assertEquals("TestClass{field2=Googley, field3=World}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitNullValues_manyFieldsOmitAfterNull() { String toTest = MoreObjects.toStringHelper(new TestClass()) .add("field1", null) .add("field2", "Googley") .add("field3", "World") .omitNullValues() .toString(); assertEquals("TestClass{field2=Googley, field3=World}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitEmptyValues_manyFieldsOmitAfterEmpty() { String toTest = MoreObjects.toStringHelper(new TestClass()) .add("field1", "") .add("field2", "Googley") .add("field3", "World") .omitEmptyValues() .toString(); assertEquals("TestClass{field2=Googley, field3=World}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitNullValues_manyFieldsLastNull() { String toTest = MoreObjects.toStringHelper(new TestClass()) .omitNullValues() .add("field1", "Hello") .add("field2", "Googley") .add("field3", null) .toString(); assertEquals("TestClass{field1=Hello, field2=Googley}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitEmptyValues_manyFieldsLastEmpty() { String toTest = MoreObjects.toStringHelper(new TestClass()) .omitEmptyValues() .add("field1", "Hello") .add("field2", "Googley") .add("field3", "") .toString(); assertEquals("TestClass{field1=Hello, field2=Googley}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitNullValues_oneValue() { String toTest = MoreObjects.toStringHelper(new TestClass()).omitEmptyValues().addValue("").toString(); assertEquals("TestClass{}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitEmptyValues_oneValue() { String toTest = MoreObjects.toStringHelper(new TestClass()).omitNullValues().addValue(null).toString(); assertEquals("TestClass{}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitNullValues_manyValuesFirstNull() { String toTest = MoreObjects.toStringHelper(new TestClass()) .omitNullValues() .addValue(null) .addValue("Googley") .addValue("World") .toString(); assertEquals("TestClass{Googley, World}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitEmptyValues_manyValuesFirstEmpty() { String toTest = MoreObjects.toStringHelper(new TestClass()) .omitEmptyValues() .addValue("") .addValue("Googley") .addValue("World") .toString(); assertEquals("TestClass{Googley, World}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitNullValues_manyValuesLastNull() { String toTest = MoreObjects.toStringHelper(new TestClass()) .omitNullValues() .addValue("Hello") .addValue("Googley") .addValue(null) .toString(); assertEquals("TestClass{Hello, Googley}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitEmptyValues_manyValuesLastEmpty() { String toTest = MoreObjects.toStringHelper(new TestClass()) .omitEmptyValues() .addValue("Hello") .addValue("Googley") .addValue("") .toString(); assertEquals("TestClass{Hello, Googley}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitNullValues_differentOrder() { String expected = "TestClass{field1=Hello, field2=Googley, field3=World}"; String toTest1 = MoreObjects.toStringHelper(new TestClass()) .omitNullValues() .add("field1", "Hello") .add("field2", "Googley") .add("field3", "World") .toString(); String toTest2 = MoreObjects.toStringHelper(new TestClass()) .add("field1", "Hello") .add("field2", "Googley") .omitNullValues() .add("field3", "World") .toString(); assertEquals(expected, toTest1); assertEquals(expected, toTest2); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitEmptyValues_differentOrder() { String expected = "TestClass{field1=Hello, field2=Googley, field3=World}"; String toTest1 = MoreObjects.toStringHelper(new TestClass()) .omitEmptyValues() .add("field1", "Hello") .add("field2", "Googley") .add("field3", "World") .toString(); String toTest2 = MoreObjects.toStringHelper(new TestClass()) .add("field1", "Hello") .add("field2", "Googley") .omitEmptyValues() .add("field3", "World") .toString(); assertEquals(expected, toTest1); assertEquals(expected, toTest2); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitNullValues_canBeCalledManyTimes() { String toTest = MoreObjects.toStringHelper(new TestClass()) .omitNullValues() .omitNullValues() .add("field1", "Hello") .omitNullValues() .add("field2", "Googley") .omitNullValues() .add("field3", "World") .toString(); assertEquals("TestClass{field1=Hello, field2=Googley, field3=World}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitEmptyValues_canBeCalledManyTimes() { String toTest = MoreObjects.toStringHelper(new TestClass()) .omitEmptyValues() .omitEmptyValues() .add("field1", "Hello") .omitEmptyValues() .add("field2", "Googley") .omitEmptyValues() .add("field3", "World") .toString(); assertEquals("TestClass{field1=Hello, field2=Googley, field3=World}", toTest); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringOmitEmptyValues_allEmptyTypes() { String toTest = MoreObjects.toStringHelper(new TestClass()) .omitEmptyValues() // CharSequences .add("field1", "") .add("field2", new StringBuilder()) // nio CharBuffer (implements CharSequence) is tested separately below // Collections and Maps .add("field11", Arrays.asList("Hello")) .add("field12", new ArrayList<>()) .add("field13", new HashMap<>()) // Optionals .add("field21", java.util.Optional.of("Googley")) .add("field22", java.util.Optional.empty()) .add("field23", OptionalInt.empty()) .add("field24", OptionalLong.empty()) .add("field25", OptionalDouble.empty()) .add("field26", Optional.of("World")) .add("field27", Optional.absent()) // Arrays .add("field31", new Object[] {"!!!"}) .add("field32", new boolean[0]) .add("field33", new byte[0]) .add("field34", new char[0]) .add("field35", new short[0]) .add("field36", new int[0]) .add("field37", new long[0]) .add("field38", new float[0]) .add("field39", new double[0]) .add("field40", new Object[0]) .toString(); assertEquals( "TestClass{field11=[Hello], field21=Optional[Googley], field26=Optional.of(World)," + " field31=[!!!]}", toTest); } @J2ktIncompatible // J2kt CharBuffer does not implement CharSequence so not recognized as empty @GwtIncompatible // CharBuffer not available public void testToStringOmitEmptyValues_charBuffer() { String toTest = MoreObjects.toStringHelper(new TestClass()) .omitEmptyValues() .add("field1", "Hello") .add("field2", CharBuffer.allocate(0)) .toString(); assertEquals("TestClass{field1=Hello}", toTest); } public void testToStringHelperWithArrays() { String[] strings = {"hello", "world"}; int[] ints = {2, 42}; Object[] objects = {"obj"}; @Nullable String[] arrayWithNull = new @Nullable String[] {null}; Object[] empty = {}; String toTest = MoreObjects.toStringHelper("TSH") .add("strings", strings) .add("ints", ints) .add("objects", objects) .add("arrayWithNull", arrayWithNull) .add("empty", empty) .toString(); assertEquals( "TSH{strings=[hello, world], ints=[2, 42], objects=[obj], arrayWithNull=[null], empty=[]}", toTest); } /** Test
with
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/h2/parser/H2ExprParser.java
{ "start": 1007, "end": 6167 }
class ____ extends SQLExprParser { private static final String[] AGGREGATE_FUNCTIONS; private static final long[] AGGREGATE_FUNCTIONS_CODES; static { String[] strings = {"AVG", "COUNT", "MAX", "MIN", "STDDEV", "SUM", "ROW_NUMBER", "ROWNUMBER"}; AGGREGATE_FUNCTIONS_CODES = FnvHash.fnv1a_64_lower(strings, true); AGGREGATE_FUNCTIONS = new String[AGGREGATE_FUNCTIONS_CODES.length]; for (String str : strings) { long hash = FnvHash.fnv1a_64_lower(str); int index = Arrays.binarySearch(AGGREGATE_FUNCTIONS_CODES, hash); AGGREGATE_FUNCTIONS[index] = str; } } public H2ExprParser(String sql) { this(new H2Lexer(sql)); this.lexer.nextToken(); } public H2ExprParser(String sql, SQLParserFeature... features) { this(new H2Lexer(sql, features)); this.lexer.nextToken(); } public H2ExprParser(Lexer lexer) { super(lexer); dbType = lexer.getDbType(); this.aggregateFunctions = AGGREGATE_FUNCTIONS; this.aggregateFunctionHashCodes = AGGREGATE_FUNCTIONS_CODES; } public SQLColumnDefinition parseColumnRest(SQLColumnDefinition column) { column = super.parseColumnRest(column); if (lexer.identifierEquals(FnvHash.Constants.GENERATED)) { lexer.nextToken(); if (lexer.token() == Token.BY) { lexer.nextToken(); accept(Token.DEFAULT); column.setGeneratedAlwaysAs(new SQLDefaultExpr()); } else { acceptIdentifier("ALWAYS"); column.setGeneratedAlwaysAs(new SQLIdentifierExpr("ALWAYS")); } accept(Token.AS); acceptIdentifier("IDENTITY"); SQLColumnDefinition.Identity identity = new SQLColumnDefinition.Identity(); if (lexer.token() == Token.LPAREN) { lexer.nextToken(); SQLIntegerExpr seed = (SQLIntegerExpr) this.primary(); accept(Token.COMMA); SQLIntegerExpr increment = (SQLIntegerExpr) this.primary(); accept(Token.RPAREN); identity.setSeed((Integer) seed.getNumber()); identity.setIncrement((Integer) increment.getNumber()); } column.setIdentity(identity); } return column; } protected SQLColumnDefinition.Identity parseIdentity0() { SQLColumnDefinition.Identity identity = new SQLColumnDefinition.Identity(); accept(Token.IDENTITY); if (lexer.token() == Token.LPAREN) { accept(Token.LPAREN); if (lexer.identifierEquals(FnvHash.Constants.START)) { lexer.nextToken(); accept(Token.WITH); if (lexer.token() == Token.LITERAL_INT) { identity.setSeed((Integer) lexer.integerValue()); lexer.nextToken(); } else { throw new ParserException("TODO " + lexer.info()); } if (lexer.token() == Token.COMMA) { lexer.nextToken(); } } if (lexer.identifierEquals(FnvHash.Constants.INCREMENT)) { lexer.nextToken(); accept(Token.BY); if (lexer.token() == Token.LITERAL_INT) { identity.setIncrement((Integer) lexer.integerValue()); lexer.nextToken(); } else { throw new ParserException("TODO " + lexer.info()); } if (lexer.token() == Token.COMMA) { lexer.nextToken(); } } if (lexer.identifierEquals(FnvHash.Constants.CYCLE)) { lexer.nextToken(); identity.setCycle(true); if (lexer.token() == Token.COMMA) { lexer.nextToken(); } } if (lexer.identifierEquals(FnvHash.Constants.MINVALUE)) { lexer.nextTokenValue(); if (lexer.token() == Token.LITERAL_INT) { identity.setMinValue((Integer) lexer.integerValue()); lexer.nextToken(); } else { throw new ParserException("TODO " + lexer.info()); } if (lexer.token() == Token.COMMA) { lexer.nextToken(); } } if (lexer.identifierEquals(FnvHash.Constants.MAXVALUE)) { lexer.nextToken(); if (lexer.token() == Token.LITERAL_INT) { identity.setMaxValue((Integer) lexer.integerValue()); lexer.nextToken(); } else { throw new ParserException("TODO " + lexer.info()); } if (lexer.token() == Token.COMMA) { lexer.nextToken(); } } accept(Token.RPAREN); } return identity; } }
H2ExprParser
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/lucene/search/uhighlight/BoundedBreakIteratorScanner.java
{ "start": 908, "end": 1832 }
class ____ a {@link BreakIterator} to find the last break after the provided offset * that would create a passage smaller than <code>maxLen</code>. * If the {@link BreakIterator} cannot find a passage smaller than the maximum length, * a secondary break iterator is used to re-split the passage at the first boundary after * maximum length. * * This is useful to split passages created by {@link BreakIterator}s like `sentence` that * can create big outliers on semi-structured text. * * * WARNING: This break iterator is designed to work with the {@link UnifiedHighlighter}. * * TODO: We should be able to create passages incrementally, starting from the offset of the first match and expanding or not * depending on the offsets of subsequent matches. This is currently impossible because {@link FieldHighlighter} uses * only the first matching offset to derive the start and end of each passage. **/ public
uses
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MisleadingEscapedSpaceTest.java
{ "start": 1722, "end": 2047 }
class ____ { // BUG: Diagnostic contains: private static final char x = '\\s'; }\ """) .doTest(); } @Test public void withinTextBlock_notAtEndOfLine_misleading() { testHelper .addSourceLines( "Test.class", """
Test
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/inference/CallBindingCallContext.java
{ "start": 2551, "end": 8677 }
class ____ extends AbstractSqlCallContext { private final List<SqlNode> adaptedArguments; private final List<DataType> argumentDataTypes; private final Function<Integer, DataType> getModelInputType; private final @Nullable DataType outputType; private final @Nullable List<StaticArgument> staticArguments; public CallBindingCallContext( DataTypeFactory dataTypeFactory, FunctionDefinition definition, SqlCallBinding binding, @Nullable RelDataType outputType, @Nullable List<StaticArgument> staticArguments) { super( dataTypeFactory, definition, binding.getOperator().getNameAsId().toString(), binding.getGroupCount() > 0); this.adaptedArguments = binding.operands(); // reorders the operands this.argumentDataTypes = new AbstractList<>() { @Override public DataType get(int pos) { final LogicalType logicalType = FlinkTypeFactory.toLogicalType(binding.getOperandType(pos)); return TypeConversions.fromLogicalToDataType(logicalType); } @Override public int size() { return binding.getOperandCount(); } }; this.getModelInputType = pos -> { final SqlNode sqlNode = adaptedArguments.get(pos); if (!(sqlNode instanceof SqlModelCall)) { throw new ValidationException( String.format( "Argument %d is not a model call, cannot get model input type.", pos)); } RelDataType type = ((SqlModelCall) sqlNode).getInputType(binding.getValidator()); final LogicalType logicalType = FlinkTypeFactory.toLogicalType(type); return TypeConversions.fromLogicalToDataType(logicalType); }; this.outputType = convertOutputType(binding, outputType); this.staticArguments = staticArguments; } @Override public boolean isArgumentLiteral(int pos) { final SqlNode sqlNode = adaptedArguments.get(pos); // Semantically a descriptor can be considered a literal, // however, Calcite represents them as a call return SqlUtil.isLiteral(sqlNode, false) || sqlNode.getKind() == SqlKind.DESCRIPTOR; } @Override public boolean isArgumentNull(int pos) { final SqlNode sqlNode = adaptedArguments.get(pos); // Default values are passed as NULL into functions. // We can introduce a dedicated CallContext.isDefault() method in the future if fine-grained // information is required. return SqlUtil.isNullLiteral(sqlNode, true) || sqlNode.getKind() == SqlKind.DEFAULT; } @Override @SuppressWarnings("unchecked") public <T> Optional<T> getArgumentValue(int pos, Class<T> clazz) { if (isArgumentNull(pos)) { return Optional.empty(); } try { final SqlNode sqlNode = adaptedArguments.get(pos); if (sqlNode.getKind() == SqlKind.DESCRIPTOR && clazz == ColumnList.class) { final List<SqlNode> columns = ((SqlCall) sqlNode).getOperandList(); if (columns.stream() .anyMatch( column -> !(column instanceof SqlIdentifier) || !((SqlIdentifier) column).isSimple())) { return Optional.empty(); } return Optional.of((T) convertColumnList(columns)); } final SqlLiteral literal = SqlLiteral.unchain(sqlNode); return Optional.ofNullable(getLiteralValueAs(literal::getValueAs, clazz)); } catch (IllegalArgumentException e) { return Optional.empty(); } } @Override public Optional<TableSemantics> getTableSemantics(int pos) { final StaticArgument staticArg = Optional.ofNullable(staticArguments).map(args -> args.get(pos)).orElse(null); if (staticArg == null || !staticArg.is(StaticArgumentTrait.TABLE)) { return Optional.empty(); } final SqlNode sqlNode = adaptedArguments.get(pos); if (!sqlNode.isA(SqlKind.QUERY) && noSetSemantics(sqlNode)) { return Optional.empty(); } return Optional.of( CallBindingTableSemantics.create(argumentDataTypes.get(pos), staticArg, sqlNode)); } @Override public Optional<ModelSemantics> getModelSemantics(int pos) { final StaticArgument staticArg = Optional.ofNullable(staticArguments).map(args -> args.get(pos)).orElse(null); if (staticArg == null || !staticArg.is(StaticArgumentTrait.MODEL)) { return Optional.empty(); } final SqlNode sqlNode = adaptedArguments.get(pos); // SqlModelCall is parsed by parser for syntax `MODEL identifier` and model is looked up if (!(sqlNode instanceof SqlModelCall)) { return Optional.empty(); } return Optional.of( CallBindingModelSemantics.create( getModelInputType.apply(pos), argumentDataTypes.get(pos))); } @Override public List<DataType> getArgumentDataTypes() { return argumentDataTypes; } @Override public Optional<DataType> getOutputDataType() { return Optional.ofNullable(outputType); } // -------------------------------------------------------------------------------------------- // TableSemantics // -------------------------------------------------------------------------------------------- private static
CallBindingCallContext
java
processing__processing4
app/src/processing/app/Util.java
{ "start": 19320, "end": 21215 }
class ____. * * @param path the input classpath * @return array of possible package names */ static public StringList packageListFromClassPath(String path) { // Map<String, Object> map = new HashMap<String, Object>(); StringList list = new StringList(); String[] pieces = PApplet.split(path, File.pathSeparatorChar); for (String piece : pieces) { //System.out.println("checking piece '" + pieces[i] + "'"); if (piece.length() != 0) { if (piece.toLowerCase().endsWith(".jar") || piece.toLowerCase().endsWith(".zip")) { //System.out.println("checking " + pieces[i]); packageListFromZip(piece, list); } else { // it's another type of file or directory File dir = new File(piece); if (dir.exists() && dir.isDirectory()) { packageListFromFolder(dir, null, list); //importCount = magicImportsRecursive(dir, null, // map); //imports, importCount); } } } } // int mapCount = map.size(); // String output[] = new String[mapCount]; // int index = 0; // Set<String> set = map.keySet(); // for (String s : set) { // output[index++] = s.replace('/', '.'); // } // return output; StringList outgoing = new StringList(list.size()); for (String item : list) { outgoing.append(item.replace('/', '.')); } return outgoing; } static private void packageListFromZip(String filename, StringList list) { try { ZipFile file = new ZipFile(filename); Enumeration<?> entries = file.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { String name = entry.getName(); // Avoid META-INF because some jokers put .
files
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/internal/Classes.java
{ "start": 14604, "end": 14711 }
class ____ null */ public void classParameterIsNotNull(Class<?> clazz) { requireNonNull(clazz, "The
is
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/util/ConfigurationParserUtils.java
{ "start": 2061, "end": 2161 }
class ____ extract related parameters from {@link Configuration} and to sanity check them. */ public
to
java
google__guava
android/guava/src/com/google/common/hash/Hashing.java
{ "start": 1877, "end": 9282 }
class ____ loaded. <b>Do not use this method</b> if hash codes may escape the current * process in any way, for example being sent over RPC, or saved to disk. For a general-purpose, * non-cryptographic hash function that will never change behavior, we suggest {@link * #murmur3_128}. * * <p>Repeated calls to this method on the same loaded {@code Hashing} class, using the same value * for {@code minimumBits}, will return identically-behaving {@link HashFunction} instances. * * @param minimumBits a positive integer. This can be arbitrarily large. The returned {@link * HashFunction} instance may use memory proportional to this integer. * @return a hash function, described above, that produces hash codes of length {@code * minimumBits} or greater */ public static HashFunction goodFastHash(int minimumBits) { int bits = checkPositiveAndMakeMultipleOf32(minimumBits); if (bits == 32) { return Murmur3_32HashFunction.GOOD_FAST_HASH_32; } if (bits <= 128) { return Murmur3_128HashFunction.GOOD_FAST_HASH_128; } // Otherwise, join together some 128-bit murmur3s int hashFunctionsNeeded = (bits + 127) / 128; HashFunction[] hashFunctions = new HashFunction[hashFunctionsNeeded]; hashFunctions[0] = Murmur3_128HashFunction.GOOD_FAST_HASH_128; int seed = GOOD_FAST_HASH_SEED; for (int i = 1; i < hashFunctionsNeeded; i++) { seed += 1500450271; // a prime; shouldn't matter hashFunctions[i] = murmur3_128(seed); } return new ConcatenatedHashFunction(hashFunctions); } /** * Used to randomize {@link #goodFastHash} instances, so that programs which persist anything * dependent on the hash codes they produce will fail sooner. */ @SuppressWarnings("GoodTime") // reading system time without TimeSource static final int GOOD_FAST_HASH_SEED = (int) System.currentTimeMillis(); /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3 * algorithm, x86 variant</a> (little-endian variant), using the given seed value, <b>with a known * bug</b> as described in the deprecation text. * * <p>The C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A), which however does not * have the bug. * * @deprecated This implementation produces incorrect hash values from the {@link * HashFunction#hashString} method if the string contains non-BMP characters. Use {@link * #murmur3_32_fixed(int)} instead. */ @Deprecated @SuppressWarnings("IdentifierName") // the best we could do for adjacent digit blocks public static HashFunction murmur3_32(int seed) { return new Murmur3_32HashFunction(seed, /* supplementaryPlaneFix= */ false); } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3 * algorithm, x86 variant</a> (little-endian variant), using the given seed value, <b>with a known * bug</b> as described in the deprecation text. * * <p>The C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A), which however does not * have the bug. * * @deprecated This implementation produces incorrect hash values from the {@link * HashFunction#hashString} method if the string contains non-BMP characters. Use {@link * #murmur3_32_fixed()} instead. */ @Deprecated @SuppressWarnings("IdentifierName") // the best we could do for adjacent digit blocks public static HashFunction murmur3_32() { return Murmur3_32HashFunction.MURMUR3_32; } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3 * algorithm, x86 variant</a> (little-endian variant), using the given seed value. * * <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). * * <p>This method is called {@code murmur3_32_fixed} because it fixes a bug in the {@code * HashFunction} returned by the original {@code murmur3_32} method. * * @since 31.0 */ @SuppressWarnings("IdentifierName") // the best we could do for adjacent digit blocks public static HashFunction murmur3_32_fixed(int seed) { return new Murmur3_32HashFunction(seed, /* supplementaryPlaneFix= */ true); } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3 * algorithm, x86 variant</a> (little-endian variant), using a seed value of zero. * * <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). * * <p>This method is called {@code murmur3_32_fixed} because it fixes a bug in the {@code * HashFunction} returned by the original {@code murmur3_32} method. * * @since 31.0 */ @SuppressWarnings("IdentifierName") // the best we could do for adjacent digit blocks public static HashFunction murmur3_32_fixed() { return Murmur3_32HashFunction.MURMUR3_32_FIXED; } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">128-bit murmur3 * algorithm, x64 variant</a> (little-endian variant), using the given seed value. * * <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). */ @SuppressWarnings("IdentifierName") // the best we could do for adjacent digit blocks public static HashFunction murmur3_128(int seed) { return new Murmur3_128HashFunction(seed); } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">128-bit murmur3 * algorithm, x64 variant</a> (little-endian variant), using a seed value of zero. * * <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). */ @SuppressWarnings("IdentifierName") // the best we could do for adjacent digit blocks public static HashFunction murmur3_128() { return Murmur3_128HashFunction.MURMUR3_128; } /** * Returns a hash function implementing the <a href="https://131002.net/siphash/">64-bit * SipHash-2-4 algorithm</a> using a seed value of {@code k = 00 01 02 ...}. * * @since 15.0 */ public static HashFunction sipHash24() { return SipHashFunction.SIP_HASH_24; } /** * Returns a hash function implementing the <a href="https://131002.net/siphash/">64-bit * SipHash-2-4 algorithm</a> using the given seed. * * @since 15.0 */ public static HashFunction sipHash24(long k0, long k1) { return new SipHashFunction(2, 4, k0, k1); } /** * Returns a hash function implementing the MD5 hash algorithm (128 hash bits). * * @deprecated If you must interoperate with a system that requires MD5, then use this method, * despite its deprecation. But if you can choose your hash function, avoid MD5, which is * neither fast nor secure. As of January 2017, we suggest: * <ul> * <li>For security: * {@link Hashing#sha256} or a higher-level API. * <li>For speed: {@link Hashing#goodFastHash}, though see its docs for caveats. * </ul> */ @Deprecated public static HashFunction md5() { return Md5Holder.MD5; } private static final
is
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/data/util/DataFormatConverters.java
{ "start": 27523, "end": 28107 }
class ____ extends IdentityConverter<DecimalData> { private static final long serialVersionUID = 3825744951173809617L; private final int precision; private final int scale; public DecimalDataConverter(int precision, int scale) { this.precision = precision; this.scale = scale; } @Override DecimalData toExternalImpl(RowData row, int column) { return row.getDecimal(column, precision, scale); } } /** Converter for RawValueData. */ public static final
DecimalDataConverter
java
quarkusio__quarkus
integration-tests/hibernate-orm-panache/src/test/java/io/quarkus/it/panache/custompu/SmokeTest.java
{ "start": 221, "end": 524 }
class ____ { @Test void testPanacheFunctionality() throws Exception { RestAssured.when().post("/custom-pu/someValue").then().body(containsString("someValue")); RestAssured.when().patch("/custom-pu/someUpdatedValue").then().body(containsString("someUpdatedValue")); } }
SmokeTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/get/TransportMultiGetAction.java
{ "start": 1801, "end": 7554 }
class ____ extends HandledTransportAction<MultiGetRequest, MultiGetResponse> { public static final String NAME = "indices:data/read/mget"; public static final ActionType<MultiGetResponse> TYPE = new ActionType<>(NAME); private final ClusterService clusterService; private final NodeClient client; private final ProjectResolver projectResolver; private final IndexNameExpressionResolver indexNameExpressionResolver; @Inject public TransportMultiGetAction( TransportService transportService, ClusterService clusterService, NodeClient client, ActionFilters actionFilters, ProjectResolver projectResolver, IndexNameExpressionResolver resolver, IndicesService indicesService ) { super(NAME, transportService, actionFilters, MultiGetRequest::new, EsExecutors.DIRECT_EXECUTOR_SERVICE); this.clusterService = clusterService; this.client = client; this.projectResolver = projectResolver; this.indexNameExpressionResolver = resolver; // register the internal TransportGetFromTranslogAction new TransportShardMultiGetFomTranslogAction(transportService, indicesService, actionFilters); } @Override protected void doExecute(Task task, final MultiGetRequest request, final ActionListener<MultiGetResponse> listener) { ClusterState clusterState = clusterService.state(); ProjectMetadata project = projectResolver.getProjectMetadata(clusterState); clusterState.blocks().globalBlockedRaiseException(project.id(), ClusterBlockLevel.READ); final AtomicArray<MultiGetItemResponse> responses = new AtomicArray<>(request.items.size()); final Map<ShardId, MultiGetShardRequest> shardRequests = new HashMap<>(); // single item cache that maps the provided index name to the resolved one Tuple<String, String> lastResolvedIndex = Tuple.tuple(null, null); for (int i = 0; i < request.items.size(); i++) { MultiGetRequest.Item item = request.items.get(i); ShardId shardId; try { String concreteSingleIndex; if (item.index().equals(lastResolvedIndex.v1())) { concreteSingleIndex = lastResolvedIndex.v2(); } else { concreteSingleIndex = indexNameExpressionResolver.concreteSingleIndex(project, item).getName(); lastResolvedIndex = Tuple.tuple(item.index(), concreteSingleIndex); } item.routing(project.resolveIndexRouting(item.routing(), item.index())); shardId = OperationRouting.shardId(project, concreteSingleIndex, item.id(), item.routing()); } catch (RoutingMissingException e) { responses.set(i, newItemFailure(e.getIndex().getName(), e.getId(), e)); continue; } catch (Exception e) { responses.set(i, newItemFailure(item.index(), item.id(), e)); continue; } MultiGetShardRequest shardRequest = shardRequests.get(shardId); if (shardRequest == null) { shardRequest = new MultiGetShardRequest(request, shardId.getIndexName(), shardId.getId()); shardRequests.put(shardId, shardRequest); } shardRequest.add(i, item); } if (shardRequests.isEmpty()) { // only failures.. listener.onResponse(new MultiGetResponse(responses.toArray(new MultiGetItemResponse[responses.length()]))); } executeShardAction(listener, responses, shardRequests); } protected void executeShardAction( ActionListener<MultiGetResponse> listener, AtomicArray<MultiGetItemResponse> responses, Map<ShardId, MultiGetShardRequest> shardRequests ) { final AtomicInteger counter = new AtomicInteger(shardRequests.size()); for (final MultiGetShardRequest shardRequest : shardRequests.values()) { client.executeLocally(TransportShardMultiGetAction.TYPE, shardRequest, new DelegatingActionListener<>(listener) { @Override public void onResponse(MultiGetShardResponse response) { for (int i = 0; i < response.locations.size(); i++) { MultiGetItemResponse itemResponse = new MultiGetItemResponse(response.responses.get(i), response.failures.get(i)); responses.set(response.locations.get(i), itemResponse); } if (counter.decrementAndGet() == 0) { finishHim(); } } @Override public void onFailure(Exception e) { // create failures for all relevant requests for (int i = 0; i < shardRequest.locations.size(); i++) { MultiGetRequest.Item item = shardRequest.items.get(i); responses.set(shardRequest.locations.get(i), newItemFailure(shardRequest.index(), item.id(), e)); } if (counter.decrementAndGet() == 0) { finishHim(); } } private void finishHim() { delegate.onResponse(new MultiGetResponse(responses.toArray(new MultiGetItemResponse[responses.length()]))); } }); } } private static MultiGetItemResponse newItemFailure(String index, String id, Exception exception) { return new MultiGetItemResponse(null, new MultiGetResponse.Failure(index, id, exception)); } }
TransportMultiGetAction
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableTake.java
{ "start": 898, "end": 1243 }
class ____<T> extends AbstractFlowableWithUpstream<T, T> { final long n; public FlowableTake(Flowable<T> source, long n) { super(source); this.n = n; } @Override protected void subscribeActual(Subscriber<? super T> s) { source.subscribe(new TakeSubscriber<>(s, n)); } static final
FlowableTake
java
google__auto
value/src/main/java/com/google/auto/value/extension/AutoValueExtension.java
{ "start": 15051, "end": 15339 }
enum ____ ordered by increasing performance (but also constraints). * * @see <a * href="https://docs.gradle.org/current/userguide/java_plugin.html#sec:incremental_annotation_processing">Gradle * documentation of its incremental annotation processing</a> */ public
are
java
quarkusio__quarkus
core/launcher/src/main/java/io/quarkus/launcher/JBangDevModeLauncher.java
{ "start": 680, "end": 1680 }
class ____ { public static void main(String... args) { System.clearProperty("quarkus.dev"); //avoid unknown config key warnings final ClassLoader originalCl = Thread.currentThread().getContextClassLoader(); try { Map<String, Object> context = new HashMap<>(); context.put("args", args); RuntimeLaunchClassLoader loader = new RuntimeLaunchClassLoader(JBangDevModeLauncher.class.getClassLoader()); Thread.currentThread().setContextClassLoader(loader); Class<?> launcher = loader.loadClass("io.quarkus.bootstrap.jbang.JBangDevModeLauncherImpl"); launcher.getDeclaredMethod("main", String[].class).invoke(null, (Object) args); } catch (Exception e) { throw new RuntimeException(e); } finally { System.clearProperty(BootstrapConstants.SERIALIZED_APP_MODEL); Thread.currentThread().setContextClassLoader(originalCl); } } }
JBangDevModeLauncher
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskExecutorToResourceManagerConnectionTest.java
{ "start": 7900, "end": 8702 }
class ____< T extends RegisteredRpcConnection<?, ?, S, ?>, S extends RegistrationResponse.Success, R extends RegistrationResponse.Rejection> implements RegistrationConnectionListener<T, S, R> { @Override public void onRegistrationSuccess(final T connection, final S success) { registrationSuccessFuture.complete(null); } @Override public void onRegistrationFailure(final Throwable failure) { registrationSuccessFuture.completeExceptionally(failure); } @Override public void onRegistrationRejection(String targetAddress, R rejection) { registrationRejectionFuture.complete(null); } } }
TestRegistrationConnectionListener
java
apache__camel
components/camel-thrift/src/test/java/org/apache/camel/component/thrift/ThriftProducerZlibCompressionTest.java
{ "start": 2032, "end": 5438 }
class ____ extends CamelTestSupport { private static final Logger LOG = LoggerFactory.getLogger(ThriftProducerZlibCompressionTest.class); private static TServerSocket serverTransport; private static TServer server; @SuppressWarnings({ "rawtypes" }) private static Calculator.Processor processor; private static final int THRIFT_TEST_PORT = AvailablePortFinder.getNextAvailable(); private static final int THRIFT_TEST_NUM1 = 12; private static final int THRIFT_TEST_NUM2 = 13; private static final int THRIFT_CLIENT_TIMEOUT = 2000; @BeforeAll @SuppressWarnings({ "unchecked", "rawtypes" }) public static void startThriftServer() throws Exception { processor = new Calculator.Processor(new CalculatorSyncServerImpl()); serverTransport = new TServerSocket( new InetSocketAddress(InetAddress.getByName("localhost"), THRIFT_TEST_PORT), THRIFT_CLIENT_TIMEOUT); TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverTransport); args.processor(processor); args.protocolFactory(new TBinaryProtocol.Factory()); args.transportFactory(new TZlibTransport.Factory()); server = new TThreadPoolServer(args); Runnable simple = new Runnable() { public void run() { LOG.info("Thrift server with zlib compression started on port: {}", THRIFT_TEST_PORT); server.serve(); } }; new Thread(simple).start(); } @AfterAll public static void stopThriftServer() { if (server != null) { server.stop(); serverTransport.close(); LOG.info("Thrift server with zlib compression stoped"); } } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void testCalculateMethodInvocation() { LOG.info("Thrift calculate method sync test start"); List requestBody = new ArrayList(); requestBody.add(1); requestBody.add(new Work(THRIFT_TEST_NUM1, THRIFT_TEST_NUM2, Operation.MULTIPLY)); Object responseBody = template.requestBody("direct:thrift-zlib-calculate", requestBody); assertNotNull(responseBody); assertTrue(responseBody instanceof Integer); assertEquals(THRIFT_TEST_NUM1 * THRIFT_TEST_NUM2, responseBody); } @Test public void testVoidMethodInvocation() { LOG.info("Thrift method with empty parameters and void output sync test start"); Object requestBody = null; Object responseBody = template.requestBody("direct:thrift-zlib-ping", requestBody); assertNull(responseBody); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:thrift-zlib-calculate") .to("thrift://localhost:" + THRIFT_TEST_PORT + "/org.apache.camel.component.thrift.generated.Calculator?method=calculate&compressionType=ZLIB&synchronous=true"); from("direct:thrift-zlib-ping") .to("thrift://localhost:" + THRIFT_TEST_PORT + "/org.apache.camel.component.thrift.generated.Calculator?method=ping&compressionType=ZLIB&synchronous=true"); } }; } }
ThriftProducerZlibCompressionTest
java
apache__kafka
coordinator-common/src/test/java/org/apache/kafka/coordinator/common/runtime/InMemoryPartitionWriter.java
{ "start": 1486, "end": 1565 }
class ____ implements PartitionWriter { private static
InMemoryPartitionWriter
java
resilience4j__resilience4j
resilience4j-timelimiter/src/main/java/io/github/resilience4j/timelimiter/event/TimeLimiterEvent.java
{ "start": 934, "end": 1002 }
enum ____ { SUCCESS, TIMEOUT, ERROR } }
Type
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/TestContextManagerMethodInvokerTests.java
{ "start": 1096, "end": 2532 }
class ____ { private static final MethodInvoker customMethodInvoker = (method, target) -> null; private final TestContextManager testContextManager = new TestContextManager(TestCase.class); private final Method testMethod = ReflectionUtils.findMethod(TestCase.class, "testMethod"); @Test void methodInvokerState() throws Exception { assertThat(testContextManager.getTestExecutionListeners()).singleElement().isInstanceOf(DemoExecutionListener.class); assertMethodInvokerState(testContextManager::beforeTestClass); assertMethodInvokerState(() -> testContextManager.prepareTestInstance(this)); assertMethodInvokerState(() -> testContextManager.beforeTestMethod(this, testMethod)); assertMethodInvokerState(() -> testContextManager.beforeTestExecution(this, testMethod)); assertMethodInvokerState(() -> testContextManager.afterTestExecution(this, testMethod, null)); assertMethodInvokerState(() -> testContextManager.afterTestMethod(this, testMethod, null)); assertMethodInvokerState(testContextManager::afterTestClass); } private void assertMethodInvokerState(Executable callback) throws Exception { testContextManager.getTestContext().setMethodInvoker(customMethodInvoker); callback.execute(); assertThat(testContextManager.getTestContext().getMethodInvoker()).isSameAs(DEFAULT_INVOKER); } @TestExecutionListeners(DemoExecutionListener.class) private static
TestContextManagerMethodInvokerTests
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/TestSubtypes.java
{ "start": 6859, "end": 7244 }
class ____; with context assertEquals("{\"@type\":\"TestSubtypes$SubD\",\"d\":0}", mapper.writeValueAsString(new SubD())); } @Test public void testDeserializationNonNamed() throws Exception { ObjectMapper mapper = jsonMapperBuilder() .registerSubtypes(SubC.class) .build(); // default name should be unqualified
name
java
apache__kafka
test-common/test-common-runtime/src/main/java/org/apache/kafka/common/test/junit/ClusterTestExtensions.java
{ "start": 15001, "end": 15108 }
class ____ { // Just used as a convenience to get default values from the annotation } }
EmptyClass
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java
{ "start": 11336, "end": 13850 }
class ____ implements RegistrationBeanAdapter<Servlet> { private final @Nullable MultipartConfigElement multipartConfig; private final ListableBeanFactory beanFactory; ServletRegistrationBeanAdapter(@Nullable MultipartConfigElement multipartConfig, ListableBeanFactory beanFactory) { this.multipartConfig = multipartConfig; this.beanFactory = beanFactory; } @Override public RegistrationBean createRegistrationBean(String beanName, Servlet source, int totalNumberOfSourceBeans) { String url = (totalNumberOfSourceBeans != 1) ? "/" + beanName + "/" : "/"; if (beanName.equals(DISPATCHER_SERVLET_NAME)) { url = "/"; // always map the main dispatcherServlet to "/" } ServletRegistrationBean<Servlet> bean = new ServletRegistrationBean<>(source, url); bean.setName(beanName); bean.setMultipartConfig(this.multipartConfig); ServletRegistration registrationAnnotation = this.beanFactory.findAnnotationOnBean(beanName, ServletRegistration.class); if (registrationAnnotation != null) { Order orderAnnotation = this.beanFactory.findAnnotationOnBean(beanName, Order.class); Assert.notNull(orderAnnotation, "'orderAnnotation' must not be null"); configureFromAnnotation(bean, registrationAnnotation, orderAnnotation); } return bean; } private void configureFromAnnotation(ServletRegistrationBean<Servlet> bean, ServletRegistration registration, Order order) { bean.setEnabled(registration.enabled()); bean.setOrder(order.value()); if (StringUtils.hasText(registration.name())) { bean.setName(registration.name()); } bean.setAsyncSupported(registration.asyncSupported()); bean.setIgnoreRegistrationFailure(registration.ignoreRegistrationFailure()); bean.setLoadOnStartup(registration.loadOnStartup()); bean.setUrlMappings(Arrays.asList(registration.urlMappings())); for (WebInitParam param : registration.initParameters()) { bean.addInitParameter(param.name(), param.value()); } bean.setMultipartConfig(new MultipartConfigElement(registration.multipartConfig())); } } /** * {@link RegistrationBeanAdapter} implementation for {@link Filter} beans. * <p> * <b>NOTE:</b> A similar implementation is used in * {@code SpringBootMockMvcBuilderCustomizer} for registering * {@code @FilterRegistration} beans with {@code @MockMvc}. If you modify this class, * please also update {@code SpringBootMockMvcBuilderCustomizer} if needed. * </p> */ private static
ServletRegistrationBeanAdapter
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/context/ContextLoaderListener.java
{ "start": 1526, "end": 6479 }
class ____ extends ContextLoader implements ServletContextListener { private @Nullable ServletContext servletContext; /** * Create a new {@code ContextLoaderListener} that will create a web application * context based on the "contextClass" and "contextConfigLocation" servlet * context-params. See {@link ContextLoader} superclass documentation for details on * default values for each. * <p>This constructor is typically used when declaring {@code ContextLoaderListener} * as a {@code <listener>} within {@code web.xml}, where a no-arg constructor is * required. * <p>The created application context will be registered into the ServletContext under * the attribute name {@link WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE} * and the Spring application context will be closed when the {@link #contextDestroyed} * lifecycle method is invoked on this listener. * @see ContextLoader * @see #ContextLoaderListener(WebApplicationContext) * @see #contextInitialized(ServletContextEvent) * @see #contextDestroyed(ServletContextEvent) */ public ContextLoaderListener() { } /** * Create a new {@code ContextLoaderListener} with the given application context, * initializing it with the {@link ServletContextEvent}-provided * {@link ServletContext} reference which is spec-restricted in terms of capabilities. * <p>It is generally preferable to initialize the application context with a * {@link org.springframework.web.WebApplicationInitializer#onStartup}-given reference * which is usually fully capable. * @see #ContextLoaderListener(WebApplicationContext, ServletContext) */ public ContextLoaderListener(WebApplicationContext rootContext) { super(rootContext); } /** * Create a new {@code ContextLoaderListener} with the given application context. This * constructor is useful in Servlet initializers where instance-based registration of * listeners is possible through the {@link jakarta.servlet.ServletContext#addListener} API. * <p>The context may or may not yet be {@linkplain * org.springframework.context.ConfigurableApplicationContext#refresh() refreshed}. If it * (a) is an implementation of {@link ConfigurableWebApplicationContext} and * (b) has <strong>not</strong> already been refreshed (the recommended approach), * then the following will occur: * <ul> * <li>If the given context has not already been assigned an {@linkplain * org.springframework.context.ConfigurableApplicationContext#setId id}, one will be assigned to it</li> * <li>{@code ServletContext} and {@code ServletConfig} objects will be delegated to * the application context</li> * <li>{@link #customizeContext} will be called</li> * <li>Any {@link org.springframework.context.ApplicationContextInitializer ApplicationContextInitializers} * specified through the "contextInitializerClasses" init-param will be applied.</li> * <li>{@link org.springframework.context.ConfigurableApplicationContext#refresh refresh()} will be called</li> * </ul> * If the context has already been refreshed or does not implement * {@code ConfigurableWebApplicationContext}, none of the above will occur under the * assumption that the user has performed these actions (or not) per his or her * specific needs. * <p>See {@link org.springframework.web.WebApplicationInitializer} for usage examples. * <p>In any case, the given application context will be registered into the * ServletContext under the attribute name {@link * WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE} and the Spring * application context will be closed when the {@link #contextDestroyed} lifecycle * method is invoked on this listener. * @param rootContext the application context to manage * @param servletContext the ServletContext to initialize with * @since 6.2 * @see #contextInitialized(ServletContextEvent) * @see #contextDestroyed(ServletContextEvent) */ public ContextLoaderListener(WebApplicationContext rootContext, ServletContext servletContext) { super(rootContext); this.servletContext = servletContext; } /** * Initialize the root web application context. */ @Override public void contextInitialized(ServletContextEvent event) { ServletContext scToUse = getServletContextToUse(event); initWebApplicationContext(scToUse); } /** * Close the root web application context. */ @Override public void contextDestroyed(ServletContextEvent event) { ServletContext scToUse = getServletContextToUse(event); closeWebApplicationContext(scToUse); ContextCleanupListener.cleanupAttributes(scToUse); } /** * Preferably use a fully-capable local ServletContext instead of * the spec-restricted ServletContextEvent-provided reference. */ private ServletContext getServletContextToUse(ServletContextEvent event) { return (this.servletContext != null ? this.servletContext : event.getServletContext()); } }
ContextLoaderListener
java
quarkusio__quarkus
extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/vertx/OpenTelemetryVertxHttpMetricsFactory.java
{ "start": 1175, "end": 1410 }
class ____ implements VertxMetricsFactory { @Override public VertxMetrics metrics(final VertxOptions options) { return new OpenTelemetryVertxHttpServerMetrics(); } public static
OpenTelemetryVertxHttpMetricsFactory
java
google__auto
value/src/main/java/com/google/auto/value/processor/TypeSimplifier.java
{ "start": 12257, "end": 16406 }
interface ____ implements. */ private static Set<TypeMirror> nonPrivateDeclaredTypes(Types typeUtils, TypeMirror type) { if (type == null) { return new TypeMirrorSet(); } else { Set<TypeMirror> declared = new TypeMirrorSet(); declared.add(type); List<TypeElement> nestedTypes = ElementFilter.typesIn(typeUtils.asElement(type).getEnclosedElements()); for (TypeElement nestedType : nestedTypes) { if (!nestedType.getModifiers().contains(PRIVATE)) { declared.add(nestedType.asType()); } } for (TypeMirror supertype : typeUtils.directSupertypes(type)) { declared.addAll(nonPrivateDeclaredTypes(typeUtils, supertype)); } return declared; } } private static Set<String> ambiguousNames(Types typeUtils, Set<TypeMirror> types) { Set<String> ambiguous = new HashSet<>(); Map<String, Name> simpleNamesToQualifiedNames = new HashMap<>(); for (TypeMirror type : types) { if (type.getKind() == TypeKind.ERROR) { throw new MissingTypeException(MoreTypes.asError(type)); } String simpleName = typeUtils.asElement(type).getSimpleName().toString(); /* * Compare by qualified names, because in Eclipse JDT, if Java 8 type annotations are used, * the same (unannotated) type may appear multiple times in the Set<TypeMirror>. * TODO(emcmanus): investigate further, because this might cause problems elsewhere. */ Name qualifiedName = ((QualifiedNameable) typeUtils.asElement(type)).getQualifiedName(); Name previous = simpleNamesToQualifiedNames.put(simpleName, qualifiedName); if (previous != null && !previous.equals(qualifiedName)) { ambiguous.add(simpleName); } } return ambiguous; } /** * Returns true if casting to the given type will elicit an unchecked warning from the compiler. * Only generic types such as {@code List<String>} produce such warnings. There will be no warning * if the type's only generic parameters are simple wildcards, as in {@code Map<?, ?>}. */ static boolean isCastingUnchecked(TypeMirror type) { return CASTING_UNCHECKED_VISITOR.visit(type, null); } private static final TypeVisitor<Boolean, Void> CASTING_UNCHECKED_VISITOR = new SimpleTypeVisitor8<Boolean, Void>(false) { @Override public Boolean visitUnknown(TypeMirror t, Void p) { // We don't know whether casting is unchecked for this mysterious type but assume it is, // so we will insert a possibly unnecessary @SuppressWarnings("unchecked"). return true; } @Override public Boolean visitArray(ArrayType t, Void p) { return visit(t.getComponentType(), p); } @Override public Boolean visitDeclared(DeclaredType t, Void p) { return t.getTypeArguments().stream().anyMatch(TypeSimplifier::uncheckedTypeArgument); } @Override public Boolean visitTypeVariable(TypeVariable t, Void p) { return true; } }; // If a type has a type argument, then casting to the type is unchecked, except if the argument // is <?> or <? extends Object>. The same applies to all type arguments, so casting to Map<?, ?> // does not produce an unchecked warning for example. private static boolean uncheckedTypeArgument(TypeMirror arg) { if (arg.getKind() == TypeKind.WILDCARD) { WildcardType wildcard = (WildcardType) arg; if (wildcard.getExtendsBound() == null || isJavaLangObject(wildcard.getExtendsBound())) { // This is <?>, unless there's a super bound, in which case it is <? super Foo> and // is erased. return (wildcard.getSuperBound() != null); } } return true; } private static boolean isJavaLangObject(TypeMirror type) { if (type.getKind() != TypeKind.DECLARED) { return false; } DeclaredType declaredType = (DeclaredType) type; TypeElement typeElement = (TypeElement) declaredType.asElement(); return typeElement.getQualifiedName().contentEquals("java.lang.Object"); } }
it
java
apache__camel
test-infra/camel-test-infra-openai-mock/src/main/java/org/apache/camel/test/infra/openai/mock/ResponseBuilder.java
{ "start": 1260, "end": 1336 }
class ____ creating different types of OpenAI API mock responses. */ public
for
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/verification/SelectedMocksInOrderVerificationTest.java
{ "start": 522, "end": 5458 }
class ____ extends TestBase { private IMethods mockOne; private IMethods mockTwo; private IMethods mockThree; @Before public void setUp() { mockOne = mock(IMethods.class); mockTwo = mock(IMethods.class); mockThree = mock(IMethods.class); mockOne.simpleMethod(1); mockTwo.simpleMethod(2); mockTwo.simpleMethod(2); mockThree.simpleMethod(3); mockTwo.simpleMethod(2); mockOne.simpleMethod(4); } @Test public void shouldVerifyAllInvocationsInOrder() { InOrder inOrder = inOrder(mockOne, mockTwo, mockThree); inOrder.verify(mockOne).simpleMethod(1); inOrder.verify(mockTwo, times(2)).simpleMethod(2); inOrder.verify(mockThree).simpleMethod(3); inOrder.verify(mockTwo).simpleMethod(2); inOrder.verify(mockOne).simpleMethod(4); verifyNoMoreInteractions(mockOne, mockTwo, mockThree); } @Test public void shouldVerifyInOrderMockTwoAndThree() { InOrder inOrder = inOrder(mockTwo, mockThree); inOrder.verify(mockTwo, times(2)).simpleMethod(2); inOrder.verify(mockThree).simpleMethod(3); inOrder.verify(mockTwo).simpleMethod(2); verifyNoMoreInteractions(mockTwo, mockThree); } @Test public void shouldVerifyInOrderMockOneAndThree() { InOrder inOrder = inOrder(mockOne, mockThree); inOrder.verify(mockOne).simpleMethod(1); inOrder.verify(mockThree).simpleMethod(3); inOrder.verify(mockOne).simpleMethod(4); verifyNoMoreInteractions(mockOne, mockThree); } @Test public void shouldVerifyMockOneInOrder() { InOrder inOrder = inOrder(mockOne); inOrder.verify(mockOne).simpleMethod(1); inOrder.verify(mockOne).simpleMethod(4); verifyNoMoreInteractions(mockOne); } @Test public void shouldFailVerificationForMockOne() { InOrder inOrder = inOrder(mockOne); inOrder.verify(mockOne).simpleMethod(1); try { inOrder.verify(mockOne).differentMethod(); fail(); } catch (VerificationInOrderFailure e) { } } @Test public void shouldFailVerificationForMockOneBecauseOfWrongOrder() { InOrder inOrder = inOrder(mockOne); inOrder.verify(mockOne).simpleMethod(4); try { inOrder.verify(mockOne).simpleMethod(1); fail(); } catch (VerificationInOrderFailure e) { } } @Test public void shouldVerifyMockTwoWhenThreeTimesUsed() { InOrder inOrder = inOrder(mockTwo); inOrder.verify(mockTwo, times(3)).simpleMethod(2); verifyNoMoreInteractions(mockTwo); } @Test public void shouldVerifyMockTwo() { InOrder inOrder = inOrder(mockTwo); inOrder.verify(mockTwo, atLeastOnce()).simpleMethod(2); verifyNoMoreInteractions(mockTwo); } @Test public void shouldFailVerificationForMockTwo() { InOrder inOrder = inOrder(mockTwo); try { inOrder.verify(mockTwo).simpleMethod(2); fail(); } catch (VerificationInOrderFailure e) { } } @Test public void shouldThrowNoMoreInvocationsForMockTwo() { InOrder inOrder = inOrder(mockTwo); try { inOrder.verify(mockTwo, times(2)).simpleMethod(2); fail(); } catch (VerificationInOrderFailure e) { } } @Test public void shouldThrowTooFewInvocationsForMockTwo() { InOrder inOrder = inOrder(mockTwo); try { inOrder.verify(mockTwo, times(4)).simpleMethod(2); fail(); } catch (VerificationInOrderFailure e) { } } @Test public void shouldThrowTooManyInvocationsForMockTwo() { InOrder inOrder = inOrder(mockTwo); try { inOrder.verify(mockTwo, times(2)).simpleMethod(2); fail(); } catch (VerificationInOrderFailure e) { } } @Test public void shouldAllowThreeTimesOnMockTwo() { InOrder inOrder = inOrder(mockTwo); inOrder.verify(mockTwo, times(3)).simpleMethod(2); verifyNoMoreInteractions(mockTwo); } @Test public void shouldVerifyMockTwoCompletely() { InOrder inOrder = inOrder(mockTwo, mockThree); inOrder.verify(mockTwo, times(2)).simpleMethod(2); inOrder.verify(mockThree).simpleMethod(3); inOrder.verify(mockTwo).simpleMethod(2); verifyNoMoreInteractions(mockTwo, mockThree); } @Test public void shouldAllowTwoTimesOnMockTwo() { InOrder inOrder = inOrder(mockTwo, mockThree); inOrder.verify(mockTwo, times(2)).simpleMethod(2); try { verifyNoMoreInteractions(mockTwo); fail(); } catch (NoInteractionsWanted e) { } } }
SelectedMocksInOrderVerificationTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/CryptoAdmin.java
{ "start": 1866, "end": 3584 }
class ____ extends Configured implements Tool { public CryptoAdmin() { this(null); } public CryptoAdmin(Configuration conf) { super(conf); } @Override public int run(String[] args) throws IOException { if (args.length == 0) { AdminHelper.printUsage(false, "crypto", COMMANDS); ToolRunner.printGenericCommandUsage(System.err); return 1; } final AdminHelper.Command command = AdminHelper.determineCommand(args[0], COMMANDS); if (command == null) { System.err.println("Can't understand command '" + args[0] + "'"); if (!args[0].startsWith("-")) { System.err.println("Command names must start with dashes."); } AdminHelper.printUsage(false, "crypto", COMMANDS); ToolRunner.printGenericCommandUsage(System.err); return 1; } final List<String> argsList = new LinkedList<String>(); for (int j = 1; j < args.length; j++) { argsList.add(args[j]); } try { return command.run(getConf(), argsList); } catch (IllegalArgumentException e) { System.err.println(prettifyException(e)); return -1; } } public static void main(String[] argsArray) throws Exception { final CryptoAdmin cryptoAdmin = new CryptoAdmin(new Configuration()); int res = ToolRunner.run(cryptoAdmin, argsArray); System.exit(res); } /** * NN exceptions contain the stack trace as part of the exception message. * When it's a known error, pretty-print the error and squish the stack trace. */ private static String prettifyException(Exception e) { return e.getClass().getSimpleName() + ": " + e.getLocalizedMessage().split("\n")[0]; } private static
CryptoAdmin
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/streamrecord/StreamRecord.java
{ "start": 1091, "end": 6460 }
class ____<T> extends StreamElement { /** The actual value held by this record. */ private T value; /** The timestamp of the record. */ private long timestamp; /** Flag whether the timestamp is actually set. */ private boolean hasTimestamp; /** Creates a new StreamRecord. The record does not have a timestamp. */ public StreamRecord(T value) { this.value = value; } /** * Creates a new StreamRecord wrapping the given value. The timestamp is set to the given * timestamp. * * @param value The value to wrap in this {@link StreamRecord} * @param timestamp The timestamp in milliseconds */ public StreamRecord(T value, long timestamp) { this.value = value; this.timestamp = timestamp; this.hasTimestamp = true; } // ------------------------------------------------------------------------ // Accessors // ------------------------------------------------------------------------ /** Returns the value wrapped in this stream value. */ public T getValue() { return value; } /** Returns the timestamp associated with this stream value in milliseconds. */ public long getTimestamp() { if (hasTimestamp) { return timestamp; } else { return Long.MIN_VALUE; // throw new IllegalStateException( // "Record has no timestamp. Is the time characteristic set to 'ProcessingTime', or // " + // "did you forget to call 'DataStream.assignTimestampsAndWatermarks(...)'?"); } } /** * Checks whether this record has a timestamp. * * @return True if the record has a timestamp, false if not. */ public boolean hasTimestamp() { return hasTimestamp; } // ------------------------------------------------------------------------ // Updating // ------------------------------------------------------------------------ /** * Replace the currently stored value by the given new value. This returns a StreamElement with * the generic type parameter that matches the new value while keeping the old timestamp. * * @param element Element to set in this stream value * @return Returns the StreamElement with replaced value */ @SuppressWarnings("unchecked") public <X> StreamRecord<X> replace(X element) { this.value = (T) element; return (StreamRecord<X>) this; } /** * Replace the currently stored value by the given new value and the currently stored timestamp * with the new timestamp. This returns a StreamElement with the generic type parameter that * matches the new value. * * @param value The new value to wrap in this StreamRecord * @param timestamp The new timestamp in milliseconds * @return Returns the StreamElement with replaced value */ @SuppressWarnings("unchecked") public <X> StreamRecord<X> replace(X value, long timestamp) { this.timestamp = timestamp; this.value = (T) value; this.hasTimestamp = true; return (StreamRecord<X>) this; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; this.hasTimestamp = true; } public void eraseTimestamp() { this.hasTimestamp = false; } // ------------------------------------------------------------------------ // Copying // ------------------------------------------------------------------------ /** * Creates a copy of this stream record. Uses the copied value as the value for the new record, * i.e., only copies timestamp fields. */ public StreamRecord<T> copy(T valueCopy) { StreamRecord<T> copy = new StreamRecord<>(valueCopy); copy.timestamp = this.timestamp; copy.hasTimestamp = this.hasTimestamp; return copy; } /** * Copies this record into the new stream record. Uses the copied value as the value for the new * record, i.e., only copies timestamp fields. */ public void copyTo(T valueCopy, StreamRecord<T> target) { target.value = valueCopy; target.timestamp = this.timestamp; target.hasTimestamp = this.hasTimestamp; } // ------------------------------------------------------------------------ // Utilities // ------------------------------------------------------------------------ @Override public boolean equals(Object o) { if (this == o) { return true; } else if (o != null && getClass() == o.getClass()) { StreamRecord<?> that = (StreamRecord<?>) o; return this.hasTimestamp == that.hasTimestamp && (!this.hasTimestamp || this.timestamp == that.timestamp) && (this.value == null ? that.value == null : this.value.equals(that.value)); } else { return false; } } @Override public int hashCode() { int result = value != null ? value.hashCode() : 0; return 31 * result + (hasTimestamp ? (int) (timestamp ^ (timestamp >>> 32)) : 0); } @Override public String toString() { return "Record @ " + (hasTimestamp ? timestamp : "(undef)") + " : " + value; } }
StreamRecord
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/concurrent/InboundMessageQueueTest.java
{ "start": 1250, "end": 13797 }
class ____ extends InboundMessageQueue<Integer> { final IntConsumer consumer; private Handler<Void> drainHandler; private volatile boolean writable; private int size; public TestChannel(IntConsumer consumer) { super(((ContextInternal) context).eventLoop(), ((ContextInternal) context).executor()); this.consumer = consumer; this.writable = true; } public TestChannel(IntConsumer consumer, int lwm, int hwm) { super(((ContextInternal) context).eventLoop(), ((ContextInternal) context).executor(), lwm, hwm); this.consumer = consumer; this.writable = true; } int size() { return size; } @Override protected void handleMessage(Integer msg) { size--; consumer.accept(msg); } @Override protected void handleResume() { writable = true; Handler<Void> handler = drainHandler; if (handler != null) { handler.handle(null); } } public boolean isWritable() { return writable; } @Override protected void handlePause() { writable = false; } final void resume() { fetch(Long.MAX_VALUE); } final int fill() { int count = 0; boolean drain = false; while (writable) { drain |= add(sequence.getAndIncrement()); count++; } size += count; if (drain) { drain(); } return count; } final boolean emit() { size++; write(sequence.getAndIncrement()); return writable; } final boolean emit(int count) { size += count; boolean drain = false; for (int i = 0; i < count; i++) { drain |= add(sequence.getAndIncrement()); } if (drain) { drain(); } return writable; } TestChannel drainHandler(Handler<Void> handler) { this.drainHandler = handler; return this; } } protected abstract Context createContext(VertxInternal vertx); @Override public void setUp() throws Exception { super.setUp(); context = createContext((VertxInternal) vertx); sequence.set(0); context.runOnContext(v -> { consumerThread = Thread.currentThread(); }); ((ContextInternal)context).nettyEventLoop().execute(() -> { producerThread = Thread.currentThread(); }); waitUntil(() -> consumerThread != null && producerThread != null); } @Override protected VertxOptions getOptions() { return super.getOptions().setWorkerPoolSize(1); } public void tearDown() throws Exception { super.tearDown(); } protected final void assertConsumer() { assertSame(consumerThread, Thread.currentThread()); } protected final void assertProducer() { assertSame(producerThread, Thread.currentThread()); } protected final void producerTask(Runnable task) { ((ContextInternal)context).nettyEventLoop().execute(task); } protected final void consumerTask(Runnable task) { context.runOnContext(v -> task.run()); } protected final TestChannel buffer(IntConsumer consumer) { return new TestChannel(consumer); } protected final TestChannel buffer(IntConsumer consumer, int lwm, int hwm) { return new TestChannel(consumer, lwm, hwm); } @Test public void testFlowing() { AtomicInteger events = new AtomicInteger(); queue = buffer(elt -> { assertConsumer(); assertEquals(0, elt); assertEquals(0, events.getAndIncrement()); testComplete(); }); producerTask(() -> { assertTrue(queue.emit()); }); await(); } @Test public void testTake() { AtomicInteger events = new AtomicInteger(); queue = buffer(elt -> { assertConsumer(); assertEquals(0, elt); assertEquals(0, events.getAndIncrement()); testComplete(); }); consumerTask(() -> { queue.pause(); queue.fetch(1); producerTask(() -> queue.emit()); }); await(); } @Test public void testFlowingAdd() { AtomicInteger events = new AtomicInteger(); queue = buffer(elt -> { assertConsumer(); events.getAndIncrement(); }); producerTask(() -> { assertTrue(queue.emit()); assertWaitUntil(() -> events.get() == 1); assertTrue(queue.emit()); assertWaitUntil(() -> events.get() == 2); testComplete(); }); await(); } @Test public void testFlowingRefill() { AtomicInteger events = new AtomicInteger(); queue = buffer(elt -> { assertConsumer(); events.getAndIncrement(); }, 5, 5).drainHandler(v -> { assertProducer(); assertEquals(8, events.get()); testComplete(); }); queue.pause(); producerTask(() -> { for (int i = 0; i < 8; i++) { assertEquals("Expected " + i + " to be bilto", i < 4, queue.emit()); } queue.resume(); }); await(); } @Test public void testPauseWhenFull() { AtomicInteger events = new AtomicInteger(); AtomicInteger reads = new AtomicInteger(); queue = buffer(elt -> { assertConsumer(); assertEquals(0, reads.get()); assertEquals(0, events.getAndIncrement()); testComplete(); }, 5, 5).drainHandler(v2 -> { assertProducer(); assertEquals(0, reads.getAndIncrement()); }); producerTask(() -> { queue.pause(); for (int i = 0; i < 5; i++) { assertEquals(i < 4, queue.emit()); } queue.fetch(1); }); await(); } @Test public void testPausedResume() { AtomicInteger reads = new AtomicInteger(); AtomicInteger events = new AtomicInteger(); queue = buffer(elt -> { assertConsumer(); events.getAndIncrement(); }, 5, 5).drainHandler(v2 -> { assertProducer(); assertEquals(0, reads.getAndIncrement()); assertEquals(5, events.get()); testComplete(); }); producerTask(() -> { queue.pause(); queue.fill(); queue.resume(); }); await(); } @Test public void testPausedDrain() { waitFor(2); AtomicInteger drained = new AtomicInteger(); AtomicInteger emitted = new AtomicInteger(); queue = buffer(elt -> { assertConsumer(); assertEquals(0, drained.get()); emitted.getAndIncrement(); }, 5, 5); queue.drainHandler(v2 -> { assertProducer(); assertEquals(0, drained.getAndIncrement()); assertEquals(5, emitted.get()); complete(); }); producerTask(() -> { queue.pause(); queue.fill(); assertEquals(0, drained.get()); assertEquals(0, emitted.get()); queue.resume(); complete(); }); await(); } @Test public void testPausedRequestLimited() { AtomicInteger events = new AtomicInteger(); AtomicInteger reads = new AtomicInteger(); queue = buffer(elt -> { assertConsumer(); events.getAndIncrement(); }, 3, 3) .drainHandler(v2 -> { assertProducer(); assertEquals(0, reads.getAndIncrement()); }); producerTask(() -> { queue.pause(); queue.fetch(1); assertEquals(0, reads.get()); assertEquals(0, events.get()); assertTrue(queue.emit()); assertEquals(0, reads.get()); waitUntilEquals(1, events::get); assertTrue(queue.emit()); assertEquals(0, reads.get()); assertEquals(1, events.get()); assertTrue(queue.emit()); assertEquals(0, reads.get()); assertEquals(1, events.get()); assertFalse(queue.emit()); assertEquals(0, reads.get()); assertEquals(1, events.get()); testComplete(); }); await(); } @Test public void testPushReturnsTrueUntilHighWatermark() { AtomicInteger emitted = new AtomicInteger(); queue = buffer(elt -> { emitted.incrementAndGet(); }, 2, 2); producerTask(() -> { queue.pause(); queue.fetch(1); assertTrue(queue.emit()); assertWaitUntil(() -> emitted.get() == 1); assertTrue(queue.emit()); assertFalse(queue.emit()); testComplete(); }); await(); } @Test public void testHighWaterMark() { queue = buffer(elt -> { }, 5, 5); producerTask(() -> { queue.pause(); queue.fill(); assertEquals(5, sequence.get()); testComplete(); }); await(); } /* @Test public void testEmptyHandler() { context.runOnContext(v1 -> { buffer = new InboundBuffer<>(context, 4L); AtomicInteger emptyCount = new AtomicInteger(); AtomicInteger itemCount = new AtomicInteger(); buffer.handler(item -> itemCount.incrementAndGet()); buffer.emptyHandler(v2 -> { assertEquals(0, emptyCount.getAndIncrement()); testComplete(); }); assertTrue(emit()); assertEquals(1, itemCount.get()); buffer.pause(); assertTrue(emit()); assertTrue(emit()); assertTrue(emit()); assertEquals(1, itemCount.get()); assertFalse(buffer.isEmpty()); for (int i = 0;i < 3;i++) { assertEquals(0, emptyCount.get()); buffer.fetch(1); } }); await(); } */ @Test public void testAddAllWhenPaused() { waitFor(2); AtomicInteger emitted = new AtomicInteger(); AtomicInteger emptied = new AtomicInteger(); AtomicInteger drained = new AtomicInteger(); queue = buffer(elt -> { emitted.incrementAndGet(); assertEquals(0, drained.get()); assertEquals(0, emptied.get()); queue.fetch(1); }, 4, 4) .drainHandler(v2 -> { assertEquals(5, emitted.get()); drained.incrementAndGet(); complete(); }); producerTask(() -> { queue.pause(); assertFalse(queue.emit(5)); queue.fetch(1); complete(); }); await(); } @Test public void testAddAllWhenFlowing() { AtomicInteger emitted = new AtomicInteger(); AtomicInteger drained = new AtomicInteger(); queue = buffer(elt -> { emitted.incrementAndGet(); }, 4, 4) .drainHandler(v2 -> drained.incrementAndGet()); producerTask(() -> { queue.emit(4); }); waitUntilEquals(1, drained::get); waitUntilEquals(4, emitted::get); } @Test public void testCheckThatPauseAfterResumeWontDoAnyEmission() { AtomicInteger emitted = new AtomicInteger(); queue = buffer(elt -> emitted.incrementAndGet(), 4, 4); producerTask(() -> { queue.pause(); queue.fill(); consumerTask(() -> { // Resume will execute an asynchronous drain operation queue.resume(); // Pause just after to ensure that no elements will be delivered to the handler queue.pause(); // Give enough time to have elements delivered vertx.setTimer(20, id -> { // Check we haven't received anything assertEquals(0, emitted.get()); testComplete(); }); }); }); await(); } @Test public void testBufferSignalingFullImmediately() { List<Integer> emitted = Collections.synchronizedList(new ArrayList<>()); AtomicInteger drained = new AtomicInteger(); queue = buffer(emitted::add, 1, 1); producerTask(() -> { queue.drainHandler(v -> { switch (drained.getAndIncrement()) { case 0: producerTask(() -> { assertFalse(queue.emit()); queue.resume(); }); break; case 1: assertEquals(Arrays.asList(0, 1), emitted); testComplete(); break; } }); queue.emit(); assertWaitUntil(() -> emitted.size() == 1); assertEquals(Collections.singletonList(0), emitted); queue.pause(); }); await(); } @Test public void testClose() { List<Integer> emitted = Collections.synchronizedList(new ArrayList<>()); List<Integer> disposed = Collections.synchronizedList(new ArrayList<>()); queue = new TestChannel(emitted::add, 1, 1) { @Override protected void handleDispose(Integer msg) { disposed.add(msg); } }; producerTask(() -> { queue.pause(); queue.emit(5); queue.closeProducer(); consumerTask(() -> { queue.closeConsumer(); assertEquals(Collections.emptyList(), emitted); assertEquals(Arrays.asList(0, 1, 2, 3, 4), disposed); producerTask(() -> { queue.write(5); testComplete(); }); }); }); await(); } }
TestChannel
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/ZoneReencryptionStatus.java
{ "start": 1264, "end": 2271 }
enum ____ { /** * Submitted for re-encryption but hasn't been picked up. * This is the initial state. */ Submitted, /** * Currently re-encrypting. */ Processing, /** * Re-encryption completed. */ Completed } private long id; private String zoneName; /** * The re-encryption status of the zone. Note this is a in-memory only * variable. On failover it will always be submitted, or completed if * completionTime != 0; */ private State state; private String ezKeyVersionName; private long submissionTime; private long completionTime; private boolean canceled; /** * Name of last file processed. It's important to record name (not inode) * because we want to restore to the position even if the inode is removed. */ private String lastCheckpointFile; private long filesReencrypted; private long numReencryptionFailures; /** * Builder of {@link ZoneReencryptionStatus}. */ public static final
State
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_285.java
{ "start": 880, "end": 1716 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "select 'a', \"a rrr122\" , avg(`id`) as 'x Y Z' from test4dmp.test where string_test = \"abdfeed\" and date_test > \"1991-01-10 00:12:11\" group by id having `x Y Z` > 10 order by 3 limit 5;"; SQLStatement stmt = SQLUtils .parseSingleStatement(sql, DbType.mysql, SQLParserFeature.SupportUnicodeCodePoint); assertEquals("SELECT 'a', 'a rrr122', avg(`id`) AS \"x Y Z\"\n" + "FROM test4dmp.test\n" + "WHERE string_test = 'abdfeed'\n" + "\tAND date_test > '1991-01-10 00:12:11'\n" + "GROUP BY id\n" + "HAVING `x Y Z` > 10\n" + "ORDER BY 3\n" + "LIMIT 5;", stmt.toString()); } }
MySqlSelectTest_285
java
apache__camel
components/camel-whatsapp/src/main/java/org/apache/camel/component/whatsapp/WhatsAppService.java
{ "start": 1048, "end": 1166 }
interface ____ { void sendMessage(Exchange exchange, AsyncCallback callback, BaseMessage message); }
WhatsAppService
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/authorization/RequiredAuthoritiesRepository.java
{ "start": 964, "end": 1286 }
interface ____ { /** * Finds additional required {@link GrantedAuthority#getAuthority()}s for the provided * username. * @param username the username. Cannot be null or empty. * @return the additional authorities required. */ List<String> findRequiredAuthorities(String username); }
RequiredAuthoritiesRepository
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/analytics/action/PostAnalyticsEventAction.java
{ "start": 2053, "end": 8715 }
class ____ extends LegacyActionRequest implements AnalyticsEvent.Context, ToXContentObject { private final String eventCollectionName; private final String eventType; private final long eventTime; private final boolean debug; private final BytesReference payload; private final XContentType xContentType; private final Map<String, List<String>> headers; private final String clientAddress; private Request( String eventCollectionName, String eventType, long eventTime, XContentType xContentType, BytesReference payload, boolean debug, @Nullable Map<String, List<String>> headers, @Nullable String clientAddress ) { this.eventCollectionName = eventCollectionName; this.eventType = eventType; this.debug = debug; this.eventTime = eventTime; this.xContentType = xContentType; this.payload = payload; this.headers = Objects.requireNonNullElse(headers, Map.of()); this.clientAddress = clientAddress; } public Request(StreamInput in) throws IOException { super(in); this.eventCollectionName = in.readString(); this.eventType = in.readString(); this.debug = in.readBoolean(); this.eventTime = in.readLong(); this.xContentType = in.readEnum(XContentType.class); this.payload = in.readBytesReference(); this.headers = in.readMap(StreamInput::readStringCollectionAsList); this.clientAddress = in.readOptionalString(); } public static RequestBuilder builder( String eventCollectionName, String eventType, XContentType xContentType, BytesReference payload ) { return new RequestBuilder(eventCollectionName, eventType, xContentType, payload); } @Override public String eventCollectionName() { return eventCollectionName; } @Override public AnalyticsEvent.Type eventType() { return AnalyticsEvent.Type.valueOf(eventType.toUpperCase(Locale.ROOT)); } @Override public long eventTime() { return eventTime; } @Override public String userAgent() { return header("User-Agent"); } @Override public String clientAddress() { return clientAddress; } public BytesReference payload() { return payload; } public XContentType xContentType() { return xContentType; } public boolean isDebug() { return debug; } Map<String, List<String>> headers() { return Collections.unmodifiableMap(headers); } private String header(String header) { final List<String> values = headers.get(header); if (values != null && values.isEmpty() == false) { return values.get(0); } return null; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (Strings.isNullOrEmpty(eventCollectionName)) { validationException = addValidationError("collection name is missing", validationException); } if (Strings.isNullOrEmpty(eventType)) { validationException = addValidationError("event type is missing", validationException); } try { if (eventType.toLowerCase(Locale.ROOT).equals(eventType) == false) { throw new IllegalArgumentException("event type must be lowercase"); } AnalyticsEvent.Type.valueOf(eventType.toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException e) { validationException = addValidationError(Strings.format("invalid event type: [%s]", eventType), validationException); } return validationException; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(eventCollectionName); out.writeString(eventType); out.writeBoolean(debug); out.writeLong(eventTime); XContentHelper.writeTo(out, xContentType); out.writeBytesReference(payload); out.writeMap(headers, StreamOutput::writeStringCollection); out.writeOptionalString(clientAddress); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Request that = (Request) o; return Objects.equals(eventCollectionName, that.eventCollectionName) && debug == that.debug && eventTime == that.eventTime && Objects.equals(eventType, that.eventType) && Objects.equals(xContentType.canonical(), that.xContentType.canonical()) && Objects.equals(payload, that.payload) && Objects.equals(headers, that.headers) && Objects.equals(clientAddress, that.clientAddress); } @Override public int hashCode() { return Objects.hash( eventCollectionName, eventType, debug, eventTime, xContentType.canonical(), payload, headers, clientAddress ); } @Override public String toString() { return Strings.toString(this); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field("event_collection_name", eventCollectionName); builder.field("debug", debug); builder.field("event_time", eventTime); builder.field("event_type", eventType); builder.field("x_content_type", xContentType); builder.field("payload", payload); builder.field("headers", headers); builder.field("client_address", clientAddress); builder.endObject(); return builder; } } public static
Request
java
alibaba__fastjson
src/main/java/com/alibaba/fastjson/asm/Opcodes.java
{ "start": 1767, "end": 2231 }
interface ____ not define all the JVM opcodes * because some opcodes are automatically handled. For example, the xLOAD and xSTORE opcodes are automatically replaced * by xLOAD_n and xSTORE_n opcodes when possible. The xLOAD_n and xSTORE_n opcodes are therefore not defined in this * interface. Likewise for LDC, automatically replaced by LDC_W or LDC2_W when necessary, WIDE, GOTO_W and JSR_W. * * @author Eric Bruneton * @author Eugene Kuleshov */ public
does
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/discovery/NestedClassSelector.java
{ "start": 4451, "end": 5836 }
class ____ be loaded. */ public Class<?> getNestedClass() { return this.nestedClassSelector.getJavaClass(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NestedClassSelector that = (NestedClassSelector) o; return this.enclosingClassSelectors.equals(that.enclosingClassSelectors) && this.nestedClassSelector.equals(that.nestedClassSelector); } @Override public int hashCode() { return Objects.hash(this.enclosingClassSelectors, this.nestedClassSelector); } @Override public String toString() { return new ToStringBuilder(this) // .append("enclosingClassNames", getEnclosingClassNames()) // .append("nestedClassName", getNestedClassName()) // .append("classLoader", getClassLoader()) // .toString(); } @Override public Optional<DiscoverySelectorIdentifier> toIdentifier() { String allClassNames = Stream.concat(enclosingClassSelectors.stream(), Stream.of(nestedClassSelector)) // .map(ClassSelector::getClassName) // .collect(joining("/")); return Optional.of(DiscoverySelectorIdentifier.create(IdentifierParser.PREFIX, allClassNames)); } /** * The {@link DiscoverySelectorIdentifierParser} for * {@link NestedClassSelector NestedClassSelectors}. */ @API(status = INTERNAL, since = "1.11") public static
cannot
java
playframework__playframework
transport/server/play-server/src/main/java/play/server/Server.java
{ "start": 4782, "end": 7328 }
class ____ { private Server.Config _config = new Server.Config(new EnumMap<>(Protocol.class), Mode.TEST); /** * Instruct the server to serve HTTP on a particular port. * * <p>Passing 0 will make it serve on a random available port. * * @param port the port on which to serve http traffic * @return the builder with port set. */ public Builder http(int port) { return _protocol(Protocol.HTTP, port); } /** * Configure the server to serve HTTPS on a particular port. * * <p>Passing 0 will make it serve on a random available port. * * @param port the port on which to serve ssl traffic * @return the builder with port set. */ public Builder https(int port) { return _protocol(Protocol.HTTPS, port); } /** * Set the mode the server should be run on (defaults to TEST) * * @param mode the Play mode (dev, prod, test) * @return the builder with Server.Config set to mode. */ public Builder mode(Mode mode) { _config = new Server.Config(_config.ports(), mode); return this; } /** * Build the server and begin serving the provided routes as configured. * * @param router the router to use. * @return the actively running server. */ public Server build(final Router router) { return build((components) -> router); } /** * Build the server and begin serving the provided routes as configured. * * @param block the router to use. * @return the actively running server. */ public Server build(Function<BuiltInComponents, Router> block) { Server.Config config = _buildConfig(); return new Server( JavaServerHelper.forRouter( JavaModeConverter.asScalaMode(config.mode()), OptionConverters.toScala(config.maybeHttpPort()), OptionConverters.toScala(config.maybeHttpsPort()), block)); } // // Private members // private Server.Config _buildConfig() { Builder builder = this; if (_config.ports().isEmpty()) { builder = this._protocol(Protocol.HTTP, 0); } return builder._config; } private Builder _protocol(Protocol protocol, int port) { Map<Protocol, Integer> newPorts = new EnumMap<>(Protocol.class); newPorts.putAll(_config.ports()); newPorts.put(protocol, port); _config = new Server.Config(newPorts, _config.mode()); return this; } } }
Builder
java
micronaut-projects__micronaut-core
http-client-jdk/src/main/java/io/micronaut/http/client/jdk/cookie/DefaultCookieDecoder.java
{ "start": 1069, "end": 1352 }
class ____ implements CookieDecoder { @Override public Optional<Cookies> decode(HttpRequest<?> request) { return Optional.of(request.getCookies()); } @Override public int getOrder() { return NettyCookieDecoder.ORDER + 1; } }
DefaultCookieDecoder
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSParametersProvider.java
{ "start": 11036, "end": 11384 }
class ____ extends LongParam { /** * Parameter name. */ public static final String NAME = HttpFSFileSystem.NEW_LENGTH_PARAM; /** * Constructor. */ public NewLengthParam() { super(NAME, 0l); } } /** * Class for overwrite parameter. */ @InterfaceAudience.Private public static
NewLengthParam
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/taskmanager/TestUntypedMessageHeaders.java
{ "start": 1344, "end": 2133 }
class ____ implements UntypedResponseMessageHeaders<EmptyRequestBody, TaskManagerMessageParameters> { static final String URL = "/foobar"; @Override public Class<EmptyRequestBody> getRequestClass() { return EmptyRequestBody.class; } @Override public TaskManagerMessageParameters getUnresolvedMessageParameters() { return new TaskManagerMessageParameters(); } @Override public HttpMethodWrapper getHttpMethod() { return HttpMethodWrapper.GET; } @Override public String getTargetRestEndpointURL() { return URL; } @Override public Collection<RuntimeRestAPIVersion> getSupportedAPIVersions() { return Collections.singleton(RuntimeRestAPIVersion.V1); } }
TestUntypedMessageHeaders
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/internal/EntityTypeImpl.java
{ "start": 1885, "end": 8220 }
class ____<J> extends AbstractIdentifiableType<J> implements SqmEntityDomainType<J>, Serializable { private final String jpaEntityName; private final JpaMetamodelImplementor metamodel; private final SqmPathSource<?> discriminatorPathSource; public EntityTypeImpl( String entityName, String jpaEntityName, boolean hasIdClass, boolean hasIdProperty, boolean hasVersion, JavaType<J> javaType, IdentifiableDomainType<? super J> superType, JpaMetamodelImplementor metamodel) { super( entityName, javaType, superType, hasIdClass, hasIdProperty, hasVersion, metamodel ); this.jpaEntityName = jpaEntityName; this.metamodel = metamodel; discriminatorPathSource = entityDiscriminatorPathSource( metamodel ); } private EntityDiscriminatorSqmPathSource<?> entityDiscriminatorPathSource(JpaMetamodelImplementor metamodel) { final EntityPersister entityDescriptor = metamodel.getMappingMetamodel() .getEntityDescriptor( getHibernateEntityName() ); final DiscriminatorType<?> discriminatorType = entityDescriptor.getDiscriminatorDomainType(); return discriminatorType == null ? null : new EntityDiscriminatorSqmPathSource<>( discriminatorType, this, entityDescriptor ); } public EntityTypeImpl( JavaType<J> javaType, IdentifiableDomainType<? super J> superType, PersistentClass persistentClass, JpaMetamodelImplementor metamodel) { this( persistentClass.getEntityName(), persistentClass.getJpaEntityName(), persistentClass.getDeclaredIdentifierMapper() != null || superType != null && superType.hasIdClass(), persistentClass.hasIdentifierProperty(), persistentClass.isVersioned(), javaType, superType, metamodel ); } public EntityTypeImpl(JavaType<J> javaTypeDescriptor, JpaMetamodelImplementor metamodel) { super( javaTypeDescriptor.getJavaTypeClass().getName(), javaTypeDescriptor, null, false, false, false, metamodel ); this.jpaEntityName = javaTypeDescriptor.getJavaTypeClass().getName(); this.metamodel = metamodel; this.discriminatorPathSource = null; } @Override public String getName() { return jpaEntityName; } @Override public Class<J> getBindableJavaType() { return getJavaType(); } @Override public String getHibernateEntityName() { return super.getTypeName(); } @Override public @Nullable SqmDomainType<J> getSqmType() { return this; } @Override public String getPathName() { return getHibernateEntityName(); } @Override public SqmEntityDomainType<J> getPathType() { return this; } @Override public @Nullable SqmPathSource<?> findSubPathSource(String name) { final PersistentAttribute<? super J,?> attribute = super.findAttribute( name ); if ( attribute != null ) { return (SqmPathSource<?>) attribute; } else if ( EntityIdentifierMapping.matchesRoleName( name ) ) { return hasSingleIdAttribute() ? findIdAttribute() : getIdentifierDescriptor(); } else if ( EntityVersionMapping.matchesRoleName( name ) ) { return hasVersionAttribute() ? findVersionAttribute() : null; } else if ( EntityDiscriminatorMapping.matchesRoleName( name ) ) { return discriminatorPathSource; } else { return null; } } @Override public @Nullable SqmPathSource<?> getIdentifierDescriptor() { return super.getIdentifierDescriptor(); } @Override public @Nullable SqmPathSource<?> findSubPathSource(String name, boolean includeSubtypes) { final PersistentAttribute<? super J,?> attribute = super.findAttribute( name ); if ( attribute != null ) { return (SqmPathSource<?>) attribute; } else { if ( includeSubtypes ) { final PersistentAttribute<?, ?> subtypeAttribute = findSubtypeAttribute( name ); if ( subtypeAttribute != null ) { return (SqmPathSource<?>) subtypeAttribute; } } if ( EntityIdentifierMapping.matchesRoleName( name ) ) { return hasSingleIdAttribute() ? findIdAttribute() : getIdentifierDescriptor(); } else if ( EntityDiscriminatorMapping.matchesRoleName( name ) ) { return discriminatorPathSource; } else { return null; } } } private SqmPersistentAttribute<?, ?> findSubtypeAttribute(String name) { SqmPersistentAttribute<?,?> subtypeAttribute = null; for ( SqmManagedDomainType<?> subtype : getSubTypes() ) { final SqmPersistentAttribute<?,?> candidate = subtype.findSubTypesAttribute( name ); if ( candidate != null ) { if ( subtypeAttribute != null && !isCompatible( subtypeAttribute, candidate, metamodel.getMappingMetamodel() ) ) { throw new PathException( String.format( Locale.ROOT, "Could not resolve attribute '%s' of '%s' due to the attribute being declared in multiple subtypes '%s' and '%s'", name, getTypeName(), subtypeAttribute.getDeclaringType().getTypeName(), candidate.getDeclaringType().getTypeName() ) ); } subtypeAttribute = candidate; } } return subtypeAttribute; } @Override public @Nullable SqmPersistentAttribute<? super J, ?> findAttribute(String name) { final var attribute = super.findAttribute( name ); if ( attribute != null ) { return attribute; } else if ( EntityIdentifierMapping.matchesRoleName( name ) ) { return findIdAttribute(); } else { return null; } } @Override public BindableType getBindableType() { return ENTITY_TYPE; } @Override public PersistenceType getPersistenceType() { return ENTITY; } @Override public Collection<? extends SqmEntityDomainType<? extends J>> getSubTypes() { //noinspection unchecked return (Collection<? extends SqmEntityDomainType<? extends J>>) super.getSubTypes(); } @Override public String toString() { return getName(); } @Override public SqmPath<J> createSqmPath(SqmPath<?> lhs, @Nullable SqmPathSource<?> intermediatePathSource) { throw new UnsupportedMappingException( "EntityType cannot be used to create an SqmPath - that would be an SqmFrom which are created directly" ); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Serialization @Serial protected Object writeReplace() throws ObjectStreamException { return new SerialForm( metamodel, getHibernateEntityName() ); } private static
EntityTypeImpl
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/RecipientListParallelFineGrainedErrorHandlingTest.java
{ "start": 5013, "end": 5280 }
class ____ { @org.apache.camel.RecipientList(stopOnException = true, parallelProcessing = true) public String sendSomewhere(Exchange exchange) { return "mock:foo,mock:bar,bean:fail,mock:baz"; } } public static
MyRecipientBean
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/isolation/PluginScanner.java
{ "start": 10923, "end": 11358 }
class ____ a dependency which is missing or invalid"; } else { return ""; } } protected LoaderSwap withClassLoader(ClassLoader loader) { ClassLoader savedLoader = Plugins.compareAndSwapLoaders(loader); try { return new LoaderSwap(savedLoader); } catch (Throwable t) { Plugins.compareAndSwapLoaders(savedLoader); throw t; } } }
has
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapelemformula/MapElementFormulaTest.java
{ "start": 631, "end": 1441 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { User gavin = new User( "gavin", "secret" ); User turin = new User( "turin", "tiger" ); Group g = new Group( "users" ); g.getUsers().put( "Gavin", gavin ); g.getUsers().put( "Turin", turin ); session.persist( g ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test @SuppressWarnings("unchecked") public void testManyToManyFormula(SessionFactoryScope scope) { scope.inTransaction( session -> { Group g = session.get( Group.class, "users" ); assertEquals( 2, g.getUsers().size() ); g.getUsers().remove( "Turin" ); } ); } }
MapElementFormulaTest
java
elastic__elasticsearch
x-pack/plugin/old-lucene-versions/src/main/java/org/elasticsearch/xpack/lucene/bwc/codecs/lucene87/BWCLucene87Codec.java
{ "start": 1635, "end": 3389 }
class ____ extends BWCCodec { private final LiveDocsFormat liveDocsFormat = new Lucene50LiveDocsFormat(); private final CompoundFormat compoundFormat = new Lucene50CompoundFormat(); private final PointsFormat pointsFormat = new Lucene86MetadataOnlyPointsFormat(); private final DocValuesFormat defaultDVFormat; private final DocValuesFormat docValuesFormat = new PerFieldDocValuesFormat() { @Override public DocValuesFormat getDocValuesFormatForField(String field) { return defaultDVFormat; } }; private final StoredFieldsFormat storedFieldsFormat; // Needed for SPI loading @SuppressWarnings("unused") public BWCLucene87Codec() { super("BWCLucene87Codec"); this.storedFieldsFormat = new Lucene87StoredFieldsFormat(Lucene87StoredFieldsFormat.Mode.BEST_COMPRESSION); this.defaultDVFormat = new Lucene80DocValuesFormat(Lucene80DocValuesFormat.Mode.BEST_COMPRESSION); } @Override protected FieldInfosFormat originalFieldInfosFormat() { return new Lucene60FieldInfosFormat(); } @Override protected SegmentInfoFormat originalSegmentInfoFormat() { return new Lucene86SegmentInfoFormat(); } @Override public StoredFieldsFormat storedFieldsFormat() { return storedFieldsFormat; } @Override public final LiveDocsFormat liveDocsFormat() { return liveDocsFormat; } @Override public CompoundFormat compoundFormat() { return compoundFormat; } @Override public PointsFormat pointsFormat() { return pointsFormat; } @Override public final DocValuesFormat docValuesFormat() { return docValuesFormat; } }
BWCLucene87Codec
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/RedundantThrowsTest.java
{ "start": 2795, "end": 3161 }
interface ____ { void f() throws FileNotFoundException, IOException, AccessDeniedException; } """) .addOutputLines( "out/Test.java", """ import java.io.IOException; import java.io.FileNotFoundException; import java.nio.file.AccessDeniedException;
Test
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/IpPrefixAutomatonUtil.java
{ "start": 1076, "end": 1192 }
class ____ utility functionality to build an Automaton based * on a prefix String on an `ip` field. */ public
contains
java
google__guava
guava/src/com/google/common/cache/Cache.java
{ "start": 1940, "end": 8074 }
interface ____<K, V> { /** * Returns the value associated with {@code key} in this cache, or {@code null} if there is no * cached value for {@code key}. * * @since 11.0 */ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this? @Nullable V getIfPresent(@CompatibleWith("K") Object key); /** * Returns the value associated with {@code key} in this cache, obtaining that value from {@code * loader} if necessary. The method improves upon the conventional "if cached, return; otherwise * create, cache and return" pattern. For further improvements, use {@link LoadingCache} and its * {@link LoadingCache#get(Object) get(K)} method instead of this one. * * <p>Among the improvements that this method and {@code LoadingCache.get(K)} both provide are: * * <ul> * <li>{@linkplain LoadingCache#get(Object) awaiting the result of a pending load} rather than * starting a redundant one * <li>eliminating the error-prone caching boilerplate * <li>tracking load {@linkplain #stats statistics} * </ul> * * <p>Among the further improvements that {@code LoadingCache} can provide but this method cannot: * * <ul> * <li>consolidation of the loader logic to {@linkplain CacheBuilder#build(CacheLoader) a single * authoritative location} * <li>{@linkplain LoadingCache#refresh refreshing of entries}, including {@linkplain * CacheBuilder#refreshAfterWrite automated refreshing} * <li>{@linkplain LoadingCache#getAll bulk loading requests}, including {@linkplain * CacheLoader#loadAll bulk loading implementations} * </ul> * * <p><b>Warning:</b> For any given key, every {@code loader} used with it should compute the same * value. Otherwise, a call that passes one {@code loader} may return the result of another call * with a differently behaving {@code loader}. For example, a call that requests a short timeout * for an RPC may wait for a similar call that requests a long timeout, or a call by an * unprivileged user may return a resource accessible only to a privileged user making a similar * call. To prevent this problem, create a key object that includes all values that affect the * result of the query. Or use {@code LoadingCache.get(K)}, which lacks the ability to refer to * state other than that in the key. * * <p><b>Warning:</b> as with {@link CacheLoader#load}, {@code loader} <b>must not</b> return * {@code null}; it may either return a non-null value or throw an exception. * * <p>No observable state associated with this cache is modified until loading completes. * * @throws ExecutionException if a checked exception was thrown while loading the value * @throws UncheckedExecutionException if an unchecked exception was thrown while loading the * value * @throws ExecutionError if an error was thrown while loading the value * @since 11.0 */ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this V get(K key, Callable<? extends V> loader) throws ExecutionException; /** * Returns a map of the values associated with {@code keys} in this cache. The returned map will * only contain entries which are already present in the cache. * * @since 11.0 */ /* * <? extends Object> is mostly the same as <?> to plain Java. But to nullness checkers, they * differ: <? extends Object> means "non-null types," while <?> means "all types." */ ImmutableMap<K, V> getAllPresent(Iterable<? extends Object> keys); /** * Associates {@code value} with {@code key} in this cache. If the cache previously contained a * value associated with {@code key}, the old value is replaced by {@code value}. * * <p>Prefer {@link #get(Object, Callable)} when using the conventional "if cached, return; * otherwise create, cache and return" pattern. * * @since 11.0 */ void put(K key, V value); /** * Copies all of the mappings from the specified map to the cache. The effect of this call is * equivalent to that of calling {@code put(k, v)} on this map once for each mapping from key * {@code k} to value {@code v} in the specified map. The behavior of this operation is undefined * if the specified map is modified while the operation is in progress. * * @since 12.0 */ void putAll(Map<? extends K, ? extends V> m); /** Discards any cached value for key {@code key}. */ void invalidate(@CompatibleWith("K") Object key); /** * Discards any cached values for keys {@code keys}. * * @since 11.0 */ // For discussion of <? extends Object>, see getAllPresent. void invalidateAll(Iterable<? extends Object> keys); /** Discards all entries in the cache. */ void invalidateAll(); /** Returns the approximate number of entries in this cache. */ long size(); /** * Returns a current snapshot of this cache's cumulative statistics, or a set of default values if * the cache is not recording statistics. All statistics begin at zero and never decrease over the * lifetime of the cache. * * <p><b>Warning:</b> this cache may not be recording statistical data. For example, a cache * created using {@link CacheBuilder} only does so if the {@link CacheBuilder#recordStats} method * was called. If statistics are not being recorded, a {@code CacheStats} instance with zero for * all values is returned. * */ CacheStats stats(); /** * Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to * the map directly affect the cache. * * <p>Iterators from the returned map are at least <i>weakly consistent</i>: they are safe for * concurrent use, but if the cache is modified (including by eviction) after the iterator is * created, it is undefined which of the changes (if any) will be reflected in that iterator. */ ConcurrentMap<K, V> asMap(); /** * Performs any pending maintenance operations needed by the cache. Exactly which activities are * performed -- if any -- is implementation-dependent. */ void cleanUp(); }
Cache
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/lucene/search/function/MinScoreScorer.java
{ "start": 825, "end": 3114 }
class ____ extends Scorer { private final Scorer in; private final float minScore; private float curScore; private final float boost; public MinScoreScorer(Scorer scorer, float minScore) { this(scorer, minScore, 1f); } public MinScoreScorer(Scorer scorer, float minScore, float boost) { this.in = scorer; this.minScore = minScore; this.boost = boost; } @Override public int docID() { return in.docID(); } @Override public float score() { return curScore * boost; } @Override public int advanceShallow(int target) throws IOException { return in.advanceShallow(target); } @Override public float getMaxScore(int upTo) throws IOException { return in.getMaxScore(upTo); } @Override public DocIdSetIterator iterator() { return TwoPhaseIterator.asDocIdSetIterator(twoPhaseIterator()); } @Override public TwoPhaseIterator twoPhaseIterator() { TwoPhaseIterator inTwoPhase = in.twoPhaseIterator(); DocIdSetIterator approximation; if (inTwoPhase == null) { approximation = in.iterator(); if (TwoPhaseIterator.unwrap(approximation) != null) { inTwoPhase = TwoPhaseIterator.unwrap(approximation); approximation = inTwoPhase.approximation(); } } else { approximation = inTwoPhase.approximation(); } final TwoPhaseIterator finalTwoPhase = inTwoPhase; return new TwoPhaseIterator(approximation) { @Override public boolean matches() throws IOException { // we need to check the two-phase iterator first // otherwise calling score() is illegal if (finalTwoPhase != null && finalTwoPhase.matches() == false) { return false; } curScore = in.score(); return curScore >= minScore; } @Override public float matchCost() { return 1000f // random constant for the score computation + (finalTwoPhase == null ? 0 : finalTwoPhase.matchCost()); } }; } }
MinScoreScorer
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaProducerFactory.java
{ "start": 1050, "end": 1469 }
interface ____ { /** * Creates a new Kafka Producer from the given configuration properties. * * @param config * <a href="https://kafka.apache.org/documentation.html#producerconfigs">Kafka Producer configuration * properties.</a> * @return a new Kafka {@link Producer}. */ Producer<byte[], byte[]> newKafkaProducer(Properties config); }
KafkaProducerFactory
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_2300/Issue2355.java
{ "start": 563, "end": 853 }
class ____ { @JSONField(serialzeFeatures = {SerializerFeature.WriteBigDecimalAsPlain}) private BigDecimal num; public BigDecimal getNum() { return num; } public void setNum(BigDecimal num) { this.num = num; } } }
VO
java
spring-projects__spring-boot
module/spring-boot-liquibase/src/test/java/org/springframework/boot/liquibase/autoconfigure/LiquibasePropertiesTests.java
{ "start": 1300, "end": 1942 }
class ____ { @Test void valuesOfShowSummaryMatchValuesOfUpdateSummaryEnum() { assertThat(namesOf(ShowSummary.values())).isEqualTo(namesOf(UpdateSummaryEnum.values())); } @Test void valuesOfShowSummaryOutputMatchValuesOfUpdateSummaryOutputEnum() { assertThat(namesOf(ShowSummaryOutput.values())).isEqualTo(namesOf(UpdateSummaryOutputEnum.values())); } @Test void valuesOfUiServiceMatchValuesOfUiServiceEnum() { assertThat(namesOf(UiService.values())).isEqualTo(namesOf(UIServiceEnum.values())); } private List<String> namesOf(Enum<?>[] input) { return Stream.of(input).map(Enum::name).toList(); } }
LiquibasePropertiesTests
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/custom/CustomGenericRepository.java
{ "start": 1202, "end": 1322 }
interface ____<T, ID extends Serializable> extends JpaRepository<T, ID> { T customMethod(ID id); }
CustomGenericRepository
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/data/DoubleArrayVector.java
{ "start": 995, "end": 5538 }
class ____ extends AbstractVector implements DoubleVector { static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(DoubleArrayVector.class) // TODO: remove these extra bytes once `asBlock` returns a block with a separate reference to the vector. + RamUsageEstimator.shallowSizeOfInstance(DoubleVectorBlock.class) // TODO: remove this if/when we account for memory used by Pages + Block.PAGE_MEM_OVERHEAD_PER_BLOCK; private final double[] values; DoubleArrayVector(double[] values, int positionCount, BlockFactory blockFactory) { super(positionCount, blockFactory); this.values = values; } static DoubleArrayVector readArrayVector(int positions, StreamInput in, BlockFactory blockFactory) throws IOException { final long preAdjustedBytes = RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + (long) positions * Double.BYTES; blockFactory.adjustBreaker(preAdjustedBytes); boolean success = false; try { double[] values = new double[positions]; for (int i = 0; i < positions; i++) { values[i] = in.readDouble(); } final var block = new DoubleArrayVector(values, positions, blockFactory); blockFactory.adjustBreaker(block.ramBytesUsed() - preAdjustedBytes); success = true; return block; } finally { if (success == false) { blockFactory.adjustBreaker(-preAdjustedBytes); } } } void writeArrayVector(int positions, StreamOutput out) throws IOException { for (int i = 0; i < positions; i++) { out.writeDouble(values[i]); } } @Override public DoubleBlock asBlock() { return new DoubleVectorBlock(this); } @Override public double getDouble(int position) { return values[position]; } @Override public ElementType elementType() { return ElementType.DOUBLE; } @Override public boolean isConstant() { return false; } @Override public DoubleVector filter(int... positions) { try (DoubleVector.Builder builder = blockFactory().newDoubleVectorBuilder(positions.length)) { for (int pos : positions) { builder.appendDouble(values[pos]); } return builder.build(); } } @Override public DoubleBlock keepMask(BooleanVector mask) { if (getPositionCount() == 0) { incRef(); return new DoubleVectorBlock(this); } if (mask.isConstant()) { if (mask.getBoolean(0)) { incRef(); return new DoubleVectorBlock(this); } return (DoubleBlock) blockFactory().newConstantNullBlock(getPositionCount()); } try (DoubleBlock.Builder builder = blockFactory().newDoubleBlockBuilder(getPositionCount())) { // TODO if X-ArrayBlock used BooleanVector for it's null mask then we could shuffle references here. for (int p = 0; p < getPositionCount(); p++) { if (mask.getBoolean(p)) { builder.appendDouble(getDouble(p)); } else { builder.appendNull(); } } return builder.build(); } } @Override public ReleasableIterator<DoubleBlock> lookup(IntBlock positions, ByteSizeValue targetBlockSize) { return new DoubleLookup(asBlock(), positions, targetBlockSize); } public static long ramBytesEstimated(double[] values) { return BASE_RAM_BYTES_USED + RamUsageEstimator.sizeOf(values); } @Override public long ramBytesUsed() { return ramBytesEstimated(values); } @Override public boolean equals(Object obj) { if (obj instanceof DoubleVector that) { return DoubleVector.equals(this, that); } return false; } @Override public int hashCode() { return DoubleVector.hash(this); } @Override public String toString() { String valuesString = IntStream.range(0, getPositionCount()) .limit(10) .mapToObj(n -> String.valueOf(values[n])) .collect(Collectors.joining(", ", "[", getPositionCount() > 10 ? ", ...]" : "]")); return getClass().getSimpleName() + "[positions=" + getPositionCount() + ", values=" + valuesString + ']'; } }
DoubleArrayVector
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/legacy/api/TableColumn.java
{ "start": 6518, "end": 7052 }
class ____ extends TableColumn { private PhysicalColumn(String name, DataType type) { super(name, type); } @Override public boolean isPhysical() { return true; } @Override public boolean isPersisted() { return true; } @Override public Optional<String> explainExtras() { return Optional.empty(); } } /** Representation of a computed column. */ @Internal public static
PhysicalColumn
java
apache__kafka
streams/src/test/java/org/apache/kafka/streams/TopologyTestDriverWrapper.java
{ "start": 1139, "end": 1376 }
class ____ access to {@link TopologyTestDriver} protected methods. * It should only be used for internal testing, in the rare occasions where the * necessary functionality is not supported by {@link TopologyTestDriver}. */ public
provides
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/token/delegation/web/TestWebDelegationToken.java
{ "start": 17912, "end": 18233 }
class ____ extends AuthenticationFilter { @Override protected Properties getConfiguration(String configPrefix, FilterConfig filterConfig) { Properties conf = new Properties(); conf.setProperty(AUTH_TYPE, PseudoAuthenticationHandler.TYPE); return conf; } } public static
NoDTFilter
java
grpc__grpc-java
census/src/main/java/io/grpc/census/CensusTracingModule.java
{ "start": 12733, "end": 15504 }
class ____ extends ServerStreamTracer { private final Span span; volatile boolean isSampledToLocalTracing; volatile int streamClosed; private int seqNo; ServerTracer(String fullMethodName, @Nullable SpanContext remoteSpan) { checkNotNull(fullMethodName, "fullMethodName"); this.span = censusTracer .spanBuilderWithRemoteParent( generateTraceSpanName(true, fullMethodName), remoteSpan) .setRecordEvents(true) .startSpan(); } @Override public void serverCallStarted(ServerCallInfo<?, ?> callInfo) { isSampledToLocalTracing = callInfo.getMethodDescriptor().isSampledToLocalTracing(); } /** * Record a finished stream and mark the current time as the end time. * * <p>Can be called from any thread without synchronization. Calling it the second time or more * is a no-op. */ @Override public void streamClosed(io.grpc.Status status) { if (streamClosedUpdater != null) { if (streamClosedUpdater.getAndSet(this, 1) != 0) { return; } } else { if (streamClosed != 0) { return; } streamClosed = 1; } span.end(createEndSpanOptions(status, isSampledToLocalTracing)); } /* TODO(dnvindhya): Replace deprecated ContextUtils usage with ContextHandleUtils to interact with io.grpc.Context as described in {@link io.opencensus.trace.unsafeContextUtils} to remove SuppressWarnings annotation. */ @SuppressWarnings("deprecation") @Override public Context filterContext(Context context) { // Access directly the unsafe trace API to create the new Context. This is a safe usage // because gRPC always creates a new Context for each of the server calls and does not // inherit from the parent Context. return io.opencensus.trace.unsafe.ContextUtils.withValue(context, span); } @Override public void outboundMessageSent( int seqNo, long optionalWireSize, long optionalUncompressedSize) { recordMessageEvent( span, MessageEvent.Type.SENT, seqNo, optionalWireSize, optionalUncompressedSize); } @Override public void inboundMessageRead( int seqNo, long optionalWireSize, long optionalUncompressedSize) { recordAnnotation( span, MessageEvent.Type.RECEIVED, seqNo, true, optionalWireSize); } @Override public void inboundMessage(int seqNo) { this.seqNo = seqNo; } @Override public void inboundUncompressedSize(long bytes) { recordAnnotation( span, MessageEvent.Type.RECEIVED, seqNo, false, bytes); } } @VisibleForTesting final
ServerTracer
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/parameters/converters/LocalDateTimeParamConverter.java
{ "start": 155, "end": 779 }
class ____ extends TemporalParamConverter<LocalDateTime> { // this can be called by generated code public LocalDateTimeParamConverter() { super(DateTimeFormatter.ISO_LOCAL_DATE_TIME); } public LocalDateTimeParamConverter(DateTimeFormatter formatter) { super(formatter); } @Override protected LocalDateTime convert(String value) { return LocalDateTime.parse(value); } @Override protected LocalDateTime convert(String value, DateTimeFormatter formatter) { return LocalDateTime.parse(value, formatter); } public static
LocalDateTimeParamConverter
java
apache__camel
components/camel-rocketmq/src/generated/java/org/apache/camel/component/rocketmq/RocketMQEndpointConfigurer.java
{ "start": 735, "end": 8870 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { RocketMQEndpoint target = (RocketMQEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesschannel": case "accessChannel": target.setAccessChannel(property(camelContext, java.lang.String.class, value)); return true; case "accesskey": case "accessKey": target.setAccessKey(property(camelContext, java.lang.String.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "consumergroup": case "consumerGroup": target.setConsumerGroup(property(camelContext, java.lang.String.class, value)); return true; case "enabletrace": case "enableTrace": target.setEnableTrace(property(camelContext, boolean.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "messageselectortype": case "messageSelectorType": target.setMessageSelectorType(property(camelContext, java.lang.String.class, value)); return true; case "namespace": target.setNamespace(property(camelContext, java.lang.String.class, value)); return true; case "namesrvaddr": case "namesrvAddr": target.setNamesrvAddr(property(camelContext, java.lang.String.class, value)); return true; case "producergroup": case "producerGroup": target.setProducerGroup(property(camelContext, java.lang.String.class, value)); return true; case "replytoconsumergroup": case "replyToConsumerGroup": target.setReplyToConsumerGroup(property(camelContext, java.lang.String.class, value)); return true; case "replytotopic": case "replyToTopic": target.setReplyToTopic(property(camelContext, java.lang.String.class, value)); return true; case "requesttimeoutcheckerintervalmillis": case "requestTimeoutCheckerIntervalMillis": target.setRequestTimeoutCheckerIntervalMillis(property(camelContext, long.class, value)); return true; case "requesttimeoutmillis": case "requestTimeoutMillis": target.setRequestTimeoutMillis(property(camelContext, long.class, value)); return true; case "secretkey": case "secretKey": target.setSecretKey(property(camelContext, java.lang.String.class, value)); return true; case "sendtag": case "sendTag": target.setSendTag(property(camelContext, java.lang.String.class, value)); return true; case "subscribesql": case "subscribeSql": target.setSubscribeSql(property(camelContext, java.lang.String.class, value)); return true; case "subscribetags": case "subscribeTags": target.setSubscribeTags(property(camelContext, java.lang.String.class, value)); return true; case "waitforsendresult": case "waitForSendResult": target.setWaitForSendResult(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "accesschannel": case "accessChannel": return java.lang.String.class; case "accesskey": case "accessKey": return java.lang.String.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "consumergroup": case "consumerGroup": return java.lang.String.class; case "enabletrace": case "enableTrace": return boolean.class; case "exceptionhandler": case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class; case "exchangepattern": case "exchangePattern": return org.apache.camel.ExchangePattern.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "messageselectortype": case "messageSelectorType": return java.lang.String.class; case "namespace": return java.lang.String.class; case "namesrvaddr": case "namesrvAddr": return java.lang.String.class; case "producergroup": case "producerGroup": return java.lang.String.class; case "replytoconsumergroup": case "replyToConsumerGroup": return java.lang.String.class; case "replytotopic": case "replyToTopic": return java.lang.String.class; case "requesttimeoutcheckerintervalmillis": case "requestTimeoutCheckerIntervalMillis": return long.class; case "requesttimeoutmillis": case "requestTimeoutMillis": return long.class; case "secretkey": case "secretKey": return java.lang.String.class; case "sendtag": case "sendTag": return java.lang.String.class; case "subscribesql": case "subscribeSql": return java.lang.String.class; case "subscribetags": case "subscribeTags": return java.lang.String.class; case "waitforsendresult": case "waitForSendResult": return boolean.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { RocketMQEndpoint target = (RocketMQEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesschannel": case "accessChannel": return target.getAccessChannel(); case "accesskey": case "accessKey": return target.getAccessKey(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "consumergroup": case "consumerGroup": return target.getConsumerGroup(); case "enabletrace": case "enableTrace": return target.isEnableTrace(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "messageselectortype": case "messageSelectorType": return target.getMessageSelectorType(); case "namespace": return target.getNamespace(); case "namesrvaddr": case "namesrvAddr": return target.getNamesrvAddr(); case "producergroup": case "producerGroup": return target.getProducerGroup(); case "replytoconsumergroup": case "replyToConsumerGroup": return target.getReplyToConsumerGroup(); case "replytotopic": case "replyToTopic": return target.getReplyToTopic(); case "requesttimeoutcheckerintervalmillis": case "requestTimeoutCheckerIntervalMillis": return target.getRequestTimeoutCheckerIntervalMillis(); case "requesttimeoutmillis": case "requestTimeoutMillis": return target.getRequestTimeoutMillis(); case "secretkey": case "secretKey": return target.getSecretKey(); case "sendtag": case "sendTag": return target.getSendTag(); case "subscribesql": case "subscribeSql": return target.getSubscribeSql(); case "subscribetags": case "subscribeTags": return target.getSubscribeTags(); case "waitforsendresult": case "waitForSendResult": return target.isWaitForSendResult(); default: return null; } } }
RocketMQEndpointConfigurer
java
spring-projects__spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/AbstractHttpSendingTransportHandler.java
{ "start": 1837, "end": 4815 }
class ____ extends AbstractTransportHandler implements SockJsSessionFactory { /** * Pattern for validating callback parameter values. */ private static final Pattern CALLBACK_PARAM_PATTERN = Pattern.compile("[0-9A-Za-z_.]*"); @Override public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, SockJsSession wsSession) throws SockJsException { AbstractHttpSockJsSession sockJsSession = (AbstractHttpSockJsSession) wsSession; // https://github.com/sockjs/sockjs-client/issues/130 // sockJsSession.setAcceptedProtocol(protocol); // Set content type before writing response.getHeaders().setContentType(getContentType()); handleRequestInternal(request, response, sockJsSession); } protected void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response, AbstractHttpSockJsSession sockJsSession) throws SockJsException { if (sockJsSession.isNew()) { if (logger.isDebugEnabled()) { logger.debug(request.getMethod() + " " + request.getURI()); } sockJsSession.handleInitialRequest(request, response, getFrameFormat(request)); } else if (sockJsSession.isClosed()) { if (logger.isDebugEnabled()) { logger.debug("Connection already closed (but not removed yet) for " + sockJsSession); } writeFrame(SockJsFrame.closeFrameGoAway(), request, response, sockJsSession); } else if (!sockJsSession.isActive()) { if (logger.isTraceEnabled()) { logger.trace("Starting " + getTransportType() + " async request."); } sockJsSession.handleSuccessiveRequest(request, response, getFrameFormat(request)); } else { if (logger.isDebugEnabled()) { logger.debug("Another " + getTransportType() + " connection still open for " + sockJsSession); } writeFrame(SockJsFrame.closeFrameAnotherConnectionOpen(), request, response, sockJsSession); } } private void writeFrame(SockJsFrame frame, ServerHttpRequest request, ServerHttpResponse response, AbstractHttpSockJsSession sockJsSession) { String formattedFrame = getFrameFormat(request).format(frame); try { response.getBody().write(formattedFrame.getBytes(SockJsFrame.CHARSET)); } catch (IOException ex) { throw new SockJsException("Failed to send " + formattedFrame, sockJsSession.getId(), ex); } } protected abstract MediaType getContentType(); protected abstract SockJsFrameFormat getFrameFormat(ServerHttpRequest request); protected final @Nullable String getCallbackParam(ServerHttpRequest request) { String query = request.getURI().getQuery(); MultiValueMap<String, String> params = UriComponentsBuilder.newInstance().query(query).build().getQueryParams(); String value = params.getFirst("c"); if (!StringUtils.hasLength(value)) { return null; } String result = UriUtils.decode(value, StandardCharsets.UTF_8); return (CALLBACK_PARAM_PATTERN.matcher(result).matches() ? result : null); } }
AbstractHttpSendingTransportHandler
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plan/logical/ExecutesOn.java
{ "start": 446, "end": 750 }
enum ____ { COORDINATOR, REMOTE, ANY; // Can be executed on either coordinator or remote nodes } ExecuteLocation executesOn(); /** * Executes on the remote nodes only (note that may include coordinator, but not on the aggregation stage). */
ExecuteLocation
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/injection/spec/InjectionSpec.java
{ "start": 526, "end": 631 }
interface ____ permits MethodHandleSpec, ExistingInstanceSpec { Class<?> requestedType(); }
InjectionSpec
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/type/AnnotatedTypeMetadata.java
{ "start": 2566, "end": 3174 }
class ____ of the annotation * type to look for * @return whether a matching annotation is defined */ default boolean isAnnotated(String annotationName) { return getAnnotations().isPresent(annotationName); } /** * Retrieve the attributes of the annotation of the given type, if any (i.e. if * defined on the underlying element, as direct annotation or meta-annotation). * <p>{@link org.springframework.core.annotation.AliasFor @AliasFor} semantics * are fully supported, both within a single annotation and within annotation * hierarchies. * @param annotationName the fully-qualified
name
java
spring-projects__spring-framework
spring-websocket/src/test/java/org/springframework/web/socket/sockjs/transport/handler/DefaultSockJsServiceTests.java
{ "start": 13847, "end": 13934 }
interface ____ extends TransportHandler, HandshakeHandler { } }
HandshakeTransportHandler
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/i18n/SimpleTimeZoneAwareLocaleContext.java
{ "start": 1195, "end": 2034 }
class ____ extends SimpleLocaleContext implements TimeZoneAwareLocaleContext { private final @Nullable TimeZone timeZone; /** * Create a new SimpleTimeZoneAwareLocaleContext that exposes the specified * Locale and TimeZone. Every {@link #getLocale()} call will return the given * Locale, and every {@link #getTimeZone()} call will return the given TimeZone. * @param locale the Locale to expose * @param timeZone the TimeZone to expose */ public SimpleTimeZoneAwareLocaleContext(@Nullable Locale locale, @Nullable TimeZone timeZone) { super(locale); this.timeZone = timeZone; } @Override public @Nullable TimeZone getTimeZone() { return this.timeZone; } @Override public String toString() { return super.toString() + " " + (this.timeZone != null ? this.timeZone : "-"); } }
SimpleTimeZoneAwareLocaleContext
java
apache__kafka
metadata/src/main/java/org/apache/kafka/image/node/FeaturesImageNode.java
{ "start": 950, "end": 2375 }
class ____ implements MetadataNode { /** * The name of this node. */ public static final String NAME = "features"; /** * The name of the metadata version child node. */ public static final String METADATA_VERSION = "metadataVersion"; /** * The prefix to put before finalized feature children. */ public static final String FINALIZED_PREFIX = "finalized_"; /** * The features image. */ private final FeaturesImage image; public FeaturesImageNode(FeaturesImage image) { this.image = image; } @Override public Collection<String> childNames() { ArrayList<String> childNames = new ArrayList<>(); childNames.add(METADATA_VERSION); for (String featureName : image.finalizedVersions().keySet()) { childNames.add(FINALIZED_PREFIX + featureName); } return childNames; } @Override public MetadataNode child(String name) { if (name.equals(METADATA_VERSION)) { return new MetadataLeafNode(image.metadataVersion().toString()); } else if (name.startsWith(FINALIZED_PREFIX)) { String key = name.substring(FINALIZED_PREFIX.length()); return new MetadataLeafNode( image.finalizedVersions().getOrDefault(key, (short) 0).toString()); } else { return null; } } }
FeaturesImageNode
java
google__dagger
javatests/dagger/internal/codegen/AssistedFactoryTest.java
{ "start": 10890, "end": 11296 }
interface ____ {", " MySubcomponentAssistedFactory mySubcomponentAssistedFactory();", "}"); Source assistedClass = CompilerTests.javaSource( "test.MyAssistedClass", "package test;", "", "import dagger.assisted.Assisted;", "import dagger.assisted.AssistedInject;", "", "final
MySubcomponent
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/doubles/Doubles_assertNotEqual_Test.java
{ "start": 1414, "end": 3273 }
class ____ extends DoublesBaseTest { @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> doubles.assertNotEqual(someInfo(), null, 8d)) .withMessage(actualIsNull()); } @Test void should_pass_if_doubles_are_not_equal() { doubles.assertNotEqual(someInfo(), 8d, 6d); } @Test void should_fail_if_doubles_are_equal() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> doubles.assertNotEqual(info, 6d, 6d)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldNotBeEqual(6d, 6d)); } @Test void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> doublesWithAbsValueComparisonStrategy.assertNotEqual(someInfo(), null, 8d)) .withMessage(actualIsNull()); } @Test void should_pass_if_doubles_are_not_equal_according_to_custom_comparison_strategy() { doublesWithAbsValueComparisonStrategy.assertNotEqual(someInfo(), 8d, 6d); } @Test void should_fail_if_doubles_are_equal_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> doublesWithAbsValueComparisonStrategy.assertNotEqual(info, 6d, -6d)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldNotBeEqual(6d, -6d, absValueComparisonStrategy)); } }
Doubles_assertNotEqual_Test
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/ldap/support/LdapMetadataResolverSettings.java
{ "start": 510, "end": 1507 }
class ____ { public static final Function<String, Setting.AffixSetting<List<String>>> ADDITIONAL_METADATA_SETTING = RealmSettings.affixSetting( "metadata", key -> Setting.stringListSetting(key, Setting.Property.NodeScope) ); public static final Function<String, Setting.AffixSetting<String>> FULL_NAME_SETTING = RealmSettings.affixSetting( "user_full_name_attribute", key -> Setting.simpleString(key, "cn", Setting.Property.NodeScope) ); public static final Function<String, Setting.AffixSetting<String>> EMAIL_SETTING = RealmSettings.affixSetting( "user_email_attribute", key -> Setting.simpleString(key, "mail", Setting.Property.NodeScope) ); private LdapMetadataResolverSettings() {} public static List<Setting.AffixSetting<?>> getSettings(String type) { return List.of(ADDITIONAL_METADATA_SETTING.apply(type), EMAIL_SETTING.apply(type), FULL_NAME_SETTING.apply(type)); } }
LdapMetadataResolverSettings
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/window/groupwindow/operator/WindowOperator.java
{ "start": 19878, "end": 22651 }
class ____ implements InternalWindowProcessFunction.Context<K, W> { @Override public <S extends State> S getPartitionedState(StateDescriptor<S, ?> stateDescriptor) throws Exception { requireNonNull(stateDescriptor, "The state properties must not be null"); return WindowOperator.this.getPartitionedState(stateDescriptor); } @Override public K currentKey() { return WindowOperator.this.currentKey(); } @Override public long currentProcessingTime() { return internalTimerService.currentProcessingTime(); } @Override public long currentWatermark() { return internalTimerService.currentWatermark(); } @Override public ZoneId getShiftTimeZone() { return shiftTimeZone; } @Override public RowData getWindowAccumulators(W window) throws Exception { windowState.setCurrentNamespace(window); return windowState.value(); } @Override public void setWindowAccumulators(W window, RowData acc) throws Exception { windowState.setCurrentNamespace(window); windowState.update(acc); } @Override public void clearWindowState(W window) throws Exception { windowState.setCurrentNamespace(window); windowState.clear(); windowAggregator.cleanup(window); } @Override public void clearPreviousState(W window) throws Exception { if (previousState != null) { previousState.setCurrentNamespace(window); previousState.clear(); } } @Override public void clearTrigger(W window) throws Exception { triggerContext.window = window; triggerContext.clear(); } @Override public void deleteCleanupTimer(W window) throws Exception { long cleanupTime = toEpochMillsForTimer(cleanupTime(window), shiftTimeZone); if (cleanupTime == Long.MAX_VALUE) { // no need to clean up because we didn't set one return; } if (windowAssigner.isEventTime()) { triggerContext.deleteEventTimeTimer(cleanupTime); } else { triggerContext.deleteProcessingTimeTimer(cleanupTime); } } @Override public void onMerge(W newWindow, Collection<W> mergedWindows) throws Exception { triggerContext.window = newWindow; triggerContext.mergedWindows = mergedWindows; triggerContext.onMerge(); } } private
WindowContext
java
quarkusio__quarkus
independent-projects/tools/devtools-testing/src/test/resources/__snapshots__/QuarkusCodestartGenerationTest/generateMavenResteasyJava/src_main_java_org_acme_GreetingResource.java
{ "start": 156, "end": 295 }
class ____ { @GET @Produces(MediaType.TEXT_PLAIN) public String hello() { return "Hello RESTEasy"; } }
GreetingResource
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java
{ "start": 18255, "end": 19830 }
class ____ not supported */ public static Class<?> loadClass(String className) throws ClassNotFoundException { ClassLoader cl = null; if (!className.startsWith("org.apache.dubbo")) { try { cl = Thread.currentThread().getContextClassLoader(); } catch (Throwable ignored) { } } if (cl == null) { cl = ClassUtils.class.getClassLoader(); } return cl.loadClass(className); } public static void runWith(ClassLoader classLoader, Runnable runnable) { Thread thread = Thread.currentThread(); ClassLoader tccl = thread.getContextClassLoader(); if (classLoader == null || classLoader.equals(tccl)) { runnable.run(); return; } thread.setContextClassLoader(classLoader); try { runnable.run(); } finally { thread.setContextClassLoader(tccl); } } /** * Resolve the {@link Class} by the specified name and {@link ClassLoader} * * @param className the name of {@link Class} * @param classLoader {@link ClassLoader} * @return If can't be resolved , return <code>null</code> * @since 2.7.6 */ public static Class<?> resolveClass(String className, ClassLoader classLoader) { Class<?> targetClass = null; try { targetClass = forName(className, classLoader); } catch (Exception ignored) { // Ignored } return targetClass; } /** * Is generic
is
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/WebAppConfigurationTestInterface.java
{ "start": 1101, "end": 1164 }
interface ____ { @Configuration
WebAppConfigurationTestInterface
java
elastic__elasticsearch
libs/geo/src/main/java/org/elasticsearch/geometry/utils/BitUtil.java
{ "start": 636, "end": 2513 }
class ____ { // magic numbers for bit interleaving private BitUtil() {} private static final long MAGIC[] = { 0x5555555555555555L, 0x3333333333333333L, 0x0F0F0F0F0F0F0F0FL, 0x00FF00FF00FF00FFL, 0x0000FFFF0000FFFFL, 0x00000000FFFFFFFFL, 0xAAAAAAAAAAAAAAAAL }; // shift values for bit interleaving private static final short SHIFT[] = { 1, 2, 4, 8, 16 }; /** * Interleaves the first 32 bits of each long value * * Adapted from: http://graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN */ public static long interleave(int even, int odd) { long v1 = 0x00000000FFFFFFFFL & even; long v2 = 0x00000000FFFFFFFFL & odd; v1 = (v1 | (v1 << SHIFT[4])) & MAGIC[4]; v1 = (v1 | (v1 << SHIFT[3])) & MAGIC[3]; v1 = (v1 | (v1 << SHIFT[2])) & MAGIC[2]; v1 = (v1 | (v1 << SHIFT[1])) & MAGIC[1]; v1 = (v1 | (v1 << SHIFT[0])) & MAGIC[0]; v2 = (v2 | (v2 << SHIFT[4])) & MAGIC[4]; v2 = (v2 | (v2 << SHIFT[3])) & MAGIC[3]; v2 = (v2 | (v2 << SHIFT[2])) & MAGIC[2]; v2 = (v2 | (v2 << SHIFT[1])) & MAGIC[1]; v2 = (v2 | (v2 << SHIFT[0])) & MAGIC[0]; return (v2 << 1) | v1; } /** * Extract just the even-bits value as a long from the bit-interleaved value */ public static long deinterleave(long b) { b &= MAGIC[0]; b = (b ^ (b >>> SHIFT[0])) & MAGIC[1]; b = (b ^ (b >>> SHIFT[1])) & MAGIC[2]; b = (b ^ (b >>> SHIFT[2])) & MAGIC[3]; b = (b ^ (b >>> SHIFT[3])) & MAGIC[4]; b = (b ^ (b >>> SHIFT[4])) & MAGIC[5]; return b; } /** * flip flops odd with even bits */ public static final long flipFlop(final long b) { return ((b & MAGIC[6]) >>> 1) | ((b & MAGIC[0]) << 1); } }
BitUtil
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/close/BImpl.java
{ "start": 870, "end": 1075 }
class ____ implements AutoCloseable, B { public BImpl(C c) {} @PreDestroy @Override public void close() throws IOException { BeanCloseOrderSpec.getClosed().add(B.class); } }
BImpl
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/bytearray/ByteArrayAssert_contains_at_Index_Test.java
{ "start": 1001, "end": 1394 }
class ____ extends ByteArrayAssertBaseTest { private Index index = someIndex(); @Override protected ByteArrayAssert invoke_api_method() { return assertions.contains((byte) 8, index); } @Override protected void verify_internal_effects() { verify(arrays).assertContains(getInfo(assertions), getActual(assertions), (byte) 8, index); } }
ByteArrayAssert_contains_at_Index_Test
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/QueryableBuiltInRolesUtils.java
{ "start": 1306, "end": 4465 }
class ____ { /** * Calculates the hash of the given role descriptor by serializing it by calling {@link RoleDescriptor#writeTo(StreamOutput)} method * and then SHA256 hashing the bytes. * * @param roleDescriptor the role descriptor to hash * @return the base64 encoded SHA256 hash of the role descriptor */ public static String calculateHash(final RoleDescriptor roleDescriptor) { final MessageDigest hash = MessageDigests.sha256(); try (XContentBuilder jsonBuilder = XContentFactory.jsonBuilder()) { roleDescriptor.toXContent(jsonBuilder, EMPTY_PARAMS); final Map<String, Object> flattenMap = Maps.flatten( XContentHelper.convertToMap(BytesReference.bytes(jsonBuilder), true, XContentType.JSON).v2(), false, true ); hash.update(flattenMap.toString().getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new IllegalStateException("failed to compute digest for [" + roleDescriptor.getName() + "] role", e); } // HEX vs Base64 encoding is a trade-off between readability and space efficiency // opting for Base64 here to reduce the size of the cluster state return Base64.getEncoder().encodeToString(hash.digest()); } /** * Determines the roles to delete by comparing the indexed roles with the roles in the built-in roles. * @return the set of roles to delete */ public static Set<String> determineRolesToDelete(final QueryableBuiltInRoles roles, final Map<String, String> indexedRolesDigests) { assert roles != null; if (indexedRolesDigests == null) { // nothing indexed, nothing to delete return Set.of(); } final Set<String> rolesToDelete = Sets.difference(indexedRolesDigests.keySet(), roles.rolesDigest().keySet()); return Collections.unmodifiableSet(rolesToDelete); } /** * Determines the roles to upsert by comparing the indexed roles and their digests with the current built-in roles. * @return the set of roles to upsert (create or update) */ public static Set<RoleDescriptor> determineRolesToUpsert( final QueryableBuiltInRoles roles, final Map<String, String> indexedRolesDigests ) { assert roles != null; final Set<RoleDescriptor> rolesToUpsert = new HashSet<>(); for (RoleDescriptor role : roles.roleDescriptors()) { final String roleDigest = roles.rolesDigest().get(role.getName()); if (indexedRolesDigests == null || indexedRolesDigests.containsKey(role.getName()) == false) { rolesToUpsert.add(role); // a new role to create } else if (indexedRolesDigests.get(role.getName()).equals(roleDigest) == false) { rolesToUpsert.add(role); // an existing role that needs to be updated } } return Collections.unmodifiableSet(rolesToUpsert); } private QueryableBuiltInRolesUtils() { throw new IllegalAccessError("not allowed"); } }
QueryableBuiltInRolesUtils
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/actuate/GatewayEndpointInfo.java
{ "start": 789, "end": 1676 }
class ____ { private String href; private List<String> methods; public String getHref() { return href; } public void setHref(String href) { this.href = href; } public String[] getMethods() { return methods.stream().toArray(String[]::new); } GatewayEndpointInfo(String href, String method) { this.href = href; this.methods = Collections.singletonList(method); } GatewayEndpointInfo(String href, List<String> methods) { this.href = href; this.methods = methods; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GatewayEndpointInfo that = (GatewayEndpointInfo) o; return Objects.equals(href, that.href) && Objects.equals(methods, that.methods); } @Override public int hashCode() { return Objects.hash(href, methods); } }
GatewayEndpointInfo
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/InferenceHelpers.java
{ "start": 939, "end": 6548 }
class ____ { private InferenceHelpers() {} /** * @return Tuple of the highest scored index and the top classes */ public static Tuple<TopClassificationValue, List<TopClassEntry>> topClasses( double[] probabilities, List<String> classificationLabels, @Nullable double[] classificationWeights, int numToInclude, PredictionFieldType predictionFieldType ) { if (classificationLabels != null && probabilities.length != classificationLabels.size()) { throw ExceptionsHelper.serverError( "model returned classification probabilities of size [{}] which is not equal to classification labels size [{}]", null, probabilities.length, classificationLabels.size() ); } double[] scores = classificationWeights == null ? probabilities : IntStream.range(0, probabilities.length).mapToDouble(i -> probabilities[i] * classificationWeights[i]).toArray(); int[] sortedIndices = IntStream.range(0, scores.length) .boxed() .sorted(Comparator.comparing(i -> scores[(Integer) i]).reversed()) .mapToInt(i -> i) .toArray(); final TopClassificationValue topClassificationValue = new TopClassificationValue( sortedIndices[0], probabilities[sortedIndices[0]], scores[sortedIndices[0]] ); if (numToInclude == 0) { return Tuple.tuple(topClassificationValue, Collections.emptyList()); } List<String> labels = classificationLabels == null ? // If we don't have the labels we should return the top classification values anyways, they will just be numeric IntStream.range(0, probabilities.length).mapToObj(String::valueOf).toList() : classificationLabels; int count = numToInclude < 0 ? probabilities.length : Math.min(numToInclude, probabilities.length); List<TopClassEntry> topClassEntries = new ArrayList<>(count); for (int i = 0; i < count; i++) { int idx = sortedIndices[i]; topClassEntries.add( new TopClassEntry( predictionFieldType.transformPredictedValue((double) idx, labels.get(idx)), probabilities[idx], scores[idx] ) ); } return Tuple.tuple(topClassificationValue, topClassEntries); } public static String classificationLabel(Integer inferenceValue, @Nullable List<String> classificationLabels) { if (classificationLabels == null) { return String.valueOf(inferenceValue); } if (inferenceValue < 0 || inferenceValue >= classificationLabels.size()) { throw ExceptionsHelper.serverError( "model returned classification value of [{}] which is not a valid index in classification labels [{}]", null, inferenceValue, classificationLabels ); } return classificationLabels.get(inferenceValue); } public static Double toDouble(Object value) { if (value instanceof Number number) { return number.doubleValue(); } if (value instanceof String str) { return stringToDouble(str); } return null; } private static Double stringToDouble(String value) { if (value.isEmpty()) { return null; } try { return Double.valueOf(value); } catch (NumberFormatException nfe) { assert false : "value is not properly formatted double [" + value + "]"; return null; } } public static Map<String, double[]> decodeFeatureImportances( Map<String, String> processedFeatureToOriginalFeatureMap, Map<String, double[]> featureImportances ) { if (processedFeatureToOriginalFeatureMap == null || processedFeatureToOriginalFeatureMap.isEmpty()) { return featureImportances; } Map<String, double[]> originalFeatureImportance = new HashMap<>(); featureImportances.forEach((feature, importance) -> { String featureName = processedFeatureToOriginalFeatureMap.getOrDefault(feature, feature); originalFeatureImportance.compute(featureName, (f, v1) -> v1 == null ? importance : sumDoubleArrays(importance, v1)); }); return originalFeatureImportance; } public static List<RegressionFeatureImportance> transformFeatureImportanceRegression(Map<String, double[]> featureImportance) { List<RegressionFeatureImportance> importances = new ArrayList<>(featureImportance.size()); featureImportance.forEach((k, v) -> importances.add(new RegressionFeatureImportance(k, v[0]))); return importances; } public static List<ClassificationFeatureImportance> transformFeatureImportanceClassification( Map<String, double[]> featureImportance, @Nullable List<String> classificationLabels, @Nullable PredictionFieldType predictionFieldType ) { List<ClassificationFeatureImportance> importances = new ArrayList<>(featureImportance.size()); final PredictionFieldType fieldType = predictionFieldType == null ? PredictionFieldType.STRING : predictionFieldType; featureImportance.forEach((k, v) -> { // This indicates logistic regression (binary classification) // If the length > 1, we assume multi-
InferenceHelpers
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/rest/action/admin/indices/RestDeleteComposableIndexTemplateAction.java
{ "start": 1190, "end": 2118 }
class ____ extends BaseRestHandler { @Override public List<Route> routes() { return List.of(new Route(DELETE, "/_index_template/{name}")); } @Override public String getName() { return "delete_composable_index_template_action"; } @Override public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException { String[] names = Strings.splitStringByCommaToArray(request.param("name")); TransportDeleteComposableIndexTemplateAction.Request deleteReq = new TransportDeleteComposableIndexTemplateAction.Request(names); deleteReq.masterNodeTimeout(getMasterNodeTimeout(request)); return channel -> client.execute( TransportDeleteComposableIndexTemplateAction.TYPE, deleteReq, new RestToXContentListener<>(channel) ); } }
RestDeleteComposableIndexTemplateAction
java
netty__netty
codec-http3/src/main/java/io/netty/handler/codec/http3/HttpConversionUtil.java
{ "start": 27266, "end": 31132 }
class ____ { /** * Translations from HTTP/3 header name to the HTTP/1.x equivalent. */ private static final CharSequenceMap<AsciiString> REQUEST_HEADER_TRANSLATIONS = new CharSequenceMap<AsciiString>(); private static final CharSequenceMap<AsciiString> RESPONSE_HEADER_TRANSLATIONS = new CharSequenceMap<AsciiString>(); static { RESPONSE_HEADER_TRANSLATIONS.add(Http3Headers.PseudoHeaderName.AUTHORITY.value(), HttpHeaderNames.HOST); RESPONSE_HEADER_TRANSLATIONS.add(Http3Headers.PseudoHeaderName.SCHEME.value(), ExtensionHeaderNames.SCHEME.text()); REQUEST_HEADER_TRANSLATIONS.add(RESPONSE_HEADER_TRANSLATIONS); RESPONSE_HEADER_TRANSLATIONS.add(Http3Headers.PseudoHeaderName.PATH.value(), ExtensionHeaderNames.PATH.text()); } private final long streamId; private final HttpHeaders output; private final CharSequenceMap<AsciiString> translations; /** * Create a new instance * * @param output The HTTP/1.x headers object to store the results of the translation * @param request if {@code true}, translates headers using the request translation map. Otherwise uses the * response translation map. */ Http3ToHttpHeaderTranslator(long streamId, HttpHeaders output, boolean request) { this.streamId = streamId; this.output = output; translations = request ? REQUEST_HEADER_TRANSLATIONS : RESPONSE_HEADER_TRANSLATIONS; } void translateHeaders(Iterable<Entry<CharSequence, CharSequence>> inputHeaders) throws Http3Exception { // lazily created as needed StringBuilder cookies = null; for (Entry<CharSequence, CharSequence> entry : inputHeaders) { final CharSequence name = entry.getKey(); final CharSequence value = entry.getValue(); AsciiString translatedName = translations.get(name); if (translatedName != null) { output.add(translatedName, AsciiString.of(value)); } else if (!Http3Headers.PseudoHeaderName.isPseudoHeader(name)) { // https://tools.ietf.org/html/rfc7540#section-8.1.2.3 // All headers that start with ':' are only valid in HTTP/3 context if (name.length() == 0 || name.charAt(0) == ':') { throw streamError(streamId, Http3ErrorCode.H3_MESSAGE_ERROR, "Invalid HTTP/3 header '" + name + "' encountered in translation to HTTP/1.x", null); } if (COOKIE.equals(name)) { // combine the cookie values into 1 header entry. // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 if (cookies == null) { cookies = InternalThreadLocalMap.get().stringBuilder(); } else if (cookies.length() > 0) { cookies.append("; "); } cookies.append(value); } else { output.add(name, value); } } } if (cookies != null) { output.add(COOKIE, cookies.toString()); } } } private static Http3Exception streamError(long streamId, Http3ErrorCode error, String msg, @Nullable Throwable cause) { return new Http3Exception(error, streamId + ": " + msg, cause); } }
Http3ToHttpHeaderTranslator
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/llama/embeddings/LlamaEmbeddingsModel.java
{ "start": 1025, "end": 1137 }
class ____ the LlamaModel and provides specific configurations and settings for embeddings tasks. */ public
extends
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionPropertiesCodeGeneratorTests.java
{ "start": 25109, "end": 25451 }
class ____ { private Class<?> test; private String spring; public Class<?> getTest() { return this.test; } public void setTest(Class<?> test) { this.test = test; } public String getSpring() { return this.spring; } public void setSpring(String spring) { this.spring = spring; } } static
PropertyValuesBean
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/VersionedRecordIterator.java
{ "start": 1257, "end": 1379 }
interface ____<V> extends Iterator<VersionedRecord<V>>, Closeable { @Override void close(); }
VersionedRecordIterator
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/logger/Log4J2DelegatingLogger.java
{ "start": 787, "end": 4409 }
class ____ extends Logger { private final AbstractLogger logger; private final MessageFormatMessageFactory messageFactory; // Synchronize access on the field private final List<LogListener> enabledListeners = new LinkedList<>(); private final AtomicBoolean interceptEnabled = new AtomicBoolean( false ); Log4J2DelegatingLogger(final String name) { super( name ); org.apache.logging.log4j.Logger logger = LogManager.getLogger( name ); if ( !( logger instanceof AbstractLogger ) ) { throw new LoggingException( "The logger for [" + name + "] does not extend AbstractLogger. Actual logger: " + logger .getClass() .getName() ); } this.logger = (AbstractLogger) logger; this.messageFactory = new MessageFormatMessageFactory(); } void registerListener(LogListener newListener) { synchronized (enabledListeners) { if ( newListener != null ) { enabledListeners.add( newListener ); interceptEnabled.set( true ); } } } void clearAllListeners() { synchronized (enabledListeners) { enabledListeners.clear(); interceptEnabled.set( false ); } } @Override public boolean isEnabled(final Level level) { return this.logger.isEnabled( translate( level ) ); } @Override protected void doLog( final Level level, final String loggerClassName, final Object message, final Object[] parameters, final Throwable thrown) { final org.apache.logging.log4j.Level translatedLevel = translate( level ); if ( interceptEnabled.get() ) { intercept( level, parameters == null || parameters.length == 0 ? String.valueOf( message ) : MessageFormat.format( String.valueOf( message ), parameters ), thrown ); } if ( !this.logger.isEnabled( translatedLevel ) ) { return; } try { this.logger.logMessage( loggerClassName, translatedLevel, null, ( parameters == null || parameters.length == 0 ) ? this.messageFactory.newMessage( message ) : this.messageFactory.newMessage( String.valueOf( message ), parameters ), thrown ); } catch (Throwable ignored) { } } private void intercept(Level level, String renderedMessage, Throwable thrown) { synchronized (enabledListeners) { for ( LogListener listener : enabledListeners ) { listener.loggedEvent( level, renderedMessage, thrown ); } } } @Override protected void doLogf( final Level level, final String loggerClassName, final String format, final Object[] parameters, final Throwable thrown) { final org.apache.logging.log4j.Level translatedLevel = translate( level ); if ( interceptEnabled.get() ) { intercept( level, parameters == null ? format : String.format( format, parameters ), thrown ); } if ( !logger.isEnabled( translatedLevel ) ) { return; } try { this.logger.logMessage( loggerClassName, translatedLevel, null, new StringFormattedMessage( format, parameters ), thrown ); } catch (Throwable ignored) { } } private static org.apache.logging.log4j.Level translate(final Level level) { if ( level == null ) { return org.apache.logging.log4j.Level.ALL; } switch ( level ) { case FATAL: return org.apache.logging.log4j.Level.FATAL; case ERROR: return org.apache.logging.log4j.Level.ERROR; case WARN: return org.apache.logging.log4j.Level.WARN; case INFO: return org.apache.logging.log4j.Level.INFO; case DEBUG: return org.apache.logging.log4j.Level.DEBUG; case TRACE: return org.apache.logging.log4j.Level.TRACE; } return org.apache.logging.log4j.Level.ALL; } }
Log4J2DelegatingLogger
java
elastic__elasticsearch
x-pack/plugin/esql-core/src/main/java/org/elasticsearch/xpack/esql/core/util/SpatialCoordinateTypes.java
{ "start": 928, "end": 4894 }
enum ____ { GEO { public Point longAsPoint(long encoded) { return new Point(GeoEncodingUtils.decodeLongitude((int) encoded), GeoEncodingUtils.decodeLatitude((int) (encoded >>> 32))); } public long pointAsLong(double x, double y) { int latitudeEncoded = encodeLatitude(y); int longitudeEncoded = encodeLongitude(x); return (((long) latitudeEncoded) << 32) | (longitudeEncoded & 0xFFFFFFFFL); } public GeometryValidator validator() { // We validate the lat/lon values, and ignore any z values return GeographyValidator.instance(true); } }, CARTESIAN { private static final int MAX_VAL_ENCODED = XYEncodingUtils.encode((float) XYEncodingUtils.MAX_VAL_INCL); private static final int MIN_VAL_ENCODED = XYEncodingUtils.encode((float) XYEncodingUtils.MIN_VAL_INCL); public Point longAsPoint(long encoded) { final int x = checkCoordinate((int) (encoded >>> 32)); final int y = checkCoordinate((int) (encoded & 0xFFFFFFFF)); return new Point(XYEncodingUtils.decode(x), XYEncodingUtils.decode(y)); } private int checkCoordinate(int i) { if (i > MAX_VAL_ENCODED || i < MIN_VAL_ENCODED) { throw new IllegalArgumentException("Failed to convert invalid encoded value to cartesian point"); } return i; } public long pointAsLong(double x, double y) { final long xi = XYEncodingUtils.encode((float) x); final long yi = XYEncodingUtils.encode((float) y); return (yi & 0xFFFFFFFFL) | xi << 32; } }, UNSPECIFIED { public Point longAsPoint(long encoded) { throw new UnsupportedOperationException("Cannot convert long to point without specifying coordinate type"); } public long pointAsLong(double x, double y) { throw new UnsupportedOperationException("Cannot convert point to long without specifying coordinate type"); } }; protected GeometryValidator validator() { return GeometryValidator.NOOP; } public abstract Point longAsPoint(long encoded); public abstract long pointAsLong(double x, double y); public long wkbAsLong(BytesRef wkb) { Point point = wkbAsPoint(wkb); return pointAsLong(point.getX(), point.getY()); } public Point wkbAsPoint(BytesRef wkb) { Geometry geometry = WellKnownBinary.fromWKB(validator(), false, wkb.bytes, wkb.offset, wkb.length); if (geometry instanceof Point point) { return point; } else { throw new IllegalArgumentException("Unsupported geometry: " + geometry.type()); } } public BytesRef longAsWkb(long encoded) { return asWkb(longAsPoint(encoded)); } public String asWkt(Geometry geometry) { return WellKnownText.toWKT(geometry); } public BytesRef asWkb(Geometry geometry) { return new BytesRef(WellKnownBinary.toWKB(geometry, ByteOrder.LITTLE_ENDIAN)); } public BytesRef wktToWkb(String wkt) { // TODO: we should be able to transform WKT to WKB without building the geometry // we should as well use different validator for cartesian and geo? try { Geometry geometry = WellKnownText.fromWKT(validator(), false, wkt); return new BytesRef(WellKnownBinary.toWKB(geometry, ByteOrder.LITTLE_ENDIAN)); } catch (Exception e) { throw new IllegalArgumentException("Failed to parse WKT: " + e.getMessage(), e); } } public String wkbToWkt(BytesRef wkb) { return WellKnownText.fromWKB(wkb.bytes, wkb.offset, wkb.length); } public Geometry wkbToGeometry(BytesRef wkb) { return WellKnownBinary.fromWKB(validator(), false, wkb.bytes, wkb.offset, wkb.length); } }
SpatialCoordinateTypes
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/GenericManyToOneParameterTest.java
{ "start": 3781, "end": 4133 }
class ____<T extends Site> implements SitedBar<T> { @ManyToOne( fetch = FetchType.LAZY, targetEntity = SiteImpl.class ) @JoinColumn( name = "BAR_ID" ) private T site; @Override public T getSite() { return (T) site; } public void setSite(final T site) { this.site = site; } } @Entity( name = "BarImpl" ) public static
BarBarImpl
java
apache__hadoop
hadoop-tools/hadoop-gcp/src/test/java/org/apache/hadoop/fs/gs/contract/ITestGoogleContractSeek.java
{ "start": 1023, "end": 1211 }
class ____ extends AbstractContractSeekTest { @Override protected AbstractFSContract createContract(Configuration conf) { return new GoogleContract(conf); } }
ITestGoogleContractSeek