id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
144786483_5 | class CreateEngagement {
public static JsonObject main(JsonObject args) {
JsonObject response = new JsonObject();
EngagementStore store = new EngagementStore(args, "engagements");
String[] tags = new String[] {"java", "cloud"};
Engagement jfokus = new Engagement( "JFokus 2019", "S... | JsonObject args = new JsonObject();
JsonObject response = CreateEngagement.main(args);
assertNotNull( response.getAsJsonPrimitive("id").getAsString());
// assertNotNull(greetings);
// assertEquals("Hello! Welcome to OpenWhisk", greetings);
}
} |
144974148_1 | class SingletonPool {
@SuppressWarnings("unchecked")
public static <I, T extends I> T get(Class<I> clazz, IFactory factory) throws Exception {
if (clazz == null) {
return null;
}
if (factory == null) {
factory = RouterComponents.getDefaultFactory();
}
... | TestSingleton o1 = SingletonPool.get(TestSingleton.class, null);
Assert.assertNotNull(o1);
TestSingleton o2 = SingletonPool.get(TestSingleton.class, null);
Assert.assertSame(o1, o2);
}
} |
145032308_0 | class DnsUntil {
public static InetSocketAddress toIpAddress(String hostName, int port) {
InetSocketAddress socketAddress;
try {
InetAddress address = InetAddress.getByName(hostName);
String ipAddress = address.getHostAddress();
socketAddress = InetSocketAddress.createUnresolved(ipAddress, ... | InetSocketAddress inetSocketAddress = DnsUntil.toIpAddress("localhost", 8001);
InetSocketAddress unresolved = InetSocketAddress.createUnresolved("127.0.0.1", 8001);
Assert.assertTrue(unresolved.equals(inetSocketAddress));
}
} |
145080847_2 | class FileDescriptor implements Cloneable {
public boolean matches(FileDescriptor other) {
if (!StringUtils.equals(directory, other.directory)) {
return false;
}
if (!StringUtils.equals(relativePath, other.relativePath)) {
return false;
}
if (filename... | FileDescriptor descriptor1 = new FileDescriptor();
FileDescriptor descriptor2 = new FileDescriptor();
assertFalse(descriptor1.matches(descriptor2));
descriptor1.setDirectory("/Users/kai");
descriptor2.setDirectory("/Users/kai");
assertFalse(descriptor1.matches(descriptor2... |
145101610_0 | class OpeningBalanceEvent extends VanillaSignedMessage<OpeningBalanceEvent> implements Validable {
public Map<Currency, Double> balances() {
return balances;
}
public long balanceAddress();
public OpeningBalanceEvent balanceAddress(long balanceAccount);
@Override public void validate();
}... | KeyPair kp7 = new KeyPair(7);
BytesStore publicKey1 = kp7.publicKey;
BytesStore secretKey1 = kp7.secretKey;
OpeningBalanceEvent obe = new OpeningBalanceEvent()
.protocol(1).messageType(1)
.balanceAddress(DecentredUtil.toAddress(publicKey1));
obe.b... |
145104488_35 | class ApplicationTokenService {
public TokenDetails getApplicationTokenDetails() {
UserKey user = getRunOnBehalfOfUser();
return getApplicationTokenDetailsForUser(user);
}
@Autowired public ApplicationTokenService(OAuthClient oAuthClient,
OidcAuthenticat... | onBehalfOfUsernameHolder.removeUser();
UserKey userKey1 = new UserKey("user1", "realm1");
onBehalfOfUsernameHolder.putUser(userKey1);
TokenDetails tokenDetails = new TokenDetails();
tokenDetails.setAccessToken("access-token123");
tokenDetails.setRefreshToken("refresh-tok... |
145126556_57 | class PrivilegesGrantorLambda implements RequestHandler<SQSEvent, Response> {
@Override
public Response handleRequest(SQSEvent event, Context context) {
logger = context.getLogger();
List<String> failedEvents = new ArrayList<>();
List<String> successfulTableNames = new ArrayList<>();
IMetaStoreClie... | SQSEvent event = new SQSEvent();
SQSEvent.SQSMessage record = new SQSEvent.SQSMessage();
record.setBody(createTableJson());
event.setRecords(Lists.newArrayList(record));
when(thriftHiveClientFactory.newInstance("thrift://uri:9083", "20000"))
.thenThrow(new HiveClientException("init error"));... |
145233455_12 | class PartitionTableFactory {
public static PartitionTable createPartitionTable(BlockDeviceDriver blockDevice)
throws IOException {
for(PartitionTableCreator creator : partitionTables) {
PartitionTable table = creator.read(blockDevice);
if(table != null) {
return tab... | BlockDeviceDriver blockDevice = new FileBlockDeviceDriver(
new URL("https://www.dropbox.com/s/w3x12zw6d6lc6x5/mbr_1_partition_hfs%2B.bin?dl=1"));
blockDevice.init();
PartitionTable table = PartitionTableFactory.createPartitionTable(blockDevice);
assertTrue(table instanc... |
145392451_3 | class ZookeeperCompensationServiceImpl implements CompensationService {
@Override
public CommonPager<TccCompensationVO> listByPage(final CompensationQuery query) {
CommonPager<TccCompensationVO> voCommonPager = new CommonPager<>();
final int currentPage = query.getPageParameter().getCurrentPage();
final int pa... |
CompensationQuery query = new CompensationQuery();
query.setApplicationName("alipay-service");
PageParameter pageParameter = new PageParameter(1, 8);
query.setPageParameter(pageParameter);
final CommonPager<TccCompensationVO> pager = compensationService.listByPage(query);
Assert.assertNotNull(pager.get... |
145393952_0 | class ListasDePuntos {
public static ParDePuntos parMasCercano(List<Punto2D> lista){
ParDePuntos p = null;
List<Punto2D> puntosX;
List<Punto2D> puntosY;
Comparator<Punto2D> ordX = new Comparator<Punto2D>(){
@Override
public int compare(Punto2D p1, Punto2D p2) {
return p1.getX().compareTo(p2.getX());... | List<Punto2D> lista = ListasDePuntos.getListaPuntosAleatoria(10000);
ParDePuntos p1 = ListasDePuntos.parMasCercano(lista);
ParDePuntos p2 = ListasDePuntos.parMasCercanoBase(0, lista.size(), lista);
if(!p1.getDistancia().equals(p2.getDistancia())){
System.out.println(p1+","+p2);
}
assertTrue(p1.getDistanc... |
145452341_0 | class UsageDataUtil {
public static void processFile(FileItem file, UserInteractionEventCallback callback) throws IOException {
log.debug(String.format("Parsing %s", file.getName()));
if (file.getContentType().startsWith("application/zip")) {
ZipInputStream zip = new ZipInputStream(file.getInputStream());
... |
final int[] countFiles = { 0 };
UsageDataUtil.processFile(zipItem, new UserInteractionEventCallback() {
public boolean visit(UserInteractionEvent uie) {
++countFiles[0];
return true;
}
});
Assert.assertEquals(18015, countFiles[0]);
}
} |
145659250_3 | class CompositeException extends RuntimeException {
@Override
public String getMessage() {
return message;
}
public CompositeException(Throwable... exceptions);
public CompositeException(Iterable<? extends Throwable> errors);
public List<Throwable> getExceptions();
@Override pub... | CompositeException compositeException = new CompositeException(ex1, ex2, ex3);
assertEquals("3 exceptions occurred. ", compositeException.getMessage());
}
} |
145711148_0 | class ByteBuddyProcessFunctionInvoker {
public static <InT, OutT> ProcessFunctionInvoker<InT, OutT> create(StreamingLedgerSpec<InT, OutT> spec) {
final ClassLoader userClassLoader = classLoader(spec);
final Class<?> generatedClass = CACHE.findOrInsert(userClassLoader, spec, () -> generateAndLoadCla... | ProcessFunctionInvoker<String, Long> generatedCodeThatInvokesUserCode =
ByteBuddyProcessFunctionInvoker.create(specification);
arguments[0].value = Long.MAX_VALUE;
generatedCodeThatInvokesUserCode.invoke("does not matter", context, arguments);
assertThat(context.emitted... |
145861384_0 | class OpenApi30SpecificationGenerator implements SpecificationGenerator {
@Override
public Specification getSpecification() {
return Specification.OPENAPI_V3;
}
public OpenApi30SpecificationGenerator();
public OpenApi30SpecificationGenerator(OpenApi3Generator generator);
@Override public String gen... | assertThat(generator.getSpecification()).isEqualTo(Specification.OPENAPI_V3);
}
} |
145862721_0 | class ExampleAgent {
static List<TransformDescriptor> readProbes(String probesFile) throws IOException {
if (probesFile == null || probesFile.trim().length() == 0) {
probesFile = DEFAULT_CONFIG;
}
File file = new File(probesFile);
List<String> lines = null;
if (file.exists()) {
lines = Files.readAllLi... | List<TransformDescriptor> probes = ExampleAgent.readProbes(null);
assertEquals(3, probes.size());
for (TransformDescriptor probe : probes) {
assertEquals(TestProgram.class.getName(), probe.getTransformedClass());
assertNotNull(probe.getTransformedMethod());
assertNotNull(probe.getTransformedDescriptor())... |
145960323_53 | class QueueReader {
public boolean hasRecordAvailable()
{
maybeReadNext();
return nextRecord != null;
}
public QueueReader(ToolOptions toolOptions);
QueueReader(ToolOptions toolOptions, ChronicleQueue chronicleQueue);
private static ChronicleQueue getChronicleQueue(ToolOpti... | when(tailer.readDocument(any(ReadMarshallable.class))).thenReturn(false);
QueueReader reader = givenReader();
assertThat(reader.hasRecordAvailable()).isFalse();
}
} |
146009627_215 | class EcmFileParticipantService {
@Transactional(rollbackFor = Exception.class)
public void inheritParticipantsFromAssignedObject(List<AcmParticipant> assignedObjectParticipants,
List<AcmParticipant> originalAssignedObjectParticipants, AcmContainer acmContainer, boolean restricted)
{
if... | final Long objectId = 1L;
final String participantLdapId = "userId2";
final String participantType = "write";
final String participantLdapId1 = "userId1";
final String participantType1 = "assignee";
final String participantLdapId2 = "userId2";
final String parti... |
146066191_2 | class GeeseService extends GeeseServiceImplBase {
@Override
public void getGeese(GetGeeseRequest request,
StreamObserver<GeeseResponse> responseObserver) {
GeeseResponse.Builder response = GeeseResponse.newBuilder();
int gooseWidth = Integer.max(request.getGooseWidth()... | InjectedFailureProvider fixtureFailureProvider = new InjectedFailureProvider();
fixtureFailureProvider.setFullFixtureEnabled(true);
grpcServerRule.getServiceRegistry()
.addService(new GeeseService((min, max) -> 0,
index -> 0, fixtureFailureProvider));
... |
146223479_3 | class SecretNotAllowedRule extends BaseTreeVisitor implements JavaFileScanner {
boolean isSecret(String name) {
return name.toLowerCase().contains("secret");
}
@Override public void scanFile(JavaFileScannerContext context);
@Override public void visitMethod(MethodTree tree);
@Override public void visitVariable... | assertFalse(rule.isSecret("other"));
}
} |
146285827_105 | class CrossOriginConfig {
public boolean isEnabled() {
return enabled;
}
private CrossOriginConfig(Builder builder);
public static Builder builder();
public static Builder builder(Config config);
public static Builder builder(CrossOriginConfig original);
public static CrossOrigin... | Config node = testConfig.get("just-disabled");
assertThat(node, is(notNullValue()));
assertThat(node.exists(), is(true));
CrossOriginConfig b = node.as(CrossOriginConfig::create).get();
assertThat(b.isEnabled(), is(false));
}
} |
146294560_3 | class TechemHandlerFactory extends BaseThingHandlerFactory {
@Override
protected ThingHandler createHandler(Thing thing) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if (thingTypeUID.equals(TechemBindingConstants.THING_TYPE_TECHEM_HKV45)
|| thingTypeUID.equals(TechemB... | ThingImpl thing = new ThingImpl(THING_TYPE_TECHEM_HKV69, "00000");
ThingHandler handler = handlerFactory.createHandler(thing);
Assertions.assertThat(handler).isNotNull();
}
} |
146386097_0 | class FeaturePlugin implements Plugin {
static FeatureGraph createFeatureGraph(
JCTree.JCCompilationUnit compilationUnit, Context context) {
FeatureGraph featureGraph =
new FeatureGraph(
compilationUnit.getSourceFile().getName(),
compilationUnit.endPositions,
com... | // ARRANGE
TestCompilation compilation = TestCompilation.compile("Test.java", "");
// ACT
FeatureGraph featureGraph =
FeaturePlugin.createFeatureGraph(compilation.compilationUnit(), compilation.context());
// ASSERT
assertThat(featureGraph.astNodes()).isEmpty();
}
} |
146510094_385 | class DatePartition extends BasePartition implements JdbcFragmentMetadata {
@Override
public String toSqlConstraint(String quoteString, DbProduct dbProduct) {
if (quoteString == null) {
throw new RuntimeException("Quote string cannot be null");
}
if (dbProduct == null) {
... | DatePartition partition = new DatePartition(COL_RAW, LocalDate.parse("2000-01-01"), null);
String constraint = partition.toSqlConstraint(QUOTE, dbProduct);
assertEquals(
COL + " >= date'2000-01-01'",
constraint
);
}
} |
146525109_27 | class InternalPhotosLibraryClient implements BackgroundResource {
public final LeaveSharedAlbumResponse leaveSharedAlbum(String shareToken) {
LeaveSharedAlbumRequest request =
LeaveSharedAlbumRequest.newBuilder().setShareToken(shareToken).build();
return leaveSharedAlbum(request);
}
protected I... | StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockPhotosLibrary.addException(exception);
try {
String shareToken = "shareToken407816601";
client.leaveSharedAlbum(shareToken);
Assert.fail("No exception raised");
} catch (InvalidArgumentExcepti... |
146535797_375 | class WearableRecyclerView extends RecyclerView {
public void setEdgeItemsCenteringEnabled(boolean isEnabled) {
mEdgeItemsCenteringEnabled = isEnabled;
if (mEdgeItemsCenteringEnabled) {
if (getChildCount() > 0) {
setupCenteredPadding();
} else {
... | mActivityRule.runOnUiThread(new Runnable() {
@Override
public void run() {
WearableRecyclerView wrv =
(WearableRecyclerView) mActivityRule.getActivity().findViewById(R.id.wrv);
wrv.setEdgeItemsCenteringEnabled(true);
}
... |
146574601_1 | class ReflectionHelper {
public static void parseServiceMetadataString(String metadataField, Map<String, List<String>> metadata) {
StringBuffer sb = new StringBuffer(metadataField);
int dot = 0;
int nextEquals = sb.indexOf(EQUALS_STRING, dot);
while (nextEquals > 0) {
S... | HashMap<String, List<String>> metadata = new HashMap<String, List<String>>();
ReflectionHelper.parseServiceMetadataString(GOOD_METADATA_2, metadata);
Assert.assertEquals(metadata.get("key1").get(0), "value1");
Assert.assertEquals(metadata.get("key2").get(0), "value2");
... |
146578832_1 | class ParallelWorldClassLoader extends ClassLoader implements Closeable {
@Override
protected URL findResource(String name) {
URL u = getParent().getResource(prefix + name);
if (u != null) {
try {
jars.add(new JarFile(new File(toJarUrl(u).toURI())));
} ca... | if (isJDK9()) return;
URL resource = pwcl.getResource("javax/xml/ws/Service.class");
URL object = pwcl.getResource("java/lang/Object.class");
String resJar = resource.getPath().substring(0, resource.getPath().indexOf("!"));
String rtJar = object.getPath().substring(0, object.getP... |
146582041_0 | class GlitchClient {
public CredentialManager getCredentialManager() {
return credentialManager;
}
private GlitchClient(OkHttpClient httpClient, Config config, Storage storage);
public static Builder builder();
public Config getConfiguration();
public OkHttpClient getHttpClient();
... | StepVerifier.create(CLIENT.getCredentialManager().valid(credential))
.expectSubscription()
.expectNextMatches(validate ->
validate.getUserId() == 120074641L &&
Objects.equals(validate.getLogin(), "sandalphon_ai") &&
... |
146633589_41 | class StringUtils {
public static String stripEnd(final String str, final String stripChars) {
int end;
if (str == null || (end = str.length()) == 0) {
return str;
}
if (stripChars == null) {
while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {
... | Assert.assertEquals("foo", StringUtils.stripEnd("foo!", "!"));
Assert.assertEquals(" foo", StringUtils.stripEnd(" foo ", " "));
Assert.assertEquals("!", StringUtils.stripEnd("!", ""));
Assert.assertEquals("#", StringUtils.stripEnd("# ", null));
Assert.assertEquals("", StringU... |
146924987_18 | class FastDatumReaderWriterUtil {
public static <T> FastSpecificDatumReader<T> getFastSpecificDatumReader(Schema schema) {
return (FastSpecificDatumReader<T>) getFastSpecificDatumReader(schema, schema);
}
private FastDatumReaderWriterUtil();
public static FastGenericDatumReader<T> getFastGenericDatumRea... | Schema testSchema = Schema.parse("{\"type\": \"record\", \"name\": \"test_record\", \"fields\":[]}");
FastSpecificDatumReader fastReader = FastDatumReaderWriterUtil.getFastSpecificDatumReader(testSchema);
Assert.assertNotNull(fastReader);
FastSpecificDatumReader newFastReader = FastDatumReaderWriterUtil... |
146941185_237 | class DataCollectionHelper {
public void setAutomaticDataCollectionEnabled(boolean isEnabled) {
// Update SharedPreferences, so that we preserve state across app restarts
sharedPreferencesUtils.setBooleanPreference(AUTO_INIT_PREFERENCES, isEnabled);
}
@Inject public DataCollectionHelper(
Firebase... | when(sharedPreferencesUtils.isPreferenceSet(DataCollectionHelper.AUTO_INIT_PREFERENCES))
.thenReturn(false);
when(sharedPreferencesUtils.isManifestSet(
DataCollectionHelper.MANIFEST_METADATA_AUTO_INIT_ENABLED))
.thenReturn(false);
when(firebaseApp.isDataCollectionDefaultEnabled()... |
146983529_45 | class StringField implements FieldType<String> {
@Override
public String convert(Object objValue) throws OperationException {
if (objValue == null) {
throw new OperationException(ErrorCode.DATATYPE_MISMATCH);
}
final String str = objValue.toString();
if (length > 0 ... | System.out.println("convert");
StringField instance;
instance = new StringField(Types.STRING, "36");
UUID expectedResult = UUID.randomUUID();
assertEquals(expectedResult.toString(), instance.convert(expectedResult));
assertEquals(expectedResult.toString(), instance.conve... |
147038962_0 | class LogTrackerRunnable implements Runnable {
@Override
public void run() {
try {
LogTrackerUtil.setContext(context);
doRun();
} catch (LogTrackerException e) {
Logger.warn("Context transfer failed", e);
} catch (Exception e) {
Logger.war... | doCallRealMethod().when(logTrackerRunnable).run();
logTrackerRunnable.run();
PowerMockito.verifyStatic(VerificationModeFactory.times(1));
LogTrackerUtil.setContext(any(Http.Context.class));
PowerMockito.verifyStatic(VerificationModeFactory.times(1));
LogTrackerUtil.clea... |
147102058_5 | class ApplicationPropertiesSourceGenerator {
public void generate() throws GeneratorException {
Configuration freeMarkerConfiguration = new Configuration();
freeMarkerConfiguration.setClassForTemplateLoading(WebXmlSourceGenerator.class,
"/templates/properties");
freeMarkerC... | ApplicationPropertiesSourceGenerator generator = getGenerator();
generator.generate();
Path propsPath = Files.find(resourceFolder.getRoot().toPath(), Integer.MAX_VALUE,
(filePath, fileAttr) -> fileAttr.isRegularFile())
.filter(path -> path.toFile().getName().equa... |
147162839_18 | class JobExecutionService {
public Collection<JobExecution> jobExecutions(Optional<String> jobNameRegexp,
Optional<String> exitCode,
int maxNumberOfExecutionsPerJobName) {
logger.debug("Getting job execution... | Collection<JobExecution> jes =
jobExecutionService.jobExecutions(empty(), Optional.of(ExitStatus.FAILED.getExitCode()), 1);
Assertions.assertThat(jes).hasSize(2);
Assertions.assertThat(jes).extracting(je -> je.getExitCode()).allMatch(s -> s.equals("FAILED"));
}
} |
147324963_118 | class Peer extends PeerSocketHandler {
public void startBlockChainDownload() {
setDownloadData(true);
// TODO: peer might still have blocks that we don't have, and even have a heavier
// chain even if the chain block count is lower.
final int blocksLeft = getPeerBlockHeightDifferenc... | Block b1 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).block;
blockChain.add(b1);
Block b2 = makeSolvedTestBlock(b1);
blockChain.add(b2);
connect();
fail.set(true);
peer.addChainDownloadStartedEventListener(Threading.SAME_THREAD, new ChainDownloadStar... |
147334432_0 | class Banking {
public static Double simpleInterest(Double principal,
Double rateOfInterest, Integer years){
Objects.requireNonNull(principal, "Principal cannot be null");
Objects.requireNonNull(rateOfInterest, "Rate of interest cannot be null");
Objects.requireNonNull(years, "Year... | Double simpleInterest = Banking.simpleInterest(1000.0, 10.0, 2);
assertThat(simpleInterest).isEqualTo(200.0);
}
} |
147522483_135 | class CombiningValidator implements Validator<T> {
@Override
public ValidationResult validate(T t) {
for (Validator<T> validator : validators) {
ValidationResult result = validator.validate(t);
if (result.isErroneous()) {
debugLog(t, validator);
validationListeners.forEach(listener -> listener.onVali... | Validator<Token> combiningValidator = new CombiningValidator<>(
TokenTestValidator.createValid(), TokenTestValidator.createInvalid(FIRST_ERROR_MESSAGE),
TokenTestValidator.createInvalid(SECOND_ERROR_MESSAGE));
String error = combiningValidator.validate(TOKEN).getErrorDescription();
assertThat(error).isE... |
147527545_2 | class Parts_Picker_Get2 extends DataSource {
@Override
protected int getDataSourceKey() {
return 1791;
}
Parts_Picker_Get2(IDataSourceCallback iDataSourceCallback, HttpDataSourceCredentials credentials, String serverName);
Parts_Picker_Get2(IDataSourceCallback iDataSourceCallback, HttpDataSourceCred... | int expected = 1791;
int output = new Parts_Picker_Get2(null, null, null).getDataSourceKey();
assertEquals(expected, output);
}
} |
147637805_24 | class InputCoverageFactory extends org.evosuite.coverage.io.input.InputCoverageFactory {
protected void detectGoals(String className, String methodName, Class<?>[] argumentClasses ,Type[] argumentTypes, List<InputCoverageTestFitness> goals){
for (int i=0; i<argumentTypes.length;i++){
Type argTy... | Type type = Type.getType(Set.class);
List<InputCoverageTestFitness> goals = new ArrayList<InputCoverageTestFitness>();
inputCoverageFactory.detectGoals("ClassA","method1",new Class[]{Set.class},new Type[]{type},goals);
assert (goals.size() == 3);
}
} |
147747963_305 | class FromInputStreamPublisher extends Publisher<byte[]> implements PublisherSource<byte[]> {
@Override
public void subscribe(final Subscriber<? super byte[]> subscriber) {
subscribeInternal(subscriber);
}
FromInputStreamPublisher(final InputStream stream);
@Override protected void hand... | initChunkedStream(smallBuff, ofAll(10), ofAll(10));
Subscriber sub = mock(Subscriber.class);
doAnswer(inv -> {
Subscription s = inv.getArgument(0);
s.request(1);
s.cancel();
return null;
}).when(sub).onSubscribe(any());
doThrow(DE... |
147802356_777 | class FP2Immutable {
FP2Immutable sqr() {
FP2 result = new FP2(fp2);
result.sqr();
return new FP2Immutable(result);
}
FP2Immutable(FP2Immutable fp2Immutable);
FP2Immutable(FP2 fp2);
FP2Immutable(FP fpA, FP fpB);
FP2Immutable(BIG big1, BIG big2);
FP2Immutable(int c);
FP2Immutabl... | assertEquals(XSQ, X.sqr());
}
} |
147809547_47 | class LogManagerProperties extends Properties {
static <T> T newObjectFrom(String name, Class<T> type) throws Exception {
try {
final Class<?> clazz = LogManagerProperties.findClass(name);
//This check avoids additional side effects when the name parameter
//is a literal... | try {
Class<?> k = ErrorAuthenticator.class;
jakarta.mail.Authenticator a;
a = LogManagerProperties.newObjectFrom(k.getName(), Authenticator.class);
assertEquals(k, a.getClass());
setPending(new ThreadDeath());
try {
a = L... |
147922185_562 | class IncidentDateExtensionUtils {
@Nullable
public static Date getValue( @Nonnull IBaseHasExtensions resource )
{
return BaseExtensionUtils.getDateValue( URL, resource );
}
private IncidentDateExtensionUtils();
public static void setValue( @Nonnull IBaseHasExtensions resource, @Null... | TestPlanDefinition planDefinition = new TestPlanDefinition();
final Date date = new Date();
IncidentDateExtensionUtils.setValue( planDefinition, date, TypeFactory::createType );
Assert.assertEquals( date, IncidentDateExtensionUtils.getValue( planDefinition ) );
}
} |
147965914_0 | class AddressService extends BaseNodeAddressService {
public AddressesExistsResponse addressesCheckExistenceAndRequestHistoryNode(AddressBulkRequest addressRequest) {
List<Hash> addressHashes = addressRequest.getAddresses();
LinkedHashMap<String, Boolean> addressHashToFoundStatusMap = new LinkedHa... | AddressBulkRequest addressBulkRequest = AddressTestUtils.generateAddressBulkRequest(
addressInLocalAddressesCollection.getHash());
AddressesExistsResponse actualResponse = addressService.addressesCheckExistenceAndRequestHistoryNode(addressBulkRequest);
AddressesExistsResponse e... |
147968892_2 | class BucketBehaviorEventsService implements IBucketEventService<BehaviorEventsData, BucketBehaviorEventsData> {
@Override
public double getBucketSumScore(BucketBehaviorEventsData bucketBehaviorEventsData) {
BucketBehaviorEventsCalculator bucketCalculator = new BucketBehaviorEventsCalculator(bucketBeha... | addBehaviorEvents();
for (int i = 0; i < 8; i++) {
addFillingTheQuestionnaireEvent(UserType.MERCHANT);
}
for (int i = 0; i < 6; i++) {
addFillingTheQuestionnaireEvent(UserType.MERCHANT);
}
double bucketSumScore = bucketBehaviorEventsService.getBu... |
147984736_17 | class CategoryServiceImpl implements CategoryService {
@Override
@LogMethod("添加收益分类")
public Category appendCategory(String userId, String name) {
AssertUtils.throwIf(exists(userId, name), BeeErrorConsts.CATEGORY_EXISTS);
Category category = new Category();
category.setCreateTime(Sy... | Assert.assertNotNull(categoryService.appendCategory(getUser().getId(), RandomUtil.randomString(6)));
}
} |
147999347_5 | class ObjectiveC extends AbstractLanguage {
@Nonnull
@Override
public String[] getFileSuffixes() {
String[] suffixes = filterEmptyStrings(configuration.getStringArray(ObjectiveCPlugin.FILE_SUFFIXES_KEY));
if (suffixes.length == 0) {
suffixes = StringUtils.split(ObjectiveCPlugin.... | String[] languageSuffixes = {"h", "m"};
settings.setProperty(ObjectiveCPlugin.FILE_SUFFIXES_KEY, languageSuffixes);
String[] actual = language.getFileSuffixes();
assertEquals(languageSuffixes, actual);
}
} |
148116142_74 | class MutableInt extends Number implements Comparable<MutableInt>, Mutable<Number> {
@Override
public Integer getValue() {
return Integer.valueOf(value);
}
public MutableInt();
public MutableInt(int value);
public MutableInt(Number value);
public MutableInt(String value);
@Override public void setValue... | MutableInt i = new MutableInt("1");
assertTrue(i.getValue() == 1);
}
} |
148428318_2 | class DataTypeUtils {
public static TypeInformation convertToArray(String arrayTypeString) {
Matcher matcher = matchCompositeType(arrayTypeString);
final String errorMsg = arrayTypeString + "convert to array type error!";
Preconditions.checkState(matcher.find(), errorMsg);
String ... | String[] normalFieldNames = new String[] { "id", "name" };
TypeInformation[] normalTypes = new TypeInformation[] {Types.INT(), Types.STRING()};
RowTypeInfo rowTypeInfo = new RowTypeInfo(normalTypes, normalFieldNames);
TypeInformation normalAtomicType = Types.OBJECT_ARRAY(Types.STRING());... |
148473211_2 | class Devon4jPackage {
public static Devon4jPackage of(String root, String application, String component, String layer, String scope,
String detail) {
String[] roots;
if (root == null) {
roots = new String[0];
} else {
roots = root.split(REGEX_PKG_SEPARATOR);
}
String[] details... |
Assertions.assertThrows(IllegalArgumentException.class, () -> {
String packageName = "...batch.api.impl";
Devon4jPackage.of(packageName);
});
}
} |
148480967_24 | class Workbench extends Control {
public final WorkbenchDialog showDialog(WorkbenchDialog dialog) {
DialogControl dialogControl = dialog.getDialogControl();
dialogControl.setWorkbench(this);
showOverlay(dialogControl, dialog.isBlocking());
return dialog;
}
public Workbench();
private Workben... | robot.interact(() -> {
when(mockDialog.isBlocking()).thenReturn(true);
assertDialogNotShown();
WorkbenchDialog result = workbench.showDialog(mockDialog);
assertDialogShown(result, true);
verify(mockDialog, atLeastOnce()).isBlocking(); // call showOverlay(...) inside showDialog()
... |
148614148_0 | class CommandQueue {
public void sendEvent(@Nonnull final T event) {
if(event == null) {
throw new IllegalArgumentException("Null value is not allowed as an event");
}
if(!canEmitEvents()) {
if(limit == -1 || queuedEvents.size() < limit) { // drop new events that don... | CommandQueue<Void> queue = new CommandQueue<>();
try {
queue.sendEvent(null);
Assert.fail();
} catch(IllegalArgumentException e) {
// OK!
}
}
} |
148617498_16 | class ConsulConfigSource extends EnabledConfigSource {
@Override
public String getValue(String key) {
if (key.startsWith(KEY_PREFIX)) {
// in case we are about to configure ourselves we simply ignore that key
return null;
}
TimedEntry entry = cache.get(k... | GetValue value = new GetValue();
value.setValue(Base64.getEncoder().encodeToString("hello".getBytes()));
when(configSource.client.getKVValue(anyString())).thenReturn(new Response<GetValue>(value, 0L, true, 0L));
assertEquals("hello", configSource.getValue("test"));
}
} |
148707832_1 | class App {
public static String sha256hex(String input) {
return DigestUtils.sha256Hex(input);
}
public static void main(String[] args);
private String INPUT;
}
class AppTest {
private String INPUT;
@Test
public void testHex() {
| String expected = "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92";
Assert.assertEquals(expected, App.sha256hex(INPUT));
}
} |
148862443_2 | class HibernateUtils {
public static SessionFactory getSessionFactory(@NonNull MetadataSources sources) {
try {
Metadata metadata = sources.getMetadataBuilder().build();
return metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
if (sources.getServiceRegistry() != null) {
... | StandardServiceRegistry serviceRegistry = getServiceRegistry();
when(sources.getMetadataBuilder()).thenThrow(new RuntimeException());
assertThrows(RuntimeException.class, () -> HibernateUtils.getSessionFactory(sources));
assertTrue(((StandardServiceRegistryImpl) serviceRegistry).isActive());
when(s... |
148886237_185 | class ListMailResources implements AdminCommand {
public void execute(AdminCommandContext context) {
final ActionReport report = context.getActionReport();
try {
List<String> list = new ArrayList<String>();
Collection<MailResource> mailResources =
domai... | createMailResource();
parameters = new ParameterMap();
org.glassfish.resources.mail.admin.cli.ListMailResources listCommand = habitat.getService(org.glassfish.resources.mail.admin.cli.ListMailResources.class);
cr.getCommandInvocation("list-mail-resources", context.getActionReport(), adm... |
148915786_0 | class Slugifier {
public static String run(String text) {
if (text == null || text.length() == 0) {
return "";
}
String toReturn = "";
try {
String normalizedText = normalize(text);
normalizedText = normalizedText.replaceAll("[^\\w\\s\\-]", "");
... | String slugifiedText = Slugifier.run("Lenovo Y520 i7-7700HQ 16GB 1TB+256SSD GTX1050 Win10 80WK004JTX");
assertEquals("", slugifiedText);
}
} |
148918310_11 | class JsdUtil {
static String flipName(String name) {
int i = name.lastIndexOf('$');
if (i != -1)
name = name.replace('$', '-');
else if ((i = name.lastIndexOf('-')) != -1)
name = name.replace('-', '$');
else
i = name.lastIndexOf('.');
return i == -1 ? Strings.flipFirstCap(name... | assertEquals("Cat", JsdUtil.flipName("cat"));
assertEquals("Cat", JsdUtil.flipName("cat"));
assertEquals("Cat", JsdUtil.flipName("cat"));
assertEquals("CAT", JsdUtil.flipName("CAT"));
assertEquals("CAT", JsdUtil.flipName("CAT"));
assertEquals("CAT", JsdUtil.flipName("CAT"));
assertEquals("... |
149088809_1 | class Exchange implements Comparable<Exchange> {
private Exchange(String name, boolean future, ZoneId zoneId, LocalTime[] marketTimes) {
this.name = name;
this.future = future;
this.zoneId = zoneId;
this.zoneOffset = LocalDateTime.now().atZone(zoneId).getOffset();
this.marke... | Exchangeable rm907 = Exchangeable.fromString("RM907");
assertTrue(rm907.exchange()==Exchange.CZCE);
}
} |
149123005_31 | class Network {
public void registerTask(final Runnable task, int startAt, TN fromNode) {
Task<TN> sw = new Task<>(task);
msgs.addMsg(new Envelope.SingleDestEnvelope<>(sw, fromNode, fromNode, time, startAt));
}
public static BitSet chooseBadNodes(Random rd, int nodeCount, int nodesDown);
public BitSet... | AtomicBoolean ab = new AtomicBoolean();
network.registerTask(() -> ab.set(true), 100, n0);
network.runMs(99);
Assert.assertFalse(ab.get());
network.runMs(1);
Assert.assertTrue(ab.get());
Assert.assertEquals(0, network.msgs.size());
}
} |
149263873_29 | class RequerySetupUtils {
@Nonnull
public static EntityDataStore<Object> getDataStore() {
SchemaModifier schemaModifier = new SchemaModifier(configuration);
schemaModifier.createTables(TableCreationMode.CREATE_NOT_EXISTS);
return new EntityDataStore<>(configuration);
}
@Nonnu... | EntityDataStore<Object> ds = RequerySetupUtils.getDataStore();
TagType tagType = randomTagType();
TagValue tagValue = randomTagValue(tagType);
ds.insert(tagType);
TagType retrieved = ds.findByKey(TagType.class, tagType.getTagTypeId());
assertEquals(tagType.getTagTypeId(... |
149270308_1 | class FlexboxLayout {
void alignContent(double crossSize) {
minCrossSize = 0;
if (flexLines.size()==0)return;
// if (flexLines.size() <= 1) {
// if (flexLines.size() == 1) {
// minCrossSize = flexLines.get(0).getMinCrossSize();
// }
// return; ... | FlexboxLayout flexboxLayout = new FlexboxLayout();
flexboxLayout.setFlexDirection(FlexDirection.ROW);
flexboxLayout.setFlexWrap(FlexWrap.WRAP);
flexboxLayout.setAlignContent(AlignContent.FLEX_START);
for (int i = 0; i < 3; i++) {
DefaultFlexItem flexItemImpl = new Def... |
149281309_19 | class QueryRequestNonPagedExecutor extends QueryRequestExecutor {
@Override
QueryResponse execute() {
QueryResponse response = new QueryResponse();
List<PartitionResponse> result = new ArrayList<>();
for (Endpoint endpoint : queryRequest.getEndpoints()) {
String host = endpo... | List<Endpoint> endpoints = new ArrayList<>();
SearchRequest searchRequest = mock(SearchRequest.class);
Endpoint endpoint1 = mock(Endpoint.class);
Endpoint endpoint2 = mock(Endpoint.class);
endpoints.add(endpoint1);
endpoints.add(endpoint2);
LdapConnectionResult ld... |
149347972_9 | class AppConfigBaseModel {
public Object getCurrentValue(String value)
{
Method[] methods = getClass().getDeclaredMethods();
Object result = null;
boolean foundMethod = false;
for (Method method : methods)
{
String getMethod = "get" + value.substring(0, 1).to... | DerivedModelWithMethods model = new DerivedModelWithMethods();
model.setSimpleEnumField(SimpleEnum.Name);
model.setComplexEnumField(ComplexEnum.Application);
model.setStringField("Another test");
model.setLongField(92345);
model.setIntField(-234);
model.setBoolFie... |
149351086_542 | class VulnerabilityRepository implements Constants {
public Map<String, Long> getNonProdInfoByEnv(String assetGroup, String severitylevel) {
Map<String, Long> nonProdInfo = new HashMap<>();
StringBuilder urlToQuery = new StringBuilder(esUrl).append("/").append(assetGroup);
urlToQuery.append("/").append(SEARCH)... |
mockStatic(PacHttpUtils.class);
when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenThrow(new Exception());
ReflectionTestUtils.setField(vulnerabilityRepository, "esUrl", "dummyEsURL");
assertTrue(vulnerabilityRepository.getNonProdInfoByEnv("ag", "3").size() == 0);
}
} |
149579497_1 | class JCTreeUtils {
public boolean hasBody(final JCTree element) {
Class bodyClass = JCTree.JCBlock.class;
Class staClass = JCTree.JCStatement.class;
Field[] declaredFields = element.getClass().getDeclaredFields();
return Arrays.stream(declaredFields)
.filter(field ... |
JCTree.JCBlock block = new JCTree.JCBlock(0, null) {
};
class Method extends JCTree.JCMethodDecl {
public Method(JCModifiers jcModifiers, Name name, JCExpression jcExpression, List<JCTypeParameter> list, JCVariableDecl jcVariableDecl, List<JCVariableDecl> list1, List<JCExpression> list2, JCBlock jcB... |
149598464_0 | class StrUtil {
public static String stringify(long byteNumber) {
if (byteNumber / TB_IN_BYTES > 0) {
return df.format((double) byteNumber / (double) TB_IN_BYTES) + "TB";
} else if (byteNumber / GB_IN_BYTES > 0) {
return df.format((double) byteNumber / (double) GB_IN_BYTES) ... | assertEquals("1B", stringify(1));
assertEquals("1.00KB", stringify(1024));
assertEquals("1.00MB", stringify(1048576));
assertEquals("1.00GB", stringify(1073741824));
assertEquals("1.00TB", stringify(1099511627776L));
}
} |
149607740_66 | class EmptyHeaders implements Headers<K, V, T> {
@Override
public V get(K name) {
return null;
}
@Override public V get(K name, V defaultValue);
@Override public V getAndRemove(K name);
@Override public V getAndRemove(K name, V defaultValue);
@Override public List<V> getAll(K name)... | assertNull(HEADERS.get("name1"));
}
} |
149641877_6 | class Publisher extends AbstractMojo {
public void execute() throws MojoExecutionException {
getLog().info("Starting Axway Publisher");
AxwayPublishingAdapter adapter = getAxwayPublishingAdapter();
PublicationReader publicationReader = getPublicationReader();
try {
final... |
final Publication publication = createPublication().setApis(
Arrays.asList(new Api().setApiSpecification("api1").setApiConfig("config1"),
new Api().setApiSpecification("spec2").setApiConfig("config2"),
new Api().setApiSpecification("spec3").setApi... |
149663208_4 | class CloudEventSerializer implements Serializer<CloudEvent> {
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
if (isKey) {
throw new IllegalArgumentException("Cannot use CloudEventSerializer as key serializer");
}
Object encodingConfig = configs.get... | CloudEventSerializer serializer = new CloudEventSerializer();
EventFormatProvider.getInstance().registerFormat(CSVFormat.INSTANCE);
HashMap<String, Object> config = new HashMap<>();
config.put(CloudEventSerializer.ENCODING_CONFIG, "STRUCTURED");
config.put(CloudEventSerializer.... |
149708915_0 | class PostService implements Service {
private void getAllPosts(ServerRequest serverRequest, ServerResponse serverResponse) {
serverResponse.send(EntityUtils.toJsonArray(this.posts.all()));
}
public PostService(PostRepository posts);
@Override public void update(Routing.Rules rules);
pri... | String path = "/posts";
WebTarget targetGetAll = client.target(URI.create("http://localhost:" + webServer.port() + path));
try (Response resGetAll = targetGetAll.request().accept(MediaType.APPLICATION_JSON_TYPE).get()) {
assertEquals(200, resGetAll.getStatus());
List<Pos... |
149732116_0 | class ShopService {
public List<Integer> getDelayMinutes() {
return IntStream.range(0, MAX_INTERVAL_PERIODS)
.map(period -> (period + 1) * DELAY_INTERVAL_MINUTES)
.filter(this::isShopOpenInMinutes)
.boxed()
.collect(Collectors.toList());
}
public Sh... | //when
List<Integer> delayMinutes = shopService.getDelayMinutes();
//then
assertTrue(delayMinutes.size() > 0);
}
} |
149851179_1 | class JSONDataLoader {
public ArrayList<Format> getFormats() throws IOException, JSONException {
ArrayList<Format> formats = new ArrayList<>();
JSONObject jsonFormats = mLocalFileHelper.getJSONFormatsFile();
JSONArray formatData = jsonFormats.getJSONArray("data");
for (int i = 0; i ... | JSONDataLoader loader = new JSONDataLoader(helperMock);
ArrayList<Format> formats = loader.getFormats();
assertNotNull(formats);
assertEquals(5, formats.size());
Format format = formats.get(0);
assertEquals(1, format.getId());
assertEquals("Standard", format.get... |
149970281_4 | class Anime {
public String getAnimeName() {
return animeName;
}
public Anime(String animeDocument);
private void setAnimeCover();
private void setAnimeName();
private void setAnimeDescription();
private void setAnimeEpisodeList();
public String getAnimeCover();
public Li... | assertThat(anime.getAnimeName().equals("One Piece"),is(true));
}
} |
150186815_7 | class EventSourcedTopology {
public static <K, C, E, A> InputStreams<K, C> addTopology(TopologyContext<K, C, E, A> ctx, final StreamsBuilder builder) {
// Consume from topics
final KStream<K, CommandRequest<K, C>> commandRequestStream = EventSourcedConsumer.commandRequestStream(ctx, builder);
... |
TopologyContext<String, TestCommand, TestEvent, Optional<TestAggregate>> ctx = ctxBuilder.buildContext();
driver = new TestDriverInitializer().build(builder -> EventSourcedTopology.addTopology(ctx, builder));
TestContextDriver<String, TestCommand, TestEvent, Optional<TestAggregate>> ctxDriver =... |
150308585_73 | class HostLogFilesRequestQueryConverter extends AbstractOperationHolderConverter<HostLogFilesRequest, SimpleFacetQuery> {
@Override
public SimpleFacetQuery convert(HostLogFilesRequest request) {
SimpleFacetQuery facetQuery = new SimpleFacetQuery();
facetQuery.addCriteria(new SimpleStringCriteria(String.for... | // GIVEN
HostLogFilesRequest request = new HostLogFilesQueryRequest();
request.setHostName("hostName");
request.setComponentName("componentName");
// WHEN
SolrQuery query = new DefaultQueryParser().doConstructSolrQuery(underTest.convert(request));
// THEN
assertEquals("?q=host%3A%28hostN... |
150309255_5 | class TimelineWebServices {
@GET
@Produces({ MediaType.APPLICATION_JSON /* , MediaType.APPLICATION_XML */})
public AboutInfo about(
@Context HttpServletRequest req,
@Context HttpServletResponse res) {
init(res);
return new AboutInfo("AMS API");
}
@Inject public TimelineWebServices(Timel... | WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("timeline")
.accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
TimelineWebServices.AboutInfo about =
response.getEntity(Tim... |
150407753_2 | class Item {
public boolean collision(PaintView paintView) {
return collision(paintView.getCircleX(),
paintView.getCircleY(),
paintView.getCircleRadius());
}
Item(int posX, int posY, int radius);
public int getX();
public int getY();
public int getRad... | SpeedupItem speedupItem = new SpeedupItem(0, 0, 10);
assertThat(speedupItem.collision(21, 0, 10), is(false));
assertThat(speedupItem.collision(20, 0, 11), is(true));
}
} |
150411824_1 | class PathParser {
public static String[] parse(String path, ConfigOptions options) {
return parse(path, options.getPathSeparator(), options.getKeyValidator());
}
public static String[] parse(String path, char pathSeparator, Pattern keyValidator);
}
class PathParserTest {
@Test
public v... | String[] keys = PathParser.parse("root.parent.child", new ConfigOptions());
assertEquals(keys[0], "root");
assertEquals(keys[1], "parent");
assertEquals(keys[2], "child");
}
} |
150434337_86 | class FMHMMListImp implements FMHMMList {
public Map<Long, FMHMMNode> loopLoadForest(String cInputString) {
Here:
for (int i = StableData.INT_ZERO; i < cInputString.length(); i++) {
if (linkedHashMap.containsKey(Long.valueOf(cInputString.charAt(i)))) {
FMHMMNode fHHMMNode = linkedHashMap.get(Long.valueO... | fail("Not yet implemented");
}
} |
150470825_0 | class SaveService {
public void saveContainer(Container c) throws Exception {
connection.saveContainer(c);
}
public SaveService(DatabaseConnection connection);
}
class SaveServiceTest {
@Test
public void testSaving() {
| Container c = new Container("c1");
SaveService s = new SaveService(new DatabaseConnectionMock());
String exceptionString = "";
Exception ex = null;
try {
s.saveContainer(c);
} catch (Exception e) {
ex = e;
exceptionString = e.getMessag... |
150573009_0 | class JsonAdapter {
public static List<DataRecord> flattenJson(DataRecord dataRecord, String json, TargetModel targetModel)
throws InvalidJSONException, ColumnFamilyNotFoundException, InvalidColumnException {
List<DataRecord> dataRecordList = new ArrayList<>();
dataRecordList.add(dataRecord);
boolean usePa... |
// test to select some of the json elements by specifying their parent
// paths
// expected result is dataRecords for only the selected json elements
// having column name with parent path i.e parentPath_colName
TargetModel target = new HdfsTargetModel("test1", hdfsExplorer);
List<DataRecord> result = Js... |
150632370_4 | class Kassapaate {
public void ostaLounas(Matkakortti kortti) {
kortti.osta(HINTA);
myytyjaLounaita++;
}
public Kassapaate();
public void lataa(Matkakortti kortti, int summa);
public int getMyytyjaLounaita();
Kassapaate kassa;
Matkakortti kortti;
}
class KassapaateTe... | when(kortti.getSaldo()).thenReturn(4);
kassa.ostaLounas(kortti);
verify(kortti, times(1)).getSaldo();
verify(kortti, times(0)).osta(anyInt());
}
} |
150673713_13 | class Retryer {
public T call(Callable<T> callable) {
long startTime = System.currentTimeMillis();
long attemptNumbers = 0;
while (true) {
attemptNumbers++;
final Attempt<T> attempt = attempt(callable, attemptNumbers, startTime);
// on retry
retryListeners.forEach(listener -> list... | AtomicInteger ato = new AtomicInteger(0);
RetryBuilder.<Integer>newBuilder().retryIfResult(rs -> rs < 3).build()
.call(ato::incrementAndGet);
Assert.assertEquals(3, ato.get());
}
} |
150677892_59 | class OpenSessionOptionBuilder {
public OpenSessionOptionBuilder setCameraByIndex(final Integer cameraByIndex) {
this.cameraByIndex = cameraByIndex;
this.cameraBySerialNumber = null;
return this;
}
public OpenSessionOptionBuilder setOpenSessionOnly(final boolean openSessionOnly);
... | final OpenSessionOption option = builder
.setCameraBySerialNumber("adawda")
.setCameraByIndex(5)
.build();
Assertions.assertFalse(option.getCameraBySerialNumber().isPresent());
Assertions.assertTrue(option.getCameraByIndex().isPresent());
}
} |
151122650_154 | class AbstractRetry implements Function<Flux<S>, Publisher<Long>> {
BackoffDelay calculateBackoff(IterationContext<T> retryContext, Instant timeoutInstant) {
if (retryContext.iteration() > maxIterations)
return RETRY_EXHAUSTED;
BackoffDelay nextBackoff = backoff.apply(retryContext);
Duration minBackoff = ne... | Instant timeoutInstant = Instant.now().plusSeconds(3);
AbstractRetry<String, Integer> abstractRetry = new AbstractRetry<String, Integer>(2, Duration.ofSeconds(1),
Backoff.fixed(Duration.ofMillis(600)), Jitter.NO_JITTER, null, null) {
@Override
public Publisher<Long> apply(Flux<Integer> intege... |
151233646_40 | class FluxCsvParser {
public void parseFluxResponse(@Nonnull final BufferedSource bufferedSource,
@Nonnull final Cancellable cancellable,
@Nonnull final FluxResponseConsumer consumer) throws IOException {
Arguments.checkNotNull(bufferedSo... |
String data = "#datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,long,string,string,string,double\n"
+ "#group,false,false,false,false,false,false,false,false,false,true\n"
+ "#default,_result,,,,,,,,,\n"
+ ",result,table,_start,_stop,_time... |
151435201_11 | class ClassBuilder {
public String build() throws Exception {
LOG.debug("Class building started for the class %s", fluent.getKlass().getSimpleName());
var list = fluent.getNodes();
if (list.size() == 0) {
throw new GeciException("There are no actual calls in the fluent structure... | var fluent = FluentBuilder.from(TestClass.class)
.one("a")
.optional("b")
.oneOrMore("c")
.zeroOrMore("d")
.oneOf("a", "b");
var result = new ClassBuilder((FluentBuilderImpl) fluent).build();
assertEqualToFile(result... |
151476055_6 | class MembershipService {
public List<String> getAllMemberships() {
Membership memberships = restService.makeCall(membershipServerUrl, membershipServerUri, Membership.class);
memberships.getMemberships().replaceAll(String::toUpperCase);
return memberships.getMemberships();
}
@Inje... |
ArrayList<String> opsMemberships;
opsMemberships = new ArrayList<>();
opsMemberships.add("Application1");
opsMemberships.add("Application2");
opsMemberships.add("Application3");
HashMap<String, List<String>> node;
node = new HashMap<>();
node.put("test",... |
151746922_0 | class FilePermissionSample {
static Acl mapPosixFilePermissionToCloudSearchAcl(Path pathToFile) throws IOException {
// Id of the identity source for external user/group IDs. Shown here,
// but may be omitted in the SDK as it is automatically applied
// based on the `api.identitySourceId` configuration p... | Path path = createTestFileWithPosixPermissions(
user("100"),
group("200"),
PosixFilePermission.OWNER_READ);
Acl acl = FilePermissionSample.mapPosixFilePermissionToCloudSearchAcl(path);
assertThat(acl.getReaders()).hasSize(1);
List<String> userPrincipalNames = acl.getReaders().st... |
152002724_0 | class SuselMetadataLoader {
public <S> Metadata load(Class<S> serviceProvider)
throws IOException, SuselMetadataNullException {
var module = serviceProvider.getModule();
var metadata = perModuleMetadataCache.get(module);
if (metadata != null) {
return metadata;
... | SuselMetadataLoader loader = new SuselMetadataLoader();
var holder = loader.load(this.getClass());
assertNotNull(holder.properties().getProperty("com.example.MyServiceImpl_Refs"),
"Susel properties should be loaded and 'com.example.MyServiceImpl_Refs' key should have a value");... |
152163398_0 | class MyApi {
public synchronized String getNow() {
return sdf.format(new Date());
}
public static void main(String[] args);
private MyApi api;
}
class MyApiTest {
private MyApi api;
@Test
public void getNow() {
| String now = api.getNow();
//相等测试断言,getNow返回值的长度是19
assertEquals(now.length(), 19);
}
} |
152242718_9 | class GetLocalIP {
protected static List<String> getIPFromInputStream(BufferedReader reader) {
if (reader != null) {
Set<String> allLines = new LinkedHashSet<>();
String line = null;
try {
while ((line = reader.readLine()) != null) {
... | BufferedReader br = mock(BufferedReader.class);
//We want to return a bogus string first and then null so there is not an infinite loop
when(br.readLine()).thenReturn("10.18.85.186","10.18.85.186",(String)null);
List<String> returnVal = GetLocalIP.getIPFromInputStream(br);
assert... |
152358305_7 | class UserMapper {
public User userFromId(String id) {
if (id == null) {
return null;
}
User user = new User();
user.setId(id);
return user;
}
public List<UserDTO> usersToUserDTOs(List<User> users);
public UserDTO userToUserDTO(User user);
public... | assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID);
assertThat(userMapper.userFromId(null)).isNull();
}
} |
152415097_16 | class ConnectionProperties {
public static ConnectionProperties from(Properties properties) throws ConfigurationException
{
Class<? extends NativeConnectionProvider> nativeConnectionProviderClass = getClassOfType(properties, CONFIG_CONNECTION_NATIVE_CLASS, DEFAULT_CONNECTION_NATIVE_CLASS, NativeConnect... | Properties properties = new Properties();
properties.put("connection.native.decorator.class", NonOverridingProviderClass.class.getName());
assertThatExceptionOfType(ConfigurationException.class).isThrownBy(() -> ConnectionProperties.from(properties));
}
} |
152559710_128 | class PrintClientOrgan implements Runnable {
@Override
public void run() {
// printuserorgan -u=1 -t=requests
Optional<Client> client = manager.getClientByID(uid);
if (!client.isPresent()) {
outputStream.println("No client exists with that user ID");
return;
... | String[] inputs = {"-u", "1", "--notanoption"};
CommandLine.run(spyPrintClientOrgan, System.out, inputs);
verify(spyPrintClientOrgan, times(0)).run();
}
} |
152655369_33 | class UrlUtils {
public static boolean isHttpOrHttps(String url) {
if (TextUtils.isEmpty(url)) {
return false;
}
return url.startsWith("http:") || url.startsWith("https:");
}
public static String normalize(@NonNull String input);
public static boolean isUrl(String ... | assertFalse(UrlUtils.isHttpOrHttps(null));
assertFalse(UrlUtils.isHttpOrHttps(""));
assertFalse(UrlUtils.isHttpOrHttps(" "));
assertFalse(UrlUtils.isHttpOrHttps("mozilla.org"));
assertFalse(UrlUtils.isHttpOrHttps("httpstrf://example.org"));
assertTrue(UrlUtils.isHttp... |
152871165_23 | class BundleImpl implements Bundle {
ClassLoader getLoader() {
return loader;
}
BundleImpl(final Manifest manifest, final File file, final BundleContextImpl context,
final Ripener.Configuration configuration, final long id,
final Collection<String> includedResources... | assertNotNull(bundle.getLoader());
}
} |
153022185_1 | class FakegenUtils {
public static void inject(@NonNull Object target, @NonNull String fieldName, Object value) {
Field field;
try {
field = target.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(target, value);
} catch (NoSu... | SimpleType simpleType = new SimpleType();
Throwable fakegenException = catchThrowable(() -> FakegenUtils.inject(simpleType, "namo", "Hello World"));
assertThat(fakegenException)
.isInstanceOf(FakegenException.class)
.hasMessage("Could not find field `namo`, but ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.