id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
22917907_1
class RangeEnforcer { public String enrichQueryString(String queryString) { int maxRange = getMaxRange(); return enforceRange(enforceRange(queryString , maxRange, fromRangePattern, "from", false), maxRange, toRangePattern, "to"); } private String enforceRange(String queryString, int maxRange, Pattern...
String queryString = "?from=50&to=150"; String result = enforcer.enrichQueryString(queryString); assertThat(result).isEqualTo("?from=50&to=100"); } }
22944710_75
class DirtyCollection implements Collection<E> { @Override public boolean remove(final Object o) { if (delegate.remove(o)) { listener.onElementsRemoved(); return true; } return false; } public DirtyCollection(final Collection<E> delegate, final DirtyLis...
collection.remove("one"); verify(listener).onElementsRemoved(); assertThat(collection).containsOnly("two", "three"); } }
22944796_124
class DeleteResponseProtocolOp extends ProtocolOp { @Override public byte getType() { return OP_TYPE_DELETE_RESPONSE; } public DeleteResponseProtocolOp(int resultCode); public DeleteResponseProtocolOp(int resultCode, LocalizableMessage errorMessage); public DeleteResponseProtocolOp(int resultCode...
DeleteResponseProtocolOp deleteResponse = new DeleteResponseProtocolOp( resultCode); assertEquals(deleteResponse.getType(), OP_TYPE_DELETE_RESPONSE); } }
22944804_331
class PacketFactory { public static Packet toPacket(byte[] octets) { // for old byte array approach we may have a array longer than packet so trim ByteBuffer down to just // packet length to prevent attribute parsing below from running off the end of the packet and onto unrelated // octets....
final String hex = "01 00 00 38 0f 40 3f 94 73 97 80 57 bd 83 d5 cb" + "98 f4 22 7a 01 06 6e 65 6d 6f 02 12 0d be 70 8d" + "93 d4 13 ce 31 96 e4 3f 78 2a 0a ee 04 06 c0 a8" + "01 10 05 06 00 00 00 03"; final ByteBuffer bfr = Utils.toBuffer(hex); dumpBfr(bfr); ...
22948530_116
class SearchResource extends ResourceBase { @GET @Path("{type: "+ ALL_TYPES_PATTERN + "}/_search") @Produces(MediaType.APPLICATION_JSON) public final Response search(@PathParam("type") String type, @QueryParam("q") String query) { if (isBlank(query)) { return Response.status(Respons...
assertEquals(SC_BAD_REQUEST, searchResource.search("person", "").getStatus()); assertEquals(SC_BAD_REQUEST, searchResource.search("work", "").getStatus()); } }
22964867_319
class UpdateAction extends DatabaseAction<T> { @Override public void apply(final DatabaseTemplate databaseTemplate) throws Throwable { final T item = item(); item.setVersion(item.getVersion() - 1); try { databaseTemplate.update(item); } catch (final PersistenceExcept...
// Given final StubItem item = new StubItem(); final Long itemVersion = randomLong(); final List<PersistenceExceptionHandler<?>> persistenceExceptionHandlers = Collections.EMPTY_LIST; final UpdateAction<StubItem> updateAction = new UpdateAction<>(item, persistenceExceptionHandler...
22970701_2
class Extractor { public RawParameters extract(final HttpServletRequest request) { final Map<String, String> contextMap = extractAllVars(request, contextList, PREFIX_VARIABLE_STRING_FUNCTION, true); final Map<TestType, String> identifierMap = extractAllVars(request, identifierList, IDENTIFIER_TEST_...
final Extractor extractor = getBasicExtractor(); final String fr = "fr"; final String userId = "123456"; final MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(LANGUAGE_HEADER_NAME, fr); request.setParameter(USER_IDENTIFIER_QUERY_PARAM, us...
22974847_14
class EnumProvider implements Provider<T> { @Override public List<String> getSuggestions(String prefix) { List<String> suggestions = Lists.newArrayList(); String test = simplify(prefix); for (T entry : enumClass.getEnumConstants()) { String name = simplify(entry.name()); ...
assertThat(provider.getSuggestions(""), containsInAnyOrder("small", "medium", "large", "very_large")); assertThat(provider.getSuggestions("s"), containsInAnyOrder("small")); assertThat(provider.getSuggestions("la"), containsInAnyOrder("large")); assertThat(provider.getSuggestions("very")...
22981257_263
class DriftDetector { static double diff(double a, double b) { Preconditions.checkArgument(a >= 0 && a < 360); Preconditions.checkArgument(b >= 0 && b < 360); double value; if (a < b) value = a + 360 - b; else value = a - b; if (value > 180) ...
assertEquals(10, diff(30, 20), PRECISION); } }
23001404_7
class UpdateEntitySchemaStatusCommand extends AbstractRestCommand { @Override public String run() { LOGGER.debug("run: enitty={}, version={}, status={}", entity, version, status); Error.reset(); Error.push(getClass().getSimpleName()); Error.push(entity); Error.push(versi...
UpdateEntitySchemaStatusCommand command = new UpdateEntitySchemaStatusCommand(metadata, null, null, null, null); String output = command.run(); Assert.assertNotNull(output); } }
23020824_110
class YahooLibFinanceService implements FinanceService { static Stock toStock(yahoofinance.Stock yahooFinanceStock) { StockQuote quote = yahooFinanceStock.getQuote(); return new Stock( yahooFinanceStock.getSymbol(), yahooFinanceStock.getName(), new PriceInfo( quote.getPrice(), quote.getChangeInPe...
yahoofinance.Stock yahooFinanceStock = new yahoofinance.Stock("MS.MI"); yahooFinanceStock.setName("Mediaset"); StockQuote quote = new StockQuote("MS.MI"); quote.setPrice(BigDecimal.ONE); quote.setPreviousClose(BigDecimal.TEN); quote.setAvgVolume(10L); quote.setAsk(new BigDecimal(2)); quote.setAskSize(3...
23040996_0
class JobDetailImpl implements Cloneable, java.io.Serializable, JobDetail { @Override public int hashCode() { JobKey key = getKey(); return key == null ? 0 : getKey().hashCode(); } public JobDetailImpl(); public JobDetailImpl(String name, Class<? extends Job> jobClass); publi...
JobDetailImpl job = new JobDetailImpl(); Assert.assertThat(job.hashCode(), Matchers.is(0)); job.setName("test"); Assert.assertThat(job.hashCode(), Matchers.not(Matchers.is(0))); job.setGroup("test"); Assert.assertThat(job.hashCode(), Matchers.not(Matchers.is(0))); } }
23043801_3
class Debug { public static void init(DebugOutput... outputs) { final DebugOutput out; final int length = outputs != null ? outputs.length : 0; if (length == 0) { out = null; } else { if (length == 1) { out = ...
final DebugOutputMock mock = new DebugOutputMock(true); Debug.init(mock); for (Level level : LEVELS) { assertCall(mock, level, new RuntimeException(), "Exception here", array("Exception here")); } assertEquals(LEVELS.length, mock.size()); } }
23062279_875
class PasswordHashCreatorBCrypt extends AbstractPasswordHashCreator { @Nonnull public String createPasswordHash (@Nonnull final IPasswordSalt aSalt, @Nonnull final String sPlainTextPassword) { ValueEnforcer.notNull (aSalt, "Salt"); ValueEnforcer.isInstanceOf (aSalt, PasswordSaltBCrypt.class, "Salt"); ...
final IPasswordSalt aSalt = new PasswordSaltBCrypt (); final String sPlainTextPassword = "123456"; final PasswordHashCreatorBCrypt a = new PasswordHashCreatorBCrypt (); final String sPW1 = a.createPasswordHash (aSalt, sPlainTextPassword); final String sPW2 = a.createPasswordHash (aSalt, sPlainTextPa...
23063531_1
class WxCpMessageRouter { public WxCpXmlOutMessage route(final WxCpXmlMessage wxMessage) { if (isDuplicateMessage(wxMessage)) { // 如果是重复消息,那么就不做处理 return null; } final List<WxCpMessageRouterRule> matchRules = new ArrayList<WxCpMessageRouterRule>(); // 收集匹配的规则 for (final WxCpMessageRo...
StringBuffer sb = new StringBuffer(); WxCpMessageRouter router = new WxCpMessageRouter(null); prepare(false, sb, router); router.route(message); Assert.assertEquals(sb.toString(), expected); } }
23088989_8
class IndexUtils { public static List<IndexMetadata> parseIndexMetadata(String serializedIndexMetadata) throws IOException { ObjectMapper jsonMapper = new DefaultIndexMapper(); TypeReference<List<IndexMetadata>> typeRef = new TypeReference<List<IndexMetadata>>() {}; return jsonMapper.readVa...
List<IndexMetadata> indexMetadataList = IndexUtils.parseIndexMetadata( "[ { \"retentionType\": \"yearly\", \"retentionPeriod\": 20, \"indexName\": \"index\" }," + "{ \"retentionType\": \"monthly\", \"retentionPeriod\": 20, \"indexName\": \"0\" }," + ...
23092563_5
class ScrimRenderer { void render(Canvas canvas, SlidrPosition position, Paint paint) { switch (position) { case LEFT: renderLeft(canvas, paint); break; case RIGHT: renderRight(canvas, paint); break; case TO...
when(decorView.getTop()).thenReturn(VERTICAL_TOP); renderer.render(canvas, SlidrPosition.VERTICAL, paint); verify(canvas).drawRect(0, BOTTOM, WIDTH, HEIGHT, paint); } }
23095954_4
class HandlerScheduler extends Scheduler { @Override @SuppressLint("NewApi") // Async will only be true when the API is available to call. public Disposable scheduleDirect(Runnable run, long delay, TimeUnit unit) { if (run == null) throw new NullPointerException("run == null"); if (unit == ...
CountingRunnable counter = new CountingRunnable(); scheduler.scheduleDirect(counter, 1, MINUTES); runUiThreadTasks(); assertEquals(0, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(1, counter.get()); } }
23112526_19
class UseCase { public void execute(DisposableObserver<T> observer, Params params) { Preconditions.checkNotNull(observer); final Observable<T> observable = this.buildUseCaseObservable(params) .subscribeOn(Schedulers.from(threadExecutor)) .observeOn(postExecutionThread.getScheduler()); add...
useCase.execute(testObserver, Params.EMPTY); assertThat(testObserver.valuesCount).isZero(); } }
23123512_33
class JavassistUtils { public static List<CtField> getAllInjectedFieldsForAnnotation(CtClass clazz, Class<? extends Annotation> annotationClazz) { List<CtField> result = new ArrayList<CtField>(); CtField[] allFields = clazz.getDeclaredFields(); for (CtField field : allFields) { if (field.hasA...
//GIVEN Class<TestClassWithAnnotatedFields> aClass = TestClassWithAnnotatedFields.class; //WHEN List<CtField> allInjectedFieldsForAnnotation2 = JavassistUtils.getAllInjectedFieldsForAnnotation( ClassPool.getDefault().get(aClass.getName()), Annotation2.class); //THEN assert...
23175652_9
class ControllerBase implements Controller, JacksonJsonView, HTMLFilterProvider, JSONErrorPageRenderer, ValidatorProvider, TextRendererProvider, JacksonJsonParamReader { Filters getFilters() { return this.filters .computeIfAbsent( this.getClass(), (klass) -> { ...
try (final MyController controller = new MyController()) { final Filters filters = controller.getFilters(); assertThat(filters.getResponseFilters().size(), is(1)); } } }
23206290_28
class AppliedFix { public static Applier fromSource(CharSequence source, EndPosTable endPositions) { return new Applier(source, endPositions); } private AppliedFix(String snippet, boolean isRemoveLine); public CharSequence getNewCodeSnippet(); public boolean isRemoveLine(); final EndPosTable endPos...
AppliedFix.Applier applier = AppliedFix.fromSource("Hello", endPositions); SuggestedFix fix = SuggestedFix.replace(0, 6, "World!"); assertThrows(IllegalArgumentException.class, () -> applier.apply(fix)); } }
23227907_129
class LanguageService implements ILanguageService { @Override public PagedMetadata<LanguageDto> getLanguages(RestListRequest requestList) { try { List<Lang> sysLangs = this.getLangManager().getAssignableLangs(); List<LanguageDto> langs = this.getLanguageDtoBuilder().convert(sysL...
PagedMetadata<LanguageDto> result = languageService.getLanguages(new RestListRequest()); assertThat(result.getBody()).hasSize(2); } }
23229174_0
class StringUtil { public boolean isMD5(String test) { return test.matches("[a-fA-F0-9]{32}"); } public List<String> getMatchingLines(String textWithNewlines, String regex); public List<String> extractFromMatchingLines( String textWithNewlines, String regex); public List<String> extractFromMatchingLines( ...
StringUtil str = new StringUtil(); assertFalse(str.isMD5( "_9054025255fb1a26e4bc422aef54eb4")); assertFalse(str.isMD5( "z9054025255fb1a26e4bc422aef54eb4")); assertFalse(str.isMD5( "9054025255fb1a26e4bc422aef54eb4")); assertTrue(str.isMD5( "79054025255fb1a26e4bc422aef54eb4")); } }
23234361_0
class XSPARQLProcessor { public String process(final Reader is) throws RecognitionException, IOException, Exception { CommonTokenStream tokenStream = createTokenStream(is); if (this.numSyntaxErrors > 0) { throw new Exception("Errors for Lexer. Translation aborted."); } CommonTree tree =...
try { for (String filename : listFiles("examples")) { if (filename.endsWith(".xsparql")) { System.out.println("Testing " + filename + " ..."); Reader queryReader = loadReaderFromClasspath(filename); processor.process(queryReader); } } } catch (Recognit...
23257998_5
class XmlConfig extends Config { @Override public String getProperty(String key) { return (String) mConfiguration.getProperty(key); } public XmlConfig(); public XmlConfig(XmlConfig parent, HierarchicalConfiguration config); public XmlConfig(File file); @Override public boolean ...
assertTrue(mConfig.hasProperty("test-property")); assertEquals("Hello world!", mConfig.getProperty("test-property")); } }
23260390_75
class SimonBeanUtils { public void setProperty(Object target, String property, Object value) { NestedResolver resolver = new NestedResolver(target, property); if (value instanceof String) { convertStringValue(resolver.getNestedTarget(), resolver.getProperty(), (String) value); } else { setObjectValue(res...
SeveralSettersIntBean bean = new SeveralSettersIntBean(); simonBeanUtils.setProperty(bean, "prop", "123"); Assert.assertEquals(bean.getIntVal(), 123); } }
23304527_39
class CSSNumberHelper { @Nullable public static CSSSimpleValueWithUnit getValueWithUnit (@Nullable final String sCSSValue) { return getValueWithUnit (sCSSValue, true); } private CSSNumberHelper(); @Nullable public static ECSSUnit getMatchingUnitInclPercentage(@Nonnull final String sCSSValue); @Nul...
assertEquals (new CSSSimpleValueWithUnit (50, ECSSUnit.PERCENTAGE), CSSNumberHelper.getValueWithUnit ("50%", true)); assertEquals (new CSSSimpleValueWithUnit (50, ECSSUnit.LENGTH_MM), CSSNumberHelper.getValueWithUnit ("50mm", true)); assertEquals (new CSSSimpleValueWithUnit (50, ECSSUnit.LENGTH_CM), CSSNumb...
23338118_10
class BoonServiceMethodCallHandler implements ServiceMethodHandler { @Override public void shutdown() { queueCallBackHandler.queueShutdown(); } public BoonServiceMethodCallHandler(final boolean invokeDynamic); @Override public Response<Object> receiveMethodCall(MethodCall<Object> methodC...
class MyService { boolean called; @QueueCallback(QueueCallbackType.SHUTDOWN) private void shutdown() { called = true; } } MyService myService = new MyService(); final BoonServiceMethodCallHandler boonServiceMethodCal...
23342644_5
class SixMonthlyExpiryDayValidator extends ExpiryDayValidator { protected int plusMonths() { return 6; } public SixMonthlyExpiryDayValidator(int expiryDays, String period); @Override protected LocalDate getMaxDateCanEdit(); protected int monthOfYear(int periodNumber); public String g...
LocalDate periodDate = new LocalDate(); int previousPeriodStart = getPreviousPeriodStart(); periodDate = periodDate.withMonthOfYear( previousPeriodStart == PREVIOUS_PERIOD_START_JANUARY ? DateTimeConstants.JANUARY : DateTimeConstants.JULY).withDayOfMonth(1...
23357238_13
class Query { public static rx.functions.Func1<Event, Boolean> parse(String query) { QueryLexer tokenSource = new QueryLexer(new ANTLRStringStream(query)); QueryParser queryParser = new QueryParser(new CommonTokenStream(tokenSource)); try { CommonTree tree = (CommonTree) queryPa...
assertTrue(Query.parse("not host = 1").call(Event.builder().withHost("2").build())); assertFalse(Query.parse("not host = 1").call(Event.builder().withHost("1").build())); assertTrue(Query.parse("host = 1 and state = 2").call(Event.builder().withHost("1").withState("2").build())); assertFalse(Qu...
23358011_19
class SchematronHelper { @Nullable public static SchematronOutputType applySchematron (@Nonnull final ISchematronResource aSchematron, @Nonnull final IReadableResource aXML) { ValueEnforcer.notNull (aSchematron, "SchematronResource"); ValueEnforcer.notNull (aXML, "XMLSource"); try { // App...
final SchematronOutputType aSO = SchematronHelper.applySchematron (SchematronResourceSCH.fromClassPath (VALID_SCHEMATRON + ".does.not.exist"), ...
23374263_2
class GateTranslator extends SolverDecorator<ISolver> { public IConstr[] it(int y, int x1, int x2) throws ContradictionException { IConstr[] constrs = new IConstr[3]; IVecInt clause = new VecInt(5); // y &lt;=&gt; (x1 -> x2) // y -> (x1 -> x2) clause.push(-y).push(-x1).push(...
gator.it(1, 2, 3); assertTrue(gator.isSatisfiable(new VecInt(new int[] { 1, 2, 3 }))); } }
23437032_19
class ShortPropertyConverter extends AbstractPropertyConverter { @Override public Object convert(String value, Context context) { return Short.valueOf(value); } @Override public boolean supports(Class<?> type); private final ShortPropertyConverter converter; } class ShortPropertyConverterTest { pr...
assertThat((Short) converter.convert( Short.toString(Short.MIN_VALUE), null), is(equalTo(Short.MIN_VALUE))); assertThat((Short) converter.convert("0", null), is(equalTo((short) 0))); assertThat((Short) converter.convert( Short.toString(Short.MAX_VALUE), null), is(e...
23441735_17
class WDLHooks { public static void onNHPCHandleMaps(NetHandlerPlayClient sender, SPacketMaps packet) { listener.onNHPCHandleMaps(sender, packet); } private WDLHooks(); public static void onWorldClientTick(WorldClient sender); public static void onWorldClientRemoveEntityFromWorld(WorldClient sender, in...
doWithMockHooks(mock -> { makeMockWorld(); SPacketMaps packet = new SPacketMaps(0, (byte)0, false, Collections.emptyList(), new byte[0], 0, 0, 0, 0); clientPlayer.connection.handleMaps(packet); verify(mock).onNHPCHandleMaps(clientPlayer.connection, packet); }); } }
23442872_21
class MessageDispatcher extends CancellableLoop { public void addListener(MessageListener<T> messageListener, int limit) { if (DEBUG) { log.info("Adding listener."); } synchronized (mutex) { EventDispatcher<MessageListener<T>> eventDispatcher = messageListeners.add(messageListener, ...
int numberOfMessages = 100; final CountDownLatch latch = new CountDownLatch(numberOfMessages); MessageDispatcher<std_msgs.Int32> messageDispatcher = new MessageDispatcher<std_msgs.Int32>(lazyMessages, executorService); messageDispatcher.addListener(new MessageListener<std_msgs.Int32>() { ...
23466307_61
class FedoraProducer extends DefaultProducer { protected String getParam(String param) { if (hasParam(param)) { return param; }//end if else { return null; }//end else } public FedoraProducer(Endpoint endpoint); protected bo...
System.out.println("Testing getParam(String, String)"); String expected = "valid"; assertEquals("Parameter should have been returned", expected, this.producer.getParam(expected, "invalid")); assertEquals("Parameter should have been returned", expected, this.producer.getParam(exp...
23479380_0
class Flyweight { public static boolean bitSet(final AtomicBuffer buffer, final int offset, final int bitIndex) { return 0 != (buffer.getByte(offset) & (1 << bitIndex)); } public Flyweight(final ByteOrder byteOrder); protected ByteOrder byteOrder(); public int offset(); public in...
final byte bits = (byte)0b1000_0000; final int bufferIndex = 8; final int bitIndex = 7; aBuff.putByte(bufferIndex, bits); for (int i = 0; i < 8; i++) { boolean result = Flyweight.bitSet(aBuff, bufferIndex, i); if (bitIndex == i) { ...
23487016_12
class MethodHandlerAccessorFactory implements AccessorFactory { @Override public <BEAN, R, P> Getter<BEAN, R, P> buildGetter(final Field field, ValueProcessor<R, P> valueProcessor) { return new MethodHandlerGetter<>(field, valueProcessor); } @Override public Getter<BEAN, R, P> buildGetter(final Method method, V...
final TestBean testBeanOne = new TestBean(); final Getter<TestBean, Long, Long> longGetter = factory.buildGetter(publicLongField, valueProcessor); testBeanOne.publicLong = 123456l; assertEquals(123456l, longGetter.getValue(testBeanOne).longValue()); } }
23491281_1
class OAuthService { public static String getEmail(String accessToken) throws Exception { final String response = get("https://api.github.com/user/emails?access_token", accessToken); ObjectMapper objectMapper = new ObjectMapper(); final ArrayList<Map<String, Object>> emailList = objectMappe...
final String response = OAuthService.getEmail("xxx"); Assert.assertEquals("tommi.s.e.laukkanen@gmail.com", response); } }
23502577_223
class InternalQueries { @NonNull public static List<Object> unmodifiableNonNullList(@Nullable Object[] args) { return args == null || args.length == 0 ? emptyList() : unmodifiableList(asList(args)); } private InternalQueries(); @NonNull public static List<...
List<String> unmodifiableList = InternalQueries.unmodifiableNonNullList(asList("1", "2", "3")); assertThatListIsImmutable(unmodifiableList); } }
23505879_79
class CudaFloatDataBuffer extends BaseCudaDataBuffer { @Override public double getDouble(long i) { return super.getFloat(i); } public CudaFloatDataBuffer(Pointer pointer, Indexer indexer, long length); public CudaFloatDataBuffer(long length); public CudaFloatDataBuffer(long length, ...
DataBuffer create = Nd4j.createBuffer(new double[]{1,2,3,4},2); assertEquals(2,create.length()); assertEquals(4,create.underlyingLength()); assertEquals(2,create.offset()); assertEquals(3,create.getDouble(0),1e-1); assertEquals(4,create.getDouble(1),1e-1); } }
23556341_8
class RpSyncService { public static boolean shouldSync(Rp rp) { if (rp == null || !rp.isSyncClientFromOp()) return false; if (rp.getLastSynced() == null) return true; if ((Utils.addTimeToDate(rp.getLastSynced(), rp.getSyncClientPeriodInSeconds(), Calendar.SECOND).g...
Rp rp = new Rp(); rp.setSyncClientFromOp(true); rp.setSyncClientPeriodInSeconds(5 * 60); assertTrue(rpSyncService.shouldSync(rp)); } }
23597915_2
class MuleInstallMojo extends AbstractMuleMojo { public void renameFile(File orig, File dest) throws MojoExecutionException { try { Files.move(orig.toPath(), dest.toPath(), REPLACE_EXISTING); } catch (IOException e) { throw new MojoExecutionException(String.format("Could not...
String origFileName = "file.temp"; String destFileName = "file.zip"; File orig = temp.newFile(origFileName); File dest = new File(temp.getRoot(), destFileName); assertThat("Origin file should exist", orig.exists()); assertThat("Destination file should not exist", !dest.exists()); mojo.ren...
23610469_295
class TypeUtils { public static boolean isArray(Type type) { Utils.checkNotNull(type, "type"); boolean array; if (type instanceof Class) { array = ((Class<?>) type).isArray(); } else if (type instanceof GenericArrayType) { array = true; } else { array = false; } return array...
assertFalse(TypeUtils.isArray(Integer.class)); } }
23615757_18
class TimedLRUCache implements Cache<K, V> { @Override public void clear() { entryTimes.clear(); keys.clear(); entries.clear(); } public TimedLRUCache(final int capacity, final long storeTime); @Override public V get(K key); @Override public synchronized void put(K key, V value); private boolean isExpi...
final int capacity = 2; final long storeTime = 1000; final String[] keys = new String[]{ "test1", "test2" }; final Integer[] values = new Integer[]{ 1, 2 }; Cache<String, Integer> cache = new TimedLRUCache<>(capacity, storeTime); for (int i = 0; i < keys.length; i ++) { cache.put(keys[i], values[i]); ...
23623214_56
class PropertiesLightblueClientConfiguration { public static LightblueClientConfiguration fromObject(Properties properties) { LightblueClientConfiguration config = new LightblueClientConfiguration(); config.setCaFilePath(properties.getProperty(CA_FILE_PATH_KEY)); config.setCertFilePath(pro...
Properties properties = new Properties(); properties.setProperty("compression", "NONE"); LightblueClientConfiguration config = PropertiesLightblueClientConfiguration.fromObject(properties); assertEquals(Compression.NONE, config.getCompression()); } }
23653549_0
class CallStats { public void initialize(final int appId, final String appSecret, final String bridgeId, final ServerInfo serverInfo, final CallStatsInitListener callStatsInitListener) { if (StringUtils.isBlank(appSecret)) { logger.error("intialize: Arguments cannot be null "); throw new Illega...
callstatslib.initialize(appId, appSecret, "jit.si.345", serverInfo, listener); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } String msg = "SDK authentication successful"; Mockito.verify(listener).onInitialized(msg); } }
23680695_16
class IndexReWriter { public void optimizeIndecies(@Nonnull final List<String> intFields, @Nonnull final List<String> stringFields, @Nonnull final FlamdexWriter w) throws IOException, I...
/* make session 1 */ MockFlamdexReader r1 = new MockFlamdexReader(Arrays.asList("if1", "if2", "if3"), Arrays.asList("sf1"), Arrays.asList("if1", "if2"), 10); r1.addIntTerm("if1", 0, 0); r1.addIntTerm("if1", 1, 1); r1.addIntTe...
23686634_8
class LoadingSupplier implements Supplier<T> { @Override public final T get() { try { previous = load(); } catch (Exception e) { LoggerFactory.getLogger(LoadingSupplier.class).error("Error looking up supplier value!", e); } return previous; } abs...
System.out.println("SupplierCache.permanent"); CacheManager cacheManager = CacheManager.createIfNeeded("TestCacheManager"); SupplierCache<Integer> cache = cacheManager.supplierCache("Groups", new RecordingSupplier(), 1, TimeUnit.HOURS); assertE...
23703244_2
class Batch implements IBatch { public String getCurrentItem() { if (monitor == null) { return null; } Object currentItem = monitor.getCurrentItem(); if (currentItem == null) { return null; } return currentItem.toString(); } public Batch(String uuid); public Batch(String uuid, String name, St...
// assert with response with no monitor assertNull(new Batch("12345", "batchName", "batchGroup").getCurrentItem()); Batch batch = new Batch("12345"); assertNull(batch.getCurrentItem()); // create the progress monitor InProcessBatchProgressMonitor mockedProgressMonitor = mock(InProcessBatchProgressMonitor....
23714731_0
class BooleanAlgebra { public boolean hasNDistinctWitnesses(P predicate, Integer numOfWitnesses) { // generate as many witnesses as requested for (int witnessID = 0; witnessID < numOfWitnesses; witnessID++) { try { // generate a witness for the predicate ...
CharPred integers = new CharPred('0', '9'); assertTrue(ba.hasNDistinctWitnesses(integers, 5)); assertTrue(ba.hasNDistinctWitnesses(integers, 0)); assertTrue(ba.hasNDistinctWitnesses(integers, 10)); assertFalse(ba.hasNDistinctWitnesses(integers, 11)); } }
23737510_18
class PartialUriTemplate { public PartialUriTemplateComponents expand(Object... parameters) { List<String> variableNames = getVariableNames(); Map<String, Object> parameterMap = new LinkedHashMap<String, Object>(); int i = 0; for (String variableName : variableNames) { ...
final PartialUriTemplate template = new PartialUriTemplate("http://example" + ".com/events{/city}?eventName=Revo+Tour&location=Schlachthof{#section}"); Map<String, Object> val = new HashMap<String, Object>(); val.put("city", "Wiesbaden"); val.put("...
23744385_373
class TimeSeries extends Series implements Cloneable, Serializable { public Number getValue(int index) { return getRawDataItem(index).getValue(); } public TimeSeries(Comparable name); public TimeSeries(Comparable name, String domain, String range); public String getDomainDescription(); ...
Number value1 = this.seriesA.getValue(new Year(1999)); assertNull(value1); int value2 = this.seriesA.getValue(new Year(2000)).intValue(); assertEquals(102000, value2); } }
23750297_2
class CheckOpenServiceFilter implements Filter, InitializingBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpServletResponse = (HttpServletResponse)response; HttpServletRequest httpServletR...
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); response.setCharacterEncoding("UTF-8"); try { request.setMethod("POST"); request.addParameter("method", "user.add"); request.addParameter("version", "1.0.0"); filter.do...
23771701_0
class AuctionDataItemReader extends AbstractAuctionFileProcess implements ItemReader { @Override public Object readItem() { while (parser.hasNext()) { Auction auction = new Auction(); if (readAuctionItem(auction)) { return auction; } } ...
itemReader.open(null); int count = 0; Auction auction; while ((auction = ((Auction) itemReader.readItem())) != null) { count ++; assertNotNull(auction); AuctionFile auctionFile = AuctionFile.findById(1L); itemProcessor.getContext().setAuc...
23786714_6
class SwrveDeeplinkManager { protected void handleDeeplink(Bundle bundle) { if (bundle != null) { String url = bundle.getString(SWRVE_FB_TARGET_URL); if (SwrveHelper.isNotNullOrEmpty(url)) { Uri data = Uri.parse(url); this.handleDeeplink(data, SWRVE_A...
// 1. Test generic_campaign_event queued / sent // 2. Test message was shown // 3. Test message details were written to cache (for QA purposes) Bundle bundle = new Bundle(); bundle.putString("target_url","swrve://app?ad_content=295411&ad_source=facebook&ad_campaign=BlackFriday"...
23803268_8
class SnapshotFileReader { public DataState readFuzzySnapshot() throws CRCValidationException, IOException { DataTree dt = new DataTree(); Map<Long, Integer> sessions = new HashMap<Long, Integer>(); InputStream snapIS = null; CheckedInputStream crcIn = null; try { ...
try { SnapshotFileReader r = new SnapshotFileReader(snap1, TS1); DataState snapshot; DataState fuzzyDataState = r.readFuzzySnapshot(); assertEquals(69,fuzzyDataState.getLastZxid()); Map<Long, Integer> sessions = fuzzyDataState.getSessions(); ...
23813195_25
class Burst { public static String friendlyName(Enum<?>[] arguments) { return friendlyName(arguments, new Annotation[0][0]); } private Burst(); public static Enum<?>[][] explodeArguments(TestConstructor constructor); public static Enum<?>[][] explodeArguments(Method method); public static String fri...
String actual = Burst.friendlyName(new Enum<?>[0]); assertThat(actual).isEqualTo(""); } }
23813803_2
class UserHandler extends Handler { @Doc("Sign up a user") @GET @Path("/signup") @HandleErrors({ @HandleError(code = 20000, exception = UsernameDuplicateException.class, description = "Username duplicate") }) public User signup( @QueryParam("username") @R...
User user = UserHandlerTester.signup("user1", "pass1", null, User.class); assertNotNull(user.id); assertEquals("user1", user.username); assertNull(user.password); } }
23831132_127
class MapUtils { public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map) { return sortByValue(map, false); } public static K keyOfHighestValue(Map<K, V> map); public static LinkedHashMap<K, V> keysOfHighestValues( Map<K, V> map, int topN...
Random random = new Random(System.currentTimeMillis()); Map<String, Integer> testMap = new HashMap<String, Integer>(1000); for (int i = 0; i < 1000; ++i) { testMap.put("SomeString" + random.nextInt(), random.nextInt()); } testMap = MapUtils.sortByValue(testMap, true)...
23892158_12
class MethodInfo { Object getData() { return data; } private MethodInfo(Method method, Object instance); static MethodInfo newInstance(Method method, Object instance); private void parseMethodAnnotations(); Method getMethod(); int getViewType(); String getTitle(); Object getInstance(); } ...
class MyConfig { @Title("Reset") @Spinner({"one"}) public void foo() { } } Object instance = new MyConfig(); Method[] methods = instance.getClass().getDeclaredMethods(); MethodInfo methodInfo = MethodInfo.newInstance(methods[0], instance); assertThat(methodInfo.getData()).isNotNull...
23907761_7
class JohnzonJsonLogic { public JsonValue apply(final JsonValue logic, final JsonValue args) { if (logic.getValueType() != JsonValue.ValueType.OBJECT) { return logic; } final JsonObject object = logic.asJsonObject(); if (object.size() > 1) { return object; ...
final JsonObject value = builderFactory.createObjectBuilder() .add("a", 1) .add("b", 2) .build(); assertEquals( JsonValue.EMPTY_JSON_ARRAY, jsonLogic.apply( builderFactory.createObjectBuilder() ...
23912550_0
class PrettySharedPreferences { protected StringEditor getStringEditor(String key) { TypeEditor typeEditor = TYPE_EDITOR_MAP.get(key); if (typeEditor == null) { typeEditor = new StringEditor(this, sharedPreferences, key); TYPE_EDITOR_MAP.put(key, typeEditor); } else ...
StringEditor stringEditor = mSharedPref.getStringEditor(TEST_KEY); assertThat(stringEditor).isInstanceOf(StringEditor.class); } }
23930639_297
class MetricRegistryImpl extends MetricRegistry { @Override public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException { checkNameIsNotNullOrEmpty(name); return register(Metadata.builder().withName(name).build(), true, metric); } public MetricRegistryI...
assertException("Metadata ['DefaultMetadata{name='%s', type=counter, unit='unit', reusable=true, description='description', displayName='display'}'] already registered, does not match provided ['DefaultMetadata{name='%s', type=counter, unit='unit', reusable=true, description='description', displayName='other'}'...
23952595_0
class ConcurrentCache implements Computable<K, V> { public V get(K key, Callable<V> callable) { Future<V> future = concurrentMap.get(key); if (future == null) { FutureTask<V> futureTask = new FutureTask<V>(callable); future = concurrentMap.putIfAbsent(key, futureTask); ...
final String key = "object"; Object result1 = cache.get(key, new Callable<Object>() { @Override public Object call() throws Exception { return new Object(); } }); Object result2 = cache.get(key, new Callable<Object>() { ...
23963494_27
class GuideProbeTargets implements Serializable, TargetContainer, OptionsList<SPTarget> { public static ImList<GuideProbeTargets> sortByGuider(final ImList<GuideProbeTargets> lst) { return lst.sort(GuiderComparator.instance); } private GuideProbeTargets(final GuideProbe guider, final OptionsList<...
ImList<GuideProbeTargets> lst = DefaultImList.create(fix.gpt_pwfs2, fix.gpt_gmos, fix.gpt_pwfs1); lst = GuideProbeTargets.sortByGuider(lst); assertSame(fix.gpt_gmos, lst.get(0)); assertSame(fix.gpt_pwfs1, lst.get(1)); assertSame(fix.gpt_pwfs2, lst.get(2)); lst = Default...
23972840_3
class ApacheHttpClient implements HttpClient { @Override public HttpResponse execute(HttpRequest request) throws HttpRuntimeException { return execute(Preconditions.checkNotNull(request), Options.DEFAULT); } public ApacheHttpClient(); public ApacheHttpClient(HttpConfig config); private HttpClientCo...
httpClient = new ApacheHttpClient(); HttpRequest request = HttpRequest.newBuilder() .setMethod(Method.POST) .setUrl(testServer.baseHttpUrl()) .setBody(ExpectedHttpResponse.newBuilder().build()) .setCompression(Compression.GZIP) .build(); HttpRespo...
23995230_9
class SentMapControl extends AbstractMapControl { public void addToSent(Short transmissionId, Segment segment) { // add to pending map dataMap.put(transmissionId, segment); } public SentMapControl(TransmissionSuccessListener listener, int maxEntries, int maxEntryOffset, ...
for (Short[] referenceGroup : referenceGroups) { Segment segment = new Segment(++dataId, serializeShorts(referenceGroup)); for (Short reference : referenceGroup) { handler.addToSent(reference, segment); } } int dataCount = 0; int refer...
24005183_2
class StringUtil { public static String arrayToJson(String[] array) { if (null == array) {return EMPTY_JSON_ARRAY;} StringWriter stringWriter = new StringWriter(); JSONWriter jsonWriter = new JSONWriter(stringWriter); try { jsonWriter.array(); for (String ...
assertEquals("[\"item1\",\"item2\"]", StringUtil.arrayToJson(new String[]{"item1","item2"})); } }
24016861_0
class ShapefileGeometryCursor extends GeometryCursor { @Override public Geometry next() { if (! hasNext()) { return null; } try { recordNumber = inputStream.readInt();//1 based int recLength = inputStream.readInt(); position += 8; ...
{ File file = getTestShapefile("polygons"); ShapefileGeometryCursor polygonShapefileCursor = new ShapefileGeometryCursor(file); GeometryCursor unionCursor = OperatorUnion.local().execute(polygonShapefileCursor, null, null); Geometry dissolvedGeometry = unionCur...
24041094_6
class Driver implements DriverService { @Override public DriverInfo getInfo() { return info; } @Override public void scanForDevices(String settingsString, DriverDeviceScanListener listener); private void scanPrimaryAddress(DriverDeviceScanListener listener, Settings settings, MBusConnectio...
assertEquals("mbus", new Driver().getInfo().getId()); } }
24084730_0
class LocalFileInputPlugin implements FileInputPlugin { private static List<String> listFiles(final PluginTask task) { // This |pathPrefixResolved| can still be a relative path from the working directory. // The path should not be normalized by Path#normalize to eliminate redundant name elements li...
final LocalFileInputPlugin.PluginTask task = buildTask("foofoo"); this.workdir.newFile("foofoo1"); this.workdir.newFile("FooFoo2"); this.workdir.newFile("barbar3"); this.workdir.newFolder("foofoo4"); this.workdir.newFile("foofoo4/foo"); this.workdir.newFile("foofo...
24114062_3
class SimpleEV3Sound implements EV3Device { static int getFrequency(String note) throws EV3ScriptException { String cleanNote = note.trim().toUpperCase(); int length = cleanNote.length(); if ((length >= 2) && (length <= 5)) { char last = cleanNote.charAt(length - 1); // Sharp or not ? ...
Assert.assertEquals(SimpleEV3Sound.getFrequency("C1"), (int) 32.7032); Assert.assertEquals(SimpleEV3Sound.getFrequency("C1#"), (int) 34.6478); Assert.assertEquals(SimpleEV3Sound.getFrequency("C2"), (int) 65.4064); Assert.assertEquals(SimpleEV3Sound.getFrequency("A3"), 220); Assert.assertEquals(Simpl...
24145690_8
class ContentTypeService extends AbstractEntityTypeService<Content, ContentTypeDto> implements IComponentUsageService { @Override public PagedMetadata<ComponentUsageEntity> getComponentUsageDetails(String componentCode, RestListRequest restListRequest) { RestContentListRequest contentListRequest = new...
int pageSize = 2; this.restListRequest.setPageSize(pageSize); // creates paged data List<Integer> pageList = Arrays.asList(1, 2); ContentDto[][] utilizers = { { ContentMockHelper.mockContentDto(0), ContentMockHelper.mockContentDto(1) }, { Content...
24155908_0
class ElasticsearchHttpReporter extends ElasticsearchReporter { public static Builder forRegistryAndIndexPrefix(MetricRegistry registry, String elasticsearchIndexPrefix) { return new Builder(registry, elasticsearchIndexPrefix); } protected ElasticsearchHttpReporter(MetricRegistry regi...
reporter.stop(); reporter = ElasticsearchHttpReporter .forRegistryAndIndexPrefix(registry, "test") .withTimestampFieldName("@timeywimey") .withClock(Clock.defaultClock()).prefixedWith(prefix) .convertRatesTo(TimeUnit.SECONDS) ...
24167016_1
class Modernizer { public Collection<ViolationOccurrence> check(ClassReader classReader) throws IOException { ModernizerClassVisitor classVisitor = new ModernizerClassVisitor( javaVersion, violations, exclusions, exclusionPatterns, ignorePackages, ignoreClassName...
ClassReader cr = new ClassReader(VectorTestClass.class.getName()); Collection<ViolationOccurrence> occurrences = createModernizer("1.0").check(cr); assertThat(occurrences).hasSize(0); } }
24224646_14
class AnnotationsInfo { public AnnotationInfo get(String annotationName) { return classAnnotations.get(annotationName); } public AnnotationsInfo(Class<?> cls); public Collection<AnnotationInfo> list(); public AnnotationInfo get(Class<?> annotationNameClass); public void append(Annota...
AnnotationsInfo info = new AnnotationsInfo(UnrelatedClass.class); assertThat(info.get("org.neo4j.ogm.domain.gh827.PackagePrivateAnnotation").get("value")).isEqualTo("v"); } }
24272313_41
class Elevator implements DoorsListener { public Status status(){ return status; } public Elevator(DoorsDriver doorsDriver); public Elevator(int startingFloor, DoorsDriver doorsDriver); public int currentFloor(); public void pushButton(int floorNumber); @Override public void doo...
// given: // when: Status status = elevator.status(); // then: Assert.assertEquals(Status.AWAITING, status); } }
24283381_1
class EcsTypeInspector { MatrixData getMatrixData() { assert model != null; return model.matrixData; } public EcsTypeInspector(List<URI> files, String resourcePrefix); SortedMap<String,List<RowTypeMapping>> getTypeMap(); boolean foundEcsClasses(); private List<EcsTypeData> findEcsTypes(ClassStore store)...
assertTypes(Arrays.asList("FactoryA"), inspector.getMatrixData().factoryColumns); } }
24338315_29
class UserManager implements Serializable { public ResultCode registerUser(String email, String name, String password, boolean registrationConfirmed) { ResultCode checkResult = checkRegistrationPreconditions(email, name); if (checkResult != ResultCode.OK) { return checkResult; } String controlCode = gene...
Mockito.when(databaseModel.isEmailRegistered("carl@example.com")).thenReturn(false); Mockito.when(databaseModel.isUserNameRegistered("Carl")).thenReturn(false); Mockito.when(databaseModel.addUser(Mockito.notNull(User.class))).thenReturn(2); Mockito.when(emailSender.sendRegistrationEmail(Mockito.eq("carl@example...
24350958_6
class Reflections { public static Value<Method> method(Class<?> clazz, String method, Object... args) { Conditions.nonNull(clazz, "clazz"); Conditions.nonNullOrEmpty(method, "method"); try { if (args != null && args.length > 0) { Class<?>[] types = Stream.of(args...
MyObject object = new MyObject(); Value<Object> value = Reflections.invoke(object, "foo"); Assert.assertTrue(value.isPresent()); Assert.assertEquals(object.foo(), value.get()); Assert.assertEquals("foo", Reflections.invoke(MyObject.class, "bar").get()); } }
24366887_1
class LunchParser { public static LunchParser getInstance() { if(instance == null) { instance = new LunchParser(); } return instance; } private LunchParser(); public void parse(); public ArrayList<LunchOffer> getLunchData(int mensaLocation); public List<Mensa> getLunchDataForAllMensas(); private...
LunchParser.getInstance(); LunchParser lp = LunchParser.getInstance(); Assert.assertNotNull(lp); } }
24384638_0
class WordUtils { public static String getWordAtIndex(String text, Integer position) { int start = position; for (; start > 0; start--) { if (Character.isWhitespace(text.charAt(start - 1))) { break; } } if (start == position) { return StringUtils.EMPTY; } return text.substring(start, positi...
// Given String text = "Blah 123 Foobar"; // When String actual1 = WordUtils.getWordAtIndex(text, 8); String actual2 = WordUtils.getWordAtIndex(text, 7); String actual3 = WordUtils.getWordAtIndex(text, 6); String actual4 = WordUtils.getWordAtIndex(text, 5); String actual5 = WordUtils.getWordAtIndex(tex...
24384732_31
class DynamoDbEncryptor implements DynamoDbEncryptionClient { private static byte[] toByteArray(ByteBuffer buffer) { buffer = buffer.duplicate(); // We can only return the array directly if: // 1. The ByteBuffer exposes an array // 2. The ByteBuffer starts at the beginning of the ar...
final byte[] expected = new byte[] {0, 1, 2, 3, 4, 5}; assertToByteArray("Wrap", expected, ByteBuffer.wrap(expected)); assertToByteArray("Wrap-RO", expected, ByteBuffer.wrap(expected).asReadOnlyBuffer()); assertToByteArray("Wrap-Truncated-Sliced", expected, ByteBuffer.wrap(new byte[] {0...
24394186_4
class Certificates { public static String[] getCNs(X509Certificate cert) { try { final String subjectPrincipal = cert.getSubjectX500Principal().getName(X500Principal.RFC2253); final LinkedList<String> cnList = new LinkedList<String>(); final LdapName subjectDN = new Ldap...
X500Principal normal = new X500Principal("CN=abc,OU=ou,O=o,C=canada,EMAILADDRESS=bob@bob.com"); X500Principal bad1 = new X500Principal("CN=\"abc,CN=foo.com,\",OU=ou,O=o,C=canada,EMAILADDRESS=bob@bob.com"); X500Principal bad2 = new X500Principal("ou=\",CN=evil.ca,\", CN=good.net"); when...
24404221_752
class AmqpDestinationHelper { public static void setToAddressFromDestination(AmqpJmsMessageFacade message, JmsDestination destination) { message.setToAddress(getDestinationAddress(destination, message.getConnection())); // Clear any previous annotations about destination type, we will add proper a...
String testAddress = "testAddress"; JmsDestination destination = new JmsTemporaryQueue("testAddress"); AmqpJmsMessageFacade message = Mockito.mock(AmqpJmsMessageFacade.class); AmqpDestinationHelper.setToAddressFromDestination(message, destination); Mockito.verify(message).setTo...
24409108_3
class User extends TypedData implements Replier { public static UserPermanentDeleteResponse permanentDelete(String id) throws AuthorizationException, ClientException, ServerException, InvalidException, RateLimitException { final URI uri = UriBuilder.newBuilder() .path("user_delete_...
String json = load("permanent_delete_response.json"); final UserPermanentDeleteResponse userPermanentDeleteResponse= mapper.readValue(json, UserPermanentDeleteResponse.class); assertEquals("123456", userPermanentDeleteResponse.getId()); } }
24416383_24
class NumberMatcher extends CommonTokensMatcher { @Override public boolean matches(String s1, String s2) { if (s1 == null && s2 == null) return true; String no1 = removeNumbers.transform(s1); String no2 = removeNumbers.transform(s2); if (noNumbersRequireRestMatch && no1.length() == 0 && no2.length() == 0) { ...
NumberMatcher matcher = new NumberMatcher(); assertTrue(matcher.matches("Abraham Lincoln came 1834 to Ealing, 4 times in a row, riding 23 horses", "Abraham Lincoln came 1934 to Ealing, 4 times in a row, riding 23 horses")); // Also true would be: assertTrue(matcher.matches("Abraham Lincoln came 1834 to Eali...
24417776_49
class GroovyChange extends Change { public static Map<String, Object> createShellContext(ApplicationContext applicationContext, Log4JPrintStream output) { final Map<String, Object> shellContext = new HashMap<>(); // hybris 5 shellCon...
// given TestBean bean = prepareBean("bean"); TestBean beanWithAlias = prepareBean("beanWithAlias"); given(applicationContext.getBeanDefinitionNames()).willReturn(new String[]{ bean.name(), beanWithAlias.name() }); given(applicationContext.getAlias...
24468283_0
class EmailReporter { public String generatePayload(String name, String email, String message, String category) throws Exception { if (email == null) email = ""; if (name == null) name = ""; String userEmail = email; String userName = name; if (userEmail.isEmpty()) { ...
EmailReporter reporter = new EmailReporter("token", "helpdeskemail"); String payload = reporter.generatePayload("name", "email", "hello\nworld", "General Feedback"); assertEquals("{\"personalizations\":[{\"subject\":\"tS Android: General Feedback\",\"to\":[{\"name\":\"Help Desk\",\"email\":\"hel...
24477567_28
class NavigableMapOLogEntryOracle implements OLogEntryOracle { @Override public QuorumConfigurationWithSeqNum getLastQuorumConfig() { if (configMap.isEmpty()) { return new QuorumConfigurationWithSeqNum(QuorumConfiguration.EMPTY, 0); } else { final Map.Entry<Long, QuorumConfiguration> lastEntry ...
havingLogged( entries() .term(7).configurationAndSeqNum(firstConfig, 1)); havingTruncatedToSeqNum(1); assertThat(oracle.getLastQuorumConfig(), is(equalTo(configurationAndSeqNum(EMPTY, 0)))); havingLogged( entries() .term(8).configurationAndSeqNum(secondConfig, 2)...
24478161_3
class ExceptionHandler implements Serializable { void verifyCaller(Callable<?> callable) { Method callMethod = getCallableMethod(callable.getClass()); for (Class<?> exceptionOrError : callMethod.getExceptionTypes()) { Preconditions.checkArgument(Exception.class.isAssignableFrom(exceptionOrError), ...
class A implements Callable<Object> { @SuppressWarnings("unused") @Override public Object call() throws IOException, InterruptedException { return null; } } class B extends A { } class C extends A { @SuppressWarnings("unused") @Override public Object call() th...
24499046_11
class GreenMailStandaloneRunner { public void doRun(Properties properties) { ServerSetup[] serverSetup = new PropertiesBasedServerSetupBuilder().build(properties); if (serverSetup.length == 0) { printUsage(System.out); } else { greenMail = new GreenMail(serverSetup...
GreenMailStandaloneRunner runner = new GreenMailStandaloneRunner(); final Properties properties = new Properties(); properties.setProperty(PropertiesBasedServerSetupBuilder.GREENMAIL_VERBOSE, ""); properties.setProperty("greenmail.setup.test.smtp", ""); properties.setProperty("gr...
24503341_1
class Tuple { @Override public int hashCode() { if ((this.first == null) && (this.second == null)) { return "".hashCode(); } return this.first == null ? this.second.hashCode() : this.first.hashCode() ^ this.second.hashCode(); } public Tuple(T firstValue, U secondValue); @Override public boolean equals...
Tuple<String, String> t1 = new Tuple<String, String>("S1", "S2"); Tuple<String, String> t2 = new Tuple<String, String>("S1", "S2"); assertEquals(t1.hashCode(), t2.hashCode()); Tuple<String, String> t3 = new Tuple<String, String>(null, null); t3.hashCode(); } }
24506674_59
class IntegerPolyfill { public static int compare(int x, int y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); } } class TestIntegerPolyfill { @Test public void integer_edge_cases_work_as_expected() {
assertEquals(0, IntegerPolyfill.compare(Integer.MIN_VALUE, Integer.MIN_VALUE)); assertEquals(0, IntegerPolyfill.compare(Integer.MAX_VALUE, Integer.MAX_VALUE)); assertThat(IntegerPolyfill.compare(Integer.MIN_VALUE, Integer.MAX_VALUE), is(lessThan(0))); assertThat(IntegerPolyfill.compare(I...
24542374_0
class StatefulFactory implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware { public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry reg) throws BeansException { logger.debug("postProcessBeanDefinitionRegistry : enter"); try { // Reflect over StatefulJ // Reflections r...
BeanDefinitionRegistry registry = new MockBeanDefinitionRegistryImpl(); BeanDefinition userRepo = BeanDefinitionBuilder .genericBeanDefinition(MockRepositoryFactoryBeanSupport.class) .getBeanDefinition(); userRepo.getPropertyValues().add("repositoryInterface", UserRepository.class.getName()); reg...
24580061_38
class ConvolutionalLayer extends LayerBase { @Override public LayerParameter generateParameterGradient(final Matrix input, final Matrix error) { final Matrix weightGradient = matrixFactory.create(kernelHeight * kernelWidth * inputChannel, outputShape[0]); for (int n = 0; n < input.getColumns(); ++n) { ...
final LayerParameter convolutionalLayerParams = convolutional3DLayer.generateParameterGradient(input3D, nextError3D); assertTrue(compare(expectedConvolutional3DLayerParams, convolutionalLayerParams, TOLERANCE)); } }
24587006_11
class StateMachine { @SuppressWarnings("unchecked") public Transition handleEvent(Transition last, E event) { final Object current = last.getState(); final Context context = last.getContext(); final String stateMachineId = context.stateMachineId(); Transition next; try...
final Transition requested = stateMachine.handleEvent(initialTransition, new RechargeEvent()); assertThat(requested).isNotNull(); assertThat(requested.getState().getClass()).isEqualTo(RECHARGE_REQUESTED_STATE.getClass()); final Optional<PinRechargedContext> pinRechagedContext = requeste...
24610319_1
class HapticInterfaceManager { public void refreshHapticData(View root) { if(proxyHolder.get() != null) { ISdl proxy = proxyHolder.get(); if (userHapticData == null) { List<HapticRect> hapticRects = new ArrayList<>(); findHapticRects(root, hapticRects...
View root = createViews(); hapticMgr.refreshHapticData(root); verify(mockProxy).sendRPC(captor.capture()); SendHapticData data = captor.getValue(); assertNotNull("SendHapticData RPC", data); List<HapticRect> list = data.getHapticRectData(); assertNotNull("List", l...