id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
8920316_6 | class AdhocProject implements Project,
FileOwnerQueryImplementation, ProjectConfiguration,
ProjectActionPerformer, ActionProvider, LogicalViewProvider {
public List<Favorite> favorites() {
List<Favorite> favorites = new ArrayList<>();
try {
Preferences forProject = prefe... | java.util.List<Favorite> favs = new ArrayList<>();
char[] chars = new char[]{'d', 'c', 'b', 'a'};
int ix = 1;
for (char c : chars) {
favs.add(new Favorite(ix *= 10, "foo/" + c));
}
project.saveFavorites(favs);
java.util.List<Favorite> nue = project.fav... |
8975145_19 | class TwoSecondIntersectionFinder implements FragmentIntersectionFinder {
public long[] sampleNumbers(Track track, Movie movie) {
List<TimeToSampleBox.Entry> entries = track.getDecodingTimeEntries();
double trackLength = 0;
for (Track thisTrack : movie.getTracks()) {
double thi... | Movie m = MovieCreator.build(Channels.newChannel(TwoSecondIntersectionFinderTest.class.getResourceAsStream("/Beethoven - Bagatelle op.119 no.11 i.m4a")));
TwoSecondIntersectionFinder intersectionFinder = new TwoSecondIntersectionFinder();
long[] s = intersectionFinder.sampleNumbers(m.getTracks()... |
9004636_25 | class FellowPlayer extends ReferencePoint {
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
FellowPlayer other = (FellowPlayer) obj;
if (mId != other.mId)
return false;
if (mNickname == null)
{
if (other.mNickname != null)
... | fellowPlayerCompare = new FellowPlayer(5, null, true, 130.7, 70.3, 0);
assert(!fellowPlayerCompare.equals(fellowPlayerOriginal));
}
} |
9020655_0 | class GuavaUtils {
public static <T> boolean isPresent(T t){
Optional<T>optionalObj = Optional.fromNullable(t);
return optionalObj.isPresent();
}
}
class GuavaUtilsTest {
@Test
public void isPresentTest(){
| B1 b = null;
assertEquals(false, GuavaUtils.isPresent(b));
b = new B1();
assertEquals(true, GuavaUtils.isPresent(b));
}
} |
9040104_3 | class LicenseResolver {
public static License read(final String license) {
final String trimmedLicense = license.trim();
if (sLicenses.containsKey(trimmedLicense)) {
return sLicenses.get(trimmedLicense);
} else {
throw new IllegalStateException(String.format("no such... | final License license = LicenseResolver.read("MIT License");
assertNotNull(license);
assertEquals("MIT License", license.getName());
}
} |
9054533_480 | class StateManager implements RouteAndActivityStateGetter, IterationStartsListener, RuinListener, InsertionStartsListener, JobInsertedListener, InsertionEndsListener {
public StateId createStateId(String name) {
if (createdStateIds.containsKey(name)) return createdStateIds.get(name);
if (stateIndex... | StateManager stateManager = new StateManager(vrpMock);
StateId stateId = stateManager.createStateId("foo-state");
Assert.assertEquals(21, stateId.getIndex());
}
} |
9078409_10 | class CloseableIterators {
public static <T> CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize) {
return wrap(Iterators.limit(iterator, limitSize), iterator);
}
private CloseableIterators();
public static CloseableIterator<T> fromStream(Stream<T> stream);
... | CloseableIterator<Integer> firstThree = limit(testIterator(), 3);
assertTrue(elementsEqual(asList(1, 2, 3).iterator(), firstThree));
assertFalse(firstThree.hasNext());
firstThree.close();
}
} |
9078421_24 | class FeatureRegistry {
public AccumuloFeatureConfig transformForClass(Class<? extends Feature> clazz) {
AccumuloFeatureConfig featureConfig = classToTransform.get(clazz);
if(featureConfig == null) {
for(Map.Entry<Class, AccumuloFeatureConfig> clazzes : classToTransform.entrySet()) {
... |
FeatureRegistry registry = new FeatureRegistry(new MetricFeatureConfig());
assertNotNull(registry.transformForClass(MyTestFeature.class));
}
} |
9090323_0 | class ZNodePath extends ZNodeLabelVector {
public static String canonicalize(final String path) {
final int length = path.length();
int lastSlash = -1;
StringBuilder builder = null;
for (int i=0; i<length; ++i) {
char c = path.charAt(i);
if ((c == SLASH) || (... | assertEquals("/", ZNodePath.canonicalize("/"));
assertEquals("/", ZNodePath.canonicalize("//"));
assertEquals("/", ZNodePath.canonicalize("///"));
assertEquals("/a", ZNodePath.canonicalize("/a"));
assertEquals("/a", ZNodePath.canonicalize("/a/"));
assertEquals("/", ZNodeP... |
9120355_0 | class NameUtilities {
public static String getFullName(Class c) {
if (c == null) {
throw new IllegalArgumentException("class cannot be null");
}
StringBuilder name = new StringBuilder();
name.append(c.getPackage().getName()).append(".");
Class klaus = c;
List<Class> enclosingClasses = new ArrayList<C... | String expected =
NameUtilitiesTest.class.getPackage().getName()+"."
+ NameUtilitiesTest.class.getSimpleName()+"."
+ "Inner"
;
String name = NameUtilities.getFullName(Inner.class);
Assert.assertEquals(expected, name);
}
} |
9121658_5 | class QueryUtils {
public static PrefixMapping usedPrefixes(Query query, PrefixMapping global) {
PrefixMapping local = query.getPrefixMapping();
PrefixMapping pm = global == null ? local : new PrefixMapping2(global, local);
PrefixMapping result = usedReferencePrefixes(query, pm);
re... | Query query = QueryFactory.create(String.join("\n",
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>",
"PREFIX foo: <http://example.org/foo/>",
"PREFIX bar: <http://example.org/bar/>",
"PREFIX baz: <http://example.org/baz/>",
"SELECT * {",
... |
9143933_12 | class HashBasedHipsterGraph implements HipsterMutableGraph<V,E> {
@Override
public boolean remove(V v){
// Remove all edges related to v
Set<GraphEdge<V, E>> edges = this.connected.get(v);
if (edges == null) return false;
for(Iterator<GraphEdge<V,E>> it = edges.iterator(); it.h... | graph.remove("v1");
assertFalse(Sets.newHashSet(graph.vertices()).contains("v1"));
}
} |
9158616_17 | class OrderMapper1_12 implements OrderMapper {
@Override
public EncounterTransaction.DrugOrder mapDrugOrder(DrugOrder openMRSDrugOrder) {
EncounterTransaction.DrugOrder drugOrder = new EncounterTransaction.DrugOrder();
drugOrder.setUuid(openMRSDrugOrder.getUuid());
if (openMRSDrugOrder.... |
DrugOrder openMrsDrugOrder = drugOrder(CareSetting.CareSettingType.OUTPATIENT, 3, "3-0-2", 5, "before meals", "boil in water", null, "ORD-100");
Concept concept = concept("newConcept", "newConceptDataType", "newConceptUuid");
openMrsDrugOrder.setConcept(concept);
EncounterTransaction.D... |
9165045_20 | class ShapePathReader implements ElementReader<ShapePath> {
@Override
public ShapePath read(Resource resource) {
checkNotNull(resource);
ShapePathImpl.ShapePathImplBuilder shapePathBuilder = ShapePathImpl.builder();
shapePathBuilder.element(resource);
shapePathBuilder.jenaPat... | assertThat(ShapePathReader.create().read(shaclPath).asSparqlPropertyPath())
.isEqualTo(propertyPathString);
}
} |
9178484_0 | class ModelRef {
static
public boolean validateId(String id){
return (id != null) && (id).matches(REGEX_ID);
}
public ModelRef(ModelRef modelRef);
public ModelRef(Principal owner, String id);
@Override public int hashCode();
@Override public boolean equals(Object object);
public Principal getOwner();
pr... | assertTrue(ModelRef.validateId("com.mycompany.Test"));
assertTrue(ModelRef.validateId("Test_v1"));
assertTrue(ModelRef.validateId("Test_v1.0"));
assertFalse(ModelRef.validateId("."));
assertFalse(ModelRef.validateId("-Test"));
}
} |
9196478_7 | class JDBCMessageStore implements MessageStore {
@Override
public Message findByMessageId(String messageId, String messageDirection) {
Map<String,Object> fields = new HashMap<>();
fields.put("message_id",messageId);
fields.put("message_box",messageDirection);
List<Message> messa... | String contentType = "application/soap+xml";
File body = fileFromClasspath("simple-as4-receipt.xml");
String messageId = "testSoapMessage1";
assertStoredMessage(messageId, contentType, body, MessageType.SIGNAL_MESSAGE_WITH_USER_MESSAGE);
messageStore.updateMessage(messageId, Ebms... |
9239163_1 | class HK2VerticleLoader extends AbstractVerticle {
@Override
public void stop(Future<Void> stopFuture) throws Exception {
classLoader = null;
parent = null;
Future<Void> future = Future.future();
future.setHandler(result -> {
// Destroy the service locator
... |
Verticle verticle = create(TestStopFailVerticle.class.getName());
verticle.stop(stopFuture);
verify(stopFuture, never()).complete();
verify(stopFuture).fail(any(Throwable.class));
}
} |
9239473_13 | class DefaultJerseyOptions implements JerseyOptions, JerseyServerOptions {
@Override
public Set<Class<?>> getComponents() {
Set<Class<?>> set = new HashSet<>();
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Consumer<JsonArray> reader = array -> {
if (arra... |
config.put(DefaultJerseyOptions.CONFIG_COMPONENTS, new JsonArray().add(MyObj.class.getName() + ".invalid"));
options.getComponents();
fail();
}
} |
9270640_1 | class UserAccount extends BaseAuditableEntity implements SocialUserDetails {
public boolean isAuthor(){
for (UserRoleType role : getRoles()) {
if (role == UserRoleType.ROLE_AUTHOR){
return true;
}
}
return false;
}
public UserAccount();
... | UserAccount normalUser = new UserAccount();
assertFalse(normalUser.isAuthor());
UserRoleType[] roles = new UserRoleType[]{UserRoleType.ROLE_USER, UserRoleType.ROLE_AUTHOR};
UserAccount author = new UserAccount("1234", roles);
assertTrue(author.isAuthor());
}
} |
9272141_1 | class ReentrantScope extends AbstractScope {
public boolean inScope() {
List<?> l = this.lists.get();
return l != null && !l.isEmpty();
}
public ReentrantScope();
public ReentrantScope(Provider<String> injectionInfoProvider);
Object[] includeStackTrace(Object... scopeContents);... | final int limit = 10;
StringBuilder constant = new StringBuilder("hello");
final boolean[] ran = new boolean[1];
//Recursively enter the scope multiple times, and ensure that the
//most recent values are the ones which are available
class One implements ThrowingFunction<I... |
9272724_6 | class Migration {
private void rollback(MongoDatabase db, Document agg) {
CountDownLatch latch = new CountDownLatch(backupQueryForCollection.size() - 1);
Document rollbacks = new Document();
agg.append("rollback", rollbacks);
for (String s : backupQueryForCollection.keySet()) {
... | Function<Class<? extends MigrationWorker>, MigrationWorker> convert = deps.get()::getInstance;
Migration[] m = new Migration[1];
new MigrationBuilder("stuff-new", 12, (mig) -> {
m[0] = (Migration) mig;
return null;
}).backup("stuff", new Document("index", new Doc... |
9291388_5 | class ProgressButton extends CompoundButton {
public void setPinned(boolean pinned) {
setChecked(pinned);
invalidate();
}
public ProgressButton(Context context);
public ProgressButton(Context context, AttributeSet attrs);
public ProgressButton(Context context, AttributeSet attrs, int defStyle);
... | button.setPinned(true);
CompoundButton.OnCheckedChangeListener publisher =
mock(CompoundButton.OnCheckedChangeListener.class);
button.setOnCheckedChangeListener(publisher);
button.toggle();
verify(publisher).onCheckedChanged(button, false);
}
} |
9294731_46 | class HydroMetadataHandler extends MetadataHandler {
protected Collection<SosTimeseries> getAvailableTimeseries(XmlObject result_xb,
SosTimeseries timeserie,
SOSMetadata metadata) throws XmlExc... | Collection<SosTimeseries> timeseries = seam.getAvailableTimeseries();
assertThat(timeseries.size(), is(140));
}
} |
9306260_2 | class PropertyTypeValidator implements ConfigHelperValidator {
@Override
public void validate(ConfigHelper configHelper) throws RuntimeException
{
for (String propertyName : configHelper.getPropertyNames())
{
Class<?> desiredType = configHelper.getPropertyType(propertyName);
... | Properties properties = new Properties();
properties.put("property", "false");
MappedConfiguration<String, Object> configuration = Mockito.mock(MappedConfiguration.class);
ConfigHelper configHelper = new ConfigHelper(properties);
configHelper.add("property", configuration);
... |
9318794_6 | class LogStore extends ChangeSupport {
@Process(actionType = FollowLogFile.class)
public void follow(final Dispatcher.Channel channel) {
if (activeLogFile == null) {
channel.nack(new IllegalStateException("Unable to follow: No active log file!"));
return;
}
navi... | LogFile logFile = new LogFile("server.log", Collections.<String>emptyList(), 0);
store.states.put(logFile.getName(), logFile);
store.activate(logFile);
store.follow(NoopChannel.INSTANCE);
assertFalse(store.pauseFollow);
LogFile activeLogFile = store.getActiveLogFile();
... |
9327416_435 | class JsonLinkConsumer {
public List<String> readLinks(final JsonReader reader, final EdmEntitySet entitySet) throws EntityProviderException {
List<String> links = null;
int openedObjects = 0;
try {
String nextName;
if (reader.peek() == JsonToken.BEGIN_ARRAY) {
nextName = FormatJson.... | final String links = "{\"d\":{\"results\":[{\"uri\":\"http://somelink\"}]}}";
JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(links)));
assertEquals(Arrays.asList("http://somelink"), new JsonLinkConsumer().readLinks(reader, null));
}
} |
9327555_9 | class FaviconDownloader {
public String downloadFaviconFromPage(String pageUrl, String directory, String fileName) {
// Try to extract the favicon URL from the page specified in the feed
String faviconUrl = null;
try {
final FaviconExtractor extractor = new FaviconExtractor(page... | // Download from page
FaviconDownloader downloader = new FaviconDownloader();
String tempDir = System.getProperty("java.io.tmpdir");
String filename = downloader.downloadFaviconFromPage("http://abstrusegoose.com", tempDir, "favicon");
assertNotNull(filename);
assertTrue(n... |
9340593_0 | class SPARQLValidator {
public Model validate(OntModel toBeValidated, String query) {
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel());
NIFNamespaces.addRLOGPrefix(model);
model.setNsPrefix("mylog", logPrefix);
QueryExecut... | OntModel output = null;
OntModel correct = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel());
correct.read(SPARQLValidator.class.getClassLoader().getResourceAsStream("nif-correct-model.ttl"), "", "Turtle");
output = SPARQLValidator.getInstance()... |
9349244_1 | class RateThisApp {
public static void stopRateDialog(final Context context){
setOptOut(context, true);
}
public static void init(Config config);
public static void setCallback(Callback callback);
public static void onCreate(Context context);
@Deprecated public static void onStart(Cont... | Context context = RuntimeEnvironment.application.getApplicationContext();
RateThisApp.stopRateDialog(context);
// check shared pref
SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences(
PREF_NAME, Context.MODE_PRIVATE);
Assert... |
9349347_3 | class CommonUtils {
public static String padRight(String inputString, int size, char paddingChar) {
final String stringToPad;
if (inputString == null) {
stringToPad = "";
}
else {
stringToPad = inputString;
}
StringBuilder padded = new StringBuilder(stringToPad);
while (padded.length() < size) ... | assertEquals(" ", CommonUtils.padRight(null, 5));
}
} |
9349893_0 | class LibreOfficeLauncherHelper {
public static String getOperatingSystem(String operatingSystemIndentifier) {
// JOptionPane.showMessageDialog(null, operatingSystemIndentifier, "Info",
// JOptionPane.ERROR_MESSAGE);
if ("linux".equalsIgnoreCase(operatingSystemIndentifier)) {
return OS_LINUX;
}... | assertEquals(LibreOfficeLauncherHelper.OS_LINUX, LibreOfficeLauncherHelper.getOperatingSystem("linux"));
assertEquals(LibreOfficeLauncherHelper.OS_LINUX, LibreOfficeLauncherHelper.getOperatingSystem("Linux"));
assertEquals(LibreOfficeLauncherHelper.OS_WINDOWS, LibreOfficeLauncherHelper.getOperatingSystem("... |
9365128_63 | class ScalableQuantity extends Quantity<N> {
@Override
public String toString() {
double valuePan = getNumber().doubleValue();
final double scaleFactor = getScaleFactor().doubleValue();
int i = getBasePower();
if (valuePan > 1.0) { // need to scale the value down
while (valuePan ... | Assert.assertEquals(new MetricScalableQuantity(100.0, 2, "b").toString(), "100.00 Mb");
Assert.assertEquals(new MetricScalableQuantity(100.0, -2, "b").toString(), "100.00 μb");
}
} |
9369619_41 | class ObjectMapperProvider {
public ObjectMapper mapper() {
return mapper;
}
public ObjectMapperProvider();
public static ObjectMapperProvider defaults();
static KasperReason translateOldErrorToKasperReason(final ObjectNode root);
public ObjectWriter objectWriter();
public Object... | // Given
final String jsonIso8601 = "\"2013-08-06T07:35:00.123Z\"";
// When
final DateTime actual = ObjectMapperProvider.INSTANCE.mapper().readValue(
jsonIso8601,
DateTime.class
);
// Then
final DateTime expectedDateTime = new Dat... |
9373411_52 | class CastingAst2CodeConverter extends AbstractAst2CodeConverter {
protected IdentifierData cast(Type goalType, IdentifierData oldId) throws IntermediateCodeGeneratorException {
if (oldId.getIdentifier().startsWith("#")) {
IdentifierData tmpId = icg.generateTempIdentifier(oldId.getType());
icg.addQuadruple(Qu... | try {
when(converter.icg.generateTempIdentifier(any(StringType.class)))
.thenReturn(new IdentifierData("tmp", new StringType(0l)));
converter.cast(new StringType(0l), new IdentifierData("test",
new ArrayType(new LongType(), 0)));
fail();
} catch (IntermediateCodeGeneratorException e) {
... |
9386489_21 | class LogFilterApplier {
public String apply(String text, String logLevel) {
if (System.getProperties().containsKey(OFF_SWITCH)) {
return text;
}
boolean displayDebugInfo = showDebugInfo();
if (config == null) config = configLoader.loadConfiguration(displayDebugInfo);
... | config.setTimestampPattern("yyyy/MM/dd");
assertEquals("", applier.apply("", MockLogLevel.INFO.name()));
}
} |
9408774_14 | class LogInjector {
public Log defaultLogger() {
return (level, debug) ->
(level == LogLevel.ERROR ? SYS_ERR : SYS_OUT)
.print(level, debug);
}
static LogInjector inst();
private static LogInjector createInstance();
}
class LogInjectorTest {
@Test
public void testDefaultLog... | // Make sure basic logging works OOTB
final String msg = "Success! " + hashCode();
borrowSout(
()-> LogInjector.DEFAULT.log(LogLevel.INFO, msg)
, lines->
Assert.assertEquals("[INFO] " + msg, lines.first())
);
assertTrue("Failed", !failed);
... |
9434210_1 | class UriBuilderImpl extends UriBuilder {
@Override
public UriBuilder replaceQueryParam(String name, Object... values) {
checkSsp();
if (queryParams == null) {
queryParams = UriComponent.decodeQuery(query.toString(), false);
query.setLength(0);
}
name =... | URI uri = new UriBuilderImpl().path("http://localhost/").replaceQueryParam("foo", "test").build();
assertEquals("http://localhost/?foo=test", uri.toString());
}
} |
9454656_0 | class TemplateDebugger {
public String render() {
STGroupFile templateGroup = new STGroupFile(templateGroupFile);
ST template = templateGroup.getInstanceOf(templateName);
if (template == null) {
throw new IllegalStateException(
String.format(
"The template named [%s] does not exist in the templat... |
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
InputStream yaml = getClass().getResourceAsStream(
"/yaml/templateDebugger.yml");
TemplateDebugger debugger = mapper.readValue(yaml,
TemplateDebugger.class);
assertNotNull(debugger);
String rendered = debugger.render();
assertNotNull(render... |
9478484_0 | class IssueRegistry extends com.android.tools.lint.client.api.IssueRegistry {
@Override public List<Issue> getIssues() {
return Arrays.asList(InjectedFieldInJobNotTransientDetector.ISSUE);
}
}
class IssueRegistryTest {
@Test public void issues() throws Exception {
| assertThat(new IssueRegistry().getIssues()).contains(
InjectedFieldInJobNotTransientDetector.ISSUE);
}
} |
9502782_0 | class ScheduledTasks {
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}
@SpyBean ScheduledTasks tasks;
}
class ScheduledTasksTest {
@SpyBean ScheduledTasks tasks;
@Test
public void reportCurrentTime() {
| await().atMost(Duration.TEN_SECONDS).untilAsserted(() -> {
verify(tasks, atLeast(2)).reportCurrentTime();
});
}
} |
9519880_0 | class WebExceptionHandlerOperationsImpl implements
WebExceptionHandlerOperations {
public String getHandledExceptionList() {
String webXmlPath = pathResolver.getIdentifier(
LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
WEB_MVC_CONFIG);
Validate.isTrue(f... |
String result;
String expected;
/*
* Test 1 - Encuentra excepciones instanciadas en el archivo de
* configuración EXC_WEB_XML
*/
expect(
pathResolver.getIdentifier(
LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
... |
9530230_2 | class Recommendations extends SimpleBenchmark {
public Map<Integer, List<Integer>> calculateRecommendations(int reps) {
Map<Integer, List<Integer>> results = null;
for (int i = 0; i < reps; i++) {
results = lambdaRecommendations.calculateRecommendations();
}
return resul... | GSLambdaRecommendations recommendations = new GSLambdaRecommendations(makePurchases());
MutableMap<Integer, MutableList<Integer>> results = recommendations.calculateRecommendations();
Assert.assertEquals(4, results.get(5).get(0).intValue());
Assert.assertEquals(5, results.g... |
9545480_17 | class InstrumentedInvokerFactory {
public Invoker create(Object service, Invoker rootInvoker) {
List<Method> timedmethods = new ArrayList<>();
List<Method> meteredmethods = new ArrayList<>();
List<Method> exceptionmeteredmethods = new ArrayList<>();
for (Method m : service.getClas... |
Timer timer = testMetricRegistry.timer("timed");
Meter meter = testMetricRegistry.meter("metered");
when(mockMetricRegistry.timer(anyString())).thenReturn(timer);
when(mockMetricRegistry.meter(anyString())).thenReturn(meter);
long oldtimervalue = timer.getCount();
long ... |
9546194_0 | class Greeter {
public String sayHello() {
return "Hello world!";
}
private Greeter greeter;
}
class GreeterTest {
private Greeter greeter;
@Test
public void greeterSaysHello() {
| assertThat(greeter.sayHello(), containsString("Hello"));
}
} |
9553726_84 | class DiscountFactor {
public static BigDecimal calculate(RateAndPeriods rateAndPeriods) {
Objects.requireNonNull(rateAndPeriods);
// (1-(1+r)^n)/1-(1+rate)
final BigDecimal ONE = CalculationContext.one();
BigDecimal div = ONE.min(ONE.add(rateAndPeriods.getRate().get()));
Bi... | assertEquals(1, DiscountFactor.calculate(RateAndPeriods.of(0.00,0)).intValueExact());
assertEquals(1, DiscountFactor.calculate(RateAndPeriods.of(0.00,1)).intValueExact());
assertEquals(1, DiscountFactor.calculate(RateAndPeriods.of(0.00,10)).intValueExact());
}
} |
9577793_0 | class RequestParams {
public static Builder builder (String resource) {
return new Builder(resource);
}
public RequestParams(
String resource,
String primaryKey,
String primaryKeyValue,
String column,
String columnValue,
String query,
List<N... | assertThrows(IllegalStateException.class, () -> RequestParams.builder(resource).value("x"));
}
} |
9580819_6 | class TkInbox implements Take {
@Override
public Response act(final Request req) throws IOException {
final String query = new RqHref.Smart(new RqHref.Base(req)).single(
"q", ""
);
return new RsPage(
"/xsl/inbox.xsl",
this.base,
req,
... | final String urn = "urn:test:2";
final MkBase base = new MkBase();
final Aliases aliases = base.user(new URN(urn)).aliases();
aliases.add("test2");
final Inbox inbox = aliases.iterate().iterator().next().inbox();
final Bout first = inbox.bout(inbox.start());
final... |
9583260_14 | class XeFlow implements Flow {
@Override
public void binding(final String name, final String type) {
this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath(
String.format(
"bindings[not(binding[name='%s' and type=%s])]",
name, XeOntology.escapeXPa... | final Directives dirs = new Directives().add("f");
final Flow flow = new XeFlow(dirs, "/f");
flow.binding("emp", "Employee");
flow.binding("one", "One");
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(new Xembler(dirs).xml()),
XhtmlMatchers.hasXPaths(
... |
9602474_1 | class FederationController {
public String getRepositoryName() throws RepositoryException{
Session repositorySession = newSession();
try {
return repositorySession.getRepository().getDescriptor(org.modeshape.jcr.api.Repository.REPOSITORY_NAME);
} finally {
repository... | assertEquals("federated-repository", federationController.getRepositoryName());
}
} |
9617158_0 | class RDAPCLI {
public static Type guessQueryType(String query) {
try {
if (query.matches("^\\d+$")) {
return Type.AUTNUM;
}
if (query.matches("^[\\d\\.:/]+$")) {
return Type.IP;
}
if (DomainName.of(query).getLevelSize() > 1) {
return Type.DOMAIN;
}
... | assertEquals(RDAPCLI.Type.AUTNUM,RDAPCLI.guessQueryType("12345"));
assertEquals(RDAPCLI.Type.IP,RDAPCLI.guessQueryType("127.0.0.0/8"));
assertEquals(RDAPCLI.Type.DOMAIN, RDAPCLI.guessQueryType("foo.example"));
assertEquals(RDAPCLI.Type.ENTITY,RDAPCLI.guessQueryType("handle"));
}
} |
9634917_6 | class OpenPathwayCommonsTask extends AbstractTask {
public String getPathwayCommonsURL() {
EnrichmentMap map = emManager.getEnrichmentMap(network.getSUID());
if(map == null)
return null;
int port = Integer.parseInt(cy3props.getProperties().getProperty("rest.port"));
String pcBaseUri = propertyManager.ge... | CyNetwork network = networkManager.getNetwork(map.getNetworkID());
CyNode node = TestUtils.getNodes(network).get("TOP1_PLUS100");
propertyManager.setValue(PropertyManager.PATHWAY_COMMONS_URL, "http://pathway.commons/paint");
@SuppressWarnings("deprecation")
String returnUri = URLEncoder.encode("http://loca... |
9650789_1 | class VerticaBulkLoaderMeta extends BaseStepMeta implements StepMetaInterface, ProvidesModelerMeta {
public String getXML() {
StringBuilder retval = new StringBuilder();
retval.append( " " + XMLHandler.addTagValue( "connection", databaseMeta == null ? "" : databaseMeta.getName() ) );
retval.append( "... | VerticaBulkLoaderMeta vbl = new VerticaBulkLoaderMeta();
vbl.setDefault();
vbl.setFieldDatabase( new String[] { "fieldDB1", "fieldDB2", "fieldDB3", "fieldDB4", "fieldDB5" } );
vbl.setFieldStream( new String[] { "fieldStr1", "fieldStr2", "fieldStr3" } );
try {
vbl.getXML();
fail( "Before... |
9657943_0 | class Stats {
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getStats()
{
StatsManager statsManager = this.statsManager;
if (this.statsManager != null)
{
return JSONSerializer.serializeStatistics(statsManager.getStatistics()).toJSONString();
}
... | Map<String, Object> fakeStats = new HashMap<>();
fakeStats.put("stat1", "value1");
fakeStats.put("stat2", "value2");
VideobridgeStatistics videobridgeStatistics = mock(VideobridgeStatistics.class);
when(videobridgeStatistics.getStats()).thenReturn(fakeStats);
when(statsMa... |
9667687_64 | class AccessControlQueries {
public ExecutionResult findAdminForResource( String resourceName )
{
String query = "MATCH (resource:Resource {name:{resourceName}})\n" +
"MATCH p=(resource)-[:WORKS_FOR|HAS_ACCOUNT*1..2]-(company)\n" +
" -[:CHILD_OF*0..3... | // Account-10 is associated with One-ManShop
// One-ManShop-CHILD_OF->Subsidiary-CHILD_OF->AcquiredLtd->CHILD_OF->BigCompany
// Liz is a member of:
// Group-6, which has ALLOWED_DO_NOT_INHERIT to OneManShop
// Group-5, which has DENIED on AcquiredLtd
// Group-4, wh... |
9685461_21 | class APIReader {
public String executePostUrl() throws IOException {
return executePostUrl("");
}
public APIReader(UriBuilder uriBuilder);
public APIReader(String url);
public APIReader(URL url);
public APIReader setHeader(String header, String value);
public String executeGet... | //Given
when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("response"));
//When
String response = apiReader.executePostUrl();
//Then
assertThat(response, is("response"));
}
} |
9702026_7 | class PathUtil {
public static Path getUserIgnoreDir()
{
return getUserSubdirectory(IGNORE_DIRECTORY_NAME);
}
public static Path getWindupUserDir();
public static Path getWindupHome();
public static void setWindupHome(Path windupHome);
public static Path getUserCacheDir();
publ... | Assert.assertEquals(Paths.get("ignore"), PathUtil.getUserIgnoreDir());
setUserHome("/foo");
Assert.assertEquals(Paths.get("/foo", ".mta", "ignore"), PathUtil.getUserIgnoreDir());
}
} |
9706311_22 | class GatewaySelector {
public Gateway select() {
return closestGateway();
}
public GatewaySelector(List<Gateway> gateways);
public Gateway select(int nClosest);
private Gateway closestGateway();
private TreeMap<Integer, Set<Gateway>> calculateOffsets();
private int timezoneDista... | when(ConfigHelper.getCurrentTimezone()).thenReturn(timezone);
gatewaySelector = new GatewaySelector(gatewayList);
ArrayList<String> gateways = new ArrayList<>();
gateways.add(gatewaySelector.select(0).getName());
gateways.add(gatewaySelector.select(1).getName());
assertT... |
9708055_10 | class CeSymmMain {
public static List<String> parseInputStructures(String filename)
throws FileNotFoundException {
File file = new File(filename);
Scanner s = new Scanner(file);
List<String> structures = new ArrayList<String>();
while (s.hasNext()) {
String name = s.next();
if (name.startsWith("#"))... | URL url = CeSymmMainTest.class.getResource("/cesymmtest.txt");
String filename = url.getFile();
List<String> names = CeSymmMain.parseInputStructures(filename);
assertEquals(6,names.size());
int i = 0;
assertEquals("d1ijqa1",names.get(i++));
assertEquals("1G6S",names.get(i++));
assertEquals("1MER.A",n... |
9713275_247 | class DuplicateOperations {
public void markDirectoryAs(Path directory, Tag tag) {
if (!isDirectory(directory)) {
logger.warn("Directory {} not valid, aborting.", directory);
return;
}
try {
int addCount = 0;
Iterator<Path> iter = Files.newDirectoryStream(directory).iterator();
while (iter.hasN... | createTempTestFiles(3);
dupOp.markDirectoryAs(tempDirectory, TAG_FOO);
verify(imageRepository, times(3)).getByPath(any(Path.class));
verify(filterRepository, never()).store(any(FilterRecord.class));
}
} |
9721255_36 | class Peer {
public ListenableFuture<Block> getBlock(Sha256Hash blockHash) throws IOException {
// This does not need to be locked.
log.info("Request to fetch block {}", blockHash);
GetDataMessage getdata = new GetDataMessage(params);
getdata.addBlock(blockHash);
return send... | control.replay();
connect();
Block b1 = createFakeBlock(blockStore).block;
blockChain.add(b1);
Block b2 = makeSolvedTestBlock(b1);
Block b3 = makeSolvedTestBlock(b2);
// Request the block.
Future<Block> resultFuture = peer.getBlock(b3.getHash())... |
9731550_14 | class BerInteger {
public int decode(InputStream iStream, boolean explicit) throws IOException {
int codeLength = 0;
if (explicit) {
codeLength += id.decodeAndCheck(iStream);
}
BerLength length = new BerLength();
codeLength += length.decode(iStream);
if (length.val < 1 || length.val > 8) {
throw... | byte[] byteCode = new byte[] { 0x02, 0x02, 0x15, (byte) 0xb3 };
ByteArrayInputStream berInputStream = new ByteArrayInputStream(byteCode);
BerInteger asn1Integer = new BerInteger();
asn1Integer.decode(berInputStream, true);
Assert.assertEquals(5555, asn1Integer.val);
}
} |
9754885_0 | class ScorePair {
public ScorePair(MatchingConfig mc) {
this.mc = mc;
vt = new VectorTable(mc);
modifiers = new ArrayList<Modifier>();
observed_vectors = new Hashtable<MatchVector, Long>();
}
public ScorePair(MatchingConfig mc);
public void addScoreModifier(Modifier sm);
public MatchResult scorePair(Re... |
// set up the records
Record rec1 = new Record(1, "foo");
Record rec2 = new Record(2, "foo");
rec1.addDemographic("(Identifier) Old OpenMRS Identifier", "111,222,333");
rec2.addDemographic("(Identifier) Old OpenMRS Identifier", "222,444,555");
// add the identifier demographic for scoring
MatchingCo... |
9755019_5 | class QualityInvestmentPlanService {
public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) {
Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create();
for (QualityViolation violation : filterViolationsByArtefactName... | QualityInvestmentPlan qualityInvestmentPlan = investmentPlanService.computeInvestmentPlan(analysis, "", 80);
QualityInvestmentPlanEntry[] investments = qualityInvestmentPlan.getEntries().toArray(new QualityInvestmentPlanEntry[0]);
assertThat(investments).hasSize(3);
assertThat(investments[0].getArtefact... |
9775946_3 | class WisePageFactory {
public static <T> T initElements(WebDriver driver, Class<T> clazz) {
T instance = instantiatePage(driver, clazz);
return initElements(driver, instance);
}
private WisePageFactory();
public static T initElements(SearchContext searchContext, T instance);
private static T instantiatePa... | DummyPageWithNoArgConstructor page = WisePageFactory.initElements(this.driver, DummyPageWithNoArgConstructor.class);
assertNotNull(page.getDummyComponent());
}
} |
9779351_36 | class LexOperator {
public Token read() throws IOException, LexerException
{
int index = in_stream.getPosition();
int line = in_stream.getLine();
int col = in_stream.getCol();
int next = in_stream.peek();
if (next == -1) {
// end of stream!
throw... | String str = "a&=b|c|=d&e^=f^g;";
LexerStream ls = new LexerStream(new StringReader(str));
LexOperator lex = new LexOperator(new BaseTokenFactory(), ls);
ls.read();
Token tok = lex.read();
assertEquals(TokenType.BitwiseAndAssign, tok.getType());
assertEquals(1... |
9797598_3 | class DefaultRegisteredServiceMfaRoleProcessorImpl implements RegisteredServiceMfaRoleProcessor {
public List<MultiFactorAuthenticationRequestContext> resolve(@NotNull final Authentication authentication,
@NotNull final WebApplicationService targetSe... | final WebApplicationService was = getTargetService();
final Authentication auth = getAuthentication(true);
final RegisteredService rswa = TestUtils.getRegisteredService("test1");
final DefaultRegisteredServiceProperty prop = new DefaultRegisteredServiceProperty();
prop.setValue... |
9812178_36 | class Schooljaar implements IBeginEinddatumEntiteit, Comparable<Schooljaar>,
Serializable {
public static Schooljaar parse(String value)
{
Pattern[] patterns = new Pattern[] {officieel, kort};
for (Pattern pattern : patterns)
{
Matcher matcher = pattern.matcher(value);
if (!matcher.matches())
{
... | assertThat(Schooljaar.parse("2008A2009"), is(nullValue()));
}
} |
9821876_552 | class DoubleConverter implements Converter<Double> {
@Override
public Double convert(String value, Class<? extends Double> type) {
if (isNullOrEmpty(value)) {
return null;
}
try {
return getNumberFormat().parse(value).doubleValue();
} catch (ParseException e) {
throw new ConversionException(new Con... | assertThat(converter.convert("10,00", Double.class), is(equalTo(new Double("10.00"))));
assertThat(converter.convert("10,01", Double.class), is(equalTo(new Double("10.01"))));
}
} |
9854553_37 | class ClassUtils {
public static String determineQualifiedName(String className) {
String readableClassName = StringUtils.removeWhitespace(className);
if (readableClassName == null) {
throw new IllegalArgumentException("readableClassName must not be null.");
} else if (readab... |
String className = "org.jadira.bindings.core.utils.string.ClassUtilsTest";
assertEquals("org.jadira.bindings.core.utils.string.ClassUtilsTest", ClassUtils.determineQualifiedName(className));
assertEquals("org.jadira.bindings.core.utils.string.ClassUtilsTest", ClassUtils.determi... |
9882334_4 | class HttpClient {
public HttpRequestBuilder post() {
return new RB(Method.POST);
}
public HttpClient();
public HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, L... | final AM am = new AM();
final String ur = "http://foo.bar:" + server.httpPort() + "/foo";
client.addActivityMonitor(am);
final DeferredAssertions assertions = new DeferredAssertions();
final Set<StateType> stateTypes = new HashSet<>();
final String[] xheader = new String[... |
9884445_95 | class OneToManyAnnotationHandler extends AbstractEntityAnnotationHandler {
@Override
public void handle(EntityMetaData metaData, Annotation annotation, Method method) {
Class<?> elementType = getElementType(method.getGenericReturnType());
CollectionMetaData collectionMetaData = new CollectionMetaData(metaData.ge... | Method method = DummyModel.class.getDeclaredMethod("getChildren");
handler.handle(metaData, annotation, method);
CollectionMetaData data = new CollectionMetaData(DummyModel.class, "children", DummyModel.class, Set.class, true);
verify(metaData).addCollection(data);
}
} |
9897034_1 | class PubService {
public Beer findBeerById(final long id) {
return beerRepository.findOne(id);
}
public long getBeersCount();
public Beer createBeer(final String name, final int alcoholPercentage);
public BrewingCompany createBrewingCompany(final String name);
public Iterable<Beer> ge... | service.populateData();
for (Beer beer : service.getAllBeers()) {
Beer foundBeer = service.findBeerById(beer.getId());
assertNotNull(foundBeer);
}
}
} |
9909566_12 | class ExportFileWriter {
public void write(final RpslObject object, final List<Tag> tags) throws IOException {
if (exportFilter.shouldExport(object)) {
final String filename = filenameStrategy.getFilename(object.getType());
if (filename != null) {
final Writer writer... | subject.write(RpslObject.parse("mntner: DEV-MNT1"), Collections.EMPTY_LIST);
subject.write(RpslObject.parse("mntner: DEV-MNT2"), Collections.EMPTY_LIST);
subject.write(RpslObject.parse("mntner: DEV-MNT3"), Collections.EMPTY_LIST);
subject.write(RpslObject.parse("mntner: DEV-MNT4"), Colle... |
9910980_2 | class ModelInterchangeMojo extends AbstractMojo {
public void execute() throws MojoExecutionException {
getLog().info("Running BPMN-MIWG test suite...");
if (!outputDirectory.exists()) {
outputDirectory.mkdirs();
}
try {
Collection<String> inputFolders = new LinkedList<String>();
if (!resources.isE... | Resource res = new Resource();
res.setDirectory("src/test/invalid-resources");
mojo.resources.add(res);
mojo.application = "Yaoqiang BPMN Editor 2.2.6";
mojo.execute();
assertTrue(overview.exists());
Document document = docBuilder.parse(overview);
XPathExpression xpath = createXpathExpression("//div[@... |
9917257_48 | class CassandraClusterCreator extends AbstractServiceConnectorCreator<Cluster, CassandraServiceInfo> {
@Override
public Cluster create(CassandraServiceInfo serviceInfo,
ServiceConnectorConfig serviceConnectorConfig) {
Builder builder = Cluster.builder()
.addContactPoints(serviceInfo.getContactPoints().toAr... |
CassandraServiceInfo info = new CassandraServiceInfo("local",
Collections.singletonList("127.0.0.1"), 9142);
CassandraClusterConfig config = new CassandraClusterConfig();
config.setCompression(ProtocolOptions.Compression.NONE);
config.setPoolingOptions(new PoolingOptions().setPoolTimeoutMillis(1234));
c... |
9922054_3 | class MyWidget extends Composite {
public void loadDataFromRpc() {
MyServiceAsync service = GWT.create(MyService.class);
service.getData(new AsyncCallback<String>() {
@Override
public void onSuccess(String result) {
data.setText(result);
}
@Override
public void onFailur... | doAnswer(returnSuccess("some data")).when(myService).getData(any(AsyncCallback.class));
widget.loadDataFromRpc();
verify(widget.data).setText("some data");
}
} |
9922058_6 | class EventBinderWriter {
void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle)
throws UnableToCompleteException {
writeBindMethodHeader(writer, target.getQualifiedSourceName());
for (JMethod method : target.getInheritableMethods()) {
EventHandler annotation... | JClassType paramType = getEventType(AbstractEvent.class);
when(paramType.isAbstract()).thenReturn(true);
JMethod method = newMethod("myMethod", paramType);
when(target.getInheritableMethods()).thenReturn(new JMethod[] {method});
try {
writer.writeDoBindEventHandlers(target, output, t... |
9941578_49 | class NetworkStatusRetriever {
NetworkStatus retrieveNetworkStatus() {
if (merlinsBeard.isConnected()) {
return NetworkStatus.newAvailableInstance();
} else {
return NetworkStatus.newUnavailableInstance();
}
}
NetworkStatusRetriever(MerlinsBeard merlinsBea... | given(merlinsBeards.isConnected()).willReturn(DISCONNECTED);
NetworkStatus networkStatus = networkStatusRetriever.retrieveNetworkStatus();
assertThat(networkStatus).isEqualTo(NetworkStatus.newUnavailableInstance());
}
} |
9949199_0 | class ParentDirectoryAuthorScoreStrategy implements ScoreStrategy<AuthorScore> {
@NotNull
@Override
public AuthorScore score(BookImportContext context) {
try {
File file = context.getFile();
String dirName = file.getParentFile().getName();
String[] rawTokens = sp... | BookImportContext bookImportContext = createMock(BookImportContext.class);
File mock = createMock(File.class);
File parent = createMock(File.class);
expect(mock.getParentFile()).andReturn(parent);
expect(parent.getName()).andReturn("Christopher, Matt");
expect(bookImpor... |
9965237_0 | class SnappyDecompressor {
public static Buffer decompress(byte[] in) {
return decompress(in, 0, in.length, null);
}
private SnappyDecompressor();
public static Buffer decompress(byte[] in, Buffer out);
public static Buffer decompress(byte[] in, int offset, int length);
public static Buffer decompress(Buffe... |
byte[] data = new byte[2];
try {
SnappyDecompressor.decompress(data);
Assert.fail("Exception was expected");
}
catch(FormatViolationException e) {
// the input data is invalid on offset 1
Assert.assertEquals(1, e.getOffset());
}
}
} |
10016717_11 | class SpannersService {
@PreAuthorize("hasPermission(#spanner, 'owner')")
public void update(Spanner spanner) {
restTemplate.put("/{0}", spanner, spanner.getId());
}
public SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String roo... | server.expect(requestTo("/1")).andExpect(method(PUT))
.andRespond(withStatus(HttpStatus.OK));
Spanner update = aSpanner().withId(1L).build();
service.update(update);
// Check that the server received the message
server.verify();
}
} |
10035739_213 | class CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> {
public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
StringBuffer buffer = new StringBuffer();
buffer.append("CREATE TABLE ").append(database.escapeTable... | for (Database database : TestContext.getInstance().getAllDatabases()) {
if (database instanceof SybaseASADatabase) {
CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME);
statement.addColumn(
COLUMN_NAME1,
TypeConverterFactory.getInstance().findType... |
10040960_712 | class DelegatingImageExtension implements ImageExtension {
public ListenableFuture<Image> createImage(final ImageTemplate template) {
ListenableFuture<Image> future = delegate.createImage(template);
// Populate the default image credentials, if missing
future = Futures.transform(future, new Funct... | ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class);
ImageExtension delegate = createMock(ImageExtension.class);
AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class);
ImageTemplate template = new ImageTemplateImpl("test") {
};
I... |
10057936_5 | class PollexorRequestTransformer implements RequestTransformer {
@NonNull @Override public Request transformRequest(@NonNull Request request) {
if (request.resourceId != 0) {
return request; // Don't transform resource requests.
}
Uri uri = request.uri;
if (uri == null) {
throw new Illega... | Request input = new Request.Builder(IMAGE_URI).resize(50, 50).build();
Request output = transformer.transformRequest(input);
assertThat(output).isNotSameAs(input);
assertThat(output.hasSize()).isFalse();
String expected = Thumbor.create(HOST).buildImage(IMAGE).resize(50, 50).toUrl();
assertThat... |
10062583_26 | class DatastoreHelper {
public static Key.Builder makeKey(Object... elements) {
Key.Builder key = Key.newBuilder();
PartitionId partitionId = null;
for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) {
PathElement.Builder pathElement = PathElement.newBuilder();
Object element... | assertEquals(
Key.newBuilder()
.addPath(Key.PathElement.newBuilder().setKind("Foo").setName("hi"))
.build(),
makeKey("Foo", "hi").build());
}
} |
10064418_31 | class FileSystemTemplateLocator extends FilePathTemplateLocator {
public static Builder builder() {
return new Builder();
}
public FileSystemTemplateLocator(int priority, String rootPath);
public FileSystemTemplateLocator(int priority, String rootPath,
String suffix);
@Overr... |
TemplateLocator locator = FileSystemTemplateLocator.builder()
.setPriority(1).setRootPath("src/test/resources/locator/file")
.setSuffix("foo").build();
// Just to init the locator
MustacheEngineBuilder.newBuilder().addTemplateLocator(locator)
.se... |
10065023_0 | class HelloWorld implements ActionBlock {
public int execute(FlowContext ctx) throws FlowExecutionException {
String name = (String) ctx.get(IN_NAME);
String message = "Hello World! ";
if (name != null) {
message += name;
}
logger.debug("Message: {}", message);
ctx.put(OUT_MESSAGE, message);
... |
HelloWorld helloWorld = new HelloWorld();
FlowContext context = new FlowContext();
context.put("name", "John");
try {
int result = helloWorld.execute(context);
context.get("message");
assertEquals(ActionBlock.NEXT, result);
assertEquals("Hello World! John", context.get("message"));
... |
10075325_3 | class ExecuteRequest extends Request implements IObserver {
public void updateStatusError(String errorMessage) {
StatusType status = StatusType.Factory.newInstance();
net.opengis.ows.x11.ExceptionReportDocument.ExceptionReport excRep = status
.addNewProcessFailed().addNewExceptionReport();
excRep.setVersion... |
FileInputStream fis = new FileInputStream(new File("src/test/resources/LRDTCCorruptInputResponseDocStatusTrue.xml"));
// parse the InputStream to create a Document
Document doc = fac.newDocumentBuilder().parse(fis);
ExecuteRequest request = new ExecuteRequest(doc);
String exceptionText = "TestError"... |
10081109_107 | class RollupEvent {
public Rollup getRollup() {
return rollup;
}
public RollupEvent(Locator loc, Rollup rollup, String unit, String gran, long ts);
public Locator getLocator();
public String getUnit();
public String getGranularityName();
public long getTimestamp();
public voi... | Assert.assertSame(rollup, event.getRollup());
}
} |
10085184_0 | class MavenRepositories {
public static List<RemoteRepository> getRemoteRepositories(MavenContainer container, Settings settings)
{
Set<RemoteRepository> remoteRepos = new HashSet<>();
remoteRepos.addAll(container.getEnabledRepositoriesFromProfile(settings));
// central repository is added if ... | SettingsBuilder settingsBuilder = new DefaultSettingsBuilderFactory().newInstance();
SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest();
settingsRequest.setUserSettingsFile(new File("src/test/resources/profiles/mirror-settings.xml"));
Settings settings = settingsBuild... |
10113030_56 | class Renderer {
public GoogleMap getMap() {
return mMap;
}
public Renderer(GoogleMap map,
Context context,
MarkerManager markerManager,
PolygonManager polygonManager,
PolylineManager polylineManager,
... | assertEquals(mMap1, mRenderer.getMap());
}
} |
10116915_0 | class ExternalSystemRecentTaskListModel extends DefaultListModel {
@SuppressWarnings("unchecked")
public void setFirst(@Nonnull ExternalTaskExecutionInfo task) {
insertElementAt(task, 0);
for (int i = 1; i < size(); i++) {
if (task.equals(getElementAt(i))) {
remove(i);
break;
}
... | List<ExternalTaskExecutionInfo> tasks = ContainerUtilRt.newArrayList();
for (int i = 0; i <= ExternalSystemConstants.RECENT_TASKS_NUMBER; i++) {
new ExternalTaskExecutionInfo(new ExternalSystemTaskExecutionSettings(), "task" + i);
}
myModel.setTasks(tasks);
myModel.setFirst(new ExternalTaskEx... |
10144081_34 | class EasyRandom extends Random {
public <T> T nextObject(final Class<T> type) {
return doPopulateBean(type, new RandomizationContext(type, parameters));
}
public EasyRandom();
public EasyRandom(final EasyRandomParameters easyRandomParameters);
public Stream<T> objects(final Class<T> ty... | HashSet<TestEnum> distinctEnumBeans = new HashSet<>();
for (int i = 0; i < 10; i++) {
distinctEnumBeans.add(easyRandom.nextObject(TestEnum.class));
}
assertThat(distinctEnumBeans.size()).isGreaterThan(1);
}
} |
10189028_10 | class ConsistentReportServiceImpl implements ConsistentReportService {
public List<ConsistentReportDO> queryConsistentReport(Map params) {
return consistentReportDao.queryConsistentReport(params);
}
public void setConsistentReportDao(ConsistentReportDao consistentReportDao);
public Integer sav... | // Map params = new HashMap();
// params.put("errorType", "read");
// params.put("pageSize", 2);
// params.put("startRow", 0);
// List<ConsistentReportDO> reportList = consistentReportService.queryConsistentReport(params);
// assertTrue(reportList != null);
// assertEqua... |
10192655_5 | class XMLParser extends AbstractXMLParser {
public static SushiEvent generateEventFromXML(String filePath) throws XMLParsingException {
Document doc = readXMLDocument(filePath);
return generateEvent(doc, null);
}
public static SushiEvent generateEventFromXML(String filePath, String pathToXSD);
public static S... | SushiEventType eventTyp = new SushiEventType("EventTaxonomy");
eventTyp.setXMLName("EventTaxonomy");
eventTyp.setTimestampName("location.timestamp");
eventTyp.save();
SushiEvent event = XMLParser.generateEventFromXML(filePathToXMLWithHierarchicalTimestamp);
assertNotNull(event);
Calendar cal = Calendar.ge... |
10195984_2 | class Index implements Iterable<IndexItem<A,I>> {
public static <A extends Annotation,I> Index<A,I> load(Class<A> annotation, Class<I> instanceType) throws IllegalArgumentException {
return load(annotation, instanceType, Thread.currentThread().getContextClassLoader());
}
private Index(Class<A> an... | TestUtils.makeSource(src, "x.A",
"import java.lang.annotation.*;",
"@Retention(RetentionPolicy.RUNTIME)",
"@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})",
"@net.java.sezpoz.Indexable",
"public @interface A {",
... |
10227537_1 | class AuthenticationUtil {
public static void configureAuthentication(String role) {
Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(role);
Authentication authentication = new UsernamePasswordAuthenticationToken(
USERNAME,
role,
... | AuthenticationUtil.configureAuthentication(ROLE);
Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
assertThat(currentAuthentication.getAuthorities()).hasSize(1);
assertThat(currentAuthentication.getAuthorities().iterator().next().getAuthorit... |
10230369_33 | class SimpleServiceLoader {
public static <T> ImmutableList<T> load(Class<? extends T> service, ClassLoader loader) {
String resourceName = "META-INF/services/" + service.getName();
List<URL> resourceUrls;
try {
resourceUrls = Collections.list(loader.getResources(resourceName));
} catch (IOExce... | ClassLoader loader = loaderForJarWithEntries(CharSequence.class.getName(), "java.lang.Thread");
try {
SimpleServiceLoader.load(CharSequence.class, loader);
fail();
} catch (ServiceConfigurationError expected) {
assertThat(expected).hasMessageThat().startsWith("Class java.lang.Thread is no... |
10262572_39 | class AS2HttpHelper {
@Nullable
public static String getCleanContentType (@Nullable final String sContentType)
{
final ContentType aCT = parseContentType (sContentType);
return aCT != null ? aCT.toString () : null;
}
private AS2HttpHelper();
@Nullable public static ContentType parseContentType(@... | assertNull (AS2HttpHelper.getCleanContentType (null));
assertNull (AS2HttpHelper.getCleanContentType (""));
assertNull (AS2HttpHelper.getCleanContentType (" "));
assertNull (AS2HttpHelper.getCleanContentType ("abc"));
assertNull (AS2HttpHelper.getCleanContentType ("abc/"));
assertEquals ("abc... |
10264172_22 | class InverseSquaredLinkFunction implements Fn {
@Override
public double evaluate(final double[] x) {
if (x.length > 1) {
throw new AIFHError("The inverse squared link function can only accept one parameter.");
}
return -Math.pow(x[0], -2);
}
}
class TestInverseSquare... | final InverseSquaredLinkFunction fn = new InverseSquaredLinkFunction();
final double[] x = {2};
final double y = fn.evaluate(x);
assertEquals(-0.25, y, AIFH.DEFAULT_PRECISION);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.