id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
45780307_43 | class StarTreeRecordStoreDefaultImpl implements StarTreeRecordStore {
@Override
public Number[] getMetricSums(StarTreeQuery query)
{
return doQuery(query).getMetricSums();
}
public StarTreeRecordStoreDefaultImpl(StarTreeConfig config,
DimensionStore dimensionStor... | StarTreeQuery query = new StarTreeQueryImpl.Builder()
.setDimensionKey(getDimensionKey("A0", StarTreeConstants.STAR, StarTreeConstants.STAR))
.setTimeRange(new TimeRange(0L, 7L))
.build(config);
Number[] sums = recordStore.getMetricSums(query);
Assert.assertEquals(sums,... |
45824158_11 | class RestUri implements Serializable {
public RestUri withoutPath() {
try {
URI parsedUri = new URI(uri);
return new RestUri(parsedUri.getScheme() + "://" + parsedUri.getHost() + ((parsedUri.getPort() > -1) ? ":" + parsedUri.getPort() : "") + "/");
} catch (URISyntaxExcepti... | RestUri restUri = new RestUri("http://1.1.1.1:8888/some_path");
assertEquals("http://1.1.1.1:8888/", restUri.withoutPath().getUri());
}
} |
45832751_0 | class JsonNodeComparator implements Comparator<JsonNode>, Serializable {
public int compare(final JsonNode o1, final JsonNode o2) {
final int r = orderValue(o1) - orderValue(o2);
if (r != 0)
return r;
final JsonNodeType type = o1 != null ? o1.getNodeType() : null;
if (type == null || type == JsonNodeType.... | final ObjectMapper mapper = new ObjectMapper();
final JsonNode j3 = mapper.readTree("3");
final JsonNode j10 = mapper.readTree("10");
final JsonNode jhoge = mapper.readTree("\"hoge\"");
final JsonNodeComparator sut = new JsonNodeComparator();
assertTrue(sut.compare(j3, j10) < 0);
assertTrue(sut.compare(... |
45860898_137 | class MaintenanceScheduleHelper {
public static void validateDuration(final String duration) {
try {
if (StringUtils.hasText(duration)) {
convertDurationToLocalTime(duration);
}
} catch (final DateTimeParseException e) {
throw new InvalidMaintenan... | final String duration = "10";
assertThatThrownBy(() -> MaintenanceScheduleHelper.validateDuration(duration))
.isInstanceOf(InvalidMaintenanceScheduleException.class).hasMessage("Provided duration is not valid")
.extracting("durationErrorIndex").containsExactly(2);
}
... |
45932568_14 | class KafkaUtilities {
public VerifyTopicState verifySupportTopic(
KafkaZkClient zkClient,
String topic,
int expPartitions,
int expReplication
) {
Objects.requireNonNull(zkClient, "zkClient must not be null");
if (topic == null || topic.isEmpty()) {
throw new IllegalArgumentE... | // Given
KafkaUtilities kUtil = new KafkaUtilities();
// When/Then
try {
kUtil.verifySupportTopic(null, anyTopic, anyPartitions, anyReplication);
fail("IllegalArgumentException expected because zkClient is null");
} catch (NullPointerException e) {
// ignore
}
}
} |
45953328_0 | class BaseInfo implements java.io.Serializable {
public void mock() {
}
public static T mockObject(Class<T> clazz);
public static List<T> mockList(int max, Class<T> clazz);
}
class BaseInfoTest {
@Test
public void testMock() {
|
// object
MyBaseInfo info = BaseInfo.mockObject(MyBaseInfo.class);
Assert.assertTrue(info.id.equals("1"));
// BaseListInfo
MyBaseListInfo listInfo = new MyBaseListInfo();
listInfo.mock();
Assert.assertTrue(listInfo.count >= 0);
if (listIn... |
45970905_0 | class XercesSax implements ContentHandler {
public String getElementContent(String tagName) {
// suche erstes Element mit tagName
int startIndex = this.result.indexOf(tagName);
String content = "";
if (startIndex > -1) {
// für jedes nachfolgende Element
for (int ... | parser.setProperty("http://xml.org/sax/properties/declaration-handler", myDeclHandler);
parser.parse("../../xml_files/dtd/internalSubset_PEReferenceIn_ExternalSubsetInternalGeneralEntity.xml");
assertEquals("file:///home/phoenix/masterthesis/Christopher_Spaeth/code/xml_files/dtd/internalSubset_P... |
45986064_19 | class OverlapHelper {
public static void evaluateOverlap(AnnotationFS gold, AnnotationFS sys,
RecognitionMeasures measures) {
if (gold.getEnd() <= sys.getBegin() || sys.getEnd() <= gold.getBegin()) {
throw new IllegalArgumentException(String.format(
... | RecognitionMeasures rm = new RecognitionMeasures();
OverlapHelper.evaluateOverlap(anno(5, 10), anno(7, 10), rm);
assertEquals(0.6, rm.getMatchedScore(), 0.001d);
assertEquals(0.4, rm.getMissedScore(), 0.001d);
assertEquals(0, rm.getSpuriousScore(), 0.001d);
}
} |
45997449_24 | class ResourceArgumentsUrn extends ResourceUrn implements IResourceArgumentsUrn {
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ResourceArgumentsU... | Map<String, Object> arguments = new HashMap<String, Object>();
arguments.put("key1", "value1");
arguments.put("key2", "value2");
ResourceArgumentsUrn urn = new ResourceArgumentsUrn("js", "local", "/js/sample/sample.js", arguments);
Assert.assertTrue(urn.equals(urn));
ResourceArgument... |
46000465_198 | class SceneUpdateManager {
SceneUpdate getApiKeyUpdate(String apiKey) {
return new SceneUpdate(STYLE_GLOBAL_VAR_API_KEY, apiKey);
}
List<SceneUpdate> getUpdatesFor(String apiKey, Locale locale, boolean transitOverlayEnabled,
boolean bikeOverlayEnabled, boolean pathOverlayEnabled);
SceneUpdate getT... | SceneUpdate update = manager.getApiKeyUpdate("api-key");
assertThat(update.getPath()).isEqualTo("global.sdk_mapzen_api_key");
assertThat(update.getValue()).isEqualTo("api-key");
}
} |
46007735_2 | class StringUtils {
public static boolean isEmpty(String string) {
return string == null || string.length() == 0;
}
private StringUtils();
}
class StringUtilsTest {
@Test
public void testStringNotEmpty() throws Exception {
| boolean empty = StringUtils.isEmpty("test");
assertFalse(empty);
}
} |
46035308_5 | class Sensey {
public void startProximityDetection(ProximityListener proximityListener) {
startLibrarySensorDetection(new ProximityDetector(proximityListener), proximityListener);
}
private Sensey();
public static Sensey getInstance();
public void init(Context context, int samplingPeriod... | addSensor(TYPE_PROXIMITY);
ProximityListener fakeListener = mock(ProximityListener.class);
sensey.startProximityDetection(fakeListener);
ProximityDetector detector = getDetector(fakeListener, ProximityDetector.class);
if (detector != null) {
assertTrue("Sensor Manager... |
46045563_14 | class FluentIterator implements ImmutableIterator<T> {
public T reduce(BinaryOperator<T> f) {
return Iterators.reduce(this, f);
}
public FluentIterator(Iterator<T> t);
public static FluentIterator<T> fluent(Iterator<T> t);
@Override public boolean hasNext();
@Override public T next()... | FluentIterator<Integer> t = fluent(repeat(10, 5));
BinaryOperator<Integer> op = (a, b) -> a + b;
int sum = t.reduce(op);
assertEquals(50, sum);
t = fluent(repeat(10, 5));
BinaryOperator<Integer> mul = (a, b) -> a * b;
int prod = t.reduce(mul);
assertEqual... |
46057717_11 | class AuthorizationCodeVerifier implements CodeVerifier {
@Override
public boolean verify(CodeChallenge codeChallenge, String providedCodeVerifier) {
try {
//no code verifier was provided and no code challenge was saved so this is a normal OAuth2 code flow
if (providedCodeVerifier.isEmpty() && !cod... | String codeVerifierValue = "::code::";
byte[] hashedCodeChallenge = MessageDigest.getInstance("SHA-256").digest(codeVerifierValue.getBytes(StandardCharsets.UTF_8));
String transformedCodeChallenge = BaseEncoding.base64Url().encode(hashedCodeChallenge);
CodeChallenge codeChallenge = new CodeChallenge(tr... |
46113606_80 | class CustomSegment extends Segment {
@Override
public boolean evaluate() {
if (!TextUtils.isEmpty(mType) && mType.equals(AppConstants.CUSTOM_SEGMENT)) {
return CustomSegmentEvaluateEnum.getEvaluator(mType, mSegmentOperator).evaluate(vwo, mOperandValue, lOperandValue);
}
ret... | VWO vwo = new VWOMock().getVWOMockObject();
PowerMockito.mockStatic(VWOPersistData.class);
PowerMockito.when(VWOPersistData.isReturningUser(ArgumentMatchers.any(VWO.class))).thenReturn(false);
String json = TestUtils.readJsonFile(getClass(), "com/vwo/mobile/segmentation/screen_height_l... |
46121851_23 | class MplProcessMaterializer extends ProcessCommandsHelper {
public @Nullable CommandChain visitProcess(MplProgram program, MplProcess process) {
if (process.getType() == INLINE) {
return null;
}
List<ChainPart> chainParts = new CopyScope().copy(process.getChainParts());
List<ChainLink> result ... | // given:
MplCommand first = some($MplCommand().withConditional(UNCONDITIONAL));
MplCommand second = some($MplCommand().withConditional(INVERT));
MplProcess process = some($MplProcess()//
.withRepeating(false)//
.withChainParts(listOf(first, second)));
// when:
CommandChain res... |
46130071_18 | class ZeromqConsumer extends DefaultConsumer {
@Override
protected void doStart() throws Exception {
super.doStart();
executor = endpoint.getCamelContext().getExecutorServiceManager().newFixedThreadPool(this, endpoint.getEndpointUri(), 1);
listener = new Listener(endpoint, processor, so... | ExecutorService executor = Executors.newFixedThreadPool(1);
when(manager.newFixedThreadPool(any(ZeromqConsumer.class), anyString(), anyInt())).thenReturn(executor);
// CONNECT mode by default
consumer.doStart();
Thread.sleep(50);
verify(socket).connect(endpoint.getSocketAddress());
}
... |
46181665_20 | class RelationCollisionUtil {
protected Namer getOneToManyNamerFromConf(OneToManyConfig o2m, Namer fromEntityNamer) {
if (o2m != null) {
if (o2m.hasElementVar() && !o2m.hasVar()) {
// the plural is calculated
return new AccessorNamer(fromEntityNamer, o2m.getElem... | RelationCollisionUtil relationUtil = new RelationCollisionUtil();
Namer fromEntityNamer = getNamer("account", "Account");
Namer result = relationUtil.getOneToManyNamerFromConf(getOneToManyConfig("unAccount", null), fromEntityNamer);
assertThat(result.getVar()).isEqualTo("unAccount");
... |
46187719_395 | class BorderRightWidth extends AbstractCssProperty<BorderRightWidth> {
public BorderRightWidth() {
setCssValue(MEDIUM);
}
public BorderRightWidth();
public BorderRightWidth(final String cssValue);
public BorderRightWidth(final BorderRightWidth borderRightWidth);
public BorderRightW... | BorderRightWidth borderRightWidth = new BorderRightWidth();
assertEquals(BorderRightWidth.MEDIUM, borderRightWidth.getCssValue());
}
} |
46204890_4 | class AutomatorAction {
public static AutomatorAction clearTextField() {
return new AutomatorAction() {
@Override
public void wrappedPerform(UiSelector selector, UiObject object) throws UiObjectNotFoundException {
object.clearTextField();
}
};
... | UiObject object = mock(UiObject.class);
AutomatorAction.clearTextField().perform(null, object);
verify(object).clearTextField();
}
} |
46223235_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异常");
}
}
} |
46251204_49 | class KeyStoreCredentialResolverBuilder {
public CredentialResolver build() throws IOException, GeneralSecurityException {
final KeyStore ks = KeyStore.getInstance(type);
try (InputStream is = open()) {
ks.load(is, password != null ? password.toCharArray() : null);
}
ret... | final File file = folder.newFile();
assertThat(file.length()).isZero();
final KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
keyStore.store(new FileOutputStream(file), "".toCharArray());
assertThat(file.length()).isGreaterThan(0);
a... |
46256078_4 | class EntityUtils {
public static void copyProperties(Object from, Object to) throws Exception {
copyPropertiesExclude(from, to, null);
}
public static void copyPropertiesExclude(Object from, Object to, String[] excludeArray);
@SuppressWarnings("unchecked") public static void copyPropertiesInc... | FromClassGetter fromClass = new FromClassGetter();
fromClass.setStringValue("[FromClass] = Save");
InnerClass innerClass = new InnerClass();
innerClass.setStringValue("[InnerClass] = Save");
fromClass.setInnerClass(innerClass);
ToClassSetter toClass = new ToClassSetter()... |
46297234_1 | class FxWeaver {
public <C, V extends Node> FxControllerAndView<C, V> load(Class<C> controllerClass) {
return load(controllerClass, null);
}
public FxWeaver(Callback<Class<?>, Object> beanFactory, Runnable closeCommand);
public V loadView(Class<C> controllerClass);
public V loadView(Clas... | FxControllerAndView<SimpleBean, Node> load = fxWeaver.load(SimpleBean.class, null, null);
assertThat(load).isNotNull();
assertThat(load.getController()).isNotNull().isInstanceOf(SimpleBean.class);
}
} |
46308509_1 | class Main {
public static void runSemanticAnalysis(AST ast) {
new SemanticAnalysis(ast).run();
Pass.printErrorsAndWarnings();
if (generatedSourceDirectory != null) {
if (AST.globalSymbolTable.getPackage().length() != 0)
generatedSourceDirectory +=
... | String input =
generateLBJavaScript("TwoFeatLearner", "testFeature1, testFeature2",
"import edu.illinois.cs.cogcomp.lbjava.features.PredefinedFeature;");
Yylex scanner = new Yylex(new ByteArrayInputStream(input.getBytes()));
AST ast = (AST) new parser(scan... |
46324355_1 | class MoodleViewModel extends AndroidViewModel {
public LiveData<RemoteResource<List<MoodleAssignmentCourse>>> getAssignmentCourses() {
if (filteredAssignmentCourses == null || filteredAssignmentCourses.getValue() == null
|| filteredAssignmentCourses.getValue().data == null) {
f... | // Prepare LiveData
MutableLiveData<RemoteResource<List<MoodleAssignmentCourse>>> liveData = new MutableLiveData<>();
when(repository.getAssignmentCourses()).thenReturn(liveData);
// Prepare Observer
Observer<RemoteResource<List<MoodleAssignmentCourse>>> observer = mock(Observer... |
46368934_70 | class Rollbar {
public Config config() {
if (rollbar != null) {
return rollbar.config();
} else {
return null;
}
}
public Rollbar(Context context);
public Rollbar(Context context, String accessToken, String environment, boolean registerExceptionHandler);
public Rollbar(Context con... | Config config;
final String notifierVersion = "1.2.3";
final String notifierName = "custom-notifier";
Rollbar sut = new Rollbar(mockApplicationContext, ACCESS_TOKEN, ENVIRONMENT, true, false, new ConfigProvider() {
@Override
public Config provide(ConfigBuilder builder) {
return buil... |
46398595_6 | class AbstractProxyConnection implements Connection {
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException
{
if(this.useRandomConnection)
{
throw new TargetDataSourceNotFoundException("setNetworkTimeout error,"+this.getTargetDataSourceNotFoundExceptionErrorMsg());
}
Jdbc... | final int[] count=new int[2];
Result result=new Result();
ExecutorService executor=Executors.newCachedThreadPool();
int milliseconds=5000;
AbstractProxyConnection proxyConnection=this.createProxyConnectionForPhysical(count, "setNetworkTimeout",result,null);
proxyConnection.setNetworkTimeout(executor, millis... |
46404009_117 | class HBaseAuditLogParser implements Serializable {
public HBaseAuditLogObject parse(String logLine) {
if(logLine == null || logLine.isEmpty()) return null;
HBaseAuditLogObject ret = new HBaseAuditLogObject();
String timestamp = "";
String user = "";
String scope = "";
... | String log = "2015-08-11 13:31:03,729 TRACE SecurityLogger.org.apache.hadoop.hbase.security.access.AccessController: Access allowed for user eagle; reason: Table permission granted; remote address: /127.0.0.1; request: get; context: (user=eagle,scope=hbase:namespace,family=info, action=READ)";
HBaseAudi... |
46413020_56 | class UrlFromStringModel implements IModel<URL> {
@Override
public URL getObject() {
final String object = model.getObject();
if (object == null) {
return null;
} else {
try {
if (URL_PATTERN.matcher(object).matches()) {
return... | final Model<String> innerModel = Model.of("");
final UrlFromStringModel instance = new UrlFromStringModel(innerModel);
innerModel.setObject(null);
assertNull(instance.getObject());
innerModel.setObject("/my/file/location");
assertEquals(new URL("file:/my/file/lo... |
46427562_3 | class SqlAvroSerde implements Serde<AvroData> {
@Override
public AvroData fromBytes(byte[] bytes) {
GenericRecord data;
try {
data = reader.read(null, DecoderFactory.get().binaryDecoder(bytes, null));
return getAvroData(data, avroSchema);
} catch (IOException e) {
String errMsg = "Ca... | AvroData decodedDatum = (AvroData)serde.fromBytes(encodeMessage(sampleOrderRecord(), orderSchema));
Assert.assertTrue(decodedDatum.schema().getType() == org.apache.samza.sql.api.data.Schema.Type.STRUCT);
Assert.assertTrue(decodedDatum.getFieldData("id").schema().getType() == org.apache.samza.sql.api.data.S... |
46450575_19 | class FloRunner {
public static <T> Result<T> runTask(Task<T> task, Config config) {
return new Result<>(new FloRunner<T>(config).run(task), loadTerminationHooks(config));
}
private FloRunner(Config config);
private static Config defaultConfig();
private static Iterable<TerminationHook> loadTerminatio... |
final Instant today = Instant.now().truncatedTo(ChronoUnit.DAYS);
final Instant yesterday = today.minus(1, ChronoUnit.DAYS);
final Task<String> baz = Task.named("baz", today).ofType(String.class)
.process(() -> {
final String bazJvm = jvmName();
log.info("baz: bazJvm={}, today=... |
46457181_2 | class GetSelectedDemoUserListUseCase extends UseCase<UserDemoEntity> {
@Override public Observable<UserDemoEntity> react() {
return repository.getSelectedUserDemoList();
}
@Inject public GetSelectedDemoUserListUseCase(UI ui, UserDemoRepository repository);
private GetSelectedDemoUserListUseC... | when(userDemoRepositoryMock.getSelectedUserDemoList()).thenReturn(Observable.just(userDemoEntityMock));
TestSubscriber<UserDemoEntity> subscriberMock = new TestSubscriber<>();
getSelectedDemoUserListUseCaseUT.react().subscribe(subscriberMock);
subscriberMock.awaitTerminalEvent();
... |
46504855_0 | class DnsServicesDiscovery extends Configurable implements DnsDiscovery {
@Override
public Set<ServiceInstance> listServiceInstances(Fqdn browsingDomain, CompoundLabel type, boolean secValidation)
throws LookupException, ConfigurationException
{
try {
ValidatorUtil.isValidDo... | try {
this.discovery = new DnsServicesDiscovery();
this.discovery.dnsSecDomain(Constants.DEFAULT_DNSSEC_DOMAIN)
.dnsServer(InetAddress.getByName(DNS_RESOLVER))
.trustAnchorDefault(Constants.DEFAULT_TRUST_ANCHOR)
... |
46506858_32 | class AuthHashGenerator {
String generateHash(String timestamp, String publicKey, String privateKey)
throws MarvelApiException {
try {
String value = timestamp + privateKey + publicKey;
MessageDigest md5Encoder = MessageDigest.getInstance("MD5");
byte[] md5Bytes = md5Encoder.digest(value.... | AuthHashGenerator authHashGenerator = new AuthHashGenerator();
String md5 = authHashGenerator.generateHash(ANY_TIMESTAMP, ANY_PUBLIC_KEY, ANY_PRIVATE_KEY);
assertEquals(VALID_MD5, md5);
}
} |
46527824_9 | class ObservableGroup {
public <T> ObservableTransformer<? super T, T> transform(Observer<? super T> observer,
String observableTag) {
return new GroupSubscriptionTransformer<>(this, Utils.getObserverTag(observer),
observableTag);
}
ObservableGroup(long groupId);
public long id();
publi... | ObservableGroup group = observableManager.newGroup();
TestObserver<Object> subscriber = new TestObserver<>();
Observable<String> sourceObservable = Observable.never();
sourceObservable.compose(group.transform(fooObserver)).subscribe(fooObserver);
subscriber.assertNotComplete();
}
} |
46547901_35 | class SearchManagerImpl implements SearchManager {
@Override
public Feature getRoomByLocation(String appIdentifier, Double longitude, Double latitude, Integer floor) throws RoomNotFoundException {
// TODO Auto-generated method stub
List<Feature> featureRooms = mapRepository.searchByLocation(appIdentifier,longitu... | //Fixture
String appIdentifier="appIdentifier";
Double longitude=1.0;
Double latitude=2.0;
Integer floor=3;
List<Feature> featureRooms=new ArrayList<Feature>();
featureRooms.add(featureRoom1);
featureRooms.add(featureRoom2);
List<List<Double>> coordinatesRoom1=new ArrayList<List<Double>>();
co... |
46569013_6 | class MyInteger {
public boolean isPrime() {
return isPrimeInternal(this.value);
}
public MyInteger(int value);
public int get();
public boolean isEven();
public boolean isOdd();
private static boolean isPrimeInternal(int v);
public static boolean isEven(int v);
public st... | for (int p : prime) {
assertTrue(MyInteger.isPrime(p));
}
}
} |
46573609_80 | class OcdsController extends GenericOCDSController {
@ApiOperation(value = "Returns a release entity for the given project id. "
+ "The project id is read from planning.budget.projectID")
@RequestMapping(value = "/api/ocds/release/budgetProjectId/{projectId:^[a-zA-Z0-9]*$}",
method = { ... | final Release release = ocdsController.ocdsByProjectId("SP001");
Assert.assertNotNull(release);
Assert.assertEquals("ocds-endpoint-001", release.getOcid());
}
} |
46615164_4 | class SettingsPresenter extends BasePresenter<SettingsContract.View> implements SettingsContract.Presenter {
@Override
public void setNewBookNotificationSubscriptionStatus(final boolean onOff) {
checkViewAttached();
analytics.trackUserToggleNewBookNotifications(onOff);
settings.setNewBo... | when(mockSettings.isSubscribedToNewBookNotification()).thenReturn(Single.just(false));
when(mockSettings.setNewBookNotificationStatus(anyBoolean())).thenReturn(Single.just(true));
presenter.setNewBookNotificationSubscriptionStatus(true);
verify(mockSettings).setNewBookNotificationStatu... |
46621580_3 | class CooldownService {
public boolean isTracked(UUID uniqueId) {
return cooldowns.getIfPresent(uniqueId) != null;
}
public CooldownService(Duration duration);
public void trackPlayer(UUID uniqueId);
private CooldownService cooldown;
}
class CooldownServiceTest {
private Cooldown... | assertThat(cooldown.isTracked(UUID.randomUUID()), is(false));
}
} |
46654747_0 | class ClassNameModel {
public String getClassName() {
return className;
}
public ClassNameModel(String className);
public TypeName getTypeName();
public String getPackage();
public String getSimpleName();
public String normalized();
@Override public int hashCode();
@Override public boolean equ... | assertEquals(IsApplication.class.getCanonicalName(),
this.classNameModel.getClassName());
}
} |
46697033_1 | class ScannerServiceImpl implements ScannerService {
@Override
public Scanner update(Scanner scanner) {
return scannerDAO.saveAndFlush(scanner);
}
@Autowired public ScannerServiceImpl(ScannerDAO scannerDAO, ScannerAppDAO scannerAppDAO);
@Override public Scanner insert(Scanner scanner);
... | Mockito.when(mockScannerDAO.saveAndFlush(testScanner)).thenReturn(testScanner);
Scanner insertedScanner = scannerService.update(testScanner);
Assert.assertNotNull(insertedScanner);
Assert.assertEquals("testScannerImage", insertedScanner.getImage());
}
} |
46709421_0 | class Timber {
public static int treeCount() {
synchronized (FOREST) {
return FOREST.size();
}
}
private Timber();
public static void v(@NonNls String message, Object... args);
public static void v(Throwable t, @NonNls String message, Object... args);
public static void d(@NonNls String me... | // inserts trees and checks if the amount of returned trees matches.
assertThat(Timber.treeCount()).isEqualTo(0);
for(int i= 1 ; i < 50 ; i++){
Timber.plant(new Timber.DebugTree());
assertThat(Timber.treeCount()).isEqualTo(i);
}
Timber.uprootAll();
assertThat(Timber.treeCount()).isEq... |
46713982_6 | class AnnotationOptionsResolver implements OptionsResolver {
@Override
public Options resolve(final String key, final JoinPoint joinPoint) throws OptionsException {
// find most specific @RateLimited annotation for invoked join point
final RateLimited rateLimited = findAnnotation(joinPoint, RateLimited.cl... | initMocks("correctWithRetry");
assertThat(new AnnotationOptionsResolver().resolve("test", joinPoint)).isEqualTo(InternalOptions
.enabled("test", 5, InternalOptions.intervalOf(30L, TimeUnit.SECONDS))
.enableRetry(4, InternalOptions.intervalOf(100L, TimeUnit.MILLISECONDS)));
}
} |
46714751_4 | class VisumPresenter {
public final int getViewCount() {
return viewHolders.size();
}
private ViewHolder<V> findViewHolderByViewId(int id);
@NonNull private ViewHolder<V> findViewHolderByViewIdOrThrow(int id);
public final void setView(int id, @Nullable V view);
private V removeView(in... |
BaseTestView viewOne = getClient();
viewOne.attachPresenter();
assertPresenterAttached(presenter, VIEW_ID, viewOne);
viewTwo.attachPresenter();
assertPresenterAttached(presenter, VIEW_ID_TWO, viewTwo);
Assert.assertEquals("Invalid view count", 2, presenter.getViewCoun... |
46776191_4 | class SFDCServiceImpl implements SFDCService {
@Override
public Map<String, Object> getLimits() {
if (!isConnected()) {
return null;
}
String baseUrl = null;
try {
baseUrl = sfdcSession.getEndPoint() + REST_ENDPOINT_URI + "/limits";
HttpGet ge... | if (!checkCanRunTests()) return;
Map<String,Object> limits = sfdcServiceImpl.getLimits();
assertNotNull("Limits object is null, an error occurred !", limits);
}
} |
46795972_1 | class HybrisHTTPRequest {
public String getHybrisConsoleOutput(String json, ServerAnwserTypes type) {
if(type == ServerAnwserTypes.EXECUTION_RESULT) {
return returnFromJSON(json, "executionResult");
}
if(type == ServerAnwserTypes.OUTPUT_TEXT) {
return returnFromJSON(... | assertEquals("Groovy Rocks!", HybrisHTTPRequest.getHybrisConsoleOutput("{\"executionResult\":\"Groovy Rocks!\",\"outputText\":\"org.springframework.security.filterChains\\norg.springframework.security.filterChainProxy\\norg.springframework.security.web.DefaultSecurityFilterChain#0\\norg.springframework.security... |
46804199_121 | class SimpleIntimaciesContent extends AbstractSubBoxContent implements ListSubBoxContent {
@Override
public List<String> getPrintEntries() {
List<String> printIntimacies = new ArrayList<>();
for (Intimacy intimacy : getModel().getEntries()) {
String text = getTextForIntimacy(intimacy);
printInt... | resources.putString("Intimacies.Sheet.Strength.Minor", "Mi");
createIntimacy("Intimacy", Negative, Minor, Tie);
assertThat(content.getPrintEntries().get(0), containsString("Mi"));
}
} |
46847195_57 | class SqlRunner {
public List<Map<String, Object>> selectAll(String sql, Object... args) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql);
try {
setParameters(ps, args);
ResultSet rs = ps.executeQuery();
return getResults(rs);
} finally {
try {
... | DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
runScript(ds, JPETSTORE_DDL);
runScript(ds, JPETSTORE_DATA);
Connection connection = ds.getConnection();
SqlRunner exec = new SqlRunner(connection);
List<Map<String, Object>> rows = exec.selectAll("SELECT * FROM PRODUCT");
conne... |
46855060_6 | class Bus {
public void unregister(Object object) {
if (object == null) {
throw new NullPointerException("Object to unregister must not be null.");
}
enforcer.enforce(this);
Map<EventType, ProducerEvent> producersInListener = finder.findAllProducers(object);
for... | StringCatcher catcher1 = new StringCatcher();
StringCatcher catcher2 = new StringCatcher();
try {
bus.unregister(catcher1);
fail("Attempting to unregister an unregistered object succeeded");
} catch (IllegalArgumentException expected) {
// OK.
... |
46898785_44 | class ConfigBuilderArgParser extends ArgParser<ConfigBuilder> {
public ConfigBuilder setTreeshake(ConfigBuilder configBuilder, String value) {
configBuilder.treeShakerMode(Config.TreeShakerMode.valueOf(value));
return configBuilder;
}
public ConfigBuilderArgParser(Options options, String[... | configBuilder = configBuilderArgParser.setTreeshake(configBuilder, Config.TreeShakerMode.aggressive.toString());
assert(configBuilder.getConfig().getTreeShakerMode().equals(Config.TreeShakerMode.aggressive));
exception.expect(IllegalArgumentException.class);
configBuilder = configBuilde... |
46900323_10 | class CouponUtil {
public static long parseDuration(String text) {
// Given a string like 1w3d4h5m, we will return a millisecond duration
long result = 0;
int numIdx = 0;
for (int i = 0; i < text.length(); i++) {
char at = text.charAt(i);
if (at == 'd' || at ... | Assert.assertEquals(TimeUnit.DAYS.toMillis(7), CouponUtil.parseDuration("xyz"));
}
} |
46931835_0 | class GaugePlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.getExtensions().create(GAUGE, GaugeExtension.class);
project.getTasks().create(GAUGE, GaugeTask.class);
}
private static final String GAUGE;
private Project project;
}
class Gaug... | project.getPluginManager().apply(GAUGE);
assertTrue(project.getPlugins().getPlugin(GAUGE) instanceof GaugePlugin);
assertFalse(project.getPlugins().getPlugin(GAUGE) instanceof JavaPlugin);
}
} |
46981783_17 | class WindowsSettingsGenerator implements ResourceGenerator<UserCredentials> {
@NotNull
@Override
public String create(@NotNull final UserCredentials userCredentials) {
final StringBuilder sb = new StringBuilder();
final String user = userCredentials.getUser();
if(!StringUtil.isEmptyOrSpaces(user)) ... | // Given
final String expectedContent = "-u:nik" + ourlineSeparator + "arg1" + ourlineSeparator + "arg 2";
final List<CommandLineArgument> additionalArgs = Arrays.asList(new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER), new CommandLineArgument("arg 2", CommandLineArgument.Type.PARAMETER))... |
47021168_25 | class FavoritasMainPresenter implements Presenter<FavoritasMainPresenter.View> {
@Override
public void initialize(View view) {
this.view = view;
view.showLoading();
loadFavoritas();
}
public FavoritasMainPresenter(ObtainFavoritasAction obtainFavoritasAction);
@Override pu... | List<Favorita> favoritas = favoritasListOf(4);
when(obtainFavoritasAction.getFavoritas()).thenReturn(Observable.just(favoritas));
presenter.initialize(view);
verify(view).showFavoritas(favoritas);
}
} |
47058190_1 | class BitcoinjBlockchainServiceImpl implements BlockChainService {
@Override
public String generateCentralWalletHash() throws BlockchainException {
try {
final org.bitcoinj.core.Wallet receiver = this.centralWallet();
String freshHash = null;
Transaction transaction ... | when(this.transactionService.getByReceiverHash(anyString())).thenReturn(null);
when(this.walletService.create(any(Wallet.class))).thenAnswer(new Answer<Wallet>() {
@Override
public Wallet answer(final InvocationOnMock invocation) throws Throwable {
final Wallet wa... |
47133978_25 | class ColorConverter {
public static Float getSaturation(Color color) {
float[] hsbValues = new float[MAX_COMPONENT];
Float saturation;
Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), hsbValues);
saturation = hsbValues[SATURATION];
return saturation;
}
... | System.out.println("---- getSaturation -----");
Color colorA = Color.BLACK;
Float expResult = (float) 0.0;
Float result = ColorConverter.getSaturation(colorA);
System.out.println("BLACK - Saturation: ["+ result +"]");
assertEquals(expResult, result);
colorA ... |
47149635_3 | class PumbaCommandLineCreator {
public static Collection<String> run(String chaosCommand, boolean random,
CubeDockerConfiguration cubeDockerConfiguration) {
String[] runningCommand = new String[8];
runningCommand[PUMBA_INDEX] = "pumba";
runningCommand[RUN_INDEX] = "run";
ru... | when(cubeDockerConfiguration.getDockerServerUri()).thenReturn("https://192.168.0.1");
final Collection<String> cli =
PumbaCommandLineCreator.run("re2:^hp|10s|KILL:SIGTERM", true, cubeDockerConfiguration);
assertThat(cli).containsExactly("pumba", "--host", "https://192.168.0.1", "--t... |
47184968_47 | class CoreFormHandlingServlet extends SlingAllMethodsServlet implements Filter {
public void doFilter(final ServletRequest request,
final ServletResponse response,
final FilterChain chain)
throws IOException, ServletException {
formsHandlingServ... | FilterChain filterChain = mock(FilterChain.class);
servlet.doFilter(context.request(), context.response(), filterChain);
verify(formsHandlingServletHelper).handleFilter(context.request(), context.response(), filterChain, EXTENSION, SELECTOR);
}
} |
47219036_277 | class Lang extends SubtagSet {
public Subtag getExtension() {
for (Subtag subtag : this) {
switch (subtag.getType()) {
case PRIMARY:
case EXTLANG:
case SCRIPT:
case REGION:
case VARIANT:
break;
case EXTENSION:
return subtag.getPrevious();
default:
return null;
}
}
return n... | Lang lang = new Lang("en");
assertNull(lang.getExtension());
lang.getLanguage().setNext(new Subtag(Type.EXTENSION, "AB"));
assertEquals(new Subtag(Language.EN), lang.getExtension());
}
} |
47246080_3 | class SaltConfigs {
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void addLaunchAttributes(EntitySpec<?> entity, Map<?,?> attributesMap) {
entity.configure(SaltConfig.SALT_SSH_LAUNCH_ATTRIBUTES, MapModifications.add((Map)attributesMap));
}
public static void addToRunList(EntityS... | app = TestApplication.Factory.newManagedInstanceForTests();
SaltConfigs.addLaunchAttributes(app, ImmutableMap.of("k1", "v1"));
Map<String, Object> attribs = app.getConfig(SaltConfig.SALT_SSH_LAUNCH_ATTRIBUTES);
Assert.assertEquals(attribs, ImmutableMap.of("k1", "v1"));
}
} |
47301462_84 | class ImmutableBitSet implements Iterable<Integer>, Serializable, Comparable<ImmutableBitSet> {
public int indexOf(int bit) {
for (int i = nextSetBit(0), k = 0;; i = nextSetBit(i + 1), ++k) {
if (i < 0) {
return -1;
}
if (i == bit) {
return k;
}
}
}
private Immut... | assertThat(ImmutableBitSet.of(0, 2, 4).indexOf(0), equalTo(0));
assertThat(ImmutableBitSet.of(0, 2, 4).indexOf(2), equalTo(1));
assertThat(ImmutableBitSet.of(0, 2, 4).indexOf(3), equalTo(-1));
assertThat(ImmutableBitSet.of(0, 2, 4).indexOf(4), equalTo(2));
assertThat(ImmutableBitSet.of(0, 2, 4).inde... |
47309610_0 | class HelloWorld {
public void sayHello() {
System.out.print("Hello World");
}
private final ByteArrayOutputStream outStream;
}
class HelloWorldTest {
private final ByteArrayOutputStream outStream;
@Test
public void testSayHello() {
| HelloWorld hw = new HelloWorld();
hw.sayHello();
Assert.assertEquals("Hello World", outStream.toString());
}
} |
47317834_77 | class DeploymentCompleteCheckJob extends CustomCheckJob<DeploymentCompleteSpec> {
@NotNull
public CheckResult<DeploymentCompleteSpec> perform(UUID correlationId) {
final String octopusUrl = props.get(OCTOPUS_URL);
if (StringUtil.isEmptyOrSpaces(octopusUrl)) {
return DeploymentComple... | DeploymentsProviderFactory deploymentsProviderFactory = new FakeDeploymentsProviderFactory(new FakeDeploymentsProviderWithNoDeployments());
String displayName = "the-display-name";
String buildType = "the-build-type";
CustomDataStorage dataStorage = new FakeCustomDataStorage();
... |
47345553_3 | class CompositeReporter implements Reporter {
@Override
public void testBlockEnd(TestBlock testBlock, List<TestBlock> parents) {
reporters.forEach(r -> r.testBlockEnd(testBlock, parents));
}
public CompositeReporter(List<Reporter> reporters);
@Override public void start(TestBlock rootBlo... | reporter.testBlockEnd(testBlock, parents);
order.verify(mockReporter1).testBlockEnd(testBlock, parents);
order.verify(mockReporter2).testBlockEnd(testBlock, parents);
}
} |
47404616_3 | class Spreadsheet extends AbstractTableModel {
@Override
public void setValueAt(Object value, int row, int column) {
// Here, we will check the type of the incoming input:
// Because the input is always a string, if the user wants to input a number
// we first convert it to a Double (we only use Doubles)... | spreadsheet.setValueAt("blah", 1, 1);
assertEquals("blah", (String)spreadsheet.getValueAt(1, 1));
}
} |
47405371_1 | class Tracklytics implements AspectListener {
@Override public void onAspectEventTriggered(TrackEvent trackEvent, Map<String, Object> attributes) {
trackEvent(new Event(trackEvent, attributes, superAttributes));
}
private Tracklytics(EventSubscriber eventSubscriber);
public static Tracklytics init(Event... | class Foo {
@TrackEvent("event_name") public void foo() {
}
}
TrackEvent trackEvent = Foo.class.getMethod("foo").getAnnotation(TrackEvent.class);
Map<String, Object> attributes = new HashMap<>();
attributes.put("key", "value");
tracklytics.onAspectEventTriggered(trackEvent, attribu... |
47419635_10 | class AcmeLazyLoadingException extends RuntimeException {
public AcmeLazyLoadingException(AcmeResource resource, AcmeException cause) {
this(requireNonNull(resource).getClass(), requireNonNull(resource).getLocation(), cause);
}
public AcmeLazyLoadingException(AcmeResource resource, AcmeException ... | Login login = mock(Login.class);
AcmeResource resource = new TestResource(login, resourceUrl);
AcmeException cause = new AcmeException("Something went wrong");
AcmeLazyLoadingException ex = new AcmeLazyLoadingException(resource, cause);
assertThat(ex, is(instanceOf(RuntimeExcep... |
47428395_15 | class StringSubstitutionException extends RuntimeException {
public final StringSubstitutionException extend(String field) {
return extend(field, false);
}
private StringSubstitutionException(
Throwable cause,
String value,
StringBuilder fieldBuilder,
... | StringSubstitutionException exception = new StringSubstitutionException(cause, VALUE);
assertException(exception.extend(1).extend("field1").extend("field2"), "field2.field1[1]");
}
} |
47442408_8 | class WelcomeConfiguration {
public boolean getBackButtonNavigatesPages() {
return builder.backButtonNavigatesPages;
}
public WelcomeConfiguration(Builder builder);
public Context getContext();
public Fragment getFragment(int index);
public Fragment createFragment(int index);
pub... | builder1.backButtonNavigatesPages(true);
assertTrue(builder1.build().getBackButtonNavigatesPages());
builder1.backButtonNavigatesPages(false);
assertFalse(builder1.build().getBackButtonNavigatesPages());
}
} |
47489502_6 | class MoviesListingPresenterImpl implements MoviesListingPresenter {
@Override
public void setView(MoviesListingView view) {
this.view = view;
displayMovies();
}
MoviesListingPresenterImpl(MoviesListingInteractor interactor);
@Override public void destroy();
private void dis... | // given:
Observable<List<Movie>> responseObservable = Observable.just(movies);
when(interactor.fetchMovies(anyInt())).thenReturn(responseObservable);
// when:
presenter.setView(view);
// then:
verify(view).showMovies(movies);
}
} |
47492058_4 | class GraphBuilder {
static Collection<Graph> buildGraphs(Map<String, Module> modules) throws ProcessorException {
LinkedList<Graph> graphs = new LinkedList<>();
for (Module module : modules.values()) {
if (module.isCompleted) {
Graph graph = buildGraph(modules, module);
validateGraph(graph);
graph... | try {
String moduleName = "ModuleName";
Collection<Provide> provides = singleton(getFakeProvide("P", "n", singleton(new Dependency("Unknown", "?"))));
Module fakeModule = getFakeModule(moduleName, provides, null, true);
GraphBuilder.buildGraphs(singletonMap(moduleName, fakeModule));
fail();
} catch (... |
47502698_12 | class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
public String getEncrypted() {
if (!isSuccess()) {
throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
}
return encrypted;
}
public F... | String message = "help";
FingerprintEncryptionResult result = new FingerprintEncryptionResult(FingerprintResult.HELP, message, null);
assertEquals(message, result.getMessage());
result.getEncrypted();
}
} |
47536480_11 | class UnSetCommand extends AbstractCommand {
public static UnSetCommand parse(String commandString, ExecutionContext sessionContext)
throws ODPSConsoleException {
if (StringUtils.isNullOrEmpty(commandString)) {
return null;
}
String[] tokens = new AntlrObject(commandString).getTokenStringAr... | UnSetCommand cmd = UnSetCommand.parse("unse testkey", null);
assertNull(cmd);
cmd = UnSetCommand.parse("unset ", null);
assertNull(cmd);
cmd = UnSetCommand.parse("unalia testkey\n", null);
assertNull(cmd);
cmd = UnSetCommand.parse("unalias \r\n", null);
assertNull(cmd);
}
} |
47582051_0 | class Proxy extends ProxyServlet {
protected void loadProperties() {
PropertyLoader.loadProperties(Property.class, "default.properties", "dumonitor.properties");
try {
proxyServer = URI.create(Property.QUERY_TURVASERVER_URL.getValue());
} catch (IllegalArgumentException e) {
ExceptionUtil.unc... | Proxy p = new Proxy();
p.loadProperties();
// Kontrollime tulemust:
assertNotNull("Vigane konfiguratsioon", Property.QUERY_TURVASERVER_URL.getValue());
assertNotNull("Proxy serveri URL on NULL", p.proxyServer);
assertEquals("Proxy serveri URL pole õige", Property.QUERY_TURVASERVER_URL.getValue(... |
47585751_4 | class ReportParser {
public ZapReport parse(InputStream inputStream) {
SMInputFactory inputFactory = ZapUtils.newStaxParser();
try {
SMHierarchicCursor rootC = inputFactory.rootElementCursor(inputStream);
SMInputCursor owaspZapReportCursor = rootC.advance(); // <OWASPZAPReport>
String ger... | ReportParser parser = new ReportParser();
InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream("report/zaproxy-report-no-instances.xml");
ZapReport zapReport = parser.parse(inputStream);
assertThat(zapReport.getGenerated()).isEqualTo("Fri, 8 Jun 2018 09:55:08");
assertT... |
47607561_359 | class StormStatusServiceImpl implements StormStatusService {
@Override
public TopologyResponse activateTopology(String name) {
TopologyResponse topologyResponse = new TopologyResponse();
String id = getTopologyId(name);
if (id != null) {
Map result = restTemplate
.postForObject(getStorm... | when(environment.getProperty(STORM_UI_SPRING_PROPERTY)).thenReturn(HTTP_STORM_UI);
when(restTemplate.getForObject(HTTP_STORM_UI + TOPOLOGY_SUMMARY_URL, TopologySummary.class)).thenReturn(new TopologySummary());
TopologyResponse expected = new TopologyResponse();
expected.setErrorMessage(TopologyStatusC... |
47613863_6 | class CodeCoverageStore {
public static void visitProbes(final int classId, final int offset,
final boolean[] probes) { // NO_UCD
final boolean[] bs = CLASS_HITS.get(classId);
bs[CLASS_HIT_INDEX] = true;
for (int i = 0; i != probes.length; i++) {
if (probes[i]) {
bs[i + offset + 1] = ... | final SideEffect2<Integer, boolean[]> se = new SideEffect2<Integer, boolean[]>() {
@Override
public void apply(final Integer classId, final boolean[] probes) {
CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1],
probes[2], probes[3]);
}
};
assertLineCombin... |
47723400_14 | class Router {
public void resetTo(Screen screen) {
if (tryHandleEmptyBackstack(screen)) {
return;
}
resetTo(screen, TransitionDirection.EXIT);
}
public Router();
public Router(boolean allowEmptyStack);
public boolean goBack();
public void goTo(Screen nex... |
router = new TestRouter(false);
Screen screenA = new ScreenA();
router.resetTo(screenA);
assertTrue(router.fromPath.isEmpty());
assertEquals(screenA, router.toPath.get(0));
assertEquals(1, router.routeChangeCount);
}
} |
47767967_0 | class ApplicationIntrospector {
static Class<?> mainClass() {
for (Map.Entry<Thread, StackTraceElement[]> stackEntry : Thread.getAllStackTraces().entrySet()) {
// thread must be called "main"
if ("main".equals(stackEntry.getKey().getName())) {
StackTraceElement[] ... |
Class<?> mainClass = ApplicationIntrospector.mainClass();
// TODO: until https://github.com/bootique/bootique/issues/52 is available,
// we can't make an exact assertion here, as tests can be started from different IDEs, etc.
assertNotNull(mainClass);
assertNotEquals(Bootique.... |
47773974_1 | class DailyTotalCostConverter {
public static List<DailyTotalCost> convertCostsToDailyCosts(List<Cost> costList) {
List<DailyTotalCost> result = new ArrayList<>();
if (costList == null || costList.size() == 0) {
// return an empty array if we have nothing to convert
return... |
// init test
mCosts = new ArrayList<>();
mCosts.add(new Cost("Transportation", "ZET", TestDateUtil.getDate(2016, Calendar.JANUARY, 4), 100.0));
mCosts.add(new Cost("Transportation", "Description", TestDateUtil.getDate(2016, Calendar.JANUARY, 2), 150.0));
mCosts.add(new Cost("Tr... |
47790264_0 | class ResteasyEmbeddedServletInitializer implements BeanFactoryPostProcessor {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
logger.debug("Post process bean factory has been called");
findJaxrsApplications(beanFactory);
// This is ... | Map<String, ServletRegistrationBean> servletRegistrationBeans = applicationContext.getBeansOfType(ServletRegistrationBean.class);
Assert.assertNotNull(servletRegistrationBeans);
// Although there are 5 sample JAX-RS Application classes, one of them is not annotated with the ApplicationPath anno... |
47810463_2 | class InstrumentedJobListener implements JobListener {
@Override
public void onJobStarted(String jobName, Map<String, Object> parameters, Consumer<Consumer<JobResult>> finishEventSource) {
JobMetrics metric = getOrCreateMetrics(jobName);
metric.getActiveCounter().inc();
Timer.Context ... | FinishEventSource finishEventSource = new FinishEventSource();
InstrumentedJobListener listener = new InstrumentedJobListener(metricRegistry);
listener.onJobStarted("j1", Collections.emptyMap(), finishEventSource);
finishEventSource.finish(JobResult.unknown(null));
assertHasMet... |
47840491_1 | class FootwearIndustryReportParser implements Callable<FootwearIndustryReports> {
@Override
public FootwearIndustryReports call() throws Exception {
final FootwearIndustryReports reports = new FootwearIndustryReports();
final FlatFileItemReader<FootwearIndustryReports> items = FootwearIndustryR... | final FootwearIndustryReportParser parser = new FootwearIndustryReportParser(
new ClassPathResource("/" + getClass().getPackage().getName().replace(".", "/") + "/FIR_Y19.csv"));
final FootwearIndustryReports reports = parser.call();
Assertions.assertThat(reports.getAvg().isHasVal... |
47873486_28 | class IntentHelper {
public static <T extends Serializable> T getExtraSerializable(final Intent intent, final String key, final T defaultValue) {
//noinspection unchecked
final T extra = (T) intent.getSerializableExtra(key);
return extra != null ? extra : defaultValue;
}
private I... | final Serializable serializable = mock(Serializable.class);
assertEquals(serializable, IntentHelper.getExtraSerializable(new Intent().putExtra("mySerializableKey", serializable), "mySerializableKey", null));
}
} |
47885608_0 | class HelloWorldController {
@RequestMapping("/")
public String sayHello() {
return "Hello,World!";
}
}
class HelloWorldControllerTest {
@Test
public void testSayHello() {
| assertEquals("Hello,World!",new HelloWorldController().sayHello());
}
} |
47892183_0 | class RxActions {
public static <T> Action1<T> act(final Action1<T> action1, final Action1<T> action2) {
return new Action1<T>() {
@Override
public void call(T t) {
action1.call(t);
action2.call(t);
}
};
}
public RxAction... | Observable
.just(1)
.doOnNext(RxActions.act(doAction(sum), doAction(sum), doAction(sum)))
.subscribe(
RxActions.act(doAction(sum), doAction(sum)),
RxActions.act(doError(arrayError), doError(arrayError),
... |
47921185_83 | class ExternalResources {
@SuppressWarnings("ConstantConditions") public static ExternalResources initialize(
@NonNull Context context, Url url) {
if (null == context) {
throw new IllegalArgumentException("Context must not be null.");
}
if (null == url) {
throw new IllegalArgumentExcep... | ExternalResources.singleton = null;
assertNotNull(ExternalResources.initialize(null, new DefaultUrl("/")));
}
} |
47923936_0 | class JsonUtils {
public static <T> String serialize(T object) {
return mGson.toJson(object);
}
public static T deserialize(String json, Class<T> clz);
public static T deserialize(JsonObject json, Class<T> clz);
public static T deserialize(String json, Type type);
}
class JsonUtilsTest {... | assertEquals("{\"name\":\"Lauren\",\"sex\":\"男\"}", JsonUtils.serialize(new User("Lauren", "男")));
}
} |
48155157_2 | class XLog {
public static Logger.Builder tag(String tag) {
return new Logger.Builder().tag(tag);
}
private XLog();
public static void init();
public static void init(int logLevel);
@Deprecated public static void init(int logLevel, LogConfiguration logConfiguration);
public static void init(LogCon... | XLog.i(MESSAGE);
assertLog(INFO, DEFAULT_TAG, MESSAGE);
logsContainer.clear();
XLog.tag(CUSTOM_TAG).i(MESSAGE);
assertLog(INFO, CUSTOM_TAG, MESSAGE);
}
} |
48183909_30 | class CnATreeElementLabelGenerator {
public static String getElementTitle(CnATreeElement element) {
if (element instanceof Safeguard) {
Safeguard safeguard = (Safeguard) element;
return createTitleForElementWithSecurityLevel(safeguard.getIdentifier(),
safeguard.g... | ItSystem itSystem = new ItSystem(null);
itSystem.setPropertyValue(ItSystem.PROP_NAME, "Server 1");
Assert.assertEquals("Server 1", CnATreeElementLabelGenerator.getElementTitle(itSystem));
}
} |
48203032_52 | class CreateServiceInstanceBindingRequest extends AsyncParameterizedServiceInstanceRequest {
public static CreateServiceInstanceBindingRequestBuilder builder() {
return new CreateServiceInstanceBindingRequestBuilder();
}
public CreateServiceInstanceBindingRequest();
public CreateServiceInstanceBindingRequest(... | CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest
.builder().platformInstanceId("platform-instance-id")
.apiInfoLocation("api-info-location")
.originatingIdentity(PlatformContext.builder()
.platform("sample-platform").build())
.asyncAccepted(true)
.serviceDefi... |
48234412_15 | class SingleChoice extends ChoiceBase {
public <T> T select(T defaultValue, List<T> options) {
return select(defaultValue, options, null);
}
private SingleChoice(Builder builder);
@SafeVarargs public final T select(T defaultValue, T... options);
public T select(T defaultValue, List<T> op... | byte[] first = new byte[14];
byte[] second = new byte[47];
byte[] third = new byte[1024];
Arrays.fill(first, (byte)147);
Arrays.fill(second, (byte)55);
Arrays.fill(third, (byte)14);
System.setProperty("clichoice.useDefault", "true");
assertEquals("Must ... |
48260005_6 | class EmailIntentBuilder {
@NotNull
static String fixLineBreaks(String text) {
return text.replaceAll("\r\n", "\n").replace('\r', '\n').replaceAll("\n", "\r\n");
}
private EmailIntentBuilder(@NotNull Context context);
@NotNull public static EmailIntentBuilder from(@NotNull Context contex... | String result = EmailIntentBuilder.fixLineBreaks("line one\r\nline two");
assertThat(result).isEqualTo("line one\r\nline two");
}
} |
48295629_35 | class BinaryAdapters {
public static BinaryInject injectionCarrier(ByteBuffer buffer) {
return new BinaryInjectAdapter(buffer);
}
private BinaryAdapters();
public static BinaryExtract extractionCarrier(ByteBuffer buffer);
}
class BinaryAdaptersTest {
@Test
public void testInjectBi... | ByteBuffer buffer = ByteBuffer.allocate(1);
BinaryInject binary = BinaryAdapters.injectionCarrier(buffer);
assertEquals(buffer, binary.injectionBuffer(1));
assertEquals(0, buffer.position());
}
} |
48305884_0 | class ColumnMapProcessor extends AbstractMarkLogicItemProcessor<Map<String, Object>> {
public void setRootLocalName(String rootName) {
this.rootLocalName = rootName;
}
public ColumnMapProcessor(ColumnMapSerializer columnMapSerializer);
public ColumnMapProcessor(ColumnMapSerializer columnMapS... | ColumnMapProcessor columnMapProcessor = new ColumnMapProcessor(new DefaultStaxColumnMapSerializer());
columnMapProcessor.setRootLocalName("test");
Map<String, Object> map = new HashMap<String, Object>();
map.put("sample", "value");
DocumentWriteOperation handle = columnMapProce... |
48360594_494 | class TextPatternUtil {
public static char[] replacePatternCharacter(Integer codePointToReplace, Random random) {
for (CharPattern charPattern : CharPattern.values()) {
if (charPattern.getReplaceChar().charValue() == codePointToReplace) {
int length = charPattern.getCodePointSiz... | Random random = new Random(569888);
char n = 'C';
int input = Integer.valueOf(n);
Integer codePoint = "嬶".codePointAt(0);
char[] replaceCharacter = TextPatternUtil.replacePatternCharacter(input, random);
Assert.assertEquals(codePoint.intValue(), new String(replaceCharacte... |
48363025_0 | class UserEventController {
@RequestMapping(value = "/createdEvent", method = RequestMethod.POST)
public ResponseEntity<String> publishCreatedEvent(@RequestBody(required = true) UserCreatedEvent userCreatedEvent,
HttpServletResponse response) {
log.debug("Adding User [{}] '{}'", us... | // Arrange
userEventController.commandGateway = gateway; //cheating a bit here, but mocking all the axon framework's beans is a pain.
when(gateway.sendAndWait(any())).thenReturn(null);
UserCreatedEvent userCreatedEvent = new UserCreatedEvent();
userCreatedEvent.setId(1L);
... |
48401967_4 | class ComponentGrid extends Grid {
public FocusPreserveExtension getFocusPreserveExtension() {
return componentGridDecorator.getFocusPreserveExtension();
}
public ComponentGrid(Class<T> typeOfRows);
public ComponentGridDecorator<T> getComponentGridDecorator();
public ComponentGrid<T> rem... | ComponentGrid grid = createTestGrid();
FocusPreserveExtension focusPreserveExtension = (FocusPreserveExtension) extractExtension(grid,
FocusPreserveExtension.class);
assertThat(focusPreserveExtension, is(sameInstance(grid.getFocusPreserveExtension())));
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.