id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
87911627_4
class MappingsConceptLineProcessor extends ConceptLineProcessor { public Concept fill(Concept concept, CsvLine line) throws IllegalArgumentException { if (!CollectionUtils.isEmpty(concept.getConceptMappings())) { concept.getConceptMappings().clear(); } String mappingsStr = line.get(HEADER_MAPPINGS_SAMEAS)...
// Setup String[] headerLine = { "Same as mappings" }; String[] line = { null }; // Replay MappingsConceptLineProcessor p = new MappingsConceptLineProcessor(cs, new ConceptMapListParser(cs)); Concept c = p.fill(new Concept(), new CsvLine(headerLine, line)); // Verif Assert.assertTrue(Collection...
87966671_7
class CrashViewModel { public int getIdentifier() { return crash.getId(); } public CrashViewModel(); public CrashViewModel(Crash crash); public String getPlace(); public String getExactLocationOfCrash(); public String getReasonOfCrash(); public String getStackTrace(); public String getCrashIn...
Crash crash = mock(Crash.class); when(crash.getId()).thenReturn(1); when(crash.getAppInfo()).thenReturn(mock(AppInfo.class)); CrashViewModel viewModel = new CrashViewModel(crash); assertThat(viewModel.getIdentifier(), is(1)); } }
87969126_3
class CodeLocationNameGenerator { public String createScanCodeLocationName(final String sourcePath, final String scanTargetPath, final String projectName, final String projectVersionName, final String prefix, final String suffix) { final String pathPiece = cleanScanTargetPath(scanTargetPath, sourcePath); ...
final String expected = "hub-common-rest/target/hub-common-rest/2.5.1-SNAPSHOT scan"; final DetectFileFinder detectFileFinder = mock(DetectFileFinder.class); when(detectFileFinder.extractFinalPieceFromPath("/Users/ekerwin/Documents/source/integration/hub-common-rest")).thenReturn("hub-common-re...
88063304_14
class TarArguments { abstract boolean extract()@Option(value = "x", mnemonic = 'x') abstract boolean extract(); abstract boolean extract()@Option(value = "c", mnemonic = 'c') abstract boolean create(); abstract boolean extract()@Option(value = "v", mnemonic = 'v') abstract boolean verbose(); abstract boolea...
f.assertThat("-x", "-f", "foo.tar").succeeds( "extract", true, "create", false, "verbose", false, "compress", false, "file", "foo.tar"); f.assertThat("-v", "-x", "-f", "foo.tar").succeeds( "extract", true, "create", false, "verbose", true, ...
88127865_3
class GuavaCompatibilityUtil { static boolean isGuavaCompatibilityFound() { return INSTANCE.isGuavaCompatibilityFound; } private GuavaCompatibilityUtil(); } class GuavaCompatibilityUtilTest { @Test public void isGuavaCompatibilityFound() {
assertTrue(GuavaCompatibilityUtil.isGuavaCompatibilityFound()); } }
88139536_4
class RxTask { @CheckReturnValue @NonNull public static <R> Maybe<R> maybe(@NonNull final Callable<Task<R>> callable) { return Single.fromCallable(callable).flatMapMaybe( new Function<Task<R>, MaybeSource<? extends R>>() { @Override public MaybeSource<? exten...
final String hello = "Hello, world!"; when(mockHelloTask.getResult()) .thenReturn(hello); when(mockHelloTask.isSuccessful()) .thenReturn(true); when(mockHelloTask.addOnCompleteListener(onComplete.capture())) .thenReturn(mockHelloTask); ...
88152958_48
class Stackifier { public void writeStructuredControlFlow(final StackifierStructuredControlFlowWriter writer) { flow.writeStructuredControlFlow(writer); } public Stackifier(final ControlFlowGraph controlFlowGraph); public void printDebug(final PrintWriter printWriter); } class StackifierTe...
final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode startNode = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); startNode.getExpressions().add(new GotoExpression(p, new BytecodeO...
88178114_50
class IndexFactoryBean extends AbstractFactoryBeanSupport<Index> implements InitializingBean { @Override public Class<?> getObjectType() { Index index = getIndex(); return index != null ? index.getClass() : Index.class; } @Override public void afterPropertiesSet(); private void applyIndexConfigurers(String...
assertThat(newIndexFactoryBean().getObjectType()).isEqualTo(Index.class); } }
88231534_1
class NoopSpanNameProvider implements MongoSpanNameProvider { @Override public String generateName(CommandStartedEvent event) { return event != null && event.getCommandName() != null ? event.getCommandName() : NO_OPERATION; } private final MongoSpanNameProvider provider; private final CommandSta...
assertEquals("unknown", provider.generateName(null)); } }
88242107_2
class AnnotationScanner { public List<AccessibleObject> getJpaAnnotatedMembers(Class<?> c, Class<? extends Annotation> annotation) { final List<AccessibleObject> jpaAnnotated = new ArrayList<AccessibleObject>(); for (Class<?> cl = c; cl != Object.class && cl != null; cl = cl.getSuperclass()) { ...
AnnotationScanner scanner = new AnnotationScanner(); List<AccessibleObject> members = scanner.getJpaAnnotatedMembers(TestInterface.class, PersistenceUnit.class); Assert.assertEquals(0, members.size()); } }
88284952_110
class SerializedObserver implements Observer<T>, Disposable { @Override public void onNext(@NonNull T t) { if (done) { return; } if (t == null) { s.dispose(); onError(new NullPointerException("onNext called with null. Null values are generally not all...
final AtomicReference<Observer<Integer>> serial = new AtomicReference<Observer<Integer>>(); TestObserver<Integer> to = new TestObserver<Integer>() { @Override public void onNext(Integer t) { if (t != null && t == 0) { serial.get().onNext(null);...
88286191_4
class PixabayImage { public int getWebformatHeight() { return webformatHeight; } public PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long ...
assertEquals(pixabayImage.getWebformatHeight(), 90); } }
88374068_4
class ClientSpanNameProvider { public static Function<HttpRequest, String> PREFIXED_REQUEST_METHOD_TARGET_NAME( final String prefix) { return (request) -> replaceIfNull(prefix, "") + replaceIfNull(request.getRequestLine().getMethod(), "unknown") + " " + replaceIfNull(standardizeUri(request....
Function<HttpRequest, String> spanNameProvider = ClientSpanNameProvider .PREFIXED_REQUEST_METHOD_TARGET_NAME("ELASTICSEARCH - "); assertEquals("ELASTICSEARCH - GET /twitter/tweet/", spanNameProvider.apply(getRequest)); assertEquals("ELASTICSEARCH - GET /twitter/tweet/?", spanNameProvider.apply(getR...
88406700_2
class RxReceiverLocal { @NonNull public static Observable<Intent> receives(@NonNull final Context context, @NonNull final IntentFilter intentFilter) { return Observable.create(new ObservableOnSubscribe<Intent>() { @Override public void subscribe(final ObservableEmitter<Intent> emitter) { ...
IntentFilter intentFilter = new IntentFilter("test"); Context context = RuntimeEnvironment.application.getApplicationContext(); TestObserver<Intent> tester = RxReceiverLocal.receives(context, intentFilter) .test(); Intent foobar = new Intent("test").putExtra("foo", "bar"...
88435530_1
class FlaxStore { static<M extends FlaxModel> M getModel(Class modelClass) { return getModel(modelClass, 0); } private FlaxStore(); static M getModel(Class modelClass, Integer modelKey); static void putModel(M model, Integer modelKey); private static Map<Class, Map<Integer, FlaxModel...
Foo fooOne = FlaxStore.getModel(Foo.class, 0); Foo fooTwo = FlaxStore.getModel(Foo.class, 0); assertEquals("fooOne and fooTwo should be the same but they are different.", fooOne, fooTwo); } }
88485241_3
class PCA9685 implements Closeable { public void setAllPwm(int on, int off) throws IOException { if (i2cDevice != null) { try { i2cDevice.writeRegByte(ALL_LED_ON_L, (byte) (on & 0xFF)); i2cDevice.writeRegByte(ALL_LED_ON_H, (byte) (on >> 8)); i2cDevice.writeRegByte(ALL_LED_OFF_L, (by...
when(peripheralManagerServiceMock.getI2cBusList()).thenReturn(i2cDevices); when(peripheralManagerServiceMock.openI2cDevice("I2C1",0x40)).thenReturn(i2cDeviceMock); when(i2cDeviceMock.readRegByte(MODE1)).thenReturn((byte)0x0); PCA9685 device = new PCA9685((byte)0x40, peripheralManagerServiceMock); ...
88544701_185
class ReconnectingFactSubscriptionWrapper implements Subscription { @Override public Subscription awaitComplete() throws SubscriptionCancelledException { for (;;) { assertSubscriptionStateNotClosed(); Subscription cur = currentSubscription.get(); if (cur != null) {...
observerAC.getValue().onComplete(); assertTimeout(Duration.ofMillis(1000), () -> { // needs to return immediately uut.awaitComplete(); }); } }
88621169_2
class EventProcessor { @EventHandler // Mark this method as an Axon Event Handler public void on(ProductAddedEvent productAddedEvent) { repo.save(new Product(productAddedEvent.getId(), productAddedEvent.getName())); LOG.info("A product was added! Id={} Name={}", productAddedEvent.getId(), produ...
// Arrange List<Product> products = new ArrayList<>(); when(repo.save(any(Product.class))) .thenAnswer(i -> { Product prod = i.getArgumentAt(0, Product.class); products.add(prod); return prod; }); ...
88711981_23
class MessageConverter_v1_0_to_Internal implements MessageConverter<Message_1_0, InternalMessage> { @Override public InternalMessage convert(Message_1_0 serverMessage, NamedAddressSpace addressSpace) { Object bodyObject = MessageConverter_from_1_0.convertBodyToObject(serverMessage); final A...
Message_1_0 sourceMessage = createTestMessage(MESSAGE_MESSAGE_ANNOTATION, null); final InternalMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType()); ass...
88787780_15
class ArrayMath { public static String toHexString(byte[] bytes) { return toHexString(bytes, 0, bytes.length); } private ArrayMath(); public static double[] add(double[] in, double[] out, int mul); public static int[] multiply(int[] in, int[] out, int mul); public static double[] mul...
assertEquals("", toHexString(bytes())); assertEquals("C5", toHexString(bytes(0xC5))); assertEquals("FEDCBA9876543210", toHexString(bytes( 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10))); } }
88794099_0
class TensorflowProcessorProperties { @NotNull public Resource getModelLocation() { return modelLocation; } @NotNull public String getOutputName(); public void setOutputName(String outputName); public void setModelLocation(Resource modelLocation); public int getOutputIndex(); public void setOutputIndex(int ...
EnvironmentTestUtils.addEnvironment(context, "tensorflow.modelLocation:/remote"); context.register(Conf.class); context.refresh(); TensorflowProcessorProperties properties = context.getBean(TensorflowProcessorProperties.class); assertThat(properties.getModelLocation(), equalTo(context.getResource("/remote")))...
88820221_9
class AbstractSizeBoundedQueue { abstract void offer(MessagePromise<?> promise)abstract void offer(MessagePromise<?> promise); abstract void offer(MessagePromise<?> promise) AbstractSizeBoundedQueue(int maxSize, MessageKey key); abstract void offer(MessagePromise<?> promise)abstract int drainTo(Consumer consumer); ...
AbstractSizeBoundedQueue queue = newQueue(OverflowStrategy.dropTail); CountDownLatch countDown = new CountDownLatch(1); for (int i = 0; i < queue.maxSize; i++) { MessagePromise<Integer> next = newPromise(i); queue.offer(next); if (i == queue.maxSize - 1) { next.addListener(future ...
88831074_192
class UnixUser { public String getDir() { return dir; } UnixUser(String userName, Passwd pwd); public UnixUser(String userName); protected UnixUser(String userName, String gecos, String dir, String shell, int uid, int gid, Set<String> groups); public String getUserName(); publ...
Assert.assertNotNull(user.getDir()); } }
88860621_0
class JavaDomUtils { public static String calculateTypeName(CompilationUnit compilationUnit, FullyQualifiedJavaType fqjt) { if (fqjt.getTypeArguments().size() > 0) { return calculateParameterizedTypeName(compilationUnit, fqjt); } if(compilationUnit == null ...
Interface interfaze = new Interface(new FullyQualifiedJavaType("com.foo.UserMapper")); FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType("java.util.Map<java.math.BigDecimal, java.util.List<com.beeant.dto.User>>"); assertEquals("java.util.Map<java.math.BigDecimal, java.util.List<c...
88873634_2
class PageIndicatorView extends LinearLayout implements PageIndicators.PageObserver, PageIndicators.PageCountObserver { @Override @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) public Drawable getDividerDrawable() { Drawable divider = super.getDividerDrawable(); if (divider instanceof S...
pageIndicatorView.setDividerDrawable(new SpaceDrawable(5)); assertThat(pageIndicatorView.getDividerDrawable(), nullValue()); } }
88944428_6
class TracerResolver { public static Tracer resolveTracer() { return resolveTracer(null); } @Deprecated protected abstract Tracer resolve(); public static Tracer resolveTracer(ClassLoader classloader); @Deprecated public static void reload(); private static boolean isDisabled(); priva...
writeServiceFile(TracerResolver.class, Mocks.NullTracerResolver.class); assertThat(TracerResolver.resolveTracer(), is(nullValue())); } }
88962042_13
class Transformers { static ClassesTransformer<JavaClass> classes() { return new AbstractClassesTransformer<JavaClass>("classes") { @Override public Iterable<JavaClass> doTransform(JavaClasses collection) { return collection; } }; } stati...
JavaClasses input = importClasses(Object.class, String.class); DescribedIterable<JavaClass> output = Transformers.classes().transform(input); assertThat(output).containsOnlyElementsOf(input); } }
88978812_18
class ColorManager { public Color nextColor(Color color) { return successor.get(color); } @Inject public ColorManager(@Named("nrColors") int nrColors, ColorFactory factory); private Color[] createColors(); private void createOrdering(); public Color firstColor(); public boolean t...
ColorManager manager = new ColorManager(NR_COLORS, Color::new); Assert.assertNull(manager.nextColor(Color.none)); } }
88985813_8
class SnapshotPostProcessor { long getConsistentApplicationModelVersion() { long applicationModelVersion = 0; if (m_beforePostProcessingVersion > 0) { applicationModelVersion = m_beforePostProcessingVersion; } // since we already validate version after postprocessing no ...
SnapshotPostProcessor snapshotPostProcessor = new SnapshotPostProcessor((snapshot, storeName) -> snapshot); assertThat(snapshotPostProcessor.getConsistentApplicationModelVersion()).isEqualTo(0L); } }
89108465_0
class StringWritableCsv { public static StringBuffer writeTo(StringBuffer sb, StringWritable... values) throws IllegalArgumentException { checkNotNull(sb, "sb"); if(null == values || values.length == 0) { return sb; } writeStringWritableToStringBuffer(values[0], sb); ...
assertTrue(StringWritableCsv.writeTo(new StringBuffer()).length() == 0); assertTrue(StringWritableCsv.writeTo(new StringBuffer(), new CharAttributeValue[]{}).length() == 0); } }
89138130_116
class FilterParser extends StringParser { public static SnowFilter parse(String text) throws StringParseException { FilterParser parser = new FilterParser(text); SnowFilter retval = new SnowFilter(); // This keeps track of whether the currently built clause is to be placed in the filter with an AND. If ...
String text = "install_status != 7 ^ install_status != 8 ^ ci.sys_class_name = u_notebook_pc ^OR ci.sys_class_name = u_tablet_pc ^OR ci.sys_class_name = u_thin_client_pc ^OR ci.sys_class_name = cmdb_ci_desktop_pc ^OR ci.sys_class_name = u_computer_pc ^OR ci.sys_class_name = u_cmdb_virtual_pc ^ ci.u_compensation_cod...
89139973_10
class CookieTray implements CookieStore { @Override public synchronized void add(URI associatedUri, HttpCookie cookie) { URI uri = new OriginUri(cookie, associatedUri).uri(); Set<HttpCookie> targetCookies = cookiesCache.get(uri); if (targetCookies == null) { targetCookies =...
URI uri = URI.create("http://google.com"); CookieStore store = new CookieTray(preferences); HttpCookie httpCookie = new HttpCookie("name", "value"); store.add(uri, httpCookie); String cookieVal = new SerializableCookie(httpCookie).asString(); verify(editor).putString(uri....
89188081_1
class LocaleChangerDelegate { void initialize() { Locale persistedLocale = persistor.load(); if (persistedLocale != null) try { currentLocale = resolver.resolve(persistedLocale); } catch (UnsupportedLocaleException e) { persistedLocale = null...
// Given doReturn(null).when(localePersistor).load(); // When sut.initialize(); // Then verify(localeResolver).resolveDefault(); } }
89198062_28
class JNDIStateFactoryImpl implements StateFactory { public Object getStateToBind(Object orig, Name name, Context ctx, Hashtable<?,?> env) throws NamingException { if (orig instanceof org.omg.CORBA.Object) { return orig; } if (!(orig instanceof Remote)) { ...
assertThat(impl.getStateToBind(new Object(), null, null, env), nullValue()); } }
89208595_2
class IdentityGenerator { public static long generate() { return generate(DEFAULT_SHARD_ID); } private IdentityGenerator(); public static Instant extractInstant(long id); public static byte extractShardId(long id); public static long generate(byte shardId); static long doGenerate(byte shardId, lon...
ExecutorService executorService = Executors.newFixedThreadPool(100); final int NUM_IDS = 1_000_000; final ConcurrentMap<Long, AtomicInteger> collisionMap = new ConcurrentHashMap<Long, AtomicInteger>(NUM_IDS); for (int i = 0; i < NUM_IDS; i++) { executorService.submit(new Runnable() { @Ov...
89212553_9
class Director implements Iterable<Stage> { @NonNull public Stage direct(@NonNull ViewGroup container) { return direct(container, container.getId()); } Director(); @NonNull public static Director hire(@NonNull Activity activity, @Nullable Bundle savedInstanceState); public boolean contains(int id);...
ViewGroup container1 = new TestContainer(RuntimeEnvironment.application); ViewGroup container2 = new TestContainer(RuntimeEnvironment.application); @IdRes int containerId1 = 1; @IdRes int containerId2 = 2; container1.setId(containerId1); container2.setId(containerId2); Stage stage1 = direct...
89217740_4
class ClusterPlacement { static List<Cluster> filterClusters( List<Cluster> clusters, List<ClusterPlacement> allPlacements) { Set<String> clusterPlacements = allPlacements.stream() .map(ClusterPlacement::token) .collect(toSet()); return clusters.stream() .filter(cluster -...
final List<ClusterPlacement> clusterPlacements = Arrays.asList(new ClusterPlacementBuilder().clusterNumber(0).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(1).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(2).clusterGeneration(0...
89221572_36
class StreamUtils { public static <T> T lz4Stream( InputStream is, final int expectedSize, final BytesConsumer<T> consumer) throws IOException { is = ensureMarkSupported(is); if (isCompressed(is)) { return readStream(is, expectedSize, consumer); } else { final FastByteArrayOutputStream ...
final byte[] bytes = StreamUtils.lz4Stream( new ByteArrayInputStream(testRecordingZippedBytes), DEFAULT_EXPECTED_SIZE, CONSUME_TO_BYTES); assertArrayEquals(testRecordingZippedBytes, bytes); } }
89231271_0
class UriTemplateParser { public static void parse(String template, Handler handler) { assert template != null; assert handler != null; int pos = 0; final int length = template.length(); State state = State.OutsideParam; StringBuilder builder = new StringBuilder(); while (pos < length) { char c = tem...
UriTemplateParser.parse("{a}/bc", handler); verify(handler).handleParam("a"); verify(handler).handleText("/bc"); verifyNoMoreInteractions(handler); } }
89233128_4
class ApNavigator implements Navigator<TypeMirror, TypeElement, VariableElement, ExecutableElement> { public VariableElement[] getEnumConstants(TypeElement clazz) { List<? extends Element> elements = env.getElementUtils().getAllMembers(clazz); Collection<VariableElement> constants = new ArrayList<V...
new Expectations() { { //The primitiveType is irrelevant for getEnumConstants() operations env.getTypeUtils().getPrimitiveType(TypeKind.BYTE); result = (PrimitiveType) null; //enumElements needs to return ENUM_CONSTANT for getEnumConstants() to work p...
89239936_2
class HttpRequestLog { public static RequestLog getRequestLog(String name) { String lookup = serverToComponent.get(name); if (lookup != null) { name = lookup; } String loggerName = "http.requests." + name; String appenderName = name + "requestlog"; Log logger = LogFactory.getLog(logger...
HttpRequestLogAppender requestLogAppender = new HttpRequestLogAppender(); requestLogAppender.setName("testrequestlog"); Logger.getLogger("http.requests.test").addAppender(requestLogAppender); RequestLog requestLog = HttpRequestLog.getRequestLog("test"); Logger.getLogger("http.requests.test").removeA...
89252015_0
class WsImportMojo extends AbstractJaxwsMojo { static String getActiveHttpProxy(Settings s) { String retVal = null; for (Proxy p : s.getProxies()) { if (p.isActive() && "http".equals(p.getProtocol())) { StringBuilder sb = new StringBuilder(); String user ...
SettingsXpp3Reader r = new SettingsXpp3Reader(); Settings s = r.read(WsImportMojoTest.class.getResourceAsStream("proxy1.xml")); String proxyString = WsImportMojo.getActiveHttpProxy(s); Assert.assertEquals(proxyString, "proxyActive:8099"); s = r.read(WsImportMojoTest.clas...
89259438_0
class TracingHttpClientBuilder extends HttpClientBuilder { public TracingHttpClientBuilder disableInjection() { this.injectDisabled = true; return this; } public TracingHttpClientBuilder(); public TracingHttpClientBuilder( RedirectStrategy redirectStrategy, boolean re...
{ HttpClient client = ((TracingHttpClientBuilder)clientBuilder).disableInjection().build(); client.execute(new HttpGet(serverUrl(RedirectHandler.MAPPING))); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(3, mockSpans.size()); ...
89302682_1
class WXBizMsgCrypt { public String encrypt(String randomStr, String text) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(CHARSET); byte[] textBytes = text.getBytes(CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte...
try { WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId); assertEquals(afterAesEncrypt2, pc.encrypt(randomStr, replyMsg2)); } catch (AesException e) { e.printStackTrace(); fail("no异常"); } } }
89335647_1
class MainActivityPresenter implements MainActivityContract.Presenter { @VisibleForTesting void checkAndroidVersionCompatibility() { if (!supportedByArtist()) { mView.showIncompatibleAndroidVersionDialog(); } } MainActivityPresenter(MainActivityContract.View view, ...
setFinalStatic(Build.VERSION.class.getField("SDK_INT"), Build.VERSION_CODES.N); mPresenter.checkAndroidVersionCompatibility(); verify(mView, never()).showIncompatibleAndroidVersionDialog(); } }
89412712_8
class PropUtil { public static boolean getBooleanProperty(Properties props, String name, boolean def) { return getBoolean(getProp(props, name), def); } private PropUtil(); public static int getIntProperty(Properties props, String name, int def); @Deprecated public static int getIntSessionPr...
Properties props = new Properties(); props.put("test", true); assertTrue(PropUtil.getBooleanProperty(props, "test", false)); } }
89435838_9
class FileTransfer implements WritableMessage { @Override public int remaining() { return ((len > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) len); } public FileTransfer(final File f); public FileTransfer(final File f, final long pos, final long len); public long writeTo(final Wr...
TCPNIOTransport t = TCPNIOTransportBuilder.newInstance().build(); FilterChainBuilder builder = FilterChainBuilder.stateless(); final File f = generateTempFile(1024 * 1024); builder.add(new TransportFilter()); builder.add(new BaseFilter() { @Override public...
89485344_21
class BankingDateInformation { public double getAmountDelta() { double amountDelta = 0.0; for (Transaction transaction : this.transactionSupplier.getAll()) { amountDelta += transaction.booking().getAmount(); } return amountDelta; } public BankingDateInformation...
// SETUP double amount = 123.456; double amount1 = 500.00; double amount2 = -100.00; Booking booking1 = new Booking(new Date(), amount1); Transaction transaction1 = new Transaction("some name","some id",booking1); Booking booking2 = new Booking(new Date(), amoun...
89507222_6
class AuthMigrator { public Task<Void> migrate(boolean cleanupDigitsSession) { final FirebaseUser currentUser = mFirebaseAuth.getCurrentUser(); final String sessionJson = mStorageHelpers.getDigitsSessionJson(); final Context context = mApp.getApplicationContext(); final RedeemableDi...
when(mockFirebaseAuth.getCurrentUser()).thenReturn(mockFirebaseUser); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertTrue(authMigrator.migrate(false).isSuccessful()); verify(mockStorageHelpers, times(0)).clearDi...
89576260_7
class JobCallbackUtil { public static boolean isThereJobCallbackProperty(Props props, JobCallbackStatusEnum status) { if (props == null || status == null) { throw new NullPointerException("One of the argument is null"); } String jobCallBackUrl = firstJobcallbackPropertyMap.get(status); ...
Props props = new Props(); props.put("abc", "def"); Assert.assertFalse(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.STARTED)); Assert.assertFalse(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.COMPLETED)); Assert.assertFalse(JobC...
89607184_16
class ManageManagerController { @GetMapping("/manage/managers") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) public RowDefinition list(String name, String department, String realName) { return new RowDefinition<Manager>() { @Override public Class...
// /manage/managers addUser(); mockMvc.perform( get("/manage/managers") ) .andExpect(status().isOk()) .andDo(print()); assertThat(true) .isTrue(); } }
89617755_61
class TypeConvertingSqlAccessor implements SqlAccessor { @Override public long getLong( int rowOffset ) throws InvalidAccessException { final long result; switch ( getType().getMinorType() ) { // 1. Regular type: case BIGINT: result = innerAccessor.getLong( rowOffset ); break; ...
final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( 2147483647 ) ); assertThat( uut1.getLong( 0 ), equalTo( 2147483647L ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( -2147483648 ) ); assertThat( uut2.getLong( 0 ), equal...
89644636_7
class ModelExtractor { public byte[] getModel(String modelUri) { return getModel(new DefaultResourceLoader().getResource(modelUri)); } public ModelExtractor(); public ModelExtractor(String frozenGraphFileExtension); public byte[] getModel(Resource modelResource); private byte[] findInArchiveStream(String ...
byte[] model = new ModelExtractor() .getModel("https://download.tensorflow.org/models/deeplabv3_mnv2_pascal_train_aug_2018_01_29.tar.gz"); assertThat(model.length, is(8773281)); } }
89676913_0
class PropertyUtils { public static <T> T get(String key, Function<String, T> parser, T defaultValue) { return get(System.getProperties(), key, parser, defaultValue); } private PropertyUtils(); public static T get(Properties props, String key, Function<String, T> parser, T defaultValue); public static...
assertEquals("bar", PropertyUtils.get("_foo", String::valueOf, "bar")); } }
89684482_0
class DefaultCallAdapterFactory extends CallAdapter.Factory { @Override public CallAdapter<?, ?> get(@Nonnull final Type returnType, @Nonnull final Annotation[] annotations, @Nonnull final Retrofit retrofit) { if (getRawType(returnType) != CompletableFuture.class) { return null; } ...
DefaultCallAdapterFactory factory = new DefaultCallAdapterFactory(false, LOGGER); Type returnType = new ParameterizedType() { @Override public Type[] getActualTypeArguments() { return new Type[]{String.class}; } @Override publi...
89791542_4
class ViewPagerAnimator implements ViewPager.OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (position == 0 && positionOffsetPixels == 0 && !isAnimating()) { onPageSelected(0); } if (isAnimating()...
numberAnimator.onPageScrolled(1, 0f, 0); numberAnimator.onPageScrolled(1, 0.1f, 10); numberAnimator.onPageScrolled(0, 0.9f, 90); assertThat(numberProperty.get()).isEqualTo(0.9f); } }
89856316_30
class EventMapper { public Event map(VEvent event, TimeZone defaultTimeZone) { Event result = new Event(); nullSave(() -> { final DateTime start = new DateTime(event.getDateStart().getValue().getTime(), DateTimeZone.forTimeZone(defaultTimeZone)); result.setStart(start, event.getDateStart().getVa...
//given final VEvent event = new VEvent(); event.setDateStart(DateTime.parse("2009-12-15T22:15:00").withZone(DateTimeZone.UTC).toDate(), true); event.setDateEnd(DateTime.parse("2010-08-13T20:15:00").withZone(DateTimeZone.UTC).toDate(), true); event.setSummary("<summary>"); event.setDescription("...
89961630_1
class MetricGetter { @SafeVarargs public static final TagValue[][] getTagCombinations(Class<? extends TagValue>... tagValueClazzes) { int combinations = 1; for (Class<? extends TagValue> clazz : tagValueClazzes) { combinations *= clazz.getEnumConstants().length; } ...
TagValue[][] expected = {{TimeoutTimedOut.TRUE}, {TimeoutTimedOut.FALSE}}; assertEquals(MetricGetter.getTagCombinations(TimeoutTimedOut.class), expected); } }
90011594_29
class SchedulerIteration { public void run(SchedulerMode mode) { mActionsToRemove.clear(); startNewActions(); runActions(mode); startDefaultSubsystemActions(mode); readyForNextRun(); } SchedulerIteration(ActionControl actionControl, RequirementsControl requireme...
ActionContext actionContext = ActionsMock.contextMocker() .runFinished(false) .build(); mActionControlMock.runningAction(actionContext); mSchedulerIteration.run(SchedulerModeMock.mockNotDisabledMode()); verify(actionContext, times(1)).run(); } }
90020587_0
class GenerateTradeData { public List<Trade> createRandomData(int number) throws Exception { // TODO Auto-generated method stub return null; } public Trade createTradeData(int number, List<Party> partyList, List<Instrument> instrumentList); private Party getRandomParty(List<Party> partyList); private Ins...
GenerateRandomInstruments ranIns = new GenerateRandomInstruments(); assert (ranIns.createRandomData(50).size() == 50); } }
90026142_0
class SegmentedLog { public void truncateSuffix(long newEndIndex) { if (newEndIndex >= getLastLogIndex()) { return; } LOG.info("Truncating log from old end index {} to new end index {}", getLastLogIndex(), newEndIndex); while (!startLogIndexSegmentMap.isE...
String raftDataDir = "./data"; SegmentedLog segmentedLog = new SegmentedLog(raftDataDir, 32); Assert.assertTrue(segmentedLog.getFirstLogIndex() == 1); List<RaftProto.LogEntry> entries = new ArrayList<>(); for (int i = 1; i < 10; i++) { RaftProto.LogEntry entry = Raft...
90036492_1
class MergedItem { static MergedItem newRow(int type, long id) { return new MergedItem(type, id, false); } private MergedItem(int type, long id, boolean injected); static MergedItem newInjectedRow(int type); @Override public boolean equals(Object o); } class MergedItemTest { @Test...
MergedItem mergedItem = MergedItem.newRow(1, 2L); assertThat(mergedItem.injected, is(false)); assertThat(mergedItem.type, is(1)); assertThat(mergedItem.id, is(2L)); } }
90043355_117
class HilbertTransformFilter { public void apply(int n, float[] x, float[] y) { Conv.conv(_filter.length,-(_filter.length-1)/2,_filter,n,0,x,n,0,y); } public HilbertTransformFilter(); public HilbertTransformFilter(int nmax, float emax, float fmin, float fmax); public ...
int[] nmax_test = {NMAX_DEFAULT,100000,100000,100000,100000}; float[] emax_test = {EMAX_DEFAULT,0.010f,0.010f,0.001f,0.001f}; float[] fmin_test = {FMIN_DEFAULT,0.050f,0.025f,0.100f,0.010f}; float[] fmax_test = {FMAX_DEFAULT,0.475f,0.450f,0.400f,0.490f}; int ntest = emax_test.length; // Lo...
90045866_1
class GeneralUtilities extends SpagoBIUtilities { public static Map<String, ParamDefaultValue> getParamsDefaultValuesUseAlsoDB(IDataSet dataSet) { Map<String, ParamDefaultValue> res = DataSetUtilities.getParamsDefaultValues(dataSet); if (res != null) { return res; } logger.warn("No params default values fo...
IDataSet dummy = new MockDataSet(); dummy.setParameters(DataSetParametersListTest.XML); Map<String, ?> dvs = GeneralUtilities.getParamsDefaultValuesUseAlsoDB(dummy); Assert.assertEquals(2, dvs.size()); Assert.assertEquals(DataSetParametersListTest.FIRST_DEFAULT_VALUE, dvs.get(DataSetParametersListTest.FIRST_P...
90096766_23
class UserJWTController { @PostMapping("/authenticate") @Timed public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVM.getUsername(), l...
// Normal authentication LoginVM vm = new LoginVM(); vm.setUsername("admin"); vm.setPassword("admin"); vm.setRememberMe(true); Mockito.doReturn("fakeToken").when(tokenProvider) .createToken(Mockito.any(Authentication.class), Mockito.anyBoolean()); m...
90135592_5
class EventBatcher { public void pushEvent(EventLog eventLogEntry, NakadiEvent nakadiEvent) { long eventSize; try { eventSize = objectMapper.writeValueAsBytes(nakadiEvent).length; } catch (Exception e) { log.error("Could not serialize event {} of type {}, skipping i...
EventLog eventLogEntry1 = eventLogEntry(1, "type1"); EventLog eventLogEntry2 = eventLogEntry(2, "type1"); EventLog eventLogEntry3 = eventLogEntry(3, "type1"); NakadiEvent nakadiEvent1 = nakadiEvent("1"); NakadiEvent nakadiEvent2 = nakadiEvent("2"); NakadiEvent nakadiEvent...
90198241_2
class ASimulator implements ISimulatorUpdater { protected ASimulator() { } protected ASimulator(); public boolean loadConfig(String aConfigFile); @Override public void update(); @Override public void setRobot(IRobotClassContainer aRobot); public String getConfigFile(); } class Test...
String file = extractFiles("testReadFile.yml"); ASimulator baseSimulator = new ASimulator(); Assertions.assertTrue(baseSimulator.loadConfig(file)); // Used to create some components new MockRobot(); AccelerometerWrapperAccessor accelerometerAccessor = DataAccessorFacto...
90217436_135
class MetaStore implements CopyMetaService, CmdletMetaService, BackupMetaService { public long getStoreFreeOfDifferentStorageType(String storageType) throws MetaStoreException { try { int sid = 0; if (storageType.equals("ram")) { sid = 0; } if (storageType.equals("ssd")) { ...
DataNodeStorageInfo info1 = new DataNodeStorageInfo("1", "ssd", 1, "1", 1, 1, 1, 1, 1); DataNodeStorageInfo info2 = new DataNodeStorageInfo("2", "ssd", 2, "2", 2, 2, 2, 2, 2); metaStore.insertDataNodeStorageInfo(info1); metaStore.insertDataNodeStorageInfo(info2); long free = metaStore.getStoreFree...
90226261_4
class CustomerResultSetExtractor implements ResultSetExtractor<PayloadWrapper<CustomerPayload>> { @Override public PayloadWrapper<CustomerPayload> extractData(ResultSet rs) throws SQLException, DataAccessException { CustomerPayload customerPayload = null; if (rs.next()) { customerPayload = new CustomerPayload...
CustomerResultSetExtractor extractor = new CustomerResultSetExtractor(); ResultSet rs = mock(ResultSet.class); given(rs.next()).willReturn(true).willReturn(false); given(rs.getString("ID")).willReturn("customer1"); given(rs.getString("NAME")).willReturn("customer name"); CustomerPayload payload = new Custo...
90329901_92
class ValueWidget extends DOMWidget { public String getString(Object input) { String ret = ""; if (input != null) { if (input instanceof String) { ret = (String) input; } else if (input instanceof byte[]) { ret = new String((byte[]) input); } else { ret = input.toStr...
//when String value = valueWidget.getString("abc".getBytes()); //then Assertions.assertThat(value).isEqualTo("abc"); } }
90406775_23
class UnitFactorMap { public String dump(Unit unit) { StringBuilder buf = new StringBuilder(); buf.append(unit).append(":\n"); Map<Unit, UnitFactor> map = factors.get(unit); for (Unit base : map.keySet()) { UnitFactor factor = map.get(base); buf.append(" ").append(factor).append(" "); ...
String factors = UnitFactors.LENGTH.dump(Unit.INCH); assertTrue(factors.contains("Factor(2.54, CENTIMETER)")); assertTrue(factors.contains("Factor(1 / 12, FOOT)")); } }
90442475_0
class FileInfosPresenter implements FileInfosContract.Presenter { @Override public void loadFileInfos() { mFileInfosRepository .listFileInfos(mDirectory) .observeOn(mSchedulerProvider.ui()) .subscribe(new Action1<List<FileInfo>>() { @O...
setAvailableFileInfos(mMockFileInfosRepository); mFileInfosPresenter.loadFileInfos(); Mockito.verify(mMockView, Mockito.times(1)).showFileInfos(Mockito.anyListOf(FileInfo.class)); } }
90446318_3
class MysqlUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { User user = userRepository.findByUsername(s); log.info("user is found! -> " + user.getUsername()); if (user == null) { ...
doReturn(null).when(repository).findByUsername(anyString()); try { userDetailsService.loadUserByUsername(anyString()); fail(); } catch (Exception e) { } } }
90489106_2
class RelevanceModel { public static Dataset concat(Dataset d1, Dataset d2) { double[][] X = concat(d1.getX(), d2.getX()); double[] y = concat(d1.getY(), d2.getY()); return new Dataset(X, y); } public static void main(String[] args); public static double[] concat(double[] y1, d...
double[] y1 = { 1.0, 2.0, 3.0 }; double[] y2 = { 4.0, 5.0 }; double[] y = RelevanceModel.concat(y1, y2); double[] expected = { 1.0, 2.0, 3.0, 4.0, 5.0 }; assertTrue(Arrays.equals(y, expected)); } }
90646801_4
class LatexTemplate { public final String populateFrom(final LatexContext context) { requireNonNull(context); final VelocityEngine velocityEngine = initializeEngine(); final VelocityContext velocityContext = prepareContext(context); return evaluateTemplate(velocityContext, velocityEngine); } public Late...
LatexTemplate template = new LatexTemplate("${keyToReplace}"); LatexContext context = new LatexContext(); context.add("keyToReplace", "value"); String result = template.populateFrom(context); assertThat(result, is("value")); } }
90675730_96
class SuffixFormatter { public String format(final Quantity.Format format, final int exponent) { switch (format) { case DECIMAL_SI: return getDecimalSiSuffix(exponent); case BINARY_SI: return getBinarySiSuffix(exponent); case DECIMAL_EXPONENT: return exponent == 0 ? "" :...
final String formattedString = new SuffixFormatter().format(Quantity.Format.BINARY_SI, 0); assertThat(formattedString, is("")); } }
90725839_1
class ConfigurationManager { static void loadProperties(Properties properties) throws InitConfigurationException { if (instance == null) { instance = getConfigInstance(); } ConfigurationUtils.loadProperties(properties, instance); } static void setEnableDefaultload(boole...
ConfigurationManager.loadPropertiesFromResources("test.properties"); assertEquals("9", ConfigurationManager.getConfigInstance().getProperty("com.ctrip.config.samples.needCount")); assertEquals("9", ConfigurationManager.getConfigInstance().getString("com.ctrip.config.samples.needCount")); ...
90792480_1
class OffsetAnimator { protected float computeValueByOffset(float positionOffset) { positionOffset = computeByTimeShift(positionOffset); positionOffset = computeByInterpolator(positionOffset); return computeExactPosition(x1, x2, positionOffset); } protected OffsetAnimator(float x1...
OffsetAnimator offsetAnimator = new OffsetAnimator(0, 100); float[] positionOffsets = PositionGenerator.generatePositionOffsets(); final float[] expectedValues = new float[100]; for (int i = 1; i < 100; i++) { expectedValues[i] = i; } final float[] actualVal...
90798597_2
class ImageViewerPresenter implements ImageViewerContract.Presenter { @Override public void deleteImage() { mImagesRepository.deleteImage(mImage); mView.displayImageDeleted(); } public ImageViewerPresenter(@NonNull ImageViewerContract.View view, @NonNull ImagesRepository repository, @...
mPresenter.deleteImage(); verify(mRepository).deleteImage(anyString()); } }
90798624_1
class MainPresenter implements MainContract.Presenter { @Override public void loadPosts() { mView.setLoadingPosts(true); mData.getPosts(new DataSource.GetPostsCallback() { @Override public void onPostsLoaded(Post[] posts) { mView.setLoadingPosts(false); ...
String errorText = "Error!"; mPresenter.loadPosts(); // Data should be loaded from data source and loading indicator should be displayed verify(mData).getPosts(mGetPostsCallbackbackCaptor.capture()); verify(mView).setLoadingPosts(true); // Trigger error mGetPos...
90847405_0
class CardTemplate { private String updateImagesPath(String template) { return template.replaceAll(IMAGE_PATH_REGEX, IMAGE_PATH_REPLACEMENT); } CardTemplate(String frontTemplate, String rearTemplate, int ord); public String getFrontTemplate(); public String getRearTemplate(); public...
String sampleText = "Che cos'è un latch SR?\n<hr id=answer>\n<div>Un circuito elettronico capace di memorizzare informazioni</div><img src=\"paste-9921374453761.jpg\" /> oppure <img src=\"paste-9921374453761.jpg\" />"; String expectedText = "Che cos'è un latch SR?\n<hr id=answer>\n<div>Un circuito elett...
90860455_7
class NodeBasedRewriteRule implements DialogRewriteRule { public Node applyTo(Node root, Set<Node> finalNodes) throws DialogRewriteException, RepositoryException { // check if the 'replacement' node exists if (!ruleNode.hasNode("replacement")) { throw new DialogRewriteExcept...
Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/rewriteFinal").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/simple").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); Set<Node> finalNo...
90881605_2
class Pager implements Runnable { public Pager(BiFunction<Long, Long, T> fetchFn, Long limit, Long pageSize) { Function<RequestPager.Page, T> fn = (page) -> { try { return fetchFn.apply(page.getLimit(), page.getOffset()); } catch (Exception e) { ...
var data = new ArrayList<Integer>(); for (var i = 0; i < 1000; i++) { data.add(i); } var pager = new Pager<>((limit, offset) -> { var start = offset; Long end = limit + offset; if (start > data.size()) { start = (long) data...
90886387_3
class GraywaterAdapter extends RecyclerView.Adapter<VH> { public void clear() { mItems.clear(); mBinderListCache.clear(); mViewHolderToItemPositionCache.clear(); mItemPositionToFirstViewHolderPositionCache.clear(); mViewHolderPreparedCache.clear(); mPreviousBoundViewHolderPosition = NO_PREVIOUS_BOUND_VIEW...
final TestAdapter adapter = new TestAdapter(); // ["https://www.tumblr.com", "https://www.tumblr.com", "https://www.tumblr.com", "one", "one", // "http://dreamynomad.com", "http://dreamynomad.com", "http://dreamynomad.com", ...] final Uri tumblrUri = Uri.parse("https://www.tumblr.com"); adapter.add(tumblrUr...
90936492_25
class AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public int loreSize(ItemStack IS) { ItemMeta IM = IS.getItemMeta(); if (IM == null) return 0; List<String> lores = IM.getLore(); if...
List<String> lores = new ArrayList<>(); lores.add("abab"); lores.add("cdcd"); lores.add("efef"); ItemStack IS = new ItemStack(Material.STONE); Mockito.doAnswer(invocation -> lores).when(mockItemMeta).getLore(); Assert.assertEquals(3, fn.loreSize(IS)); } }
90985502_0
class ClassLoaderUtil { public static String classnameFromFilename(final String filename) { Objects.requireNonNull(filename); return StreamSupport.stream( Paths.get(filename.replaceFirst("\\.class$", "")).spliterator(), false) .map(Path::toString) ...
assertEquals( "com.example.Foo", ClassLoaderUtil.classnameFromFilename("com/example/Foo.class")); } }
91037889_4
class LobbyPresenter extends BasePresenter<LobbyView> { void onReportDataError(Throwable throwable) { Timber.e(throwable, "report error"); view.displayReportError(); } @Inject LobbyPresenter(LobbyReportUseCase lobbyReportUseCase, SchedulersFacade schedulersFacade); String getLocalRe...
// WHEN testSubject.onReportDataError(null); // THEN verify(view).displayReportError(); } }
91054623_7
class UtilAll { public static int getPid() { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String name = runtime.getName(); // format: "pid@hostname" try { return Integer.parseInt(name.substring(0, name.indexOf('@'))); } catch (Exception e) { ...
int pid = UtilAll.getPid(); System.out.println("PID = " + pid); assertTrue(pid > 0); } }
91104663_9
class JsonUtils { @Nullable public static List<String> parseOptStringList(@Nullable JSONArray jsonArray) { if (jsonArray == null) { return null; } final List<String> list = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { final String i...
JSONArray jsonArray = new JSONArray(); String testString = "Test"; jsonArray.put(testString); List<String> stringList = JsonUtils.parseOptStringList(jsonArray); Assert.assertNotNull(stringList); String first = stringList.get(0); Assert.assertEquals(testString,...
91120647_47
class JsonXMLArrayProvider extends AbstractJsonXMLProvider { @Override public void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, ...
JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLVirtualSampleRootElement.class.getAnnotation(JsonXML.class)}; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); List<SampleRootElement> list = new ArrayList<Samp...
91155672_2
class WebhookAPI { @GET @Produces(MediaType.APPLICATION_JSON) public static Response get() { return Responses.ok(Webhooks.instance().hooks()); } @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public static Response get(@PathParam("id") long id); @POST @Consumes(MediaType.APP...
Response res = target("").path("1").request() .get(); assertEquals(404, res.getStatus()); } }
91247102_8
class WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (O...
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)...
91324844_0
class Post extends AuditableEntity { @PrePersist public void slugify(){ this.slug = new Slugify().slugify(this.title); } } class PostTest { @Test public void testSlug() {
System.out.println("getSlug"); Post instance = new Post(); instance.setTitle("test post 1"); instance.slugify(); assertEquals("test-post-1", instance.getSlug()); } }
91367377_1
class GraphExporter { public BufferedImage exportCurrentGraph(mxGraph graph, double scale, UIAbstractBlock selectedBlock, BlockState<? extends LatticeElement> state) { BufferedImage graphImage; int stateImageWidth = (int) (STATE_AREA_WIDTH * scale); BufferedImage stateImage = null; ...
BufferedImage exportedImage = graphExporter.exportCurrentGraph(graph, 2.0, null, null); BufferedImage referenceImage = ImageIO.read(getClass().getResourceAsStream("/export-medium.png")); Assert.assertEquals("", TestUtils.bufferedImagesEqual(exportedImage, referenceImage, 10, 300, 10)); } }
91427887_1
class Tracing extends org.apache.cassandra.tracing.Tracing { Span spanFromPayload(Tracer tracer, @Nullable Map<String, ByteBuffer> payload) { ByteBuffer b3 = payload != null ? payload.get("b3") : null; if (b3 == null) return tracer.nextSpan(); TraceContextOrSamplingFlags extracted = B3SingleFormat.parseB...
assertThat(cassandraTracing.spanFromPayload(tracing.tracer(), Collections.emptyMap())) .isNotNull(); } }
91470090_46
class Web3Impl implements Web3 { @Override public BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx) { BlockResultDTO s = null; try { Block block = blockchain.getBlockByHash(stringHexToByteArray(blockHash)); if (block == null) { ...
/* Structure: * Genesis * | | | * A B C * | \ / ____/ * D E * | / * F * * A-D-F mainchain * B and C uncles of E * E uncle of F * */ World world = new World(); Web3Impl...
91478358_21
class Topic { public static Topic split(String path) { if (path == null) { return null; } path = path.replaceAll("(^/+|/$)+", ""); if (path.isEmpty()) { return null; } return new Topic(Arrays.asList(path.split("\\/+"))); } private ...
final Topic topic = Topic.split(""); Assert.assertNull(topic); } }
91547699_1
class SaveBmiService extends IntentService { public static void start(Context context, BmiValue bmiValue) { Intent intent = new Intent(context, SaveBmiService.class); intent.putExtra(PARAM_KEY_BMI_VALUE, bmiValue); context.startService(intent); } public SaveBmiService(); @Ove...
Context context = mock(Context.class); SaveBmiService.start(context, mock(BmiValue.class)); verify(context, times(1)).startService((Intent) any()); } }
91552889_11
class FParser { public static String evaljs(String script) { try { return JS.eval("JSON.stringify(" + script + ")").toString(); } catch (ScriptException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return "undefined"; } public static List<Strin...
System.out.println("Evaljs"); String script = "floor(100 + random() * 900)"; String result = FParser.evaljs(script); assertTrue(result.matches("[0-9]{3}"), "Test random "); script = "'test'+ floor(100 + random() * 900)+'vt@gmail.com'"; result = (String) JS...
91571398_0
class RedisAppender implements Appender { public RedisThrottlerJmxBean getJmxBean() { return throttler.getJmxBean(); } private RedisAppender(Builder builder); public Configuration getConfig(); @Override public String getName(); @Override public Layout<? extends Serializable> getLayou...
LOGGER.debug("creating the logger"); Logger logger = LOGGER_CONTEXT_RESOURCE .getLoggerContext() .getLogger(RedisAppenderTest.class.getCanonicalName()); int expectedMessageCount = MIN_MESSAGE_COUNT + RANDOM.nextInt(MAX_MESSAGE_COUNT - MIN_MESSAGE_COUNT); ...