id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
91583905_213 | class SchemaHomology {
public boolean tablesMatch(Table table1, Table table2) {
noDifferences = true;
checkTable(table1, table2);
return noDifferences;
}
public SchemaHomology();
public SchemaHomology(DifferenceWriter differenceWriter);
public SchemaHomology(DifferenceWriter differenceWriter,... | assertFalse(schemaHomology.tablesMatch(pearTable, pearTableModifiedWidth));
}
} |
91584792_0 | class ByteArraySchema implements DeserializationSchema<byte[]>, SerializationSchema<byte[]> {
public TypeInformation<byte[]> getProducedType() { return PrimitiveArrayTypeInfo.BYTE_PRIMITIVE_ARRAY_TYPE_INFO; @Override
public TypeInformation<byte[]> getProducedType() { return PrimitiveArrayTypeInfo.BYTE_PRIMITIV... | final ByteArraySchema schema = new ByteArraySchema();
final ByteArraySchema copy = CommonTestUtils.createCopySerializable(schema);
assertEquals(schema.getProducedType(), copy.getProducedType());
}
} |
91595685_5 | class Sampler {
static Note extractMostFrequentNote(List<PitchDifference> samples) {
Map<Note, Integer> noteFrequencies = new HashMap<>();
for (PitchDifference pitchDifference : samples) {
Note closest = pitchDifference.closest;
if (noteFrequencies.containsKey(closest)) {
... | List<PitchDifference> samples = new ArrayList<>();
samples.add(new PitchDifference(G3, 2D));
samples.add(new PitchDifference(E2, 2D));
samples.add(new PitchDifference(B3, 3D));
samples.add(new PitchDifference(E2, 2D));
samples.add(new PitchDifference(B3, 3D));
N... |
91663814_3 | class LoginPresenter extends BaseRxJavaPresenter<LoginContract.View> implements LoginContract.Presenter {
@Override
public void onEdtUserNameChanged(String userName) {
if (!TextUtil.isEmpty(userName)) {
mView.showClearUserNameButton();
} else {
mView.hideClearUserNameBut... | mLoginPresenter.onEdtUserNameChanged("a");
verify(mLoginView).showClearUserNameButton();
}
} |
91674936_332 | class ServletUtils {
static void setServletParameters(ServletContext servletContext) {
UploadConfig uploadConfig = new UploadConfig();
MultipartConfigElement multipartConfig = uploadConfig.toMultipartConfigElement();
if (multipartConfig == null) {
return;
}
File dir = createUploadDir(servl... | Map<String, ServletRegistration> servletRegistrations = new HashMap<>();
servletRegistrations.put("d1", d1);
servletRegistrations.put("d2", d2);
new Expectations() {
{
servletContext.getServletRegistrations();
result = servletRegistrations;
d1.getClassName();
result... |
91725602_1 | class Castle {
public static boolean flushIfNeeded(String url) {
// Flush if request to whitelisted url
if (isUrlWhiteListed(url)) {
flush();
return true;
}
return false;
}
private Castle(Application application, CastleConfiguration castleConfigurat... | // Make sure flush is done for whitelisted base url
boolean flushed = Castle.flushIfNeeded("https://google.com/");
// FlushIfNeeded returns true if url is whitelisted and flush() is called
Assert.assertTrue(flushed);
// Make sure flush is NOT done for non whitelisted base url
... |
91826174_48 | class RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> {
@Override
protected Query getComponentQuery(final RRestoreBlobData data) throws IOException {
RRestoreFacet facet = getRestoreFacet(data);
RestoreBlobData blobData = data.getBlobData();
Map<String, String> attributes;
tr... | restoreBlobStrategy.getComponentQuery(rRestoreBlobData);
verify(rRestoreFacet, times(1)).getComponentQuery(anyMapOf(String.class, String.class));
}
} |
91952715_2 | class FileTools {
public static File doChooseFile(String extension, String directory, String type) {
if (MainWindow.getInstance().getActiveProject() != null) {
File projectPath = new File(System.getProperty("project.path") + File.separator + directory);
if (projectPath.exists()) {
... | System.out.println("doChooseFile");
String extension = "";
String directory = "";
String type = "";
File expResult = null;
File result = FileTools.doChooseFile(extension, directory, type);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call... |
91956337_0 | class WXBizMsgCrypt {
String encrypt(String randomStr, String text) throws AesException {
ByteGroup byteCollector = new ByteGroup();
byte[] randomStrBytes = randomStr.getBytes(CHARSET);
byte[] textBytes = text.getBytes(CHARSET);
byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
byte[] appid... | try {
WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
assertEquals(afterAesEncrypt, pc.encrypt(randomStr, replyMsg));
} catch (AesException e) {
e.printStackTrace();
fail("no异常");
}
}
} |
91984043_2 | class AvailableSegment extends Segment implements Serializable {
public void dataProvided(List<ITEM> items) {
if (items == null) {
dataProvided(items, 0);
} else {
dataProvided(items, getFrom() + items.size());
}
}
public AvailableSegment(UncoveringDataModel<?> model, int page);
publ... | AvailableSegment<TestItem> a = new AvailableSegment<>(model, 2);
assertNull(a.get(20));
assertNull(a.get(29));
assertNull(a.get(19));
assertNull(a.get(30));
assertEquals(0, a.getMaxIndex());
a.dataProvided(TestItem.range(20, 29));
assertEquals("p.20", a.get(20).toString());
assert... |
91984923_2 | class TomorrowWeatherViewModel extends WeatherViewModel {
public void loadForecastWeatherDataForTomorrow()
{
Location lastKnownLocation = locationService.lastLocation();
if (lastKnownLocation != null)
{
double longitude = lastKnownLocation.getLongitude();
double ... | when(locationService.lastLocation()).thenReturn(null);
vm.onViewAttached();
vm.loadForecastWeatherDataForTomorrow();
verifyZeroInteractions(weatherService);
}
} |
92027307_1 | class SyncTrigger {
public void check(){
check(false);
}
public SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold);
public SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold, ResetRule resetRule);
... |
SyncTrigger syncTrigger = new SyncTrigger(
() -> mockTrigger.triggered(),
() -> mockThreshold.shouldTrigger(),
ONLY_AFTER_REVERSION);
//no trigger
when(mockThreshold.shouldTrigger()).thenReturn(false);
syncTrigger.check();
verify(... |
92033442_103 | class XpathUtils {
public static Byte asByte(String expression, Node node)
throws XPathExpressionException {
String byteString = evaluateAsString(expression, node);
return (isEmptyString(byteString)) ? null : Byte.valueOf(byteString);
}
public static Document documentFrom(Input... | Document document = XpathUtils.documentFrom(DOCUMENT);
assertEquals(new Byte((byte) 123), XpathUtils.asByte("Foo/PositiveByte", document));
assertEquals(new Byte((byte) -99), XpathUtils.asByte("Foo/NegativeByte", document));
assertEquals(null, XpathUtils.asByte("Foo/Empty", document));
... |
92062193_3 | class PeriodicRateGenerator implements RateGenerator {
@Override
public double getRate(long time) {
double valueInPeriod = normalizeValue(time);
double result = rateFunction(valueInPeriod);
LOGGER.trace("rateFunction returned: {} for value: {}", result, valueInPeriod);
return re... | // GIVEN
ConcretePeriodicRateGenerator periodicRateGenerator = new ConcretePeriodicRateGenerator(100);
// WHEN
double rate = periodicRateGenerator.getRate(TimeUnit.SECONDS.toNanos(399));
// THEN
Assert.assertEquals(99d, rate, DELTA);
}
} |
92116596_22 | class LocalNotification implements ISerializable, IDeserializable {
public void deserialize(JSONObject jsonObject) {
if (jsonObject != null) {
code = jsonObject.optString("code", code);
tickerText = jsonObject.optString("tickerText", tickerText);
title = jsonObject.optSt... | try {
when(jsonObject.getJSONArray("actionData")).thenReturn(jsonArray);
when(jsonArray.length()).thenReturn(2);
when(jsonArray.getInt(0)).thenReturn(101);
when(jsonArray.getInt(1)).thenThrow(mock(JSONException.class));
getSubject().deserialize(jsonOb... |
92120027_58 | class SubStr {
public static String getSmallestAndLargest(String str, int k) {
if (str == null || str.length() < k || k <= 0) {
return "\n";
}
String smallest = str.substring(0, k);
String largest = smallest;
// Loop to check
for (int i = 1; i < str.len... | Map<String, String> mapIO = new HashMap<String, String>() {{
put("welcometojava", "ava\nwel");
}};
for (Map.Entry<String, String> io : mapIO.entrySet()) {
String ret = SubStr.getSmallestAndLargest(io.getKey(), 3);
Assert.assertEquals(io.getValue(), ret);
... |
92150440_1 | class HookMetadataParser {
SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException {
return parse(className -> true); // Parse all classes found in the JAR files.
}
public HookMetadataParser(Collection<Path> hookJars);
public SortedSet<HookMetadata> parse(Predicate<String>... | String expected = PrimitiveTypesTestHook.class.getName() + " instruments [com.example.Some]:\n" +
" * arrayArgs(java.lang.Object[], int[], java.lang.String[])\n" +
" * boxedArgs(java.lang.Boolean, java.lang.Character, java.lang.Byte, java.lang.Short, java.lang.Integer, java.lan... |
92184534_26 | class Fork implements IFork {
@Override
public boolean isPassed(int timestamp) {
return items.getFirst().isPassed(timestamp);
}
public Fork(BlockID genesisBlockID, ForkItem[] items, String beginAll);
public Fork(BlockID genesisBlockID, ForkItem[] items);
public Fork(BlockID genesisB... | assertFalse("Before fork", forkState.isPassed(50));
assertFalse("Fork started", forkState.isPassed(100));
assertFalse("On fork", forkState.isPassed(150));
assertFalse("Fork ended", forkState.isPassed(200));
assertTrue("After fork", forkState.isPassed(250));
}
} |
92225522_5 | class Queue {
void append(@NonNull MobileEventJson event) {
long now = Time.now();
if (event.userId == null) {
event.userId = userIdProvider.getUserId();
}
if (this.config.acceptSameEventAfter > 0 &&
state.lastEvent != null &&
now < stat... | Queue.UploadRequester uploadRequester = mock(Queue.UploadRequester.class);
Queue queue = new Queue(null, USER_ID_PROVIDER, uploadRequester,
new Queue.Config.Builder()
.withUploadWhenMoreThan(5)
.withUploadWhenOlderThan(10000)
... |
92269851_15 | class SentinelVersion {
public boolean greaterThan(SentinelVersion version) {
if (version == null) {
return true;
}
return getFullVersion() > version.getFullVersion();
}
public SentinelVersion();
public SentinelVersion(int major, int minor, int fix);
public S... | assertTrue(new SentinelVersion(2, 0, 0).greaterThan(new SentinelVersion(1, 0, 0)));
assertTrue(new SentinelVersion(1, 1, 0).greaterThan(new SentinelVersion(1, 0, 0)));
assertTrue(new SentinelVersion(1, 1, 2).greaterThan(new SentinelVersion(1, 1, 0)));
assertTrue(new SentinelVersion(1, 1,... |
92312271_14 | class SenseHatColor {
public static SenseHatColor fromRGB(int red, int green, int blue) {
short r = (short) ((red >> 3) & 0b11111);
short g = (short) ((green >> 2) & 0b111111);
short b = (short) ((blue >> 3) & 0b11111);
return new SenseHatColor(r, g, b);
}
SenseHatColor(... | assertThat(SenseHatColor.fromRGB(0f ,0f, 1f).getSenseHatColor()).isEqualTo(0x001F);
}
} |
92362395_119 | class ConfigUtils {
public static Properties loadProperties(String fileName) {
return loadProperties(fileName, false, false);
}
private ConfigUtils();
public static boolean isNotEmpty(String value);
public static boolean isEmpty(String value);
public static boolean isDefault(String v... | Properties p = ConfigUtils.loadProperties("notExisted", true);
Properties expected = new Properties();
Assert.assertEquals(expected, p);
p = ConfigUtils.loadProperties("notExisted", false);
Assert.assertEquals(expected, p);
}
} |
92375988_132 | class ProxyDestructor implements CancellableCleanAction<Class<?>> {
@Override
public void clean() {
if (destroyed || cancelled) {
return;
}
destroyed = true;
// Do not perform the destructor if the native handle is not valid.
if (!nativeHandle.isValid()) {
return;
}
long ... | long rawNativeHandle = 1L;
NativeHandle handle = spy(new NativeHandle(rawNativeHandle));
LongConsumer destructor = mock(LongConsumer.class);
ProxyDestructor d = newDestructor(handle, destructor);
// Clean multiple times.
int attemptsToClean = 3;
for (int i = 0; i < attemptsToClean; i++) {
... |
92377986_4 | class RegisterViewModel extends BaseViewModel {
protected boolean isLoginValid() {
boolean valid = true;
if (mLoginValidator != null && !mLoginValidator.isValid(mLogin.get())) {
mLoginError.set(mViewAccess.getLoginErrorMessage());
valid = false;
} else {
... | when(mModel.mLoginValidator.isValid(any())).thenReturn(false);
when(mModel.mViewAccess.getLoginErrorMessage()).thenReturn("error");
assertThat(mModel.isLoginValid(), is(false));
assertThat(Strings.isNullOrEmpty(mModel.mLoginError.get()), is(false));
}
} |
92469890_21 | class TimeUtils {
public static Date getNowDate() {
return new Date();
}
private TimeUtils();
public static String millis2String(long millis);
public static String millis2String(long millis, DateFormat format);
public static long string2Millis(String time);
public static long str... | assertEquals(System.currentTimeMillis(), TimeUtils.date2Millis(TimeUtils.getNowDate()), delta);
}
} |
92486066_10 | class BuildEventHandler implements EventHandler {
@Override
public void processEvents(final List<Event> eventList, final Set<String> dashboardIds) {
final List<String> ids = eventList.stream()
.map(Event::getCollectionId)
.map(String.class::cast)
.collect(Collectors.... | final Dashboard dashboard1 = new Dashboard()
.setName("dashboard1")
.setCodeRepos(Arrays.asList("http://repo1.git", "http://repo2.git"));
final Dashboard dashboard2 = new Dashboard()
.setName("dashboard2")
.setCodeRepos(Arrays.asList(".*repo3.*", "http://r... |
92500825_0 | class DataServiceBase implements TableDataService {
@Override
public List<Map<String, String>> getPageEntries(PaginationCriteria paginationCriteria) throws TableDataException {
List<T> data = getData(paginationCriteria);
log.debug("Table data retrieved...");
List<Map<String, String>> r... | List<Map<String, String>> data = dataService.getPageEntries(null);
assertEquals(5, data.size());
assertEquals("Lisa", data.get(0).get("name"));
assertEquals("2", data.get(1).get("id"));
assertEquals("38", data.get(2).get("age"));
}
} |
92515991_163 | class ChainedFailedMessageAction implements FailedMessageAction {
@Override
public void accept(FailedMessage failedMessage) {
actions.forEach(action -> action.accept(failedMessage));
}
public ChainedFailedMessageAction(@JsonProperty("actions") List<FailedMessageAction> actions);
@Overrid... | ChainedFailedMessageAction underTest = new ChainedFailedMessageAction(Arrays.asList(
failedMessageAction1, failedMessageAction2
));
underTest.accept(failedMessage);
verify(failedMessageAction1).accept(failedMessage);
verify(failedMessageAction2).accept(failedMes... |
92536940_1 | class CircularBuffer {
@SuppressWarnings("unchecked")
public T getItem(int index) {
int target = head - index;
if (target < 0) target = queue.length + target;
return (T) queue[target];
}
public CircularBuffer(int size);
public void enqueue(T item);
public int size();
... | CircularBuffer<Integer> queue = new CircularBuffer<>(3);
queue.enqueue(0);
assertEquals((Integer) 0, queue.getItem(0));
queue.enqueue(1);
assertEquals((Integer) 1, queue.getItem(0));
assertEquals((Integer) 0, queue.getItem(1));
queue.enqueue(2);
assertEqua... |
92611668_3 | class KubeCloudClient implements CloudClientEx {
@Override
public boolean canStartNewInstance(@NotNull CloudImage cloudImage) {
KubeCloudImage kubeCloudImage = (KubeCloudImage) cloudImage;
String kubeCloudImageId = kubeCloudImage.getId();
if(!myImageIdToImageMap.containsKey(kubeCloudIma... | KubeCloudImage image = m.mock(KubeCloudImage.class);
m.checking(new Expectations(){{
allowing(image).getName(); will(returnValue("image-1-name"));
allowing(image).getId(); will(returnValue("image-1-id"));
allowing(image).getRunningInstanceCount(); will(returnValue(0))... |
92615561_5 | class BoltCursor implements AutoCloseable {
public BoltKeyValue next() {
try(KeyValue.ByValue keyValue = BoltNative.BoltDBCursor_Next(objectId)) {
return keyValue.hasKeyValue() ? new BoltKeyValue(keyValue.getKey(), keyValue.getValue()) : null;
}
}
public BoltCursor(long object... | try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) {
bolt.update(boltTransaction -> {
try (BoltBucket ignored1 = boltTransaction.createBucket("test1".getBytes())) {
try (BoltBucket ignored2 = boltTransaction.createBucket("test2".getBytes())) {
... |
92632486_1 | class TableStats {
public int estimateTableCardinality(double selectivityFactor) {
// some code goes here
return (int) Math.ceil(totalTuples() * selectivityFactor);
}
public TableStats(int tableid, int ioCostPerPage);
public static TableStats getTableStats(String tablename);
publ... | TableStats s = new TableStats(this.tableId, IO_COST);
// Try a random selectivity
Assert.assertEquals(306, s.estimateTableCardinality(0.3));
// Make sure we get all rows with 100% selectivity, and none with 0%
Assert.assertEquals(1020, s.estimateTableCardinality(1.0));
Assert.assertEquals(0, s.estimat... |
92746837_311 | class MetadataReportBuilder extends AbstractBuilder<MetadataReportConfig, MetadataReportBuilder> {
public MetadataReportBuilder address(String address) {
this.address = address;
return getThis();
}
public MetadataReportBuilder username(String username);
public MetadataReportBuilder pas... | MetadataReportBuilder builder = new MetadataReportBuilder();
builder.address("address");
Assertions.assertEquals("address", builder.build().getAddress());
}
} |
92755785_4 | class EmailValidator {
public boolean isValid(CharSequence email) {
return email != null && EMAIL_ADDRESS.matcher(email).matches();
}
public Observable<Boolean> checkEmail(CharSequence email);
EmailValidator tested;
}
class EmailValidatorTest {
EmailValidator tested;
@Test
public void should_... | assertThat(tested.isValid(null)).isFalse();
}
} |
92768732_18 | class GroovyConditionShell {
public ConditionScript parse(final String script) throws ConditionParsingException {
return parse(script, true);
}
public GroovyConditionShell(final GroovyConditionCache conditionCache);
private ConditionScript parse(
final String script,
final bo... | ConditionScript parsedScript = this.shell.parse(script);
Assert.assertNotNull(parsedScript);
}
} |
92944959_7 | class Singleton4 {
public static final Singleton4 getInstance() {
if (INSTANCE == null) {
INSTANCE = Singleton4Holder.obj ;
}
return INSTANCE ;
}
private Singleton4();
}
class Singleton4Test {
@Test
public void test_single() {
|
Assert.assertTrue(Singleton4.getInstance() == Singleton4.getInstance());
}
} |
92951080_4 | class LCOVSensor implements Sensor {
public boolean shouldExecuteOnProject(Project project) {
return _1C.KEY.equalsIgnoreCase(project.getLanguageKey())
&& StringUtils.isNotBlank(_1c.getSettings().getString(_1CPlugin.LCOV_REPORT_PATH));
}
public LCOVSensor(_1C _1c);
public void analyse(Project proj... | Project project = mockProject(new Java());
assertThat(sensor.shouldExecuteOnProject(project)).isFalse();
project = mockProject(new _1C(settings));
assertThat(sensor.shouldExecuteOnProject(project)).isTrue();
settings.setProperty(_1CPlugin.LCOV_REPORT_PATH, "");
assertThat(sensor.shouldExecuteO... |
92956570_25 | class BuildConfiguration implements Serializable {
public ArchiveCompression getCompression() {
return compression;
}
public BuildConfiguration();
public boolean isDockerFileMode();
public String getDockerFile();
public String getDockerArchive();
public String getContextDir();
... | BuildConfiguration config =
new BuildConfiguration.Builder().
compression("gzip").build();
assertEquals(gzip, config.getCompression());
config = new BuildConfiguration.Builder().build();
assertEquals(none, config.getCompression());
config =
... |
92974732_0 | class ObjModel extends IndexedModel {
protected static void parseInts(String str, int[] ints) {
int len = str.length();
int intIndex = 0;
int currentInt = -1;
ints[0] = -1;
ints[1] = -1;
ints[2] = -1;
for (int i = 0; i < len; i++) {
char c = str.... | int[] ints = new int[4];
ObjModel.parseInts("1/2/3", ints);
assertEquals(ints[0], 1);
assertEquals(ints[1], 2);
assertEquals(ints[2], 3);
ObjModel.parseInts("111/222/333/444", ints);
assertEquals(ints[0], 111);
assertEquals(ints[1], 222);
assertE... |
92980167_129 | class EncryptedBatchWriter implements BatchWriter {
@Override
public void addMutation(Mutation mutation) throws MutationsRejectedException {
for (ColumnUpdate update : mutation.getUpdates()) {
MutableEntry entry = new MutableEntry(mutation.getRow(), update);
if (update.isDeleted()) {
if (!... | when(mockConnector.createBatchWriter(TEST_TABLE, null)).thenReturn(mockWriter);
BatchWriter writer = new EncryptedBatchWriter(mockConnector, TEST_TABLE, null, getConfig("encrypt-entry.ini"), KEYS);
Mutation mutation = new Mutation("row".getBytes());
mutation.putDelete("colF1".getBytes(), "colQ".getByte... |
92982984_62 | class TypeFetchers {
public static TypeFetcher fromTypes() {
return new TypeFetcher() {
// this is technically invalid, as different apis might call. Won't happen, but could.
// make better
Iterable<TypeDeclaration> foundInApi;
@Override
public... |
when(api.types()).thenReturn(Arrays.asList(t1, t2, t3));
TypeDeclaration typeDeclaration = TypeFetchers.fromTypes().fetchType(api, "t1");
assertSame(t1, typeDeclaration);
}
} |
93055348_0 | class Highlight extends UserNote implements Comparable<Highlight> {
@NonNull
public static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized,
PageInfo pageInfo,
... | ArrayList<ContentValues> highlightsReturn = Highlight.deserializeToContentValues(serialized1,pagId,0);
ArrayList<ContentValues> highlightsGiven = new ArrayList<>();
ContentValues contentValues = new ContentValues();
contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_PAGE_I... |
93131587_43 | class CodeGenerator {
public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) {
Objects.requireNonNull(tables);
//get package from the table models
final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName();
... | Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:rt-cg-main", "", "");
assertNotNull(connection);
File tempFile = Helpers.getResourceAsFile("codegenerator/test.sql");
assertNotNull(tempFile);
DatabaseManager.executePreparationScripts(connect... |
93181581_6 | class SqlStringUtils {
public static StatementKind getStatementKind(String sql)
{
String prefix = sql.trim();
prefix = prefix.length() < 10 ? prefix : prefix.substring(0, 10);
prefix = prefix.toLowerCase();
if (prefix.startsWith("select"))
{
return SELECT;
... | assertThat(
SqlStringUtils.getStatementKind(" SELECT * FROM FOO"),
is(SELECT)
);
assertThat(
SqlStringUtils.getStatementKind("insert into alabalanicafoorbar values ()"),
is(INSERT)
);
asse... |
93201544_1 | class LoggerRegistry {
public <T extends LogEvent> Logger<T> getLogger(Supplier<?> supplier, Function<? super LoggerKey, ? extends Logger> builder) {
final String name = getLoggerName();
return getLogger(name, supplier, builder);
}
public Logger<T> getLogger(String name, Supplier<?> supplier, Function<?... | final Logger logEventLogger = LoggerFactory.getLogger();
logEventLogger.debug(e -> String.format("Logger %s ", logEventLogger.getName()));
final Logger<SpecializedLogEvent> specializedLogEventLogger =
LoggerFactory.getLogger(new SpecializedLogEventSupplier());
assertFalse(logEventLogg... |
93268041_15 | class SecretsManager {
public void assertCurrentStageExists(final String secretId) {
final GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest();
getSecretValueRequest.setSecretId(secretId);
getSecretValueRequest.setVersionStage(CURRENT.getAwsName());
getDelegate... | // given
final GetSecretValueRequest request = new GetSecretValueRequest();
request.setSecretId("secret");
request.setVersionStage("AWSCURRENT");
given(delegate.getSecretValue(eq(request))).willThrow(new ResourceNotFoundException("not found"));
// when / then (exception ... |
93307435_0 | class HeapUnit {
public static HeapImage captureHeap() throws IOException {
String path = "target/heapunit/" + System.currentTimeMillis() + ".hprof";
return new SimpleHeapImage(HeapDumpProcuder.makeHeapDump(path, TimeUnit.SECONDS.toMillis(60)));
}
}
class HeapUnitTest {
@Test
public ... |
@SuppressWarnings("unused")
TestInstance tt = new TestInstance();
HeapImage hi = HeapUnit.captureHeap();
System.out.println("String count: " + hi.instanceCount(String.class));
Assert.assertTrue(hi.instanceCount(String.class) > 0);
System.out.pr... |
93314642_136 | class NumberScalingUtils {
public static BigInteger translate(
final BigInteger sourceAmount, final int sourceScale, final int destinationScale
) {
Objects.requireNonNull(sourceAmount, "sourceAmount must not be null");
Preconditions.checkArgument(sourceAmount.compareTo(BigInteger.ZERO) >= 0, "sourceAmo... | assertThat(NumberScalingUtils.translate(
sourceSettlementQuantity.amount(), sourceSettlementQuantity.scale(), expectedSettlementQuantity.scale()
)).as(description).isEqualTo(expectedSettlementQuantity.amount());
}
} |
93364077_10 | class AttractionRepository {
@VisibleForTesting
static AttractionCollection buildNightLifeCollection() {
ArrayList<Attraction> attractions = new ArrayList<>();
attractions.add(new Attraction(
R.drawable.social,
R.string.social_title,
... | assertThat(AttractionRepository.buildNightLifeCollection(), instanceOf(AttractionCollection.class));
}
} |
93389699_3 | class CompositeValidator extends Validator<T> {
@Override public void validate(T t) throws CompositeValidationException {
List<ValidationException> exceptions = new ArrayList<>();
for (Validator<? super T> validator : validators) {
try {
validator.validate(t);
} catch (ValidationException... | try {
reflectiveValidator.validate(new Foo(5));
reflectiveValidator.validate(new Foo(6));
reflectiveValidator.validate(new Foo(7));
reflectiveValidator.validate(new Foo(8));
reflectiveValidator.validate(new Foo(9));
reflectiveValidator.validate(new Foo(10));
} catch (Validati... |
93475299_4 | class TracingCallback implements Callback {
@Override
public void onCompletion(RecordMetadata metadata, Exception exception) {
if (exception != null) {
for (SpanDecorator decorator : spanDecorators) {
decorator.onError(exception, span);
}
}
try (Scope ignored = tracer.scopeManager(... | Span span = mockTracer.buildSpan("test").start();
try (Scope ignored = mockTracer.activateSpan(span)) {
TracingCallback callback = new TracingCallback(null, span, mockTracer,
Arrays.asList(SpanDecorator.STANDARD_TAGS, createDecorator()));
callback.onCompletion(null, new RuntimeException("t... |
93584385_175 | class CMSClient {
public void updateActionOrderState(DelegateExecution exec, CmsActionOrderSimple aos, String newState) {
aos.setActionState(OpsActionState.valueOf(newState));
try {
if (newState.equalsIgnoreCase(COMPLETE)) {
CmsActionOrder ao = cmsUtil.custSimple2Action... | DelegateExecution delegateExecution = mock(DelegateExecution.class);
CmsOpsProcedure cmsOpsProcedure = mock(CmsOpsProcedure.class);
when(delegateExecution.getVariable("proc")).thenReturn(cmsOpsProcedure);
CmsActionOrderSimple cmsActionOrderSimple= new CmsActionOrderSimple();
cmsActionOrderSimple.setActionId(... |
93627493_4 | class PlaceHolderManager {
public static String processMessage(String message, BungeeChatContext context) {
final StringBuilder builder = new StringBuilder();
final List<BungeeChatPlaceHolder> placeholders =
getApplicableStream(context).collect(Collectors.toList());
processMessageInternal(messag... | final String message = "Test %xxx% %hi%";
assertEquals(message, PlaceHolderManager.processMessage(message, EMPTY_CONTEXT));
}
} |
93642073_6 | class Registry {
public boolean isInRegistry(String url) {
if (getMockedEndpointsMethod == null) {
return false;
}
Set<String> mockedEndpoints = getMockedEndpoints();
for (String endpoint : mockedEndpoints) {
if (endpointMatches(endpoint, url)) {
... | // Given
MocksRegistry.setRegistry(new HashSet<>(asList(
"/path3/path4",
"/path1/path2"
)));
// When
boolean result = testee.isInRegistry("http://example.com/path3/path4?someArg=a&otherArg=b");
// Then
assertTrue(result);
}
} |
93682788_19 | class PeoplePresenter implements PeopleContract.Presenter, LoaderManager.LoaderCallbacks<List<Person>> {
@Override
public void onLoadFinished(Loader<List<Person>> loader, List<Person> data) {
// This callback may be called twice, once for the cache and once for loading
// the data from the ser... |
mPeoplePresenter.onLoadFinished(mock(Loader.class), null);
verify(mPeopleView).showLoadingPeopleError();
}
} |
93754068_10 | class CollectionManagementService {
protected void checkAndInstallConfiguration(String configName) throws IOException {
this.checkAndInstallConfiguration(configName, false);
}
public CollectionManagementService(List<String> zkHosts);
public CollectionManagementService(List<String> zkHost, St... | String configName = "com.rbmhtechnology.vind:backend-solr:1.1.2";
service.checkAndInstallConfiguration(configName);
assertTrue(service.configurationIsDeployed(configName));
}
} |
93782049_221 | class FormatOptionHandler {
public static Object parse(final VType value, String text, final FormatOption format)
{
try
{
switch (format)
{
case STRING:
return text;
case HEX:
{ // Remove trailing text (units or part ... | VType value = VDouble.of(3.16, Alarm.none(), Time.now(), display);
Object parsed = FormatOptionHandler.parse(value, "42.5 Socks", FormatOption.DEFAULT);
assertThat(parsed, instanceOf(Number.class));
assertThat(((Number)parsed).doubleValue(), equalTo(42.5));
}
} |
93861612_50 | class FeatureFileContentRenderer {
private String formatDocString(final String docString) {
if (docString == null || docString.isEmpty()) {
return "";
}
return "\"\"\"" + LINE_SEPARATOR + docString + LINE_SEPARATOR + "\"\"\"" + LINE_SEPARATOR;
}
private String getRender... | String expectedOutput = "Feature: featureName\n" +
"\n" +
"Scenario: scenarioName\n" +
"Step 1\n" +
"\"\"\"\n" +
"DOCSTRING LINE 1\n" +
"DOCSTRING LINE 2\n" +
"\"\"\"\n" +
"\n# Source ... |
93868467_35 | class RedisList extends Commands {
public String index(String key, long index) {
return getJedis().lindex(key, index);
}
private RedisList();
public synchronized static RedisList getInstance();
public long rPush(String key, String... values);
public long lPush(String key, String... values);
public... | deleteKeyForTest();
redisList.rPush(testKey,"tests");
String result = redisList.index(testKey, 0L);
Assert.assertEquals("tests", result);
deleteKeyForTest();
}
} |
93951167_2 | class SplashUrlDecoder {
public static LaunchData getLaunchType(String launchUri) {
if (launchUri == null) {
launchUri = "";
}
LaunchData data;
if (launchUri.contains(ADD_ISSUER_PATH)) {
data = handleAddIssuerUri(launchUri);
if (data != null) {
... | LaunchData launchData = SplashUrlDecoder.getLaunchType(ADD_ISSUER_URL);
assertEquals(ADD_ISSUER, launchData.getLaunchType());
assertEquals("https://certificates.learningmachine.com/issuer/asdf.json", launchData.getIntroUrl());
assertEquals("a*bcd", launchData.getNonce());
}
} |
93973957_0 | class Cloud {
public void createPacketsFile() {
File packetsFile = new File(this.sharedDir, "Packets.txt");
if (packetsFile.exists()) {
try {
packetsFile.createNewFile();
} catch (IOException e) {
log.error("Cannot create", e);
}
}
try (PrintWriter writer = new PrintWriter(new FileOutputStrea... | Cloud cloud = new Cloud();
cloud.createPacketsFile();
File file = new File(cloud.getSharedDir(), "Packets.txt");
try (BufferedReader inputStream = new BufferedReader(new FileReader(file))) {
List<String> lines = inputStream.lines().collect(Collectors.toList());
for (int i = 0; i < lines.size(); i++) {
... |
94000641_0 | class QuestionRepository implements QuestionDataSource {
@Override public Flowable<List<Question>> loadQuestions(boolean forceRemote) {
if (forceRemote) {
return refreshData();
} else {
if (caches.size() > 0) {
// if cache is available, return it immediately
return Flowable.just(c... | // Given
repository.caches.addAll(questions);
// When
repository.loadQuestions(false).subscribe(questionsTestSubscriber);
// Then
// No interaction with local storage or remote source
verifyZeroInteractions(localDataSource);
verifyZeroInteractions(remoteDataSource);
questionsTestS... |
94090559_61 | class CacheUtils {
public long getCacheSize() {
return mCacheManager.getCacheSize();
}
private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount);
public static CacheUtils getInstance();
public static CacheUtils getInstance(String cacheName);
public static CacheUtils getI... | Assert.assertEquals(FileUtils.getDirLength(file1), mCacheUtils1.getCacheSize());
Assert.assertEquals(FileUtils.getDirLength(file2), mCacheUtils2.getCacheSize());
}
} |
94165107_13 | class PageHelper {
public <P extends BasePageObject<P>> P newInstance(Class<P> expectedPage, Object... params) {
try {
// Account for PageObjects that only have a BrowserBasedTest constructor.
if (params.length > 0) {
Class<?>[] constructorArguments = new Class<?>[2... |
PageHelper tpo = setUpMocks();
TestPageObject testPageObject = tpo.newInstance(TestPageObject.class);
assertNotNull("Should not be null when constructing instance of "
+ TestPageObject.class.getName(),
testPageObject);
}
} |
94222613_4 | class BaggageMetricLabel implements MetricLabel {
@Override
public Object value(SpanData spanData) {
Object ret = spanData.getBaggageItem(name());
return ret == null ? defaultValue : ret;
}
public BaggageMetricLabel(String name, Object defaultValue);
@Override public String name(... | MetricLabel label = new BaggageMetricLabel(TEST_LABEL, TEST_LABEL_DEFAULT);
SpanData spanData = mock(SpanData.class);
when(spanData.getBaggageItem(anyString())).thenReturn("BaggageValue");
assertEquals("BaggageValue", label.value(spanData));
verify(spanData, times(1)).ge... |
94284531_10 | class ShadowResources {
public String getString(@StringRes int id) throws NotFoundException {
return getText(id).toString();
}
public ShadowResources();
@NonNull protected CharSequence getText(@StringRes int id);
@NonNull public String[] getStringArray(@ArrayRes int id);
@NonNull pub... | Assert.assertEquals("KBUnitTest", resources.getString(R.string.test_string));
}
} |
94457960_67 | class JSPackagerClient implements ReconnectingWebSocket.MessageCallback {
@Override
public void onMessage(ResponseBody response) {
if (response.contentType() != WebSocket.TEXT) {
FLog.w(
TAG,
"Websocket received message with payload of unexpected type " + response.contentType());
re... | RequestHandler handler = mock(RequestHandler.class);
final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler));
client.onMessage(
ResponseBody.create(
WebSocket.TEXT,
"{\"version\": 2}"));
verify(handler, never()).onNoti... |
94459145_2 | class PdfParser {
public static Codebook parseCodebookPdf(SupportedCodebook codebookSource) {
try (InputStream codebookPdfStream = codebookSource.getCodebookPdfInputStream();) {
List<String> codebookTextLines = extractTextLinesFromPdf(codebookPdfStream);
Codebook codebook = new Codebook(codebookSource);
... | for (SupportedCodebook supportedCodebook : SupportedCodebook.values()) {
LOGGER.info("Looking for sections in codebook: {}", supportedCodebook.name());
Codebook codebook = PdfParser.parseCodebookPdf(supportedCodebook);
/*
* Since this test runs against all of the PDFs, it's mostly just a
* "make su... |
94524678_483 | class Configuration extends AbstractConfiguration {
public boolean isDisplaySearchRssLinks() {
return getLocalBoolean("rss.displaySearchRssLinks", true);
}
public Configuration(String configFilePath);
protected static Set<String> loadStopwords(String stopwordsFilePath);
public Set<String... | Assert.assertFalse(DataManager.getInstance().getConfiguration().isDisplaySearchRssLinks());
}
} |
94570463_0 | class RxStores {
public static <STATE> Observable<STATE> states(Store<STATE> store) {
if (store == null) {
throw new IllegalArgumentException("Store is null");
}
return Observable.create(new StoreOnSubscribe<>(store), BackpressureMode.ERROR);
}
private RxStores();
}
class RxStoresTest {
... | //GIVEN
Store<Integer> store = new Store<>(0);
TestSubscriber<Integer> testSubscriber = new TestSubscriber<>();
//WHEN
states(store).subscribe(testSubscriber);
//THEN
testSubscriber.assertNoTerminalEvent();
testSubscriber.assertValue(0);
}
} |
94627909_0 | class CameraClient {
public Call<State> state() {
return service.state();
}
public CameraClient();
CameraClient(String basePath);
public Call<Info> info();
public Call<ListFiles.Response> listFiles(ListFiles listFilesCommand);
public Call<Status> commandStatus(Command.CommandId id);
private C... | final MockResponse mockResponse = new MockResponse()
.setResponseCode(200)
.setBody(loadFile("fixtures/cameraStateResponse.json"));
server.enqueue(mockResponse);
final Response<State> response = client.state().execute();
assertThat(response.code(), equalTo(200));
final State state... |
94631072_0 | class LocationFragment extends LifecycleFragment implements LocationListener {
@Override
public void onAttach(Context context) {
super.onAttach(context);
FragmentActivity activity = getActivity();
LocationViewModel locationViewModel = getViewModelProvider(activity).get(LocationViewModel... |
locationFragment.onAttach(context);
verify(locationLiveData).observe(eq(locationFragment), any(Observer.class));
}
} |
94749724_21 | class AddEditNotePresenter implements
AddEditNoteContract.Presenter, TokenCompleteTextView.TokenListener<Tag> {
@Override
public void saveNote(String noteNote, List<Tag> noteTags) {
if (isNewNote()) {
createNote(noteNote, noteTags);
} else {
updateNote(noteNote, ... | String noteNote = defaultNote.getNote();
String linkId = defaultNote.getLinkId();
List<Tag> noteTags = defaultNote.getTags();
when(repository.saveNote(any(Note.class), eq(false)))
.thenReturn(Observable.just(DataSource.ItemState.DEFERRED));
presenter.saveNote(not... |
94803952_27 | class MarkLogicBooleanQuery extends MarkLogicQuery implements BooleanQuery,MarkLogicQueryDependent {
@Override
public boolean evaluate() throws QueryEvaluationException {
try {
sync();
return getMarkLogicClient().sendBooleanQuery(getQueryString(), getBindings(), getIncludeInferr... | String queryString = "ASK {GRAPH <http://example.org/test/g27> {<http://semanticbible.org/ns/2006/NTNames#Shelah1> ?p ?o}}";
conn.setOptimizeLevel(0);
BooleanQuery booleanQuery = conn.prepareBooleanQuery(QueryLanguage.SPARQL, queryString);
boolean results = booleanQuery.evaluate();
... |
94876336_0 | class HelloWorld {
public static String getHelloWorld() {
return "Hello from Java!";
}
}
class HelloWorldTest {
@Test
public void testHelloWorld() {
| assertEquals("Hello from Java!", HelloWorld.getHelloWorld());
}
} |
94914141_3 | class LiveboardImpl extends StopLocationImpl implements Liveboard, Serializable {
public LiveboardType getLiveboardType() {
return mType;
}
public LiveboardImpl(StopLocation station, VehicleStop[] stops, DateTime searchTime, LiveboardType type, QueryTimeDefinition timeDefinition);
public Veh... | DateTime mDateTime = DateTime.now();
StopLocation station = Mockito.mock(StopLocation.class);
Mockito.when(station.getHafasId()).thenReturn("008814001");
VehicleStop stop = Mockito.mock(VehicleStop.class);
VehicleStop[] stops = new VehicleStop[]{stop};
Liveboard departing... |
94987426_0 | class Base32Utils {
public static String encode(byte[] input) {
byte b;
int symbol;
int carry = 0;
int shift = 3;
StringBuilder sb = new StringBuilder();
for (byte value : input) {
b = value;
symbol = carry | (b >> shift);
sb.appe... | assertEquals("MY", Base32Utils.encode("f".getBytes()));
assertEquals("MZXQ", Base32Utils.encode("fo".getBytes()));
assertEquals("MZXW6", Base32Utils.encode("foo".getBytes()));
assertEquals("MZXW6YQ", Base32Utils.encode("foob".getBytes()));
assertEquals("MZXW6YTB", Base32Utils.enc... |
95187094_29 | class HttpStubAuthenticatorConfig {
@Override
public String toString() {
return "HttpStubAuthenticatorConfig [uri: " + uri + ", poolSize: " + poolSize + ", timeoutMillis: " + timeoutMillis + "]";
}
public HttpStubAuthenticatorConfig withURI(URI uri);
public HttpStubAuthenticatorConfig withPoolSize(int p... | try (HttpStubAuthenticator auth = new MappingContext()
.withParser(new SnakeyamlParser())
.fromStream(HttpStubAuthenticatorConfigTest.class.getClassLoader().getResourceAsStream("http-stub-auth-config.yaml"))
.map(HttpStubAuthenticator.class)) {
assertEquals(new URI("http://localhost:80... |
95211078_2 | class CamtUtil {
public static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd) {
try (ByteArrayInputStream xmlAsStream = new ByteArrayInputStream(xmlAsBytes);
InputStream xsdAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathToXsd)) {
SchemaFactory fa... | byte[] bytes = readXml(INVALID_XML);
assertFalse(CamtUtil.isMatchingXsdSchema(bytes, CAMT054V00104.getXsdPath()));
assertFalse(CamtUtil.isMatchingXsdSchema(readXml(VALID_CAMT53_XML), CAMT054V00104.getXsdPath()));
assertFalse(CamtUtil.isMatchingXsdSchema(readXml(VALID_CAMT54_XML), CAMT053V00104.getXsdPath()));
... |
95222532_3 | class HdfsFSImageTool {
protected static int run(String[] args) {
final IExecutionExceptionHandler exceptionHandler = (ex, commandLine, parseResult) -> {
commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage()));
if (getRootLogger().isInfoEnabled()) {
... | final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
HdfsFSImageTool.out = new PrintStream(byteArrayOutputStream);
HdfsFSImageTool.err = HdfsFSImageTool.out;
HdfsFSImageTool.run(new String[]{"-V"});
Pattern pattern = Pattern.compile("Version 1\\..*\n... |
95247186_80 | class RuntimeController implements RuntimeApiDelegate {
@Override
public ResponseEntity<Runtime> getRuntime(String workspaceNamespace) {
String firecloudWorkspaceName = lookupWorkspace(workspaceNamespace).getFirecloudName();
workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain(
works... | testLeoRuntime.setLabels(ImmutableMap.of("all-of-us-config", "preset-hail-genomic-analysis"));
when(userRuntimesApi.getRuntime(BILLING_PROJECT_ID, getRuntimeName()))
.thenReturn(testLeoRuntime);
assertThat(runtimeController.getRuntime(BILLING_PROJECT_ID).getBody().getConfigurationType())
.... |
95247959_322 | class StaticImmutableTableSchema implements TableSchema<T> {
public static <T, B> Builder<T, B> builder(Class<T> itemClass, Class<B> builderClass) {
return new Builder<>(itemClass, builderClass);
}
private StaticImmutableTableSchema(Builder<T, B> builder);
@Override public StaticTableMetadat... | Set<Float> valueSet = new HashSet<>(asList(1.2f, 3.4f, 5.6f));
List<String> expectedList = valueSet.stream().map(Object::toString).collect(toList());
verifyNullableAttribute(EnhancedType.setOf(Float.class),
a -> a.name("value")
... |
95282920_2 | class HelloWithRepositoryController {
@GetMapping("/hello/data/{name}")
public Hello sayHi(@PathVariable String name) {
Optional<Person> person
= personRepository.findByFirstName(name);
String message =
person.map(person1 ->
String.format... | // Arrange
Person somkiat = new Person("somkiat", "pui");
given(personRepository.findByFirstName("somkiat"))
.willReturn(Optional.of(somkiat));
// Act
Hello hello = controller.sayHi("somkiat");
// Assert
assertEquals("Hello somkiat", hello.getMes... |
95342834_0 | class BaseController extends Controller {
@NonNull @Override
protected final View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
U view = createView(inflater, container);
view.setController(getThis());
return view;
}
public BaseController();
public BaseControll... | DummyView dummyView = (DummyView) dummyController.onCreateView(null, null);
Assert.assertEquals(dummyController, dummyView.getController());
}
} |
95357887_71 | class TasksPresenter implements TasksContract.Presenter {
@Override
public void completeTask(@NonNull Task completedTask) {
checkNotNull(completedTask, "completedTask cannot be null!");
mTasksRepository.completeTask(completedTask);
mTasksView.showTaskMarkedComplete();
loadTasks(... | // Given a stubbed task
Task task = new Task("Details Requested", "For this task");
// And no tasks available in the repository
when(mTasksRepository.getTasks()).thenReturn(Flowable.empty());
// When task is marked as complete
mTasksPresenter.completeTask(task);
... |
95374722_0 | class ByteArrayDequeue {
public void push(byte[] src) {
push(src, 0, src.length);
}
public ByteArrayDequeue();
ByteArrayDequeue(int initalCapacity);
public int getRemaining();
public void push(byte[] src, int srcOffset, int srcLengthToPush);
public void pushLast(byte[] src);
... | for (int i = 0; i < 200; i++) {
push("ABCDEFGH");
push("IJK");
assertEquals("ABCDE", pop(5));
assertEquals("FGHIJK", pop(6));
}
}
} |
95380855_2 | class IssueTextUtils {
public static String getFormattedIssueTitle(String volume, int number) {
return String.format(Locale.US, "%s #%d", volume, number);
}
public static String getFormattedIssueName(String issue, String volume, int number);
private static final String ISSUE_NAME;
private static final ... | assertEquals("getFormattedIssueTitle method returned incorrect string!",
FORMATTED_NAME_SHORT,
IssueTextUtils.getFormattedIssueTitle(VOLUME_NAME, ISSUE_NUMBER));
}
} |
95459293_16 | class TranslationUtils {
public static String toString(Object obj) {
return (obj == null) ? null : obj.toString();
}
private TranslationUtils();
public static Date toDate(DateTime date);
public static Date toDate(LocalDate ldate);
public static Date toDate(Calendar date);
public ... | URL url = null;
try {
url = new URL("http://localhost:80/");
} catch (MalformedURLException e) {
fail(e.getMessage());
}
assertEquals("http://localhost:80/", TranslationUtils.toString(url));
}
} |
95534270_328 | class CliBootstrap {
static File getPlatformRootPath(CliBootstrapEnvironment env) {
// make sure APPNG_HOME is set and valid
File appngHome = env.getFileFromEnv(APPNG_HOME);
return checkFile(APPNG_HOME, appngHome, true);
}
public static void main(String[] args);
public static int run(String[] args);
static... | try {
CliBootstrap.getPlatformRootPath(cliBootstrapEnvironment);
Assert.fail("IllegalArgumentException expected, but no exception has been thrown.");
} catch (IllegalArgumentException e) {
Assert.assertEquals("APPNG_HOME is not defined!", e.getMessage());
}
}
} |
95563905_4 | class RangeOverlapMerger {
static List<Range> join(List<Range> ranges) {
RangeOverlapMerger calculator = new RangeOverlapMerger(ranges);
return calculator.joinOverlappingRanges();
}
private RangeOverlapMerger(@NonNull List<Range> ranges);
private List<Range> joinOverlappingRanges();
... | List<Range> ranges = asList(
range(from(2017, Calendar.JANUARY, 1), from(2017, Calendar.JANUARY, 4)),
range(from(2017, Calendar.JANUARY, 6), from(2017, Calendar.JANUARY, 9))
);
assertEquals(ranges.size(), 2);
List<Range> result = RangeOverlapMerger.join(r... |
95591183_2 | class NetworkMonitor extends Monitor {
@Override
public void stop() {
super.stop();
if (!networkActivityDisposable.isDisposed()) {
networkActivityDisposable.dispose();
logger.d(TAG, "stop: disposed networkActivityDisposable");
}
}
public NetworkMonitor... | TestUtilComponent testUtilComponent = DaggerTestUtilComponent.builder()
.appModule(new AppModule(mockContext))
.fakeDateTimeModule(new FakeDateTimeModule())
.testLoggerModule(new TestLoggerModule())
.build();
PublishSubject<NetworkActivity... |
95603001_3 | class ArticleRepository implements IRepository<Article> {
@Override
public Observable<Article> get(int id) {
if(!cacheStore.isInCache(id)) {
if (isNetworkConnection()) {
return remoteSource.get(id)
.doOnNext(this::saveToLocal)
... | setDataSourceResult(local);
repository.get()
.observeOn(SCHEDULER.io())
.subscribeOn(SCHEDULER.ui())
.subscribe(this::resultShouldNotBeNull);
verify(local).get();
verify(mapper).map(anyList());
verify(manager).getActiveNetworkInfo... |
95646670_0 | class WikidataHyponyms extends JCasAnnotator_ImplBase {
public String getWikidataId(String language, String title) throws JSONException, IOException {
if(title.contains("#"))
return null;
String url = "https://"+
language+
".wikipedia.org/w/api.php?action=query&titles="+title+"&ppprop=wikibase_item&pro... | WikidataHyponyms WikidataHyponyms = new WikidataHyponyms();
assertEquals("Q4692", WikidataHyponyms.getWikidataId("de", "Renaissance"));
assertEquals("Q169243", WikidataHyponyms.getWikidataId("en","Protagoras"));
}
} |
95657746_0 | class Strings {
public static String format(final String format, final Object... args) {
String retVal = format;
for (final Object current : args) {
retVal = retVal.replaceFirst("[%][s]", current.toString());
}
return retVal;
}
}
class StringsTest {
@Test
... | this.assertFormat("Some test here %s.", 54);
this.assertFormat("Some test here %s and there %s, and test [%s]. sfsfs !!!", 54, 59, "HAHA");
this.assertFormat("Some test here %s and there %s, and test [%s]. sfsfs !!!", 54, 59, "HAHA", "DONT SHOW");
Assert.assertEquals("Formatting is n... |
95752629_38 | class AuthConfiguration {
public void setHttpProxyHost(String httpProxyHost) {
this.httpProxyHost = httpProxyHost;
}
public String getClient();
public void setClient(String client);
public String getTenant();
public void setTenant(String tenant);
public String getKey();
public ... | final AuthConfiguration auth = new AuthConfiguration();
auth.setHttpProxyHost("httpProxyHost1");
assertEquals("httpProxyHost1", auth.getHttpProxyHost());
}
} |
95896976_5 | class PairwiseRankingLearningAlgorithm extends AObjectRankingWithBaseLearner<PairwiseRankingConfiguration> {
@Override
public PairwiseRankingLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException {
return (PairwiseRankingLearningModel) super.train(dataset);
}
public Pairwi... | File file = new File(getTestRessourcePathFor(OBJECT_RANKING_DATASET_B));
PairwiseRankingLearningAlgorithm algortihm = new PairwiseRankingLearningAlgorithm();
DatasetFile datasetFile = new DatasetFile(file);
ObjectRankingDatasetParser objectRankingParser = (ObjectRankingDatasetParser) algortihm.g... |
95924484_0 | class Snippet {
@GetMapping(path = "/{id}")
public SnippetEntity getSnippet(@PathVariable("id") String id) {
return snippetService.getSnippet(id);
}
@GetMapping() public Page<SnippetEntity> getSnippets(@RequestParam(value = "from", defaultValue = "0") final int from,
... | ResponseEntity<String> response = restTemplate.getForEntity(SNIPPET_ENDPOINT, String.class);
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
Page<SnippetEntity> page = TestUtils.getObjectFromString(response.getBody(), new TypeReference<Page<SnippetEntity>>() {
});
... |
95946882_10 | class TransactionsTotalCalculator {
public Total getAccountBalance(Currency toCurrency, long accountId) {
WhereFilter filter = selectedAccountOnly(this.filter, accountId);
return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter);
}
public TransactionsTotalCal... | TransactionBuilder.withDb(db).account(a1).dateTime(DateTime.date(2012, 1, 10)).amount(1).create();
assertFalse(c.getAccountBalance(c1, a1.id).isError()); // no conversion
assertFalse(c.getAccountBalance(c3, a1.id).isError()); // all rates are available
Total total = c.getAccountBalance... |
95958400_35 | class ChargeCalculator {
public double getCharge(Date date, double quantity) {
double charge;
if (date.before(SUMMER_START) || date.after(SUMMER_END))
charge = quantity * winterRate + winterServiceCharge;
else charge = quantity * summerRate;
return charge;
}
}
clas... | ChargeCalculator chargeCalculator = new ChargeCalculator();
double charge = chargeCalculator.getCharge(new Date(2011, 11, 1), 100);
assertEquals(400, charge, 0);
}
} |
96021764_6 | class CronParser {
public static Matcher parse(String cron) throws InvalidCronException {
return new CronParser(cron).parse();
}
CronParser(final char[] cron);
CronParser(final String cron);
public static Matcher parse(final char[] cron);
public Matcher parse();
private int sk... | Matcher matcher;
matcher = new CronParser("3,5,8 1,2,3 * *").parse();
assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 0, 1, true)));
assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 1, 1, true)));
assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 2, 1, true)));
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.