id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
7480345_95 | class CallbackMethodCompiler extends BroMethodCompiler {
protected static String createCallbackCWrapper(FunctionType functionType, String name, String innerName) {
// We order structs by name in reverse order. The names are constructed
// such that nested structs get names which are naturally order... | assertEquals(
"void* f_inner(void);\n" +
"void* f(void) {\n" +
" return f_inner();\n" +
"}\n",
CallbackMethodCompiler.createCallbackCWrapper(
new FunctionType(I8_PTR), "f", "f_inner"));
}
} |
7481569_302 | class ProjectHelper {
public Set<Project> getUngroupedRepositories() {
return cacheProjects(PROJECT_HELPER_UNGROUPED_REPOSITORIES, ungroupedRepositories);
}
private ProjectHelper(PageConfig cfg);
public static ProjectHelper getInstance(PageConfig cfg);
public List<RepositoryInfo> getRepo... | Set<Project> result = helper.getUngroupedRepositories();
Assert.assertEquals(2, result.size());
for (Project p : result) {
Assert.assertTrue(p.getName().startsWith("allowed_"));
}
}
} |
7482468_0 | class Column implements QueryElement {
@Override
public String toString()
{
return Visitors.readable(this);
}
public Column(SelectorName selectorName);
public Column(SelectorName selectorName, String propertyName, String columnName);
public Column(ColumnFunction columnFunction, String c... | Column column = new Column(new SelectorName("selectorName"));
assertThat(column.toString(), is("selectorName.*"));
}
} |
7499734_214 | class Hazelcast {
@Deprecated
public static <E> IList<E> getList(String name) {
return getDefaultInstance().getList(name);
}
private Hazelcast();
@Deprecated public static HazelcastInstance init(Config config);
@Deprecated public static HazelcastInstance getDefaultInstance();
@De... | IList<String> list = Hazelcast.getList("testListIsEmpty");
assertTrue(list.isEmpty());
list.add("Hello World");
assertFalse(list.isEmpty());
}
} |
7506968_32 | class RepositoryTableModel extends AbstractTableModel {
public Class getColumnClass( final int column ) {
if ( column == 2 ) {
return Date.class;
}
return String.class;
}
public RepositoryTableModel();
public boolean isShowHiddenFiles();
public void setShowHiddenFiles( final boolean show... | RepositoryTableModel repoTableModel = new RepositoryTableModel();
assertNotNull( repoTableModel );
assertEquals( Date.class, repoTableModel.getColumnClass( 2 ) );
assertEquals( String.class, repoTableModel.getColumnClass( 1 ) );
}
} |
7575297_13 | class HtmlUtils {
public static String removeTag(String html, String tagName) {
Element bodyElement = Jsoup.parse(html).body();
bodyElement.getElementsByTag(tagName).remove();
return bodyElement.html();
}
public static String text(String html);
public static String text(String ... | String html = "<a onclick='alert(1)' onBlur='alert(1)'>你好</a><A>1</a>";
Assert.assertEquals("", HtmlUtils.removeTag(html, "a"));
}
} |
7589324_102 | class RepositoryTodoIndexService implements TodoIndexService {
@Transactional
@Override
public void deleteFromIndex(Long id) {
LOGGER.debug("Deleting an existing document with id: {}", id);
repository.delete(id.toString());
}
@Transactional @Override public void addToIndex(Todo tod... | service.deleteFromIndex(1L);
verify(repositoryMock, times(1)).delete("1");
verifyNoMoreInteractions(repositoryMock);
}
} |
7593542_1 | class MyBean {
public String sayHello(String name, boolean hipster) {
return (hipster) ? ("Yo " + name) : ("Hello " + name);
}
}
class MyBeanTest {
@Test
public void testHello() {
| MyBean bean = new MyBean();
final String result = bean.sayHello("Scott", false);
Assert.assertEquals("Hello Scott", result);
}
} |
7612313_0 | class PasswordCache extends I2PAppThread implements PasswordHolder {
@Override
public synchronized DerivedKey getKey() throws IOException, GeneralSecurityException {
if (derivedKey == null)
createDerivedKey();
return derivedKey;
}
public PasswordCache(Configuration configu... | passwordCache.setPassword(PASSWORD);
DerivedKey derivedKey = passwordCache.getKey();
assertEquals(derivedKey.scryptParams, FileEncryptionConstants.KDF_PARAMETERS);
byte[] expectedKey = FileEncryptionUtil.getEncryptionKey(PASSWORD, derivedKey.salt, derivedKey.scryptParams);
assert... |
7623114_51 | class CompareOp {
public static int acompare(double x1, double x2) {
if (isZero(x1 - x2)) {
return 0;
} else {
return Double.compare(x1, x2);
}
}
public static boolean isZero(double x);
public static boolean isZero(float x);
public static boolean isZ... | float tol = 0.01f;
float x1 = 100;
float x2 = x1 - tol / 10;
assertEquals(0, CompareOp.acompare(x1, x2, tol));
x2 = x1 - tol * 10;
assertTrue(CompareOp.acompare(x1, x2, tol) > 0);
x2 = x1 + tol * 10;
assertTrue(CompareOp.acompare... |
7676364_12 | class ThreadPoolManager {
public static synchronized ThreadPoolExecutor getExecutor(ThreadPoolBuilder builder,
RegionCoprocessorEnvironment env) {
return getExecutor(builder, env.getSharedData());
}
static synchronized ThreadPoolExecutor getExecutor(ThreadPoolBuilder builder,
Map<String, Object>... | Map<String, Object> cache = new HashMap<String, Object>();
ThreadPoolBuilder builder = new ThreadPoolBuilder(name.getTableNameString(), new Configuration(false));
ThreadPoolExecutor exec = ThreadPoolManager.getExecutor(builder, cache);
assertNotNull("Got a null exector from the pool!", exec);
//shut... |
7707976_1 | class SimpleDBChronicle extends Chronicle {
@Override
public void add(ChronologicalRecord item) {
add(Collections.singleton(item).iterator(), 0);
}
public SimpleDBChronicle(AmazonSimpleDBClient client, String key);
private ReplaceableItem getItem(ChronologicalRecord record);
@Override public void add(Iterat... | chronicle.add(getTestItem(0));
Assert.assertEquals(1, chronicle.getNumEvents(0, System.currentTimeMillis()));
Assert.assertEquals(1, getChronicle().getNumEvents(0, System.currentTimeMillis()));
}
} |
7710120_32 | class ConditionalCriteriaBuilder {
public static <T> ConditionRoot<T> criteriaFor(Class<T> clazz) {
return new ConditionalCriteriaBuilder<T>().new RootBuilderImpl();
}
private ConditionalCriteriaBuilder();
}
class ConditionalCriteriaBuilderTest {
@Test
public void shouldBuildEqualsCond... | ConditionalCriteria criteria = criteriaFor(Person.class).lbrace().withProperty(aaa()).eq(1234).rbrace()
.buildSingle();
assertEquals("aaa", criteria.getPropertyName());
assertEquals(ConditionalCriteria.Operator.Equal, criteria.getOperator());
assertEquals(1234, criteria.... |
7731254_63 | class IdParser {
public static Node[] parse(String id) {
if (id.length() == 0) {
return EMPTY_NODES_ARRAY;
}
List<Node> result = Lists.newArrayList();
Iterable<String> split = SeparatorChar.SPLITTER.split(id);
for (String s : split) {
if (s.charAt(0... | try {
parse("form:table:@rows(");
fail();
} catch (IllegalArgumentException e) {
// ignore
}
try {
parse("form:table:@rows(12");
fail();
} catch (IllegalArgumentException e) {
// ignore
}
as... |
7742400_8 | class Unix {
native static int symlink(String linkedToPath, String symlinkPath)native static int symlink(String linkedToPath, String symlinkPath);
native static int symlink(String linkedToPath, String symlinkPath)protected static native int getIntDefine(String definedName);
native static int symlink(String linkedToPa... | if(!isUnix())
return;
File f = File.createTempFile("testSymlink", ".test");
File d = new File(f.getParentFile(), f.getName()+".dir");
d.mkdir();
File a = new File(d, "a");
a.createNewFile();
File b = new File(d, "b");
int result = Unix.symlink(a.getPath(), b.getPath());
assertTrue(result == 0)... |
7762720_25 | class TranscriptModel implements java.io.Serializable, Constants {
public int getExonCount() {
return this.exonCount;
}
private TranscriptModel();
public static TranscriptModel createTranscriptModel();
public void setAccessionNumber(String acc);
public void setChromosome(byte c);
... | int N = uc010wrv.getExonCount();
Assert.assertEquals(18,N);
}
} |
7766448_1 | class DemoApiTool {
public static String sign(String appKey, String secret, Map<String, String> paramMap)
{
// 对参数名进行字典排序
String[] keyArray = paramMap.keySet().toArray(new String[0]);
Arrays.sort(keyArray);
// 拼接有序的参数名-值串
StringBuilder stringBuilder = new StringBuilder(... | String appKey = "XXXXXXXX";
String secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("city", "上海");
paramMap.put("latitude", "31.21524");
paramMap.put("longitude", "121.420033");
paramMap.put("c... |
7767313_22 | class JsonFileBackedDAO implements DemandSideDAO {
public synchronized void loadData(String dbLocation) throws DSPException {
try {
if ((dbLocation != null) && (dbLocation != "")) {
this.dbLocation = dbLocation;
} else { // otherwise use a default location and filename relative to this class
this.... | try
{
dao.loadData("dummyfile.json");
}
catch (Exception e)
{
assertTrue("The DSPException should occur", e.getClass().getName().equals("org.openrtb.dsp.intf.model.DSPException"));
String msg = "dummyfile.json (The system cannot find the file s... |
7783162_11 | class MoneyAlgorithmics {
public MonetaryAmount addAll(MonetaryAmount... amounts) {
throw new UnsupportedOperationException();
}
public MonetaryAmount multiply(MonetaryAmount amount, Number factor);
public MonetaryAmount subtract(MonetaryAmount amount, MonetaryAmount amt2);
public Monetary... | assertEquals(Money.of(20, "CHF"), alg.addAll(Money.of(10, "CHF"), Money.of(10, "CHF")));
assertEquals(Money.of(20.8, "CHF"), alg.addAll(Money.of(10.5, "CHF"), Money.of(10.3, "CHF")));
assertEquals(Money.of(-90, "CHF"), alg.addAll(Money.of(-100.3, "CHF"), Money.of(10.3, "CHF")));
assertEq... |
7823906_2 | class LabelUtil {
public static String getResourceLabel(String key) {
try {
ResourceBundle res = ResourceBundle.getBundle("labels",
new EncodedControl("UTF-8"));
return res.getString(key);
} catch (MissingResourceException me) {
logger.warn("Unable to find ResourceBUndle", me);
return key;
}
}... | String actual = LabelUtil.getResourceLabel("non-existing-key");
Assert.assertEquals("non-existing-key", actual);
}
} |
7826526_51 | class ZeroFilterFunc extends FilterFunc {
public final Boolean exec(final Tuple input) throws ExecException {
if (input == null || input.get(0) == null) {
return false;
}
if (mode.equals("default")) {
String xCS = (String) input.get(1);
if (containsXcsVa... | Tuple input = tupleFactory.newTuple(2);
input.set(0, "http://en.m.wikipedia.org/wiki/The_Slave_Hunters");
input.set(1, "zero=420-01");
ZeroFilterFunc zero = new ZeroFilterFunc("default");
assertTrue(zero.exec(input));
}
} |
7832943_3 | class PersistentEphemeralNode {
@VisibleForTesting
String getActualPath() throws ExecutionException, InterruptedException {
return _async.getActualPath();
}
public PersistentEphemeralNode(CuratorFramework curator, String basePath, byte[] data, CreateMode mode);
public void close(long dur... | PersistentEphemeralNode node = createNode(PATH);
byte[] bytes = _curator.getData().forPath(node.getActualPath());
assertArrayEquals(bytes, DATA);
}
} |
7837044_3 | class DiscoveryThread extends Thread {
protected MulticastSocket createSocket() throws UnknownHostException, IOException {
InetAddress address = InetAddress.getByName(multicastAddress);
MulticastSocket socket = new MulticastSocket(port);
socket.joinGroup(address);
return socket;
... | DiscoveryListener listener = mock(DiscoveryListener.class);
DiscoveryThread thread = new DiscoveryThread(
AndroidNetworkIntents.DEFAULT_MULTICAST_ADDRESS,
AndroidNetworkIntents.DEFAULT_PORT,
listener
);
MulticastSocket socket1 = thread.createSocket()... |
7842918_5 | class EntityCollections {
public static void setEntityRefsFromEntities(Collection<String> refs, Collection<Entity> entities)
{
refs.clear();
for (Iterator<Entity> i = entities.iterator(); i.hasNext();)
{
Entity entity = i.next();
refs.add(entity.getReference());
}
}
public static boolean isIntersect... | Entity e1 = mock(Entity.class);
when(e1.getReference()).thenReturn("/ref/e1");
Entity e2 = mock(Entity.class);
when(e2.getReference()).thenReturn("/ref/e2");
ArrayList<String> refernces = new ArrayList<String>();
setEntityRefsFromEntities(refernces,
Arrays.asList(new Entity[] { e1, e2 }));
assertTrue... |
7891529_103 | class InputDialogFooter extends Composite {
@UiHandler("cancelButton")
public void handleCancelClick(final ClickEvent event) {
this.actionDelegate.cancelled();
}
@Inject public InputDialogFooter(final @Nonnull UILocalizationConstant messages);
public void setDelegate(final ActionDelegate... | footer.handleCancelClick(mock(ClickEvent.class));
verify(actionDelegate).cancelled();
}
} |
7891564_7 | class ReferencesManager {
public static Pair<String, String> modifyBodyWithReferences(Message message, String body) {
if (body == null || body.isEmpty() || body.trim().isEmpty()) return new Pair<>(body, null);
List<ExtensionElement> elements = message.getExtensions(ReferenceElement.ELEMENT, Refere... | String expected = "<font color='#9e9e9e'>\u2503</font> This is a quote\n" +
"<font color='#9e9e9e'>\u2503</font> of two lines\n" +
"Hello world!";
Pair<String, String> result = ReferencesManager.modifyBodyWithReferences(message4, body4);
assert... |
7908045_0 | class ReleaseSymbolType extends SymbolType implements Rule, Translation {
@Override
public String toTarget(Translator translator, Symbol symbol) {
Release release;
try {
release = new Release(symbol.getProperty(OptionType.RELEASE.name()));
} catch (Exception e) {
return "<strong>Malformed r... | Symbol symbol = new Symbol(releaseSymbolType);
symbol.putProperty(ReleaseSymbolType.OptionType.RELEASE.name(), "20121220");
String html = releaseSymbolType.toTarget(null, symbol);
assertTrue(html.contains("<h3>release \n" +
"\t<a href=\"\">20121220</a>\n" +
"</h3>"));
asser... |
7923123_11 | class CalendarPickerView extends ListView {
public FluentInitializer init(Date minDate, Date maxDate, TimeZone timeZone, Locale locale) {
if (minDate == null || maxDate == null) {
throw new IllegalArgumentException(
"minDate and maxDate must be non-null. " + dbg(minDate, maxDate));
}
if ... | view.init(minDate, maxDate, timeZone, locale) //
.inMode(SINGLE);
assertThat(view.highlightedCals).hasSize(0);
assertThat(view.highlightedCells).hasSize(0);
}
} |
7968180_69 | class CytoPanelStateChangedEvent extends AbstractCyEvent<Object> {
public CytoPanelState getNewState() {
return newState;
}
public CytoPanelStateChangedEvent(final Object source, final CytoPanel cp, final CytoPanelState newState);
public CytoPanel getCytoPanel();
CytoPanelStateChangedEvent event;
@Mock
p... | assertEquals(newState, event.getNewState());
}
} |
7983535_9 | class TypeUtil {
public final static Type getCollectionType(Type type) {
if (type instanceof GenericArrayType) {
return ((GenericArrayType) type).getGenericComponentType();
} else if (type instanceof Class<?>) {
Class<?> clazz = (Class<?>) type;
if (clazz.isArray())
return clazz.get... | assertEquals(Object.class, getCollectionType(Collection.class));
assertEquals(Number.class, getCollectionType(tListN));
assertEquals(Number.class, expandType(getCollectionType(tListE), ParametrizedClass.class));
assertEquals(Object.class, expandType(getCollectionType(tListF), ParametrizedClass.class));
... |
7997879_106 | class TextFormat {
public static void write004(Writer writer, Enumeration<Collector.MetricFamilySamples> mfs) throws IOException {
/* See http://prometheus.io/docs/instrumenting/exposition_formats/
* for the output format specification. */
while(mfs.hasMoreElements()) {
Collector.MetricFamilySampl... | Gauge labels = Gauge.build().name("labels").help("help").labelNames("l").register(registry);
labels.labels("ąćčęntěd a\nb\\c\"d").inc();
TextFormat.write004(writer, registry.metricFamilySamples());
assertEquals("# HELP labels help\n"
+ "# TYPE labels gauge\n"
+ "labels{... |
8000878_7 | class RaygunStripWrappedExceptionFilter implements IRaygunOnBeforeSend, IRaygunSendEventFactory<IRaygunOnBeforeSend> {
public RaygunMessage onBeforeSend(RaygunClient client, RaygunMessage message) {
if(message.getDetails() != null
&& message.getDetails().getError() != null
... | RaygunStripWrappedExceptionFilter f = new RaygunStripWrappedExceptionFilter(ClassNotFoundException.class);
RaygunMessage message = new RaygunMessage();
message.getDetails().setError(new RaygunErrorMessage(new Exception("keep me!", new ClassNotFoundException("keep me too!"))));
f.onBefor... |
8010626_2018 | class VcfImporterService implements ImportService {
@Transactional
@Override
public EntityImportReport doImport(
RepositoryCollection source,
MetadataAction metadataAction,
DataAction dataAction,
@Nullable @CheckForNull String packageId) {
if (dataAction != DataAction.ADD) {
thr... | RepositoryCollection source = mock(RepositoryCollection.class);
String defaultPackage = "package";
assertThrows(
IllegalArgumentException.class,
() ->
vcfImporterService.doImport(
source, MetadataAction.ADD, DataAction.ADD_UPDATE_EXISTING, defaultPackage));
}
} |
8015168_6 | class Vectoriser {
public Vector vectorise(Document document) {
Vector body = luceneEncode(bodyCard, document.getBody());
Vector title = luceneEncode(titleCard, document.getTitle());
//Vector tags = luceneEncode(tagCard, Strings.collectionToCommaDelimitedString(document.getTags()));
//Vector reputation = Vect... | Vectoriser vectorise = new Vectoriser();
Document doc = Document.of("first second", "", "", 0.0, new HashSet<String>());
Vector vec = vectorise.vectorise(doc);
assertEquals("Adding one term should result in two dimensions set to one.",
4,
vec.getNumNondefaultElements());
}
} |
8022939_8 | class DefaultLocalizationProvider implements LocalizationProvider {
@Override
public String getString(String key) {
return getPropertyResolver().getString(checkNotNull(key));
}
private DefaultLocalizationProvider(Builder builder);
@Override public Boolean getBoolean(String key);
@Ove... | thrown.expect(UnsupportedLocationException.class);
String expectedMessage = "Unsupported location: '" + LOCATION + "'";
thrown.expectMessage(expectedMessage);
LocalizationProvider localizationProvider = createDefault();
when(localeResolver.getLocale()).thenReturn(Locale.ITALY);
... |
8025185_0 | class LanguageDictionary {
public AppleLanguage getLanguage() {
return language;
}
public LanguageDictionary(String lprojName);
public static LanguageDictionary createFromFile(File f);
public JSONObject readContentFromBinaryFile(File binaryFile);
public void addJSONContent(JSONObject content);
pri... | String name = "French";
LanguageDictionary dict = new LanguageDictionary(name);
Assert.assertEquals(dict.getLanguage().getIsoCode(), "fr");
}
} |
8031741_0 | class Calculator {
public static Position findPosition(Position startingLocation,
Position endLocation, double distanceTravelled) {
double distance = distanceTravelled / 6371000;
LatLonPoint result = GreatCircle.pointAtDistanceBetweenPoints(
Math.toRadians(startingLocat... | double lat = ParseUtils.parseLatitude("61 00.000N");
double lon = ParseUtils.parseLongitude("051 00.000W");
Position start = Position.create(lat, lon);
Position result = Calculator.findPosition(start, 45.0, 9260.0);
assertNotNull(result);
assertEquals("61 03.530N", resu... |
8033805_0 | class JavaClass {
public int returnInputValue(int input) {
return input;
}
private static final int TEST_VALUE;
}
class JavaClassTest {
private static final int TEST_VALUE;
@Test
public void shouldReturnGivenValue() {
| JavaClass javaClass = new JavaClass();
int returnedValue = javaClass.returnInputValue(TEST_VALUE);
assertThat(returnedValue).isEqualTo(TEST_VALUE);
}
} |
8037199_2 | class Template {
public static String renderWhereStringTemplate(String sqlWhereString, Dialect dialect, SQLFunctionRegistry functionRegistry) {
return renderWhereStringTemplate(sqlWhereString, TEMPLATE, dialect, functionRegistry);
}
private Template();
@Deprecated @SuppressWarnings({ "JavaDoc" }) public stati... | String fragment = "trim( col )";
String template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY );
assertEquals( "trim(" + Template.TEMPLATE + ".col)", template );
fragment = "trim( from col )";
template = Template.renderWhereStringTemplate( fragment, Template.T... |
8049046_20 | class SimpleListPropertyCommandExecutor implements ListPropertyCommandExecutor {
@Override
public void execute(final AddToList command) {
final List<Object> list = getListOrFail(command);
final Object value = valueMapper.map(command.getValue());
silentChangeExecutor.execute(list, new ... | final AddToList command1 = new AddToList(exemplaryListId, exemplaryVersionChange, new Value("second"), 0);
final AddToList command2 = new AddToList(exemplaryListId, exemplaryVersionChange, new Value("first"), 0);
final AddToList command3 = new AddToList(exemplaryListId, exemplaryVersionChange, n... |
8054843_6 | class Hack {
public static HackedObject into(final Object source) {
return new HackedMirrorObject(source);
}
private Hack();
public static R mirrorStaticMethod(final String tag, final R fallback, final Object... args);
private static Method findSourceStaticMethod(final StackTraceElement[] stack, final int nu... | assertFail(ClassNotFoundException.class, Hack.into("NoSuchClass").method("nonSense").withoutParams());
assertFail(ClassNotFoundException.class, Hack.into(Simple.class).field("mIntField").ofType("NoSuchType"));
assertFail(ClassNotFoundException.class, Hack.into(Simple.class).staticField("mStaticField").ofType("NoS... |
8131104_25 | class RotationsToDistanceDecoder implements Decoder<T> {
@Override
public void update(T newPage) {
decoder.update(newPage);
}
public RotationsToDistanceDecoder(FilteredBroadcastMessenger<TaggedTelemetryEvent> updateHub, BigDecimal wheelCircumference);
public void reset();
@Override p... | FilteredBroadcastMessenger<TaggedTelemetryEvent> bus = new FilteredBroadcastMessenger<TaggedTelemetryEvent>();
class FreqListener implements BroadcastListener<TaggedTelemetryEvent> {
private long rotations;
public void receiveMessage(TaggedTelemetryEvent telemetryEvent) {
... |
8134070_1 | class UserManagerImpl extends UniversalManagerImpl implements UserManager, UserService {
public User getUser(String userId) {
return dao.get(new Integer(userId));
}
@Required public void setPasswordEncoder(PasswordEncoder passwordEncoder);
public List<User> getUsers(User user);
public Stri... | final User testData = new User("1");
testData.getRoles().add(new Role("user"));
// set expected behavior on dao
context.checking(new Expectations() {{
one(userDao).get(with(equal(1)));
will(returnValue(testData));
}});
User user = userMan... |
8135809_1 | class LuaSquidSensor implements Sensor {
@Override
public void execute(SensorContext context) {
FileSystem fileSystem = context.fileSystem();
FilePredicates predicates = fileSystem.predicates();
List<SquidAstVisitor<LexerlessGrammar>> visitors = new ArrayList<>(checks.all());
visitors.add(new FileL... | DefaultFileSystem fs = new DefaultFileSystem(TEST_DIR);
tester.setFileSystem(fs);
DefaultInputFile inputFile = new DefaultInputFile("key", "smallFile.lua")
.setType(InputFile.Type.MAIN)
.setLanguage(Lua.KEY)
.initMetadata(new FileMetadata().readMetadata(new FileReader(new File(TEST_DIR, "s... |
8139882_0 | class KieWorkbenchEntryPoint extends DefaultWorkbenchEntryPoint {
@PostConstruct
public void init() {
appFormerJsBridge.init("org.kie.bc.KIEWebapp");
homeConfiguration.setMonitoring(true);
workbench.addStartupBlocker(KieWorkbenchEntryPoint.class);
// Due to a limitatio... | kieWorkbenchEntryPoint.init();
verify(workbench).addStartupBlocker(KieWorkbenchEntryPoint.class);
verify(navTreeEditor).setMaxLevels(NavTreeDefinitions.GROUP_WORKBENCH,
2);
}
} |
8143599_92 | class SmppObject {
static public void setDebug(Debug dbg) {
debug = dbg;
}
static public void setEvent(Event evt);
static public Debug getDebug();
static public Event getEvent();
}
class SmppObjectTest {
@Test
public void testSetDebug() {
| Debug debug = mock(Debug.class);
SmppObject.setDebug(debug);
assertEquals(debug, SmppObject.getDebug());
}
} |
8147920_29 | class StatementSizeEstimator {
public static long estimatedSizeOf(Statement statement) {
Value object = statement.getObject();
Resource context = statement.getContext();
long result = STATEMENT_OVERHEAD
+ 2 * URI_BNODE_OVERHEAD // subject, predicate
+ OBJ_REF... | // Arrange
Statement statement = VALUE_FACTORY.createStatement(
VALUE_FACTORY.createBNode("http://a"),
VALUE_FACTORY.createURI("http://b"),
VALUE_FACTORY.createURI("http://c"),
VALUE_FACTORY.createURI("http://d"));
// Act
l... |
8155767_6 | class OwmClient {
public WeatherStatusResponse currentWeatherAtCity (float lat, float lon, int cnt) throws IOException, JSONException { //, boolean cluster, OwmClient.Lang lang) {
String subUrl = String.format (Locale.ROOT, "find/city?lat=%f&lon=%f&cnt=%d&cluster=yes",
Float.valueOf (lat), Float.valueOf (lon), ... | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_AT_CITY_ID_MOSKOW);
OwmClient owm = new OwmClient (mockHttpClient);
StatusWeatherData weatherData = owm.currentWeatherAtCity (524901);
assertEquals ("Moscow", weatherData.getName ());
assertEquals (524901, weatherData.getId... |
8166928_10 | class FunctionConsumer extends DefaultConsumer {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
long deliveryTag = envelope.getDeliveryTag();
Stopwatch stopwatch = Stopwatch.createStarted();
... | FunctionConsumer<TestMsg> consumer =
new FunctionConsumer<>(channel, msg -> {
throw new RuntimeException("Message processing failed on purpose.");
}, TestMsg.class, "name", metrics);
consumer.handleDelivery(null, envelope, null, message);
verify(channel)... |
8176370_4 | class HtmlHyperlink extends HtmlTagWithContent {
public void setHref(String href) {
this.href = href;
}
public HtmlHyperlink();
public HtmlHyperlink(String href, String label);
@Override protected StringBuilder getHtmlAttributes();
public String getHref();
public String getOnclick();
... | hyperlink.setId("fullId");
hyperlink.addCssClass("classy");
hyperlink.addCssStyle("styly");
hyperlink.setHref("fullHref");
hyperlink.addContent("valued");
assertThat(hyperlink.toHtml().toString()).isEqualTo("<a id=\"fullId\" class=\"classy\" style=\"styly\" href=\"fullHref\">valued</a>");
}
} |
8188105_4 | class OftpComponent extends DefaultComponent {
public OftpSettings getSettings() {
return settings;
}
public OftpComponent();
public OftpComponent(CamelContext context);
@Override protected void doStart();
@Override protected void doStop();
@Override protected Endpoint createEndpoint(String uri, String re... | OftpServerEndpoint endpoint = resolveMandatoryEndpoint("oftp-server://TheServerOID:secret@myhost/?" +
"userData=DEV&debSize=1496&restart=true&cipherSuite=tripledesRsaSha1");
OftpSettings config = endpoint.getSettings();
assertEquals("userData", "DEV", config.getUserData());
assertEquals("debSize", 1496, co... |
8201183_0 | class System extends Thread implements PlugIn {
public System(EngineManager engine) {
setName("System");
this.engine = engine;
}
public System(EngineManager engine);
@Override public void reciveMsg(SCSMsg msg);
private SCSMsg setTime(SCSMsg msg);
private Value getVersion();
private Value getKernel();
pr... | System sys = new System(null);
assertNotNull("System must be create", sys);
}
} |
8204840_6 | class TextContent extends Content implements LineText.ChangeListener {
@Override
public void onChange()
{
refresh();
}
public TextContent(LineText text);
@Override public void draw(Graphics2D graphics);
@Override protected void refreshUp();
@Override protected void refreshDow... | SingleLineText singleLineText = new SingleLineText();
TextContent textContent = new TextContent(singleLineText);
TestingRefreshContent testingRefreshContent = new TestingRefreshContent();
testingRefreshContent.setAsParent(textContent);
assertEquals(0, testingRefreshContent.refre... |
8212556_25 | class StringTools {
public static boolean isBlank(CharSequence sourceSequence) {
int sequenceLength;
if (sourceSequence == null || (sequenceLength = sourceSequence.length()) == 0) {
return true;
}
for (int i = 0; i < sequenceLength; i++) {
if ((Character.isWh... | Assert.assertFalse(StringTools.isBlank(" a a "));
Assert.assertFalse(StringTools.isBlank("a a"));
Assert.assertFalse(StringTools.isBlank(" a "));
Assert.assertFalse(StringTools.isBlank("a"));
Assert.assertTrue(StringTools.isBlank(" "));
Assert.assertTrue(StringTools.isB... |
8236056_71 | class ShortMap implements Iterable<ShortMap.Entry<V>> {
public V remove (short key) {
if (key == 0) {
if (!hasZeroValue) return null;
V oldValue = zeroValue;
zeroValue = null;
hasZeroValue = false;
size--;
return oldValue;
}
... | testAdd();
Assert.assertNull(shortMap.remove((short) 100));
Assert.assertEquals("NewExample123", shortMap.remove((short) 123));
Assert.assertEquals(2, shortMap.size);
Assert.assertEquals("Example34", shortMap.remove((short) 34));
Assert.assertEquals(1, shortMap.size);
... |
8262372_172 | class FavoredNodeAssignmentHelper {
Map<HRegionInfo, ServerName[]> placeSecondaryAndTertiaryRS(
Map<HRegionInfo, ServerName> primaryRSMap) {
Map<HRegionInfo, ServerName[]> secondaryAndTertiaryMap =
new HashMap<HRegionInfo, ServerName[]>();
for (Map.Entry<HRegionInfo, ServerName> entry : primary... | // Test the case where there is only one server in one rack and another rack
// has more servers. We try to choose secondary/tertiary on different
// racks than what the primary is on. But if the other rack doesn't have
// enough nodes to have both secondary/tertiary RSs, the tertiary is placed
// o... |
8276360_0 | class FileIngestorRouteBuilder extends RouteBuilder {
protected String getEnqueueRecordsDestinationUri() {
return "activemq:queue:" + recordsQueueName;
}
@Override public void configure();
public String getSourceDirPath();
public void setSourceDirPath(String sourceDirPath);
public String getDoneDirPath();
p... | RouteDefinition routeDef = context.getRouteDefinition(
FileIngestorRouteBuilder.ENQUEUE_RECORD_ROUTE_ID);
routeDef.adviceWith(context, new RouteBuilder() {
@Override
public void configure() throws Exception {
interceptSendToEndpoint(builder.getEnqueueRecordsDestinationUri())
.choice()
... |
8279377_2 | class DVUtil {
static Double calculateDurationAgainstDvTemporal(String value, DvTemporal operationTemporal, String symbol) {
DateTime dateTime = getDateTime(operationTemporal, value);
return calculateDurationAgainstDateTime(value, dateTime, symbol);
}
public static DataValue createDV(
... | Double aDouble = DVUtil.calculateDurationAgainstDvTemporal("365, d", new DvDateTime("2016-01-01T12:00:00"), "-");
assertThat(aDouble, equalTo(3.1536E10));
}
} |
8289370_122 | class AttachmentService {
public boolean updateAttachmentContent(String name, EntityRef parent, IndicatingInputStream is, long length, boolean silent) {
Map<String,String> headers = Collections.singletonMap("Content-Type", "application/octet-stream");
MyResultInfo result = new MyResultInfo();
... | handler.addRequest("PUT", "/qcbin/rest/domains/domain/projects/project/defects/1/attachments/logfile.txt", 200)
.expectHeader("Content-Type", "application/octet-stream")
.content("attachmentServiceTest_attachment.xml");
handler.async();
addEntityListener(new Enti... |
8296012_4 | class StreamLogger implements Runnable {
@Override
public void run() {
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
log.info(line);
}
} catch (IOException e) {
throw new TaskException("Exception while interce... | Log mockLog = EasyMock.createStrictMock(Log.class);
mockLog.info("Two peas in a bucket.");
mockLog.info("Big ham ham ham.");
EasyMock.expectLastCall();
EasyMock.replay(mockLog);
InputStream in = new ByteArrayInputStream("Two peas in a bucket.\nBig ham ham ham.\n".getByte... |
8322886_1 | class MixPanelOutputConnector extends AbstractPipelineComponent implements OutputConnector, Configurable<JSONObject> {
protected void logActivity(JSONObject payload) throws JSONException, IOException {
String eventName = payload.getString("event");
JSONObject properties = payload.getJSONObject("pro... | MixPanelOutputConnector mixPanelOutputConnector = new MixPanelOutputConnector() {
@Override
protected MixpanelAPI getMixpanelAPI() {
return new MixpanelAPI(mockMixpanelServer.getServerURL() + "/track", null);
}
};
mixPanelOutputConnector.setPip... |
8333478_3 | class SpaceTaskAPIController {
@RequestMapping(value = "/execute",method=RequestMethod.POST)
public ModelAndView executeTask(@RequestParam String spaceName,@RequestParam String locators,@RequestBody SpaceTaskRequest body)
{
return execute(spaceName,locators,body);
}
public SpaceTaskAPIController();
private ... | space.getTypeManager().registerTypeDescriptor(new SpaceTypeDescriptorBuilder("test-type")
.idProperty("id",false).addFixedProperty("val",String.class).create());
space.clear(new Object());
SpaceDocument d=new SpaceDocument("test-type");
d.setProperty("id",0);
d.setProperty("val","val0");
space.write(d);... |
8369425_1 | class StableTicksAxis extends ValueAxis<Number> {
public static double calculateTickSpacing( double delta, int maxTicks ) {
if ( delta == 0.0 )
return 0.0;
if ( delta <= 0.0 )
throw new IllegalArgumentException( "delta must be positive" );
if ( maxTicks < 1 )
throw new IllegalArgumentException( "must b... | assertEquals( 5e10, StableTicksAxis.calculateTickSpacing( 23e10, 5 ), 0.0001e10 );
}
} |
8411032_2 | class Trie {
public T check(final String aString) {
final char[] chars = aString.toCharArray();
for (int i = 0; i < chars.length; i++) {
final Node<T> root = this.roots.get(chars[i]);
if (root != null) {
final T res = root.check(chars, i);
if ... | final String toBeChecked = "Test";
final Elem z = this.trie.check(toBeChecked);
Assert.assertNull(z);
}
} |
8426406_624 | class RegexStringMatcher extends BodyMatcher<NottableString> {
public boolean matches(String matched) {
return matches(null, string(matched));
}
public RegexStringMatcher(MockServerLogger mockServerLogger, boolean controlPlaneMatcher);
RegexStringMatcher(MockServerLogger mockServerLogger, N... | assertFalse(notMatcher(new RegexStringMatcher(new MockServerLogger(), string("some_value"), true)).matches("some_value"));
}
} |
8427412_17 | class StockOperationServiceImpl extends BaseOpenmrsService implements IStockOperationService {
public void calculateReservations(StockOperation operation) {
if (operation == null) {
throw new IllegalArgumentException("The operation must be defined");
}
/*
We want to ensure that duplicated transactions ar... | Stockroom sourceRoom = stockroomDataService.getById(0);
Stockroom destRoom = stockroomDataService.getById(1);
Item item0 = itemDataService.getById(0);
Item item2 = itemDataService.getById(2);
// Add some item stock with different qualifiers to the source room
ItemStockDetail detail1 = new ItemStockDetail(... |
8428305_19 | class Indexer implements ActorStateUpdateListener {
@Override
public final void onUpdate(List<? extends ActorStateUpdate> updates) {
updates.stream().filter(
update -> update.getActorClass().getAnnotation(IndexConfig.class) != null
).forEach(update ->
{
... | ActorStateUpdate update = createActorStateUpdateReindexing("1.0.0");
when(update.getLifecycleStep()).thenReturn(ActorLifecycleStep.ACTIVATE);
indexer.onUpdate(newArrayList(update));
await()
.atMost(Durations.ONE_MINUTE)
.pollInterval(ONE_HUNDRED_MILLISEC... |
8436798_1 | class FormExtractor implements IExtractor {
@Override
public String extractValue(IHttpRequest request) {
return StringUtils.defaultIfEmpty(request.getFormParameterValue(key), null);
}
public FormExtractor(String key);
}
class FormExtractorTest {
@Test
public void testFormExtraction()
{
| IHttpRequest request = mock(IHttpRequest.class);
when(request.getFormParameterValue(eq("testField"))).thenReturn("test");
FormExtractor extractor = new FormExtractor("testField");
assertEquals("test", extractor.extractValue(request));
when(request.getFormParameterValue(eq("testField"))).thenReturn(null)... |
8467178_18 | class Configuration {
public void setEndpoints(String notify, String sessions) throws IllegalArgumentException {
if (notify == null || notify.isEmpty()) {
throw new IllegalArgumentException("Notify endpoint cannot be empty or null.");
} else {
if (delivery instanceof HttpDel... | Delivery delivery = new Delivery() {
@Override
public void deliver(Serializer serializer, Object object, Map<String, String> headers) {
}
@Override
public void close() {
}
};
config.delivery = delivery;
config.sessi... |
8497273_2 | class PathUtils {
public static String relativePath(File parent, File child) {
Preconditions.checkArgument(contains(parent, child));
String parentName = conventPath(parent);
String childName = conventPath(child);
String relative = childName.substring(parentName.length());
... | File parent = new File("/");
File child = new File("/");
Assert.assertEquals(PathUtils.relativePath(parent, child), "/");
parent = new File("/");
child = new File("/opt");
Assert.assertEquals(PathUtils.relativePath(parent, child), "/opt");
parent = new File("/"... |
8504385_1 | class ServerOption implements Serializable {
public static Gson getGson() {
Gson gson = new GsonBuilder().
registerTypeAdapter(ServerOption.class, new ServerOptionParentDeserializer()).
excludeFieldsWithoutExposeAnnotation().
create();
return gson;
}
public ServerOption();
public ServerOption(fi... | URL url = Thread.currentThread().getContextClassLoader().getResource("at/alladin/rmbt/util/model/option/test3.json");
File file = new File(url.getPath());
ServerOptionContainer options = new ServerOptionContainer(
new ArrayList<>(Arrays.asList(ServerOption.getGson().fromJson(new FileReader(file), ServerOption... |
8530120_97 | class Asset {
public void copyAssetsFromContent(File path) {
copy(path, config.getDestinationFolder(), FileUtil.getNotContentFileFilter());
}
@Deprecated public Asset(File source, File destination, CompositeConfiguration config);
public Asset(JBakeConfiguration config);
public void copy... | URL contentUrl = this.getClass().getResource("/fixture/content");
File contents = new File(contentUrl.getFile());
Asset asset = new Asset(config);
asset.copyAssetsFromContent(contents);
int totalFiles = countFiles(folder.toFile());
int expected = 3;
Assertions.a... |
8570603_1 | class PipedPromise extends DeferredObject<D_OUT, F_OUT, P_OUT> implements Promise<D_OUT, F_OUT, P_OUT> {
protected Promise<? extends D_OUT, ? extends F_OUT, ? extends P_OUT> pipe(
Promise<? extends D_OUT, ? extends F_OUT, ? extends P_OUT> promise) {
promise.done(new DoneCallback<D_OUT>() {
@Override
public... | final ValueHolder<String> preRewireValue = new ValueHolder<String>();
final ValueHolder<String> postRewireValue = new ValueHolder<String>();
Callable<Integer> task = new Callable<Integer>() {
public Integer call() {
throw new RuntimeException("oops");
}
};
deferredManager.when(task).pipe(null, new... |
8575137_0 | class BindingSet implements BindingInformationProvider {
static String asHumanDescription(Collection<? extends MemberViewBinding> bindings) {
Iterator<? extends MemberViewBinding> iterator = bindings.iterator();
switch (bindings.size()) {
case 1:
return iterator.next().getDescription();
c... | MemberViewBinding one = new TestViewBinding("one");
MemberViewBinding two = new TestViewBinding("two");
MemberViewBinding three = new TestViewBinding("three");
String result1 = asHumanDescription(singletonList(one));
assertThat(result1).isEqualTo("one");
String result2 = asHumanDescription(asL... |
8582237_64 | class UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> {
@Override
public long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation) {
double startSelectivity = start==null?0.0d:quantilesSketch.getCDF(new ExecRow[]{start})[0];
... | Assert.assertEquals(4000.0d,(double) impl.rangeSelectivity(row2000,row6000,true,false),50.0d);
}
} |
8595333_34 | class HttpConfiguration {
public int getMaxHttpConnection() {
return maxHttpConnection;
}
public HttpConfiguration();
public String getIpAddress();
public void setIpAddress(String ipAddress);
public String getProxyUserName();
public void setProxyUserName(String proxyUserName);
public String getProxyPasswo... | Assert.assertEquals(httpConf.getMaxHttpConnection(), 10);
}
} |
8599516_1 | class RecyclingPagerAdapter extends PagerAdapter {
@Override public final void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
int viewType = getItemViewType(position);
if (viewType != IGNORE_ITEM_VIEW_TYPE) {
recycleBin.add... | LinearLayout container = new LinearLayout(context);
TextView child = new TextView(context);
container.addView(child);
RecyclingPagerAdapter adapter = new RecyclingPagerAdapter(recycleBin) {
@Override public int getItemViewType(int position) {
return IGNORE_ITEM_VIEW_TYPE;
}
@... |
8621768_4 | class Loader {
public ClassLoader getClassLoader() {
// get jars if somehing changed
File[] jars = getJarsIfSomeIsModifiedAfterInterval();
if (jars == null)
return currentClassLoader;
// update classloader
synchronized (this) {
try {
// copy jars to a new spooldir
File newSpoolDir = copyJars... |
updateJar("a");
updateJar("b");
msg("change to urlcl");
Thread.sleep(200);
ClassLoader cur = loader.getClassLoader();
assertTr(cur != parent);
assertTr(cur instanceof JarClassLoader);
// loader.close();
msg("no change");
Thread.sleep(200);
assertTr(cur == loader.getClassLoader());
msg("chang... |
8629076_1 | class FileTools {
public static File doChoosePath() {
JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home"));
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) {
return fil... | System.out.println("doChoosePath");
File expResult = null;
File result = FileTools.doChoosePath();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
} |
8648747_53 | class CryptoUtils {
public synchronized long toDigest(final String key) throws DigestException, UnsupportedEncodingException {
if (key == null) {
throw new NullPointerException("You attempted to convert a null string into a hash digest");
}
final byte[] bytes = key.getB... | assertNotEquals(cryptoUtils.toDigest(imageUrl1), cryptoUtils.toDigest(imageUrl3));
}
} |
8672234_4 | class Speller {
public List<String> replaceRunOnWords(final String original) {
final List<CandidateData> candidateData = replaceRunOnWordCandidates(original);
final List<String> candidates = new ArrayList<>();
for (CandidateData candidate : candidateData) {
candidates.add(candidate.word);
}
... | final Speller spell = new Speller(dictionary);
Assertions.assertThat(spell.replaceRunOnWords("abaka")).isEmpty();
Assertions.assertThat(spell.replaceRunOnWords("abakaabace")).contains("abaka abace");
Assertions.assertThat(spell.replaceRunOnWords("Abakaabace")).contains("Abaka abace");
// Test on an... |
8680105_8 | class WorldDestination extends SimpleDestination {
@NotNull
@Override
protected EntityCoordinates getDestination() throws TeleportException {
MultiverseWorld mvWorld = this.getApi().getWorldManager().getWorld(world);
if (mvWorld == null) {
throw new TeleportException(Message.bu... | BasePlayer player = api.getServerInterface().getPlayer("Player");
assertNotNull(player);
// Location must be middle of block since our safe teleporter does this
((Entity) player).teleport(Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 50.5, 50, 50.5, 0, 0));
Worl... |
8682860_4 | class TimerPresenter implements TimerActivityContract.UserActionsListener {
public static void roundTimeUp(Calendar calendar) {
calendar.set(Calendar.SECOND, 0);
// Round to the nearest MINUTE_INCREMENT, advancing the clock at least MINIMUM_INCREMENT.
int remainder = calendar.get(Calendar.M... | Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.MINUTE, TimerPresenter.MINIMUM_INCREMENT);
TimerPresenter.roundTimeUp(calendar);
assertThat(calendar.get(Calendar.SECOND), is(0));
assertThat(calendar.get(Calendar.MINUTE), is(TimerPresenter.MINUTE_INCREMENT));
... |
8693016_2 | class RF1Importer extends BaseImporter {
public VersionRows extractVersionRows() {
// Read all the concepts from the raw data
List<ConceptRow> crs = new ArrayList<ConceptRow>();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamRead... | try {
RF1Importer rf1i = new RF1Importer(
this.getClass().getResourceAsStream("/rf1_con_test.txt"),
this.getClass().getResourceAsStream("/rf1_rel_test.txt"),
"20110731");
VersionRows vr1 = rf1i.extractVersionRows();
... |
8706918_55 | class Newer extends BaseExpression {
@Override
public Result apply(PathData item) throws IOException {
if(getFileStatus(item).getModificationTime() > filetime) {
return Result.PASS;
}
return Result.FAIL;
}
public Newer();
@Override public void initialise(FindOptions options);
@Override... | FileStatus fileStatus = mock(FileStatus.class);
when(fileStatus.getModificationTime()).thenReturn(NOW - (4l*86400000));
fs.setFileStatus("newer.file", fileStatus);
PathData item = new PathData("/directory/path/newer.file", fs.getConf());
assertEquals(Result.PASS, newer.apply(item));
}
} |
8714569_2 | class NormalisedOntology implements Serializable {
public Set<Inclusion> normalise(final Set<? extends Axiom> inclusions) {
// Exhaustively apply NF1 to NF4
Set<Inclusion> newIs = transformAxiom(inclusions);
Set<Inclusion> oldIs = new HashSet<Inclusion>(newIs.size());
final... | IFactory factory = new CoreFactory();
// Add roles
NamedRole container = new NamedRole("container");
NamedRole contains = new NamedRole("contains");
// Add features
NamedFeature mgPerTablet = new NamedFeature("mgPerTablet");
// Add concepts
NamedConcept... |
8715861_5 | class PGTypeTable implements Table<PGTypeTable.Row> {
@Override
public String getSQL(Version currentVersion) {
return Tables.getSQL(SQL, currentVersion);
}
private PGTypeTable();
@Override public Row createRow(Context context, ResultBatch resultBatch, int rowIdx);
@Rule
public final ExpectedExcep... | assertEquals(INSTANCE.getSQL(Version.parse("9.1.9")), SQL[3]);
}
} |
8731044_81 | class TemplatingFunctions {
public Property inheritProperty(Node content, String relPath) throws RepositoryException {
if (content == null) {
return null;
}
if (StringUtils.isBlank(relPath)) {
throw new IllegalArgumentException("relative path cannot be null or empty"... | // GIVEN
// WHEN
Property property = functions.inheritProperty(topPage, "iMaybeExistSomewhereElseButNotHere");
Property property2 = functions.inheritProperty(topPageComponent, "iMaybeExistSomewhereElseButNotHere");
// THEN
assertNull(property);
assertNull(propert... |
8744004_2 | class MyService {
@POST
@Path("/permissions")
public Response permissions(String body, @Context GraphDatabaseService db) throws IOException {
String[] splits = body.split(",");
PermissionRequest ids = new PermissionRequest(splits[0], splits[1]);
Set<String> documents = new HashSet<S... | String ids = "A,DOC1 DOC2 DOC3 DOC4 DOC5 DOC6 DOC7";
Response response = service.permissions(ids, db);
List list = objectMapper.readValue((String) response.getEntity(), List.class);
assertEquals(new HashSet<String>(Arrays.asList("DOC1", "DOC2", "DOC3", "DOC4", "DOC5", "DOC7")), new Hash... |
8750145_6 | class List {
public abstract <B> List<B> map(Function<A, B> func)public abstract <B> List<B> map(Function<A, B> func);
public abstract <B> List<B> map(Function<A, B> func)private List();
public abstract <B> List<B> map(Function<A, B> func)public abstract List<B> bind(Function<A, List<B>> func);
public abstract <B> ... | // Given a list
List<Integer> list = itemList(1, 2, 3);
// When an increment function is mapped across it
List<Integer> result = list.map(i -> i + 1);
// Then each of the elements is incremented
assert(result.equals(itemList(2, 3, 4)));
}
} |
8757198_2 | class TarjanLowestCommonAncestor {
public V calculate(V start, V a, V b)
{
List<LcaRequestResponse<V>> list =
new LinkedList<LcaRequestResponse<V>>();
list.add(new LcaRequestResponse<V>(a, b));
return calculate(start, list).get(0);
}
TarjanLowestCommonAncestor(Gra... | DirectedGraph<String, DefaultEdge> g = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
g.addVertex("a");
g.addVertex("b");
g.addVertex("c");
g.addVertex("d");
g.addVertex("e");
g.addVertex("f");
g.addVertex("g");
g.addEdge("a", "b");
g.addEdge("b", "c");
g.addEdge("c", "d");
g.addEdge("d... |
8759133_1 | class ZuulFiltersModule extends AbstractModule {
@VisibleForTesting
String[] findFilterLocations(AbstractConfiguration config) {
String[] locations = config.getStringArray("zuul.filters.locations");
if (locations == null) {
locations = new String[]{"inbound", "outbound", "endpoint"}... | Mockito.when(configuration.getStringArray("zuul.filters.locations")).thenReturn(new String[0]);
String[] filterLocations = module.findFilterLocations(configuration);
assertThat(filterLocations.length, equalTo(0));
}
} |
8772570_1 | class FreeDBTAGWizardPlugin implements TAGWizardPlugin {
@Override
public String getName()
{
return NAME;
}
@Override public float getVersion();
@Override public float getMinimumMessicVersion();
@Override public String getDescription( Locale locale );
@Override public Propertie... | FreeDBTAGWizardPlugin d = new FreeDBTAGWizardPlugin();
Assert.assertTrue( d.getName().equals( FreeDBTAGWizardPlugin.NAME ) );
}
} |
8777778_3 | class MsgDeliveryTagMapping {
void basicReject(long deliveryTag, boolean requeue) throws IOException {
Map<Long, MsgResponse> rejections = deliveryTags.subMap(deliveryTag, deliveryTag + 1);
eachChannelOnce(rejections, MsgResult.REJECT, false, requeue);
rejections.clear();
}
MsgDeliveryTagMapping()... | when(envelope.getDeliveryTag()).thenReturn(43L);
Envelope e = map.envelopeWithPseudoDeliveryTag(channel, envelope);
assertNotEquals(43L, e.getDeliveryTag());
assertDoesNotThrow(() -> map.basicReject(e.getDeliveryTag(), false));
assertDoesNotThrow(() -> verify(channel).basicReject(43L, false));
}
... |
8786725_102 | class DeviceManager implements RadarListener {
@Override
public void deviceLeft(NetworkDevice device) {
if (device == null || device.getNetworkDeviceName() == null || device.getNetworkDeviceType() == null) return;
// Remove what services this device has.
logger.info("Device "+device.getNetworkDeviceName()+" of... | NetworkDevice leavingGuy = networkDevice("ADDR_UNKNOWN", "UNEXISTANT");
assertEquals(1, dao.list().size());
UpDriver driver = new UpDriver("DD");
driver.addService("s");
driverDao
.insert(new DriverModel("id1", driver, currentDevice.getName()));
driverDao
.insert(new DriverModel("id2", driver, curre... |
8791847_17 | class IntRange extends AbstractList<Integer> implements ArrayWritable<Integer>, RandomAccess, Serializable {
@Override
public int size() {
return size;
}
IntRange(int start, int end);
IntRange(int start, int end, int step);
@Override public Integer get(int index);
public int i... | Assert.assertEquals(ir0.size(), 10);
Assert.assertEquals(ir1.size(), 4);
}
} |
8824082_4 | class BeanPropertiesMapper implements NodePropertiesMapper<T> {
public T mapNodeProperties(final NodeRef nodeRef, final Map<QName, Serializable> properties) {
try {
T mappedObject = this.mappedClass.newInstance();
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
afterBeanWrapp... | Date testDate = new Date();
BeanPropertiesMapper<CmFolder> mapper = new BeanPropertiesMapperRegistry(namespaceService, dictionaryService)
.addBeanPropertiesMapper(this.mapper).getForClass(CmFolder.class);
CmFolder cmFolder = mapper.mapNodeProperties(NODE_REF,
ImmutableMap.of(QName.createQName("custom_uri"... |
8853829_0 | class Order {
public double getTotal() {
double total = 0;
for (Product product : products) {
total += product.getPrice();
}
return total;
}
public Order(Product ... products);
private static final double ERROR;
}
class OrderTest {
private static final double ERROR;
@Test
public void should_su... | Order order = new Order(new Product(30), new Product(40.0));
assertEquals(70.0, order.getTotal(), ERROR);
}
} |
8859474_6 | class JSources extends JNode {
List<JPackage> getHierarchyPackages(List<JavaPackage> packages) {
Map<String, JPackage> pkgMap = new HashMap<>();
for (JavaPackage pkg : packages) {
addPackage(pkgMap, new JPackage(pkg, wrapper));
}
// merge packages without classes
boolean repeat;
do {
repeat = false;... | List<JavaPackage> packages = asList(
newPkg("a.p1"),
newPkg("a.b.c.p2"),
newPkg("a.b.c.p3"),
newPkg("d.e"),
newPkg("d.f.a"));
List<JPackage> out = sources.getHierarchyPackages(packages);
assertThat(out, hasSize(2));
assertThat(out.get(0).getName(), is("a"));
assertThat(out.get(0).getInner... |
8914350_60 | class AsyncSuroSender implements Runnable {
public void run() {
boolean sent = false;
boolean retried = false;
long startTS = System.currentTimeMillis();
for (int i = 0; i < config.getRetryCount(); ++i) {
ConnectionPool.SuroConnection connection = connectionPool.chooseC... | AsyncSuroClient client = injector.getInstance(AsyncSuroClient.class);
for (SuroServer4Test c : servers) {
c.setTryLater();
}
AsyncSuroSender sender = new AsyncSuroSender(
TestConnectionPool.createMessageSet(600),
client,
injec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.