id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
618103_0 | class DataRetrieverTask extends AsyncTask<String, String, Void> {
@Override
protected Void doInBackground(final String... args) {
errors = new ArrayList<>();
List<Bank> banks;
if (bankId != -1) {
banks = new ArrayList<>();
banks.add(getBankFromDb(bankId, parent))... | Bank bank = Mockito.mock(Bank.class);
Mockito.when(bank.isDisabled()).thenReturn(true);
TestableDataRetrieverTask testMe = new TestableDataRetrieverTask(bank);
testMe.doInBackground();
// Single disabled bank should be updated
Mockito.verify(bank, Mockito.atLeastOnce())... |
618681_8 | class NonBreakPointsLoaderImpl implements NonBreakPointsLoader {
@Override
public List<String> loadNBSP(String lang) {
if (lang == null || lang.isEmpty()) {
throw new IllegalArgumentException("Lang must be filled to search for file!");
}
List<String> result = loadForKey(lang);
if (result == null) {
int... | List<String> lines = new NonBreakPointsLoaderImpl().loadNBSP("de");
assertEquals(1, lines.size());
assertEquals("deRuleščřžýá", lines.get(0)); // tests also UTF-8 chars
}
} |
620505_0 | class ZooKeeperService extends Service {
private List<String> getHosts(List<NodeMetadata> nodes) {
return Lists.transform(Lists.newArrayList(nodes),
new Function<NodeMetadata, String>() {
@Override
public String apply(NodeMetadata node) {
String publicIp = Iterables.get(node.getPublicAddresses(), ... | class ConnectionWatcher implements Watcher {
private ZooKeeper zk;
private CountDownLatch latch = new CountDownLatch(1);
public void connect(String hosts) throws IOException, InterruptedException {
zk = new ZooKeeper(hosts, 5000, this);
latch.await();
}
public ZooKeepe... |
643234_13 | class SauceLabsContextView implements ContextView {
public void show(String scenario, String step) {
sendContextMessage(step);
}
public SauceLabsContextView(WebDriverProvider webDriverProvider);
private void sendContextMessage(String step);
public void close();
private StringBuilder... | shouldBarf = true;
slcv.show("boo!", "oops");
assertThat(script.toString(), Matchers.equalTo(""));
}
} |
651333_3 | class Parser {
public static Expression parse(String text) {
text = text.replaceAll("\\s*,\\s*", ",");
StringTokenizer st = new StringTokenizer(text, "$%,\'[])", true);
MethodExpression root = new MethodExpression("eval");
Stack<MethodExpression> stack = new Stack<MethodExpression>(... | Expression t = Parser.parse("'%artist%'%title%");
s.getTrackData().addArtist("artist here");
s.getTrackData().addTitle("title here");
assertEquals("%artist%title here", t.eval(s));
}
} |
657157_0 | class HebrewQueryParser extends QueryParser {
@Override
public org.apache.lucene.search.Query parse(String query) throws ParseException {
String q = "";
for (int i = 0; i < query.length(); i++) {
if (query.charAt(i) == '"' && i + 1 < query.length() && !Character.isWhitespace(query.c... |
QueryParser qp = new HebrewQueryParser("f", new StandardAnalyzer());
qp.parse("צה\"ל");
qp.parse("\"צהל\"");
qp.parse("כל הכבוד לצה\"ל");
qp.parse("\"כל הכבוד לצה\"ל\"");
qp.parse("\"כל הכבוד\" לצה\"ל");
qp.parse("מנכ\"לית");
try {
qp.parse(... |
662539_11 | class ProductStitcher {
public static void validateSourceProducts(String[] sourceFilePaths) throws IOException {
final int sourceProductLength = sourceFilePaths[0].length();
for (String sourceFilePath : sourceFilePaths) {
if (sourceFilePath.length() != sourceProductLength) {
... | // correct products
String[] inputProducts = new String[]{
"C://test//MER_FRS_CCL2W_20120309_074759_000001893112_00265_52434_0001.nc",
"C://test//MER_FRS_CCL2W_20120309_074740_000000563112_00265_52434_0001.nc",
"C://test//MER_FRS_CCL2W_20120309_075032_0000... |
663418_71 | class StatusCodeTypeAdapter extends RestDataTypeAdapter {
@Override
public String toString(Object obj) {
if(obj==null)
return "null";
if(obj.toString().trim().equals(""))
return "blank";
return obj.toString();
}
@Override public boolean equals(Object r1, Object r2);
@Override public Object parse(Stri... | assertEquals("200", adapter.toString("200"));
assertEquals("blank", adapter.toString(" "));
assertEquals("null", adapter.toString(null));
}
} |
666662_0 | class CyclicCharBuffer {
public void append(char c) {
if (isFull()) {
removeFirst();
}
insertLast(c);
}
public CyclicCharBuffer(int capacity);
public int length();
public char charAt(int i);
private int index(int i);
private boolean isFull();
priva... | CyclicCharBuffer buffer = new CyclicCharBuffer(UNUSED_CAPACITY);
buffer.append('a');
buffer.append('b');
assertHasString("ab", buffer);
}
} |
667236_1 | class AbstractAndroidMojo extends AbstractMojo {
protected String extractPackageNameFromAndroidManifest(File androidManifestFile) throws MojoExecutionException {
final URL xmlURL;
try {
xmlURL = androidManifestFile.toURI().toURL();
} catch (MalformedURLException e) {
... | final URL url = this.getClass().getResource("AndroidManifest.xml");
final URI uri = url.toURI();
final File file = new File(uri);
final String foundTargetPackage = androidMojo.extractPackageNameFromAndroidManifest(file);
Assert.... |
678267_10 | class DateUtility {
public static DateTime parseXSDDateTime(String input) {
Matcher m = XSD_DATETIME.matcher(input);
if (!m.find()) {
throw new IllegalArgumentException(input +
" is not a valid XML Schema 1.1 dateTime.");
}
int year = Integer.parseIn... | String s4 = "-0001-12-31T24:00:00Z";
DateTime dt4 = DateUtility.parseXSDDateTime(s4);
String s5 = "0000-01-01T00:00:00Z";
DateTime dt5 = DateUtility.parseXSDDateTime(s5);
assertTrue(dt4.isEqual(dt5));
}
} |
684382_1 | class VersionCheckUtil {
public static boolean validateMinJREVersion(String runtimeVersion, String minVersion){
String[] requestedVersioning = minVersion.split("\\.");
String[] clientVersioning = runtimeVersion.split("\\.");
if (requestedVersioning.length < 3 || clientVersioning.length < 3)
return false;
... | boolean passed = VersionCheckUtil.validateMinJREVersion("1.8.0_11", "1.7.0_51");
Assert.assertTrue(passed, "The version check should pass.");
}
} |
690050_71 | class UserServiceImpl implements UserService {
protected String generateCode() {
return UUID.randomUUID().toString();
}
@Override @Transactional(readOnly = true) public long countUserForRole(Role role);
@Override @Transactional(readOnly = true) public boolean existsUsername(String username);
... | assertNotNull(impl.generateCode());
}
} |
692484_7 | class GramKeyPartitioner implements Partitioner<GramKey, Gram> {
@Override
public int getPartition(GramKey key, Gram value, int numPartitions) {
// see: http://svn.apache.org/viewvc/hadoop/mapreduce/trunk/src/java/org/apache/hadoop/mapreduce/lib/partition/BinaryPartitioner.java?revision=816664&view=markup
... | byte[] foo = new byte[1];
foo[0] = 1;
foo[0] = 2;
byte[] empty = new byte[0];
GramKey a = new GramKey(new Gram("foo", 1, Gram.Type.HEAD), empty);
GramKey b = new GramKey(new Gram("foo", 1, Gram.Type.HEAD), foo);
byte[] bar = new byte[1];
GramKey c = new GramKey(new Gram("foo", 2, Gram.... |
697210_2 | class CSVReader implements Closeable {
public String[] readNext() throws IOException {
while (recordsQueue.isEmpty() && !eof) {
char[] data = new char[CHUNK_SIZE];
int size = r.read(data);
if (size == -1) {
break;
}
processChunk(da... | String[] files = new String[]{"/com/gooddata/util/crazy.csv", "/com/gooddata/util/crazy.csv.win"};
for (final String f : files) {
Reader reader = new InputStreamReader(
CSVReaderTest.class.getResourceAsStream(f),
"utf8");
CSVReader csv = ne... |
711931_2 | class GalleryComm implements PreferenceNames {
public boolean checkAuth() {
throw new RuntimeException("This method is not available on this protocol");
}
protected GalleryComm(Gallery g, StatusUpdate su);
public void uploadFiles(StatusUpdate su, boolean async);
public void fetchAlbums(StatusUpdate su, boole... | g.setKey("badkey");
g.setUsername("admin");
g.setPassword("admin");
assertTrue(comm.checkAuth());
}
} |
726694_18 | class Node implements INode, IsSerializable {
@Override
public double findMaximumDistanceToLeaf()
{
return this.findMaximumDistanceToLeaf(0.0);
}
public Node(int id, String label);
public Node(Node[] children);
public Node();
@Override public String findLabelOfFirstLeafNode();
@Override public int find... | Node root = new Node();
Node a = new Node();
a.setBranchLength(1.0);
Node b = new Node();
b.setBranchLength(2.0);
Node c = new Node();
c.setBranchLength(1.0);
Node d = new Node();
d.setBranchLength(3.0);
root.addChild(a);
root.addChild(b);
b.addChild(c);
b.addChild(d);
double distan... |
747707_9 | class HexFormatter {
public static void writeBytes(PrintStream print, byte[] bytes) {
writeBytes(print, bytes, 0, bytes.length);
}
public static void writeBytes(PrintStream print, byte[] bytes, int offset, int length);
private static void printLine(PrintStream print, int count, byte[] bytes, i... | writeBytes(print, new byte[]{'a', 0x00, 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't'});
assertEquals("61 00 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 a.cdefgh ijklmnop" + EOL +
"71 72 73 74 qrst" + E... |
749137_19 | class SimpleRestInterceptor extends AtmosphereInterceptorAdapter {
protected static JSONObject parseJsonPart(Reader reader) throws JSONException {
return (JSONObject)(new JSONTokener(reader).nextValue());
}
public SimpleRestInterceptor();
@Override public void configure(AtmosphereConfig conf... | final String data = "{'id': \"123\", \"size\" : 69124, 'ack' : true }";
Reader r = new StringReader(data);
JSONObject jsonpart = SimpleRestInterceptor.parseJsonPart(r);
Map<String, Object> expectedHeaders = new HashMap<String, Object>();
expectedHeaders.put("id", "123");
... |
762097_13 | class QueryBinder {
public static void bind(AnnotationBindingContext bindingContext) {
List<AnnotationInstance> annotations = bindingContext.getIndex().getAnnotations( JPADotNames.NAMED_QUERY );
for ( AnnotationInstance query : annotations ) {
bindNamedQuery( bindingContext.getMetadataImplementor(), query );
... | @NamedNativeQuery(name = "fubar", query = "SELECT * FROM FOO", resultClass = Foo.class)
class Foo {
}
Index index = JandexHelper.indexForClass( service, Foo.class );
QueryBinder.bind( new AnnotationBindingContextImpl( meta, index ) );
NamedSQLQueryDefinition namedQuery = meta.getNamedNativeQuery( "fubar" )... |
763770_9 | class Neo4jStorage implements DMXStorage {
@Override
public List<TopicModelImpl> fetchTopicsByPropertyRange(String propUri, Number from, Number to) {
return buildTopics(queryIndexByPropertyRange(topicIndex, propUri, from, to));
}
Neo4jStorage(String databasePath, ModelFactoryImpl mf);
@... | List<TopicModelImpl> topics;
topics = db.fetchTopicsByPropertyRange("score", 1L, 1000L); assertEquals(3, topics.size());
topics = db.fetchTopicsByPropertyRange("score", 23L, 23L); assertEquals(2, topics.size());
topics = db.fetchTopicsByPropertyRange("score", 23L, 1234L); assertEquals... |
766240_36 | class StubAnimation implements IsAnimation {
public void tick(final double progress) {
if (progress < 0 || progress > 1.0) {
throw new IllegalStateException("New progress must be between 0 and 1");
}
if (isCancelled()) {
throw new IllegalStateException("Animation is cancelled");
}
if ... | StubAnimation a = new StubAnimation(l);
try {
a.tick(1.0);
fail();
} catch (IllegalStateException ise) {
assertThat(ise.getMessage(), is("Animation is not currently in progress"));
}
}
} |
766548_687 | class SpringSecurityContextPrincipalPopulator implements PrincipalPopulator,
Transformer<Request, Principal> {
private Principal getPrincipal()
{
try
{
SecurityContext securityCtx = SecurityContextHolder.getContext();
if (securityCtx == null)
{
... | context.checking(new Expectations()
{
{
oneOf(securityContext).getAuthentication();
will(returnValue(authentication));
oneOf(authentication).getPrincipal();
will(returnValue(null));
}
});
assertNull... |
771158_3 | class StatementComparator implements Comparator<Statement> {
@Override
public int compare(Statement first, Statement second) {
// Cannot use Statement.equals as it does not take Context into account,
// but can check for reference equality (==)
if (first == second) {
return ... | statement1 = valueFactory.createStatement(testSubjectUri1, testPredicateUri1, testObjectUri1, null);
statement2 = valueFactory.createStatement(testSubjectUri1, testPredicateUri1, testObjectUri1, null);
assertEquals(0, testComparator.compare(statement1, statement2));
assertEquals(0, test... |
774658_11 | class Util {
static Protocol determineProtocol(String server) {
checkNotNull(server);
String[] splitServer = server.split(":");
Protocol protocol = Protocol.HTTPS;
if (splitServer.length > 1) {
String port = splitServer[1];
String protocolInTheUrl = splitSe... | // Given
String testUrl = "https://sqs.softwaremill.pl";
// When and then
assertThat(determineProtocol(testUrl)).isEqualTo(Protocol.HTTPS);
}
} |
782257_47 | class ConnectorServiceImpl implements ConnectorService {
@Override
public Connection open( final String aName ) throws IOException
{
return open( aName, ConnectorService.READ_WRITE );
}
public ConnectorServiceImpl( final BundleContext aContext );
static final String determineSchemeName( final String... | final MyConnectionFactory factory = create( new String[] { Protocols.FTP.protocol(), Protocols.HTTP.protocol() },
1 );
registerConnectionFactory( factory );
Connection returnedConn = this.connectorService.open( Protocols.HTTP.url() );
assertEquals( factory.getConnection(), returnedConn );
... |
806019_7 | class IntegerDataItem implements DataItem {
@Override
public Short getShort()
{
return value.shortValue();
}
public IntegerDataItem();
public IntegerDataItem(final int value);
@Override public Boolean getBoolean();
@Override public Byte getByte();
@Override public Intege... | Assert.assertEquals(value0.getShort(), Short.valueOf((short) 0));
Assert.assertEquals(value1.getShort(), Short.valueOf((short) 1));
Assert.assertEquals(value1000000.getShort(), Short.valueOf((short) 16960)); //overflow
Assert.assertEquals(valueMinus1000000.getShort(), Short.valueOf((shor... |
811072_0 | class HelloEJB {
public String sayHelloEJB(String name) {
return "Hello " + name;
}
@EJB
private HelloEJB helloEJB;
}
class HelloEJBTest {
@EJB
private HelloEJB helloEJB;
@Test
public void testHelloEJB() {
| String result = helloEJB.sayHelloEJB("Michael");
assertEquals("Hello Michael", result);
}
} |
812511_8 | class CertificateUtil {
public static X500Principal toPrincipal(String globusID) {
if (globusID == null) {
return null;
}
String id = globusID.trim();
StringBuilder buf = new StringBuilder(id.length());
if (!id.isEmpty()) {
final int IDLE = 0;
... | X500Principal principal =
CertificateUtil.toPrincipal("");
assertThat(principal, is(new X500Principal("")));
}
} |
819907_5 | class JsonObjects {
static String annotationToString(Annotation annotation) {
StringBuilder string = new StringBuilder();
string.append('@').append(annotation.annotationType().getName()).append('(');
String classAffix = ".class";
String quotationMark = "\"";
try {
... | String expectedOutcome = "@org.jboss.weld.probe.JsonObjectsTest$SomeAnnotation(someInt=1, someString=\"bar\", someStringArray={\"charlie\", \"delta\"})";
assertEquals(expectedOutcome, JsonObjects.annotationToString(getBarTypeAnnotation()));
assertEquals(expectedOutcome, JsonObjects.annotationToS... |
828909_18 | class AccessController extends BaseRegionObserver implements MasterObserver, AccessControllerProtocol {
@Override
public void preCompactSelection(final ObserverContext<RegionCoprocessorEnvironment> e,
final Store store, final List<StoreFile> candidates) throws IOException {
requirePermission(getTableName... | PrivilegedExceptionAction action = new PrivilegedExceptionAction() {
public Object run() throws Exception {
ACCESS_CONTROLLER.preCompactSelection(ObserverContext.createAndPrepare(RCP_ENV, null), null, null);
return null;
}
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWN... |
832025_13 | class RetrofitApiClient {
public Blog getBlogEntries() throws IOException {
Response<BlogFeedDto> response = blogApi.getBlogEntries().execute();
return response.body().toBlog();
}
@SuppressWarnings("deprecation") public RetrofitApiClient(Builder builder);
private static String toBboxString(double lo... | // given
stubFor(get(urlPathEqualTo("/news/feed/"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/rss+xml; charset=UTF-8")
.withBodyFile("blogfeed.xml")));
// when
Blog blog = apiClient.getBlogEn... |
832676_97 | class RunMojo extends MojoSupport {
void addFeatureRepositories(Object featureService) throws MojoExecutionException {
if (featureRepositories != null) {
try {
Class<? extends Object> serviceClass = featureService.getClass();
Method addRepositoryMethod = serviceClass.g... | FeaturesService featureService = mock(FeaturesService.class);
replay(featureService);
RunMojo mojo = new RunMojo();
String[] empty = new String[0];
setPrivateField(mojo, "featureRepositories", empty);
mojo.addFeatureRepositories(featureService);
verify(featureSer... |
832679_7 | class InstallModuleFromGit implements Statement {
@Override
public String render(OsFamily arg0) {
return exec(
"git clone " + (vcsBranch != null ? "-b " + vcsBranch + " " : "") + url + " " + MODULES_DIR
+ module).render(arg0);
}
public InstallModuleFromGit(String module, URI url... |
InstallModuleFromGit nginx = new InstallModuleFromGit("nginx", URI
.create("git://github.com/puppetlabs/puppetlabs-nginx.git"), "WHIRR-385");
assertEquals("git clone -b WHIRR-385 git://github.com/puppetlabs/puppetlabs-nginx.git /etc/puppet/modules/nginx\n", nginx
.render(OsFamily.UNIX));
... |
832680_187 | class IsolatedClassLoader extends URLClassLoader {
@Override
public synchronized Class loadClass( String name )
throws ClassNotFoundException
{
if ( childDelegation )
{
Class<?> c = findLoadedClass( name );
if ( c == null )
{
try
... | Class<?> isolatedClass = classLoader.loadClass( AbstractProvider.class.getName() );
assertThat( isolatedClass, is( notNullValue() ) );
assertThat( isolatedClass.getName(), is( AbstractProvider.class.getName() ) );
assertThat( isolatedClass, is( not( (Class) AbstractProvider.class ) ) );
... |
834344_39 | class StringValidations {
public static boolean isZipCode(final String zipCode)
{
if (zipCode != null)
{
return zipCode.matches("\\d{5}((-| +)\\d{4})?$");
}
return false;
}
public static boolean isAlphabetic(final String text);
public static boolean isAlphanumeric(fina... | assertTrue(StringValidations.isZipCode("28212"));
}
} |
844592_1 | class LogPerLineExceptionHandlingStrategyFactory implements ExceptionHandlingStrategyFactory {
public ExceptionHandlingStrategy makeExceptionHandlingStrategy(
final Level logLevel, final PrintStream originalPrintStream) {
return new LogPerLineExceptionHandlingStrategy(logLevel);
}
priv... | ExceptionHandlingStrategy strategy = STRATEGY_FACTORY.makeExceptionHandlingStrategy(Level.ERROR, null);
strategy.handleExceptionLine(EXCEPTION_LINE, log);
assertEquals(asList(error(STACKTRACE, EXCEPTION_LINE)), log.getLoggingEvents());
}
} |
851175_3 | class MfgMSAProductReader extends AbstractProductReader {
static boolean mfgAlbedoFileNameMatches(String fileName) {
if (!(fileName.matches("MSA_Albedo_L2.0_V[0-9].[0-9]{2}_[0-9]{3}_[0-9]{4}_[0-9]{3}_[0-9]{3}.(?i)(hdf)"))) {
throw new IllegalArgumentException("Input file name '" + fileName +
... | String filename = "bla.txt";
try {
MfgMSAProductReader.mfgAlbedoFileNameMatches(filename);
} catch (Exception e) {
assertEquals(true, e instanceof IllegalArgumentException);
assertEquals("Input file name '" + filename +
"' does not match na... |
859322_0 | class FacesResourceProcessor {
public static byte[] execute(URL url, InputStream input, String encoding) throws IOException {
byte[] bytes;
try {
StringBuilder sb = new StringBuilder();
UnicodeReader reader = new UnicodeReader(input, encoding);
try {
char[] cbuf = new char[32];
... |
URL url;
byte[] bytes;
String encoding = (String) ResourceUtils.getProperty("app.encoding");
url = ResourceUtils.getClasspathResource("META-INF/pages/index.html");
bytes = FacesResourceProcessor.execute(url, url.openConnection().getInputStream(), encoding);
assertEquals(
"<!DOCTYPE html>\n" + ... |
860694_1 | class ZipUtils {
public static void zipDir(final File zipFile, final File srcDir, final String prefix) throws IOException
{
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
try
{
addZipPrefixes(srcDir, out, prefix);
addZipDir(srcDir, out,... | File zipFile = new File(tempDir, "zip-nested-prefix.zip");
ZipUtils.zipDir(zipFile, sourceZipDir, NESTED_PREFIX);
zip = new ZipFile(zipFile);
final Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements())
{
final ZipEntry zi... |
860937_24 | class DenseDoubleVector implements DoubleVector {
@Override
public final DoubleVector subtractFrom(double v) {
DenseDoubleVector newv = new DenseDoubleVector(vector.length);
for (int i = 0; i < vector.length; i++) {
newv.set(i, v - vector[i]);
}
return newv;
}
public DenseDoubleVector()... | double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8};
DoubleVector vec1 = new DenseDoubleVector(vals1);
double constant = 10;
DoubleVector vec3 = vec1.subtractFrom(constant);
for (int i = 0; i < vals1.length; ++i) {
assertEquals(constant - vec1.get(i), vec3.get(i), 0.000001);
}
}
} |
862445_0 | class MultiXmlDocumentReader implements DocumentProducer {
@Override
public Iterator<Document> iterator() {
if (inputStream != null) {
throw new IllegalStateException("already fetched inputStream!");
}
return new MultiXmlDocumentIterator();
}
@Override public void init();
@Ov... | reader.setElemMatch(QName.valueOf("{mynamespace}state"));
reader.setInput(new ClassPathResource("/dummyXml.xml"));
int count = 0;
for (Document document : reader) {
count++;
assertNotNull(((DomRawData)document.getRawData()).getDom());
}
assertEquals(2,count);
}
... |
870849_0 | class JGitAPIExceptions {
public static RuntimeException exceptionWithFriendlyMessageFor(Exception e) {
Throwable cause = getRootCause(e);
String message = cause.getMessage();
if (message == null) {
message = cause.getClass().getSimpleName();
}
if (cause instance... | RuntimeException re = exceptionWithFriendlyMessageFor(new NullPointerException());
assertThat(re.getMessage(), equalTo("NullPointerException"));
}
} |
884758_0 | class GrizzlyExecutorService extends AbstractExecutorService implements ExtendedThreadPool {
public static GrizzlyExecutorService createInstance() {
return createInstance(ThreadPoolConfig.DEFAULT);
}
protected GrizzlyExecutorService(ThreadPoolConfig config);
protected GrizzlyExecutorService(... | int threads = 100;
ThreadPoolConfig cfg = new ThreadPoolConfig("test", -1, threads,
null, -1, 0, null, null, Thread.NORM_PRIORITY, null);
GrizzlyExecutorService r = GrizzlyExecutorService.createInstance(cfg);
final int tasks = 2000000;
doTest(r,tasks);
... |
889932_13 | class RSASha1SignatureService implements SignatureService {
@Override
public String getSignatureMethod() {
return METHOD;
}
public RSASha1SignatureService(PrivateKey privateKey);
@Override public String getSignature(String baseString, String apiSecret, String tokenSecret);
private f... | final String expected = "RSA-SHA1";
assertEquals(expected, service.getSignatureMethod());
}
} |
892275_5 | class RxJava3CallAdapterFactory extends CallAdapter.Factory {
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public static RxJava3CallAdapterFactory createWithScheduler(Scheduler scheduler) {
if (scheduler == null) throw new NullPointerException("scheduler == null");
return new... | try {
RxJava3CallAdapterFactory.createWithScheduler(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("scheduler == null");
}
}
} |
899555_4 | class ElementProviderExtension implements IOCExtensionConfigurator {
static Collection<String> elemental2ElementTags(final MetaClass type) {
final Collection<String> customElementTags = customElementTags(type);
if (!customElementTags.isEmpty()) {
return customElementTags;
}
return Elemental2T... |
final Collection<String> tags = elemental2ElementTags(
metaClass(CustomElement.WithCustomTag.ChildWithoutElementAnnotation.class));
//@Element annotation is not inherited
assertEquals(emptyList(), tags);
}
} |
901534_1 | class UmlModelLoader extends ModelLoader<UmlModel, File> {
@Override
public UmlModel loadModel(File modelFile) throws UmlModelException {
if (modelFile == null) {
return new UmlModel(UmlModelProducer.getInstance().createUmlModel(null));
}
try {
Model model = ge... |
UmlModelLoader loader = new UmlModelLoader();
UmlModel umlModel = loader.loadModel(new File("conf/template/uml/sample.uml"));
Assert.assertNotNull(umlModel);
Assert.assertNotNull(umlModel.getModel());
Assert.assertSame(ModelImpl.class, umlModel.getModel().getClass());
}
} |
904044_3 | class VariableResolver {
public abstract Object resolve(String name)public abstract Object resolve(String name);
public abstract Object resolve(String name)public abstract String replaceTokens(String template);
}
class TestVariableResolver {
@Test
public void testNestedNamespace() {
| VariableResolverImpl vri = new VariableResolverImpl();
Map<String, Object> ns = new HashMap<String, Object>();
ns.put("world", "WORLD");
vri.addNamespace("hello", ns);
ns = new HashMap<String, Object>();
ns.put("world1", "WORLD1");
vri.addNamespace("hello.my", ns);
Assert.assertEquals("W... |
904873_9 | class Parser {
public String getResourceName()
{
return m_resourceName;
}
public Parser( final String path );
}
class ParserTest {
@Test
public void getResourceNameWithLeadingSlash()
throws MalformedURLException
{
| assertEquals( "Resource name", "resource", new Parser( "/resource" ).getResourceName() );
}
} |
906854_11 | class CompositeScannerProvisionOption extends AbstractUrlProvisionOption<CompositeScannerProvisionOption> implements Scanner {
public String getURL()
{
return new StringBuilder()
.append( SCHEMA )
.append( SEPARATOR_SCHEME )
.append( super.getURL() )
.app... | assertThat(
"Scan composite url",
new CompositeScannerProvisionOption(
maven().groupId( "bar" ).artifactId( "foo" ).type( "composite" )
).getURL(),
is( equalTo( "scan-composite:mvn:bar/foo//composite@update" ) )
);
}
} |
907274_29 | class EventBusManager {
public <T extends EventBus> T register(Class<T> busType, Object subscriber) {
return this.register(busType,subscriber,null);
}
public EventBusManager();
public T register(Class<T> busType, Object subscriber,EventBus parentEventBus);
private boolean isPrivateEventBus(Class<T> bu... | EventBus eventBus = eventBusManager.register(StubPrivateEventBus.class,new Object());
EventBus eventBus2 = eventBusManager.register(StubPrivateEventBus.class,new Object());
Assert.assertNotSame("Same event bus instances",eventBus,eventBus2);
}
} |
908709_29 | class TextUtil {
public static String cleanTerm(String term) {
term = term.toLowerCase().trim();
if (term.matches("[0-9\\-\\.:]+"))
return "<NUM>";
if (term.startsWith("http:") ||
term.startsWith("ftp:"))
return "<URL>";
while (term.length() > 0 ... | String[] numbers = {
"1900", ":123", "1-2", "1.2", "10000:", "125121", ".123", "123.",
};
for (String number : numbers)
assertEquals("<NUM>", TextUtil.cleanTerm(number));
}
} |
909809_66 | class ChartMarkersParameter extends AbstractParameter {
void addFreeMarker(final Marker marker, final double xPos, final double yPos) {
markers.add(new FreeMarker(marker, xPos, yPos));
}
void addFillAreaMarker(final FillAreaType fillAreaType, final Color color, final int startLineIndex, final int... | final ChartMarkersParameter p = new ChartMarkersParameter();
final Marker sm = Markers.newShapeMarker(Shape.CIRCLE, PERU, 13, Priority.LOW);
p.addFreeMarker(sm, 10, 20);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString());
final String expectedString = "chm... |
912291_21 | class SpecificCharacterSet {
public byte[] encode(String val, String delimiters) {
return codecs[0].encode(val);
}
protected SpecificCharacterSet(Codec[] codecs, String... codes);
public static SpecificCharacterSet getDefaultCharacterSet();
public static void setDefaultCharacterSet(Strin... | assertArrayEquals(HEBREW_PERSON_NAME_BYTE,
iso8859_8().encode(HEBREW_PERSON_NAME, PN_DELIMS));
}
} |
915029_21 | class FilteredObservableList extends AbstractObservableList<E> {
@Override
public E remove(final int index) {
return d_inner.remove((int) d_indices.get(index));
}
public FilteredObservableList(final ObservableList<E> inner, final Predicate<E> filter);
private void initializeIndices();
public void setFilter(... | ListDataListener mock = createStrictMock(ListDataListener.class);
replay(mock);
d_outer.addListDataListener(mock);
d_inner.remove("Daan");
assertEquals(Arrays.asList("Gert", "Jan"), d_outer);
verify(mock);
}
} |
917362_1 | class Solve {
Solve() {
}
Solve();
public int solve(int dimension, int[][] gridCopy);
public static int[] rc2box(int i, int j);
private void fillSquare(int i, int j, int K);
private int countNumKnown();
}
class SolveTest {
@Test
public void testGameGrid() {
| Solve grid1 = new Solve();
GameGrid grid = new GameGrid(9);
assertTrue(0< grid1.solve(9, grid.grid));
}
} |
917947_24 | class CglibProxyFactory extends AbstractProxyFactory {
public boolean canProxy(final Class<?> type) {
return !Modifier.isFinal(type.getModifiers());
}
public CglibProxyFactory();
public CglibProxyFactory(boolean interceptDuringConstruction);
public T createProxy(final Invoker invoker, f... | ProxyFactory factory = new CglibProxyFactory();
assertFalse(factory.canProxy(String.class));
}
} |
918574_14 | class Path {
public static String normalizeResourcePath(final String path) {
if (path == null) {
return null;
}
String normalizedPath = replaceSlashes(path.trim());
if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) {
normalizedPath = normalizedPath.substring(1);
}
return normalizedP... | assertEquals("Normalized", "/", Path.normalizeResourcePath("/ "));
}
} |
921110_24 | class BootstrapConfigForGroup implements Function<String, DatabagItem> {
@Override
public DatabagItem apply(String from) {
DatabagItem bootstrapConfig = api.getDatabagItem(databag, from);
checkState(bootstrapConfig != null, "databag item %s/%s not found", databag, from);
return bootstrapConfig;... | ChefApi chefApi = createMock(ChefApi.class);
Client client = createMock(Client.class);
BootstrapConfigForGroup fn = new BootstrapConfigForGroup("jclouds", chefApi);
expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn(null);
replay(client);
replay(chefApi);
fn.apply("... |
922501_4 | class RepositoryDirectoryUtil {
public static List<String> getEntries(File root)
{
return walk(root.toURI(), root);
}
public static List<String> walk(URI root, File dir);
private static String stackToPath(List<File> stack, File leaf);
private static void addEntry(StringBuilder sb, File... | final File dir = tmp.newFolder("names");
new File(dir, "foo.txt").createNewFile();
new File(dir, "a/b").mkdirs();
new File(dir, "a/bar.txt").createNewFile();
new File(dir, "c").mkdirs();
assertEquals(newArrayList("a/", "a/b/", "a/bar.txt", "c/", "foo.txt"), RepositoryDi... |
927454_3 | class PublisherConfirms {
static boolean waitUntil(Duration timeout, BooleanSupplier condition) throws InterruptedException {
int waited = 0;
while (!condition.getAsBoolean() && waited < timeout.toMillis()) {
Thread.sleep(100L);
waited = +100;
}
return condit... | Channel ch = connection.createChannel();
ch.confirmSelect();
Map<Long, String> outstandingConfirms = resendUnconfirmedMessages(ch);
assertThat(waitUntil(Duration.ofSeconds(5), () -> outstandingConfirms.isEmpty())).isTrue();
ch.close();
Set<String> receivedMessages = Conc... |
936063_9 | class CreateISO {
public void process(ISO9660Config iso9660Config, RockRidgeConfig rrConfig, JolietConfig jolietConfig,
ElToritoConfig elToritoConfig) throws HandlerException {
if (iso9660Config == null) {
throw new NullPointerException("Cannot create ISO without ISO9660... | File outfile = new File(workDir, "truncate.iso");
ISO9660RootDirectory root = new ISO9660RootDirectory();
root.addFile(new ISO9660File(new ByteArrayDataReference("Hello, world!".getBytes(StandardCharsets.UTF_8)) , "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.wsdl", 1121040000l));
Stre... |
940337_6 | class PathUtil {
static String getRelativeFileInternal(File canonicalBaseFile, File canonicalFileToRelativize) {
ArrayList<String> basePath = getPathComponents(canonicalBaseFile);
ArrayList<String> pathToRelativize = getPathComponents(canonicalFileToRelativize);
//if the roots aren't the s... | File[] roots = File.listRoots();
File basePath = new File(roots[0] + "some");
File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir");
String path = PathUtil.getRelativeFileInternal(basePath, relativePath);
Assert.assertEquals(path, "dir");
}
} |
944926_18 | class EventBus {
public void register(Object object) {
subscribeAll(finder.findAllSubscribers(object));
}
public void subscribe(Class<?> clazz, EventHandler handler);
public void subscribeAll(Multimap<Class<?>, EventHandler> handlers);
public void unsubscribe(Class<?> clazz, EventHandler h... | Subscriber subscriber = new Subscriber();
eventBus.register(subscriber);
Event e1 = new Event();
eventBus.post(e1);
Event e2 = new Event();
eventBus.post(e2);
assertEquals(asList(e1, e2), subscriber.events);
}
} |
947990_0 | class ValidadorDniNie implements ConstraintValidator<ValidarDniNie, Asociado> {
@Override
public boolean isValid(Asociado asociado, ConstraintValidatorContext context) {
if (asociado == null || asociado.getFechaNacimiento() == null)
return true;
context.disableDefaultConstraintViol... | asociado.setDni("AAA");
asociado.setFechaNacimiento(null);
assertTrue(validador.isValid(asociado, context));
}
} |
960343_8 | class SimpleFormula implements ICompactTripletsStructure, ICompactTripletsStructureHolder {
public boolean evaluate(Properties properties)
{
boolean result = true;
for (int j = 0; j < getTiers().size(); j++)
{
for (ITripletValue tiplet : getTier(j))
{
... | ITabularFormula formula = Helper.createFormula(1, 2, 3);
ObjectArrayList route = new ObjectArrayList();
// Route contains inverse values
route.add(new SimpleVertex(new SimpleTripletPermutation(1, 2, 3), 0, _111_instance, null));
assertTrue(formula.evaluate(rout... |
960760_9 | class QuadTree implements Layer, BoundingBoxChangeListener {
@Override
public void bringToFront(final DrawingObject dob) {
if (threadSafe) {
synchronized (lock) {
insertionOrder.put(dob, ++insertionOrderLargest);
}
} else {
insertionOrder.put(dob, ++insertionOrderLargest);
}
}
@SuppressWarnings... |
Set<DrawingObject> set;
addAllRectangles();
set = tree.getDrawingObjects(true);
assertTrue(set.toArray()[0] == rectangle1);
assertTrue(set.toArray()[3] == rectangle4);
tree.bringToFront(rectangle1);
set = tree.getDrawingObjects(true);
assertTrue(set.toArray()[3] == rectangle1);
tree.bringToFront(... |
990281_80 | class ConfiguredBeanResolver implements BeanResolver {
@Override
public <T> BeanHolder<T> resolve(Class<T> typeReference) {
Contracts.assertNotNull( typeReference, "typeReference" );
try {
return beanProvider.forType( typeReference );
}
catch (SearchException e) {
try {
return resolveSingleConfigur... | // Setup
BeanReference<Type1> beanReference1Mock = beanReferenceMock();
BeanReference<Type1> beanReference2Mock = beanReferenceMock();
BeanConfigurer beanConfigurer1 = context -> {
context.define( Type1.class, beanReference1Mock );
};
BeanConfigurer beanConfigurer2 = context -> {
context.define( Type... |
991965_51 | class Iterables {
public static <T> Iterable<T> mix( final Iterable<T>... iterables )
{
return new Iterable<T>()
{
@Override
public Iterator<T> iterator()
{
final Iterable<Iterator<T>> iterators = toList(map( new Function<Iterable<T>, Iterator... | assertThat( Iterables.toList(Iterables.mix( Iterables.iterable( "A","B","C" ),Iterables.iterable( "1","2","3","4","5" ),Iterables.iterable( "X","Y","Z" ) )).toString(), equalTo( "[A, 1, X, B, 2, Y, C, 3, Z, 4, 5]" ));
}
} |
992007_8 | class ParameterizedTypes {
public static <S, T extends S> Type[] findTypeVariables( Class<T> type, Class<S> searchType )
{
return ParameterizedTypes.findParameterizedType( type, searchType ).getActualTypeArguments();
}
private ParameterizedTypes();
public static ParameterizedType findPar... | assertArrayEquals(
((ParameterizedType) GarbageMan.class.getGenericInterfaces()[0]).getActualTypeArguments(),
ParameterizedTypes.findTypeVariables( GarbageMan.class, HandlerOf.class )
);
}
} |
992012_3 | class CapitalizingIdentifierConverter implements IdentifierConverter {
public Object getValueFromData( final Map<String, Object> rawData, final QualifiedName qualifiedName )
{
String convertedIdentifier = convertIdentifier( qualifiedName );
if( rawData.containsKey( convertedIdentifier ) )
... | Map<String, Object> rawData = new HashMap<String, Object>();
assertEquals( "converted key and found value", null, converter.getValueFromData( rawData, QualifiedName.fromQN( "aaa:abc" ) ) );
}
} |
992971_0 | class ExceptionStack implements Serializable {
public Collection<Throwable> getCauseElements() {
return Collections.unmodifiableCollection(this.causes);
}
public ExceptionStack();
public ExceptionStack(final Throwable exception);
@Deprecated protected ExceptionStack(final Collection<Thr... | SQLTransactionRollbackException transactionRollbackException = new SQLTransactionRollbackException();
SQLRecoverableException recoverableException = new SQLRecoverableException();
SQLSyntaxErrorException syntaxErrorException = new SQLSyntaxErrorException();
recoverableException.setNextEx... |
993994_1 | class HttpLoader {
public LoadedXml load(final String url, final int timeout) {
try {
final InputStream stream = loadAsStream(url, timeout);
final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
final Document document = builder.parse(stream);
... | HttpLoader httpLoader = new HttpLoader();
final LoadedXml loadedXml = httpLoader.load("http://localhost:33333/test-timeout.xml?_ox&sleep=100", 300);
assertFalse(loadedXml.isEmpty());
}
} |
1001284_61 | class Reflection {
public static Object defaultValueOf(
Class<? extends Annotation> annotationType,
String attribute) {
try {
return annotationType.getMethod(attribute).getDefaultValue();
} catch (Exception ex) {
throw reflectionException(ex);
}
... | assertEquals("baz", defaultValueOf(Foo.class, "bar"));
}
} |
1006123_0 | class ClientWave {
public Wavelet fetchWavelet(WaveId waveId, WaveletId waveletId)
throws ClientWaveException {
return fetchWavelet(waveId, waveletId, null);
}
public ClientWave(JSONRpcHandler jsonHandler);
public List<JsonRpcResponse> submit(Wavelet wavelet);
public Wavelet blindWavelet(WaveId waveId, Wa... |
ClientWave wave = new ClientWave(new JSONRpcHandler() {
public String request(String jsonBody) throws Exception {
Assert
.assertEquals(
"[{\"method\":\"wave.robot.fetchWave\",\"id\":\"op1\",\"params\":{\"waveId\":\"googlewave.com!testwaveid\",\"waveletId\":\"googlewave.com!conv+root\"}}]",
... |
1007836_19 | class CyclicWordsKata {
public List<List<String>> process()
{
List<List<String>> processed = new ArrayList<List<String>>();
Map<Integer,List<String>> buckets ;
List<List<String>> returnArray ;
buckets = separateInputBySize(_input);
if(buckets == null)
return proc... | String[] input = null;
CyclicWordsKata tester = new CyclicWordsKata(input);
List<List<String>> results = tester.process();
assertNull("results", results);
}
} |
1014623_5 | class Configuration {
static String getRequiredConfigValue(final String propertyName)
{
String value = getConfiguration().getProperty(propertyName);
if (value == null)
{
throw new ConfigurationException("Te requested property [" + propertyName
+ "] was not s... | assertEquals(getRequiredConfigValue(REDIS_HOST), "localhost");
}
} |
1017889_4 | class Path implements Iterable<String>, Serializable {
public Path append(Path relative) {
if (relative == null) {
throw new IllegalArgumentException("Argument 'relative' cannot be null");
}
if (relative.isAbsolute()) {
throw new IllegalArgumentException("Cannot appe... | assertEquals(new Path("/").append(new Path("foo")), new Path("/foo"));
assertEquals(new Path("/").append(new Path("foo/bar")), new Path("/foo/bar"));
assertEquals(new Path("/foo").append(new Path("bar")), new Path("/foo/bar"));
assertEquals(new Path("/foo").append(new Path("../bar")), ne... |
1020601_4 | class NumberConverter implements ConditionalConverter<Object, Number> {
public Number convert(MappingContext<Object, Number> context) {
Object source = context.getSource();
if (source == null)
return null;
Class<?> destinationType = Primitives.wrapperFor(context.getDestinationType());
if (sou... | XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
assertEquals(xmlGregorianCalendar.toGregorianCalendar().getTimeInMillis(), convert(xmlGregorianCalendar, Long.class));
}
} |
1024699_26 | class G3Client implements IG3Client {
public List<Item> getAlbumAndSubAlbums(int albumId)
throws G3GalleryException {
List<Item> items = new ArrayList<Item>();
Item item = getItems(albumId, items, "album");
// we add to the list the parent album
items.add(0, item);
return items;
}
public G3Client(Str... |
List<Item> subAlbums = itemClient.getAlbumAndSubAlbums(11);
boolean foundRecentlyAddedAlbum = false;
for (Item album : subAlbums) {
// we test if we can find the previously added album
if (album.getEntity().getId() == createdAlbumId) {
foundRecentlyAddedAlbum = true;
}
}
assertTrue(foundRecent... |
1025574_2 | class ToolSpec {
String toXMlFormatted() throws JAXBException, UnsupportedEncodingException {
//Create marshaller
Marshaller m = jc.createMarshaller();
m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
m.marshal(this, bos);
return bos... | fail("Not yet implemented");
}
} |
1028034_7 | class NURBS {
public double[] getBasicFunctions(int i, double u) {
double[] n = new double[degree + 1];
n[0] = 1.0;
double[] left = new double[degree + 1];
double[] right = new double[degree + 1];
for (int j = 1; j <= degree; j++) {
left[j] = u - this.knots[(i ... | Point3D[] points = new Point3D[]{};
double[] knots = new double[]{0, 0, 0, 1, 2, 3, 4, 4, 5, 5};
double[] w = new double[]{};
NURBS n = new NURBS(points, knots, w, 2);
double[] bf = n.getBasicFunctions(4, 2.5);
assertEquals(3, bf.length);
assertEquals(1.0 / 8.0, ... |
1031515_0 | class LocalizedFieldNames {
public Lookup createLookup(List<String> keys) {
return new LookupImpl(keys);
}
public void setMessageSource(MessageSource messageSource);
private String fieldNameToKey(String fieldName);
private String localizedToKey(String localizedName);
private Reloadabl... | LocalizedFieldNames.Lookup lookup = localizedFieldNames.createLookup(Arrays.asList("dc.title"));
final Locale english = new Locale("en");
String title = lookup.toLocalizedName("dc_title", english);
Assert.assertEquals("Title", title);
String fieldName = lookup.toFieldName(title, ... |
1052717_4 | class AnnotatedFieldProcessor {
static <X> Set<Field> camelInjectAnnotatedFieldsIn(final Class<X> type) {
final Set<Field> camelInjectAnnotatedFields = new HashSet<Field>();
for (final Field fieldToInspect : allFieldsAndSuperclassFieldsIn(type)) {
if (isAnnotatedWithOneOf(fieldToInspect, CAMEL)) {
camelInj... | final Set<Field> camelInjectAnnotatedFields = AnnotatedFieldProcessor
.camelInjectAnnotatedFieldsIn(BeanHavingEndpointInjectAnnotatedField.class);
assertEquals("AnnotatedFieldProcessor.hasCamelInjectAnnotatedFields("
+ BeanHavingEndpointInjectAnnotatedField.class.getName()
+ ") should... |
1068402_84 | class VersionMatcher implements Serializable {
public boolean versionSupported(final String requiredVersion, final String publishedVersion) {
if (requiredVersion == null) {
throw new IllegalArgumentException("requiredVersion is null");
}
if (publishedVersion == null) {
... | VersionMatcher versionMatcher = new VersionMatcher();
Assert.assertFalse(versionMatcher.versionSupported("3.24.1", "3.23.13.4, 3.24"));
Assert.assertFalse(versionMatcher.versionSupported("3.23.1", "3.23.13.4, 3.24"));
Assert.assertTrue(versionMatcher.versionSupported("3.23.1", "3.23, 3.2... |
1071043_0 | class NativeQuestionSetImporter extends AbstractQuestionSetImporter {
@Override
public QuestionSet processDocument( Document doc ) throws ParseException {
Element root = doc.getRootElement();
if ( !root.getName().equalsIgnoreCase( "QuestionSet" ) )
throw new ParseException( "Questi... | Collection<QuestionSet> bundledQuestionSets = QuestionSetManager.loadBundledQuestionSets();
NativeQuestionSetImporter questionSetImporter = new NativeQuestionSetImporter();
XmlQuestionSetParser questionSetParser = new XmlQuestionSetParser();
for (QuestionSet questionSet : bundledQuestion... |
1071767_0 | class IPNMessageParser {
public IPNMessage parse() {
IPNMessage.Builder builder = new IPNMessage.Builder(nvp);
if(validated)
builder.validated();
for(Map.Entry<String, String> param : nvp.entrySet()) {
addVariable(builder, param);
}
return builder.build();
}
public IPNMessageParser(Map<String, Str... | final Map<String, String> nvp = new HashMap<String, String>();
nvp.put("txn_type", "unknown");
parser = new IPNMessageParser(nvp, true);
final IPNMessage message = parser.parse();
assertThat(message.getTransactionType(), nullValue());
}
} |
1072630_1 | class EntityMapper implements PathMapper<T> {
public abstract T mapPath(EntityPath<S,E> entityPath)public abstract T mapPath(EntityPath<S,E> entityPath);
public abstract T mapPath(EntityPath<S,E> entityPath)protected EntityMapper(GraphDatabaseContext graphDatabaseContext);
public abstract T mapPath(EntityPath<S,E> ... | Person michael = new Person("Michael", 36).persist();
EntityMapper<Person, Person, String> mapper = new EntityMapper<Person, Person, String>(ctx) {
@Override
public String mapPath(EntityPath<Person, Person> entityPath) {
return entityPath.<Person>startEntity().get... |
1076094_132 | class CompositeGatewayManager implements GatewayManager {
@Transactional
@SuppressWarnings("unchecked")
public Set<GatewayResponse> sendMessage(GatewayRequest gatewayRequest)
{
if ( gatewayRequest
.getMessageRequest()
.getMessageType() == MessageType.VOICE ) {
return voiceGatewayManager.send... |
Set<GatewayResponse> voiceResponseSet = new HashSet<GatewayResponse>();
voiceResponseSet.add(voiceGatewayResponse);
expect(voiceManager.sendMessage(voiceGatewayRequest)).andReturn(voiceResponseSet);
replay(voiceManager);
compositeGateway.sendMessage(voiceGatewayRequest);
verify(voiceManager);
... |
1076159_32 | class ConstructorAnalysis {
static AnalysisResult analyse(
Class<?> klass, Constructor<?> constructor) throws IOException {
Class<?>[] parameterTypes = constructor.getParameterTypes();
InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class");
if (in == null) {
... | InputStream classInputStream = this.getClass().getResourceAsStream("example_scala_class02.bin");
assertNotNull(classInputStream);
Map<String, FormalParameter> assignements =
analyse(classInputStream,
"com/kaching/user/GetAllModels",
"com/kaching/platform/queryengine/AbstractQuery",... |
1076632_14 | class StaffMessageServiceImpl implements StaffMessageService {
public void sendStaffCareMessages(Date startDate, Date endDate,
Date deliveryDate, Date deliveryTime,
String[] careGroups,
boolean sendUpc... |
Date forDate = new Date();
String careGroups[] = {"ANC", "TT", "IPT"};
Location location = new Location();
location.setName("Test Facility");
Facility facility = new Facility();
facility.setLocation(location);
facility.setPhoneNumber("+1 555 123-1234");
... |
1077753_0 | class SQLFile {
public static List<String> statementsFrom(Reader reader) throws IOException {
SQLFile file = new SQLFile();
file.parse(reader);
return file.getStatements();
}
public void parse(Reader in);
private String stripOffTrailingComment(String line);
public List<Stri... | String firstLine = "CREATE TABLE 'testTable'";
String secondLine = "_id INTEGER PRIMARY KEY AUTOINCREMENT;";
String singleLineCommand = firstLine + " " + secondLine;
String multiLineCommand = firstLine + "\n" + secondLine;
List<String> statementsFromMultiline = SQLFile.statements... |
1079636_7 | class DifferenceAccumulatingHandler extends AbstractDiffHandler {
protected boolean isClassConsidered( final String className ) {
// Fix case where class names are reported with '.'
final String fixedClassName = className.replace('.', '/');
for ( String exclude : this.excludes ) {
... |
List<String> inclusions = new ArrayList<String>();
Set<String> inclusionSet = new HashSet<String>( inclusions );
List<String> exclusions = new ArrayList<String>();
exclusions.add( "java/*" );
Set<String> exclusionSet = new HashSet<String>( exclusions );
Assert.assertEqu... |
1081991_13 | class DependenciesDeployer {
static void writeDependenciesFeature(Writer writer, ProvisionOption<?>... provisionOptions) {
XMLOutputFactory xof = XMLOutputFactory.newInstance();
xof.setProperty("javax.xml.stream.isRepairingNamespaces", true);
XMLStreamWriter sw = null;
try {
... | MavenArtifactProvisionOption option = mavenBundle().groupId("mygroup").artifactId("myArtifactId").version("1.0");
StringWriter wr = new StringWriter();
DependenciesDeployer.writeDependenciesFeature(wr, option);
Assert.assertEquals(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\... |
1089023_0 | class AsyncCountDownLatch extends CountDownLatch implements Completable.Source {
@Override
public void subscribe(Completable.Observer subscriber) {
completionSignal.subscribe(subscriber);
}
public AsyncCountDownLatch(int count);
public boolean isCompleted();
public void countDown();
... | AsyncCountDownLatch latch = new AsyncCountDownLatch(0);
MyObserver subscriber = new MyObserver();
latch.subscribe(subscriber);
Assert.assertFalse(subscriber.onSubscribeSeen.get());
Assert.assertTrue(subscriber.onCompleteSeen.get());
}
} |
1090553_36 | class FlagValueCalculator {
@Nullable
public <V> V queryValue(@Nullable RegionAssociable subject, Flag<V> flag) {
Collection<V> values = queryAllValues(subject, flag, true);
return flag.chooseValue(values);
}
public FlagValueCalculator(List<ProtectedRegion> regions, @Nullable Protecte... | MockApplicableRegionSet mock = new MockApplicableRegionSet();
LocalPlayer nonMember = mock.createPlayer();
LocalPlayer member = mock.createPlayer();
ProtectedRegion global = mock.global();
global.getMembers().addPlayer(member);
FlagValueCalculator result = mock.getFlag... |
1091655_1 | class ManagedBasicDataSource extends BasicDataSource {
public String getMBeanName() {
return mBeanName;
}
public ManagedBasicDataSource();
public ManagedBasicDataSource(String mBeanName);
public ManagedBasicDataSource(MBeanServer mBeanServer, String mBeanName);
protected synchroniz... | final ManagedBasicDataSource testDataSource = (ManagedBasicDataSource) ManagedBasicDataSourceFactory.createDataSource(new Properties());
assertTrue(getMBeanServerConnection().isRegistered(new ObjectName(testDataSource.getMBeanName())));
}
} |
1091966_0 | class RequestReader {
public Request read(InputStream in) throws IOException {
String header = null;
String body = null;
byte[] headerBytes = new byte[headerLength];
int n = in.read(headerBytes);
if (n > 0) {
header = new String(headerBytes, encoding);
... | String body = "123ABC";
String header = rightPad("", headerBodyLengthBeginIndex) + leftPad(String.valueOf(body.length()), headerBodyLengthEndIndex - headerBodyLengthBeginIndex, "0") + rightPad("", headerLength - headerBodyLengthEndIndex);
byte[] buffer = new byte[header.length() + body.length()... |
1095208_79 | class WeatherService extends TimeslotPhaseProcessor implements
InitializationService {
@Override
public void activate (Instant time, int phaseNumber)
{
long msec = time.getMillis();
if (msec % (getWeatherReqInterval() * TimeService.HOUR) != 0) {
log.info("WeatherService reports not time to grab... |
weatherService.activate(start, 1);
// There should be 24 predictions in the forecast
assertEquals(24, weatherForecastRepo.currentWeatherForecast()
.getPredictions().size());
// Predictions should increment by one each time
int i = 1;
for (WeatherForecastPrediction p : weathe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.