id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
83583832_18 | class NewPipe {
public static String getNameOfService(int id) {
try {
//noinspection ConstantConditions
return getService(id).getServiceInfo().getName();
} catch (Exception e) {
System.err.println("Service id not known");
e.printStackTrace();
... | assertEquals(NewPipe.getNameOfService(YouTube.getServiceId()), YouTube.getServiceInfo().getName());
}
} |
83664920_147 | class ExperimentalIdentifierCheck extends DoubleDispatchVisitorCheck {
@VisibleForTesting
void setIdentifiersToExclude(String identifiersToExclude) {
this.identifiersToExclude = identifiersToExclude;
}
@Override public void visitValue(ValueTree tree);
@Override public void validateParameters();
privat... | try {
ExperimentalIdentifierCheck check = new ExperimentalIdentifierCheck();
check.setIdentifiersToExclude("(");
CssCheckVerifier.issuesOnCssFile(check, getTestFile("experimentalIdentifierUsage.css")).noMore();
} catch (IllegalStateException e) {
assertThat(e.getMessage()).isEqualTo("Che... |
83751371_7 | class FailsafeS3Decorator extends S3Decorator {
public static FailsafeS3Decorator decorate(AmazonS3 s3) {
return decorate(s3, defaultCircuitBreaker());
}
private FailsafeS3Decorator(AmazonS3 delegate, CircuitBreaker circuitBreaker);
@Override protected AmazonS3 getDelegate();
@Override protected T cal... | AmazonS3 s3 = FailsafeS3Decorator.decorate(new NotAuthedS3Client());
for (int i = 0; i < 100; i++ ) {
try {
s3.getObjectMetadata("test-bucket", "test-key");
} catch (AmazonServiceException e) {
assertThat(e.getStatusCode()).isEqualTo(403);
}
Thread.sleep(50);
}
}
... |
83883701_21 | class JavaFXToggleButtonElement extends JavaFXElement {
@Override
public boolean marathon_select(String value) {
boolean selected = Boolean.parseBoolean(value);
boolean current = ((ToggleButton) node).isSelected();
if (selected != current) {
click();
}
return... | RadioButton radioButtonNode = (RadioButton) getPrimaryStage().getScene().getRoot().lookup(".radio-button");
AssertJUnit.assertEquals(false, radioButtonNode.isSelected());
radioButton.marathon_select("true");
new Wait("Waiting for the radio button selection.") {
@Override
... |
83904496_5 | class ReactiveExecutionStrategy extends ExecutionStrategy {
@Override
public ExecutionResult execute(ExecutionContext context, ExecutionParameters parameters) throws NonNullableFieldWasNullException {
Map<String, List<Field>> fields = parameters.fields();
Object source = parameters.source();
... | GraphQLObjectType innerType = newObject()
.name("Inner")
.field(newStringField("b").staticValue("foo"))
.build();
GraphQLSchema schema = newQuerySchema(it -> it
.field(
newField("a", new GraphQLList(innerType))
... |
83932318_5 | class PokeDataSource {
public Observable<String> getPokemonStringObservable(String id) {
return pokemonService.getPokemon(id)
.map(new Function<Pokemon, String>() {
@Override
public String apply(@NonNull Pokemon pokemon) throws Exception {
... | PokeDataSource dataSource = new PokeDataSource(pokemonService);
TestObserver<String> observer = new TestObserver<>();
dataSource.getPokemonStringObservable("12").subscribe(observer);
RecordedRequest recordedRequest = getMockWebServer().takeRequest();
assertEquals("application/... |
83938778_1 | class MoveValidator {
public static void throwIfInvalidMove(Matrix matrix, ScrambleMove move) {
switch (move.move) {
case SWAP:
MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.Swap.X1), Plane.X);
MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.Swap.Y1), Plane.Y... | Matrix testMatrix = getTestMatrix(MoveValidator.MIN_SIZE_FOR_SCRAMBLING);
for(Map.Entry<ScrambleMoves, ScrambleMove> curEntry : validMoves.entrySet()){
MoveValidator.throwIfInvalidMove(testMatrix, curEntry.getValue());
MoveValidator.throwIfInvalidMove(testMatrix, curEntry.getValue(), curEntry.getKey());
... |
84008299_43 | class DateGenerator {
public Date getExpirationDate() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_WEEK, 1);
return c.getTime();
}
}
class DateGeneratorTest {
@Test
public void testExpirationDate() {
| Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_WEEK, 1);
DateGenerator dateGenerator = new DateGenerator();
Calendar c2 = Calendar.getInstance();
c2.setTime(dateGenerator.getExpirationDate());
assertEquals(c.get(Calendar.DAY_OF_WEEK), c2.get(Calendar.DAY_OF_... |
84059135_25 | class StateBundle implements Parcelable {
@Nullable
public double[] getDoubleArray(@Nullable String key) {
Object o = map.get(key);
if(o == null) {
return null;
}
try {
return (double[]) o;
} catch(ClassCastException e) {
typeWarning(k... | StateBundle stateBundle = new StateBundle();
assertThat(stateBundle.getDoubleArray("key")).isNull();
}
} |
84142745_46 | class UIManagerModuleConstants {
public static Map<String, Object> getConstants() {
HashMap<String, Object> constants = new HashMap<String, Object>();
constants.put(
"UIView",
MapBuilder.of(
"ContentMode",
MapBuilder.of(
"ScaleAspectFit",
... | ViewManager mockViewManager = mock(ViewManager.class);
List<ViewManager> viewManagers = Arrays.asList(mockViewManager);
when(mockViewManager.getName()).thenReturn("SomeView");
when(mockViewManager.getNativeProps())
.thenReturn(MapBuilder.of("fooProp", "number"));
UIManagerModule uiManagerMod... |
84190084_2 | class MovieDetailsViewModel extends MovieViewModel {
public void getMovieDetails(long movieId) {
isMovieLoading.set(true);
errorViewShowing.set(false);
mMoviesRepository.getMovieDetails(movieId)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedule... | // given a movie repository
setupRepository();
// when get movie details is called
mDetailsViewModel.getMovieDetails(MOVIE_ID);
// then verify that the repository makes api call
verify(mMovieRepository).getMovieDetails(MOVIE_ID);
// assert that the loading indi... |
84210505_0 | class RtmClientBuilder {
URI createUri(String endpoint, String appKey) {
if (Strings.isNullOrEmpty(endpoint)) {
throw new IllegalArgumentException();
}
Pattern verPattern = Pattern.compile("/(v\\d+)$");
Matcher m = verPattern.matcher(endpoint);
String fullEndpoint = endpoint;
if (!m.f... | RtmClientBuilder builder = new RtmClientBuilder("foo", "bar");
// legacy format
assertThat(
builder.createUri("ws://xxx.api.com/v1", "appkey").toString(),
equalTo("ws://xxx.api.com/v1?appkey=appkey")
);
// new format with slash
assertThat(
builder.createUri("ws://xxx.api... |
84302839_8 | class ReflectionUtils {
public static Map<String, Type> getTypeParameters(Class<?> subclass, Class<?> superclass) {
// Gather implemented interfaces and superclass.
List<Type> genericSupertypes = Stream.concat(
Stream.of(subclass.getGenericSuperclass()), Stream.of(subclass.getGeneri... | MyParameterizedClassC myParameterizedObject = new MyParameterizedClassC() {
};
Map<String, Type> expectedTypeParameters = new HashMap<>();
expectedTypeParameters.put("A", Long.class);
final Map<String, Type> typeParameters = ReflectionUtils.getTypeParameters(
myP... |
84311940_42 | class SearchUserExecutor implements RequestExecutor {
@Override
public GoPluginApiResponse execute() throws Exception {
Map<String, String> requestParam = Util.GSON.fromJson(request.requestBody(), Map.class);
String searchTerm = requestParam.get(SEARCH_TERM);
List<AuthConfig> authConfig... | final GoPluginApiRequest request = mock(GoPluginApiRequest.class);
mockPasswordFileWith("/var/etc/password_1.properties", "myname");
mockPasswordFileWith("/var/etc/password_2.properties", "yournamed", "bar", "myname");
mockPasswordFileWith("/var/etc/password_3.properties", "nameless", "... |
84320045_0 | class GraphicsBounds {
public static Rectangle createBounds() {
return new BufferedImage(800, 600, BufferedImage.TYPE_3BYTE_BGR)
.createGraphics()
.getDeviceConfiguration()
.getBounds();
}
public static void main(String[] args);
}
class GraphicsBoundsTest {
@Test
void createBounds() throws Excep... | assertThat(GraphicsBounds.createBounds())
.isEqualTo(new Rectangle(0, 0, 800, 600));
}
} |
84372863_7 | class SequenceProgram implements Program {
@Override
public RelNode run(RelOptPlanner relOptPlanner,
RelNode relNode,
RelTraitSet relTraitSet,
List<RelOptMaterialization> relOptMaterializationList,
List<RelOptLattice> relOptLatticeList) {
for (Program program : programs) {
relNode = program.run(relO... | program = new SequenceProgram();
RelNode result = program.run(planner, inNode, relTraitSet, relOptMaterializationList, relOptLatticeList);
Assert.assertSame(inNode, result);
}
} |
84382452_2 | class BankAccountService {
public static TransferResult transfer(BankAccount to, BankAccount from, Money money) {
BankAccount updatedFrom = from.withdrawTo(to, money);
BankAccount updatedTo = to.depositFrom(from, money);
return TransferResult.of(updatedTo, updatedFrom);
}
}
class Bank... | Money initialMoney = Money.of(10000);
BankAccount bankAccount1 = BankAccount.of(IdGenerator.generateId()).depositCash(initialMoney);
BankAccount bankAccount2 = BankAccount.of(IdGenerator.generateId()).depositCash(initialMoney);
System.out.println("bankAccount1 = " + bankAccount1.getBala... |
84398452_82 | class Config {
public final Optional<Duration> poolValidationInterval() {
return poolValidationInterval;
}
private Config(final String dataSourceSupplierClass, final String host, final int port, final String user,
final Charset charset, final ScheduledExecutorService scheduler, final Optional<String>... | final Config c = Config.create(dataSourceSupplierClass, host, port, user);
final Duration poolValidationInterval = Duration.ofSeconds(100);
assertEquals(Optional.of(poolValidationInterval),
c.poolValidationInterval(poolValidationInterval).poolValidationInterval());
}
} |
84439902_1 | class ChangeSets {
public static void migrate(final ConnectionContext connectionContext, String fileName, String changeSetsToLoadSeparatedByComma) throws MintleafException {
migrate(connectionContext, fileName, changeSetsToLoadSeparatedByComma.split(","));
}
public static void applySource(final Co... | ChangeSets.migrate(testDb.getNewConnection(), "res:/Testddl.sql", new String[]{"create tables"});
Assert.assertTrue(testDbQueries.isTableExists("mintleaf.TABLE1"));
Assert.assertTrue(testDbQueries.isTableExists("mintleaf.TABLE2"));
ChangeSets.migrate(testDb.getNewConnection(), "res:/Te... |
84466727_13 | class VolumeRepository implements Closeable {
PersistentVolumeClaim getClaim(VolumeRequest volumeRequest) {
return claims.computeIfAbsent(volumeRequest, this::createClaim);
}
public VolumeRepository(KubernetesClient client);
private PersistentVolumeClaim createClaim(VolumeRequest volumeRequest);
@Over... | VolumeRequest request = VolumeRequest.volumeRequest("storage-class-name", "16Gi");
volumeRepository.getClaim(request);
volumeRepository.getClaim(request);
verify(pvcs, times(1)).create(any());
}
} |
84488372_5 | class InMemoryBackend implements IStateHistoryBackend {
@Override
public StateInterval doSingularQuery(long t, int attributeQuark)
throws TimeRangeException, AttributeNotFoundException {
if (!checkValidTime(t)) {
throw new TimeRangeException(ssid + " Time:" + t + ", Start:" + st... | try {
StateInterval interval = fixture.doSingularQuery(0, 0);
assertNotNull(interval);
assertEquals(0, interval.getStart());
assertEquals(90, interval.getEnd());
assertEquals(0, ((IntegerStateValue) interval.getStateValue()).getValue());
} cat... |
84506236_31 | class Utils {
public static boolean invokeSetterQuietly(Object obj, String setterName, Class<?> valueKlass, Object value)
{
if (obj == null)
return false;
try
{
invokeSetter(obj, setterName, valueKlass, value);
return true;
}
catch (T... | ObjectWithSetter obj = new ObjectWithSetter();
assertTrue(Utils.invokeSetterQuietly(obj, "setValue", String.class, "foo"));
assertEquals("happy path", "foo", obj.value);
assertTrue(Utils.invokeSetterQuietly(obj, "setValue", String.class, null));
assertNull("can set null value",... |
84521629_2 | class AEMDataLayerInterceptorFilter implements Filter {
boolean resourceHierarchyHasACycle(Resource resource) {
String resourceType = resource.getResourceType();
Set<String> resourceTypeSet = new HashSet<>();
ResourceResolver resolver = resource.getResourceResolver();
while (resourceType != null) {
if (r... | AEMDataLayerInterceptorFilter filter = context.getService(AEMDataLayerInterceptorFilter.class);
context.currentPage("/test/page-with-cloud-config");
assertThat(filter.resourceHierarchyHasACycle(context.currentResource())).as("has a cycle should be false")
.isFalse();
}
} |
84603051_206 | class ClusterFilters {
public static ClusterFilter forNextInJoinOrder() {
return NEXT_IN_JOIN_ORDER;
}
private ClusterFilters();
public static ClusterFilter forNext();
public static ClusterFilter forNode(ClusterNodeId nodeId);
public static ClusterFilter forNode(ClusterNode node);
... | repeat(5, i -> {
List<ClusterNode> nodesList = new ArrayList<>();
repeat(5, j -> nodesList.add(newNode(newNodeId(), i == j /* <- Local node. */, null, null, j)));
ClusterNode expected;
if (i == 4) {
// If last is local then should take the first... |
84616200_110 | class KetamaNodeLocator {
public String getPrimary(final String key) {
final List<String> rv = getNodesForKey(hash(key), 1);
assert rv != null && rv.get(0) != null: "Found no node for key " + key;
return rv.get(0);
}
public KetamaNodeLocator(final List<String> nodes);
public ... | final int nodeSize = 5;
final int keySize = 10000;
final List<String> nodes = generateRandomStrings(nodeSize);
final List<String> weightedNodes = new ArrayList<String>(nodes);
weightedNodes.add(nodes.get(3)); // 20%
for (int ix = 0; ix < 4; ix++) { weightedNodes.add(nodes... |
84678166_0 | class Config {
public String getApiHost() {
return apiHost;
}
public Config(String clientId,
String secret,
String apiHost,
boolean useHttps,
List<Scope> scopes,
OkHttpClient httpClient,
Ht... | Config c = newConfig("hostwithhttp.com:1234");
assertThat(c.getApiHost()).isEqualTo("hostwithhttp.com:1234");
assertThat( newConfig("http://example.com").getApiHost()).isEqualTo("example.com");
assertThat( newConfig("https://other.com:1234").getApiHost()).isEqualTo("other.com:1234");
}
} |
84742920_34 | class PointDComparatorY extends PointDComparator {
public int compareEpsilon(PointD a, PointD b) {
return compareEpsilon(a, b, epsilon);
}
public PointDComparatorY();
public PointDComparatorY(double epsilon);
@Override public int compare(PointD a, PointD b);
public static int compar... | assertEquals(-1, PointDComparatorY.compareEpsilon(new PointD(1, 2), new PointD(1.1, 2), 0.01));
assertEquals(-1, PointDComparatorY.compareEpsilon(new PointD(1, 2), new PointD(1, 2.1), 0.01));
assertEquals(+1, PointDComparatorY.compareEpsilon(new PointD(1, 2), new PointD(0.9, 2), 0.01));
... |
84750226_67 | class AuctionRequestBuilder extends AbstractMarketDataRequestBuilder<Map<String, Auction>, AuctionRequestBuilder> implements IEXApiRestRequest<Map<String, Auction>>, IEXCloudV1RestRequest<Map<String, Auction>> {
@Override
public RestRequest<Map<String, Auction>> build() {
return RestRequestBuilder.<Map... | final String symbol = "IBM";
final RestRequest<Map<String, Auction>> request = new AuctionRequestBuilder()
.withSymbol(symbol)
.build();
assertThat(request.getMethodType()).isEqualTo(MethodType.GET);
assertThat(request.getPath()).isEqualTo("/deep/auction... |
84765740_2 | class Config implements Runnable {
static Config getConfig(String[] args) {
Config config = new Config();
CommandLine.run(config, System.err, args);
return config;
}
@Override public void run();
}
class ConfigTest {
@Test
public void testCommand() {
| String[] args = {"","train","task","tt"};
Config config = Config.getConfig(args);
Assert.assertEquals(config.isTrain, false);
Assert.assertEquals(config.task, "tt");
}
} |
84791542_0 | class User {
public boolean isReady() {
return getStatus() == Status.READY;
}
public User();
public User(long id, String email, String nickname);
public long getId();
public void setId(long id);
public String getEmail();
public void setEmail(String email);
public String ... | User user = new User();
user.enterRoom(1);
assertEquals(false, user.isReady());
}
} |
84838073_0 | class UserClass implements Serializable {
public void setPassword(String password) throws UserException {
int MIN_PASSWORD_LENGTH = 6;
int MAX_PASSWORD_LENGTH = 16;
if((password != null && !password.isEmpty()) &&
(password.length() < MIN_PASSWORD_LENGTH ||
... | boolean isValid = false;
UserClass userClass = new UserClass();
try {
isValid = true;
userClass.setPassword("nome");
} catch (UserException e) {
isValid = false;
e.printStackTrace();
}
assertFalse(isValid);
}
} |
84880723_86 | class Fullfill {
@NotNull
public static List<File> multiple(
GeneratorEnvironment environment,
@NotNull File templates[],
File outputFolder,
@NotNull File sourceFolder,
String version) throws IOException, NoSuchAlgorithmException {
List<File> result = new ArrayList<>();
CDepMa... | File templates[] = new File[]{
new File("../third_party/mini-firebase/cdep-manifest-app.yml"),
new File("../third_party/mini-firebase/cdep-manifest-database.yml")
};
File output = new File(".test-files/testMiniFirebase").getAbsoluteFile();
output.delete();
List<File> result = Fullfil... |
84974822_23 | class TransformWithSerializerNodeImpl implements SerializeWithTransformerNode {
@Override
public String toString()
{
return this.transformationChain.transformToString();
}
TransformWithSerializerNodeImpl(TransformationChain transformationChain);
@Override public void to(OutputStream out);
@Override public... | node.toString();
verify(transformationChain).transformToString();
}
} |
85088788_0 | class Calculator {
public int add(int a, int b) {
return a + b;
}
public int multiply(int a, int b);
private Calculator underTest;
}
class CalculatorTest {
private Calculator underTest;
@Test
public void add() throws Exception {
| assertThat(underTest.add(3, 3), is(6));
}
} |
85113353_16 | class Artifact {
public static Artifact fromPath(Path path) {
String extension = com.google.common.io.Files.getFileExtension(path.toString());
if (Files.exists(path.resolve("WEB-INF"))) {
if (Files.exists(path.resolve("WEB-INF/appengine-web.xml"))) {
return new Artifact(ArtifactType.COMPAT_EXP... | int thrown = 0;
for (Path p : invalidArtifacts) {
try {
Artifact.fromPath(p);
} catch (IllegalArgumentException e) {
thrown++;
}
}
assertEquals(invalidArtifacts.size(), thrown);
}
} |
85172071_211 | class MultivariateFactorization {
@SuppressWarnings("unchecked")
public static <Term extends AMonomial<Term>,
Poly extends AMultivariatePolynomial<Term, Poly>>
PolynomialFactorDecomposition<Poly> FactorInGF(final Poly polynomial) {
if (canConvertToZp64(polynomial))
return Fa... | // todo: discover
IntegersZp64 domain = new IntegersZp64(33554467);
String[] vars = {"a", "b", "c", "d", "e", "f", "g"};
MultivariatePolynomialZp64
factors[] =
{
MultivariatePolynomialZp64.parse("25078271*b^5*c*d^2*e^2*f^6*g^3+22985... |
85184501_8 | class IntFloatHashMap implements IntFloatMap {
public boolean isHash() {
return true;
}
public IntFloatHashMap(int size);
public int size();
public int capacity();
public float averageOpsPerAccess();
private int collisionInspection(boolean countMultiple);
public int collision... | assertTrue(new IntFloatHashMap(10).isHash());
}
} |
85229098_2 | class DespesaService {
public BigDecimal findTotalPagoMesAtual() {
return findTotalAPagarMesAtual(true);
}
public List<Despesa> findAll();
public Page<Despesa> findAll(DespesaBuscaTO despesaBuscaTO);
private PageRequest getPaginacaoOrdenada(DespesaBuscaTO despesaBuscaTO);
@Transactiona... | despesaService.save(Despesa.builder()
.data(LocalDate.now())
.valor(BigDecimal.valueOf(70))
.descricao("Conta de Luz")
.categoria(Categoria.MORARIA)
.paga(false)
.build());
despesaService.save(Despesa.builde... |
85239682_95 | class RxUtils {
public static <T> Observable<T> singleOrEmpty(Observable<? extends Collection<T>> collectionObservable) {
return collectionObservable.toList().concatMap(lists -> {
if (lists.size() > 1) {
return Observable.error(new IllegalArgumentException("Observable contains m... | Observable<Foo> fooObservable = RxUtils.singleOrEmpty(Observable.empty());
assertThat(fooObservable.toList().toBlocking().single()).isEmpty();
}
} |
85242760_0 | class SpanBuilderR implements Tracer.SpanBuilder {
@Override
public Span start() {
Span wspan = wrapped.start();
String spanId = UUID.randomUUID().toString();
wspan.setBaggageItem(BAGGAGE_SPANID_KEY, spanId);
// shamelessly copied from io.jaegertracing.internal.JaegerTracer.Spa... | final String spanId = "some-span-id-" + System.currentTimeMillis();
final Map<String, String> parentBaggage = new HashMap<>();
parentBaggage.put(SpanBuilderR.BAGGAGE_SPANID_KEY, spanId);
// setup mocks
when(scopeManagerMock.activeSpan()).thenReturn(parentSpanMock);
when(... |
85416181_1 | class MetricsCounter {
@Schedule(minute = "*",second = "*/10",hour = "*")
public void calculateMetrics() {
System.out.println(".");
this.successesPerSecond = ((double)(success.longValue() - this.lastSuccess))/10;
this.lastSuccess = success.longValue();
this.overflowsPerSecond =... | this.cut.lastSuccess = 10;
this.cut.success.set(40);
this.cut.calculateMetrics();
assertThat(this.cut.successesPerSecond,is(3d));
assertThat(this.cut.lastSuccess,is(this.cut.success.longValue()));
}
} |
85416613_5 | class VectorCommand {
public static VectorCommand createVectorCommand(String svgCommandString) {
SVGCommand cmd = SVGCommand.valueOf(svgCommandString.substring(0, 1));
String[] argsAsString = svgCommandString.substring(1).split(SVG_ARG_DELIMITER);
float[] args = new float[argsAsString.length];
int i ... | // Absolute coordinates
VectorCommand cubicToCommand = VectorCommand.createVectorCommand("C1,2,3,4,5,6");
Assert.assertTrue(cubicToCommand instanceof VectorCommand.CubicToCommand);
Assert.assertEquals(VectorCommand.ArgFormat.ABSOLUTE, cubicToCommand.mArgFormat);
Assert.assertEquals(6, cubicToCommand... |
85497373_2 | class BooksActivityPresenter {
public void loadBooks() {
compositeDisposable.add(booksRepository.getBooks()
.subscribeOn(Schedulers.io())
.observeOn(mainScheduler)
.subscribeWith(new DisposableSingleObserver<List<Book>>() {
@Override
... | when(booksRepository.getBooks()).thenReturn(Single.<List<Book>>error(new Throwable("boom")));
presenter.loadBooks();
verify(view).displayError();
}
} |
85541447_3 | class Activator {
@Activate
public void start(ActivatorConfiguration config) {
String[] authorizableIds = config.pwdreset_authorizables();
Session session = null;
try {
ResourceResolver resolver = resolverFactory.getAdministrativeResourceResolver(null);
UserMan... | when(mockResolverFactory.getAdministrativeResourceResolver(null)).thenThrow(new LoginException());
Activator activator = spy(createActivator());
activator.start(mockConfiguration);
verify(mockAuthorizable, times(0)).changePassword(anyString());
verify(mockSession, times(0)).sav... |
85686334_7 | class Objects {
static boolean equals(Object a, Object b) {
return (a == null) ? (b == null) : a.equals(b);
}
static boolean deepEquals(Object a, Object b);
static int hash(Object... values);
static String toString(Object o);
}
class ObjectsTest {
@Test public void equals_differentBooleanParams_returnFals... | // Given
final boolean paramA = true;
final boolean paramB = false;
// When
final boolean result = Objects.equals(paramA, paramB);
// Then
assertThat(result, is(false));
}
} |
85692970_89 | class NativeServerStart implements ServerStart {
@Override
public final void acceptNextClient() throws ClientConnectionFailedException {
final Logging logging = loggingValue.get();
logging.debug("Accepting next client.");
logging.trace("Checking ConnectorCore value ..");
logging.trace("Requesting next Client... | // Arrange
doThrow(ClientConnectionFailedException.class).when(connectorCore).handleNext();
serverStart.launch();
// Act
serverStart.acceptNextClient();
// Assert
fail();
}
} |
85710339_5 | class ExpandableGroup extends NestedGroup {
public Group getGroup(int position) {
if (position == 0) {
return parent;
} else {
return children.get(position - 1);
}
}
public ExpandableGroup(Group expandableItem);
@Override public void add(Group group);
... | ExpandableGroup expandableGroup = new ExpandableGroup(parent);
Section section = new Section();
int sectionSize = 5;
for (int i = 0; i < sectionSize; i++) {
section.add(new DummyItem());
}
expandableGroup.add(section);
Item lastItem = new DummyItem();
... |
85713388_0 | class Table implements Iterable<TableRow> {
public static <T> T[] parse(final Class<T> rowType, final String[] headerAndRows) {
return parse(rowType, headerAndRows, new SpockitoValueConverter());
}
private Table();
private Table(final String headerString);
public int getColumnCount();
... | //when
final Row[] rows = Table.parse(Row.class, new String[] {
"| index | listOfInteger | emptyString |",
"| 0 | [1;2;3;4;5;6] | |",
"| 1 | [9;8;7;6;5;4] | '' |"
});
//then
assertEquals(2, rows.length,... |
85780482_11 | class SimpleUploadDataStore implements UploadDataStore {
@SuppressLint("CommitPrefEdits")
@NonNull
@Override
public Observable<Job> update(@NonNull Status status) {
return get(status.id())
.filter(job -> !Job.isInvalid(job))
.flatMap(job -> save(job.withStatus(st... | final Job test = createTestJob();
final String json = gson.toJson(test);
final String key = SimpleUploadDataStore.jobIdKey(test.id());
final Set<String> keys = new HashSet<>();
keys.add(key);
final SharedPreferences.Editor editor = sharedPreferences.edit();
edito... |
85830116_8 | class DynamicInvokeEventAdaptor implements Function<NewtonEvent, Boolean>, Consumer<NewtonEvent> {
@Override
public void accept(NewtonEvent event) {
apply(event);
}
public DynamicInvokeEventAdaptor(Object target, Class<? extends Annotation> annotation);
@Override public Boolean apply(New... | Handler handler = new Handler();
new DynamicInvokeEventAdaptor(handler, EventHandler.class).accept(new Event1());
assertTrue(handler.event instanceof Event1);
}
} |
85838297_0 | class Signatures {
public static String sign(String urlString, String algorithm, String secretKey) {
if (algorithm != null && !algorithm.equals(HMAC_SHA256_ALGORITHM)) {
throw new RuntimeException("Unsupported signature: " + algorithm);
}
if (secretKey == null) {
thr... | String secretKey = "1234567890";
String requestUrl = "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&AssociateTag=mytag-20&Operation=ItemLookup&ItemId=0679722769&ResponseGroup=Images,ItemAttributes,Offers,Reviews&Version=2013-08-01&Timestamp=2014-... |
85860202_0 | class NowPlayingPresenterImpl implements NowPlayingPresenter, NowPlayingResponseModel {
@Override
public void infoLoaded(List<MovieInfo> movieInfoList) {
/*
Note - translate internal business logic to presenter logic
*/
List<MovieViewInfo> movieViewInfoList = new ArrayList<>();... | //
//Arrange
//
NowPlayingPresenterImpl nowPlayingPresenter =
new NowPlayingPresenterImpl(mockNowPlayingViewModel, mockNowPlayingInteractor);
List<MovieInfo> movieInfoList = new ArrayList<>();
movieInfoList.add(movieInfo);
ArgumentCaptor<List<Mov... |
85880302_5 | class AppServerConfig implements ServerConfig {
@Override
public MetricsListener metricsListener() {
return guiceValues.metricsListener;
}
protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule);
public AppServerConfig(Config appCo... | // given
Config configNoReporters =
TypesafeConfigUtil.loadConfigForAppIdAndEnvironment(APP_ID, "compiletimetest")
.withValue("metrics.slf4j.reporting.enabled", ConfigValueFactory.fromAnyRef(false))
.withValue("metrics.graphite.repo... |
85987914_7 | class Cell implements Comparable<Cell>, Iterable<Cell> {
public boolean withdraw(int requested) {
int expectedCount = Math.min(requested / nominal, count);
int expectedCash = expectedCount * nominal;
boolean nextCellResult = true;
if (requested != expectedCash) {
nextCel... | Cell cell = new Cell(1, 100);
Assert.assertFalse(cell.withdraw(101));
}
} |
86001819_20 | class GenbankSeqEntry extends SequenceEntry {
public Long getOrgId() { return this.orgId; public Long getOrgId() { return this.orgId; }
public Long getOrgId() { return this.orgId; GenbankSeqEntry(AbstractSequence sequence);
public Long getOrgId() { return this.orgId; GenbankSeqEntry(AbstractSequence sequence, Map... | assertEquals("tests whether organism ids are extracted accurately", (Long) 4000000648L,
proteinSeqEntries.get(0).getOrgId());
assertEquals("tests whether organism ids are extracted accurately", (Long) 4000002681L,
proteinSeqEntries.get(1).getOrgId());
assertEquals("tests whether organism id... |
86105877_10 | class AfterExecuteDmlEvent extends ExecuteDmlEvent {
@Override
public int hashCode() {
return Objects.hash(getStatement().hashCode(), getNumberOfRowsAffected());
}
public AfterExecuteDmlEvent(Statement statement, long numberOfRowsAffected);
public long getNumberOfRowsAffected();
@Override public boolean equ... | AfterExecuteDmlEvent afterExecuteDmlEventa1 = new AfterExecuteDmlEvent(Statement.of("a"), 1L);
AfterExecuteDmlEvent afterExecuteDmlEventa1x = new AfterExecuteDmlEvent(Statement.of("a"), 1L);
AfterExecuteDmlEvent afterExecuteDmlEventa2 = new AfterExecuteDmlEvent(Statement.of("a"), 2L);
AfterExecuteDmlEvent aft... |
86106666_1 | class HttpHeadersInjectAdapter implements TextMap {
@Override
public void put(String key, String value) {
Collection<String> values = headers.get(key);
if (values == null) {
values = new ArrayList<>(1);
headers.put(key, values);
}
try {
value... | Map<String, Collection<String>> headers = new HashMap<>();
headers.put("x-header", Collections.unmodifiableList(Arrays.asList("123:123:123:1")));
HttpHeadersInjectAdapter adapter = new HttpHeadersInjectAdapter(headers);
adapter.put("x-header", "123:456:456:1");
assertEquals(hea... |
86107810_13 | class CpcFileServiceImpl implements CpcFileService {
@Override
public InputStreamResource getFileById(String fileId) {
Metadata metadata = getMetadataById(fileId);
if (isAnUnprocessedCpcFile(metadata)) {
return new InputStreamResource(storageService.getFileByLocationId(metadata.getSubmissionLocator()));
}
... | when(dbService.getMetadataById(anyString())).thenReturn(buildFakeMetadata(true, false, false));
when(storageService.getFileByLocationId("test")).thenReturn(new ByteArrayInputStream("1337".getBytes()));
InputStreamResource outcome = objectUnderTest.getFileById("test");
verify(dbService, times(1)).getMetadataBy... |
86108100_8 | class IDLTools {
public static boolean epsilonEqualsByteSequence(IDLSequence.Byte a, IDLSequence.Byte b, double epsilon)
{
return epsilonEqualsPrimitiveSequence(a::get, b::get, a, b, epsilon);
}
public static boolean equals(StringBuilder a, StringBuilder b);
public static boolean epsilonEquals(do... | Byte a;
Byte b;
a = new Byte(10, "type_9");
b = new Byte(10, "type_9");
assertTrue("Sequences not equal", IDLTools.epsilonEqualsByteSequence(a, b, 0.0));
a = new Byte(5, "type_9");
b = new Byte(10, "type_9");
assertTrue("Sequences not equal", IDLTools.epsilonEqualsByteS... |
86205415_42 | class TimeWheel {
public boolean add(String id, Callable<?> func, Duration delay) {
if (Objects.isNull(delay)) {
log.warn("delay is null: id={}", id);
return false;
}
if (Objects.isNull(func)) {
log.warn("func is null: id={}", id);
return false;
}
if (cacheTasks.containsK... | boolean result = timeWheel.add("id", () -> null, Duration.ofMillis(10000));
Assert.assertTrue(result);
}
} |
86230857_2 | class SpeakerController {
@DeleteMapping("/{id}")
public ResponseEntity deleteSpeaker(@PathVariable long id) {
speakerRepository.delete(id);
return ResponseEntity.noContent().build();
}
@GetMapping(path = "/{id}") public ResponseEntity<SpeakerResource> getSpeaker(@PathVariable long id)... | //Given
Speaker speakerToDelete = given.speaker("TO_DELETE").company("COMPANY").save();
//When
ResultActions actions = mockMvc.perform(RestDocumentationRequestBuilders.delete("/speakers/{id}", speakerToDelete.getId()))
.andDo(print());
//Then
actions.and... |
86269383_2 | class Tag {
public int getEndIndex() {
return mEndIndex;
}
private Tag(final Builder builder);
public String getWord();
public int getStartIndex();
private static final String TEST_WORD;
private static final int TEST_START_INDEX;
private static final int TEST_END_INDEX;
... | // Given // When // Then
assertEquals(TEST_END_INDEX, mTag.getEndIndex());
}
} |
86278665_1 | class KubeHelper extends MultiInstProcessor {
public static KubeOpt inst(String instanceId) {
return multiInst("KUBE", instanceId);
}
public static void init(String instanceId, Logger log, String base64KubeConfig);
}
class KubeHelperTest extends MultiInstProcessor {
@Test
public void te... | KubeHelper.inst("").delete("ns-test", KubeRES.NAME_SPACE);
Assert.assertFalse(KubeHelper.inst("").exist("ns-test", KubeRES.NAME_SPACE));
KubeHelper.inst("").create($.file.readAllByClassPath("ns-test.yaml", "UTF-8"));
Assert.assertTrue(KubeHelper.inst("").exist("ns-test", KubeRES.NAME_SP... |
86291168_20 | class SqlTaskSubmitter {
protected final <R> void submitSqlStatementTask(
CheckedSqlFunction<? super Statement, ? extends R> function,
BiConsumer<? super R, ? super Throwable> callback
) {
submit(new SqlStatementTask<>(function, wrapCallback(callback)));
}
protected fin... | addStages(submitter.submitSqlStatementTask(statement -> callCounter.addAndGet(1)));
assertThat(callCounter.get(), is(3));
}
} |
86325095_0 | class OptimisticAlexandriaMarkupClient {
public AppInfo getAbout() {
return unwrap(delegate.getAbout());
}
public OptimisticAlexandriaMarkupClient(final URI alexandriaURI);
public OptimisticAlexandriaMarkupClient(final String alexandriaURI);
public OptimisticAlexandriaMarkupClient(final URI alexandri... | AppInfo about = client.getAbout();
assertThat(about.getVersion()).isNotEmpty();
}
} |
86331365_134 | class Strings {
public static String substr(String str, int start) {
return StringUtils.substring(str, start);
}
private Strings();
public static Boolean isNullorEmpty(String string);
public static int findString(String searchExpr, String exprIn);
public static int findString(String ... | System.out.println("substr");
String str = "Juan Perez Benitez";
int start = 5;
int charactersReturned = 5;
String expResult = "Perez";
String result = Strings.substr(str, start, charactersReturned);
assertEquals(expResult, result);
start = 5;
... |
86339121_17 | class ContinuousOplogFetcher implements OplogFetcher {
@Override
public OplogBatch fetch() throws StopReplicationException, RollbackReplicationException {
if (state.isClosed()) {
return FinishedOplogBatch.getInstance();
}
try {
return retrier.retry(() -> {
try {
if (state... | int oplogSize = 1000;
List<OplogOperation> oplog = createInsertStream(this::createSimpleInsert)
.limit(oplogSize)
.collect(Collectors.toList());
oplogSupplier = () -> oplog;
OplogOperation firstOp = oplog.get(0);
ContinuousOplogFetcher fetcher = factory.createFetcher(firstOp.getHas... |
86369859_5 | class ColliderUtils {
public static boolean overlaping(float minA, float maxA, float minB, float maxB) {
if (maxA < minA) {
// swap values
float a = maxA;
maxA = minA;
minA = a;
}
if (maxB < minB) {
// swap values
floa... | assertEquals("values arent overlaping, but method returns true.", false, ColliderUtils.overlaping(0, 1, 2, 3));
assertEquals("values arent overlaping, but method returns true.", false,
ColliderUtils.overlaping(2, 3, 3.1f, 4));
assertEquals("values are overlaping, but method retur... |
86398553_5 | class Mockito {
public static <T> When<T> when(T t){
return new When<T>();
}
public static T mock(Class<T> t);
@Mock
private List mockList;
}
class MockitoTest {
@Mock
private List mockList;
@Test
public void testCallBack(){
| when(mockList.get(Integer.MAX_VALUE)).thenAnswer(invocation -> {
Object mock = invocation.getMock();
Object[] arguments = invocation.getArguments();
return new StringBuilder().append(mock).append(",").append(Arrays.asList(arguments)).toString();
});
System.ou... |
86400116_6 | class AccessPointURI {
public String getHosts() {
return hosts;
}
AccessPointURI(String accessPointString);
public String getAccessPointString();
public String getDriverType();
public String getAccountId();
public String getRegion();
private void validateAccessPointString(St... | AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI);
assertThat(accessPointURI.getHosts()).isEqualTo("rocketmq.apache.org");
String multipleHostsURI = "oms:rocketmq://alice@rocketmq.apache.org,pulsar.apache.org:9091/us-east:default_space";
accessPointURI = new AccessPointU... |
86418271_0 | class TwitterMessageProducer extends MessageProducerSupport {
StatusListener getStatusListener() {
return statusListener;
}
public TwitterMessageProducer(TwitterStream twitterStream, MessageChannel outputChannel);
@Override protected void onInit();
@Override public void doStart();
@Override public v... | StatusListener statusListener = twitterMessageProducer.getStatusListener();
Status status = mock(Status.class);
statusListener.onStatus(status);
Message<?> statusMessage = outputChannel.receive();
assertSame(status, statusMessage.getPayload());
}
} |
86422972_0 | class EmailValidator {
public static boolean isValidEmail(CharSequence email) {
return email != null && EMAIL_PATTERN.matcher(email).matches();
}
}
class EmailValidatorTest {
@Test public void isValidEmail() throws Exception {
| assertThat(EmailValidator.isValidEmail("jaredsburrows@gmail.com")).isTrue();
}
} |
86461287_24 | class JobServiceImpl implements JobService {
@Override
public long countNameDistinctly(long teamId) {
return jobRepository.countNameDistinctly(teamId);
}
@Autowired public JobServiceImpl(JobRepository jobRepository);
@Override public long countNameDistinctly();
@Autowired
private JobRepository jobReposito... | assertEquals(0, jobService.countNameDistinctly());
TeamLampsDTO team = teamService.create(new TeamCreateDTO("Team 1"));
LampDTO lampDTO = lampService.create(new LampCreateDTO("hueId", "Lampe 1", team.getId()));
assertEquals(0, jobService.countNameDistinctly(team.getId()));
LampUpdateDTO lampUpdateDTO... |
86607520_10 | class MacroRemover extends EntryFilter {
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
// Matches _VBA_PROJECT_CUR, VBA, ... :)
if (!isMacro(entryName)) {
return true;
}
LOGGER.info("Found Macros, removing them.");
StringBuilder infos = new StringB... | Entry entry = mock(Entry.class);
doReturn("_VBA_PROJECT_CUR").when(entry).getName();
assertFalse(instance.test(entry), "A macro entry should not be copied over");
BleachTestBase.assertThreatsFound(session, 1);
reset(session);
}
} |
86651310_0 | class Altitude implements IWrappedInteger<Altitude>, Comparable<Altitude> {
@Override
public int compareTo(final Altitude that) {
return Integer.compare(this.val, that.val);
}
public Altitude(final int val);
@Override public int intValue();
@Override public boolean equals(final Object object);
@Ov... | {
final Altitude a1 = new Altitude(0);
final Altitude a2 = new Altitude(0);
Assert.assertTrue(a1.compareTo(a2) == 0);
}
{
final Altitude a1 = new Altitude(1);
final Altitude a2 = new Altitude(2);
Assert.assertTrue(a1.compareTo(a2) < 0);
}
{
final Altitude ... |
86653231_59 | class FusionEngine extends LocationEngine implements LocationListener {
@Override public Location getLastLocation() {
final List<String> providers = locationManager.getAllProviders();
final long minTime = clock.getCurrentTimeInMillis() - RECENT_UPDATE_THRESHOLD_IN_MILLIS;
Location bestLocation = null;
... | assertThat(fusionEngine.getLastLocation()).isNull();
}
} |
86653876_0 | class ResourceUtil {
public static InputStream getResourceAsStream(String path) {
if (StrUtil.startWithIgnoreCase(path, CLASSPATH_PRE)) {
path = path.substring(CLASSPATH_PRE.length());
}
return getClassLoader().getResourceAsStream(path);
}
public static String getAbsolutePath(String path);
public static ... | InputStream resourceAsStream = ResourceUtil.getResourceAsStream("classpath:config/tio-quartz.properties");
Assert.assertNotNull(resourceAsStream);
try {
resourceAsStream.close();
} catch (IOException e) {
//ignore
}
}
} |
86663812_36 | class DiffUtils {
public static <T> Patch<T> diff(List<T> original, List<T> revised, DiffAlgorithmListener progress) {
return DiffUtils.diff(original, revised, new MyersDiff<>(), progress);
}
private DiffUtils();
public static Patch<T> diff(List<T> original, List<T> revised);
public stat... | final Patch<String> patch = DiffUtils.diff(Arrays.asList("hhh"), Arrays.
asList("hhh", "jjj", "kkk"), true);
assertNotNull(patch);
assertEquals(2, patch.getDeltas().size());
AbstractDelta<String> delta = patch.getDeltas().get(0);
assertTrue(delta instanceof Equal... |
86707239_25 | class Lex {
@NonNull
public static LexList list(@NonNull List<? extends CharSequence> items) {
return list(items.toArray(new CharSequence[]{}));
}
public static void init(@NonNull Application app);
public static void init(@NonNull Application app, @NonNull String openDelimiter, @NonNull St... | assertEquals("No items.", Lex.list(new CharSequence[]{})
.separator(", ")
.twoItemSeparator(" and ")
.lastItemSeparator(", and ")
.emptyText("No items.")
.make().toString());
}
} |
86711482_3 | class TokensReader {
public Tokens read(final File file) throws Throwable {
final Tokens tokens = new Tokens();
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = builder.parse(new BOMInputStream(new F... | File file = temp.newFile("main", "results.xml");
FileUtils.copyURLToFile(getClass().getResource("/results/tokensSingle.xml"), file);
Tokens tokens = sut.read(file);
Assert.assertEquals(1, tokens.getTokens().size());
Assert.assertEquals(10, tokens.getComplexity());
Token token = tokens.getTokens().get(0);
... |
86808110_225 | class ByQualifiedNameRegexMatcher implements CriteriaMatcher<Element, String> {
@Override
public boolean checkForMatchingCharacteristic(Element element, String toCheckFor) {
if (element != null && toCheckFor != null) {
String name = null;
switch (element.getKind()) {
... |
Element element = Mockito.mock(Element.class);
Name nameOfElement = Mockito.mock(Name.class);
Mockito.when(nameOfElement.toString()).thenReturn("XXX");
Mockito.when(element.getKind()).thenReturn(ElementKind.METHOD);
Mockito.when(element.getSimpleName()).thenReturn(nameOfEleme... |
86871676_13 | class BookingServiceImpl implements BookingService {
@Override
public List<Booking> getBookingsByUser(String user) {
try {
List<BookingImpl> bookingImpls = bookingRepository.findByCustomerId(user);
List<Booking> bookings = new ArrayList<Booking>();
for (Booking b : b... | when(bookingRepository.findByCustomerId(booking.getCustomerId())).thenReturn(singletonList(booking));
List<Booking> bookings = bookingService.getBookingsByUser(booking.getCustomerId());
assertThat(bookings, contains(booking));
}
} |
86918234_1 | class Traceur {
public static void enableLogging() {
enableLogging(new TraceurConfig(true));
}
private Traceur();
@SuppressWarnings({"unchecked", "rawtypes"}) public synchronized static void enableLogging(TraceurConfig config);
public static synchronized void disableLogging();
public... | // Assumption - Shims are not filtered when filtering is disabled
Traceur.enableLogging(new TraceurConfig(false));
try {
StreamFactory.createNullPointerExceptionObservable().blockingFirst();
Assertions.failBecauseExceptionWasNotThrown(Throwable.class);
} catch (Th... |
86987836_1 | class DialogManagerImpl implements DialogManager {
@Override
public void dismissDialog(final int dialogId) {
final Dialog dialog = mDialogInstances.get(dialogId);
if (dialog != null) {
dialog.dismiss();
mDialogInstances.remove(dialogId);
mDialogConfigs.remove... | // setup the callback
final DialogManagerCallback callback = createCallbackMock();
final Dialog dialogMock = createDialogMock();
when(callback.onCreateDialog(eq(KNOWN_DIALOG), isNull())).thenReturn(dialogMock);
mDialogManager.setCallback(callback);
mDialogManager.showDial... |
87095183_2 | class EmailCommandHandler {
public EmailAggregate getByUUID(String uuid) {
return EmailAggregate.from(uuid, eventSourcingService.getRelatedEvents(uuid));
}
public EmailCommandHandler(
EventSourcingService eventSourcingService,
EventPublisher eventPublisher
);
publ... | String uuid = "123";
Mockito.when(eventSourcingService.getAggregate(Mockito.anyString()))
.thenReturn(new EventStream());
EmailAggregate byUUID = commandHandler.getByUUID(uuid);
Assert.assertTrue(byUUID.getState().getEmail() == null);
}
} |
87212987_55 | class SymbolManager extends AnnotationManager<SymbolLayer, Symbol, SymbolOptions, OnSymbolDragListener, OnSymbolClickListener, OnSymbolLongClickListener> {
@UiThread
public List<Symbol> create(@NonNull String json) {
return create(FeatureCollection.fromJson(json));
}
@UiThread public SymbolManager(@NonNu... | symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController);
verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textRadialOffset(get("text-radial-offset")))));
SymbolOptions options = new SymbolOptions().withLatLng(n... |
87220385_0 | class TightCouplingProcessor {
public List<View> generateView() {
Assert.notNull(project, "Project must not be null");
Assert.notNull(projectEvent, "Event must not be null");
Assert.notNull(commit, "Commit must not be null");
Assert.notNull(commit, "Commit must contain files");
... |
MessageDigest md5 = java.security.MessageDigest.getInstance("MD5");
Commit commit = new Commit(Arrays.asList(new File("file1.txt"),
new File("file2.txt")));
Project project = new Project("test");
project.setIdentity(1L);
project.setOwner("test");
projec... |
87225655_0 | class InvocationStatistics {
public void addInvocation(Invocation invocation) {
numberOfInvocations++;
if (this.methodName != null) {
this.methodName = invocation.getMethodName();
}
this.recentDuration = invocation.getRecentDuration();
this.lastInvocationTimestam... | Invocation first = new Invocation(null, 15, null, 1);
Invocation second = new Invocation(null, 15, null, 2);
Invocation another = new Invocation(null, 30, null, 2);
this.cut.addInvocation(first);
this.cut.addInvocation(second);
this.cut.addInvocation(another);
lon... |
87289313_111 | class AreIn extends KoryphePredicate<Collection<?>> {
@JsonIgnore
public Collection<?> getValues() {
return allowedValues;
}
public AreIn();
public AreIn(final Collection<?> allowedValues);
public AreIn(final Object... allowedValues);
public void setValues(final Collection<?> a... | // Given
final AreIn filter = new AreIn(VALUE1);
// When
final String json = JsonSerialiser.serialise(filter);
// Then
JsonSerialiser.assertEquals(String.format("{%n" +
" \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.AreIn\",%n" +
" ... |
87336871_1224 | class AbstractOrganisationFinanceService extends BaseTransactionalService implements OrganisationFinanceService {
@Override
public ServiceResult<Boolean> isShowStateAidAgreement(long targetId, long organisationId) {
return getStateAidEligibilityForCompetition(targetId).andOnSuccess(eligibility -> {
... | competition.setStateAid(true);
when(organisationService.findById(organisationId)).thenReturn(serviceSuccess(organisation));
assertTrue((boolean) service.isShowStateAidAgreement(targetId, organisationId).getSuccess());
}
} |
87392130_25 | class OIDCCoreProtocolConfiguration extends AbstractOIDCFlowAwareProfileConfiguration implements InitializableComponent, AuthenticationProfileConfiguration {
public void setPostAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows) {
Constraint.isNotNull(flows, "Collection of flows c... | Assert.assertTrue(config.getPostAuthenticationFlows().isEmpty());
Collection<String> flows = new ArrayList<String>();
flows.add("value");
config.setPostAuthenticationFlows(flows);
Assert.assertTrue(config.getPostAuthenticationFlows().contains("value"));
}
} |
87402251_6 | class GreetingService {
public String greetFromRepoJpa() {
Hello databaseSide =
helloRepoJpa.save(new Hello(0, "Greetings from the paging and sorting database side"));
Optional<Hello> byId = helloRepoJpa.findById(databaseSide.getId());
return byId.orElse(new Hello(-99, "not found")).getMessage();... | String message = "message";
Hello saveObject = new Hello(0, message);
when(helloRepoJpaMock.save(any(Hello.class))).thenReturn(saveObject);
when(helloRepoJpaMock.findById(saveObject.getId())).thenReturn(Optional.of(saveObject));
assertThat(greetingService.greetFromRepoJpa(), is(message));
verif... |
87455763_63 | class NavigationViewEventDispatcher {
void onNavigationFinished() {
if (navigationListener != null) {
navigationListener.onNavigationFinished();
}
}
void initializeListeners(
@NonNull NavigationViewOptions navigationViewOptions,
@NonNull NavigationViewModel navigationViewModel... | NavigationViewEventDispatcher eventDispatcher = new NavigationViewEventDispatcher();
NavigationListener navigationListener = mock(NavigationListener.class);
eventDispatcher.onNavigationFinished();
verify(navigationListener, times(0)).onNavigationFinished();
}
} |
87548125_15 | class AbstractnessRule extends AbstractPackageAnalyzerRule implements PackageAnalyzerRule {
@Override
public void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model) {
final Integer maximum = Integer.valueOf(rule.param(PARAM_MAXIMUM));
for (final Package<Location> packageT... | final Model<Location> model = createModel();
subject.scanModel(sensorContext, activeRule, model);
// Check one issue on packageA
Assert.assertEquals(3, sensorContext.allIssues().size());
Map<String, Issue> issues = sensorContext.allIssues().stream().collect(
Collectors.toMap(issue -> issue.primaryLocatio... |
87556817_49 | class TextMarkupDocumentReader {
public TextMarkupDocument parseString(String text, final TextMarkupDocumentSection otherSection) {
ImmutableList<TextMarkupDocumentSection> textMarkupDocumentSections = this.parseString(text, this.firstLevelElements, true, "////");
if (otherSection != null) {
... | TextMarkupDocument doc = textMarkupDocumentReader.parseString(
"\n\n\r\n/*This is my comment that I want to ignore*/\n" +
"//// " + TextMarkupDocumentReader.TAG_METADATA + " k1=v1 k2=v2\r\n" +
"//// " + TextMarkupDocumentReader.TAG_METADATA + " k3=... |
87590893_59 | class MoreFutures {
@Deprecated
public static <V> V getDoneUnchecked(Future<V> future) {
/*
* We throw IllegalStateException, since the call could succeed later. Perhaps we "should" throw
* IllegalArgumentException, since the call could succeed with a different argument. Those
* exceptions' ... | ListeningExecutorService executorService =
MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
CountDownLatch latch = new CountDownLatch(1);
ListenableFuture<String> future = executorService.submit(() -> {
latch.await(1, TimeUnit.MINUTES);
... |
87839153_1 | class RoutersService {
public void put(final RouterMeta routerMeta) {
final JsonEventToLogger event = new JsonEventToLogger(this.getClass());
String logCorrelation = routerMeta.correlation;
event.put("correlation", logCorrelation);
try {
String key = MessageFormat.forma... | //Arrange
RouterMeta routerMeta = new RouterMeta();
routerMeta.groupId = "group-local";
routerMeta.localIP = "127.0.0.1";
routerMeta.version = "1";
String versionNewest = "2";
routerMeta.envId = "1";
routerMeta.zoneId = null;
Environment env = new... |
87859908_476 | class CountedAspect {
private Counter.Builder counter(ProceedingJoinPoint pjp, Counted counted) {
Counter.Builder builder = Counter.builder(counted.value()).tags(tagsBasedOnJoinPoint.apply(pjp));
String description = counted.description();
if (!description.isEmpty()) {
builder.d... | countedService.succeedWithMetrics();
Counter counter = meterRegistry.get("metric.success")
.tag("method", "succeedWithMetrics")
.tag("class", "io.micrometer.core.aop.CountedAspectTest$CountedService")
.tag("extra", "tag")
.tag("result", "s... |
87869865_3 | class StringUtils {
public static int skip_spaces_reverse(StringBuilder s, int pos) {
return skip_char_reverse(s, " \t\n\r", pos);
}
static boolean contains(char c, String what);
static int skip_char(StringBuilder s, String what, int pos);
static int skip_char_reverse(StringBuilder s, String what, int pos);
p... | System.out.println("skip_spaces_reverse");
assertEquals(15, StringUtils.skip_spaces_reverse(new StringBuilder("das ist ein Test"), 15));
assertEquals(10, StringUtils.skip_spaces_reverse(new StringBuilder("das ist ein \t Test"), 14));
assertEquals(10, StringUtils.skip_spaces_reverse... |
87910456_7 | class Feature6LoWPANProtocol extends Feature {
public boolean getNetworkNodeList(NetworkNodeListCallback callback) {
Log.d("6lowpan","getNetworkNodeList: "+mRequestTimeout);
if(mRequestTimeout !=null)
return false;
mNodeListCallback = callback;
getParentNode().enableNot... |
mFeature.getNetworkNodeList(mNodeListCallback);
NetworkRequest cmd = new NetworkRequest(mFeature.getLastWriteData());
Assert.assertEquals(GET_NODE_LIST_CMD_ID,cmd.getCommandId());
Assert.assertEquals(6,cmd.getLength());
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.