id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
96048740_17 | class DeviceMessageHandler extends Handler {
@Override public void handleMessage(Message message) {
super.handleMessage(message);
if (listener != null) {
listener.onMessageReceived(message);
}
}
DeviceMessageHandler(final DeviceMessageListener deviceMessageListener);
@Mock
private Devi... | // given
DeviceMessageHandler handler = new DeviceMessageHandler(null);
// when
handler.handleMessage(message);
// then
verify(deviceMessageListener, times(0)).onMessageReceived(message);
}
} |
96060769_12 | class MDSMapObjectInspector implements SettableMapObjectInspector {
@Override
public ObjectInspector getMapValueObjectInspector(){
return valueObjectInspector;
}
public MDSMapObjectInspector( final MapTypeInfo typeInfo );
@Override public ObjectInspector getMapKeyObjectInspector();
@Override public ... | MapTypeInfo info = new MapTypeInfo();
info.setMapKeyTypeInfo( TypeInfoFactory.stringTypeInfo );
info.setMapValueTypeInfo( TypeInfoFactory.stringTypeInfo );
MDSMapObjectInspector inspector = new MDSMapObjectInspector( info );
assertTrue( inspector.getMapValueObjectInspector() instanceof StringObjectI... |
96066104_1 | class Promise {
public static <U> Promise <U> race (Promise <U>... promises)
{
return race (Arrays.asList (promises));
}
public Promise(PromiseExecutor<T> impl);
public Promise(String name, PromiseExecutor<T> impl);
private Promise(T value);
private Promise(Throwable reason);
private Promise(... | synchronized (this.lock_)
{
Promise<Integer> p =
Promise.race (
new Promise<> (settlement -> {
{
try
{
Thread.sleep (500);
settlement.resolve (10);
}
catc... |
96094840_5 | class JSONObject extends JSONGetter<String> implements JSON, Map<String, Object> {
public <T> T toBean(Class<T> clazz) {
return toBean(clazz, false);
}
public JSONObject();
public JSONObject(JSONObject jsonObject, String... names);
public JSONObject(JSONTokener x);
public JSONObject(Object source);
publi... | UserA userA = new UserA();
userA.setA("A user");
userA.setName("nameTest");
userA.setDate(new Date());
JSONObject userAJson = JSONUtil.parseObj(userA);
UserB userB = JSONUtil.toBean(userAJson, UserB.class);
Assert.assertEquals(userA.getName(), userB.getName());
Assert.assertEquals(userA.getDate(),... |
96114330_134 | class RuleBuilder {
public static Builder<RuleBuilder, DecisionTreeRule> creator() {
return Builder.instanceOf(RuleBuilder.create(), RuleBuilder.validate(), RuleBuilder::builds);
}
public static DecisionTreeRule builds(final RuleBuilder builder);
private static Supplier<RuleBuilder> create();
... | final Instant startTime = Instant.now().minus(1, ChronoUnit.DAYS);
final Instant endTime = Instant.now().plus(1, ChronoUnit.DAYS);
final DecisionTreeRule rule = RuleBuilder.creator().with(RuleBuilder::input, Arrays.asList("test1", "test2"))
.with(RuleBuilder::setDriverCount, 2L)... |
96121797_109 | class ElasticSearchRestHighImpl implements ElasticSearchService {
@Override
public Future<Boolean> bulkInsert(
String index, List<Map<String, Object>> dataList, RequestContext context) {
long startTime = System.currentTimeMillis();
logger.info(
context,
"ElasticSearchRestHighImpl:bulk... | mockRulesForBulk(false);
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map = new HashMap<>();
map.put(JsonKey.IDENTIFIER, "0001");
list.add(map);
Future<Boolean> result = esService.bulkInsert("test", list, null);
boolean res = (boolean) ElasticSearchHelper.getRespon... |
96123627_156 | class RequestValidator {
@SuppressWarnings("unchecked")
public static void validateUpdateContent(Request contentRequestDto) {
List<Map<String, Object>> list =
(List<Map<String, Object>>) (contentRequestDto.getRequest().get(JsonKey.CONTENTS));
if(CollectionUtils.isNotEmpty(list)) {
for (Ma... | Request request = new Request();
List<Map<String, Object>> listOfMap = new ArrayList<>();
Map<String, Object> requestObj = new HashMap<>();
requestObj.put(JsonKey.CONTENT_ID, "do_1233343");
listOfMap.add(requestObj);
Map<String, Object> innerMap = new HashMap<>();
innerMap.put(JsonKey.CONTEN... |
96242277_10 | class InternetRadioService {
public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) {
List<InternetRadioSource> sources;
if (cachedSources.containsKey(radio.getId())) {
LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl());
sourc... | List<InternetRadioSource> radioSources = internetRadioService.getInternetRadioSources(radioMoveLoop);
// A PlaylistHasTooManyRedirects exception is thrown internally,
// and the `getInternetRadioSources` method logs it and returns 0 sources.
Assert.assertEquals(0, radioSources.size());
... |
96331237_57 | class CsarImpl implements Csar {
@Override
public Optional<Transformation> getTransformation(String platformId) {
Transformation t = transformations.get(platformId);
return Optional.ofNullable(t);
}
public CsarImpl(File rootDir, String identifier, Log log);
private List<Lifecycle... | Optional<Transformation> result = csar.getTransformation(PLATFORM1.id);
assertTrue(result.isPresent());
assertEquals(transformation1, result.get());
}
} |
96367327_165 | class SpyImpl implements Spy {
@Nonnull
@Override
public ObserverInfo asObserverInfo( @Nonnull final Observer observer )
{
return observer.asInfo();
}
SpyImpl( @Nullable final ArezContext context );
@Override public void addSpyEventHandler( @Nonnull final SpyEventHandler handler );
@Override pu... | final ArezContext context = Arez.context();
final Observer observer = context.observer( AbstractTest::observeADependency );
final ObserverInfo info = context.getSpy().asObserverInfo( observer );
assertEquals( info.getName(), observer.getName() );
}
} |
96455695_1 | class RepositoryInitializationService {
@EventListener
@Transactional
public void initialize(ApplicationReadyEvent event) {
synchronizeRepositories();
synchronizePackageMetadata();
}
public RepositoryInitializationService(RepositoryRepository repositoryRepository,
PackageMetadataRepository packageMetadat... | assertThat(repositoryRepository.count()).isEqualTo(2);
assertThat(repositoryRepository.findByName("test").getUrl()).isEqualTo("classpath:/repositories/binaries/test");
// Note, this is a brittle assertion.
assertThat(packageMetadataRepository.count()).isGreaterThan(5);
}
} |
96467418_0 | class DefaultClientHeadersFactoryImpl implements ClientHeadersFactory {
@Override
public MultivaluedMap<String, String> update(MultivaluedMap<String, String> incomingHeaders,
MultivaluedMap<String, String> clientOutgoingHeaders) {
if (LOG.isLoggable(Lev... | MultivaluedMap<String, String> incomingHeaders = mockIncomingHeaders();
MultivaluedMap<String, String> clientOutgoingHeaders = new MultivaluedHashMap<>();
MultivaluedMap<String, String> updatedHeaders = impl.update(incomingHeaders, clientOutgoingHeaders);
assertNotNull(updatedHeaders);
... |
96480746_9 | class DebugBashCodeToggleSupport {
public String disableDebugging(String sourceCode) throws IOException {
int index = sourceCode.indexOf(DEBUG_POSTFIX);
if (index == -1) {
return sourceCode;
}
int pos = index + DEBUG_POSTFIX.length();
String data = sourceCode.sub... | assertEquals("#! /bin/mybash", supportToTest.disableDebugging(EXPECTED_DEBUG_ENABLED_CODE + "#! /bin/mybash"));
}
} |
96517640_0 | class LoginViewModel extends BaseViewModel<LoginNavigator> {
public void login(String email, String password) {
setIsLoading(true);
getCompositeDisposable().add(getDataManager()
.doServerLoginApiCall(new LoginRequest.ServerLoginRequest(email, password))
.doOnSuccess(... | String email = "dummy@gmail.com";
String password = "password";
LoginResponse loginResponse = new LoginResponse();
doReturn(Single.just(loginResponse))
.when(mMockDataManager)
.doServerLoginApiCall(new LoginRequest.ServerLoginRequest(email, password));
... |
96553293_2 | class RAMLtoSwagger implements Constants {
@SuppressWarnings("WeakerAccess, unused")
public String convertToSwagger(String raml) {
return convertToSwagger(raml, null);
}
RAMLtoSwagger();
private void initializeRespCodes();
private String getResponseMessage(int code);
private voi... | String raml = IOUtils.resourceToString("/product-api.raml", Charset.forName("UTF-8"));
Assert.assertNotNull(raml);
String swagger = raml2Swagger.convertToSwagger(raml);
Assert.assertNotNull(swagger);
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<Str... |
96556232_64 | class KeepaliveReaderWrapper implements DelegatingReader<D, B>,Runnable, Closeable {
@Override
public void close() {
// Do not interrupt, it's not our executor
scheduledFuture.cancel(false);
}
public KeepaliveReaderWrapper(@Nonnull final Reader<D, B> delegate,
... | final CapturingFailListener listener = new CapturingFailListener();
final KeepaliveReaderWrapper<DataObject, Builder<DataObject>> keepaliveWrapper =
new KeepaliveReaderWrapper<>(delegate, exec, TestingException.class, 1, listener);
keepaliveWrapper.readCurrentAttributes(id, bui... |
96556656_626 | class VppCommonModule extends AbstractModule {
@Override
protected void configure() {
install(ConfigurationModule.create());
// Inject non-dependency configuration
requestInjection(VppConfigAttributes.class);
bind(VppStatusListener.class).toInstance(new VppStatusListener());
... | initMocks(this);
Guice.createInjector(new VppCommonModule(), BoundFieldModule.of(this)).injectMembers(this);
assertThat(readerFactories, is(not(empty())));
assertEquals(15, JvppReplyConsumer.JvppReplyTimeoutHolder.getTimeout());
}
} |
96573099_91 | class FilterParser {
public List<List<IdentifierMatcher>> parse() throws ParseException {
eatSeparators();
while (!atEnd()) {
List<IdentifierMatcher> list = new ArrayList<>();
while (!atEnd()) {
if (current() == '/') {
list.add(parseRegex(... | Assert.assertEquals("/foo.bar/0", toString(new FilterParser("/foo.bar/").parse()));
}
} |
96577896_6 | class GetPutFile extends AbstractFileAnalyzer {
@Override
public DataSetRefs analyze(AnalysisContext context, ProvenanceEventRecord event) {
final URI uri = parseUri(event.getTransitUri());
final String clusterName = context.getClusterResolver().fromHostname(uri.getHost());
final Data... | final String processorName = "PutFile";
final String transitUri = "file:/var/data/landing/sample_z";
final ProvenanceEventRecord record = Mockito.mock(ProvenanceEventRecord.class);
when(record.getComponentType()).thenReturn(processorName);
when(record.getTransitUri()).thenReturn... |
96755147_0 | class MailController {
@RequestMapping(value = "/{targetId}", method = RequestMethod.GET)
@ApiOperation(value = "按照发信人或收信人的id以及发信状态", notes = "target是指定按照收信人还是发信人查询,可选值是sender和receiver;如果是按照收信人查询,那么必须指定mail_status,可选值为ALL、NOT_VIEWED、VIEWED;如果是按照发信人查询,则不需要给出该参数", response = PageInfo.class)
@ApiResponses(val... | String url = "/mails/2";
MultiValueMap<String,String> params = new LinkedMultiValueMap<>();
params.put("target", Arrays.asList("receiver"));
params.put("mail_status",Arrays.asList("all"));
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(url).params(params).accept(Med... |
96760451_0 | class UrlFactory extends RegexNamedEntityFactory {
@Override
protected List<NamedPattern> getRegexes(SpanCollection spanCollection, String lang) {
return Collections.singletonList(new NamedPattern(URL, URL_PATTERN));
}
@Override protected RegexNerProcessor.NamedEntity createNamedEntity(String ... | Pattern p = new UrlFactory().getRegexes(null, null).get(0).getPattern();
String url1 = "http://foo.com/blah_blah/";
String url2 = "Ein beispiel: https://www.example.com/foo/?bar=baz&inga=42&quux";
String wrong_url1 = "khttp://foo.bar?q=Spaces should be encoded";
String wrong_url... |
96845301_0 | class ZuulRateLimitFilter extends ZuulFilter {
@Override
public Object run() {
RequestContext context = getCurrentRequestContext();
HttpServletRequest request = context.getRequest();
Long remainingLimit = null;
for (RateLimitCheck<HttpServletRequest> rl : filterConfig.getRateLimitChecks()) {
Consum... | MockHttpServletRequest request = new MockHttpServletRequest("GET", "/url");
RequestContext context = new RequestContext();
context.setRequest(request);
RequestContext.testSetCurrentContext(context);
when(rateLimitCheck1.rateLimit(any(), Mockito.anyBoolean())).thenReturn(consum... |
96905440_32 | class TracedThreadPoolTaskScheduler extends ThreadPoolTaskScheduler {
@Override
public void setAwaitTerminationSeconds(int awaitTerminationSeconds) {
delegate.setAwaitTerminationSeconds(awaitTerminationSeconds);
}
public TracedThreadPoolTaskScheduler(Tracer tracer, ThreadPoolTaskScheduler delegate);
@... | scheduler.setAwaitTerminationSeconds(5);
verify(delegate).setAwaitTerminationSeconds(5);
}
} |
96925861_0 | class UserRepository {
public LiveData<User> getUser(String email) {
MutableLiveData<User> liveData = new MutableLiveData<>();
userDao.loadUser(email)
.compose(transformers.applySchedulersToFlowable())
.subscribe(liveData::setValue, Timber::d);
userApi.getU... | User userEntity = new User("john.doe@gmail.com", "John", "Doe");
com.jonathanpetitfrere.mvvm.repository.api.model.User userModel = mapper.toModel(userEntity);
when(transformers.applySchedulersToFlowable()).thenReturn(flowable -> flowable);
when(userDao.loadUser(anyString())).thenReturn(... |
96952895_12 | class DelegatingIdlingResourceScheduler extends IdlingResourceScheduler {
@Override public Worker createWorker() {
final Worker delegateWorker = delegate.createWorker();
return new Worker() {
private final CompositeSubscription subscriptions = new CompositeSubscription(delegateWorker);
@Override... | Scheduler.Worker worker = scheduler.createWorker();
worker.unsubscribe();
worker.schedule(new CountingAction());
assertIdle(0);
}
} |
96973263_25 | class Trie {
public Trie findNode(final FocusString string) {
if (terminator) {
// Match achieved - and we're at a domain boundary. This is important, because
// we don't want to return on partial domain matches. (E.g. if the trie node is bar.com,
// and the search strin... | final Trie trie = Trie.createRootNode();
assertNull(trie.findNode(FocusString.create("hello")));
final Trie putNode = trie.put(FocusString.create("hello"));
final Trie foundNode = trie.findNode(FocusString.create("hello"));
assertNotNull(putNode);
assertNotNull(foundNo... |
97025950_3 | class CollectionUtils {
public static <T extends Comparable<T>> T findMostPopularElement(
List<T> list) {
Preconditions.checkNotNull(list, "The list cannot be null");
Collections.sort(list);
T previous = list.get(0);
T popular = list.get(0);
int count = 1;
int maxCount = 1;
for (int i = 1; i < lis... | Integer[] array = {1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7, 8};
List<Integer> list = new ArrayList<>(Arrays.asList(array));
assertEquals((Integer) 5, CollectionUtils.findMostPopularElement(list));
}
} |
97029141_10 | class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ... |
final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint = new JwtAuthenticationEntryPoint();
jwtAuthenticationEntryPoint.commence(request, response, authException);
verify(response, times(1)).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
} |
97034221_41 | class StringUtils {
public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) {
final List<String> tokens = new ArrayList<>();
Optional<String> token = firstToken(input, startDelimiter, endDelimiter);
while(token.isPresent()) {
final String tokenValue = token.get();
t... | final String input = "___${____${TOKEN_1}__}___${TOKEN_2}__";
final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter);
assertEquals(2, tokens.size());
assertEquals("TOKEN_1", tokens.get(0));
assertEquals("TOKEN_2", tokens.get(1));
}
} |
97047427_10 | class AbstractMinikubeMojo extends AbstractMojo {
@VisibleForTesting
List<String> buildMinikubeCommand() {
List<String> execString = new ArrayList<>();
execString.add(minikube);
execString.add(getCommand());
if (flags != null) {
execString.addAll(flags);
}
execString.addAll(getMoreFla... | spyAbstractMinikubeMojo.setMinikube("path/to/minikube");
spyAbstractMinikubeMojo.setFlags(ImmutableList.of("someFlag1", "someFlag2"));
Mockito.when(spyAbstractMinikubeMojo.getCommand()).thenReturn("somecommand");
Mockito.when(spyAbstractMinikubeMojo.getMoreFlags())
.thenReturn(ImmutableList.of(... |
97106222_97 | class SecretIdentifier {
@Override
public String toString() {
return name;
}
@JsonCreator public SecretIdentifier(@JsonProperty("name") String name);
@Override public int hashCode();
@Override public boolean equals(final Object obj);
}
class SecretIdentifierTest {
@Test
pu... | SecretIdentifier secret = new SecretIdentifier("fooBar1");
assertEquals(secret.name, "fooBar1");
assertEquals(secret.toString(), "fooBar1");
}
} |
97111736_1 | class LambdaHandler implements RequestStreamHandler {
@Override
public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
I inputObject = deserializeEventJson(input, getInputType());
O handlerResult = handleRequest(inputObject, context);
ser... | String jsonInputAndExpectedOutput = "{\"value\":\"testValue\"}";
InputStream exampleInputStream = new ByteArrayInputStream(jsonInputAndExpectedOutput.getBytes(StandardCharsets.UTF_8));
OutputStream exampleOutputStream = new OutputStream() {
private final StringBuilder stringBuilder ... |
97115482_19 | class OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc {
public Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo )
throws UserNotFoundException, NotAuthorizedException {
Queue<Element> elems = repo.loadM... | BareJID userJid = BareJID.bareJIDInstance("user1@example.com");
JID res1 = JID.jidInstance(userJid, "res1");
XMPPResourceConnection session1 = getSession(JID.jidInstance("c2s@example.com/" + UUID.randomUUID().toString()), res1);
assertEquals(Arrays.asList(session1), session1.getActiveSessions());
Element pa... |
97231654_23 | class DateCalcExpressionParser {
public Queue<Token> parse(String text) {
final Queue<Token> tokens = new ArrayDeque<>();
if (text != null) {
text = text.trim();
if (!text.isEmpty()) {
boolean matchFound = false;
for (InfoWrapper iw : infos) ... | Queue<Token> words = parser.parse("12:37am");
Assert.assertEquals(words.size(), 1);
Assert.assertTrue(words.poll() instanceof TimeToken);
}
} |
97286202_0 | class Book {
public void addAuthor(Author author) {
authors.add(createAuthorRef(author));
}
private AuthorRef createAuthorRef(Author author);
@Autowired BookRepo bookRepo;
@Autowired AuthorRepo authorRepo;
}
class BookTest {
@Autowired BookRepo bookRepo;
@Autowired AuthorRepo authorRepo;
@Test
public ... |
Author author = new Author();
author.name = "Greg L. Turnquist";
author = authorRepo.save(author);
Book book = new Book();
book.title = "Spring Boot";
book.addAuthor(author);
bookRepo.save(book);
bookRepo.deleteAll();
assertThat(authorRepo.count()).isEqualTo(1);
}
} |
97291552_29 | class BitStringBerEncoder implements BerEncoder {
@Override
public void encode( @NotNull WriterContext context ) throws IOException
{
assert context.getType().getFamily() == Family.BIT_STRING;
assert context.getValue().getKind() == Kind.BYTE_ARRAY;
ByteArrayValue arrayValue = context.getValue().toByteArrayVal... | Scope scope = CoreModule.getInstance().createScope();
Type type = UniversalType.BIT_STRING.ref().resolve( scope );
Value value = CoreUtils.byteArrayFromBitString( VALUE_01010000000000B );
try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) )
{
when( writer.getRules() ).thenReturn( BerRules.DER ... |
97306203_11 | class Minting {
public void mint(List<Token> tokens) throws ExecutionException, InterruptedException {
for(Token token:tokens) {
if(modumToken == null) {
LOG.error("no modum token bean created");
} else {
Future<TransactionReceipt> receipt = modumToke... | dataBtc(1).dataBtc(2);
rateBtc(101, 1_050_001);
rateBtc(102, 7);
int current = 0;
current = minting.mint(current, 100, 0, 1 * 100_000_000, 0, "w1");
Assert.assertEquals(0, current);
current = minting.mint(current, 102, 0, 1 * 100_000_000, 0, "w2");
Asser... |
97484669_19 | class BerObjectIdentifier implements Serializable, BerType {
@Override
public int decode(InputStream is) throws IOException {
return decode(is, true);
}
public BerObjectIdentifier();
public BerObjectIdentifier(byte[] code);
public BerObjectIdentifier(int[] value);
@Override public int encode(Out... |
ByteArrayInputStream berInputStream = new ByteArrayInputStream(expectedBytes);
BerObjectIdentifier oi = new BerObjectIdentifier();
oi.decode(berInputStream, true);
assertArrayEquals(objectIdentifierComponents, oi.value);
ByteArrayInputStream berInputStream2 = new ByteArrayInputStream(expectedByt... |
97490945_457 | class FederatedHMSHandler extends FacebookBase implements CloseableIHMSHandler {
@Override
@Loggable(value = Loggable.DEBUG, skipResult = true, name = INVOCATION_LOG_NAME)
public GetFileMetadataResult get_file_metadata(GetFileMetadataRequest req) throws TException {
return getPrimaryClient().get_file_metadat... | GetFileMetadataRequest request = new GetFileMetadataRequest();
GetFileMetadataResult expected = new GetFileMetadataResult();
when(primaryClient.get_file_metadata(request)).thenReturn(expected);
GetFileMetadataResult result = handler.get_file_metadata(request);
assertThat(result, is(expected));
}
... |
97492141_16 | class RuleMetadataLoader {
public void addRulesByRuleKey(NewRepository repository, List<String> ruleKeys) {
for (String ruleKey : ruleKeys) {
addRuleByRuleKey(repository, ruleKey);
}
}
public RuleMetadataLoader(String resourceFolder);
public RuleMetadataLoader(String resourceFolder, String def... | ruleMetadataLoader.addRulesByRuleKey(newRepository, Arrays.asList("S110", "S100"));
newRepository.done();
RulesDefinition.Repository repository = context.repository(RULE_REPOSITORY_KEY);
RulesDefinition.Rule ruleS110 = repository.rule("S110");
assertThat(ruleS110).isNotNull();
assertThat(ruleS1... |
97518356_346 | class SimpleLimitExchangeRemover {
public static Prel apply(PlannerSettings settings, Prel input){
if(!settings.isTrivialSingularOptimized() || settings.isLeafLimitsEnabled()) {
return input;
}
if(input.accept(new Identifier(), false)){
return input.accept(new AllExchangeRemover(), null);
... | Prel input =
newScreen(
newLimit(0, 10,
newProject(exprs(), rowType(),
newUnionExchange(
newLimit(0, 10,
newProject(exprs(), rowType(),
newSoftScan(rowType())
... |
97570753_0 | class ThriftyConverterFactory extends Converter.Factory {
public static ThriftyConverterFactory create(ProtocolType protocolType) {
return new ThriftyConverterFactory(protocolType);
}
private ThriftyConverterFactory(ProtocolType protocolType);
@SuppressWarnings("unchecked") private static Ad... | Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(ThriftyConverterFactory.create(ProtocolType.BINARY))
.build();
BrokenService brokenService = retrofit.create(BrokenService.class);
try {
brokenSe... |
97580115_12 | class Pool {
@Nullable
public T get() {
synchronized (lock) {
T item = queue.poll();
if (item != null) {
activeCount++; // poll decreases, this fixes
LOG.v("GET - Reusing recycled item.", this);
return item;
}
... | pool.get();
assertEquals(1, instances);
}
} |
97598061_24 | class JUnitCoreParameters {
public boolean isParallelismSelected()
{
return isParallelSuites() || isParallelClasses() || isParallelMethods();
}
public JUnitCoreParameters( Map<String, String> properties );
private static Collection<String> lowerCase( String... elements );
private boo... | assertTrue( newTestSetClasses().isParallelismSelected() );
assertTrue( newTestSetMethods().isParallelismSelected() );
assertTrue( newTestSetBoth().isParallelismSelected() );
}
} |
97621321_1155 | class SmartRegisterClients extends ArrayList<SmartRegisterClient> {
public SmartRegisterClients applyFilter(final FilterOption villageFilter, final
ServiceModeOption serviceModeOption, final FilterOption searchFilter, SortOption sortOption) {
SmartRegisterClients results = new SmartRegisterClients();
... | SmartRegisterClients originalClients = getSmartRegisterClientsWithProperDetails();
SmartRegisterClients filteredClients = originalClients.applyFilter(
new AllClientsFilter(),
allEligibleCoupleServiceMode,
new ECSearchOption(""),
new HighPri... |
97621363_0 | class ImageUtils {
public static int profileImageResourceByGender(String gender) {
if (StringUtils.isNotBlank(gender)) {
if (gender.equalsIgnoreCase(PathConstants.GENDER.MALE)) {
return R.drawable.child_boy_infant;
} else if (gender.equalsIgnoreCase(PathConstants.GEN... | assertEquals(ImageUtils.profileImageResourceByGender(""), R.drawable.child_boy_infant);
}
} |
97638785_4 | class ScrollEventCalculator {
public boolean isAtScrollEnd() {
RecyclerView.LayoutManager layoutManager =
recyclerViewScrollEvent.view().getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager... | //
//Arrange
//
LinearLayoutManager mockLinearLayoutManager = Mockito.mock(LinearLayoutManager.class);
RecyclerView mockRecyclerView = Mockito.mock(RecyclerView.class);
RecyclerViewScrollEvent mockRecyclerViewScrollEvent = Mockito.mock(RecyclerViewScrollEvent.class);
... |
97664518_9 | class BarcodeInfo {
CalendarEvent getCalendarEvent() {
return mCalendarEvent;
}
Rect getBoundingBox();
public void setBoundingBox(Rect boundingBox);
Contact getContact();
public void setContact(Contact contact);
UrlBookmark getUrlBookmark();
public void setUrlBookmark(UrlBoo... | BarcodeInfo.CalendarEvent calendarEvent = new BarcodeInfo.CalendarEvent();
BarcodeInfo barcodeInfo = new BarcodeInfo();
barcodeInfo.setCalendarEvent(calendarEvent);
assertEquals(barcodeInfo.getCalendarEvent(), calendarEvent);
}
} |
97805491_0 | class MCacheDb extends AbstractActor {
public String getValue(String key) {
return this.map.get(key);
}
@Override public Receive createReceive();
ActorSystem actorSystem;
}
class MCacheDbTest {
ActorSystem actorSystem;
@Test
public void testPut() {
| TestActorRef<MCacheDb> actorRef = TestActorRef.create(actorSystem, Props.create(MCacheDb.class));
actorRef.tell(new SetRequest("key", "value"), ActorRef.noSender());
MCacheDb mCacheDb = actorRef.underlyingActor();
Assert.assertEquals(mCacheDb.getValue("key"), "value");
}
} |
97935002_3 | class HelloWorldImpl implements HelloWorldPortType {
@Override
public Greeting sayHello(Person person) {
String firstName = person.getFirstName();
LOGGER.info("firstName={}", firstName);
String lasttName = person.getLastName();
LOGGER.info("lastName={}", lasttName);
ObjectFactory factory = ne... | Person person = new Person();
person.setFirstName("Jane");
person.setLastName("Doe");
Greeting greeting = helloWorldRequesterProxy.sayHello(person);
assertEquals("Hello Jane Doe!", greeting.getText());
}
} |
98013453_9 | class AtlasMapType extends AtlasType {
@Override
public Map<Object, Object> createDefaultValue() {
Map<Object, Object> ret = new HashMap<>();
Object key = keyType.createDefaultValue();
if ( key != null) {
ret.put(key, valueType.createDefaultValue());
}
re... | Map<Object, Object> defValue = intIntMapType.createDefaultValue();
assertEquals(defValue.size(), 1);
}
} |
98026470_1 | class Event {
public static Event create() {
return Event.builder().build();
}
protected Event(String id, String name, Serializable data);
protected Event(String id, String name);
protected Event(Builder builder);
protected Event();
protected static Builder builder();
public static Builder id... | Event event = Event.create();
assertThat(event).isNotNull();
}
} |
98080471_0 | class DataSourceController {
@RequestMapping(method = RequestMethod.PUT)
@ResponseBody
public GetDatasourceResponse put(@PathVariable("tenant") String tenantId,
@PathVariable("datasource") String dataSourceId,
@RequestParam(value = "validate", required = false) Boolean validate,
... | final String tenant = name.getMethodName();
tenantRegistry.createTenantContext(tenant);
final RestDataSourceDefinition dataSourceDefinition = new RestDataSourceDefinition();
dataSourceDefinition.setType("foo bar");
dataSourceDefinition.set("hello", "world");
final GetDa... |
98085592_14 | class OntologyTerms {
public static <O extends Ontology<?, ?>> Set<TermId> parentsOf(TermId termId, O ontology) {
Set<TermId> result = new HashSet<>();
visitParentsOf(termId, ontology, new TermVisitor<O>() {
@Override
public boolean visit(O ontology, TermId termId) {
result.add(termId);
... | assertEquals(
"[ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000004], ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000007], ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000001], ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000002]]",
Ontolo... |
98171786_53 | class AttributesExtractor {
static Map<String, String> getMetaAttributes(Class<?> clazz) {
requireNonNull(clazz, "clazz cannot be null");
return attributesByTypeCache.computeIfAbsent(clazz, c -> getMetaAttributes(getAnnotations(c)));
}
private AttributesExtractor();
static Map<String... | // when
Map<String, String> attributes = getMetaAttributes(getMethod(CustomizableValueUsage.class, "customizableOnly"));
// then
assertThat(attributes).containsOnly(
entry("name", "method-level")
);
}
} |
98175571_291 | class ParametersHooksO {
public void showTimeFields(final ViewDefinitionState view) {
orderService.changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM, DELAYED_EFFECTIVE_DATE_FROM_TIME);
orderService.changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM, EARLIER_EF... | // given
// when
parametersHooksO.showTimeFields(view);
// then
verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM,
DELAYED_EFFECTIVE_DATE_FROM_TIME);
verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_... |
98184950_2 | class Sha1Digest implements MessageDigest {
public void save(String source) throws IOException {
final String digest = calculate(source);
final File file = new File(source + "." + HASH_NAME);
if (file.exists()) {
if (!file.delete()) {
throw new IOException("Una... | Sha1Digest sha1Digest = new Sha1Digest();
sha1Digest.save(MESSAGE_FILE);
sha1Digest.verify(MESSAGE_FILE);
}
} |
98396630_0 | class SnackbarAdapter extends RecyclerView.Adapter<SnackbarAdapter.ViewHolder> {
public boolean isEmpty() {
return mSnackbarViews == null || mSnackbarViews.size() == 0;
}
@Override public ViewHolder onCreateViewHolder(ViewGroup parent, int position);
@Override public void onBindViewHolder(View... | Assert.assertTrue(mAdapter.isEmpty());
}
} |
98410891_42 | class ThreadPoolKiller {
public static void shutdown(ExecutorService threadPool, String name) {
shutdown(threadPool, name, DEFAULT_WAIT_DOWN_SECONDS);
}
public static void shutdown(ExecutorService threadPool, String name, long waitSeconds);
}
class ThreadPoolKillerTest {
@Test
public void testCleanSh... | final int wait = 1;
ExecutorService threadPool = mock(ExecutorService.class);
when(threadPool.awaitTermination(wait, TimeUnit.SECONDS)).thenReturn(true);
ThreadPoolKiller.shutdown(threadPool, "TestPool", wait);
verify(threadPool).shutdown();
verify(threadPool).awaitTermination(wait, TimeUnit.SEC... |
98480042_5 | class MetaClient {
public MetaProto.StringListType listDatabases()
{
MetaProto.NoneType none = MetaProto.NoneType.newBuilder().build();
MetaProto.StringListType stringList;
try {
stringList = metaBlockingStub.listDatabases(none);
}
catch (StatusRuntimeExcepti... | MetaProto.StringListType expect = MetaProto.StringListType.newBuilder().addStr("test").addStr("regular").build();
MetaProto.StringListType stringList = client.listDatabases();
assertEquals(expect, stringList);
}
} |
98490554_6 | class RetryerBuilder {
public RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass) {
Preconditions.checkNotNull(exceptionClass, "exceptionClass may not be null");
rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate<V>(exceptionClass));
... | Callable<Boolean> callable = noIOExceptionAfter5Attempts();
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
.retryIfExceptionOfType(IOException.class)
.build();
assertTrue(retryer.call(callable));
callable = noIllegalStateExceptionAfter5At... |
98639195_9 | class FixDoubles {
static Object fix(Object orig) {
if (orig instanceof List) {
final List<?> list = MappingContext.cast(orig);
final List<Object> copy = new ArrayList<>(list.size());
for (Object obj : list) {
copy.add(fix(obj));
}
return copy;
} else if (orig instanceof... | assertEquals(Arrays.asList(8_000_000_000L), FixDoubles.fix(Arrays.asList(8_000_000_000.0)));
}
} |
98709134_1 | class HttpDateHeaderFormatUtil {
public static String nowAsHttpDateString() {
return timeAsHttpDateString(ZonedDateTime.now(ZoneId.of("GMT")));
}
public static String timeAsHttpDateString(ZonedDateTime gmtTime);
}
class HttpDateHeaderFormatUtilTest {
@Test
public void shouldFormatDateNow() {
| Assert.assertNotNull((HttpDateHeaderFormatUtil.nowAsHttpDateString()));
}
} |
98801926_32 | class BcCryptWorkFactorService {
int getStrength(long previousDuration, long currentDuration, int strength) {
if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) {
return strength - 1;
} else {
return strength;
}
}
public BcryptWorkFactor calculateStrengthDivideAndConq... | // given
// when
int actual = bcCryptWorkFactorService.getStrength(960, 1021, 5);
// then
assertThat(actual).isEqualTo(5);
}
} |
98805906_15 | class Logger {
private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) {
Objects.requireNonNull(level, "LogLevel must not be null.");
switch (level) {
case TRACE:
return logger.isTraceEnabled();
case DEBUG:
return logger.isDebugEnab... | LoggingSystem.get(ClassLoader.getSystemClassLoader())
.setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.INFO);
assertTrue(logger.isEnabled(LogLevel.INFO, "logger name"));
}
} |
98876601_2 | class OCPSUtils {
@Deprecated
public static long[] toLongArray(List<Long> ls) {
long[] output = new long[ls.size()];
int i = 0;
for (Long l : ls) {
output[i] = l;
i++;
}
return output;
}
@Deprecated public static String[] toStringArray(List<String> ls);
}
class OCPSUtilsTest {
@Test
public... | List<Long> inputArr = new ArrayList<>();
inputArr.add(12L);
inputArr.add(13L);
inputArr.add(14L);
long[] outputArr = OCPSUtils.toLongArray(inputArr);
long[] expectedOutputArr = {12L, 13L, 14L};
Assert.assertArrayEquals(outputArr, expectedOutputArr);
}
} |
98885701_0 | class CDICommandBus implements CommandBus {
@Override
public <R, C extends Command<R>> R execute(C command) {
CommandHandler<R, C> commandHandler = (CommandHandler<R, C>) registry.get(command.getClass());
return commandHandler.handle(command);
}
@Inject public CDICommandBus(Registry registry);
@Mo... | when(registry.get(HelloCommand.class)).thenReturn(handler);
HelloCommand command = new HelloCommand("joe");
commandBus.execute(command);
verify(handler).handle(command);
}
} |
98887914_2 | class SoundViewModel extends BaseObservable {
@Bindable
public String getTitle() {
return mSound.getName();
}
public SoundViewModel(BeatBox beatBox);
public Sound getSound();
public void setSound(Sound sound);
public void onButtonClicked();
private BeatBox mBeatBox;
priv... | assertThat(mSubject.getTitle(), is(mSound.getName()));
}
} |
99030958_0 | class AvroSchemaIterator implements Iterable<Schema>,
Iterator<Schema> {
@Override
public Iterator<Schema> iterator() {
return this;
}
public AvroSchemaIterator(Schema rootSchema);
@Override public boolean hasNext();
@Override public Schema next();
private static List<Schema> getChildNodes... | Schema sample = AvroSchemaGeneratorTest.getSampleSchema();
boolean baseSeen = false, recursiveSeen = false, compositeSeen = false,
arraySeen = false, mapSeen = false;
for (Schema schema : new AvroSchemaIterator(sample)) {
if (schema.getName().equals("SampleBaseType")) {
baseSeen = ... |
99161825_30 | class DebugWebViewClientLogger implements LogControl {
public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) {
if (loggingEnabled) {
logger.logError(String.format(LOCALE, "%s onTooManyRedirects()", SPACE));
}
}
public DebugWebViewClientLogger();
... | final Message cancelMsg = Mockito.mock(Message.class);
final Message continueMsg = Mockito.mock(Message.class);
logger.setLoggingEnabled(false);
logger.onTooManyRedirects(webView, cancelMsg, continueMsg);
verifyLogNotCalled();
logger.setLoggingEnabled(true);
log... |
99244131_2 | class InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware {
@Override
protected boolean internalCancel(String appName, String id, boolean isReplication) {
handleCancelation(appName, id, isReplication);
return super.internalCancel(appName, id, isReplication);
}
public Ins... | // calling tested method
instanceRegistry.internalCancel(APP_NAME, HOST_NAME, false);
// event of proper type is registered
assertEquals(1, this.testEvents.applicationEvents.size());
assertTrue(this.testEvents.applicationEvents.get(0) instanceof EurekaInstanceCanceledEvent);
// event details are correct
f... |
99313507_1 | class MigrateUtils {
public static SortedMap<String, List<MigrateTask>> balanceExpand(List<List<NodeIndexRange>> integerListMap, List<String> oldDataNodes, List<String> newDataNodes, int slotsTotalNum) {
int newNodeSize = oldDataNodes.size() + newDataNodes.size();
int newSlotPerNode = slotsTotalNum... | List<List<NodeIndexRange>> integerListMap = new ArrayList<>();
integerListMap.add(Lists.newArrayList(new NodeIndexRange(0, 0, 32)));
integerListMap.add(Lists.newArrayList(new NodeIndexRange(1, 33, 65)));
integerListMap.add(Lists.newArrayList(new NodeIndexRange(2, 66, 99)));
int t... |
99413042_0 | class EmailSender {
void sendEmail(String to, String from, String title, String content) {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setTo(to);
mail.setFrom(from);
mail.setSubject(title);
mail.setText(content);
javaMailSender.send(mail);
}
Ema... | // Given
String to = "test@codecouple.pl";
String from = "blog@codecouple.pl";
String title = "Title";
String content = "Content";
// When
emailSender.sendEmail(to, from, title, content);
// Then
MimeMessage[] receivedMessages = server.getReceivedM... |
99449332_6 | class OAuthClientConfiguration {
public Uri getRedirectUri() {
return mRedirectUri;
}
@VisibleForTesting OAuthClientConfiguration(
final Context context,
final SharedPreferences prefs,
final InputStream configurationStream);
@AnyThread public static OAuthC... | assertThat(sut.getRedirectUri()).isEqualTo(
Uri.parse("com.okta.appauth.android.test:/oauth2redirect"));
}
} |
99486588_8 | class GesturePane extends Control implements GesturePaneOps {
@Override
public void centreOn(Point2D pointOnTarget) {
// move to centre point and apply scale
Point2D delta = pointOnTarget.subtract(targetPointAtViewportCentre());
translateBy(new Dimension2D(delta.getX(), delta.getY()));
}
public GesturePane... | final double zoom = 2d;
final double dx = 300d;
final double dy = 200d;
pane.setScrollBarPolicy(ScrollBarPolicy.NEVER);
pane.zoomTo(zoom, pane.targetPointAtViewportCentre());
final Transform last = target.captureTransform();
pane.centreOn(new Point2D(dx, dy));
final Transform now = target.captureTransfo... |
99686575_3 | class BookResource {
@PUT
@Path("/{id : \\d+}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Update a Book", response = Book.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "The book is updated"),
@ApiResponse(code = 400, messa... | final Book book = new Book("Joshua Bloch", "Effective Java (3rd Edition)", 2018, "Tech", " 978-0-1346-8599-1");
final Response response = webTarget.path("{id}")
.resolveTemplate("id", 1)
.request()
... |
99695762_5 | class SecKillRecoveryService {
public SecKillRecoveryCheckResult<T> check(PromotionEntity promotion) {
List<EventEntity> entities = this.repository.findByPromotionId(promotion.getPromotionId());
if (!entities.isEmpty()) {
long count = entities.stream()
.filter(event -> SecKillEventType.Coupon... | SecKillRecoveryCheckResult<String> result = recoveryService.check(runningPromotion);
assertThat(result.isStarted(), is(true));
assertThat(result.isFinished(), is(false));
assertThat(result.remainingCoupons(), is(runningPromotion.getNumberOfCoupons() - 1));
assertThat(result.getClaimedCustomers(), co... |
99742967_18 | class DimensionMapper {
public List<Dimension> getDimensions(final Metric metric, final MetricRecorder.RecorderContext context)
{
//Flattening the context hierarchy here allows this dimension mapper to work with multiple cloudwatch
//recorders. If a recorder wants to precompute the flattened hi... | String childId = UUID.randomUUID().toString();
MetricRecorder.RecorderContext context = new MetricRecorder.RecorderContext(ContextData.withId(ID)
.add(StandardContext.SERVICE, SERVICE_NAME)
.build());
MetricRecorder.Rec... |
99851447_1 | class DocHighlighter {
protected void highlightSingleFieldValue(String field, String s,
Set<HighlightingQuery> highlightingQueries,
Analyzer analyzer,
AtomicBoolean anythingHighlig... | String s = "the quick brown fox as well as some other fox and quick";
SpanQuery spanQuery = new SpanOrQuery(foxQuick, foxAs);
Analyzer analyzer = new WhitespaceAnalyzer();
ContentHandler handler = new ToHTMLContentHandler();
RhapsodeXHTMLHandler xhtml = new RhapsodeXHTMLHandler(... |
100021742_27 | class ListenerContainerFactory {
public AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName) {
DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer();
listenerContainer.setConnectionFactory(connectionFactory);
listen... | ListenerContainerFactory factory = new ListenerContainerFactory(mockConnectionFactory);
AbstractMessageListenerContainer container = factory.getListenerContainer("testTopic", "testSubscription");
assertThat(container.getConnectionFactory()).isEqualTo(mockConnectionFactory);
assertThat(co... |
100077276_0 | class LookupEngine {
public String fetchDOI(String input) {
//From grobid
// Pattern DOIPattern = Pattern.compile("(10\\.\\d{4,5}\\/[\\S]+[^;,.\\s])");
Matcher doiMatcher = DOIPattern.matcher(input);
while (doiMatcher.find()) {
if (doiMatcher.groupCount() == 1) {
... | String input = "{\"reference-count\":176,\"publisher\":\"IOP Publishing\",\"issue\":\"4\",\"content-domain\":{\"domain\":[],\"crossmark-restriction\":false},\"short-container-title\":[\"Russ. Chem. Rev.\"],\"published-print\":{\"date-parts\":[[1998,4,30]]},\"DOI\":\"10.1070/rc1998v067n04abeh000372\",\"type\":\"... |
100086904_0 | class SupplyLocationBulkUploadController {
public List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations) {
return this.service.saveSupplyLocationsZipContains504(locations);
}
@Autowired public SupplyLocationBulkUploadController(SupplyLocationRepository repository);
@Auto... | List<SupplyLocation> locations = new ArrayList<>();
locations.add(generateSupplyLocations(4, 4, "504"));
when(service.saveSupplyLocationsZipContains504(inputLocations)).thenReturn(locations);
assertThat(controller.uploadFitleredLocations(inputLocations)).size().isEqualTo(1);
ass... |
100135378_9 | class JacksonPropertyScanner implements PropertyScanner {
@Override
public List<Property> getProperties(Type type) {
return getJacksonProperties(type).stream()
.filter(JacksonPropertyScanner::isReadable)
.map(this::conver... | assertTrue(scanner.getProperties(int.class).isEmpty());
}
} |
100262257_3 | class OptimizedBubbleSort {
public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) {
if (array == null) {
return 0;
}
int counter = 0;
//make sure we enter into first loop of the "while"
boolean swapped = true;
int lastSwap = array... |
String[] array = {"d", "a", "c", "b"};
sorter.sort(array, new StringComparator(), false);
assertEquals("a", array[0]);
assertEquals("b", array[1]);
assertEquals("c", array[2]);
assertEquals("d", array[3]);
}
} |
100280380_0 | class AxonDBEventStore extends AbstractEventStore {
@Override
public TrackingEventStream openStream(TrackingToken trackingToken) {
return storageEngine().openStream(trackingToken);
}
public AxonDBEventStore(AxonDBConfiguration configuration, Serializer serializer);
public AxonDBEventStor... | UnitOfWork<Message<?>> uow = DefaultUnitOfWork.startAndGet(null);
testSubject.publish(GenericEventMessage.asEventMessage("Test1"),
GenericEventMessage.asEventMessage("Test2"),
GenericEventMessage.asEventMessage("Test3"));
uow.commit();
... |
100295611_13 | class CollectionHelper {
@SafeVarargs
@Nullable
public static <T> List<T> toList(@Nullable T... arguments) {
if (arguments != null) {
if (arguments.length == 1) {
return Collections.singletonList(arguments[0]);
}
if (arguments.length > 1) {
return Arrays.asList(arguments);
}
}
return null... | assertThat(CollectionHelper.toList((List<String>) null)).isNull();
assertThat(CollectionHelper.toList(Arrays.asList(1))).isInstanceOf(List.class)
.containsExactly(1);
assertThat(CollectionHelper.toList(Arrays.asList(1, 2, 3)))
.isInstanceOf(List.class).containsExactly(1, 2, 3);
Set<Long> set = new Hash... |
100361171_9 | class ObservableWebSocketClient extends ObservableMessengerClient {
@NonNull
protected Intent getServiceIntent(String clientId) {
Intent intent = super.getServiceIntent(clientId);
intent.putExtra(KEY_CHANNEL_TYPE, CHANNEL_WEBSOCKET);
return intent;
}
public ObservableWebSocket... |
Intent bindIntent = observableWebSocketClient.getServiceIntent("7878");
assertThat(bindIntent).isNotNull();
assertThat(bindIntent.hasExtra(KEY_CHANNEL_TYPE)).isTrue();
assertThat(bindIntent.getStringExtra(KEY_CHANNEL_TYPE)).isEqualTo(CHANNEL_WEBSOCKET);
assertThat(bindIntent.ha... |
100388774_0 | class BaseHumanName extends BaseResource {
public String getDisplayName(){
List<String> names = Arrays.asList(getPrefix(), getGivenName(), getFamilyName(), getSuffix());
return names.stream().filter(Objects::nonNull).collect(Collectors.joining(" "));
}
public HumanName.NameUse getNameUse()... | BaseHumanName name = new BaseHumanName();
String displayName = name.getDisplayName();
assertThat(displayName, not(nullValue()));
assertThat(displayName, equalTo(""));
}
} |
100394036_2 | class AuthRepository {
@NonNull
public FirebaseAuthLiveData getFirebaseAuthLiveData() {
return firebaseAuthLiveData;
}
@Inject public AuthRepository(FirebaseAuthLiveData firebaseAuthLiveData);
@InjectMocks
private AuthRepository authRepository;
@Mock
private FirebaseAuthLiveD... | //Act
FirebaseAuthLiveData expectedData = authRepository.getFirebaseAuthLiveData();
//Assert
assertThat(expectedData, equalTo(firebaseAuthLiveData));
}
} |
100402355_74 | class SlowBrokerFinder implements MetricAnomalyFinder<BrokerEntity> {
@Override
public Collection<MetricAnomaly<BrokerEntity>> metricAnomalies(Map<BrokerEntity, ValuesAndExtrapolations> metricsHistoryByBroker,
Map<BrokerEntity, ValuesAndExtrapolation... | SlowBrokerFinder slowBrokerFinder = createSlowBrokerFinder();
Map<BrokerEntity, ValuesAndExtrapolations> history =
createHistory(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS),
populateMetricValues(NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARI... |
100407794_0 | class RichTextElementConverter {
public RichTextElement convert(RichTextElement orig) {
if (orig.getValue() == null) {
return orig;
}
orig.setValue(resolveLinks(orig));
orig.setValue(resolveLinkedItems(orig));
if (richTextElementResolver != null) {
or... | RichTextElementConverter converter = new RichTextElementConverter(
Link::getUrlSlug,
() -> "/404",
content -> content,
null,
null);
RichTextElement original = new RichTextElement();
original.setValue("<p>Each AeroPre... |
100417935_19 | class WatchDog extends DukesVerticle {
public WatchDog(Car car) throws Exception {
super(Characters.FLASH);
this.car = car;
Environment env = Config.getEnvironment();
HEARTBEAT_INTERVAL_MS=env.getInteger(Config.WATCHDOG_HEARTBEAT_INTERVAL_MS);
MAX_MISSED_BEATS=env.getInteger(Config.WATCHDOG_MAX_MISSED_BEAT... | ClusterStarter clusterStarter=new ClusterStarter();
// sideffect is to use dummy configuration
// which also effects watchdog
Car car=TestCar.getCar();
Environment env = Config.getEnvironment();
int heartBeatInterval=env.getInteger(Config.WATCHDOG_HEARTBEAT_INTERVAL_MS);
assertEquals(20,heartBeatInterval)... |
100418846_46 | class SplitJoinPermission extends Permission {
@Override
public void deserialize(Binder data, BiDeserializer deserializer) {
super.deserialize(data, deserializer);
initFromParams();
}
public SplitJoinPermission(Role role, Binder params);
private SplitJoinPermission();
protec... | Contract c = createCoin();
c.addSignerKeyFromFile(PRIVATE_KEY_PATH);
sealCheckTrace(c, true);
Contract c2 = c.split(1)[0];
sealCheckTrace(c2, true);
Binder sd2 = DefaultBiMapper.serialize(c2);
Binder state = (Binder) sd2.get("state");
assertNotNull(st... |
100470026_0 | class StandaloneBean {
public String returnMessage() {
return message;
}
private EJBContainer ec;
private Context ctx;
private static final Logger logger;
}
class StandaloneBeanTest {
private EJBContainer ec;
private Context ctx;
private static final Logger logger;
@Tes... | logger.info("Testing standalone.ejb.StandaloneBean.returnMessage()");
StandaloneBean instance =
(StandaloneBean) ctx.lookup("java:global/classes/StandaloneBean");
String expResult = "Greetings!";
String result = instance.returnMessage();
assertEquals(expResult, r... |
100470837_4 | class MetalSearcher extends Searcher {
@Override
public Result search(Query query, Execution execution) {
QueryTree tree = query.getModel().getQueryTree();
if (isMetalQuery(tree)) {
OrItem orItem = new OrItem();
orItem.addItem(tree.getRoot());
orItem.addItem(... |
DocumentSourceSearcher docSource = new DocumentSourceSearcher();
Query testQuery = new Query();
testQuery.setTraceLevel(6);
testQuery.getModel().getQueryTree().setRoot(new WordItem("drum","album"));
Result mockResult = new Result(testQuery);
mockResult.hits().add(new Hi... |
100522769_15 | class Label {
@SuppressWarnings("PMD.ShortMethodName")
public static String of(Element element) {
return of(element.getClass());
}
private Label();
@SuppressWarnings("PMD.ShortMethodName") public static String of(Class<? extends Element> elementType);
}
class LabelTest {
@Test
public void test... | assertEquals("develops", of(Develops.class));
assertEquals("develops", of(develops));
}
} |
100544309_2 | class CounterViewModel extends BaseObservable {
public void decrement() {
setCount(getCount() - 1);
}
public void increment();
@Bindable public int getCount();
private void setCount(int count);
private CounterViewModel counterViewModel;
}
class CounterViewModelTest {
private Co... | for (int i = 1; i <= 5; i++) {
counterViewModel.decrement();
Assert.assertEquals(i * -1, counterViewModel.getCount());
}
}
} |
100566396_36 | class RegexUtil {
public String getMacthResult(String regex, String source, int index) {
return getMacthResult(regex,source,index,null);
}
private RegexUtil();
public static RegexUtil getInstance();
public List<String> getMacthAllResult(String regex, String source, int index);
public... |
String exected = "uuid_tt_dd=1449951587432284316_20171009; bdshare_firstime=1507526697430; _JQCMT_ifcookie=1; _JQCMT_browser=9b9bfcf50ae6c14645788efed25613f9; UN=weixin_38032099; UE=\\\"\\\"; BT=1509089267060; ADHOC_MEMBERSHIP_CLIENT_ID1.0=f4889c67-3d52-6eb3-6cb4-e7a329d9b3c5; Hm_ct_6bcd52f51e9b3dce32bec4a3997... |
100677440_5 | class TrafficDensity2 {
private CountByLane countByLane(int lanesNumber, double[] speedLimit, double speed){
for(int i = 1; i <= lanesNumber; i++){
if(speed <= speedLimit[i - 1]){
return new CountByLane(1, i);
}
}
return new CountByLane(1, lanesNumber... | int[] count ={0};
double[] speeds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
TrafficDensity2 trafficDensity = new TrafficDensity2(){
@Override
protected double calcSpeed(Vehicle vehicle, double traction, double timeSec) {
return speeds[count[0]++];
... |
100683024_676 | class LdifRevertor {
public static List<LdifEntry> reverseRename( Entry entry, Rdn newRdn, boolean deleteOldRdn )
throws LdapInvalidDnException
{
return reverseMoveAndRename( entry, null, newRdn, deleteOldRdn );
}
private LdifRevertor();
public static LdifEntry reverseAdd( Dn dn ... | Dn dn = new Dn( "cn=test,ou=system" );
Rdn oldRdn = new Rdn( "cn=test" );
Rdn newRdn = new Rdn( "cn=joe+sn=small" );
Entry entry = new DefaultEntry( dn,
"objectClass: top",
"objectClass: person",
"cn: test",
"sn: small",
"sn: t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.