id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
21148694_16 | class CellTimestampComparator implements Comparator<Cell> {
public int compare(Cell o1, Cell o2) {
return Long.valueOf(o1.getTimestamp()).compareTo(o2.getTimestamp());
}
}
class CellTimestampComparatorTest {
@Test
public void test_equal() {
| // mocking
Cell cell1 = Mockito.mock(Cell.class);
Mockito.when(cell1.getTimestamp()).thenReturn(13945345808L);
Cell cell2 = Mockito.mock(Cell.class);
Mockito.when(cell2.getTimestamp()).thenReturn(13945345808L);
CellTimestampComparator comparator = new CellTimestampComparator();
// actual c... |
21153865_10 | class SearchTool extends AbstractAuthBasedThriftServiceClient {
protected static Output getQuestions(String query) {
// ?:What is blue?
// ?:"What is blue?"
// ?:What is blue
Matcher matcher = PATTERN.matcher(query);
List<String> questions = new ArrayList<>();
while (matcher.find()) {
... | String q1 = "?:What is blue? ?:What is green?";
Output output = SearchTool.getQuestions(q1);
assertEquals("What is blue?", output.items.get(0));
assertEquals("What is green?", output.items.get(1));
assertEquals("", output.query);
String q2 = "colors ?:\"What is red?\" ?:... |
21180741_325 | class FhirSystemDaoR4 extends BaseHapiFhirSystemDao<Bundle, Meta> {
@Transactional(propagation = Propagation.NEVER)
@Override
public Bundle transaction(RequestDetails theRequestDetails, Bundle theRequest) {
return myTransactionProcessor.transaction(theRequestDetails, theRequest);
}
@Override @PostConstruct pub... | Bundle inputBundle = new Bundle();
inputBundle.setType(Bundle.BundleType.TRANSACTION);
Encounter enc1 = new Encounter();
enc1.addIdentifier().setSystem("urn:foo").setValue("12345");
inputBundle
.addEntry()
.setResource(enc1)
.getRequest()
.setMethod(HTTPVerb.PUT)
.setUrl("Encounter?identifier=... |
21182169_0 | class UriQueryParser {
public static Map<String, List<String>> getUrlParameters(String url) {
try {
final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>();
final String[] pairs = getQuery(url).split("&");
for (String pair : pairs) {
... |
String uri = "/stuff/test?param1=itworked¶m2=rad¶m1=cool";
Map<String, List<String>> params = UriQueryParser.getUrlParameters(uri);
assertNotNull(params);
assertEquals(2, params.get("param1").size());
assertEquals("itworked", params.get("param1").get(0));
asser... |
21190869_0 | class AuroraTableNameServiceImpl implements AuroraTableNameService<T> {
@Override
public Try<TableName> resolveTableNameByHint(T hint) {
Validate.notNull(hint);
TableName tableName = tableNameResolver.apply(hint);
if (tableNames != null && !containsInTableNames(tableName)) {
... | AuroraTableNameService<Integer> atns = AuroraTableNameServiceFactory.create(new AbstractTableNameResolver<Integer>("user") {
@Override
protected String getSuffixName(Integer hint) {
return Integer.toString(hint % 2);
}
});
TableName tableName1 ... |
21193524_24 | class Util {
public static String toLinux(String s) {
return s.replace("\r\n", "\n");
}
private Util();
public static boolean isSingleValue(SqlCall call);
public static void discard(Object o);
public static void discard(int i);
public static void discard(boolean b);
public static void discard(do... | String[] before = {
"Get a dose of her in jackboots and kilt",
"She's killer-diller when she's dressed to the hilt",
"She's the kind of a girl that makes The News of The World",
"Yes you could say she was attractively built.",
"Yeah yeah yeah."
};
String[] after = {
... |
21217047_173 | class InPlaceRightRotator implements Rotator<E, MutableBinaryTreeNode<E>> {
@Override
public void rotate(ParentReference<MutableBinaryTreeNode<E>> reference, MutableBinaryTreeNode<E> currentRoot) {
final MutableBinaryTreeNodeImpl<E> root = (MutableBinaryTreeNodeImpl<E>)currentRoot;
final Mutabl... | final ParentReferenceFactoryImpl<String> factory = new ParentReferenceFactoryImpl<>();
final MutableBinaryTreeNodeImpl<String> a = new MutableBinaryTreeNodeImpl<>("a");
final MutableBinaryTreeNodeImpl<String> c = new MutableBinaryTreeNodeImpl<>("c");
final MutableBinaryTreeNodeImpl<Strin... |
21235372_2 | class Fibo {
public static int fibo(int n) {
if (n < 0) {
throw new IllegalArgumentException("n must be positive");
}
if (n <= 1) {
return n;
}
return fibo(n - 1) + fibo(n - 2);
}
@Parameter(0)
public int x;
@Parameter(1)
public i... | assumeThat(expectedException).isNotNull();
assertWhen((p) -> Fibo.fibo(p), x).throwException(
instanceOf(expectedException));
}
} |
21242302_0 | class TemplateImpl implements Template {
@Override
public String getTemplateStringWithoutColumnNames() {
return templateStringWithoutColumnNames;
}
TemplateImpl();
TemplateImpl(String template);
private static boolean isEscaped(int index, char[] chars);
@Override public String... |
assertEquals("http://ex.org/",
new TemplateImpl("http://ex.org/").getTemplateStringWithoutColumnNames());
assertEquals("http://ex.org/{}",
new TemplateImpl("http://ex.org/{name}").getTemplateStringWithoutColumnNames());
assertEquals("http://ex.org/{}/",
... |
21248236_23 | class LitecoinAddressValidator implements ICryptoAddressValidator {
@Override
public boolean isAddressValid(String address) {
if (address.startsWith("L") || address.startsWith("3") || address.startsWith("M")) {
try {
Base58.decodeToBigInteger(address);
Base58... | LitecoinAddressValidator lav = new LitecoinAddressValidator();
String address = "MMR2PV6EqX617NYzVsztfMFRZTr6zDHWQx";
boolean isValid = lav.isAddressValid(address);
Assert.assertTrue(isValid);
}
} |
21252787_66 | class NodeRef implements Bounded, Comparable<NodeRef> {
public static void checkValidPath(final String path) {
if (path == null) {
throw new IllegalArgumentException("null path");
}
if (path.isEmpty()) {
throw new IllegalArgumentException("empty path");
}
... | assertThrows(IllegalArgumentException.class, () -> NodeRef.checkValidPath(null));
}
} |
21257044_10 | class ServerInstanceContext {
public static ServerInstanceContext initialize() {
try {
return new ServerInstanceContext();
} catch (Exception e) {
LOGGER.warn("Caught exception initializing AWS Instance Context.",e);
return null;
}
}
private Ser... | Assert.assertNull(ServerInstanceContext.initialize());
}
} |
21266289_82 | class CommodityActionService {
public int getMonthlyValue(Commodity commodity, Date startingDate, Date endDate, DataElementType dataElementType) {
SQLiteOpenHelper openHelper = LmisSqliteOpenHelper.getInstance(context);
int commodityActionValueQuantity = 0;
try {
Dao<CommodityAc... | Commodity commodity = commodityService.all().get(1);
Calendar calendar = Calendar.getInstance();
calendar.set(2014, Calendar.APRIL, 01);
Date startDate = calendar.getTime();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date endDa... |
21285858_2 | class MesosNimbus implements INimbus {
public Map<String, List<TaskInfo>> getTasksToLaunch(Topologies topologies,
Map<String, Collection<WorkerSlot>> slots,
Map<String, AggregatedOffers> aggregatedOffersPerNod... | TopologyDetails t1 = TestUtils.constructTopologyDetails("t1",
MesosNimbusTest.DEFAULT_WORKER_COUNT,
MesosCommon.DEFAULT_WORKER_CPU,
Meso... |
21330228_66 | class GroovyshCommand implements CliCommand {
@Override
public int run(@Nonnull ProcessStream process) throws CmdLineException {
IO io = new IO(new BufferedInputStream(process.in()), process.out(), process.err());
// Do not use .inputrc as jline does not interpret it correctly: https://github... | stdin("D.runtime.threads.size()%n");
run("groovysh", "--in", "threaddump:" + logPath);
assertThat(err.toString(), equalTo(""));
assertThat(out.toString(), containsString(" 18%n"));
assertThat(this, succeeded());
}
} |
21352848_115 | class CreateCandidatesMapper implements MapFunction<ParsedWikiDocument, WikiDocumentOutput> {
public static int closestIdentifierPosition(List<Integer> positions, int wordIdx) {
if (positions.isEmpty()) {
return -1;
}
Iterator<Integer> it = positions.iterator();
int bestPos = it.next();
int... | List<Integer> positions = Arrays.asList(10);
int actual = CreateCandidatesMapper.closestIdentifierPosition(positions, 4);
assertEquals(10, actual);
}
} |
21357013_15 | class ProtoDOMBuilder {
public static ProtoNode buildDOM(byte[] data) throws ProtoReaderException {
ProtoStreamNode node = new ProtoStreamNode(-1, data);
return node;
}
private ProtoDOMBuilder();
public static ProtoNode buildDOM(byte[] data, int startOffset, int dataSize);
priva... | ByteArrayOutputStream subOut = new ByteArrayOutputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ProtoWriter pw = new ProtoWriter(out);
pw.put(TEST_TAG_1);
pw.put(CoreTags.TAG_STREAM, subOut);
pw.put(TEST_TAG_2, "test");
pw.flush();
Pro... |
21357853_0 | class DateTimeUtils {
public static String iso8601UTCFromDate(Date date) {
if (date == null) {
return "";
}
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat formatter = ISO8601_FORMAT.get();
formatter.setTimeZone(tz);
String iso8601date = formatter.... | // Arrange
TimeZone.setDefault(TimeZone.getTimeZone("GMT+2:00"));
Date date = new Date(mDefaultDate);
String expected = "2019-07-30T10:54:18+00:00";
// Act
String actual = DateTimeUtils.iso8601UTCFromDate(date);
// Assert
assertThat(actual).isEqualTo(exp... |
21363553_1 | class JMHAssertions {
public static JMHRunBuilderAssert assertJMH() {
return new RunBuilderAssert();
}
private JMHAssertions();
public static JMHRunResultsAssert assertJMH(Options options);
public static JMHRunResultsAssert assertJMH(Collection<RunResult> results);
public static JMHR... | assertJMH().hasResults();
}
} |
21366948_53 | class MetaverseLogicalIdGenerator implements ILogicalIdGenerator {
@Override
public String generateId( IHasProperties propertiesNode ) {
Set<String> propertyKeys = getLogicalIdPropertyKeys();
if ( propertiesNode.getPropertyKeys().size() == 0 ) {
return null;
}
String logicalId = null;
... | String[] logicalIdKeys = new String[] { "name", "type", "dataSource" };
idGenerator = new MetaverseLogicalIdGenerator( logicalIdKeys );
String expected = "{\"dataSource\":{\"name\":\"Sampledata\",\"type\":\"Database Connection\"}," +
"\"name\":\"SALES_DATA\",\"type\":\"Database Table\"}";
when( ... |
21367254_93 | class Linear extends TransferFunction implements Serializable {
@Override
public double getDerivative(double net) {
return this.slope;
}
public Linear();
public Linear(double slope);
public Linear(Properties properties);
public double getSlope();
public void setSlope(double slope);
@Override public dou... | double result = instance.getDerivative(input);
assertEquals(1, result, 0.0);
}
} |
21388581_1 | class RdbmsReader extends AbstractRdbmsComponentRuntime {
public static Map<Integer, String> getSqlColumnEntityHints(String sql) {
Map<Integer, String> columnEntityHints = new HashMap<Integer, String>();
String columns = sql.substring(sql.toLowerCase().indexOf("select") + 6, getFromIndex(sql));
... | String sql = "select\r\n ISNULL(a,ISNULL(z,'')) /*COLA*/, 'lastName, firstName'/*COLB*/, c/* COLC */, d /* \"COL D\" */ from test;";
Map<Integer, String> hints = RdbmsReader.getSqlColumnEntityHints(sql);
assertEquals(hints.get(1), "COLA");
assertEquals(hints.get(2), "COLB");
as... |
21394954_5 | class BootErrorCollector {
public OperationStepHandler getReadBootErrorsHandler() {
return this.listBootErrorsHandler;
}
public BootErrorCollector();
void addFailureDescription(final ModelNode operation, final ModelNode failureDescription);
private ModelNode getErrors();
}
class BootE... | BootErrorCollector instance = new BootErrorCollector();
BootErrorCollector.ListBootErrorsHandler handler = (BootErrorCollector.ListBootErrorsHandler) instance.getReadBootErrorsHandler();
assertThat(handler, is(notNullValue()));
OperationEntry entry = createOperationEntry(true, false);
... |
21432552_2 | class OpenRtbValidator {
public boolean validate(BidRequest request, BidResponse.Builder response) {
return !OpenRtbUtils.removeBids(response, bid -> validate(request, bid));
}
@Inject public OpenRtbValidator(MetricRegistry metricRegistry);
public boolean validate(BidRequest request, Bid.Builder bid);
... | BidResponse.Builder response = testResponse(testBid()
.addAllAdomain(asList("adv0.com", "adv2.com", "adv3.com"))
.addAllAttr(asList(CreativeAttribute.SURVEYS)));
validator.validate(requestBanner, response);
assertThat(OpenRtbUtils.bids(response)).isEmpty();
}
} |
21458450_10 | class RPCServiceImpl extends RemoteServiceServlet implements RPCService {
public void removeWindowsEventData(String windowSession, String windowId) {
String lookupKey = windowSession + ApplicationLocalStore.OBJECT_DELIMITER + windowId;
ApplicationLocalStore.getInstance().deleteAll(lookupKey);
}
protected void ... | String windowSession = "windowSessionId";
String windowId1 = "windowId1";
String windowId2 = "windowId2";
String generatedKey1 = windowSession + ApplicationLocalStore.OBJECT_DELIMITER + windowId1;
String generatedKey2 = windowSession + ApplicationLocalStore.OBJECT_DELIMITER + windowId2;
ApplicationLocalS... |
21462033_32 | class InfinityExponentialBackoffManager implements BackoffManager {
public void reset(@NonNull final String providerName,
@NonNull final Operation operation) {
OPFLog.logMethod(providerName, operation);
getManagerByOperation(operation).reset(providerName, operation);
}
... | for (final Operation operation : Operation.values()) {
for (int i = 0; i < NUM_OF_TRIES; ++i) {
manager.getTryDelay(PROVIDER_A, operation);
manager.getTryDelay(PROVIDER_B, operation);
}
manager.reset(PROVIDER_A, operation);
assertTr... |
21477166_0 | class ChineseWordTokenizer implements WordTokenizer {
@Override
public List<String> tokenize(final String sentence) {
return TOKENIZER.tokenize(sentence);
}
private static final Logger LOGGER;
}
class ChineseWordTokenizerTest {
private static final Logger LOGGER;
@Test
public v... | final long time = System.currentTimeMillis();
final WordTokenizer tokenizer = new ChineseWordTokenizer();
LOGGER.info("load time: " + (System.currentTimeMillis() - time) + " ms");
assertEquals(Arrays.asList("弹道导弹"), tokenizer.tokenize("弹道导弹"));
assertEquals(Arrays.asList("我", "... |
21499094_4 | class XmlDecoder implements UaDecoder {
@Override
public StatusCode decodeStatusCode(String field) {
if (nextStartElement(field)) {
UInteger value = Unsigned.uint(0);
if (nextStartElement("Code")) {
value = decodeUInt32(null);
requireNextEndEleme... | XmlDecoder decoder = new XmlDecoder();
decoder.setInput(new ByteArrayInputStream("<Value><Code>0</Code></Value>".getBytes()));
assertEquals(decoder.decodeStatusCode("Value").getValue(), 0);
decoder.setInput(new ByteArrayInputStream("<Value><Code>1</Code></Value>".getBytes()));
... |
21500212_4 | class UtilAll {
public static int getPid() {
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
String name = runtime.getName(); // format: "pid@hostname"
try {
return Integer.parseInt(name.substring(0, name.indexOf('@')));
}
catch (Exception e) {
... | int pid = UtilAll.getPid();
System.out.println("PID = " + pid);
assertTrue(pid > 0);
}
} |
21548299_5 | class AttributeMunger {
public void transformSensorStringReplacingWithPublicAddressAndPort(
final EntityAndAttribute<String> targetToUpdate,
final Optional<EntityAndAttribute<Integer>> optionalTargetPort,
final Iterable<? extends AttributeSensor<String>> targetsToMatch,
... | final AttributeSensor<String> TARGET_HOSTNAME = new BasicAttributeSensor<String>(String.class, "hostname");
final AttributeSensor<String> OTHER_HOSTNAME = new BasicAttributeSensor<String>(String.class, "otherhostname");
final AttributeSensor<Integer> TARGET_PORT = new BasicAttributeSensor<Intege... |
21556616_137 | class BufferedReader extends Reader {
public String readLine() {
verifyNotClosed();
/* has the underlying stream been exhausted? */
if (pos == end && fillBuf() == -1)
return null;
for (int charPos = pos; charPos < end; charPos++) {
char ch = buf[charPos];
... | BufferedReader br = getBufferedReader();
char currentChar;
char[] line = new char[8192];
int index = -1;
br.mark(8192);
while ((currentChar = (char) br.read()) != '\n') {
line[++index] = currentChar;
}
// drop the unused characters in line buf... |
21580302_82 | class MappingController {
public ComponentFormSet mapUserSubmissionToEntry(SubmissionFormTemplate template, UserSubmission userSubmission) throws MappingException
{
ComponentFormSet componentFormSet = new ComponentFormSet();
ComponentAll mainComponent = new ComponentAll();
Component component = new Component(... | setupMockService();
SubmissionFormTemplate template = new SubmissionFormTemplate();
template.setSections(new ArrayList<>());
SubmissionFormSection section = new SubmissionFormSection();
section.setFields(new ArrayList<>());
SubmissionFormField submissionFormField = new SubmissionFormField();
submissionF... |
21600105_14 | class SyncService {
List<Snapshot> calculateMissingSnapshots(
Collection<Snapshot> sourceSnapshots,
Set<SnapshotEntry> availableSnapshots) {
List<Snapshot> result = new ArrayList<>();
HashSet<Integer> availableSnapshotNrs = new HashSet<>();
for (SnapshotEntry e : ava... |
ArrayList<Snapshot> snapshots = new ArrayList<>();
snapshots.add(new Snapshot(1, null, null));
Snapshot snapshot3 = new Snapshot(3, null, null);
snapshots.add(snapshot3);
Set<SnapshotEntry> snapshotNumbers = new HashSet<>();
snapshotNumbers.add(new SnapshotEntry(1, null... |
21621670_3 | class RelocationInformationRequiredInfoValidation extends GenericValidation {
@Override
public boolean validate(AttributedDocumentEvent event) {
boolean valid = true;
TravelRelocationDocument document = (TravelRelocationDocument) event.getDocument();
// Check to see if from country is... | TravelRelocationDocument document = new TravelRelocationDocument();
ActualExpense expense = new ActualExpense();
expense.setExpenseAmount(new KualiDecimal(100));
document.addActualExpense(expense);
document.setFromCountryCode(validation.USA_COUNTRY_CODE);
AttributedDocum... |
21631528_12 | class AuthenticationInsight implements Parcelable {
public String getRegulationEnvironment() {
return mRegulationEnvironment;
}
public AuthenticationInsight();
private AuthenticationInsight(Parcel in);
static AuthenticationInsight fromJson(JSONObject json);
@Override public int desc... | AuthenticationInsight insight = AuthenticationInsight.CREATOR.createFromParcel(Parcel.obtain());
assertEquals(null, insight.getRegulationEnvironment());
}
} |
21634100_460 | class SdkInputStream extends InputStream implements MetricAware {
protected final void abortIfNeeded() {
if (Thread.interrupted()) {
try {
abort(); // execute subclass specific abortion logic
} catch (IOException e) {
LogFactory.getLog(getClass()).deb... | final List<Integer> abortionCount = new ArrayList<Integer>();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
ByteArrayInputStream bais = new ByteArrayInputStream(
"Content".getBytes(StringUtils.UTF8));
... |
21654705_0 | class EtutorCVSReader {
public static List<String> readUNummer(BufferedReader reader) throws IOException {
final List<String> uNummern = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
// use comma as separator
String[] record = line.sp... |
final URL url = this.getClass().getResource(TEST_ETUTOR_EXPORT);
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(url.getFile())));
List<String> uNummern = EtutorCVSReader.readUNummer(bufferedReader);
bufferedReader.close();
Assert.assertNotNull(uNum... |
21668967_1 | class ElasticsearchQuery implements SimpleQuery<ElasticsearchQuery<K>>, Fetchable<K> {
@Override
public ElasticsearchQuery<K> where(Predicate... o) {
return queryMixin.where(o);
}
public ElasticsearchQuery(Client client, Function<SearchHit, K> transformer, ElasticsearchSerializer serializer);... | assertQuery(user.firstName.eq("Jaakko"), u1);
assertQuery(user.firstName.equalsIgnoreCase("jaakko"), u1);
assertQuery(user.lastName.eq("Aakkonen"), u3);
assertQuery(user.firstName.in("Jaakko","Teppo"), u1);
assertQuery(user.lastName.in("Aakkonen", "BeekkoNen"), u3, u4);
... |
21765334_3 | class XmlParser {
public static List<Object[]> parse(CharSequence xml, String... fields) {
List<Object[]> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
if (xml != null && xml.length() != 0) {
Map<String, Integer> fieldMap = new HashMap<>(fields.length);
... | assertEquals(new Object[]{ "test&<>", "1" }, XmlParser.parse("<e><name>test&<></name><age>1</age></e>", "name", "age").get(0));
assertEquals(new Object[]{ "test&<>", "1" }, XmlParser.parse("<e><age>1</age><name>test&<></name></e>", "name", "age").get(0));
assertEquals(new Obj... |
21765535_41 | class FightCalculator {
public Fight attack(UUID attackerId, UUID defenderId, UUID planetId, Ships attackingShips, Ships defendingShips, long round) {
LOGGER.debug("Fight between {} and {}", attackingShips, defendingShips);
Ships remainingDefendingShips = fight(attackingShips, defendingShips);
... | Fight fight = sut.attack(ATTACKER_ID, DEFENDER_ID, PLANET_ID, new Ships(new Ship(ShipType.MOSQUITO, 3)), new Ships(new Ship(ShipType.MOSQUITO, 5)), ROUND);
assertThat(fight.getRemainingAttackerShips().countByType(ShipType.MOSQUITO), is(0L));
assertThat(fight.getRemainingDefenderShips().countByT... |
21770648_34 | class JdbcStore implements Store {
@Override
public List<Message> dequeueOut(String id, int offset) {
Validate.notNull(id);
Validate.isTrue(offset >= 0);
List<byte[]> serializedMessages = outQueue.dequeueOut(id, offset);
return serializedMessages.stream()
.map(d... | List<Message> actual = fixture.dequeueOut("id", 0);
assertTrue(actual.isEmpty());
}
} |
21775167_46 | class IssuesSearchRequest extends SearchRequest {
public IssuesSearchRequest setRepo(String repo, String userName) {
add(new KeyValueStringSearchItem("repo", userName + "/" + repo));
return this;
}
public IssuesSearchRequest setIsOpen(boolean isOpen);
public IssuesSearchRequest setIsPullRequest(Boolea... | String s = builder.setRepo("gitskarios", "alorma").build();
assertThat(s).contains("repo:alorma/gitskarios");
}
} |
21788064_0 | class FragmentFileSet {
public void run() throws IOException {
FlatPackageWriterImpl flatPackageWriter = new FlatPackageWriterImpl(0);
flatPackageWriter.setDebugOutput(debug);
flatPackageWriter.setOutputDirectory(outputDir);
Movie movie = new Movie();
for (File input : input... | File tmpDir = createTmpDir();
File outputDir = createTmpDir();
copyResource("/smoothstreaming/audio-96000.mp4", tmpDir);
copyResource("/smoothstreaming/video-128h-75kbps.mp4", tmpDir);
copyResource("/smoothstreaming/video-192h-155kbps.mp4", tmpDir);
copyResource("/smooths... |
21797449_58 | class ColorUtils {
public static String toRGBCode(final Color color) {
return String.format("#%02X%02X%02X", //
(int) (color.getRed() * 255), //
(int) (color.getGreen() * 255), //
(int) (color.getBlue() * 255));
}
private ColorUtils();
public s... | assertEquals("#000000", ColorUtils.toRGBCode(Color.BLACK));
assertEquals("#FFFFFF", ColorUtils.toRGBCode(Color.WHITE));
assertEquals("#0A0B0C", ColorUtils.toRGBCode(Color.web("#0a0b0c")));
}
} |
21825681_23 | class GridFeature extends AbstractDiscreteFeature<GeoPosition, GridCell4D> {
public MapFeature extractMapFeature(Set<String> varIds, RegularGrid targetGrid,
Double elevation, DateTime time) throws DataReadingException {
GridDomain domain = getDomain();
/*
* Find the elevation ... | int startX = 10;
int startY = 20;
int xSize = 10;
int ySize = 10;
RegularGrid targetGrid = new RegularGridImpl(startX - 0.5, startY - 0.5, startX + xSize
+ 0.5, startY + ySize + 0.5, null, xSize + 1, ySize + 1);
/*
* Useful check that the target... |
21833183_42 | class FileListSorter implements Comparator<LayoutElementParcelable> {
@Override
public int compare(LayoutElementParcelable file1, LayoutElementParcelable file2) {
/*File f1;
if(!file1.hasSymlink()) {
f1=new File(file1.getDesc());
} else {
f1=new File(file1.getSymlink());
}
F... | FileListSorter fileListSorter = new FileListSorter(-1, 2, 1);
LayoutElementParcelable file1 =
new LayoutElementParcelable(
ApplicationProvider.getApplicationContext(),
"abc1.txt",
"C:\\AmazeFileManager\\abc1",
"user",
"symlink",
"10... |
21858951_204 | class IOUtilities extends Static {
public static Path toPath(Object candidate) throws IOException, IllegalArgumentException {
if (candidate == null) {
return null;
}
if (candidate instanceof Path) {
return (Path) candidate;
}
if (candidate instanceof... | Path pathObj = Files.createTempFile("path", ".tmp");
File fileObj = File.createTempFile("file", ".tmp");
URI uriObj = URI.create("file:/tmp");
URL urlFileObj = new URL("file:/tmp");
try {
//convert to Path
assertNull(IOUtilities.toPath(null));
... |
21860658_55 | class SimplePDP {
public boolean isAuthorized(final String ip, final String referer) {
final String toEvaluate = replaceVariablesInRule(ip, referer);
boolean result = false;
try {
result = (Boolean)SCRIPT_ENGINE.eval(toEvaluate);
} catch (ScriptException ex) {
... | final SimplePDP pdp = new SimplePDP(RULE1);
assertFalse(pdp.isAuthorized("17.15.25.3", "test"));
}
} |
21907146_11 | class InstantMapper extends TypedMapper<Instant> {
@Override
protected Instant extractByIndex(ResultSet r, int index) throws SQLException {
final Timestamp timestamp = calendar.isPresent() ? r.getTimestamp(index, cloneCalendar()) : r.getTimestamp(index);
return timestamp == null ? null : timest... | when(resultSet.getTimestamp(1)).thenReturn(null);
Instant actual = new InstantMapper().extractByIndex(resultSet, 1);
assertThat(actual).isNull();
}
} |
21910720_11 | class GoogleAppsSdkUtils {
public static User retrieveUser(Directory directoryClient, String userKey) throws IOException {
LOG.debug("retrieveUser() - {}", userKey);
Directory.Users.Get request = null;
try {
request = directoryClient.users().get(userKey);
} catch (IOEx... | User user = GoogleAppsSdkUtils.retrieveUser(directoryClient, TEST_USER);
assertEquals("Test", user.getName().getGivenName());
}
} |
21919832_0 | class StringFormatUtils {
public static String addAtEndIfNotPresent(final String string, final String suffix) {
return string == null ? suffix : !string.endsWith(suffix) ? string + suffix : string;
}
private StringFormatUtils();
private final String string;
private final String suffix;
... | assertEquals(expected, StringFormatUtils.addAtEndIfNotPresent(string, suffix));
}
} |
21921396_10 | class ServiceElementFactory {
public static ServiceElement create(final ServiceSignature signature, File configFile) throws IOException,
ConfigurationException,
... | ServiceDeployment deployment = new ServiceDeployment();
deployment.setConfig(getConfigDir()+"/PlannedConfig.groovy");
ServiceElement service = ServiceElementFactory.create(deployment, new File(getConfigDir()+"/PlannedConfig.groovy"));
Assert.assertTrue(service.getPlanned()==10);
... |
21942754_2 | class CloudFoundryAppServiceDiscoveryClient extends CloudFoundryDiscoveryClient {
@Override
public List<ServiceInstance> getInstances(String serviceId) {
return getCloudFoundryService().getApplicationInstances(serviceId)
.filter(tuple -> tuple.getT1().getUrls().stream().anyMatch(this::isInternalDomain)).map(tu... | String serviceId = "billing";
ApplicationDetail applicationDetail = ApplicationDetail.builder().id("billing1").name("billing").instances(1)
.memoryLimit(1024).stack("cflinux2").diskQuota(1024).requestedState("Running").runningInstances(1)
.urls("billing.apps.example.com", "billing.apps.internal").build();
... |
21967508_32 | class BaseUploader {
public final boolean uploadGlucoseDataSets(List<GlucoseDataSet> glucoseDataSets) {
if (glucoseDataSets == null) {
return true;
}
boolean output = true;
for (GlucoseDataSet glucoseDataSet : glucoseDataSets) {
try {
output &... | List<GlucoseDataSet> list = Lists.newArrayList(
mockGlucoseDataSet(),
mockGlucoseDataSet(),
mockGlucoseDataSet());
mockUploader.uploadGlucoseDataSets(list);
assertThat(mockUploader.glucoseDataSets, hasSize(3));
}
} |
21977200_13 | class EchoCommandHandler {
String applyReplacements(StringBuilder builder) {
boolean prepand = false;
if(builder.length() >= 1 && builder.charAt(0) == '\\'){
//our regexpr doesn't work if a special char is at the beginning!
builder.insert(0, '_');
prepand = true;
}
//\c
if(builder.indexOf("\\c") !... | assertEquals(" \u0007", applyReplacement(" \\a"));
assertEquals(" \b", applyReplacement(" \\b"));
assertEquals(" \u001B", applyReplacement(" \\e"));
assertEquals(" \f", applyReplacement(" \\f"));
assertEquals(" \n", applyReplacement(" \\n"));
assertEquals(" \r", applyReplacement(" \\r"));
assertEquals(" \... |
21980975_88 | class LuceneProxyNodeQuery extends Query {
@Override
public void setBoost(final float b) {
nodeQuery.setBoost(b);
}
public LuceneProxyNodeQuery(final NodeQuery nq);
@Override public Weight createWeight(final IndexSearcher searcher);
@Override public Query rewrite(final IndexReader reader);
@Overri... | final float boost = 2.5f;
this.addDocument("\"aaa ccc\" \"one five\" . \"aaa bbb\" \"ccc eee\" .");
BooleanQuery bq1 = new BooleanQuery();
NodeTermQuery tq = new NodeTermQuery(new Term (DEFAULT_TEST_FIELD, "one"));
tq.setBoost(boost);
bq1.add(new LuceneProxyNodeQuery(tq), Occur.MUST);
bq1.... |
21993347_98 | class TagsBuilder {
public T withTag(String k, String v) {
extraTags.add(new BasicTag(k, v));
return (T) this;
}
protected TagsBuilder();
public T withTag(String k, Boolean v);
public T withTag(String k, Enum<E> v);
public T withTag(Tag t);
public T withTags(String... tags);
public T withTag... | Id id = new Builder()
.withTag(new BasicTag("k", "v"))
.build();
Assertions.assertEquals(newId("k", "v"), id);
}
} |
21996028_0 | class Card {
public String getIssueKey() {
return MatcherUtils.singleMatch(desc, "browse/([\\w-]+)");
}
private Card();
public Card(Swimlane swimlane, String name);
public Card(Issue issue, String jiraUrl);
public Card(Swimlane swimlane, Issue issue, String jiraUrl);
public St... | String issueKey = "HW-34305";
Card card = new Card(new Swimlane(new Board("board-name"), "swim-lane"), new Issue(issueKey), "jira-url");
assertEquals(issueKey, card.getIssueKey());
}
} |
22027221_0 | class Util {
public static int countChars(String string, int character) {
int count = 0;
int currIndex = 0;
while (true) {
currIndex = string.indexOf(character, currIndex);
if (currIndex == -1)
break;
++currIndex; // Start next search from next character
++count;
}
return count;
}
static ... | assertTrue(Util.countChars("abcxdefxghix", 'x') == 3);
assertTrue(Util.countChars("", 'x') == 0);
assertTrue(Util.countChars("abc\ndef", '\n') == 1);
}
} |
22045363_246 | class AlosAV2Metadata extends XmlMetadata {
@Override
public int getRasterHeight() {
if (height == 0) {
try {
height = Integer.parseInt(getAttributeValue(AlosAV2Constants.PATH_IMG_NUM_ROWS, AlosAV2Constants.STRING_ZERO));
} catch (NumberFormatException e) {
... | assertEquals(200, metadata.getRasterHeight());
}
} |
22080403_1 | class AvroExhibit {
public static Exhibit create(GenericRecord record) {
Schema schema = record.getSchema();
ExhibitDescriptor desc = createDescriptor(schema);
List<Object> attrValues = Lists.newArrayListWithExpectedSize(desc.attributes().size());
for (int i = 0; i < desc.attributes().size(); i++) {
... | GenericData.Record in1 = new GenericData.Record(inner);
in1.put("f1", null);
in1.put("f2", true);
in1.put("f3", 1729);
GenericData.Record in2 = new GenericData.Record(inner);
in2.put("f1", "josh");
in2.put("f3", 29);
List<GenericData.Record> recs = Lists.newArrayList(in1, in2);
Gener... |
22095939_158 | class MemoryChannel extends BasicChannelSemantics {
@Override
public void configure(Context context) {
try {
capacity = context.getInteger("capacity", defaultCapacity);
} catch(NumberFormatException e) {
capacity = defaultCapacity;
LOGGER.warn("Invalid capacity specified, initializing cha... | Context context = new Context();
Map<String, String> parms = new HashMap<String, String>();
parms.put("byteCapacity", "2000");
parms.put("byteCapacityBufferPercentage", "20");
context.putAll(parms);
Configurables.configure(channel, context);
byte[] eventBody = new byte[405];
Transacti... |
22102786_119 | class DefaultRiskAnalysis implements RiskAnalysis {
@Override
public Result analyze() {
checkState(!analyzed);
analyzed = true;
Result result = analyzeIsFinal();
if (result != Result.OK)
return result;
return analyzeIsStandard();
}
private Default... | Transaction tx = new Transaction(params);
tx.addInput(params.getGenesisBlock().getTransactions().get(0).getOutput(0));
// A pay to address output
tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1.toAddress(params)));
// A pay to pubkey output
tx.addOutput(Coin... |
22104852_1 | class ConcordanceArrayWindowSearcher {
public void search(IndexSearcher searcher, String fieldName,
Query mainQuery, Query filterQuery, Analyzer analyzer,
ArrayWindowVisitor visitor, DocIdBuilder docIdBuilder) throws IllegalArgumentException,
TargetTokenNotFoundExcepti... | String[] docs = new String[]{"aa ba ca da ea fa", "ba ca da ga fa ea"};
Analyzer analyzer = getAnalyzer(
MockTokenFilter.EMPTY_STOPSET, 50, 100);
Directory directory = getDirectory(analyzer, docs);
IndexReader reader = DirectoryReader.open(directory);
IndexSearcher indexSearcher = new IndexS... |
22248638_1 | class ClassUtils {
public static void getClassesWithAnnotation(String packageName,
Class<? extends Annotation> annotationClass,
ClassVisitor visitor)
throws ClassLoadingException {
LOGGER.trace("Finding classes with... | try {
List<Class<?>> classes = new ArrayList<>();
ClassUtils.getClassesWithAnnotation(
"org.junit.runner.notification",
RunListener.ThreadSafe.class,
classes::add
);
assertThat(classes.size(), greaterThan(0));
} catch (ClassLoadingException e) {
e.prin... |
22254856_57 | class CompositeNotifier implements Notifier {
@Override
public Mono<Void> notify(InstanceEvent event) {
return Flux.fromIterable(delegates).flatMap((d) -> d.notify(event).onErrorResume((error) -> {
log.warn("Unexpected exception while triggering notifications. Notification might not be sent.", error);
return... | TestNotifier notifier1 = new TestNotifier();
TestNotifier notifier2 = new TestNotifier();
CompositeNotifier compositeNotifier = new CompositeNotifier(Arrays.asList(notifier1, notifier2));
StepVerifier.create(compositeNotifier.notify(APP_DOWN)).verifyComplete();
assertThat(notifier1.getEvents()).containsOnly... |
22266761_0 | class Statistics {
public String getMeteringPointName() {
return meteringPointName;
}
public Statistics(String meteringPointName);
public void addValue(long actual);
public BigDecimal average();
public BigDecimal standardDeviation();
public List<Average> getAverages();
public long getCounter();
public lo... | assertThat(classUnderTests.getMeteringPointName(),
is(METERING_POINT_NAME));
}
} |
22269384_141 | class ClassificationDistribution extends AbstractOryxResource {
@GET
@Path("{datum}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<IDValue> get(@PathParam("datum") String datum) throws OryxServingException {
check(datum != null && !datum.isEmpty(), "Missing input da... | List<IDValue> recs = target("/classificationDistribution/A,-5,").request()
.accept(MediaType.APPLICATION_JSON_TYPE).get(LIST_ID_VALUE_TYPE);
Assert.assertEquals("X", recs.get(0).getID());
Assert.assertEquals((1.0 / 6.0 + 2 * (100.0 / 1400.0)) / 3,
recs.get(0).getValue(),
... |
22289790_6 | class ExceptionUtils {
public static String toString(Throwable error) {
if (error == null)
return null;
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
error.printStackTrace(printWriter);
return stringWrit... | Exception ex = new Exception("Erf");
String str = ExceptionUtils.toString(ex);
assertThat(str).startsWith("" +
"java.lang.Exception: Erf\n" +
"\tat tzatziki.util.ExceptionUtilsTest.toString_should_return_the_stacktrace(ExceptionUtilsTest.java:");
}
} |
22292873_19 | class CommentsConverter implements Converter {
private String getPostContents(String title, String description) {
if (StringUtils.isEmpty(title)) {
return description;
}
if (StringUtils.isEmpty(description)) {
return title;
}
return title + "\n\n" +... | Comment comment = convertComments("comment-default.json").get(0);
assertThat(comment.getAuthor(), equalTo("awesomesaucetester"));
assertThat(comment.getPostContents(), equalTo("first reply lol"));
assertThat(comment.isScoreHidden(), equalTo(true));
assertThat(comment.getScore(),... |
22318767_3 | class JsonRpcClient {
@NotNull
public RequestBuilder<Object> createRequest() {
return new RequestBuilder<Object>(transport, mapper);
}
public JsonRpcClient(@NotNull Transport transport);
public JsonRpcClient(@NotNull Transport transport, @NotNull ObjectMapper mapper);
@NotNull publi... | JsonRpcClient client = initClient("add_player");
Boolean result = client.createRequest()
.id("asd671")
.method("add")
.param("player", new Player("Kevin", "Shattenkirk",
new Team("St. Louis Blues", "NHL"), 22, Position.DEFENDER,
... |
22337952_55 | class ConcurrentCache implements Cache {
@Override
public void init() {
if (mCache == null) {
return;
}
synchronized (this) {
Billing.debug(TAG, "Initializing cache");
mCache.init();
}
}
ConcurrentCache(@Nullable Cache cache);
... | final Cache mockCache = mock(Cache.class);
final ConcurrentCache cache = new ConcurrentCache(mockCache);
cache.init();
verify(mockCache, times(1)).init();
}
} |
22342877_72 | class UrlBeaconUrlCompressor {
public static byte[] compress(String urlString) throws MalformedURLException {
byte[] compressedBytes = null;
if (urlString != null) {
// Figure the compressed bytes can't be longer than the original string.
byte[] byteBuffer = new byte[urlStri... | String testURL = "http://google.ca";
byte[] expectedBytes = {0x02, 'g', 'o', 'o', 'g', 'l', 'e', '.', 'c', 'a'};
assertTrue(Arrays.equals(expectedBytes, UrlBeaconUrlCompressor.compress(testURL)));
}
} |
22344826_5 | class ButtonWithProgressVM extends SimpleButtonVM implements ProgressButtonVM {
@Override
public void showLoading() {
loading = true;
notifyShowProgress();
}
public ButtonWithProgressVM(int layoutId, boolean enabled, int clickableResId,
int[] enableDisableResIds, ButtonCommand actionCommand, int imageView... | ButtonWithProgressVM buttonWithProgressVM = (ButtonWithProgressVM) buttonVM;
buttonWithProgressVM.registerListener(mockedButtonVMListener);
buttonWithProgressVM.showLoading();
verify(mockedButtonVMListener).onProgressValueChanged(true,
buttonWithProgressVM);
}
} |
22384317_54 | class DiffSyncController {
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(
value="${spring.diffsync.path:}/{resource}",
method=RequestMethod.PATCH)
public Patch patch(@PathVariable("resource") String resource, @RequestBody Patch patch) throws PatchException {
PersistenceCallback<?> persisten... | TodoRepository todoRepository = todoRepository();
MockMvc mvc = mockMvc(todoRepository);
mvc.perform(
patch(RESOURCE_PATH + "/2")
.content(resource("patch-change-entity-id"))
.accept(JSON_PATCH)
.contentType(JSON_PATCH))
.andExpect(status().isOk())
.andExpect(content().string("[]"))
.a... |
22395060_25 | class SpreadProcessingSystem extends BaseEntitySystem {
protected abstract void process(int entityId)protected abstract void process(int entityId);
protected abstract void process(int entityId)public SpreadProcessingSystem(Aspect.Builder aspect, float roundTripTime);
protected abstract void process(int entityId)publ... |
final World world = bakeWorld(new MySpreadProcessingSystem(10, 1));
world.delta=0.09f;
world.process();
assertAllPenguinsPoked(0);
}
} |
22412169_0 | class ElasticsearchClientConfiguration {
public static Settings getSettings(ConnectorClusterConfig configuration) {
Map<String, String> setting = new HashMap<String, String>();
setting.put(NODE_DATA.getElasticSearchOption(), recoverdOptionValue(configuration.getConnectorOptions(), NODE_DATA));
... |
Map<String, String> connectorOptions = new HashMap<>();
connectorOptions.put(NODE_DATA.getManifestOption(), "true");
connectorOptions.put(NODE_MASTER.getManifestOption(), "true");
Map<String, String> clusterOptions = new HashMap<>();
clusterOptions.put(HOST.getManifestOption()... |
22424494_3 | class OpenstackAgentProperties extends AgentLifeCycleAdapter {
@Override
public void afterAgentConfigurationLoaded(@NotNull BuildAgent agent) {
try {
if ("true".equals(agentConfiguration.getConfigurationParameters().get(OpenstackCloudParameters.AGENT_METADATA_DISABLE))) {
LO... | Map<String, String> parameters = new HashMap<String, String>();
parameters.put(OpenstackCloudParameters.AGENT_METADATA_DISABLE, "true");
prepareAgentProperties("meta_data_noUserData.json", parameters).afterAgentConfigurationLoaded(null);
Assert.assertTrue(Lo4jBeanAppender.contains("Opens... |
22430910_1 | class DefaultConfigurator implements Configuration<Map<String, Object>> {
@Override
public void configure(final Configurable configurable) {
currentState.configure(configurable);
}
@SuppressWarnings("unchecked") @Override public T getParameter(final String name, final T defaultValue);
void transitionTo(final ... | final File configurationFile = File.createTempFile(randomString(), ".yaml");
final Map<String, Object> configuration = createSampleConfiguration(configurationFile);
System.setProperty(
DefaultConfigurator.CONFIGURATION_FILE_SYSTEM_PROPERTY,
configurationFile.getAbsolutePath());
cut.configure(dummy... |
22441031_2 | class ViewHelper {
public String renderPluginDashboard(PluginContext context) {
return renderPluginTemplate(context, context.getDashboardPath());
}
@Autowired public ViewHelper(WebfrontEngine pluginsEngine, ApplicationContext context);
public String renderPluginWidgetContent(PluginContext co... | assertEquals("<p>Hello, World!</p>Hey", viewHelper.renderPluginDashboard(getContext("test-started")));
}
} |
22527647_2 | class TailTypeInjector {
public List<TailType> getTailTypeFromArgs(String... types) {
List<TailType> tailers = new LinkedList<TailType>();
TailType tailType = null;
for (String type : types) {
if ("".equals(type)) {
System.out.println("------------- WARNING -----... | TailTypeInjector inj = new TailTypeInjector();
List<TailType> tailTypeFromArgs = inj.getTailTypeFromArgs("NoopTailType");
assertTrue(tailTypeFromArgs.get(0) instanceof NoopTailType);
}
} |
22542759_31 | class MetadataEntity implements Iterable<MetadataEntity.KeyValue> {
public static Builder builder() {
return new Builder();
}
private MetadataEntity(LinkedHashMap<String, String> details, String type);
public MetadataEntity(MetadataEntity metadataEntity);
public static MetadataEntity ofNamespace(Stri... | // empty builder should fail
try {
MetadataEntity.builder().build();
Assert.fail();
} catch (IllegalArgumentException e) {
// expected
}
// test that builder builds metadata entity correctly
MetadataEntity metadataEntity = MetadataEntity.builder().append(MetadataEntity.NAMESPAC... |
22614011_1 | class RosettaMapperFactory implements ResultSetMapperFactory {
@Override
public boolean accepts(@SuppressWarnings("rawtypes") Class type, StatementContext ctx) {
return !(type.isPrimitive() || type.isArray() || type.isAnnotation() || BuiltInArgumentFactory.canAccept(type));
}
@Override @SuppressWarnings({... | assertThat(mapperFactory.accepts(Integer.TYPE, null)).isFalse();
}
} |
22661024_1 | class MongoStore extends StoreBase {
@Override
public String[] keys() throws IOException {
/* create the empty array list */
List<String> keys = new ArrayList<String>();
/* build the query */
BasicDBObject sessionKeyQuery = new BasicDBObject();
sessionKeyQuery.put(appContextProperty, this.getName());
... | /* get the keys. this should always return a list, even if it's empty */
String[] keys = this.mongoStore.keys();
assertNotNull(keys);
}
} |
22686950_5 | class Filtering {
public static String filter(String input, Map<String, String> variables) {
if (variables.isEmpty()) {
return input;
}
if (input == null || input.isEmpty()) {
return input;
}
String current = input;
String last = input;
while (current.contains("${") && curre... | String out = Filtering.filter("hello ${world} ${period}", new FluentMap<>()
.add("name", "vert.x")
.add("world", "${name}"));
assertThat(out).isEqualTo("hello vert.x ${period}");
}
} |
22693515_14 | class OWLAxiomRenamer implements OWLAxiomVisitor {
public OWLAxiom rename(OWLAxiom axiom){
Map<OWLEntity, OWLEntity> renaming = new HashMap<>();
expressionRenamer = new OWLClassExpressionRenamer(df, renaming);
boolean multipleClasses = axiom.getClassesInSignature().size() > 1;
expressionRenamer.setMultipleCla... | StringRenderer.setRenderer(rendering);
OWLAxiom ax1 = df.getOWLSubClassOfAxiom(clsA, clsB);
OWLAxiom ax2 = df.getOWLSubClassOfAxiom(clsB, clsC);
System.out.print(ax1 + "->");ax1 = renamer.rename(ax1);System.out.println(ax1);
System.out.print(ax2 + "->");ax2 = renamer.rename(ax2);System.out.println(ax1);
... |
22725357_0 | class HtmlUnitHtmlFetcher implements HtmlFetcher {
@Override
public String fetch(String url) {
try{
LOGGER.debug("url:"+url);
HtmlPage htmlPage = WEB_CLIENT.getPage(url);
String html = htmlPage.getBody().asXml();
LOGGER.debug("html:"+html);
re... |
HtmlFetcher htmlFetcher = new HtmlUnitHtmlFetcher();
String html = htmlFetcher.fetch("http://apdplat.org");
assertEquals(true, html.contains("APDPlat的主要特性如下"));
assertEquals(true, html.contains("1、jsearch:高性能的全文检索工具包"));
assertEquals(true, html.contains("2、Java分布式中文分词组件 - word... |
22734513_237 | class RequireJsBundleListener implements BundleListener {
public void init() {
this.serviceRegistrationMap = new ConcurrentHashMap<>();
this.requireConfigMap = new ConcurrentHashMap<>();
this.bundleContext.addBundleListener( this );
for ( Bundle bundle : this.bundleContext.getBundles() ) {
th... | Bundle mockBundleNoClientSide = this.createMockBundle( "non-client-side-bundle", "0.1", Bundle.ACTIVE );
Bundle mockBundleWithPackageJson = this.createMockPackageJsonBundle( "lib1", "1.0", Bundle.ACTIVE );
Bundle mockBundleWithRequireJson = this.createMockRequireJsonBundle( "lib2", "2.0", Bundle.ACTIVE );
... |
22750538_1 | class NodeManager {
public boolean setNodeProperty(Long id, String key, Object value, GraphDatabaseService graphDb)
{
boolean success = true;
// Update the node's property in cache
Map<String, Object> node = globalNodeCache.getIfPresent(id);
if(node == null)
{
... | GraphDatabaseService db = setUpDb();
NodeManager nodeManager = new NodeManager();
NodeManager.globalNodeCache.invalidateAll();
DataNodeManager.dataCache.invalidateAll();
DataNodeManager dataNodeManager = new DataNodeManager();
// Write some nodes to the database
... |
22760763_9 | class RoaringInspection {
public static RoaringBitmap[] extract(RoaringBitmap bitmap, int[] ukeys) {
RoaringArray array = bitmap.highLowContainer;
short[] keys = intToShortKeys(ukeys);
RoaringBitmap[] extract = new RoaringBitmap[keys.length];
for (int i = 0; i < keys.length; i++) {
... | RoaringBitmap bitmap1 = new RoaringBitmap();
Random r = new Random(123);
for (int i = 0; i < 3_000_000; i += 65_536) {
if (r.nextBoolean()) {
bitmap1.add(i);
}
}
RoaringBitmap bitmap2 = new RoaringBitmap();
bitmap2.flip(0, 3_000_00... |
22789601_112 | class Moshi {
@CheckReturnValue
public <T> JsonAdapter<T> adapter(Type type) {
return adapter(type, Util.NO_ANNOTATIONS);
}
Moshi(Builder builder);
@CheckReturnValue public JsonAdapter<T> adapter(Class<T> type);
@CheckReturnValue public JsonAdapter<T> adapter(Type type, Class<? extends Annotation> ... | Moshi moshi = new Moshi.Builder().add(LocalizedBooleanAdapter.FACTORY).build();
Baguette baguette = new Baguette();
baguette.avecBeurre = true;
baguette.withButter = true;
JsonAdapter<Baguette> adapter = moshi.adapter(Baguette.class);
assertThat(adapter.toJson(baguette))
.isEqualTo("{\... |
22790488_229 | class VideoResource {
public String getDetails(Integer id, String... fields) throws Exception {
if (fields.length == 0) {
return videos.get(id).toString();
}
return fieldJsonMapper.toJson(videos.get(id), fields);
}
public VideoResource(FieldJsonMapper fieldJsonMapper, Map<Integer, Video> vide... | var fields = new String[]{"id", "title", "length"};
var expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178}";
Mockito.when(fieldJsonMapper.toJson(Matchers.any(Video.class), Matchers.eq(fields))).thenReturn(expectedDetails);
var actualFieldsDetails = resource.getDetails(2, fields);
... |
22794824_19 | class MapGenerator implements Generator<Map<K, V>> {
@Override
public Map<K, V> next() {
final int size = randomValues.randomInteger(sizeRange.lowerBound(), sizeRange.upperBound());
final HashMap<K, V> map = new HashMap<>();
int misses = 0;
while (map.size() < size) {
... | final Generator<Map<Integer, Integer>> generator = RDG.map(generatingRandomIntegers(), generatingRandomIntegers(), -1);
assertThat(generator.next()).isEmpty();
}
} |
22815625_10 | class SpecialMath {
public static double evaluatePolynomial(double x, double[] coefficients) {
double value = 0.0;
for (int i = 0; i < coefficients.length; i++)
value = value * x + coefficients[i];
return value;
}
public static double getMachineEpsilon();
public static double calculateCompleteEllipti... |
assertEquals(evaluatePolynomial(5, new double[] {3, 0, 1 }), 76.0, 0.00001);
assertEquals(evaluatePolynomial(0.13, new double[] {0.7, -6.6, 4.1, 0.3, -3.43, -1}), -1.43368133549, 0.000001);
}
} |
22824768_4 | class CFMLParser {
public CFScriptStatement parseScript(String cfscript) throws ParseException, IOException {
CommonTokenStream tokens = createTokenStream(cfscript);
ScriptBlockContext scriptBlockContext = parseScriptBlockContext(tokens);
CFScriptStatement result = scriptVisitor.visit(scriptBlockContext);
if ... | String script = "var x = 1; y =; createObject('java','java.lang.String');";
CFScriptStatement scriptStatement = null;
try {
scriptStatement = fCfmlParser.parseScript(script);
} catch (Exception e) {
// TODO Auto-generated catch block
return;
}
// assertNotNull(scriptStatement);
}
} |
22829409_13 | class TinyORM implements Closeable {
public <T extends Row<?>> Paginated<T> searchBySQLWithPager(@NonNull final Class<T> klass, final String sql,
final List<Object> params, final long entriesPerPage) {
return searchBySQLWithPager(klass, sql, params, entriesPerPage, getReadConnection());
}
public TinyORM(Conn... | IntStream.rangeClosed(1, 10).forEach(i -> {
try {
this.orm.insert(Member.class).value("name", "m" + i)
.executeSelect();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
{
Paginated<Member> paginated = this.orm.searchBySQLWithPager(
Member.class, "SELECT * FROM `member` O... |
22835310_14 | class LevelTranslator {
public Level fromString(String[] string) {
Tile[][] field;
Level level = new Level();
int indexOfProperties = 0;
for (; string[indexOfProperties].charAt(0) != '#'; indexOfProperties++) {
switch (indexOfProperties) {
case 0:
... | Level resultingLevel = sut.fromString(levelAsString);
assertThat(resultingLevel, is(level));
}
} |
22880877_4 | class AeSimpleSHA1 {
@Nullable
public static String SHA1(String text) {
try {
final MessageDigest md = MessageDigest.getInstance("SHA-1");
//noinspection CharsetObjectCanBeUsed - NOTE fix not applicable on API16
md.update(text.getBytes("iso-8859-1"), 0, text.length()... | final String sha1ForProbe = AeSimpleSHA1.SHA1("probe");
assertThat(sha1ForProbe).isEqualTo("a949c530710f9fca76b45776267c68967fa891e7");
}
} |
22882266_64 | class BundleContextServiceListener implements ServiceListener {
@Override
public void serviceChanged( ServiceEvent serviceEvent ) {
if ( referenceToInstanceMap.containsKey( serviceEvent.getServiceReference() ) ) {
Object instance = referenceToInstanceMap.get( serviceEvent.getServiceReference() );
L... | Object instance = mock( Object.class );
referenceToInstanceMap.put( serviceReference, instance );
DelayedInstanceNotifier delayedInstanceNotifier = mock( DelayedInstanceNotifier.class );
when( delayedInstanceNotifierFactory.create( instance, LifecycleEvent.STOP ) )
.thenReturn( delayedInstanceNoti... |
22910855_18 | class Timeslot {
@Override
public String toString() {
String endToConcatenate = end != null ? " - " + end : "";
return start + endToConcatenate;
}
@JsonCreator public Timeslot(@JsonProperty("start") String start, @JsonProperty("end") String end);
public Timeslot(String start);
... | Timeslot timeslot = new Timeslot("15:30");
String formatedTimeslot = timeslot.toString();
assertEquals("15:30", formatedTimeslot);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.