id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
50600325_6
class WidgetController { @RequestMapping( method = POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<WidgetConfigResource> createWidget( @PathVariable String slug, @RequestBody WidgetConfigResource widgetConfigResource) { ...
ConstrainedFields fields = fields(WidgetConfigResource.class); WidgetConfig widgetConfig = widgetConfig(); WidgetConfigResource widgetConfigResource = widgetConfigResource(); when(dashboardService.load(any())).thenReturn(dashboard()); when(widgetService.saveWidget(any(WidgetConfig.class))).thenRetu...
50632308_5
class RMP { public Observable<Professor> getProfessor(final Parameter params) { Observable<Professor> professorFromClient = mRMPClient.findProfessor(params) //Since this is first in the chain, don't try an error just yet. .onErrorResumeNext(Observable.<Professor>empty()) ...
Parameter params = new Parameter("rutgers", "Computer Science", "Newark", "101", "", "NOPROFESSOR"); Professor result = rmp.getProfessor(params).toBlocking().lastOrDefault(null); assertNull(result); } }
50677285_8
class AssociatedLegendrePolynomial implements UnivariateFunction { @Override public final double value(double x) { return this.sign * (FastMath.pow(1.0-FastMath.pow(x,2.0),m/2.0) * legendre.value(x)); } public AssociatedLegendrePolynomial(int l, int m); public final int getL(); publi...
final double increment = 1e-4; final AssociatedLegendrePolynomial alp = new AssociatedLegendrePolynomial(2,2); for (double x = -1.0;x<=1.0;x+=increment) { assertEquals(3.0*(1-Math.pow(x,2)), alp.value(x), 1e-8); } } }
50679300_6
class JWTFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String ...
MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer "); request.setRequestURI("/api/test"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain...
50726401_0
class DateUtils { public static Long rfc3339ToMills(String dateInString) { Calendar cal = Calendar.getInstance(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss.SSSSSS", Locale.getDefault()); try { cal.setTime(simpleDateFormat.parse(dateInString ...
assertEquals(1572374198000L , DateUtils.rfc3339ToMills("2019-10-29T18:36:38.000GMT").longValue()); long epoch = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); assertTrue(((epoch - DateUtils.rfc3339ToMills("abc").longValue()) < 1000)); epoch = LocalDateTime...
50726840_5
class XmlSanitizer { public static String sanitize(final String input, final String tag) { Pattern p = Pattern.compile("<" + tag + ">(.+?)</" + tag + ">", Pattern.DOTALL); if (BuildConfig.DEBUG) Log.d(TAG, "sanitize(): Using pattern \"" + p.pattern() + "\""); Matcher m = p.matcher(input); ...
String sanitized = XmlSanitizer.sanitize(rawText1, "body"); assertThat(sanitized, is(equalTo(sanitizedText1))); } }
50753889_0
class LoyaltyCardViewActivity extends AppCompatActivity { @Override public void onBackPressed() { if (barcodeIsFullscreen) { setFullscreen(false); return; } super.onBackPressed(); return; } private void extractIntentFields(Intent intent)...
ActivityController activityController = createActivityWithLoyaltyCard(false); Activity activity = (Activity)activityController.get(); DBHelper db = new DBHelper(activity); db.insertLoyaltyCard("store", "note", BARCODE_DATA, BARCODE_TYPE, Color.BLACK, Color.WHITE); activityContr...
50834437_9
class Destination { public Port getPort() { return port; } public Destination(String host, Port port); public Destination(String uriString); private void setDefaultPort(String scheme); private boolean noPort(URI uri); public boolean noPort(); public String getHost(); pri...
Destination destination = new Destination("https://mysite.org/path"); Assert.assertEquals(ImmutablePort.of(443), destination.getPort()); } }
50842364_180
class IdBasedDataProvider extends BaseDataProvider<ID, T> { @Override public int size(Query<T, SerializablePredicate<T>> query) { SortOrders so = createSortOrder(query); FilterConverter<T> converter = getFilterConverter(); Filter filter = converter.convert(query.getFilter().orElse(null...
when(service.findIds(isNull(), isNull(), any())) .thenReturn(List.of(1, 2, 3)); provider = new IdBasedDataProvider<>(service, emf.getModel(TestEntity.class)); provider.size(query); provider.setCurrentlySelectedId(2); assertTrue(provider.hasPreviousItemId()); Integer next = provider.getPreviousItemId(...
50882844_11
class Orbit { public double getMeanAngularMotion() { return MathUtils.TWO_PI / getPeriod(); } public Orbit(Body body, double a, double e, double i, double lan, double aop); public Body getBody(); public double getSemiMajorAxis(); public double getSMA(); public double getEccentricity(); public double getAp...
Body b = new Body("Earth", 398600441800000.0); double a = 6774500; double e = 0.0006531; double i = Math.toRadians(51.6443); double lan = Math.toRadians(117.8784); double aop = Math.toRadians(15.1371); Orbit o = new Orbit(b, a, e, i, lan, aop); TestUtils.assertRelativelyEquals(0.00113227786, o.getMean...
50950973_17
class AnnotatedText implements Serializable { @SuppressWarnings("unchecked") public ListAttribute<LayoutRegion> getLayoutRegions() { return (ListAttribute<LayoutRegion>) attributes.get(AttributeKey.LAYOUT_REGION.key()); } AnnotatedText(CharSequence data, Map<String, BaseAtt...
final String data = "This is unstructured text. bla bla bla.\nThis\tis\tfragmented\t\text.\n"; AnnotatedText.Builder builder = new AnnotatedText.Builder().data(data); ListAttribute.Builder<LayoutRegion> layoutRegionBuilder = new ListAttribute.Builder<>(LayoutRegion.class); LayoutRegion....
50951613_2
class RangeUtil { public static int map(float value, float fromLow, float fromHigh, int toLow, int toHigh) { return map(value, fromLow, fromHigh, toLow, toHigh, DEFAULT_MAP_CONSTRAIN); } public static int constrain(int value, int min, int max); public static float constrain(float value, float min, float max); ...
float min_pulse_width_ms = 0.75f; float max_pulse_width_ms = 2.25f; float minus90_pulse_width_ms = 1f; float plus90_pulse_width_ms = 2f; Assert.assertEquals( RangeUtil.map(min_pulse_width_ms, minus90_pulse_width_ms, plus90_pulse_width_ms, 0, 180, false), -45); Assert.assertEquals( RangeUtil.map(max...
50961051_0
class IndicatorMatchers { public static IndicatorMatcher build() { return unused -> true; } public static IndicatorMatcherBuilder includes(String... indicatorNames); public static IndicatorMatcherBuilder excludes(String... indicatorNames); } class IndicatorMatchersTest { @Test publi...
assertTrue(IndicatorMatchers.build().matches(new A())); } }
50999206_4
class Pbkdf2PasswordHashImpl implements Pbkdf2PasswordHash { @Override public boolean verify(char[] password, String hashedPassword) { EncodedPasswordHash encodedPasswordHash = new EncodedPasswordHash(hashedPassword); byte[] hashToVerify = pbkdf2( password, encod...
// since -1 (or illegal value) is not captured within Soteria .... hashImpl.verify("Soteria".toCharArray(), encodedPassword(encodedHash1, salt1, "PBKDF2WithHmacSHA256", -1)); } }
51015648_148
class RxJava3Adapter { public static <T> Mono<T> singleToMono(Single<T> source) { return new SingleAsMono<>(source); } RxJava3Adapter(); public static Flux<T> flowableToFlux(Flowable<T> source); public static Flowable<T> fluxToFlowable(Flux<T> source); public static Flowable<T> mono...
Mono<Integer> m = Single.just(1) .to(RxJava3Adapter::singleToMono); StepVerifier.create(m) .expectNext(1) .expectComplete() .verify(); } }
51016215_1
class RewardConfirmationMarshaller implements Marshaller { @Override public void marshal(Object graph, Result result) throws XmlMappingException, IOException { RewardConfirmation rewardConfirmation = (RewardConfirmation) graph; Assert.hasText(rewardConfirmation.getDiningTransactionId(), "'diningTransactionId'...
RewardConfirmation rewardConfirmation = mock(RewardConfirmation.class); when(rewardConfirmation.getDiningTransactionId()).thenReturn("w00t"); DOMResult result = new DOMResult(); marshaller.marshal(rewardConfirmation, result); DOMSource source = new DOMSource(result.getNode()); assertThat(xpathTemplate.evalu...
51074108_36
class LocalContext { public void registerNewState(Long version, String name, String description, String hookIdentifier, String taskIdentifier, Long retryCount, Long timeout, List<Even...
localContext.registerNew("fooBar", 1, "someDescription",null, "defaultElbId"); EventDefinition dummyDependency = new EventDefinition("someName","com.blah.some.Event"); EventDefinition dummyOutput = new EventDefinition("someOutput","com.blah.some.Event"); localContext.regi...
51074728_33
class PoliciedServiceLevelEvaluator implements IServiceLevelEvaluator { @Override public List<IViolation> evaluate( IAgreement agreement, IGuaranteeTerm term, List<IMonitoringMetric> metrics, Date now) { logger.debug("evaluate(agreement={}, term={}, servicelevel={})", agreement.getAgreementId(), term.getKp...
IPolicy policy; System.out.println("---testEvaluateWithPolicy1()---"); /* * t-2, t-3 are breaches but are separated more than policy interval -> 0 violations */ List<IMonitoringMetric> metrics = setUpWithPolicies(null, null); policy = newPolicy("LATENCY", 2, new Date(900)); ...
51083005_0
class UniqueFilter extends AbstractConsumerStage<String> { public OutputPort<String> getOutputPort() { return this.outputPort; } public UniqueFilter(); @Override protected void execute(final String element); private UniqueFilter uniqueFilter; private List<String> inputList; priv...
final List<String> outputList = new ArrayList<>(); StageTester.test(this.uniqueFilter).and().send(this.inputList).to(this.uniqueFilter.getInputPort()).and() .receive(outputList).from(this.uniqueFilter.getOutputPort()).start(); Assert.assertEquals("Not the correct number of result...
51113763_8
class InMemoryAccountRepository implements AccountRepository { @Override public int deleteAccount(Long id) { accountMap.remove(id); return 1; } @Override public List<Account> getAccounts(); @Override public Account getAccount(Long id); @Override public int getNumberOfAccounts()...
// Get the number of accounts before deleting int beforeCount = repository.getNumberOfAccounts(); Account account = repository.getAccount(3L); // Delete an account and check that num is one less repository.deleteAccount(3L); int afterCount = repository.getNumberOfAccount...
51161341_58
class WordCap implements Comparable<WordCap>, Serializable { @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WordCap wordCap = (WordCap) o; if (isCapitalized != wordCap.isCapit...
WordCap wordCap = new WordCap("aWord", false); assertFalse(wordCap.equals("aString")); } }
51247796_1
class Krb5ServerHelper { public Identity getClientIdentity(byte[] serviceTicket){ try { DerValue APREQ = extractAPREQ(serviceTicket); Ticket authenticationTicket = extractAuthenticationTicketFromAPREQ(APREQ.toDerInputStream(), APREQ.length()); Identity identity = decryptAuthenticationTicket(authenticationT...
Identity clientIdentity = krb5ServerHelper.getClientIdentity(serviceTicket); System.out.println(clientIdentity.toString()); assertEquals("Username - Expected: " + clientUsername + " Actual: " + clientIdentity.getUsername(), clientUsername, clientIdentity.getUsername()); assertEquals("Realm - Expected: " + clie...
51291746_15
class SpringBeanService { public <T> T getBeanDefinition(File configFile, Project project, String id, Class<T> type) { LSParser parser = XMLUtils.createLSParser(); GetSpringBeanFilter filter = new GetSpringBeanFilter(id, type); parser.setFilter(filter); List<File> configFiles = ne...
File tempFile = createTempContextFile("citrus-context-find"); SchemaModel schema = springBeanConfigService.getBeanDefinition(tempFile, project, "helloSchema", SchemaModel.class); Assert.assertEquals(schema.getId(), "helloSchema"); Assert.assertEquals(schema.getLocation(), "classpath:co...
51307016_350
class PemReader { public static List<Entry> readAll(final Path path) throws IOException { Objects.requireNonNull(path); try (Reader reader = Files.newBufferedReader(path, StandardCharsets.US_ASCII)) { return readAll(reader); } } private PemReader(); public static...
final List<Entry> result = PemReader.readAll(this.basePath2.resolve("empty.pem")); assertTrue(result.isEmpty()); } }
51357073_11
class AnnotatedBuilder extends RunnerBuilder { @Override public Runner runnerForClass(Class<?> testClass) throws Exception { for (Class<?> currentTestClass = testClass; currentTestClass != null; currentTestClass = getEnclosingClassForNonStaticMemberClass(currentTestClass)) { Ru...
Runner runner = builder.runnerForClass(OuterClass.InnerClassWithOwnRunWith.MostInnerClass.class); assertThat(runner, is(instanceOf(InnerRunner.class))); RunnerSpy runnerSpy = (RunnerSpy) runner; assertThat(runnerSpy.getInvokedTestClass(), is((Object) OuterClass.InnerClassWithOwnRunWith....
51379345_108
class PatchFileCreator { public static PreparationResult prepareAndValidate(File patchFile, File toDir, UpdaterUI ui) throws IOException, OperationCancelledException { Patch patch; ZipFile zipFile = new...
Patch patch = createPatch(); assertAppliedAndRevertedCorrectly(patch, PatchFileCreator.prepareAndValidate(myFile, myOlderDir, TEST_UI)); } }
51437409_1
class LightLexer extends AbstractLexer { @Override public TokenizedSource convert() { LightLexerWorker worker = new LightLexerWorker(this); return worker.convert(); } public LightLexer(String source); private static final String DEFAULT; private static final String INDENTATIO...
Lexer indentationLexer = new LightLexer(PandaURLSource.fromPath(INDENTATION).getContent()); TokenizedSource source = indentationLexer.convert(); Assertions.assertNotNull(source); Assertions.assertTrue(source.size() > 0); } }
51441531_1
class User { public boolean checkSecretAnswer(String answer) throws InvalidKeySpecException, NoSuchAlgorithmException { if (answer == null) return false; byte[] salt = Base64.decodeBase64(this.secretAnswerSalt); KeySpec spec = new PBEKeySpec(answer.toCharArray(), s...
final User fixture = mapper.readValue(fixture("fixtures/user.json"), User.class); assertThat(fixture.checkSecretAnswer("deneme")).isEqualTo(true); assertThat(fixture.checkSecretAnswer("nope")).isEqualTo(false); } }
51447395_22
class UserViewModel extends BaseObservable { public String getUsername() { return user.getLogin(); } public UserViewModel(User user); public String getImageUrl(); @BindingAdapter({ "bind:imageUrl" }) public static void loadImage(ImageView view, String imageUrl); public void setUser(User user); @M...
Assert.assertEquals(mockUser.getLogin(), userViewModel.getUsername()); } }
51451752_7
class DiffCommandsCalculator { public List<AdapterCommand> diff(@NonNull List<T> newList) { if (newList == null) { throw new NullPointerException("newList == null"); } int newSize = newList.size(); // first time called if (oldList == null) { oldList = new ArrayList<>(); oldLis...
// Warmup ItemChangedDetector<Item> changeDetector = new Detector(); List<Item> items = newList("a", "b", "c", "d", "e", "f"); calculator.diff(items); items.remove(1); items.remove(3); List<AdapterCommand> commands = calculator.diff(items); Assert.assertEquals(2, commands.size()); ...
51498833_0
class Coinbase { public static void sign(FIXMessage message, String secret) { StringBuilder presign = new StringBuilder(); appendField(message, SendingTime, "SendingTime(52)", presign); presign.append(SOH); presign.append(Logon); presign.append(SOH); appendField(mes...
FIXMessage message = new FIXMessage(64, 64); message.addField(SenderCompID).setString("foo"); message.addField(TargetCompID).setString("Coinbase"); message.addField(MsgSeqNum).setInt(1); message.addField(SendingTime).setString("20160118-09:30:00.000"); message.addField(E...
51536707_3
class PresentationEntityMapper { @Contract("null -> null") public PresentationStripe transform(final @Nullable DomainStripe domainStripe) { PresentationStripe ret = null; if (domainStripe != null) { ret = new PresentationStripe(); ret.setAlt(domainStripe.getAlt()); ret.setDay(domainStrip...
final DomainStripe source = new DomainStripe(); source.setAlt(generateString(Value.NULL)); source.setDay(generateString(Value.NULL)); source.setImg(generateString(Value.NULL)); source.setLink(generateString(Value.NULL)); source.setMonth(generateString(Value.NULL)); source.setYear(generateSt...
51575637_10
class RepositoriesPresenter extends BasePresenter<RepositoriesView> { public void onErrorCancel() { getViewState().hideError(); } public RepositoriesPresenter(); @Override protected void onFirstViewAttach(); public void loadNextRepositories(int currentCount); public void loadRepositories(boolean isRefreshin...
presenter.onErrorCancel(); verify(repositoriesViewState).hideError(); } }
51592804_5
class JenaExtensionRegistry extends WrappingRegistry implements ExtensionRegistry { @Override public Extension getExtension(final URI uri) { return new JenaExtension(uri); } @Override @Reference // (target = "org.fcrepo.apix.registry.contains=org.fcrepo.apix.model.Extension") public void setRe...
final String EXPOSED_AT = "/svc:/123()"; when(registryDelegate.get(EXTENSION_URI)).thenReturn(rdfResource(EXTENSION, ltriple(EXTENSION, PROP_EXPOSES_SERVICE_AT, EXPOSED_AT))); assertEquals(Scope.REPOSITORY, toTest.getExtension(EXTENSION_URI).exposed().scope()); } }
51621524_2
class EtherFormatter { public static String formatWeiAsEther(long wei) { double ether = (double) wei / 1000000000000000000L; return String.format(Locale.getDefault(), "%.2f" + "ETH", ether); } } class EtherFormatterTest { @Test public void testFormatEtherFraction2() throws Exception...
assertThat(EtherFormatter.formatWeiAsEther(2119000000000000000L), is("2.12ETH")); } }
51650903_1
class ContentPresenter extends BasePresenter<ContentMvpView> { public void getCats(List<Cat> cats) { checkViewAttached(); mSubscription = mDataManager.getCats(cats) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(n...
List<Cat> cats = TestDataFactory.makeCats(10); stubDataManagerGetCats(Single.just(cats)); mContentPresenter.getCats(cats); verify(mMockContentMvpView).showCats(cats); verify(mMockContentMvpView, never()).showCatsError(); } }
51677030_11
class WordnetPresenter implements MeaningPresenter { public void onDownloadClicked() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { contextHelper.openDictionariesActivity(); controller.onDownloadClicked(); }else { contextHelper.startDownload(Constants.WO...
presenter.onDownloadClicked(); verify(contextHelper).startDownload(Constants.WORDNET); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { verify(controller).onDownloadClicked(); } else { verify(controller, never()).onDownloadClicked(); } } }
51719162_1
class RxCurryingFunc { public static <A, B, R> Func1<A, Func1<B, R>> curry(final Func2<A, B, R> func) { return new Func1<A, Func1<B, R>>() { @Override public Func1<B, R> call(final A a) { return new Func1<B, R>() { @Override pu...
Func1<String, Func1<String, Func1<String, Func1<String, Func1<String, String>>>>> secondVariable = RxCurryingFunc .curry(new Func5<String, String, String, String, String, String>() { @Override public String call(String first, String second, String third, S...
51724669_1
class OsgiaasJavaCompilerService implements JavacService { @Override public <T> Optional<Class<T>> compileJavaClass( ClassLoaderContext classLoaderContext, String qualifiedName, String code, ...
String classDef = "package com.acme.util;" + "import java.util.function.IntSupplier;" + "public class ZeroSupplier implements IntSupplier {" + "public int getAsInt() { return 0; }" + "}"; Class<?> cls = javacService.compileJavaClass( Defau...
51744006_40
class Ngsi2Client { public ListenableFuture<String[]> bulkRegister(BulkRegisterRequest bulkRegisterRequest) { return adapt(request(HttpMethod.POST, UriComponentsBuilder.fromHttpUrl(baseURL).path("v2/op/register").toUriString(), bulkRegisterRequest, String[].class)); } private Ngsi2Client(); p...
mockServer.expect(requestTo(baseURL + "/v2/op/register")) .andExpect(method(HttpMethod.POST)) .andExpect(header("Content-Type", MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.actionType").value("UPDATE")) .andExpect(jsonPath("$.registra...
51754367_9
class FixValue implements FixNode { public T getValue() { return value; } public FixValue(FixType type, T value); public FixValue(String name); public FixValue(String name, FixType type); public FixValue(String name, FixType type, T value); @SuppressWarnings("unchecked") public void assign(FixV...
FixValue<Integer> op1 = new FixValue<Integer>("op1", FixType.intType, 3); FixValue<Integer> op2 = new FixValue<Integer>("op2", FixType.intType, 4); assertEquals(Integer.valueOf(7), fixValueOperations.add.apply(op1, op2).getValue()); } }
51787752_4
class S3StorageDriver implements BackupStorageDriver { String getPrefixKey(BackupRestoreContext ctx) throws URISyntaxException { URI uri = new URI(ctx.getExternalLocation()); String[] segments = uri.getPath().split("/"); int startIndex = uri.getScheme().equals(AmazonS3Client.S3_SERVICE_NAM...
String backupName = "backup-name"; String nestedPath = "nested-path"; BackupRestoreContext backupRestoreContext = BackupRestoreContext.create( "node-id", backupName, "s3://cassandrabackup/" + nestedPath, "local-location", ...
51848128_26
class PatternMatch { public boolean matches(String value) { return compliedPattern.matcher(value).matches(); } public PatternMatch(String pattern); private String pattern(String pattern); } class PatternMatchTest { @Test public void testMatches() {
assertThat(new PatternMatch("/").matches("/aaa/"), is(false)); assertThat(new PatternMatch("aaa").matches("b"), is(false)); assertThat(new PatternMatch("aaa").matches("aaa"), is(true)); assertThat(new PatternMatch("a*c").matches("abc"), is(true)); assertThat(new PatternMatch("a...
51858172_86
class HttpCallImplWithConnectionPooling implements HttpCall<T> { @Override public T doPost(final String url, final Object data, final Class<T> toMap, final Map<String, String> headers, final Map<String, String> queryParams, final String accept, final String type, final i...
stubFor(post(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withSt...
51861689_5
class ClusterList { public List<String> get() { return Lists.newArrayList(this.config.clusters().trim().split(",")) .stream() .filter(cluster -> !cluster.isEmpty()) .collect(Collectors.toList()); } public ClusterList(Config config); } class ClusterListTest { ...
final List<String> clusters = new ClusterList( new ClusterListTest.FakeConfig("cluster1,cluster2,cluster3") ).get(); Assertions.assertThat(clusters) .hasSize(3) .contains("cluster1", "cluster2", "cluster3"); } }
51906847_3
class HistoneProcessingExceptionProcessor { public final void process(HttpServletRequest request, HttpServletResponse response, Exception exception, String templateLocation) throws Exception { Exception cause = getRootCause(exception); if (supports(cause.getClass())) {...
try { exceptionProcessor.process(request, response, new Exception("Some exception occured"), "someLocation"); fail("Exception should be thrown"); } catch (Exception ex) { assertThat(ex.getMessage(), is("Error evaluating histone template 'someLocati...
51909350_89
class NgsiClient { public HttpHeaders getRequestHeaders() { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MediaType.APPLICATION_XML); requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML)); return requestHeaders; } pub...
HttpHeaders httpHeaders = ngsiClient.getRequestHeaders(null); assertEquals(MediaType.APPLICATION_XML, httpHeaders.getContentType()); assertTrue(httpHeaders.getAccept().contains(MediaType.APPLICATION_XML)); } }
51920891_21
class FileToRelativePath implements Function<File, String> { @Override public String apply(File f) { return this.workingDir.toURI().relativize(f.toURI()).toString(); } public FileToRelativePath(File workingDir); @Rule public TemporaryFolder tempFolder; } class FileToRelativePathTest { @Rule p...
public void testApply(String path) throws IOException { File base = this.tempFolder.newFolder(); Assert.assertEquals(path, new FileToRelativePath(base).apply(new File(base, path))); } }
51934971_1
class WordToPdfRenditionProvider implements RenditionProvider { @Override public InputStream convert(InputStream fromInputSource, String toMimeType) { try { WordprocessingMLPackage pkg = WordprocessingMLPackage.load(fromInputSource); FieldUpdater updater = new FieldUpdater(pkg); updater.update(true); ...
InputStream converted = service.convert(this.getClass().getResourceAsStream("/sample-docx2.docx"),"application/pdf"); assertThat(converted.available(), is(greaterThan(0))); assertThat(((ObservableInputStream)converted).getObservers(), hasItem(is(instanceOf(FileRemover.class)))); String content = pdfToText(con...
51949991_110
class LinuxSyslogYearSetter { @Override public String toString() { String str = ""; str += " source=" + m_source; str += " year=" + m_currentYear; str += " lastSeenMessage=" + DateTimeUtils.timestampToHumanDateAndTimeAndStampUTC(m_lastSeenMessageDate.getMillis()); retur...
String source = "aSource"; int nineties = 1990; lsys = new LinuxSyslogYearSetter(source, nineties); DateTimeZone dtz = DateTimeZone.forID("America/New_York"); DateTime dt = new DateTime(0L, dtz); lsys.getDesiredYear(dt); String actual = lsys.toString(); a...
51958035_0
class KeywordOptimizerUtil { public static StatsEstimate calculateMean(StatsEstimate min, StatsEstimate max) { Money meanAverageCpc = calculateMean(min.getAverageCpc(), max.getAverageCpc()); Double meanAveragePosition = calculateMean(min.getAveragePosition(), max.getAveragePosition()); Double meanClicks ...
Money lowCpc = new Money(); lowCpc.setMicroAmount(1_000_000L); Money lowTotal = new Money(); lowTotal.setMicroAmount(10_000_000L); StatsEstimate lowEstimate = new StatsEstimate(lowCpc, 3.0, 0.01, 1000.0F, 100_000.0F, lowTotal); Money highCpc = new Money(); highCpc.setMicroAmount(9_000_000L)...
51960935_1
class InfiniteScrollListener extends RecyclerView.OnScrollListener { protected boolean canLoadMoreItems() { final int visibleItemsCount = layoutManager.getChildCount(); final int totalItemsCount = layoutManager.getItemCount(); final int pastVisibleItemsCount = layoutManager.findFirstVisibleItemPosition()...
// given int visibleItemsCount = 10; int totalItemsCount = 20; int pastVisibleItemsCount = 15; int itemsPerRequest = 10; InfiniteScrollListener listener = createListener(manager, itemsPerRequest); // when when(manager.getChildCount()).thenReturn(visibleItemsCount); when(manager.getI...
51989270_60
class ViewableWriter implements MessageBodyWriter<Viewable> { @Override public void writeTo(Viewable viewable, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException, WebApplicat...
ViewableWriter writer = new ViewableWriter(); Field mvcField = writer.getClass().getDeclaredField("mvc"); mvcField.setAccessible(true); mvcField.set(writer, new MvcContextImpl()); ViewEngineFinder finder = EasyMock.createStrictMock(ViewEngineFinder.class); Field...
52030103_407
class Viewport { public boolean intersect(int x, int y, int width, int height) { if (this.width > 0 && this.height > 0 && width > 0 && height > 0 && this.x < (x + width) && x < (this.x + this.width) && this.y < (y + height) && y < (this.y + this.height)) { i...
Viewport a = new Viewport(30, 100, 3, 3); Viewport adjacentEast = new Viewport(31, 103, 1, 1); Viewport copy = new Viewport(a); boolean intersected = a.intersect(adjacentEast); assertFalse("adjacent, no intersection", intersected); assertEquals("adjacent, no changed", a...
52040340_135
class HTTPSCustomizer implements Customizer { public void customize() { if (!this.managementCoreService.isUnsatisfied()) { if (certInfo.isValid()) { ManagementCoreService management = this.managementCoreService.get(); if (management == null) { ...
HTTPSCustomizer customizer = new HTTPSCustomizer(); customizer.undertow = new UndertowFraction(); customizer.undertow.applyDefaults(); customizer.certInfo = new CertInfo("myhost.com", "./my/path"); customizer.managementCoreService = new MockInstance<>(new ManagementCoreService())...
52095301_4
class Experiment { public T run(Callable<T> control, Callable<T> candidate) throws Exception { if (isAsync()) { return runAsync(control, candidate); } else { return runSync(control, candidate); } } public Experiment(MetricsProvider<?> metricsProvider); ...
Integer val = new Experiment<Integer>("test", true, new NoopMetricsProvider()) .run(() -> null, () -> null); assertThat(val).isNull(); } }
52113991_5
class NewestVersionSelector extends ConflictResolver.VersionSelector { @Override public void selectVersion(ConflictResolver.ConflictContext context) throws RepositoryException { ConflictGroup group = new ConflictGroup(); for (ConflictResolver.ConflictItem item : context.getItems()) { ...
NewestVersionSelector selector = new NewestVersionSelector(); List<ConflictResolver.ConflictItem> items = new ArrayList<>(); items.add(new ConflictResolver.ConflictItem(null, createNode("1.0.1.Alpha4"), 0, 0)); items.add(new ConflictResolver.ConflictItem(null, createNode("1.0.0.Final"),...
52139656_0
class EnumAdapter implements IPreferenceAdapter<T> { @Nonnull @Override public Observable<T> observe(@Nonnull String key, @Nonnull T defaultValue, @Nonnull IGateway gateway) { return gateway.observeString(key, toString(defaultValue)).map(new Function<String, T>() { @Override public T apply(...
when(gateway.observeString("testKey", NUMBER.ONE.name())) .thenReturn(Observable.just(NUMBER.TWO.name())); Observable<NUMBER> observable = adapter.observe("testKey", NUMBER.ONE, gateway); observable.subscribe(observer); verify(gateway).observeString("testKey", NUMBER.ON...
52143457_2
class Polymer { @JsOverlay public static String toCamelCase(String text) { String bactrianCamel = Stream.of(text.split("[^a-zA-Z0-9]")) .map(v -> v.substring(0, 1).toUpperCase() + v.substring(1).toLowerCase()) .collect(Collectors.joining()); return bactrianCamel....
assertEquals("thisIsSomeText", Polymer.toCamelCase("THIS_IS_SOME_TEXT")); } }
52145597_9
class TasksViewModel extends BaseViewModel<TasksViewModel.State> { protected void onTaskUpdate(Task task) { Task tmp; int n = mTasks.size(); for (int i = 0; i < n; i++) { tmp = mTasks.get(i); if (task.getId().equals(tmp.getId())) { tmp.setTitle(task.getTitle()); tmp.setDescrip...
Task taskA = new Task("title a", "description a"); List<Task> tasks = mTasksViewModel.getTasks(); tasks.add(taskA); Task taskB = new Task(taskA.getId(), "title b", "description b"); mTasksViewModel.onTaskUpdate(taskB); verify(mTasksViewModel, times(1)).setState(eq(TasksViewModel.State.UPDATED_...
52192427_0
class GreeterService implements Greeter.Iface { @Override public HelloReply sayHello(HelloRequest req) throws TException { return new HelloReply("Hello " + req.getName()); } @Value("${nifty.port}") public int port; private Greeter.Client client; } class GreeterServiceTest { @Value("${nifty.port}"...
HelloRequest msg = new HelloRequest("Dude"); HelloReply resp = client.sayHello(msg); assertEquals(resp.message, "Hello Dude"); } }
52212248_0
class Bus { public <T> void post(T event) { if (event == null) { throw new NullPointerException("Event cannot be null"); } synchronized (listenerLock) { for (Map.Entry<Class, List<Subscription>> entry : currentThreadListeners.entrySet()) { checkAndPos...
Bus bus = new Bus.Builder() .setMainScheduler(Schedulers.trampoline()) .setBackgroundScheduler(Schedulers.trampoline()) .setCurrentScheduler(Schedulers.trampoline()) .build(); String uid = UUID.randomUUID().toString(); setTestUid(u...
52227745_2
class SubscriptionLimiter { public static <T> Observable<T> limitSubscriptions(int maxNumber, Observable<T> source) { State state = new State(); return Observable.create(subscriber -> { synchronized (state) { if (state.getNumberOfSubscriptions() == maxNumber) { ...
// given PublishSubject<Integer> subject = PublishSubject.create(); Observable<Integer> limitedObservable = SubscriptionLimiter.limitSubscriptions(1, subject); TestSubscriber<Integer> subscriber = new TestSubscriber<>(); // when limitedObservable.subscribe(subscriber); ...
52228869_0
class AuthKeyGen { public static AwsKeyPair generateKeypair() throws NoSuchAlgorithmException { String accessKey = "-"; String secretKey = "-"; while (accessKey.contains("-") || accessKey.contains("_") || secretKey.contains("-") || secretKey.contains("_")) { KeyG...
for (int i = 0 ; i < 1000; i++){ AuthKeyGen.AwsKeyPair keyPair = AuthKeyGen.generateKeypair(); System.out.println(keyPair); assertFalse(keyPair.awsAccessKeyId.contains("-")); assertFalse(keyPair.awsAccessKeyId.contains("_")); assertFalse(keyPair.awsSecretAc...
52264160_3
class FileSortUtils { public void performSortOperation(int option, List<File> pdf) { switch (option) { case DATE_INDEX: sortFilesByDateNewestToOldest(pdf); break; case NAME_INDEX: sortByNameAlphabetical(pdf); break; ...
// given long[] sizes = {10000, 1000, 100, 50, 2000, 2500}; for (int i = 0; i < sizes.length; i++) when(mFiles.get(i).length()).thenReturn(sizes[i]); File[] expected = new File[]{mFiles.get(0), mFiles.get(5), mFiles.get(4), mFiles.get(1), mFiles.get(2), mFile...
52371323_51
class GuavaCache implements MetricIdCache.Cache<T> { @Override public MetricId get(final MetricId base, final T key) throws ExecutionException { return cache.get(key, new Callable<MetricId>() { @Override public MetricId call() throws Exception { return loader.loa...
Assert.assertEquals(MetricId.EMPTY.tagged("endpoint", "foo"), endpointCache.get("foo")); Assert.assertEquals(MetricId.EMPTY.tagged("endpoint", "foo"), endpointCache.get("foo")); Assert.assertEquals(1, callCount.get()); Assert.assertEquals(MetricId.EMPTY.tagged("endpoint", "bar"), endpoi...
52404147_87
class StatisticsUtilities { public static double minimum(double[] xs) { double min = xs[0]; // Stores the minimum value to be returned later; is assumed to be the value at the first Index for (int i = 1; i < xs.length; i++) { // Cycles through the Array to search for the minimum value min = Math.min(min, xs[i]...
double[] test = { 1, 1, 1, 12, 2, 2, 2, 23, 3, 3, 3, 500}; double[] test2 = { 1, 2, 3, 4, 5 }; double[] test3 = { 1, 1, 100, 50 }; double[] test4 = { 50, 50, 51, 51 }; double[] test5 = { 100, 500, 101 }; assertEquals(StatisticsUtilities.minimum(test), 1, ERROR); assertEquals(StatisticsUtilities.minimum(te...
52453918_4
class ElloURI { public static boolean shouldLoadInApp(String url) { if (url.matches("^(https?://)?((w{3}|preview.)?ello.(co|ninja)|(ello-webapp-epic|ello-webapp-rainbow|ello-fg-stage1|ello-fg-stage2).herokuapp.com)/?\\S*$")) { return true; } else if (url.matches("/\\S*$")) { ...
assertFalse("https://hello.co should NOT load in app", ElloURI.shouldLoadInApp("https://hello.co")); assertFalse("https://www.google.com should NOT load in app", ElloURI.shouldLoadInApp("https://www.google.com")); assertFalse("yo/sean should NOT load in app", ElloURI.shouldLoadInApp("yo/sean"));...
52460731_1
class Permissive { public static String[] filterPermissions(Context context, String[] permissions, int filter) { final ArrayList<String> filtered = new ArrayList<>(); for (String permission : permissions) { if (checkPermissionInt(context, permission) == filter) { filtered.add(permission); ...
String[] result = Permissive.filterPermissions(mockContext, new String[]{TEST_DENIED_PERMISSION, TEST_GRANTED_PERMISSION}, PackageManager.PERMISSION_GRANTED); assertArrayEquals(result, new String[]{TEST_GRANTED_PERMISSION}); result = Permissive.filterPermissions...
52478731_6
class PhenotypeAssociation extends AbstractAuditable implements gemma.gsec.model.Securable { public Collection<Characteristic> getPhenotypes() { return this.phenotypes; } public PhenotypeAssociation(); public Characteristic getAssociationType(); public void setAssociationType( Characteri...
// 1- findEvidenceByGeneNCBI Collection<EvidenceValueObject<? extends PhenotypeAssociation>> evidences = this.phenotypeAssociationManagerService .findEvidenceByGeneNCBI( this.geneNCBI ); assertNotNull( evidences ); assertEquals( 1, evidences.size() ); EvidenceVal...
52507351_18
class QueryUtils { public static String discoverTablespace(String defaultTableSpace, String query) { if (query == null) { return defaultTableSpace; } final Matcher matcher = TABLE_SPACE_NAME_PATTERN.matcher(query); /* A find will be used, no trim is needed */ i...
String defaultTableSpace = TableSpace.DEFAULT; String theTableSpace = "myts"; assertEquals(defaultTableSpace, QueryUtils.discoverTablespace(defaultTableSpace, "update test")); assertEquals(defaultTableSpace, QueryUtils.discoverTablespace(defaultTableSpace, "")); assertEquals(theT...
52509220_290
class Paths { @UserFunction @Description("apoc.path.combine(path1, path2) - combines the paths into one if the connecting node matches") public Path combine(@Name("first") Path first, @Name("second") Path second) { if (first == null) return second; if (second == null) return first; ...
TestUtil.testCall(db, "MATCH p1 = (a:A)-[:NEXT]->(b:B), p2 = (b)-[:NEXT]->() RETURN apoc.path.combine(p1,p2) as p",(row) -> assertPath(row, 2, "A", "C")); TestUtil.testCall(db, "MATCH p1 = (a:A)-[:NEXT]->(b:B) RETURN apoc.path.combine(p1,null) as p",(row) -> assertPath(row, 1, "A", "B")); TestUt...
52531953_1
class StudyDao extends BaseDao<Study> { @Override public void persist(Study entity) { persistUsersIfNecessary(entity.getAdministrators()); persistUsersIfNecessary(entity.getParticipants()); assert entity.getAuthor() != null; super.persist(entity); } @Autowired public S...
final Study study = Generator.generateStudy(true); study.setAuthor(author); assertNull(study.getKey()); executeInTransaction(() -> studyDao.persist(study)); assertNotNull(study.getKey()); final Study result = studyDao.findByKey(study.getKey()); assertNotNull(resu...
52565845_4
class PaginationDo implements Serializable { public void setTotalRowCnt(int totalRowCnt) { this.totalRowCnt = totalRowCnt; setPageNums(null); } public PaginationDo(); public PaginationDo(int pageNumCount, int rowCntPerPage); public int getCurrentPageNum(); public void setCur...
PaginationDo pagination = new PaginationDo(5, 50); assertThat("有効判定 no", pagination.isEnabled(), is(false)); pagination.setTotalRowCnt(0); assertThat("有効判定 yes", pagination.isEnabled(), is(true)); } }
52597910_0
class QualityConverter { public static short toShort(final byte[] value) { final byte[] ba = reverseAllBitsAndBytes(value); final ByteBuffer bb = ByteBuffer.wrap(ba); final short s = bb.getShort(); LOGGER.debug("Converting byte array [{}], reversed [{}] into short [{}]", toString(...
// arrange final byte[] ba = new byte[2]; ba[0] = (byte) 193; ba[1] = (byte) 0; // act final short s = QualityConverter.toShort(ba); // assert assertEquals(131, s); } }
52628247_15
class Utils { public static double stdev(double[] a) { double m = mean(a); double sumsq = 0; for (double v : a) sumsq += (v-m)*(v-m); return Math.sqrt(sumsq / a.length); } public static double median(ArrayList<Double> arrList); public static double mean(double[] x); ...
assertThat(Utils.stdev(new double[]{42}), is(0d)); } }
52632533_7
class BaggageImpl { public BaggageImpl split() { Handlers.preSplit(this); Map<ByteString, SetMultimap<ByteString, ByteString>> copiedData = Maps.newHashMapWithExpectedSize(contents.size()); for (ByteString namespace : contents.keySet()) { copiedData.put(namespace, HashMultimap.c...
BaggageImpl b = new BaggageImpl(); ByteString myname = ByteString.copyFrom("namespace".getBytes()); ByteString myname2 = ByteString.copyFrom("namespace2".getBytes()); ByteString mybytes = ByteString.copyFrom("k1".getBytes()); ByteString mybytes2 = ByteString.copyFrom("k2".getByte...
52679228_0
class MessagingConnectionService implements ConnectionListener { public void notifyMissionMessageReceivers(Message message) { try { for (MessageReceiver receiver : missionMessageReceivers) { switch (message.getPayloadType()) { case AssignMission: ...
AssignMissionMessage assignMissionMessage = new AssignMissionMessage(); MissionDto mission = new MissionDto(); assignMissionMessage.setMission(mission); String messageStr = messageConverter.parseMessageToString(assignMissionMessage); JsonBasedMessageConverter jsonBasedMessageCo...
52689062_0
class SketchyMovingMAD implements OutlierAlgorithm { public SketchyMovingMAD() { } public SketchyMovingMAD(); public SketchyMovingMAD(OutlierConfig config); public SketchyMovingMAD withConfig(OutlierConfig config); public Map<String, Distribution.Context> getMedianDistributions(); publ...
Random r = new Random(0); List<DataPoint> points = new ArrayList<>(); DescriptiveStatistics stats = new DescriptiveStatistics(); DescriptiveStatistics medianStats = new DescriptiveStatistics(); OutlierConfig config = JSONUtil.INSTANCE.load(madConfig, OutlierConfig.class); ...
52732011_3
class ByteArrayUtil { public static String asCharDetail(final byte b) { if (b < ' ' || (b & 0xFF) > 127) { // add hex value (always two digits) final String hex = Integer.toHexString(b & 0xFF); if (hex.length() < 2) { return SPECIAL_CHAR + "0" + hex; } else { return SPECIAL_CHAR + he...
fail("Not yet implemented"); } }
52774196_41
class DefaultKeyStorage implements KeyStorage { @Override public Set<String> names() { Entries entries = load(); return entries.keySet(); } public DefaultKeyStorage(); public DefaultKeyStorage(String directoryName, String fileName); @Override public void delete(String keyName); @Override publ...
Set<String> names = storage.names(); assertNotNull(names); assertTrue(names.isEmpty()); } }
52800193_1
class AutoCaptureSource { static Optional<AutoCaptureSource> newInstance(String value, SourceType type) { boolean isSupportedType = type == SourceType.DEFAULT_PATH || type == SourceType.FILE; Path path = type == SourceType.DEFAULT_PATH ? Paths.get(HoverflyConstants.DEFAULT_HOVERFLY...
Optional<AutoCaptureSource> autoCaptureSource = AutoCaptureSource.newInstance("test-service-https.json", HoverflySimulate.SourceType.CLASSPATH); assertThat(autoCaptureSource).isNotPresent(); } }
52956887_17
class Utils { public static int getBitRange(final int b, final int s, final int n) { return (((b & MASK) >> (s & MASK)) & ((1 << (n & MASK)) - 1)) & MASK; } private Utils(); public static byte[] concatByteArray(final byte[] a, final byte[] b); public static int mergeBytes...
int b = 1; int s = 0; int n = 1; int expResult = 1; int result = Utils.getBitRange(b, s, n); assertEquals(expResult, result); } }
52997044_6
class IdentityFactory { public static UserPasswordIdentity createFromUserPassword(String user, String password) { return new UserPasswordIdentity(user,password); } private IdentityFactory(); public static TokenIdentity createFromToken(String token); } class IdentityFactoryTest { @Test...
UserPasswordIdentity identity = IdentityFactory.createFromUserPassword("USER", null); Assert.assertThat(identity.getUsername(), equalTo("USER")); Assert.assertThat(identity.getPassword(), nullValue()); } }
52999284_1
class MapRedStatsLogModule extends BaseLogModule { @VisibleForTesting static String toJson(Counters counters) throws SerializationException { ArrayNode countersJsonNode = JsonNodeFactory.instance.arrayNode(); ArrayNode groupsJsonNode = JsonNodeFactory.instance.arrayNode(); for (Group group: counters) ...
Counters counters = new Counters(); counters.incrCounter("SomeCounterGroupName", "SomeCounterName", 3); String json = MapRedStatsLogModule.toJson(counters); assertEquals( "[{\"groupName\":\"SomeCounterGroupName\",\"counters\":[{\"counterNa" + "me\":\"SomeCounterName\",\"value\":3}]}]",...
53002524_6
class RxFunctions { public static <T> Func1<T, Boolean> not(final Func1<T, Boolean> func1) { return new Func1<T, Boolean>() { @Override public Boolean call(T t) { return !func1.call(t); } }; } private RxFunctions(); public static Fu...
User retired = new User("bla", "bla", 90, 10); Assert.assertEquals(!IS_RETIRED.call(retired), RxFunctions.not(IS_RETIRED).call(retired)); } }
53019432_1
class RegularUtil { public static boolean isInt(String s) { return INT.matcher(s).matches(); } public static boolean isIpAddress(String ip); } class RegularUtilTest { @Test public void testIsInt() throws Exception {
assertEquals(true, (RegularUtil.isInt("45645"))); assertEquals(false, (RegularUtil.isInt("23.1"))); } }
53073438_7
class XGH { public Axiom axiom(int number) { if (number < 1 || number > axioms.size()) { throw new IllegalArgumentException(String.format("Axiom %d is not defined", number)); } return axioms.get(number - 1); } public XGH(String lang); public XGH(); private void initialize(Locale locale)...
Spec.given(new XGH()) .expect(doing(xgh -> xgh.axiom(1)), to().succeed()) .expect(doing(xgh -> xgh.axiom(23)), to().fail()) .expect(doing(xgh -> xgh.axiom(0)), to().fail()); for (int i = 1 ; i <= 22 ; i++) { Spec.given(new XGH()) .expect(axiom(i), to().have(number(i))); ...
53084625_1
class ProxyController { @RequestMapping public void staticProxy(HttpServletRequest request, HttpServletResponse response) throws IOException, SystemException, PortalException { // /pocjsportlet/p/portletId/path String requestURI = request.getRequestURI(); String portletId = getPortletId...
mockServer.when(request("/path/to/angular.png")) .respond(response(TestUtil.getFileContents("website/angular.png")) .withHeader(new Header(HttpHeaders.Names.CONTENT_TYPE, "image/png"))); MockHttpServletResponse response = new MockHttpServletResponse(); Mo...
53088165_1
class BeanBoxUtils { public static Constructor<?> getConstructor(Class<?> clazz, Class<?>... paramTypes) {// NOSONAR try { return clazz.getConstructor(paramTypes); } catch (SecurityException e) { throw new IllegalStateException("Security exception found for Constructor: " + e.getMessage()); } catch (NoSuc...
BeanBox box = class2BeanBox(Constinject1.class); Assert.assertEquals(Constinject1.class.getConstructor(), box.getConstructor()); box = class2BeanBox(Constinject2.class); Assert.assertEquals(Constinject2.class.getConstructor(String.class), box.getConstructor()); box = class2BeanBox(Constinject3.class); Ass...
53127403_391
class InstanceService { public List<Instance> findInstancesByIds(Set<Long> instanceIds) { Iterable<Instance> instances = instanceRepository.findAllById(instanceIds); return Lists.newArrayList(instances); } public InstanceService( final InstanceRepository instanceRepository, final InstanceCo...
String someAppId = "someAppId"; String someClusterName = "someClusterName"; String someDataCenter = "someDataCenter"; String someIp = "someIp"; String anotherIp = "anotherIp"; Instance someInstance = instanceService.createInstance(assembleInstance(someAppId, someClusterName, someDataCen...
53169994_0
class MainPresenter { void getFitnessData() { fitnessSessionDataList.clear(); view.showLoading(); DataReadRequest.Builder dataReadRequestBuilder = getDataReadRequestBuilder(); DataReadRequest dataReadRequest = dataReadRequestBuilder.build(); DataReadRequest dataReadRequestS...
doReturn(Observable.empty()).when(history).readBuckets(Matchers.any(DataReadRequest.class)); mainPresenter.getFitnessData(); ArgumentCaptor<List> fitnessSessionDataCaptor = ArgumentCaptor.forClass(List.class); verify(mainView, times(1)).onFitnessSessionDataLoaded(fitnessSessionDataCap...
53222598_8
class RedisDBHandler implements IDBHandler { @Override public boolean update(String key, int sequenceId, byte[] value) { boolean isUpdated = false; try { if (hasKey(key)) { byte[] serializedKey = serialize(key); byte[] serializedSequenceId = serialize(sequenceId); if (redis.hexists(serializedKey, ...
byte[] serializedValue = "foo".getBytes(); String key = dbHandler.store(serializedValue); boolean b = dbHandler.update(key, 0, "foobar".getBytes()); assertTrue(b); } }
53225573_7
class OperatorConditionalBinding implements Observable.Operator<T, T> { @Override public Subscriber<? super T> call(final Subscriber<? super T> child) { return new Subscriber<T>(child) { @Override public void onCompleted() { Assertions.assertUiThread(); ...
OperatorConditionalBinding<String, Object> op = new OperatorConditionalBinding<String, Object>( new Object(), UtilityFunctions.alwaysFalse()); Subscriber<? super String> sub = op.call(subscriber); sub.onNext("one"); sub.onNext("two"); sub.onCompleted(); s...
53246590_0
class StaticGsonProcessor extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (annotations.isEmpty()) { return true; } long t0 = System.currentTimeMillis(); StaticGsonContext context =...
JavaFileObject modelFile = JavaFileObjects.forResource("Book.java"); assert_().about(javaSource()) .that(modelFile) .processedWith(new StaticGsonProcessor()) .compilesWithoutWarnings(); } }
53251585_1
class LocationUtils { static boolean isInside(LocationUSourceData data, Location location) { for (LatLong center : data.locations) { if (inside(center, data.radius, location.getLatitude(), location.getLongitude())) { return true; } } return false; ...
Assert.assertTrue( LocationUtils.inside(LatLong.fromString("50, 50"), 150000, LatLong.fromString("50, 51")) ); Assert.assertFalse( LocationUtils.inside(LatLong.fromString("50, 50"), 100000, LatLong.fromString("50, 51")) ); } }
53265801_2
class RxAppStateMonitor { @NonNull public static Observable<AppState> monitor(@NonNull Application app) { return Observable.create(new AppStateObservableOnSubscribe(new DefaultAppStateRecognizer(app))); } } class RxAppStateMonitorTest { @Test public void emitsAppStates() {
FakeApplication fakeApplication = new FakeApplication(); TestObserver<AppState> subscriber = TestObserver.create(); RxAppStateMonitor.monitor(fakeApplication).subscribe(subscriber); fakeApplication.goForeground(); fakeApplication.goBackground(); subscriber.assertValues(FOREGROUND, BACKGROUND);...
53275454_0
class Deserializer { public Resource createObjectFromString(String resourceName) throws InstantiationException, IllegalAccessException, NotExtendingResourceException { Class objectClass = registeredClasses.get(resourceName); try { return (Resource) objectClass.newInstance(); } catch (InstantiationE...
HashMap<String, Class> mockMap = mock(HashMap.class); when(mockMap.get("articles")).thenReturn(Article.class); Deserializer.setRegisteredClasses(mockMap); Deserializer deserializer = new Deserializer(); Resource resource = deserializer.createObjectFromString("articles"); assertNotNull(resource...
53291241_5
class VeraCliArgParser { public boolean isHelp() { return this.help; } public boolean showVersion(); public boolean listProfiles(); public boolean isVerbose(); public int maxFailuresDisplayed(); public int maxFailures(); public boolean fixMetadata(); public String prefix(); public String saveFolder(); pu...
// Test default is false assertFalse(VeraCliArgParser.DEFAULT_ARGS.isHelp()); // Test empty String[] args doesn't change that VeraCliArgParser parser = new VeraCliArgParser(); JCommander jCommander = initialiseJCommander(parser); jCommander.parse(new String[] {}); ...
53291713_0
class DateUtils { public static String prettyTime(String timeInMillisec) { if (timeInMillisec == null) { return ""; } return prettyTime(Long.parseLong(timeInMillisec), OmniNotes.getAppContext().getResources().getConfiguration().locale); } public static String getString(long date, String format); public s...
long now = Calendar.getInstance().getTimeInMillis(); String prettyTime = DateUtils.prettyTime(now, Locale.ENGLISH); Assert.assertEquals(prettyTime.toLowerCase(), "moments ago"); prettyTime = DateUtils.prettyTime(now + 10 * 60 * 1000, Locale.ENGLISH); Assert.assertEquals(prettyTime.toLowerCase(), "10 minutes...