id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
38958995_5
class TreeNode implements Iterable<TreeNode<T>>, Serializable, Cloneable { public abstract Collection<? extends TreeNode<T>> subtrees()public abstract Collection<? extends TreeNode<T>> subtrees(); public abstract Collection<? extends TreeNode<T>> subtrees()public TreeNode(T data); public abstract Collection<? extend...
// Test if subtrees are correctly determined String message = "Subtrees collection was incorrectly determined"; Collection<TreeNode<String>> mSubtreesLevel1 = new HashSet<>(3); mSubtreesLevel1.add(node1); mSubtreesLevel1.add(node2); mSubtreesLevel1.add(node9); assertEquals(message, mSubtreesLevel1, root....
39005675_10
class FloatBag implements AnyBag<FloatBag> { @Override public void copyFrom(FloatBag from) { copyFrom(from, true); } public FloatBag(); @Override public void copyFrom(FloatBag from, boolean clearExceeding); @Override public void copyFrom(FloatBag from, int length); @Override publ...
// Test copyFrom(bag) and copyFrom(bag, clearExceeding) FloatBag bag0, bag1; float e0 = 1f, e1 = 1f, e2 = 1f, e3 = 1f; bag0 = new FloatBag(); bag0.set(0, e0); bag0.set(3, e1); bag0.set(9, e2); bag1 = new FloatBag(); bag1.copyFrom(bag0); as...
39006243_14
class CustomerController { @RequestMapping(value = "/customers/create", method = RequestMethod.GET) public String showCreateCustomerFormPage(ModelMap modelMap) { modelMap.addAttribute("createCustomerForm", new Customer()); logger.info("Accessed Create Customer page"); logger.debug("Retrieved createCustomerForm...
assertEquals("customers/customers-createCustomer", customerController.showCreateCustomerFormPage(new ModelMap())); } }
39013067_1
class ScheduleExpression { public Calendar ceil(Calendar cal) { if (contains(cal)) return cal; Calendar cal2 = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)); if (!containsDayOfWeek(cal2)) do cal2.add(C...
ScheduleExpression[] schedules = { ScheduleExpression.valueOf("hour=18-6 dayOfWeek=*"), ScheduleExpression.valueOf("hour=* dayOfWeek=0,6") }; assertEquals(new GregorianCalendar(2015, 9, 8, 18, 0), ScheduleExpression.ceil( new GregorianCalendar(201...
39063523_96
class PhysicalInventoryPresenter extends InventoryPresenter { public Observable<Object> doInventory(final String sign) { return Observable.create(subscriber -> { try { List<StockMovementItem> newestEachMovementItems = movementRepository.queryEachStockCardNewestMovement(); ...
String signature = "signature"; presenter.getInventoryViewModelList().addAll(getStockCardViewModels()); when(stockMovementRepositoryMock.queryEachStockCardNewestMovement()).thenReturn(getInversionDateOrTimeStockMovementItem()); TestSubscriber<Object> subscriber = new TestSubscriber<>(); ...
39075884_0
class GuavaCollectors { public static <T,R,C,V> Collector<T, ?, Table<R, C, V>> toTable( Function<? super T, ? extends R> rowMapper, Function<? super T, ? extends C> columnMapper, Function<? super T, ? extends V> valueMapper) { return toTable(rowMapper, columnMapper, val...
Table<String, String, Integer> table = Stream.of(10, 11).collect( GuavaCollectors.toTable(Object::toString, this::generateColumn, Function.identity())); Truth.assertThat(table).hasSize(2); Truth.assertThat(table).containsCell("10", "column", 10); Truth.assertThat(table).c...
39091281_17
class RxFirebaseDatabase { @NonNull @CheckReturnValue public static <T> Single<T> dataOf( @NonNull DatabaseReference ref, @NonNull Class<T> clazz) { return data(ref).compose(new SingleTransformerOfClazz<>(clazz)); } private RxFirebaseDatabase(); @NonNull @CheckReturnValue...
TestObserver<String> sub = TestObserver.create(); RxFirebaseDatabase.dataOf(mockDatabaseReference, String.class) .subscribe(sub); verifyDataReferenceAddListenerForSingleValueEvent(); callValueEventOnDataChange("Foo"); sub.assertComplete(); sub.assertNoE...
39092083_1119
class ShippingServiceFacadeImpl implements ShippingServiceFacade { @Override public PriceModel getCartShippingTotal(final ShoppingCart cart) { final String currency = cart.getCurrencyCode(); final BigDecimal deliveriesCount = new BigDecimal(cart.getShippingList().size()); final BigDec...
final ShopService shopService = context.mock(ShopService.class, "shopService"); final ShoppingCart cart = context.mock(ShoppingCart.class, "cart"); final ShoppingContext cartCtx = context.mock(ShoppingContext.class, "cartCtx"); final Total cartTotal = context.mock(Total.class, "cartTot...
39158944_4
class NavigationManagerImpl implements NavigationManager { @Override public NavigationPageItem getFooterNavigation() { Page footerNavRoot = siteRoot.getRelativePage(FOOTERNAV_RELATIVE_PATH); if (footerNavRoot != null) { return getFooterNavigationSpecific(footerNavRoot); } else { Page si...
// delete footer navigation in sample content Resource footerNavResource = context.resourceResolver().getResource("/content/wcm-io-samples/en/tools/navigation/footernav"); context.resourceResolver().delete(footerNavResource); NavigationPageItem rootItem = underTest.getFooterNavigation(); List<Navi...
39160554_85
class CSSInclude { public @Nullable String getInclude() { return include; } @PostConstruct private void activate(); private @NotNull String buildIncludeString(@NotNull List<String> libraryPaths); } class CSSIncludeTest { @Test void testInvalid() {
context.request().setAttribute("categories", CATEGORY_INVALID); CSSInclude underTest = AdaptTo.notNull(context.request(), CSSInclude.class); assertNull(underTest.getInclude()); } }
39161492_0
class GreeterService { public Greeting greet(String salutation, String name) { Assert.notNull(salutation, "salutation is required"); Assert.notNull(name, "name is required"); return rest.getForObject(URI_TEMPLATE, Greeting.class, salutation, name); } public GreeterService(RestTemplate restTemplate); @Mock...
given(this.rest.getForObject("//greeter-messages/greeting?salutation={salutation}&name={name}", Greeting.class, "Hello", "Bob")) .willReturn(new Greeting("Hello Bob")); assertThat(this.greeter.greet("Hello", "Bob")) .isNotNull() .isEqualToComparingFieldByField(new Greeting("Hello Bob")); } }
39175817_2
class DotEnvFileParser extends AbstractEnvVarsProvider { @NotNull @Override protected Map<String, String> getEnvVars(@NotNull Map<String, String> runConfigEnv, @NotNull String path) throws EnvFileErrorException { Map<String, String> result = new LinkedHashMap<>(); try { List<St...
Map<String, String> result = parser.getEnvVars(Collections.emptyMap(), getFile("inline-comments.env")); Assert.assertEquals("foo#bar", result.get("key1")); Assert.assertEquals("foo", result.get("key2")); Assert.assertEquals("foo #bar", result.get("key3")); Assert.assertEquals("fo...
39183519_16
class DrawerBackgroundView { public void disableBlurredLayers() { blurBackground.setVisibility(View.GONE); orginalBackground.setVisibility(View.GONE); } public DrawerBackgroundView(DrawerLayoutWithBlurredBackground drawerLayoutWithBlurredBackground); public synchronized void addBlurr...
//given drawerBackgroundView.blurBackground.setVisibility(View.VISIBLE); drawerBackgroundView.orginalBackground.setVisibility(View.VISIBLE); //when drawerBackgroundView.disableBlurredLayers(); //then assertThat(drawerBackgroundView.blurBackground.getVisibility()...
39197120_0
class ProvideAndRegisterDocumentSet extends XdsCommon { static OMText getBinaryNode(OMElement document) { Iterator<OMNode> childrenIterator = document.getChildren(); while (childrenIterator.hasNext()) { OMNode container = childrenIterator.next(); if (container instanceof OMText && StringUtils.isNotBlank((...
String message = IOUtils.toString(ProvideAndRegisterDocumentSetTest.class.getResourceAsStream("/data/submit_document.xml")); String documentString = IOUtils.toString(ProvideAndRegisterDocumentSetTest.class.getResourceAsStream("/data/referral_summary.xml")); //replace document and submission set uniqueId variables...
39198986_1
class AgentConfiguration { public String getArgs(String agentId) { return arguments.getProperty(agentId); } public AgentConfiguration(Set<String> agents, String args); private String extractPropertyFile(String remaining); private Properties loadProperties(String propFile); private St...
String p = createTestProps("port=8577","9999:other.json"); String[] data = new String[] { p,"port=8577","9999:other.json", p + ",jmx_exporter{{567:config.json}}","port=8577","567:config.json", "jmx_exporter{{567:config.json}}," + p,"port=8577","567:config....
39229420_6
class LongRangeUtils { public static LongRange getIntersection(final LongRange range1, final LongRange range2) { if (!range1.overlapsRange(range2)) { return null; } else { // The intersection is the [larger min, smaller max]. final long min1 = range1.getMinimumLong(); final long max1 ...
// [2, 7] intersection [0, 1] = null final LongRange intersection1 = LongRangeUtils.getIntersection(ORIGINAL, OUTSIDE); // The result should be null assertNull(intersection1); // [2, 7] intersection [2, 3] = [2, 3] final LongRange intersection2 = LongRangeUtils.getIntersection(ORIGINAL, SAME_ED...
39244945_2
class Main { public static void main(String[] args) { System.out.println("Hello Subproject2!"); } private final ByteArrayOutputStream outContent; } class MainTest { private final ByteArrayOutputStream outContent; @Test public void testMain() {
Main.main(new String[]{}); Assert.assertEquals("Hello Subproject2!", outContent.toString().trim()); } }
39255205_0
class InternalHeaderClickListener implements View.OnClickListener { @Override public void onClick(final View view) { informHeaderListeners(); } public InternalHeaderClickListener(final int columnIndex, final Set<TableHeaderClickListener> listeners); private void informHeaderListeners(); ...
// given listeners.add(firstListenerMock); listeners.add(secondListenerMock); // when cut.onClick(null); // then Mockito.verify(firstListenerMock, Mockito.times(1)).onHeaderClicked(TEST_ROW_INDEX); Mockito.verify(secondListenerMock, Mockito.times(1)).onH...
39269291_1
class PushReportMapper { public static PushReport mapFromImportSummaryToPushReport(ImportSummary importSummary, String importSummaryKey) { PushReport pushReport = new PushReport(); List<PushConflict> conflictList = new ArrayList<>(); if (importSummary.getConflicts() != null) { ...
//given ImportSummary importSummary = givenAImportSummary(IMPORT_SUMMARY_CONFLICT_RESPONSE); PushReport pushReport = PushReportMapper.mapFromImportSummaryToPushReport(importSummary, EVENT_UID_KEY); //then assertThat(pushReport.getEventUid().equals(importSummary.g...
39285768_16
class TableExtRetriever extends AbstractRetriever { void retrieveViewTableUsage() throws SQLException { final InformationSchemaViews informationSchemaViews = getRetrieverConnection().getInformationSchemaViews(); if (!informationSchemaViews.hasQuery(VIEW_TABLE_USAGE)) { LOGGER.log( Le...
int viewCount; final Collection<Table> tables = catalog.getTables(); viewCount = 0; assertThat(tables, hasSize(19)); for (final Table table : tables) { if (!(table instanceof View)) { continue; } viewCount = viewCount + 1; final View view = (View) table; assert...
39314095_2
class FileManager { public Path calculatePathForNode(SimpleNode node, List<SimpleNode> simpleNodes) { List<SimpleNode> parents = findParentsForNode(node, simpleNodes); String path = ""; for (SimpleNode p : parents) { String label = p.getLabel(); label = label.replace...
//arrange SimpleNode toFind = FileManagerCreators.createValidSimpleNode("asdf", "myfile.java", "0"); List<SimpleNode> arrayOfNodes = FileManagerCreators.createSimpleListOfNodes(toFind); //act Path path = sut.calculatePathForNode(toFind, arrayOfNodes); //assert a...
39342898_17
class Group { public void clearGroup(K groupKey) { Array<T> list = map.get(groupKey); if (list != null) { list.clear(); } } public void addToGroup(K groupKey, T object); public Array<T> getAll(); public Array<K> getGroupKeys(); public void remove(T object); public void ...
Group<String, String> group = new Group<String, String>(); group.addToGroup("a", "b"); group.addToGroup("a", "c"); group.addToGroup("b", "b"); group.clearGroup("a"); assertThat(group.getGroup("a")).isEmpty(); assertThat(group.getGroup("b")).containsExactly("b"); } }
39376231_5
class DateHelper { public static Date getTime(Date datetime) { Date time = new Date(0); time.setHours(datetime.getHours()); time.setMinutes(datetime.getMinutes()); time.setSeconds(datetime.getSeconds()); return time; } private DateHelper(); public static Strin...
Calendar cal = Calendar.getInstance(); cal.set(2015, Calendar.FEBRUARY, 23, 15, 0, 0); Date time = DateHelper.getTime(cal.getTime()); assertTrue(DateHelper.isOnlyTime(time)); } }
39392321_43
class ExprSimplifier { @SuppressWarnings("unchecked") public static <T extends Type> Expr<T> simplify(final Expr<T> expr, final Valuation valuation) { return (Expr<T>) TABLE.dispatch(expr, valuation); } private ExprSimplifier(); private static Expr<?> simplifyRef(final RefExpr<?> expr, final Valuation val); ...
assertEquals( Bv(new boolean[] {false, false, false, true}), simplify(BvExprs.SMod( Bv(new boolean[] {false, true, false, false}), Bv(new boolean[] {false, false, true, true}) )) ); assertEquals( Bv(new boolean[] {false, false, false, false}), simplify(BvExprs.SMod(e, e)) ); } }
39411151_22
class OutlineImpl implements Outline<T> { @Override public Collection<String> propertyNames() { return getProperties().keySet(); } public OutlineImpl(T members, boolean camelCased); private static String capitalize(String string); private static Method findMethod(Class<?> start, Stri...
assertThat(OutlineBuilder.DEFAULT.defaultCamelCased().build(TestBeanClass.class).propertyNames(), hasItems("readWriteProperty", "readOnlyProperty", "booleanProperty")); assertEquals(0, actualBeanMethodInvocations); } }
39412278_6
class Id { public static String build(String id, String... additionalIds) { return build(id, '-', additionalIds); } private Id(); public static String unique(); public static String unique(String id, String... additionalIds); static String build(String id, char separator, String... a...
// must result in the same ID String id1 = Id.build("foo_bar"); String id2 = Id.build("foo-bar"); String id3 = Id.build("foo bar"); assertEquals(id1, id2); assertEquals(id1, id3); assertEquals(id2, id3); // must result in the same ID String id4 = ...
39427174_36
class BCQuery { public void queryRefundStatusAsync(final BCReqParams.BCChannelTypes channel, final String refundNum, final BCCallback callback) { if (callback == null) { Log.w(TAG, "请初始化callback"); return; } BCCache.executorSer...
BeeCloud.setSandbox(true); query.queryRefundStatusAsync(BCReqParams.BCChannelTypes.WX, "refundnum", new BCCallback() { @Override public void done(BCResult result) { Assert.assertTrue(result instanceof BCRefu...
39477878_2
class Escaping { public static String escapeHtml(String input) { // Avoid building a new string in the majority of cases (nothing to escape) StringBuilder sb = null; loop: for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); String replacemen...
assertEquals("nothing to escape", Escaping.escapeHtml("nothing to escape")); assertEquals("&amp;", Escaping.escapeHtml("&")); assertEquals("&lt;", Escaping.escapeHtml("<")); assertEquals("&gt;", Escaping.escapeHtml(">")); assertEquals("&quot;", Escaping.escapeHtml("\"")); ...
39513536_41
class ConBox { public static Constraint complexMembers() { return new PathConstraint("Complex/component*"); } public static Constraint erToPE(); public static Constraint peToER(); public static Constraint peToControl(); public static Constraint peToControlledConv(); public static Constraint peToControlledIn...
Pattern p = new Pattern(Complex.class, "Complex"); p.add(ConBox.complexMembers(), "Complex", "member"); Blacklist blacklist = new Blacklist(); blacklist.addEntry("http://pid.nci.nih.gov/biopaxpid_679", 0, null); // GDP ER ID p.add(new NonUbique(blacklist), "member"); // not GDP List<Match> list = Searcher....
39525650_3
class ApplicationPath { public static String get(Bundle bundle) { return bundle.getHeaders().get(HEADER_APPLICATON_PATH); } private ApplicationPath(); public static String get(BundleContext bundleContext); public static String get(ComponentContext componentContext); private static final String TEST...
assertEquals(TEST_PATH, ApplicationPath.get(componentContext)); } }
39526634_1
class RenderUtil { public static EBarElementFilled[] calculateBarFill(final int numberOfParts, final float percentFilled) { if (numberOfParts < 1) { return null; } final EBarElementFilled[] fills = new EBarElementFilled[numberOfParts]; // how much should be in a part for it to be considered full? final f...
final int length = 2; final EBarElementFilled[] calculateBarFill0Percent = RenderUtil.calculateBarFill(length, RenderUtil.PERCENT_0); assertNotNull("excpected to get an array of float", calculateBarFill0Percent); assertEquals("double bar filled - checking size of array", length, calculateBarFill0Percent.le...
39570183_1
class JvmOptionsUtils { public static String extractDirectory(String jvmOptions) { if (jvmOptions == null || jvmOptions.trim().length() == 0) { return null; } if (jvmOptions.indexOf(CLOUDUNIT_SHARED_DIR) == -1) { return null; } // we get cloudunit.shared=... String subStringFromStar...
String dir = JvmOptionsUtils.extractDirectory("-Dkey=value -Dcloudunit.shared=tartapion"); Assert.assertEquals("tartapion", dir); dir = JvmOptionsUtils.extractDirectory("-Dkey=value -Dcloudunit.shared=tartapion -Dkey2=value2"); Assert.assertEquals("tartapion", dir); } }
39583456_2
class TravelAgent { String getBackupGuide() { return "None available! Your backup guide is: Cookie"; } public TravelAgent(RestTemplate rest); @HystrixCommand(fallbackMethod = "getBackupGuide") public String getGuide(); @Mock private RestTemplate restTemplate; private TravelAgent travelAgent; } class Tra...
String guide = this.travelAgent.getBackupGuide(); assertThat(guide).isEqualTo("None available! Your backup guide is: Cookie"); } }
39676740_41
class SvgConverter { public List<SvgPath> parseQRCodeMatrix(QRCode qrcode) { Objects.requireNonNull(qrcode); List<SvgPath> paths = Lists.newArrayList(); //We read line by line for (int y = 0; y < qrcode.getMatrix().getHeight(); y++) { //We read the point from the left ...
QRCode qrCode = new QRCode(); qrCode.setMatrix(new ByteMatrix(4, 2)); assertThat(svgConverter.parseQRCodeMatrix(qrCode)).isEmpty(); } }
39683376_0
class UserService { @Scheduled(cron = "0 0 0 * * ?") public void removeOldPersistentTokens() { LocalDate now = new LocalDate(); persistentTokenRepository.findByTokenDateBefore(now.minusMonths(1)).stream().forEach(token ->{ log.debug("Deleting token {}", token.getSeries()); ...
User admin = userRepository.findOneByLogin("admin").get(); int existingCount = persistentTokenRepository.findByUser(admin).size(); generateUserToken(admin, "1111-1111", new LocalDate()); LocalDate now = new LocalDate(); generateUserToken(admin, "2222-2222", now.minusDays(32)); ...
39694047_5
class GithubClient { @Cacheable("github.commits") public List<Commit> getRecentCommits(String organization, String project) { ResponseEntity<Commit[]> response = doGetRecentCommit(organization, project); return Arrays.asList(response.getBody()); } public GithubClient(CounterService counterService, RestTempla...
expectJson("https://api.github.com/repos/spring-projects/spring-boot/commits", "github/no-commit.json"); List<Commit> latestCommit = this.githubClient.getRecentCommits("spring-projects", "spring-boot"); assertThat(latestCommit).hasSize(0); verify(this.counterService, times(1)).increment("cfp.github.requests...
39705783_1
class ProblemBuilder { public ThrowableProblem build() { return new DefaultProblem(type, title, status, detail, instance, cause, new LinkedHashMap<>(parameters)); } ProblemBuilder(); public ProblemBuilder withType(@Nullable final URI type); public ProblemBuilder withTitle(@Nullable fina...
final Problem problem = Problem.builder().build(); assertThat(problem, hasFeature("type", Problem::getType, hasToString("about:blank"))); assertThat(problem, hasFeature("title", Problem::getTitle, is(nullValue()))); assertThat(problem, hasFeature("status", Problem::getStatus, is(nullVal...
39726618_3
class ExportPDF { public static final void save(File file, Component c) { save(file, c, c.getWidth(), c.getHeight()); } public static final File selectFile(); public static final File selectFile(Component c); public static final void save(File file, Component c, int width, int height); } class TestExportPDF ...
JButton b = new JButton("test"); b.setSize(100, 100); File file = File.createTempFile("itext-text", ".pdf"); ExportPDF.save(file, b); assertTrue(file.exists()); assertTrue(file.length() > 0); file.delete(); assertFalse(file.exists()); } }
39727052_0
class StanfordTagger extends AbstractTagger { public ListMatrix<ListMatrix<MapMatrix<String, Object>>> tag(String text) throws Exception { ListMatrix<ListMatrix<MapMatrix<String, Object>>> sentenceList = new DefaultListMatrix<ListMatrix<MapMatrix<String, Object>>>(); Annotation document = new Anno...
if (tagger == null) { return; } List<ListMatrix<MapMatrix<String, Object>>> list = tagger.tag(s1); System.out.println(list.get(0).get(0)); assertEquals(2, list.size()); assertEquals(1, list.get(0).getColumnCount()); assertEquals(11, list.get(0).getRowCount()); assertEquals(1, list.get(1).get...
39764417_15
class PeerManager { public @Nullable Connection get(@NotNull Channel channel) { Peer peer = peers.get(channel.remoteAddress()); return peer == null ? null : peer.getConnection(channel.id()); } public PeerManager(Bootstrap clientBootstrap); public Connection findOrNew(@NotNull SocketA...
InetAddress host = InetAddress.getByName(null); // create server final TChannel server = new TChannel.Builder("server") .setServerHost(host) .build(); final SubChannel subServer = server.makeSubChannel("server") .register("echo", new EchoHandler()); ...
39770930_15
class JsonWireUtils { public static String getFullSessionId(String uri) { String tail = uri.substring(WD_HUB_SESSION.length()); int end = tail.indexOf('/'); if (end < 0) { return tail; } return tail.substring(0, end); } private JsonWireUtils(); pub...
String routeHash = md5Hex("hubAddress".getBytes(StandardCharsets.UTF_8)); String sessionId = randomUUID().toString(); String expected = routeHash + sessionId; assertThat(getFullSessionId(sessionRequest(routeHash, sessionId, "")), is(equalTo(expected))); assertThat(getFullSessionI...
39772980_4
class ValidationResult { public static IValidationResult ok() { return OK; } private ValidationResult(); public static IValidationResult create(); public static IValidationResult create(final IValidationMessage message); public static IValidationResult info(final String text); pu...
final IValidationResult ok = ValidationResult.ok(); Assert.assertEquals(ok.getWorstFirst().getType(), MessageType.OK); } }
39793957_7
class ProgressFormatter { protected static CharSequence format(long durationInSecondsSinceLoopStart, int count, int total, long durationLoopingStart, long countLoopingStart) { StringBuilder result = new StringBuilder(); result.append(count).append("/").append(total); if ((count > countLoo...
long t3_15 = 3 * 60 + 15; int durationLoopingStart = 0; int countLoopingStart = 0; int first = 1; int last = 60; Assert.assertEquals("a", "1/60 00:03:15/03:15:00", ProgressFormatter.format(t3_15, first + countLoopingStart, last + countLoopingStart, du...
39875602_1
class ChaCha20 { protected static void quarterRound(int[] x, int a, int b, int c, int d) { x[a] += x[b]; x[d] = ROTATE(x[d] ^ x[a], 16); x[c] += x[d]; x[b] = ROTATE(x[b] ^ x[c], 12); x[a] += x[b]; x[d] = ROTATE(x[d] ^ x[a], 8); x[c] += x[d]; x[b] = RO...
int buf[] = { 0x879531e0, 0xc5ecf37d, 0x516461b1, 0xc9a62f8a, 0x44c20ef3, 0x3390af7f, 0xd9fc690b, 0x2a5f714c, 0x53372767, 0xb00a5631, 0x974c541a, 0x359e9963, 0x5c971061, 0x3d631689, 0x2098d9d6, 0x91dbd320 }; int expected[] = { ...
39894970_0
class SplunkLogOutputConnector extends AbstractOutputConnector implements OutputConnector { @Override public OutputInteraction createOutputInteraction() throws ConnectorException { return new SplunkLogOutputInteraction(); } } class SplunkLogOutputConnectorTest { @Test public void testCreateOutputInteract...
// fail("Not yet implemented"); OutputInteraction oi = null; try { oi = new SplunkLogOutputConnector().createOutputInteraction(); } catch (ConnectorException e) { e.printStackTrace(); } if (oi == null) { fail("unable to get outputinteraction"); } else { Properties props = new Properties(); p...
39905749_2
class LazyExpirableCache implements Cache { @Override public Observable<Boolean> remove(String key) { return underlyingCache.remove(key); } private LazyExpirableCache(RxCache underlyingCache, long expireMillis, Observable<Long> timeObservable); public static LazyExpirableCache fromCache(...
RxCache underlyingCache = mock(RxCache.class); LazyExpirableCache lazyExpirableCache = LazyExpirableCache.fromCache(underlyingCache, 10, TimeUnit.SECONDS, simpleTimeProvider); String cacheKey = "cache_key"; when(underlyingCache.remove(eq(cacheKey))).thenReturn(Observab...
39922362_104
class RunningStats { public double stddev() { return Math.sqrt(variance()); } public void push(double x); public double mean(); public double variance(); public double skewness(); public double kurtosis(); } class RunningStatsTest { @Test public void testVarianceWithNoEntry() {
RunningStats runningStats = new RunningStats(); Assert.assertEquals(0.0d, runningStats.stddev(), 0.001); } }
39924219_1
class MetricConverter { public static double getSRM(double inEBC) { return (int) Math.round(inEBC / SRM); } public static double getEBC(double inSRM); public static double getEBC(String inSRM); public static String getPlato(double gravity); public static boolean isCountryMetric(String ...
assert(1 == MetricConverter.getSRM(2)); assert(2 == MetricConverter.getSRM(4)); assert(10 == MetricConverter.getSRM(20)); assert(40 == MetricConverter.getSRM(79)); assert(-1 == MetricConverter.getSRM(-2)); assert(0 == MetricConverter.getSRM(0)); } }
39970786_0
class TodoManagerImpl { public void add(final Callback<Boolean> callback, final Todo todo) { todoMap.put(todo.getId(), todo); callback.resolve(true); } public TodoManagerImpl(); public void remove(final Callback<Boolean> callback, final String id); public void list(final Callback...
/* A list of promises for things we want to do all at once. */ final List<Promise<Boolean>> promises = new ArrayList<>(3); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean success = new AtomicBoolean(); /** Add a todoItem to the client add method */ ...
39997974_2
class ArticleService { public Mono<String> fetchArticle(String articleName) { return cache.lookup(articleName); } @Autowired public ArticleService(WikiService wikiService, CountService countService, RatingService ratingService, @Value("${article.cache.size}") int cacheSi...
StepVerifier.create(articleService.fetchArticle(EIGENWERT_ARTICLE.getName())) .expectNext(EIGENWERT_ARTICLE.getContent()) .verifyComplete(); } }
40049579_18
class GarageServiceImpl implements GarageService { @Override public Result addCar(Car car) { Preconditions.checkNotNull(car, "car should not be null"); Result result = FluentValidator.checkAll().failOver() .on(car.getManufacturer(), new CarManufacturerValidator()) ...
Result result = garageService.addCar(new Car("BMW", "XXXXX1234", 0)); System.out.println(result); assertThat(result.isSuccess(), is(false)); assertThat(result.getErrorNumber(), is(2)); assertThat(result.getErrors().get(0), is(String.format(CarError.SEATCOUNT_ERROR.msg(), 0))); ...
40055799_111
class SimpleHashService extends HashService { @Override public String hash(String plaintext) { return plaintext; } SimpleHashService(boolean serverSideHashEnabled, boolean allowCommonMistakes); @Override boolean isMatchExact(String plaintext, String hashed); private final HashService hashService; ...
String plaintext = "Password"; String hashed = hashService.hash(plaintext); assertTrue(hashService.isMatch(plaintext, hashed)); String capsLock = "pASSWORD"; assertFalse(hashService.isMatch(capsLock, hashed)); String extraFirstCharacter = "*Password"; assertFalse(hashService.isMatch(extra...
40111808_37
class TypedMap implements Map<String, Object> { public Set<String> keySet() { return inner.keySet(); } public TypedMap(final RecordType type); public TypedMap(final RecordType type, final Map<? extends String, ? extends Object> map); public RecordType getType(); public Type getFieldType(final String fieldN...
Map<String, Object> values = new HashMap<String, Object>(); values.put("intValue", 1); values.put("booleanValue", true); String[] stringArray = new String[] { "a", "b", "c" }; values.put("stringArray", stringArray); TypedMap map = new TypedMap(recordType, values); Set<String> keySet = map.keySet(); ass...
40115035_16
class EventMapper { public Event eventFromContextElement(ContextElement contextElement) throws EventProcessingException, TypeNotFoundException { String eventId = contextElement.getEntityId().getId(); String eventType = contextElement.getEntityId().getType(); Event event = new Event(eventTy...
ContextElement ce = new ContextElement(); ce.setEntityId(new EntityId("S1", "TempSensor", false)); List<ContextAttribute> attributes = new LinkedList<>(); attributes.add(new ContextAttribute("1", "string", "hello")); attributes.add(new ContextAttribute("1_string", null, "hello")...
40167498_37
class IpUtils { public static Integer ip2int(String ipAddress) { Inet4Address a; try { a = (Inet4Address) InetAddress.getByName(ipAddress); } catch (UnknownHostException e) { _log.error(ExceptionUtils.errorInfo(e)); return null; } byte[] b...
Integer ip2int = ip2int("10.1.1.0"); Assert.notNull(ip2int); int ip = ip2int; assertEquals(167837952, ip); assertEquals(0x0A010100, ip); } }
40182023_27
class TelegramBot { public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); } public TelegramBot(String botToken); TelegramBot(Builder builder); public void execute(T request, Callback<T, R> callback); public Str...
Message message = bot.execute(new SendSticker(chatId, stickerFileAnim)).message(); MessageTest.checkMessage(message); StickerTest.check(message.sticker(), false, true); assertTrue(message.sticker().isAnimated()); message = bot.execute(new SendSticker(chatId, stickerId)).message(...
40213809_69
class BearingWidget extends QuestionWidget implements BinaryDataReceiver { @Override public IAnswerData getAnswer() { String answerText = binding.answerText.getText().toString(); return answerText.isEmpty() ? null : new StringData(answerText); } public BearingWidget(Context context, Q...
assertThat(createWidget(promptWithAnswer(null)).getAnswer(), nullValue()); } }
40235586_15
class DefaultNetworkMetrics implements NetworkMetrics { @Override public Optional<NetworkInterface> networkInterfaceById(String id) { return hal.getNetworkIFs().stream().filter(n -> n.getName().equalsIgnoreCase(id)).map( mapToNetworkInterface()).findAny(); } protected DefaultN...
when(networkInterface1.isLoopback()).thenThrow(new SocketException("Shrug")); Optional<NetworkInterface> en1 = provider.networkInterfaceById("en0"); assertTrue(en1.isPresent()); assertFalse(en1.get().isLoopback()); } }
40266095_32
class PageRankRanking extends JCasAnnotator_ImplBase { @Override public void process(JCas jcas) throws AnalysisEngineProcessException { getContext().getLogger().log(Level.CONFIG, "Entering " + this.getClass().getSimpleName()); pageRank.initializeFromAnnotationPairIterator( JCas...
Map<String,Double> expectedResults = new HashMap<String,Double>(); expectedResults.put("sentence", 1.6487752080270504); expectedResults.put("second", 0.8508165279819666); expectedResults.put("long", 0.5004082639909833); expectedResults.put("more", 0.5004082639909833); ex...
40317158_3
class MZTabUtils { public static SplitList<String> parseGOTermList(String target) { SplitList<String> list = parseStringList(COMMA, target); SplitList<String> goList = new SplitList<String>(COMMA); for (String item : list) { item = parseString(item); if (item.starts...
SplitList<String> goList; StringBuilder sb = new StringBuilder(); goList = parseGOTermList(sb.toString()); assertTrue(goList.size() == 0); sb.append("GO:0005515"); goList = parseGOTermList(sb.toString()); assertTrue(goList.size() == 1); sb.append(",GO:0...
40321883_9
class MainTypesUtil { public List<String> getMainTypesByTumorTypes(Set<TumorType> tumorTypes) { Set<String> mainTypes = new HashSet<>(); // skip the root node, "TISSUE". Just add it's children for (TumorType tumorType : tumorTypes) { if (tumorType.getMainType() != null && tumorT...
List<String> returnedMainTypeList = mainTypesUtil.getMainTypesByTumorTypes(new HashSet<>(expectedTumorTypeMap.values())); StringBuilder failureReport = new StringBuilder(); int failureCount = 0; if (returnedMainTypeList.size() != expectedMainTypeList.size()) { failureCount++...
40396716_0
class T411V2Provider extends DownloadFinder implements EpisodeFinder, MusicAlbumFinder, TVShowSeasonProvider, MovieProvider, BookFinder, MagazineProvider { @Override public List<SearchResult> findDownloadsForMagazine(String issueSearchString) throws Exception { List<SearchResult> results = extract(issueSearchStrin...
fail("Not yet implemented"); } }
40404190_2
class RestartableSet implements Launcher { @Override public void launch(int id) { restartable(id).launch(); } public RestartableSet(ValueMap.Builder out); public RestartableSet(ValueMap in, ValueMap.Builder out); @Override public Observable<Notification<T>> channel(int id, DeliveryM...
ValueMap.Builder builder = ValueMap.builder(); RestartableSet set1 = new RestartableSet(builder); Subscription subscription = subscribeRestartable(method, subscriber1, scheduler, set1); launch(set1); subscription.unsubscribe(); ValueMap state = builder.build(); ...
40405884_15
class PersistedHistogram { public Path saveToFile(final Path outputDirectory, final String namePrefix) throws IOException { requireNonNull(outputDirectory); final String prefix = namePrefix.trim(); if (prefix.isEmpty()) { throw new IllegalArgumentException("Name pre...
assertThrows(IllegalArgumentException.class, () -> persistedHistogram.saveToFile(tempDir, " \t \n ")); } }
40442532_2
class AbstractPermissionListener implements PermissionListener { @Override public void onPermissionDenied(PermissionDeniedResponse response) { if (!contextProvider.isActivityContextAvailable()) { PermissionsUIViews.showPermissionToast(contextProvider.getApplicationContext(), getPermissionDeniedFe...
DummyPermissionListenerImplementation dummyPermissionListenerImplementation = new DummyPermissionListenerImplementation(contextProvider, stubString); setUpActivityContextInitializedScenario(); dummyPermissionListenerImplementation.onPermissionDenied( new Permiss...
40457462_109
class GunEnemy extends Enemy<TimestampedFiringAngle> { @Override public void initRound() { super.initRound(); lastNonZeroVelocity = 0; previousVelocity = 0; timeSinceDirectionChange = 0; timeSinceVelocityChange = 0; hitLocations.clear(); } public GunEnemy(String botName, double distan...
GunEnemy gunData = newGunEnemy(); gunData.energy = 10; gunData.alive = false; gunData.setRobotState(RobotState.newBuilder() .setLocation(newLocation()) .setTime(1) .build()); gunData.initRound(); assertEquals(100, gunData.energy, 0.01); assertTrue(gunData.alive); ...
40510168_72
class PollUtils { public static boolean poll(BooleanSupplier cond, long periodMs, long timeoutMs) { return poll((n) -> cond.getAsBoolean(), periodMs, timeoutMs, null); } public static boolean poll(InterruptablePredicate<T> cond, long periodMs, long timeoutMs, T arg); public static Optional<T> poll(Interru...
long now1 = System.currentTimeMillis(); boolean returnValue = PollUtils.poll((c) -> System.currentTimeMillis() >= now1 + c, 100, 600, 400); Assert.assertTrue(returnValue); long now2 = System.currentTimeMillis(); Assert.assertTrue(now2 - now1 >= 350); } }
40527870_200
class DefaultBundleFilter extends MotechBundleFilter { @Override public boolean passesCriteria(Bundle bundle) { return bundle != null && !isPlatformBundle(bundle) && importsExportsMotechPackage(bundle); } private boolean importsExportsMotechPackage(Bundle bundle); private boolean isPlatfor...
when(headers.get(ExtendedBundleInformation.EXPORT_PACKAGE)).thenReturn(MOTECH_IMPORT_EXPORT); when(bundle.getSymbolicName()).thenReturn("org.apache.felix.framework"); assertFalse(bundleFilter.passesCriteria(bundle)); } }
40536165_6
class Validation extends AbsModule<Validation.ExtAsync, Validation.ExtRxJava> { public PromotionResponse validate(ValidationContext context) throws IOException { Map<String, String> queryParams = createQueryParamsForContext(context); return api.validatePromotion(queryParams).execute().body(); }...
List<OrderItem> orderItems = new ArrayList<>(); orderItems.add(new OrderItem("0", "sku_0", 1, 10)); validation.validate("SAMPLE_CODE", ValidationContext.create(100, orderItems)); Map<String, String> expectedQueryParams = new LinkedHashMap<>(); expectedQueryParams.put("amount", "...
40538806_4
class MeasurementUnit { public static MeasurementUnit getFromLocale(Locale locale) { String countryCode = locale.getCountry(); ArrayList<String> countriesUsingImperial = new ArrayList<>(Arrays.asList(Locale.US.getCountry())); if (countriesUsingImperial.contains(countryCode...
assertEquals(MeasurementUnit.getFromLocale(Locale.US), MeasurementUnit.Imperial); assertEquals(MeasurementUnit.getFromLocale(Locale.JAPAN), MeasurementUnit.Metric); assertEquals(MeasurementUnit.getFromLocale(Locale.FRANCE), MeasurementUnit.Metric); } }
40541952_2
class ScriptTools { public static boolean testScript (byte[] script, byte[] template, byte[]... parameters) { Script s = new Script(script); List<ScriptChunk> chunks = s.getChunks(); int parameter = 0; for (int i = 0; i < chunks.size(); i++) { boolean correct = false;...
//Changed one byte of the original sequence byte[] script = Tools.hexStringToByteArray ("A905AABBCCDDEE87630C049284008271007438924817570408796688527C1D0987093827AA980083A9FF89113947892811990283990428406678096552AE"); byte[] p1 = Tools.hexStringToByteArray("aa bb cc dd ee"); ...
40557971_13
class MainPresenter implements Callback<SearchResult>, BarcodeListener { @Subscribe @SuppressWarnings("WeakerAccess") public void productDetailsFragmentDismissed(@SuppressWarnings("UnusedParameters") ProductDetailsFragmentDismissedEvent event) { viewBinder.dismissProductDetailsView(); } ...
presenter.productDetailsFragmentDismissed(null); verify(viewBinder).dismissProductDetailsView(); } }
40563017_0
class Serialization { private Yaml yaml() { return this.cachedYaml.get(); } private Serialization(@Nullable Void v); public CommentsManager getCommentsManager(); private Yaml createYaml(); private Gson gson(); public void addTrueValues(String... strings); public void addF...
Serialization global = prepareSerialization(); EntityStorage entityStorage = prepareObject(); System.out.println("[YAML] Deserializing javabean: \n"); { String toYaml = global.toYaml(entityStorage.beanObject); System.out.println(toYaml); Assert.asser...
40563645_11
class ItemIdComposer { public static boolean isExpandableGroup(long composedId) { return (composedId != RecyclerView.NO_ID) && ((composedId & BIT_MASK_CHILD_ID) == BIT_MASK_CHILD_ID); } private ItemIdComposer(); public static long composeExpandableChildId(@IntRange(from = MIN_GROUP_ID, to = ...
// zero assertThat(ItemIdComposer.isExpandableGroup(0L), is(false)); // NO_ID assertThat(ItemIdComposer.isExpandableGroup(RecyclerView.NO_ID), is(false)); // not group - 1 assertThat(ItemIdComposer.isExpandableGroup(ItemIdComposer.BIT_MASK_CHILD_ID >> 1), is(false)); ...
40605386_2
class MDNSDiscover { static Result decode(byte[] packet, int packetLength) throws IOException { Result result = new Result(); decode(packet, packetLength, result); return result; } private static byte[] discoverPacket(String serviceType); static byte[] queryPacket(String servic...
byte[] packet = createReplyPacket(); Result r = decode(packet, packet.length); // check A record assertEquals("192.168.1.100", r.a.ipaddr); assertEquals("dev0123456789.local", r.a.fqdn); assertEquals(10, r.a.ttl); // check SRV record assertEquals(0, r.sr...
40616171_1
class Waiter { public boolean wake() { synchronized (lock) { if (!isWaiting) { return false; } else { woken = true; lock.notify(); return true; } } } public Waiter(Duration duration); p...
Waiter waiter = new Waiter(Duration.ofMillis(1000)); Future<Long> waitTime = executor.submit(new WaitForWaiter(waiter)); sleep(20); // give executor time to get to wait(..) waiter.wake(); assertTrue(waitTime.get() < 100L, "Waited: " + waitTime.get()); Future<Long> waitT...
40628209_514
class ParseFacebookUtils { public static Task<Void> unlinkInBackground(ParseUser user) { checkInitialization(); return user.unlinkFromInBackground(AUTH_TYPE); } private ParseFacebookUtils(); public static boolean isLinked(ParseUser user); public static void initialize(Context con...
ParseUser user = mock(ParseUser.class); when(user.unlinkFromInBackground(anyString())).thenReturn(Task.<Void>forResult(null)); ParseFacebookUtils.isInitialized = true; ParseFacebookUtils.unlinkInBackground(user); verify(user).unlinkFromInBackground("facebook"); } }
40667226_1
class LoginActivity extends BaseActivity { public boolean check() { if (name.getText().toString().equals("")) { nameLayout.setError(getString(R.string.empty_username)); return false; } if (pwd.getText().toString().equals("")) { passwordLayout.setError(get...
emailEditText.setText("username"); activity.findViewById(R.id.login_submit).performClick(); assert(!activity.check()); } }
40695309_7
class Path implements Iterable<Path> { public boolean isLast() { if(isRoot()) return true; return (pathElements.length <= 1); } public Path(); public Path(String path); private Path(String[] pathElements); public String[] getPathElements(); public String getFirstEle...
Path instance = new Path("/www"); boolean result = instance.isLast(); assertEquals(true, result); } }
40712527_0
class CompanyService { public String add(Company companyDto) { Company company = new Company(); company.setName(companyDto.getName()); company.setAddress(companyDto.getAddress()); company.setHeadcount(companyDto.getHeadcount()); company.setStatus(Status.OPEN); Company result = companyRepository.save...
Company companyDto = new Company(); companyDto.setName("plantlink"); companyDto.setAddress("westlake"); companyDto.setHeadcount(2); String id = companyService.add(companyDto); Assert.assertNotNull(id); } }
40714460_5
class ServiceMethodInvoker { public Flux<ServiceMessage> invokeBidirectional(Publisher<ServiceMessage> publisher) { return Flux.from(publisher) .switchOnFirst( (first, messages) -> Mono.deferWithContext(context -> authenticate(first.get(), context)) .flatMa...
final String methodName = "throwException3"; final Class<? extends StubService> serviceClass = stubService.getClass(); final Method method = serviceClass.getMethod(methodName, Flux.class); final MethodInfo methodInfo = new MethodInfo( serviceClass.getName(), methodName, ...
40737618_12
class PrizePresenter extends RxPresenter<PrizeView, ArrayList<Prize> > implements Comparator<Prize> { @Override void onNext(ArrayList<Prize> prizes) { Collections.sort(prizes, this); if (isViewAttached()) { getView().showPrizes(prizes); } } public void updatePrizes(); ...
ArrayList<Prize> prizes = new ArrayList<>(); prizes.add(new Prize()); presenter.onNext(prizes); verify(view).showPrizes(prizes); } }
40753051_36
class Transformers { public byte[] transformAsBytes(Source input, Format format) throws TransformerException { return transformAsBytes(input, format, Collections.<String, Object>emptyMap()); } public Source transform(Source input, Format format); public Source transform(Source input, Format fo...
InputStream goldenIS = TransformersTest.class.getResourceAsStream("alephXServerDetailResponseAsMarcXml.xml"); assertNotNull(goldenIS); InputStream xmlIS = TransformersTest.class.getResourceAsStream("alephXServerDetailResponseAsOaiMarc.xml"); assertNotNull(xmlIS); StreamSource str...
40762184_0
class ExceptionUtils { public static void insertMessage(Throwable onObject, String msg) { try { Field field = Throwable.class.getDeclaredField("detailMessage"); //Method("initCause", new Class[]{Throwable.class}); field.setAccessible(true); if (onObject.getMessage() != n...
"and the original message must not be deleted" } ) @Test public void testInsertMessage() throws Exception { final RuntimeException exception = new RuntimeException(MESSAGE); insertMessage(exception, NEW_MESSAGE); assertTrue(exception.getMessage().con...
40763113_5
class MergingException extends Exception { public static void throwIfNonEmpty(Collection<Message> messages) throws MergingException { if (!messages.isEmpty()) { throw new MergingException(null, Iterables.toArray(messages, Message.class)); } } protected MergingException(@Nullab...
MergingException.throwIfNonEmpty(ImmutableList.<Message>of()); try { MergingException.throwIfNonEmpty(ImmutableList.<Message>of( new Message(Message.Kind.ERROR, "Message", SourceFilePosition.UNKNOWN))); fail(); } catch (MergingException e) { ...
40779062_1
class ClassMatcher { static boolean matchesAsInnerClass(String classFqn, List<String> fqns) { for (String fqn : fqns) { if (classFqn.startsWith(fqn + "$")) { return true; } } return false; } private ClassMatcher(); static boolean anyMatchesAsClassOrPackage(List<String> classFqns, List<String> f...
assertTrue(ClassMatcher.matchesAsInnerClass("hu.awm.MyClass$InnerClass", Collections.singletonList("hu.awm.MyClass"))); assertTrue(ClassMatcher.matchesAsInnerClass("hu.awm.MyClass$InnerClass$InnerInnerClass", Collections.singletonList("hu.awm.MyClass"))); assertTrue(ClassMatcher.matchesAsInnerClass("hu.awm.MyClas...
40780878_15
class JSONRulesDefinition implements RulesDefinition { @Override public void define(Context context) { NewRepository repository = context .createRepository(JSONLanguage.KEY, JSONLanguage.KEY) .setName(CheckList.REPOSITORY_NAME); new AnnotationBasedRulesDefinition(repository, JSONLanguage.KEY)....
JSONRulesDefinition rulesDefinition = new JSONRulesDefinition(); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); RulesDefinition.Repository repository = context.repository("json"); assertThat(repository.name()).isEqualTo("SonarQube"); assertThat...
40961773_3
class PatternsGenerator implements ResourceGenerator<Context> { @NotNull @Override public String create(@NotNull final Context context) { final Document doc = myDocumentManager.createDocument(); final Element patternsElement = doc.createElement(PATTERNS_ELEMENT); String thresholdsStr = myParametersSe...
// Given String expectedContent = "<Patterns>" + "<Pattern>Method1</Pattern>" + "<Pattern>Method2</Pattern>" + "</Patterns>"; final CommandLineSetup setup = new CommandLineSetup("tool", Collections.<CommandLineArgument>e...
40970642_3
class DrawingService { public static Draw drawNumbers(LocalDate date) { Random random = new Random(date.toEpochDay()); Draw.DrawBuilder builder = Draw.builder().withDate(date); do { Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1); if (number < MIN_NUMBER_IN_D...
LocalDate date = LocalDate.parse("2012-01-01"); LocalDate maxDate = LocalDate.parse("2013-01-01"); while (true) { Draw draw = DrawingService.drawNumbers(date); if (draw.getNumbers().contains(49)) { break; } date = date.plusDays(1); ...
40976537_0
class CachingService { public boolean exists(String name) { return cache.containsValue(name); } public CachingService(RemoteCache<String, String> cache); public CachingService(RemoteCacheManager cacheManager); public void storeName(String id, String name); @RegisterExtension static Infi...
// Grab the cache created in the context of this test RemoteCache<String, String> cache = infinispanServerExtension.hotrod().create(); // Put some data in the cache cache.put("123", "Mickey"); cache.put("456", "Donald"); // Create the CachingService, using the cache created in the ...
40977450_7
class ClubSquadBuilder { public ClubSquad build() { squad.add(goalkeepers.remove(0)); addToSquad(ClubSquad.TOTAL_DEFENDERS, asList(defenders, midfielders, attackers, goalkeepers)); addToSquad(ClubSquad.TOTAL_MIDFIELDERS, asList(midfielders, attackers, defenders, goalkeepers)); addToSquad(ClubSquad.T...
Player[] players = new Player[] { buildPlayer("LB"), buildPlayer("CB"), buildPlayer("CB"), buildPlayer("CDM"), buildPlayer("RW"), buildPlayer("LM"), buildPlayer("CM"), buildPlayer("GK"), buildPlayer("ST"), buildPlayer("CAM"), buildPlayer("CDM") }; ClubSquadBuilder builder = new ClubSquadBuilder(...
40998919_6
class AdviceTraits { public static Optional<MediaType> getProblemMediaType(final List<MediaType> mediaTypes) { for (final MediaType mediaType : mediaTypes) { if (mediaType.includes(APPLICATION_JSON) || mediaType.includes(PROBLEM)) { return Optional.of(PROBLEM); } els...
List<MediaType> mediaTypes = Arrays.asList(MediaType.TEXT_PLAIN, MediaTypes.PROBLEM, MediaTypes.X_PROBLEM); Optional<MediaType> mediaType = AdviceTraits.getProblemMediaType(mediaTypes); assertTrue(mediaType.isPresent()); assertThat(mediaType.get(), is(MediaTypes.PROBLEM)); } }
41012501_0
class PDFExtractor { @SneakyThrows public PDFDoc extractFromInputStream(InputStream is) { return extractResultFromInputStream(is).document; } public PDFExtractor(Options opts); public PDFExtractor(); private static List<String> guessKeywordList(String listStr); private static List<String> guessAu...
String pdfPath = "/coordinate_calibrator.pdf"; InputStream pdfInputStream = getClass().getResourceAsStream(pdfPath); PDFExtractor.Options opts = PDFExtractor.Options.builder().useHeuristicTitle(true).build(); PDFDoc doc = new PDFExtractor(opts).extractFromInputStream(pdfInputStream); for(PDFPag...
41053417_6
class MemberService { public void syncMembers() { log.info("> Sync members"); syncLocalMembers(); syncRemoteMembers(); log.info("< Synced members"); } private void syncLocalMembers(); private void syncRemoteMembers(); private void attachMemberToGroups(Member member...
//given //TestAppConfig //when memberService.syncMembers(); //then Optional<MembershipEntryEntity> entry = membershipRepository.findFirstByMemberIdAndGroupIdOrderByDateDesc("member1", "group1"); assertThat(entry).isPresent(); assertThat(entry.get().getEv...
41057956_15
class IconTabLayout extends TabLayout { @Override public void setTabsFromPagerAdapter(@NonNull PagerAdapter adapter) { super.setTabsFromPagerAdapter( pageTitlesVisible ? adapter : TitleNullifyingPagerAdapter.from(adapter)); if (isLayoutPagerAdapterInstance(adapter)) { setTabIconsFromLayoutPage...
// given IconTabLayout iconTabLayout = new IconTabLayout(RuntimeEnvironment.application); // when iconTabLayout.setTabsFromPagerAdapter(pagerAdapter); // then assertThat(iconTabLayout.getTabAt(0)).hasIcon(null).hasText("barbers"); assertThat(iconTabLayout.getTabAt(1)).hasIcon(null).hasText...
41091157_5
class HomePageController extends AbstractController implements IController { @Override public ModelAndView doGet(ModelMap model) { log.info("Requesting doGet of " + this.getClass()); return buildModelAndView( getModelViewName(), model, new ModelP...
ModelMap model = new ModelMap(); assertEquals("homePage", controller.doGet(model)); } }
41092630_14
class RequestExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(SmartCosmosException.class) protected ResponseEntity<?> handleSmartCosmosExceptionMethod(SmartCosmosException exception, WebRequest request) { if (exception.getCause() == null) { logException(exception...
SmartCosmosException smartCosmosException = new SmartCosmosException("just message, no cause"); ResponseEntity responseEntity = handler.handleSmartCosmosExceptionMethod(smartCosmosException, webRequest); assertEquals(responseEntity.getStatusCode(), HttpStatus.INTERNAL_SERVER_ERROR); ass...
41104075_6
class IngestJob extends AbstractJob { @Override public int run(String[] args) throws Exception { addInputOption(); addOutputOption(); addOption(JOB_NAME_OPTION, "jn", "Optional name to give the Hadoop Job.", false); addOption(ZK_CONNECT_OPTION, "zk", "Connection string for ZooKeeper. Either...
String warc = "warc/at.warc"; File warcFile = new File(ClassLoader.getSystemClassLoader().getResource(warc).getPath()); assertTrue(warc + " does not exist: " + warcFile.getAbsolutePath(), warcFile.exists()); Path input = new Path(tempDir, warc); addContentToFS(input, Files.toString(warcFile, Charset...
41115262_3
class Device { @NonNull @SuppressWarnings("deprecation") public static JobRequest.NetworkType getNetworkType(@NonNull Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo; t...
NetworkInfo networkInfo = mock(NetworkInfo.class); when(networkInfo.isConnected()).thenReturn(false); when(networkInfo.isConnectedOrConnecting()).thenReturn(false); ConnectivityManager connectivityManager = mock(ConnectivityManager.class); when(connectivityManager.getActiveNetwo...
41152339_2
class MonetaryFormat { public CharSequence format(Monetary monetary) { return format(monetary, monetary.smallestUnitExponent()); } public MonetaryFormat(); private MonetaryFormat(char negativeSign, char positiveSign, char zeroDigit, char decimalMark, int minDecimals, ...
assertEquals("0.1", format(Coin.parseCoin("0.1"), 0, 1, 2, 3)); assertEquals("0.010", format(Coin.parseCoin("0.01"), 0, 1, 2, 3)); assertEquals("0.001", format(Coin.parseCoin("0.001"), 0, 1, 2, 3)); assertEquals("0.000100", format(Coin.parseCoin("0.0001"), 0, 1, 2, 3)); assertEqu...