id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
213770342_10 | class CommonUtil {
public static Integer determinePriceCatForCPD(double price)
{
if (price >= 0 && price <= 3)
{
return 1;
}
if (price > 3 && price <= 5)
{
return 2;
}
if (price > 5)
{
return 3;
}
... | double d = 10.456;
assertEquals(3, (int) CommonUtil.determinePriceCatForCPD(d));
d = 005D;
assertEquals(2, (int) CommonUtil.determinePriceCatForCPD(d));
d = 0.69999999999999;
assertEquals(1, (int) CommonUtil.determinePriceCatForCPD(d));
d = 7.123456789;
as... |
213777474_6 | class PointerItem extends BaseItem {
public Set<ContextItem> contextItems() {
HashSet<ContextItem> contextItems = new HashSet<>(context.size());
for (Map.Entry<String, AttributeValue> entry : context.entrySet()) {
contextItems.add(ContextItem.fromContext(entry.getKey(), partitionKey));
}
return... | Map<String, String> context = sampleContext();
PointerItem item = PointerItem.generate(context);
Set<ContextItem> expectedContextItems = new HashSet<>(context.size());
for (Map.Entry<String, String> entry : context.entrySet()) {
ContextItem i = ContextItem.fromContext(entry.getKey(), item.partitio... |
213825606_2 | class ZuulFiltersModule extends AbstractModule {
@VisibleForTesting
String[] findClassNames(AbstractConfiguration config) {
// Find individually-specified filter classes.
String[] filterClassNamesStrArray = config.getStringArray("zuul.filters.classes");
Stream<String> classNameStream =... | when(configuration.getStringArray(eq("zuul.filters.classes"))).thenReturn(new String[]{});
when(configuration.getStringArray(eq("zuul.filters.packages"))).thenReturn(new String[]{});
String[] classNames = module.findClassNames(configuration);
assertThat(classNames.length, equalTo(0));
... |
213981789_184 | class ActorProxyImpl implements ActorProxy, InvocationHandler {
@Override
public <T> Mono<T> invokeActorMethod(String methodName, Object data, TypeRef<T> type) {
return this.daprClient.invokeActorMethod(actorType, actorId.toString(), methodName, this.serialize(data))
.filter(s -> s.length > 0)
... | final DaprClient daprClient = mock(DaprClient.class);
when(daprClient.invokeActorMethod(anyString(), anyString(), anyString(), Mockito.isNotNull()))
.thenReturn(
Mono.just("{\n\t\t\"propertyA\": \"valueA\",\n\t\t\"propertyB\": \"valueB\"\n\t}".getBytes()));
final ActorProxy actorProxy = n... |
214200976_3 | class RendezvousNodeRouter implements NodeRouter<N> {
@Override
public Optional<N> getNode(String nodeId) {
return strategy.getNode(nodeId, ring, hashFunction);
}
private RendezvousNodeRouter(
Collection<N> initialNodes, HashFunction hashFunction, RendezvousStrategy<N> strategy);
public static N... | NodeRouter<WeightedNode> router = createRendezvousRouter();
assertFalse(router.getNode("key").isPresent());
}
} |
214396571_4 | class StatusUtil {
public static String[] getRowData(DeploymentStatus deploymentStatus) {
if (deploymentStatus == null) {
return null;
}
String age = getAge(deploymentStatus.getAge());
String statusMsg = deploymentStatus.getServiceStatus() != null ? deploymentStatus.getS... | deploymentStatus.setAge(null);
assertNotNull(StatusUtil.getRowData(deploymentStatus));
}
} |
214418380_15 | class CgmesDLModel {
public PropertyBags getTerminals() {
LOG.info("Querying triple store for terminals");
return queryTripleStore(TERMINALS_QUERY_KEY);
}
public CgmesDLModel(TripleStore tripleStore);
public CgmesDLModel(TripleStore tripleStore, QueryCatalog queryCatalog);
priva... | assertEquals(terminals, cgmesDLModel.getTerminals());
removeQueryCatalogKey(CgmesDLModel.TERMINALS_QUERY_KEY);
assertEquals(new PropertyBags(), cgmesDLModel.getTerminals());
}
} |
215203638_16 | class NotificationFactory {
PushNotification handleMessage(@NonNull RemoteMessage message)
throws InvalidNotificationException {
return this.handleMessage(message.getData().get(MESSAGE_ID), message.getData().get(MESSAGE));
}
NotificationFactory(StorageClient storageClient);
Pus... | Map<String, String> baseMessage = generateBaseMessage();
baseMessage.remove(PushParser.CHALLENGE);
RemoteMessage remoteMessage = generateMockRemoteMessage(MESSAGE_ID, CORRECT_SECRET, baseMessage);
try {
notificationFactory.handleMessage(remoteMessage);
Assert.fai... |
215394390_112 | class BlockUtils {
public static boolean isNullRow(Block block, int row)
{
if (row > block.getRowCount() - 1) {
throw new RuntimeException("block has " + block.getRowCount()
+ " rows but requested to check " + row);
}
//If any column is non-null then ret... | Schema schema = SchemaBuilder.newBuilder()
.addField("col1", new ArrowType.Int(32, true))
.addField("col2", new ArrowType.Int(32, true))
.addField("col3", new ArrowType.Timestamp(org.apache.arrow.vector.types.TimeUnit.MILLISECOND, "UTC"))
.build();... |
215496017_7 | class KonduitPythonUtils {
public static void insertBytesIntoPythonVariables(Data ret, PythonVariables outputs, String variable, PythonConfig pythonConfig) throws IOException {
PythonIO pythonIO = pythonConfig.getIoOutputs().get(variable);
Preconditions.checkState(pythonConfig.getIoOutputs().contai... | PythonIO lenOutput = PythonIO.builder()
.name("len_input")
.type(ValueType.INT64)
.pythonType("int")
.build();
PythonIO pythonInput = PythonIO.builder()
.type(ValueType.BYTES)
.pythonType("bytes")
... |
215605392_4 | class CreateHandler extends BaseHandler<CallbackContext> {
@Override
public ProgressEvent<ResourceModel, CallbackContext> handleRequest(
final AmazonWebServicesClientProxy proxy,
final ResourceHandlerRequest<ResourceModel> request,
final CallbackContext callbackContext,
... | CreateHandler createHandler = new CreateHandler(alertApiClient);
// do some before assertions
assertThat(model.getNrqlCondition().getId()).isNull();
assertThat(model.getNrqlCondition().getName()).isEqualTo("TestNRQLCondition");
// oh no, bad request! Throw an exception.
... |
215680638_2 | class CynosureController extends Controller {
@Action(method = HttpMethod.GET)
public ActionResult refresh_provider(HttpContext context) {
String path = context.Request.getParams().get("path");
logger.info("path:" + path);
JsonResult jsonResult = cynosureService.queryProviderOrConsumerL... | ConfigManager.getInstance().put(ConfigManager.KEY_ZKSTR,server.getConnectString());
ZkHelper zkHelper = ZkInstanceUtil.getInstance();
zkHelper.addPersistent("/root/data/a/data","{\"a\":1}");
zkHelper.addPersistent("/root/data/b/data","{\"a\":2}");
zkHelper.addPersistent("/root/d... |
215805400_0 | class IDGenerator {
public static String newCeptaID() {
return String.format("CPTA-%s", UUID.randomUUID().toString());
}
}
class IDGeneratorTest {
@Test
public void testGeneratesUniqueIds() {
| List<String> ids = Arrays.asList(new String[1000]).parallelStream().map(i -> IDGenerator.newCeptaID())
.collect(Collectors.toList());
Assert.assertFalse(hasDuplicates(ids));
}
} |
215881965_0 | class StanfordCoreNLPService {
public Map<String, List<String>> extractEntities(final String text, final String entityTypes) throws RuntimeException {
final String[] entityTypeList = entityTypes.split((","));
boolean extractLocations = false;
final List<String> locationNerTagList = new ArrayList<String>(... | StanfordCoreNLPService svc = new StanfordCoreNLPService(StanfordCoreNLPService.createPipeline(null));
final String text = "ALBUQUERQUE, N.M. — A worldwide film production company is expanding to Albuquerque, according to Albuquerque Business First. The company, Production Resource Group, has worked on various ... |
215941972_171 | class GenericFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
if (inv.getMethodName().equals(Constants.$INVOKE)
&& inv.getArguments() != null
&& inv.getArguments().length == 3
&& !GenericS... |
Method genericInvoke = GenericService.class.getMethods()[0];
Map<String, Object> person = new HashMap<String, Object>();
person.put("name", "dubbo");
person.put("age", 10);
RpcInvocation invocation = new RpcInvocation("sayHi", genericInvoke.getParameterTypes()
... |
215950115_181 | class ClientConfigHelper {
public Map<String, ConsumerGroupVo> getConfig() {
try {
InputStream inputStream = getConfigFileStream();
return getConfig(inputStream);
} catch (Exception ex) {
log.error("加载配置文件异常,异常信息:" + ex.getMessage(), ex);
throw new RuntimeException(ex);
}
}
public ClientConfigH... | try {
Map<String, ConsumerGroupVo> maps = ClientConfigHelper.getConfig(consumerError);
assertEquals("consumerError 解析异常", 1, maps.size());
} catch (Exception e) {
// TODO: handle exception
}
try {
Map<String, ConsumerGroupVo> maps = ClientConfigHelper.getConfig(consumerGroupError);
assertEquals("... |
216000802_8 | class RqueueConfig {
public String getProcessingQueueChannelName(String queueName) {
if (dbVersion == 1) {
return "rqueue-processing-channel::" + queueName;
}
return prefix + getProcessingQueueChannelSuffix() + getTaggedName(queueName);
}
public String getQueuesKey();
private String getSimpl... | assertEquals(
"rqueue-processing-channel::test",
rqueueConfigVersion1.getProcessingQueueChannelName("test"));
assertEquals(
"__rq::p-channel::test", rqueueConfigVersion2.getProcessingQueueChannelName("test"));
assertEquals(
"__rq::p-channel::{test}",
rqueueConfigVersi... |
216204232_22 | class JdbcSpitterRepository implements SpitterRepository {
public Spitter findOne(long id) {
return jdbcTemplate.queryForObject(
SELECT_SPITTER + " where id=?", new SpitterRowMapper(), id);
}
@Autowired public JdbcSpitterRepository(JdbcTemplate jdbcTemplate);
@CacheEvict(key="123", value = { "spittleCac... | assertSpitter(0, spitterRepository.findOne(1L));
assertSpitter(1, spitterRepository.findOne(2L));
assertSpitter(2, spitterRepository.findOne(3L));
assertSpitter(3, spitterRepository.findOne(4L));
}
} |
216231037_5 | class HeroController {
@PostMapping("/hero/new")
public String addNewHero(@ModelAttribute("newHero") NewHeroModel newHeroModel) {
Hero hero = newHeroModel.getHero();
String repositoryName = newHeroModel.getRepository();
heroService.addHeroToRepository(hero, repositoryName);
retu... | NewHeroModel model = mock(NewHeroModel.class);
when(model.getRepository()).thenReturn(REPOSITORY);
when(model.getHero()).thenReturn(new Hero());
String view = subjectUnderTest.addNewHero(model);
assertThat(view).isEqualTo("redirect:/hero");
verify(heroService).addHeroToRe... |
216526613_4 | class RotationImpl implements Rotation {
@Override
public void rotate() {
locker.executeWithLock(this::doRotate);
}
@Inject @SuppressWarnings("checkstyle:ParameterNumber") // public RotationImpl(KeyGenerator generator, KeyRotationConfig config,
Juggler juggler, @Nullab... | // Fills the keystore
rotation.rotate();
Set<String> expiredIds = entries().all().stream().map(KeyAlias::getAlias).collect(Collectors.toSet());
assertThat(expiredIds).hasSize(2 * NUM_VALID);
when(timeSource.instant()).thenReturn(BASE_TIME.plus(VALIDITY_DT).plusSeconds(1));
... |
216840838_64 | class StigmaExtractor {
@Nullable
public Stigma extractStigma(@Nonnull final RawStigmaToken stigmaToken) {
Assert.notNull(stigmaToken, "stigmaToken must not be null");
final JWT jwt;
try {
jwt = JWTParser.parse(stigmaToken.getValue());
} catch (ParseException e) {
... | // given
given(tokenDecrypter.decrypt(any(com.nimbusds.jwt.JWT.class))).willReturn(decryptedToken);
given(decryptedToken.isValid()).willReturn(false);
// when
final Stigma stigma = stigmaExtractor.extractStigma(STIGMA_TOKEN);
// then
assertThat(stigma).isNull();... |
216898288_0 | class HeapMonitorPipeline {
public static DataStream<HeapAlert> computeHeapAlerts(DataStream<HeapMetrics> statsInput, ParameterTool params) {
return statsInput.flatMap(new AlertingFunction(params)).name("Create Alerts");
}
public static void main(String[] args);
private static Set<HeapAlert> testOutput;
}
cl... |
final String alertMask = "42";
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
HeapMetrics alert1 = testStats(0.42);
HeapMetrics regular1 = testStats(0.452);
HeapMetrics regular2 = testStats(0.245);
HeapMetrics alert2 = testStats(0.9423);
DataStreamSource<HeapMet... |
217054700_44 | class ByteUtil {
public static byte[] merge(byte[] ... byteArrays){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
try {
for(byte[] a: byteArrays ){
outputStream.write( a );
}
} catch (IOException e){
log.debug("Failed ... | String random1 = RandomStringUtils.random(50, true, true);
byte[] expResult = (random1).getBytes();
byte[] result = ByteUtil.merge(random1.getBytes(), new byte[0]);
Assertions.assertArrayEquals(expResult, result);
}
} |
217157573_2 | class ClusteredCompositeBlobStore implements BlobStore, ThreadCachingBean {
@Override
public boolean removeListener(BlobStoreListener listener) {
Boolean result = listeners.remove(listener);
cache.get().values().forEach(entry->{entry.store.removeListener(listener);});
StoreAndConfig def... | bsAgg = EasyMock.createMock("bsAgg", BlobStoreAggregator.class);
tld = EasyMock.createMock("tld", TileLayerDispatcher.class);
testBlobStoreInfo = EasyMock.createMock("testBlobStoreInfo", BlobStoreInfo.class);
testBlobStore1 = EasyMock.createMock("testBlobStore1", BlobStore.class... |
217172162_0 | class UserServiceImpl implements UserService {
@Override
public List<User> getUsers() {
return userRepository.findAll();
}
@Autowired public UserServiceImpl(UserRepository userRepository);
@Override public User getUser(long id);
@Override public User addUser(String nickname, String e... | //expected
List<User> expected = new ArrayList<>();
expected.add(new User(1L, "user1", "user1@mail.com", "pass"));
expected.add(new User(2L, "user2", "user2@mail.com", "test"));
//actual
List<User> actual = userService.getUsers();
//assert
assertEquals(e... |
217311696_5 | class DelegatingProperties extends Properties {
@Override
public Collection<Object> values() {
return environmentProperties.get().values();
}
public DelegatingProperties(Properties baseline);
private Properties buildNewEnvironment(Properties baseline);
@Override public synchronized Object get(Object key);
... | DelegatingProperties properties = propertiesWithRegularAndScopedKey("key", "key");
Collection<Object> values = properties.values();
assertThat(values).containsExactlyInAnyOrder("y");
}
} |
217419171_3 | class SCMTriggerConverter extends SingleTypedConverter<SCMTrigger> {
@Override
public boolean convert(ConverterRequest request, ConverterResult result, Object target)
{
SCMTrigger scmTrigger = (SCMTrigger) target;
String cronValue = scmTrigger.getSpec();
ModelASTTrigger modelASTTr... | String projectName = Long.toString( System.currentTimeMillis() );
FreeStyleProject p = j.createFreeStyleProject( projectName );
SCMTrigger trigger = new SCMTrigger( "H */4 * * 1-5" );
p.addTrigger( trigger );
SCMTriggerConverter converter = j.jenkins
.getExtensionLi... |
217479559_0 | class SimpleHttpsServer implements Callable<Integer> {
public void stop(int timeoutMillis) {
running = false;
if (debug) {
System.err.println("Stopping the HTTPS server (timeout " + timeoutMillis + " ms)");
}
httpsServer.stop(timeoutMillis);
}
public Integer cal... | PrintStream oldOut = System.out;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
SimpleHttpsServer server = new SimpleHttpsServer();
try {
System.setOut(new PrintStream(baos));
new CommandLine(server).execute("--port=7999");
String expected ... |
217587403_3 | class TextTranslations {
public static Component translate(Component text, Locale locale) {
return RENDERER.render(text, locale);
}
private TextTranslations();
public static SortedSet<String> getKeys();
public static Set<Locale> getLocales();
public static Locale getNearestLocale(Locale locale);
@... | final TranslatableComponent text = TranslatableComponent.of("entity.Creeper.name");
assertEquals(text, translate(text, US), "mojang translation did not pass-through");
}
} |
218804581_3 | class StringUtil {
public static List<String> tokenize(String value,
String delimiters,
boolean trimTokens,
boolean ignoreEmptyTokens) {
List<String> tokens = new ArrayList<>();
if (value == nu... | List<String> result = StringUtil.tokenize(STR, DELIMITERS, false, false);
assertEquals(6, result.size());
assertEquals("a ", result.get(0));
assertEquals(" b", result.get(1));
assertEquals(" c ", result.get(2));
assertEquals("", result.get(3));
assertEquals("d", result.get(4));
assertEqu... |
218912806_9 | class TaskHandler {
public boolean completeTaskByTaskID(String taskID){
try {
processEngine.getTaskService()
.complete(taskID);
} catch (ActivitiObjectNotFoundException e) {
logger.info("[任务完成操作失败] " + e.getMessage());
return false;
}
... | // Assert.assertFalse(ts.completeTaskByTaskID("6666"));
Assert.assertTrue(ts.completeTaskByTaskID("25005"));
}
} |
219180652_0 | class BlockState {
@Override
public String toString() {
StringJoiner sj = new StringJoiner(",");
for (Entry<String, String> e : getProperties().entrySet()){
sj.add(e.getKey() + "=" + e.getValue());
}
return getFullId() + "[" + sj.toString() + "]";
}
public BlockState(String id);
public BlockState... | BlockState blockState = new BlockState("someblock");
assertEquals("minecraft:someblock[]", blockState.toString());
blockState = blockState.with("testProp", "testVal");
assertEquals("minecraft:someblock[testProp=testVal]", blockState.toString());
blockState = blockState.with("testProp2", "testVal2");
Str... |
219454065_18 | class Recipient {
public void markNotified(@NonNull NotificationType type) {
Validate.notNull(type);
Optional.ofNullable(getNotifications().get(type))
.ifPresent(settings -> {
Validate.isTrue(settings.isActive());
settings.markNotified();
... | NotificationSettings backup = NotificationSettings.builder()
.active(false)
.frequency(Frequency.MONTHLY)
.build();
Recipient recipient = Recipient.builder()
.username(USERNAME)
.email(EMAIL)
.notification(No... |
219701790_135 | class CosineProc extends AlphaSimilarityProc<CosineAlgorithm, CosineConfig> {
@Procedure(name = "gds.alpha.similarity.cosine.stream", mode = READ)
@Description(DESCRIPTION)
public Stream<SimilarityResult> cosineStream(
@Name(value = "graphName") Object graphNameOrConfig,
@Name(value = "conf... | runQueryWithResultConsumer(STATEMENT_STREAM, map("config", map("concurrency", 1, "topK", 0), "missingValue", 0),
results -> {
assertTrue(results.hasNext());
assert01(results.next());
assert02(results.next());
assert03(results.next());
... |
220248572_1 | class FileUtil extends cn.hutool.core.io.FileUtil {
public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot >-1) && (dot < (filename.length() - 1))) {
return filename.... | Assert.assertEquals("foo", FileUtil.getExtensionName("foo"));
Assert.assertEquals("exe", FileUtil.getExtensionName("bar.exe"));
}
} |
220262191_21 | class ShadowTrafficFilter extends OncePerRequestFilter {
@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
String path = request.getRequestURI();
Map<String, String> headerKeyValueMap = new HashMap<>();
ShadowTrafficConfig shadowT... | when(shadowTrafficConfigHelper.getConfig()).thenReturn(config);
when(config.isEnabled()).thenReturn(true);
when(request.getRequestURI()).thenReturn("/hotels");
List<ShadowTrafficConfig.InclusionPattern> inclusionPatterns = new ArrayList<>();
inclusionPatterns.add(null);
... |
221155810_2 | class KisiServiceImpl implements KisiService {
@Override
public List<KisiDto> getAll() {
List<Kisi> kisiler = kisiRepository.findAll();
List<KisiDto> kisiDtos = new ArrayList<>();
kisiler.forEach(it -> {
KisiDto kisiDto =new KisiDto();
kisiDto.setId(it.getId());... | Kisi kisi = new Kisi();
kisi.setId(1L);
kisi.setAdi("Test-Name");
kisi.setSoyadi("Test-Lastname");
when(kisiRepository.findAll()).thenReturn(Collections.singletonList(kisi));
List<KisiDto> kisiDtos = kisiService.getAll();
assertEquals(kisiDtos.size(), 1);
... |
221881722_45 | class StochasticOscillatorK extends SingleValueIndicator {
public double getValue() {
return value;
}
public StochasticOscillatorK(TimeInterval interval);
public StochasticOscillatorK(int length, TimeInterval interval);
@Override protected boolean process(Candle candle, double value, boolean updating);
@Ov... |
StochasticOscillatorK ind = new StochasticOscillatorK(minutes(1));
double[][] values = new double[][]{
{44.98, 119.13, 119.50, 116.00},
{45.05, 116.75, 119.94, 116.00},
{45.11, 113.50, 118.44, 111.63},
{45.19, 111.56, 114.19, 110.06},
{45.12, 112.25, 112.81, 109.63},
{45.15, 110.00, 113.44... |
221992547_32 | class RandomCutForest {
public List<Neighbor> getNearNeighborsInSample(double[] point, double distanceThreshold) {
checkNotNull(point, "point must not be null");
checkArgument(distanceThreshold > 0, "distanceThreshold must be greater than 0");
if (!isOutputReady()) {
return Col... | assertThrows(NullPointerException.class, () -> forest.getNearNeighborsInSample(null, 101.1));
assertThrows(IllegalArgumentException.class,
() -> forest.getNearNeighborsInSample(new double[] { 1.1, 2.2 }, -101.1));
assertThrows(IllegalArgumentException.class,
() ->... |
222008690_16 | class CloverSerializerExtension extends JpsModelSerializerExtension {
@NotNull
@Override
public List<? extends JpsModulePropertiesSerializer<?>> getModulePropertiesSerializers() {
return Collections.emptyList();
}
@NotNull @Override public List<? extends JpsGlobalExtensionSerializer> getGl... | final List<? extends JpsModulePropertiesSerializer<?>> serializers =
new CloverSerializerExtension().getModulePropertiesSerializers();
assertEquals(0, serializers.size());
}
} |
222455446_0 | class UserService {
@Transactional(readOnly = true)
public UserResponse getUser(Integer userId) {
final Optional<TestUser> user = userRepository.findById(userId);
return user.map(UserService::toUserResponse).orElseThrow(NotFoundException::new);
}
@Inject public UserService(UserReposi... | // just sample test
final UserResponse user = userService.getUser(2);
assertEquals(Integer.valueOf(2), user.getId());
assertEquals("John Doe", user.getName());
}
} |
222514148_1 | class ClassFileDetectorStream extends InputStream {
public boolean isClass() {
return isClass;
}
public ClassFileDetectorStream(String name, InputStream input);
@Override public int read(byte[] bytes);
@Override public int read(byte[] bytes, int offset, int length);
@Override public int read();
pr... | ByteArrayInputStream data = new ByteArrayInputStream(VALID_CLASS);
ClassFileDetectorStream detector = new ClassFileDetectorStream("Foo.class", data);
byte[] read = readAll(detector);
assertThat(detector.isClass()).isTrue();
assertThat(read).isEqualTo(VALID_CLASS);
}
} |
222710815_0 | class ContextAssert extends AbstractAssert<ContextAssert, Context> {
public ContextAssert containsOnly(Context other) {
Map.Entry<Object, Object>[] otherArray = other.stream().toArray(ARRAY_GENERATOR);
//we use containsOnly and not containsExactlyInAnyOrder because we don't care about duplicates
iterables.asse... | assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> Assertions.assertThat(Context.of(1, 10).stream()).containsOnly(new AbstractMap.SimpleEntry<>("foo", "bar")))
.withMessage("\nExpecting:\n <[1=10]>\nto contain only:\n <[foo=bar]>\nelements not found:" +
"\n <[foo=bar]>\nand elements no... |
223482145_0 | class Handler implements RequestStreamHandler {
@Override
public void handleRequest(InputStream is, OutputStream os, Context context) throws IOException {
LambdaLogger logger = context.getLogger();
String input = Utils.toString(is);
try {
Request request = GSON.fromJson(inpu... | Context context = new MockContext();
Handler handler = new Handler();
Request request = new Request();
request.setInputImageUrl("https://djl-ai.s3.amazonaws.com/resources/images/kitten.jpg");
Gson gson = new Gson();
byte[] buf = gson.toJson(request).getBytes(StandardChar... |
223551095_1807 | class QueryImpl implements Query, ResourceInstance {
@Override
public Result execute()
throws UnsupportedPropertyException,
SystemException,
NoSuchResourceException,
NoSuchParentResourceException {
queryForResources();
return getResult(null);
}
public Quer... | ResourceDefinition resourceDefinition = createNiceMock(ResourceDefinition.class);
Map<Resource.Type, String> mapIds = new HashMap<>();
// expectations
expect(resourceDefinition.getType()).andReturn(Resource.Type.Cluster).anyTimes();
Set<SubResourceDefinition> setChildren = new HashSet<>();
set... |
224061261_10 | class ServletHandler extends XRayHandler {
@Override
public void handleResponse(Event event) {
HttpServletNetworkResponseEvent responseEvent = (HttpServletNetworkResponseEvent) event;
Segment currentSegment = getSegment();
// No need to log since a Context Missing Error will already be... | HttpServletNetworkRequestEvent requestEvent = new HttpServletNetworkRequestEvent(ORIGIN, 1, 1, "test", "test");
HttpServletNetworkResponseEvent responseEvent = new HttpServletNetworkResponseEvent(ORIGIN, requestEvent);
// Explicitly clear context
AWSXRay.clearTraceEntity();
Asse... |
224235390_87 | class GenericRecordSerializer extends JsonSerializer<GenericRecord> {
@Override
public void serialize(final GenericRecord record,
final JsonGenerator gen,
final SerializerProvider serializers) throws IOException {
gen.writeRawValue(getJsonString(reco... |
Schema.Parser parser = new Schema.Parser();
Schema schema = parser.parse(SCHEMA);
GenericRecord record = new GenericData.Record(schema);
record.put("name", "kafka");
record.put("created", NOW.toEpochMilli());
Writer jsonWriter = new StringWriter();
JsonGenerator... |
224256826_30 | class AcknowledgeableWorkBufferTranslator implements Translator<List<Acknowledgeable<W>>, Acknowledgeable<W>> {
@Override
public Translation<List<Acknowledgeable<W>>, Acknowledgeable<W>> apply(List<Acknowledgeable<W>> buffer) {
List<Acknowledgeable<W>> nonCanceledBuffer = WorkBuffers.collectNonCanceled... | AcknowledgeableWorkBufferTranslator<TestWork> translator =
new AcknowledgeableWorkBufferTranslator<>(workReducer, TestWork::prepare, failureReference);
TestWork work = TestWork.create(WorkType.COMMIT, "URL");
AcknowledgeableTestWork acknowledgeableWork = new AcknowledgeableTestWork(... |
224537036_84 | class DelfiDeliveryService implements DeliveryService {
@Override
public DeliveryResponse getResources(InputPayload inputPayload, MessageHeaders headers) {
log.debug("Getting resources for following SRNs and headers : {}, {}", inputPayload, headers);
String authorizationToken = extractHeaderByName(headers... |
// given
ProcessingResult result1 = new ProcessingResult();
ProcessingResult result2 = new ProcessingResult();
when(dataProcessingJob.process(eq(SRN_1), eq(AUTH), eq(PARTITION)))
.thenReturn(processingResultCompletableFutureOne);
when(dataProcessingJob.process(eq(SRN_2), eq(AUTH), eq(PARTI... |
224764811_71 | class SlayerPlugin extends Plugin {
@Subscribe
public void onGameTick(GameTick tick)
{
// update the lingering presence of npcs in the slayer xp consideration list
Iterator<NPCPresence> presenceIterator = lingeringPresences.iterator();
while (presenceIterator.hasNext())
{
NPCPresence presence = presenceI... | Widget npcDialog = mock(Widget.class);
when(npcDialog.getText()).thenReturn(TASK_ACTIVATESLAYERGEM_WILDERNESS);
when(client.getWidget(WidgetInfo.DIALOG_NPC_TEXT)).thenReturn(npcDialog);
slayerPlugin.onGameTick(GameTick.INSTANCE);
assertEquals("bandits", slayerPlugin.getCurrentTask().getTaskName());
assertE... |
224846645_331 | class NativeSettingsImpl implements NativeSettings, Serializable {
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NativeSettingsImpl that = (NativeSettings... | EqualsVerifier.forClass(NativeSettingsImpl.class).verify();
}
} |
225545609_1 | class PoolString implements CharSequence, java.io.Serializable {
public PoolString after(PoolString other) {
if (other.isEmpty()) {
return this;
}
Preconditions.checkArgument(other.base == base);
Preconditions.checkArgument(other.startIndex == startIndex);
if (other.endIndex == endIndex) {
return empt... | PoolString abcdef = PoolString.of("abcdef");
PoolString untilA = abcdef.until("a");
Assertions.assertThat(untilA).hasToString("");
Assertions.assertThat(abcdef.after(untilA)).hasToString("abcdef");
PoolString untilC = abcdef.until("c");
Assertions.assertThat(untilC).hasToString("ab");
Assertions.assertT... |
225818900_8 | class TaskHelper {
public static String createEndpointOptionsFromProperties(Map<String, String> props, String prefix) {
return props.keySet().stream()
.filter(k -> k.startsWith(prefix))
.map(k -> k.replace(prefix, "") + "=" + props.get(k))
.reduce((o1, o2) ->... | Map<String, String> props = new HashMap<String, String>() {
{
put("prefix.key1", "value1");
put("prefix.key2", "value2");
}
};
String result = TaskHelper.createEndpointOptionsFromProperties(props, "prefix.");
assertEquals("?key1=v... |
226861344_62 | class MulBlockingQueue {
@SuppressWarnings("unchecked") public List<E> poll(BitSet queueIds)
throws InterruptedException {
ArrayList<E> re = new ArrayList<>(queueIds.cardinality());
for (int id = queueIds.nextSetBit(0); id >= 0; id = queueIds.nextSetBit(id + 1)) {
DalQueue dalqu... | MulBlockingQueue<Payload> mq = new MulBlockingQueue<>(1024);
BitSet indexs = new BitSet(2);
indexs.set(mq.register("eosgroup1"));
indexs.set(mq.register("eosgroup2"));
List<Payload> packets = mq.poll(indexs);
Assert.assertTrue(packets.isEmpty());
mq.put(new Paylo... |
227063129_281 | class RangerValidator {
List<RangerPolicy> getPolicies(final String serviceName, final String policyName) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> RangerValidator.getPolicies(" + serviceName + ", " + policyName + ")");
}
List<RangerPolicy> policies = null;
try {
SearchFilter filter = new SearchFilte... |
// returns null when store returns null
String policyName = "aPolicy";
String serviceName = "aService";
SearchFilter filter = new SearchFilter();
filter.setParam(SearchFilter.POLICY_NAME, policyName);
filter.setParam(SearchFilter.SERVICE_NAME, serviceName);
when(_store.getPolicies(filter)).thenReturn(... |
227131980_94 | class TagUtils {
public static <T> MultivaluedMap<String, T> sanitizeHeaders(MultivaluedMap<String, T> headers) {
MultivaluedMap<String, T> sanitizedHeaders = new MultivaluedHashMap<>();
headers.forEach(
(key, value) -> {
if (AUTHORIZATION.equalsIgnoreCase(key)) {
sanitizedHead... | MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
headers.put(AUTHORIZATION, singletonList("1234"));
MultivaluedMap<String, ?> sanitizedHeaders = sanitizeHeaders(headers);
assertThat(sanitizedHeaders.getFirst(AUTHORIZATION)).isEqualTo("…");
}
} |
227144695_1 | class Jacobian {
public static double[][] approxJacobian(double[] x, Vector2VectorFunc func, double... arg)
{
final int n = x.length;
final double[] f0;
if (arg != null && arg.length > 0)
{
f0 = func.apply(x, arg);
}
else
{
f0 = fu... | final Vector2VectorFunc testFunc = (x, arg) -> x;
final double[] inputArr = new double[]{-1, -1, 2, 4, 5, 6, 8};
final double[][] fprime = Jacobian.approxJacobian(inputArr, testFunc);
for (int i = 0; i < fprime.length; i++)
{
for (int j = 0; j < fprime[0].length; j+... |
228257340_39 | class Purpose implements com.iabtcf.extras.gvl.Purpose {
@Override
public boolean getConsentable() {
return consentable;
}
@Override public int getId();
@Override public String getName();
@Override public String getDescription();
@Override public String getDescriptionLegal();
@... | Assert.assertTrue(purposeTen.getConsentable());
}
} |
228959889_0 | class Murmur3_128HashFunction implements HashFunction {
public byte[] hashBytes(byte[] var1) {
return newHasher().hashBytes(var1);
}
public Murmur3_128HashFunction(int seed);
public Hasher newHasher();
public byte[] hashBytes(byte[] var1, int var2, int var3);
}
class Murmur3_128HashFun... | final byte[] byteArray1 = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};
final byte[] byteArray2 = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8};
final byte[] byteArray3 = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9};
final byte[] expectedResult1 = new byte[]{-36, -65,... |
229095535_2 | class LibraryUserDetailsService implements UserDetailsService, UserDetailsPasswordService {
@Override
public UserDetails updatePassword(UserDetails user, String newPassword) {
return userService
.findOneByEmail(user.getUsername())
.map(
u -> {
LOGGER.info(
... | User user =
new User("Hans", "Test", "test@example.com", "secret", Collections.singleton("USER"));
UserDetails userDetails = new AuthenticatedUser(user);
given(userService.findOneByEmail(any())).willReturn(Optional.of(user));
given(userService.save(any()))
.willReturn(
new U... |
229869608_0 | class StingProcessor extends AbstractStandardProcessor {
@Nonnull
private String toFilename( @Nonnull final TypeElement typeElement )
{
return GeneratorUtil.getGeneratedClassName( typeElement, "", "" ).toString().replace( ".", "/" );
}
@Nonnull @Override protected String getIssueTrackerURL();
@Nonnull... | final List<String> expectedOutputs =
Collections.singletonList( toFilename( "expected", classname, "Sting_", "_Fragment.java" ) );
final List<JavaFileObject> javaFileObjects = inputs( classname );
javaFileObjects.addAll( inputs( additionalClassnames ) );
assertSuccessfulCompile( javaFileObjects, e... |
230080058_1 | class MapUtils {
public static Map<String, Object> flatMap(@NonNull Map<String, Object> map, String joinKey) {
return recursiveFlat(map, joinKey, new ArrayList<>());
}
public static List<Map<String, Object>> flatMaps(@NonNull List<Map<String, Object>> maps, String joinKey);
public static List<... | String json = "{" +
" \"1\":\"value 1\"," +
" \"2\":{" +
" \"2.1\":{" +
" \"2.1.1\":\"value 2.1.1\"" +
" }" +
" }" +
"}";
Map<String, Object> map = JSONObject... |
230236469_32 | class Script {
public Address getToAddress(NetworkParameters params) throws ScriptException {
return getToAddress(params, false);
}
private Script();
Script(List<ScriptChunk> chunks);
public Script(byte[] programBytes);
public Script(byte[] programBytes, long creationTimeSeconds);... | // P2PK
ECKey toKey = new ECKey();
Address toAddress = LegacyAddress.fromKey(TESTNET, toKey);
assertEquals(toAddress, ScriptBuilder.createP2PKOutputScript(toKey).getToAddress(TESTNET, true));
// pay to pubkey hash
assertEquals(toAddress, ScriptBuilder.createOutputScript(t... |
231329990_0 | class VertxTcpClientProvider implements NetworkProvider<TcpClientProperties> {
@Nonnull
@Override
public VertxTcpClient createNetwork(@Nonnull TcpClientProperties properties) {
VertxTcpClient client = new VertxTcpClient(properties.getId());
initClient(client, properties);
return c... | Vertx vertx = Vertx.vertx();
vertx.createNetServer()
.connectHandler(socket -> {
socket.write("tes");
socket.write("ttest");
})
.listen(12311);
VertxTcpClientProvider provider = new VertxTcpClientProvider(i... |
231519592_3 | class RefrigeratorInitCmdExe implements ExecutorI<Response, RefrigeratorInitCommand> {
@Override
public Response execute(RefrigeratorInitCommand cmd) {
refrigeratorMapper.truncate();
RefrigeratorRandomProfile refrigeratorRandomProfile = new RefrigeratorRandomProfile();
//先把大象全家都装进冰箱.... | Response response = refrigeratorInitCmdExe.execute(new RefrigeratorInitCommand());
assertTrue(response.isSuccess(),"业务执行失败");
}
} |
231533573_2 | class TubeBaseSessionFactory implements InnerSessionFactory {
public TubeBaseSessionFactory(final ClientFactory clientFactory,
final TubeClientConfig tubeClientConfig) throws TubeClientException {
super();
this.checkConfig(tubeClientConfig);
this.tubeClient... | TubeClientConfig config = mock(TubeClientConfig.class);
when(config.getMasterInfo()).thenReturn(new MasterInfo("192.168.1.1:18080"));
ClientFactory clientFactory = mock(ClientFactory.class);
PowerMockito.mockStatic(AddressUtils.class);
PowerMockito.when(AddressUtils.getLocalAddr... |
232306581_4 | class Ut0Crc32 {
public static long crc32(byte[] data, int offset, int len) {
long crc = 0xFFFFFFFFL;
long[][] table = init(UT_CRC_32_SLICE_8_TABLE_THREAD_LOCAL.get());
/* Calculate byte-by-byte up to an 8-byte aligned address. After
this consume the input 8-bytes at a time. */
// In C code, it... | String str = "innodb";
byte[] bytes = str.getBytes();
assertThat(Ut0Crc32.crc32(bytes, 0, bytes.length), is(1090276284L));
assertThat(Ut0Crc32.crc32ByteByByte(bytes, 0, bytes.length), is(1090276284L));
}
} |
232664319_8 | class CypherBasedMigration implements Migration {
List<String> getStatements() {
List<String> availableStatements = this.statements;
if (availableStatements == null) {
synchronized (this) {
availableStatements = this.statements;
if (availableStatements == null) {
this.statements = readStatements(... |
// Those are in eu.michael-simons.neo4j.neo4j-migrations:test-migrations
URL resource = CypherBasedMigrationTest.class.getResource("/some/changeset/V0002__create_new_data.cypher");
CypherBasedMigration migration = new CypherBasedMigration(resource);
List<String> statements = migration.getStatements();
asser... |
232712706_9 | class EtcdMetaStore implements MetaStore {
@Override
public void watch(WatchType type, LongConsumer consumer) {
switch (type) {
case SCHEMAVERSION:
etcdClient.watch(SCHEMA_VERSION_PATH, false, consumer);
break;
case SCHEMATASK:
etcdClient.watch(TASK_LIST, true, consumer);
... | int parallel = 16;
CountDownLatch latch = new CountDownLatch(parallel);
ConcurrentHashMap<Integer, EtcdMetaStore> storeMap = new ConcurrentHashMap();
for (int i = 0; i < parallel; i++) {
EtcdMetaStore metaStore = new EtcdMetaStore();
Properties properties = IOUtil.loadResource("jim.properti... |
233941256_356 | class DateRangeParser implements ConditionalValueParser {
public DateRange getRange(String dateRangeString) throws ParseException {
if (dateRangeString == null || dateRangeString.isEmpty())
throw new IllegalArgumentException("Passing empty Strings is not allowed");
String[] dateArr = d... | DateRange dateRange = dateRangeParser.getRange("Sep-Mar");
assertFalse(dateRange.isInRange(getCalendar(2014, Calendar.AUGUST, 31)));
assertTrue(dateRange.isInRange(getCalendar(2014, Calendar.SEPTEMBER, 1)));
assertTrue(dateRange.isInRange(getCalendar(2014, Calendar.DECEMBER, 24)));
... |
234365176_2 | class SexpTokenizer {
public static List<Token> tokenize(InputStream in) throws SexpParserException, IOException {
return SexpTokenizer.tokenize(in);
}
private SexpTokenizer();
public static List<Token> tokenize(Reader in);
private void close();
private void flush();
private List<Token> getParsedTokens();
... | String testStr = "( defun \n test;no comments\n () \"hi ;no comment here \n there\") ;this is a comment";
StringReader input = new StringReader(testStr);
List<Token> expectedList = new ArrayList<>();
expectedList.add(new Token("(", 1));
expectedList.add(new Token("defun", 1));
expectedList.add(new Token("te... |
234994470_5 | class AudioResource extends AbstractMediaResource<Audio> {
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path(ResourceDefinitions.Path.Common.SEARCH_FULL_PATH)
@Timed(name = MediaService.MetricsDefinitions.SearchAudio.TIMER_NAME, displayName =
METRICS_PREFIX + '.' + MediaService.MetricsDefinitions.SearchAu... | Client client = ClientBuilder.newClient();
WebTarget target =
client.target(
AUDIO_PATH + ResourceDefinitions.Path.Common.SEARCH_PATH + "/pink floyd");
List<Audio> audio = getResponseResult(target);
client.close();
assertEquals(145, audio.size());
}
} |
235035304_9 | class MongoUriParser {
public static String[] getHosts(String mongoUri) {
Matcher m = MONGO_URI_PATTERN.matcher(mongoUri);
if (m.find()) {
return Optional.ofNullable(m.group(2))
.map(hosts -> hosts.split(","))
.orElseThrow(() -> new RuntimeException("unsupported mongo uri"));
} els... | String[] mongoHosts = MongoUriParser.getHosts("mongodb://us3r:P%40ssw0rd@mongo0.exmpl.com:27017/dbName?authSource=admin&authSource2=admin2");
assertEquals(1, mongoHosts.length);
assertEquals("mongo0.exmpl.com:27017", mongoHosts[0]);
}
} |
235406671_1 | class DifficultyCalculator {
public Difficulty getNextJobDifficulty(Miner miner) {
// when few shares have been submitted, use the starting difficulty
if (miner.getValidSharesSubmitted() < wait) {
return new Difficulty(startDiff);
}
// hashrate = hashes submitted / conn... | final BigInteger startDiff = BigInteger.valueOf(5000);
final DifficultyCalculator difficultyCalculator =
new DifficultyCalculator(1, 1, 5000L, 5);
for (int i = 0; i < 5; i++) {
final Miner miner = new Miner();
miner.setValidSharesSubmitted((long) i);
... |
235577942_315 | class AuthorizationService {
public boolean hasManagerPrivilegeForDepartment(Long departmentId) {
UserContextRole userRole = userRoleFromContextService.getUserRoleInUnitId(departmentId);
return userRole.isHigherAuthorityTypeThan(UserContextRole.OKRMEMBER);
}
@Autowired public AuthorizationService(UserR... | mockCurrentUserRole(UserContextRole.OKRMANAGER);
boolean actual = authorizationService.hasManagerPrivilegeForDepartment(departmentId);
Assert.assertTrue(actual);
}
} |
235590282_3 | class UserMapper {
public List<User> userDTOsToUsers(List<UserDTO> userDTOs) {
return userDTOs.stream()
.filter(Objects::nonNull)
.map(this::userDTOToUser)
.collect(Collectors.toList());
}
public List<UserDTO> usersToUserDTOs(List<User> users);
public UserDT... | userDto.setAuthorities(null);
List<UserDTO> usersDto = new ArrayList<>();
usersDto.add(userDto);
List<User> users = userMapper.userDTOsToUsers(usersDto);
assertThat(users).isNotEmpty();
assertThat(users).size().isEqualTo(1);
assertThat(users.get(0).getAuthoriti... |
235957092_0 | class RLParamParser {
public RLParams getParams(String jsonStr) {
JSONObject jsonParams = new JSONObject(jsonStr);
RLParams params = new RLParams();
if (jsonParams.has("params")) {
JSONArray paramList = jsonParams.getJSONArray("params");
for (int i = 0; i < paramList... | RLParamParser parser = new RLParamParser();
RLParams params = parser.getParams("{\"params\" : [{\"type\": \"int_array\", \"name\": \"numc\", \"val\": [1,2,4]}]}");
List<Integer> numc = (List<Integer>) params.get("numc");
Integer[] expectedNumc = new Integer[]{1, 2, 4};
assertArra... |
235979171_1 | class RegistryActionFunction {
public Try<FileInputStream> tryStreamFileSubjects() {
File file = new File(this.config.getString("avro.subjects.yaml"));
return Try
.ofFailable(() -> new FileInputStream(file))
.onFailure((t) -> logger.error("Fail to load the yaml fil... | Config config = ConfigFactory
.parseResources("application-test.conf")
.withValue("avro.subjects.yaml", ConfigValueFactory.fromAnyRef("/totally/fake/path/to.yaml"));
service = new RegistryActionFunction(config);
Try<FileInputStream> triedInputStream = service.tr... |
236336373_3 | class HeapPriorityQueue extends AbstractPriorityQueue<K,V> {
public Entry<K,V> removeMin() @Override
public Entry<K,V> removeMin() ;
public Entry<K,V> removeMin() public HeapPriorityQueue();
public Entry<K,V> removeMin() public HeapPriorityQueue(Comparator<K> comp);
public Entry<K,V> removeMin() protecte... | Integer[] arr = new Integer[] {35,26,15,24,33,4,12,1,23,21,2,5};
HeapPriorityQueue<Integer, String> pq = new HeapPriorityQueue<>();
for(Integer i : arr) pq.insert(i, Integer.toString(i));
assertEquals(1, pq.removeMin().getKey());
assertEquals(11, pq.size());
assertEquals(2, pq.min().getKey());
}
} |
236431478_5 | class HelloSpringBoot {
@PostMapping("text")
public String text(@RequestBody String text){
return text;
}
@RequestMapping("string") @ResponseStatus(HttpStatus.OK) public String helloString();
@RequestMapping(value = "json") public Messages helloJson();
@GetMapping(value = "param") pub... | String string = "Hi,Spring Boot";
String result = this.restTemplate.postForObject("/hello/text", string, String.class);
assertThat(result).isEqualTo(string);
}
} |
237265610_7 | class FindMeetingQuery {
public Collection<TimeRange> query(Collection<Event> events, MeetingRequest request) {
throw new UnsupportedOperationException("TODO: Implement this method.");
}
private static final Collection<Event> NO_EVENTS;
private static final Collection<String> NO_ATTENDEES;
private stati... | // Have an event for each person, but have the first event be contained in the second event.
// This rules out using the method .contains for event A in event B.
// |--B--|
// Events : |----A----|
//
// Day : |---------------------|
// Option... |
238661958_7 | class PrescriptionController {
@PutMapping("/{id}")
public void update(@RequestHeader(Constants.GRANT_HEADER) PureGrant grant,
@PathVariable("id") String prescriptionId, @RequestBody Prescription prescription) {
if (StringUtils.isNotBlank(prescription.getId()) && !StringUtils.equals(prescriptionId, prescription... | String prescriptionId = this.prescriptions.iterator().next();
HttpHeaders headers = new HttpHeaders();
headers.set(Constants.GRANT_HEADER, this.registeredPhysician.getGrant());
HttpEntity<?> entity = new HttpEntity<>(headers);
ResponseEntity<Prescription> response;
// Get prescription
response = this.re... |
239025775_39 | class MoreBodyPublishers {
public static BodyPublisher ofObject(Object object, @Nullable MediaType mediaType) {
TypeRef<?> runtimeType = TypeRef.from(object.getClass());
Encoder encoder =
Encoder.getEncoder(runtimeType, mediaType)
.orElseThrow(() -> unsupportedConversion(runtimeType, medi... | var content = CharBuffer.wrap("<p>very important text</p>");
var body = ofObject(content, MediaType.parse("text/html"));
assertEquals(content, US_ASCII.decode(BodyCollector.collect(body)));
}
} |
239499581_3 | class SqlParserServiceImpl implements SqlParserService {
@Override
public List<SqlCreateTable> sqlTableParser(String ddlSql) throws Exception {
List<SqlCreateTable> result = new LinkedList<>();
SqlNodeList nodeList = SqlUtils.parseSql(ddlSql);
for (SqlNode sqlNode : nodeList) {
if (sqlNode instan... | String table = "CREATE TABLE tbl1 (\n" +
" `a` bigint,\n" +
" `date` date,\n" +
" h varchar, \n" +
" g as 2 * (a + 1), \n" +
" ts as toTimestamp(b, 'yyyy-MM-dd HH:mm:ss'), \n" +
" b varchar,\n" +
" proc as PROCTIME(), \n" +
" PRIMARY KEY (a, b)... |
240818625_0 | class ObjectOrderRandomizer {
public static JsonAdapter.Factory create() {
return new Factory(new Random());
}
public static JsonAdapter.Factory create(Random random);
}
class ObjectOrderRandomizerTest {
@Test public void createNoNulls() {
| try {
ObjectOrderRandomizer.create(null);
fail();
} catch (NullPointerException expected) {
}
}
} |
241565088_0 | class Gmp {
public static BigInteger exactDivide(BigInteger dividend, BigInteger divisor) {
if (divisor.signum() == 0) {
throw new ArithmeticException("BigInteger divide by zero");
}
return INSTANCE.get().exactDivImpl(dividend, divisor);
}
private Gmp();
public static void checkLoaded();
... | assertEquals(BigInteger.valueOf(1), exactDivide(BigInteger.valueOf(1), BigInteger.valueOf(1)));
assertEquals(BigInteger.valueOf(3), exactDivide(BigInteger.valueOf(9), BigInteger.valueOf(3)));
assertEquals(BigInteger.valueOf(4), exactDivide(BigInteger.valueOf(12), BigInteger.valueOf(3)));
Random rnd = ne... |
242737551_29 | class TodoResource {
@PUT
@Path("/{id}")
@Transactional
@Operation(description = "Update a todo")
@APIResponses({
@APIResponse(responseCode = "204", description = "Todo updated"),
@APIResponse(responseCode = "400", description = "Invalid request data",
content = @Content(schema = @Schem... | Todo defaultTodo = TestTodos.newDefaultTodo();
ModifiedTodo modifiedTodo = new ModifiedTodo();
modifiedTodo.setTitle(defaultTodo.getTitle());
modifiedTodo.setDescription(null);
modifiedTodo.setDueDate(defaultTodo.getDueDate());
modifiedTodo.setDone(true);
Mockito.doReturn(Optional.empty())... |
244294736_5 | class ConsulMetaDataCollector implements MetaDataCollector {
@Override
public String getConsumerMetaData(MetadataIdentifier key) {
return doGetMetaData(key);
}
@Override public URL getUrl();
@Override public void setUrl(URL url);
@Override public void init();
@Override public Strin... | MetadataIdentifier identifier = buildIdentifier(false);
Map<String, String> consumerParams = new HashMap<>();
consumerParams.put("k1", "v1");
consumerParams.put("k2", "1");
consumerParams.put("k3", "true");
String metadata = gson.toJson(consumerParams);
consulMet... |
244419190_1 | class WeatherQueries {
public Iterable<Integer> getMaxTemperatures(LocalDate fromDate, LocalDate toDate, String location) throws IOException {
Iterable<DailyWeatherInfo> weatherInfos = weatherApi.pastWeather(fromDate, toDate, location);
return QueriesEager.map(weatherInfos, dwi -> dwi.getTempMaxC(... | // Arrange
final LocalDate fromDate = LocalDate.of(2020, 3, 1);
final LocalDate toDate = LocalDate.of(2020, 3, 5);
String location = "Lisbon";
WeatherQueries wq = new WeatherQueries(new MemoryWeatherApi());
// Act
Iterable<Integer> maxTemperatures = wq.getMaxTe... |
244941906_7 | class CouplingFilterUtils {
static boolean matchCoupling(final CouplingFilter filter, final MethodCoupling coupling) {
return matchString(filter.getSourcePackagePattern(), coupling.getSource().getPackageName()) &&
matchString(filter.getSourceClassPattern(), coupling.getSource().getSimpleClas... | assertThat(matchCoupling(new CouplingFilter.Builder().sourcePackage("[\\w\\.]+").build(), DEFAULT_COUPLING)).isTrue();
assertThat(matchCoupling(new CouplingFilter.Builder().sourcePackage("\\d+").build(), DEFAULT_COUPLING)).isFalse();
}
} |
246041169_0 | class Elevator {
public boolean call(String button) {
int begin = getAFloor();
int end = getAFloor();
int buttonPressedFloor = getAFloor();
if (button.equalsIgnoreCase("Up")) // For Up
{
return (begin <= buttonPressedFloor && buttonPressedFloor < end) || (begi... |
Elevator lift = new Elevator();
int button = 3;
boolean expected = lift.call("Up");
Assertions.assertEquals(expected, true);
}
} |
246630390_1 | class SensorisParquetSplittedUDFExample implements SplittedUDF {
@Override
public byte[] merge(Map<String, Object> keys, Iterator<byte[]> files) {
return ParquetHelper.mergeFiles(files);
}
@Override public Map<Map<String, Object>, byte[]> getSplittedKeys(
Map<MetadataName, String> map, byte[] bytes)... | List<byte[]> list = Arrays.asList(b1, b2);
Iterator<byte[]> it = list.iterator();
List<byte[]> list2 = Arrays.asList(b3, b4);
Iterator<byte[]> it2 = list2.iterator();
byte[] a1 = example.aggregate(new HashMap<>(), it);
byte[] a2 = example.aggregate(new HashMap<>(), it2);
Iterator<byte[]> ... |
246677383_5 | class TransformationConfig {
public void buildExpressionNotation(String expressionBegin, String expressionEnd) {
this.expressionNotationBegin = expressionBegin;
this.expressionNotationEnd = expressionEnd;
String regexExpression = Pattern.quote(expressionNotationBegin) + EXPRESSION_PART + Pa... | TransformationConfig config = new TransformationConfig();
String expressionBegin = "[[";
String expressionEnd = "]]";
config.buildExpressionNotation(expressionBegin, expressionEnd);
assertEquals("Expression notation begin part is wrong after buildExpressionNotation()", expression... |
247595825_0 | class RedisEndpointAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnAvailableEndpoint
public RedisDescribeAvailableResourceEndpoint redisDescribeAvailableResourceEndpoint() {
return new RedisDescribeAvailableResourceEndpoint(aliCloudProperties,
redisProperties);
}
public RedisEndpointAut... | Object response = redisDescribeAvailableResourceEndpoint.describeAvailableResource("cn-hangzhou");
assertNotNull(response);
}
} |
248283523_3 | class RegionApi {
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public RegionsDto getAllRegions() {
LOGGER.info("REGION GET ALL API");
var allRegions = service.getAllRegions();
var dtoList = new ArrayList<RegionDto>();
allRegions.forEach(region -> {
var d... |
var region1 = new RegionEntity();
region1.setRegionId(1);
region1.setRegionName("地域1");
region1.setCreationTimestamp(LocalDateTime.now());
var region2 = new RegionEntity();
region2.setRegionId(2);
region2.setRegionName("地域2");
region2.setCreationTimestam... |
248529016_1 | class RetryHandlerUtils {
public static boolean isRetryHandlerMethod(Class<?> targetClass, Method method) {
if ("handle".equals(method.getName()) && method.getParameterCount() == 1 && method.isBridge() && method.isSynthetic()) {
//RetryHandler接口有泛型,需要特殊处理
return true;
}
... | Assertions.assertThat(RetryHandlerUtils.isRetryHandlerMethod(ObjectRetryHandler.class, getMethodByName(ObjectRetryHandler.class, "handle"))).isTrue();
Assertions.assertThat(RetryHandlerUtils.isRetryHandlerMethod(GenericRetryHandler.class, getMethodByName(GenericRetryHandler.class, "handle"))).isTrue();
... |
248826224_5 | class Book {
public ISBN getIsbn() {
return isbn;
}
public Book(String isbn, String author, String name);
}
class BookTest {
@Test
void testConvert13to10() {
| Book b;
b = new Book("9780306406157", "", "");
assertEquals("0306406152", b.getIsbn().isbn10().toString());
b = new Book("9780596007126", "", "");
assertEquals("0596007124", b.getIsbn().isbn10().toString());
b = new Book("9781491950357", "", "");
assertEquals("1491950358", b.getIsbn().isbn10().toSt... |
248828585_8 | class TokenProvider {
public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(key).parseClaimsJws(authToken);
return true;
} catch (JwtException | IllegalArgumentException e) {
log.info("Invalid JWT token.");
log.trace("Inva... | boolean isTokenValid = tokenProvider.validateToken(createTokenWithDifferentSignature());
assertThat(isTokenValid).isEqualTo(false);
}
} |
250091476_0 | class TokenFetcherService {
static String getPrincipalFromKeytab(String keytabLocation) {
try {
return Keytab
.read(new File(keytabLocation))
.getEntries().get(0)
.getPrincipalName()
.split("@")[0]
.replace('\\', '/');
} catch (Exception ex) {
thr... | String keytabLocation = "dummy.keytab";
String expectedPrincipalName = "somedomain/somehost";
String fullPrincipalName = expectedPrincipalName + "@somecompany.com";
Keytab kt = new Keytab();
KeytabEntry kte = new KeytabEntry(fullPrincipalName, 0,
new KerberosTime(), (byte) (0), new Encrypti... |
251049092_17 | class OpenWeatherMapWeather implements Weather {
@Override
public List<WeatherCondition> getConditions() {
return Collections.unmodifiableList(new ArrayList<WeatherCondition>(this.conditions));
}
public OpenWeatherMapWeather(Context context);
public OpenWeatherMapWeather(Context context,... | OpenWeatherMapWeather weather = WeatherUtils.createOpenWeather(context);
List<WeatherCondition> conditions = weather.getConditions();
assertEquals(8, conditions.size());
assertEquals(289, conditions.get(0).getTemperature(TemperatureUnit.K).getHigh());
assertEquals(295, conditions... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.