id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
53330030_1
class StdSchedulerFactory implements SchedulerFactory { static Properties overrideWithSysProps(Properties props, Logger log) { Properties sysProps = null; try { sysProps = System.getProperties(); } catch (AccessControlException e) { log.warn( "Skippin...
Properties p = new Properties(); p.setProperty("nonsense1", "hello1"); p.setProperty("nonsense2", "hello2"); System.setProperty("nonsense1", "boo1"); String osName = System.getProperty("os.name"); Properties q = StdSchedulerFactory.overrideWithSysProps(p, NOPLogger.NOP_LOGGER); assert...
53336998_2
class GetPeople extends RosieUseCase { public PaginatedCollection<Person> getAllPeopleInCache() { Collection<Person> allPeople; try { allPeople = peopleRepository.getAll(ReadPolicy.CACHE_ONLY); } catch (Exception e) { allPeople = new ArrayList<>(); } ...
//given Collection<Person> nonEmptyCacheList = new ArrayList<>(); nonEmptyCacheList.add(new Person(PERSON_NAME, PERSON_GENDER, PERSON_BIRTH_YEAR, PERSON_URL)); PaginatedCollection<Person> expectedPeopleList = PaginatedCollectionUtils.createPaginatedCollection( nonEmptyCac...
53354223_6
class InternalIdToLongIterator implements EdgeIterator, ReusableInternalIdToLongIterator { public InternalIdToLongIterator(LongToInternalIntBiMap nodesIndexMap, EdgeTypeMask edgeTypeMask) { this.nodesIndexMap = nodesIndexMap; this.edgeTypeMask = edgeTypeMask; this.currentNodeId = 0; } public Intern...
LongToInternalIntBiMap nodesToIndexBiMap = new ArrayBasedLongToInternalIntBiMap(10, 0.5, -1, -1L, nullStatsReceiver); int n = 7; int[] expectedIndices = new int[n]; long[] expectedEntries = new long[n]; for (int i = 0; i < n; i++) { expectedIndices[i] = nodesToIndexBiMap.put(i); ...
53367115_69
class GraphResourceRepository extends GraphGenericRepository<ResourceEntity> implements ResourceRepository, ResourceHierarchicalRepository { @Override public <S extends ResourceEntity> S findOne(final Example<S> example) { throw new UnsupportedOperationException(MESSAGE); } @Override public Re...
List<ResourceEntity> resourceEntities = new ArrayList<>(); ResourceEntity resourceEntity1 = persistRandomResourcetoZone1AndAssert(); Long resourceId1 = resourceEntity1.getId(); resourceEntities.add(resourceEntity1); ResourceEntity resourceEntity2 = persistRandomResourcetoZone1A...
53430304_5
class RealWhorlwind extends Whorlwind { @Override public Observable<ReadResult> read(@NonNull String name) { return Observable.create(new FingerprintAuthOnSubscribe(fingerprintManager, storage, name, // readerScanning, dataLock, this)); } RealWhorlwind(Context context, FingerprintManager fingerpri...
shadowContext.grantPermissions(USE_FINGERPRINT); when(fingerprintManager.isHardwareDetected()).thenReturn(true); when(fingerprintManager.hasEnrolledFingerprints()).thenReturn(true); Observable<ReadResult> read = whorlwind.read("a"); shadowContext.denyPermissions(USE_FINGERPRINT); try { r...
53431695_1
class Utils { public static float getHue(float value, float min, float max, int minColor, int maxColor) { float hue; if (min == max || value <= min) { hue = minColor; } else if (value > max) { hue = maxColor; } else { float colorValue = (value - m...
float hue = Utils.getHue(0, 0, 100, 120, 360); Assert.assertEquals(hue, 120, 0.1); hue = Utils.getHue(4, 1, 7, 90, 180); Assert.assertEquals(hue, 135, 0.1); } }
53478785_2
class LocalBroadcaster implements DownloadListener { public void onDownloadEnd(String torrentFile, int downloadState) { broadcast(DownloadEndBroadcast.createIntent(torrentFile, downloadState)); } public LocalBroadcaster(Context context); public void onDownloadStart(String torrentFile); p...
final String torrentFile = "file"; final int downloadState = 42; LocalBroadcaster localBroadcaster = new LocalBroadcaster(RuntimeEnvironment.application); localBroadcaster.onDownloadEnd(torrentFile, downloadState); LocalBroadcastManager localBroadcastManager = LocalBroadcastManag...
53502006_0
class TemplateInjector { public String injectToTemplate(String template, Object scope) { Mustache mustache = mustacheFactoryUnescapeHtml.compile(new StringReader(template), "template"); StringWriter result = new StringWriter(); try { mustache.execute(result, new Object[] { scop...
String varName = "testVar"; String varValue = "testVarValue"; String template = String.format("{{#lowercase}}{{%s}}{{/lowercase}}", varName); String result = templateInjector.injectToTemplate(template, singletonMap(varName, varValue)); assertThat(result).isEqualTo(varValue.toLow...
53510819_2
class RxWear { public void resetDefaultTimeout() { timeoutTime = null; timeoutUnit = null; } public RxWear(@NonNull Context ctx); public void setDefaultTimeout(long time, @NonNull TimeUnit timeUnit); public Completable checkConnection(); public Single<GoogleApiClient> getWear...
rxWear.setDefaultTimeout(TIMEOUT_TIME, TIMEOUT_TIMEUNIT); rxWear.resetDefaultTimeout(); assertNull(rxWear.timeoutTime); assertNull(rxWear.timeoutUnit); } }
53511222_34
class RecentEmojiManager implements RecentEmoji { @Override @SuppressWarnings({ "PMD.AvoidDeeplyNestedIfStmts", "checkstyle:nestedifdepth" }) @NonNull public Collection<Emoji> getRecentEmojis() { if (emojiList.size() == 0) { final String savedRecentEmojis = sharedPreferences.getString(RECENT_EMOJIS, ""); ...
assertThat(recentEmojiManager.getRecentEmojis()).isEmpty(); } }
53561724_0
class PostgreSQLJournal extends AbstractService implements Journal { @SneakyThrows @Override public <T extends Entity> Optional<T> get(UUID uuid) { Optional<T> result; Connection connection = dataSource.getConnection(); refreshConnectionRegistry(connection); PreparedStatemen...
assertEquals(serializationResult(TestClass.builder().pByte(Byte.MIN_VALUE).build()).pByte(), Byte.MIN_VALUE); assertEquals(serializationResult(TestClass.builder().pByte(Byte.MAX_VALUE).build()).pByte(), Byte.MAX_VALUE); assertEquals((byte)serializationResult(TestClass.builder().oByte(Byte.MIN_V...
53566183_5
class Functions { public static <T> Function<T,Integer> unpartitioned() { return zero(); } @SuppressWarnings("unchecked") public static UnaryOperator<T> identity(); @SuppressWarnings("unchecked") public static Function<T,Integer> zero(); public static void closeFunction(Object function); ...
String s = "hello"; assertEquals(Integer.valueOf(0), unpartitioned().apply(s)); Integer i = 42; assertEquals(Integer.valueOf(0), unpartitioned().apply(i)); Object o = new Object(); assertEquals(Integer.valueOf(0), unpartitioned().apply(o)); } }
53590096_30
class DateUtils { public static String dateToStringWithFormat(Date dateToString, String dateFormat) { if (dateToString != null) { DateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); return simpleDateFormat.format(dateToString); } else { return null; } } private DateUti...
String date = DateUtils.dateToStringWithFormat(null, DateFormatConstants.DATE_FORMAT_TIME); assertNull(date); } }
53592496_0
class GetImageFragment extends WolmoFragment<T> { protected void selectImageFromGallery( @NonNull final OnImageReturnCallback onImageReturnCallback) { permissionManager.requestPermission(this, new PermissionListener() { @Override public void onPermissionsGranted() { ...
GetImageFragment.OnImageReturnCallback callbackMock = mock(GetImageFragment.OnImageReturnCallback.class); doAnswer(invocation -> { ((PermissionListener) invocation.getArgument(1)).onPermissionsGranted(); return null; }).when(mPermissionManagerMock).requestPermission(any(...
53645841_12
class SendMessageHelper { static long getNextSendingInMillis(Record record, long currentTimeMillis) { int delta = Const.MILLIS_PER_MINUTE; // используется, чтобы избежать повторной отправки в одно время. int repeatType = record.getRepeatType(); Calendar calendar = Calendar.getInstance(); ...
mRecord.setRepeatType(Record.REPEAT_TYPE_DAYS_IN_WEEK); mRecord.setDayOfWeek(mTodayOfWeek, false); mRecord.setDayOfWeek(Calendar.WEDNESDAY, true); mRecord.setHour(12); mRecord.setMinute(15); long sendingInMillis = SendMessageHelper.getNextSendingInMillis(mRecord, mTodayT...
53684862_11
class BitmapUtils { public static void recycleBitmap(Bitmap bitmap){ if (bitmap != null && !bitmap.isRecycled()) bitmap.recycle(); } private BitmapUtils(); public static void recycleBitmapFromImageView(ImageView imageView); public static byte[] bitmapToBytes(Bitmap bitmap); ...
try{ Bitmap bitmap = null; BitmapUtils.recycleBitmap(bitmap); }catch(Exception e){ fail("no exception should be thrown"); } } }
53690584_2
class ExpressionTokenizer { protected boolean isQuoted(String str, int pos) { int start = str.indexOf("\""); if(start < 0 || pos < start) { return false; } int end = str.indexOf("\"", start + 1); if(end < 0) { return false; } if(pos <=...
String str = "01234\"67890"; ExpressionTokenizer t = new ExpressionTokenizer(str); assertFalse(t.isQuoted(str, 11)); assertFalse(t.isQuoted(str, 15)); } }
53691181_2
class ScrubGestureDetector implements View.OnTouchListener { @Override public boolean onTouch(View v, MotionEvent event) { if (!enabled) return false; final float x = event.getX(); final float y = event.getY(); switch (event.getActionMasked()) { case MotionEvent.ACT...
final long downTime = 0; // make just under the timeout final long moveTime = ScrubGestureDetector.LONG_PRESS_TIMEOUT_MS - 1; // make just over the touch-slop final float scrubX = 9, scrubY = 9; final MotionEvent down = getMotionEvent(MotionEvent.ACTION_DOWN, 0, 0, 0, 0);...
53703548_16
class AuthenticationProviderConfigurer extends SecurityConfigurerAdapter<Void, ServiceProviderBuilder> { @Override public void init(ServiceProviderBuilder builder) throws Exception { authenticationProviderBean = builder.getSharedObject(SAMLAuthenticationProvider.class); config = builder.getShar...
AuthenticationProviderConfigurer configurer = new AuthenticationProviderConfigurer(); configurer.init(builder); verify(builder).getSharedObject(eq(SAMLAuthenticationProvider.class)); verify(builder).getSharedObject(eq(SAMLSSOProperties.class)); } }
53723623_0
class DefaultErrorBundle implements ErrorBundle { @Override public String getErrorMessage() { return (exception == null) ? DEFAULT_ERROR_MSG : this.exception.getMessage(); } public DefaultErrorBundle(Throwable exception); @Override public Throwable getException(); private DefaultErrorBundle defaultEr...
String message = "a message"; when(mockException.getMessage()).thenReturn(message); String result = defaultErrorBundle.getErrorMessage(); Assert.assertEquals(message, result); verify(mockException).getMessage(); } }
53726669_15
class PasswordEditText extends AppCompatEditText { public void togglePasswordVisibility() { setPasswordVisible(!passwordVisible); } public PasswordEditText(Context context); public PasswordEditText(Context context, AttributeSet attrs); public PasswordEditText(Context context, AttributeSet attrs, int ...
AttributeSet attrs = createCustomIconsAttributeSet(); PasswordEditText actual = new PasswordEditText(RuntimeEnvironment.application, attrs, 0); actual.togglePasswordVisibility(); assertThat(actual).hasToggle(R.drawable.ic_icon_square); } }
53789166_0
class CollisionChecker { public boolean check(long time, int location) { if(currentInstant != time) { currentInstant = time; bitSet.clear(); } if(bitSet.get(location)) { return false; } bitSet.set(location); return true; } ...
CollisionChecker collisionChecker = new CollisionChecker(); Assert.assertTrue(collisionChecker.check(100, 1)); Assert.assertFalse(collisionChecker.check(100, 1)); for (int i = 0; i < 1000; i++) { Assert.assertTrue(collisionChecker.check(101, i)); Assert.assertFals...
53823931_0
class KryoSerializer extends Serializer<T> implements Serializable { @Override public T copy(Kryo kryo, T original) { try { preSerialize(original); try(CopyStream output = new CopyStream(4096)) { HTMObjectOutput writer = serializer.getObjectOutput(output); ...
Tuple expected = new Tuple(42); Tuple actual = kryo.copy(expected); assertNotSame(expected, actual); assertEquals(expected, actual); } }
53846545_0
class SpaceSaving { public boolean inc(long key) { // find location for key int index = 0; FingerPrintAux hash = indices.getHash(key); // find current location of key in set index = (int) indices.getOrDefault(hash, -1); // if key is not in set if (index < argmin) { index = Math.max(0, argmin-1); /...
long key = 611; int n = 1<<10; int size = 1<<5; SpaceSaving ss = new SpaceSaving(n, size, 10); // increment same key size-1 times and make sure there are no overflows. for (int i=0; i < size - 1;++i) { System.out.println(i); assertEquals(ss.bound(key), i); assertFalse(ss.inc(key)); } // increme...
53877122_9
class TurbolinksSession implements TurbolinksScrollUpCallback { public Activity getActivity() { return activity; } private TurbolinksSession(final Context context); public static TurbolinksSession getNew(Context context); public static TurbolinksSession getDefault(Context context); p...
assertThat(turbolinksSession.getActivity()).isNull(); } }
53932231_31
class Parser { public List<PatternRule> parse() { if (used) { throw new IllegalStateException("Parser.parse can only be called once per instance"); } used = true; return rules(); } public Parser(final List<Token> tokens, final Consumer<? super DslError> errorReporter); public Token getSubFunctionIde...
final List<Token> tokens = Arrays.asList( new Token(EXISTENCE, "existence", 0), new Token(IDENTIFIER, "test", 0), new Token(COLON, ":", 0), new Token(IDENTIFIER, "x", 0), new Token(PLUS, "+", 0), new Token(IDENTIFIER, "y", 0), new Token(ARROW, "->", 0), new Token(EOF, "", 0) ); fin...
53940095_2
class ScaldingInterpreter extends Interpreter { @Override public InterpreterResult interpret(String cmd, InterpreterContext contextInterpreter) { logger.info("Running Scalding command '" + cmd + "'"); if (cmd == null || cmd.trim().length() == 0) { return new InterpreterResult(Code.SUCCESS); } ...
assertEquals(InterpreterResult.Code.SUCCESS, repl.interpret("\"123\"\n.toInt", context).code()); } }
53950433_0
class MTIssueRegistry extends IssueRegistry { @Override public synchronized List<Issue> getIssues() { System.out.println("==== MT lint start ===="); return Arrays.asList( LogDetector.ISSUE, HashMapForJDK7Detector.ISSUE ); } private MTIssueRegistr...
int size = mtIssueRegistry.getIssues().size(); assertThat(size).isEqualTo(2); } }
53966381_4
class LandscapeWatcher { @EventListener({ HeartbeatEvent.class }) public void discoverLandscape() { logger.debug("Discovering landscape"); List<String> applications = this.discoveryClient.getServices() .stream() .filter(this.applicationFilters) .collect(Collectors.toList()); Catalog catalog = thi...
when(this.discoveryClient.getServices()).thenReturn(Collections.singletonList("a")); when(this.catalog.getApplications()).thenReturn(Collections.singletonList("a")); ServiceInstance serviceInstance = new DefaultServiceInstance("a-1", "a", "host", 8080, false); when(this.discoveryClient.getInstances("a")).thenRe...
53976910_33
class RegexToGramQueryTranslator { public static GramBooleanQuery translate(String regex) throws com.google.re2j.PatternSyntaxException { return translate(regex, TranslatorUtils.DEFAULT_GRAM_LENGTH); } public static GramBooleanQuery translate(String regex, int gramLength); private static Rege...
String regex = "abc+"; GramBooleanQuery exactQuery = RegexToGramQueryTranslator.translate(regex); GramBooleanQuery expectedQuery = GramBooleanQuery.newLeafNode("abc"); printTranslatorResult(regex); Assert.assertEquals(expectedQuery, exactQuery); Assert.assertEquals(ex...
54034223_9
class RestUtils { public static <T> T post(URI url, Object request, Class<T> responseType) { Assert.notNull(url); Assert.notNull(responseType); return restTemplate.postForObject(url, request, responseType); } public static void setRestTemplate(RestTemplate restTemplate); publi...
Long id = RestUtils.post(baseUrl + "/demo/save", new Demo(2L, "sunhao"), Long.class, new Object[0]); Assert.assertEquals(2L, id.longValue()); } }
54064354_1
class IOReader { static String mimeTypeFromExtension(String path) { if (path == null || path.length() == 0) { return null; } final int indexOfDot = path.lastIndexOf('.'); if (indexOfDot == -1) { return null; } final String ext = path.subst...
assertThat(IOReader.mimeTypeFromExtension("file.zip"), is(nullValue())); assertThat(IOReader.mimeTypeFromExtension("file.abc"), is(nullValue())); } }
54069741_37
class EncoderUtils { public static List<BioAssemblyData> generateBioassemblies(StructureDataInterface structureDataInterface) { int numBioassemblies = structureDataInterface.getNumBioassemblies(); List<BioAssemblyData> outList = new ArrayList<>(); for (int i=0; i<numBioassemblies; i++) { BioAssemblyData bioa...
List<BioAssemblyData> bioAssemblyData = new ArrayList<>(); BioAssemblyData bioAssemblyOne = new BioAssemblyData("1"); bioAssemblyData.add(bioAssemblyOne); List<BioAssemblyTransformation> bioAssemblyOneTransforms = new ArrayList<>(); BioAssemblyTransformation bioassOneTransOne = new BioAssemblyTransformation()...
54086678_0
class SimpleThreadpool { private SimpleThreadpool(int threadCount) { // Increment pool count poolCount.incrementAndGet(); this.runnables = new ConcurrentLinkedQueue<>(); this.execute = new AtomicBoolean(true); this.threads = new ArrayList<>(); for (int threadIndex = ...
int runnableCount = 10; SimpleThreadpool threadpool = SimpleThreadpool.getInstance(); final AtomicInteger count = new AtomicInteger(0); Runnable r = new Runnable() { @Override public void run() { count.getAndIncrement(); } }; ...
54088253_3
class ParaList implements Serializable { public ParaList(List<StoreParas> lists) { if ( lists == null ) throw new RuntimeException("lists can not be null"); this.lists = lists; this.size = lists.size(); } public ParaList(List<StoreParas> lists); public int getSize(); pub...
public void TestParaList() { int size = 3; List<StoreParas> list = new ArrayList<StoreParas>(size); for ( int i = 0 ; i < size ; i++) { list.add( new StoreParas(OpType.Put, Key.createKey("test-"+i), new BlockValue(("test-"+i).getBytes() ,i, (short ) 0)) ); } ...
54102761_87
class SSOLogoutServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String token = req.getParameter("authToken"); if (token == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Toke...
// given HttpServletRequest request = new MockHttpServletRequest("http://localhost:8080/sso/logout", null, 0, "POST", null); // when servlet.doPost(request, response); // when , verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), eq("Toke...
54135763_1
class ClosedCaptionManagerFactory { public CaptionManager createCaptionManager(Context context) { if (androidVersion.isMarshmallowOrHigher()) { return ClosedCaptionManagerMarshmallow.newInstance(context); } else if (androidVersion.isKitKatOrHigher()) { return ClosedCaptionMa...
when(mockAndroidVersion.isKitKatOrHigher()).thenReturn(true); CaptionManager captionManager = closedCaptionManagerFactory.createCaptionManager(mockContext); assertThat(captionManager).isInstanceOf(ClosedCaptionManagerKitKat.class); } }
54149022_115
class ProductBaselinesResource { @GET @ApiOperation(value = "Get product-baseline by id", response = ProductBaselineDTO.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful retrieval of ProductBaselineDTO"), @ApiResponse(code = 401, message = "Un...
PartUsageLink partLink = new PartUsageLink(); List<PartLink> partLinks = Collections.singletonList(partLink); partLink.setComponent(partMaster); Mockito.when(productBaselineService.getBaseline(baseline.getId())) .thenReturn(baseline); Mockito.when(productService...
54189483_34
class AbstractWagon implements Wagon { @Override public final void removeSessionListener(SessionListener sessionListener) { this.sessionListenerSupport.removeSessionListener(sessionListener); } protected AbstractWagon(boolean supportsDirectoryCopy); protected AbstractWagon(boolean suppor...
this.wagon.removeSessionListener(this.sessionListener); verify(this.sessionListenerSupport).removeSessionListener(this.sessionListener); } }
54218417_0
class VoiceService { public byte[] say(VoiceParameter param) { L.debug("#say: param=" + param); if (param == null) { throw new IllegalArgumentException("param is null."); } if (StringUtils.isBlank(param.getText())) { throw new IllegalArgumentException("param...
VoiceParameter param = new VoiceParameter(); param.setText("こんにちは"); byte[] result = _s.say(param); String md5 = "6863e3bcac79948b7c2cc24283d4571f"; assertThat(DigestUtils.md5Hex(result), is(md5)); } }
54231507_31
class DecoratedOptions extends DecoratedChild<WebDriver.Options,DecoratedWebDriver> implements WebDriver.Options { @Override public WebDriver.Window window() { return new Activator<WebDriver.Window>().activate(getTopmostDecorated().createDecorated(getOriginal().window())); } public DecoratedOptions(final...
final WebDriver.Window window = mock(WebDriver.Window.class); verifyDecoratingFunction(WebDriver.Options::window, window, WebDriver.Window::maximize); } }
54240230_0
class BooleanActions { @CheckResult @NonNull public static Action1<? super Boolean> not(@NonNull final Action1<? super Boolean> a1) { return new Action1<Boolean>() { @Override public void call(Boolean aBoolean) { a1.call(Boolean.FALSE.equals(aBoolean)); ...
Action1<? super Boolean> action1 = Mockito.mock(Action1.class); Action1<? super Boolean> action2 = BooleanActions.not(action1); action2.call(true); Mockito.verify(action1).call(false); action2.call(false); Mockito.verify(action1).call(true); } }
54252267_125
class StatusLogger extends PeriodicStatusReporter { @Override public void initialize(Properties properties, QueryableStatusAggregator queryableStatusAggregator) { this.queryableStatusAggregator = queryableStatusAggregator; String periodString = properties.getProperty(REPORT_PERIOD_KEY); ...
IOException ioException = new IOException("This is an expected test exception"); Mockito.when(queryableStatusAggregator.statusReport(MOCK_QUERY)).thenThrow(ioException); statusLogger.initialize(getProperties(LogLevel.WARN), queryableStatusAggregator); statusLogger.start(); veri...
54297956_1
class MainPresenter { public void onSaveButtonClick(String note) { if (note.isEmpty()) { return; } mModel.addNoteToList(note); mView.clearNoteEditText(); mView.updateRecyclerView(mModel.getNoteList()); } public MainPresenter(MainView view, MainModel mod...
String note = "note"; presenter.onSaveButtonClick(note); verify(model).addNoteToList(note); verify(view).clearNoteEditText(); verify(view).updateRecyclerView(model.getNoteList()); } }
54311516_1
class RangeUtils { public static float getFloatValueInRange(float fromRangeMin, float fromRangeMax, float toRangeMin, float toRangeMax, float fromRangeValue) { float oldRange = (fromRangeMax - fromRangeMin); float newRange = (toRangeMax - toRangeMin); return (((fromRangeValue - fromRangeMin) * newR...
int fromMin = 0; int fromMax = 100; int toMin = 0; int toMax = 1; float result = RangeUtils.getFloatValueInRange(fromMin, fromMax, toMin, toMax, 50); Assert.assertTrue(result == 0.5f); } }
54370839_7
class ServiceDiscoveryRestEndpoint { private void publish(RoutingContext routingContext) { JsonObject json = routingContext.getBodyAsJson(); Record record = new Record(json); discovery.publish(record, ar -> { if (ar.failed()) { routingContext.fail(ar.cause()); } else { routing...
HelloService svc = new HelloServiceImpl("stuff"); ProxyHelper.registerService(HelloService.class, vertx, svc, "address"); Record record1 = EventBusService.createRecord("Hello", "address", HelloService.class, new JsonObject().put("key", "foo")); Record record2 = EventBusService.createRecord("Hello...
54371579_8
class RxPresenter extends Presenter<View> { public void add(Subscription subscription) { subscriptions.add(subscription); } public Observable<View> view(); public void remove(Subscription subscription); public void restartable(int restartableId, Func0<Subscription> factory); public voi...
RxPresenter presenter = new RxPresenter(); Subscription mock = Mockito.mock(Subscription.class); when(mock.isUnsubscribed()).thenReturn(false); presenter.add(mock); presenter.onDestroy(); verify(mock, times(1)).unsubscribe(); verify(mock, atLeastOnce()).isUnsubscr...
54417824_7
class NetworkMapper { public List<com.nilhcem.devoxxfr.data.app.model.Session> toAppSessions(@Nullable List<Session> from, @NonNull Map<Integer, com.nilhcem.devoxxfr.data.app.model.Speaker> speakersMap) { if (from == null) { return null; } return stream(from).map(session -> new...
// Given LocalDateTime startAt = LocalDateTime.now(); Session session = new Session(1, startAt, 20, Room.EXHIBITION_FLOOR.id, singletonList(10), "title", "description"); Map<Integer, com.nilhcem.devoxxfr.data.app.model.Speaker> speakersMap = new HashMap<>(); speakersMap.put(10, n...
54438413_0
class PokedexPager { public Observable<List<PokemonItem>> pokemon() { return Observable.concat(nextRequests.map(new Func1<HttpUrl, Observable<Page<PokemonItem>>>() { @Override public Observable<Page<PokemonItem>> call(HttpUrl url) { Single<Page<PokemonItem>> call = u...
PokeService service = mock(PokeService.class); when(service.firstPokemonPage()).thenReturn(Single.just(Page.create(0, null, null, Arrays.asList( PokemonItem.create("bulbasaur", HttpUrl.parse("http://url")) )))); PokedexPager pager = new PokedexPager(service); Test...
54478052_12
class SignOut { public Observable<Void> execute() { return mRepository.query(new SessionQuery.SignOut()); } public SignOut(Repository<? extends User> repository); @Mock private Repository<ExampleUser> mMockRepository; private SignOut mTarget; } class SignOutTest { @Mock p...
// Setup when(mMockRepository.query(eq(new SessionQuery.SignOut()))) .thenReturn(Observable.empty()); // Execute mTarget.execute(); // Assert verify(mMockRepository, times(1)).query(eq(new SessionQuery.SignOut())); } }
54492045_0
class Tools { public static boolean intToBool (int i) { return !(i == 0); } public static int getRandom(int min, int max); public static String getMethodName(final int depth); public static Transaction applyBIP69(Transaction transaction); public static List<TransactionSignature> getCha...
assertEquals(Tools.intToBool(1), true); assertEquals(Tools.intToBool(0), false); assertEquals(Tools.intToBool(2), true); assertEquals(Tools.intToBool(3), true); } }
54584892_4
class Schema implements AttributeContainer { public void setAttributes(List<Attribute> attributes) { attributeNamesMap.clear(); for (Attribute attribute : attributes) { String name = attribute.getName(); if (name == null) { LOG.warn("Attribute name was null, skipping name indexing");...
fail("Not yet implemented"); } }
54587242_1
class FilesArchiverFactory { public static FilesArchiver createFromURI(String uri) throws IOException { try { URI outputURI = new URI(uri); String scheme = outputURI.getScheme(); logger.info("Got scheme " + scheme + " for URI " + uri); if (scheme...
String tarFilePath = "testfolder.tar"; File tarFile = new File(tarFilePath); tarFile.delete(); FilesArchiver archiver = FilesArchiverFactory.createFromURI( tarFilePath); assertEquals("No scheme with tar extension should create a TarArchiver", archi...
54620819_7
class PackageList { @Nonnull @MustNotContainNull public List<Package> getPackages() { return this.packages; } public PackageList(@Nonnull @MustNotContainNull final File file, @Nonnull final String text, @Nonnull final ContentProvider contentProvider); @Nonnull static String removeComment(@Nonnull fi...
assertEquals(0, new PackageList(FAKE_FILE, "", STUB_CP).getPackages().size()); } }
54636367_72
class SignatureTypeResolver { static String resolveSignatureType(ValidationConclusion validationConclusion) { if (CollectionUtils.isEmpty(validationConclusion.getSignatures()) || isTstTypeContainer(validationConclusion)) { return NA; } String signatureFormat = validationConclus...
assertEquals(NA, resolveSignatureType(new ValidationConclusion())); } }
54650297_55
class Expand implements ValueExpression { @Override public ImmutableList<Value> eval(final ParseState parseState, final Encoding encoding) { final ImmutableList<Value> baseList = bases.eval(parseState, encoding); if (baseList.isEmpty()) { return baseList; } return co...
ImmutableList<Value> result = exp(ref("a"), con(SIZE)).eval(createFromByteStream(DUMMY_STREAM).add(PARSEVALUE_2).add(PARSEVALUE_1), enc()); assertEquals(2 * SIZE, result.size); for (int i = 0; i < SIZE; i++) { assertEquals(VALUE_1, result.head.asNumeric().intValueExact()); ...
54671444_27
class ByteArrayParameter extends AbstractParameter<byte[][]> { @Override public byte[][] valueIn(String text, Type type) { if (text == null) return null; String[] values = text.split(regexSplitter); if (values.length == 0) return null; byte[][] arrays = new byte[values.length][]; for (int i=0; i<values...
ByteArrayParameter bap = new ByteArrayParameter("a", "aye", " "); byte[][] values = bap.valueIn("1", null); assertNull(values); values = bap.valueIn("1 4", null); assertNull(values); values = bap.valueIn("e 7", null); assertNull(values); values = bap.valu...
54709439_5
class OIDCUserManager { public Principal updateUser(IDTokenClaimsSet idToken, UserInfo userInfo) throws XWikiException, QueryException, OIDCException { // Check allowed/forbidden groups checkAllowedGroups(userInfo); Map<String, String> formatMap = createFormatMap(idToken, userI...
this.oldcore.getConfigurationSource().setProperty(OIDCClientConfiguration.PROP_GROUPS_ALLOWED, Arrays.asList("pgroup1", "pgroup2")); this.oldcore.getConfigurationSource().setProperty(OIDCClientConfiguration.PROP_GROUPS_CLAIM, "groupclaim"); this.oldcore.getConfigurationSource().setPr...
54712998_14
class MetaWeblog { public String newPost(String blogid, Post post, boolean publish) throws XmlRpcException { if (blogid == null || post == null || post.getDateCreated() == null || post.getDescription() == null || post.getTitle() == null) { throw new IllegalArgumentException( ...
Object[] pramas = {"1", configInfo.getUserName(), configInfo.getPassword(), ReflectUtil.toXMLRPCParams(post), true}; String postId = "2"; when(xmlRpcClient.execute(anyString(), any(Object[].class))).thenReturn(postId); assertThat(metaWeblog.newPost("1", post, true)).isEqualTo(postId); ...
54755680_10
class PodcastDirectoryHelper { public static String getITunesId(Uri uri) { if (uri == null) { throw new IllegalArgumentException("uri is null"); } String id = ""; List<String> segments = uri.getPathSegments(); for (int i = 0; segments != null && i < segments.s...
Uri uri = Mockito.mock(Uri.class); when(uri.getPathSegments()).thenReturn( Arrays.asList("us", "podcast", "the-vergecast", "id430333725")); String id = PodcastDirectoryHelper.getITunesId(uri); Assert.assertEquals("430333725", id); } }
54767260_93
class GSSCallback extends SaslRpcServer.SaslGssCallbackHandler { boolean allowConnect(String principal) { String allowedPrincipals = conf.get(ServerConfig.ALLOW_CONNECT); if (allowedPrincipals == null) { return false; } String principalShortName; if (KerberosName.hasRulesBeenSet()) { ...
//Test with ruleset not set String validPrincipal = "hive@GCE.CLOUDERA.COM"; assertTrue("Authenticate valid user", callBack.allowConnect(validPrincipal)); String invalidPrincipal = "impala@GCE.CLOUDERA.COM"; assertFalse("Do not authenticate invalid user", callBack.allowConnect(invalidPrincipal)); ...
54821190_1
class PackageListActivityPresenterImpl implements IPackageListActivityPresenter { @Override public void loadPackages(boolean refresh) { if (mView != null) { mView.hideContentView(); mView.showWaitDialog(); mPackageInteractor.getInstalledPackages(refresh) ...
ArrayList<InstalledPackageHeader> toReturn = new ArrayList<>(); toReturn.add(Mockito.mock(InstalledPackageHeader.class)); when(mPackageInteractor.getInstalledPackages(false)).thenReturn(Observable.just(toReturn)); mPresenter.loadPackages(false); verify(mView, times(1)).hideCon...
54830123_3
class SwaggerBasePathRewritingFilter extends SendResponseFilter { @Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); context.getResponse().setCharacterEncoding("UTF-8"); String rewrittenResponse = rewriteBasePath(context); context.setRe...
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL); RequestContext context = RequestContext.getCurrentContext(); context.setRequest(request); MockHttpServletResponse response = new MockHttpServletResponse(); context.setResponse(response...
54853773_0
class Utils { static Class<?> messageClass(Object message) { final Class<?> messageClass = message.getClass(); if (messageClass.isAnonymousClass() || messageClass.getSimpleName().contains("-$Lambda$") // Jack || messageClass.getSimpleName().contains("$$Lambda$")) ...
SAMType instance = new SAMType() { @Override public void doSmt() { } }; assertThat(Utils.messageClass(instance), CoreMatchers.<Class<?>>equalTo(SAMType.class)); } }
54889602_1
class PipelineUtils implements Serializable { public static Set<String> extractRequiredInputColumns(Transformer[] transformers) { Set<String> inputColumns = new HashSet<>(); //Add inputs for each transformer in the input set for(Transformer t : transformers) { inputColumns.addA...
Transformer t = createTransformer(Arrays.asList("a", "b", "c"), Arrays.asList("a1", "b1", "c")); Set<String> inputs = PipelineUtils.extractRequiredInputColumns(new Transformer[] {t}); assertEquals(inputs.size(), 3); assertTrue(inputs.containsAll(Arrays.asList("a","b","c"))); asse...
54898732_267
class ConcurrentMapBasedLongToIntFunctionMemoizer extends ConcurrentMapBasedMemoizer<KEY, Integer> implements LongToIntFunction { @Override public int applyAsInt(final long value) { final KEY key = keyFunction.apply(value); return computeIfAbsent(key, givenKey -> Integer.valueOf(function.applyA...
// given final ConcurrentMap<Long, Integer> cache = new ConcurrentHashMap<>(); final LongToIntFunction function = input -> 123; final LongFunction<Long> keyFunction = Long::valueOf; // when final ConcurrentMapBasedLongToIntFunctionMemoizer<Long> memoizer = new Concurrent...
54903613_14
class CompassInstaller extends ScssFrameworkInstaller { protected void correctFilesImports(final File sourcesFolder, final int level) throws IOException { final File[] listFiles = sourcesFolder.listFiles(); if (listFiles == null) { return; } for (final File file : listFiles) { if (file.isDirectory()) { ...
// Prepare final CompassInstaller compassInstaller = new CompassInstaller( this.project, this.logger); // Level 0 final File scssFileLevel0 = this.folder.newFile(".scss"); FileUtils.write(scssFileLevel0, "@import \"compass/test0\"",Charset.defaultCharset()); ...
54904766_6
class BitcoinScriptPatternParser { public static String getPaymentDestination(byte[] scriptPubKey) { if (scriptPubKey==null) { return null; } // test if anyone can spend output if (scriptPubKey.length==0) { return "anyone"; // need to check also ScriptSig for OP_TRUE } // test if standard transaction Bitcoin...
String result = BitcoinScriptPatternParser.getPaymentDestination(new byte[0]); assertEquals( "anyone",result,"Empty script means anyone can spend"); } }
54905500_2
class StandardJsonLogger implements JsonLogger { @Override public JsonLogger list(String key, List list) { try { jsonObject.add(key, gson.toJsonTree(list)); } catch (Exception e) { jsonObject.add(key, gson.toJsonTree(formatException(e))); } return this; } public StandardJsonLo...
List<String> list = new LinkedList<>(); list.add("value1"); list.add("value2"); logger.list("someList", list).log(); Mockito.verify(this.messageConsumer).accept(Mockito.contains("\"someList\":[\"value1\",\"value2\"]")); } }
54914992_6
class SlotListImpl implements SlotList<T> { @Override public Slot find(T listener) { for (Slot slot : list) { if (slot.listener() == listener) { return slot; } } return null; } @Override public int size(); @Override public boolean add...
assertEquals(slotList.find(listeners[3]).listener(), listeners[3]); assertThat(slotList.find(null), nullValue()); assertThat(slotList.find(mock(Runnable.class)), nullValue()); } }
54973527_552
class ChangeConfig extends AbstractConsoleController { @RequestMapping(value = {"/config/sentinel/check/" + CLUSTER_NAME_PATH_VARIABLE + "/stop/{maintainMinutes}", "/config/sentinel/check/" + CLUSTER_NAME_PATH_VARIABLE + "/stop"}, method = RequestMethod.POST) public RetMessage stopSentinelCheck(Htt...
AtomicInteger expectedMinutes = new AtomicInteger(0); Mockito.doAnswer(invocation -> { Integer minutes = invocation.getArgumentAt(1, Integer.class); Assert.assertEquals(minutes.intValue(), expectedMinutes.get()); return null; }).when(configService).stopSentine...
54976745_192
class Ellipsoid { public List<Vector3d> samplePoints(final long n) throws RuntimeException { if (!samplingInitialized()) { throw new RuntimeException("Sampling has not been initialized"); } final List<Vector3d> points = isotropicSampling.calculate(new double[] { a, b, c }, n); points.forEach(this::mapTo...
// SETUP final double a = 2.0; final double b = 3.0; final double c = 4.0; final Ellipsoid ellipsoid = new Ellipsoid(a, b, c); final Vector3dc centroid = new Vector3d(4, 5, 6); ellipsoid.setCentroid(centroid); final double sinAlpha = Math.sin(Math.PI / 4.0); final double cosAlpha = Math.cos(Math.PI / ...
54995528_0
class JSONApiConverter { public <T extends Resource> JSONApiObject<T> fromJson(String jsonObject) { JSONApiObject jsonApiObject = new JSONApiObject(); try { JSONObject json = new JSONObject(jsonObject); HashMap<String, Resource> includes = new HashMap<>(); if (j...
String json = fileLoader.getContent("jsons/conversation.json"); JSONApiObject<Conversation> result = subject.fromJson(json); assertFalse(result.hasErrors()); Conversation conversation = result.getData().get(0); assertEquals("4214653", conversation.getId()); assertEqual...
55090874_3
class DateUtils { public static Date calculateNextTermBeginAfter(Date after, Date startDate, boolean excludeFirstTerm, ValidRuntimes runtimes) { if (after == null) { return null; } if (startDate == null) { return null; } if (runtimes == null) { return null; } Calendar afterCal = Calendar.getIn...
Date startDate = Date.from(ZonedDateTime .ofLocal(LocalDate.of(2016, 9, 23).atStartOfDay(), ZoneId.systemDefault(), null) .toInstant()); ValidRuntimes runtimes = new ValidRuntimes(); runtimes.firstMinRuntimeCount = 6; runtimes.firstMinRuntimeType = IntervalType.MONTHS; runtimes.followingMinRuntimeCou...
55091967_9
class RealmAssetHelper { public void loadDatabaseToStorage(String databaseFolder, String databaseName, IRealmAssetHelperStorageListener listener) throws RuntimeException { mOsUtil.clearCache(); if (mOsUtil.isEmpty(databaseName)) { throw new RuntimeException("The database name is empty"...
IRealmAssetHelperStorageListener listener = Mockito.mock(IRealmAssetHelperStorageListener.class); Mockito.when(osUtil.getCurrentDbVersion(Mockito.any(Context.class), Mockito.anyString())).thenReturn(2); Mockito.when(osUtil.getAssetsDbVersion(Mockito.any(Context.class), Mockito.anyString(), Mocki...
55123394_4
class ProductGateway { @HystrixCommand(ignoreExceptions = RemoteCallException.class) public List<ProductDto> findAllProducts() { List<ProductDto> productDtos = productClient.findAllProducts(); try { Thread.sleep(2000L); } catch (InterruptedException e) { e.print...
List<ProductDto> productDtos = productGateway.findAllProducts(); assertThat(productDtos.isEmpty(), is(false)); } }
55133617_5
class AnnotationVerifier { void verify(TypeElement type) { Validated validatedAnnotation = type.getAnnotation(Validated.class); if (validatedAnnotation == null) { abortWithError("Annotation processor for @" + Validated.class.getSimpleName() + " was invoked with a typ...
Set<Modifier> modSet = new HashSet<>(); modSet.add(Modifier.PROTECTED); Messager messager = mock(Messager.class); Elements element = mock(Elements.class); Types types = mock(Types.class); AnnotationVerifier verifier = new AnnotationVerifier(messager, element, types); ...
55151975_5
class MockWebServerPlus implements TestRule { public List<MockResponse> enqueue(String... paths) { if (paths == null) { return null; } List<MockResponse> mockResponseList = new ArrayList<>(); for (String path : paths) { Fixture fixture = Fixture.parseFrom(path, parser); MockResponse...
server.enqueue(Fixtures.SIMPLE_NO_BODY); Response response = execute(); assertFixture(response).statusCode(200); } }
55209260_2
class JSONUtil { public static <T> T toObject(String json, Class<T> clazz) { T object; try { object = mapper.readValue(json, clazz); } catch (Exception e) { LOGGER.error("JSON String Can't covert to Java Object!"); throw new RuntimeException(e); }...
JSONObject jsonObject = new JSONObject(1, "bysocket", 33); String jsonStr = JSONUtil.toJSONString(jsonObject); JSONObject resultObject = JSONUtil.toObject(jsonStr, JSONObject.class); Assert.assertEquals(jsonObject.toString(), resultObject.toString()); } }
55224431_4
class CuratorZookeeperClient extends AbstractZookeeperClient<CuratorWatcher> { @Override public List<String> getChildren(String path) { try { return client.getChildren().forPath(path); } catch (NoNodeException e) { return null; } catch (Exception e) { ...
String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; curatorClient.create(path, false); curatorClient.create(path + "/provider1", false); curatorClient.create(path + "/provider2", false); List<String> children = curatorClient.getChildren(path); assertThat(...
55231859_7
class SwaggerBasePathRewritingFilter extends SendResponseFilter { @Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); if (!context.getResponseGZipped()) { context.getResponse().setCharacterEncoding("UTF-8"); } String rewritt...
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL); RequestContext context = RequestContext.getCurrentContext(); context.setRequest(request); MockHttpServletResponse response = new MockHttpServletResponse(); context.setResponseGZipped(f...
55246521_78
class ITableRepositoryImpl implements ITableRepository { @Override public void createITable(Index index) { logger.info("Creating iTable for index: " + index.toString()); PreparedStatement createStmt = PreparedStatementFactory.getPreparedStatement(generateTableCreationSyntax(index), session)...
System.out.println("createITable"); Index index = Fixtures.createTestIndexOneField(); ITableRepository instance = new ITableRepositoryImpl(f.getSession()); boolean result = instance.iTableExists(index); assertEquals(false, result);//make sure it doesn't exist yet instanc...
55265221_1
class SortHelper { public boolean saveSortByPreference(Sort sort) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString( PREF_SORT_BY_KEY, sort.toString() ); return editor.commit(); } @Inject public SortHelper(Shared...
sort = Sort.HIGHEST_RATED; mockSortHelper = createMockSharedPreference(); mockSortHelper.saveSortByPreference(sort); assertEquals(sort, mockSortHelper.getSortByPreference()); } }
55321773_1
class HouseRepository implements HousesDomain.Repository { @Override public Observable<List<GoTHouse>> getList() { Observable<List<GoTHouse>> observable; if (localDataSource.isExpired()) { observable = networkDataSource.getAll() .doOnNext(houses -> { localDataSource.removeAll(h...
when(localDataSource.isExpired()).thenReturn(EXPIRED); when(networkDataSource.getAll()).thenReturn(getSevenHousesObservable()); repository.getList() .subscribe(list -> Assert.assertThat(list.size(), Is.is(7)), throwable -> fail()); verify(networkDataSource).getAll(); verify(localDataSource...
55332367_37
class KeyTree { public KeyTree.Node add(final String path) { KeyTree.Node parent = this.root; String key = path; if (path != null) { final int i = path.lastIndexOf('.'); if (i >= 0) { final String parentPath = path.substring(0, i); key...
final YamlConfiguration configuration = new YamlConfiguration(); final YamlConfigurationOptions options = new TestYamlConfigurationOptions(configuration); final KeyTree tree = new KeyTree(options); final String defaultnodekey = "defaultnodekey"; final String nodewithcommentkey = ...
55332995_0
class TwilioAccess { public boolean send(final String to, final String body) { // Build a filter for the MessageList final List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("Body", body)); params.add(new BasicNameValuePair("To", to)); params.a...
System.out.println("testFailCall"); TwilioAccess t = new TwilioAccess("1234567890", "1234567890", "1234567890"); assertFalse(t.send("1234567890", "This is the body")); } }
55380427_12
class SwaggerConfluenceConfig { public boolean isGenerateNumericPrefixes() { return generateNumericPrefixes; } public SwaggerConfluenceConfig(); public Integer getAncestorId(); public void setAncestorId(final Integer ancestorId); public String getAuthentication(); public void set...
assertTrue("Default Should \"true\"", swaggerConfluenceConfig.isGenerateNumericPrefixes()); } }
55402141_1
class Note extends Home { public void onClickPlus() { if (onPlus) { if (plus > 0) { plus--; } onPlus = false; } else { plus++; onPlus = true; } } } class NoteTest { @Test public void onClickPlus_cance...
Note note = new Note(); note.onPlus = true; note.onClickPlus(); assertFalse(note.onPlus); assertEquals(note.plus, 0); } }
55493271_108
class CategoricalScale { public ScaleCategory scaleRawValue(int rawValue) throws EepOutOfRangeException { for(ScaleCategory category : categories) { if(category.fallsIntoCategory(rawValue)) { return category; } } throw new EepOutOfRangeException( "Raw value ''{0}...
ScaleCategory category1 = new ScaleCategory("Category 1", 0, 49, "CAT1", 1); ScaleCategory category2 = new ScaleCategory("Category 2", 50, 99, "CAT2", 2); Set<ScaleCategory> categories = new HashSet<ScaleCategory>(); categories.add(category1); categories.add(category2); CategoricalScale scale ...
55498563_29
class RedisKeyValueStateProvider implements StateProvider { StateConfig getStateConfig(Map stormConf) throws Exception { StateConfig stateConfig = null; String providerConfig = null; ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetec...
RedisKeyValueStateProvider provider = new RedisKeyValueStateProvider(); Map<String, String> stormConf = new HashMap<>(); //stormConf.put(Config.TOPOLOGY_STATE_PROVIDER_CONFIG, "{\"keyClass\":\"String\"}"); RedisKeyValueStateProvider.StateConfig config = provider.getStateConfig(stormConf...
55504627_162
class MavenConfigurationExtractor { public static Map<String, Object> extract(Xpp3Dom root) { if (root == null) { return new HashMap<>(); } return getElement(root); } private MavenConfigurationExtractor(); private static Map<String, Object> getElement(Xpp3Dom ele...
// Given final Plugin fakePlugin = createFakePlugin("<a>" + "<b>b</b>" + "</a>"); // When final Map<String, Object> config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration()); // Then final Map<String, Object> expected...
55520127_6
class SearchParameterResolver { public RuntimeSearchParam getSearchParameterDefinition(String dataType, String path) { return this.getSearchParameterDefinition(dataType, path, (RestSearchParameterTypeEnum)null); } public SearchParameterResolver(FhirContext context); public RuntimeSearchParam...
SearchParameterResolver resolver = new SearchParameterResolver(FhirContext.forR4()); RuntimeSearchParam param = resolver.getSearchParameterDefinition("ServiceRequest", "authoredOn", RestSearchParameterTypeEnum.DATE); assertNotNull(param); assertEquals("authored", param.g...
55524213_0
class Circle implements Shape { @Override public Position getPosition() { return position; } public Circle(final int radius, final Position position); @Override public String getName(); @Override public double getArea(); } class CircleTest { @Test public void testCreateCir...
Position position = new Position(0, 1); Circle c = new Circle(1, position); final double expectedArea = 2 * Math.PI; assertEquals("Circle[area = " + expectedArea + "]", c.getDescription()); assertEquals(0, c.getPosition().getX()); assertEquals(1, c.getPosition().getY())...
55560812_32
class AlertTemplateValidator implements Validator<AlertTemplate> { @Override public void validate(AlertTemplate template) throws ValidationException { if (template.getDestination() == null || template.getDestination().trim().isEmpty()) { throw new ValidationException("Alert target can't be empty"); } if (te...
AlertTemplateValidator validator = new AlertTemplateValidator(); AlertTemplate template = new AlertTemplate((short)2); template.setMedia("http"); template.setSubject("hello"); template.setBody("hello $x"); template.setTemplateName("Template"); template.setDestination("htt://google.com"); try { valida...
55638412_70
class TurfMeasurement { public static double bearing(@NonNull Point point1, @NonNull Point point2) { double lon1 = degreesToRadians(point1.longitude()); double lon2 = degreesToRadians(point2.longitude()); double lat1 = degreesToRadians(point1.latitude()); double lat2 = degreesToRadians(point2.latitu...
Point pt1 = Point.fromLngLat(-75.4, 39.4); Point pt2 = Point.fromLngLat(-75.534, 39.123); assertNotEquals(TurfMeasurement.bearing(pt1, pt2), 0, DELTA); } }
55668012_0
class Session { synchronized int setSendingData(ByteBuffer data) { final int remaining = data.remaining(); sendingStream.write(data.array(), data.position(), data.remaining()); return remaining; } Session(int sourceIp, int sourcePort, int destinationIp, int destinationPort); synchronized void decreaseAmo...
final Session session = new Session(1, 2, 3, 4); final byte[] test = "Hello, World.".getBytes(); final ByteBuffer buffer = ByteBuffer.wrap(test); // Move position to 5 for (int i = 0; i < 5; i++) buffer.get(); session.setSendingData(buffer); final ...
55673705_10
class ConstraintsModifier { public void looseConstraints(String stateId) { looseConstraints(stateId, 0f, false); } public ConstraintsModifier(Network network); public ConstraintsModifier(Network network, ConstraintsModifierConfig config); public void looseConstraints(String stateId, flo...
ConstraintsModifier constraintsModifier = new ConstraintsModifier(network, config); try { constraintsModifier.looseConstraints(null, violations); fail(); } catch (Throwable e) { } try { constraintsModifier.looseConstraints(StateManagerConstant...
55705999_5
class ListUtils { public static void shiftItemsWithFixedDistance(List<?> list, int[] indexArray, int offset) { Arrays.sort(indexArray); int unionOffset = computeUnionOffset(list, indexArray, offset); shiftItemsDirectly(list, indexArray, unionOffset); } public static int[] toIntArra...
List<String> list = Arrays.asList("A", "B", "C", "D", "E"); ListUtils.shiftItemsWithFixedDistance(list, new int[]{1, 4}, 10); Assert.assertArrayEquals(new String[]{"A", "B", "C", "D", "E"}, list.toArray()); ListUtils.shiftItemsWithFixedDistance(list, new int[]{0, 2}, -10); Asser...
55707462_42
class SmartTitleComparator extends AbstractMovieComparator { @Override public boolean areEqual(@NonNull Movie movie1, @NonNull Movie movie2) { val title1 = movie1.getTitle(); val title2 = movie2.getTitle(); for (StringModifier m1 : modifiers) { for (StringModifier m2 : modi...
assertTrue(comparator.areEqual( new Movie("The boy, who lived", 2010), new Movie("The boy who lived", 2010) )); assertTrue(comparator.areEqual( new Movie("Independence Day: Resurgence", 2016), new Movie("Independence Day Resurgence...
55719869_4
class MuseHandler implements Closeable { void setFocusListener() { this.focusListener = new MuseDataListener() { @Override public void receiveMuseDataPacket(MuseDataPacket museDataPacket) { if (museDataPacket.getPacketType() == MuseDataPacketType.CONCENTRATION) { ...
class FocusHolder{ double focus; @Subscribe public void set(MuseHandler.FocusReading reading){ this.focus = reading.getFocus(); } } FocusHolder holder = new FocusHolder(); this.eventBus.register(holder); this.museHandler.setFoc...