id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
48402328_30
class TerminalCharacter { public boolean equalsIgnoreCharacter(TerminalCharacter that) { return style.equals(that.style) && color.equals(that.color); } public TerminalCharacter(char c); public TerminalCharacter(char c, TerminalTextStyle style); public TerminalCharacter(char c, TerminalC...
TerminalCharacter c1 = new TerminalCharacter('a', new TerminalColor(Color.RED, Color.BLUE)); TerminalCharacter c2 = new TerminalCharacter('b', new TerminalColor(Color.RED, Color.BLUE)); assertTrue(c1.equalsIgnoreCharacter(c2)); } }
48418599_0
class CommandHandlerProvider implements ApplicationContextAware { public NewCommandSourceHandler getHandler(final String entity, final String action) { Preconditions.checkArgument(StringUtils.isNoneEmpty(entity), "An entity must be given!"); Preconditions.checkArgument(StringUtils.isNoneEmpty(actio...
final Long testCommandId = 815L; final NewCommandSourceHandler registeredHandler = this.commandHandlerProvider.getHandler("HUMAN", "UPDATE"); final CommandProcessingResult result = registeredHandler .processCommand(JsonCommand.fromExistingCommand(testCommandId, null, null, null...
48427914_2
class FileDownloadUtils { public static long parseContentLengthFromContentRange(String contentRange) { if (contentRange == null || contentRange.length() == 0) return -1; final String pattern = "bytes (\\d+)-(\\d+)/\\d+"; try { final Pattern r = Pattern.compile(pattern); ...
long length = FileDownloadUtils.parseContentLengthFromContentRange(""); assertThat(length).isEqualTo(-1); } }
48430544_5
class GuiceVerticleFactory implements VerticleFactory { @Override public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception { verticleName = VerticleFactory.removePrefix(verticleName); Class clazz; if (verticleName.endsWith(".java")) { Co...
// Arrange String identifier = GuiceVerticleFactory.PREFIX + ":" + VerticleWithDependency.class.getName(); // Act Verticle verticle = factory.createVerticle(identifier, this.getClass().getClassLoader()); // Assert assertThat(verticle).isExactlyInstanceOf(VerticleWithDep...
48443654_15
class TimestampUtils { public static String getISO8601StringForTime(long time) { return ISO8601Utils.format(new Date(time), true); } public static String getReadableDate(long time); public static Date getDateForISO8601String(String time); public static Integer getDaysBetweenDates(@Nullable...
String ts = "2017-09-12T23:04:02.000Z"; String formattedString = TimestampUtils.getISO8601StringForTime(1505257442000l); Assert.assertNotNull(formattedString); Assert.assertEquals(ts, formattedString); } }
48446680_4
class EasyPermissions { public static void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults, @NonNull Object......
EasyPermissions.onRequestPermissionsResult(TestActivity.REQUEST_CODE, ALL_PERMS, SMS_DENIED_RESULT, spyActivity); verify(spyActivity, times(1)) .onPermissionsGranted(integerCaptor.capture(), listCaptor.capture()); assertThat(integerCaptor.getValue()).isEqualTo(TestActivity.REQUE...
48451041_1
class BigdataSailRemoteRepositoryConnection implements RepositoryConnection { @Override public void export(final RDFHandler handler, final Resource... c) throws RepositoryException, RDFHandlerException { exportStatements(null, null, null, true, handler, c); } public BigdataSailRemoteRepositoryConnection...
final RDFHandler handler = new RDFHandlerBase(); con.exportStatements(s, p, o, includeInferred, handler, c); assertEquals(EncodeDecodeValue.encodeValue(s), remote.data.opts.getRequestParam("s")); assertEquals(EncodeDecodeValue.encodeValue(p), remote.data.opts.getRequestParam("p")); assertEquals(EncodeDecodeVa...
48454315_0
class Transformer implements ClassFileTransformer { @Override public byte[] transform(final ClassLoader loader, final String className, final Class<?> classBeingRedefined, final ProtectionDomain protectionDomain, final byte[] classfileBuffer) throws IllegalClassFormatException { try { ...
final ClassNode cn = createClassNode(AsyncFunction.class, cw -> { MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "apply", "(Ljava/lang/Object;)Lcom/ea/async/Task;", null, new String[]{ "java/lang/Exception" }); mv.visitCode(); mv.visitVarInsn(ALOAD, 1); mv.visitTyp...
48461129_4
class Img implements ImgBase<Pixel> { public int getValue(final int x, final int y){ return this.data[y*this.width + x]; } public Img(int width, int height); public Img(Dimension dimension); public Img(BufferedImage bimg); public Img(int width, int height, int[] data); public Img(Dimension dim, int[] da...
Img img = new Img(400, 400); img.paint(g->{ g.setColor(new Color(0xffff0000)); g.drawLine(0, 0, 400, 400); }); img.forEach(px->{ if(px.getX() == px.getY()){ assertEquals(0xffff0000, px.getValue()); } else { assertEquals(0, px.getValue()); } }); } }
48485491_32
class ServiceResponseDecoder implements HttpResponseDecoder<ServiceResponse<T>> { @Override public ServiceResponse<T> decode(HttpResponse httpResponse) throws Exception { Map<String, String> headers = getHeaders(httpResponse); collectedHeaders.forEach((k, v) -> Optional.ofNullable(localCollecte...
HttpResponse mockHttpResponse = mock(HttpResponse.class); StatusLine mockStatusLine = mock(StatusLine.class); HttpEntity mockEntity = mock(HttpEntity.class); InputStream stream = mock(InputStream.class); String errorString = "{\"error\":\"testing error\"}"; Map<String, C...
48500629_64
class FieldDocumentationGenerator { public FieldDescriptors generateDocumentation(Type baseType, TypeFactory typeFactory) throws JsonMappingException { JavaType javaBaseType = typeFactory.constructType(baseType); List<JavaType> types = resolveAllTypes(javaBaseType, typeFactory, typeMapp...
// given ObjectMapper mapper = createMapper(); mockFieldComment(FirstLevel.class, "second", "2nd level"); mockFieldComment(SecondLevel.class, "third", "3rd level"); mockFieldComment(ThirdLevel.class, "fourth", "4th level"); mockFieldComment(FourthLevel.class, "fifth", "5t...
48520201_2
class MathUtils { public static float angle(float x1, float y1, float x2, float y2) { return (float) Math.toDegrees(Math.atan2(x2 - x1, y2 - y1)); } public static float barryCentric(Vector3 p1, Vector3 p2, Vector3 p3, Vector2 pos); public static float dst(float x1, float y1, float x2, float y2...
assertEquals(45.0f, MathUtils.angle(0.0f,0.0f,1.0f,1.0f), 0.0f); } }
48524181_1
class Paperwork { public String get(String key) { init(); return json.optString(key); } public Paperwork(Context context); public Paperwork(Context context, String filename); private void init(); private String getFileContents(); } class PaperworkTest { @Test pub...
final Paperwork paperwork = new Paperwork(RuntimeEnvironment.application); assertEquals("hell yeah", paperwork.get("testing rocks")); } }
48536970_0
class MapExample { public static <T, U> Map<T, U> createMap(SimpleEntry<T, U>... entries) { return Stream.of(entries).collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue)); } public static void doSth(Map<T, U> map); } class MapExampleTest { @Test public void shouldCreateAHashMapUsi...
Map<String, Integer> nameAndAge = MapExample.createMap(new SimpleEntry<>("shekhar", 32), new SimpleEntry<>("rahul", 33), new SimpleEntry<>("sameer", 33)); assertThat(nameAndAge.size(), equalTo(3)); } }
48556027_3
class TwitterOauth { public static String getOautHeaderString(Credentials credentials, String method, String baseUrl, Map<String, String> params) { String nonce = UUID.randomUUID().toString(); int time = Math.round(System.currentTimeMillis()/1000L); return getOautHeaderString(credentials, m...
String consumerKey = "xvz1evFS4wEEPTGEFPHBog"; String nonce = "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg"; String signature = "tnnArxj06cWHq44gCs1OSKk/jLY="; int time = 1318622958; String token = "370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb"; String expected = "OA...
48577594_47
class CloudFormation { public void signalReady(String stackName, String resourceName) { Preconditions.checkArgument(stackName != null && !stackName.isEmpty()); Preconditions.checkArgument(resourceName != null && !resourceName.isEmpty()); SignalResourceRequest req = new SignalResourceRequest...
HashMap<String, String> tags = new HashMap<>(); tags.put(CloudFormation.TAG_CLOUDFORMATION_LOGICAL_ID, "resourceTag"); tags.put(CloudFormation.TAG_CLOUDFORMATION_STACK_NAME, "stackTag"); Mockito.when(this.ec2Mock.getInstanceTags()).thenReturn(tags); try { this.cloudF...
48581176_1
class EventParser { public static Map<EventEnum, Map<String, Integer>> parseEvent(File file){ if(null==file || !file.exists()) return null; System.out.println(file.getName()+"==========================="); LOGGER.debug("开始处理文件:{}", file.getName()); LineProcessor<Map<EventEnum, Ma...
String path=FileUtils.corpousPath+"/train/test-arg.txt"; System.out.println(path); //String path = this.getClass().getClassLoader().getResource("train/test-arg.txt").getPath(); File file = new File(path); Assert.assertTrue(null!=file && file.exists()); Map<EventEnum, Map<Strin...
48583116_1
class Trip implements Serializable, Comparable<Trip>, Cloneable { public final String getNote() { return mNote; } public Trip(); public Trip(final String parName, final GregorianCalendar parStartDate, final GregorianCalendar parEndDate, final S...
assertEquals(mTestTrip.getNote(), TRIP_NOTE); mTestTrip.setNote(UPDATED_TRIP_NOTE); assertEquals(mTestTrip.getNote(), UPDATED_TRIP_NOTE); } }
48641480_0
class MainService { public String doSomething() { if (restService.executeServerCall()) { return "Hello world"; } else { throw new RuntimeException("Error!"); } } @Inject public MainService(RestService restService); @Rule public JUnitDaggerMockRule rule...
when(restService.executeServerCall()).thenReturn(true); String s = mainService.doSomething(); assertThat(s).isEqualTo("Hello world"); } }
48675485_89
class ContextFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { Map<String, String> attachments = invocation.getAttachments(); if (attachments != null) { attachments = new HashMap<String, String>(attachments); att...
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); Invoker<DemoService> invoker = new MyInvoker<DemoService>(url); Invocation invocation = new MockInvocation(); Result result = contextFilter.invoke(invoker, invocation); assertNull(RpcContext.getContext().getInv...
48688246_1
class TimestampBasedStreamSource implements StreamSource, DbHostInfo { static String findLastFileStartLeTimestamp(long targetTimestamp, List<String> binlogFiles, ExtractValidBeginTimestampFunction beginTimestampFunction) { int max = binlogFiles.size() - 1; // 先尝试最后一个文件,最后一个文件的第一个事件时间l...
Assert.assertEquals("mysql-bin.005596", findLastFileStartLeTimestamp(150L, binlogFiles, extractValidBeginTimestampFunction)); } }
48699616_1
class Primes { public static boolean isPrime(int n) { for (int i = 2; i < n; i++) { if (n % i == 0) { return false; } } return true; } public static boolean isPrimeFast(int n); public static boolean isPrimeWhile(int n); public static boolean isPrime(long n); } class PrimeTe...
long n = Integer.MAX_VALUE; Assert.assertTrue(Primes.isPrime(n)); } }
48709314_5
class StringBuilderUtils { public static boolean startsWith(@NonNull StringBuilder stringBuilder, @NonNull String start) { return stringBuilder.indexOf(start) == 0; } public static void replace(@NonNull StringBuilder stringBuilder, @NonNull String toReplace, ...
StringBuilder stringBuilder = new StringBuilder("1234567890"); Assert.assertTrue(StringBuilderUtils.startsWith(stringBuilder, "1")); Assert.assertFalse(StringBuilderUtils.startsWith(stringBuilder, "2")); } }
48789600_2
class BootstrapHandler { public BootstrapResponse bootstrap(final Identity sender, final BootstrapRequest request) { final String endpoint = request.getEndpointName(); // Start session, checking the BS credentials final BootstrapSession bsSession = this.bsSessionManager.begin(endpoint, sen...
final MockBootstrapSessionManager bsSessionManager = new MockBootstrapSessionManager(true); final LwM2mBootstrapRequestSender requestSender = new MockRequestSender(true); final BootstrapStore bsStore = new BootstrapStore() { @Override public BootstrapConfig getBootstrap(...
48804926_31
class KeywordRouter implements Router { @Override public Agent[] route(Request request) { String requestText = request.getText().toLowerCase(); String[] tokens = tokenizer.tokenize(requestText); if (tokens.length == 0) { return new Agent[0]; } Set<Agent> age...
Agent agent1 = mock(Agent.class); MultiValuedMap params1 = new MultiValuedMap(); params1.addString(KeywordRouter.KEYWORDS, "time"); params1.addString(KeywordRouter.KEYWORDS, "date"); Agent agent2 = mock(Agent.class); MultiValuedMap params2 = new MultiValuedMap(); ...
48812966_0
class PermitQueue { @SuppressWarnings("unchecked") public <RESP> CompletableFuture<RESP> runRequest(Supplier<CompletableFuture<RESP>> processor) { long countId = counter.getAndIncrement(); long time = System.currentTimeMillis(); CompletableFuture<RESP> future = new CompletableFuture<RESP>(); queue.add(new Q...
CompletableFuture<Long> future1 = new CompletableFuture<Long>(); svc.addToReturn(future1); CompletableFuture<Long> future2 = new CompletableFuture<Long>(); svc.addToReturn(future2); CompletableFuture<Long> future3 = new CompletableFuture<Long>(); svc.addToReturn(future3); queue2.runRequest(() -> svc.ru...
48878116_0
class SessionDao { public void updateAllSync(List<Session> sessions) { speakerRelation().deleter().execute(); categoryRelation().deleter().execute(); placeRelation().deleter().execute(); for (Session session : sessions) { insertSpeaker(session.speaker); inse...
sessionDao.updateAllSync(SESSIONS); assertThat(orma.selectFromSpeaker().idEq(SPEAKER_ID1)).hasSize(1); assertThat(orma.selectFromPlace().idEq(PLACE_ID1)).hasSize(1); assertThat(orma.selectFromCategory().idEq(CATEGORY_ID1)).hasSize(1); assertThat(orma.selectFromSession().idEq(SES...
48891106_15
class MatchdirFilter extends Filter { public void process(ScoreChart scorechart, User user, InetAddress source, char direction, InodeHandleInterface file, RemoteSlave sourceSlave) { boolean validPath = _negateExpr != _p.matcher(file.getPath()).matches(); if (validPath) { ...
Properties p = new Properties(); p.put("1.assign", "slave1+100, slave2-100"); p.put("1.match", "/path1/*"); Filter f = new MatchdirFilter(1, p); ScoreChart sc = new ScoreChart(Arrays.asList(rslaves)); f.process(sc, null, null, Transfer.TRANSFER_SENDING_DOWNLOAD, new Dir...
48911497_1
class StudentHelper { public static Long extractLongIdFromUniqueId(String uniqueId) { String[] uniqueIdArray = uniqueId.split("_"); Long longId = Long.valueOf(uniqueIdArray[1]); return longId; } public static String extractDeviceIdFromUniqueId(String uniqueId); public static St...
String uniqueId = "4113947bec18b7ad_1"; Long longId = StudentHelper.extractLongIdFromUniqueId(uniqueId); assertThat(longId, is(1L)); } }
48961876_0
class UpdatePosEvent { public int getPosition() { return position; } public UpdatePosEvent(int position); private static UpdatePosEvent event; } class UpdatePosEventTest { private static UpdatePosEvent event; @Test public void test() {
assertThat(event.getPosition(), is(5)); } }
49018889_0
class TransformerConfig { public Set<Integer> findPeriod(String symbol, String interval) { String key = (symbol + interval).toLowerCase(); if (!periods.containsKey(key)) { Node<String> n1 = periodsTree.getOtherwiseChild(symbol, "*"); if (n1 == null) throw new IllegalArgumentException("...
InputStream content = new DefaultResourceLoader().getResource("classpath:yml/sample.yml").getInputStream(); Map<String, Object> vals = new Yaml().loadAs(content, Map.class); Map<String, List<Map>> transformers = (Map) vals.get("transformers"); List<Map<String, String>> numchance = (List) transformers...
49031895_62
class Agent extends WorldEntity implements Drawable { public boolean equip(ToolType type) { if (!this.canEquip(type)) { return false; } Map<String, String> attributes; switch (type.displayName()) { case "Axe": createNewResource(); ...
assertTrue(agent.equip(ToolType.SHOVEL)); assertTrue(agent.equip(ToolType.AXE)); assertTrue(agent.equip(ToolType.HAMMER)); assertTrue(agent.equip(ToolType.HOE)); assertTrue(agent.equip(ToolType.PICKAXE)); assertTrue(agent.equip(ToolType.SICKLE)); assertFalse(agent...
49057615_42
class DockerModuleHandle implements ModuleHandle { @Override public Future<Void> start() { if (dockerPull) { return pullImage().compose(x -> prepareContainer()); } return prepareContainer(); } DockerModuleHandle(Vertx vertx, LaunchDescriptor desc, String id, Ports port...
Vertx vertx = Vertx.vertx(); LaunchDescriptor ld = new LaunchDescriptor(); ld.setDockerImage("folioci/mod-users:5.0.0-SNAPSHOT"); ld.setDockerPull(false); Ports ports = new Ports(9232, 9233); JsonObject conf = new JsonObject().put("dockerUrl", "tcp://localhost:9231"); DockerModuleHandle dh...
49067019_7
class DateTimes { public static long getNextOccurrence(long now, DayOfWeek dayOfWeek, int hour, int minute) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(now); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); if (cal...
Calendar expected = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin")); expected.set(2016, Calendar.JULY, 8, 13, 0, 0); expected.set(Calendar.MILLISECOND, 0); assertEquals(expected.getTimeInMillis(), DateTimes.getNextOccurrence(JULY_FIRST_2016, DayOfWeek.FRIDAY, 13, 0)); } ...
49071798_21
class SamhsaMatcher implements Predicate<ExplanationOfBenefit> { @Override public boolean test(ExplanationOfBenefit eob) { ClaimType claimType = TransformerUtils.getClaimType(eob); if (claimType == ClaimType.CARRIER) { return testCarrierOrDmeClaim(eob); } else if (claimType == ClaimType.DME) { return tes...
SamhsaMatcher matcher = new SamhsaMatcher(); ExplanationOfBenefit sampleEob = getSampleAClaim(ClaimType.HOSPICE); Coding sampleEobDiagnosis = sampleEob.getDiagnosisFirstRep().getDiagnosisCodeableConcept().getCodingFirstRep(); sampleEobDiagnosis.setSystem(IcdCode.CODING_SYSTEM_ICD_10).setCode(SAMPLE_SAMHSA_ICD_...
49078733_0
class ListPresenter extends BasePresenter<ListArcticleView> { @Override public void detachView() { super.detachView(); getBlogPosts.unsubscribe(); } @Inject public ListPresenter(GetBlogPosts getBlogPosts); @Override public void attachView(ListArcticleView mvpView); public void getPosts(int page, b...
presenter.detachView(); Mockito.verify(getPosts).unsubscribe(); } }
49126308_11
class ElasticScroll implements DatabaseScrolling { @Override public DatabaseScrolling withScrollSize(final int size) { search.setSize(size); return this; } ElasticScroll( final Client client, final SearchRequestBuilder search, final TimeValue timeValue); @Override public DatabaseScrol...
scroll.withScrollSize(123); verify(search).setSize(123); } }
49135503_26
class CircularBuffer { int forwards(final int currentPosition){ if (currentPosition == buffer.length-1){ return 0; }else{ return currentPosition + 1; } } public CircularBuffer(final int size); public void write(final byte data); public void readAll...
final CircularBuffer buffer = new CircularBuffer(10); assertEquals(1, buffer.forwards(0)); assertEquals(5, buffer.forwards(4)); assertEquals(0, buffer.forwards(9)); } }
49206166_56
class QuotedStringTokenizer implements ITokenizer { @Override public String[] tokenize(String input) { String[] result = tokenizeWithRegExp(input); if(trimValues) { result = StringUtils.trimAllElements(result); } return result; } public QuotedStringTokeniz...
String input = "\" Value0,Value1 \", Value2"; String[] result = new QuotedStringTokenizer(",", false).tokenize(input); Assert.assertNotNull(result); Assert.assertEquals(2, result.length); Assert.assertEquals(" Value0,Value1 ", result[0]); Assert.assertEquals(" Value2", ...
49230474_2
class Cappuccino { public static void markAsBusy(@NonNull Object object) { markAsBusy(nameOf(object)); } private Cappuccino(); @NonNull public static CappuccinoResourceWatcher newIdlingResourceWatcher(@NonNull Object resource); @NonNull public static CappuccinoResourceWatcher newIdlingRe...
// This test is doing double-duty, testing both the Object and String versions of the method CappuccinoResourceWatcher watcher1 = Cappuccino.newIdlingResourceWatcher(ANY_NAME); CappuccinoResourceWatcher watcher2 = Cappuccino.newIdlingResourceWatcher(new Object()); Cappuccino.markAsBusy(...
49235392_12
class StandardCrimeModel implements CrimeModel { @Override public void setTitle(String title) { crime.setTitle(title); } public StandardCrimeModel(Crime crime); @Override public Date getDate(); @Override public void setSolved(boolean solved); } class StandardCrimeModelTest { @...
Crime crime = new Crime(); StandardCrimeModel model = new StandardCrimeModel(crime); model.setTitle("title"); assertThat(crime.getTitle(), is(equalTo("title"))); } }
49250409_4
class State { public void setLoading(@Nullable String path) { if (!isLoaded(path)) { loadState = LoadState.LOADING; this.path = path; } } @Nullable public String getPath(); public boolean isDeinit(); public void setDeinit(); public boolean isInit(); ...
subject.setLoading(PATH_A); assertInit(true); } }
49317403_22
class ScheduleDayPresenter extends BaseFragmentPresenter<ScheduleDayView> { @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); this.view.initSlotsList(scheduleDay.getSlots()); } public ScheduleDayPresent...
// When presenter.onViewCreated(null, null); // Then verify(view).initSlotsList(slots); } }
49339629_39
class MulticastSender extends UDPSender { @Override public void init() throws Exception { Configuration configuration = getConfiguration(); SocketAddress la = Util. computeLocalEndpoint( configuration.getNetworkInterface(), confi...
Configuration c = new Configuration(); assertNull(c.getInetAddress()); MulticastSender s = getSenderToTest(c); try { s.init(); fail("should have thrown exception"); } catch(UserErrorException e) { String msg = e.getMessage(); ...
49354052_361
class DefaultByteBufHolder implements ByteBufHolder { @Override public String toString() { return StringUtil.simpleClassName(this) + '(' + contentToString() + ')'; } public DefaultByteBufHolder(ByteBuf data); @Override public ByteBuf content(); @Override public ByteBufHolder copy(); ...
ByteBufHolder holder = new DefaultByteBufHolder(Unpooled.buffer()); assertEquals(1, holder.refCnt()); assertNotNull(holder.toString()); assertTrue(holder.release()); assertNotNull(holder.toString()); } }
49362377_10
class ReportHandler { public synchronized HandleStatus handleReport(Intent intent) { HandleStatus status = HandleStatus.HANDLED; boolean isOnline = mNetworkManager.isOnline() && canUseNetwork(); try { if (null == intent.getExtras()) return status; int event = intent....
mConfig.setBulkSize(2); when(mStorage.addEvent(mTable, DATA)).thenReturn(2); Intent intent = newReport(SdkEvent.ENQUEUE, reportMap); mHandler.handleReport(intent); verify(mStorage, times(1)).addEvent(mTable, DATA); verify(mStorage, times(1)).getEvents(mTable, mConfig.getB...
49384652_18
class MasterSlaveJobSummaryServiceImpl extends AbstractService implements MasterSlaveJobSummaryService { @Override public synchronized void saveJobSummary(MasterSlaveJobSummary masterSlaveJobSummary) { MasterSlaveJobData masterSlaveJobData = masterSlaveApiFactory.jobApi().getJob(masterSlaveJobSummary.g...
masterSlaveJobService.saveJob(getSampleJarFile(), "com.zuoxiaolong"); List<MasterSlaveJobSummary> jobSummaries = masterSlaveJobSummaryService.getAllJobSummaries(); MasterSlaveJobSummary jobSummary = jobSummaries.get(0); jobSummary.setJobCron("0 * * * * ?"); jobSummary.setMisfireP...
49420416_0
class Fetcher { public Fetcher skipNulls() { this.skipNulls = true; return this; } public Fetcher(Cursor cursor); public static Fetcher of(Cursor cursor); public Optional<ResultT> toValue(Converter<ResultT> converter); public List<ResultT> toList(Converter<ResultT> converter)...
when(cursor.getCount()).thenReturn(3); when(cursor.moveToNext()).thenReturn(true, true, true, false); when(cursor.getString(0)).thenReturn("First", null, "Third"); Fetcher fetcher = Fetcher.of(cursor).skipNulls(); List<String> result = fetcher.toList(Converter.STRING); assertThat(result).isNotNu...
49445030_0
class IntegerUtils { public static int log10(long unsigned) { if (unsigned != 0) { int digits = maxLog10ForLeadingZeros[Long.numberOfLeadingZeros(unsigned)]; return digits + (unsigned >= powersOf10[digits] ? 1 : 0); } else { return 1; } } private...
assertEquals(1, IntegerUtils.log10(1)); assertEquals(1, IntegerUtils.log10(9)); assertEquals(2, IntegerUtils.log10(10)); assertEquals(2, IntegerUtils.log10(11)); assertEquals(2, IntegerUtils.log10(99)); assertEquals(3, IntegerUtils.log10(100)); assertEquals(3, I...
49461308_5
class RemoteUserFederationProviderFactory implements UserFederationProviderFactory { @Override public UserFederationSyncResult syncChangedUsers(KeycloakSessionFactory sessionFactory, String realmId, UserFederationProviderModel model, Date lastSync) { throw new UnsupportedOperationException("This fe...
String realmId = UUID.randomUUID().toString(); Date lastSync = new Date(); factory.syncChangedUsers(keycloakSessionFactory, realmId, userFederationProviderModel, lastSync); verifyZeroInteractions(keycloakSession, keycloakSessionFactory, realmId, userFederationProviderModel, lastSync); ...
49472222_0
class FoCorsFilter implements ContainerResponseFilter { List<String> parseCorsAllowedOrigins(String corsAllowedOriginsStr) { List<String> resultList = new ArrayList<>(); corsAllowedOriginsStr = StringUtils.trimToNull(corsAllowedOriginsStr); String[] originArray = StringUtils.split(corsAllowedOriginsStr, ";"); ...
FoCorsFilter filter = new FoCorsFilter(); assertArrayEquals(new String[0], filter.parseCorsAllowedOrigins(" ").toArray()); assertArrayEquals(new String[]{"http://foo.com", "https://bar.com:2018"}, filter.parseCorsAllowedOrigins(" http://foo.com ; https://bar.com:2018 ").toArray(...
49473421_2
class Promote { public static Condition.Value every(int n) { return new Condition().every(n); public static Condition.Value every(int n) { return new Condition().every(n); } public static Condition.Value every(int n) { return new Condition().every(n); public static Condition.Value after(int n); public static Conditio...
assertThat(Promote.every(2).times().show(c, 100, null), is(true)); assertThat(Promote.every(2).times().show(c, 100, null), is(false)); assertThat(Promote.every(2).times().show(c, 100, null), is(true)); assertThat(Promote.every(2).times().show(c, 100, null), is(false)); assertThat(Promote.every(2).times().show...
49493793_5
class Binder { static void bind(SQLiteStmt stmt, int index, Object value) { if (value == null) { stmt.bindNull(index); } else if (value instanceof Integer || value instanceof Long || value instanceof Short) { stmt.bindLong(index, ((Number) val...
Binder.bind(mStmt, 6, "test"); Mockito.verify(mStmt).bindString(6, "test"); } }
49517364_2
class TokenRegistry implements InvalidClientIdHandler, InternalRegistrationProgressListener { public void receive(String token) throws JSONException { Log.d(TAG, "Received token for " + platformType.toString() + ": " + token); SharedPreferences preferences = PreferenceManager.getDefaultSharedPrefer...
tokenRegistry.receive("mysuperspecialfcmtoken"); verify(factory).newTokenUploadHandler(context, stack); ArgumentCaptor paramsCaptor = ArgumentCaptor.forClass(StringEntity.class); verify(client).post( eq(context), eq("https://nativepushclient-cluster1.pus...
49529486_102
class PaymentMethodsPresenter extends BasePresenter<PaymentMethods.View> implements PaymentMethods.Actions { @Override public void start() { definePaymentMethodsExclusions(); retrievePaymentMethods(); if (showBankDeals && isViewAttached()) { getView().showBankDeals(); ...
final List<PaymentMethod> paymentMethodsStub = PaymentMethodStub.getAllBySite(Sites.ARGENTINA.getId()); when(paymentMethodsRepository.getPaymentMethods()).thenReturn(new StubSuccessMpCall(paymentMethodsStub)); presenter.start(); verify(view).showProgress(); verify(view).showPay...
49574503_10
class Either implements Union2<L, R> { public static <L, R> Either<L, R> right(R value) { return new Right<>(value); } Either(); public static Either<L, R> left(L value); public abstract boolean isLeft(); public abstract boolean isRight(); @Deprecated public abstract void fold(A...
Either<EventA, EventB> right = Either.right(eventB); right.continued(actionA, actionB); verify(actionB).call(eventB); verifyNoMoreInteractions(actionA); } }
49610798_1
class KeyboardRow extends ArrayList<KeyboardButton> implements Validable { public void addAll(List<String> buttonNames) { buttonNames.forEach(name -> super.add(new KeyboardButton(name))); } public boolean add(String text); public void add(int index, String text); public boolean contains(St...
final KeyboardRow keyboardRow = new KeyboardRow(); keyboardRow.addAll(new ArrayList<String>()); assertTrue(keyboardRow.isEmpty()); } }
49656131_127
class Router { public void launchCreateDeckFlow(Activity activity, NewDeckContext newDeckContext) { Intent createIntent = new Intent(activity, GetStartedDeckActivity.class); createIntent.putExtra(AddDeckActivity.INTENT_KEY_DECK, newDeckContext); activity.startActivityForResult(createIntent,...
Activity activity = mock(Activity.class); NewDeckContext newDeckContext = mock(NewDeckContext.class); router.launchCreateDeckFlow(activity, newDeckContext); ArgumentCaptor<Intent> argument = ArgumentCaptor.forClass(Intent.class); verify(activity).startActivityForResult(argument...
49670957_523
class Substring implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length < 2 || args.length > 3) { throw new ValueExprEvaluationException("Incorrect number of arguments for SUBSTR: " + args.length); } Value argVa...
Literal pattern = f.createLiteral("12345"); Literal startIndex = f.createLiteral(2); Literal length = f.createLiteral(3); Literal result = substrFunc.evaluate(f, pattern, startIndex, length); assertEquals("234", result.getLabel()); } }
49671662_1
class WifiConfigStoreParser { public static List<WifiNetwork> parse(InputStream in) throws XmlPullParserException, IOException { List<WifiNetwork> wifiNetworks = new ArrayList<>(); try { XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser...
InputStream wifiConfigStoreFileStream = getClass().getClassLoader().getResourceAsStream("test_WifiConfigStore.xml"); List<WifiNetwork> parsedWifiNetworks = WifiConfigStoreParser.parse(wifiConfigStoreFileStream); assertEquals(expectedWifiNetworks.size(), parsedWifiNetworks.size()...
49678622_1
class ServerBulletinSummary extends ShortServerBulletinSummary { public UniversalId getUniversalId() { return UniversalId.createFromAccountAndLocalId(accountId, getLocalId()); } public ServerBulletinSummary(UniversalId uidToUse, String lastModifiedToUse, String serverTimestampToUse); public ServerBulletinSum...
String accountId = "account1"; String localId = "localid1"; String lastModified = "2014-06-07"; String serverTimestamp = "2012-02-04"; UniversalId uid = UniversalId.createFromAccountAndLocalId(accountId, localId); ShortServerBulletinSummary shortSummary = new ShortServerBulletinSummary(localId, lastModified...
49730727_2
class Gandalf { @SuppressWarnings("PMD.AvoidCatchingGenericException") public void shallIPass(Context context, final GandalfCallback gandalfCallback) { LoggerUtil.logD("Fetching bootstrap"); new BootstrapApi(context, okHttpClient, bootstrapUrl, customDeserializer, callbackExecutor) ...
enqueueMockResponse("updateRequired.json"); final CountDownLatch countDownLatch = new CountDownLatch(1); GandalfCallback mockCallback = getGandalfCallback(countDownLatch); getGandalfInstance(VERSION_NAME, 6).shallIPass(mockContext, mockCallback); boolean status = countDownLat...
49733838_82
class ExecutorService { @Scheduled(fixedDelay = 2000, initialDelay = 500) public void checkExecutors() { for (Executor executor : executors) { checkExecutor(executor); } startExecutions(); } @Autowired public ExecutorService( ExecutionSource executions,...
ExecutionSource executions = Mockito.mock(ExecutionSource.class); ExecutorEventListener eventListener = null; Configuration configuration = Mockito.mock(Configuration.class); Mockito.when(configuration.getExecutorUri()).thenReturn("iri"); ExecutorRestClient restClient = null; ...
49743270_13
class ExceptionFilters { public static Predicate<Throwable> markAllExceptions() { return new AnyThrowable(); } private ExceptionFilters(); public static Predicate<Throwable> markCheckedExceptions(); } class ExceptionFiltersTest { @Test public void testMarkAll() throws Exception {
assertTrue(ExceptionFilters.markAllExceptions().test(new Throwable())); assertTrue(ExceptionFilters.markAllExceptions().test(new RuntimeException())); assertTrue(ExceptionFilters.markAllExceptions().test(new NullPointerException())); assertTrue(ExceptionFilters.markAllExceptions().test(n...
49763242_868
class KeyProvider { public static Options options(Configuration conf) { return new Options(conf); } public KeyProvider(Configuration conf); public Configuration getConf(); public boolean isTransient(); public abstract KeyVersion getKeyVersion(String versionName ...
Configuration conf = new Configuration(); conf.set(KeyProvider.DEFAULT_CIPHER_NAME, "myCipher"); conf.setInt(KeyProvider.DEFAULT_BITLENGTH_NAME, 512); Map<String, String> attributes = new HashMap<String, String>(); attributes.put("a", "A"); KeyProvider.Options options = KeyProvider.options(conf)...
49778000_0
class BudgetAdapter extends ArrayAdapter<Budget> { @Override public View getView(int position, View convertView, ViewGroup parent) { // Get the data item for this position Budget item = getItem(position); ViewHolder holder; // Check if an existing view is being reused, oth...
ActivityController activityController = Robolectric.buildActivity(BudgetActivity.class).create(); Activity activity = (Activity)activityController.get(); DBHelper db = new DBHelper(activity); final String NAME = "name"; final int BUDGET = 100; final double CURRENT = 50.0...
49818800_19
class JavaApiConverter { public static CacheResponse createJavaCacheResponse(final Response response) { final Headers headers = response.headers(); final ResponseBody body = response.body(); if (response.request().isHttps()) { final Handshake handshake = response.handshake(); return new Secur...
Request okRequest = createArbitraryOkRequest().newBuilder() .url("http://insecure/request") .post(createRequestBody("RequestBody")) .build(); ResponseBody responseBody = createResponseBody("ResponseBody"); Response okResponse = createArbitraryOkResponse(okRequest)...
49871069_0
class RxComboDetector { @VisibleForTesting static Flowable<Integer> detect(Flowable<Integer> clicks, final long maxIntervalMillis, final int minComboTimesCared) { return clicks.timestamp() .scan((lastOne, thisOne) -> { if (thisOne.time() - lastOne.time() ...
Flowable<Integer> mockClicks = Flowable .create(emitter -> { emitter.onNext(1); sleepSilently(50); emitter.onNext(1); sleepSilently(50); emitter.onNext(1); sleepSilently(50); ...
49876476_740
class TableMetaData { private Map<String, ColumnMetaData> getColumns(final Collection<ColumnMetaData> columnMetaDataList) { Map<String, ColumnMetaData> result = new LinkedHashMap<>(columnMetaDataList.size(), 1); for (ColumnMetaData each : columnMetaDataList) { String lowerColumnName = e...
tableMetaData = new TableMetaData(); assertThat(tableMetaData.getColumns(), is(Collections.emptyMap())); } }
49896881_40
class DataHubImpl implements DataHub { @Override public boolean isServerVersionValid(String versionString) { try{ Versions.MarkLogicVersion serverVersion = versions.getMLVersion(versionString); if (!(serverVersion.getMajor() == 9 || serverVersion.getMajor() == 10)) { ...
assertFalse(dh.isServerVersionValid("8.0-7")); } }
49904163_6
class Query { public City getCityByCrime(City c) { this.city = c; String name = c.getName(); name = name.replace("\'", "\'\'"); queryCityData = "SELECT * FROM Cities WHERE city=\'" + name + "\' AND state=\'" + states.get(c.getState()) + "\';"; queryHousingData = "SELECT id, place_name, place_id, p...
for(int i = 0; i < 27; i++) { City c = q.getCityData(cities[i][0]); boolean c_one = true, c_two = true, c_three = true, c_four = true, c_five = true; if(num[i][0] != -1.0f) c_one = c.getIndex_nsa() == num[i][0]; if(num[i][1] != -1.0f) c_two = c.getIndex_sa() == num[i][1]; if(num[i][2]...
49929380_213
class ReportGenerator implements IReportGenerator { protected synchronized void writeRoundTripToFile(RoundTrip roundTrip) { logger.info("Writing round trip to result file: " + roundTrip); String resultString = roundTrip.getResults() + "\n"; try { Files.write(Paths.get(outputFile...
Path path = Files.createTempFile("ReportGeneratorUnitTest", ".txt"); reportGenerator.outputFile = path.toString(); String expected = "2016-03-19T07:01:10,Long,ABC,100,100.23,0,2016-03-20T06:01:10,101.23,0,Short,XYZ,50,250.34,0,251.34,0"; Ticker longTicker = new StockTicker("ABC"); ...
49950879_41
class PostLexer implements TokenSource { @Override public Token nextToken() { LOGGER.trace("Entering nextToken()"); if (!heap.isEmpty()) { return heap.poll(); } while (true) { getNextToken(); switch (currToken.getType()) { case PreprocessorParser.AMPIF: prepro...
ParseUnit unit = new ParseUnit(new File(SRC_DIR, "lexer15.p"), session); TokenSource stream = unit.lex(); ProToken tok = (ProToken) stream.nextToken(); assertEquals(tok.getNodeType(), ABLNodeType.PROPARSEDIRECTIVE); assertEquals(tok.getChannel(), ProToken.PROPARSE_CHANNEL); tok = (ProToken) str...
49979053_5
class EventsFilter { public void parse(String query) throws BadRequestResponseException { this.deviceGuid = null; this.locationGuid = null; this.channel = null; this.startingTimestamp = null; this.endTimestamp = null; if (!StringUtils.hasText(query)) { ...
try { EventsFilter filter = new EventsFilter(); filter.parse("timestamp:>2007/01/14"); fail(); } catch (final BadRequestResponseException e) { final String msg = "Not ISO Date: 2007/01/14"; assertEquals(msg, e.getMessage()); } } ...
50041690_6
class ColorUtil { public synchronized static String RgbToAnsi(String rgb, ColorSetting colorSetting) { switch(colorSetting) { case OFF: return ""; case ON: return getClosestTerminalCode(colors.get(rgb), ansiColorsToTerminalCodes); case EXT...
// set java.awt.headless so that we don't activate the awt bug (see issue #982) System.setProperty("java.awt.headless", "true"); assertEquals("", ColorUtil.RgbToAnsi("red", ColorSetting.OFF)); assertEquals("\u001b[31m", ColorUtil.RgbToAnsi("red", ColorSetting.ON)); } }
50056934_79
class ZKLogSegmentMetadataStore implements LogSegmentMetadataStore, Watcher, Children2Callback { @Override public void updateLogSegment(Transaction<Object> txn, LogSegmentMetadata segment) { byte[] finalisedData = segment.getFinalisedData().getBytes(UTF_8); Op updateOp = Op.setData(segment.getZ...
LogSegmentMetadata segment = createLogSegment(1L, 99L); Transaction<Object> createTxn = lsmStore.transaction(); lsmStore.createLogSegment(createTxn, segment); FutureUtils.result(createTxn.execute()); // the log segment should be created assertNotNull("LogSegment " + segme...
50068565_2
class MapFrequencyFinder implements FrequencyFinder { @Override public double getFrequency(NoteName name) { return notes.get(name); } public MapFrequencyFinder(); private MapFrequencyFinder finder; } class MapFrequencyFinderTest { private MapFrequencyFinder finder; @Test ...
double frequency = finder.getFrequency(NoteName.B); assertEquals(123.5, frequency, 0.0); } }
50104552_0
class PdfTextStyle { public float getFontSize() { return fontSize; } public PdfTextStyle(float fontSize, PdfFont defaultFont, PDColor color, String style); public PdfTextStyle(String config); public PdfFont getFont(); public PDColor getColor(); public PDFont getCurrentFontStyle(...
float fontSize = 10.5f; PDColor red = new PDColor(new float[] {1.0f, 0.0f, 0.0f}, PDDeviceRGB.INSTANCE); PdfTextStyle config = new PdfTextStyle(fontSize, PdfFont.TIMES_ROMAN, red, "regular"); Assert.assertEquals(fontSize, config.getFontSize(), delta); } }
50105719_75
class SearchUtils { public static int kmp(ByteBuffer buf, byte[] sought) { if (sought == null || sought.length == 0) { return -1; } if (sought.length == 1) { int i = buf.position(); while (buf.hasRemaining()) { if (buf.get(i) == sought[0]...
byte[] sought = new byte[]{9}; assertThat(SearchUtils.kmp(buf, sought)).isEqualTo(5); } }
50118546_8
class ConfigurationStateUpdater { @VisibleForTesting PipelineInterpreter.State reload() { return reloadAndSave(); } @Inject public ConfigurationStateUpdater(RuleService ruleService, PipelineService pipelineService, Pipe...
final Injector injector = Guice.createInjector( new InMemoryServicesModule(), new ProcessorFunctionsModule(), new SchedulerBindings(), binder -> binder.install(new FactoryModuleBuilder().build(PipelineInterpreter.State.Factory.class)), ...
50140860_2
class ObjectMapperModule implements com.google.inject.Module { public ObjectMapperModule registerModule(Module module) { modulesToAdd.add(module); return this; } public ObjectMapperModule(); public ObjectMapperModule(Class<? extends Annotation> annotation); public ObjectMapperModule(Annotation ...
final Injector injector = Guice.createInjector( new ObjectMapperModule().registerModule(IntegerAsBase16Module.class, Ann.class), new Module() { @Override public void configure(Binder binder) { ...
50151956_0
class MessageRestController { @RequestMapping("/message") String getMessage() { return this.message; } @Autowired private ConfigurableEnvironment environment; @Autowired private MessageRestController controller; @Autowired private ContextRefresher refresher; } class ConfigurationClientApplicationTest { ...
assertThat(controller.getMessage()).isNotEqualTo("Hello test"); TestPropertyValues .of("message:Hello test") .applyTo(environment); assertThat(controller.getMessage()).isNotEqualTo("Hello test"); refresher.refresh(); assertThat(controller.getMessage()).isEqualTo("Hello test"); } }
50154902_18
class WrappingDividerAdapter extends PowerAdapterWrapper { @Override public int getItemCount() { if (getObserverCount() > 0) { return mItemCount; } return getItemCount(super.getItemCount()); } WrappingDividerAdapter(@NonNull PowerAdapter adapter, ...
configure(5, SHOW_LEADING_AND_TRAILING); mFakeAdapter.clear(); assertThat(mDividerAdapter.getItemCount()).isEqualTo(2); verify(mObserver).onItemRangeRemoved(0, 5); verify(mObserver).onItemRangeInserted(0, 1); verify(mObserver).onItemRangeInserted(1, 1); verifyNoMo...
50179515_11
class WalletToolsBTC implements IWalletTools { public MasterPrivateKeyBTC getMasterPrivateKey(String seedMnemonicSeparatedBySpaces, String password, String cryptoCurrency, int standard){ if (password == null) { password = ""; } List<String> split = ImmutableList.copyOf(Splitter....
Assert.assertEquals("xprv9s21ZrQH143K3vrXj7RW2pKgDjYifyseBrZjGSnxm6ik7JeSeQMn3mE7VjvfBQhMj8hBZja7cgs2EshvQQp2Akguei7WPkJiHH7CQtMs9mJ", masterPrivateKey.getPRV()); Assert.assertEquals("xpub6C4oSHiKXiakT4f7Ukj5FDzFmgpNrM3P895aLuymmtvvMuLp5vum1MRrh9SnEzaQBBCY7homGSefdc1HJU46vPzLj8jVcGFzBGC4ZQfVVui", master...
50185885_14
class FacebookSubscriber implements FlowableOnSubscribe<LoginResult> { @Override public void subscribe(FlowableEmitter<LoginResult> emitter) throws Exception { mCallback = new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult result) { if (!emitter.is...
mFacebookSubscriber.subscribe(mEmitter); when(mEmitter.isCancelled()).thenReturn(true); mFacebookSubscriber.mCallback.onError(new FacebookException()); verify(mEmitter, never()).onError(any(Throwable.class)); verify(mEmitter, never()).onNext(any(LoginResult.class)); verif...
50244301_3
class BitIntegerSet implements Set<Integer>, ReversibleIterable<Integer> { @NotNull @Override public Object[] toArray() { Object[] array = new Object[cardinality()]; int i = 0; for (Integer bitIndex : this) { array[i++] = bitIndex; } return array; } ...
BitIntegerSet intSet = new BitIntegerSet(); int[] result = intSet.toArray((int[]) null); assertArrayEquals(EMPTY, result); } }
50276657_1
class AbstractAcceptance implements Acceptance { @Override public Response handle(Request request) { Result result = null; Call call = request.getCall(); try { Object resObj = serviceInvoker.invoke(call.getService(), call.getGroup(), call.getMethod(), call.ge...
Request request = new Request(12345, SerializeType.JACKSON, new Call(DemoService.class.getName(), "", 3000, "hello", new Object[] { "guojinfei", 34 }, new Class<?>[] { String.class, int.class })); Response response = acceptance.handle(request); System.out.println(response); ...
50300127_2
class BasketCalculator { public float calculatePrice(List<String> books) { NormalizeBasket normalizeBasket = new NormalizeBasket(); normalizeBasket.addBooks(books); float amount = 0.0f; for (SetCollection collection : normalizeBasket.getCollections()) { int numBooks = collection.numBooks(); ...
BasketCalculator basketCalculator = new BasketCalculator(); List<String> basket = givenBasketWithBooks(FIRST_BOOK, FIRST_BOOK); float amount = basketCalculator.calculatePrice(basket); assertEquals(8 * 2, amount, DELTA_ZERO); } }
50309640_18
class ConsulAdvertiser { public boolean register( final String applicationScheme, final int applicationPort, final int adminPort) { return register(applicationScheme, applicationPort, adminPort, null); } public ConsulAdvertiser( final Environment environment, final ConsulFactory configura...
factory.setServicePort(8888); factory.setServiceAddress("127.0.0.1"); when(agent.isRegistered(anyString())).thenReturn(false); final ConsulAdvertiser advertiser = new ConsulAdvertiser(environment, factory, consul, serviceId); advertiser.register("http", 8080, 8081); final ImmutableRegi...
50326811_11
class LowMemorySet extends AbstractSet<T> implements Set<T> { @Override public boolean add(T t) { if (contains(t)) return false; backing.add(t); this.sort(); return true; } protected LowMemorySet(List<T> list); public static LowMemorySet<T> create(); public st...
LowMemorySet<String> set = LowMemorySet.copyOf(ELEMENTS); assertFalse(set.contains("Techcable")); set.add("Techcable"); assertTrue(set.contains("Techcable")); set.addAll(ImmutableList.of("Techcable", "PhanaticD", "Dragonslayer293", "Aikar")); assertTrue(set.contains("Tech...
50371312_4
class SoapUIRecipeExecutor implements RecipeExecutor { @Override public Execution executeRecipe(TestRecipe recipe) { applyRecipeFilters(recipe); return postRecipe(recipe, false); } @Override public Execution submitRecipe(TestRecipe recipe); private void applyRecipeFilters(TestRecip...
TestRecipe testRecipe = newTestRecipe( groovyScriptStep("println 'Hello Earth'") ).buildTestRecipe(); Execution execution = executor.executeRecipe(testRecipe); assertThat(execution.getId(), is(not(nullValue()))); assertThat(execution.getCurrentStatus(), is(TestJob...
50380775_9
class TurbolinksSession implements TurbolinksScrollUpCallback { public Activity getActivity() { return activity; } private TurbolinksSession(final Context context); public static TurbolinksSession getNew(Context context); public static TurbolinksSession getDefault(Context context); p...
assertThat(turbolinksSession.getActivity()).isNull(); } }
50436236_104
class CopyNumberChange { CopyNumberChange(@NotNull final List<StructuralVariantLegPloidy> structuralVariants) { assert (!structuralVariants.isEmpty()); final StructuralVariantLegPloidy template = structuralVariants.get(0); double copyNumberDifference = copyNumberDifference(template); ...
final StructuralVariantLegPloidy leg1 = svPloidy(-1, 1, 2, 1.6); final StructuralVariantLegPloidy leg2 = svPloidy(1, 1.5, 2, 1.6); final List<StructuralVariantLegPloidy> legList = Lists.newArrayList(leg1, leg2); assertPloidy(2.5, legList); assertCopyNumberChange(-0.4, legList); ...
50446559_84
class BoltNeo4jStatement extends Neo4jStatement { public static Statement newInstance(boolean debug, BoltNeo4jConnectionImpl connection, int... rsParams) { Statement statement = new BoltNeo4jStatement(connection, rsParams); ((Neo4jStatement) statement).setDebug(debug); return (Statement) Proxy.newProxyInstance(...
Statement statement = BoltNeo4jStatement.newInstance(false, mockConnectionOpenWithTransactionThatReturns(null)); statement.close(); verify(mockedRS, never()).close(); } }
50459141_8
class ChronosController { @RequestMapping(value="/job/{id}", method=RequestMethod.DELETE) public @ResponseBody Response deleteJob(@PathVariable("id") Long id) throws NotFoundException { JobSpec aJob = getJob(id); jobDao.deleteJob(aJob.getId()); return SUCCESS; } @Autowired public ChronosCon...
JobSpec aJob = getTestJob("Some Job"); when(jobDao.getJob(aJob.getId())).thenReturn(aJob); MockHttpServletRequestBuilder request = delete(String.format("/api/job/%s", aJob.getId())); mockMvc.perform(request) .andExpect(status().isOk()) .andExpect(content().string(success)); verify(jobD...
50552134_4
class JarUtils { public static JarFile toJarFile(URL jarURL) throws IOException { JarFile jarFile = null; final String jarAbsolutePath = resolveJarAbsolutePath(jarURL); if (jarAbsolutePath == null) return null; jarFile = new JarFile(jarAbsolutePath); return jarFi...
URL resourceURL = ClassLoaderUtils.getClassResource(classLoader, String.class); JarFile jarFile = JarUtils.toJarFile(resourceURL); JarFile rtJarFile = new JarFile(new File(SystemUtils.JAVA_HOME, "/lib/rt.jar")); Assert.assertNotNull(jarFile); Assert.assertEquals(rtJarFile.getName...
50560378_1
class PostRepository extends AbstractRepository<Post, Long> { public List<Post> findByKeyword(String keyword) { return stream().filter(p -> p.getTitle().contains(keyword) || p.getContent().contains(keyword)) .collect(toList()); } public long countByKeyword(String keyword); @Ove...
List<Post> foundPosts = posts.findByKeyword("test123"); assertEquals(0, foundPosts.size()); } }
50571610_0
class TenantContextHeaderInterceptor implements ClientHttpRequestInterceptor { public void setHeaderName(String headerName) { this.headerName = headerName; } @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution); private TenantContextHeaderInterce...
this.interceptor.setHeaderName("context"); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(this.interceptor); RestTemplate template = new RestTemplate(); template.setInterceptors(interceptors); MockRestServiceServer mockServer = MockRestServiceServer.createServer(tem...
50579018_38
class Value extends Expirable { @Override public Object getValue() { return value; } public Value(); public Value(Object version, long timestamp, Object value); @Override @SuppressWarnings("unchecked") public boolean isReplaceableBy(long txTimestamp, Object newVersion, Comparator ve...
String expectedValue = "Some value"; Value value = new Value(null, 100L, expectedValue); assertNull(value.getValue(99L)); } }
50594316_20
class GTSEncoder implements Cloneable { public synchronized void merge(GTSEncoder encoder) throws IOException { if (this.readonly) { throw new RuntimeException("Encoder is read-only."); } // // If the current encoder is empty and the base timestamps and wrapping // keys match, simply reset...
long now = System.currentTimeMillis() * 1000L; byte[] key = new byte[32]; GTSEncoder encoder1 = new GTSEncoder(now - 1000000L, key); encoder1.addValue(now, 111L, 11L, new BigDecimal("1.11")); encoder1.addValue(now + 1000000L, 222L, 22L, new BigDecimal("2.22")); GTSEncoder encoder2 = ne...