id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
162657830_5 | class Strings {
public static String repeat(char value, int n) {
return new String(new char[n]).replace("\0", String.valueOf(value));
}
public static String zeros(int n);
public static boolean isEmpty(String s);
}
class StringsTest {
@Test
public void testRepeat() {
| Assertions.assertEquals(repeat('0', 0), "");
Assertions.assertEquals(repeat('1', 3), "111");
}
} |
162700032_23 | class NetworkingModule extends ReactContextBaseJavaModule {
@ReactMethod
/**
* @param timeout value of 0 results in no timeout
*/
public void sendRequest(
String method,
String url,
final int requestId,
ReadableArray headers,
ReadableMap data,
final String responseType,
... | RCTDeviceEventEmitter emitter = mock(RCTDeviceEventEmitter.class);
ReactApplicationContext context = mock(ReactApplicationContext.class);
when(context.getJSModule(any(Class.class))).thenReturn(emitter);
OkHttpClient httpClient = mock(OkHttpClient.class);
OkHttpClient.Builder clientBuilder = mock(Ok... |
162806930_1 | class StringUtils {
@Nonnull
@MustNotContainNull
public static List<String> extractJdepsModuleNames(@Nonnull final String text) {
final List<String> result = new ArrayList<>();
for (final String line : text.split("\\n")) {
final Matcher lineMatcher = PATTERN_MODULE_LINE.matcher(line);
if (lin... | final String text = IOUtils.resourceToString("jmods.out", StandardCharsets.UTF_8, StringUtilsTest.class.getClassLoader());
final List<String> modules = StringUtils.extractJdepsModuleNames(text);
assertArrayEquals(
new String[] {
"java.base",
"java.compiler",
"java... |
162897877_8 | class ByteSequenceMap implements SequenceMap<ByteBuffer> {
public void put(final ByteBuffer value, final long id)
{
if (value.remaining() > maxKeyLength)
{
throw new IllegalArgumentException("Key too long");
}
if (liveEntryCount > entryCountToTriggerRehash)
{... | map.put(SEARCH_TERM, ID);
assertSearchResult(map, SEARCH_TERM, ID);
}
} |
162913798_8 | class Plain implements Formatted {
@Override
public Text formatted() {
return this.glossary.definitions()
.sorted()
.map(Definition::text)
// @checkstyle BracketsStructure (3 lines)
.reduce((formatted, definition) -> new Joined(
new TextOf... | Assertions.assertThat(
new Plain(
new EmptyGlossary()
).formatted()
).isEqualTo(
new TextOf("No definitions found.")
);
}
} |
162933940_1 | class MathUtils {
public static double average(double[] nums) {
if(nums.length == 0) {
return 0;
}
double sum = 0;
for(int i = 0; i < nums.length; i++) {
sum += nums[i];
}
return sum/nums.length;
}
private MathUtils();
public st... | assertEquals(6, MathUtils.average(6.0), 0.0001);
assertEquals(6, MathUtils.average(5.0, 7.0), 0.0001);
assertEquals(-6.0, MathUtils.average(-6.0), 0.0001);
assertEquals(-6, MathUtils.average(-5.0, -7.0), 0.0001);
assertEquals(0, MathUtils.average(0.0), 0.0001);
assertEqua... |
163078506_3 | class Functions {
public static HKDFKeys hkdf_expand(
BytesValue srcNodeId,
BytesValue destNodeId,
BytesValue srcPrivKey,
BytesValue destPubKey,
BytesValue idNonce) {
BytesValue keyAgreement = deriveECDHKeyAgreement(srcPrivKey, destPubKey);
return hkdf_expand(srcNodeId, destNode... | BytesValue idNonce =
Bytes32.fromHexString("68b02a985ecb99cc2d10cf188879d93ae7684c4f4707770017b078c6497c5a5d");
Functions.HKDFKeys keys1 =
Functions.hkdf_expand(
nodeId1,
nodeId2,
testKey1,
BytesValue.wrap(ECKeyPair.create(testKey2.extractArray()).... |
163079637_162 | class DateUtil extends AbstractCaller {
@Description("Returns the current date/time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware).<br/>"
+ "If modified date time is on weekend and <code>skipWeekends</code> is <code>true</code> then the next working day... | for (int hoursDiff = -1; hoursDiff <= 1; hoursDiff += 1) {
for (int minutsDiff = -10; minutsDiff <= 10; minutsDiff += 10) {
long defaultOffsetSeconds = TimeUnit.HOURS.toSeconds(3);
long offsetSeconds = defaultOffsetSeconds + TimeUnit.HOURS.toSeconds(hoursDiff) + Tim... |
163147839_94 | class ConfigurationStore implements Serializable {
public short getShort(String key, short defaultValue, String description,
ItemConstraint constraint)
throws NumberFormatException {
Objects.requireNonNull(key, "key is null");
ConfigurationItem configItem = configurationItems.ge... | short value = 2;
short result = store.getShort("testKeyshort", value);
assertEquals(result, value);
}
} |
163179422_1 | class Identifiers {
public static Identifier withPath(Identifier base, String path) {
return transformer(base).path(path).apply();
}
private Identifiers();
public static Identifier withNamespace(Identifier base, String namespace);
public static Identifier prefixPath(Identifier base, String prefix);
public s... | Identifier base = new Identifier("foo:baz/qux");
assertEquals(new Identifier("foo:bar"), Identifiers.withPath(base, "bar"));
assertEquals(new Identifier("foo:bar/baz"), Identifiers.withPath(base, "bar/baz"),
"Multilevel path test failed");
}
} |
163244687_111 | class MixAll {
public static boolean compareAndIncreaseOnly(final AtomicLong target, final long value) {
long prev = target.get();
while (value > prev) {
boolean updated = target.compareAndSet(prev, value);
if (updated)
return true;
prev = target... | AtomicLong target = new AtomicLong(5);
assertThat(MixAll.compareAndIncreaseOnly(target, 6)).isTrue();
assertThat(target.get()).isEqualTo(6);
assertThat(MixAll.compareAndIncreaseOnly(target, 4)).isFalse();
assertThat(target.get()).isEqualTo(6);
}
} |
163387337_170 | class PreparedStatementProxy extends AbstractPreparedStatementProxy implements PreparedStatement, ParametersHolder {
@Override
public Map<Integer,ArrayList<Object>> getParameters() {
return parameters;
}
public PreparedStatementProxy(AbstractConnectionProxy connectionProxy, PreparedStatement ... | preparedStatementProxy.clearParameters();
preparedStatementProxy.setNull(1, JDBCType.DECIMAL.getVendorTypeNumber());
Assertions.assertEquals(Null.get(), preparedStatementProxy.getParamsByIndex(1).get(0));
preparedStatementProxy.clearParameters();
preparedStatementProxy.setNull(1... |
163399836_3 | class HBaseClient {
public static HBaseClient getInstance() {
if (instance == null) {
synchronized (HBaseClient.class) {
if (instance == null) {
instance = new HBaseClient();
}
}
}
return instance;
}
privat... | HBaseClient client = HBaseClient.getInstance();
Assert.assertNotNull(client);
}
} |
163474295_49 | class ApiArticleController {
@ApiOperation(value = "根据标签id查询文章", notes = "根据标签id查询文章")
@GetMapping("/tag/{tagId}")
public JsonData<Page<ArticleDto>> findArticleByTagId(@PathVariable String tagId,
@PageableDefault(sort = "create_at", direction = DESC) Pageable pa... | when(articleService.findArticleByTagId(anyString(), any())).thenReturn(null);
JsonData<Page<ArticleDto>> result = apiArticleController.findArticleByTagId("tagId", null);
Assertions.assertEquals(new JsonData<Page<ArticleDto>>(true, 0, "message", any()), result);
}
} |
163514144_9 | class TypeUtils {
@Nullable
public static ArgType replaceClassGenerics(RootNode root, ArgType instanceType, ArgType typeWithGeneric) {
if (typeWithGeneric == null) {
return null;
}
if (instanceType.isGeneric()) {
List<GenericInfo> generics = root.getClassGenerics(instanceType);
if (generics.isEmpty())... | // check classpath graph
List<GenericInfo> classGenerics = root.getClassGenerics(ArgType.object("java.util.ArrayList"));
assertThat(classGenerics, hasSize(1));
GenericInfo genericInfo = classGenerics.get(0);
assertThat(genericInfo.getGenericType(), is(ArgType.genericType("E")));
assertThat(genericInfo.getEx... |
163566292_1 | class DocumentRegistry {
@Nullable
public SwaggerV2Documentation get(String serviceName) {
return storage.get(serviceName);
}
public static DocumentRegistry getInstance();
public void put(String serviceName, SwaggerV2Documentation swaggerV2Documentation);
}
class DocumentRegistryTest {
... | SwaggerV2Documentation swaggerV2Documentation = Mockito.mock(SwaggerV2Documentation.class);
DocumentRegistry.getInstance().put("foo", swaggerV2Documentation);
assertEquals(swaggerV2Documentation, DocumentRegistry.getInstance().get("foo"));
}
} |
163648692_206 | class AccessRightService {
@PreAuthorize("hasAuthority('VIEW_CLIENT_ACL_SUBJECTS')")
public List<AccessRightHolderDto> findAccessRightHolders(ClientId clientId, String memberNameOrGroupDescription,
XRoadObjectType subjectType, String instance, String memberClass, String memberGroupCode,
... | public void findAccessRightHoldersByInstance() throws Throwable {
List<AccessRightHolderDto> dtos = accessRightService.findAccessRightHolders(TestUtils.getM1Ss1ClientId(), null,
null, TestUtils.INSTANCE_EE, null, null, null);
assertEquals(4, dtos.size());
}
} |
163652398_6 | class GenericGermanyKnxProjectCharacteristics extends KnxProjectCharacteristics {
@Override
public boolean isPrimarySwitch(GroupAddress ga) {
// pre-select based on super
boolean isPotentialPrimary = super.isPrimarySwitch(ga);
if (!isPotentialPrimary) {
LOG.debug("Not a primary switch GA due to DPT mismatch... | assertTrue(characteristics.isPrimarySwitch(gaWithName("Licht Küche Ein/Aus")));
assertFalse(characteristics.isPrimarySwitch(gaWithName("Licht Küche Status Ein/Aus")));
assertFalse(characteristics.isPrimarySwitch(gaWithName("Rückmeldungen Schalten Licht")));
}
} |
163711177_0 | class StringUtil {
public static String format(String format, Object... arguments) {
return MessageFormatter.arrayFormat(format, arguments).getMessage();
}
public static String randomString(int length);
}
class StringUtilTest {
@Test
public void format() {
| String a = "A";
String placeholder = "{}";
String b = "B";
String c = "C";
assertEquals(a + b + c, StringUtil.format(a + placeholder + c, b));
}
} |
163795687_31 | class RedisStorage implements IStorage {
@Override
public long getSequenceNumber() throws Exception {
return redisService.increaseAndGet(key("/sequence"), 1);
}
private Closeable lockStrategyRuntime(String strategyName);
private Closeable lockFactory();
private Closeable lockTask(Strin... | long s0 = this.storage.getSequenceNumber();
long s1 = this.storage.getSequenceNumber();
assertTrue(s0 < s1);
}
} |
163808152_100 | class RouterFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
// 如果是 fetch 请求,则不做任何处理
if(RequestUtil.isFetch(httpServletR... | RouterFilter routerFilter = new RouterFilter();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/src/a.js");
request.setServletPath("/src/a.js");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain() {
@Override
public voi... |
163840922_7 | class TabDelimitedCertificateFilter extends QwacCertificateFilter {
@Override
public String getEncodedTppQwacCert(HttpServletRequest httpRequest) {
if (httpRequest.getHeader(HEADER_NAME) == null) {
return null;
}
String certificateWithTabs = httpRequest.getHeader(HEADER_NAME);
return certifi... | HttpServletRequest mock = Mockito.mock(HttpServletRequest.class);
Mockito.when(mock.getHeader(Mockito.anyString())).thenReturn("string\twith\ttabs");
String stringWithoutTabs = tabDelimitedCertificateFilter.getEncodedTppQwacCert(mock);
assertEquals("stringwithtabs", stringWithoutTabs);
}
} |
164034455_1 | class RandomUtils {
public static boolean getTrueWithProbability(double probability) {
probability *= 100;
int randomProbability = ThreadLocalRandom.current().nextInt(0, 100);
return probability > randomProbability;
}
public static void waitRandom(long minSeconds, long maxSeconds);
public static v... |
//given
double probability = 1.0;
//when
boolean output = RandomUtils.getTrueWithProbability(probability);
//then
assertTrue(output);
}
} |
164079951_0 | class DepartmentController {
@GetMapping("/departments")
public List<Department> departments() {
return this.departmentDao.findAll();
}
public DepartmentController(DSLContext dsl, Configuration jooqConfiguration);
@GetMapping("/department/{no}") public Department findDepartment(@PathVariable("no") Str... | var typeRef = new ParameterizedTypeReference<List<Department>>() {
// nothing_here
};
var response = this.restTemplate.exchange("/departments", HttpMethod.GET, null,
typeRef);
List<Department> departments = response.getBody();
assertThat(departments.get(0).getId()).isEqualTo(1);
... |
164098851_3 | class TodoController {
@ApiOperation(value = "Retrieve all todos for a user by passing in his name", notes = "A list of matching todos is returned. Currently pagination is not supported.", response = Todo.class, responseContainer = "List", produces = "application/json")
@GetMapping("/users/{name}/todos")
public Lis... | List<Todo> mockList = Arrays.asList(new Todo(1, "Jack", "Learn Spring MVC", new Date(), false),
new Todo(2, "Jack", "Learn Struts", new Date(), false));
when(service.retrieveTodos(anyString())).thenReturn(mockList);
MvcResult result = mvc
.perform(MockMvcRequestBuilders.get("/users/Jack/todos").accept(Med... |
164113249_6 | class AuthorizationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
FilterChain filterChain
) throws ServletException, IOExc... | when(request.getHeader(HEADER_NAME))
.thenReturn(null);
filter.doFilterInternal(request, response, filterChain);
verify(claims, times(0)).getSubject();
}
} |
164181730_0 | class FileProvider implements IPassive, ISeekableProvider, IPullableProvider, IPipeConnectionListener, IStreamTypeAwareProvider {
public IMessage pullMessage(IPipe pipe) throws IOException {
// there is no need for sync here, the readers use semaphore locks
if (this.pipe == pipe) {
if (... | // get dummy scope
WebScope scope = (WebScope) applicationContext.getBean("web.scope");
// test file fixture
File file = new File("target/test-classes/fixtures/test.flv");
// new file provider instance
FileProvider provider = new FileProvider(scope, file);
// data... |
164305542_22 | class ProtoToAvroSchema {
public static String convert(ProtoDomain pd, String messageName)
throws IOException, StatusRuntimeException {
Descriptors.Descriptor descriptor = pd.getDescriptorByName(messageName);
if (descriptor == null) {
throw Status.fromCode(Status.Code.NOT_FOUND)
.withDe... | String node = getJsonNode("testComplexExtEnum");
final DescriptorProtos.FileDescriptorProto fileDescriptorProto =
TestComplexExtEnum.getDescriptor().getFile().toProto();
ProtoDomain protoDomain = ProtoDomain.builder().add(fileDescriptorProto).build();
String avroSchema =
ProtoToAvroSch... |
164497122_3 | class RelationBuilder extends GeometryBuilder<Relation> {
public Geometry build(Relation entity) {
// Check whether the relation is a multipolygon
Map<String, String> tags = entity.getTags();
if (!"multipolygon".equals(tags.get("type"))) {
return null;
}
// Collect the members of the relat... | assertNull(RELATION_BUILDER.build(RELATION_0));
assertNull(RELATION_BUILDER.build(RELATION_1));
assertTrue(RELATION_BUILDER.build(RELATION_2) instanceof Polygon);
assertTrue(RELATION_BUILDER.build(RELATION_3) instanceof MultiPolygon);
assertTrue(RELATION_BUILDER.build(RELATION_4) instanceof MultiPol... |
164546163_13 | class ScanReadResult extends AbstractReadResult<T> {
@Override
protected Spliterator<T> spliterator() {
if (iterationStarted) {
throw new IllegalStateException("ScanReadResult can only be iterated once.");
}
iterationStarted = true;
return new ScanReadResultSpliterat... | Spliterator<Item> spliterator = build(initialRequest(), result(null)).spliterator().trySplit();
assertThat(spliterator).isNull();
}
} |
164875108_24 | class TracingProvider implements CorrelationDataProvider {
public TracingProvider(Tracer tracer) {
this.tracer = tracer;
}
public TracingProvider(Tracer tracer);
@Override public Map<String, ?> correlationDataFor(Message<?> message);
private MockTracer mockTracer;
}
class TracingProvi... | MockSpan span = mockTracer.buildSpan("test").start();
ScopeManager scopeManager = mockTracer.scopeManager();
try (final Scope ignored = scopeManager.activate(span)) {
Message<String> message = new GenericMessage<>("payload", MetaData.emptyInstance());
TracingProvider tra... |
164962081_1 | class AnalyziedResult {
public int getStatusCode() {
return statusCode;
}
public AnalyziedResult(Builder builder);
public TsdbHttpStatus getHttpStatus();
public String getContent();
public HttpResponse getHttpResponse();
@Override public String toString();
private HttpRespon... | // get
HttpGet request = new HttpGet("http://localhost:4242");
try {
response = httpAsyncClient.execute(request, null);
assertTrue(response.getStatusLine().getStatusCode() == 200);
} catch (InterruptedException e) {
e.printStackTrace();
} catch... |
164972617_10 | class SimpleReadWriteLock {
public synchronized boolean tryWriteLock() {
if (!isFree()) {
return false;
} else {
status = -1;
return true;
}
}
public synchronized boolean tryReadLock();
public synchronized void releaseReadLock();
public s... | SimpleReadWriteLock lock = new SimpleReadWriteLock();
assertEquals(true, lock.tryWriteLock());
assertEquals(false, lock.tryWriteLock());
}
} |
165007814_10 | class HttpClientDownloader extends AbstractDownloader {
@Override
public Page download(Request request, Task task) {
if (task == null || task.getSite() == null) {
throw new NullPointerException("task or site can not be null");
}
CloseableHttpResponse httpResponse = null;
... | HttpClientDownloader httpClientDownloader = new HttpClientDownloader();
Task task = Site.me().setDomain("localhost").setCycleRetryTimes(5).toTask();
Request request = new Request(PAGE_ALWAYS_NOT_EXISTS);
Page page = httpClientDownloader.download(request, task);
assertThat(page.is... |
165026546_174 | class ConflictDetectionResultConverter {
DiagnosisSet convertDiagnosisSet(int[] diagnosisSet) {
final List<DiagnosisElement> elements = Arrays.stream(diagnosisSet)
.mapToObj(this::convertDiagnosisElement)
.collect(Collectors.toList());
return new DiagnosisSet(elemen... | final TestModel expandedTestModel = mock(TestModel.class);
when(expandedTestModel.getForbiddenTupleLists()).thenReturn(Collections.emptyList());
when(expandedTestModel.getErrorTupleLists()).thenReturn(Arrays.asList(
new TupleList(10, new int[] {0}, Collections.singletonList(new i... |
165063056_1 | class DiagramHandler {
public Handler<RoutingContext> createPost(String serviceName) {
return routingContext -> {
try {
FileFormat fileFormat;
String diagramSource;
MIMEHeader contentType = routingContext.parsedHeaders().contentType();
if (contentType != null && contentType.... | DiagramHandler diagramHandler = new DiagramHandler(mockDiagramService(Lists.newArrayList(FileFormat.SVG), null));
MockDiagramRequest mockDiagramRequest = new MockDiagramRequest();
mockDiagramRequest.setMethod(HttpMethod.POST);
mockDiagramRequest.addAccept("text/html");
mockDiagramRequest.setContentT... |
165292138_11 | class SchedulerJobResource {
@GET
@Path("/{projectName}/{exploratoryName}/{computationalName}")
@Produces(MediaType.APPLICATION_JSON)
public Response fetchSchedulerJobForComputationalResource(@Auth UserInfo userInfo,
@PathParam("exploratoryName") String exploratoryName,
@PathParam... | when(schedulerJobService.fetchSchedulerJobForComputationalResource(anyString(), anyString(), anyString(), anyString()))
.thenReturn(getSchedulerJobDTO());
final Response response = resources.getJerseyTest()
.target("/infrastructure_provision/exploratory_environment/schedu... |
165543540_0 | class BonusService {
@Transactional
public void calculateBonus(Bonus bonus) {
if (bonusRepository.existsById(bonus.getId())) {
log.info("Bonus id {} already exists - ignored", bonus.getId());
} else {
bonusRepository.save(bonus);
}
}
@Autowired public BonusService(BonusRepository bonusRepository);
... | long countBefore = bonusRepository.count();
Bonus bonus = new Bonus(42L,
new Customer(23L, "Eberhard", "Wolff"),
new Date(0L), 42.0);
bonusService.calculateBonus(bonus);
assertThat(bonusRepository.count(), is(countBefore + 1));
assertThat(bonusRepository.findById(42L).get().getUpdated().getTime(), equ... |
165549674_5 | class Base64BinaryType extends PrimitiveType<byte[]> implements IPrimitiveType<byte[]>, IBaseHasExtensions, IElement, Externalizable {
@Override
public byte[] getValue() {
return myValue;
}
public Base64BinaryType();
public Base64BinaryType(byte[] theBytes);
public Base64BinaryType(String theValue)... | String v = "dGhpcyBpcyB2YWxpZCBiYXNlNjQ=";
Base64BinaryType b64 = new Base64BinaryType(v);
Assertions.assertNotNull(b64);
Assertions.assertNotNull(b64.getValue());
Assertions.assertEquals(v, b64.asStringValue());
}
} |
165671355_2 | class TurtleSoup {
public static double calculateHeadingToPoint(double currentHeading, int currentX, int currentY, int targetX,
int targetY) {
// throw new RuntimeException("implement me!");
if(currentX == targetX && currentY == targetY)
return 0.0;
double degreess = Math.atan2(targetY - currentY, targetX... | assertEquals(0.0, TurtleSoup.calculateHeadingToPoint(0.0, 0, 0, 0, 1), 0.001);
assertEquals(0.0, TurtleSoup.calculateHeadingToPoint(0.0, 0, 0, 0, 0), 0.001);
assertEquals(90.0, TurtleSoup.calculateHeadingToPoint(0.0, 0, 0, 1, 0), 0.001);
assertEquals(359.0, TurtleSoup.calculateHeadingToP... |
165758293_75 | class GlueMetastoreClientDelegate {
public org.apache.hadoop.hive.metastore.api.Partition getPartition(String dbName, String tblName, String partitionName)
throws TException {
checkArgument(StringUtils.isNotEmpty(dbName), "dbName cannot be null or empty");
checkArgument(StringUtils.isNotEmpty(tblName),... | when(glueClient.getPartition(any(GetPartitionRequest.class)))
.thenThrow(new EntityNotFoundException("Test exception: partition not found"));
metastoreClientDelegate.getPartition(testDb.getName(), testTbl.getName(), "testPart");
verify(glueClient, times(1)).getPartition(any(GetPartitionRequest.class))... |
165787430_1 | class FizzBuzzBazz {
public static ArrayList<Integer> fizzBuzzBazz(){
ArrayList<Integer> fizz = new ArrayList<Integer>();
int loopNumber;
System.out.println("Enter a whole number:");
//Create buffered reader in try catch so buffered reader auto closes.
try(BufferedReader rea... | ArrayList<Integer> fizzBuzzBazz = new ArrayList<Integer>();
ByteArrayInputStream in = new ByteArrayInputStream("a".getBytes());
System.setIn(in);
Exception e = assertThrows(NumberFormatException.class, () -> {FizzBuzzBazz.fizzBuzzBazz(); });
assertEquals("Error: Non-number entere... |
165861304_3 | class TwitterSocialQueryResult implements SocialQueryResult {
public static List<SocialMessage> translate(List<Status> statuses) {
if (statuses == null) {
return null;
}
List<SocialMessage> socialMessages = statuses.stream().map(status -> {
SocialMessage message = new SocialMessage(status.ge... | String text = "Hello";
Date date = new Date();
int retweetCount = 5;
String language = "EN";
boolean isRetweeted = true;
int id = 8;
Status someStatus = new MockStatus(text, isRetweeted, date, id, retweetCount, language);
List<SocialMessage> translate = TwitterSocialQueryResult.translat... |
165869297_0 | class CalcSoundex implements LevenshteinPhonetic {
@Override
public PhoneticWordDist getPhonetic(String word1, String word2) {
// return the distance
PhoneticWordDist phoneticWordDist = new PhoneticWordDist(word1, word2, null,null,-1) ;
try {
String phoneticWord1 = executeJavaStript(word1).toString();
St... | //File inputFile = new File("./data/dfFautePrediction.csv");
//File outputFile = new File("./data/dfFautePredictionSoundex.csv");
LevenshteinPhonetic calcSoundex = new CalcSoundex();
PhoneticWordDist phoneticWordDist = calcSoundex.getPhonetic("metphomie", "metformine");
assertEquals(phoneticWordDist.getPhonet... |
165964380_1 | class JsThunkFx implements JsThunk {
@Override
public <T> void setMember(Object scope, String member, T val)
{
JSObject jsObj = ((DomjnateJSObjectAccess)scope).__DomjnateGetJSObjectFromProxy();
jsObj.setMember(member, DomjnateFx.unwrapObject(val, this));
}
@Override public Object getConstru... | Fx.runBlankWebPageInFx((WebEngine engine) -> {
JSObject jsWin = (JSObject)engine.executeScript("window");
jsWin.setMember("fnobj", new Supplier<Integer>() {
@Override public Integer get()
{
return 9;
}});
Assert.assertEquals(9, jsWin.ev... |
165997095_1 | class ElasticsearchEvolution {
public static ElasticsearchEvolutionConfig configure() {
return new ElasticsearchEvolutionConfig();
}
public ElasticsearchEvolution(ElasticsearchEvolutionConfig elasticsearchEvolutionConfig,
RestHighLevelClient restHighLevelClient);... | String indexName = "es_evolution";
int historyMaxQuerySize = 6;
ElasticsearchEvolution underTest = ElasticsearchEvolution.configure()
.setLocations(singletonList("classpath:es/ElasticsearchEvolutionTest/migrate_OK"))
.setHistoryIndex(indexName)
.se... |
166023376_12 | class ReflectionUtils {
public Method getSetterMethodForField(final Class<?> fieldClass, final String fieldName, final Class<?> fieldType) {
final String cacheKey = "SetterMethod-" + fieldClass.getName() + '-' + fieldName;
return CACHE_MANAGER.getFromCache(cacheKey, Method.class).orElseGet(() -> {
... | // GIVEN
MutableToFoo mutableToFoo = createMutableToFoo(null);
Method idSetterMethod = underTest.getSetterMethodForField(MutableToFoo.class, LIST_FIELD_NAME, List.class);
// WHEN
ThrowingCallable actual = () ->
getMethod(underTest.getClass(), INVOKE_METHOD_NAME,... |
166116543_0 | class DefaultJwtService implements JwtService {
@Override
public Optional<String> getSubFromToken(String token) {
try {
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
return Optional.ofNullable(claimsJws.getBody().getSubject());
} catc... | Optional<String> optional = jwtService.getSubFromToken("123");
assertThat(optional.isPresent(), is(false));
}
} |
166249209_1 | class FileFeedbackWrapper {
public Optional<Double> getGlobalAverageForLine(int line) {
List<LineExecution> filteredHistory = getLatestVersionAttributeForLine(line, new ArrayList<>(), l -> l.getPerformance().getRequestProfileHistory(), p -> p.getProfileStartTimestamp());
OptionalDouble average = fi... | Optional<Double> globalAverageForLine = fileFeedbackWrapper.getGlobalAverageForLine(1);
Assert.assertTrue(globalAverageForLine.isPresent());
Assert.assertEquals(100.0, globalAverageForLine.get(), 0.0);
globalAverageForLine = fileFeedbackWrapper.getGlobalAverageForLine(4);
Asse... |
166365902_11 | class ObjectMapTool {
public static Float getFloat(Map param, String key) {
if (param == null || isEmpty(key)) {
return null;
}
Object v = param.get(key);
if (v == null) {
return null;
}
return parseFloat(v.toString());
}
public static Long parseLong(String input);
public static Double parseDoub... | Map<String, String> map = new HashMap<>();
map.put("float", "1.1");
assertEquals(Float.valueOf("1.1"), getFloat(map, "float"));
}
} |
166387176_29 | class Util {
public static <E> List<E> quotientList( final List<E> list, final int n, final int k ) {
if ( n <= 0 || k < 0 || k >= n ) {
throw new IllegalArgumentException( "n must be positive; k must be between 0 and n - 1" );
}
final int size = (list.size() + n - k - 1) / n;
... | List<String> beatles = Arrays.asList( "john", "paul", "george", "ringo" );
final List list0 = Util.quotientList( beatles, 3, 0 );
assertEquals( 2, list0.size() );
assertEquals( "john", list0.get( 0 ) );
assertEquals( "ringo", list0.get( 1 ) );
final List list1 = Util.quo... |
166396744_4 | class Message {
public static byte[] encrypt(byte[] decrypted, SecretKeySpec aes) throws InvalidKeyException, IllegalArgumentException {
final ByteBuffer output = ByteBuffer.allocate(NONCE_SIZE + decrypted.length + OVERHEAD);
final Cipher cipher;
try {
cipher = Cipher.getInstanc... | System.out.println("MessageTest.encrypting a message: " + vector);
final byte[] want = Helper.combine(vector.getBytes("nonce"), vector.getBytes("ciphertext"));
final byte[] test = Message.encrypt(vector.getBytes("plaintext"), vector.getBytes("key"));
System.out.println("decrypted:");
... |
166411274_1 | class ZooKeeperGroupMembershipHandler implements GroupMembershipHandler, AutoCloseable {
@Override
public void watchEvent(String eventId, EventCallback callback) {
try {
final String path = "/proxy/events";
final String eventpath = "/proxy/events/" + eventId;
LOG.in... | try (TestingServer testingServer = new TestingServer(2229, tmpDir.newFolder());) {
testingServer.start();
try (ZooKeeperGroupMembershipHandler peer1 = new ZooKeeperGroupMembershipHandler(testingServer.getConnectString(),
6000, false /*acl */, peerId1, Collections.EMPT... |
166515022_733 | class DecimalAverageAggregation extends SqlAggregationFunction {
@VisibleForTesting
public static BigDecimal average(LongDecimalWithOverflowAndLongState state, DecimalType type)
{
BigDecimal sum = new BigDecimal(Decimals.decodeUnscaledValue(state.getLongDecimal()), type.getScale());
BigDeci... | addToState(state, TWO.pow(126));
addToState(state, TWO.pow(126));
addToState(state, TWO.pow(125));
assertEquals(state.getOverflow(), 1);
assertEquals(state.getLongDecimal(), unscaledDecimal(TWO.pow(125)));
addToState(state, TWO.pow(126).negate());
addToState(sta... |
166629127_1 | class TurtleSoup {
public static int calculatePolygonSidesFromAngle(double angle) {
throw new RuntimeException("implement me!");
}
public static void drawSquare(Turtle turtle, int sideLength);
public static double calculateRegularPolygonAngle(int sides);
public static void drawRegularPolyg... | assertEquals(3, TurtleSoup.calculatePolygonSidesFromAngle(60.0));
assertEquals(7, TurtleSoup.calculatePolygonSidesFromAngle(128.57));
assertEquals(5, TurtleSoup.calculatePolygonSidesFromAngle(108.0));
}
} |
166637026_9 | class BucketWriter {
public synchronized void append(final Event event)
throws IOException, InterruptedException {
checkAndThrowInterruptedException();
// If idleFuture is not null, cancel it before we move forward to avoid a
// close call in the middle of the append.
if (idleFuture != null... | int maxBytes = 300;
MockHDFSWriter hdfsWriter = new MockHDFSWriter();
BucketWriter bucketWriter = new BucketWriter(
0, maxBytes, 0, 0, ctx, "/tmp", "file", "", ".tmp", null, null,
SequenceFile.CompressionType.NONE, hdfsWriter, timedRollerPool, proxy,
new SinkCounter("test-bucket-writ... |
166956579_6 | class ConsumeMediaTypeExpression extends AbstractMediaTypeExpression {
public final boolean match(MediaType contentType) {
boolean match = getMediaType().includes(contentType);
return (!isNegated() ? match : !match);
}
ConsumeMediaTypeExpression(String expression);
ConsumeMediaType... | ConsumeMediaTypeExpression expression = createExpression(MediaType.ALL_VALUE);
Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8));
expression = createExpression(MediaType.APPLICATION_JSON_VALUE);
Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8));
... |
167216638_260 | class OAuth2ApplicationScopeAliasesResolversImpl implements OAuth2ApplicationScopeAliasesResolvers {
@Override
public DataFetcher<OAuth2ApplicationScopeAliases> createOAuth2ApplicationScopeAliasesDataFetcher() {
return environment -> {
long companyId = util.getLongArg(environment, "companyI... | // Given
Map<String, Object> arguments = new HashMap<>();
arguments.put("companyId", COMPANY_ID);
arguments.put("userId", USER_ID);
arguments.put("userName", USER_NAME);
arguments.put("oAuth2ApplicationId", OAUTH2_APPLICATION_ID);
arguments.put("scopeAliasesList",... |
167261547_272 | class Acl {
public Set<Principal> getDeniedReaders() {
return getClonedCopy(deniedReaders, ImmutableSet.toImmutableSet());
}
private Acl(Builder builder);
public Set<Principal> getReaders();
public Set<Principal> getOwners();
public String getInheritFrom();
public String getInheritFromFragment();
... | Acl acl = new Acl.Builder()
.setReaders(user("AllowedUser1", "AllowedUser2"))
.setDeniedReaders(group("DeniedGroup"))
.setOwners(user("AllowedUser1"))
.build();
assertEquals(group("DeniedGroup"), acl.getDeniedReaders());
thrown.expect(UnsupportedOperationException.class);
... |
167412136_28 | class NewsViewModel extends ViewModel {
public void fetchNews() {
disposable.add(apiClient.fetchNews()
.doOnEvent((newsList, throwable) -> onLoading())
.compose(rxSingleSchedulers.applySchedulers())
.subscribe(this::onSuccess,
this::on... | // Mock API response
when(apiClient.fetchNews()).thenReturn(Single.just(new NewsList()));
viewModel.fetchNews();
verify(observer).onChanged(NewsListViewState.LOADING_STATE);
verify(observer).onChanged(NewsListViewState.SUCCESS_STATE);
}
} |
167431476_86 | class ChatCommandsPlugin extends Plugin {
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.SERVER && chatMessage.getType() != ChatMessageType.FILTERED)
{
return;
}
String message = chatMessage.getMessage();
Matcher matcher = KILLCOUNT_PATTERN... | when(client.getUsername()).thenReturn("Adam");
ChatMessage chatMessageEvent = new ChatMessage(null, SERVER, "", "Your Corporeal Beast kill count is: <col=ff0000>4</col>.", null, 0);
chatCommandsPlugin.onChatMessage(chatMessageEvent);
verify(configManager).setConfiguration("killcount.adam", "corporeal beast", ... |
167468844_0 | class App {
public static List<URL> getResources(String name) throws IOException {
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
return Collections.list(classLoader.getResources(name));
}
public static void main(String[] args);
}
class AppTest {
@Test
public void shouldSo... |
// act
final List<URL> resources = getResources("folder/subfolder");
// assert
assertFalse(resources.isEmpty());
assertTrue(resources.get(0).toString().contains("subfolder"));
}
} |
167492840_26 | class CellStsUtils {
public static String getIssuerName(String cellName, String namespace) {
if (StringUtils.isEmpty(namespace)) {
namespace = Constants.DEFAULT_NAMESPACE;
}
if (cellName.equals(Constants.COMPOSITE_CELL_NAME)) {
return new StringBuilder(cellName).app... |
Assert.assertEquals(CellStsUtils.getIssuerName("hr", "ns1"), new StringBuilder("hr")
.append(Constants.STS_SERVICE).append(".").append("ns1").toString());
}
} |
167560273_3 | class Invariant {
boolean isNewYearEve(LocalDate date) {
return date.getDayOfMonth() == 31 && date.getMonthValue() == 12;
}
private Invariant cut;
}
class InvariantTest {
private Invariant cut;
@Test
public void _2018_08_31() {
| assertThat(cut.isNewYearEve(LocalDate.of(2018, 8, 31))).isFalse();
}
} |
167634307_0 | class EventRegistrationService {
@Transactional
public Person createPerson(String name) {
if (name == null || name.trim().length() == 0) {
throw new IllegalArgumentException("Person name cannot be empty!");
} else if (personRepository.existsById(name)) {
throw new IllegalArgumentException("Person has alrea... | assertEquals(0, service.getAllPersons().size());
String name = "Oscar";
try {
service.createPerson(name);
} catch (IllegalArgumentException e) {
// Check that no error occurred
fail();
}
List<Person> allPersons = service.getAllPersons();
assertEquals(1, allPersons.size());
assertEquals(name... |
167954168_7 | class UserRepository {
public Completable deleteUser() {
return Completable.fromAction(userDao::deleteAll);
}
@Inject UserRepository(UserDao userDao);
public Single<UserEntity> getUser();
public Completable putOrPostUser(String userName, String password);
@Mock
private UserDao u... | repo.deleteUser()
.test()
.assertComplete();
}
} |
168063420_0 | class CfSpringCloudConfigClientProcessor implements CfEnvProcessor {
@Override
public boolean accept(CfService service) {
return service.existsByTagIgnoreCase("configuration");
}
@Override public void process(CfCredentials cfCredentials, Map<String, Object> properties);
@Override public CfEnvProcessorPropertie... | boolean actual = configClientProcessor.accept(configServerService);
assertThat(actual).isTrue();
}
} |
168190985_181 | class DeviceLowBatteryGenerator extends AlertGenerator {
@Override
protected void handleModelChanged(SubsystemContext<PlaceMonitorSubsystemModel> context, Model model, AlertScratchPad scratchPad) {
Map<String, Date> lowBatteries = context.model().getLowBatteryNotificationSent();
// remove all previo... | replay();
Map<String, Date> lowBattery = ImmutableMap.of(lock.getAddress().getRepresentation(), new Date());
model.setLowBatteryNotificationSent(lowBattery);
generator.handleModelChanged(context, model, scratchPad);
String key = AlertKeys.key(SmartHomeAlert.ALERTTYPE_DEV_WARN_BATTERY_LOW,... |
168419532_1 | class ServiceHelper {
public static Properties getLocalProperties(String fileName) {
Properties properties = new Properties();
InputStream inputStream = ServiceHelper.class.getClassLoader().getResourceAsStream(fileName);
try {
properties.load(inputStream);
} catch (IOExc... |
String apikey = ServiceHelper.getLocalProperties("local.properties").getProperty("cloudant_apikey");
String host = ServiceHelper.getLocalProperties("local.properties").getProperty("cloudant_host");
// assertEquals("SOMETHING", apikey);
// assertEquals("SOMETHING", host);
}
} |
168531964_0 | class StringNaturalCompare implements Comparator<String> {
public int compare(String s1, String s2)
{
int result = strnatcmp0(s1, s2, true);
return(result);
}
private static int compareRight(String s1, int ind1, String s2, int ind2);
public static int compareLeft(String s1, int ind... | Comparator<String> comp = new StringNaturalCompare();
String str1 = "1";
String str2 = "2";
assertEquals("string natural comparison error for " + str1 + " " + str2, -1, comp.compare(str1, str2));
str1 = "u1";
str2 = "u2";
assertEquals("string natural comparison er... |
168665843_2 | class BookController {
@PatchMapping("/books/{id}")
Book patch(@RequestBody Map<String, String> update, @PathVariable Long id) {
return repository.findById(id)
.map(x -> {
String author = update.get("author");
if (!StringUtils.isEmpty(author)) {... |
String patchInJson = "{\"price\":\"99.99\"}";
mockMvc.perform(patch("/books/1")
.content(patchInJson)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
.andExpect(status().isMethodNotAllowed());
verify(mockRepository, times(1)).find... |
169045057_4 | class EmployeeService {
public List<Employee> allInFRIR() {
return this.employeeRepository.findAll(EmployeeSpecifications.workInDepartmentFRIR);
}
public EmployeeService(EmployeeRepository employeeRepository);
public List<Employee> allOlderThen20();
public List<Employee> allOlderThen20In... | var inFrir = employeeService.allInFRIR();
Assert.assertTrue(inFrir.stream().allMatch(emp -> emp.getDepartment().getName().equals("FRIR")));
Assert.assertEquals(2, inFrir.size());
}
} |
169045197_5 | class RabbitMqBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof SimpleRabbitListenerContainerFactory) {
SimpleRabbitListenerContainerFactory factory = (SimpleRabbitListen... | // given
Object object = new Object();
// when
Object result = rabbitMqBeanPostProcessor.postProcessBeforeInitialization(object, "object");
// then
assertThat(result).isNotNull();
assertThat(result).isSameAs(object);
}
} |
169102492_121 | class JobQueueBatch implements Serializable {
public void setCompletedStatus(UUID aggregatorID) {
if (this.status != JobStatus.RUNNING) {
throw new JobQueueFailure(jobID, batchID, String.format("Cannot complete. JobStatus: %s", this.status));
}
if (!this.patients.isEmpty() && (t... | final var job = Mockito.spy(createJobQueueBatch());
job.status = JobStatus.RUNNING;
job.patientIndex = 2;
job.setCompletedStatus(aggregatorID);
assertEquals(JobStatus.COMPLETED, job.getStatus());
assertFalse(job.getAggregatorID().isPresent());
assertNotNull(job.... |
169158153_22 | class BasicHistogramAggregator extends ConcurrentMonoidIntTable implements Aggregator {
@Override
public void apply(final String[] tags, final long value, final long timestamp) {
super.apply(tags, value, timestamp);
}
public BasicHistogramAggregator(final String metricId, final DistributionBucket buckets... | DistributionBucket bucket = new DistributionBucket(new long[]{0, 10, 100});
final BasicHistogramAggregator table = new BasicHistogramAggregator("test", bucket, 128);
final Object lock = new Object();
synchronized (table) {
new Thread(() -> {
for (int i = 0; i < 64; i++) {
table.a... |
169246391_13 | class InfluxLineProtocolRecordReader implements RecordReader {
@Override
public Record nextRecord(final boolean coerceTypes, final boolean dropUnknownFields)
throws IOException, MalformedRecordException {
String protocol = reader.readLine();
return mapInlineProtocol(protocol, coer... |
String data = "weather,location=us\\ midwest temperature=82 1465839830100400200";
RecordReader recordReader = readerFactory.createRecordReader(variables, toInputData(data), -1,logger);
Record record = recordReader.nextRecord();
Map tags = (Map) record.getValue(InfluxLineProtocolRecord... |
169292412_2 | class ListHelper {
public static int getDefaultResolutionIndex(final Context context,
final List<VideoStream> videoStreams) {
String defaultResolution = computeDefaultResolution(context,
R.string.default_resolution_key, R.string.default_resolu... | List<VideoStream> testList = Arrays.asList(
new VideoStream("", MediaFormat.MPEG_4, /**/ "720p"),
new VideoStream("", MediaFormat.v3GPP, /**/ "240p"),
new VideoStream("", MediaFormat.WEBM, /**/ "480p"),
new VideoStream("", MediaFormat.WEBM... |
169318041_2 | class StartupLogger {
String getStartingMessage() {
StringBuilder sb = new StringBuilder();
String sdnRx = getVersionOf(Node.class).map(v -> "SDN/RX v" + v).orElse("an unknown version of SDN/RX");
String sdC = getVersionOf(AbstractMappingContext.class).map(v -> "Spring Data Commons v" + v)
.orElse("an unkn... |
String message = new StartupLogger(Mode.IMPERATIVE).getStartingMessage();
assertThat(message).matches(
"Bootstrapping imperative Neo4j repositories based on an unknown version of SDN\\/RX with Spring Data Commons v2\\.\\d+\\.\\d+.RELEASE and Neo4j Driver v4\\.\\d+\\.\\d+(?:-.*)\\.");
}
} |
169410903_89 | class BasicAuthPasswordVariableAccessor extends VariableAccessor {
@Override
public Map<AttributeType, SetVariableValidator> getVariableValidators() {
return variableValidators;
}
public BasicAuthPasswordVariableAccessor(Station station, StationStore stationStore);
@Override public Strin... | SetVariableValidator setVariableValidator = basicAuthPasswordVariableAccessor.getVariableValidators().get(AttributeType.ACTUAL);
CiString1000 invalidPassword = new CiString1000("12345");
SetVariableResult result = setVariableValidator.validate(attributePath(), invalidPassword);
assert... |
169530455_2 | class Trie {
public TrieResult<T> getLastOnPath(CharSequence key) {
return getLastOnPath(key, 0);
}
protected Trie();
public Trie(boolean forward);
public TrieResult<T>[] getAll(CharSequence key, int from);
public int getCells();
public int getCellsPnt();
public int getCells... | Trie t = TrieLoadSaveHelper.load(Paths.get("src/test/resources/defaultTrie.dic"), TrieDataType.STRING);
TrieResult cs = t.getLastOnPath("트리케라톱스");
Assert.assertEquals("초식공룡", cs.getData());
t = TrieLoadSaveHelper.load(Paths.get("src/test/resources/defaultTrie.dic"), TrieDataType.STRING)... |
169625797_41 | class StructureTreeRewriter {
public Node rewrite(Node root) throws RewriteException, RepositoryException {
logger.debug("Rewriting page's content tree rooted at {}", root.getPath());
/*
* Description of the algorithm:
* - traverse the tree rooted at root's parent in pre-order
... |
Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/matches/jcr:content").adaptTo(Node.class);
StructureTreeRewriter rewriter = new StructureTreeRewriter(rules);
Node rewrittenNode = rewriter.rewrite(rootNode);
assertFalse(rewrittenNode.hasProperty("cq:designPath"));... |
169697931_0 | class Evaluator {
public boolean evaluate(Evaluatable evaluatable, JsonNode node) {
return evaluatable.accept(new LogicEvaluator(new EvaluationContext(parseContext.parse(node), this)));
}
public Evaluator();
public Evaluator(ErrorHandlingStrategy errorHandlingStrategy);
final JsonNode n... | final Evaluator evaluator = new Evaluator();
Assert.assertTrue(
evaluator.evaluate(
Equals.builder()
.lhs(new ObjectValue("a"))
.rhs(new ObjectValue("a"))
.build()
... |
169709790_3 | class RouteGuideService extends RouteGuideGrpc.RouteGuideImplBase {
@Override
public StreamObserver<RouteNote> routeChat(final StreamObserver<RouteNote> responseObserver) {
logger.info("RouteChat");
return new StreamObserver<RouteNote>() {
@Override
public void onNext(Ro... | Point p1 = Point.newBuilder().setLongitude(1).setLatitude(1).build();
Point p2 = Point.newBuilder().setLongitude(2).setLatitude(2).build();
RouteNote n1 = RouteNote.newBuilder().setLocation(p1).setMessage("m1").build();
RouteNote n2 = RouteNote.newBuilder().setLocation(p2).setMessage("m2... |
169802047_99 | class Template {
public Template resolveBy(Resolver resolver, DeclaringComponent currentComponent) {
String replaced = content.replace("${this@templateName}", templateNameWithoutBrackets());
Matcher m = pattern.matcher(replaced);
if (!m.find()) return withContent(replaced);
StringB... | Entry<String, String> entry = System.getenv().entrySet().iterator().next();
String result = new Template("name", source, templatePattern, "${env@" + entry.getKey() + "}").
resolveBy(resolver(), root).getContent();
UnaryOperator<String> escape = v -> v.replaceAll("\\\\+", "/");
... |
169815639_0 | class ApodDetailPresenter extends BasePresenter<ApodDetailContract.View> implements ApodDetailContract.Presenter {
@Override
public void fetchApodData() {
view.hideApod();
view.showProgressBar();
apodInteractor.getApodDataFromRemote(new ApodDetailsInteractor.onDetailsFetched() {
... | presenter.fetchApodData();
verify(interactor).getApodDataFromRemote(fetchDataCallbackCaptor.capture());
fetchDataCallbackCaptor.getValue().onSuccess(APOD_DATA);
}
} |
169872920_32 | class SeriesTableView extends Control {
public final ObservableList<Series<X, Y>> getData() {
return dataProperty().get();
}
public SeriesTableView();
public SeriesTableView(Series<X, Y> series);
public SeriesTableView(ObservableList<Series<X, Y>> seriesList);
public SeriesTableVie... | SeriesTableView<Number, Number> view = initSkin(new SeriesTableView<>(SERIES1));
TableView<?> tableView = getTableView(view);
assertEquals(SERIES1.getData().size(), tableView.getItems().size());
assertEquals(SERIES1.getData().get(0).getXValue(), getXColumn(view,... |
169934394_1 | class DiffLineFilter extends AutomaticBean implements Filter {
@Override
public boolean accept(AuditEvent event) {
List<Edit> editList = fileEditMap.get(event.getFileName());
if (CollectionUtils.isEmpty(editList)) {
return false;
}
for (Edit edit : editList) {
... | String fileName = "test";
int lineNum = 10;
int beginB = 5;
int endB = 9;
LocalizedMessage message = PowerMockito.mock(LocalizedMessage.class);
PowerMockito.doReturn(EmptyLineSeparatorCheck.class.getName()).when(message).getSourceName();
AuditEvent event = Power... |
169959995_13 | class Jogador {
public static JogadorBuilder builder() {
return new JogadorBuilder();
}
Jogador(String nome, String cidade, String pais, int gols, Posicao posicao);
public String getNome();
public String getCidade();
public String getPais();
public int getGols();
public Posi... | Jogador neymar = Jogador.builder().withNome("Neymar")
.withCidade("Salvador")
.withPais("Brasil").withGols(10)
.withPosicao(Posicao.ATAQUE).build();
assertNotNull(neymar);
}
} |
170136874_2 | class Address {
@Override
public String toString() {
return address;
}
public Address(PrivateKey privateKey);
public Address(PublicKey publicKey);
public Address(String address);
public static boolean isValid(String address);
public byte[] getBytes();
private final Str... | Assert.assertEquals(TEST_ADDRESS, new Address(TEST_PUB_KEY).toString());
}
} |
170551715_5 | class PathValue {
@Override
public String toString() {
return value;
}
public PathValue(final String value);
public Path resolvePath(@NotNull final PathResolver pathResolver);
@Override public boolean equals(final Object o);
@Override public int hashCode();
}
class PathValueTes... | Assertions.assertEquals("/test/toString", new PathValue("/test/toString").toString());
}
} |
170565218_0 | class Password {
public static boolean longEnough(String password) {
return password.length() >= 8;
}
public static String generateSalt();
public static String hash(String password, String salt);
public static boolean containsUpperCase(String password);
public static boolean containsLo... | Assert.assertFalse(Password.longEnough(""));
}
} |
170829387_12 | class WebAuthn4jAuthenticator implements Authenticator {
public void authenticate(AuthenticationFlowContext context) {
LoginFormsProvider form = context.form();
Map<String, String> params = generateParameters(context.getRealm(), context.getUriInfo().getBaseUri());
context.getAuthenticationS... | // set up mock
List<String> publicKeyCredentialIds = new ArrayList<>();
publicKeyCredentialIds.add(getRandomString(32));
when(context.getUser().getAttribute(WebAuthnConstants.PUBKEY_CRED_ID_ATTR)).thenReturn(publicKeyCredentialIds);
// test
try {
authenticator.a... |
170883666_59 | class GrokPatternCompiler {
public GrokMatcher compile(final String expression) {
Objects.requireNonNull(expression, "expression can't be null");
LOG.info("Starting to compile grok matcher expression : {}", expression);
ArrayList<GrokPattern> patterns = new ArrayList<>();
final Str... | final GrokMatcher matcher = compiler.compile("%{ISO8601_TIMEZONE} %{LOGLEVEL} %{GREEDYDATA}");
Assert.assertNotNull(matcher);
Assert.assertNotNull(matcher.getGrokPattern("ISO8601_TIMEZONE"));
Assert.assertNotNull(matcher.getGrokPattern("LOGLEVEL"));
Assert.assertNotNull(matcher.g... |
171042873_88 | class MetricJob {
@ConditionalOnProperty(value = "scheduling.enabled", havingValue = "true")
@Scheduled(cron = "0 * * * * *")
@Retryable
public void send() {
List<Metric> metrics = metricService.collect();
metricService.send(metrics);
}
@Rule
public MockitoRule mockitoRule;... | final List<Metric> metrics =
List.of(
Metric.builder()
.name("metric1")
.time(1L)
.value(BigDecimal.ONE)
.build(),
Metric.builder()
.name("metric2")
... |
171116174_14 | class JpaEntity implements IdentifiableEntity<ID> {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!getClass().isInstance(o)) return false;
return getId() != null && getId().equals(((JpaEntity) o).getId());
}
@Override public String toString();
@Override public int hashCode();
... | for (int i = 0; i < 1000; i++) {
assertThat(x.equals(y)).isTrue();
}
}
} |
171132936_6 | class StringUtil {
public static String deleteCRLFOnce(String input) {
return input.replaceAll("((\r\n)|\n)[\\s\t ]*(\\1)+", "$1").replaceAll("^((\r\n)|\n)", "");
}
public static String getMiddleString(String text, String lStr, String rStr);
public static String str2HexStr(String str);
public static String hex... | assertEquals("fooBar", StringUtil.deleteCRLFOnce("fooBar"));
assertEquals("foo\nBar", StringUtil.deleteCRLFOnce("foo\n\nBar"));
}
} |
171867537_7 | class CORSFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
responseContext.getHeaders().add("Acces... |
// create the objects to be mocked
ContainerRequestContext requestContext = mock(ContainerRequestContext.class);
ContainerResponseContext responseContext = mock(ContainerResponseContext.class);
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
when(responseContext.getHeaders()).thenRet... |
172090523_83 | class ParserWrapper implements Parser {
@Override
public <T extends Enum<T>> T getEnum(Class<T> enumClass) throws MatchbookSDKParsingException {
if (isNotNullValue()) {
try {
String value = jsonParser.getValueAsString().toUpperCase().replace('-', '_');
try {
... | doThrow(IOException.class).when(jsonParser).getValueAsString();
when(jsonParser.hasToken(JsonToken.VALUE_NULL)).thenReturn(false);
assertThatExceptionOfType(MatchbookSDKParsingException.class)
.isThrownBy(() -> unit.getEnum(TestEnum.class));
}
} |
172494483_1 | class CurrentUserHandlerMethodArgumentResolver implements
HandlerMethodArgumentResolver {
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterAnnotation(CurrentUser.class) != null
&& methodParameter.getParameterType().equals(User.class);
}
public Object re... | assertTrue(resolver.supportsParameter(validParam));
assertFalse(resolver.supportsParameter(notAnnotatedParam));
assertFalse(resolver.supportsParameter(wrongTypeParam));
}
} |
172695826_2 | class EDKeyPair implements IKeyPair {
@Override
public boolean verifySignature(byte[] message, byte[] sigBytes) {
try {
EdDSAEngine sgr = new EdDSAEngine(MessageDigest.getInstance("SHA-512"));
sgr.initVerify(new EdDSAPublicKey(new EdDSAPublicKeySpec(keySpec.getA(), ed25519)));
... | assertTrue(edKeyPair.verifySignature(message, B16.decode(expectedSig)));
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.