id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
17939962_0 | class FTDISerialDevice extends UsbSerialDevice {
static byte[] adaptArray(byte[] ftdiData)
{
int length = ftdiData.length;
if(length > 64)
{
int n = 1;
int p = 64;
// Precalculate length without FTDI headers
while(p < length)
{... | byte[] onlyHeaders = {1, 2};
byte[] adapted = FTDISerialDevice.adaptArray(onlyHeaders);
Assert.assertEquals("Should be empty", 0, adapted.length);
byte[] adaptAgain = FTDISerialDevice.adaptArray(onlyHeaders);
Assert.assertSame("Should be the same instance of empty array", adapted... |
17959249_7 | class ConstraintParser {
public String parse() {
Map<String, ClassConstraints> classNameToValidationRulesMap = new HashMap<>();
for (Class clazz : classpathScanner.findClassesToParse()) {
if (clazz != null) {
ClassConstraints classValidationRules = new AnnotatedClass(clazz, options.getExcluded... | // given
parserConfiguredFor(Lists.newArrayList(TestModelWithEmailAnnotation.class.getPackage().getName()),
emptyStringList());
// when
String json = parser.parse();
// then
assertThat(json, containsString(TestModelWithEmailAnnotation.class.getSimpleName()));
assertThat(json, containsS... |
17959600_0 | class NumerusRollingNumber {
public void increment(NumerusRollingNumberEvent type, Boolean doNotBlock) {
Bucket lastBucket = getCurrentBucket(doNotBlock);
if (lastBucket == null)
return;
lastBucket.getAdder(type).increment();
}
public NumerusRollingNumber(NumerusRollin... | MockedTime time = new MockedTime();
try {
NumerusRollingNumber counter = new NumerusRollingNumber(EventType.BOOTSTRAP, time, 200, 10);
// we start out with 0 buckets in the queue
assertEquals(0, counter.buckets.size());
// add 1
counter.incre... |
17971137_149 | class LogicalPlanner extends BaseAlgebraVisitor<LogicalPlanner.PlanContext, LogicalNode> {
public LogicalPlan createPlan(Expr expr) throws PlanningException {
return createPlan(expr, false);
}
public LogicalPlanner(CatalogService catalog);
@VisibleForTesting public LogicalPlan createPlan(Expr expr, bool... | Expr expr = sqlAnalyzer.parse(ALIAS[0]);
LogicalNode plan = planner.createPlan(expr).getRootBlock().getRoot();
LogicalRootNode root = (LogicalRootNode) plan;
testJsonSerDerObject(root);
Schema finalSchema = root.getOutSchema();
Iterator<Column> it = finalSchema.getColumns().iterator();
Colu... |
17971138_20 | class LazyTuple implements Tuple, Cloneable {
@Override
public boolean equals(Object obj) {
if (obj instanceof Tuple) {
Tuple other = (Tuple) obj;
return Arrays.equals(getValues(), other.getValues());
}
return false;
}
public LazyTuple(Schema schema, byte[][] textBytes, long offset);
... | int colNum = schema.size();
LazyTuple t1 = new LazyTuple(schema, new byte[colNum][], -1);
LazyTuple t2 = new LazyTuple(schema, new byte[colNum][], -1);
t1.put(0, DatumFactory.createInt4(1));
t1.put(1, DatumFactory.createInt4(2));
t1.put(3, DatumFactory.createInt4(2));
t2.put(0, DatumFactor... |
17971683_0 | class HibernateBookDao implements BookDao {
@Override
public Book addBook(Book book) {
sessionFactory.getCurrentSession().persist(book);
return book;
}
public HibernateBookDao(SessionFactory sessionFactory);
@Override public void removeBook(Book book);
@SpringBean("bookDao")... | Book book = new Book("Hibernate in Action");
book.setTags(new LinkedHashSet<String>(asList("blog", "java")));
assertNotNull(dao.addBook(book).getId());
}
} |
17987394_23 | class LocationSerializer implements JsonSerializer<JSON.Location> {
@Override public JsonElement serialize(JSON.Location src, Type typeOfSrc,
JsonSerializationContext context) {
JsonObject jsonObject = (JsonObject) new GsonBuilder().create().toJsonTree(src);
if (src.heading < 0 || src.heading >= 360) {... | location.heading = 361;
assertThat(locationSerializer.serialize(location, JSON.Location.class, null).toString())
.doesNotContain("\"heading\":361");
}
} |
17988451_2 | class ElasticsearchItemWriter implements ItemWriter<IndexQuery>, InitializingBean {
@Override
public void write(List<? extends IndexQuery> items) throws Exception {
if(isActualTransactionActive()) {
addToBuffer(items);
}else {
writeItems(items);
}
}
public ElasticsearchItemWriter(ElasticsearchOperat... |
IndexQueryBuilder builder = new IndexQueryBuilder();
builder.withObject(dummyDocument);
List<IndexQuery> items = asList(builder.build());
writer.write(items);
verify(elasticsearchOperations).index(items.iterator().next());
}
} |
17994739_3 | class ManifestOptimizer {
public static void adjustMinMax(AdaptationSetType adaptationSetType, Function<RepresentationType, Long> get, ObjLongConsumer<AdaptationSetType> setMin, ObjLongConsumer<AdaptationSetType> setMax) {
List<RepresentationType> representations = adaptationSetType.getRepresentation();
... | MPDtype mpd = read(new File(ManifestOptimizerTest.class.getProtectionDomain().getCodeSource().getLocation().getFile() + "/com/castlabs/dash/dashfragmenter/representation/exampleManifest.mpd"));
ManifestOptimizer.adjustMinMax(mpd.getPeriod().get(0).getAdaptationSet().get(0), RepresentationType::getBandw... |
18023059_2 | class Sha256Hasher extends Hasher {
@PostConstruct
public void init() {
rn = new SecureRandom();
}
@Override public String hash(String value);
@Override public boolean compareInternal(String plainText, String previousHash);
@Override public String getName();
private String hash256(... | SecureRandom random = new SecureRandom();
Sha256Hasher hasher = new Sha256Hasher();
hasher.init();
String password;
for (int i =0; i < 100; i++){
password = new BigInteger(130, random).toString(32);
Assert.assertTrue(hasher.compare(password, hasher.transfo... |
18035587_2 | class DefaultLandMatcher implements LandMatcher {
@Override
public boolean match(String className, String pattern) {
return matchExactlyFullQualifiedClassName(className, pattern) ||
matchFullQualifiedPackageNameAndItsSubPackage(className, pattern) ||
matchFullQualifiedPa... | assertTrue(matcher.match("foo.A", "foo.A"));
assertTrue(matcher.match("foo.A", "foo.*"));
assertTrue(matcher.match("foo.Air123", "foo.*"));
assertFalse(matcher.match("foo1.Air123", "foo.*"));
assertFalse(matcher.match("foo.p.A", "foo.*"));
assertTrue(matcher.match("foo.... |
18093759_63 | class OracleSpecifics {
static Connection createCustomDriverConnection(OracleDriverConnectionInfo connInfo,
ConnectorMessages cm) {
try {
return SQLUtil.getDriverMangerConnection(connInfo.getDriver(), connInfo.getUrl(),
connInfo.getUser(), connInfo.getPassword())... | String user = TEST_PROPS.getStringProperty("customDriver.user");
String password = TEST_PROPS.getStringProperty("customDriver.password");
String url = TEST_PROPS.getStringProperty("customDriver.url");
String driver = TEST_PROPS.getStringProperty("customDriver.driverClassName");
C... |
18114836_20 | class X509CertificateUtil {
public static String getPropertyFromX500Principal(X509Certificate cert, String propertyName) {
String propertyValue = null;
String principalName = cert.getSubjectX500Principal().getName();
log.debug("Found principalName = {}", principalName);
Pattern pattern = createPattern(... | X509Certificate cert = mock(X509Certificate.class);
X500Principal principal = new X500Principal("OU=JavaSoft, O=Sun Microsystems, C=US");
when(cert.getSubjectX500Principal()).thenReturn(principal);
try {
X509CertificateUtil.getPropertyFromX500Principal(cert, "CN");
fail();
} catch (Exception e) {
... |
18133301_36 | class ModalApplication extends SimpleApplication implements Application {
public E getMode() {
return mode;
}
protected ModalApplication(
Class<E> modeClass,
E defaultMode,
String[] args);
Optional<E> determineMode(Class<E> modeClass, String[] args);
... | TestModes mode = new TestModalApplication(ARGS_MISSING).getMode();
assertThat(mode, equalTo(TestModes.PROD));
}
} |
18143415_0 | class MutableString {
public void clear()
{
m_string = "";
}
public MutableString();
public MutableString(String s);
public MutableString(MutableString s);
public int indexOf(String s);
public int indexOf(String s, int fromIndex);
public void trim();
public int length();
public MutableString[] split(... | MutableString ms1 = new MutableString("abc");
ms1.clear();
assertEquals("", ms1.toString());
assertEquals(0, ms1.length());
}
} |
18150497_4 | class CertUtils {
public static String confirmationMethodHashS256(String certificateAsPem) {
if (org.apache.commons.lang.StringUtils.isBlank(certificateAsPem)) {
return "";
}
try {
certificateAsPem = org.apache.commons.lang.StringUtils.remove(certificateAsPem, "-----... | Assert.assertEquals("A4DtL2JmUMhAsvJj5tKyn64SqzmuXbMrJa0n761y5v0", CertUtils.confirmationMethodHashS256(TEST_PEM_1));
Assert.assertEquals("A4DtL2JmUMhAsvJj5tKyn64SqzmuXbMrJa0n761y5v0", CertUtils.confirmationMethodHashS256(TEST_PEM_2));
Assert.assertEquals("A4DtL2JmUMhAsvJj5tKyn64SqzmuXbMrJa0n761... |
18188420_0 | class ArchiveUtils {
public static void extractArchive (Path archivePath, Path extractToDirectory)
throws IOException, CompressorException, ArchiveException {
try (InputStream jdkInputStream = new BufferedInputStream(Files.newInputStream(archivePath))) {
String compressorType = null;
try {
compr... | String someFilename = "some-file.txt";
Path someFilePath = tempDir.resolve(someFilename);
Files.write(someFilePath, "Hello world\n".getBytes(StandardCharsets.UTF_8));
Path archiveZip = tempDir.resolve("archive.zip");
// Create an archive, add entry, update file, add same entry
try (OutputStream... |
18202815_119 | class StringConverter implements TypeConverter<String> {
public String convert(Integer target) {
return target.toString();
}
public StringConverter();
public String convert(Long target);
public String convert(BigInteger target);
public String convert(Float target);
public String ... |
assertThat(new StringConverter().convert(Integer.valueOf(10)), is("10"));
}
} |
18208577_2 | class EasyObjectCursor extends AbstractCursor implements EasyCursor {
@Override
public int getColumnIndex(final String columnName) {
final String column = applyAlias(columnName);
return mFieldAccessor.getFieldIndexByName(column);
}
public EasyObjectCursor(final Class<T> clazz, final L... | final EasyCursor cursor = TestObjectCursorBuilder.getCursor("int");
final int intIndex = cursor.getColumnIndex("int");
final int idIndex = cursor.getColumnIndex("_id");
assertEquals(intIndex, idIndex);
}
} |
18227906_9 | class FontPackage {
public static boolean validFontPackFolder(String path) {
final File folder = new File(path);
if (!folder.exists() || !folder.isDirectory()) return false;
final String[] fileList = folder.list();
if (fileList == null) return false;
final Set<String> fileNameSet = new HashSet<>(... | File invalidFontPackFolder = getFileResource(INVALID_FONT_FOLDER_NAME);
assertFalse(FontPackage.validFontPackFolder(invalidFontPackFolder.getPath()));
}
} |
18249859_0 | class PasswordHash {
public static String createHash(String password) {
Args.notBlank(password, "password");
return createHash(StringUtil.toUtf8Bytes(password));
}
private PasswordHash();
public static String createHash(byte[] password);
public static String createHash(byte[] password, int saltSiz... | Set<String> passwordHashes = new HashSet<>(20);
for (int i = 0; i < 10; i++) {
String passwordHash = PasswordHash.createHash("p\r\nassw0Rd!");
Assert.assertFalse("PasswordHash duplication occurs",
passwordHashes.contains(passwordHash));
passwordHashes.add(passwordHash);
}
}
} |
18259368_4 | class Chaining {
public static <T> Chain<T> chain(final List<T> list) {
return new Chaining.Chain<T>(list);
}
public static E first(final Iterable<E> iterable);
public static List<T> map(final List<E> list, final Function<? super E, T> func);
public static List<E> sortBy(final List<E> iter... | final List<Map<String, Object>> stooges = new ArrayList<Map<String, Object>>() { {
add(new LinkedHashMap<String, Object>() { { put("name", "curly"); put("age", 25); } });
add(new LinkedHashMap<String, Object>() { { put("name", "moe"); put("age", 21); } });
add(new LinkedHashM... |
18259510_3 | class RestrictSerializationToBaseClassFactory implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
Class incoming = type.getRawType();
if (subClasses != null) {
boolean matched = false;
for (Class<? extends B> subClass : subClass... | Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new RestrictSerializationToBaseClassFactory<Base>(Base.class, Sub1.class))
.create();
String json = gson.toJson(new Container());
assertTrue(json.contains("\"a\":1"));
assertFalse(json.contains("\"b\""));
assertTrue(json.contains(... |
18269132_9 | class Utils {
@NonNull
public static String appendPath(@NonNull String first,
@NonNull String second) {
String result = first + SEP + second;
while (result.contains("//")) {
result = result.replaceAll("//", "/");
}
if (result.len... | assertEquals("A/B", Utils.appendPath("A", "/B"));
assertEquals("/A/B", Utils.appendPath("/A", "/B"));
assertEquals("/A/B/C/D", Utils.appendPath("/A/B", "/C/D"));
assertEquals("/A/B/C/D", Utils.appendPath("/A/B", "/C/D/"));
}
} |
18288221_2 | class JMeterSensor implements Sensor {
protected GlobalSummary getGlobalSummary(Project project) {
GlobalSummary globalSummary = null;
String localJtlPath = getLocalJtlFilePath(project);
String projectName = project.getName();
try {
if (!StringUtils.isBlank(localJtlPath)) {
// ... |
// Start jmeter report server.
// Testing plugin targeting remote jmeter report server,
// then we need a running server.
JMeterReportServer server = new JMeterReportServer();
server.start();
try {
Thread.sleep(SERVER_START_TIME);
} catch (InterruptedException e) {
// Server must ... |
18298933_24 | class AlumnosUseCaseImpl implements AlumnosUseCase {
@Override
public Single<List<Alumno>> getListaAlumnos() {
// return Single.<List<Alumno>>error(new Throwable("No se pudo acceder"));
return Single.just(Arrays.asList(
new Alumno("Baldomero", "Su casa", "http://lorempixel.com/10... | // when.
TestObserver<List<Alumno>> observer = mAlumnosUseCase.getListaAlumnos().test();
// then.
observer.awaitTerminalEvent();
observer.assertNoErrors();
observer.assertValueCount(1);
assertEquals(observer.values().get(0).get(0).getNombre(), "Baldomero");
}
... |
18338023_11 | class GsonMapper {
public static <T> BodyReader<T> json(Class<T> type) {
return INSTANCE.reader(type);
}
public GsonMapper(Gson gson);
public static BodyWriter json(Object value);
public BodyReader<T> reader(Class<T> type);
public BodyWriter writer(Object value);
}
class GsonMapper... | String json = "{\"name\":\"world\"}";
Hello hello = json(Hello.class).readFrom(new ByteArrayInputStream(json.getBytes()));
assertThat(hello.getName(), equalTo("world"));
}
} |
18345774_2 | class RequestInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
if (requestHandler != null) {
return modifyRequest(chain);
}
return chain.proceed(chain.request());
}
private Response modifyRequest(Chain chain);
private void addHeaders(... | assertThat(requestInterceptor.intercept(new TestChain())).isInstanceOf(Response.class);
}
} |
18347965_3 | class JerseyJaxRsEntity implements JaxRsEntity {
@Override
public <T extends Annotation> Optional<T> getAnnotation(Class<T> annotationType) {
Class castClass = Cast.toClass(input);
return (Optional<T>) Optional.fromNullable(castClass.getAnnotation(annotationType));
}
public JerseyJaxRsEntity(Type i... |
JerseyJaxRsEntity entity = new JerseyJaxRsEntity(Foo.class, null);
Optional<Ignore> annotations = entity.getAnnotation(Ignore.class);
assertTrue(annotations.isPresent());
}
} |
18355892_3 | class MainPresenter {
public void onFinished(List<String> items) {
if (mainView != null) {
mainView.setItems(items);
mainView.hideProgress();
}
}
MainPresenter(MainView mainView, FindItemsInteractor findItemsInteractor);
void onResume();
void onItemClic... | List<String> items = Arrays.asList("Model", "View", "Controller");
presenter.onFinished(items);
verify(view, times(1)).setItems(items);
verify(view, times(1)).hideProgress();
}
} |
18358222_9 | class MessageService {
public List<Message> getMessagesMatchingFilter(MessageFilter filter) {
Date calcFromDate = Optional.ofNullable(filter.getFromDate()).orElse(startOfDay());
Date calcToDate = Optional.ofNullable(filter.getFromDate()).orElse(endOfDay());
Integer calcPage = Optional.ofNul... | MessageFilter filter = new MessageFilter();
when(messageRepository.findByDateBetweenAndDirectionIn(
notNull(),
notNull(),
directionsCaptor.capture(),
pageableCaptor.capture())
).thenReturn(singleResult());
assertHasSingleR... |
18369808_1 | class BRITWalletId {
public byte[] getBytes() {
return Arrays.copyOf(britWalletId, britWalletId.length);
}
public BRITWalletId(byte[] seed);
public BRITWalletId(String britWalletIdInHex);
@Override public String toString();
@Override public boolean equals(Object o);
@Override public int hashCode... | SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator();
byte[] seed = seedGenerator.convertToSeed(Bip39SeedPhraseGenerator.split(SEED_PHRASE_2));
BRITWalletId walletId = new BRITWalletId(seed);
assertThat(walletId).isNotNull();
assertThat(walletId.getBytes()).isNotNull();
String wa... |
18369848_20 | class LayerDistributor implements Serializable {
public List<List<Double>> distribute(final List<SectionData> sectionDataList) {
final List<LayerData> layerList = groupSectionsByZ(sectionDataList);
Collections.sort(layerList); // sort layers by tile count
bucketList = bucketLayers(layerLi... |
final int numberOfBuckets = 3;
final List<Long> tileCounts = LongStream.of(10, 10, 30, 28, 7, 9).boxed().collect(Collectors.toList());
// should be distributed as: | 30 | 28, 7 | 10, 10, 9 |
final List<SectionData> sectionDataList = new ArrayList<>();
double z = 1.0;
f... |
18379456_33 | class DnssecClient extends ReliableDnsClient {
public DnssecQueryResult queryDnssec(CharSequence name, TYPE type) throws IOException {
Question q = new Question(name, type, CLASS.IN);
return queryDnssec(q);
}
public DnssecClient();
public DnssecClient(DnsCache cache);
@Override ... | DnssecClient client = constructDnssecClient();
applyZones(client,
signedRootZone(
sign(rootKSK, "", rootPrivateKSK, algorithm,
record("", rootKSK),
record("", rootZSK)),
sign(r... |
18394987_39 | class AbstractTemplateOutputBuilder extends AbstractOutputBuilder {
protected JtwigModel createModel(AbstractTestDataEntity abstractTestDataEntity) {
JtwigModel model = JtwigModel.newModel()
.with(TEST_DATA_ENTITY.getName(), abstractTestDataEntity)
.with(SAKULI_PROPERTIES.ge... | JtwigModel model = testling.createModel(testSuite);
assertEquals(model.get(TEST_DATA_ENTITY.getName()).get().getValue(), testSuite);
assertEquals(model.get(SAKULI_PROPERTIES.getName()).get().getValue(), sakuliProperties);
assertEquals(model.get(CHECK_MK_PROPERTIES.getName()).get().getVal... |
18409234_18 | class Timestamps {
public static String format(long timestampMillis) {
return FORMATTER.format(LocalTime.ofNanoOfDay(timestampMillis % (24 * 60 * 60 * 1000) * 1_000_000));
}
private Timestamps();
}
class TimestampsTest {
@Test
public void testFirstMidnight() {
| long timestampMillis = 0L;
assertEquals("00:00:00.000", Timestamps.format(timestampMillis));
}
} |
18419894_75 | class ScriptParserImpl implements ScriptParser {
public <T extends AstRegion> T parseWithStrategy(String input, ScriptParseStrategy<T> strategy)
throws ScriptParseException {
T result = null;
int newStart = 0;
int newEnd = input.length();
CharStream ais = CharStreams.f... |
String script =
"# tcp.client.accept-then-close\n" +
"accept 'tcp://localhost:7788'\n" +
"accepted\n" +
"connected\n" +
"close\n" +
"closed\n";
ScriptParserImpl parser = new ScriptParserImpl();
AstS... |
18433849_10 | class GameActivity extends RoboFragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {
public void chooseBox(View view){
String boxIdString = getResources().getResourceEntryName(view.getId());
int boxId = Integer.parseInt(boxIdString.substring(boxIdString.length() - 1));
ToeStr... | when(toeGame.getTurn()).thenReturn(GameSymbol.O);
Button button = Mockito.mock(Button.class);
when(button.getId()).thenReturn(R.id.box_8);
activity.chooseBox(button);
ToeStrategy expectedStrategy = new ToeStrategyExplicit(8, GameSymbol.O);
verify(toeGame).chooseBox(any(... |
18451768_22 | class FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection {
public boolean isConnecting() {
return serviceConnectionManager.isConnecting();
}
public FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager,
Fu... | api.isConnecting();
verify(connectionManager).isConnecting();
}
} |
18473213_0 | class XeroClient {
protected static <T> T unmarshallResponse(String responseBody, Class<T> clazz) {
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
Source source = new StreamSource(new ByteArrayInputStream(responseBody.getByt... | String xml = getResourceAsString("create-invoice-response.xml");
ResponseType response = XeroClient.unmarshallResponse(xml, ResponseType.class);
Assert.assertNotNull(response);
}
} |
18495485_110 | class PublisherEuropeanaDao {
public List<SourceDocumentReferenceMetaInfo> retrieveMetaInfo(final Collection<String> sourceDocumentReferenceIds) {
if (null == sourceDocumentReferenceIds || sourceDocumentReferenceIds.isEmpty()) {
return Collections.EMPTY_LIST;
}
LOG.debug(Logging... | assertTrue(europeanaDao.retrieveMetaInfo(Collections.EMPTY_LIST).isEmpty());
}
} |
18499671_0 | class RawXJC2Mojo extends AbstractXJC2Mojo<O> {
void collectBindingUrisFromArtifact(File file, List<URI> bindingUris) throws MojoExecutionException {
try (JarFile jarFile = new JarFile(file))
{
final Enumeration<JarEntry> jarFileEntries = jarFile.entries();
while (jarFileEntries.hasMoreElements()) {
Jar... | List<URI> bindings = new ArrayList<>();
final RawXJC2Mojo<Void> mojo = new RawXJC2Mojo<Void>() {
@Override
protected OptionsFactory<Void> getOptionsFactory() {
throw new UnsupportedOperationException();
}
@Override
public void doExecute(Void options) throws MojoExecut... |
18500436_4 | class YtsClient {
public UserModule user() {
if (userModule == null) {
throw new IllegalStateException("User module not loaded. Call YtsClient.Builder.withUser() ");
}
return userModule;
}
private YtsClient();
public BookmarkModule bookmarks();
public CommentM... | client = new YtsClient
.Builder()
.withUser()
.build();
assertNotNull(client);
assertNotNull(client.user());
assertBookmarksModuleException(client);
assertCommentModuleException(client);
assertMoviesModuleException(client);... |
18506893_7 | class JavaToJavaccDependencyAction implements Action<Project> {
@Override
public void execute(Project project) {
if (!project.getPlugins().hasPlugin("java")) {
return;
}
configureCompileJJTreeTask(project);
configureCompileJavaccTask(project);
}
private voi... | project = Mockito.mock(Project.class, Answers.RETURNS_MOCKS.get());
JavaToJavaccDependencyAction action = new JavaToJavaccDependencyAction();
action.execute(project);
Mockito.verify(project).getPlugins();
Mockito.verifyNoMoreInteractions(project);
}
} |
18511687_47 | class SystemProperty {
public String getPlugin() {
return plugin;
}
private SystemProperty(final Builder<T> builder);
private static Stream<Object> getObjectStream(final String value, final SystemProperty systemProperty);
public static Collection<SystemProperty> getProperties();
@Sup... |
final SystemProperty<Long> longProperty = SystemProperty.Builder.ofType(Long.class)
.setKey("a-plugin-property")
.setDefaultValue(42L)
.setPlugin("TestPluginName")
.setDynamic(false)
.build();
assertThat(longProperty.getPlugin(), is("TestPlug... |
18512985_3 | class WordSequence implements Comparable<WordSequence> {
public static WordSequence asWordSequence(final Dictionary dictionary,
String... words) {
Word[] dictWords = new Word[words.length];
for (int i = 0; i < words.length; i++) {
dictWords[i] = dictionary.getWord(words[i]);... | assertThat(asWordSequence(dictionary, "one"),
lessThan(asWordSequence(dictionary, "two")));
assertThat(asWordSequence(dictionary, "one"),
lessThan(asWordSequence(dictionary, "one", "two")));
assertThat(asWordSequence(dictionary, "one", "two"),
less... |
18516668_30 | class AbstractConnectionSpecFactory implements ConnectionSpecFactory {
protected ConnectionSpec newConnectionSpecInstance(final Class<?> connectionSpecClass,
final Class<?>[] constructorParameterTypes,
fin... | TestConnectionSpecImpl spec = (TestConnectionSpecImpl)
factory.newConnectionSpecInstance(
TestConnectionSpecImpl.class,
new Class<?>[]{int.class, String.class},
new Object[]{4711, "property2"});
assertThat(spec.prop... |
18532549_1 | class SoupBinTCPSession implements Closeable {
public int receive() throws IOException {
int bytes = channel.read(rxBuffer);
if (bytes <= 0)
return bytes;
rxBuffer.flip();
while (parse());
rxBuffer.compact();
receivedData();
return bytes;
... | loginRejected.rejectReasonCode = SoupBinTCP.LOGIN_REJECT_CODE_NOT_AUTHORIZED;
server.reject(loginRejected);
while (clientStatus.collect().size() != 1)
client.receive();
assertEquals(asList(new LoginRejected(SoupBinTCP.LOGIN_REJECT_CODE_NOT_AUTHORIZED)),
cli... |
18559877_1 | class CaptchaNoJsHtmlParser {
public void parseChallengeTitle(
String responseHtml,
CaptchaInfo captchaInfo
) throws CaptchaNoJsV2ParsingError {
Matcher matcher = challengeTitlePattern.matcher(responseHtml);
if (!matcher.find()) {
throw new CaptchaNoJsV2Parsi... | for (int i = 0; i < inputDataList.size(); ++i) {
String inputData = inputDataList.get(i);
CaptchaInfo captchaInfo = new CaptchaInfo();
parser.parseChallengeTitle(inputData, captchaInfo);
String title = captchaInfo.captchaTitle.getTitle();
assertEquals... |
18560435_15 | class ModifiedVariable implements Variable, Cloneable {
@Override
public String getSyntaxString() {
log.trace("syntax string of variable {} will be retrieved", variable);
return variable.getSyntaxString();
}
public ModifiedVariable(final Variable variable, final List<VariableModifier>... | assertEquals(modifiedVariable.getSyntaxString(), variable.getSyntaxString());
}
} |
18610267_4 | class EventService {
public EventHandlerStatus dispatchEvent(HttpServletRequest httpRequest) {
ApiContext apiContext = new MozuApiContext(httpRequest);
Event event = null;
// get the event from the request and validate
try {
String body = IOUtils.toString(httpRequest.ge... | final String jsonString = deletedEventJson();
new Expectations() {
{ mockHttpServletRequest.getHeader(Headers.X_VOL_TENANT_DOMAIN); result=TENANT_URL; }
{ mockHttpServletRequest.getHeader(Headers.X_VOL_SITE_DOMAIN); result=SITE_URL; }
{ mockHttpServletRequest.getIntH... |
18627126_85 | class PropagateErrorsDownloadPolicy extends AbstractPolicy implements DownloadErrorPolicy {
@Override
public boolean applyPolicy( PolicyOption policySetting, Properties request, StorageAsset localFile, Exception exception,
Map<String, Exception> previousExceptions )
thro... | DownloadErrorPolicy policy = lookupPolicy();
StorageAsset localFile = getFile();
Properties request = createRequest();
Exception ex = new RuntimeException();
Map<String, Exception> exMap = new HashMap<>();
assertFalse(policy.applyPolicy( PropagateErrorsDownloadPolicy.IG... |
18641766_9 | class IOUtil {
public static void writeInt(OutputStream output, int value) throws IOException {
byte[] writeBuffer = new byte[4];
writeBuffer[0] = (byte) (value & 0xFF);
writeBuffer[1] = (byte) ((value>>8) & 0xFF);
writeBuffer[2] = (byte) ((value>>16) & 0xFF);
writeBuffer[3] = (byte) ((value>>24) & 0xFF);
... | try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
IOUtil.writeInt(bout, 3);
IOUtil.writeInt(bout, 4);
IOUtil.writeInt(bout, 0xFF0000AA);
IOUtil.writeInt(bout, 0xAABBCCDD);
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
long a = IOUtil.readInt(bi... |
18672634_8 | class ProductResource {
@GET
@Path("{productId}")
public ProductDto getProduct(@PathParam("productId") String productId) {
Product product = productRepository.getProduct(productId);
if (product == null) {
throw new IllegalArgumentException("No such product: " + productId);
}
logger.info("Re... |
String bookId = UUID.randomUUID().toString();
Book book = new Book(bookId, "1234567890", "Book Title", "");
String productId = UUID.randomUUID().toString();
Product product = new Product(productId, book, 1000L, null);
when(productRepository.getProduct(productId)).thenReturn(product);
ProductDt... |
18693684_0 | class TitleBuilder extends UpdateBuilder {
public String buildCondensed() {
String title = "";
if(validNotificationsResponse() && validInboxResponse()) {
title = resources.getString(R.string.message_condensed, inboxResponse.count);
title += " ";
title += resource... | String title = "Mail: 0 Updates: 0";
InboxResponse inboxResponse = createInboxResponse(0);
NotificationsResponse notificationsResponse = createNotificationResponse(0);
TitleBuilder titleBuilder = new TitleBuilder(notificationsResponse, inboxResponse, resources);
assertEquals(titl... |
18709657_13 | class ViManager implements ViNodeSet {
@Override
public synchronized ViNode node(String namePattern) {
ensureAlive();
if (liveNodes.containsKey(namePattern)) {
return liveNodes.get(namePattern);
}
else if (deadNodes.containsKey(namePattern)) {
return deadNodes.get(namePattern);
}
else if (dynamicSe... | try {
man.node("aa").exec(new ExceptionalRunnable());
} catch (Exception e) {
e.printStackTrace();
ArithmeticException exception = (ArithmeticException) e;
// expect that exception not changed
boolean found = false;
for (StackTrace... |
18749529_0 | class FaultInfoBuilder {
public static StepFaultCause blame(Blame blame) {
return new Builder(blame);
}
}
class FaultInfoBuilderTest {
@Test
public void testBlame() throws Exception {
| FaultInfo faultInfo = FaultInfoBuilder
.blame(Blame.CLIENT)
.faultCause("InvalidInput")
.applicationErrorCode(null)
.message("Invalid input")
.retrySameLocation(Retry.no())
.retryOtherLocations(Retry.no())
... |
18759272_59 | class CurrentClient {
public ClosedConnectionReport closeConnections(CloseType closeType) {
return closeConnectionsByUrl(closeType, "");
}
private CurrentClient(String host, int port, int socketTimeout);
public static CurrentClientBuilder builder();
public ConnectionReport getConnections... | //given
stubFor(delete(urlEqualTo(connectionsUrl + "?type=reset")).willReturn(aResponse().withBody("{\n"
+ " \"closed_connections\": [{\n"
+ " \"host\": \"127.0.0.1\",\n"
+ " \"port\": 57518\n"
+ " }, {\n"
+ " \"host\": \"127.0.0.1\"... |
18774289_3 | class MerkleTree {
public Leaf rightLeaf()
{
return (rightLeaf);
}
public MerkleTree(MessageDigest md);
private byte[] digest(Leaf leaf);
public void add(final MerkleTree leftTree, final MerkleTree rightTree);
public void add(final Leaf leftLeaf, final Leaf rightLeaf);
public MerkleTree leftTree();
publi... | Leaf rightLeaf = leafTree.rightLeaf();
assertTrue(rightLeaf.toString().equals(rightLeafString));
}
} |
18778871_50 | class AccountReceivableEntryListener {
@EventHandler
public void handleCreated(AccountReceivableFeeCreatedEvent event) {
AccountReceivableFeeEntry entry = new AccountReceivableFeeEntry();
entry.copy(event);
repository.save(entry);
}
@EventHandler public void handleConfirmed(Acc... | FeeId feeId = new FeeId();
FeeStatus feeStatus = FeeStatus.PENDING;
BigMoney amount = BigMoney.parse("BTC 30");
FeeType feeType = FeeType.PAY_COIN;
Date dueDate = new Date();
Date businessCreationTime = new Date();
String portfolioId = "portfolioId";
Strin... |
18817575_7 | class OsgiModelSource {
@Override
public int hashCode() {
return this.hashCode;
}
public OsgiModelSource(ModelDefinition<T> modelDefinition, ResourceModelFactory factory, Bundle bundle);
public T getModel(ContentToModelMappingCallback<T> callback);
public Class<?> getModelType();
... | OsgiModelSource<?> one = new OsgiModelSource<>(modelDefinition("one"), mock(ResourceModelFactory.class), this.bundleOne);
OsgiModelSource<?> two = new OsgiModelSource<>(modelDefinition("one"), mock(ResourceModelFactory.class), this.bundleOne);
assertThat(one.hashCode()).isEqualTo(two.hashCode()... |
18826763_2 | class PersonCollector {
public List<Person> getValidPeople() {
return validPeople;
}
public PersonCollector(PersonValidator personValidator);
public void addPerson(Person person);
PersonCollector personCollector;
}
class PersonCollectorTest {
PersonCollector personCollector;
@Test
public void perso... | assertEquals(0, personCollector.getValidPeople().size());
}
} |
18830102_391 | class JsonPropertyDeserializer {
public Map<String, Object> readPropertyStandalone(JsonReader reader, final EdmProperty edmProperty,
final DeserializerProperties readProperties) throws EntityProviderException {
return readPropertyStandalone(reader, EntityInfoAggregator.create(edmProperty), readProperties);... | String simplePropertyJson = "{\"d\":{\"Age\":67}}";
JsonReader reader = prepareReader(simplePropertyJson);
final EdmProperty edmProperty =
(EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age");
DeserializerProperties readProperties = mock(Deserializer... |
18830782_0 | class UserRetriever {
public void retrieveUser(final UserCallback callback) {
mExecutor.execute(new RetrieveUserTask(callback));
}
public UserRetriever(final WebService webService, final AsyncTaskExecutor executor);
}
class UserRetrieverTest {
@Test
public void retrieveUser_retrievesUser_andNotifies... | /* Given */
User user = new User();
WebService webService = mock(WebService.class);
when(webService.retrieveUser()).thenReturn(user);
UserRetriever.UserCallback callback = mock(UserRetriever.UserCallback.class);
UserRetriever userRetriever = new UserRetriever(webService, TestAsyncTaskExecutor... |
18831720_2 | class ListUtil {
public static String join(Collection c) {
return join(c, ", ");
}
public static String join(Collection c, String join);
}
class ListUtilTest {
@Test
public void shouldJoinAListUsingComma(){
| ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
assertThat(ListUtil.join(list), is("a, b, c"));
}
} |
18871700_92 | class FreeformQuery extends AbstractTransactionalQuery implements
QueryDelegate {
@Override
@SuppressWarnings("deprecation")
public boolean containsRowWithKey(Object... keys) throws SQLException {
String query = null;
boolean contains = false;
if (delegate != null) {
... | FreeformQuery query = new FreeformQuery("SELECT * FROM people",
Arrays.asList("ID"), connectionPool);
Assert.assertFalse(query.containsRowWithKey(38796));
}
} |
18894744_18 | class JavascriptObject {
protected Object invokeJavascript(String function) {
return checkUndefined(jsObject.call(function));
}
protected JavascriptObject();
protected JavascriptObject(String type);
protected JavascriptObject( String type, String stringRepresentation );
protected J... | String arg = "myArg";
Object[] argArray = new Object[] {arg};
String function = "myFunction";
String result = "result";
when(mockJsObject.call(function, argArray)).thenReturn(result);
Object returnValue = testJavascriptObject.invokeJavascript(function, arg);
... |
18907185_6 | class ValueShardedJedis extends Sharded<Jedis, JedisShardInfo> implements JedisCommands {
@Override
public Long incrBy(String key, long integer) {
Long result = 0L;
if (this.exists(key)) {
Long newValue = Long.valueOf(this.get(key)).longValue() + integer;
this.del(key);
this.set(key, newValue.toString()... | assertEquals(shardedJedis.incrBy("string:decrby", 5).longValue(), 5L);
assertEquals(shardedJedis.incrBy("string:decrby", 5).longValue(), 10L);
}
} |
18910111_9 | class FormValidator {
public static ValidationResult isValid(Form form) {
if (form == null) {
throw new IllegalAddException("Arugment cannot be null");
}
Class<? extends Object> type = form.getClass();
String key = type.getName();
ValidatorContianer contianer = c... | MockForm form = new MockForm();
form.setEmail("zxc@msun.com");
form.setPassword("hello1234");
ValidationResult valid = FormValidator.isValid(form);
System.out.println(valid);
assertTrue(valid.isValid());
assertFalse(valid.isFieldError("email"));
}
} |
18912218_12 | class Capsule implements Runnable, InvocationHandler {
static List<String> expandArgs(List<String> args0, List<String> args) {
final List<String> args1 = new ArrayList<String>();
boolean expanded = false;
for (String a : args0) {
if (a.startsWith("$")) {
if (a.eq... | assertEquals(list("x", "y", "z"), Capsule.expandArgs(list("x", "y", "z"), CapsuleTest.<String>list()));
assertEquals(list("a", "b", "c"), Capsule.expandArgs(CapsuleTest.<String>list(), list("a", "b", "c")));
assertEquals(list("x", "y", "z", "a", "b", "c"), Capsule.expandArgs(list("x", "y", "z"),... |
18942355_240 | class AbstractEventList implements EventList<E> {
@Override
public void replaceAll(UnaryOperator<E> operator) {
updates.beginEvent(true); // nested due to set below
for (int i = size() - 1; i >= 0; i--) {
E oldValue = get(i);
E newValue = operat... | AbstractEventList<String> list = new AbstractEventList<String>() {
@Override
public int size() {
return 1;
}
@Override
public String get(int index) {
if (index != 0) throw new IndexOutOfBoundsException("Wha??");
... |
18948102_0 | class FixSaxParser implements BytesSaxParser {
@Override
public void parse(Bytes bytes) {
long limit = bytes.readLimit(), limit2 = limit;
while (limit2 > bytes.readPosition() && bytes.readByte(limit2 - 1) != FIELD_TERMINATOR)
limit2--;
bytes.readLimit(limit2);
while... | String s = "8=FIX.4.2|9=130|35=D|34=659|49=BROKER04|56=REUTERS|52=20070123-19:09:43|38=1000|59=1|100=N|40=1|11=ORD10001|60=20070123-19:01:17|55=HPQ|54=1|21=2|10=004|";
Bytes bbb = Bytes.from(s.replace('|', '\u0001'));
final StringBuilder sb = new StringBuilder();
FixSaxParser parser = ne... |
18974940_126 | class AccountController {
public String getWebClientId() {
return mAppConfig.getString("appspot_webClientId");
}
@Inject public AccountController(
SharedPreferences preferences,
AccountManager accountManager,
AppConfig appConfig,
String accountType)... | mAccountController.getWebClientId();
verify(mAppConfig).getString("appspot_webClientId");
}
} |
18982942_19 | class WayHelper {
public static List<Node> isParallel(final List<Node> aFirstWay, final List<Node> aSecondWay) {
ArrayList<Node> aFirstWayCopy = new ArrayList<Node>(aFirstWay);
ArrayList<Node> aSecondWayCopy = new ArrayList<Node>(aSecondWay);
List<Node> retval = isParallelInternal(aFirstWa... | Node start = new Node(1, 1, new Date(), null, 0, 1.0, 5.0);
Node testStart = new Node(2, 1, new Date(), null, 0, 1.00001, 5.0);
Node end = new Node(3, 1, new Date(), null, 0, 1.0, 10.0);
Node afterEnd = new Node(4, 1, new Date(), null, 0, 1.0, 20.0);
Node testEnd = n... |
18997610_32 | class ClasspathHelper {
public static String loadFileFromClasspath(String location) {
InputStream inputStream = ClasspathHelper.class.getResourceAsStream(location);
if(inputStream == null) {
inputStream = ClasspathHelper.class.getClassLoader().getResourceAsStream(location);
}
... | final String contents = ClasspathHelper.loadFileFromClasspath("classpathTest.txt");
assertEquals(contents, "How now brown cow?");
}
} |
19008038_65 | class OwlApiUtils {
public static String getIri(OWLDeclarationAxiom expression) {
return expression.getEntity().getIRI().toString();
}
public static Optional<Object> getTypedLiteralValue(OWLLiteral literal);
static String hash(String input);
public static String getIri(OWLClassExpression expression);
... | String ontologyIri = "http://x.org/ontology";
OWLOntology ontology = manager.createOntology(IRI.create(ontologyIri));
assertThat(OwlApiUtils.getIri(ontology), is(ontologyIri));
}
} |
19024198_201 | class HttpRequestEncoder extends HttpObjectEncoder<HttpRequest> {
@Override
protected void encodeInitialLine(ByteBuf buf, HttpRequest request) throws Exception {
request.getMethod().encode(buf);
buf.writeByte(SP);
// Add / as absolute path if no is present.
// See http://tools.... | HttpRequestEncoder encoder = new HttpRequestEncoder();
ByteBuf buffer = Unpooled.buffer(64);
encoder.encodeInitialLine(buffer, new DefaultHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.GET, "/"));
String req = buffer.toString(Charset.forName("US-ASCII"));
assertEqua... |
19062268_150 | class ImmutableMediaType implements MediaType {
@Override
public Map<String,String> parameters() {
return this.parameters;
}
ImmutableMediaType(final MediaRangeSyntax syntax, final String type, final String subtype, String suffix, final Map<String, String> parameters);
@Override public String type();
@Over... | ImmutableMediaType sut=new ImmutableMediaType(MediaRangeSyntax.RFC7230,"type","subtype",null,null);
assertThat(sut.parameters(),notNullValue());
assertThat(sut.parameters().isEmpty(),equalTo(true));
}
} |
19067639_125 | class WebHookPayloadManager {
public Boolean isRegisteredFormat(String format){
return formats.containsKey(format.toLowerCase());
}
public WebHookPayloadManager(SBuildServer server);
public void registerPayloadFormat(WebHookPayload payloadFormat);
public WebHookPayload getFormat(String formatShortname);
pub... | assertEquals(true, manager.isRegisteredFormat("one"));
assertEquals(false, manager.isRegisteredFormat("none"));
}
} |
19069584_1 | class VariablesResolver {
public static String replaceAllVariables(String strVars) {
return replaceAllVariables(strVars, null);
}
private VariablesResolver();
public static void configure(Properties props);
public static void configure();
public static URL getVariablessUrl();
sta... |
assertFalse(VariablesResolver.containsVariable("novariable"));
assertFalse(VariablesResolver.containsVariable("$(varTest"));
assertTrue(VariablesResolver.containsVariable("$(varTest)"));
assertTrue(VariablesResolver.containsVariable("a string $(varTest) with variable"));
assertT... |
19076996_898 | class EndpointHelper {
public static Endpoint lookupEndpoint(EndpointKey epKey, ReadOnlyTransaction transaction) {
Optional<Endpoint> optionalEp =
readFromDs(LogicalDatastoreType.OPERATIONAL, endpointIid(epKey.getL2Context(), epKey.getMacAddress()),
transaction);
if (op... | when(readOptional.isPresent()).thenReturn(true);
when(readOptional.get()).thenReturn(endpoint);
Endpoint result = EndpointHelper.lookupEndpoint(epKey, readTransaction);
assertEquals(result, endpoint);
}
} |
19097627_21 | class GravityAttributeProcessor extends AttributeProcessor<V> {
@Override
public Value compile(@Nullable Value value, Context context) {
if (null == value) {
return NO_GRAVITY;
}
return ParseHelper.getGravity(value.getAsString());
}
@Override public void handleValue(V view, Value value);
@... | AttributeProcessor processor = new GravityAttributeProcessor() {
@Override
public void setGravity(View view, @Gravity int gravity) {
}
};
Value value = processor.compile(new Primitive("top|left"), null);
int gravity = Gravity.TOP | Gravity.LEFT;
assertThat(value.getAsInt(), is(gr... |
19097773_39 | class DateUtil {
public static Date parse(String dateString, String format) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false);
Date date = sdf.parse(dateString);
return date;
} catch (Exception e) {
LOGGER.... | String formatString = "yyyy-MM-dd HH:mm:ss";
String dateString = "2015-01-22 01:44:50";
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2015);
c.set(Calendar.MONTH, 0);
c.set(Calendar.DAY_OF_MONTH, 22);
c.set(Calendar.HOUR_OF_DAY, 01);
c.set(Calendar.MINU... |
19116210_36 | class OrgMatchingItemProcessor extends BaseItemProcessor implements ItemProcessor<OrgData, OrgData> {
@Override
public OrgData process(OrgData input) throws Exception {
ServiceContext context = getServiceContext();
List<ValidationError> errors = Lists.newArrayList();
if (StringUtils.isBlank(input.getOrg().getO... | FieldSet fieldSet = new DefaultFieldSet(OrgLineTokenizer.COL_NAMES, OrgLineTokenizer.COL_NAMES);
orgData.setFieldSet(fieldSet);
Mockito.when(
organizationService.getMatch(org.mockito.Matchers.any(ServiceContext.class),
org.mockito.Matchers.any(Org.class))).thenReturn(null);
Map<String, String> asMap =... |
19141372_0 | class SipInvite {
boolean hasRemotePartyId() {
return remotePartyId != null;
}
SipInvite(String packet);
private CallerInformationHeader extractFromLikeHeader(String header);
boolean hasPAssertedIdentity();
CallerInformationHeader getPAssertedIdentity();
CallerInformationHead... | assertTrue(new SipInvite(INVITE_PACKET_WITH_REMOTE_PARTY_ID).hasRemotePartyId());
assertFalse(new SipInvite(INVITE_PACKET_WITHOUT_REMOTE_PARTY_ID).hasRemotePartyId());
}
} |
19169174_57 | class JSONArrayRequestDecorator extends RequestDecorator<T> {
@NonNull
public String getElementsKey() {
return elementsKey;
}
public JSONArrayRequestDecorator(@NonNull final Request<T> request, @NonNull final String elementsKey);
@Override protected Response<T> parseNetworkResponse(final NetworkResponse resp... | assertEquals(ELEMENTS_KEY, decorator.getElementsKey());
}
} |
19253642_1 | class BDecoder {
public static BEValue bdecode(InputStream in) throws IOException {
return new BDecoder(in).bdecode();
}
public BDecoder(InputStream in);
public byte[] get_special_map_digest();
public void set_special_map_name(String name);
public int getNextIndicator();
public B... | try {
FileInputStream in = null;
in = new FileInputStream(f);
Map m = new BDecoder(in).bdecode().getMap();
BEValue val = (BEValue) m.get("minId");
if (val == null) {
throw new InvalidBEncodingException("minId");
}
... |
19260634_12 | class AdapterItemBinding {
public int getLayoutResourceId() {
return mLayoutResourceId;
}
public AdapterItemBinding(final int layoutResourceId);
public AdapterItemBinding(final int layoutResourceId, final Binding binding);
public AdapterItemBinding(final int layoutResourceId, final Set<... | AdapterItemBinding adapterItemBinding = new AdapterItemBinding(1);
int layoutResourceId = adapterItemBinding.getLayoutResourceId();
assertThat(layoutResourceId).isEqualTo(1);
adapterItemBinding = new AdapterItemBinding(2, new TextBinder(0,new ViewModelColumn("TABLE_NAME", "COLUMN_NAME",... |
19260719_0 | class CacHookingAgent {
static void processArgs(String args, Config config) {
String[] split = args.split(",\\s*");
for (String s : split) {
if (s.equals("debug")) {
DEBUG = true;
}
if (s.equals("tty")) {
config.setTty(true);
}
if (s.startsWith("context=")) {
CONTEXT = s.replace("contex... | Config config = new Config();
CacHookingAgent.processArgs("", config);
assertEquals(false, CacHookingAgent.DEBUG);
assertEquals("TLS", CacHookingAgent.CONTEXT);
CacHookingAgent.processArgs("load,debug,context=SSLv3", config);
assertEquals(true, CacHookingAgent.DEBUG);
assertEquals("SSLv3", CacHookingAg... |
19271154_30 | class PriorityQueue implements Iterable<E> {
public abstract E pop()@Nullable
public abstract E pop();
public abstract E pop()public abstract boolean isEmpty();
public abstract E pop()public abstract int size();
public abstract E pop()public abstract E push(@NotNull P priority, @NotNull E value);
... | final PriorityQueue<Priority, String> queue = populateAndCopyQueue();
assertEquals("7", queue.pop());
assertEquals("2", queue.pop());
assertEquals("4", queue.pop());
assertEquals("1", queue.pop());
assertEquals("3", queue.pop());
assertEquals("5", queue.pop());
... |
19276770_0 | class UUID {
private UUID() {
}
private UUID();
public static String uuid();
private static int randomInt(int radix);
private static final Pattern UUID_PATTERN;
}
class UuidTest {
private static final Pattern UUID_PATTERN;
@Test
public void uuid() {
| for (int i = 0; i < 100; i++) {
String id = UUID.uuid();
assertNotNull(id);
assertTrue(UUID_PATTERN.matcher(id).matches());
}
}
} |
19308274_7 | class PumlLineParser {
void parseLine(final String line) {
if(line == null) return;
String normalizedLine = line.trim().toLowerCase();
// inlcudes cannot be handled because of working directory mismatch while scanning
if(normalizedLine.startsWith("!include")) {
return;... | final String asciidoc = "=== Level 1\n" +
"\n" +
"\n" +
"The following diagram shows the main building blocks of the system and their interdependencies:\n" +
"\n" +
... |
19317653_20 | class CloudantToDo {
public boolean isCompleted() {
return completed;
}
public CloudantToDo();
public CloudantToDo(ToDo td);
public String get_id();
public void set_id(String _id);
public String get_rev();
public void set_rev(String _rev);
public String getTitle();
public void setTitle(Stri... | CloudantToDo ctd = new CloudantToDo(td);
assertFalse(ctd.isCompleted());
ctd = new CloudantToDo();
ctd.setCompleted(true);
assertTrue(ctd.isCompleted());
}
} |
19351480_28 | class JenkinsJobProperty extends AbstractJenkinsProperty {
public List<String> getPathComponents() {
return Arrays.asList(withFolders(job).split("/job/"));
}
public JenkinsJobProperty(JenkinsConfiguration configuration, String job);
public String getUrl();
private String withFolders(Stri... | JenkinsJobProperty property = new JenkinsJobProperty(
new JenkinsConfiguration("Test", "http://jenkins", "", ""),
"test/job/test-master/job/test-master-build"
);
assertEquals(Arrays.asList("test", "test-master", "test-master-build"), property.getPathComponents());... |
19361874_2 | class HelloAppEngine extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/plain");
response.getWriter().println("Hello App Engine - Flexible!");
}
public static String getInfo();
private... | servletUnderTest.doGet(mockRequest, mockResponse);
// We expect our hello world response.
assertThat(responseWriter.toString())
.named("HelloAppEngine response")
.contains("Hello App Engine - Flexible!");
}
} |
19367053_0 | class RelativeRootMeanSquaredErrorMT extends AbstractMultiTargetErrorMeasurer {
@Override
public double getCurrentError() {
if(weightSeen==0)
return Double.MAX_VALUE;
else
{
double sum=0;
int numOutputs=sumSquaredError.length;
for (int i=0; i<numOutputs; i++)
sum+=Math.sqrt(sumSquaredError[i]/s... | assertEquals(0.9402350854416155, m.getCurrentError(), 0.0000001);
}
} |
19368221_328 | class TemplateProcessor {
public static String processTemplateContents(String templateContents, EntityDriver driver, Map<String,? extends Object> extraSubstitutions) {
return processTemplateContents(templateContents, new EntityAndMapTemplateModel(driver, extraSubstitutions));
}
protected static Te... | mgmt.getBrooklynProperties().put("global.mykey", "myval");
String templateContents = "${mgmt['global.mykey']}";
String result = TemplateProcessor.processTemplateContents(templateContents, app, ImmutableMap.<String,Object>of());
assertEquals(result, "myval");
}
} |
19370824_2 | class GenericCoverageSensor implements Sensor {
@Override
public boolean shouldExecuteOnProject(Project project) {
return StringUtils.isNotEmpty(coverageReportPath(null)) || StringUtils.isNotEmpty(itReportPath()) ||
StringUtils.isNotEmpty(overallReportPath()) || StringUtils.isNotEmpty(unitTestReportPath(... | configureOldReportPath("coverage.xml");
assertThat(sensor.shouldExecuteOnProject(project)).isTrue();
}
} |
19383958_20 | class SpreadsheetSnippets {
public BatchUpdateSpreadsheetResponse pivotTables(String spreadsheetId) throws IOException {
Sheets service = this.service;
// Create two sheets for our pivot table.
List<Request> sheetsRequests = new ArrayList<>();
sheetsRequests.add(new Request().setAd... | String spreadsheetId = this.createTestSpreadsheet();
BatchUpdateSpreadsheetResponse result = this.snippets.pivotTables(spreadsheetId);
assertNotNull(result);
}
} |
19394307_2 | class LongPreference extends AbsPreference<Long> {
@Override public Long get() {
return getPreferences().getLong(getKey(), getDefaultValue());
}
public LongPreference(SharedPreferences preferences, String key);
public LongPreference(SharedPreferences preferences, String key, long defaultValue);
@Over... | // Arrange
long expected = 2;
String key = "testKey2";
preferences.edit().putLong(key, expected).commit();
LongPreference preference = new LongPreference(preferences, key);
// Act
long result = preference.get();
// Assert
assertThat(result).isEqualTo(expected);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.